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, and whether file provenance
3//! (ADR-029) is on. The engine applies the list in `engine/taint.rs`; the CLI
4//! keeps provenance in the audit log.
5
6use serde::{Deserialize, Serialize};
7
8use crate::pattern::GlobPattern;
9use crate::policy::PolicyError;
10
11/// Files whose change runs code or steers the agent later, beyond the edit
12/// itself: CI, git hooks, editor tasks, the build and test definitions of every
13/// ecosystem whose commands the default policy runs, and agent instructions and
14/// settings. Writing them is ordinary work, until the session has read content an
15/// attacker may control. Source and test files, including test-runner configs
16/// written in JavaScript (`jest.config.js`), are not listed: they are code the run
17/// executes like any other file, and the command that runs them is named in a
18/// listed file (`package.json`).
19const PROTECTED_WRITES: [&str; 108] = [
20    "**/.github/workflows/**",
21    "**/.gitlab-ci.yml",
22    "**/.circleci/**",
23    "**/azure-pipelines.yml",
24    "**/Jenkinsfile",
25    "**/.buildkite/**",
26    "**/.husky/**",
27    "**/.githooks/**",
28    "**/.pre-commit-config.yaml",
29    "**/lefthook.yml",
30    "**/.lefthook.yml",
31    "**/.vscode/**",
32    // JavaScript: scripts, and package-manager settings that pick the script shell
33    "**/package.json",
34    "**/.npmrc",
35    "**/.yarnrc",
36    "**/.yarnrc.yml",
37    "**/pnpm-workspace.yaml",
38    // make, just, task
39    "**/Makefile",
40    "**/makefile",
41    "**/GNUmakefile",
42    "**/*.mk",
43    "**/justfile",
44    "**/Justfile",
45    "**/.justfile",
46    "**/Taskfile.yml",
47    "**/Taskfile.yaml",
48    // Rust: build scripts, `[build]`/`runner` settings
49    "**/build.rs",
50    "**/Cargo.toml",
51    "**/.cargo/config",
52    "**/.cargo/config.toml",
53    // Go: a `toolchain` line downloads and runs another Go
54    "**/go.mod",
55    "**/go.work",
56    // CMake
57    "**/CMakeLists.txt",
58    "**/*.cmake",
59    "**/CMakePresets.json",
60    "**/CMakeUserPresets.json",
61    // Maven
62    "**/pom.xml",
63    "**/.mvn/**",
64    "**/mvnw",
65    "**/mvnw.cmd",
66    // Gradle
67    "**/*.gradle",
68    "**/*.gradle.kts",
69    "**/gradle.properties",
70    "**/gradlew",
71    "**/gradlew.bat",
72    "**/gradle/wrapper/**",
73    // .NET: projects and the MSBuild files they import
74    "**/*.csproj",
75    "**/*.fsproj",
76    "**/*.vbproj",
77    "**/*.props",
78    "**/*.targets",
79    "**/global.json",
80    "**/NuGet.config",
81    "**/nuget.config",
82    // Ruby
83    "**/Rakefile",
84    "**/*.rake",
85    "**/Gemfile",
86    "**/*.gemspec",
87    "**/.rspec",
88    // PHP
89    "**/composer.json",
90    "**/artisan",
91    "**/phpunit.xml",
92    "**/phpunit.xml.dist",
93    // Python: pytest loads `conftest.py` and its config before any test
94    "**/conftest.py",
95    "**/pytest.ini",
96    "**/pyproject.toml",
97    "**/setup.py",
98    "**/setup.cfg",
99    "**/tox.ini",
100    "**/noxfile.py",
101    // containers
102    "**/Dockerfile",
103    "**/docker-compose*.yml",
104    "**/docker-compose*.yaml",
105    "**/compose*.yml",
106    "**/compose*.yaml",
107    // agents
108    "**/CLAUDE.md",
109    "**/AGENTS.md",
110    "**/.claude/**",
111    "**/.claude.json",
112    "**/.codex/**",
113    "**/.cursor/**",
114    "**/.cursorrules",
115    "**/.mcp.json",
116    // generated:taint from each host spec's `protect.taint` (openmoat-hosts `tests/protect.rs`)
117    // OpenClaw: its configuration, OpenMoat's plugin and the plugin directories the
118    // Gateway loads; not the whole state directory, whose workspace is ordinary work
119    "**/.openclaw",
120    "**/.openclaw/openclaw.json",
121    "**/.openclaw/openmoat",
122    "**/.openclaw/openmoat/**",
123    "**/.openclaw/extensions/**",
124    // the database where the Gateway keeps cron jobs and exec approvals
125    "**/.openclaw/state/**",
126    // GitHub Copilot CLI: its hooks, settings, MCP servers, plugins and custom
127    // agents, not its session folders; a repository's hooks, settings and
128    // instructions
129    "**/.copilot",
130    "**/.copilot/hooks",
131    "**/.copilot/hooks/**",
132    "**/.copilot/settings.json",
133    "**/.copilot/config.json",
134    "**/.copilot/mcp-config.json",
135    "**/.copilot/installed-plugins/**",
136    "**/.copilot/agents/**",
137    "**/.github/hooks/**",
138    "**/.github/mcp.json",
139    "**/.github/agents/**",
140    "**/.github/copilot/**",
141    "**/.github/copilot-instructions.md",
142    // pi: its agent directory (extensions, settings, trust decisions) and a
143    // project's `.pi` (extensions, settings, MCP servers, system prompt)
144    "**/.pi",
145    "**/.pi/**",
146    // Gemini CLI: its settings, extensions and the memory file it loads into
147    // every session
148    "**/GEMINI.md",
149    "**/.gemini",
150    "**/.gemini/**",
151    // /generated
152    // OpenMoat's own state (`kernel-self` denies it outright)
153    "**/.moat/**",
154];
155
156/// The `taint:` section. Absent in policies written before it existed.
157#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
158#[serde(deny_unknown_fields)]
159pub struct TaintSettings {
160    /// Path globs a write to asks once the session read untrusted content, in
161    /// addition to the built-in list, which a policy cannot shorten. No `!`
162    /// exclusions, for the same reason.
163    #[serde(default)]
164    pub protected_writes: Vec<String>,
165    /// File provenance (ADR-029): a file a session wrote after reading
166    /// untrusted content taints the sessions that later read or run it.
167    /// Absent means on; `false` turns it off.
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub provenance: Option<bool>,
170}
171
172impl TaintSettings {
173    /// Whether file provenance is on under `settings` (the policy's `taint:`
174    /// section, if any). On unless the section says `provenance: false`.
175    #[must_use]
176    pub fn provenance_on(settings: Option<&Self>) -> bool {
177        settings.and_then(|s| s.provenance).unwrap_or(true)
178    }
179}
180
181/// The built-in protected paths followed by the ones `settings` adds.
182pub(crate) fn protected_writes(settings: Option<&TaintSettings>) -> impl Iterator<Item = &str> {
183    PROTECTED_WRITES.into_iter().chain(
184        settings
185            .into_iter()
186            .flat_map(|s| s.protected_writes.iter().map(String::as_str)),
187    )
188}
189
190/// Each added path is a glob that compiles and is not an exclusion, which
191/// would take a built-in path out of protection.
192pub(crate) fn check(settings: Option<&TaintSettings>) -> Result<(), PolicyError> {
193    let problem = |problem: String| PolicyError::Rule {
194        rule: "taint.protected_writes".to_owned(),
195        problem,
196    };
197    for p in settings.iter().flat_map(|s| &s.protected_writes) {
198        if p.trim_start().starts_with('!') {
199            return Err(problem(format!(
200                "`{p}` is an exclusion; the list can only add paths"
201            )));
202        }
203        GlobPattern::compile(p, false).map_err(|e| problem(e.to_string()))?;
204    }
205    Ok(())
206}
207
208#[cfg(test)]
209mod tests {
210    use crate::policy::{Policy, PolicyError};
211
212    #[test]
213    fn protected_writes_must_be_plain_globs() {
214        let ok = "version: 1\ntaint:\n  protected_writes: ['**/deploy/**', '${project}/run.sh']\n";
215        assert_eq!(
216            Policy::parse(ok)
217                .unwrap()
218                .taint
219                .unwrap()
220                .protected_writes
221                .len(),
222            2
223        );
224        assert!(Policy::parse("version: 1\ntaint: {}\n").is_ok());
225        for bad in ["'**/[x'", "'!**/package.json'", "''"] {
226            let yaml = format!("version: 1\ntaint:\n  protected_writes: [{bad}]\n");
227            assert!(
228                matches!(Policy::parse(&yaml), Err(PolicyError::Rule { rule, .. }) if rule == "taint.protected_writes"),
229                "{bad} must be rejected"
230            );
231        }
232        assert!(Policy::parse("version: 1\ntaint: { bogus: [] }\n").is_err());
233    }
234
235    #[test]
236    fn provenance_is_on_unless_the_policy_turns_it_off() {
237        use super::TaintSettings;
238        let on =
239            |yaml: &str| TaintSettings::provenance_on(Policy::parse(yaml).unwrap().taint.as_ref());
240        assert!(on("version: 1\n"));
241        assert!(on("version: 1\ntaint: {}\n"));
242        assert!(on("version: 1\ntaint: { provenance: true }\n"));
243        assert!(!on("version: 1\ntaint: { provenance: false }\n"));
244        assert!(Policy::parse("version: 1\ntaint: { provenance: maybe }\n").is_err());
245    }
246
247    /// A path a `fs.write` pattern of the default policy names: `~` as a home,
248    /// `**/` as a project, a trailing `/**` as a file below, `*` as a word.
249    fn sample(pattern: &str) -> String {
250        let path = pattern
251            .replacen('~', "/home/u", 1)
252            .replacen("**/", "/home/u/work/repo/", 1);
253        let path = match path.strip_suffix("/**") {
254            Some(dir) => format!("{dir}/x"),
255            None => path,
256        };
257        path.replace('*', "v1")
258    }
259
260    /// One list of "files that run later": every file `runs-later` asks for and
261    /// every OpenMoat or host config file `kernel-self` denies is also a write
262    /// session taint protects. (`sandbox/patterns.rs` `RUNS_LATER` is checked
263    /// against `runs-later` in the CLI.)
264    #[test]
265    fn protected_writes_cover_runs_later_and_the_kernel_config_files() {
266        let policy = Policy::parse(crate::DEFAULT_POLICY).unwrap();
267        let protected: Vec<_> = super::PROTECTED_WRITES
268            .iter()
269            .map(|p| crate::pattern::GlobPattern::compile(p, false).unwrap())
270            .collect();
271        let rule = |groups: &[crate::RuleGroup], id: &str| {
272            groups.iter().find(|g| g.id == id).unwrap().fs_write.clone()
273        };
274        let mut files = rule(&policy.ask, "runs-later");
275        // the binary is not a file that runs later as configuration does
276        files.extend(rule(&policy.deny, "kernel-self").into_iter().filter(|p| {
277            !["/bin/moat", "apps/moat", "/bin/openmoat", "apps/openmoat"]
278                .iter()
279                .any(|binary| p.contains(binary))
280        }));
281        assert!(files.len() > 30, "{files:?}");
282        for pattern in &files {
283            let path = sample(pattern);
284            assert!(
285                protected.iter().any(|g| g.is_match(&path)),
286                "`{pattern}` ({path}) is not in PROTECTED_WRITES"
287            );
288        }
289    }
290}