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