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}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
51#[serde(rename_all = "kebab-case")]
52pub enum UntrustedKind {
53 Web,
55 Mcp,
57 UnknownTool,
59 File,
61}
62
63impl UntrustedKind {
64 #[must_use]
66 pub fn of(atom: &AtomicAction) -> Option<Self> {
67 match atom {
68 AtomicAction::Fetch { .. } | AtomicAction::WebSearch { .. } => Some(Self::Web),
69 AtomicAction::McpTool { .. } => Some(Self::Mcp),
70 AtomicAction::UnknownTool { .. } => Some(Self::UnknownTool),
71 _ => None,
72 }
73 }
74
75 #[must_use]
77 pub fn as_str(self) -> &'static str {
78 match self {
79 Self::Web => "web",
80 Self::Mcp => "mcp",
81 Self::UnknownTool => "unknown-tool",
82 Self::File => "file",
83 }
84 }
85
86 #[must_use]
88 pub fn describe(self) -> &'static str {
89 match self {
90 Self::Web => "web content",
91 Self::Mcp => "an MCP tool result",
92 Self::UnknownTool => "an unknown tool's result",
93 Self::File => "a file an exposed session wrote",
94 }
95 }
96}
97
98impl Taint {
99 pub fn absorb(&mut self, other: Taint) {
101 for secret in other.secrets {
102 if !self.secrets.contains(&secret) {
103 self.secrets.push(secret);
104 }
105 }
106 if self.untrusted.is_none() {
107 self.untrusted = other.untrusted;
108 }
109 }
110}
111
112pub(super) fn compile_protected(
114 policy: &Policy,
115 ctx: &EvalContext,
116) -> Result<Vec<GlobPattern>, PolicyError> {
117 crate::taint::protected_writes(policy.taint.as_ref())
118 .flat_map(|p| ctx.spellings(p))
119 .map(|p| GlobPattern::compile(&p, ctx.case_insensitive_paths))
120 .collect()
121}
122
123impl CompiledPolicy<'_> {
124 #[must_use]
130 pub fn exposure(&self, action: &Action, cwd: &str, paths: &dyn PathResolver) -> Taint {
131 let ctx = EvalContext {
132 cwd: cwd.to_owned(),
133 ..self.ctx.clone()
134 };
135 let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
136 self.exposure_of(&atoms)
137 }
138
139 #[must_use]
144 pub fn exposure_and_collection(
145 &self,
146 action: &Action,
147 cwd: &str,
148 paths: &dyn PathResolver,
149 is_dir: &dyn Fn(&str) -> bool,
150 ) -> (Taint, super::staging::Staging) {
151 let ctx = EvalContext {
152 cwd: cwd.to_owned(),
153 ..self.ctx.clone()
154 };
155 let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
156 (
157 self.exposure_of(&atoms),
158 self.collected(&atoms, &ctx, paths, is_dir),
159 )
160 }
161
162 fn exposure_of(&self, atoms: &[AtomicAction]) -> Taint {
164 let mut taint = Taint::default();
165 for atom in atoms {
166 match atom {
167 AtomicAction::FsRead { .. } if self.names_secret(atom) => {
168 taint.absorb(Taint {
169 secrets: vec![Secret {
170 source: atom.describe(),
171 host: None,
172 }],
173 untrusted: None,
174 });
175 }
176 _ if self.taints(atom).is_some() => {
177 taint.untrusted.get_or_insert_with(|| atom.describe());
178 }
179 _ => {}
180 }
181 }
182 taint
183 }
184
185 #[must_use]
189 pub fn untrusted_read(
190 &self,
191 action: &Action,
192 cwd: &str,
193 paths: &dyn PathResolver,
194 ) -> Option<(UntrustedKind, String)> {
195 let ctx = EvalContext {
196 cwd: cwd.to_owned(),
197 ..self.ctx.clone()
198 };
199 let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
200 atoms
201 .iter()
202 .find_map(|atom| self.taints(atom).map(|kind| (kind, atom.describe())))
203 }
204
205 fn taints(&self, atom: &AtomicAction) -> Option<UntrustedKind> {
211 let kind = UntrustedKind::of(atom)?;
212 match atom {
213 AtomicAction::McpTool { name }
214 if crate::taint::is_metadata_tool(self.policy.taint.as_ref(), name) =>
215 {
216 None
217 }
218 _ => Some(kind),
219 }
220 }
221
222 #[must_use]
228 pub fn with_taint(
229 &self,
230 decision: Decision,
231 action: &Action,
232 paths: &dyn PathResolver,
233 taint: &Taint,
234 ) -> Decision {
235 if *taint == Taint::default() {
238 return decision;
239 }
240 let encoded = if taint.secrets.is_empty() {
244 Vec::new()
245 } else {
246 super::egress::encoded_atoms(action.shown(), |host| {
247 taint.secrets.iter().all(|s| {
248 s.host
249 .as_deref()
250 .is_some_and(|own| own.eq_ignore_ascii_case(host))
251 })
252 })
253 };
254 let encoded = encoded
255 .iter()
256 .filter_map(|atom| self.matched_rules(atom))
257 .filter(|hit| matches!(hit.verdict, Verdict::Deny | Verdict::Review));
258 self.atoms(action, paths)
259 .0
260 .iter()
261 .filter_map(|atom| self.tainted(atom, taint))
262 .chain(encoded)
263 .fold(decision, |mut acc, next| {
264 acc.merge(next);
265 acc
266 })
267 }
268
269 fn tainted(&self, atom: &AtomicAction, taint: &Taint) -> Option<Decision> {
270 let reason = match atom {
271 AtomicAction::Net { host }
272 | AtomicAction::NetWord { host }
273 | AtomicAction::Fetch { host } => {
274 let secret = taint.secrets.iter().find(|s| {
275 !s.host
276 .as_deref()
277 .is_some_and(|own| own.eq_ignore_ascii_case(host))
278 })?;
279 secret_reason(secret, atom)
280 }
281 AtomicAction::McpTool { .. }
282 | AtomicAction::WebSearch { .. }
283 | AtomicAction::UnknownTool { .. } => secret_reason(taint.secrets.first()?, atom),
284 AtomicAction::FsWrite { path } if any_match(&self.protected, path.as_str()) => {
285 format!(
286 "the session read untrusted content ({}); {} changes what runs or what the agent is told later",
287 taint.untrusted.as_ref()?,
288 atom.describe()
289 )
290 }
291 _ => return None,
292 };
293 Some(Decision::single(Verdict::Review, TAINT_RULE, reason))
294 }
295
296 fn names_secret(&self, atom: &AtomicAction) -> bool {
297 [&self.deny, &self.repo_review, &self.allow, &self.review]
301 .into_iter()
302 .flatten()
303 .any(|g| {
304 let id = g.id.as_str();
305 (id == SECRET_RULE
306 || id
307 .strip_prefix(REPO_RULE_PREFIX)
308 .is_some_and(|rest| rest == SECRET_RULE))
309 && g.matches(atom)
310 })
311 }
312}
313
314fn secret_reason(secret: &Secret, atom: &AtomicAction) -> String {
315 format!(
316 "the session read secret material ({}); {} could carry it out",
317 secret.source,
318 atom.describe()
319 )
320}