Skip to main content

openmoat_core/
engine.rs

1//! The decision engine (docs/POLICY.md §4, docs/ARCHITECTURE.md §4).
2//!
3//! Per atomic action: `deny → allow → review → defaults`. Across the atomic
4//! actions of one tool call: strictest verdict wins. Deny rules are absolute;
5//! an allow rule can never override a deny, so "deny by default with holes"
6//! is expressed through per-kind `defaults`, never through a deny rule.
7
8use std::borrow::Cow;
9
10use crate::action::{Action, AtomicAction};
11use crate::kind::Kind;
12use crate::pattern::{GlobPattern, ShellPattern, any_match};
13use crate::policy::{Policy, PolicyError, RuleGroup};
14use crate::programs::{self, NoResolver, ProgramResolver};
15use crate::realpath::PathResolver;
16use crate::verdict::{Decision, Verdict};
17
18mod aliases;
19mod atoms;
20mod contents;
21mod context;
22mod egress;
23mod injection;
24mod packages;
25mod staging;
26mod taint;
27
28use atoms::{checked_atoms, value_read_atoms};
29pub use staging::{STAGING_ATOM, Staging};
30pub use taint::{Secret, Taint, UntrustedKind};
31
32/// Everything the engine needs from the environment. Supplied by the caller.
33#[derive(Debug, Clone)]
34pub struct EvalContext {
35    /// The user's home directory, for `~` and `$HOME`.
36    pub home: String,
37    /// The trusted project root, for `${project}`. `None` when the session has
38    /// no project the caller is willing to trust (it would be the home directory,
39    /// one of its ancestors or a filesystem root): every pattern naming
40    /// `${project}` then matches nothing, so project-scoped allows do not apply.
41    pub project: Option<String>,
42    /// `home` with its symlinks resolved, when that differs (a home on a linked
43    /// volume, a Windows 8.3 short name). Patterns naming `~` match under both
44    /// spellings, since the caller's [`PathResolver`] reports paths in this one.
45    pub real_home: Option<String>,
46    /// `project` with its symlinks resolved, when that differs (macOS `/tmp` →
47    /// `/private/tmp`, `~/code` → `/Volumes/dev/code`). Patterns naming
48    /// `${project}` match under both spellings, exclusions included, so a file
49    /// in the project is the project's however its path is written. A link
50    /// *inside* the project changes nothing here: its target is checked as is.
51    pub real_project: Option<String>,
52    /// Directories an environment variable moved out of the home directory
53    /// (`MOAT_HOME`, `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `CURSOR_CONFIG_DIR`), as
54    /// `(default, moved)` pairs such as `("~/.claude", "/srv/claude")`. A
55    /// pattern naming `default` or a path below it also matches the same path
56    /// under `moved`, so rules about a host's directory follow it when it moves.
57    pub moved_dirs: Vec<(String, String)>,
58    /// The directory relative paths are taken from.
59    pub cwd: String,
60    /// Whether file paths compare case-insensitively, as on the default macOS
61    /// and Windows file systems. Host names always do; names never do.
62    pub case_insensitive_paths: bool,
63}
64
65/// A policy with all patterns compiled for one evaluation context.
66///
67/// Compile once per process (or per policy reload) and reuse for every tool
68/// call; compilation dominates the cost of a single decision. It borrows the
69/// policy ([`Self::compile`]) or owns it ([`Self::compile_owned`], for a caller
70/// such as `openmoat-sdk` that keeps one engine for as long as it likes).
71#[derive(Debug)]
72pub struct CompiledPolicy<'p> {
73    policy: Cow<'p, Policy>,
74    ctx: EvalContext,
75    deny: Vec<CompiledGroup>,
76    repo_review: Vec<CompiledGroup>,
77    allow: Vec<CompiledGroup>,
78    review: Vec<CompiledGroup>,
79    defer: Vec<CompiledGroup>,
80    /// Paths whose writes need review once the session read untrusted content (`taint`).
81    protected: Vec<GlobPattern>,
82    /// The folders deny rules' paths lie in, which reading or writing needs review for.
83    folders: contents::ProtectedFolders,
84    /// Where a read is not collection (ADR-061, proposed): the project, read
85    /// roots, caches, temporary folders and `staging.ignore`.
86    inside: Vec<GlobPattern>,
87    /// Every `requests:` entry, for the requests commands send (ADR-062).
88    requests: crate::requests::RequestRules,
89}
90
91#[derive(Debug)]
92struct CompiledGroup {
93    /// The group's id, as decisions name it.
94    id: String,
95    /// The group's `reason`, which prefixes each of its reasons.
96    reason: Option<String>,
97    shell: Vec<ShellPattern>,
98    /// Glob patterns per kind, indexed by `Kind as usize`; the shell slot is empty.
99    globs: [Vec<GlobPattern>; Kind::ALL.len()],
100    /// For an allow group, its `net` and `fetch` patterns without the
101    /// `host:port` ones ([`crate::host::port_pattern`]), which a host without a
102    /// port is matched against: `*:8443` allows port 8443 of every host to the
103    /// proxy, and must not also match an IPv6 address whose text ends in
104    /// `:8443`. Deny and review rules keep them: there they only refuse more.
105    bare_hosts: Option<[Vec<GlobPattern>; Kind::ALL.len()]>,
106}
107
108/// Whether `pattern` is a `net` or `fetch` pattern written `host:port`, not an
109/// exclusion.
110fn names_port(pattern: &str) -> bool {
111    !pattern.starts_with('!') && crate::host::port_pattern(pattern).is_some()
112}
113
114impl<'p> CompiledPolicy<'p> {
115    /// Compile every pattern of `policy` for `ctx`. Fails on a pattern that does
116    /// not compile, and on a `moved_dirs` entry whose `default` could alias every
117    /// pattern (empty, bare `/`, or not an absolute or `~/`-rooted directory).
118    pub fn compile(policy: &'p Policy, ctx: &EvalContext) -> Result<Self, PolicyError> {
119        Self::build(Cow::Borrowed(policy), ctx)
120    }
121
122    /// [`Self::compile`] for a policy the result keeps, so it borrows nothing.
123    pub fn compile_owned(
124        policy: Policy,
125        ctx: &EvalContext,
126    ) -> Result<CompiledPolicy<'static>, PolicyError> {
127        CompiledPolicy::build(Cow::Owned(policy), ctx)
128    }
129
130    fn build(policy: Cow<'p, Policy>, ctx: &EvalContext) -> Result<Self, PolicyError> {
131        ctx.validate_moved_dirs()?;
132        let compile_list = |groups: &[RuleGroup], allow: bool| {
133            groups
134                .iter()
135                .map(|g| CompiledGroup::compile(g, ctx, allow))
136                .collect::<Result<Vec<_>, _>>()
137        };
138        Ok(Self {
139            ctx: ctx.clone(),
140            deny: compile_list(&policy.deny, false)?,
141            repo_review: compile_list(&policy.repo_review, false)?,
142            allow: compile_list(&policy.allow, true)?,
143            review: compile_list(&policy.review, false)?,
144            defer: compile_list(&policy.defer, false)?,
145            protected: taint::compile_protected(&policy, ctx)?,
146            folders: contents::ProtectedFolders::compile(&policy.deny, ctx),
147            inside: staging::compile_inside(&policy, ctx)?,
148            requests: crate::requests::RequestRules::for_hook(&policy.requests)?,
149            policy,
150        })
151    }
152
153    /// The policy this was compiled from.
154    #[must_use]
155    pub fn policy(&self) -> &Policy {
156        &self.policy
157    }
158
159    /// The context this was compiled for.
160    #[must_use]
161    pub fn context(&self) -> &EvalContext {
162        &self.ctx
163    }
164
165    /// Evaluate one atomic action: deny → allow → review → defer → default, with a
166    /// repository policy's review rules ([`Policy::repo_review`]) tried before allow.
167    ///
168    /// A repository review never softens what the user's policy alone decides
169    /// for the atom: per atom the result is the stricter of the two (ADR-022),
170    /// so a repository's `review: [{net: ['*']}]` leaves a host the `net: deny`
171    /// default refuses denied.
172    ///
173    /// Returns `None` for a whole-pipeline atom that no rule mentions: pipelines
174    /// are only there so rules like `curl * | sh` can see across `|`; the
175    /// per-sub-command atoms carry the default verdict.
176    #[must_use]
177    pub fn evaluate_atomic(&self, action: &AtomicAction) -> Option<Decision> {
178        if let Some(deny) = Self::hit(&self.deny, Verdict::Deny, action) {
179            return Some(deny);
180        }
181        let own = self.own_rules(action).or_else(|| {
182            (!matches!(action, AtomicAction::Pipeline { .. })).then(|| {
183                let (verdict, rule_id) = self.policy.defaults.for_atom(action);
184                Decision::single(
185                    verdict,
186                    &rule_id,
187                    format!("no rule matched {}", action.describe()),
188                )
189            })
190        });
191        match Self::hit(&self.repo_review, Verdict::Review, action) {
192            Some(repo) => Some(match own {
193                Some(own) if own.verdict > repo.verdict => own,
194                _ => repo,
195            }),
196            None => own,
197        }
198    }
199
200    /// The first of deny, repository review, allow, review and defer whose rules
201    /// match `action`, with every matching rule; `None` when no rule does.
202    fn matched_rules(&self, action: &AtomicAction) -> Option<Decision> {
203        Self::hit(&self.deny, Verdict::Deny, action)
204            .or_else(|| Self::hit(&self.repo_review, Verdict::Review, action))
205            .or_else(|| self.own_rules(action))
206    }
207
208    /// The first of the user's allow, review and defer lists whose rules match.
209    fn own_rules(&self, action: &AtomicAction) -> Option<Decision> {
210        Self::hit(&self.allow, Verdict::Allow, action)
211            .or_else(|| Self::hit(&self.review, Verdict::Review, action))
212            .or_else(|| Self::hit(&self.defer, Verdict::Defer, action))
213    }
214
215    /// `verdict` with every group of `groups` that matches `action`; `None`
216    /// when none does.
217    fn hit(groups: &[CompiledGroup], verdict: Verdict, action: &AtomicAction) -> Option<Decision> {
218        let mut hit = Decision::new(verdict);
219        for g in groups.iter().filter(|g| g.matches(action)) {
220            let why = g.reason.as_ref().map_or_else(
221                || action.describe(),
222                |r| format!("{r}: {}", action.describe()),
223            );
224            hit.push(&g.id, why);
225        }
226        (!hit.rules.is_empty()).then_some(hit)
227    }
228}
229
230impl CompiledGroup {
231    /// `allow` says whether the group is an allow rule ([`Self::bare_hosts`]).
232    fn compile(group: &RuleGroup, ctx: &EvalContext, allow: bool) -> Result<Self, PolicyError> {
233        let shell = group
234            .shell
235            .iter()
236            .map(|p| ShellPattern::compile(p))
237            .collect::<Result<_, _>>()?;
238        let mut globs: [Vec<GlobPattern>; Kind::ALL.len()] = Default::default();
239        let mut bare: [Vec<GlobPattern>; Kind::ALL.len()] = Default::default();
240        for kind in Kind::ALL.into_iter().filter(|k| *k != Kind::Shell) {
241            let case_insensitive = match kind {
242                Kind::FsRead | Kind::FsWrite => ctx.case_insensitive_paths,
243                Kind::Net | Kind::Fetch => true,
244                _ => false,
245            };
246            let compile = |patterns: &mut dyn Iterator<Item = &String>| {
247                patterns
248                    .flat_map(|p| ctx.spellings(p))
249                    .map(|p| GlobPattern::compile(&p, case_insensitive))
250                    .collect::<Result<Vec<_>, _>>()
251            };
252            let patterns = group.patterns(kind);
253            globs[kind as usize] = compile(&mut patterns.iter())?;
254            if matches!(kind, Kind::Net | Kind::Fetch) {
255                bare[kind as usize] = compile(&mut patterns.iter().filter(|p| !names_port(p)))?;
256            }
257        }
258        Ok(Self {
259            id: group.id.clone(),
260            reason: group.reason.clone(),
261            shell,
262            globs,
263            bare_hosts: allow.then_some(bare),
264        })
265    }
266
267    fn matches(&self, action: &AtomicAction) -> bool {
268        match (action, action.subject()) {
269            (AtomicAction::Shell { argv } | AtomicAction::Pipeline { argv }, _) => {
270                any_match(&self.shell, argv.as_slice())
271            }
272            (_, Some(subject)) => {
273                let globs = match &self.bare_hosts {
274                    Some(bare)
275                        if matches!(
276                            action,
277                            AtomicAction::Net { .. } | AtomicAction::Fetch { .. }
278                        ) && crate::host::port_pattern(subject).is_none() =>
279                    {
280                        bare
281                    }
282                    _ => &self.globs,
283                };
284                action
285                    .kind()
286                    .rule_kinds()
287                    .iter()
288                    .any(|k| any_match(&globs[*k as usize], subject))
289            }
290            (_, None) => false,
291        }
292    }
293}
294
295impl CompiledPolicy<'_> {
296    /// Decide one host action without executable resolution.
297    ///
298    /// Unparseable input yields the policy's catch-all verdict (`review` or
299    /// `defer`) with the parser's reason, never `allow`.
300    #[must_use]
301    pub fn decide(&self, action: &Action) -> Decision {
302        self.decide_with(action, &NoResolver, &NoResolver)
303    }
304
305    /// The atomic actions [`Self::decide_with`] evaluates for `action`, with an
306    /// extra atom for every path an unquoted glob operand names in the
307    /// directories `paths` lists, and for every read or write `paths` resolves
308    /// through a symlink; and the reason when part of the action cannot be
309    /// classified or a glob not expanded in full (`review`).
310    #[must_use]
311    pub fn atoms(
312        &self,
313        action: &Action,
314        paths: &dyn PathResolver,
315    ) -> (Vec<AtomicAction>, Option<String>) {
316        let (atoms, unparsed) = self.all_atoms(action, paths);
317        (atoms, unparsed.map(|u| u.reason))
318    }
319
320    /// [`checked_atoms`] and the atoms of any token or placeholder they send
321    /// where it does not belong ([`egress`]), and of personal data they send
322    /// that a rule of this policy names (ADR-052).
323    fn all_atoms(
324        &self,
325        action: &Action,
326        paths: &dyn PathResolver,
327    ) -> (Vec<AtomicAction>, Option<crate::shell::Unparsed>) {
328        let (mut atoms, unparsed) = checked_atoms(action, &self.ctx, self.opens_as(), paths);
329        let egress = egress::atoms(action, &atoms, &self.policy.secrets)
330            .into_iter()
331            .filter(|atom| !egress::is_personal(atom) || self.matched_rules(atom).is_some());
332        atoms.extend(egress);
333        (atoms, unparsed)
334    }
335
336    /// How a read-only page open is decided under this policy (ADR-047).
337    fn opens_as(&self) -> atoms::Opens {
338        atoms::Opens {
339            as_fetch: self.policy.browser_open_is_fetch(),
340        }
341    }
342
343    /// The commands of `action` that publish local commits (`git push`, `gh pr
344    /// create`), each with the directories it may run in. Only a shell command
345    /// has any.
346    #[must_use]
347    pub fn pushes(&self, action: &Action) -> Vec<crate::shell::push::Push> {
348        let Action::Shell { command } = action.shown() else {
349            return Vec::new();
350        };
351        crate::shell::push::pushes(
352            command,
353            &crate::shell::ShellContext {
354                home: &self.ctx.home,
355                cwd: &[Some(self.ctx.cwd.clone())],
356            },
357        )
358    }
359
360    /// The files `action` runs as code (ADR-039): a script an interpreter or a
361    /// shell runs (`python3 x.py`, `bash x.sh`, `source x`), a file it loads
362    /// first (`node -r ./x.js`) and a program named by a path (`./x`), through
363    /// every wrapper the classifier unwraps (`env`, `time`, `bash -c '…'`), as
364    /// canonical paths, each also as `paths` resolves it through a symlink.
365    /// Only a shell command runs any; a test runner, build tool or package
366    /// script (`pytest`, `npm test`, `go run .`) names none.
367    #[must_use]
368    pub fn executed(&self, action: &Action, paths: &dyn PathResolver) -> Vec<String> {
369        let Action::Shell { command } = action.shown() else {
370            return Vec::new();
371        };
372        atoms::executed_files(command, &self.ctx, paths)
373    }
374
375    /// Decide one host action, resolving shell programs through `resolver` so
376    /// that `executables` pins and installation pins are enforced, and paths
377    /// through `paths` so a symlink cannot move a read or write past a rule.
378    #[must_use]
379    pub fn decide_with(
380        &self,
381        action: &Action,
382        resolver: &dyn ProgramResolver,
383        paths: &dyn PathResolver,
384    ) -> Decision {
385        let (atoms, unparsed) = self.all_atoms(action, paths);
386        // a runner's package the project installed or declared (ADR-102)
387        let atoms = packages::on_hand(atoms, &self.ctx, resolver);
388        let pins = atoms.iter().filter_map(|atom| match atom {
389            AtomicAction::Shell { argv } => {
390                programs::check(&argv[0], &self.policy.executables, resolver)
391            }
392            _ => None,
393        });
394        // Another spelling of a command (OpenMoat's binary under another name
395        // or case) adds the deny or review its rules give, and nothing else.
396        let aliased = aliases::aliases(&atoms, &self.ctx, resolver, paths)
397            .into_iter()
398            .filter_map(|atom| self.matched_rules(&atom))
399            .filter(|hit| matches!(hit.verdict, Verdict::Deny | Verdict::Review));
400        // A path only an MCP argument's value looks like, under a key the
401        // adapter does not know, adds the deny its read would get and nothing
402        // else: no new review or defer for a value that is not a path.
403        let value_reads = value_read_atoms(action, &self.ctx, paths)
404            .into_iter()
405            .filter_map(|atom| Self::hit(&self.deny, Verdict::Deny, &atom));
406        // A part that could not be parsed, or arguments the adapter did not
407        // search, may name anything: never allow (defer or review, ADR-025), and let
408        // a deny on the rest still win. A line not read in full, or one past a
409        // classifier limit, needs review: a deny in what was not read must not defer.
410        let verdict = self.policy.defaults.unclassified();
411        let unparsed = unparsed.map(|u| {
412            let verdict = if u.needs_review {
413                Verdict::Review
414            } else {
415                verdict
416            };
417            unparseable(
418                verdict,
419                format!("could not parse action safely: {}", u.reason),
420            )
421        });
422        let unchecked = match action.shown() {
423            Action::McpTool {
424                unchecked: Some(limit),
425                ..
426            } => Some(unparseable(
427                verdict,
428                format!("mcp arguments not fully checked: {limit}"),
429            )),
430            _ => None,
431        };
432        // What the payload does not show may be anything: at least `review`.
433        let partial = match action {
434            Action::Unchecked { reason, .. } => Some(Decision::single(
435                Verdict::Review,
436                crate::rule_id::UNCHECKED,
437                reason.clone(),
438            )),
439            _ => None,
440        };
441        // A folder holding paths a deny rule names needs review, whatever allows it (ADR-038).
442        let folders = atoms.iter().filter_map(|atom| self.folders.decide(atom));
443        // The requests a command or fetch tool sends to a `requests:` host
444        // (ADR-062): a deny or a review, never an allow.
445        let requests = crate::requests::hook::decisions(&self.requests, action, &atoms);
446        atoms
447            .iter()
448            .filter_map(|atom| self.evaluate_atomic(atom))
449            .chain(folders)
450            .chain(requests)
451            .chain(aliased)
452            .chain(value_reads)
453            .chain(pins)
454            .chain(unparsed)
455            .chain(unchecked)
456            .chain(partial)
457            .reduce(|mut acc, next| {
458                acc.merge(next);
459                acc
460            })
461            .unwrap_or_else(|| unparseable(verdict, "action has no evaluable parts".to_owned()))
462    }
463}
464
465/// Input that cannot be classified: the policy's catch-all, never `allow` (ADR-025).
466fn unparseable(verdict: Verdict, reason: String) -> Decision {
467    Decision::single(verdict, crate::rule_id::UNPARSEABLE, reason)
468}
469
470/// Compile `policy` for `ctx` and decide a single action.
471///
472/// Convenience for one-shot callers; long-lived callers should keep a
473/// [`CompiledPolicy`] instead.
474pub fn evaluate(
475    policy: &Policy,
476    ctx: &EvalContext,
477    action: &Action,
478) -> Result<Decision, PolicyError> {
479    Ok(CompiledPolicy::compile(policy, ctx)?.decide(action))
480}
481
482#[cfg(test)]
483mod tests;