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