1use serde::{Deserialize, Serialize};
10
11use super::{CompiledPolicy, EvalContext, checked_atoms};
12use crate::action::{Action, AtomicAction};
13use crate::pattern::{Built, 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 built: &mut Built,
144) -> Result<Vec<GlobPattern>, PolicyError> {
145 crate::taint::protected_writes(policy.taint.as_ref())
146 .flat_map(|p| ctx.spellings(p))
147 .map(|p| GlobPattern::compile_in(&p, ctx.case_insensitive_paths, built))
148 .collect()
149}
150
151pub(super) fn compile_private(
153 policy: &Policy,
154 ctx: &EvalContext,
155 built: &mut Built,
156) -> Result<Vec<GlobPattern>, PolicyError> {
157 policy
158 .taint
159 .iter()
160 .flat_map(|t| &t.private_paths)
161 .flat_map(|p| ctx.spellings(p))
162 .map(|p| GlobPattern::compile_in(&p, ctx.case_insensitive_paths, built))
163 .collect()
164}
165
166impl CompiledPolicy<'_> {
167 #[must_use]
173 pub fn exposure(&self, action: &Action, cwd: &str, paths: &dyn PathResolver) -> Taint {
174 let ctx = EvalContext {
175 cwd: cwd.to_owned(),
176 ..self.ctx.clone()
177 };
178 let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
179 self.exposure_in(action, &atoms)
180 }
181
182 #[must_use]
187 pub fn exposure_and_collection(
188 &self,
189 action: &Action,
190 cwd: &str,
191 paths: &dyn PathResolver,
192 is_dir: &dyn Fn(&str) -> bool,
193 ) -> (Taint, super::staging::Staging) {
194 let ctx = EvalContext {
195 cwd: cwd.to_owned(),
196 ..self.ctx.clone()
197 };
198 let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
199 (
200 self.exposure_in(action, &atoms),
201 self.collected(&atoms, &ctx, paths, is_dir),
202 )
203 }
204
205 fn exposure_in(&self, action: &Action, atoms: &[AtomicAction]) -> Taint {
209 let mut taint = self.exposure_of(atoms);
210 taint.private = self.private_read(atoms);
211 let metadata = atoms.iter().any(|atom| {
212 matches!(atom, AtomicAction::McpTool { .. }) && self.taints(atom).is_none()
213 });
214 if !metadata {
215 taint.seen = self.output_source_in(action, atoms);
216 }
217 if let Some(secret) = taint.secrets.first().map(|s| s.source.clone()) {
218 taint.add_label(super::labels::LABEL_SECRET, &secret);
219 }
220 if let Some(private) = taint.private.clone() {
221 taint.add_label(super::labels::LABEL_PRIVATE, &private);
222 }
223 for atom in atoms {
224 if let Some(kind) = self.taints(atom) {
225 let name = super::labels::untrusted_label(kind, atom);
226 taint.add_label(&name, &atom.describe());
227 }
228 }
229 if let Some(seen) = taint.seen.clone() {
230 taint.add_label(super::labels::LABEL_EXTERNAL, &seen);
231 }
232 taint
233 }
234
235 fn exposure_of(&self, atoms: &[AtomicAction]) -> Taint {
237 let mut taint = Taint::default();
238 for atom in atoms {
239 match atom {
240 AtomicAction::FsRead { .. } if self.names_secret(atom) => {
241 taint.absorb(Taint {
242 secrets: vec![Secret {
243 source: atom.describe(),
244 host: None,
245 }],
246 ..Taint::default()
247 });
248 }
249 _ if self.taints(atom).is_some() => {
250 taint.untrusted.get_or_insert_with(|| atom.describe());
251 }
252 _ => {}
253 }
254 }
255 taint
256 }
257
258 #[must_use]
262 pub fn untrusted_read(
263 &self,
264 action: &Action,
265 cwd: &str,
266 paths: &dyn PathResolver,
267 ) -> Option<(UntrustedKind, String)> {
268 let ctx = EvalContext {
269 cwd: cwd.to_owned(),
270 ..self.ctx.clone()
271 };
272 let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
273 atoms
274 .iter()
275 .find_map(|atom| self.taints(atom).map(|kind| (kind, atom.describe())))
276 }
277
278 pub(super) fn taints(&self, atom: &AtomicAction) -> Option<UntrustedKind> {
284 let kind = UntrustedKind::of(atom)?;
285 match atom {
286 AtomicAction::McpTool { name }
287 if crate::taint::is_metadata_tool(self.policy.taint.as_ref(), name) =>
288 {
289 None
290 }
291 _ => Some(kind),
292 }
293 }
294
295 #[must_use]
301 pub fn with_taint(
302 &self,
303 decision: Decision,
304 action: &Action,
305 paths: &dyn PathResolver,
306 taint: &Taint,
307 ) -> Decision {
308 if *taint == Taint::default() {
311 return decision;
312 }
313 let encoded = if taint.secrets.is_empty() {
317 Vec::new()
318 } else {
319 super::egress::encoded_atoms(action.shown(), |host| {
320 taint.secrets.iter().all(|s| {
321 s.host
322 .as_deref()
323 .is_some_and(|own| own.eq_ignore_ascii_case(host))
324 })
325 })
326 };
327 let encoded = encoded
328 .iter()
329 .filter_map(|atom| self.matched_rules(atom))
330 .filter(|hit| matches!(hit.verdict, Verdict::Deny | Verdict::Review));
331 let atoms = self.atoms(action, paths).0;
332 let flows = self.label_flows(action, &atoms, taint);
333 atoms
334 .iter()
335 .filter_map(|atom| self.tainted(atom, taint))
336 .chain(encoded)
337 .chain(flows)
338 .fold(decision, |mut acc, next| {
339 acc.merge(next);
340 acc
341 })
342 }
343
344 fn tainted(&self, atom: &AtomicAction, taint: &Taint) -> Option<Decision> {
345 let reason = match atom {
346 AtomicAction::Net { host }
347 | AtomicAction::NetWord { host }
348 | AtomicAction::Fetch { host } => {
349 let secret = taint.secrets.iter().find(|s| {
350 !s.host
351 .as_deref()
352 .is_some_and(|own| own.eq_ignore_ascii_case(host))
353 })?;
354 secret_reason(secret, atom)
355 }
356 AtomicAction::McpTool { .. }
357 | AtomicAction::WebSearch { .. }
358 | AtomicAction::UnknownTool { .. } => secret_reason(taint.secrets.first()?, atom),
359 AtomicAction::FsWrite { path } if any_match(&self.protected, path.as_str()) => {
360 format!(
361 "the session read untrusted content ({}); {} changes what runs or what the agent is told later",
362 taint.untrusted.as_ref()?,
363 atom.describe()
364 )
365 }
366 _ => return None,
367 };
368 Some(Decision::single(Verdict::Review, TAINT_RULE, reason))
369 }
370
371 pub(super) fn names_secret(&self, atom: &AtomicAction) -> bool {
372 [&self.deny, &self.repo_review, &self.allow, &self.review]
376 .into_iter()
377 .flatten()
378 .any(|g| {
379 let id = g.id.as_str();
380 (id == SECRET_RULE
381 || id
382 .strip_prefix(REPO_RULE_PREFIX)
383 .is_some_and(|rest| rest == SECRET_RULE))
384 && g.matches(atom)
385 })
386 }
387}
388
389fn secret_reason(secret: &Secret, atom: &AtomicAction) -> String {
390 format!(
391 "the session read secret material ({}); {} could carry it out",
392 secret.source,
393 atom.describe()
394 )
395}