Skip to main content

openmoat_core/engine/
arguments.rs

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