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