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