openmoat_core/policy.rs
1//! Policy file model, loading and linting (docs/POLICY.md).
2
3use std::collections::{BTreeMap, BTreeSet};
4
5/// Fallback verdicts when no rule matches: one verdict for everything, or a map
6/// from action kind (`shell`, `fs.read`, `fs.write`, `net`, `fetch`,
7/// `web.search`, `tool.unknown`, `env.read`, `env.set`, `mcp`, or `"*"`) to a verdict; a `fetch`
8/// without its own entry takes the `net` one. This is how "outbound network is
9/// deny-by-default" is expressed, because deny rules are absolute and cannot
10/// be punched through by allow rules (ADR-002).
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(untagged)]
13pub enum Defaults {
14 /// The same verdict for every kind.
15 All(Verdict),
16 /// A verdict per kind name (`net`, `fs.read`, …), with `*` as the fallback.
17 PerKind(BTreeMap<String, Verdict>),
18}
19
20impl Defaults {
21 /// Verdict and synthetic rule id (`default` or `default.<kind>`) for a kind.
22 #[must_use]
23 pub fn for_kind(&self, kind: Kind) -> (Verdict, String) {
24 match self {
25 Self::All(v) => (*v, crate::rule_id::DEFAULT.to_owned()),
26 Self::PerKind(map) => kind
27 .rule_kinds()
28 .iter()
29 .find_map(|k| {
30 map.get(k.as_str())
31 .map(|v| (*v, format!("{}{k}", crate::rule_id::DEFAULT_PREFIX)))
32 })
33 .unwrap_or_else(|| {
34 (
35 map.get("*").copied().unwrap_or(Verdict::Review),
36 crate::rule_id::DEFAULT.to_owned(),
37 )
38 }),
39 }
40 }
41
42 /// The default for an atom no rule matched: [`Self::for_kind`], except that a
43 /// word that only looks like a host is no network evidence and gets
44 /// [`Self::unclassified`] (ADR-025).
45 #[must_use]
46 pub fn for_atom(&self, atom: &crate::AtomicAction) -> (Verdict, String) {
47 match atom {
48 crate::AtomicAction::NetWord { .. } => {
49 (self.unclassified(), crate::rule_id::DEFAULT.to_owned())
50 }
51 _ => self.for_kind(atom.kind()),
52 }
53 }
54
55 /// What OpenMoat gives a call it cannot classify, or a word that only looks
56 /// like a host: `defer` under a catch-all (`"*"`) of `allow` or `defer`, else
57 /// `review` (ADR-025). Never `allow`, and never a deny nothing named.
58 #[must_use]
59 pub fn unclassified(&self) -> Verdict {
60 let catch_all = match self {
61 Self::All(v) => *v,
62 Self::PerKind(map) => map.get("*").copied().unwrap_or(Verdict::Review),
63 };
64 catch_all.clamp(Verdict::Defer, Verdict::Review)
65 }
66}
67
68use serde::{Deserialize, Serialize};
69
70use crate::kind::Kind;
71use crate::pattern::{Checked, GlobPattern, ShellPattern};
72use crate::secret::{self, Secret};
73use crate::staging::{self, StagingSettings};
74use crate::taint::{self, TaintSettings};
75use crate::verdict::Verdict;
76
77mod approval;
78mod env_name;
79mod error;
80mod hook_only;
81mod old_names;
82mod require;
83mod schema;
84mod text;
85
86pub use approval::Approval;
87pub use env_name::{RunEnv, env_name_problem};
88pub use error::PolicyError;
89pub use require::{Require, RequiredBy, RequiredLevel, Requirement, RunBoundary};
90pub(crate) use schema::check as check_version;
91pub use schema::{Declared as DeclaredVersion, declared as declared_version};
92pub use text::{TITLE_MAX_CHARS, WHY_MAX_CHARS};
93
94pub use old_names::OldNames;
95
96/// The policy schema version (`version:`) this build reads; any other is an error.
97pub const SUPPORTED_VERSION: u32 = 1;
98
99/// One named group of patterns. A group matches when **any** of its patterns
100/// matches the atomic action of the corresponding kind.
101#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(deny_unknown_fields)]
103pub struct RuleGroup {
104 /// Stable identifier shown in decisions and the audit log.
105 pub id: String,
106 /// Text prepended to the reason when this group decides.
107 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub reason: Option<String>,
109 /// What the rule stops or holds, in the person's words ("reading your SSH
110 /// private key"): the first line of the message an agent and its person
111 /// see when this group denies or holds a call (ADR-059). One line.
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub title: Option<String>,
114 /// Why the rule exists, in one line, shown under [`Self::title`].
115 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub why: Option<String>,
117 /// Shell patterns (token prefixes, `*`, `!`, trailing `$`).
118 #[serde(default, skip_serializing_if = "Vec::is_empty")]
119 pub shell: Vec<String>,
120 /// Path globs for file reads.
121 #[serde(default, rename = "fs.read", skip_serializing_if = "Vec::is_empty")]
122 pub fs_read: Vec<String>,
123 /// Path globs for file writes.
124 #[serde(default, rename = "fs.write", skip_serializing_if = "Vec::is_empty")]
125 pub fs_write: Vec<String>,
126 /// Host globs for any network access, fetches included.
127 #[serde(default, skip_serializing_if = "Vec::is_empty")]
128 pub net: Vec<String>,
129 /// Host globs for read-only fetches by a host's fetch tool only.
130 #[serde(default, skip_serializing_if = "Vec::is_empty")]
131 pub fetch: Vec<String>,
132 /// Variable-name globs for reads.
133 #[serde(default, rename = "env.read", skip_serializing_if = "Vec::is_empty")]
134 pub env_read: Vec<String>,
135 /// Variable-name globs for sets.
136 #[serde(default, rename = "env.set", skip_serializing_if = "Vec::is_empty")]
137 pub env_set: Vec<String>,
138 /// MCP tool-name globs.
139 #[serde(default, skip_serializing_if = "Vec::is_empty")]
140 pub mcp: Vec<String>,
141 /// Applied by the hook only (ADR-034): OS layers leave this group's
142 /// `fs.read` and `fs.write` paths to the other rules, so a build tool a
143 /// sandboxed command runs can still read them. `deny` groups only, never
144 /// with `net` or `fetch`.
145 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
146 pub hook_only: bool,
147 /// Argument conditions (ADR-113): the group matches a call only when one
148 /// of its patterns does and every condition holds. `deny` and `review`
149 /// groups only, so a condition can only narrow what the group holds.
150 #[serde(default, skip_serializing_if = "Vec::is_empty")]
151 pub when: Vec<crate::predicate::Predicate>,
152}
153
154impl RuleGroup {
155 /// The patterns this group lists for `kind`.
156 #[must_use]
157 pub fn patterns(&self, kind: Kind) -> &[String] {
158 match kind {
159 Kind::Shell => &self.shell,
160 Kind::FsRead => &self.fs_read,
161 Kind::FsWrite => &self.fs_write,
162 Kind::Net => &self.net,
163 Kind::Fetch => &self.fetch,
164 // A query or an unknown tool names no host or path to match; only
165 // `defaults` decide them.
166 Kind::WebSearch | Kind::UnknownTool => &[],
167 Kind::EnvRead => &self.env_read,
168 Kind::EnvSet => &self.env_set,
169 Kind::Mcp => &self.mcp,
170 }
171 }
172
173 fn is_empty(&self) -> bool {
174 Kind::ALL.iter().all(|k| self.patterns(*k).is_empty())
175 }
176
177 /// Check that every pattern of this group parses, naming the group in the
178 /// error: what [`Policy::lint`] does for each group.
179 ///
180 /// # Errors
181 /// [`PolicyError::Rule`] for the first pattern that does not parse.
182 pub fn check_patterns(&self) -> Result<(), PolicyError> {
183 self.check_patterns_in(&mut Checked::default())
184 }
185
186 /// [`Self::check_patterns`], not building again what `checked` holds.
187 fn check_patterns_in(&self, checked: &mut Checked) -> Result<(), PolicyError> {
188 for kind in Kind::ALL {
189 for p in self.patterns(kind) {
190 let compiled = if kind == Kind::Shell {
191 ShellPattern::check(p, checked)
192 } else {
193 GlobPattern::check(p, checked)
194 };
195 compiled.map_err(|e| rule_err(&self.id, &e))?;
196 }
197 }
198 Ok(())
199 }
200}
201
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(deny_unknown_fields)]
204pub struct Scope {
205 #[serde(default = "default_roots")]
206 pub project_roots: Vec<String>,
207}
208
209fn default_roots() -> Vec<String> {
210 vec![".".to_owned()]
211}
212
213impl Default for Scope {
214 fn default() -> Self {
215 Self {
216 project_roots: default_roots(),
217 }
218 }
219}
220
221/// The policy document (`policy.yaml`), as written by users.
222#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
223#[serde(deny_unknown_fields)]
224pub struct Policy {
225 /// Schema version; only 1 is supported.
226 pub version: u32,
227 /// Verdict when no rule matches.
228 #[serde(default = "default_verdict")]
229 pub defaults: Defaults,
230 /// Reserved for multi-root projects; parsed so existing files stay valid,
231 /// not yet consulted (`policy lint` warns).
232 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub scope: Option<Scope>,
234 /// Evaluated first; a match is final.
235 #[serde(default)]
236 pub deny: Vec<RuleGroup>,
237 /// Evaluated after `deny`.
238 #[serde(default)]
239 pub allow: Vec<RuleGroup>,
240 /// Evaluated after `allow`: calls a person reviews. Read from `ask:` too,
241 /// its name before ADR-053 ([`OldNames`]).
242 #[serde(default, alias = "ask")]
243 pub review: Vec<RuleGroup>,
244 /// Evaluated after `review`: calls the agent's own permission flow decides
245 /// (ADR-025). Absent in policies written before it existed.
246 #[serde(default, skip_serializing_if = "Vec::is_empty")]
247 pub defer: Vec<RuleGroup>,
248 /// Reserved for the kernel's own approval prompt; parsed so existing files
249 /// stay valid, not yet consulted (`policy lint` warns).
250 #[serde(default, skip_serializing_if = "Option::is_none")]
251 pub approval: Option<Approval>,
252 /// Basename → allowed absolute paths (defeats PATH poisoning).
253 #[serde(default)]
254 pub executables: BTreeMap<String, Vec<String>>,
255 /// What the operating-system layers OpenMoat configures need beyond the rules
256 /// (ADR-018). Absent in policies written before it existed.
257 #[serde(default, skip_serializing_if = "Option::is_none")]
258 pub sandbox: Option<SandboxSettings>,
259 /// Secrets `moat proxy` keeps from the agent and injects for one host each.
260 #[serde(default, skip_serializing_if = "Vec::is_empty")]
261 pub secrets: Vec<Secret>,
262 /// Method and path rules for allowed hosts (ADR-062): what the hook reads
263 /// in commands and fetch tools, and the proxy inside the tunnels it
264 /// terminates. They only narrow what `net` and `fetch` allow.
265 #[serde(default, skip_serializing_if = "Vec::is_empty")]
266 pub requests: Vec<crate::requests::RequestEntry>,
267 /// What `openmoat proxy` does with a connection to a `requests:` host it
268 /// cannot terminate (ADR-062): `refuse` (absent, the default) or `relay`.
269 /// Only the person's own policy holds it.
270 #[serde(default, skip_serializing_if = "Option::is_none")]
271 pub requests_untrusted: Option<crate::requests::Untrusted>,
272 /// What session taint protects beyond the built-in list. Absent in older policies.
273 #[serde(default, skip_serializing_if = "Option::is_none")]
274 pub taint: Option<TaintSettings>,
275 /// When a session counts as having collected files outside the project
276 /// (ADR-061, proposed): the `@staging-egress` atom's thresholds. Absent in
277 /// older policies, which means the defaults.
278 #[serde(default, skip_serializing_if = "Option::is_none")]
279 pub staging: Option<StagingSettings>,
280 /// Trust a repository policy only when its detached signature
281 /// (`policy.yaml.sig`) verifies against a key the person trusted (ADR-031):
282 /// a signed one needs no `moat trust`, and an unsigned one is not trusted even
283 /// after `moat trust`. Off by default: then only `moat trust` lets a
284 /// repository policy allow.
285 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
286 pub require_signed_repo_policy: bool,
287 /// How `moat mcp proxy` treats tool definitions (ADR-032). Absent in older policies.
288 #[serde(default, skip_serializing_if = "Option::is_none")]
289 pub mcp: Option<McpSettings>,
290 /// The levels `openmoat policy check-diff` reports its content checks at
291 /// (ADR-055). Absent in older policies: each check's own level.
292 #[serde(default, skip_serializing_if = "Option::is_none")]
293 pub check_diff: Option<crate::diffscan::Settings>,
294 /// The least protection level each agent must be at for `openmoat guard`
295 /// to decide its calls; below it, every call is denied
296 /// (`protection-required`, ADR-064). Absent in older policies and the
297 /// default: nothing is required.
298 #[serde(default, skip_serializing_if = "Option::is_none")]
299 pub require: Option<Require>,
300 /// What a `defer` becomes when the agent reports a mode in which it runs
301 /// calls with no person asked (ADR-102): `defer` (absent, the default)
302 /// leaves it to the agent, `review` holds it for a person. Only the
303 /// person's own policy holds it: a repository policy or a pack with the key
304 /// does not parse.
305 #[serde(default, skip_serializing_if = "Option::is_none")]
306 pub unattended: Option<Unattended>,
307 /// What a new or changed hook command, plugin hook or git program no
308 /// person accepted does to the calls of the agent that loads it
309 /// (`hooks.foreign`, ADR-109). Absent, the default: only one whose
310 /// command the policy denies changes them. Only the person's own policy
311 /// holds it: a repository policy or a pack with the key does not parse.
312 #[serde(default, skip_serializing_if = "Option::is_none")]
313 pub hooks: Option<HookSettings>,
314 /// The `require:` sections of the repository policy and the packs merged
315 /// in ([`Policy::add_requirement`]), read with [`Self::require`] by
316 /// [`Policy::required_for`], which takes the strictest: they raise a
317 /// level, never lower one. Never read from or written to a file.
318 #[serde(skip)]
319 pub require_added: Vec<(RequiredBy, Require)>,
320 /// Review rules merged in from a repository policy ([`crate::RepoPolicy`],
321 /// ADR-022) or a policy pack (ADR-031). Tried after `deny` and before
322 /// `allow`, so a repository can make an action the user allows need review.
323 /// Never read from or written to a file, and not lowered to OS layers, which
324 /// are generated from the user policy alone.
325 #[serde(skip)]
326 pub repo_review: Vec<RuleGroup>,
327 /// Where the file used `ask`, the old name of `review` (ADR-053), which
328 /// `policy lint` warns about. Set by [`Policy::parse`]; never written.
329 #[serde(skip)]
330 pub old_names: OldNames,
331}
332
333/// The `sandbox:` section (ADR-018, ADR-019).
334#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
335#[serde(deny_unknown_fields)]
336pub struct SandboxSettings {
337 /// Paths (directories or files) the OS layers let commands read although no
338 /// allow rule covers them: system and toolchain directories every build
339 /// reads. The hook decision ignores them, and deny rules win over them in
340 /// every layer. Absolute or `~/…`, never a glob.
341 #[serde(default)]
342 pub read_roots: Vec<String>,
343 /// The loopback port `moat proxy` listens on and the host sandboxes send
344 /// their commands' traffic to; absent, the CLI's default.
345 #[serde(default, skip_serializing_if = "Option::is_none")]
346 pub proxy_port: Option<std::num::NonZeroU16>,
347 /// Let `moat proxy` forward a TLS `ClientHello` that carries an encrypted
348 /// server name (ECH, ESNI). Off, such a tunnel is refused: the server acts
349 /// on the encrypted name, which may be another site than the allowed host.
350 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
351 pub proxy_allow_ech: bool,
352 /// Let `moat proxy` serve a request that carries no session credential,
353 /// with no session (ADR-044). Off, such a request gets 407: a session's
354 /// taint and connection share cannot be escaped by sending no credential,
355 /// and other local processes cannot use the proxy. `moat run` ignores it.
356 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
357 pub proxy_serve_without_credential: bool,
358 /// Days a package version must have been published before the package
359 /// managers `moat run` starts install it (ADR-030); `0` turns this off,
360 /// absent is 7 days ([`Policy::package_min_release_age_days`]).
361 #[serde(default, skip_serializing_if = "Option::is_none")]
362 pub package_min_release_age_days: Option<u16>,
363 /// Whether `openmoat run` passes on the whole environment it is started
364 /// from or only its allowlist (ADR-105); absent, [`RunEnv::DEFAULT`].
365 /// `require.run: full-boundary` scrubs whatever this says. Read from the
366 /// person's own policy alone: a repository policy or a pack has no
367 /// `sandbox:`.
368 #[serde(default, skip_serializing_if = "Option::is_none")]
369 pub env: Option<RunEnv>,
370 /// Names of inherited environment variables `openmoat run` passes on
371 /// when it scrubs the environment, beyond its own list and the agent's
372 /// (ADR-077, ADR-105). Names only, never a pattern. Read from the person's
373 /// own policy alone: a repository policy or a pack has no `sandbox:`.
374 #[serde(default, skip_serializing_if = "Vec::is_empty")]
375 pub env_allow: Vec<String>,
376 /// What `openmoat run`'s Lightweight tier on Linux without a network
377 /// namespace grants at the top of the project (ADR-090): `protected`
378 /// grants it entry by entry, so nothing can be created there and `.env`,
379 /// `.git` and `.moat` stay covered; `writable` grants it whole, so new
380 /// entries and save-by-rename work there and those paths are open to the
381 /// agent's commands. Never read by the Isolated tier or the network
382 /// namespace. Read from the person's own policy alone: a repository policy
383 /// or a pack has no `sandbox:`.
384 #[serde(default, skip_serializing_if = "ProjectTop::is_protected")]
385 pub project_top: ProjectTop,
386 /// What `openmoat run` does when a file of the project would turn the
387 /// agent's OpenMoat hook off as the session starts (ADR-098): `refuse`
388 /// (absent) does not start the agent; `start` starts it anyway, says so
389 /// and records it. Read from the person's own policy alone: a repository
390 /// policy or a pack has no `sandbox:`.
391 #[serde(default, skip_serializing_if = "ProjectHookOff::is_refuse")]
392 pub project_hook_off: ProjectHookOff,
393 /// `openmoat run` starts only when every kernel feature of its protection
394 /// score is in force (ADR-108): planned before the start, confirmed after
395 /// it, so a missing Landlock step, a port-only network or the Lightweight
396 /// tier refuses the run (fail closed). Read from the person's own policy
397 /// alone: a repository policy or a pack has no `sandbox:`.
398 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
399 pub strict: bool,
400 /// The guest image and size of `openmoat run --vm`'s microVM tier
401 /// (ADR-128, a design: the tier does not boot yet). Read from the
402 /// person's own policy alone.
403 #[serde(default, skip_serializing_if = "Option::is_none")]
404 pub vm: Option<crate::vm::VmSettings>,
405}
406
407/// `sandbox.project_hook_off` (ADR-098).
408#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
409#[serde(rename_all = "lowercase")]
410pub enum ProjectHookOff {
411 /// The agent does not start.
412 #[default]
413 Refuse,
414 /// The agent starts without OpenMoat's hook; the run says so and records it.
415 Start,
416}
417
418impl ProjectHookOff {
419 /// Whether this is the default, [`ProjectHookOff::Refuse`].
420 #[must_use]
421 pub fn is_refuse(&self) -> bool {
422 *self == Self::Refuse
423 }
424}
425
426/// `sandbox.project_top` (ADR-090).
427#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
428#[serde(rename_all = "lowercase")]
429pub enum ProjectTop {
430 /// Granted entry by entry: the policy's denies at the top hold.
431 #[default]
432 Protected,
433 /// Granted whole: the top is writable, and `.env` and `.git/hooks` there
434 /// are open to the agent's commands.
435 Writable,
436}
437
438impl ProjectTop {
439 /// Whether this is the default, [`ProjectTop::Protected`].
440 #[must_use]
441 pub fn is_protected(&self) -> bool {
442 *self == Self::Protected
443 }
444}
445
446/// The `mcp:` section (ADR-032).
447#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
448#[serde(deny_unknown_fields)]
449pub struct McpSettings {
450 /// Pin every tool `moat mcp proxy` sees from a server it has no pins for,
451 /// as it is, instead of holding them until `moat mcp accept`. Off by
452 /// default: a server that is malicious on first contact would get its
453 /// tool descriptions pinned as good.
454 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
455 pub trust_first_sight: bool,
456 /// How an MCP call that only opens or reads one web page is decided
457 /// (ADR-047): `fetch` (absent) as a `fetch` of its host, like `WebFetch`;
458 /// `net` as a `net` connection, which the default policy denies for
459 /// unlisted hosts.
460 #[serde(default, skip_serializing_if = "Option::is_none")]
461 pub browser_open: Option<BrowserOpen>,
462 /// MCP servers, by the name `openmoat mcp proxy --server` gives them,
463 /// whose data flows are trusted (ADR-058): text such a server returned may
464 /// reach another server's tool that writes or sends, and a call to such a
465 /// server may carry another server's text, without a `mcp-cross-server`
466 /// review.
467 #[serde(default, skip_serializing_if = "Vec::is_empty")]
468 pub flow_trusted: Vec<String>,
469 /// Pass a wrapped server's sampling requests (`sampling/createMessage`,
470 /// as a request or in a 2026-07-28 result's `inputRequests`) to the host,
471 /// which would have the model write text for the server. Off by default:
472 /// `openmoat mcp proxy` refuses them (ADR-114).
473 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
474 pub allow_sampling: bool,
475}
476
477/// `mcp.browser_open`: the kind a read-only page open of an MCP tool is decided as.
478#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
479#[serde(rename_all = "lowercase")]
480pub enum BrowserOpen {
481 /// A `fetch` of the page's host (the default).
482 Fetch,
483 /// A `net` connection to the page's host, as any other MCP URL argument.
484 Net,
485}
486
487/// `unattended:`: what a `defer` becomes in an agent mode that runs calls
488/// with no person asked (auto-approve, YOLO, headless; ADR-102).
489#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
490#[serde(rename_all = "lowercase")]
491pub enum Unattended {
492 /// The agent decides it, as everywhere else (ADR-025): in such a mode it
493 /// runs. The default.
494 #[default]
495 Defer,
496 /// OpenMoat holds it for review, and a review there is answered as a deny
497 /// that says how to approve it (or sent to the approvals channel).
498 Review,
499}
500
501/// The `hooks:` section (ADR-109).
502#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
503#[serde(deny_unknown_fields)]
504pub struct HookSettings {
505 /// What a hook the foreign-hook ledger finds new or changed does to the
506 /// agent's calls; absent, [`ForeignHooks::Warn`].
507 #[serde(default)]
508 pub foreign: ForeignHooks,
509}
510
511/// `hooks.foreign`: what a new or changed hook command, plugin hook or git
512/// program no person accepted does to the calls of the agent that loads it
513/// (ADR-109).
514#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
515#[serde(rename_all = "lowercase")]
516pub enum ForeignHooks {
517 /// `openmoat status`, `doctor` and `watch` name it; the calls change only
518 /// while its command is one the policy denies, which denies them. The
519 /// default.
520 #[default]
521 Warn,
522 /// Every one holds the calls for review (a deny where its command is
523 /// denied) until a person accepts it.
524 Hold,
525}
526
527/// The release age `moat run` requires of new package versions when the policy
528/// does not say (ADR-030).
529pub const DEFAULT_PACKAGE_MIN_RELEASE_AGE_DAYS: u16 = 7;
530
531impl Policy {
532 /// The days a package version must have been published before `moat run`
533 /// lets npm and uv install it; `0` is off.
534 #[must_use]
535 pub fn package_min_release_age_days(&self) -> u16 {
536 self.sandbox
537 .as_ref()
538 .and_then(|s| s.package_min_release_age_days)
539 .unwrap_or(DEFAULT_PACKAGE_MIN_RELEASE_AGE_DAYS)
540 }
541
542 /// What the person's own policy says `openmoat run` passes on of its
543 /// environment (`sandbox.env`, ADR-105); `None` when it says nothing,
544 /// which means [`RunEnv::DEFAULT`]. `require.run: full-boundary` scrubs
545 /// whatever this says.
546 #[must_use]
547 pub fn run_env(&self) -> Option<RunEnv> {
548 self.sandbox.as_ref().and_then(|s| s.env)
549 }
550
551 /// What `openmoat run` without a network namespace grants at the project's
552 /// top (`sandbox.project_top`, ADR-090); [`ProjectTop::Protected`] unless
553 /// the person's own policy says otherwise.
554 #[must_use]
555 pub fn project_top(&self) -> ProjectTop {
556 self.sandbox
557 .as_ref()
558 .map(|s| s.project_top)
559 .unwrap_or_default()
560 }
561
562 /// What `openmoat run` does when a project's file would turn the agent's
563 /// hook off (`sandbox.project_hook_off`, ADR-098); [`ProjectHookOff::Refuse`]
564 /// unless the person's own policy says otherwise.
565 #[must_use]
566 pub fn project_hook_off(&self) -> ProjectHookOff {
567 self.sandbox
568 .as_ref()
569 .map(|s| s.project_hook_off)
570 .unwrap_or_default()
571 }
572
573 /// Whether `openmoat run` refuses to start without its whole protection
574 /// score (`sandbox.strict`, ADR-108); `false` unless the person's own
575 /// policy says so.
576 #[must_use]
577 pub fn sandbox_strict(&self) -> bool {
578 self.sandbox.as_ref().is_some_and(|s| s.strict)
579 }
580
581 /// What a `defer` becomes in an agent mode that asks no person
582 /// (`unattended:`, ADR-102): `defer` unless the policy says `review`.
583 #[must_use]
584 pub fn unattended(&self) -> Unattended {
585 self.unattended.unwrap_or_default()
586 }
587
588 /// What a new or changed foreign hook does to the agent's calls
589 /// (`hooks.foreign`, ADR-109): [`ForeignHooks::Warn`] unless the person's
590 /// own policy says `hold`.
591 #[must_use]
592 pub fn foreign_hooks(&self) -> ForeignHooks {
593 self.hooks.map(|h| h.foreign).unwrap_or_default()
594 }
595
596 /// Whether `moat mcp proxy` pins a new server's tools without a person
597 /// accepting them (`mcp.trust_first_sight`, ADR-032).
598 #[must_use]
599 pub fn trust_mcp_first_sight(&self) -> bool {
600 self.mcp.as_ref().is_some_and(|m| m.trust_first_sight)
601 }
602
603 /// Whether an MCP call that only opens a web page is decided as a `fetch`
604 /// (`mcp.browser_open`, ADR-047): yes unless the policy says `net`.
605 #[must_use]
606 pub fn browser_open_is_fetch(&self) -> bool {
607 self.mcp.as_ref().and_then(|m| m.browser_open) != Some(BrowserOpen::Net)
608 }
609
610 /// The MCP servers whose data flows need no `mcp-cross-server` review
611 /// (`mcp.flow_trusted`, ADR-058).
612 #[must_use]
613 pub fn mcp_flow_trusted(&self) -> &[String] {
614 self.mcp.as_ref().map_or(&[], |m| m.flow_trusted.as_slice())
615 }
616
617 /// Whether `openmoat mcp proxy` passes a server's sampling requests on
618 /// (`mcp.allow_sampling`, ADR-114).
619 #[must_use]
620 pub fn allow_mcp_sampling(&self) -> bool {
621 self.mcp.as_ref().is_some_and(|m| m.allow_sampling)
622 }
623}
624
625fn default_verdict() -> Defaults {
626 Defaults::All(Verdict::Review)
627}
628
629impl Policy {
630 /// Parse and lint a policy document. Pure: takes the YAML text.
631 pub fn parse(yaml: &str) -> Result<Self, PolicyError> {
632 // One deserialize, then the errors in the order they always came:
633 // the schema version first, then the old names, then the parse error.
634 let parsed: Result<Self, _> = crate::yaml::from_str(yaml);
635 match &parsed {
636 Ok(policy) => schema::check_parsed(policy.version)?,
637 Err(_) => schema::check(yaml)?,
638 }
639 let old_names = old_names::find(yaml)?;
640 let mut policy = parsed.map_err(PolicyError::Parse)?;
641 policy.old_names = old_names;
642 policy.lint()?;
643 Ok(policy)
644 }
645
646 /// Structural validation independent of any environment: [`Self::lint_structure`]
647 /// and every pattern's syntax ([`RuleGroup::check_patterns`]).
648 pub fn lint(&self) -> Result<(), PolicyError> {
649 self.lint_structure()?;
650 let mut checked = Checked::default();
651 self.groups()
652 .try_for_each(|group| group.check_patterns_in(&mut checked))
653 }
654
655 /// [`Self::lint`] without parsing each pattern again, for a policy that
656 /// gained rule groups after a full lint, such as a merge of rules each
657 /// checked when they were read (a repository policy, a pack, `openmoat allow`
658 /// rules): the new groups' patterns are checked with
659 /// [`RuleGroup::check_patterns`], and nothing else needs reparsing. Parsing
660 /// every pattern costs more than the rest of the lint together, and
661 /// [`crate::CompiledPolicy::compile`] reports a bad one in any case.
662 pub fn lint_structure(&self) -> Result<(), PolicyError> {
663 if self.version != SUPPORTED_VERSION {
664 return Err(PolicyError::Version {
665 found: self.version,
666 supported: SUPPORTED_VERSION,
667 });
668 }
669 let mut ids = BTreeSet::new();
670 for group in self.groups() {
671 if group.id.trim().is_empty() {
672 return Err(PolicyError::Rule {
673 rule: "<unnamed>".into(),
674 problem: "missing id".into(),
675 });
676 }
677 if !ids.insert(group.id.clone()) {
678 return Err(PolicyError::DuplicateId(group.id.clone()));
679 }
680 if group.is_empty() {
681 return Err(PolicyError::EmptyRule(group.id.clone()));
682 }
683 text::check(group)?;
684 }
685 let narrowing = self
686 .deny
687 .iter()
688 .chain(&self.repo_review)
689 .chain(&self.review);
690 for group in narrowing {
691 crate::predicate::check(group, true)?;
692 }
693 for group in self.allow.iter().chain(&self.defer) {
694 crate::predicate::check(group, false)?;
695 }
696 hook_only::check(self)?;
697 for (name, paths) in &self.executables {
698 if paths.is_empty() {
699 return Err(PolicyError::Rule {
700 rule: format!("executables.{name}"),
701 problem: "no paths listed".into(),
702 });
703 }
704 if let Some(bad) = paths.iter().find(|p| !crate::paths::is_absolute(p)) {
705 return Err(PolicyError::Rule {
706 rule: format!("executables.{name}"),
707 problem: format!("`{bad}` is not an absolute path"),
708 });
709 }
710 }
711 for root in self.sandbox.iter().flat_map(|s| &s.read_roots) {
712 lint_read_root(root)?;
713 }
714 for name in self.sandbox.iter().flat_map(|s| &s.env_allow) {
715 if let Some(problem) = env_name_problem(name) {
716 return Err(PolicyError::Rule {
717 rule: "sandbox.env_allow".to_owned(),
718 problem: format!("`{name}` {problem}"),
719 });
720 }
721 }
722 taint::check(self.taint.as_ref())?;
723 crate::vm::check(self.sandbox.as_ref().and_then(|s| s.vm.as_ref()))?;
724 staging::check(self.staging.as_ref())?;
725 crate::diffscan::check(self.check_diff.as_ref())?;
726 require::check(self.require.as_ref())?;
727 for (_, added) in &self.require_added {
728 require::check(Some(added))?;
729 }
730 secret::check(&self.secrets)?;
731 crate::requests::check(&self.requests)
732 }
733
734 /// What `openmoat proxy` does with a connection to a `requests:` host it
735 /// cannot terminate (`requests_untrusted:`): refuse it unless the policy
736 /// says `relay`.
737 #[must_use]
738 pub fn requests_untrusted(&self) -> crate::requests::Untrusted {
739 self.requests_untrusted.unwrap_or_default()
740 }
741
742 /// Every rule group, in the order the engine tries the lists.
743 fn groups(&self) -> impl Iterator<Item = &RuleGroup> {
744 self.deny
745 .iter()
746 .chain(&self.repo_review)
747 .chain(&self.allow)
748 .chain(&self.review)
749 .chain(&self.defer)
750 }
751
752 /// Number of rule groups in `deny`, `allow` and `review`.
753 #[must_use]
754 pub fn rule_count(&self) -> (usize, usize, usize) {
755 (self.deny.len(), self.allow.len(), self.review.len())
756 }
757}
758
759/// An OS layer takes a read root literally, and a root that is the disk or the
760/// home directory would undo every default deny.
761fn lint_read_root(root: &str) -> Result<(), PolicyError> {
762 let trimmed = root.trim_end_matches(['/', '\\']);
763 let problem = if !(crate::paths::is_absolute(root) || root.starts_with("~/")) {
764 "must be absolute or start with `~/`"
765 } else if root.contains(['*', '?', '[', ']', '{', '}', '!', '$']) {
766 "must be a plain path, not a glob or a variable"
767 } else if root.split(['/', '\\']).any(|s| s == "." || s == "..") {
768 "must not contain `.` or `..` segments"
769 } else if trimmed == "~" {
770 "must not be the home directory"
771 } else if trimmed.is_empty() || (trimmed.len() == 2 && trimmed.ends_with(':')) {
772 "must not be a filesystem root"
773 } else {
774 return Ok(());
775 };
776 Err(PolicyError::Rule {
777 rule: "sandbox.read_roots".to_owned(),
778 problem: format!("`{root}` {problem}"),
779 })
780}
781
782fn rule_err(rule: &str, e: &PolicyError) -> PolicyError {
783 PolicyError::Rule {
784 rule: rule.to_owned(),
785 problem: e.to_string(),
786 }
787}
788
789#[cfg(test)]
790mod tests;