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::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 /// Names of inherited environment variables `openmoat run` passes on
391 /// under `require.run: full-boundary`, beyond its own list and the
392 /// agent's (ADR-077). Names only, never a pattern. Read from the person's
393 /// own policy alone: a repository policy or a pack has no `sandbox:`.
394 #[serde(default, skip_serializing_if = "Vec::is_empty")]
395 pub env_allow: Vec<String>,
396 /// What `openmoat run`'s Lightweight tier on Linux without a network
397 /// namespace grants at the top of the project (ADR-090): `protected`
398 /// grants it entry by entry, so nothing can be created there and `.env`,
399 /// `.git` and `.moat` stay covered; `writable` grants it whole, so new
400 /// entries and save-by-rename work there and those paths are open to the
401 /// agent's commands. Never read by the Isolated tier or the network
402 /// namespace. Read from the person's own policy alone: a repository policy
403 /// or a pack has no `sandbox:`.
404 #[serde(default, skip_serializing_if = "ProjectTop::is_protected")]
405 pub project_top: ProjectTop,
406 /// What `openmoat run` does when a file of the project would turn the
407 /// agent's OpenMoat hook off as the session starts (ADR-098): `refuse`
408 /// (absent) does not start the agent; `start` starts it anyway, says so
409 /// and records it. Read from the person's own policy alone: a repository
410 /// policy or a pack has no `sandbox:`.
411 #[serde(default, skip_serializing_if = "ProjectHookOff::is_refuse")]
412 pub project_hook_off: ProjectHookOff,
413}
414
415/// `sandbox.project_hook_off` (ADR-098).
416#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
417#[serde(rename_all = "lowercase")]
418pub enum ProjectHookOff {
419 /// The agent does not start.
420 #[default]
421 Refuse,
422 /// The agent starts without OpenMoat's hook; the run says so and records it.
423 Start,
424}
425
426impl ProjectHookOff {
427 /// Whether this is the default, [`ProjectHookOff::Refuse`].
428 #[must_use]
429 pub fn is_refuse(&self) -> bool {
430 *self == Self::Refuse
431 }
432}
433
434/// `sandbox.project_top` (ADR-090).
435#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
436#[serde(rename_all = "lowercase")]
437pub enum ProjectTop {
438 /// Granted entry by entry: the policy's denies at the top hold.
439 #[default]
440 Protected,
441 /// Granted whole: the top is writable, and `.env` and `.git/hooks` there
442 /// are open to the agent's commands.
443 Writable,
444}
445
446impl ProjectTop {
447 /// Whether this is the default, [`ProjectTop::Protected`].
448 #[must_use]
449 pub fn is_protected(&self) -> bool {
450 *self == Self::Protected
451 }
452}
453
454/// The `mcp:` section (ADR-032).
455#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
456#[serde(deny_unknown_fields)]
457pub struct McpSettings {
458 /// Pin every tool `moat mcp proxy` sees from a server it has no pins for,
459 /// as it is, instead of holding them until `moat mcp accept`. Off by
460 /// default: a server that is malicious on first contact would get its
461 /// tool descriptions pinned as good.
462 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
463 pub trust_first_sight: bool,
464 /// How an MCP call that only opens or reads one web page is decided
465 /// (ADR-047): `fetch` (absent) as a `fetch` of its host, like `WebFetch`;
466 /// `net` as a `net` connection, which the default policy denies for
467 /// unlisted hosts.
468 #[serde(default, skip_serializing_if = "Option::is_none")]
469 pub browser_open: Option<BrowserOpen>,
470 /// MCP servers, by the name `openmoat mcp proxy --server` gives them,
471 /// whose data flows are trusted (ADR-058): text such a server returned may
472 /// reach another server's tool that writes or sends, and a call to such a
473 /// server may carry another server's text, without a `mcp-cross-server`
474 /// review.
475 #[serde(default, skip_serializing_if = "Vec::is_empty")]
476 pub flow_trusted: Vec<String>,
477}
478
479/// `mcp.browser_open`: the kind a read-only page open of an MCP tool is decided as.
480#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
481#[serde(rename_all = "lowercase")]
482pub enum BrowserOpen {
483 /// A `fetch` of the page's host (the default).
484 Fetch,
485 /// A `net` connection to the page's host, as any other MCP URL argument.
486 Net,
487}
488
489/// `unattended:`: what a `defer` becomes in an agent mode that runs calls
490/// with no person asked (auto-approve, YOLO, headless; ADR-102).
491#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
492#[serde(rename_all = "lowercase")]
493pub enum Unattended {
494 /// The agent decides it, as everywhere else (ADR-025): in such a mode it
495 /// runs. The default.
496 #[default]
497 Defer,
498 /// OpenMoat holds it for review, and a review there is answered as a deny
499 /// that says how to approve it (or sent to the approvals channel).
500 Review,
501}
502
503/// The release age `moat run` requires of new package versions when the policy
504/// does not say (ADR-030).
505pub const DEFAULT_PACKAGE_MIN_RELEASE_AGE_DAYS: u16 = 7;
506
507impl Policy {
508 /// The days a package version must have been published before `moat run`
509 /// lets npm and uv install it; `0` is off.
510 #[must_use]
511 pub fn package_min_release_age_days(&self) -> u16 {
512 self.sandbox
513 .as_ref()
514 .and_then(|s| s.package_min_release_age_days)
515 .unwrap_or(DEFAULT_PACKAGE_MIN_RELEASE_AGE_DAYS)
516 }
517
518 /// What `openmoat run` without a network namespace grants at the project's
519 /// top (`sandbox.project_top`, ADR-090); [`ProjectTop::Protected`] unless
520 /// the person's own policy says otherwise.
521 #[must_use]
522 pub fn project_top(&self) -> ProjectTop {
523 self.sandbox
524 .as_ref()
525 .map(|s| s.project_top)
526 .unwrap_or_default()
527 }
528
529 /// What `openmoat run` does when a project's file would turn the agent's
530 /// hook off (`sandbox.project_hook_off`, ADR-098); [`ProjectHookOff::Refuse`]
531 /// unless the person's own policy says otherwise.
532 #[must_use]
533 pub fn project_hook_off(&self) -> ProjectHookOff {
534 self.sandbox
535 .as_ref()
536 .map(|s| s.project_hook_off)
537 .unwrap_or_default()
538 }
539
540 /// What a `defer` becomes in an agent mode that asks no person
541 /// (`unattended:`, ADR-102): `defer` unless the policy says `review`.
542 #[must_use]
543 pub fn unattended(&self) -> Unattended {
544 self.unattended.unwrap_or_default()
545 }
546
547 /// Whether `moat mcp proxy` pins a new server's tools without a person
548 /// accepting them (`mcp.trust_first_sight`, ADR-032).
549 #[must_use]
550 pub fn trust_mcp_first_sight(&self) -> bool {
551 self.mcp.as_ref().is_some_and(|m| m.trust_first_sight)
552 }
553
554 /// Whether an MCP call that only opens a web page is decided as a `fetch`
555 /// (`mcp.browser_open`, ADR-047): yes unless the policy says `net`.
556 #[must_use]
557 pub fn browser_open_is_fetch(&self) -> bool {
558 self.mcp.as_ref().and_then(|m| m.browser_open) != Some(BrowserOpen::Net)
559 }
560
561 /// The MCP servers whose data flows need no `mcp-cross-server` review
562 /// (`mcp.flow_trusted`, ADR-058).
563 #[must_use]
564 pub fn mcp_flow_trusted(&self) -> &[String] {
565 self.mcp.as_ref().map_or(&[], |m| m.flow_trusted.as_slice())
566 }
567}
568
569fn default_verdict() -> Defaults {
570 Defaults::All(Verdict::Review)
571}
572
573impl Policy {
574 /// Parse and lint a policy document. Pure: takes the YAML text.
575 pub fn parse(yaml: &str) -> Result<Self, PolicyError> {
576 schema::check(yaml)?;
577 let old_names = old_names::find(yaml)?;
578 let mut policy: Self = crate::yaml::from_str(yaml).map_err(PolicyError::Parse)?;
579 policy.old_names = old_names;
580 policy.lint()?;
581 Ok(policy)
582 }
583
584 /// Structural validation independent of any environment: [`Self::lint_structure`]
585 /// and every pattern's syntax ([`RuleGroup::check_patterns`]).
586 pub fn lint(&self) -> Result<(), PolicyError> {
587 self.lint_structure()?;
588 self.groups().try_for_each(RuleGroup::check_patterns)
589 }
590
591 /// [`Self::lint`] without parsing each pattern again, for a policy that
592 /// gained rule groups after a full lint, such as a merge of rules each
593 /// checked when they were read (a repository policy, a pack, `openmoat allow`
594 /// rules): the new groups' patterns are checked with
595 /// [`RuleGroup::check_patterns`], and nothing else needs reparsing. Parsing
596 /// every pattern costs more than the rest of the lint together, and
597 /// [`crate::CompiledPolicy::compile`] reports a bad one in any case.
598 pub fn lint_structure(&self) -> Result<(), PolicyError> {
599 if self.version != SUPPORTED_VERSION {
600 return Err(PolicyError::Version {
601 found: self.version,
602 supported: SUPPORTED_VERSION,
603 });
604 }
605 let mut ids = BTreeSet::new();
606 for group in self.groups() {
607 if group.id.trim().is_empty() {
608 return Err(PolicyError::Rule {
609 rule: "<unnamed>".into(),
610 problem: "missing id".into(),
611 });
612 }
613 if !ids.insert(group.id.clone()) {
614 return Err(PolicyError::DuplicateId(group.id.clone()));
615 }
616 if group.is_empty() {
617 return Err(PolicyError::EmptyRule(group.id.clone()));
618 }
619 text::check(group)?;
620 }
621 hook_only::check(self)?;
622 for (name, paths) in &self.executables {
623 if paths.is_empty() {
624 return Err(PolicyError::Rule {
625 rule: format!("executables.{name}"),
626 problem: "no paths listed".into(),
627 });
628 }
629 if let Some(bad) = paths.iter().find(|p| !crate::paths::is_absolute(p)) {
630 return Err(PolicyError::Rule {
631 rule: format!("executables.{name}"),
632 problem: format!("`{bad}` is not an absolute path"),
633 });
634 }
635 }
636 for root in self.sandbox.iter().flat_map(|s| &s.read_roots) {
637 lint_read_root(root)?;
638 }
639 for name in self.sandbox.iter().flat_map(|s| &s.env_allow) {
640 if let Some(problem) = env_name_problem(name) {
641 return Err(PolicyError::Rule {
642 rule: "sandbox.env_allow".to_owned(),
643 problem: format!("`{name}` {problem}"),
644 });
645 }
646 }
647 taint::check(self.taint.as_ref())?;
648 staging::check(self.staging.as_ref())?;
649 crate::diffscan::check(self.check_diff.as_ref())?;
650 require::check(self.require.as_ref())?;
651 for (_, added) in &self.require_added {
652 require::check(Some(added))?;
653 }
654 secret::check(&self.secrets)?;
655 crate::requests::check(&self.requests)
656 }
657
658 /// What `openmoat proxy` does with a connection to a `requests:` host it
659 /// cannot terminate (`requests_untrusted:`): refuse it unless the policy
660 /// says `relay`.
661 #[must_use]
662 pub fn requests_untrusted(&self) -> crate::requests::Untrusted {
663 self.requests_untrusted.unwrap_or_default()
664 }
665
666 /// Every rule group, in the order the engine tries the lists.
667 fn groups(&self) -> impl Iterator<Item = &RuleGroup> {
668 self.deny
669 .iter()
670 .chain(&self.repo_review)
671 .chain(&self.allow)
672 .chain(&self.review)
673 .chain(&self.defer)
674 }
675
676 /// Number of rule groups in `deny`, `allow` and `review`.
677 #[must_use]
678 pub fn rule_count(&self) -> (usize, usize, usize) {
679 (self.deny.len(), self.allow.len(), self.review.len())
680 }
681}
682
683/// An OS layer takes a read root literally, and a root that is the disk or the
684/// home directory would undo every default deny.
685fn lint_read_root(root: &str) -> Result<(), PolicyError> {
686 let trimmed = root.trim_end_matches(['/', '\\']);
687 let problem = if !(crate::paths::is_absolute(root) || root.starts_with("~/")) {
688 "must be absolute or start with `~/`"
689 } else if root.contains(['*', '?', '[', ']', '{', '}', '!', '$']) {
690 "must be a plain path, not a glob or a variable"
691 } else if root.split(['/', '\\']).any(|s| s == "." || s == "..") {
692 "must not contain `.` or `..` segments"
693 } else if trimmed == "~" {
694 "must not be the home directory"
695 } else if trimmed.is_empty() || (trimmed.len() == 2 && trimmed.ends_with(':')) {
696 "must not be a filesystem root"
697 } else {
698 return Ok(());
699 };
700 Err(PolicyError::Rule {
701 rule: "sandbox.read_roots".to_owned(),
702 problem: format!("`{root}` {problem}"),
703 })
704}
705
706fn rule_err(rule: &str, e: &PolicyError) -> PolicyError {
707 PolicyError::Rule {
708 rule: rule.to_owned(),
709 problem: e.to_string(),
710 }
711}
712
713#[cfg(test)]
714mod tests;