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