Skip to main content

eval_magic/sandbox/
policy.rs

1//! Write-boundary primitives.
2//!
3//! Stateless classifiers shared by the armed guard ([`super::decide`]) and
4//! `pipeline::detect-stray-writes`: which tools write, which Bash commands
5//! mutate state outside a sandbox, and whether a path falls under an allowed
6//! root. Tool names come from the adapters' cross-harness vocabulary union
7//! ([`all_tool_vocabulary`]), so no harness's tool naming is hardcoded here.
8
9use std::path::Path;
10use std::sync::LazyLock;
11
12use regex::Regex;
13use serde_json::Value;
14
15use crate::adapters::all_tool_vocabulary;
16
17/// True for a tool name that writes the filesystem with a single target path
18/// argument, in any harness's vocabulary.
19pub fn is_write_tool(tool_name: &str) -> bool {
20    all_tool_vocabulary()
21        .write_tools
22        .iter()
23        .any(|t| t == tool_name)
24}
25
26/// True for an apply_patch-style tool whose payload carries patch targets
27/// (extracted with [`apply_patch_paths`]), in any harness's vocabulary.
28pub fn is_patch_tool(tool_name: &str) -> bool {
29    all_tool_vocabulary()
30        .patch_tools
31        .iter()
32        .any(|t| t == tool_name)
33}
34
35/// True for a shell-execution tool carrying a `command` argument, in any
36/// harness's vocabulary.
37pub fn is_shell_tool(tool_name: &str) -> bool {
38    all_tool_vocabulary()
39        .shell_tools
40        .iter()
41        .any(|t| t == tool_name)
42}
43
44/// Bash command patterns that mutate state outside an eval's sandbox. Heuristics
45/// — Bash is too flexible to parse exactly. `detect-stray-writes` surfaces these
46/// as warnings; the opt-in guard denies them. Each is meaningful only when the
47/// command does not reference an allowed root (see [`classify_bash`]).
48///
49/// Compiled once. The patterns are known-valid, so a compile failure here is a
50/// programmer error and panics.
51static BASH_MUTATION_PATTERNS: LazyLock<Vec<(Regex, &'static str)>> = LazyLock::new(|| {
52    let config_dirs = crate::adapters::all_config_dir_names()
53        .iter()
54        .map(|d| regex::escape(d))
55        .collect::<Vec<_>>()
56        .join("|");
57    [
58        (
59            r"\b(npm|pnpm|yarn|bun)\s+(install|add|ci|i)\b".to_string(),
60            "package install/add",
61        ),
62        (r"\bpip3?\s+install\b".to_string(), "pip install"),
63        (r"\bsed\s+-i\b".to_string(), "in-place file edit (sed -i)"),
64        (
65            r"\bgit\s+(commit|add|push|checkout|reset|restore|merge|rebase)\b".to_string(),
66            "git mutation",
67        ),
68        (
69            r"\bgit\s+worktree\s+add\b".to_string(),
70            "git worktree add (working tree outside the sandbox)",
71        ),
72        // A create/copy/move/link verb whose operand is a path under any
73        // harness config dir (`adapters::all_config_dir_names`) — catches
74        // stray writes to a config dir that aren't a `>` redirect (caught
75        // below). Read-only verbs (`cat`, `ls`) aren't listed, so inspecting
76        // the dirs stays allowed.
77        (
78            format!(r"\b(cp|mv|mkdir|touch|ln|rsync|install)\b[^|;&\n]*({config_dirs})(/|\b)"),
79            "path under a harness config dir",
80        ),
81        // The same create verbs whose operand is a top-level `skills/` directory —
82        // catches a bare `skills/` left in the cwd. `skills-data` and other
83        // `skills`-prefixed names are excluded by the trailing `/`, whitespace, or
84        // end-of-string boundary.
85        (
86            r#"\b(cp|mv|mkdir|touch|ln|rsync)\b[^|;&\n]*[\s'"=/]\.{0,2}/?skills(/|\s|$)"#
87                .to_string(),
88            "creates a bare skills/ dir",
89        ),
90        (
91            r"(^|\s)(>>?|tee)\s".to_string(),
92            "output redirection to a file",
93        ),
94    ]
95    .into_iter()
96    .map(|(re, reason)| {
97        (
98            Regex::new(&re)
99                .unwrap_or_else(|e| panic!("bundled bash pattern {re:?} is invalid: {e}")),
100            reason,
101        )
102    })
103    .collect()
104});
105
106/// Pull the target path from a write tool's arguments (`file_path` →
107/// `notebook_path` → `path`). Returns `None` when the input is not an object or
108/// carries no string path.
109pub fn path_arg(args: &Value) -> Option<&str> {
110    let obj = args.as_object()?;
111    ["file_path", "notebook_path", "path"]
112        .iter()
113        .find_map(|k| obj.get(*k).and_then(Value::as_str))
114}
115
116/// Extract file paths from a Codex `apply_patch` hook payload. Codex can expose
117/// patch targets as a structured `files` list or as freeform patch text; collect
118/// both so the guard can deny unknown or out-of-bounds patches before they run.
119pub fn apply_patch_paths(args: &Value) -> Vec<String> {
120    let mut out = Vec::new();
121    let Some(obj) = args.as_object() else {
122        return out;
123    };
124
125    if let Some(files) = obj.get("files") {
126        collect_file_values(files, &mut out);
127    }
128
129    for key in ["patch", "input", "content"] {
130        if let Some(text) = obj.get(key).and_then(Value::as_str) {
131            collect_patch_header_paths(text, &mut out);
132        }
133    }
134
135    out.sort();
136    out.dedup();
137    out
138}
139
140fn collect_file_values(value: &Value, out: &mut Vec<String>) {
141    match value {
142        Value::String(path) => out.push(path.to_string()),
143        Value::Array(items) => {
144            for item in items {
145                collect_file_values(item, out);
146            }
147        }
148        Value::Object(obj) => {
149            for key in ["file_path", "path", "absolute_file_path", "move_path"] {
150                if let Some(path) = obj.get(key).and_then(Value::as_str) {
151                    out.push(path.to_string());
152                }
153            }
154        }
155        _ => {}
156    }
157}
158
159fn collect_patch_header_paths(text: &str, out: &mut Vec<String>) {
160    for line in text.lines() {
161        for prefix in [
162            "*** Add File: ",
163            "*** Update File: ",
164            "*** Delete File: ",
165            "*** Move to: ",
166        ] {
167            if let Some(path) = line.strip_prefix(prefix) {
168                let path = path.trim();
169                if !path.is_empty() {
170                    out.push(path.to_string());
171                }
172            }
173        }
174    }
175}
176
177/// Lexically absolutize a path: join onto `repo_root` if relative, then normalize.
178/// Mirrors node's `resolve()` — no symlink resolution or existence requirement.
179fn absolutize(target: &str, repo_root: &Path) -> std::path::PathBuf {
180    let joined = if Path::new(target).is_absolute() {
181        std::path::PathBuf::from(target)
182    } else {
183        repo_root.join(target)
184    };
185    // `std::path::absolute` normalizes `.`/`..` lexically without touching disk.
186    std::path::absolute(&joined).unwrap_or(joined)
187}
188
189/// True when `target` resolves to `dir` or a descendant of it. Relative `target`s
190/// resolve against `repo_root`. `Path::starts_with` matches whole path
191/// components, so `.eval-magic2` is correctly not under `.eval-magic`.
192pub fn is_under(target: &str, dir: &str, repo_root: &Path) -> bool {
193    let base = absolutize(dir, repo_root);
194    let abs = absolutize(target, repo_root);
195    abs.starts_with(&base)
196}
197
198/// True when `target` is under any of `dirs`.
199pub fn is_under_any(target: &str, dirs: &[String], repo_root: &Path) -> bool {
200    dirs.iter().any(|d| is_under(target, d, repo_root))
201}
202
203/// If a Bash command matches a mutation pattern and is not scoped to one of
204/// `allowed_roots`, return the human reason; otherwise `None`. A command is
205/// treated as scoped when it textually references an allowed root.
206pub fn classify_bash(command: &str, allowed_roots: &[String]) -> Option<&'static str> {
207    if command.is_empty() {
208        return None;
209    }
210    if allowed_roots.iter().any(|r| command.contains(r)) {
211        return None;
212    }
213    BASH_MUTATION_PATTERNS
214        .iter()
215        .find(|(re, _)| re.is_match(command))
216        .map(|(_, reason)| *reason)
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use serde_json::json;
223
224    const ROOTS: [&str; 2] = ["/work/.eval-magic", "/work/.claude/skills"];
225
226    fn roots() -> Vec<String> {
227        ROOTS.iter().map(|s| s.to_string()).collect()
228    }
229
230    #[test]
231    fn is_write_tool_matches_every_harness_write_tool() {
232        for t in ["Write", "Edit", "MultiEdit", "NotebookEdit", "file_change"] {
233            assert!(is_write_tool(t), "{t} should be a write tool");
234        }
235        for t in ["Read", "Bash", "Grep", "apply_patch", ""] {
236            assert!(!is_write_tool(t), "{t} should not be a write tool");
237        }
238    }
239
240    #[test]
241    fn is_patch_tool_matches_apply_patch_style_tools_only() {
242        assert!(is_patch_tool("apply_patch"));
243        for t in ["Write", "Bash", "file_change", ""] {
244            assert!(!is_patch_tool(t), "{t} should not be a patch tool");
245        }
246    }
247
248    #[test]
249    fn is_shell_tool_matches_every_harness_shell_tool() {
250        for t in ["Bash", "command_execution"] {
251            assert!(is_shell_tool(t), "{t} should be a shell tool");
252        }
253        for t in ["Write", "apply_patch", ""] {
254            assert!(!is_shell_tool(t), "{t} should not be a shell tool");
255        }
256    }
257
258    #[test]
259    fn path_arg_prefers_file_path_then_notebook_then_path() {
260        assert_eq!(path_arg(&json!({ "file_path": "/a" })), Some("/a"));
261        assert_eq!(path_arg(&json!({ "notebook_path": "/b" })), Some("/b"));
262        assert_eq!(path_arg(&json!({ "path": "/c" })), Some("/c"));
263        assert_eq!(
264            path_arg(&json!({ "file_path": "/a", "path": "/c" })),
265            Some("/a")
266        );
267        assert_eq!(path_arg(&json!({ "command": "ls" })), None);
268        assert_eq!(path_arg(&json!("not an object")), None);
269    }
270
271    #[test]
272    fn apply_patch_paths_collects_structured_and_freeform_targets() {
273        let paths = apply_patch_paths(&json!({
274            "files": [
275                "/tmp/out.md",
276                { "path": "src/lib.rs" },
277                { "move_path": "src/new.rs" }
278            ],
279            "patch": "*** Begin Patch\n*** Update File: docs/a.md\n*** Move to: docs/b.md\n*** End Patch\n"
280        }));
281        assert_eq!(
282            paths,
283            vec![
284                "/tmp/out.md".to_string(),
285                "docs/a.md".to_string(),
286                "docs/b.md".to_string(),
287                "src/lib.rs".to_string(),
288                "src/new.rs".to_string(),
289            ]
290        );
291    }
292
293    #[test]
294    fn is_under_matches_dir_and_descendants() {
295        let repo = Path::new("/work");
296        assert!(is_under("/work/.eval-magic", "/work/.eval-magic", repo));
297        assert!(is_under(
298            "/work/.eval-magic/x/out.md",
299            "/work/.eval-magic",
300            repo
301        ));
302        assert!(!is_under("/work/runner/run.ts", "/work/.eval-magic", repo));
303        // `.eval-magic2` is not under `.eval-magic` (separator boundary).
304        assert!(!is_under("/work/.eval-magic2/x", "/work/.eval-magic", repo));
305    }
306
307    #[test]
308    fn is_under_resolves_relative_targets_against_repo_root() {
309        let repo = Path::new("/work");
310        assert!(is_under(".eval-magic/x", "/work/.eval-magic", repo));
311    }
312
313    #[test]
314    fn is_under_any_checks_every_root() {
315        let repo = Path::new("/work");
316        assert!(is_under_any("/work/.claude/skills/s", &roots(), repo));
317        assert!(!is_under_any("/etc/passwd", &roots(), repo));
318    }
319
320    #[test]
321    fn classify_bash_flags_install_and_git_mutations() {
322        assert_eq!(
323            classify_bash("npm install left-pad", &roots()),
324            Some("package install/add")
325        );
326        assert_eq!(
327            classify_bash("git worktree add ../wt -b scratch", &roots()),
328            Some("git worktree add (working tree outside the sandbox)")
329        );
330        assert_eq!(
331            classify_bash("echo hi > out.log", &roots()),
332            Some("output redirection to a file")
333        );
334    }
335
336    #[test]
337    fn classify_bash_flags_creates_under_every_harness_config_dir_but_allows_reads() {
338        for dir in crate::adapters::all_config_dir_names() {
339            assert_eq!(
340                classify_bash(&format!("mkdir -p {dir}/x"), &[]),
341                Some("path under a harness config dir"),
342                "mkdir under {dir} should be flagged"
343            );
344            assert_eq!(
345                classify_bash(&format!("cp evil.json {dir}/hooks.json"), &[]),
346                Some("path under a harness config dir"),
347                "cp into {dir} should be flagged"
348            );
349            assert_eq!(
350                classify_bash(&format!("cat {dir}/settings.json"), &[]),
351                None,
352                "read of {dir} should stay allowed"
353            );
354            assert_eq!(classify_bash(&format!("ls {dir}"), &[]), None);
355        }
356    }
357
358    #[test]
359    fn classify_bash_allows_scoped_and_readonly_commands() {
360        // Textually references an allowed root → scoped → allowed.
361        assert_eq!(
362            classify_bash("echo hi > /work/.eval-magic/x/log", &roots()),
363            None
364        );
365        assert_eq!(classify_bash("ls -la /", &roots()), None);
366        assert_eq!(classify_bash("", &roots()), None);
367    }
368}