fix(fermata): what a command writes meets the rules, also when it is not there yet

cp a.txt vendor/new, touch .env, echo x > .env and curl -o vendor/new are stopped under a
rule. Verb::Writes covers redirect targets, a list of writing verbs, sed -i, dd of= and
the value of -o. It meets [policy.write] as well as .botignore and [policy.read], and not
the read gate: writing a file reveals nothing.
This commit is contained in:
2026-11-07 09:00:45 +01:00
parent 8dd5a81bc8
commit bc984b8625
5 changed files with 167 additions and 45 deletions
+39 -19
View File
@@ -12,9 +12,9 @@ use std::path::{Component, Path, PathBuf};
pub enum Dialect { Posix, PowerShell }
/// What a command does with the paths it names: shows their text, shows at most a name
/// or a size, or anything else.
/// or a size, writes or removes them, or anything else.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verb { Prints, Metadata, Other }
pub enum Verb { Prints, Metadata, Writes, Other }
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandPath {
@@ -33,6 +33,9 @@ const GIT_METADATA: &[&str] = &["status", "check-ignore", "ls-files", "commit"];
const PREFIXES: &[&str] = &[
"sudo", "env", "time", "nohup", "command", "exec", "timeout", "nice", "ionice", "stdbuf", "xargs", "busybox", "if", "elif", "then", "else", "while", "until", "do", "!", "{",
];
/// Verbs that write or remove every path they name, and verbs that write only the last.
const WRITES_ALL: &[&str] = &["mv", "rm", "rmdir", "touch", "mkdir", "tee", "truncate", "shred", "set-content", "add-content", "out-file", "new-item", "remove-item", "move-item"];
const WRITES_LAST: &[&str] = &["cp", "ln", "install", "rsync", "scp", "copy-item"];
/// Shells that take a command line by a flag: see [`takes_a_line`].
const SHELLS: &[&str] = &["bash", "sh", "zsh", "dash", "ksh", "mksh", "ash", "yash", "fish", "csh", "tcsh", "pwsh", "powershell", "cmd"];
/// Verbs whose first word is a pattern, unless `-e` or `-f` gives it.
@@ -157,16 +160,17 @@ pub fn command_paths(command: &str, dialect: Dialect, cwd: &Path, home: Option<&
}
match (word, rest.next()) {
("<", Some(target)) if run == 1 => inputs.push(target),
(">", Some(target)) => outputs.push(target),
// `2>&1` names a file descriptor.
(">", Some(target)) if !target.chars().all(|c| c.is_ascii_digit()) => outputs.push(target),
_ => {}
}
}
let (verb, named, inner) = named_words(&args);
let (verb, named, written, inner) = named_words(&args);
found.extend(inner.iter().flat_map(|inner| command_paths(inner, dialect, cwd, home)));
let read = inputs.iter().map(|word| (*word, Verb::Prints, true));
let written = outputs.iter().map(|word| (*word, verb, true));
for (word, verb, redirect) in read.chain(named.iter().map(|word| (*word, verb, false))).chain(written) {
found.extend(word_paths(word, redirect, cwd, home).into_iter().map(|path| CommandPath { path, verb }));
let written = outputs.iter().chain(&written).map(|word| (*word, Verb::Writes, true));
for (word, verb, new) in read.chain(named.iter().map(|word| (*word, verb, false))).chain(written) {
found.extend(word_paths(word, new, cwd, home).into_iter().map(|path| CommandPath { path, verb }));
}
}
found
@@ -180,12 +184,12 @@ fn takes_a_line(flag: &str) -> bool {
}
/// The segment's verb class, the words that may name a path (not the verb word, a flag or
/// a pattern position; `--file=.env` and `X=.env` name what follows the `=`) and the
/// command line it hands to a shell. A verb goes by its file name. A wrapper goes by its
/// a pattern position; `--file=.env` and `X=.env` name what follows the `=`), the words it
/// writes to and the command line it hands to a shell. A verb goes by its file name. A wrapper goes by its
/// file name only as a bare word or an absolute path: `./do` is a project's script, and
/// `/home/me/env` may be one, so the word after an absolute path still counts as a path.
/// A metadata verb has to be a bare word: `./test .env` may do anything with the file.
fn named_words<'a>(args: &[&'a str]) -> (Verb, Vec<&'a str>, Option<&'a str>) {
fn named_words<'a>(args: &[&'a str]) -> (Verb, Vec<&'a str>, Vec<&'a str>, Option<&'a str>) {
let base = |word: &str| Path::new(word).file_name().and_then(|n| n.to_str()).unwrap_or(word).to_ascii_lowercase().trim_end_matches(".exe").to_string();
let is_name = |name: &str| !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_');
let mut named = Vec::new();
@@ -204,7 +208,7 @@ fn named_words<'a>(args: &[&'a str]) -> (Verb, Vec<&'a str>, Option<&'a str>) {
at += 1;
}
let Some(verb_word) = args.get(at) else {
return (Verb::Other, named, None);
return (Verb::Other, named, Vec::new(), None);
};
if by_path {
named.push(verb_word);
@@ -223,10 +227,16 @@ fn named_words<'a>(args: &[&'a str]) -> (Verb, Vec<&'a str>, Option<&'a str>) {
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 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));
let is_output = !pattern_first && matches!(previous, "-o" | "--output") || (name == "wget" && previous == "-O");
previous = word;
if is_pattern {
if is_output {
written.push(word);
}
if is_pattern || is_output {
continue;
}
if !word.starts_with('-') {
@@ -236,17 +246,27 @@ fn named_words<'a>(args: &[&'a str]) -> (Verb, Vec<&'a str>, Option<&'a str>) {
}
named.push(word);
}
named.extend(word.split_once('=').map(|(_, value)| value));
match word.split_once('=') {
Some(("--output", value)) => written.push(value),
Some(("of", value)) if name == "dd" => written.push(value),
Some((_, value)) => named.push(value),
None => {}
}
(verb, named, inner)
}
if WRITES_ALL.contains(&name.as_str()) || (name == "sed" && rest.iter().any(|w| w.starts_with("-i"))) {
written.extend(named.drain(from..));
} else if WRITES_LAST.contains(&name.as_str()) && named.len() > from {
written.extend(named.pop());
}
(verb, named, written, inner)
}
/// The paths one word names. A word counts when it is a file or a `redirect`'s target,
/// or when it holds a separator and is there or may be once the shell expands it: a
/// The paths one word names. A word counts when it is a file or `new`, a file the command
/// makes, or when it holds a separator and is there or may be once the shell expands it: a
/// package, a branch and a host's path hold one too. Text with spaces and an address
/// count only as a real file. A glob reaches the files of its one directory and, as in
/// a shell, a dotfile only when it starts with `.`.
fn word_paths(word: &str, redirect: bool, cwd: &Path, home: Option<&Path>) -> Vec<PathBuf> {
fn word_paths(word: &str, new: bool, cwd: &Path, home: Option<&Path>) -> Vec<PathBuf> {
let expanded = home
.and_then(|home| Some(home.join(["~/", "$HOME/", "${HOME}/"].iter().find_map(|p| word.strip_prefix(p))?)))
.map_or_else(|| word.to_string(), |path| path.to_string_lossy().into_owned());
@@ -266,6 +286,6 @@ fn word_paths(word: &str, redirect: bool, cwd: &Path, home: Option<&Path>) -> Ve
}
let path = absolute(Path::new(&expanded), cwd);
let prose = word.contains(char::is_whitespace) || word.contains("://");
let reached = redirect || path.exists() || word.contains(['$', '*', '?']);
if path.is_file() || (word.contains('/') && !prose && reached) { vec![path] } else { Vec::new() }
let reached = path.exists() || word.contains(['$', '*', '?']);
if path.is_file() || (!prose && (new || (word.contains('/') && reached))) { vec![path] } else { Vec::new() }
}
+6 -2
View File
@@ -102,14 +102,18 @@ impl Policy {
}
/// What the paths `command` names meet, by verb class: nothing for a verb that only
/// names them, the read rules for any other, and the read gate for one that prints them.
/// `[policy.write]` does not reach commands.
/// names them, the read rules for any other, the read gate for one that prints them,
/// and the write rules and the read rules for one that writes them.
pub fn check_command_paths(&self, command: &str, dialect: Dialect, cwd: &Path) -> Result<Decision, PolicyError> {
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);
for named in command_paths(command, dialect, cwd, home.as_deref()) {
let decision = match named.verb {
Verb::Prints => self.check(Op::Read, &named.path)?,
Verb::Other => self.check_path_rules(Op::Read, &named.path)?,
Verb::Writes => match self.check_path_rules(Op::Write, &named.path)? {
Decision::Allow => self.check_path_rules(Op::Read, &named.path)?,
stopped => stopped,
},
Verb::Metadata => Decision::Allow,
};
if decision.is_blocking() {
+71 -3
View File
@@ -103,12 +103,80 @@ fn a_bad_command_rule_keeps_the_path_rule() {
assert_eq!(bash(p.path(), "ls"), json!({}));
}
/// `[policy.write]` does not reach commands.
/// `[policy.write]` meets what a command writes, and not what it only reads.
#[test]
fn a_write_rule_is_not_applied_to_a_command() {
let p = project(&[(".botsecrets", "[policy.write]\npatterns = [\"a.txt\"]\n"), ("a.txt", "x")]);
fn a_write_rule_meets_what_a_command_writes_and_nothing_else() {
let p = project(&[(".botsecrets", "[policy.write]\npatterns = [\"a.txt\", \"vendor/**\"]\n"), ("a.txt", "x")]);
assert_eq!(bash(p.path(), "cat a.txt"), json!({}));
assert_eq!(bash(p.path(), "cp a.txt b.txt"), json!({}));
assert_eq!(bash(p.path(), "ls a.txt"), json!({}));
for command in ["cp b.txt a.txt", "mv a.txt b.txt", "rm a.txt", "touch a.txt", "tee a.txt", "echo x > a.txt", "echo x >> a.txt", "sed -i s/a/b/ a.txt", "curl -o vendor/new https://example.invalid/x", "touch vendor/new"] {
assert_eq!(verdict(&bash(p.path(), command)), "deny", "{command}");
}
}
/// A file a command is about to make is not there yet, and it still meets the rule.
#[test]
fn a_command_that_writes_into_a_ruled_path_meets_the_rule() {
let p = project(&[(".botignore", "vendor/\n.env\n"), ("vendor/a", "x"), ("a.txt", "x")]);
for command in [
"cp a.txt vendor/new",
"cp -r a.txt ./vendor/new",
"mv a.txt vendor/new",
"ln -s a.txt vendor/new",
"install a.txt vendor/new",
"rsync a.txt vendor/new",
"scp a.txt vendor/new",
"touch vendor/new",
"mkdir vendor/new",
"mkdir -p vendor/x/y",
"rm vendor/new",
"tee vendor/new",
"truncate -s 0 vendor/new",
"dd if=a.txt of=vendor/new",
"sudo cp a.txt vendor/new",
"bash -c 'touch vendor/new'",
"curl -o vendor/new https://example.invalid/x",
"curl --output vendor/new https://example.invalid/x",
"curl --output=vendor/new https://example.invalid/x",
"gcc -o vendor/new a.c",
"wget -O vendor/new https://example.invalid/x",
// A file that is not there yet and has no separator.
"touch .env",
"cp a.txt .env",
"echo x > .env",
"echo x >> .env",
"cat a.txt > .env",
] {
assert_eq!(verdict(&bash(p.path(), command)), "deny", "{command}");
}
assert_eq!(verdict(&tool(p.path(), "PowerShell", "Set-Content vendor\\new x")), "deny");
assert_eq!(verdict(&tool(p.path(), "PowerShell", "Copy-Item a.txt vendor\\new")), "deny");
for command in [
// The rule's name in a place that writes nothing.
"composer require vendor/package",
"curl example.invalid/vendor/a",
"curl -O example.invalid/vendor/a",
"cp a.txt b.txt",
"touch b.txt",
"mkdir other",
"echo .env > b.txt",
"echo x > /dev/null",
"echo x 2>&1",
"grep -o vendor/x a.txt",
] {
assert_eq!(bash(p.path(), command), json!({}), "{command}");
}
}
/// A write is no read: the read gate does not stop it, only a rule does.
#[test]
fn a_write_over_a_file_it_cannot_mask_does_not_meet_the_read_gate() {
let p = project(&[("id_rsa", PEM), ("a.txt", "x")]);
for command in ["cp a.txt id_rsa", "echo x > id_rsa", "rm id_rsa", "touch id_rsa"] {
assert_eq!(bash(p.path(), command), json!({}), "{command}");
}
assert_eq!(verdict(&bash(p.path(), "cp id_rsa a.txt")), "none", "the source of a copy is no printing verb's");
}
#[test]
+46 -17
View File
@@ -6,7 +6,7 @@ use std::fs;
use std::path::{Path, PathBuf};
use tempfile::TempDir;
use Dialect::{Posix, PowerShell};
use Verb::{Metadata, Other, Prints};
use Verb::{Metadata, Other, Prints, Writes};
/// A project and a home of their own.
struct Fixture {
@@ -117,18 +117,51 @@ fn a_word_after_an_input_redirect_is_a_printing_path_and_never_the_verb() {
("ls < .env", ENV_PRINTS),
("<.env cat a.txt", &[(".env", Prints), ("a.txt", Prints)]),
// The verb is still the one after the redirect.
("<.env rm a.txt", &[(".env", Prints), ("a.txt", Other)]),
("<.env rm a.txt", &[(".env", Prints), ("a.txt", Writes)]),
]);
}
#[test]
fn a_word_after_an_output_redirect_takes_the_verb_of_its_segment() {
fn a_word_after_an_output_redirect_is_written() {
check(Posix, &[
("echo .env >> .gitignore", &[(".env", Metadata), (".gitignore", Metadata)]),
("cat a.txt > .env", &[("a.txt", Prints), (".env", Prints)]),
(">a.txt cat .env", &[(".env", Prints), ("a.txt", Prints)]),
("npm test > .env", ENV_OTHER),
("cat .env 2>/dev/null", &[(".env", Prints), ("/dev/null", Prints)]),
("echo .env >> .gitignore", &[(".env", Metadata), (".gitignore", Writes)]),
("cat a.txt > .env", &[("a.txt", Prints), (".env", Writes)]),
(">a.txt cat .env", &[(".env", Prints), ("a.txt", Writes)]),
("npm test > .env", &[(".env", Writes)]),
("cat .env 2>/dev/null", &[(".env", Prints), ("/dev/null", Writes)]),
// Not there yet, and no separator.
("tool > new", &[("new", Writes)]),
// A file descriptor is no file.
("tool 2>&1", NOTHING),
]);
}
#[test]
fn a_writing_verb_writes_its_target() {
check(Posix, &[
("cp .env a-copy", &[(".env", Other), ("a-copy", Writes)]),
("cp -r .env build/new", &[(".env", Other), ("build/new", Writes)]),
("ln -s a.txt new", &[("a.txt", Other), ("new", Writes)]),
("mv .env a-copy", &[(".env", Writes), ("a-copy", Writes)]),
("rm .env", &[(".env", Writes)]),
("touch new", &[("new", Writes)]),
("mkdir -p build/x/y", &[("build/x/y", Writes)]),
("tee -a new", &[("new", Writes)]),
("dd if=.env of=new", &[(".env", Other), ("new", Writes)]),
("sed -i s/a/b/ .env", &[(".env", Writes)]),
("sed -i.bak s/a/b/ .env", &[(".env", Writes)]),
("curl -o new https://example.invalid/x", &[("new", Writes)]),
("curl --output=new https://example.invalid/x", &[("new", Writes)]),
("wget -O new https://example.invalid/x", &[("new", Writes)]),
("sort -o new a.txt", &[("a.txt", Prints), ("new", Writes)]),
// These print: `-o` is a flag of its own, and the first word stays the pattern.
("grep -o build/new a.txt", &[("a.txt", Prints)]),
("curl -O example.invalid/build/new", NOTHING),
]);
check(PowerShell, &[
("Remove-Item .\\.env", &[(".env", Writes)]),
("Set-Content new x", &[("new", Writes), ("x", Writes)]),
("Copy-Item a.txt new", &[("a.txt", Other), ("new", Writes)]),
]);
}
@@ -145,7 +178,7 @@ fn a_word_is_a_path_when_it_is_a_file_or_holds_a_separator_and_is_there() {
// What is not there is a package, a branch or a host's path, unless a redirect
// writes it or the shell may expand it.
("cat build/new", NOTHING),
("tool > build/new", &[("build/new", Other)]),
("tool > build/new", &[("build/new", Writes)]),
("tool < build/new", &[("build/new", Prints)]),
("tool $X/new", &[("$X/new", Other)]),
("cat vendor/", &[("vendor", Prints)]),
@@ -245,9 +278,6 @@ fn everything_else_is_other() {
("source .env", ENV_OTHER),
(". .env", ENV_OTHER),
("source .env && npm test", ENV_OTHER),
("cp .env a-copy", ENV_OTHER),
("mv .env a-copy", ENV_OTHER),
("rm .env", ENV_OTHER),
("python .env", ENV_OTHER),
("docker cp .env c:/x", ENV_OTHER),
("git add .env", ENV_OTHER),
@@ -392,10 +422,10 @@ fn a_comment_names_nothing() {
#[test]
fn a_heredoc_body_is_text() {
check(Posix, &[
("cat > a.txt <<EOF\nsee cat .env and vendor/a\nEOF\nls", &[("a.txt", Prints)]),
("cat > a.txt <<'EOF'\nsee cat .env\nEOF", &[("a.txt", Prints)]),
("cat > a.txt << \"EOF\"\nsee cat .env\nEOF\ncat .env", &[("a.txt", Prints), (".env", Prints)]),
("cat > a.txt <<-EOF\n\tsee cat .env\n\tEOF\ncat .env", &[("a.txt", Prints), (".env", Prints)]),
("cat > a.txt <<EOF\nsee cat .env and vendor/a\nEOF\nls", &[("a.txt", Writes)]),
("cat > a.txt <<'EOF'\nsee cat .env\nEOF", &[("a.txt", Writes)]),
("cat > a.txt << \"EOF\"\nsee cat .env\nEOF\ncat .env", &[("a.txt", Writes), (".env", Prints)]),
("cat > a.txt <<-EOF\n\tsee cat .env\n\tEOF\ncat .env", &[("a.txt", Writes), (".env", Prints)]),
("git commit -F - <<EOF\nfix .env loading\nEOF", NOTHING),
// Never closed: no heredoc, and what follows runs. Under-denial is the worse error.
("cat <<EOF\ncat .env", ENV_PRINTS),
@@ -439,7 +469,6 @@ fn powershell_paths_keep_their_backslashes() {
("gc `.env", ENV_PRINTS),
("gc \"`.env\"", ENV_PRINTS),
("gc my` dir\\.env", &[("my dir/.env", Prints)]),
("Remove-Item .\\.env", ENV_OTHER),
]);
}
+5 -4
View File
@@ -441,14 +441,15 @@ fn a_flag_value_as_verb_and_a_glob_over_directories_pass_the_read_gate() {
}
}
/// A file a command is about to make is not there to check, so a rule on its directory
/// does not stop it. A redirect's target is checked.
/// Writing verbs are a list. A new file named to any other program is not there to check,
/// and a flag's value is one word among others.
#[test]
fn a_new_file_a_command_names_is_not_checked_unless_a_redirect_writes_it() {
fn a_new_file_named_to_a_verb_off_the_writing_list_is_not_checked() {
let p = project(&[(".botignore", b"vendor/\n"), ("vendor/a", b"x"), ("a.txt", b"x")]);
for command in ["cp a.txt vendor/new", "touch vendor/new", "mkdir vendor/new"] {
for command in ["git clone https://example.invalid/x vendor/new", "unzip a.zip -d vendor/new", "python make.py vendor/new", "cp --target-directory=vendor/new a.txt"] {
assert!(passes(&p.bash(command)), "{command}");
}
assert!(denied(&p.bash("cp a.txt vendor/new")), "control");
assert!(denied(&p.bash("tool > vendor/new")), "control");
}