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 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 { .. } | AtomicAction::McpTool { .. } => {
98 taint.untrusted.get_or_insert_with(|| atom.describe());
99 }
100 _ => {}
101 }
102 }
103 taint
104 }
105
106 /// `decision` for `action`, tightened by `taint`: after secret material,
107 /// network to any host but the secret's own, and every MCP call (its
108 /// server's hosts are unknown), asks; after untrusted content, a write to
109 /// a protected path asks. Merging keeps the strictest verdict, so this
110 /// never loosens a decision.
111 #[must_use]
112 pub fn with_taint(
113 &self,
114 decision: Decision,
115 action: &Action,
116 paths: &dyn PathResolver,
117 taint: &Taint,
118 ) -> Decision {
119 // A clean session tightens nothing; skip classifying (and listing the
120 // directories of glob operands) a second time.
121 if *taint == Taint::default() {
122 return decision;
123 }
124 self.atoms(action, paths)
125 .0
126 .iter()
127 .filter_map(|atom| self.tainted(atom, taint))
128 .fold(decision, |mut acc, next| {
129 acc.merge(next);
130 acc
131 })
132 }
133
134 fn tainted(&self, atom: &AtomicAction, taint: &Taint) -> Option<Decision> {
135 let reason = match atom {
136 AtomicAction::Net { host } | AtomicAction::Fetch { host } => {
137 let secret = taint.secrets.iter().find(|s| {
138 !s.host
139 .as_deref()
140 .is_some_and(|own| own.eq_ignore_ascii_case(host))
141 })?;
142 secret_reason(secret, atom)
143 }
144 AtomicAction::McpTool { .. } => secret_reason(taint.secrets.first()?, atom),
145 AtomicAction::FsWrite { path } if any_match(&self.protected, path.as_str()) => {
146 format!(
147 "the session read untrusted content ({}); {} changes what runs or what the agent is told later",
148 taint.untrusted.as_ref()?,
149 atom.describe()
150 )
151 }
152 _ => return None,
153 };
154 Some(Decision::single(Verdict::Ask, TAINT_RULE, reason))
155 }
156
157 fn names_secret(&self, atom: &AtomicAction) -> bool {
158 // A repository policy's rules are renamed to `repo:<id>` by `RepoPolicy::merge`,
159 // so match the base id and the prefixed one; `repo_ask` carries the ask rules
160 // merged in (ADR-022), so iterate it too.
161 [&self.deny, &self.repo_ask, &self.allow, &self.ask]
162 .into_iter()
163 .flatten()
164 .any(|g| {
165 let id = g.group.id.as_str();
166 (id == SECRET_RULE
167 || id
168 .strip_prefix(REPO_RULE_PREFIX)
169 .is_some_and(|rest| rest == SECRET_RULE))
170 && g.matches(atom)
171 })
172 }
173}
174
175fn secret_reason(secret: &Secret, atom: &AtomicAction) -> String {
176 format!(
177 "the session read secret material ({}); {} could carry it out",
178 secret.source,
179 atom.describe()
180 )
181}