1use 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;
17use crate::rule_id::{SECRETS_PATHS as SECRET_RULE, SESSION_TAINT as TAINT_RULE};
23use crate::verdict::{Decision, Verdict};
24
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Secret {
28 pub source: String,
30 pub host: Option<String>,
35}
36
37#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
39pub struct Taint {
40 pub secrets: Vec<Secret>,
42 pub untrusted: Option<String>,
44 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub private: Option<String>,
49 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub seen: Option<String>,
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
63#[serde(rename_all = "kebab-case")]
64pub enum UntrustedKind {
65 Web,
67 Mcp,
69 UnknownTool,
71 File,
73}
74
75impl UntrustedKind {
76 #[must_use]
78 pub fn of(atom: &AtomicAction) -> Option<Self> {
79 match atom {
80 AtomicAction::Fetch { .. } | AtomicAction::WebSearch { .. } => Some(Self::Web),
81 AtomicAction::McpTool { .. } => Some(Self::Mcp),
82 AtomicAction::UnknownTool { .. } => Some(Self::UnknownTool),
83 _ => None,
84 }
85 }
86
87 #[must_use]
89 pub fn as_str(self) -> &'static str {
90 match self {
91 Self::Web => "web",
92 Self::Mcp => "mcp",
93 Self::UnknownTool => "unknown-tool",
94 Self::File => "file",
95 }
96 }
97
98 #[must_use]
100 pub fn describe(self) -> &'static str {
101 match self {
102 Self::Web => "web content",
103 Self::Mcp => "an MCP tool result",
104 Self::UnknownTool => "an unknown tool's result",
105 Self::File => "a file an exposed session wrote",
106 }
107 }
108}
109
110impl Taint {
111 pub fn absorb(&mut self, other: Taint) {
113 for secret in other.secrets {
114 if !self.secrets.contains(&secret) {
115 self.secrets.push(secret);
116 }
117 }
118 if self.untrusted.is_none() {
119 self.untrusted = other.untrusted;
120 }
121 if self.private.is_none() {
122 self.private = other.private;
123 }
124 if self.seen.is_none() {
125 self.seen = other.seen;
126 }
127 }
128}
129
130pub(super) fn compile_protected(
132 policy: &Policy,
133 ctx: &EvalContext,
134) -> Result<Vec<GlobPattern>, PolicyError> {
135 crate::taint::protected_writes(policy.taint.as_ref())
136 .flat_map(|p| ctx.spellings(p))
137 .map(|p| GlobPattern::compile(&p, ctx.case_insensitive_paths))
138 .collect()
139}
140
141pub(super) fn compile_private(
143 policy: &Policy,
144 ctx: &EvalContext,
145) -> Result<Vec<GlobPattern>, PolicyError> {
146 policy
147 .taint
148 .iter()
149 .flat_map(|t| &t.private_paths)
150 .flat_map(|p| ctx.spellings(p))
151 .map(|p| GlobPattern::compile(&p, ctx.case_insensitive_paths))
152 .collect()
153}
154
155impl CompiledPolicy<'_> {
156 #[must_use]
162 pub fn exposure(&self, action: &Action, cwd: &str, paths: &dyn PathResolver) -> Taint {
163 let ctx = EvalContext {
164 cwd: cwd.to_owned(),
165 ..self.ctx.clone()
166 };
167 let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
168 self.exposure_in(action, &atoms)
169 }
170
171 #[must_use]
176 pub fn exposure_and_collection(
177 &self,
178 action: &Action,
179 cwd: &str,
180 paths: &dyn PathResolver,
181 is_dir: &dyn Fn(&str) -> bool,
182 ) -> (Taint, super::staging::Staging) {
183 let ctx = EvalContext {
184 cwd: cwd.to_owned(),
185 ..self.ctx.clone()
186 };
187 let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
188 (
189 self.exposure_in(action, &atoms),
190 self.collected(&atoms, &ctx, paths, is_dir),
191 )
192 }
193
194 fn exposure_in(&self, action: &Action, atoms: &[AtomicAction]) -> Taint {
198 let mut taint = self.exposure_of(atoms);
199 taint.private = self.private_read(atoms);
200 let metadata = atoms.iter().any(|atom| {
201 matches!(atom, AtomicAction::McpTool { .. }) && self.taints(atom).is_none()
202 });
203 if !metadata {
204 taint.seen = self.output_source_in(action, atoms);
205 }
206 taint
207 }
208
209 fn exposure_of(&self, atoms: &[AtomicAction]) -> Taint {
211 let mut taint = Taint::default();
212 for atom in atoms {
213 match atom {
214 AtomicAction::FsRead { .. } if self.names_secret(atom) => {
215 taint.absorb(Taint {
216 secrets: vec![Secret {
217 source: atom.describe(),
218 host: None,
219 }],
220 ..Taint::default()
221 });
222 }
223 _ if self.taints(atom).is_some() => {
224 taint.untrusted.get_or_insert_with(|| atom.describe());
225 }
226 _ => {}
227 }
228 }
229 taint
230 }
231
232 #[must_use]
236 pub fn untrusted_read(
237 &self,
238 action: &Action,
239 cwd: &str,
240 paths: &dyn PathResolver,
241 ) -> Option<(UntrustedKind, String)> {
242 let ctx = EvalContext {
243 cwd: cwd.to_owned(),
244 ..self.ctx.clone()
245 };
246 let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
247 atoms
248 .iter()
249 .find_map(|atom| self.taints(atom).map(|kind| (kind, atom.describe())))
250 }
251
252 pub(super) fn taints(&self, atom: &AtomicAction) -> Option<UntrustedKind> {
258 let kind = UntrustedKind::of(atom)?;
259 match atom {
260 AtomicAction::McpTool { name }
261 if crate::taint::is_metadata_tool(self.policy.taint.as_ref(), name) =>
262 {
263 None
264 }
265 _ => Some(kind),
266 }
267 }
268
269 #[must_use]
275 pub fn with_taint(
276 &self,
277 decision: Decision,
278 action: &Action,
279 paths: &dyn PathResolver,
280 taint: &Taint,
281 ) -> Decision {
282 if *taint == Taint::default() {
285 return decision;
286 }
287 let encoded = if taint.secrets.is_empty() {
291 Vec::new()
292 } else {
293 super::egress::encoded_atoms(action.shown(), |host| {
294 taint.secrets.iter().all(|s| {
295 s.host
296 .as_deref()
297 .is_some_and(|own| own.eq_ignore_ascii_case(host))
298 })
299 })
300 };
301 let encoded = encoded
302 .iter()
303 .filter_map(|atom| self.matched_rules(atom))
304 .filter(|hit| matches!(hit.verdict, Verdict::Deny | Verdict::Review));
305 self.atoms(action, paths)
306 .0
307 .iter()
308 .filter_map(|atom| self.tainted(atom, taint))
309 .chain(encoded)
310 .fold(decision, |mut acc, next| {
311 acc.merge(next);
312 acc
313 })
314 }
315
316 fn tainted(&self, atom: &AtomicAction, taint: &Taint) -> Option<Decision> {
317 let reason = match atom {
318 AtomicAction::Net { host }
319 | AtomicAction::NetWord { host }
320 | AtomicAction::Fetch { host } => {
321 let secret = taint.secrets.iter().find(|s| {
322 !s.host
323 .as_deref()
324 .is_some_and(|own| own.eq_ignore_ascii_case(host))
325 })?;
326 secret_reason(secret, atom)
327 }
328 AtomicAction::McpTool { .. }
329 | AtomicAction::WebSearch { .. }
330 | AtomicAction::UnknownTool { .. } => secret_reason(taint.secrets.first()?, atom),
331 AtomicAction::FsWrite { path } if any_match(&self.protected, path.as_str()) => {
332 format!(
333 "the session read untrusted content ({}); {} changes what runs or what the agent is told later",
334 taint.untrusted.as_ref()?,
335 atom.describe()
336 )
337 }
338 _ => return None,
339 };
340 Some(Decision::single(Verdict::Review, TAINT_RULE, reason))
341 }
342
343 pub(super) fn names_secret(&self, atom: &AtomicAction) -> bool {
344 [&self.deny, &self.repo_review, &self.allow, &self.review]
348 .into_iter()
349 .flatten()
350 .any(|g| {
351 let id = g.id.as_str();
352 (id == SECRET_RULE
353 || id
354 .strip_prefix(REPO_RULE_PREFIX)
355 .is_some_and(|rest| rest == SECRET_RULE))
356 && g.matches(atom)
357 })
358 }
359}
360
361fn secret_reason(secret: &Secret, atom: &AtomicAction) -> String {
362 format!(
363 "the session read secret material ({}); {} could carry it out",
364 secret.source,
365 atom.describe()
366 )
367}