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