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}
396
397/// `sandbox.project_hook_off` (ADR-098).
398#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
399#[serde(rename_all = "lowercase")]
400pub enum ProjectHookOff {
401 /// The agent does not start.
402 #[default]
403 Refuse,
404 /// The agent starts without OpenMoat's hook; the run says so and records it.
405 Start,
406}
407
408impl ProjectHookOff {
409 /// Whether this is the default, [`ProjectHookOff::Refuse`].
410 #[must_use]
411 pub fn is_refuse(&self) -> bool {
412 *self == Self::Refuse
413 }
414}
415
416/// `sandbox.project_top` (ADR-090).
417#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
418#[serde(rename_all = "lowercase")]
419pub enum ProjectTop {
420 /// Granted entry by entry: the policy's denies at the top hold.
421 #[default]
422 Protected,
423 /// Granted whole: the top is writable, and `.env` and `.git/hooks` there
424 /// are open to the agent's commands.
425 Writable,
426}
427
428impl ProjectTop {
429 /// Whether this is the default, [`ProjectTop::Protected`].
430 #[must_use]
431 pub fn is_protected(&self) -> bool {
432 *self == Self::Protected
433 }
434}
435
436/// The `mcp:` section (ADR-032).
437#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
438#[serde(deny_unknown_fields)]
439pub struct McpSettings {
440 /// Pin every tool `moat mcp proxy` sees from a server it has no pins for,
441 /// as it is, instead of holding them until `moat mcp accept`. Off by
442 /// default: a server that is malicious on first contact would get its
443 /// tool descriptions pinned as good.
444 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
445 pub trust_first_sight: bool,
446 /// How an MCP call that only opens or reads one web page is decided
447 /// (ADR-047): `fetch` (absent) as a `fetch` of its host, like `WebFetch`;
448 /// `net` as a `net` connection, which the default policy denies for
449 /// unlisted hosts.
450 #[serde(default, skip_serializing_if = "Option::is_none")]
451 pub browser_open: Option<BrowserOpen>,
452 /// MCP servers, by the name `openmoat mcp proxy --server` gives them,
453 /// whose data flows are trusted (ADR-058): text such a server returned may
454 /// reach another server's tool that writes or sends, and a call to such a
455 /// server may carry another server's text, without a `mcp-cross-server`
456 /// review.
457 #[serde(default, skip_serializing_if = "Vec::is_empty")]
458 pub flow_trusted: Vec<String>,
459 /// Pass a wrapped server's sampling requests (`sampling/createMessage`,
460 /// as a request or in a 2026-07-28 result's `inputRequests`) to the host,
461 /// which would have the model write text for the server. Off by default:
462 /// `openmoat mcp proxy` refuses them (ADR-114).
463 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
464 pub allow_sampling: bool,
465}
466
467/// `mcp.browser_open`: the kind a read-only page open of an MCP tool is decided as.
468#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
469#[serde(rename_all = "lowercase")]
470pub enum BrowserOpen {
471 /// A `fetch` of the page's host (the default).
472 Fetch,
473 /// A `net` connection to the page's host, as any other MCP URL argument.
474 Net,
475}
476
477/// `unattended:`: what a `defer` becomes in an agent mode that runs calls
478/// with no person asked (auto-approve, YOLO, headless; ADR-102).
479#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
480#[serde(rename_all = "lowercase")]
481pub enum Unattended {
482 /// The agent decides it, as everywhere else (ADR-025): in such a mode it
483 /// runs. The default.
484 #[default]
485 Defer,
486 /// OpenMoat holds it for review, and a review there is answered as a deny
487 /// that says how to approve it (or sent to the approvals channel).
488 Review,
489}
490
491/// The `hooks:` section (ADR-109).
492#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
493#[serde(deny_unknown_fields)]
494pub struct HookSettings {
495 /// What a hook the foreign-hook ledger finds new or changed does to the
496 /// agent's calls; absent, [`ForeignHooks::Warn`].
497 #[serde(default)]
498 pub foreign: ForeignHooks,
499}
500
501/// `hooks.foreign`: what a new or changed hook command, plugin hook or git
502/// program no person accepted does to the calls of the agent that loads it
503/// (ADR-109).
504#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
505#[serde(rename_all = "lowercase")]
506pub enum ForeignHooks {
507 /// `openmoat status`, `doctor` and `watch` name it; the calls change only
508 /// while its command is one the policy denies, which denies them. The
509 /// default.
510 #[default]
511 Warn,
512 /// Every one holds the calls for review (a deny where its command is
513 /// denied) until a person accepts it.
514 Hold,
515}
516
517/// The release age `moat run` requires of new package versions when the policy
518/// does not say (ADR-030).
519pub const DEFAULT_PACKAGE_MIN_RELEASE_AGE_DAYS: u16 = 7;
520
521impl Policy {
522 /// The days a package version must have been published before `moat run`
523 /// lets npm and uv install it; `0` is off.
524 #[must_use]
525 pub fn package_min_release_age_days(&self) -> u16 {
526 self.sandbox
527 .as_ref()
528 .and_then(|s| s.package_min_release_age_days)
529 .unwrap_or(DEFAULT_PACKAGE_MIN_RELEASE_AGE_DAYS)
530 }
531
532 /// What the person's own policy says `openmoat run` passes on of its
533 /// environment (`sandbox.env`, ADR-105); `None` when it says nothing,
534 /// which means [`RunEnv::DEFAULT`]. `require.run: full-boundary` scrubs
535 /// whatever this says.
536 #[must_use]
537 pub fn run_env(&self) -> Option<RunEnv> {
538 self.sandbox.as_ref().and_then(|s| s.env)
539 }
540
541 /// What `openmoat run` without a network namespace grants at the project's
542 /// top (`sandbox.project_top`, ADR-090); [`ProjectTop::Protected`] unless
543 /// the person's own policy says otherwise.
544 #[must_use]
545 pub fn project_top(&self) -> ProjectTop {
546 self.sandbox
547 .as_ref()
548 .map(|s| s.project_top)
549 .unwrap_or_default()
550 }
551
552 /// What `openmoat run` does when a project's file would turn the agent's
553 /// hook off (`sandbox.project_hook_off`, ADR-098); [`ProjectHookOff::Refuse`]
554 /// unless the person's own policy says otherwise.
555 #[must_use]
556 pub fn project_hook_off(&self) -> ProjectHookOff {
557 self.sandbox
558 .as_ref()
559 .map(|s| s.project_hook_off)
560 .unwrap_or_default()
561 }
562
563 /// Whether `openmoat run` refuses to start without its whole protection
564 /// score (`sandbox.strict`, ADR-108); `false` unless the person's own
565 /// policy says so.
566 #[must_use]
567 pub fn sandbox_strict(&self) -> bool {
568 self.sandbox.as_ref().is_some_and(|s| s.strict)
569 }
570
571 /// What a `defer` becomes in an agent mode that asks no person
572 /// (`unattended:`, ADR-102): `defer` unless the policy says `review`.
573 #[must_use]
574 pub fn unattended(&self) -> Unattended {
575 self.unattended.unwrap_or_default()
576 }
577
578 /// What a new or changed foreign hook does to the agent's calls
579 /// (`hooks.foreign`, ADR-109): [`ForeignHooks::Warn`] unless the person's
580 /// own policy says `hold`.
581 #[must_use]
582 pub fn foreign_hooks(&self) -> ForeignHooks {
583 self.hooks.map(|h| h.foreign).unwrap_or_default()
584 }
585
586 /// Whether `moat mcp proxy` pins a new server's tools without a person
587 /// accepting them (`mcp.trust_first_sight`, ADR-032).
588 #[must_use]
589 pub fn trust_mcp_first_sight(&self) -> bool {
590 self.mcp.as_ref().is_some_and(|m| m.trust_first_sight)
591 }
592
593 /// Whether an MCP call that only opens a web page is decided as a `fetch`
594 /// (`mcp.browser_open`, ADR-047): yes unless the policy says `net`.
595 #[must_use]
596 pub fn browser_open_is_fetch(&self) -> bool {
597 self.mcp.as_ref().and_then(|m| m.browser_open) != Some(BrowserOpen::Net)
598 }
599
600 /// The MCP servers whose data flows need no `mcp-cross-server` review
601 /// (`mcp.flow_trusted`, ADR-058).
602 #[must_use]
603 pub fn mcp_flow_trusted(&self) -> &[String] {
604 self.mcp.as_ref().map_or(&[], |m| m.flow_trusted.as_slice())
605 }
606
607 /// Whether `openmoat mcp proxy` passes a server's sampling requests on
608 /// (`mcp.allow_sampling`, ADR-114).
609 #[must_use]
610 pub fn allow_mcp_sampling(&self) -> bool {
611 self.mcp.as_ref().is_some_and(|m| m.allow_sampling)
612 }
613}
614
615fn default_verdict() -> Defaults {
616 Defaults::All(Verdict::Review)
617}
618
619impl Policy {
620 /// Parse and lint a policy document. Pure: takes the YAML text.
621 pub fn parse(yaml: &str) -> Result<Self, PolicyError> {
622 schema::check(yaml)?;
623 let old_names = old_names::find(yaml)?;
624 let mut policy: Self = crate::yaml::from_str(yaml).map_err(PolicyError::Parse)?;
625 policy.old_names = old_names;
626 policy.lint()?;
627 Ok(policy)
628 }
629
630 /// Structural validation independent of any environment: [`Self::lint_structure`]
631 /// and every pattern's syntax ([`RuleGroup::check_patterns`]).
632 pub fn lint(&self) -> Result<(), PolicyError> {
633 self.lint_structure()?;
634 self.groups().try_for_each(RuleGroup::check_patterns)
635 }
636
637 /// [`Self::lint`] without parsing each pattern again, for a policy that
638 /// gained rule groups after a full lint, such as a merge of rules each
639 /// checked when they were read (a repository policy, a pack, `openmoat allow`
640 /// rules): the new groups' patterns are checked with
641 /// [`RuleGroup::check_patterns`], and nothing else needs reparsing. Parsing
642 /// every pattern costs more than the rest of the lint together, and
643 /// [`crate::CompiledPolicy::compile`] reports a bad one in any case.
644 pub fn lint_structure(&self) -> Result<(), PolicyError> {
645 if self.version != SUPPORTED_VERSION {
646 return Err(PolicyError::Version {
647 found: self.version,
648 supported: SUPPORTED_VERSION,
649 });
650 }
651 let mut ids = BTreeSet::new();
652 for group in self.groups() {
653 if group.id.trim().is_empty() {
654 return Err(PolicyError::Rule {
655 rule: "<unnamed>".into(),
656 problem: "missing id".into(),
657 });
658 }
659 if !ids.insert(group.id.clone()) {
660 return Err(PolicyError::DuplicateId(group.id.clone()));
661 }
662 if group.is_empty() {
663 return Err(PolicyError::EmptyRule(group.id.clone()));
664 }
665 text::check(group)?;
666 }
667 let narrowing = self
668 .deny
669 .iter()
670 .chain(&self.repo_review)
671 .chain(&self.review);
672 for group in narrowing {
673 crate::predicate::check(group, true)?;
674 }
675 for group in self.allow.iter().chain(&self.defer) {
676 crate::predicate::check(group, false)?;
677 }
678 hook_only::check(self)?;
679 for (name, paths) in &self.executables {
680 if paths.is_empty() {
681 return Err(PolicyError::Rule {
682 rule: format!("executables.{name}"),
683 problem: "no paths listed".into(),
684 });
685 }
686 if let Some(bad) = paths.iter().find(|p| !crate::paths::is_absolute(p)) {
687 return Err(PolicyError::Rule {
688 rule: format!("executables.{name}"),
689 problem: format!("`{bad}` is not an absolute path"),
690 });
691 }
692 }
693 for root in self.sandbox.iter().flat_map(|s| &s.read_roots) {
694 lint_read_root(root)?;
695 }
696 for name in self.sandbox.iter().flat_map(|s| &s.env_allow) {
697 if let Some(problem) = env_name_problem(name) {
698 return Err(PolicyError::Rule {
699 rule: "sandbox.env_allow".to_owned(),
700 problem: format!("`{name}` {problem}"),
701 });
702 }
703 }
704 taint::check(self.taint.as_ref())?;
705 staging::check(self.staging.as_ref())?;
706 crate::diffscan::check(self.check_diff.as_ref())?;
707 require::check(self.require.as_ref())?;
708 for (_, added) in &self.require_added {
709 require::check(Some(added))?;
710 }
711 secret::check(&self.secrets)?;
712 crate::requests::check(&self.requests)
713 }
714
715 /// What `openmoat proxy` does with a connection to a `requests:` host it
716 /// cannot terminate (`requests_untrusted:`): refuse it unless the policy
717 /// says `relay`.
718 #[must_use]
719 pub fn requests_untrusted(&self) -> crate::requests::Untrusted {
720 self.requests_untrusted.unwrap_or_default()
721 }
722
723 /// Every rule group, in the order the engine tries the lists.
724 fn groups(&self) -> impl Iterator<Item = &RuleGroup> {
725 self.deny
726 .iter()
727 .chain(&self.repo_review)
728 .chain(&self.allow)
729 .chain(&self.review)
730 .chain(&self.defer)
731 }
732
733 /// Number of rule groups in `deny`, `allow` and `review`.
734 #[must_use]
735 pub fn rule_count(&self) -> (usize, usize, usize) {
736 (self.deny.len(), self.allow.len(), self.review.len())
737 }
738}
739
740/// An OS layer takes a read root literally, and a root that is the disk or the
741/// home directory would undo every default deny.
742fn lint_read_root(root: &str) -> Result<(), PolicyError> {
743 let trimmed = root.trim_end_matches(['/', '\\']);
744 let problem = if !(crate::paths::is_absolute(root) || root.starts_with("~/")) {
745 "must be absolute or start with `~/`"
746 } else if root.contains(['*', '?', '[', ']', '{', '}', '!', '$']) {
747 "must be a plain path, not a glob or a variable"
748 } else if root.split(['/', '\\']).any(|s| s == "." || s == "..") {
749 "must not contain `.` or `..` segments"
750 } else if trimmed == "~" {
751 "must not be the home directory"
752 } else if trimmed.is_empty() || (trimmed.len() == 2 && trimmed.ends_with(':')) {
753 "must not be a filesystem root"
754 } else {
755 return Ok(());
756 };
757 Err(PolicyError::Rule {
758 rule: "sandbox.read_roots".to_owned(),
759 problem: format!("`{root}` {problem}"),
760 })
761}
762
763fn rule_err(rule: &str, e: &PolicyError) -> PolicyError {
764 PolicyError::Rule {
765 rule: rule.to_owned(),
766 problem: e.to_string(),
767 }
768}
769
770#[cfg(test)]
771mod tests;