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 #[serde(default, skip_serializing_if = "Vec::is_empty")]
61 pub labels: Vec<super::labels::Label>,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
69#[serde(rename_all = "kebab-case")]
70pub enum UntrustedKind {
71 Web,
73 Mcp,
75 UnknownTool,
77 File,
79}
80
81impl UntrustedKind {
82 #[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 #[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 #[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 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
139pub(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
150pub(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 #[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 #[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 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 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 #[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 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 #[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 if *taint == Taint::default() {
309 return decision;
310 }
311 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 [&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}