use super::{CompiledPolicy, Taint};
use crate::action::{Action, AtomicAction};
use crate::pattern::any_match;
use crate::realpath::PathResolver;
use crate::repo::REPO_RULE_PREFIX;
use crate::rule_id;
use crate::verdict::{Decision, Verdict};
use crate::{host, shell};
const PRIVATE_RULES: &[&str] = &[
rule_id::SECRETS_PATHS,
rule_id::AGENT_CREDENTIALS,
rule_id::BUILD_CREDENTIALS,
rule_id::KERBEROS_TICKETS,
rule_id::CANARY,
rule_id::ENV_DUMP,
rule_id::ENV_SECRETS,
];
const PUBLISHERS: &[(&str, &[&str])] = &[
("git", &["push", "send-email"]),
(
"gh",
&[
"gist create",
"gist edit",
"pr create",
"pr comment",
"pr edit",
"issue create",
"issue comment",
"issue edit",
"release create",
"release upload",
"api",
"repo create",
],
),
(
"glab",
&[
"mr create",
"mr note",
"issue create",
"issue note",
"release create",
"api",
"snippet create",
],
),
("npm", &["publish"]),
("pnpm", &["publish"]),
("yarn", &["publish", "npm publish"]),
("bun", &["publish"]),
("cargo", &["publish"]),
("twine", &["upload"]),
("gem", &["push"]),
("docker", &["push"]),
("podman", &["push"]),
("poetry", &["publish"]),
("uv", &["publish"]),
];
pub(super) const ACTING: &[&str] = &[
"send", "post", "upload", "create", "write", "put", "publish", "share", "comment", "message",
];
impl CompiledPolicy<'_> {
pub(super) fn private_read(&self, atoms: &[AtomicAction]) -> Option<String> {
atoms.iter().find_map(|atom| {
let private = match atom {
AtomicAction::FsRead { path } => {
(!self.names_secret(atom) && self.names_private(atom))
|| any_match(&self.private, path.as_str())
|| self
.folders
.rules_held(atom)
.iter()
.any(|rule| is_private_rule(rule))
}
AtomicAction::Shell { .. } | AtomicAction::EnvRead { .. } => {
self.names_private(atom)
}
_ => false,
};
private.then(|| atom.describe())
})
}
fn names_private(&self, atom: &AtomicAction) -> bool {
[&self.deny, &self.repo_review, &self.allow, &self.review]
.into_iter()
.flatten()
.any(|g| is_private_rule(&g.id) && g.matches(atom))
}
pub(super) fn egress_targets(&self, action: &Action, atoms: &[AtomicAction]) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut add = |target: String| {
if !out.contains(&target) {
out.push(target);
}
};
for atom in atoms {
match atom {
AtomicAction::Net { host } | AtomicAction::Fetch { host }
if !host::is_loopback(host) =>
{
add(host.clone());
}
AtomicAction::WebSearch { .. } => add("web-search".to_owned()),
AtomicAction::Shell { argv } => {
if let Some(publish) = publishes(argv) {
add(publish);
}
}
_ => {}
}
}
for push in self.pushes(action) {
let words: Vec<&str> = push.argv.iter().take(2).map(String::as_str).collect();
add(words.join("-"));
}
if let Action::McpTool {
name,
writes,
hosts,
..
} = action.shown()
{
let tool = name
.rsplit("__")
.next()
.unwrap_or(name)
.to_ascii_lowercase();
if !writes.is_empty() || !hosts.is_empty() || ACTING.iter().any(|w| tool.contains(w)) {
let server = name.split("__").nth(1).unwrap_or(name);
add(format!("mcp:{server}"));
}
}
out
}
#[must_use]
pub fn with_trifecta(
&self,
decision: Decision,
action: &Action,
paths: &dyn PathResolver,
taint: &Taint,
) -> Decision {
let untrusted = taint.untrusted.as_ref().or(taint.seen.as_ref());
let private_read = !taint.secrets.is_empty() || taint.private.is_some();
let (Some(untrusted), true) = (untrusted, private_read) else {
return decision;
};
if decision.verdict == Verdict::Deny {
return decision;
}
let (atoms, _) = self.atoms(action, paths);
let targets: Vec<String> = self
.egress_targets(action, &atoms)
.into_iter()
.filter(|target| taint.private.is_some() || !owned_by_secrets(taint, target))
.collect();
if targets.is_empty() {
return decision;
}
let private = taint.private.clone().unwrap_or_else(|| {
taint
.secrets
.iter()
.find(|s| s.host.is_none())
.or(taint.secrets.first())
.map(|s| s.source.clone())
.unwrap_or_default()
});
let verdict = crate::taint::TaintSettings::trifecta_under(self.policy.taint.as_ref());
let reason = format!(
"this session read private data ({private}) and content someone else may have \
written ({untrusted}), and this call can send data to {}",
targets.join(", ")
);
let mut out = decision;
out.merge(Decision::single(verdict, rule_id::LETHAL_TRIFECTA, reason));
out
}
}
fn owned_by_secrets(taint: &Taint, target: &str) -> bool {
!taint.secrets.is_empty()
&& taint.secrets.iter().all(|s| {
s.host
.as_deref()
.is_some_and(|own| own.eq_ignore_ascii_case(target))
})
}
fn is_private_rule(id: &str) -> bool {
let base = id.strip_prefix(REPO_RULE_PREFIX).unwrap_or(id);
PRIVATE_RULES.contains(&base)
}
fn publishes(argv: &[String]) -> Option<String> {
let program = shell::program_name(argv);
let (_, commands) = PUBLISHERS.iter().find(|(p, _)| *p == program)?;
let words: Vec<&str> = argv
.iter()
.skip(1)
.filter(|w| !w.starts_with('-'))
.take(2)
.map(String::as_str)
.collect();
commands.iter().find_map(|command| {
let wanted: Vec<&str> = command.split(' ').collect();
(words.len() >= wanted.len() && words[..wanted.len()] == wanted[..])
.then(|| format!("{program}-{}", wanted.join("-")))
})
}