use serde::{Deserialize, Serialize};
use super::{CompiledPolicy, EvalContext, checked_atoms};
use crate::action::{Action, AtomicAction};
use crate::pattern::{Built, GlobPattern, any_match};
use crate::policy::{Policy, PolicyError};
use crate::realpath::PathResolver;
use crate::repo::REPO_RULE_PREFIX;
use crate::rule_id::{SECRETS_PATHS as SECRET_RULE, SESSION_TAINT as TAINT_RULE};
use crate::verdict::{Decision, Verdict};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Secret {
pub source: String,
pub host: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Taint {
pub secrets: Vec<Secret>,
pub untrusted: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub private: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub seen: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub labels: Vec<super::labels::Label>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum UntrustedKind {
Web,
Mcp,
UnknownTool,
File,
}
impl UntrustedKind {
#[must_use]
pub fn of(atom: &AtomicAction) -> Option<Self> {
match atom {
AtomicAction::Fetch { .. } | AtomicAction::WebSearch { .. } => Some(Self::Web),
AtomicAction::McpTool { .. } => Some(Self::Mcp),
AtomicAction::UnknownTool { .. } => Some(Self::UnknownTool),
_ => None,
}
}
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Web => "web",
Self::Mcp => "mcp",
Self::UnknownTool => "unknown-tool",
Self::File => "file",
}
}
#[must_use]
pub fn describe(self) -> &'static str {
match self {
Self::Web => "web content",
Self::Mcp => "an MCP tool result",
Self::UnknownTool => "an unknown tool's result",
Self::File => "a file an exposed session wrote",
}
}
}
impl Taint {
pub fn absorb(&mut self, other: Taint) {
for secret in other.secrets {
if !self.secrets.contains(&secret) {
self.secrets.push(secret);
}
}
if self.untrusted.is_none() {
self.untrusted = other.untrusted;
}
if self.private.is_none() {
self.private = other.private;
}
if self.seen.is_none() {
self.seen = other.seen;
}
for label in other.labels {
self.add_label(&label.name, &label.source);
}
}
}
pub(super) fn compile_protected(
policy: &Policy,
ctx: &EvalContext,
built: &mut Built,
) -> Result<Vec<GlobPattern>, PolicyError> {
crate::taint::protected_writes(policy.taint.as_ref())
.flat_map(|p| ctx.spellings(p))
.map(|p| GlobPattern::compile_in(&p, ctx.case_insensitive_paths, built))
.collect()
}
pub(super) fn compile_private(
policy: &Policy,
ctx: &EvalContext,
built: &mut Built,
) -> Result<Vec<GlobPattern>, PolicyError> {
policy
.taint
.iter()
.flat_map(|t| &t.private_paths)
.flat_map(|p| ctx.spellings(p))
.map(|p| GlobPattern::compile_in(&p, ctx.case_insensitive_paths, built))
.collect()
}
impl CompiledPolicy<'_> {
#[must_use]
pub fn exposure(&self, action: &Action, cwd: &str, paths: &dyn PathResolver) -> Taint {
let ctx = EvalContext {
cwd: cwd.to_owned(),
..self.ctx.clone()
};
let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
self.exposure_in(action, &atoms)
}
#[must_use]
pub fn exposure_and_collection(
&self,
action: &Action,
cwd: &str,
paths: &dyn PathResolver,
is_dir: &dyn Fn(&str) -> bool,
) -> (Taint, super::staging::Staging) {
let ctx = EvalContext {
cwd: cwd.to_owned(),
..self.ctx.clone()
};
let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
(
self.exposure_in(action, &atoms),
self.collected(&atoms, &ctx, paths, is_dir),
)
}
fn exposure_in(&self, action: &Action, atoms: &[AtomicAction]) -> Taint {
let mut taint = self.exposure_of(atoms);
taint.private = self.private_read(atoms);
let metadata = atoms.iter().any(|atom| {
matches!(atom, AtomicAction::McpTool { .. }) && self.taints(atom).is_none()
});
if !metadata {
taint.seen = self.output_source_in(action, atoms);
}
if let Some(secret) = taint.secrets.first().map(|s| s.source.clone()) {
taint.add_label(super::labels::LABEL_SECRET, &secret);
}
if let Some(private) = taint.private.clone() {
taint.add_label(super::labels::LABEL_PRIVATE, &private);
}
for atom in atoms {
if let Some(kind) = self.taints(atom) {
let name = super::labels::untrusted_label(kind, atom);
taint.add_label(&name, &atom.describe());
}
}
if let Some(seen) = taint.seen.clone() {
taint.add_label(super::labels::LABEL_EXTERNAL, &seen);
}
taint
}
fn exposure_of(&self, atoms: &[AtomicAction]) -> Taint {
let mut taint = Taint::default();
for atom in atoms {
match atom {
AtomicAction::FsRead { .. } if self.names_secret(atom) => {
taint.absorb(Taint {
secrets: vec![Secret {
source: atom.describe(),
host: None,
}],
..Taint::default()
});
}
_ if self.taints(atom).is_some() => {
taint.untrusted.get_or_insert_with(|| atom.describe());
}
_ => {}
}
}
taint
}
#[must_use]
pub fn untrusted_read(
&self,
action: &Action,
cwd: &str,
paths: &dyn PathResolver,
) -> Option<(UntrustedKind, String)> {
let ctx = EvalContext {
cwd: cwd.to_owned(),
..self.ctx.clone()
};
let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
atoms
.iter()
.find_map(|atom| self.taints(atom).map(|kind| (kind, atom.describe())))
}
pub(super) fn taints(&self, atom: &AtomicAction) -> Option<UntrustedKind> {
let kind = UntrustedKind::of(atom)?;
match atom {
AtomicAction::McpTool { name }
if crate::taint::is_metadata_tool(self.policy.taint.as_ref(), name) =>
{
None
}
_ => Some(kind),
}
}
#[must_use]
pub fn with_taint(
&self,
decision: Decision,
action: &Action,
paths: &dyn PathResolver,
taint: &Taint,
) -> Decision {
if *taint == Taint::default() {
return decision;
}
let encoded = if taint.secrets.is_empty() {
Vec::new()
} else {
super::egress::encoded_atoms(action.shown(), |host| {
taint.secrets.iter().all(|s| {
s.host
.as_deref()
.is_some_and(|own| own.eq_ignore_ascii_case(host))
})
})
};
let encoded = encoded
.iter()
.filter_map(|atom| self.matched_rules(atom))
.filter(|hit| matches!(hit.verdict, Verdict::Deny | Verdict::Review));
let atoms = self.atoms(action, paths).0;
let flows = self.label_flows(action, &atoms, taint);
atoms
.iter()
.filter_map(|atom| self.tainted(atom, taint))
.chain(encoded)
.chain(flows)
.fold(decision, |mut acc, next| {
acc.merge(next);
acc
})
}
fn tainted(&self, atom: &AtomicAction, taint: &Taint) -> Option<Decision> {
let reason = match atom {
AtomicAction::Net { host }
| AtomicAction::NetWord { host }
| AtomicAction::Fetch { host } => {
let secret = taint.secrets.iter().find(|s| {
!s.host
.as_deref()
.is_some_and(|own| own.eq_ignore_ascii_case(host))
})?;
secret_reason(secret, atom)
}
AtomicAction::McpTool { .. }
| AtomicAction::WebSearch { .. }
| AtomicAction::UnknownTool { .. } => secret_reason(taint.secrets.first()?, atom),
AtomicAction::FsWrite { path } if any_match(&self.protected, path.as_str()) => {
format!(
"the session read untrusted content ({}); {} changes what runs or what the agent is told later",
taint.untrusted.as_ref()?,
atom.describe()
)
}
_ => return None,
};
Some(Decision::single(Verdict::Review, TAINT_RULE, reason))
}
pub(super) fn names_secret(&self, atom: &AtomicAction) -> bool {
[&self.deny, &self.repo_review, &self.allow, &self.review]
.into_iter()
.flatten()
.any(|g| {
let id = g.id.as_str();
(id == SECRET_RULE
|| id
.strip_prefix(REPO_RULE_PREFIX)
.is_some_and(|rest| rest == SECRET_RULE))
&& g.matches(atom)
})
}
}
fn secret_reason(secret: &Secret, atom: &AtomicAction) -> String {
format!(
"the session read secret material ({}); {} could carry it out",
secret.source,
atom.describe()
)
}