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    /// 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) -> Result<Vec<GlobPattern>, PolicyError> {
144    crate::taint::protected_writes(policy.taint.as_ref())
145        .flat_map(|p| ctx.spellings(p))
146        .map(|p| GlobPattern::compile(&p, ctx.case_insensitive_paths))
147        .collect()
148}
149
150/// The paths `policy`'s `taint.private_paths` names, compiled for `ctx`.
151pub(super) fn compile_private(
152    policy: &Policy,
153    ctx: &EvalContext,
154) -> Result<Vec<GlobPattern>, PolicyError> {
155    policy
156        .taint
157        .iter()
158        .flat_map(|t| &t.private_paths)
159        .flat_map(|p| ctx.spellings(p))
160        .map(|p| GlobPattern::compile(&p, ctx.case_insensitive_paths))
161        .collect()
162}
163
164impl CompiledPolicy<'_> {
165    /// What running `action` in `cwd` exposed its session to: secret material
166    /// from a read the `secrets-paths` group names, untrusted content from a
167    /// fetch, a web search, an unknown tool or an MCP result, except a
168    /// metadata tool's (`taint.metadata_tools`). The caller passes only calls that ran; the parts
169    /// of an action that cannot be classified expose nothing they can name.
170    #[must_use]
171    pub fn exposure(&self, action: &Action, cwd: &str, paths: &dyn PathResolver) -> Taint {
172        let ctx = EvalContext {
173            cwd: cwd.to_owned(),
174            ..self.ctx.clone()
175        };
176        let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
177        self.exposure_in(action, &atoms)
178    }
179
180    /// [`Self::exposure`] and [`Self::collection`] of one call that ran in
181    /// `cwd`, with its atoms worked out once: what a session's fold takes from
182    /// each of its calls, for half the classifying and path resolving of the
183    /// two apart.
184    #[must_use]
185    pub fn exposure_and_collection(
186        &self,
187        action: &Action,
188        cwd: &str,
189        paths: &dyn PathResolver,
190        is_dir: &dyn Fn(&str) -> bool,
191    ) -> (Taint, super::staging::Staging) {
192        let ctx = EvalContext {
193            cwd: cwd.to_owned(),
194            ..self.ctx.clone()
195        };
196        let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
197        (
198            self.exposure_in(action, &atoms),
199            self.collected(&atoms, &ctx, paths, is_dir),
200        )
201    }
202
203    /// [`Self::exposure_of`] of `action`'s atoms, with the private data they
204    /// read and the output someone else may have written that `action` read
205    /// (ADR-113).
206    fn exposure_in(&self, action: &Action, atoms: &[AtomicAction]) -> Taint {
207        let mut taint = self.exposure_of(atoms);
208        taint.private = self.private_read(atoms);
209        let metadata = atoms.iter().any(|atom| {
210            matches!(atom, AtomicAction::McpTool { .. }) && self.taints(atom).is_none()
211        });
212        if !metadata {
213            taint.seen = self.output_source_in(action, atoms);
214        }
215        if let Some(secret) = taint.secrets.first().map(|s| s.source.clone()) {
216            taint.add_label(super::labels::LABEL_SECRET, &secret);
217        }
218        if let Some(private) = taint.private.clone() {
219            taint.add_label(super::labels::LABEL_PRIVATE, &private);
220        }
221        for atom in atoms {
222            if let Some(kind) = self.taints(atom) {
223                let name = super::labels::untrusted_label(kind, atom);
224                taint.add_label(&name, &atom.describe());
225            }
226        }
227        if let Some(seen) = taint.seen.clone() {
228            taint.add_label(super::labels::LABEL_EXTERNAL, &seen);
229        }
230        taint
231    }
232
233    /// What the checked atoms of one call exposed its session to.
234    fn exposure_of(&self, atoms: &[AtomicAction]) -> Taint {
235        let mut taint = Taint::default();
236        for atom in atoms {
237            match atom {
238                AtomicAction::FsRead { .. } if self.names_secret(atom) => {
239                    taint.absorb(Taint {
240                        secrets: vec![Secret {
241                            source: atom.describe(),
242                            host: None,
243                        }],
244                        ..Taint::default()
245                    });
246                }
247                _ if self.taints(atom).is_some() => {
248                    taint.untrusted.get_or_insert_with(|| atom.describe());
249                }
250                _ => {}
251            }
252        }
253        taint
254    }
255
256    /// The first untrusted content running `action` in `cwd` read, with what
257    /// kind it is: the same atoms [`CompiledPolicy::exposure`] counts, for
258    /// reports that say where the content came from (ADR-056).
259    #[must_use]
260    pub fn untrusted_read(
261        &self,
262        action: &Action,
263        cwd: &str,
264        paths: &dyn PathResolver,
265    ) -> Option<(UntrustedKind, String)> {
266        let ctx = EvalContext {
267            cwd: cwd.to_owned(),
268            ..self.ctx.clone()
269        };
270        let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
271        atoms
272            .iter()
273            .find_map(|atom| self.taints(atom).map(|kind| (kind, atom.describe())))
274    }
275
276    /// The kind of untrusted content `atom` brings into its session, which
277    /// then taints it: [`UntrustedKind::of`], except the result of an MCP tool
278    /// that returns metadata, not content (a browser's tab list,
279    /// `taint.metadata_tools`). Injected input still reads that result
280    /// ([`Self::output_source`]): a page sets its own title and URL.
281    pub(super) fn taints(&self, atom: &AtomicAction) -> Option<UntrustedKind> {
282        let kind = UntrustedKind::of(atom)?;
283        match atom {
284            AtomicAction::McpTool { name }
285                if crate::taint::is_metadata_tool(self.policy.taint.as_ref(), name) =>
286            {
287                None
288            }
289            _ => Some(kind),
290        }
291    }
292
293    /// `decision` for `action`, tightened by `taint`: after secret material,
294    /// network to any host but the secret's own, and every MCP call, web
295    /// search and unknown tool (the hosts they reach are unknown), needs review; after untrusted content, a write to
296    /// a protected path needs review. Merging keeps the strictest verdict, so this
297    /// never loosens a decision.
298    #[must_use]
299    pub fn with_taint(
300        &self,
301        decision: Decision,
302        action: &Action,
303        paths: &dyn PathResolver,
304        taint: &Taint,
305    ) -> Decision {
306        // A clean session tightens nothing; skip classifying (and listing the
307        // directories of glob operands) a second time.
308        if *taint == Taint::default() {
309            return decision;
310        }
311        // After a secret read, a long encoded value in a URL is what a secret
312        // looks like on its way out: `@encoded-egress` atoms, which the policy's
313        // rules decide (`encoded-egress` denies them in the default policy).
314        let encoded = if taint.secrets.is_empty() {
315            Vec::new()
316        } else {
317            super::egress::encoded_atoms(action.shown(), |host| {
318                taint.secrets.iter().all(|s| {
319                    s.host
320                        .as_deref()
321                        .is_some_and(|own| own.eq_ignore_ascii_case(host))
322                })
323            })
324        };
325        let encoded = encoded
326            .iter()
327            .filter_map(|atom| self.matched_rules(atom))
328            .filter(|hit| matches!(hit.verdict, Verdict::Deny | Verdict::Review));
329        let atoms = self.atoms(action, paths).0;
330        let flows = self.label_flows(action, &atoms, taint);
331        atoms
332            .iter()
333            .filter_map(|atom| self.tainted(atom, taint))
334            .chain(encoded)
335            .chain(flows)
336            .fold(decision, |mut acc, next| {
337                acc.merge(next);
338                acc
339            })
340    }
341
342    fn tainted(&self, atom: &AtomicAction, taint: &Taint) -> Option<Decision> {
343        let reason = match atom {
344            AtomicAction::Net { host }
345            | AtomicAction::NetWord { host }
346            | AtomicAction::Fetch { host } => {
347                let secret = taint.secrets.iter().find(|s| {
348                    !s.host
349                        .as_deref()
350                        .is_some_and(|own| own.eq_ignore_ascii_case(host))
351                })?;
352                secret_reason(secret, atom)
353            }
354            AtomicAction::McpTool { .. }
355            | AtomicAction::WebSearch { .. }
356            | AtomicAction::UnknownTool { .. } => secret_reason(taint.secrets.first()?, atom),
357            AtomicAction::FsWrite { path } if any_match(&self.protected, path.as_str()) => {
358                format!(
359                    "the session read untrusted content ({}); {} changes what runs or what the agent is told later",
360                    taint.untrusted.as_ref()?,
361                    atom.describe()
362                )
363            }
364            _ => return None,
365        };
366        Some(Decision::single(Verdict::Review, TAINT_RULE, reason))
367    }
368
369    pub(super) fn names_secret(&self, atom: &AtomicAction) -> bool {
370        // A repository policy's rules are renamed to `repo:<id>` by `RepoPolicy::merge`,
371        // so match the base id and the prefixed one; `repo_review` carries the review rules
372        // merged in (ADR-022), so iterate it too.
373        [&self.deny, &self.repo_review, &self.allow, &self.review]
374            .into_iter()
375            .flatten()
376            .any(|g| {
377                let id = g.id.as_str();
378                (id == SECRET_RULE
379                    || id
380                        .strip_prefix(REPO_RULE_PREFIX)
381                        .is_some_and(|rest| rest == SECRET_RULE))
382                    && g.matches(atom)
383            })
384    }
385}
386
387fn secret_reason(secret: &Secret, atom: &AtomicAction) -> String {
388    format!(
389        "the session read secret material ({}); {} could carry it out",
390        secret.source,
391        atom.describe()
392    )
393}