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}
353
354impl TaintSettings {
355    /// Whether file provenance is on under `settings` (the policy's `taint:`
356    /// section, if any). On unless the section says `provenance: false`.
357    #[must_use]
358    pub fn provenance_on(settings: Option<&Self>) -> bool {
359        settings.and_then(|s| s.provenance).unwrap_or(true)
360    }
361}
362
363/// The built-in protected paths followed by the ones `settings` adds.
364pub(crate) fn protected_writes(settings: Option<&TaintSettings>) -> impl Iterator<Item = &str> {
365    PROTECTED_WRITES.iter().copied().chain(
366        settings
367            .into_iter()
368            .flat_map(|s| s.protected_writes.iter().map(String::as_str)),
369    )
370}
371
372/// Whether the MCP tool `name` returns metadata (the built-in list, unless a
373/// configured server took its server's name, and the ones `settings` adds),
374/// whose result does not taint the session.
375pub(crate) fn is_metadata_tool(settings: Option<&TaintSettings>, name: &str) -> bool {
376    let defined =
377        |server: &str| settings.is_some_and(|s| s.defined_servers.iter().any(|d| d == server));
378    let built_in = name
379        .strip_prefix(MCP_PREFIX)
380        .and_then(|rest| rest.split_once("__"))
381        .is_some_and(|(server, tool)| {
382            BUILTIN_METADATA_TOOLS.contains(&(server, tool)) && !defined(server)
383        });
384    built_in || settings.is_some_and(|s| s.metadata_tools.iter().any(|tool| tool == name))
385}
386
387/// Each added path is a glob that compiles and is not an exclusion, which
388/// would take a built-in path out of protection; each added metadata tool is
389/// one MCP tool's full name.
390pub(crate) fn check(settings: Option<&TaintSettings>) -> Result<(), PolicyError> {
391    check_protected_writes(settings)?;
392    check_metadata_tools(settings)
393}
394
395fn check_protected_writes(settings: Option<&TaintSettings>) -> Result<(), PolicyError> {
396    let problem = |problem: String| PolicyError::Rule {
397        rule: "taint.protected_writes".to_owned(),
398        problem,
399    };
400    for p in settings.iter().flat_map(|s| &s.protected_writes) {
401        if p.trim_start().starts_with('!') {
402            return Err(problem(format!(
403                "`{p}` is an exclusion; the list can only add paths"
404            )));
405        }
406        GlobPattern::compile(p, false).map_err(|e| problem(e.to_string()))?;
407    }
408    Ok(())
409}
410
411/// Names are compared exactly, so a glob would match no tool: each entry is
412/// one full `mcp__<server>__<tool>` name.
413fn check_metadata_tools(settings: Option<&TaintSettings>) -> Result<(), PolicyError> {
414    let Some(bad) = settings
415        .iter()
416        .flat_map(|s| &s.metadata_tools)
417        .find(|name| !is_tool_name(name))
418    else {
419        return Ok(());
420    };
421    Err(PolicyError::Rule {
422        rule: "taint.metadata_tools".to_owned(),
423        problem: format!(
424            "`{bad}` is not one MCP tool's full name (`mcp__<server>__<tool>`, no wildcards)"
425        ),
426    })
427}
428
429/// Whether `name` is `mcp__<server>__<tool>` with both parts present and no
430/// space or glob character.
431fn is_tool_name(name: &str) -> bool {
432    let plain = !name
433        .chars()
434        .any(|c| c.is_whitespace() || matches!(c, '*' | '?' | '[' | ']' | '{' | '}' | '!'));
435    plain
436        && name
437            .strip_prefix(MCP_PREFIX)
438            .and_then(|rest| rest.split_once("__"))
439            .is_some_and(|(server, tool)| !server.is_empty() && !tool.is_empty())
440}
441
442#[cfg(test)]
443mod tests {
444    use crate::policy::{Policy, PolicyError};
445
446    #[test]
447    fn protected_writes_must_be_plain_globs() {
448        let ok = "version: 1\ntaint:\n  protected_writes: ['**/deploy/**', '${project}/run.sh']\n";
449        assert_eq!(
450            Policy::parse(ok)
451                .unwrap()
452                .taint
453                .unwrap()
454                .protected_writes
455                .len(),
456            2
457        );
458        assert!(Policy::parse("version: 1\ntaint: {}\n").is_ok());
459        for bad in ["'**/[x'", "'!**/package.json'", "''"] {
460            let yaml = format!("version: 1\ntaint:\n  protected_writes: [{bad}]\n");
461            assert!(
462                matches!(Policy::parse(&yaml), Err(PolicyError::Rule { rule, .. }) if rule == "taint.protected_writes"),
463                "{bad} must be rejected"
464            );
465        }
466        assert!(Policy::parse("version: 1\ntaint: { bogus: [] }\n").is_err());
467    }
468
469    #[test]
470    fn metadata_tools_are_full_mcp_tool_names() {
471        let yaml = |list: &str| format!("version: 1\ntaint:\n  metadata_tools: [{list}]\n");
472        let ok = Policy::parse(&yaml("mcp__tabs__list_tabs")).unwrap();
473        let settings = ok.taint.as_ref();
474        assert!(super::is_metadata_tool(settings, "mcp__tabs__list_tabs"));
475        assert!(super::is_metadata_tool(
476            settings,
477            "mcp__claude-in-chrome__tabs_context_mcp"
478        ));
479        assert!(!super::is_metadata_tool(settings, "mcp__tabs__read_tab"));
480        assert!(!super::is_metadata_tool(
481            None,
482            "mcp__claude-in-chrome__get_page_text"
483        ));
484        for bad in [
485            "'mcp__tabs__*'",
486            "list_tabs",
487            "'mcp__tabs__'",
488            "'mcp____x'",
489            "''",
490        ] {
491            assert!(
492                matches!(Policy::parse(&yaml(bad)), Err(PolicyError::Rule { rule, .. }) if rule == "taint.metadata_tools"),
493                "{bad} must be rejected"
494            );
495        }
496    }
497
498    /// The built-in list names only tools that list tabs, windows, browsers or
499    /// shortcuts: none of Claude in Chrome's page-content tools.
500    #[test]
501    fn built_in_metadata_tools_leave_page_content_tools_out() {
502        for tool in [
503            "get_page_text",
504            "read_page",
505            "find",
506            "navigate",
507            "javascript_tool",
508            "read_console_messages",
509            "read_network_requests",
510            "computer",
511            "gif_creator",
512            "upload_image",
513            "form_input",
514            "file_upload",
515            "shortcuts_execute",
516            "browser_batch",
517        ] {
518            let name = format!("mcp__claude-in-chrome__{tool}");
519            assert!(!super::is_metadata_tool(None, &name), "{name}");
520        }
521        assert_ne!(super::BUILTIN_METADATA_TOOLS.len(), 0);
522        for (server, tool) in super::BUILTIN_METADATA_TOOLS {
523            let name = format!("mcp__{server}__{tool}");
524            assert!(super::is_tool_name(&name), "{name}");
525            assert!(super::is_metadata_tool(None, &name), "{name}");
526            // a configured server that took the name is another program
527            let defined = super::TaintSettings {
528                defined_servers: vec![(*server).to_owned()],
529                ..super::TaintSettings::default()
530            };
531            assert!(!super::is_metadata_tool(Some(&defined), &name), "{name}");
532        }
533    }
534
535    /// The list's hand-written paths, outside the block generated from the
536    /// host specs (which `openmoat-hosts` `tests/protect.rs` checks against
537    /// them). A path removed or added by hand changes this count, so the
538    /// change is made on purpose, here too.
539    const HAND_WRITTEN: usize = 109;
540
541    #[test]
542    fn the_hand_written_protected_writes_keep_their_count() {
543        let source = include_str!("taint.rs");
544        let list = source
545            .split_once("const PROTECTED_WRITES")
546            .and_then(|(_, rest)| rest.split_once("\n];"))
547            .unwrap()
548            .0;
549        let (mut hand, mut generated, mut inside) = (0, 0, false);
550        for line in list.lines().map(str::trim) {
551            if line.starts_with("// generated:") {
552                inside = true;
553            } else if line.starts_with("// /generated") {
554                inside = false;
555            } else if line.starts_with('"') {
556                *(if inside { &mut generated } else { &mut hand }) += 1;
557            }
558        }
559        assert_eq!(
560            hand, HAND_WRITTEN,
561            "a hand-written path was added or removed"
562        );
563        assert_ne!(generated, 0, "the generated block is empty");
564        assert_eq!(hand + generated, super::PROTECTED_WRITES.len());
565    }
566
567    #[test]
568    fn provenance_is_on_unless_the_policy_turns_it_off() {
569        use super::TaintSettings;
570        let on =
571            |yaml: &str| TaintSettings::provenance_on(Policy::parse(yaml).unwrap().taint.as_ref());
572        assert!(on("version: 1\n"));
573        assert!(on("version: 1\ntaint: {}\n"));
574        assert!(on("version: 1\ntaint: { provenance: true }\n"));
575        assert!(!on("version: 1\ntaint: { provenance: false }\n"));
576        assert!(Policy::parse("version: 1\ntaint: { provenance: maybe }\n").is_err());
577    }
578
579    /// A path a `fs.write` pattern of the default policy names: `~` as a home,
580    /// `**/` as a project, a trailing `/**` as a file below, `*` as a word.
581    fn sample(pattern: &str) -> String {
582        let path = pattern
583            .replacen('~', "/home/u", 1)
584            .replacen("**/", "/home/u/work/repo/", 1);
585        let path = match path.strip_suffix("/**") {
586            Some(dir) => format!("{dir}/x"),
587            None => path,
588        };
589        path.replace('*', "v1")
590    }
591
592    /// One list of "files that run later": every file `runs-later` holds for review and
593    /// every OpenMoat or host config file `kernel-self` denies is also a write
594    /// session taint protects. (`sandbox/patterns.rs` `RUNS_LATER` is checked
595    /// against `runs-later` in the CLI.)
596    #[test]
597    fn protected_writes_cover_runs_later_and_the_kernel_config_files() {
598        let policy = Policy::parse(crate::DEFAULT_POLICY).unwrap();
599        let protected: Vec<_> = super::PROTECTED_WRITES
600            .iter()
601            .map(|p| crate::pattern::GlobPattern::compile(p, false).unwrap())
602            .collect();
603        let rule = |groups: &[crate::RuleGroup], id: &str| {
604            groups.iter().find(|g| g.id == id).unwrap().fs_write.clone()
605        };
606        let mut files = rule(&policy.review, "runs-later");
607        // the binary is not a file that runs later as configuration does
608        files.extend(
609            rule(&policy.deny, crate::rule_id::KERNEL_SELF)
610                .into_iter()
611                .filter(|p| {
612                    !["/bin/moat", "apps/moat", "/bin/openmoat", "apps/openmoat"]
613                        .iter()
614                        .any(|binary| p.contains(binary))
615                }),
616        );
617        assert!(files.len() > 30, "{files:?}");
618        for pattern in &files {
619            let path = sample(pattern);
620            assert!(
621                protected.iter().any(|g| g.is_match(&path)),
622                "`{pattern}` ({path}) is not in PROTECTED_WRITES"
623            );
624        }
625    }
626}