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