Skip to main content

trusty_code/mcp/
trust.rs

1//! The trust gate over the project tier (#5428).
2//!
3//! Why: `<project>/.trusty-code/mcp.toml` is REPO-TRACKED content. Honouring
4//! an arbitrary `command` from it means anyone who can land a commit — or
5//! anyone whose repo you clone — chooses a subprocess this harness spawns with
6//! the operator's ambient credentials. That is remote code execution, and it
7//! is the same vector `trusty_agents::mcp::shared::merge_mcp_json` gates
8//! `.mcp.json` behind (#3266).
9//!
10//! What: the project tier may say WHICH of the operator's globally configured
11//! servers this project uses, never WHAT a server runs. A `Disable` always
12//! passes — switching a connector off can only reduce what runs. A `Set` passes
13//! only when it is content-equivalent to a global entry of the same name.
14//! "Content-equivalent" is exactly [`transport_equivalent`]: the identical
15//! command, args and env for stdio, the identical url and headers for a remote
16//! entry. Name-only matching is NOT sufficient; that would let a project keep a
17//! trusted name and swap the command behind it, which is the whole attack.
18//! Anything else is refused as an [`McpIssue`] whose remedy names the global
19//! file — the operator's own file, which they alone write.
20//!
21//! An accepted `Set` contributes exactly TWO things: its `name` (which matched)
22//! and its `enabled` flag. `transport` is byte-identical by construction, and
23//! `extensions` is DISCARDED and replaced with the global entry's — see
24//! [`gate`]. `extensions` is an uninterpreted `serde_json` map every consumer
25//! reads its own semantics out of (`trusty-agents` reads `auth`, `scopes` and
26//! `discover` from it), so letting a repo-tracked file write it would hand that
27//! file a second, unchecked channel into consumer behaviour — the same trust
28//! boundary the transport comparison draws, walked around.
29//!
30//! // #5428: trust-by-content per the #7422/#3033 ruling.
31//!
32//! Test: `super::tests::trust_tests` — the whole module.
33
34use std::path::Path;
35
36use trusty_mcp::config::{McpServerConfig, McpServerOverride, McpTransport};
37
38use super::config::{McpIssue, McpTier, ProjectOverrides};
39
40/// What the operator must do to let a refused entry through.
41const REMEDY: &str = "Add this server to ~/.trusty-tools/mcp/servers.toml, the file only you \
42                      write. A project may choose among the servers configured there and \
43                      disable them; it may not introduce or alter a command this harness runs.";
44
45/// Whether two transports describe the SAME connection, byte for byte.
46///
47/// Why: the trust decision turns on content, not on a name, so this is the
48/// whole comparison the gate rests on. A partial comparison — command but not
49/// args, url but not headers — would leave exactly the gap the gate exists to
50/// close.
51/// What: variants must match, and every field within them. `BTreeMap` equality
52/// covers `env` and `headers` including key order-independence and arity.
53/// Test: `super::tests::trust_tests::an_identical_stdio_entry_is_equivalent`,
54/// `super::tests::trust_tests::a_differing_arg_is_not_equivalent`,
55/// `super::tests::trust_tests::a_differing_env_value_is_not_equivalent`,
56/// `super::tests::trust_tests::http_and_sse_at_the_same_url_are_not_equivalent`.
57pub fn transport_equivalent(project: &McpTransport, global: &McpTransport) -> bool {
58    match (project, global) {
59        (
60            McpTransport::Stdio {
61                command: pc,
62                args: pa,
63                env: pe,
64            },
65            McpTransport::Stdio {
66                command: gc,
67                args: ga,
68                env: ge,
69            },
70        ) => pc == gc && pa == ga && pe == ge,
71        (
72            McpTransport::Http {
73                url: pu,
74                headers: ph,
75            },
76            McpTransport::Http {
77                url: gu,
78                headers: gh,
79            },
80        ) => pu == gu && ph == gh,
81        (
82            McpTransport::Sse {
83                url: pu,
84                headers: ph,
85            },
86            McpTransport::Sse {
87                url: gu,
88                headers: gh,
89            },
90        ) => pu == gu && ph == gh,
91        _ => false,
92    }
93}
94
95/// Split the project's table into overrides the resolver may see and refusals.
96///
97/// Why: the single place the repo-content trust decision is made, so no caller
98/// can reach `trusty_mcp::config::resolve` with an ungated project entry.
99/// What: every `disabled` name becomes a `Disable` unconditionally. Every
100/// `servers` entry becomes a `Set` only when a global entry of the same name
101/// exists AND [`transport_equivalent`] holds — which still lets the project
102/// flip `enabled`, because that field is outside the transport. Everything else
103/// is refused with an [`McpIssue`] and a `tracing::warn!`. `project_path` names
104/// the file in the finding and is never read here.
105///
106/// An accepted `Set` is emitted with the GLOBAL entry's `extensions`, not its
107/// own: only `name` and `enabled` cross the boundary. See the module doc.
108///
109/// Disables are emitted BEFORE sets, matching
110/// `trusty_agents::assistants::mcp::McpOverrides::as_overrides`, so a name in
111/// both lists resolves as the more specific `Set` under the resolver's
112/// left-to-right fold.
113/// Test: `super::tests::trust_tests::a_matching_set_is_accepted`,
114/// `super::tests::trust_tests::a_set_with_a_new_command_is_refused`,
115/// `super::tests::trust_tests::a_set_naming_no_global_server_is_refused`,
116/// `super::tests::trust_tests::a_set_may_re_enable_a_disabled_global_entry`,
117/// `super::tests::trust_tests::a_set_cannot_smuggle_its_own_extensions`,
118/// `super::tests::trust_tests::a_disable_always_passes`.
119pub fn gate(
120    global: &[McpServerConfig],
121    overrides: &ProjectOverrides,
122    project_path: &Path,
123) -> (Vec<McpServerOverride>, Vec<McpIssue>) {
124    let mut accepted = Vec::with_capacity(overrides.disabled.len() + overrides.servers.len());
125    let mut refused = Vec::new();
126
127    for name in &overrides.disabled {
128        accepted.push(McpServerOverride::Disable { name: name.clone() });
129    }
130
131    for server in &overrides.servers {
132        let Some(matching) = global.iter().find(|g| g.name == server.name) else {
133            refused.push(refusal(
134                project_path,
135                &server.name,
136                "names a server the shared MCP server file does not define",
137            ));
138            continue;
139        };
140        if !transport_equivalent(&server.transport, &matching.transport) {
141            refused.push(refusal(
142                project_path,
143                &server.name,
144                "redefines how that server is reached, which a project may not do",
145            ));
146            continue;
147        }
148        // #5428: extensions never cross the trust boundary. `transport` is
149        // already byte-identical, so this keeps the project's `name` and
150        // `enabled` and nothing else it wrote.
151        let mut honoured = server.clone();
152        honoured.extensions = matching.extensions.clone();
153        accepted.push(McpServerOverride::Set(honoured));
154    }
155
156    (accepted, refused)
157}
158
159/// One refusal, logged and returned.
160///
161/// What: the detail names the server and what it tried, and NOTHING of the
162/// transport — an `env` value or an auth header in a log line is the leak the
163/// redacted `Debug` on `McpTransport` exists to prevent, and a refusal message
164/// must not reintroduce it.
165fn refusal(path: &Path, server: &str, what: &str) -> McpIssue {
166    tracing::warn!(
167        path = %path.display(),
168        server = %server,
169        "mcp: refusing a project-tier MCP entry that {what}",
170    );
171    McpIssue {
172        tier: McpTier::Project,
173        path: path.to_path_buf(),
174        detail: format!("the project entry {server:?} {what}; it was not loaded"),
175        remedy: REMEDY.to_string(),
176    }
177}