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