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    // OpenClaw: its configuration, OpenMoat's plugin and the plugin directories the
117    // Gateway loads; not the whole state directory, whose workspace is ordinary work
118    "**/.openclaw",
119    "**/.openclaw/openclaw.json",
120    "**/.openclaw/openmoat",
121    "**/.openclaw/openmoat/**",
122    "**/.openclaw/extensions/**",
123    // the database where the Gateway keeps cron jobs and exec approvals
124    "**/.openclaw/state/**",
125    // GitHub Copilot CLI: its hooks, settings, MCP servers, plugins and custom
126    // agents, not its session folders; a repository's hooks, settings and
127    // instructions
128    "**/.copilot",
129    "**/.copilot/hooks",
130    "**/.copilot/hooks/**",
131    "**/.copilot/settings.json",
132    "**/.copilot/config.json",
133    "**/.copilot/mcp-config.json",
134    "**/.copilot/installed-plugins/**",
135    "**/.copilot/agents/**",
136    "**/.github/hooks/**",
137    "**/.github/mcp.json",
138    "**/.github/agents/**",
139    "**/.github/copilot/**",
140    "**/.github/copilot-instructions.md",
141    // pi: its agent directory (extensions, settings, trust decisions) and a
142    // project's `.pi` (extensions, settings, MCP servers, system prompt)
143    "**/.pi",
144    "**/.pi/**",
145    // Gemini CLI: its settings, extensions and the memory file it loads into
146    // every session
147    "**/GEMINI.md",
148    "**/.gemini",
149    "**/.gemini/**",
150    // OpenMoat's own state (`kernel-self` denies it outright)
151    "**/.moat/**",
152];
153
154/// The `taint:` section. Absent in policies written before it existed.
155#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
156#[serde(deny_unknown_fields)]
157pub struct TaintSettings {
158    /// Path globs a write to asks once the session read untrusted content, in
159    /// addition to the built-in list, which a policy cannot shorten. No `!`
160    /// exclusions, for the same reason.
161    #[serde(default)]
162    pub protected_writes: Vec<String>,
163    /// File provenance (ADR-029): a file a session wrote after reading
164    /// untrusted content taints the sessions that later read or run it.
165    /// Absent means on; `false` turns it off.
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub provenance: Option<bool>,
168}
169
170impl TaintSettings {
171    /// Whether file provenance is on under `settings` (the policy's `taint:`
172    /// section, if any). On unless the section says `provenance: false`.
173    #[must_use]
174    pub fn provenance_on(settings: Option<&Self>) -> bool {
175        settings.and_then(|s| s.provenance).unwrap_or(true)
176    }
177}
178
179/// The built-in protected paths followed by the ones `settings` adds.
180pub(crate) fn protected_writes(settings: Option<&TaintSettings>) -> impl Iterator<Item = &str> {
181    PROTECTED_WRITES.into_iter().chain(
182        settings
183            .into_iter()
184            .flat_map(|s| s.protected_writes.iter().map(String::as_str)),
185    )
186}
187
188/// Each added path is a glob that compiles and is not an exclusion, which
189/// would take a built-in path out of protection.
190pub(crate) fn check(settings: Option<&TaintSettings>) -> Result<(), PolicyError> {
191    let problem = |problem: String| PolicyError::Rule {
192        rule: "taint.protected_writes".to_owned(),
193        problem,
194    };
195    for p in settings.iter().flat_map(|s| &s.protected_writes) {
196        if p.trim_start().starts_with('!') {
197            return Err(problem(format!(
198                "`{p}` is an exclusion; the list can only add paths"
199            )));
200        }
201        GlobPattern::compile(p, false).map_err(|e| problem(e.to_string()))?;
202    }
203    Ok(())
204}
205
206#[cfg(test)]
207mod tests {
208    use crate::policy::{Policy, PolicyError};
209
210    #[test]
211    fn protected_writes_must_be_plain_globs() {
212        let ok = "version: 1\ntaint:\n  protected_writes: ['**/deploy/**', '${project}/run.sh']\n";
213        assert_eq!(
214            Policy::parse(ok)
215                .unwrap()
216                .taint
217                .unwrap()
218                .protected_writes
219                .len(),
220            2
221        );
222        assert!(Policy::parse("version: 1\ntaint: {}\n").is_ok());
223        for bad in ["'**/[x'", "'!**/package.json'", "''"] {
224            let yaml = format!("version: 1\ntaint:\n  protected_writes: [{bad}]\n");
225            assert!(
226                matches!(Policy::parse(&yaml), Err(PolicyError::Rule { rule, .. }) if rule == "taint.protected_writes"),
227                "{bad} must be rejected"
228            );
229        }
230        assert!(Policy::parse("version: 1\ntaint: { bogus: [] }\n").is_err());
231    }
232
233    #[test]
234    fn provenance_is_on_unless_the_policy_turns_it_off() {
235        use super::TaintSettings;
236        let on =
237            |yaml: &str| TaintSettings::provenance_on(Policy::parse(yaml).unwrap().taint.as_ref());
238        assert!(on("version: 1\n"));
239        assert!(on("version: 1\ntaint: {}\n"));
240        assert!(on("version: 1\ntaint: { provenance: true }\n"));
241        assert!(!on("version: 1\ntaint: { provenance: false }\n"));
242        assert!(Policy::parse("version: 1\ntaint: { provenance: maybe }\n").is_err());
243    }
244
245    /// A path a `fs.write` pattern of the default policy names: `~` as a home,
246    /// `**/` as a project, a trailing `/**` as a file below, `*` as a word.
247    fn sample(pattern: &str) -> String {
248        let path = pattern
249            .replacen('~', "/home/u", 1)
250            .replacen("**/", "/home/u/work/repo/", 1);
251        let path = match path.strip_suffix("/**") {
252            Some(dir) => format!("{dir}/x"),
253            None => path,
254        };
255        path.replace('*', "v1")
256    }
257
258    /// One list of "files that run later": every file `runs-later` asks for and
259    /// every OpenMoat or host config file `kernel-self` denies is also a write
260    /// session taint protects. (`sandbox/patterns.rs` `RUNS_LATER` is checked
261    /// against `runs-later` in the CLI.)
262    #[test]
263    fn protected_writes_cover_runs_later_and_the_kernel_config_files() {
264        let policy = Policy::parse(crate::DEFAULT_POLICY).unwrap();
265        let protected: Vec<_> = super::PROTECTED_WRITES
266            .iter()
267            .map(|p| crate::pattern::GlobPattern::compile(p, false).unwrap())
268            .collect();
269        let rule = |groups: &[crate::RuleGroup], id: &str| {
270            groups.iter().find(|g| g.id == id).unwrap().fs_write.clone()
271        };
272        let mut files = rule(&policy.ask, "runs-later");
273        // the binary is not a file that runs later as configuration does
274        files.extend(rule(&policy.deny, "kernel-self").into_iter().filter(|p| {
275            !["/bin/moat", "apps/moat", "/bin/openmoat", "apps/openmoat"]
276                .iter()
277                .any(|binary| p.contains(binary))
278        }));
279        assert!(files.len() > 30, "{files:?}");
280        for pattern in &files {
281            let path = sample(pattern);
282            assert!(
283                protected.iter().any(|g| g.is_match(&path)),
284                "`{pattern}` ({path}) is not in PROTECTED_WRITES"
285            );
286        }
287    }
288}