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