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::{Built, 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    /// Where the data the session holds came from, by source, not by text
57    /// (ADR-126): `web`, `mcp:<server>`, `secret`, …, each with the first call
58    /// that brought it in. [`Taint::label_set`] adds the ones the other facts
59    /// imply.
60    #[serde(default, skip_serializing_if = "Vec::is_empty")]
61    pub labels: Vec<super::labels::Label>,
62}
63
64/// Where untrusted content a session read came from: the one list of what
65/// injected input reads (ADR-057) and, less the metadata tools
66/// (`taint.metadata_tools`), of what taints a session, which
67/// [`CompiledPolicy::exposure`] and the provenance report (ADR-056) both use.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
69#[serde(rename_all = "kebab-case")]
70pub enum UntrustedKind {
71    /// A web page or search result (`fetch`, `web search`).
72    Web,
73    /// The result of an MCP tool.
74    Mcp,
75    /// The result of a host tool OpenMoat does not know.
76    UnknownTool,
77    /// A file a session that had read untrusted content wrote (ADR-029).
78    File,
79}
80
81impl UntrustedKind {
82    /// The kind of untrusted content `atom` reads, if it reads any.
83    #[must_use]
84    pub fn of(atom: &AtomicAction) -> Option<Self> {
85        match atom {
86            AtomicAction::Fetch { .. } | AtomicAction::WebSearch { .. } => Some(Self::Web),
87            AtomicAction::McpTool { .. } => Some(Self::Mcp),
88            AtomicAction::UnknownTool { .. } => Some(Self::UnknownTool),
89            _ => None,
90        }
91    }
92
93    /// The spelling notes and reports use.
94    #[must_use]
95    pub fn as_str(self) -> &'static str {
96        match self {
97            Self::Web => "web",
98            Self::Mcp => "mcp",
99            Self::UnknownTool => "unknown-tool",
100            Self::File => "file",
101        }
102    }
103
104    /// How a report names it: "after reading web content".
105    #[must_use]
106    pub fn describe(self) -> &'static str {
107        match self {
108            Self::Web => "web content",
109            Self::Mcp => "an MCP tool result",
110            Self::UnknownTool => "an unknown tool's result",
111            Self::File => "a file an exposed session wrote",
112        }
113    }
114}
115
116impl Taint {
117    /// Add what another call exposed the session to.
118    pub fn absorb(&mut self, other: Taint) {
119        for secret in other.secrets {
120            if !self.secrets.contains(&secret) {
121                self.secrets.push(secret);
122            }
123        }
124        if self.untrusted.is_none() {
125            self.untrusted = other.untrusted;
126        }
127        if self.private.is_none() {
128            self.private = other.private;
129        }
130        if self.seen.is_none() {
131            self.seen = other.seen;
132        }
133        for label in other.labels {
134            self.add_label(&label.name, &label.source);
135        }
136    }
137}
138
139/// The built-in protected paths and the ones `policy` adds, compiled for `ctx`.
140pub(super) fn compile_protected(
141    policy: &Policy,
142    ctx: &EvalContext,
143    built: &mut Built,
144) -> Result<Vec<GlobPattern>, PolicyError> {
145    crate::taint::protected_writes(policy.taint.as_ref())
146        .flat_map(|p| ctx.spellings(p))
147        .map(|p| GlobPattern::compile_in(&p, ctx.case_insensitive_paths, built))
148        .collect()
149}
150
151/// The paths `policy`'s `taint.private_paths` names, compiled for `ctx`.
152pub(super) fn compile_private(
153    policy: &Policy,
154    ctx: &EvalContext,
155    built: &mut Built,
156) -> Result<Vec<GlobPattern>, PolicyError> {
157    policy
158        .taint
159        .iter()
160        .flat_map(|t| &t.private_paths)
161        .flat_map(|p| ctx.spellings(p))
162        .map(|p| GlobPattern::compile_in(&p, ctx.case_insensitive_paths, built))
163        .collect()
164}
165
166impl CompiledPolicy<'_> {
167    /// What running `action` in `cwd` exposed its session to: secret material
168    /// from a read the `secrets-paths` group names, untrusted content from a
169    /// fetch, a web search, an unknown tool or an MCP result, except a
170    /// metadata tool's (`taint.metadata_tools`). The caller passes only calls that ran; the parts
171    /// of an action that cannot be classified expose nothing they can name.
172    #[must_use]
173    pub fn exposure(&self, action: &Action, cwd: &str, paths: &dyn PathResolver) -> Taint {
174        let ctx = EvalContext {
175            cwd: cwd.to_owned(),
176            ..self.ctx.clone()
177        };
178        let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
179        self.exposure_in(action, &atoms)
180    }
181
182    /// [`Self::exposure`] and [`Self::collection`] of one call that ran in
183    /// `cwd`, with its atoms worked out once: what a session's fold takes from
184    /// each of its calls, for half the classifying and path resolving of the
185    /// two apart.
186    #[must_use]
187    pub fn exposure_and_collection(
188        &self,
189        action: &Action,
190        cwd: &str,
191        paths: &dyn PathResolver,
192        is_dir: &dyn Fn(&str) -> bool,
193    ) -> (Taint, super::staging::Staging) {
194        let ctx = EvalContext {
195            cwd: cwd.to_owned(),
196            ..self.ctx.clone()
197        };
198        let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
199        (
200            self.exposure_in(action, &atoms),
201            self.collected(&atoms, &ctx, paths, is_dir),
202        )
203    }
204
205    /// [`Self::exposure_of`] of `action`'s atoms, with the private data they
206    /// read and the output someone else may have written that `action` read
207    /// (ADR-113).
208    fn exposure_in(&self, action: &Action, atoms: &[AtomicAction]) -> Taint {
209        let mut taint = self.exposure_of(atoms);
210        taint.private = self.private_read(atoms);
211        let metadata = atoms.iter().any(|atom| {
212            matches!(atom, AtomicAction::McpTool { .. }) && self.taints(atom).is_none()
213        });
214        if !metadata {
215            taint.seen = self.output_source_in(action, atoms);
216        }
217        if let Some(secret) = taint.secrets.first().map(|s| s.source.clone()) {
218            taint.add_label(super::labels::LABEL_SECRET, &secret);
219        }
220        if let Some(private) = taint.private.clone() {
221            taint.add_label(super::labels::LABEL_PRIVATE, &private);
222        }
223        for atom in atoms {
224            if let Some(kind) = self.taints(atom) {
225                let name = super::labels::untrusted_label(kind, atom);
226                taint.add_label(&name, &atom.describe());
227            }
228        }
229        if let Some(seen) = taint.seen.clone() {
230            taint.add_label(super::labels::LABEL_EXTERNAL, &seen);
231        }
232        taint
233    }
234
235    /// What the checked atoms of one call exposed its session to.
236    fn exposure_of(&self, atoms: &[AtomicAction]) -> Taint {
237        let mut taint = Taint::default();
238        for atom in atoms {
239            match atom {
240                AtomicAction::FsRead { .. } if self.names_secret(atom) => {
241                    taint.absorb(Taint {
242                        secrets: vec![Secret {
243                            source: atom.describe(),
244                            host: None,
245                        }],
246                        ..Taint::default()
247                    });
248                }
249                _ if self.taints(atom).is_some() => {
250                    taint.untrusted.get_or_insert_with(|| atom.describe());
251                }
252                _ => {}
253            }
254        }
255        taint
256    }
257
258    /// The first untrusted content running `action` in `cwd` read, with what
259    /// kind it is: the same atoms [`CompiledPolicy::exposure`] counts, for
260    /// reports that say where the content came from (ADR-056).
261    #[must_use]
262    pub fn untrusted_read(
263        &self,
264        action: &Action,
265        cwd: &str,
266        paths: &dyn PathResolver,
267    ) -> Option<(UntrustedKind, String)> {
268        let ctx = EvalContext {
269            cwd: cwd.to_owned(),
270            ..self.ctx.clone()
271        };
272        let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
273        atoms
274            .iter()
275            .find_map(|atom| self.taints(atom).map(|kind| (kind, atom.describe())))
276    }
277
278    /// The kind of untrusted content `atom` brings into its session, which
279    /// then taints it: [`UntrustedKind::of`], except the result of an MCP tool
280    /// that returns metadata, not content (a browser's tab list,
281    /// `taint.metadata_tools`). Injected input still reads that result
282    /// ([`Self::output_source`]): a page sets its own title and URL.
283    pub(super) fn taints(&self, atom: &AtomicAction) -> Option<UntrustedKind> {
284        let kind = UntrustedKind::of(atom)?;
285        match atom {
286            AtomicAction::McpTool { name }
287                if crate::taint::is_metadata_tool(self.policy.taint.as_ref(), name) =>
288            {
289                None
290            }
291            _ => Some(kind),
292        }
293    }
294
295    /// `decision` for `action`, tightened by `taint`: after secret material,
296    /// network to any host but the secret's own, and every MCP call, web
297    /// search and unknown tool (the hosts they reach are unknown), needs review; after untrusted content, a write to
298    /// a protected path needs review. Merging keeps the strictest verdict, so this
299    /// never loosens a decision.
300    #[must_use]
301    pub fn with_taint(
302        &self,
303        decision: Decision,
304        action: &Action,
305        paths: &dyn PathResolver,
306        taint: &Taint,
307    ) -> Decision {
308        // A clean session tightens nothing; skip classifying (and listing the
309        // directories of glob operands) a second time.
310        if *taint == Taint::default() {
311            return decision;
312        }
313        // After a secret read, a long encoded value in a URL is what a secret
314        // looks like on its way out: `@encoded-egress` atoms, which the policy's
315        // rules decide (`encoded-egress` denies them in the default policy).
316        let encoded = if taint.secrets.is_empty() {
317            Vec::new()
318        } else {
319            super::egress::encoded_atoms(action.shown(), |host| {
320                taint.secrets.iter().all(|s| {
321                    s.host
322                        .as_deref()
323                        .is_some_and(|own| own.eq_ignore_ascii_case(host))
324                })
325            })
326        };
327        let encoded = encoded
328            .iter()
329            .filter_map(|atom| self.matched_rules(atom))
330            .filter(|hit| matches!(hit.verdict, Verdict::Deny | Verdict::Review));
331        let atoms = self.atoms(action, paths).0;
332        let flows = self.label_flows(action, &atoms, taint);
333        atoms
334            .iter()
335            .filter_map(|atom| self.tainted(atom, taint))
336            .chain(encoded)
337            .chain(flows)
338            .fold(decision, |mut acc, next| {
339                acc.merge(next);
340                acc
341            })
342    }
343
344    fn tainted(&self, atom: &AtomicAction, taint: &Taint) -> Option<Decision> {
345        let reason = match atom {
346            AtomicAction::Net { host }
347            | AtomicAction::NetWord { host }
348            | AtomicAction::Fetch { host } => {
349                let secret = taint.secrets.iter().find(|s| {
350                    !s.host
351                        .as_deref()
352                        .is_some_and(|own| own.eq_ignore_ascii_case(host))
353                })?;
354                secret_reason(secret, atom)
355            }
356            AtomicAction::McpTool { .. }
357            | AtomicAction::WebSearch { .. }
358            | AtomicAction::UnknownTool { .. } => secret_reason(taint.secrets.first()?, atom),
359            AtomicAction::FsWrite { path } if any_match(&self.protected, path.as_str()) => {
360                format!(
361                    "the session read untrusted content ({}); {} changes what runs or what the agent is told later",
362                    taint.untrusted.as_ref()?,
363                    atom.describe()
364                )
365            }
366            _ => return None,
367        };
368        Some(Decision::single(Verdict::Review, TAINT_RULE, reason))
369    }
370
371    pub(super) fn names_secret(&self, atom: &AtomicAction) -> bool {
372        // A repository policy's rules are renamed to `repo:<id>` by `RepoPolicy::merge`,
373        // so match the base id and the prefixed one; `repo_review` carries the review rules
374        // merged in (ADR-022), so iterate it too.
375        [&self.deny, &self.repo_review, &self.allow, &self.review]
376            .into_iter()
377            .flatten()
378            .any(|g| {
379                let id = g.id.as_str();
380                (id == SECRET_RULE
381                    || id
382                        .strip_prefix(REPO_RULE_PREFIX)
383                        .is_some_and(|rest| rest == SECRET_RULE))
384                    && g.matches(atom)
385            })
386    }
387}
388
389fn secret_reason(secret: &Secret, atom: &AtomicAction) -> String {
390    format!(
391        "the session read secret material ({}); {} could carry it out",
392        secret.source,
393        atom.describe()
394    )
395}