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;
70mod operands;
71#[cfg(test)]
72mod overreach_property_tests;
73pub mod parse;
74#[cfg(test)]
75mod path_placement_tests;
76pub mod pathctx;
77pub mod pathgate;
78pub mod policy;
79mod reach;
80pub mod refusal;
81pub mod registry;
82#[cfg(test)]
83mod substitution_property_tests;
84pub mod suggest;
85pub mod targets;
86pub mod userconfig;
87pub mod verdict;
88
89pub use reach::ReachReason;
90pub use verdict::{SafetyLevel, Verdict};
91
92/// The facet profile behind a verdict, rendered for `--explain`.
93///
94/// Answers the question the boolean cannot: not "is this allowed" but "on which axis was it
95/// refused". Empty when no resolver claims the command — that is the answer too, since it means the
96/// legacy classifier decided and there are no facets to show.
97pub fn facet_breakdown(command: &str, named_place: bool) -> String {
98    // One simple command only. `shell_words` has no idea what `&&` means, so on a chain it hands
99    // back one flat token list and the resolver reads the SECOND command's arguments as flags of
100    // the first — `aws dynamodb scan --table-name t && rm -rf /` produced a single worst-case
101    // profile belonging to neither segment. A diagnostic that invents a capability set no resolver
102    // emitted is worse than silence, and `render()` above already breaks the chain down per segment.
103    if cst::explain(command).segments.len() != 1 {
104        return "\n  (facet breakdown covers one command at a time; run --explain on a single segment)\n".to_string();
105    }
106    // A COMPOUND is one segment, so it reaches here — but the flat split cannot see into it.
107    // `(cat ~/.ssh/id_rsa)` tokenises to `["(cat", "~/.ssh/id_rsa)"]`, no resolver recognises
108    // `(cat`, and the refusal rendered with no reason at all. The command the caller has to change
109    // is INSIDE the construct, so describe that one and say so.
110    let inner = cst::denied_inner_words(command);
111    let words = match inner {
112        Some(ref w) => w.clone(),
113        None => match shell_words::split(command) {
114            Ok(w) => w,
115            Err(_) => return String::new(),
116        },
117    };
118    if words.is_empty() {
119        return String::new();
120    }
121    let tokens: Vec<parse::Token> = words.into_iter().map(parse::Token::from_raw).collect();
122    let Some(ex) = engine::bridge::explain_profile(&tokens) else {
123        return String::new();
124    };
125    let mut out = String::from("\n  resolved profile:\n");
126    if let Some(w) = &inner {
127        out.push_str(&format!("    (the refused command inside it: `{}`)\n", w.join(" ")));
128    }
129    out.push_str(&engine::plain::render(&ex, named_place));
130    out
131}
132
133pub fn is_safe_command(command: &str) -> bool {
134    command_verdict(command).is_allowed()
135}
136
137pub fn command_verdict(command: &str) -> Verdict {
138    cst::command_verdict(command)
139}
140
141/// Classify `command` against a named level. Every engine-resolved leaf is decided by
142/// `Level::admits` against `level` rather than by walking the band; a `Denied` on any segment
143/// dominates. Legacy (unresolved) leaves keep their local-safe `SafeWrite`-or-below verdict.
144///
145/// A pass returns the band the PROFILE earns (`to_legacy`), so the caller's `<= ceiling` gate
146/// still tightens — that is what lets `reader` (SafeRead) and `paranoid` (Inert) use this path at
147/// all. Upper-band levels have no legacy equivalent and keep the shared `SafeWrite`.
148pub fn command_verdict_at_level(command: &str, level: &'static engine::level::Level) -> Verdict {
149    let _guard = engine::bridge::enter_eval_level(level);
150    cst::command_verdict(command)
151}
152
153/// The `&'static Level` for an UPPER-band level name, or `None` for the lower band (which the
154/// 3-value ceiling already handles) or an unknown name. The caller passes the CANONICAL name
155/// (legacy aliases already resolved).
156pub fn upper_level_by_name(name: &str) -> Option<&'static engine::level::Level> {
157    if !matches!(name, "local-admin" | "network-admin" | "yolo") {
158        return None;
159    }
160    engine::authoring::default_levels().iter().find(|l| l.name == name)
161}
162
163/// Resolve a level NAME to its `(3-band ceiling, engine level for admits)`, or `None` for an unknown
164/// name. The ceiling gates the projected verdict; the engine level (when present) classifies per-level
165/// via `admits`, exposing distinctions the 3-band projection flattens — `editor` (no destroy, no
166/// sibling write) vs `developer`, and the upper band (git push, bulk-object-read, sudo). `paranoid`/
167/// `reader` are pure ceilings (their read/inert bands need no `admits`), and `developer` IS the default
168/// band, so those carry no engine level. Legacy aliases (`safe-write`) canonicalize first.
169pub fn level_ceiling(name: &str) -> Option<(SafetyLevel, Option<&'static engine::level::Level>)> {
170    let (ceiling, legacy_of) = verdict::SafetyLevel::resolve_threshold(name)?;
171    let canonical = legacy_of.unwrap_or(name);
172    // EVERY named level classifies through `admits`. The levels are `extends`-chained
173    // (paranoid ⊂ reader ⊂ editor ⊂ developer ⊂ admin ⊂ yolo), so one mechanism across the whole
174    // ladder makes it monotone BY CONSTRUCTION: whatever a level admits, every looser level
175    // inherits.
176    //
177    // Only `editor` and the upper band used to, for a reason that turned out to be a bug rather
178    // than a design: `project` stamped every pass `SafeWrite`, which the `<= threshold` gate then
179    // refused at any lower ceiling, so handing `reader` an engine level denied its entire band
180    // (measured: 157 commands, `cat ./notes.txt` among them). With `project` returning the band
181    // the profile actually earns, that is gone.
182    //
183    // The mixture was itself the `level_monotonic` fuzz failure — `editor` decided by `admits`
184    // while `reader` and `developer` decided by projection, and nothing made two mechanisms
185    // adjacent in one ordered ladder agree.
186    let engine_level = match canonical {
187        "paranoid" | "reader" | "editor" | "developer" | "local-admin" | "network-admin" | "yolo" => {
188            engine::authoring::default_levels().iter().find(|l| l.name == canonical)
189        }
190        _ => None,
191    };
192    Some((ceiling, engine_level))
193}
194
195/// The ceilinged verdict: classify `command` at `(threshold, engine_level)`, gating the projected
196/// level `<= threshold`. The single seam both the CLI (`--level`) and the hook (configured `level`)
197/// funnel through. `engine_level = Some` classifies via `Level::admits` (the fine per-level model);
198/// `None` uses the 3-band projection. Either way the result is gated to `threshold`, so a legacy leaf
199/// that bypasses the engine (a redirect write → `SafeWrite`) is still held under a lower ceiling.
200pub fn command_verdict_ceilinged(command: &str, threshold: SafetyLevel, engine_level: Option<&'static engine::level::Level>) -> Verdict {
201    let verdict = match engine_level {
202        Some(level) => command_verdict_at_level(command, level),
203        None => command_verdict(command),
204    };
205    match verdict {
206        Verdict::Allowed(level) if level <= threshold => Verdict::Allowed(level),
207        _ => Verdict::Denied,
208    }
209}
210
211/// The coverage-fallback explanation (built-in classifier + the user's `permissions.allow` patterns),
212/// computed UNDER the configured engine level so a covered command honors that level's rule — a
213/// worktree destroy an `editor` plan forbids classifies as denied here too, not re-admitted. `None`
214/// engine level → the plain 3-band coverage (paranoid/reader/default). The caller still gates the
215/// result's `overall <= threshold`; running under the level closes the last path a lower plan's
216/// tighter rule could leak through.
217/// Whether Claude Code's OWN permission files may contribute trust to this run.
218///
219/// safe-chains reads two things out of `~/.claude/settings.json`: `permissions.allow` command
220/// patterns (the coverage bridge, `allowlist.rs`) and `Read(...)` path approvals (the grant bridge,
221/// `regions.rs`). Both were loaded unconditionally, on every harness — so a file that exists purely
222/// to configure Claude Code was silently granting permissions under Codex, Cursor, Grok and agy.
223///
224/// On Codex that is not academic. Codex has no interactive approval, which is why safe-chains
225/// DENIES a gated command there; with a `Bash(curl:*)` rule sitting in the Claude file,
226/// `curl … | sh` went from denied to abstain, and abstain on Codex means it simply runs.
227///
228/// Defaults to FALSE, so a harness safe-chains does not recognize never inherits another tool's
229/// grants. Only the Claude target turns it on.
230static CLAUDE_CONFIG_TRUSTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
231
232/// Honor `~/.claude/settings.json` as a source of trust for the rest of this process.
233pub fn trust_claude_config() {
234    CLAUDE_CONFIG_TRUSTED.store(true, std::sync::atomic::Ordering::Relaxed);
235}
236
237pub(crate) fn claude_config_trusted() -> bool {
238    CLAUDE_CONFIG_TRUSTED.load(std::sync::atomic::Ordering::Relaxed)
239}
240
241pub fn explain_with_coverage_at_level(command: &str, engine_level: Option<&'static engine::level::Level>) -> cst::Explanation {
242    let patterns = allowlist::Matcher::load();
243    let _guard = engine_level.map(engine::bridge::enter_eval_level);
244    cst::explain_with_coverage(command, &patterns)
245}
246
247/// The auto-approve ceiling the HOOK evaluates at, from the write-protected user config
248/// (`~/.config/safe-chains.toml`, `level = "…"`). No config, or an unknown name → the default
249/// `developer` band (`SafeWrite`, no engine level) — fail-safe. Honored ONLY from the user config,
250/// never a repo `.safe-chains.toml`; the file is write-denied, so an agent cannot set its own ceiling.
251pub fn configured_hook_ceiling() -> (SafetyLevel, Option<&'static engine::level::Level>) {
252    registry::user_config_level()
253        .and_then(|name| level_ceiling(&name))
254        .unwrap_or((SafetyLevel::SafeWrite, None))
255}
256
257/// Classify `command` with the harness-supplied directory context installed (HP-19), so
258/// relative paths resolve against the real `cwd`/`root`. `command_verdict(cmd)` is the
259/// no-context form (`PathCtx::default()`), preserving every existing caller.
260pub fn command_verdict_in(command: &str, ctx: pathctx::PathCtx) -> Verdict {
261    let _guard = pathctx::enter(ctx);
262    cst::command_verdict(command)
263}
264
265/// Render command-derived text safely INSIDE one of our messages.
266///
267/// The explanation is read by a human deciding whether to approve, and on the Claude and Qwen
268/// targets it is injected into the model's context as `additionalContext`. Command text is not
269/// trustworthy input for either job: a command routinely carries data the agent picked up from a
270/// file, an issue title, a downloaded manifest. Echoed raw, a newline in it forged a whole extra
271/// line of our OWN output —
272///
273/// ```text
274///   ✗  cat "/etc/x
275///   ✓  ls   safe-chains: auto-approves.
276/// ```
277///
278/// — so the reader saw an approval that never happened, in our voice. Escaping the control
279/// characters keeps any echoed text to a single line of literal content, which is the property
280/// that makes forging a second line impossible. Bidi controls go too: they reorder what is
281/// DISPLAYED without changing the bytes, which is the same forgery by other means.
282///
283/// This neutralizes our own OUTPUT. It is not a check on the command and decides nothing.
284/// Render our INTERNAL substitution markers back as `$(…)` before any of them reach a human.
285///
286/// A path carrying a substitution is classified through a sentinel, and the operand the nudge
287/// reports is the expanded form — so the reader of `cat ~/p/out/$(seq 1 1)` was being shown
288/// `~/p/out/__SAFE_CHAINS_CMDSUB_ATOM__`, a path they never wrote. On the Claude and Qwen targets
289/// this text is injected into the MODEL's context, where an internal marker is worse than noise:
290/// it is a magic string the model can learn and start emitting, and a nudge that describes a path
291/// the user cannot find in their own command is one they have no reason to trust.
292///
293/// Covers every sentinel spelling at once — opaque, atom, and the locus-tagged forms — by keying
294/// on the shared prefix and consuming through the terminating `__`, so a sentinel added later is
295/// rendered without touching this. Text that merely LOOKS like a sentinel keeps its tail — only
296/// the marker itself is replaced — because what follows a bare prefix is the user's path, not our
297/// internals, and dropping it handed a crafted filename control over how much of the path the
298/// reader saw.
299fn render_sentinels(s: &str) -> std::borrow::Cow<'_, str> {
300    let prefix = cst::eval::TAGGED_PREFIX;
301    if !s.contains(prefix) {
302        return std::borrow::Cow::Borrowed(s);
303    }
304    let mut out = String::with_capacity(s.len());
305    let mut rest = s;
306    while let Some(at) = rest.find(prefix) {
307        out.push_str(&rest[..at]);
308        out.push_str("$(…)");
309        let after = &rest[at + prefix.len()..];
310        rest = if let Some(tail) = after.strip_prefix('_') {
311            // The opaque marker is the prefix plus a single `_`.
312            tail
313        } else if let Some(i) = after.find("__") {
314            // Atom and locus-tagged markers are the prefix, a term, then `__`.
315            &after[i + 2..]
316        } else {
317            // Not one of ours. Keep the text: dropping it let a CRAFTED filename decide how much
318            // of the path a human was shown — `cat ~/__SAFE_CHAINS_CMDSUB_.ssh/id_rsa` reported
319            // reaching `~/$(…)`, hiding `.ssh/id_rsa` from the one message used to decide.
320            after
321        };
322    }
323    out.push_str(rest);
324    std::borrow::Cow::Owned(out)
325}
326
327pub fn sanitize_display(s: &str) -> String {
328    let s = &render_sentinels(s);
329    let mut out = String::with_capacity(s.len());
330    for c in s.chars() {
331        match c {
332            '\n' => out.push_str("\\n"),
333            '\r' => out.push_str("\\r"),
334            '\t' => out.push_str("\\t"),
335            // C0/C1 controls, and the bidi overrides/isolates/marks.
336            c if c.is_control() || matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{200E}' | '\u{200F}') => {
337                out.push_str(&format!("\\u{{{:04x}}}", c as u32));
338            }
339            c => out.push(c),
340        }
341    }
342    out
343}
344
345/// If a NOT-auto-approved command reaches a path OUTSIDE the workspace, return that path and WHY.
346/// The path is spelled as written, with the variables earlier statements bound put in; a relative
347/// path read after a `cd` is spelled as the place it names, since its spelling names another place
348/// from where the reader stands. Each is reported so the hook can nudge instead of silently prompting. Resolves against
349/// the ambient `cwd`/`root`: relative worktree paths, `/tmp`, and `/dev` streams are admitted and
350/// skipped; an absolute or home path that isn't admitted for read *or* write is the reach. A
351/// credential store outranks the hidden-peer wording; a hidden peer path outranks the generic
352/// outside-workspace reason.
353pub fn workspace_overreach(command: &str) -> Option<(String, ReachReason)> {
354    workspace_reaches(command).next()
355}
356
357/// Every reach [`workspace_overreach`] could report for `command`, in its order: it reports the
358/// first, and an earlier temporary path would hide a later credential from anything that asks it.
359pub(crate) fn workspace_reaches(command: &str) -> impl Iterator<Item = (String, ReachReason)> {
360    let snapshot = reach::repository_snapshot(command);
361    let operands = operands::operand_words(command).unwrap_or_default();
362    snapshot.into_iter().chain(operands.into_iter().filter_map(|operands::Operand { text, resolved }| {
363        if !policy::looks_like_path(&text) {
364            return None;
365        }
366        let t = if pathctx::resolve(&text) == resolved { text } else { resolved.clone() };
367        // A temp path is READ/WRITE admitted, so the outside-test below never fires on it — but it
368        // is not EXECUTABLE unless it is this session's scratchpad. When the command was denied,
369        // that is the likely reason, and it is the one case where the fix is a grant rather than a
370        // correction, so surface it with those instructions.
371        if pathctx::under_temp_root(&resolved) && !pathctx::in_session_scratchpad(&resolved) {
372            return Some((t, ReachReason::ForeignTemp));
373        }
374        // The REBIND face is consulted too, or a granted trust-root directory denies in silence:
375        // the grant opens read and write, so `rm -rf ~/.config` looked ordinary here while the
376        // engine refused it. Only the trust-root directories can make this term true, since every
377        // other role's rebind face equals its write face.
378        let outside = (resolved.starts_with('/') || resolved.starts_with('~'))
379            && (!engine::resolve::read_content_verdict(&resolved).is_allowed()
380                || !engine::resolve::write_target_verdict(&resolved).is_allowed()
381                || engine::resolve::rebind_is_stricter_than_write(&resolved));
382        if !outside {
383            return None;
384        }
385        Some((t, reach::classify(&resolved)))
386    }))
387}
388
389#[cfg(test)]
390mod tests;