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