1use super::{CompiledPolicy, EvalContext};
11use crate::action::{Action, AtomicAction};
12use crate::arguments::Arguments;
13use crate::injection::{InjectedLookup, Token, TokenKind};
14use crate::pattern::{Built, GlobPattern, any_match};
15use crate::policy::PolicyError;
16use crate::predicate::{Predicate, Test};
17use crate::realpath::PathResolver;
18use crate::verdict::{Decision, Verdict};
19
20const SHOWN_CHARS: usize = 80;
22
23#[derive(Debug)]
25pub(super) struct CompiledWhen {
26 conditions: Vec<Condition>,
27}
28
29#[derive(Debug)]
30struct Condition {
31 names: Option<Vec<String>>,
33 test: Test,
34 negated: bool,
35 patterns: Vec<GlobPattern>,
36 shown: String,
38}
39
40impl CompiledWhen {
41 pub(super) fn compile(
43 when: &[Predicate],
44 ctx: &EvalContext,
45 built: &mut Built,
46 ) -> Result<Option<Self>, PolicyError> {
47 if when.is_empty() {
48 return Ok(None);
49 }
50 let conditions = when
51 .iter()
52 .filter_map(|p| p.test().map(|t| (p, t)))
53 .map(|(predicate, (test, negated, list))| {
54 let mut compile = |p: &str, ci: bool| GlobPattern::compile_in(p, ci, built);
55 let patterns = match test {
56 Test::Under => list
57 .iter()
58 .flat_map(|p| ctx.spellings(p))
59 .flat_map(|p| {
60 let root = p.trim_end_matches('/').to_owned();
61 [format!("{root}/**"), root]
62 })
63 .map(|p| compile(&p, ctx.case_insensitive_paths))
64 .collect::<Result<Vec<_>, _>>()?,
65 Test::HostIn | Test::In => list
66 .iter()
67 .map(|p| compile(p, true))
68 .collect::<Result<Vec<_>, _>>()?,
69 Test::Matches => list
70 .iter()
71 .map(|p| compile(p, false))
72 .collect::<Result<Vec<_>, _>>()?,
73 Test::Untrusted => Vec::new(),
74 };
75 Ok(Condition {
76 names: predicate
77 .arg
78 .as_ref()
79 .map(|a| a.names().into_iter().map(str::to_owned).collect()),
80 test,
81 negated,
82 patterns,
83 shown: predicate.describe(),
84 })
85 })
86 .collect::<Result<Vec<_>, PolicyError>>()?;
87 Ok(Some(Self { conditions }))
88 }
89}
90
91struct Call<'a> {
93 policy: &'a CompiledPolicy<'a>,
94 atoms: &'a [AtomicAction],
95 args: &'a Arguments,
96 seen: &'a dyn InjectedLookup,
97}
98
99impl CompiledPolicy<'_> {
100 #[must_use]
108 pub fn with_arguments(
109 &self,
110 decision: Decision,
111 action: &Action,
112 paths: &dyn PathResolver,
113 args: &Arguments,
114 seen: &dyn InjectedLookup,
115 ) -> Decision {
116 let lists = [
117 (&self.deny, Verdict::Deny),
118 (&self.repo_review, Verdict::Review),
119 (&self.review, Verdict::Review),
120 ];
121 let conditional = lists
122 .iter()
123 .any(|(groups, _)| groups.iter().any(|g| g.when.is_some()));
124 if !conditional {
125 return decision;
126 }
127 let (atoms, _) = self.all_atoms(action, paths);
128 let mut all = derived(action);
129 all.extend(args);
130 let call = Call {
131 policy: self,
132 atoms: &atoms,
133 args: &all,
134 seen,
135 };
136 let mut out = decision;
137 for (groups, verdict) in lists {
138 for group in groups {
139 let Some(when) = &group.when else {
140 continue;
141 };
142 if !atoms.iter().any(|atom| group.matches_patterns(atom)) {
143 continue;
144 }
145 let Some(witness) = when.holds(&call) else {
146 continue;
147 };
148 let why = group
149 .reason
150 .as_ref()
151 .map_or_else(|| witness.clone(), |r| format!("{r}: {witness}"));
152 out.merge(Decision::single(verdict, &group.id, why));
153 }
154 }
155 out
156 }
157}
158
159impl CompiledWhen {
160 fn holds(&self, call: &Call<'_>) -> Option<String> {
162 let witnesses: Option<Vec<String>> =
163 self.conditions.iter().map(|c| c.holds(call)).collect();
164 witnesses.map(|w| w.join("; "))
165 }
166}
167
168impl Condition {
169 fn holds(&self, call: &Call<'_>) -> Option<String> {
171 let values = self.values(call);
172 if !self.negated {
173 return values
174 .iter()
175 .find(|(_, v)| self.passes(call, v))
176 .map(|(k, v)| format!("{k} {} is {}", shown(v), self.shown));
177 }
178 if values.is_empty() {
179 return Some(format!("the call names no value for {}", self.shown));
180 }
181 if call.args.is_cut() {
182 return Some(format!(
183 "not every argument was read, so {} cannot be ruled out",
184 self.shown
185 ));
186 }
187 values
188 .iter()
189 .find(|(_, v)| !self.passes(call, v))
190 .map(|(k, v)| format!("{k} {} is {}", shown(v), self.shown))
191 }
192
193 fn values(&self, call: &Call<'_>) -> Vec<(String, String)> {
197 let ctx = &call.policy.ctx;
198 let Some(names) = &self.names else {
199 return match self.test {
200 Test::Under => atom_values(call.atoms, |atom| match atom {
201 AtomicAction::FsRead { path } | AtomicAction::FsWrite { path } => {
202 Some(path.as_str())
203 }
204 _ => None,
205 }),
206 Test::HostIn => atom_values(call.atoms, |atom| match atom {
207 AtomicAction::Net { host } | AtomicAction::Fetch { host } => Some(host),
208 _ => None,
209 }),
210 _ => self.read_args(call, &["*".to_owned()], ctx),
211 };
212 };
213 self.read_args(call, names, ctx)
214 }
215
216 fn read_args(
217 &self,
218 call: &Call<'_>,
219 names: &[String],
220 ctx: &EvalContext,
221 ) -> Vec<(String, String)> {
222 let mut out = Vec::new();
223 for (key, value) in call.args.values_of(names) {
224 let label = format!("`{key}`");
225 match self.test {
226 Test::Under => {
227 let path = crate::host::file_url_path(value).unwrap_or_else(|| {
228 crate::paths::normalise(value, &ctx.home, ctx.project.as_deref(), &ctx.cwd)
229 });
230 out.push((label, path));
231 }
232 Test::HostIn => {
233 let host = if value.contains("://") {
234 crate::host::of_url(value)
235 } else {
236 crate::host::of_word(value)
237 };
238 let host = host.map_or_else(
239 || value.trim().to_ascii_lowercase(),
240 |h| crate::host::canonical(&h),
241 );
242 out.push((label, host));
243 }
244 Test::In => out.extend(addresses(value).map(|a| (label.clone(), a))),
245 Test::Matches | Test::Untrusted => out.push((label, value.to_owned())),
246 }
247 }
248 out
249 }
250
251 fn passes(&self, call: &Call<'_>, value: &str) -> bool {
253 match self.test {
254 Test::Untrusted => untrusted(call, value),
255 Test::HostIn => any_match(&self.patterns, crate::host::canonical(value).as_str()),
256 _ => any_match(&self.patterns, value),
257 }
258 }
259}
260
261fn atom_values<'a>(
263 atoms: &'a [AtomicAction],
264 pick: impl Fn(&'a AtomicAction) -> Option<&'a str>,
265) -> Vec<(String, String)> {
266 atoms
267 .iter()
268 .filter_map(|atom| pick(atom).map(|v| (atom.kind().as_str().to_owned(), v.to_owned())))
269 .collect()
270}
271
272fn addresses(value: &str) -> impl Iterator<Item = String> + '_ {
275 value.split([',', ';']).filter_map(|part| {
276 let part = part.trim();
277 let inner = match (part.find('<'), part.rfind('>')) {
278 (Some(open), Some(close)) if open < close => &part[open + 1..close],
279 _ => part,
280 };
281 let address = inner.trim().to_lowercase();
282 (!address.is_empty()).then_some(address)
283 })
284}
285
286fn untrusted(call: &Call<'_>, value: &str) -> bool {
289 let found = crate::injection::candidates(value);
290 let ctx = &call.policy.ctx;
291 let hosts = found
292 .url_hosts
293 .iter()
294 .chain(&found.word_hosts)
295 .flat_map(|h| super::injection::host_tokens(h, &[TokenKind::UrlHost, TokenKind::WordHost]));
296 let paths = found.paths.iter().filter_map(|raw| {
297 let path = crate::paths::resolve(raw, &ctx.home, ctx.project.as_deref(), Some(&ctx.cwd))?;
298 Some(Token {
299 kind: TokenKind::Path,
300 text: call.policy.path_key(&path),
301 })
302 });
303 hosts
304 .chain(paths)
305 .any(|token| call.seen.source_of(&token).is_some())
306}
307
308fn shown(value: &str) -> String {
310 let mut text: String = value.chars().take(SHOWN_CHARS).collect();
311 if value.chars().count() > SHOWN_CHARS {
312 text.push('…');
313 }
314 format!("`{text}`")
315}
316
317fn derived(action: &Action) -> Arguments {
321 let mut out = Arguments::new();
322 let mut all = |key: &str, values: &[String]| {
323 for value in values {
324 out.push(&[key], value);
325 }
326 };
327 match action {
328 Action::Shell { command } | Action::ForeignShell { command, .. } => {
329 all("command", std::slice::from_ref(command));
330 }
331 Action::FsRead { path } | Action::FsWrite { path } => {
332 all("path", std::slice::from_ref(path));
333 }
334 Action::Net { url } | Action::Fetch { url } => all("url", std::slice::from_ref(url)),
335 Action::WebSearch { query } => all("query", std::slice::from_ref(query)),
336 Action::Patch { writes } => all("path", writes),
337 Action::ReadFiles { paths } => all("path", paths),
338 Action::McpTool {
339 reads,
340 writes,
341 hosts,
342 opens,
343 commands,
344 ..
345 } => {
346 all("path", reads);
347 all("path", writes);
348 all("url", hosts);
349 all("url", opens);
350 all("command", commands);
351 }
352 Action::UnknownTool {
353 reads,
354 writes,
355 hosts,
356 commands,
357 ..
358 } => {
359 all("path", reads);
360 all("path", writes);
361 all("url", hosts);
362 all("command", commands);
363 }
364 Action::Unchecked { action, .. } => return derived(action),
365 }
366 out
367}