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