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 super::{CompiledPolicy, EvalContext, checked_atoms};
10use crate::action::{Action, AtomicAction};
11use crate::pattern::{GlobPattern, any_match};
12use crate::policy::{Policy, PolicyError};
13use crate::realpath::PathResolver;
14use crate::repo::REPO_RULE_PREFIX;
15use crate::verdict::{Decision, Verdict};
16
17/// The rule group whose `fs.read` patterns name secret material, wherever the
18/// policy puts it. In the default policy it denies, so only a policy that asks
19/// for these reads lets one run and taint the session. A repository policy's
20/// group with the same base id (prefixed to `repo:secrets-paths` by
21/// `RepoPolicy::merge`) is also taint-significant.
22const SECRET_RULE: &str = "secrets-paths";
23
24/// The rule id a tightened decision carries.
25const TAINT_RULE: &str = "session-taint";
26
27/// Where secret material in a session came from.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct Secret {
30 /// What brought it in, for reasons (`read /Users/me/.ssh/id_rsa`).
31 pub source: String,
32 /// The one host the secret belongs to and may still go to. `None` for a
33 /// file read: it belongs to no host, so every host asks. The secrets
34 /// broker (ADR-020) raises a `Secret` with its own host when a brokered
35 /// value is used, so later requests to other hosts ask.
36 pub host: Option<String>,
37}
38
39/// What earlier calls of one session exposed it to.
40#[derive(Debug, Clone, Default, PartialEq, Eq)]
41pub struct Taint {
42 /// Secret material the session read, de-duplicated by source.
43 pub secrets: Vec<Secret>,
44 /// The first untrusted content the session read (`fetch docs.rs`), if any.
45 pub untrusted: Option<String>,
46}
47
48impl Taint {
49 /// Add what another call exposed the session to.
50 pub fn absorb(&mut self, other: Taint) {
51 for secret in other.secrets {
52 if !self.secrets.contains(&secret) {
53 self.secrets.push(secret);
54 }
55 }
56 if self.untrusted.is_none() {
57 self.untrusted = other.untrusted;
58 }
59 }
60}
61
62/// The built-in protected paths and the ones `policy` adds, compiled for `ctx`.
63pub(super) fn compile_protected(
64 policy: &Policy,
65 ctx: &EvalContext,
66) -> Result<Vec<GlobPattern>, PolicyError> {
67 crate::taint::protected_writes(policy.taint.as_ref())
68 .flat_map(|p| ctx.spellings(p))
69 .map(|p| GlobPattern::compile(&p, ctx.case_insensitive_paths))
70 .collect()
71}
72
73impl CompiledPolicy<'_> {
74 /// What running `action` in `cwd` exposed its session to: secret material
75 /// from a read the `secrets-paths` group names, untrusted content from a
76 /// fetch, a web search or an MCP result. The caller passes only calls that ran; the parts
77 /// of an action that cannot be classified expose nothing they can name.
78 #[must_use]
79 pub fn exposure(&self, action: &Action, cwd: &str, paths: &dyn PathResolver) -> Taint {
80 let ctx = EvalContext {
81 cwd: cwd.to_owned(),
82 ..self.ctx.clone()
83 };
84 let (atoms, _) = checked_atoms(action, &ctx, paths);
85 let mut taint = Taint::default();
86 for atom in atoms {
87 match atom {
88 AtomicAction::FsRead { .. } if self.names_secret(&atom) => {
89 taint.absorb(Taint {
90 secrets: vec![Secret {
91 source: atom.describe(),
92 host: None,
93 }],
94 untrusted: None,
95 });
96 }
97 AtomicAction::Fetch { .. }
98 | AtomicAction::WebSearch { .. }
99 | AtomicAction::McpTool { .. } => {
100 taint.untrusted.get_or_insert_with(|| atom.describe());
101 }
102 _ => {}
103 }
104 }
105 taint
106 }
107
108 /// `decision` for `action`, tightened by `taint`: after secret material,
109 /// network to any host but the secret's own, and every MCP call and web
110 /// search (the hosts they reach are unknown), asks; after untrusted content, a write to
111 /// a protected path asks. Merging keeps the strictest verdict, so this
112 /// never loosens a decision.
113 #[must_use]
114 pub fn with_taint(
115 &self,
116 decision: Decision,
117 action: &Action,
118 paths: &dyn PathResolver,
119 taint: &Taint,
120 ) -> Decision {
121 // A clean session tightens nothing; skip classifying (and listing the
122 // directories of glob operands) a second time.
123 if *taint == Taint::default() {
124 return decision;
125 }
126 self.atoms(action, paths)
127 .0
128 .iter()
129 .filter_map(|atom| self.tainted(atom, taint))
130 .fold(decision, |mut acc, next| {
131 acc.merge(next);
132 acc
133 })
134 }
135
136 fn tainted(&self, atom: &AtomicAction, taint: &Taint) -> Option<Decision> {
137 let reason = match atom {
138 AtomicAction::Net { host } | AtomicAction::Fetch { host } => {
139 let secret = taint.secrets.iter().find(|s| {
140 !s.host
141 .as_deref()
142 .is_some_and(|own| own.eq_ignore_ascii_case(host))
143 })?;
144 secret_reason(secret, atom)
145 }
146 AtomicAction::McpTool { .. } | AtomicAction::WebSearch { .. } => {
147 secret_reason(taint.secrets.first()?, atom)
148 }
149 AtomicAction::FsWrite { path } if any_match(&self.protected, path.as_str()) => {
150 format!(
151 "the session read untrusted content ({}); {} changes what runs or what the agent is told later",
152 taint.untrusted.as_ref()?,
153 atom.describe()
154 )
155 }
156 _ => return None,
157 };
158 Some(Decision::single(Verdict::Ask, TAINT_RULE, reason))
159 }
160
161 fn names_secret(&self, atom: &AtomicAction) -> bool {
162 // A repository policy's rules are renamed to `repo:<id>` by `RepoPolicy::merge`,
163 // so match the base id and the prefixed one; `repo_ask` carries the ask rules
164 // merged in (ADR-022), so iterate it too.
165 [&self.deny, &self.repo_ask, &self.allow, &self.ask]
166 .into_iter()
167 .flatten()
168 .any(|g| {
169 let id = g.group.id.as_str();
170 (id == SECRET_RULE
171 || id
172 .strip_prefix(REPO_RULE_PREFIX)
173 .is_some_and(|rest| rest == SECRET_RULE))
174 && g.matches(atom)
175 })
176 }
177}
178
179fn secret_reason(secret: &Secret, atom: &AtomicAction) -> String {
180 format!(
181 "the session read secret material ({}); {} could carry it out",
182 secret.source,
183 atom.describe()
184 )
185}