Skip to main content

safe_chains/
lib.rs

1// Generated test names keep the flag case they spell (`-D` and `-d` differ), so they opt out of non_snake_case.
2#[cfg(test)]
3macro_rules! safe {
4    ($($name:ident: $cmd:expr),* $(,)?) => {
5        $(#[test] #[allow(non_snake_case)] fn $name() { assert!(check($cmd), "expected safe: {}", $cmd); })*
6    };
7}
8
9#[cfg(test)]
10macro_rules! denied {
11    ($($name:ident: $cmd:expr),* $(,)?) => {
12        $(#[test] #[allow(non_snake_case)] fn $name() { assert!(!check($cmd), "expected denied: {}", $cmd); })*
13    };
14}
15
16#[cfg(test)]
17macro_rules! inert {
18    ($($name:ident: $cmd:expr),* $(,)?) => {
19        $(#[test] #[allow(non_snake_case)] fn $name() {
20            assert_eq!(
21                crate::command_verdict($cmd),
22                crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::Inert),
23                "expected Inert: {}", $cmd,
24            );
25        })*
26    };
27}
28
29#[cfg(test)]
30macro_rules! safe_read {
31    ($($name:ident: $cmd:expr),* $(,)?) => {
32        $(#[test] #[allow(non_snake_case)] fn $name() {
33            assert_eq!(
34                crate::command_verdict($cmd),
35                crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::SafeRead),
36                "expected SafeRead: {}", $cmd,
37            );
38        })*
39    };
40}
41
42#[cfg(test)]
43macro_rules! safe_write {
44    ($($name:ident: $cmd:expr),* $(,)?) => {
45        $(#[test] #[allow(non_snake_case)] fn $name() {
46            assert_eq!(
47                crate::command_verdict($cmd),
48                crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::SafeWrite),
49                "expected SafeWrite: {}", $cmd,
50            );
51        })*
52    };
53}
54
55pub mod allowlist;
56pub mod cli;
57#[cfg(test)]
58mod composition;
59pub mod cst;
60pub mod decisionlog;
61pub mod docs;
62pub mod engine;
63mod envvars;
64pub mod explain_fix;
65#[cfg(test)]
66mod handler_property_tests;
67mod handlers;
68pub mod mcp;
69pub mod netloc;
70#[cfg(test)]
71mod overreach_property_tests;
72pub mod parse;
73#[cfg(test)]
74mod path_placement_tests;
75pub mod pathctx;
76pub mod pathgate;
77pub mod policy;
78mod reach;
79pub mod refusal;
80pub mod registry;
81#[cfg(test)]
82mod substitution_property_tests;
83pub mod suggest;
84pub mod targets;
85pub mod userconfig;
86pub mod verdict;
87
88pub use reach::ReachReason;
89pub use verdict::{SafetyLevel, Verdict};
90
91/// The facet profile behind a verdict, rendered for `--explain`.
92///
93/// Answers the question the boolean cannot: not "is this allowed" but "on which axis was it
94/// refused". Empty when no resolver claims the command — that is the answer too, since it means the
95/// legacy classifier decided and there are no facets to show.
96pub fn facet_breakdown(command: &str) -> String {
97    // One simple command only. `shell_words` has no idea what `&&` means, so on a chain it hands
98    // back one flat token list and the resolver reads the SECOND command's arguments as flags of
99    // the first — `aws dynamodb scan --table-name t && rm -rf /` produced a single worst-case
100    // profile belonging to neither segment. A diagnostic that invents a capability set no resolver
101    // emitted is worse than silence, and `render()` above already breaks the chain down per segment.
102    if cst::explain(command).segments.len() != 1 {
103        return "\n  (facet breakdown covers one command at a time; run --explain on a single segment)\n".to_string();
104    }
105    // A COMPOUND is one segment, so it reaches here — but the flat split cannot see into it.
106    // `(cat ~/.ssh/id_rsa)` tokenises to `["(cat", "~/.ssh/id_rsa)"]`, no resolver recognises
107    // `(cat`, and the refusal rendered with no reason at all. The command the caller has to change
108    // is INSIDE the construct, so describe that one and say so.
109    let inner = cst::denied_inner_words(command);
110    let words = match inner {
111        Some(ref w) => w.clone(),
112        None => match shell_words::split(command) {
113            Ok(w) => w,
114            Err(_) => return String::new(),
115        },
116    };
117    if words.is_empty() {
118        return String::new();
119    }
120    let tokens: Vec<parse::Token> = words.into_iter().map(parse::Token::from_raw).collect();
121    let Some(ex) = engine::bridge::explain_profile(&tokens) else {
122        return String::new();
123    };
124    let mut out = String::from("\n  resolved profile:\n");
125    if let Some(w) = &inner {
126        out.push_str(&format!("    (the refused command inside it: `{}`)\n", w.join(" ")));
127    }
128    out.push_str(&engine::plain::render(&ex));
129    out
130}
131
132pub fn is_safe_command(command: &str) -> bool {
133    command_verdict(command).is_allowed()
134}
135
136pub fn command_verdict(command: &str) -> Verdict {
137    cst::command_verdict(command)
138}
139
140/// Classify `command` against a named level. Every engine-resolved leaf is decided by
141/// `Level::admits` against `level` rather than by walking the band; a `Denied` on any segment
142/// dominates. Legacy (unresolved) leaves keep their local-safe `SafeWrite`-or-below verdict.
143///
144/// A pass returns the band the PROFILE earns (`to_legacy`), so the caller's `<= ceiling` gate
145/// still tightens — that is what lets `reader` (SafeRead) and `paranoid` (Inert) use this path at
146/// all. Upper-band levels have no legacy equivalent and keep the shared `SafeWrite`.
147pub fn command_verdict_at_level(command: &str, level: &'static engine::level::Level) -> Verdict {
148    let _guard = engine::bridge::enter_eval_level(level);
149    cst::command_verdict(command)
150}
151
152/// The `&'static Level` for an UPPER-band level name, or `None` for the lower band (which the
153/// 3-value ceiling already handles) or an unknown name. The caller passes the CANONICAL name
154/// (legacy aliases already resolved).
155pub fn upper_level_by_name(name: &str) -> Option<&'static engine::level::Level> {
156    if !matches!(name, "local-admin" | "network-admin" | "yolo") {
157        return None;
158    }
159    engine::authoring::default_levels().iter().find(|l| l.name == name)
160}
161
162/// Resolve a level NAME to its `(3-band ceiling, engine level for admits)`, or `None` for an unknown
163/// name. The ceiling gates the projected verdict; the engine level (when present) classifies per-level
164/// via `admits`, exposing distinctions the 3-band projection flattens — `editor` (no destroy, no
165/// sibling write) vs `developer`, and the upper band (git push, bulk-object-read, sudo). `paranoid`/
166/// `reader` are pure ceilings (their read/inert bands need no `admits`), and `developer` IS the default
167/// band, so those carry no engine level. Legacy aliases (`safe-write`) canonicalize first.
168pub fn level_ceiling(name: &str) -> Option<(SafetyLevel, Option<&'static engine::level::Level>)> {
169    let (ceiling, legacy_of) = verdict::SafetyLevel::resolve_threshold(name)?;
170    let canonical = legacy_of.unwrap_or(name);
171    // EVERY named level classifies through `admits`. The levels are `extends`-chained
172    // (paranoid ⊂ reader ⊂ editor ⊂ developer ⊂ admin ⊂ yolo), so one mechanism across the whole
173    // ladder makes it monotone BY CONSTRUCTION: whatever a level admits, every looser level
174    // inherits.
175    //
176    // Only `editor` and the upper band used to, for a reason that turned out to be a bug rather
177    // than a design: `project` stamped every pass `SafeWrite`, which the `<= threshold` gate then
178    // refused at any lower ceiling, so handing `reader` an engine level denied its entire band
179    // (measured: 157 commands, `cat ./notes.txt` among them). With `project` returning the band
180    // the profile actually earns, that is gone.
181    //
182    // The mixture was itself the `level_monotonic` fuzz failure — `editor` decided by `admits`
183    // while `reader` and `developer` decided by projection, and nothing made two mechanisms
184    // adjacent in one ordered ladder agree.
185    let engine_level = match canonical {
186        "paranoid" | "reader" | "editor" | "developer" | "local-admin" | "network-admin" | "yolo" => {
187            engine::authoring::default_levels().iter().find(|l| l.name == canonical)
188        }
189        _ => None,
190    };
191    Some((ceiling, engine_level))
192}
193
194/// The ceilinged verdict: classify `command` at `(threshold, engine_level)`, gating the projected
195/// level `<= threshold`. The single seam both the CLI (`--level`) and the hook (configured `level`)
196/// funnel through. `engine_level = Some` classifies via `Level::admits` (the fine per-level model);
197/// `None` uses the 3-band projection. Either way the result is gated to `threshold`, so a legacy leaf
198/// that bypasses the engine (a redirect write → `SafeWrite`) is still held under a lower ceiling.
199pub fn command_verdict_ceilinged(command: &str, threshold: SafetyLevel, engine_level: Option<&'static engine::level::Level>) -> Verdict {
200    let verdict = match engine_level {
201        Some(level) => command_verdict_at_level(command, level),
202        None => command_verdict(command),
203    };
204    match verdict {
205        Verdict::Allowed(level) if level <= threshold => Verdict::Allowed(level),
206        _ => Verdict::Denied,
207    }
208}
209
210/// The coverage-fallback explanation (built-in classifier + the user's `permissions.allow` patterns),
211/// computed UNDER the configured engine level so a covered command honors that level's rule — a
212/// worktree destroy an `editor` plan forbids classifies as denied here too, not re-admitted. `None`
213/// engine level → the plain 3-band coverage (paranoid/reader/default). The caller still gates the
214/// result's `overall <= threshold`; running under the level closes the last path a lower plan's
215/// tighter rule could leak through.
216/// Whether Claude Code's OWN permission files may contribute trust to this run.
217///
218/// safe-chains reads two things out of `~/.claude/settings.json`: `permissions.allow` command
219/// patterns (the coverage bridge, `allowlist.rs`) and `Read(...)` path approvals (the grant bridge,
220/// `regions.rs`). Both were loaded unconditionally, on every harness — so a file that exists purely
221/// to configure Claude Code was silently granting permissions under Codex, Cursor, Grok and agy.
222///
223/// On Codex that is not academic. Codex has no interactive approval, which is why safe-chains
224/// DENIES a gated command there; with a `Bash(curl:*)` rule sitting in the Claude file,
225/// `curl … | sh` went from denied to abstain, and abstain on Codex means it simply runs.
226///
227/// Defaults to FALSE, so a harness safe-chains does not recognize never inherits another tool's
228/// grants. Only the Claude target turns it on.
229static CLAUDE_CONFIG_TRUSTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
230
231/// Honor `~/.claude/settings.json` as a source of trust for the rest of this process.
232pub fn trust_claude_config() {
233    CLAUDE_CONFIG_TRUSTED.store(true, std::sync::atomic::Ordering::Relaxed);
234}
235
236pub(crate) fn claude_config_trusted() -> bool {
237    CLAUDE_CONFIG_TRUSTED.load(std::sync::atomic::Ordering::Relaxed)
238}
239
240pub fn explain_with_coverage_at_level(command: &str, engine_level: Option<&'static engine::level::Level>) -> cst::Explanation {
241    let patterns = allowlist::Matcher::load();
242    let _guard = engine_level.map(engine::bridge::enter_eval_level);
243    cst::explain_with_coverage(command, &patterns)
244}
245
246/// The auto-approve ceiling the HOOK evaluates at, from the write-protected user config
247/// (`~/.config/safe-chains.toml`, `level = "…"`). No config, or an unknown name → the default
248/// `developer` band (`SafeWrite`, no engine level) — fail-safe. Honored ONLY from the user config,
249/// never a repo `.safe-chains.toml`; the file is write-denied, so an agent cannot set its own ceiling.
250pub fn configured_hook_ceiling() -> (SafetyLevel, Option<&'static engine::level::Level>) {
251    registry::user_config_level()
252        .and_then(|name| level_ceiling(&name))
253        .unwrap_or((SafetyLevel::SafeWrite, None))
254}
255
256/// Classify `command` with the harness-supplied directory context installed (HP-19), so
257/// relative paths resolve against the real `cwd`/`root`. `command_verdict(cmd)` is the
258/// no-context form (`PathCtx::default()`), preserving every existing caller.
259pub fn command_verdict_in(command: &str, ctx: pathctx::PathCtx) -> Verdict {
260    let _guard = pathctx::enter(ctx);
261    cst::command_verdict(command)
262}
263
264/// Render command-derived text safely INSIDE one of our messages.
265///
266/// The explanation is read by a human deciding whether to approve, and on the Claude and Qwen
267/// targets it is injected into the model's context as `additionalContext`. Command text is not
268/// trustworthy input for either job: a command routinely carries data the agent picked up from a
269/// file, an issue title, a downloaded manifest. Echoed raw, a newline in it forged a whole extra
270/// line of our OWN output —
271///
272/// ```text
273///   ✗  cat "/etc/x
274///   ✓  ls   safe-chains: auto-approves.
275/// ```
276///
277/// — so the reader saw an approval that never happened, in our voice. Escaping the control
278/// characters keeps any echoed text to a single line of literal content, which is the property
279/// that makes forging a second line impossible. Bidi controls go too: they reorder what is
280/// DISPLAYED without changing the bytes, which is the same forgery by other means.
281///
282/// This neutralizes our own OUTPUT. It is not a check on the command and decides nothing.
283/// Render our INTERNAL substitution markers back as `$(…)` before any of them reach a human.
284///
285/// A path carrying a substitution is classified through a sentinel, and the operand the nudge
286/// reports is the expanded form — so the reader of `cat ~/p/out/$(seq 1 1)` was being shown
287/// `~/p/out/__SAFE_CHAINS_CMDSUB_ATOM__`, a path they never wrote. On the Claude and Qwen targets
288/// this text is injected into the MODEL's context, where an internal marker is worse than noise:
289/// it is a magic string the model can learn and start emitting, and a nudge that describes a path
290/// the user cannot find in their own command is one they have no reason to trust.
291///
292/// Covers every sentinel spelling at once — opaque, atom, and the locus-tagged forms — by keying
293/// on the shared prefix and consuming through the terminating `__`, so a sentinel added later is
294/// rendered without touching this. Text that merely LOOKS like a sentinel keeps its tail — only
295/// the marker itself is replaced — because what follows a bare prefix is the user's path, not our
296/// internals, and dropping it handed a crafted filename control over how much of the path the
297/// reader saw.
298fn render_sentinels(s: &str) -> std::borrow::Cow<'_, str> {
299    let prefix = cst::eval::TAGGED_PREFIX;
300    if !s.contains(prefix) {
301        return std::borrow::Cow::Borrowed(s);
302    }
303    let mut out = String::with_capacity(s.len());
304    let mut rest = s;
305    while let Some(at) = rest.find(prefix) {
306        out.push_str(&rest[..at]);
307        out.push_str("$(…)");
308        let after = &rest[at + prefix.len()..];
309        rest = if let Some(tail) = after.strip_prefix('_') {
310            // The opaque marker is the prefix plus a single `_`.
311            tail
312        } else if let Some(i) = after.find("__") {
313            // Atom and locus-tagged markers are the prefix, a term, then `__`.
314            &after[i + 2..]
315        } else {
316            // Not one of ours. Keep the text: dropping it let a CRAFTED filename decide how much
317            // of the path a human was shown — `cat ~/__SAFE_CHAINS_CMDSUB_.ssh/id_rsa` reported
318            // reaching `~/$(…)`, hiding `.ssh/id_rsa` from the one message used to decide.
319            after
320        };
321    }
322    out.push_str(rest);
323    std::borrow::Cow::Owned(out)
324}
325
326pub fn sanitize_display(s: &str) -> String {
327    let s = &render_sentinels(s);
328    let mut out = String::with_capacity(s.len());
329    for c in s.chars() {
330        match c {
331            '\n' => out.push_str("\\n"),
332            '\r' => out.push_str("\\r"),
333            '\t' => out.push_str("\\t"),
334            // C0/C1 controls, and the bidi overrides/isolates/marks.
335            c if c.is_control() || matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{200E}' | '\u{200F}') => {
336                out.push_str(&format!("\\u{{{:04x}}}", c as u32));
337            }
338            c => out.push(c),
339        }
340    }
341    out
342}
343
344/// If a NOT-auto-approved command reaches a path OUTSIDE the workspace, return that path (its
345/// original spelling) and WHY, so the hook can nudge instead of silently prompting. Resolves against
346/// the ambient `cwd`/`root`: relative worktree paths, `/tmp`, and `/dev` streams are admitted and
347/// skipped; an absolute or home path that isn't admitted for read *or* write is the reach. A
348/// credential store outranks the hidden-peer wording; a hidden peer path outranks the generic
349/// outside-workspace reason.
350pub fn workspace_overreach(command: &str) -> Option<(String, ReachReason)> {
351    if let Some(found) = reach::repository_snapshot(command) {
352        return Some(found);
353    }
354    let tokens = operand_words(command)?;
355    tokens.into_iter().find_map(|t| {
356        if !policy::looks_like_path(&t) {
357            return None;
358        }
359        let resolved = pathctx::resolve(&t).into_owned();
360        // A temp path is READ/WRITE admitted, so the outside-test below never fires on it — but it
361        // is not EXECUTABLE unless it is this session's scratchpad. When the command was denied,
362        // that is the likely reason, and it is the one case where the fix is a grant rather than a
363        // correction, so surface it with those instructions.
364        if pathctx::under_temp_root(&resolved) && !pathctx::in_session_scratchpad(&resolved) {
365            return Some((t, ReachReason::ForeignTemp));
366        }
367        // The REBIND face is consulted too, or a granted trust-root directory denies in silence:
368        // the grant opens read and write, so `rm -rf ~/.config` looked ordinary here while the
369        // engine refused it. Only the trust-root directories can make this term true, since every
370        // other role's rebind face equals its write face.
371        let outside = (resolved.starts_with('/') || resolved.starts_with('~'))
372            && (!engine::resolve::read_content_verdict(&resolved).is_allowed()
373                || !engine::resolve::write_target_verdict(&resolved).is_allowed()
374                || engine::resolve::rebind_is_stricter_than_write(&resolved));
375        if !outside {
376            return None;
377        }
378        Some((t, reach::classify(&resolved)))
379    })
380}
381
382/// The words a command actually RUNS with, for explaining a denial.
383///
384/// This must agree with the parse the verdict came from, so it walks the CST. Splitting the raw
385/// string instead (`shell_words::split`) tokenizes text the shell never treats as an argument —
386/// above all a heredoc BODY, which is data. `git commit -m "$(cat <<'EOF' … EOF)"` whose message
387/// merely MENTIONS `/etc/hosts` was reported as "reaches /etc/hosts", naming a false reason for the
388/// denial and advising the reader to grant that path — a config widening the command never needed.
389///
390/// Falls back to the raw split only when the command does not parse, where a best-effort nudge on
391/// approximate tokens still beats none.
392fn operand_words(command: &str) -> Option<Vec<String>> {
393    let Some(script) = cst::parse(command) else {
394        return shell_words::split(command).ok();
395    };
396    let mut out = Vec::new();
397    collect_script_words(&script, &mut out);
398    Some(out)
399}
400
401/// A word contributes its own expansions AND the words of any command substitution inside it: the
402/// inner command runs, so `notacommand $(cat /etc/shadow)` really does read the file, even though
403/// `expand()` renders the substitution as an opaque stand-in and hides the path.
404fn collect_word(word: &cst::Word, out: &mut Vec<String>) {
405    out.extend(word.expand());
406    for part in &word.0 {
407        collect_part_subs(part, out);
408    }
409}
410
411/// The words of any command SUBSTITUTION inside a word part, and nothing else — the part's own
412/// literal text is the caller's business, because whether it counts as an operand depends on where
413/// the word came from (a heredoc body's literal text never does).
414fn collect_part_subs(part: &cst::WordPart, out: &mut Vec<String>) {
415    use cst::WordPart;
416    match part {
417        WordPart::CmdSub(script) | WordPart::ProcSub(script) => collect_script_words(script, out),
418        WordPart::DQuote(inner) => collect_word(inner, out),
419        // Arithmetic contributes no operand of its own — its value is a number — but a `$( )`
420        // inside it runs, and that command's words are operands the verdict layer classifies.
421        WordPart::Arith(inner) => collect_word(inner, out),
422        WordPart::Lit(_) | WordPart::Escape(_) | WordPart::SQuote(_) | WordPart::AnsiC(_) | WordPart::Backtick(_) => {}
423    }
424}
425
426fn collect_script_words(script: &cst::Script, out: &mut Vec<String>) {
427    for stmt in &script.0 {
428        for cmd in &stmt.pipeline.commands {
429            collect_cmd_words(cmd, out);
430        }
431    }
432}
433
434/// A redirect TARGET is a path the command opens, so it is a reach and must be reported —
435/// `notacommand > /etc/passwd` names `/etc/passwd`. A heredoc DELIMITER is not a path at all, and
436/// its body never appears in the CST, which is the whole point.
437fn collect_redir_words(redirs: &[cst::Redir], out: &mut Vec<String>) {
438    use cst::Redir;
439    for redir in redirs {
440        match redir {
441            Redir::Write { target, .. } | Redir::Read { target, .. } | Redir::ReadWrite { target, .. } | Redir::HereStr(target) => {
442                collect_word(target, out)
443            }
444            // Only the body's SUBSTITUTIONS, never its literal text. Behind a bare delimiter a
445            // `$(cat /etc/shadow)` in the body really runs, so it is a reach worth naming; the
446            // prose around it is data and naming it would state a false reason for the denial.
447            Redir::HereDoc { body, .. } => {
448                for part in &body.0 {
449                    collect_part_subs(part, out);
450                }
451            }
452            Redir::DupFd { .. } => {}
453        }
454    }
455}
456
457fn collect_cmd_words(cmd: &cst::Cmd, out: &mut Vec<String>) {
458    use cst::Cmd;
459    let words = |ws: &[cst::Word], out: &mut Vec<String>| {
460        for w in ws {
461            collect_word(w, out);
462        }
463    };
464    match cmd {
465        Cmd::Simple(s) => {
466            words(&s.words, out);
467            collect_redir_words(&s.redirs, out);
468        }
469        Cmd::Subshell { body, redirs } | Cmd::BraceGroup { body, redirs } => {
470            collect_script_words(body, out);
471            collect_redir_words(redirs, out);
472        }
473        Cmd::For { items, body, redirs, .. } => {
474            words(items, out);
475            collect_script_words(body, out);
476            collect_redir_words(redirs, out);
477        }
478        Cmd::While { cond, body, redirs } | Cmd::Until { cond, body, redirs } => {
479            collect_script_words(cond, out);
480            collect_script_words(body, out);
481            collect_redir_words(redirs, out);
482        }
483        Cmd::If { branches, else_body, redirs } => {
484            collect_redir_words(redirs, out);
485            for branch in branches {
486                collect_script_words(&branch.cond, out);
487                collect_script_words(&branch.body, out);
488            }
489            if let Some(body) = else_body {
490                collect_script_words(body, out);
491            }
492        }
493        Cmd::DoubleBracket { words: ws, redirs } => {
494            words(ws, out);
495            collect_redir_words(redirs, out);
496        }
497        Cmd::Case { subject, arms, redirs } => {
498            collect_word(subject, out);
499            for arm in arms {
500                collect_script_words(&arm.body, out);
501            }
502            collect_redir_words(redirs, out);
503        }
504        Cmd::FunctionDef { body, .. } => collect_script_words(body, out),
505    }
506}
507
508#[cfg(test)]
509mod tests;