diff --git a/src/core/paths.rs b/src/core/paths.rs index 48f28a5..692bb96 100644 --- a/src/core/paths.rs +++ b/src/core/paths.rs @@ -82,24 +82,45 @@ pub fn expand_home(word: &str, home: Option<&Path>) -> String { #[derive(Default)] struct Splitter { - segments: Vec>, - words: Vec, + segments: Vec>, + words: Vec, word: Option, heredoc: Option, + /// The last thing read was an unquoted `<` or `>`. + after_redirect: bool, +} + +/// A word, or an unquoted `<` or `>`: a quoted `'>'` is a word and never this. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Token { + Word(String), + Redirect(char), } impl Splitter { fn push(&mut self, c: char) { self.word.get_or_insert_with(String::new).push(c); + self.after_redirect = false; + } + + fn start_quote(&mut self) { + self.word.get_or_insert_with(String::new); + self.after_redirect = false; + } + + fn redirect(&mut self, c: char) { + self.end_word(); + self.words.push(Token::Redirect(c)); + self.after_redirect = true; } fn end_word(&mut self) { if let Some(word) = self.word.take() { // `<<` opens a heredoc, `<<<` a one-word string. - if self.words.iter().rev().take_while(|w| *w == "<").count() == 2 { + if self.words.iter().rev().take_while(|w| **w == Token::Redirect('<')).count() == 2 { self.heredoc = Some(word.trim_start_matches('-').to_string()); } - self.words.push(word); + self.words.push(Token::Word(word)); } } @@ -111,10 +132,18 @@ impl Splitter { } } -/// A command's words, one list per simple command. `<` and `>` are words of their own, -/// also when quoted, which a check this short can afford. A comment and a heredoc's -/// body are left out: they are text no command reads as a path. +/// A command's words, one list per simple command, with an unquoted `<` and `>` as words of +/// their own. A comment and a heredoc's body are left out: they are text no command reads +/// as a path. pub fn segments(command: &str, dialect: Dialect) -> Vec> { + let text = |token: Token| match token { + Token::Word(word) => word, + Token::Redirect(c) => c.to_string(), + }; + tokens(command, dialect).into_iter().map(|segment| segment.into_iter().map(text).collect()).collect() +} + +fn tokens(command: &str, dialect: Dialect) -> Vec> { let chars: Vec = command.chars().collect(); let escape = if dialect == Dialect::Posix { '\\' } else { '`' }; let (mut s, mut quote, mut i) = (Splitter::default(), None, 0); @@ -135,7 +164,7 @@ pub fn segments(command: &str, dialect: Dialect) -> Vec> { (Some(_), _) => s.push(c), (None, '\'' | '"') => { quote = Some(c); - s.word.get_or_insert_with(String::new); + s.start_quote(); } (None, '#') if s.word.is_none() => i += chars[i..].iter().take_while(|next| **next != '\n').count(), (None, '\n') => { @@ -149,12 +178,9 @@ pub fn segments(command: &str, dialect: Dialect) -> Vec> { } } // `2>&1` and `>|` stay in their segment: this `&` starts no job, this `|` no pipe. - (None, '&' | '|') if s.word.is_none() && s.words.last().is_some_and(|w| w == ">") => {} + (None, '&' | '|') if s.word.is_none() && s.after_redirect && s.words.last() == Some(&Token::Redirect('>')) => {} (None, ';' | '|' | '&' | '(' | ')' | '`') => s.end_segment(), - (None, '<' | '>') => { - s.end_word(); - s.words.push(c.to_string()); - } + (None, '<' | '>') => s.redirect(c), (None, _) if c.is_whitespace() => s.end_word(), (None, _) => s.push(c), } @@ -169,28 +195,31 @@ pub fn segments(command: &str, dialect: Dialect) -> Vec> { /// or a here-string names nothing. pub fn command_paths(command: &str, dialect: Dialect, cwd: &Path, home: Option<&Path>) -> Vec { let mut found = Vec::new(); - for words in segments(command, dialect) { + for words in tokens(command, dialect) { let (mut args, mut inputs, mut outputs) = (Vec::new(), Vec::new(), Vec::new()); - let mut rest = words.iter().map(String::as_str).peekable(); - while let Some(word) = rest.next() { - if word != "<" && word != ">" { - args.push(word); - continue; - } + let mut rest = words.iter().peekable(); + while let Some(token) = rest.next() { + let op = match token { + Token::Word(word) => { + args.push(word.as_str()); + continue; + } + Token::Redirect(op) => *op, + }; let mut run = 1; - while rest.next_if_eq(&word).is_some() { + while rest.next_if_eq(&token).is_some() { run += 1; } - match (word, rest.next()) { + match (op, rest.next()) { // `<>` opens its target both ways: it is read as well as written. - ("<", Some(">")) if run == 1 => { - let target = rest.next(); + ('<', Some(Token::Redirect('>'))) if run == 1 => { + let target = word_of(rest.next()); inputs.extend(target); outputs.extend(target); } - ("<", Some(target)) if run == 1 => inputs.push(target), + ('<', Some(Token::Word(target))) if run == 1 => inputs.push(target.as_str()), // `2>&1` names a file descriptor. - (">", Some(target)) if !target.chars().all(|c| c.is_ascii_digit()) => outputs.push(target), + ('>', Some(Token::Word(target))) if !target.chars().all(|c| c.is_ascii_digit()) => outputs.push(target.as_str()), _ => {} } } @@ -216,6 +245,21 @@ fn takes_a_value(verb: &str, flag: &str) -> bool { LONG_VALUE_FLAGS.contains(&flag) || (flag.starts_with('-') && !flag.starts_with("--") && flag.ends_with(|c| short.contains(c))) } +/// Whether `word` gives a pattern verb its pattern, so that its first other word is a file: +/// `-e`, `-f`, `--regexp`, `--file`, `--expression`, with or without `=`, or a short cluster +/// holding `e` or `f` (`-eAPI`, `-ie`, `-fp`). awk's `-e` is gawk's, and `e` in a cluster none. +fn gives_a_pattern(verb: &str, word: &str) -> bool { + let long = ["--regexp", "--file", "--expression", "--source"].iter().any(|flag| word == *flag || word.strip_prefix(flag).is_some_and(|rest| rest.starts_with('='))); + let letters: &[char] = if verb == "awk" { &['f'] } else { &['e', 'f'] }; + let short = word.starts_with('-') && !word.starts_with("--") && word.len() > 1; + long || word == "-e" || (short && word[1..].contains(letters)) +} + +/// Whether the word after `flag` is a pattern: `-e API`, `-ie API`, `--regexp API`. +fn takes_a_pattern(flag: &str) -> bool { + matches!(flag, "--regexp" | "--expression" | "--source") || (flag.starts_with('-') && !flag.starts_with("--") && flag.ends_with('e')) +} + /// git's command, past its quiet flags and `-C `. fn git_command<'a>(rest: &[&'a str]) -> Option<&'a str> { let mut words = rest.iter().copied(); @@ -241,22 +285,85 @@ fn takes_a_line(shell: &str, flag: &str) -> bool { } } +/// Flags of a POSIX shell that take the next word: `-o pipefail`, `+O extglob`, `--rcfile x`. +fn shell_flag_takes_a_value(shell: &str, flag: &str) -> bool { + let short = !flag.starts_with("--") && flag.len() > 1 && flag.ends_with(['o', 'O']); + short || matches!(flag, "--rcfile" | "--init-file" | "--init-command") || (shell == "fish" && flag == "-C") +} + +/// PowerShell's flags that take no value. Every other one does: `-ExecutionPolicy Bypass`. +const POWERSHELL_SWITCHES: &[&str] = &["-noprofile", "-nop", "-nologo", "-noninteractive", "-noni", "-noexit", "-login", "-l", "-interactive", "-mta", "-sta"]; + +/// The text of a word token. +fn word_of(token: Option<&Token>) -> Option<&str> { + match token { + Some(Token::Word(word)) => Some(word.as_str()), + _ => None, + } +} + +/// A word quoted for a POSIX shell. +fn quoted(word: &str) -> String { + format!("'{}'", word.replace('\'', "'\\''")) +} + /// The command line a shell or `eval` is given, and how many of `rest` stand before it and -/// are the command's own. All the words after the flag count: `eval` joins its arguments, -/// `cmd /c` takes several, and `bash -c 'cat "$1"' _ .env` reads the last. +/// are the command's own. The line flag is looked for among the shell's leading options +/// only: after a script's name, or PowerShell's `-File`, a flag is the script's. `eval`, +/// `cmd` and PowerShell join the words after it. A POSIX shell takes one line, and the +/// words after it are its arguments, which the line may print: they get a segment of +/// their own that prints them, so `bash -c 'cat "$1"; echo done' _ .env` reads `.env`. fn given_line(name: &str, rest: &[&str]) -> Option<(String, usize)> { - let line = |words: &[&str]| Some(words.iter().copied().filter(|w| !w.starts_with('-')).collect::>().join(" ")).filter(|line| !line.is_empty()); + let joined = |words: &[&str]| Some(words.iter().copied().filter(|w| !w.starts_with('-')).collect::>().join(" ")).filter(|line| !line.is_empty()); if name == "eval" { - return Some((line(rest)?, 0)); + return Some((joined(rest)?, 0)); } if !SHELLS.contains(&name) { return None; } - if let Some(value) = rest.iter().find_map(|w| w.strip_prefix("--command=")) { - return Some((value.to_string(), rest.len())); + let powershell = matches!(name, "pwsh" | "powershell"); + let is_flag = |word: &str| word.starts_with(['-', '+']) || (name == "cmd" && word.starts_with('/')); + let takes_value = |word: &str| match powershell { + true => !POWERSHELL_SWITCHES.contains(&word.to_ascii_lowercase().as_str()), + false => shell_flag_takes_a_value(name, word), + }; + let mut at = 0; + let (flag_at, given) = loop { + let word = *rest.get(at)?; + if let Some(line) = word.strip_prefix("--command=") { + break (at, Some(line)); + } + if takes_a_line(name, word) { + break (at, None); + } + let file = powershell && word.len() > 1 && "-file".starts_with(&word.to_ascii_lowercase()); + if !is_flag(word) || file { + return None; + } + at += 1 + usize::from(takes_value(word)); + }; + let mut after = flag_at + 1; + if powershell || name == "cmd" { + return Some((joined(&rest[after..])?, flag_at)); + } + let line = match given { + Some(line) => line, + None => { + // `bash -c -o pipefail 'line'`: options may follow the flag. + after += usize::from(shell_flag_takes_a_value(name, rest[flag_at])); + while let Some(word) = rest.get(after).filter(|word| is_flag(word)) { + after += 1 + usize::from(shell_flag_takes_a_value(name, word)); + } + let line = *rest.get(after)?; + after += 1; + line + } + }; + let arguments: Vec = rest.get(after..).unwrap_or_default().iter().map(|word| quoted(word)).collect(); + match arguments.is_empty() { + true => Some((line.to_string(), flag_at)), + false => Some((format!("{line}\ncat {}", arguments.join(" ")), flag_at)), } - let at = rest.iter().position(|w| takes_a_line(name, w))?; - Some((line(&rest[at + 1..])?, at)) } /// The value `word` holds of an output `flag`: `-ofile`, `--output=file`. @@ -316,12 +423,12 @@ fn named_words<'a>(args: &[&'a str]) -> (Verb, Vec<&'a str>, Vec<&'a str>, Optio _ => &[], }; let pattern_first = PATTERN_FIRST.contains(&name.as_str()); - let mut pattern_due = pattern_first && !rest.iter().any(|w| matches!(*w, "-e" | "-f")); + let mut pattern_due = pattern_first && !rest.iter().any(|w| gives_a_pattern(&name, w)); let mut previous = ""; let mut written = Vec::new(); let from = named.len(); for word in rest.iter().copied() { - let is_pattern = (pattern_first && previous == "-e") || (name == "find" && FIND_PATTERNS.contains(&previous)) || (TAKES_EXCLUDES_SPACED.contains(&name.as_str()) && EXCLUDES_SPACED.contains(&previous)) || takes_a_value(&name, previous); + let is_pattern = (pattern_first && takes_a_pattern(previous)) || (name == "find" && FIND_PATTERNS.contains(&previous)) || (TAKES_EXCLUDES_SPACED.contains(&name.as_str()) && EXCLUDES_SPACED.contains(&previous)) || takes_a_value(&name, previous); let is_output_flag = |flag: &&str| if flag.len() == 2 { *flag == previous } else { flag.eq_ignore_ascii_case(previous) }; let output = if output_flags.iter().any(|flag| is_output_flag(&flag)) { Some(word) } else { output_flags.iter().find_map(|flag| attached_value(word, flag)) }; previous = word; diff --git a/tests/cli_command_paths.rs b/tests/cli_command_paths.rs index 0559882..75f4971 100644 --- a/tests/cli_command_paths.rs +++ b/tests/cli_command_paths.rs @@ -668,3 +668,225 @@ fn a_command_line_is_read_in_every_flag_spelling() { assert_eq!(bash(p.path(), command), json!({}), "{command}"); } } + +/// N-1: the words after a POSIX shell's line are its arguments, and the line may print them. +/// They are read on their own, so the line's last segment or a comment does not decide them. +#[test] +fn the_words_after_a_shells_line_are_read_as_what_it_may_print() { + let p = project(&[(".botignore", ".env\n"), (".env", ENV), ("id_rsa", PEM)]); + for command in [ + "bash -c 'cat \"$1\"; echo done' _ .env", + "bash -c 'cat \"$1\" && echo done' _ .env", + "bash -c 'source \"$1\"; printf ok' _ .env", + "bash -c 'cat \"$1\" | ls' _ .env", + "bash -c 'cat \"$1\" # read' _ .env", + "bash -c 'cat \"$1\"\necho done' _ .env", + "fish --command='cat $argv' .env", + // The read gate. + "bash -c 'cat \"$1\"; true' _ id_rsa", + "bash -c -o pipefail 'cat id_rsa'", + "bash -o pipefail -c 'cat id_rsa'", + ] { + assert_eq!(verdict(&bash(p.path(), command)), "deny", "{command}"); + } + for command in ["bash -c 'echo hi' _ a.txt", "bash -c 'ls \"$1\"' _ a-name"] { + assert_eq!(bash(p.path(), command), json!({}), "{command}"); + } +} + +/// N-2: a shell's line flag stands among its leading options. After a script's name, or +/// PowerShell's `-File`, a flag is the script's own. +#[test] +fn a_flag_after_a_scripts_name_is_the_scripts_own() { + for rule in RULES { + let p = project(&[rule, (".env", ENV)]); + for command in [ + "bash run.sh -c .env", + "bash run.sh -config .env", + "bash run.sh -source .env", + "bash run.sh -check .env", + "bash run.sh -vc .env", + "sh run.sh -secrets .env", + "sh -x run.sh -conf .env", + "fish run.fish -config .env", + "bash run.sh --command .env", + "pwsh -File x.ps1 -c .env", + "pwsh x.ps1 -c .env", + ] { + assert_eq!(verdict(&bash(p.path(), command)), "deny", "{rule:?}: {command}"); + } + for command in ["pwsh -NoProfile -ExecutionPolicy Bypass -Command 'cat .env'", "bash --norc -o pipefail -ce 'cat .env'", "cmd /s /c type .env"] { + assert_eq!(verdict(&bash(p.path(), command)), "deny", "{rule:?}: {command}"); + } + } +} + +/// N-3: a quoted `<`, `>` or `|` is a word, never an operator. +#[test] +fn a_quoted_operator_is_a_word() { + let p = project(&[(".botignore", ".env\n"), (".env", ENV), ("id_rsa", PEM)]); + for command in [ + "echo '>' | cat .env", + "echo \">\" | cat .env", + "printf '>' | cat .env", + "ls '>' | cat .env", + "echo \">\" && cat .env", + "echo '>' & cat .env", + "echo '<' '<' EOF\ncat .env\nEOF", + // The read gate. + "echo '>' | cat id_rsa", + "cat '>' id_rsa", + "cat \"<\" id_rsa", + ] { + assert_eq!(verdict(&bash(p.path(), command)), "deny", "{command}"); + } +} + +/// S-1: a pattern given attached or with `=` spends the pattern slot, so the file after it +/// is still a file. +#[test] +fn a_pattern_given_attached_or_with_an_equals_sign_leaves_the_file_a_file() { + let p = project(&[(".botignore", ".env\n"), (".env", ENV), ("id_rsa", PEM)]); + for command in [ + "grep -eAPI .env", + "grep --regexp=API .env", + "grep --regexp API .env", + "rg -eAPI .env", + "rg --regexp=API .env", + "sed -ep .env", + "sed --expression=p .env", + "sed --expression p .env", + "sed -nep .env", + "grep -ieAPI .env", + "grep -ie API .env", + "grep -fp .env", + "grep --file=p .env", + "rg --file=p .env", + "awk -fp .env", + "awk --file=p .env", + // The read gate. + "grep -eFAKE id_rsa", + "grep --regexp=FAKE id_rsa", + "rg -eFAKE id_rsa", + "sed -ep id_rsa", + "sed --expression=p id_rsa", + "grep -fp id_rsa", + ] { + assert_eq!(verdict(&bash(p.path(), command)), "deny", "{command}"); + } + for command in ["grep -e .env a.txt", "grep --regexp .env a.txt", "sed -e s/.env/x/ a.txt", "grep -ie .env a.txt"] { + assert_eq!(bash(p.path(), command), json!({}), "{command}"); + } +} + +/// Ordinary commands under rules a project may well have pass, as the re-check's probe ran +/// them (`jq .env a.txt` is left out: it is stopped, and was before). +#[test] +fn ordinary_commands_pass_under_common_rules() { + let p = project(&[ + (".botignore", ".env\n.env.*\nsecrets/\nvendor/\nnode_modules/\ntarget/\n*.log\n"), + (".botsecrets", "[policy.write]\npatterns = [\".claude/**\", \"*.lock\", \"Cargo.lock\"]\n"), + (".env", ENV), + ("a.txt", "x"), + ("README.md", "x"), + ("src/main.rs", "x"), + ("Cargo.lock", "x"), + ("node_modules/a", "x"), + ("target/a", "x"), + ]); + for command in [ + "cargo test 2>&1 | tail -20", + "cargo build 2>&1 | tee build.txt", + "git status", + "git diff", + "git log --oneline -5", + "git add -A", + "git commit -m 'update .env loading'", + "git push", + "ls -la", + "ls -o", + "ls -la src", + "grep -rn foo src", + "grep -n .env README.md", + "rg -n '.env' src", + "rg --ignore-case foo src", + "rg --no-ignore foo", + "sed -n 1,20p src/main.rs", + "sed -i 's/a/b/' src/main.rs", + "sed -Ei 's/a/b/' src/main.rs", + "head -5 a.txt", + "cat a.txt | sort -u", + "sort -o a.txt a.txt", + "sort -u a.txt -o b.txt", + "find . -name '*.rs'", + "find . -name .env", + "mkdir -p build/x", + "cp a.txt b.txt", + "mv a.txt c.txt", + "rm -f out.txt", + "touch new.txt", + "echo hi > out.txt", + "echo hi >| out.txt", + "cat a.txt > 'my file.txt'", + "curl -o out.bin https://example.invalid", + "curl -sS -o /dev/null https://example.invalid", + "wget -O- https://example.invalid", + "wget -O - https://example.invalid", + "gcc -o out a.c", + "gcc -O2 -o out a.c", + "ssh -o StrictHostKeyChecking=no host ls", + "ssh -oBatchMode=yes host ls", + "scp a.txt host:/srv/vendor/x", + "rsync -a src/ host:/srv/vendor/x", + "rsync -a src/ user@host:vendor/x", + "kubectl get pods -o yaml", + "kubectl get pods -o json", + "docker ps --format x", + "bash -c 'ls -la'", + "bash -lc 'cargo test'", + "sh -c 'echo hi; ls'", + "bash -ec 'make test'", + "bash run.sh", + "bash run.sh --config conf.yml", + "bash run.sh -c conf.yml", + "sh -c 'grep -c foo a.txt'", + "bash -c 'echo .env'", + "bash -c 'echo hi' _ a.txt", + "ps -o pid,cmd", + "ps aux -o pid", + "du -sh target", + "ls target", + "ls node_modules", + "npm install", + "npm test", + "npx tsc -o dist", + "pytest -o log_cli=true", + "tsc --outDir dist", + "uv run pytest", + "python x.py -o out.txt", + "tar --exclude=node_modules -czf x.tgz .", + "tar --exclude node_modules -czf x.tgz .", + "grep --exclude-dir target foo -r .", + "grep --exclude-dir=target foo -r .", + "rg -g '!target' foo", + "ls 2>/dev/null", + "which cargo", + "env", + "printenv PATH", + "export X=1", + "time cargo check", + "timeout 60 cargo test", + "nohup ls &", + "echo '>' ", + "grep '>' a.txt", + "grep '>' a.txt | head", + "awk '{print $1}' a.txt", + "awk -F: '{print $1}' a.txt", + "cut -d: -f1 a.txt", + "xargs -n1 echo", + "cargo build > build.txt 2>&1", + ] { + assert_eq!(bash(p.path(), command), json!({}), "{command}"); + } +} +