1use super::{CompiledPolicy, Taint};
14use crate::action::{Action, AtomicAction};
15use crate::pattern::any_match;
16use crate::realpath::PathResolver;
17use crate::repo::REPO_RULE_PREFIX;
18use crate::rule_id;
19use crate::verdict::{Decision, Verdict};
20use crate::{host, shell};
21
22const PRIVATE_RULES: &[&str] = &[
28 rule_id::SECRETS_PATHS,
29 rule_id::AGENT_CREDENTIALS,
30 rule_id::BUILD_CREDENTIALS,
31 rule_id::KERBEROS_TICKETS,
32 rule_id::CANARY,
33 rule_id::ENV_DUMP,
34 rule_id::ENV_SECRETS,
35];
36
37const PUBLISHERS: &[(&str, &[&str])] = &[
41 ("git", &["push", "send-email"]),
42 (
43 "gh",
44 &[
45 "gist create",
46 "gist edit",
47 "pr create",
48 "pr comment",
49 "pr edit",
50 "issue create",
51 "issue comment",
52 "issue edit",
53 "release create",
54 "release upload",
55 "api",
56 "repo create",
57 ],
58 ),
59 (
60 "glab",
61 &[
62 "mr create",
63 "mr note",
64 "issue create",
65 "issue note",
66 "release create",
67 "api",
68 "snippet create",
69 ],
70 ),
71 ("npm", &["publish"]),
72 ("pnpm", &["publish"]),
73 ("yarn", &["publish", "npm publish"]),
74 ("bun", &["publish"]),
75 ("cargo", &["publish"]),
76 ("twine", &["upload"]),
77 ("gem", &["push"]),
78 ("docker", &["push"]),
79 ("podman", &["push"]),
80 ("poetry", &["publish"]),
81 ("uv", &["publish"]),
82];
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub(super) enum EgressSink {
88 Network,
90 WebSearch,
92 Publish,
94 McpSend,
96}
97
98impl EgressSink {
99 pub(super) fn as_str(self) -> &'static str {
101 match self {
102 Self::Network => "network",
103 Self::WebSearch => "web-search",
104 Self::Publish => "publish",
105 Self::McpSend => "mcp-send",
106 }
107 }
108}
109
110pub(super) const ACTING: &[&str] = &[
112 "send", "post", "upload", "create", "write", "put", "publish", "share", "comment", "message",
113];
114
115impl CompiledPolicy<'_> {
116 pub(super) fn private_read(&self, atoms: &[AtomicAction]) -> Option<String> {
121 atoms.iter().find_map(|atom| {
122 let private = match atom {
123 AtomicAction::FsRead { path } => {
124 (!self.names_secret(atom) && self.names_private(atom))
125 || any_match(&self.private, path.as_str())
126 || self
127 .folders
128 .rules_held(atom)
129 .iter()
130 .any(|rule| is_private_rule(rule))
131 }
132 AtomicAction::Shell { .. } | AtomicAction::EnvRead { .. } => {
133 self.names_private(atom)
134 }
135 _ => false,
136 };
137 private.then(|| atom.describe())
138 })
139 }
140
141 fn names_private(&self, atom: &AtomicAction) -> bool {
143 [&self.deny, &self.repo_review, &self.allow, &self.review]
144 .into_iter()
145 .flatten()
146 .any(|g| is_private_rule(&g.id) && g.matches(atom))
147 }
148
149 pub(super) fn egress_targets(&self, action: &Action, atoms: &[AtomicAction]) -> Vec<String> {
154 self.egress_sinks(action, atoms)
155 .into_iter()
156 .map(|(_, target)| target)
157 .collect()
158 }
159
160 pub(super) fn egress_sinks(
163 &self,
164 action: &Action,
165 atoms: &[AtomicAction],
166 ) -> Vec<(EgressSink, String)> {
167 let mut out: Vec<(EgressSink, String)> = Vec::new();
168 let mut add = |sink: EgressSink, target: String| {
169 if !out.iter().any(|(_, t)| *t == target) {
170 out.push((sink, target));
171 }
172 };
173 for atom in atoms {
174 match atom {
175 AtomicAction::Net { host } | AtomicAction::Fetch { host }
176 if !host::is_loopback(host) =>
177 {
178 add(EgressSink::Network, host.clone());
179 }
180 AtomicAction::WebSearch { .. } => {
181 add(EgressSink::WebSearch, "web-search".to_owned());
182 }
183 AtomicAction::Shell { argv } => {
184 if let Some(publish) = publishes(argv) {
185 add(EgressSink::Publish, publish);
186 }
187 }
188 _ => {}
189 }
190 }
191 for push in self.pushes(action) {
192 let words: Vec<&str> = push.argv.iter().take(2).map(String::as_str).collect();
193 add(EgressSink::Publish, words.join("-"));
194 }
195 if let Action::McpTool {
196 name,
197 writes,
198 hosts,
199 ..
200 } = action.shown()
201 {
202 let tool = name
203 .rsplit("__")
204 .next()
205 .unwrap_or(name)
206 .to_ascii_lowercase();
207 if !writes.is_empty() || !hosts.is_empty() || ACTING.iter().any(|w| tool.contains(w)) {
208 let server = name.split("__").nth(1).unwrap_or(name);
209 add(EgressSink::McpSend, format!("mcp:{server}"));
210 }
211 }
212 out
213 }
214
215 #[must_use]
223 pub fn with_trifecta(
224 &self,
225 decision: Decision,
226 action: &Action,
227 paths: &dyn PathResolver,
228 taint: &Taint,
229 ) -> Decision {
230 let untrusted = taint.untrusted.as_ref().or(taint.seen.as_ref());
231 let private_read = !taint.secrets.is_empty() || taint.private.is_some();
232 let (Some(untrusted), true) = (untrusted, private_read) else {
233 return decision;
234 };
235 if decision.verdict == Verdict::Deny {
236 return decision;
237 }
238 let (atoms, _) = self.atoms(action, paths);
239 let targets: Vec<String> = self
240 .egress_targets(action, &atoms)
241 .into_iter()
242 .filter(|target| taint.private.is_some() || !owned_by_secrets(taint, target))
243 .collect();
244 if targets.is_empty() {
245 return decision;
246 }
247 let private = taint.private.clone().unwrap_or_else(|| {
248 taint
249 .secrets
250 .iter()
251 .find(|s| s.host.is_none())
252 .or(taint.secrets.first())
253 .map(|s| s.source.clone())
254 .unwrap_or_default()
255 });
256 let verdict = crate::taint::TaintSettings::trifecta_under(self.policy.taint.as_ref());
257 let reason = format!(
261 "this session read private data ({private}) and content someone else may have \
262 written ({untrusted}), and this call can send data to {}",
263 targets.join(", ")
264 );
265 let mut out = decision;
266 out.merge(Decision::single(verdict, rule_id::LETHAL_TRIFECTA, reason));
267 out
268 }
269}
270
271pub(super) fn owned_by_secrets(taint: &Taint, target: &str) -> bool {
274 !taint.secrets.is_empty()
275 && taint.secrets.iter().all(|s| {
276 s.host
277 .as_deref()
278 .is_some_and(|own| own.eq_ignore_ascii_case(target))
279 })
280}
281
282fn is_private_rule(id: &str) -> bool {
284 let base = id.strip_prefix(REPO_RULE_PREFIX).unwrap_or(id);
285 PRIVATE_RULES.contains(&base)
286}
287
288fn publishes(argv: &[String]) -> Option<String> {
291 let program = shell::program_name(argv);
292 let (_, commands) = PUBLISHERS.iter().find(|(p, _)| *p == program)?;
293 let words: Vec<&str> = argv
294 .iter()
295 .skip(1)
296 .filter(|w| !w.starts_with('-'))
297 .take(2)
298 .map(String::as_str)
299 .collect();
300 commands.iter().find_map(|command| {
301 let wanted: Vec<&str> = command.split(' ').collect();
302 (words.len() >= wanted.len() && words[..wanted.len()] == wanted[..])
303 .then(|| format!("{program}-{}", wanted.join("-")))
304 })
305}