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