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::{Built, 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 // Each text the policy names is built once (`pattern/built.rs`).
144 let mut built = Built::default();
145 let mut compile_list = |groups: &[RuleGroup], allow: bool| {
146 groups
147 .iter()
148 .map(|g| CompiledGroup::compile(g, ctx, allow, &mut built))
149 .collect::<Result<Vec<_>, _>>()
150 };
151 let deny = compile_list(&policy.deny, false)?;
152 let repo_review = compile_list(&policy.repo_review, false)?;
153 let allow = compile_list(&policy.allow, true)?;
154 let review = compile_list(&policy.review, false)?;
155 let defer = compile_list(&policy.defer, false)?;
156 Ok(Self {
157 ctx: ctx.clone(),
158 deny,
159 repo_review,
160 allow,
161 review,
162 defer,
163 protected: taint::compile_protected(&policy, ctx, &mut built)?,
164 folders: contents::ProtectedFolders::compile(&policy.deny, ctx),
165 inside: staging::compile_inside(&policy, ctx, &mut built)?,
166 requests: crate::requests::RequestRules::for_hook(&policy.requests)?,
167 private: taint::compile_private(&policy, ctx, &mut built)?,
168 policy,
169 })
170 }
171
172 /// The policy this was compiled from.
173 #[must_use]
174 pub fn policy(&self) -> &Policy {
175 &self.policy
176 }
177
178 /// The context this was compiled for.
179 #[must_use]
180 pub fn context(&self) -> &EvalContext {
181 &self.ctx
182 }
183
184 /// Evaluate one atomic action: deny → allow → review → defer → default, with a
185 /// repository policy's review rules ([`Policy::repo_review`]) tried before allow.
186 ///
187 /// A repository review never softens what the user's policy alone decides
188 /// for the atom: per atom the result is the stricter of the two (ADR-022),
189 /// so a repository's `review: [{net: ['*']}]` leaves a host the `net: deny`
190 /// default refuses denied.
191 ///
192 /// Returns `None` for a whole-pipeline atom that no rule mentions: pipelines
193 /// are only there so rules like `curl * | sh` can see across `|`; the
194 /// per-sub-command atoms carry the default verdict.
195 #[must_use]
196 pub fn evaluate_atomic(&self, action: &AtomicAction) -> Option<Decision> {
197 if let Some(deny) = Self::hit(&self.deny, Verdict::Deny, action) {
198 return Some(deny);
199 }
200 let own = self.own_rules(action).or_else(|| {
201 (!matches!(action, AtomicAction::Pipeline { .. })).then(|| {
202 let (verdict, rule_id) = self.policy.defaults.for_atom(action);
203 Decision::single(
204 verdict,
205 &rule_id,
206 format!("no rule matched {}", action.describe()),
207 )
208 })
209 });
210 match Self::hit(&self.repo_review, Verdict::Review, action) {
211 Some(repo) => Some(match own {
212 Some(own) if own.verdict > repo.verdict => own,
213 _ => repo,
214 }),
215 None => own,
216 }
217 }
218
219 /// The first of deny, repository review, allow, review and defer whose rules
220 /// match `action`, with every matching rule; `None` when no rule does.
221 fn matched_rules(&self, action: &AtomicAction) -> Option<Decision> {
222 Self::hit(&self.deny, Verdict::Deny, action)
223 .or_else(|| Self::hit(&self.repo_review, Verdict::Review, action))
224 .or_else(|| self.own_rules(action))
225 }
226
227 /// The first of the user's allow, review and defer lists whose rules match.
228 fn own_rules(&self, action: &AtomicAction) -> Option<Decision> {
229 Self::hit(&self.allow, Verdict::Allow, action)
230 .or_else(|| Self::hit(&self.review, Verdict::Review, action))
231 .or_else(|| Self::hit(&self.defer, Verdict::Defer, action))
232 }
233
234 /// `verdict` with every group of `groups` that matches `action`; `None`
235 /// when none does.
236 fn hit(groups: &[CompiledGroup], verdict: Verdict, action: &AtomicAction) -> Option<Decision> {
237 let mut hit = Decision::new(verdict);
238 for g in groups.iter().filter(|g| g.matches(action)) {
239 let why = g.reason.as_ref().map_or_else(
240 || action.describe(),
241 |r| format!("{r}: {}", action.describe()),
242 );
243 hit.push(&g.id, why);
244 }
245 (!hit.rules.is_empty()).then_some(hit)
246 }
247}
248
249impl CompiledGroup {
250 /// `allow` says whether the group is an allow rule ([`Self::bare_hosts`]);
251 /// `built`, the globs this compile built so far.
252 fn compile(
253 group: &RuleGroup,
254 ctx: &EvalContext,
255 allow: bool,
256 built: &mut Built,
257 ) -> Result<Self, PolicyError> {
258 let shell = group
259 .shell
260 .iter()
261 .map(|p| ShellPattern::compile_in(p, built))
262 .collect::<Result<_, _>>()?;
263 let mut globs: [Vec<GlobPattern>; Kind::ALL.len()] = Default::default();
264 let mut bare: [Vec<GlobPattern>; Kind::ALL.len()] = Default::default();
265 for kind in Kind::ALL.into_iter().filter(|k| *k != Kind::Shell) {
266 let case_insensitive = match kind {
267 Kind::FsRead | Kind::FsWrite => ctx.case_insensitive_paths,
268 Kind::Net | Kind::Fetch => true,
269 _ => false,
270 };
271 let mut compile = |patterns: &mut dyn Iterator<Item = &String>| {
272 patterns
273 .flat_map(|p| ctx.spellings(p))
274 .map(|p| GlobPattern::compile_in(&p, case_insensitive, built))
275 .collect::<Result<Vec<_>, _>>()
276 };
277 let patterns = group.patterns(kind);
278 globs[kind as usize] = compile(&mut patterns.iter())?;
279 if matches!(kind, Kind::Net | Kind::Fetch) {
280 bare[kind as usize] = compile(&mut patterns.iter().filter(|p| !names_port(p)))?;
281 }
282 }
283 Ok(Self {
284 id: group.id.clone(),
285 reason: group.reason.clone(),
286 shell,
287 globs,
288 bare_hosts: allow.then_some(bare),
289 when: arguments::CompiledWhen::compile(&group.when, ctx, built)?,
290 })
291 }
292
293 /// Whether the group matches `action` on its own: never for a group with
294 /// `when` conditions, which only a whole call can satisfy.
295 fn matches(&self, action: &AtomicAction) -> bool {
296 self.when.is_none() && self.matches_patterns(action)
297 }
298
299 /// Whether one of the group's patterns matches `action`.
300 fn matches_patterns(&self, action: &AtomicAction) -> bool {
301 match (action, action.subject()) {
302 (AtomicAction::Shell { argv } | AtomicAction::Pipeline { argv }, _) => {
303 any_match(&self.shell, argv.as_slice())
304 }
305 (_, Some(subject)) => {
306 let globs = match &self.bare_hosts {
307 Some(bare)
308 if matches!(
309 action,
310 AtomicAction::Net { .. } | AtomicAction::Fetch { .. }
311 ) && crate::host::port_pattern(subject).is_none() =>
312 {
313 bare
314 }
315 _ => &self.globs,
316 };
317 action
318 .kind()
319 .rule_kinds()
320 .iter()
321 .any(|k| any_match(&globs[*k as usize], subject))
322 }
323 (_, None) => false,
324 }
325 }
326}
327
328impl CompiledPolicy<'_> {
329 /// Decide one host action without executable resolution.
330 ///
331 /// Unparseable input yields the policy's catch-all verdict (`review` or
332 /// `defer`) with the parser's reason, never `allow`.
333 #[must_use]
334 pub fn decide(&self, action: &Action) -> Decision {
335 self.decide_with(action, &NoResolver, &NoResolver)
336 }
337
338 /// The atomic actions [`Self::decide_with`] evaluates for `action`, with an
339 /// extra atom for every path an unquoted glob operand names in the
340 /// directories `paths` lists, and for every read or write `paths` resolves
341 /// through a symlink; and the reason when part of the action cannot be
342 /// classified or a glob not expanded in full (`review`).
343 #[must_use]
344 pub fn atoms(
345 &self,
346 action: &Action,
347 paths: &dyn PathResolver,
348 ) -> (Vec<AtomicAction>, Option<String>) {
349 let (atoms, unparsed) = self.all_atoms(action, paths);
350 (atoms, unparsed.map(|u| u.reason))
351 }
352
353 /// [`checked_atoms`] and the atoms of any token or placeholder they send
354 /// where it does not belong ([`egress`]), and of personal data and
355 /// unprefixed credentials they send that a rule of this policy names (ADR-052).
356 fn all_atoms(
357 &self,
358 action: &Action,
359 paths: &dyn PathResolver,
360 ) -> (Vec<AtomicAction>, Option<crate::shell::Unparsed>) {
361 let (mut atoms, unparsed) = checked_atoms(action, &self.ctx, self.opens_as(), paths);
362 let egress = egress::atoms(action, &atoms, &self.policy.secrets)
363 .into_iter()
364 .filter(|atom| !egress::counts_where_named(atom) || self.matched_rules(atom).is_some())
365 // data in a host name counts only on its way to a host no rule allows (ADR-123)
366 .filter(|atom| egress::host_data(atom).is_none_or(|host| !self.allows_host(host)));
367 atoms.extend(egress);
368 (atoms, unparsed)
369 }
370
371 /// Whether an allow rule of the policy lists `host` for a connection.
372 fn allows_host(&self, host: &str) -> bool {
373 let net = AtomicAction::Net {
374 host: host.to_owned(),
375 };
376 self.matched_rules(&net)
377 .is_some_and(|d| d.verdict == Verdict::Allow)
378 }
379
380 /// How a read-only page open is decided under this policy (ADR-047).
381 fn opens_as(&self) -> atoms::Opens {
382 atoms::Opens {
383 as_fetch: self.policy.browser_open_is_fetch(),
384 }
385 }
386
387 /// The commands of `action` that publish local commits (`git push`, `gh pr
388 /// create`), each with the directories it may run in. Only a shell command
389 /// has any.
390 #[must_use]
391 pub fn pushes(&self, action: &Action) -> Vec<crate::shell::push::Push> {
392 let Action::Shell { command } = action.shown() else {
393 return Vec::new();
394 };
395 crate::shell::push::pushes(
396 command,
397 &crate::shell::ShellContext {
398 home: &self.ctx.home,
399 cwd: &[Some(self.ctx.cwd.clone())],
400 },
401 )
402 }
403
404 /// The files `action` runs as code (ADR-039): a script an interpreter or a
405 /// shell runs (`python3 x.py`, `bash x.sh`, `source x`), a file it loads
406 /// first (`node -r ./x.js`) and a program named by a path (`./x`), through
407 /// every wrapper the classifier unwraps (`env`, `time`, `bash -c '…'`), as
408 /// canonical paths, each also as `paths` resolves it through a symlink.
409 /// Only a shell command runs any; a test runner, build tool or package
410 /// script (`pytest`, `npm test`, `go run .`) names none.
411 #[must_use]
412 pub fn executed(&self, action: &Action, paths: &dyn PathResolver) -> Vec<String> {
413 let Action::Shell { command } = action.shown() else {
414 return Vec::new();
415 };
416 atoms::executed_files(command, &self.ctx, paths)
417 }
418
419 /// Decide one host action, resolving shell programs through `resolver` so
420 /// that `executables` pins and installation pins are enforced, and paths
421 /// through `paths` so a symlink cannot move a read or write past a rule.
422 #[must_use]
423 pub fn decide_with(
424 &self,
425 action: &Action,
426 resolver: &dyn ProgramResolver,
427 paths: &dyn PathResolver,
428 ) -> Decision {
429 let (atoms, unparsed) = self.all_atoms(action, paths);
430 // a runner's package the project installed or declared (ADR-102)
431 let atoms = packages::on_hand(atoms, &self.ctx, resolver);
432 let pins = atoms.iter().filter_map(|atom| match atom {
433 AtomicAction::Shell { argv } => {
434 programs::check(&argv[0], &self.policy.executables, resolver)
435 }
436 _ => None,
437 });
438 // Another spelling of a command (OpenMoat's binary under another name
439 // or case) adds the deny or review its rules give, and nothing else.
440 let aliased = aliases::aliases(&atoms, &self.ctx, resolver, paths)
441 .into_iter()
442 .filter_map(|atom| self.matched_rules(&atom))
443 .filter(|hit| matches!(hit.verdict, Verdict::Deny | Verdict::Review));
444 // A path only an MCP argument's value looks like, under a key the
445 // adapter does not know, adds the deny its read would get and nothing
446 // else: no new review or defer for a value that is not a path.
447 let value_reads = value_read_atoms(action, &self.ctx, paths)
448 .into_iter()
449 .filter_map(|atom| Self::hit(&self.deny, Verdict::Deny, &atom));
450 // A part that could not be parsed, or arguments the adapter did not
451 // search, may name anything: never allow (defer or review, ADR-025), and let
452 // a deny on the rest still win. A line not read in full, or one past a
453 // classifier limit, needs review: a deny in what was not read must not defer.
454 let verdict = self.policy.defaults.unclassified();
455 let unparsed = unparsed.map(|u| {
456 let verdict = if u.needs_review {
457 Verdict::Review
458 } else {
459 verdict
460 };
461 unparseable(
462 verdict,
463 format!("could not parse action safely: {}", u.reason),
464 )
465 });
466 let unchecked = match action.shown() {
467 Action::McpTool {
468 unchecked: Some(limit),
469 ..
470 } => Some(unparseable(
471 verdict,
472 format!("mcp arguments not fully checked: {limit}"),
473 )),
474 _ => None,
475 };
476 // What the payload does not show may be anything: at least `review`.
477 let partial = match action {
478 Action::Unchecked { reason, .. } => Some(Decision::single(
479 Verdict::Review,
480 crate::rule_id::UNCHECKED,
481 reason.clone(),
482 )),
483 _ => None,
484 };
485 // A folder holding paths a deny rule names needs review, whatever allows it (ADR-038).
486 let folders = atoms.iter().filter_map(|atom| self.folders.decide(atom));
487 // The requests a command or fetch tool sends to a `requests:` host
488 // (ADR-062): a deny or a review, never an allow.
489 let requests = crate::requests::hook::decisions(&self.requests, action, &atoms);
490 atoms
491 .iter()
492 .filter_map(|atom| self.evaluate_atomic(atom))
493 .chain(folders)
494 .chain(requests)
495 .chain(aliased)
496 .chain(value_reads)
497 .chain(pins)
498 .chain(unparsed)
499 .chain(unchecked)
500 .chain(partial)
501 .reduce(|mut acc, next| {
502 acc.merge(next);
503 acc
504 })
505 .unwrap_or_else(|| unparseable(verdict, "action has no evaluable parts".to_owned()))
506 }
507}
508
509/// Input that cannot be classified: the policy's catch-all, never `allow` (ADR-025).
510fn unparseable(verdict: Verdict, reason: String) -> Decision {
511 Decision::single(verdict, crate::rule_id::UNPARSEABLE, reason)
512}
513
514/// Compile `policy` for `ctx` and decide a single action.
515///
516/// Convenience for one-shot callers; long-lived callers should keep a
517/// [`CompiledPolicy`] instead.
518pub fn evaluate(
519 policy: &Policy,
520 ctx: &EvalContext,
521 action: &Action,
522) -> Result<Decision, PolicyError> {
523 Ok(CompiledPolicy::compile(policy, ctx)?.decide(action))
524}
525
526#[cfg(test)]
527mod tests;