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, "default".to_owned()),
26            Self::PerKind(map) => kind
27                .rule_kinds()
28                .iter()
29                .find_map(|k| map.get(k.as_str()).map(|v| (*v, format!("default.{k}"))))
30                .unwrap_or_else(|| {
31                    (
32                        map.get("*").copied().unwrap_or(Verdict::Review),
33                        "default".to_owned(),
34                    )
35                }),
36        }
37    }
38
39    /// The default for an atom no rule matched: [`Self::for_kind`], except that a
40    /// word that only looks like a host is no network evidence and gets
41    /// [`Self::unclassified`] (ADR-025).
42    #[must_use]
43    pub fn for_atom(&self, atom: &crate::AtomicAction) -> (Verdict, String) {
44        match atom {
45            crate::AtomicAction::NetWord { .. } => (self.unclassified(), "default".to_owned()),
46            _ => self.for_kind(atom.kind()),
47        }
48    }
49
50    /// What OpenMoat gives a call it cannot classify, or a word that only looks
51    /// like a host: `defer` under a catch-all (`"*"`) of `allow` or `defer`, else
52    /// `review` (ADR-025). Never `allow`, and never a deny nothing named.
53    #[must_use]
54    pub fn unclassified(&self) -> Verdict {
55        let catch_all = match self {
56            Self::All(v) => *v,
57            Self::PerKind(map) => map.get("*").copied().unwrap_or(Verdict::Review),
58        };
59        catch_all.clamp(Verdict::Defer, Verdict::Review)
60    }
61}
62
63use serde::{Deserialize, Serialize};
64use thiserror::Error;
65
66use crate::kind::Kind;
67use crate::pattern::{GlobPattern, ShellPattern};
68use crate::secret::{self, Secret};
69use crate::taint::{self, TaintSettings};
70use crate::verdict::Verdict;
71
72mod hook_only;
73mod old_names;
74
75pub use old_names::OldNames;
76
77/// The policy schema version (`version:`) this build reads; any other is an error.
78pub const SUPPORTED_VERSION: u32 = 1;
79
80/// Why a policy file cannot be used. Any of these keeps `guard` from deciding.
81///
82/// Messages include their cause, so no variant also exposes it as `source`:
83/// a chained report (`{:#}`) would print it twice.
84#[derive(Debug, Error)]
85#[non_exhaustive]
86pub enum PolicyError {
87    /// The file is not valid YAML or does not fit the schema.
88    #[error("policy parse error: {0}")]
89    Parse(crate::yaml::Error),
90    /// The `version` key names a schema this build does not know.
91    #[error("unsupported policy version {found}; this build supports {supported}")]
92    Version {
93        /// The version in the file.
94        found: u32,
95        /// The version this build supports.
96        supported: u32,
97    },
98    /// Two rule groups share an id.
99    #[error("duplicate rule id `{0}`")]
100    DuplicateId(String),
101    /// A rule group lists no patterns.
102    #[error("rule `{0}` has no patterns")]
103    EmptyRule(String),
104    /// A pattern is empty (or only `!`/`$`).
105    #[error("empty pattern")]
106    EmptyPattern,
107    /// A glob does not compile.
108    #[error("bad glob `{pattern}`: {error}")]
109    BadGlob {
110        /// The pattern as written.
111        pattern: String,
112        /// The glob compiler's explanation.
113        error: globset::Error,
114    },
115    /// A shell pattern does not tokenise (unbalanced quotes, a here-document).
116    #[error("bad shell pattern `{pattern}` (unbalanced quotes?)")]
117    BadShellPattern {
118        /// The pattern as written.
119        pattern: String,
120    },
121    /// The file has both `ask:` and `review:` (ADR-053): `ask` is the old name
122    /// of `review`, and which list was meant cannot be told.
123    #[error(
124        "the policy has both `{old}:` and `{new}:`; `{old}` is the old name of `{new}`: \
125         move the `{old}:` rules into `{new}:` (`openmoat policy upgrade` renames a policy \
126         that has only `{old}:`)"
127    )]
128    OldAndNewName {
129        /// The old key.
130        old: &'static str,
131        /// The current key.
132        new: &'static str,
133    },
134    /// A rule group or `executables` entry is invalid; `problem` says why.
135    #[error("rule `{rule}`: {problem}")]
136    Rule {
137        /// Rule id, or `executables.<name>`.
138        rule: String,
139        /// What is wrong.
140        problem: String,
141    },
142}
143
144/// One named group of patterns. A group matches when **any** of its patterns
145/// matches the atomic action of the corresponding kind.
146#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
147#[serde(deny_unknown_fields)]
148pub struct RuleGroup {
149    /// Stable identifier shown in decisions and the audit log.
150    pub id: String,
151    /// Text prepended to the reason when this group decides.
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub reason: Option<String>,
154    /// Shell patterns (token prefixes, `*`, `!`, trailing `$`).
155    #[serde(default, skip_serializing_if = "Vec::is_empty")]
156    pub shell: Vec<String>,
157    /// Path globs for file reads.
158    #[serde(default, rename = "fs.read", skip_serializing_if = "Vec::is_empty")]
159    pub fs_read: Vec<String>,
160    /// Path globs for file writes.
161    #[serde(default, rename = "fs.write", skip_serializing_if = "Vec::is_empty")]
162    pub fs_write: Vec<String>,
163    /// Host globs for any network access, fetches included.
164    #[serde(default, skip_serializing_if = "Vec::is_empty")]
165    pub net: Vec<String>,
166    /// Host globs for read-only fetches by a host's fetch tool only.
167    #[serde(default, skip_serializing_if = "Vec::is_empty")]
168    pub fetch: Vec<String>,
169    /// Variable-name globs for reads.
170    #[serde(default, rename = "env.read", skip_serializing_if = "Vec::is_empty")]
171    pub env_read: Vec<String>,
172    /// Variable-name globs for sets.
173    #[serde(default, rename = "env.set", skip_serializing_if = "Vec::is_empty")]
174    pub env_set: Vec<String>,
175    /// MCP tool-name globs.
176    #[serde(default, skip_serializing_if = "Vec::is_empty")]
177    pub mcp: Vec<String>,
178    /// Applied by the hook only (ADR-034): OS layers leave this group's
179    /// `fs.read` and `fs.write` paths to the other rules, so a build tool a
180    /// sandboxed command runs can still read them. `deny` groups only, never
181    /// with `net` or `fetch`.
182    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
183    pub hook_only: bool,
184}
185
186impl RuleGroup {
187    /// The patterns this group lists for `kind`.
188    #[must_use]
189    pub fn patterns(&self, kind: Kind) -> &[String] {
190        match kind {
191            Kind::Shell => &self.shell,
192            Kind::FsRead => &self.fs_read,
193            Kind::FsWrite => &self.fs_write,
194            Kind::Net => &self.net,
195            Kind::Fetch => &self.fetch,
196            // A query or an unknown tool names no host or path to match; only
197            // `defaults` decide them.
198            Kind::WebSearch | Kind::UnknownTool => &[],
199            Kind::EnvRead => &self.env_read,
200            Kind::EnvSet => &self.env_set,
201            Kind::Mcp => &self.mcp,
202        }
203    }
204
205    fn is_empty(&self) -> bool {
206        Kind::ALL.iter().all(|k| self.patterns(*k).is_empty())
207    }
208
209    /// Check that every pattern of this group parses, naming the group in the
210    /// error: what [`Policy::lint`] does for each group.
211    ///
212    /// # Errors
213    /// [`PolicyError::Rule`] for the first pattern that does not parse.
214    pub fn check_patterns(&self) -> Result<(), PolicyError> {
215        for kind in Kind::ALL {
216            for p in self.patterns(kind) {
217                let compiled = if kind == Kind::Shell {
218                    ShellPattern::compile(p).map(drop)
219                } else {
220                    GlobPattern::compile(p, false).map(drop)
221                };
222                compiled.map_err(|e| rule_err(&self.id, &e))?;
223            }
224        }
225        Ok(())
226    }
227}
228
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230#[serde(deny_unknown_fields)]
231pub struct Scope {
232    #[serde(default = "default_roots")]
233    pub project_roots: Vec<String>,
234}
235
236fn default_roots() -> Vec<String> {
237    vec![".".to_owned()]
238}
239
240impl Default for Scope {
241    fn default() -> Self {
242        Self {
243            project_roots: default_roots(),
244        }
245    }
246}
247
248#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(rename_all = "lowercase")]
250pub enum ApprovalChannel {
251    Terminal,
252    Telegram,
253}
254
255#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
256#[serde(rename_all = "lowercase")]
257pub enum RememberScope {
258    Once,
259    Session,
260    Permanent,
261}
262
263#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
264#[serde(deny_unknown_fields)]
265pub struct Approval {
266    #[serde(default = "default_channel")]
267    pub channel: ApprovalChannel,
268    #[serde(default = "default_remember")]
269    pub remember: RememberScope,
270    #[serde(default = "default_timeout")]
271    pub timeout_s: u32,
272}
273
274fn default_channel() -> ApprovalChannel {
275    ApprovalChannel::Terminal
276}
277fn default_remember() -> RememberScope {
278    RememberScope::Session
279}
280fn default_timeout() -> u32 {
281    300
282}
283
284impl Default for Approval {
285    fn default() -> Self {
286        Self {
287            channel: default_channel(),
288            remember: default_remember(),
289            timeout_s: default_timeout(),
290        }
291    }
292}
293
294/// The policy document (`policy.yaml`), as written by users.
295#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
296#[serde(deny_unknown_fields)]
297pub struct Policy {
298    /// Schema version; only 1 is supported.
299    pub version: u32,
300    /// Verdict when no rule matches.
301    #[serde(default = "default_verdict")]
302    pub defaults: Defaults,
303    /// Reserved for multi-root projects; parsed so existing files stay valid,
304    /// not yet consulted (`policy lint` warns).
305    #[serde(default, skip_serializing_if = "Option::is_none")]
306    pub scope: Option<Scope>,
307    /// Evaluated first; a match is final.
308    #[serde(default)]
309    pub deny: Vec<RuleGroup>,
310    /// Evaluated after `deny`.
311    #[serde(default)]
312    pub allow: Vec<RuleGroup>,
313    /// Evaluated after `allow`: calls a person reviews. Read from `ask:` too,
314    /// its name before ADR-053 ([`OldNames`]).
315    #[serde(default, alias = "ask")]
316    pub review: Vec<RuleGroup>,
317    /// Evaluated after `review`: calls the agent's own permission flow decides
318    /// (ADR-025). Absent in policies written before it existed.
319    #[serde(default, skip_serializing_if = "Vec::is_empty")]
320    pub defer: Vec<RuleGroup>,
321    /// Reserved for the kernel's own approval prompt; parsed so existing files
322    /// stay valid, not yet consulted (`policy lint` warns).
323    #[serde(default, skip_serializing_if = "Option::is_none")]
324    pub approval: Option<Approval>,
325    /// Basename → allowed absolute paths (defeats PATH poisoning).
326    #[serde(default)]
327    pub executables: BTreeMap<String, Vec<String>>,
328    /// What the operating-system layers OpenMoat configures need beyond the rules
329    /// (ADR-018). Absent in policies written before it existed.
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    pub sandbox: Option<SandboxSettings>,
332    /// Secrets `moat proxy` keeps from the agent and injects for one host each.
333    #[serde(default, skip_serializing_if = "Vec::is_empty")]
334    pub secrets: Vec<Secret>,
335    /// What session taint protects beyond the built-in list. Absent in older policies.
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub taint: Option<TaintSettings>,
338    /// Trust a repository policy only when its detached signature
339    /// (`policy.yaml.sig`) verifies against a key the person trusted (ADR-031):
340    /// a signed one needs no `moat trust`, and an unsigned one is not trusted even
341    /// after `moat trust`. Off by default: then only `moat trust` lets a
342    /// repository policy allow.
343    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
344    pub require_signed_repo_policy: bool,
345    /// How `moat mcp proxy` treats tool definitions (ADR-032). Absent in older policies.
346    #[serde(default, skip_serializing_if = "Option::is_none")]
347    pub mcp: Option<McpSettings>,
348    /// Review rules merged in from a repository policy ([`crate::RepoPolicy`],
349    /// ADR-022) or a policy pack (ADR-031). Tried after `deny` and before
350    /// `allow`, so a repository can make an action the user allows need review.
351    /// Never read from or written to a file, and not lowered to OS layers, which
352    /// are generated from the user policy alone.
353    #[serde(skip)]
354    pub repo_review: Vec<RuleGroup>,
355    /// Where the file used `ask`, the old name of `review` (ADR-053), which
356    /// `policy lint` warns about. Set by [`Policy::parse`]; never written.
357    #[serde(skip)]
358    pub old_names: OldNames,
359}
360
361/// The `sandbox:` section (ADR-018, ADR-019).
362#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
363#[serde(deny_unknown_fields)]
364pub struct SandboxSettings {
365    /// Paths (directories or files) the OS layers let commands read although no
366    /// allow rule covers them: system and toolchain directories every build
367    /// reads. The hook decision ignores them, and deny rules win over them in
368    /// every layer. Absolute or `~/…`, never a glob.
369    #[serde(default)]
370    pub read_roots: Vec<String>,
371    /// The loopback port `moat proxy` listens on and the host sandboxes send
372    /// their commands' traffic to; absent, the CLI's default.
373    #[serde(default, skip_serializing_if = "Option::is_none")]
374    pub proxy_port: Option<std::num::NonZeroU16>,
375    /// Let `moat proxy` forward a TLS `ClientHello` that carries an encrypted
376    /// server name (ECH, ESNI). Off, such a tunnel is refused: the server acts
377    /// on the encrypted name, which may be another site than the allowed host.
378    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
379    pub proxy_allow_ech: bool,
380    /// Let `moat proxy` serve a request that carries no session credential,
381    /// with no session (ADR-044). Off, such a request gets 407: a session's
382    /// taint and connection share cannot be escaped by sending no credential,
383    /// and other local processes cannot use the proxy. `moat run` ignores it.
384    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
385    pub proxy_serve_without_credential: bool,
386    /// Days a package version must have been published before the package
387    /// managers `moat run` starts install it (ADR-030); `0` turns this off,
388    /// absent is 7 days ([`Policy::package_min_release_age_days`]).
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub package_min_release_age_days: Option<u16>,
391}
392
393/// The `mcp:` section (ADR-032).
394#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
395#[serde(deny_unknown_fields)]
396pub struct McpSettings {
397    /// Pin every tool `moat mcp proxy` sees from a server it has no pins for,
398    /// as it is, instead of holding them until `moat mcp accept`. Off by
399    /// default: a server that is malicious on first contact would get its
400    /// tool descriptions pinned as good.
401    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
402    pub trust_first_sight: bool,
403    /// How an MCP call that only opens or reads one web page is decided
404    /// (ADR-047): `fetch` (absent) as a `fetch` of its host, like `WebFetch`;
405    /// `net` as a `net` connection, which the default policy denies for
406    /// unlisted hosts.
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub browser_open: Option<BrowserOpen>,
409}
410
411/// `mcp.browser_open`: the kind a read-only page open of an MCP tool is decided as.
412#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
413#[serde(rename_all = "lowercase")]
414pub enum BrowserOpen {
415    /// A `fetch` of the page's host (the default).
416    Fetch,
417    /// A `net` connection to the page's host, as any other MCP URL argument.
418    Net,
419}
420
421/// The release age `moat run` requires of new package versions when the policy
422/// does not say (ADR-030).
423pub const DEFAULT_PACKAGE_MIN_RELEASE_AGE_DAYS: u16 = 7;
424
425impl Policy {
426    /// The days a package version must have been published before `moat run`
427    /// lets npm and uv install it; `0` is off.
428    #[must_use]
429    pub fn package_min_release_age_days(&self) -> u16 {
430        self.sandbox
431            .as_ref()
432            .and_then(|s| s.package_min_release_age_days)
433            .unwrap_or(DEFAULT_PACKAGE_MIN_RELEASE_AGE_DAYS)
434    }
435
436    /// Whether `moat mcp proxy` pins a new server's tools without a person
437    /// accepting them (`mcp.trust_first_sight`, ADR-032).
438    #[must_use]
439    pub fn trust_mcp_first_sight(&self) -> bool {
440        self.mcp.as_ref().is_some_and(|m| m.trust_first_sight)
441    }
442
443    /// Whether an MCP call that only opens a web page is decided as a `fetch`
444    /// (`mcp.browser_open`, ADR-047): yes unless the policy says `net`.
445    #[must_use]
446    pub fn browser_open_is_fetch(&self) -> bool {
447        self.mcp.as_ref().and_then(|m| m.browser_open) != Some(BrowserOpen::Net)
448    }
449}
450
451fn default_verdict() -> Defaults {
452    Defaults::All(Verdict::Review)
453}
454
455impl Policy {
456    /// Parse and lint a policy document. Pure: takes the YAML text.
457    pub fn parse(yaml: &str) -> Result<Self, PolicyError> {
458        let old_names = old_names::find(yaml)?;
459        let mut policy: Self = crate::yaml::from_str(yaml).map_err(PolicyError::Parse)?;
460        policy.old_names = old_names;
461        policy.lint()?;
462        Ok(policy)
463    }
464
465    /// Structural validation independent of any environment: [`Self::lint_structure`]
466    /// and every pattern's syntax ([`RuleGroup::check_patterns`]).
467    pub fn lint(&self) -> Result<(), PolicyError> {
468        self.lint_structure()?;
469        self.groups().try_for_each(RuleGroup::check_patterns)
470    }
471
472    /// [`Self::lint`] without parsing each pattern again, for a policy that
473    /// gained rule groups after a full lint, such as a merge of rules each
474    /// checked when they were read (a repository policy, a pack, `openmoat allow`
475    /// rules): the new groups' patterns are checked with
476    /// [`RuleGroup::check_patterns`], and nothing else needs reparsing. Parsing
477    /// every pattern costs more than the rest of the lint together, and
478    /// [`crate::CompiledPolicy::compile`] reports a bad one in any case.
479    pub fn lint_structure(&self) -> Result<(), PolicyError> {
480        if self.version != SUPPORTED_VERSION {
481            return Err(PolicyError::Version {
482                found: self.version,
483                supported: SUPPORTED_VERSION,
484            });
485        }
486        let mut ids = BTreeSet::new();
487        for group in self.groups() {
488            if group.id.trim().is_empty() {
489                return Err(PolicyError::Rule {
490                    rule: "<unnamed>".into(),
491                    problem: "missing id".into(),
492                });
493            }
494            if !ids.insert(group.id.clone()) {
495                return Err(PolicyError::DuplicateId(group.id.clone()));
496            }
497            if group.is_empty() {
498                return Err(PolicyError::EmptyRule(group.id.clone()));
499            }
500        }
501        hook_only::check(self)?;
502        for (name, paths) in &self.executables {
503            if paths.is_empty() {
504                return Err(PolicyError::Rule {
505                    rule: format!("executables.{name}"),
506                    problem: "no paths listed".into(),
507                });
508            }
509            if let Some(bad) = paths.iter().find(|p| !crate::paths::is_absolute(p)) {
510                return Err(PolicyError::Rule {
511                    rule: format!("executables.{name}"),
512                    problem: format!("`{bad}` is not an absolute path"),
513                });
514            }
515        }
516        for root in self.sandbox.iter().flat_map(|s| &s.read_roots) {
517            lint_read_root(root)?;
518        }
519        taint::check(self.taint.as_ref())?;
520        secret::check(&self.secrets)
521    }
522
523    /// Every rule group, in the order the engine tries the lists.
524    fn groups(&self) -> impl Iterator<Item = &RuleGroup> {
525        self.deny
526            .iter()
527            .chain(&self.repo_review)
528            .chain(&self.allow)
529            .chain(&self.review)
530            .chain(&self.defer)
531    }
532
533    /// Number of rule groups in `deny`, `allow` and `review`.
534    #[must_use]
535    pub fn rule_count(&self) -> (usize, usize, usize) {
536        (self.deny.len(), self.allow.len(), self.review.len())
537    }
538}
539
540/// An OS layer takes a read root literally, and a root that is the disk or the
541/// home directory would undo every default deny.
542fn lint_read_root(root: &str) -> Result<(), PolicyError> {
543    let trimmed = root.trim_end_matches(['/', '\\']);
544    let problem = if !(crate::paths::is_absolute(root) || root.starts_with("~/")) {
545        "must be absolute or start with `~/`"
546    } else if root.contains(['*', '?', '[', ']', '{', '}', '!', '$']) {
547        "must be a plain path, not a glob or a variable"
548    } else if root.split(['/', '\\']).any(|s| s == "." || s == "..") {
549        "must not contain `.` or `..` segments"
550    } else if trimmed == "~" {
551        "must not be the home directory"
552    } else if trimmed.is_empty() || (trimmed.len() == 2 && trimmed.ends_with(':')) {
553        "must not be a filesystem root"
554    } else {
555        return Ok(());
556    };
557    Err(PolicyError::Rule {
558        rule: "sandbox.read_roots".to_owned(),
559        problem: format!("`{root}` {problem}"),
560    })
561}
562
563fn rule_err(rule: &str, e: &PolicyError) -> PolicyError {
564    PolicyError::Rule {
565        rule: rule.to_owned(),
566        problem: e.to_string(),
567    }
568}
569
570#[cfg(test)]
571mod tests;