Files
fermata/tests/cli_bad_patterns.rs
T
g4borg 6bf602aa6a 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.
2026-11-07 02:00:45 +01:00

214 lines
8.2 KiB
Rust

//! 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());
}