Skip to main content

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    /// What session taint protects beyond the built-in list. Absent in older policies.
357    #[serde(default, skip_serializing_if = "Option::is_none")]
358    pub taint: Option<TaintSettings>,
359    /// When a session counts as having collected files outside the project
360    /// (ADR-061, proposed): the `@staging-egress` atom's thresholds. Absent in
361    /// older policies, which means the defaults.
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub staging: Option<StagingSettings>,
364    /// Trust a repository policy only when its detached signature
365    /// (`policy.yaml.sig`) verifies against a key the person trusted (ADR-031):
366    /// a signed one needs no `moat trust`, and an unsigned one is not trusted even
367    /// after `moat trust`. Off by default: then only `moat trust` lets a
368    /// repository policy allow.
369    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
370    pub require_signed_repo_policy: bool,
371    /// How `moat mcp proxy` treats tool definitions (ADR-032). Absent in older policies.
372    #[serde(default, skip_serializing_if = "Option::is_none")]
373    pub mcp: Option<McpSettings>,
374    /// The levels `openmoat policy check-diff` reports its content checks at
375    /// (ADR-055). Absent in older policies: each check's own level.
376    #[serde(default, skip_serializing_if = "Option::is_none")]
377    pub check_diff: Option<crate::diffscan::Settings>,
378    /// The least protection level each agent must be at for `openmoat guard`
379    /// to decide its calls; below it, every call is denied
380    /// (`protection-required`, ADR-064). Absent in older policies and the
381    /// default: nothing is required.
382    #[serde(default, skip_serializing_if = "Option::is_none")]
383    pub require: Option<Require>,
384    /// What a `defer` becomes when the agent reports a mode in which it runs
385    /// calls with no person asked (ADR-102): `defer` (absent, the default)
386    /// leaves it to the agent, `review` holds it for a person. Only the
387    /// person's own policy holds it: a repository policy or a pack with the key
388    /// does not parse.
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub unattended: Option<Unattended>,
391    /// The `require:` sections of the repository policy and the packs merged
392    /// in ([`Policy::add_requirement`]), read with [`Self::require`] by
393    /// [`Policy::required_for`], which takes the strictest: they raise a
394    /// level, never lower one. Never read from or written to a file.
395    #[serde(skip)]
396    pub require_added: Vec<(RequiredBy, Require)>,
397    /// Review rules merged in from a repository policy ([`crate::RepoPolicy`],
398    /// ADR-022) or a policy pack (ADR-031). Tried after `deny` and before
399    /// `allow`, so a repository can make an action the user allows need review.
400    /// Never read from or written to a file, and not lowered to OS layers, which
401    /// are generated from the user policy alone.
402    #[serde(skip)]
403    pub repo_review: Vec<RuleGroup>,
404    /// Where the file used `ask`, the old name of `review` (ADR-053), which
405    /// `policy lint` warns about. Set by [`Policy::parse`]; never written.
406    #[serde(skip)]
407    pub old_names: OldNames,
408}
409
410/// The `sandbox:` section (ADR-018, ADR-019).
411#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
412#[serde(deny_unknown_fields)]
413pub struct SandboxSettings {
414    /// Paths (directories or files) the OS layers let commands read although no
415    /// allow rule covers them: system and toolchain directories every build
416    /// reads. The hook decision ignores them, and deny rules win over them in
417    /// every layer. Absolute or `~/…`, never a glob.
418    #[serde(default)]
419    pub read_roots: Vec<String>,
420    /// The loopback port `moat proxy` listens on and the host sandboxes send
421    /// their commands' traffic to; absent, the CLI's default.
422    #[serde(default, skip_serializing_if = "Option::is_none")]
423    pub proxy_port: Option<std::num::NonZeroU16>,
424    /// Let `moat proxy` forward a TLS `ClientHello` that carries an encrypted
425    /// server name (ECH, ESNI). Off, such a tunnel is refused: the server acts
426    /// on the encrypted name, which may be another site than the allowed host.
427    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
428    pub proxy_allow_ech: bool,
429    /// Let `moat proxy` serve a request that carries no session credential,
430    /// with no session (ADR-044). Off, such a request gets 407: a session's
431    /// taint and connection share cannot be escaped by sending no credential,
432    /// and other local processes cannot use the proxy. `moat run` ignores it.
433    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
434    pub proxy_serve_without_credential: bool,
435    /// Days a package version must have been published before the package
436    /// managers `moat run` starts install it (ADR-030); `0` turns this off,
437    /// absent is 7 days ([`Policy::package_min_release_age_days`]).
438    #[serde(default, skip_serializing_if = "Option::is_none")]
439    pub package_min_release_age_days: Option<u16>,
440    /// Names of inherited environment variables `openmoat run` passes on
441    /// under `require.run: full-boundary`, beyond its own list and the
442    /// agent's (ADR-077). Names only, never a pattern. Read from the person's
443    /// own policy alone: a repository policy or a pack has no `sandbox:`.
444    #[serde(default, skip_serializing_if = "Vec::is_empty")]
445    pub env_allow: Vec<String>,
446    /// What `openmoat run`'s Lightweight tier on Linux without a network
447    /// namespace grants at the top of the project (ADR-090): `protected`
448    /// grants it entry by entry, so nothing can be created there and `.env`,
449    /// `.git` and `.moat` stay covered; `writable` grants it whole, so new
450    /// entries and save-by-rename work there and those paths are open to the
451    /// agent's commands. Never read by the Isolated tier or the network
452    /// namespace. Read from the person's own policy alone: a repository policy
453    /// or a pack has no `sandbox:`.
454    #[serde(default, skip_serializing_if = "ProjectTop::is_protected")]
455    pub project_top: ProjectTop,
456    /// What `openmoat run` does when a file of the project would turn the
457    /// agent's OpenMoat hook off as the session starts (ADR-098): `refuse`
458    /// (absent) does not start the agent; `start` starts it anyway, says so
459    /// and records it. Read from the person's own policy alone: a repository
460    /// policy or a pack has no `sandbox:`.
461    #[serde(default, skip_serializing_if = "ProjectHookOff::is_refuse")]
462    pub project_hook_off: ProjectHookOff,
463}
464
465/// `sandbox.project_hook_off` (ADR-098).
466#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
467#[serde(rename_all = "lowercase")]
468pub enum ProjectHookOff {
469    /// The agent does not start.
470    #[default]
471    Refuse,
472    /// The agent starts without OpenMoat's hook; the run says so and records it.
473    Start,
474}
475
476impl ProjectHookOff {
477    /// Whether this is the default, [`ProjectHookOff::Refuse`].
478    #[must_use]
479    pub fn is_refuse(&self) -> bool {
480        *self == Self::Refuse
481    }
482}
483
484/// `sandbox.project_top` (ADR-090).
485#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
486#[serde(rename_all = "lowercase")]
487pub enum ProjectTop {
488    /// Granted entry by entry: the policy's denies at the top hold.
489    #[default]
490    Protected,
491    /// Granted whole: the top is writable, and `.env` and `.git/hooks` there
492    /// are open to the agent's commands.
493    Writable,
494}
495
496impl ProjectTop {
497    /// Whether this is the default, [`ProjectTop::Protected`].
498    #[must_use]
499    pub fn is_protected(&self) -> bool {
500        *self == Self::Protected
501    }
502}
503
504/// The `mcp:` section (ADR-032).
505#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
506#[serde(deny_unknown_fields)]
507pub struct McpSettings {
508    /// Pin every tool `moat mcp proxy` sees from a server it has no pins for,
509    /// as it is, instead of holding them until `moat mcp accept`. Off by
510    /// default: a server that is malicious on first contact would get its
511    /// tool descriptions pinned as good.
512    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
513    pub trust_first_sight: bool,
514    /// How an MCP call that only opens or reads one web page is decided
515    /// (ADR-047): `fetch` (absent) as a `fetch` of its host, like `WebFetch`;
516    /// `net` as a `net` connection, which the default policy denies for
517    /// unlisted hosts.
518    #[serde(default, skip_serializing_if = "Option::is_none")]
519    pub browser_open: Option<BrowserOpen>,
520    /// MCP servers, by the name `openmoat mcp proxy --server` gives them,
521    /// whose data flows are trusted (ADR-058): text such a server returned may
522    /// reach another server's tool that writes or sends, and a call to such a
523    /// server may carry another server's text, without a `mcp-cross-server`
524    /// review.
525    #[serde(default, skip_serializing_if = "Vec::is_empty")]
526    pub flow_trusted: Vec<String>,
527}
528
529/// `mcp.browser_open`: the kind a read-only page open of an MCP tool is decided as.
530#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
531#[serde(rename_all = "lowercase")]
532pub enum BrowserOpen {
533    /// A `fetch` of the page's host (the default).
534    Fetch,
535    /// A `net` connection to the page's host, as any other MCP URL argument.
536    Net,
537}
538
539/// `unattended:`: what a `defer` becomes in an agent mode that runs calls
540/// with no person asked (auto-approve, YOLO, headless; ADR-102).
541#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
542#[serde(rename_all = "lowercase")]
543pub enum Unattended {
544    /// The agent decides it, as everywhere else (ADR-025): in such a mode it
545    /// runs. The default.
546    #[default]
547    Defer,
548    /// OpenMoat holds it for review, and a review there is answered as a deny
549    /// that says how to approve it (or sent to the approvals channel).
550    Review,
551}
552
553/// The release age `moat run` requires of new package versions when the policy
554/// does not say (ADR-030).
555pub const DEFAULT_PACKAGE_MIN_RELEASE_AGE_DAYS: u16 = 7;
556
557impl Policy {
558    /// The days a package version must have been published before `moat run`
559    /// lets npm and uv install it; `0` is off.
560    #[must_use]
561    pub fn package_min_release_age_days(&self) -> u16 {
562        self.sandbox
563            .as_ref()
564            .and_then(|s| s.package_min_release_age_days)
565            .unwrap_or(DEFAULT_PACKAGE_MIN_RELEASE_AGE_DAYS)
566    }
567
568    /// What `openmoat run` without a network namespace grants at the project's
569    /// top (`sandbox.project_top`, ADR-090); [`ProjectTop::Protected`] unless
570    /// the person's own policy says otherwise.
571    #[must_use]
572    pub fn project_top(&self) -> ProjectTop {
573        self.sandbox
574            .as_ref()
575            .map(|s| s.project_top)
576            .unwrap_or_default()
577    }
578
579    /// What `openmoat run` does when a project's file would turn the agent's
580    /// hook off (`sandbox.project_hook_off`, ADR-098); [`ProjectHookOff::Refuse`]
581    /// unless the person's own policy says otherwise.
582    #[must_use]
583    pub fn project_hook_off(&self) -> ProjectHookOff {
584        self.sandbox
585            .as_ref()
586            .map(|s| s.project_hook_off)
587            .unwrap_or_default()
588    }
589
590    /// What a `defer` becomes in an agent mode that asks no person
591    /// (`unattended:`, ADR-102): `defer` unless the policy says `review`.
592    #[must_use]
593    pub fn unattended(&self) -> Unattended {
594        self.unattended.unwrap_or_default()
595    }
596
597    /// Whether `moat mcp proxy` pins a new server's tools without a person
598    /// accepting them (`mcp.trust_first_sight`, ADR-032).
599    #[must_use]
600    pub fn trust_mcp_first_sight(&self) -> bool {
601        self.mcp.as_ref().is_some_and(|m| m.trust_first_sight)
602    }
603
604    /// Whether an MCP call that only opens a web page is decided as a `fetch`
605    /// (`mcp.browser_open`, ADR-047): yes unless the policy says `net`.
606    #[must_use]
607    pub fn browser_open_is_fetch(&self) -> bool {
608        self.mcp.as_ref().and_then(|m| m.browser_open) != Some(BrowserOpen::Net)
609    }
610
611    /// The MCP servers whose data flows need no `mcp-cross-server` review
612    /// (`mcp.flow_trusted`, ADR-058).
613    #[must_use]
614    pub fn mcp_flow_trusted(&self) -> &[String] {
615        self.mcp.as_ref().map_or(&[], |m| m.flow_trusted.as_slice())
616    }
617}
618
619fn default_verdict() -> Defaults {
620    Defaults::All(Verdict::Review)
621}
622
623impl Policy {
624    /// Parse and lint a policy document. Pure: takes the YAML text.
625    pub fn parse(yaml: &str) -> Result<Self, PolicyError> {
626        let old_names = old_names::find(yaml)?;
627        let mut policy: Self = crate::yaml::from_str(yaml).map_err(PolicyError::Parse)?;
628        policy.old_names = old_names;
629        policy.lint()?;
630        Ok(policy)
631    }
632
633    /// Structural validation independent of any environment: [`Self::lint_structure`]
634    /// and every pattern's syntax ([`RuleGroup::check_patterns`]).
635    pub fn lint(&self) -> Result<(), PolicyError> {
636        self.lint_structure()?;
637        self.groups().try_for_each(RuleGroup::check_patterns)
638    }
639
640    /// [`Self::lint`] without parsing each pattern again, for a policy that
641    /// gained rule groups after a full lint, such as a merge of rules each
642    /// checked when they were read (a repository policy, a pack, `openmoat allow`
643    /// rules): the new groups' patterns are checked with
644    /// [`RuleGroup::check_patterns`], and nothing else needs reparsing. Parsing
645    /// every pattern costs more than the rest of the lint together, and
646    /// [`crate::CompiledPolicy::compile`] reports a bad one in any case.
647    pub fn lint_structure(&self) -> Result<(), PolicyError> {
648        if self.version != SUPPORTED_VERSION {
649            return Err(PolicyError::Version {
650                found: self.version,
651                supported: SUPPORTED_VERSION,
652            });
653        }
654        let mut ids = BTreeSet::new();
655        for group in self.groups() {
656            if group.id.trim().is_empty() {
657                return Err(PolicyError::Rule {
658                    rule: "<unnamed>".into(),
659                    problem: "missing id".into(),
660                });
661            }
662            if !ids.insert(group.id.clone()) {
663                return Err(PolicyError::DuplicateId(group.id.clone()));
664            }
665            if group.is_empty() {
666                return Err(PolicyError::EmptyRule(group.id.clone()));
667            }
668            text::check(group)?;
669        }
670        hook_only::check(self)?;
671        for (name, paths) in &self.executables {
672            if paths.is_empty() {
673                return Err(PolicyError::Rule {
674                    rule: format!("executables.{name}"),
675                    problem: "no paths listed".into(),
676                });
677            }
678            if let Some(bad) = paths.iter().find(|p| !crate::paths::is_absolute(p)) {
679                return Err(PolicyError::Rule {
680                    rule: format!("executables.{name}"),
681                    problem: format!("`{bad}` is not an absolute path"),
682                });
683            }
684        }
685        for root in self.sandbox.iter().flat_map(|s| &s.read_roots) {
686            lint_read_root(root)?;
687        }
688        for name in self.sandbox.iter().flat_map(|s| &s.env_allow) {
689            if let Some(problem) = env_name_problem(name) {
690                return Err(PolicyError::Rule {
691                    rule: "sandbox.env_allow".to_owned(),
692                    problem: format!("`{name}` {problem}"),
693                });
694            }
695        }
696        taint::check(self.taint.as_ref())?;
697        staging::check(self.staging.as_ref())?;
698        crate::diffscan::check(self.check_diff.as_ref())?;
699        require::check(self.require.as_ref())?;
700        for (_, added) in &self.require_added {
701            require::check(Some(added))?;
702        }
703        secret::check(&self.secrets)
704    }
705
706    /// Every rule group, in the order the engine tries the lists.
707    fn groups(&self) -> impl Iterator<Item = &RuleGroup> {
708        self.deny
709            .iter()
710            .chain(&self.repo_review)
711            .chain(&self.allow)
712            .chain(&self.review)
713            .chain(&self.defer)
714    }
715
716    /// Number of rule groups in `deny`, `allow` and `review`.
717    #[must_use]
718    pub fn rule_count(&self) -> (usize, usize, usize) {
719        (self.deny.len(), self.allow.len(), self.review.len())
720    }
721}
722
723/// An OS layer takes a read root literally, and a root that is the disk or the
724/// home directory would undo every default deny.
725fn lint_read_root(root: &str) -> Result<(), PolicyError> {
726    let trimmed = root.trim_end_matches(['/', '\\']);
727    let problem = if !(crate::paths::is_absolute(root) || root.starts_with("~/")) {
728        "must be absolute or start with `~/`"
729    } else if root.contains(['*', '?', '[', ']', '{', '}', '!', '$']) {
730        "must be a plain path, not a glob or a variable"
731    } else if root.split(['/', '\\']).any(|s| s == "." || s == "..") {
732        "must not contain `.` or `..` segments"
733    } else if trimmed == "~" {
734        "must not be the home directory"
735    } else if trimmed.is_empty() || (trimmed.len() == 2 && trimmed.ends_with(':')) {
736        "must not be a filesystem root"
737    } else {
738        return Ok(());
739    };
740    Err(PolicyError::Rule {
741        rule: "sandbox.read_roots".to_owned(),
742        problem: format!("`{root}` {problem}"),
743    })
744}
745
746fn rule_err(rule: &str, e: &PolicyError) -> PolicyError {
747    PolicyError::Rule {
748        rule: rule.to_owned(),
749        problem: e.to_string(),
750    }
751}
752
753#[cfg(test)]
754mod tests;