Skip to main content

openmoat_core/engine/
taint.rs

1//! Session taint (ADR-020): what earlier calls of a session brought into it,
2//! and how that tightens later decisions.
3//!
4//! The caller keeps the session's history (the CLI reads it from the audit
5//! log) and folds [`CompiledPolicy::exposure`] over the calls that ran. The
6//! resulting [`Taint`] then goes into [`CompiledPolicy::with_taint`], which can
7//! only turn an outcome stricter.
8
9use serde::{Deserialize, Serialize};
10
11use super::{CompiledPolicy, EvalContext, checked_atoms};
12use crate::action::{Action, AtomicAction};
13use crate::pattern::{GlobPattern, any_match};
14use crate::policy::{Policy, PolicyError};
15use crate::realpath::PathResolver;
16use crate::repo::REPO_RULE_PREFIX;
17// `SECRET_RULE`: the rule group whose `fs.read` patterns name secret
18// material, wherever the policy puts it. In the default policy it denies, so
19// only a policy that reviews for these reads lets one run and taint the
20// session. A repository policy's group with the same base id (prefixed to
21// `repo:secrets-paths` by `RepoPolicy::merge`) is also taint-significant.
22use crate::rule_id::{SECRETS_PATHS as SECRET_RULE, SESSION_TAINT as TAINT_RULE};
23use crate::verdict::{Decision, Verdict};
24
25/// Where secret material in a session came from.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Secret {
28    /// What brought it in, for reasons (`read /Users/me/.ssh/id_rsa`).
29    pub source: String,
30    /// The one host the secret belongs to and may still go to. `None` for a
31    /// file read: it belongs to no host, so every host needs review. The secrets
32    /// broker (ADR-020) raises a `Secret` with its own host when a brokered
33    /// value is used, so later requests to other hosts need review.
34    pub host: Option<String>,
35}
36
37/// What earlier calls of one session exposed it to.
38#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
39pub struct Taint {
40    /// Secret material the session read, de-duplicated by source.
41    pub secrets: Vec<Secret>,
42    /// The first untrusted content the session read (`fetch docs.rs`), if any.
43    pub untrusted: Option<String>,
44    /// The first private data the session read other than secret material:
45    /// an agent's or a build tool's credentials, a decoy key, the whole
46    /// environment, a file `taint.private_paths` names (ADR-113).
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub private: Option<String>,
49    /// The first output the session read that someone else may have written:
50    /// what `untrusted` counts, and also a forge's issue and pull-request text
51    /// and a command's read from a host the policy does not allow
52    /// (`CompiledPolicy::output_source`, ADR-057). Not a metadata tool's
53    /// result. One part of the lethal trifecta (ADR-113).
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub seen: Option<String>,
56}
57
58/// Where untrusted content a session read came from: the one list of what
59/// injected input reads (ADR-057) and, less the metadata tools
60/// (`taint.metadata_tools`), of what taints a session, which
61/// [`CompiledPolicy::exposure`] and the provenance report (ADR-056) both use.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
63#[serde(rename_all = "kebab-case")]
64pub enum UntrustedKind {
65    /// A web page or search result (`fetch`, `web search`).
66    Web,
67    /// The result of an MCP tool.
68    Mcp,
69    /// The result of a host tool OpenMoat does not know.
70    UnknownTool,
71    /// A file a session that had read untrusted content wrote (ADR-029).
72    File,
73}
74
75impl UntrustedKind {
76    /// The kind of untrusted content `atom` reads, if it reads any.
77    #[must_use]
78    pub fn of(atom: &AtomicAction) -> Option<Self> {
79        match atom {
80            AtomicAction::Fetch { .. } | AtomicAction::WebSearch { .. } => Some(Self::Web),
81            AtomicAction::McpTool { .. } => Some(Self::Mcp),
82            AtomicAction::UnknownTool { .. } => Some(Self::UnknownTool),
83            _ => None,
84        }
85    }
86
87    /// The spelling notes and reports use.
88    #[must_use]
89    pub fn as_str(self) -> &'static str {
90        match self {
91            Self::Web => "web",
92            Self::Mcp => "mcp",
93            Self::UnknownTool => "unknown-tool",
94            Self::File => "file",
95        }
96    }
97
98    /// How a report names it: "after reading web content".
99    #[must_use]
100    pub fn describe(self) -> &'static str {
101        match self {
102            Self::Web => "web content",
103            Self::Mcp => "an MCP tool result",
104            Self::UnknownTool => "an unknown tool's result",
105            Self::File => "a file an exposed session wrote",
106        }
107    }
108}
109
110impl Taint {
111    /// Add what another call exposed the session to.
112    pub fn absorb(&mut self, other: Taint) {
113        for secret in other.secrets {
114            if !self.secrets.contains(&secret) {
115                self.secrets.push(secret);
116            }
117        }
118        if self.untrusted.is_none() {
119            self.untrusted = other.untrusted;
120        }
121        if self.private.is_none() {
122            self.private = other.private;
123        }
124        if self.seen.is_none() {
125            self.seen = other.seen;
126        }
127    }
128}
129
130/// The built-in protected paths and the ones `policy` adds, compiled for `ctx`.
131pub(super) fn compile_protected(
132    policy: &Policy,
133    ctx: &EvalContext,
134) -> Result<Vec<GlobPattern>, PolicyError> {
135    crate::taint::protected_writes(policy.taint.as_ref())
136        .flat_map(|p| ctx.spellings(p))
137        .map(|p| GlobPattern::compile(&p, ctx.case_insensitive_paths))
138        .collect()
139}
140
141/// The paths `policy`'s `taint.private_paths` names, compiled for `ctx`.
142pub(super) fn compile_private(
143    policy: &Policy,
144    ctx: &EvalContext,
145) -> Result<Vec<GlobPattern>, PolicyError> {
146    policy
147        .taint
148        .iter()
149        .flat_map(|t| &t.private_paths)
150        .flat_map(|p| ctx.spellings(p))
151        .map(|p| GlobPattern::compile(&p, ctx.case_insensitive_paths))
152        .collect()
153}
154
155impl CompiledPolicy<'_> {
156    /// What running `action` in `cwd` exposed its session to: secret material
157    /// from a read the `secrets-paths` group names, untrusted content from a
158    /// fetch, a web search, an unknown tool or an MCP result, except a
159    /// metadata tool's (`taint.metadata_tools`). The caller passes only calls that ran; the parts
160    /// of an action that cannot be classified expose nothing they can name.
161    #[must_use]
162    pub fn exposure(&self, action: &Action, cwd: &str, paths: &dyn PathResolver) -> Taint {
163        let ctx = EvalContext {
164            cwd: cwd.to_owned(),
165            ..self.ctx.clone()
166        };
167        let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
168        self.exposure_in(action, &atoms)
169    }
170
171    /// [`Self::exposure`] and [`Self::collection`] of one call that ran in
172    /// `cwd`, with its atoms worked out once: what a session's fold takes from
173    /// each of its calls, for half the classifying and path resolving of the
174    /// two apart.
175    #[must_use]
176    pub fn exposure_and_collection(
177        &self,
178        action: &Action,
179        cwd: &str,
180        paths: &dyn PathResolver,
181        is_dir: &dyn Fn(&str) -> bool,
182    ) -> (Taint, super::staging::Staging) {
183        let ctx = EvalContext {
184            cwd: cwd.to_owned(),
185            ..self.ctx.clone()
186        };
187        let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
188        (
189            self.exposure_in(action, &atoms),
190            self.collected(&atoms, &ctx, paths, is_dir),
191        )
192    }
193
194    /// [`Self::exposure_of`] of `action`'s atoms, with the private data they
195    /// read and the output someone else may have written that `action` read
196    /// (ADR-113).
197    fn exposure_in(&self, action: &Action, atoms: &[AtomicAction]) -> Taint {
198        let mut taint = self.exposure_of(atoms);
199        taint.private = self.private_read(atoms);
200        let metadata = atoms.iter().any(|atom| {
201            matches!(atom, AtomicAction::McpTool { .. }) && self.taints(atom).is_none()
202        });
203        if !metadata {
204            taint.seen = self.output_source_in(action, atoms);
205        }
206        taint
207    }
208
209    /// What the checked atoms of one call exposed its session to.
210    fn exposure_of(&self, atoms: &[AtomicAction]) -> Taint {
211        let mut taint = Taint::default();
212        for atom in atoms {
213            match atom {
214                AtomicAction::FsRead { .. } if self.names_secret(atom) => {
215                    taint.absorb(Taint {
216                        secrets: vec![Secret {
217                            source: atom.describe(),
218                            host: None,
219                        }],
220                        ..Taint::default()
221                    });
222                }
223                _ if self.taints(atom).is_some() => {
224                    taint.untrusted.get_or_insert_with(|| atom.describe());
225                }
226                _ => {}
227            }
228        }
229        taint
230    }
231
232    /// The first untrusted content running `action` in `cwd` read, with what
233    /// kind it is: the same atoms [`CompiledPolicy::exposure`] counts, for
234    /// reports that say where the content came from (ADR-056).
235    #[must_use]
236    pub fn untrusted_read(
237        &self,
238        action: &Action,
239        cwd: &str,
240        paths: &dyn PathResolver,
241    ) -> Option<(UntrustedKind, String)> {
242        let ctx = EvalContext {
243            cwd: cwd.to_owned(),
244            ..self.ctx.clone()
245        };
246        let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
247        atoms
248            .iter()
249            .find_map(|atom| self.taints(atom).map(|kind| (kind, atom.describe())))
250    }
251
252    /// The kind of untrusted content `atom` brings into its session, which
253    /// then taints it: [`UntrustedKind::of`], except the result of an MCP tool
254    /// that returns metadata, not content (a browser's tab list,
255    /// `taint.metadata_tools`). Injected input still reads that result
256    /// ([`Self::output_source`]): a page sets its own title and URL.
257    pub(super) fn taints(&self, atom: &AtomicAction) -> Option<UntrustedKind> {
258        let kind = UntrustedKind::of(atom)?;
259        match atom {
260            AtomicAction::McpTool { name }
261                if crate::taint::is_metadata_tool(self.policy.taint.as_ref(), name) =>
262            {
263                None
264            }
265            _ => Some(kind),
266        }
267    }
268
269    /// `decision` for `action`, tightened by `taint`: after secret material,
270    /// network to any host but the secret's own, and every MCP call, web
271    /// search and unknown tool (the hosts they reach are unknown), needs review; after untrusted content, a write to
272    /// a protected path needs review. Merging keeps the strictest verdict, so this
273    /// never loosens a decision.
274    #[must_use]
275    pub fn with_taint(
276        &self,
277        decision: Decision,
278        action: &Action,
279        paths: &dyn PathResolver,
280        taint: &Taint,
281    ) -> Decision {
282        // A clean session tightens nothing; skip classifying (and listing the
283        // directories of glob operands) a second time.
284        if *taint == Taint::default() {
285            return decision;
286        }
287        // After a secret read, a long encoded value in a URL is what a secret
288        // looks like on its way out: `@encoded-egress` atoms, which the policy's
289        // rules decide (`encoded-egress` denies them in the default policy).
290        let encoded = if taint.secrets.is_empty() {
291            Vec::new()
292        } else {
293            super::egress::encoded_atoms(action.shown(), |host| {
294                taint.secrets.iter().all(|s| {
295                    s.host
296                        .as_deref()
297                        .is_some_and(|own| own.eq_ignore_ascii_case(host))
298                })
299            })
300        };
301        let encoded = encoded
302            .iter()
303            .filter_map(|atom| self.matched_rules(atom))
304            .filter(|hit| matches!(hit.verdict, Verdict::Deny | Verdict::Review));
305        self.atoms(action, paths)
306            .0
307            .iter()
308            .filter_map(|atom| self.tainted(atom, taint))
309            .chain(encoded)
310            .fold(decision, |mut acc, next| {
311                acc.merge(next);
312                acc
313            })
314    }
315
316    fn tainted(&self, atom: &AtomicAction, taint: &Taint) -> Option<Decision> {
317        let reason = match atom {
318            AtomicAction::Net { host }
319            | AtomicAction::NetWord { host }
320            | AtomicAction::Fetch { host } => {
321                let secret = taint.secrets.iter().find(|s| {
322                    !s.host
323                        .as_deref()
324                        .is_some_and(|own| own.eq_ignore_ascii_case(host))
325                })?;
326                secret_reason(secret, atom)
327            }
328            AtomicAction::McpTool { .. }
329            | AtomicAction::WebSearch { .. }
330            | AtomicAction::UnknownTool { .. } => secret_reason(taint.secrets.first()?, atom),
331            AtomicAction::FsWrite { path } if any_match(&self.protected, path.as_str()) => {
332                format!(
333                    "the session read untrusted content ({}); {} changes what runs or what the agent is told later",
334                    taint.untrusted.as_ref()?,
335                    atom.describe()
336                )
337            }
338            _ => return None,
339        };
340        Some(Decision::single(Verdict::Review, TAINT_RULE, reason))
341    }
342
343    pub(super) fn names_secret(&self, atom: &AtomicAction) -> bool {
344        // A repository policy's rules are renamed to `repo:<id>` by `RepoPolicy::merge`,
345        // so match the base id and the prefixed one; `repo_review` carries the review rules
346        // merged in (ADR-022), so iterate it too.
347        [&self.deny, &self.repo_review, &self.allow, &self.review]
348            .into_iter()
349            .flatten()
350            .any(|g| {
351                let id = g.id.as_str();
352                (id == SECRET_RULE
353                    || id
354                        .strip_prefix(REPO_RULE_PREFIX)
355                        .is_some_and(|rest| rest == SECRET_RULE))
356                    && g.matches(atom)
357            })
358    }
359}
360
361fn secret_reason(secret: &Secret, atom: &AtomicAction) -> String {
362    format!(
363        "the session read secret material ({}); {} could carry it out",
364        secret.source,
365        atom.describe()
366    )
367}