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