Skip to main content

safe_chains/
lib.rs

1// The generated test names spell the command and its flags verbatim, and FLAG CASE IS MEANINGFUL:
2// find takes both `-D` and `-d`, `-P` and `-p`, `-L` and `-l`, and commands like `asn1Decoding` and
3// `checkLocalKDC` are camel-case upstream. Lowercasing to satisfy `non_snake_case` would erase the
4// distinction the test exists to pin, so the generated items opt out instead.
5#[cfg(test)]
6macro_rules! safe {
7    ($($name:ident: $cmd:expr),* $(,)?) => {
8        $(#[test] #[allow(non_snake_case)] fn $name() { assert!(check($cmd), "expected safe: {}", $cmd); })*
9    };
10}
11
12#[cfg(test)]
13macro_rules! denied {
14    ($($name:ident: $cmd:expr),* $(,)?) => {
15        $(#[test] #[allow(non_snake_case)] fn $name() { assert!(!check($cmd), "expected denied: {}", $cmd); })*
16    };
17}
18
19#[cfg(test)]
20macro_rules! inert {
21    ($($name:ident: $cmd:expr),* $(,)?) => {
22        $(#[test] #[allow(non_snake_case)] fn $name() {
23            assert_eq!(
24                crate::command_verdict($cmd),
25                crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::Inert),
26                "expected Inert: {}", $cmd,
27            );
28        })*
29    };
30}
31
32#[cfg(test)]
33macro_rules! safe_read {
34    ($($name:ident: $cmd:expr),* $(,)?) => {
35        $(#[test] #[allow(non_snake_case)] fn $name() {
36            assert_eq!(
37                crate::command_verdict($cmd),
38                crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::SafeRead),
39                "expected SafeRead: {}", $cmd,
40            );
41        })*
42    };
43}
44
45#[cfg(test)]
46macro_rules! safe_write {
47    ($($name:ident: $cmd:expr),* $(,)?) => {
48        $(#[test] #[allow(non_snake_case)] fn $name() {
49            assert_eq!(
50                crate::command_verdict($cmd),
51                crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::SafeWrite),
52                "expected SafeWrite: {}", $cmd,
53            );
54        })*
55    };
56}
57
58pub mod allowlist;
59pub mod cli;
60#[cfg(test)]
61mod composition;
62pub mod cst;
63pub mod decisionlog;
64pub mod docs;
65pub mod engine;
66mod envvars;
67#[cfg(test)]
68mod handler_property_tests;
69mod handlers;
70pub mod netloc;
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;
79pub mod refusal;
80pub mod registry;
81#[cfg(test)]
82mod substitution_property_tests;
83pub mod suggest;
84pub mod targets;
85pub mod verdict;
86
87pub use verdict::{SafetyLevel, Verdict};
88
89/// The facet profile behind a verdict, rendered for `--explain`.
90///
91/// Answers the question the boolean cannot: not "is this allowed" but "on which axis was it
92/// refused". Empty when no resolver claims the command — that is the answer too, since it means the
93/// legacy classifier decided and there are no facets to show.
94pub fn facet_breakdown(command: &str) -> String {
95    // One simple command only. `shell_words` has no idea what `&&` means, so on a chain it hands
96    // back one flat token list and the resolver reads the SECOND command's arguments as flags of
97    // the first — `aws dynamodb scan --table-name t && rm -rf /` produced a single worst-case
98    // profile belonging to neither segment. A diagnostic that invents a capability set no resolver
99    // emitted is worse than silence, and `render()` above already breaks the chain down per segment.
100    if cst::explain(command).segments.len() != 1 {
101        return "\n  (facet breakdown covers one command at a time; run --explain on a single segment)\n".to_string();
102    }
103    // A COMPOUND is one segment, so it reaches here — but the flat split cannot see into it.
104    // `(cat ~/.ssh/id_rsa)` tokenises to `["(cat", "~/.ssh/id_rsa)"]`, no resolver recognises
105    // `(cat`, and the refusal rendered with no reason at all. The command the caller has to change
106    // is INSIDE the construct, so describe that one and say so.
107    let inner = cst::denied_inner_words(command);
108    let words = match inner {
109        Some(ref w) => w.clone(),
110        None => match shell_words::split(command) {
111            Ok(w) => w,
112            Err(_) => return String::new(),
113        },
114    };
115    if words.is_empty() {
116        return String::new();
117    }
118    let tokens: Vec<parse::Token> = words.into_iter().map(parse::Token::from_raw).collect();
119    let Some(ex) = engine::bridge::explain_profile(&tokens) else {
120        return String::new();
121    };
122    let mut out = String::from("\n  resolved profile:\n");
123    if let Some(w) = &inner {
124        out.push_str(&format!("    (the refused command inside it: `{}`)\n", w.join(" ")));
125    }
126    for (because, facets) in &ex.capabilities {
127        out.push_str(&format!("    · {because}\n"));
128        for (name, term) in facets {
129            out.push_str(&format!("        {name:<28} {term}\n"));
130        }
131    }
132    match &ex.blocked_by {
133        Some((level, mismatch)) => {
134            out.push_str(&format!("\n  refused by `{level}` (the most permissive auto-approving level):\n    {mismatch}\n",));
135        }
136        None => out.push_str("\n  admitted by the auto-approve band.\n"),
137    }
138    out
139}
140
141pub fn is_safe_command(command: &str) -> bool {
142    command_verdict(command).is_allowed()
143}
144
145pub fn command_verdict(command: &str) -> Verdict {
146    cst::command_verdict(command)
147}
148
149/// Classify `command` against a named level. Every engine-resolved leaf is decided by
150/// `Level::admits` against `level` rather than by walking the band; a `Denied` on any segment
151/// dominates. Legacy (unresolved) leaves keep their local-safe `SafeWrite`-or-below verdict.
152///
153/// A pass returns the band the PROFILE earns (`to_legacy`), so the caller's `<= ceiling` gate
154/// still tightens — that is what lets `reader` (SafeRead) and `paranoid` (Inert) use this path at
155/// all. Upper-band levels have no legacy equivalent and keep the shared `SafeWrite`.
156pub fn command_verdict_at_level(command: &str, level: &'static engine::level::Level) -> Verdict {
157    let _guard = engine::bridge::enter_eval_level(level);
158    cst::command_verdict(command)
159}
160
161/// The `&'static Level` for an UPPER-band level name, or `None` for the lower band (which the
162/// 3-value ceiling already handles) or an unknown name. The caller passes the CANONICAL name
163/// (legacy aliases already resolved).
164pub fn upper_level_by_name(name: &str) -> Option<&'static engine::level::Level> {
165    if !matches!(name, "local-admin" | "network-admin" | "yolo") {
166        return None;
167    }
168    engine::authoring::default_levels().iter().find(|l| l.name == name)
169}
170
171/// Resolve a level NAME to its `(3-band ceiling, engine level for admits)`, or `None` for an unknown
172/// name. The ceiling gates the projected verdict; the engine level (when present) classifies per-level
173/// via `admits`, exposing distinctions the 3-band projection flattens — `editor` (no destroy, no
174/// sibling write) vs `developer`, and the upper band (git push, bulk-object-read, sudo). `paranoid`/
175/// `reader` are pure ceilings (their read/inert bands need no `admits`), and `developer` IS the default
176/// band, so those carry no engine level. Legacy aliases (`safe-write`) canonicalize first.
177pub fn level_ceiling(name: &str) -> Option<(SafetyLevel, Option<&'static engine::level::Level>)> {
178    let (ceiling, legacy_of) = verdict::SafetyLevel::resolve_threshold(name)?;
179    let canonical = legacy_of.unwrap_or(name);
180    // EVERY named level classifies through `admits`. The levels are `extends`-chained
181    // (paranoid ⊂ reader ⊂ editor ⊂ developer ⊂ admin ⊂ yolo), so one mechanism across the whole
182    // ladder makes it monotone BY CONSTRUCTION: whatever a level admits, every looser level
183    // inherits.
184    //
185    // Only `editor` and the upper band used to, for a reason that turned out to be a bug rather
186    // than a design: `project` stamped every pass `SafeWrite`, which the `<= threshold` gate then
187    // refused at any lower ceiling, so handing `reader` an engine level denied its entire band
188    // (measured: 157 commands, `cat ./notes.txt` among them). With `project` returning the band
189    // the profile actually earns, that is gone.
190    //
191    // The mixture was itself the `level_monotonic` fuzz failure — `editor` decided by `admits`
192    // while `reader` and `developer` decided by projection, and nothing made two mechanisms
193    // adjacent in one ordered ladder agree.
194    let engine_level = match canonical {
195        "paranoid" | "reader" | "editor" | "developer" | "local-admin" | "network-admin" | "yolo" => {
196            engine::authoring::default_levels().iter().find(|l| l.name == canonical)
197        }
198        _ => None,
199    };
200    Some((ceiling, engine_level))
201}
202
203/// The ceilinged verdict: classify `command` at `(threshold, engine_level)`, gating the projected
204/// level `<= threshold`. The single seam both the CLI (`--level`) and the hook (configured `level`)
205/// funnel through. `engine_level = Some` classifies via `Level::admits` (the fine per-level model);
206/// `None` uses the 3-band projection. Either way the result is gated to `threshold`, so a legacy leaf
207/// that bypasses the engine (a redirect write → `SafeWrite`) is still held under a lower ceiling.
208pub fn command_verdict_ceilinged(command: &str, threshold: SafetyLevel, engine_level: Option<&'static engine::level::Level>) -> Verdict {
209    let verdict = match engine_level {
210        Some(level) => command_verdict_at_level(command, level),
211        None => command_verdict(command),
212    };
213    match verdict {
214        Verdict::Allowed(level) if level <= threshold => Verdict::Allowed(level),
215        _ => Verdict::Denied,
216    }
217}
218
219/// The coverage-fallback explanation (built-in classifier + the user's `permissions.allow` patterns),
220/// computed UNDER the configured engine level so a covered command honors that level's rule — a
221/// worktree destroy an `editor` plan forbids classifies as denied here too, not re-admitted. `None`
222/// engine level → the plain 3-band coverage (paranoid/reader/default). The caller still gates the
223/// result's `overall <= threshold`; running under the level closes the last path a lower plan's
224/// tighter rule could leak through.
225/// Whether Claude Code's OWN permission files may contribute trust to this run.
226///
227/// safe-chains reads two things out of `~/.claude/settings.json`: `permissions.allow` command
228/// patterns (the coverage bridge, `allowlist.rs`) and `Read(...)` path approvals (the grant bridge,
229/// `regions.rs`). Both were loaded unconditionally, on every harness — so a file that exists purely
230/// to configure Claude Code was silently granting permissions under Codex, Cursor, Grok and agy.
231///
232/// On Codex that is not academic. Codex has no interactive approval, which is why safe-chains
233/// DENIES a gated command there; with a `Bash(curl:*)` rule sitting in the Claude file,
234/// `curl … | sh` went from denied to abstain, and abstain on Codex means it simply runs.
235///
236/// Defaults to FALSE, so a harness safe-chains does not recognize never inherits another tool's
237/// grants. Only the Claude target turns it on.
238static CLAUDE_CONFIG_TRUSTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
239
240/// Honor `~/.claude/settings.json` as a source of trust for the rest of this process.
241pub fn trust_claude_config() {
242    CLAUDE_CONFIG_TRUSTED.store(true, std::sync::atomic::Ordering::Relaxed);
243}
244
245pub(crate) fn claude_config_trusted() -> bool {
246    CLAUDE_CONFIG_TRUSTED.load(std::sync::atomic::Ordering::Relaxed)
247}
248
249pub fn explain_with_coverage_at_level(command: &str, engine_level: Option<&'static engine::level::Level>) -> cst::Explanation {
250    let patterns = allowlist::Matcher::load();
251    let _guard = engine_level.map(engine::bridge::enter_eval_level);
252    cst::explain_with_coverage(command, &patterns)
253}
254
255/// The auto-approve ceiling the HOOK evaluates at, from the write-protected user config
256/// (`~/.config/safe-chains.toml`, `level = "…"`). No config, or an unknown name → the default
257/// `developer` band (`SafeWrite`, no engine level) — fail-safe. Honored ONLY from the user config,
258/// never a repo `.safe-chains.toml`; the file is write-denied, so an agent cannot set its own ceiling.
259pub fn configured_hook_ceiling() -> (SafetyLevel, Option<&'static engine::level::Level>) {
260    registry::user_config_level()
261        .and_then(|name| level_ceiling(&name))
262        .unwrap_or((SafetyLevel::SafeWrite, None))
263}
264
265/// Classify `command` with the harness-supplied directory context installed (HP-19), so
266/// relative paths resolve against the real `cwd`/`root`. `command_verdict(cmd)` is the
267/// no-context form (`PathCtx::default()`), preserving every existing caller.
268pub fn command_verdict_in(command: &str, ctx: pathctx::PathCtx) -> Verdict {
269    let _guard = pathctx::enter(ctx);
270    cst::command_verdict(command)
271}
272
273/// Why a not-auto-approved command's path reach was flagged — so the nudge can explain the actual
274/// reason instead of a one-size-fits-all "outside the working directory". A peer's hidden file and a
275/// path genuinely above cwd both deny, but the remedy differs, and conflating them is what reads as
276/// "directory parsing is broken".
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub enum ReachReason {
279    /// A known credential store (`.ssh`, `.aws`, keychain…).
280    Credential,
281    /// A file safe-chains reads its OWN permissions from (`~/.config/safe-chains.toml`,
282    /// `~/.claude/settings.json`). Distinct from `OutsideWorkspace` because the generic remedy
283    /// there — grant the path — is not merely unhelpful but FALSE: the write face is frozen, so
284    /// following the advice changes nothing. For safe-chains' own config it is also circular,
285    /// telling the user to edit the file they are being stopped from editing.
286    FrozenTrustFile,
287    /// The DIRECTORY a trust file lives in. Distinct from `FrozenTrustFile` because only HALF of
288    /// it is refused: writing a file into `~/.config` is ordinary and stays allowed, and only
289    /// removing or replacing the directory is not. Copy that said "this is refused" flatly would
290    /// misdescribe a directory the user explicitly granted.
291    FrozenTrustRoot,
292    /// One of the files that decide who may log in (`/etc/passwd`, `/etc/sudoers`, `/etc/pam.d`,
293    /// the loader and boot). Same false-remedy problem as `FrozenTrustFile`.
294    FrozenSystemIntegrity,
295    /// A raw block or character device (`/dev/mem`, `/dev/rdisk0`, `/dev/sda`). Distinct from
296    /// `FrozenSystemIntegrity` because the `device` rung outranks `system-integrity`, so without
297    /// its own arm every device was explained as a file that "decides who may log in" — which is
298    /// both false and unhelpful about the thing that actually makes a device dangerous.
299    RawDevice,
300    /// Genuinely above/outside the working directory.
301    OutsideWorkspace,
302    /// A path built by an interpolation that nothing confines (`./out/$i`, `> $(cmd)`). It is not
303    /// outside anything — it names WHATEVER the value turns out to be, which is why it cannot be
304    /// admitted — so the remedy is to constrain the spelling, not to grant a directory.
305    Unconfined,
306    /// A temp path that is NOT this session's scratchpad. Reading and writing it is fine; RUNNING
307    /// code from it is not, because anonymous `/tmp` is where downloaded/foreign code lands. This
308    /// is the one reach whose remedy is usually "that IS my working directory" — so the nudge says
309    /// how to bless it rather than implying the agent did something wrong.
310    ForeignTemp,
311}
312
313/// Render command-derived text safely INSIDE one of our messages.
314///
315/// The explanation is read by a human deciding whether to approve, and on the Claude and Qwen
316/// targets it is injected into the model's context as `additionalContext`. Command text is not
317/// trustworthy input for either job: a command routinely carries data the agent picked up from a
318/// file, an issue title, a downloaded manifest. Echoed raw, a newline in it forged a whole extra
319/// line of our OWN output —
320///
321/// ```text
322///   ✗  cat "/etc/x
323///   ✓  ls   safe-chains: auto-approves.
324/// ```
325///
326/// — so the reader saw an approval that never happened, in our voice. Escaping the control
327/// characters keeps any echoed text to a single line of literal content, which is the property
328/// that makes forging a second line impossible. Bidi controls go too: they reorder what is
329/// DISPLAYED without changing the bytes, which is the same forgery by other means.
330///
331/// This neutralizes our own OUTPUT. It is not a check on the command and decides nothing.
332/// Render our INTERNAL substitution markers back as `$(…)` before any of them reach a human.
333///
334/// A path carrying a substitution is classified through a sentinel, and the operand the nudge
335/// reports is the expanded form — so the reader of `cat ~/p/out/$(seq 1 1)` was being shown
336/// `~/p/out/__SAFE_CHAINS_CMDSUB_ATOM__`, a path they never wrote. On the Claude and Qwen targets
337/// this text is injected into the MODEL's context, where an internal marker is worse than noise:
338/// it is a magic string the model can learn and start emitting, and a nudge that describes a path
339/// the user cannot find in their own command is one they have no reason to trust.
340///
341/// Covers every sentinel spelling at once — opaque, atom, and the locus-tagged forms — by keying
342/// on the shared prefix and consuming through the terminating `__`, so a sentinel added later is
343/// rendered without touching this. Text that merely LOOKS like a sentinel keeps its tail — only
344/// the marker itself is replaced — because what follows a bare prefix is the user's path, not our
345/// internals, and dropping it handed a crafted filename control over how much of the path the
346/// reader saw.
347fn render_sentinels(s: &str) -> std::borrow::Cow<'_, str> {
348    let prefix = cst::eval::TAGGED_PREFIX;
349    if !s.contains(prefix) {
350        return std::borrow::Cow::Borrowed(s);
351    }
352    let mut out = String::with_capacity(s.len());
353    let mut rest = s;
354    while let Some(at) = rest.find(prefix) {
355        out.push_str(&rest[..at]);
356        out.push_str("$(…)");
357        let after = &rest[at + prefix.len()..];
358        rest = if let Some(tail) = after.strip_prefix('_') {
359            // The opaque marker is the prefix plus a single `_`.
360            tail
361        } else if let Some(i) = after.find("__") {
362            // Atom and locus-tagged markers are the prefix, a term, then `__`.
363            &after[i + 2..]
364        } else {
365            // Not one of ours. Keep the text: dropping it let a CRAFTED filename decide how much
366            // of the path a human was shown — `cat ~/__SAFE_CHAINS_CMDSUB_.ssh/id_rsa` reported
367            // reaching `~/$(…)`, hiding `.ssh/id_rsa` from the one message used to decide.
368            after
369        };
370    }
371    out.push_str(rest);
372    std::borrow::Cow::Owned(out)
373}
374
375pub fn sanitize_display(s: &str) -> String {
376    let s = &render_sentinels(s);
377    let mut out = String::with_capacity(s.len());
378    for c in s.chars() {
379        match c {
380            '\n' => out.push_str("\\n"),
381            '\r' => out.push_str("\\r"),
382            '\t' => out.push_str("\\t"),
383            // C0/C1 controls, and the bidi overrides/isolates/marks.
384            c if c.is_control() || matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{200E}' | '\u{200F}') => {
385                out.push_str(&format!("\\u{{{:04x}}}", c as u32));
386            }
387            c => out.push(c),
388        }
389    }
390    out
391}
392
393impl ReachReason {
394    /// The self-contained nudge body ("it reaches `X`, …") including the reason-appropriate remedy.
395    /// Callers add their own framing (block / please-confirm) and the docs link.
396    /// Whether naming this path in `~/.config/safe-chains.toml` actually changes the verdict.
397    ///
398    /// The refusal copy offers a grant, or explains that granting will not help, and the two must
399    /// not diverge: advice that does nothing costs more than silence, because the reader follows
400    /// it, sees no change, and stops believing the rest. `a_refusal_offers_a_grant_only_when_one_
401    /// would_work` runs the verdict twice — once with the grant applied — and holds this to it.
402    ///
403    /// `Credential` is `true` as of 2026-09-01 and was `false` before it. A grant naming a store
404    /// used to move the locus and leave `reads_secret` set, so the message's "name that path"
405    /// advice was FALSE while reading exactly right. That is the failure this pairing exists to
406    /// catch, and it went unnoticed because nothing compared the sentence to the behaviour.
407    pub fn grant_helps(self) -> bool {
408        match self {
409            // A grant that NAMES the store clears the shield for reading it.
410            ReachReason::Credential | ReachReason::RawDevice => true,
411            // "That IS my working directory" is the usual answer here.
412            ReachReason::ForeignTemp | ReachReason::OutsideWorkspace => true,
413            // Frozen faces stay frozen however specifically they are named: an agent that can edit
414            // the trust file decides what is approved next, and one that can write `/etc/sudoers`
415            // owns the machine's authorization substrate.
416            ReachReason::FrozenTrustFile | ReachReason::FrozenTrustRoot | ReachReason::FrozenSystemIntegrity => false,
417            // There is no path to grant. The remedy is to constrain the spelling.
418            ReachReason::Unconfined => false,
419        }
420    }
421
422    pub fn message(self, path: &str) -> String {
423        let path = &sanitize_display(path);
424        match self {
425            ReachReason::Credential => format!(
426                "it reaches `{path}`, a credential store. The agent has no ordinary reason to touch \
427                 one. If that was not intended, stop it. If you do want to allow it, name that path \
428                 in ~/.config/safe-chains.toml. A grant on a parent directory does not reach a \
429                 credential store"
430            ),
431            ReachReason::RawDevice => format!(
432                "it reaches `{path}`, a raw device. Reading one is not reading a file — a disk \
433                 device hands over every file on it and memory hands over every secret in it — and \
434                 writing one goes underneath the filesystem entirely. If you do want the read, \
435                 name that path in ~/.config/safe-chains.toml; the write stays refused"
436            ),
437            ReachReason::FrozenTrustFile => format!(
438                "it reaches `{path}`. safe-chains reads its own permissions from that file, so a \
439                 write there is never auto-approved. Granting the path does not change that, \
440                 because an agent that can edit this file can decide what gets approved next. Edit \
441                 it yourself if you meant to change it"
442            ),
443            ReachReason::FrozenTrustRoot => format!(
444                "it reaches `{path}`. safe-chains reads its own permissions from a file in that \
445                 directory, so removing or replacing the directory itself is never auto-approved: \
446                 doing that would point the trust root somewhere else. Writing files into it is \
447                 fine, and granting the path does not change either half. Move or delete it \
448                 yourself if you meant to"
449            ),
450            ReachReason::FrozenSystemIntegrity => format!(
451                "it reaches `{path}`. That file decides who may log in and what they may do, so a \
452                 write there is never auto-approved. Granting the path does not change that. Edit \
453                 it yourself if you meant to change it"
454            ),
455            ReachReason::ForeignTemp => format!(
456                "it runs code from `{path}`, a temporary directory that is not this session's \
457                 scratchpad. Reading and writing temp files is fine. Running code from there is \
458                 not, because a downloaded script lands in the same place. If this is a working \
459                 directory you trust, grant it in ~/.config/safe-chains.toml. A scratchpad the \
460                 harness reports for this session is recognized on its own and needs no grant"
461            ),
462            ReachReason::Unconfined => format!(
463                "the path `{path}` is built by an interpolation, so what it names depends on a \
464                 value the command does not show. It could be anywhere, which is why it cannot be \
465                 auto-approved. If the interpolated part cannot contain a `/`, put literal text \
466                 beside it in the same path component. `out/dx_$i.txt` is approved where `out/$i` \
467                 is not: the first is a filename whatever `$i` holds, and the second could be `..`"
468            ),
469            ReachReason::OutsideWorkspace => match pathctx::cwd().map(|c| sanitize_display(&c)) {
470                Some(cwd) => format!(
471                    "it reaches `{path}`, outside the working directory `{cwd}`. If the agent is \
472                     running from the wrong directory, relaunch it where you meant to be. To allow \
473                     it from here, grant that path in ~/.config/safe-chains.toml"
474                ),
475                None => format!(
476                    "it reaches `{path}`, outside the working directory. To allow it, grant that \
477                     path in ~/.config/safe-chains.toml"
478                ),
479            },
480        }
481    }
482}
483
484/// If a NOT-auto-approved command reaches a path OUTSIDE the workspace, return that path (its
485/// original spelling) and WHY, so the hook can nudge instead of silently prompting. Resolves against
486/// the ambient `cwd`/`root`: relative worktree paths, `/tmp`, and `/dev` streams are admitted and
487/// skipped; an absolute or home path that isn't admitted for read *or* write is the reach. A
488/// credential store outranks the hidden-peer wording; a hidden peer path outranks the generic
489/// outside-workspace reason.
490pub fn workspace_overreach(command: &str) -> Option<(String, ReachReason)> {
491    let tokens = operand_words(command)?;
492    tokens.into_iter().find_map(|t| {
493        if !policy::looks_like_path(&t) {
494            return None;
495        }
496        let resolved = pathctx::resolve(&t).into_owned();
497        // A temp path is READ/WRITE admitted, so the outside-test below never fires on it — but it
498        // is not EXECUTABLE unless it is this session's scratchpad. When the command was denied,
499        // that is the likely reason, and it is the one case where the fix is a grant rather than a
500        // correction, so surface it with those instructions.
501        if pathctx::under_temp_root(&resolved) && !pathctx::in_session_scratchpad(&resolved) {
502            return Some((t, ReachReason::ForeignTemp));
503        }
504        // The REBIND face is consulted too, or a granted trust-root directory denies in silence:
505        // the grant opens read and write, so `rm -rf ~/.config` looked ordinary here while the
506        // engine refused it. Only the trust-root directories can make this term true, since every
507        // other role's rebind face equals its write face.
508        let outside = (resolved.starts_with('/') || resolved.starts_with('~'))
509            && (!engine::resolve::read_content_verdict(&resolved).is_allowed()
510                || !engine::resolve::write_target_verdict(&resolved).is_allowed()
511                || engine::resolve::rebind_is_stricter_than_write(&resolved));
512        if !outside {
513            return None;
514        }
515        // Asked on the LITERAL structure, so an interpolated component cannot strip the credential
516        // warning off a path that plainly names one. `cat ~/.ssh/$(id)` was reported as merely
517        // "built by an interpolation" — offering to flank it, which can never help, while dropping
518        // the one sentence that matters — and the CONFINED spelling fell through to
519        // "outside the working directory", whose remedy is to GRANT the path.
520        //
521        // Granting a credential store IS possible now (a grant covers what it names), so the
522        // objection is no longer "that remedy cannot work". It is that the generic wording says
523        // "grant that path" while meaning the ordinary parent-directory grant, which is exactly
524        // the form a credential store does not accept. The Credential arm spells out the
525        // difference instead.
526        let reason = if engine::resolve::names_credential_store(&resolved) {
527            ReachReason::Credential
528        } else if let Some(kind) = engine::resolve::frozen_write_kind(&resolved) {
529            // Ahead of Unconfined and OutsideWorkspace for the same reason Credential is: both of
530            // those end in "grant that path", which for a frozen write face is FALSE rather than
531            // merely vague, and for safe-chains' own config it is circular as well.
532            match kind {
533                engine::resolve::FrozenWrite::TrustFile => ReachReason::FrozenTrustFile,
534                engine::resolve::FrozenWrite::TrustRootDir => ReachReason::FrozenTrustRoot,
535                engine::resolve::FrozenWrite::SystemIntegrity => ReachReason::FrozenSystemIntegrity,
536                engine::resolve::FrozenWrite::RawDevice => ReachReason::RawDevice,
537            }
538        } else if engine::resolve::anchoring_of(&resolved) == crate::engine::facet::Anchoring::Opaque {
539            // Ahead of OutsideWorkspace because it is the more specific diagnosis of the SAME
540            // refusal, and the generic wording actively misleads here: it names a working-directory
541            // problem the user does not have and a remedy (grant the path) that cannot work,
542            // since the path is not a fixed path at all.
543            ReachReason::Unconfined
544        } else {
545            ReachReason::OutsideWorkspace
546        };
547        Some((t, reason))
548    })
549}
550
551/// The words a command actually RUNS with, for explaining a denial.
552///
553/// This must agree with the parse the verdict came from, so it walks the CST. Splitting the raw
554/// string instead (`shell_words::split`) tokenizes text the shell never treats as an argument —
555/// above all a heredoc BODY, which is data. `git commit -m "$(cat <<'EOF' … EOF)"` whose message
556/// merely MENTIONS `/etc/hosts` was reported as "reaches /etc/hosts", naming a false reason for the
557/// denial and advising the reader to grant that path — a config widening the command never needed.
558///
559/// Falls back to the raw split only when the command does not parse, where a best-effort nudge on
560/// approximate tokens still beats none.
561fn operand_words(command: &str) -> Option<Vec<String>> {
562    let Some(script) = cst::parse(command) else {
563        return shell_words::split(command).ok();
564    };
565    let mut out = Vec::new();
566    collect_script_words(&script, &mut out);
567    Some(out)
568}
569
570/// A word contributes its own expansions AND the words of any command substitution inside it: the
571/// inner command runs, so `notacommand $(cat /etc/shadow)` really does read the file, even though
572/// `expand()` renders the substitution as an opaque stand-in and hides the path.
573fn collect_word(word: &cst::Word, out: &mut Vec<String>) {
574    out.extend(word.expand());
575    for part in &word.0 {
576        collect_part_subs(part, out);
577    }
578}
579
580/// The words of any command SUBSTITUTION inside a word part, and nothing else — the part's own
581/// literal text is the caller's business, because whether it counts as an operand depends on where
582/// the word came from (a heredoc body's literal text never does).
583fn collect_part_subs(part: &cst::WordPart, out: &mut Vec<String>) {
584    use cst::WordPart;
585    match part {
586        WordPart::CmdSub(script) | WordPart::ProcSub(script) => collect_script_words(script, out),
587        WordPart::DQuote(inner) => collect_word(inner, out),
588        // Arithmetic contributes no operand of its own — its value is a number — but a `$( )`
589        // inside it runs, and that command's words are operands the verdict layer classifies.
590        WordPart::Arith(inner) => collect_word(inner, out),
591        WordPart::Lit(_) | WordPart::Escape(_) | WordPart::SQuote(_) | WordPart::AnsiC(_) | WordPart::Backtick(_) => {}
592    }
593}
594
595fn collect_script_words(script: &cst::Script, out: &mut Vec<String>) {
596    for stmt in &script.0 {
597        for cmd in &stmt.pipeline.commands {
598            collect_cmd_words(cmd, out);
599        }
600    }
601}
602
603/// A redirect TARGET is a path the command opens, so it is a reach and must be reported —
604/// `notacommand > /etc/passwd` names `/etc/passwd`. A heredoc DELIMITER is not a path at all, and
605/// its body never appears in the CST, which is the whole point.
606fn collect_redir_words(redirs: &[cst::Redir], out: &mut Vec<String>) {
607    use cst::Redir;
608    for redir in redirs {
609        match redir {
610            Redir::Write { target, .. } | Redir::Read { target, .. } | Redir::ReadWrite { target, .. } | Redir::HereStr(target) => {
611                collect_word(target, out)
612            }
613            // Only the body's SUBSTITUTIONS, never its literal text. Behind a bare delimiter a
614            // `$(cat /etc/shadow)` in the body really runs, so it is a reach worth naming; the
615            // prose around it is data and naming it would state a false reason for the denial.
616            Redir::HereDoc { body, .. } => {
617                for part in &body.0 {
618                    collect_part_subs(part, out);
619                }
620            }
621            Redir::DupFd { .. } => {}
622        }
623    }
624}
625
626fn collect_cmd_words(cmd: &cst::Cmd, out: &mut Vec<String>) {
627    use cst::Cmd;
628    let words = |ws: &[cst::Word], out: &mut Vec<String>| {
629        for w in ws {
630            collect_word(w, out);
631        }
632    };
633    match cmd {
634        Cmd::Simple(s) => {
635            words(&s.words, out);
636            collect_redir_words(&s.redirs, out);
637        }
638        Cmd::Subshell { body, redirs } | Cmd::BraceGroup { body, redirs } => {
639            collect_script_words(body, out);
640            collect_redir_words(redirs, out);
641        }
642        Cmd::For { items, body, redirs, .. } => {
643            words(items, out);
644            collect_script_words(body, out);
645            collect_redir_words(redirs, out);
646        }
647        Cmd::While { cond, body, redirs } | Cmd::Until { cond, body, redirs } => {
648            collect_script_words(cond, out);
649            collect_script_words(body, out);
650            collect_redir_words(redirs, out);
651        }
652        Cmd::If { branches, else_body, redirs } => {
653            collect_redir_words(redirs, out);
654            for branch in branches {
655                collect_script_words(&branch.cond, out);
656                collect_script_words(&branch.body, out);
657            }
658            if let Some(body) = else_body {
659                collect_script_words(body, out);
660            }
661        }
662        Cmd::DoubleBracket { words: ws, redirs } => {
663            words(ws, out);
664            collect_redir_words(redirs, out);
665        }
666        Cmd::Case { subject, arms, redirs } => {
667            collect_word(subject, out);
668            for arm in arms {
669                collect_script_words(&arm.body, out);
670            }
671            collect_redir_words(redirs, out);
672        }
673        Cmd::FunctionDef { body, .. } => collect_script_words(body, out),
674    }
675}
676
677#[cfg(test)]
678mod tests;