Skip to main content

openmoat_core/
taint.rs

1//! The policy's `taint:` section (ADR-020, docs/POLICY.md §4.1): what session
2//! taint protects beyond the built-in list, which MCP tools return metadata
3//! rather than content, and whether file provenance (ADR-029) is on. The
4//! engine applies the lists in `engine/taint.rs`; the CLI keeps provenance in
5//! the audit log.
6
7use serde::{Deserialize, Serialize};
8
9use crate::pattern::GlobPattern;
10use crate::policy::PolicyError;
11
12/// MCP tools, as `(server, tool)`, of a server an agent provides itself, which
13/// no MCP configuration file defines, whose result is the server's own
14/// bookkeeping, not content an attacker writes (a browser's tab, window and
15/// shortcut lists). Their results do not taint the session (ADR-057 amendment
16/// of 2026-11-07), and are still read for injected input: a host, path or
17/// command in a tab's title or URL is kept with the tool as its source. A tool
18/// counts only while no configured server takes its server's name
19/// ([`TaintSettings::defined_servers`], ADR-069). Generated from each host's
20/// spec, which names the sources.
21const BUILTIN_METADATA_TOOLS: &[(&str, &str)] = &[
22    // generated:metadata-tools from each host spec's `builtin_mcp` (openmoat-hosts `tests/protect.rs`)
23    // Claude Code: Claude in Chrome's tab, window, browser and shortcut lists (tab ids,
24    // titles, URLs), the browser's own bookkeeping
25    ("claude-in-chrome", "list_connected_browsers"),
26    ("claude-in-chrome", "resize_window"),
27    ("claude-in-chrome", "select_browser"),
28    ("claude-in-chrome", "shortcuts_list"),
29    ("claude-in-chrome", "switch_browser"),
30    ("claude-in-chrome", "tabs_close_mcp"),
31    ("claude-in-chrome", "tabs_context_mcp"),
32    ("claude-in-chrome", "tabs_create_mcp"),
33    // /generated
34];
35
36/// How every MCP tool's name starts (`mcp__<server>__<tool>`).
37const MCP_PREFIX: &str = "mcp__";
38
39/// Files whose change runs code or steers the agent later, beyond the edit
40/// itself: CI, git hooks, editor tasks, the build and test definitions of every
41/// ecosystem whose commands the default policy runs, and agent instructions and
42/// settings. Writing them is ordinary work, until the session has read content an
43/// attacker may control. Source and test files, including test-runner configs
44/// written in JavaScript (`jest.config.js`), are not listed: they are code the run
45/// executes like any other file, and the command that runs them is named in a
46/// listed file (`package.json`).
47const PROTECTED_WRITES: &[&str] = &[
48    "**/.github/workflows/**",
49    "**/.gitlab-ci.yml",
50    "**/.circleci/**",
51    "**/azure-pipelines.yml",
52    "**/Jenkinsfile",
53    "**/.buildkite/**",
54    "**/.husky/**",
55    // the folders a repository's `core.hooksPath` usually names (`runs-later`)
56    "**/.githooks/**",
57    "**/.git-hooks/**",
58    "**/githooks/**",
59    "**/git-hooks/**",
60    "**/.githooks",
61    "**/.git-hooks",
62    "**/githooks",
63    "**/git-hooks",
64    "**/.pre-commit-config.yaml",
65    "**/lefthook.yml",
66    "**/.lefthook.yml",
67    "**/.vscode/**",
68    // the editors' project configuration, which the editor runs (ADR-060)
69    "**/.vscode",
70    "**/*.code-workspace",
71    "**/.idea/**",
72    "**/.idea",
73    "**/*.run.xml",
74    // JavaScript: scripts, and package-manager settings that pick the script shell
75    "**/package.json",
76    "**/.npmrc",
77    "**/bunfig.toml",
78    "**/.yarnrc",
79    "**/.yarnrc.yml",
80    "**/pnpm-workspace.yaml",
81    // make, just, task
82    "**/Makefile",
83    "**/makefile",
84    "**/GNUmakefile",
85    "**/*.mk",
86    "**/justfile",
87    "**/Justfile",
88    "**/.justfile",
89    "**/Taskfile.yml",
90    "**/Taskfile.yaml",
91    // Rust: build scripts, `[build]`/`runner` settings
92    "**/build.rs",
93    "**/Cargo.toml",
94    "**/.cargo/config",
95    "**/.cargo/config.toml",
96    // Go: a `toolchain` line downloads and runs another Go
97    "**/go.mod",
98    "**/go.work",
99    // CMake
100    "**/CMakeLists.txt",
101    "**/*.cmake",
102    "**/CMakePresets.json",
103    "**/CMakeUserPresets.json",
104    // Maven
105    "**/pom.xml",
106    "**/.mvn/**",
107    "**/mvnw",
108    "**/mvnw.cmd",
109    // Gradle
110    "**/*.gradle",
111    "**/*.gradle.kts",
112    "**/gradle.properties",
113    "**/gradlew",
114    "**/gradlew.bat",
115    "**/gradle/wrapper/**",
116    // .NET: projects and the MSBuild files they import
117    "**/*.csproj",
118    "**/*.fsproj",
119    "**/*.vbproj",
120    "**/*.props",
121    "**/*.targets",
122    "**/global.json",
123    "**/NuGet.config",
124    "**/nuget.config",
125    // Ruby
126    "**/Rakefile",
127    "**/*.rake",
128    "**/Gemfile",
129    "**/*.gemspec",
130    "**/.rspec",
131    // PHP
132    "**/composer.json",
133    "**/artisan",
134    "**/phpunit.xml",
135    "**/phpunit.xml.dist",
136    // Python: pytest loads `conftest.py` and its config before any test
137    "**/conftest.py",
138    "**/pytest.ini",
139    "**/pyproject.toml",
140    "**/setup.py",
141    "**/setup.cfg",
142    "**/tox.ini",
143    "**/noxfile.py",
144    // what every Python start runs (`runs-later`)
145    "**/site-packages/*.pth",
146    "**/dist-packages/*.pth",
147    "**/sitecustomize.py",
148    "**/usercustomize.py",
149    "**/.venv/bin/**",
150    "**/venv/bin/**",
151    "**/.venv/bin",
152    "**/venv/bin",
153    "**/.devcontainer/**",
154    "**/.devcontainer",
155    "**/.devcontainer.json",
156    // containers
157    "**/Dockerfile",
158    "**/docker-compose*.yml",
159    "**/docker-compose*.yaml",
160    "**/compose*.yml",
161    "**/compose*.yaml",
162    // instruction files the next session of an agent obeys (ADR-057): the
163    // `AGENTS.md` several agents load, Windsurf's rules, and GitHub Copilot's
164    // path-scoped instructions
165    "**/AGENTS.md",
166    "**/.windsurfrules",
167    "**/.windsurf/rules/**",
168    "**/.github/instructions/**",
169    // OpenMoat's user services and their systemd drop-ins (`kernel-self`, ADR-094)
170    "**/.config/systemd/user/*moat-*",
171    "**/.config/systemd/user/*moat-*/**",
172    "/run/user/*/systemd/*/*moat-*",
173    "/run/user/*/systemd/*/*moat-*/**",
174    "**/Library/LaunchAgents/dev.openmoat.*",
175    // generated:taint from each host spec's `protect.taint` (openmoat-hosts `tests/protect.rs`)
176    // Claude Code: the memory file it loads into every session, its directory
177    // (settings, hooks, skills, agents, memory) and a project's, the person's MCP
178    // servers and a project's
179    "**/CLAUDE.md",
180    "**/.claude/**",
181    "**/.claude.json",
182    "**/.mcp.json",
183    // Codex: its directory (configuration, hooks, skills) and a project's
184    "**/.codex/**",
185    // Cursor: its directory (hooks, MCP servers, rules) and a project's, and the
186    // rules file it loads into every session
187    "**/.cursor/**",
188    "**/.cursorrules",
189    // Continue CLI: its configuration, whose MCP servers it starts
190    "**/.continue/config.yaml",
191    // OpenClaw: its configuration, OpenMoat's plugin and the plugin directories the
192    // Gateway loads; not the whole state directory, whose workspace is ordinary work
193    "**/.openclaw",
194    "**/.openclaw/openclaw.json",
195    "**/.openclaw/openmoat",
196    "**/.openclaw/openmoat/**",
197    "**/.openclaw/extensions/**",
198    // the database where the Gateway keeps cron jobs and exec approvals
199    "**/.openclaw/state/**",
200    // GitHub Copilot CLI: its hooks, settings, MCP servers, plugins and custom
201    // agents, not its session folders; a repository's hooks, settings and
202    // instructions
203    "**/.copilot",
204    "**/.copilot/hooks",
205    "**/.copilot/hooks/**",
206    "**/.copilot/settings.json",
207    "**/.copilot/config.json",
208    "**/.copilot/mcp-config.json",
209    "**/.copilot/installed-plugins/**",
210    "**/.copilot/agents/**",
211    "**/.github/hooks/**",
212    "**/.github/mcp.json",
213    "**/.github/agents/**",
214    "**/.github/copilot/**",
215    "**/.github/copilot-instructions.md",
216    // pi: its agent directory (extensions, settings, trust decisions) and a
217    // project's `.pi` (extensions, settings, MCP servers, system prompt)
218    "**/.pi",
219    "**/.pi/**",
220    // Gemini CLI: its settings, extensions and the memory file it loads into
221    // every session
222    "**/GEMINI.md",
223    "**/.gemini",
224    "**/.gemini/**",
225    // OpenCode: its configuration directory, a project's `.opencode` and
226    // `opencode.json[c]` (plugins, custom tools, commands, MCP servers, permission
227    // rules) and the npm plugins it caches
228    "**/.config/opencode",
229    "**/.config/opencode/**",
230    "**/.opencode",
231    "**/.opencode/**",
232    "**/opencode.json",
233    "**/opencode.jsonc",
234    "**/.cache/opencode/node_modules/**",
235    // Hermes Agent: the skills, cron jobs, memories and persona it loads into
236    // later sessions, and a project's `.hermes.md` and plugins
237    "~/.hermes/skills/**",
238    "~/.hermes/cron/**",
239    "~/.hermes/memories/**",
240    "~/.hermes/SOUL.md",
241    "**/.hermes.md",
242    "**/.hermes/**",
243    // Cline: its directory (settings, MCP servers, hooks, plugins), the
244    // rules, workflows and hooks in `Documents/Cline`, and a project's `.cline`
245    // and `.clinerules` (hooks, plugins, rules)
246    "**/.cline",
247    "**/.cline/**",
248    "**/Documents/Cline/**",
249    "**/.clinerules",
250    "**/.clinerules/**",
251    // goose: the hints it loads into every session, its configuration, saved
252    // recipes and plugin settings, and the plugins whose hooks it runs
253    "**/.goosehints",
254    "~/.config/goose",
255    "~/.config/goose/**",
256    "**/.config/goose/**",
257    "**/.agents/plugins",
258    "**/.agents/plugins/**",
259    // Antigravity CLI: its hook and MCP files, and the plugins it loads
260    "~/.gemini/config",
261    "~/.gemini/config/**",
262    "**/.agents/hooks.json",
263    "**/.agents/mcp_config.json",
264    // Qwen Code: its settings, extensions and the memory file it loads into
265    // every session
266    "**/QWEN.md",
267    "**/.qwen",
268    "**/.qwen/**",
269    // Crush: a project's configuration files, which add hooks and MCP servers, and
270    // its `crushrc` scripts; and its global configuration and data file, which
271    // `kernel-self` denies writing
272    "**/.config/crush",
273    "**/.config/crush/**",
274    "**/.local/share/crush/crush.json",
275    "**/crush.json",
276    "**/.crush.json",
277    "**/crushrc",
278    "**/.crushrc",
279    "**/.crush/**",
280    // Agent Skills, loaded by Codex, Cursor, GitHub Copilot CLI, pi, Gemini CLI,
281    // OpenCode, goose, Antigravity CLI, Crush:
282    // the shared `.agents/skills` folder and the folder above it
283    "**/.agents",
284    "**/.agents/skills",
285    "**/.agents/skills/**",
286    // Claude Code: OpenMoat's plugin as its marketplace installs it, and that
287    // marketplace's clone
288    "**/.claude/plugins/cache/crocodile-labs/openmoat",
289    "**/.claude/plugins/cache/crocodile-labs/openmoat/**",
290    "**/.claude/plugins/marketplaces/crocodile-labs",
291    "**/.claude/plugins/marketplaces/crocodile-labs/**",
292    // Cursor: OpenMoat's plugin, wherever below its plugins folder Cursor keeps it
293    "**/.cursor/plugins/**/openmoat",
294    "**/.cursor/plugins/**/openmoat/**",
295    // OpenClaw: OpenMoat's ClawHub package, below its state directory or in an npm
296    // folder
297    "**/.openclaw/**/openmoat-clawhub",
298    "**/.openclaw/**/openmoat-clawhub/**",
299    "**/node_modules/@openmoat/openclaw",
300    "**/node_modules/@openmoat/openclaw/**",
301    // GitHub Copilot CLI: OpenMoat's plugin, from a marketplace or straight from
302    // its repository
303    "**/.copilot/installed-plugins/*/openmoat",
304    "**/.copilot/installed-plugins/*/openmoat/**",
305    "**/.copilot/installed-plugins/_direct/*openmoat*",
306    "**/.copilot/installed-plugins/_direct/*openmoat*/**",
307    // pi: OpenMoat's package, in whichever npm folder holds it
308    "**/.pi/agent/**/@openmoat/pi",
309    "**/.pi/agent/**/@openmoat/pi/**",
310    "**/node_modules/@openmoat/pi",
311    "**/node_modules/@openmoat/pi/**",
312    // Gemini CLI: OpenMoat's extension
313    "**/.gemini/extensions/openmoat",
314    "**/.gemini/extensions/openmoat/**",
315    // OpenCode: OpenMoat's npm plugin, in whichever npm folder holds it
316    "**/node_modules/@openmoat/opencode",
317    "**/node_modules/@openmoat/opencode/**",
318    // /generated
319    // OpenMoat's own state (`kernel-self` denies it outright)
320    "**/.moat/**",
321];
322
323/// The `taint:` section. Absent in policies written before it existed.
324#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
325#[serde(deny_unknown_fields)]
326pub struct TaintSettings {
327    /// Path globs whose writes need review once the session read untrusted content, in
328    /// addition to the built-in list, which a policy cannot shorten. No `!`
329    /// exclusions, for the same reason.
330    #[serde(default)]
331    pub protected_writes: Vec<String>,
332    /// MCP tools, by full name (`mcp__<server>__<tool>`), whose result is the
333    /// server's own metadata rather than content an attacker writes, in
334    /// addition to the built-in list: their results do not taint the session,
335    /// and their output still feeds injected input (ADR-057).
336    #[serde(default, skip_serializing_if = "Vec::is_empty")]
337    pub metadata_tools: Vec<String>,
338    /// MCP servers, by name, that an agent's MCP configuration or OpenMoat's
339    /// pins define. The built-in metadata tools are those of servers an agent
340    /// provides itself; one defined here under such a name is not it, and
341    /// every tool of it taints the session.
342    /// The CLI adds the names it finds pinned; a policy may list more, which
343    /// can only make more results taint. `metadata_tools` still counts: a
344    /// person who lists a tool there trusts it by its full name.
345    #[serde(default, skip_serializing_if = "Vec::is_empty")]
346    pub defined_servers: Vec<String>,
347    /// File provenance (ADR-029): a file a session wrote after reading
348    /// untrusted content taints the sessions that later read or run it.
349    /// Absent means on; `false` turns it off.
350    #[serde(default, skip_serializing_if = "Option::is_none")]
351    pub provenance: Option<bool>,
352    /// Path globs whose reads count as private data for the lethal trifecta
353    /// and staging (ADR-113), in addition to the paths of the built-in private
354    /// rules (`secrets-paths`, `agent-credentials`, …), which a policy cannot
355    /// shorten. No `!` exclusions.
356    #[serde(default, skip_serializing_if = "Vec::is_empty")]
357    pub private_paths: Vec<String>,
358    /// What a call that can send data out gets once the session read private
359    /// data and untrusted content (ADR-113): `review` (absent, the default) or
360    /// `deny`. There is no value that turns it off.
361    #[serde(default, skip_serializing_if = "Option::is_none")]
362    pub trifecta: Option<TrifectaVerdict>,
363}
364
365/// The verdict of the lethal trifecta (`taint.trifecta`, ADR-113).
366#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
367#[serde(rename_all = "lowercase")]
368pub enum TrifectaVerdict {
369    /// A person reviews the call.
370    #[default]
371    Review,
372    /// The call is denied.
373    Deny,
374}
375
376impl TaintSettings {
377    /// The trifecta's verdict under `settings`: `review` unless it says `deny`.
378    #[must_use]
379    pub fn trifecta_under(settings: Option<&Self>) -> crate::verdict::Verdict {
380        match settings.and_then(|s| s.trifecta).unwrap_or_default() {
381            TrifectaVerdict::Review => crate::verdict::Verdict::Review,
382            TrifectaVerdict::Deny => crate::verdict::Verdict::Deny,
383        }
384    }
385
386    /// Whether file provenance is on under `settings` (the policy's `taint:`
387    /// section, if any). On unless the section says `provenance: false`.
388    #[must_use]
389    pub fn provenance_on(settings: Option<&Self>) -> bool {
390        settings.and_then(|s| s.provenance).unwrap_or(true)
391    }
392}
393
394/// The built-in protected paths followed by the ones `settings` adds.
395pub(crate) fn protected_writes(settings: Option<&TaintSettings>) -> impl Iterator<Item = &str> {
396    PROTECTED_WRITES.iter().copied().chain(
397        settings
398            .into_iter()
399            .flat_map(|s| s.protected_writes.iter().map(String::as_str)),
400    )
401}
402
403/// Whether the MCP tool `name` returns metadata (the built-in list, unless a
404/// configured server took its server's name, and the ones `settings` adds),
405/// whose result does not taint the session.
406pub(crate) fn is_metadata_tool(settings: Option<&TaintSettings>, name: &str) -> bool {
407    let defined =
408        |server: &str| settings.is_some_and(|s| s.defined_servers.iter().any(|d| d == server));
409    let built_in = name
410        .strip_prefix(MCP_PREFIX)
411        .and_then(|rest| rest.split_once("__"))
412        .is_some_and(|(server, tool)| {
413            BUILTIN_METADATA_TOOLS.contains(&(server, tool)) && !defined(server)
414        });
415    built_in || settings.is_some_and(|s| s.metadata_tools.iter().any(|tool| tool == name))
416}
417
418/// Each added path is a glob that compiles and is not an exclusion, which
419/// would take a built-in path out of protection; each added metadata tool is
420/// one MCP tool's full name.
421pub(crate) fn check(settings: Option<&TaintSettings>) -> Result<(), PolicyError> {
422    check_protected_writes(settings)?;
423    check_metadata_tools(settings)
424}
425
426fn check_protected_writes(settings: Option<&TaintSettings>) -> Result<(), PolicyError> {
427    check_globs(
428        "taint.protected_writes",
429        settings.iter().flat_map(|s| &s.protected_writes),
430    )?;
431    check_globs(
432        "taint.private_paths",
433        settings.iter().flat_map(|s| &s.private_paths),
434    )
435}
436
437/// Each of `globs` compiles and is not an exclusion.
438fn check_globs<'a>(rule: &str, globs: impl Iterator<Item = &'a String>) -> Result<(), PolicyError> {
439    let problem = |problem: String| PolicyError::Rule {
440        rule: rule.to_owned(),
441        problem,
442    };
443    for p in globs {
444        if p.trim_start().starts_with('!') {
445            return Err(problem(format!(
446                "`{p}` is an exclusion; the list can only add paths"
447            )));
448        }
449        GlobPattern::compile(p, false).map_err(|e| problem(e.to_string()))?;
450    }
451    Ok(())
452}
453
454/// Names are compared exactly, so a glob would match no tool: each entry is
455/// one full `mcp__<server>__<tool>` name.
456fn check_metadata_tools(settings: Option<&TaintSettings>) -> Result<(), PolicyError> {
457    let Some(bad) = settings
458        .iter()
459        .flat_map(|s| &s.metadata_tools)
460        .find(|name| !is_tool_name(name))
461    else {
462        return Ok(());
463    };
464    Err(PolicyError::Rule {
465        rule: "taint.metadata_tools".to_owned(),
466        problem: format!(
467            "`{bad}` is not one MCP tool's full name (`mcp__<server>__<tool>`, no wildcards)"
468        ),
469    })
470}
471
472/// Whether `name` is `mcp__<server>__<tool>` with both parts present and no
473/// space or glob character.
474fn is_tool_name(name: &str) -> bool {
475    let plain = !name
476        .chars()
477        .any(|c| c.is_whitespace() || matches!(c, '*' | '?' | '[' | ']' | '{' | '}' | '!'));
478    plain
479        && name
480            .strip_prefix(MCP_PREFIX)
481            .and_then(|rest| rest.split_once("__"))
482            .is_some_and(|(server, tool)| !server.is_empty() && !tool.is_empty())
483}
484
485#[cfg(test)]
486mod tests {
487    use crate::policy::{Policy, PolicyError};
488
489    #[test]
490    fn protected_writes_must_be_plain_globs() {
491        let ok = "version: 1\ntaint:\n  protected_writes: ['**/deploy/**', '${project}/run.sh']\n";
492        assert_eq!(
493            Policy::parse(ok)
494                .unwrap()
495                .taint
496                .unwrap()
497                .protected_writes
498                .len(),
499            2
500        );
501        assert!(Policy::parse("version: 1\ntaint: {}\n").is_ok());
502        for bad in ["'**/[x'", "'!**/package.json'", "''"] {
503            let yaml = format!("version: 1\ntaint:\n  protected_writes: [{bad}]\n");
504            assert!(
505                matches!(Policy::parse(&yaml), Err(PolicyError::Rule { rule, .. }) if rule == "taint.protected_writes"),
506                "{bad} must be rejected"
507            );
508        }
509        assert!(Policy::parse("version: 1\ntaint: { bogus: [] }\n").is_err());
510    }
511
512    #[test]
513    fn metadata_tools_are_full_mcp_tool_names() {
514        let yaml = |list: &str| format!("version: 1\ntaint:\n  metadata_tools: [{list}]\n");
515        let ok = Policy::parse(&yaml("mcp__tabs__list_tabs")).unwrap();
516        let settings = ok.taint.as_ref();
517        assert!(super::is_metadata_tool(settings, "mcp__tabs__list_tabs"));
518        assert!(super::is_metadata_tool(
519            settings,
520            "mcp__claude-in-chrome__tabs_context_mcp"
521        ));
522        assert!(!super::is_metadata_tool(settings, "mcp__tabs__read_tab"));
523        assert!(!super::is_metadata_tool(
524            None,
525            "mcp__claude-in-chrome__get_page_text"
526        ));
527        for bad in [
528            "'mcp__tabs__*'",
529            "list_tabs",
530            "'mcp__tabs__'",
531            "'mcp____x'",
532            "''",
533        ] {
534            assert!(
535                matches!(Policy::parse(&yaml(bad)), Err(PolicyError::Rule { rule, .. }) if rule == "taint.metadata_tools"),
536                "{bad} must be rejected"
537            );
538        }
539    }
540
541    /// The built-in list names only tools that list tabs, windows, browsers or
542    /// shortcuts: none of Claude in Chrome's page-content tools.
543    #[test]
544    fn built_in_metadata_tools_leave_page_content_tools_out() {
545        for tool in [
546            "get_page_text",
547            "read_page",
548            "find",
549            "navigate",
550            "javascript_tool",
551            "read_console_messages",
552            "read_network_requests",
553            "computer",
554            "gif_creator",
555            "upload_image",
556            "form_input",
557            "file_upload",
558            "shortcuts_execute",
559            "browser_batch",
560        ] {
561            let name = format!("mcp__claude-in-chrome__{tool}");
562            assert!(!super::is_metadata_tool(None, &name), "{name}");
563        }
564        assert_ne!(super::BUILTIN_METADATA_TOOLS.len(), 0);
565        for (server, tool) in super::BUILTIN_METADATA_TOOLS {
566            let name = format!("mcp__{server}__{tool}");
567            assert!(super::is_tool_name(&name), "{name}");
568            assert!(super::is_metadata_tool(None, &name), "{name}");
569            // a configured server that took the name is another program
570            let defined = super::TaintSettings {
571                defined_servers: vec![(*server).to_owned()],
572                ..super::TaintSettings::default()
573            };
574            assert!(!super::is_metadata_tool(Some(&defined), &name), "{name}");
575        }
576    }
577
578    /// The list's hand-written paths, outside the block generated from the
579    /// host specs (which `openmoat-hosts` `tests/protect.rs` checks against
580    /// them). A path removed or added by hand changes this count, so the
581    /// change is made on purpose, here too.
582    const HAND_WRITTEN: usize = 109;
583
584    #[test]
585    fn the_hand_written_protected_writes_keep_their_count() {
586        let source = include_str!("taint.rs");
587        let list = source
588            .split_once("const PROTECTED_WRITES")
589            .and_then(|(_, rest)| rest.split_once("\n];"))
590            .unwrap()
591            .0;
592        let (mut hand, mut generated, mut inside) = (0, 0, false);
593        for line in list.lines().map(str::trim) {
594            if line.starts_with("// generated:") {
595                inside = true;
596            } else if line.starts_with("// /generated") {
597                inside = false;
598            } else if line.starts_with('"') {
599                *(if inside { &mut generated } else { &mut hand }) += 1;
600            }
601        }
602        assert_eq!(
603            hand, HAND_WRITTEN,
604            "a hand-written path was added or removed"
605        );
606        assert_ne!(generated, 0, "the generated block is empty");
607        assert_eq!(hand + generated, super::PROTECTED_WRITES.len());
608    }
609
610    #[test]
611    fn provenance_is_on_unless_the_policy_turns_it_off() {
612        use super::TaintSettings;
613        let on =
614            |yaml: &str| TaintSettings::provenance_on(Policy::parse(yaml).unwrap().taint.as_ref());
615        assert!(on("version: 1\n"));
616        assert!(on("version: 1\ntaint: {}\n"));
617        assert!(on("version: 1\ntaint: { provenance: true }\n"));
618        assert!(!on("version: 1\ntaint: { provenance: false }\n"));
619        assert!(Policy::parse("version: 1\ntaint: { provenance: maybe }\n").is_err());
620    }
621
622    /// A path a `fs.write` pattern of the default policy names: `~` as a home,
623    /// `**/` as a project, a trailing `/**` as a file below, `*` as a word.
624    fn sample(pattern: &str) -> String {
625        let path = pattern
626            .replacen('~', "/home/u", 1)
627            .replacen("**/", "/home/u/work/repo/", 1);
628        let path = match path.strip_suffix("/**") {
629            Some(dir) => format!("{dir}/x"),
630            None => path,
631        };
632        path.replace('*', "v1")
633    }
634
635    /// One list of "files that run later": every file `runs-later` holds for review and
636    /// every OpenMoat or host config file `kernel-self` denies is also a write
637    /// session taint protects. (`sandbox/patterns.rs` `RUNS_LATER` is checked
638    /// against `runs-later` in the CLI.)
639    #[test]
640    fn protected_writes_cover_runs_later_and_the_kernel_config_files() {
641        let policy = Policy::parse(crate::DEFAULT_POLICY).unwrap();
642        let protected: Vec<_> = super::PROTECTED_WRITES
643            .iter()
644            .map(|p| crate::pattern::GlobPattern::compile(p, false).unwrap())
645            .collect();
646        let rule = |groups: &[crate::RuleGroup], id: &str| {
647            groups.iter().find(|g| g.id == id).unwrap().fs_write.clone()
648        };
649        let mut files = rule(&policy.review, "runs-later");
650        // the binary is not a file that runs later as configuration does
651        files.extend(
652            rule(&policy.deny, crate::rule_id::KERNEL_SELF)
653                .into_iter()
654                .filter(|p| {
655                    !["/bin/moat", "apps/moat", "/bin/openmoat", "apps/openmoat"]
656                        .iter()
657                        .any(|binary| p.contains(binary))
658                }),
659        );
660        assert!(files.len() > 30, "{files:?}");
661        for pattern in &files {
662            let path = sample(pattern);
663            assert!(
664                protected.iter().any(|g| g.is_match(&path)),
665                "`{pattern}` ({path}) is not in PROTECTED_WRITES"
666            );
667        }
668    }
669}