Files
fermata/tests/cli_hook_secret_formats.rs
T
g4borg 8998540375 fix(fermata): a certificate file is judged by all of its text, not by its armor labels
API_TOKEN=x, a lowercase private block or a raw key beside a certificate block no longer
pass the read gate. Bag Attributes, subject= and issuer=, a CA bundle's comments and the
head of x509 -text stay allowed, so real PEMs keep passing.
2026-11-07 09:02:19 +01:00

454 lines
19 KiB
Rust

//! One test per row of the default secret list: what a Read and a printing command of the
//! file meet before the tool runs, and whether the file's value is masked in what a Read
//! and a command show, under the default and under `deny`. All values are fake.
use assert_cmd::Command;
use serde_json::{json, Value};
use std::fs;
use std::path::PathBuf;
use tempfile::TempDir;
const VALUE: &str = "fake-value-in-the-file";
const MASK: &str = "*****";
const SETTINGS: [&str; 2] = ["", "[enforcement]\non_parse_error = \"deny\"\n"];
const DENY: &str = SETTINGS[1];
struct Project {
dir: TempDir,
home: TempDir,
}
fn project(botsecrets: &str, name: &str, content: &[u8]) -> Project {
let dir = tempfile::tempdir().unwrap();
fs::create_dir(dir.path().join(".git")).unwrap();
fs::write(dir.path().join(".botsecrets"), botsecrets).unwrap();
let path = dir.path().join(name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, 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 path(&self, name: &str) -> PathBuf {
self.dir.path().join(name)
}
fn pre_read(&self, name: &str) -> Value {
self.hook("pre-tool-use", json!({"tool_name": "Read", "tool_input": {"file_path": self.path(name)}}))
}
fn pre_cat(&self, name: &str) -> Value {
self.hook("pre-tool-use", json!({"tool_name": "Bash", "tool_input": {"command": format!("cat {name}")}}))
}
/// What PostToolUse answers to a Read that showed `text`.
fn post_read(&self, name: &str, text: &str) -> Value {
let path = self.path(name);
self.hook(
"post-tool-use",
json!({"tool_name": "Read", "tool_input": {"file_path": path}, "tool_response": {"type": "text", "file": {"filePath": path, "content": text, "numLines": 1, "startLine": 1, "totalLines": 1}}}),
)
}
/// What PostToolUse answers to a command that printed `text`.
fn post_bash(&self, text: &str) -> Value {
self.hook(
"post-tool-use",
json!({"tool_name": "Bash", "tool_input": {"command": "echo $X"}, "tool_response": {"stdout": text, "stderr": "", "interrupted": false, "isImage": false}}),
)
}
}
#[derive(Clone, Copy, PartialEq)]
enum Read {
Passes,
Stopped,
}
#[derive(Clone, Copy, PartialEq)]
enum Elsewhere {
Masked,
NotMasked,
}
fn replaced(out: &Value) -> bool {
out["hookSpecificOutput"].get("updatedToolOutput").is_some()
}
/// The row's verdicts for each `(file, content)`, with `value` shown in the output,
/// under the default and under `deny`.
fn row(files: &[(&str, Vec<u8>)], value: &str, read: Read, elsewhere: Elsewhere) {
for setting in SETTINGS {
for (name, content) in files {
let p = project(setting, name, content);
let label = format!("{name} under {setting:?}");
for out in [p.pre_read(name), p.pre_cat(name)] {
match read {
Read::Passes => assert_eq!(out, json!({}), "{label}"),
Read::Stopped => {
assert_eq!(out["hookSpecificOutput"]["permissionDecision"], "deny", "{label}: {out}");
let reason = out["hookSpecificOutput"]["permissionDecisionReason"].as_str().unwrap();
assert!(reason.contains(name) && reason.contains("on_unparsed_read"), "{label}: {reason}");
assert!(!out.to_string().contains(value), "{label}: {out}");
}
}
}
for out in [p.post_read(name, &format!("x {value} y")), p.post_bash(&format!("x {value} y"))] {
match elsewhere {
Elsewhere::Masked => {
assert!(replaced(&out), "{label}: nothing masked: {out}");
assert!(!out.to_string().contains(value) && out.to_string().contains(MASK), "{label}: {out}");
}
Elsewhere::NotMasked => assert!(!replaced(&out), "{label}: {out}"),
}
}
}
}
}
fn text(name: &'static str, content: String) -> (&'static str, Vec<u8>) {
(name, content.into_bytes())
}
fn pem(label: &str, body: &str) -> String {
format!("-----BEGIN {label}-----\n{body}\n-----END {label}-----\n")
}
fn private_pem() -> String {
pem("PRIVATE KEY", VALUE)
}
fn state() -> String {
format!("{{\"outputs\":{{\"db_password\":{{\"value\":\"{VALUE}\",\"sensitive\":true}}}}}}")
}
const BINARY: &[u8] = b"\x30\x82\xff\xfe\x00fake";
// ---------------------------------------------------------------------------
// The rows
// ---------------------------------------------------------------------------
#[test]
fn the_formats_of_old_pass_and_mask_by_key() {
let files = [
text(".env", format!("API_TOKEN={VALUE}\n")),
text(".env.local", format!("API_TOKEN={VALUE}\n")),
text("prod.env", format!("API_TOKEN={VALUE}\n")),
text("secrets.toml", format!("api_token = \"{VALUE}\"\n")),
text("secrets.json", format!("{{\"api_token\": \"{VALUE}\"}}")),
text("secrets.yaml", format!("api_token: {VALUE}\n")),
text("secrets.py", format!("API_TOKEN = \"{VALUE}\"\n")),
text("secrets.properties", format!("api_token={VALUE}\n")),
text(".docker/config.json", format!("{{\"auths\": {{\"reg\": {{\"auth\": \"{VALUE}\"}}}}}}")),
text("service-account.json", format!("{{\"private_key\": \"{VALUE}\"}}")),
];
row(&files, VALUE, Read::Passes, Elsewhere::Masked);
}
#[test]
fn tfvars_pass_and_mask_by_key() {
let files = [
text("terraform.tfvars", format!("db_password = \"{VALUE}\"\n")),
text("prod.auto.tfvars", format!("db_password = \"{VALUE}\"\n")),
];
row(&files, VALUE, Read::Passes, Elsewhere::Masked);
}
#[test]
fn aws_credentials_pass_and_mask_by_key() {
let files = [text(".aws/credentials", format!("[default]\naws_secret_access_key = {VALUE}\n"))];
row(&files, VALUE, Read::Passes, Elsewhere::Masked);
}
/// No parser, by decision: the gate stops the direct routes, and the value is a named
/// limit anywhere else.
#[test]
fn netrc_and_htpasswd_are_stopped_and_not_masked_elsewhere() {
let files = [
text(".netrc", format!("machine x login u password {VALUE}\n")),
text(".htpasswd", format!("u:{VALUE}\n")),
];
row(&files, VALUE, Read::Stopped, Elsewhere::NotMasked);
}
/// A state file marks what is sensitive by position, so a key filter misses some of it:
/// parsed for what the keys show, and never read whole.
#[test]
fn terraform_state_is_stopped_and_masked_by_key_elsewhere() {
let files = [text("terraform.tfstate", state()), text("x.tfstate", state()), text("x.tfstate.backup", state())];
row(&files, VALUE, Read::Stopped, Elsewhere::Masked);
}
#[test]
fn a_state_files_value_under_no_secret_key_is_why_it_is_stopped() {
let unnamed = format!("{{\"outputs\":{{\"db\":{{\"value\":\"{VALUE}\",\"sensitive\":true}}}}}}");
row(&[text("terraform.tfstate", unnamed)], VALUE, Read::Stopped, Elsewhere::NotMasked);
}
#[test]
fn a_private_pem_is_stopped_and_its_body_masked_elsewhere() {
let files = [
text("server.pem", private_pem()),
text("server.key", pem("RSA PRIVATE KEY", VALUE)),
text("id_rsa", pem("OPENSSH PRIVATE KEY", VALUE)),
text("id_ed25519", pem("OPENSSH PRIVATE KEY", VALUE)),
text("id_ecdsa", pem("EC PRIVATE KEY", VALUE)),
text("config/master.key", private_pem()),
text("config/credentials/prod.key", private_pem()),
text("mixed.pem", format!("{}{}", pem("CERTIFICATE", "fake-certificate-body"), private_pem())),
];
row(&files, VALUE, Read::Stopped, Elsewhere::Masked);
}
#[test]
fn a_key_file_of_one_long_token_is_stopped_and_masked_elsewhere() {
let token = "fake0123456789abcdef";
row(&[text("config/master.key", format!("{token}\n"))], token, Read::Stopped, Elsewhere::Masked);
}
/// A word in a text `.key` must not be masked in every output: it is stopped, and adds nothing.
#[test]
fn a_text_key_file_is_stopped_and_adds_no_entry() {
for (content, shown) in [
("localhost\n", "localhost"),
("fake0123456789a\n", "fake0123456789a"),
("Fake licence text, with several words in it.\n", "several words"),
] {
row(&[text("server.key", content.to_string())], shown, Read::Stopped, Elsewhere::NotMasked);
}
}
#[test]
fn a_certificate_only_pem_passes_and_adds_no_entry() {
let files = [
text("ca.pem", pem("CERTIFICATE", VALUE)),
text("chain.pem", format!("{}{}", pem("CERTIFICATE", VALUE), pem("CERTIFICATE", "fake-second-body"))),
text("server.pub.key", pem("PUBLIC KEY", VALUE)),
];
row(&files, VALUE, Read::Passes, Elsewhere::NotMasked);
}
/// Certificates with the text real files carry around them are certificate-only. Text that
/// is none of that makes the file a secret again.
#[test]
fn a_certificate_file_is_judged_by_all_of_its_text() {
const CERT: &str = "-----BEGIN CERTIFICATE-----\nFAKEFAKEfakeFAKEfake\n-----END CERTIFICATE-----\n";
let denied = |out: Value| out["hookSpecificOutput"]["permissionDecision"] == "deny";
for content in [
CERT.to_string(),
CERT.replace('\n', "\r\n"),
format!("\n{CERT}\n{CERT}"),
format!("Bag Attributes\n friendlyName: fake-name\n localKeyID: 01 02 03\nsubject=/CN=fake\nissuer=/CN=fake\n{CERT}"),
format!("# Issuer: CN=Fake Root O=Fake\n# Label: \"Fake\"\n# SHA256 Fingerprint: 01:02\n{CERT}"),
format!("Certificate:\n Data:\n Version: 3 (0x2)\n{CERT}"),
] {
let p = project("", "server.pem", content.as_bytes());
assert!(!denied(p.pre_read("server.pem")), "{content:?}");
assert!(!denied(p.pre_cat("server.pem")), "{content:?}");
}
for content in [
format!("{CERT}API_TOKEN=fake-beside-a-cert\n"),
format!("API_TOKEN=fake-beside-a-cert\n{CERT}"),
format!("# API_TOKEN=fake-beside-a-cert\n{CERT}"),
format!("{CERT}fake-beside-a-cert\n"),
format!("{CERT}-----begin private key-----\nfake-beside-a-cert\n"),
format!("{CERT}-----BEGIN PRIVATE KEY-----\nfake-beside-a-cert\n-----END PRIVATE KEY-----\n"),
"# -----BEGIN CERTIFICATE-----\nfake-beside-a-cert\n".to_string(),
// A block that holds another, or never ends, is no certificate.
"-----BEGIN CERTIFICATE-----\n-----BEGIN PRIVATE KEY-----\nfake\n-----END PRIVATE KEY-----\n".to_string(),
"-----BEGIN CERTIFICATE-----\nfake\n".to_string(),
] {
let p = project("", "server.pem", content.as_bytes());
assert!(denied(p.pre_read("server.pem")), "{content:?}");
assert!(denied(p.pre_cat("server.pem")), "{content:?}");
}
}
/// Binary, whatever the name: stopped on Read, and under `deny` no refusal of everything else.
#[test]
fn a_binary_key_file_is_stopped_and_refuses_nothing() {
let files = [("server.key", BINARY.to_vec()), ("server.pem", BINARY.to_vec()), ("id_rsa", BINARY.to_vec())];
row(&files, VALUE, Read::Stopped, Elsewhere::NotMasked);
}
#[test]
fn p12_and_pfx_are_stopped_and_not_masked_elsewhere() {
let files = [("a.p12", BINARY.to_vec()), ("a.pfx", BINARY.to_vec())];
row(&files, VALUE, Read::Stopped, Elsewhere::NotMasked);
}
#[test]
fn source_named_like_a_secret_file_passes_and_masks_nothing() {
let files = [
text("secrets.rs", format!("const API_TOKEN: &str = \"{VALUE}\";\n")),
text("credentials.ts", format!("export const API_TOKEN = \"{VALUE}\";\n")),
];
row(&files, VALUE, Read::Passes, Elsewhere::NotMasked);
}
#[test]
fn secret_files_in_shell_and_ini_forms_pass_and_mask_by_key() {
let files = [
text("secrets.sh", format!("export API_TOKEN={VALUE}\n")),
text("secrets.bash", format!("export API_TOKEN=\"{VALUE}\"\n")),
text("secrets.zsh", format!("API_TOKEN='{VALUE}'\n")),
text("secrets.ini", format!("[main]\napi_token = {VALUE}\n")),
text("secrets.conf", format!("api_token = {VALUE}\n")),
text("secrets.cfg", format!("api_token={VALUE}\n")),
text("credentials.conf", format!("api_token = {VALUE}\n")),
];
row(&files, VALUE, Read::Passes, Elsewhere::Masked);
}
#[test]
fn any_other_secret_file_is_stopped_and_not_masked_elsewhere() {
let files = [
text("secrets.txt", format!("API_TOKEN={VALUE}\n")),
text("credentials.bak", format!("API_TOKEN={VALUE}\n")),
text("secrets.toml~", format!("api_token = \"{VALUE}\"\n")),
];
row(&files, VALUE, Read::Stopped, Elsewhere::NotMasked);
}
/// A format that fails to parse is stopped on Read. Elsewhere a note says so and the value
/// passes, and under `deny` the output is refused.
#[test]
fn a_file_with_a_format_that_fails_is_stopped_and_refuses_under_deny() {
for (name, content) in [
("secrets.toml", format!("api_token = \"{VALUE}\" broken [\n").into_bytes()),
("x.tfstate", format!("{{\"api_token\": \"{VALUE}\"").into_bytes()),
(".env.gpg", b"\x85\x02\xff\xfe\x00fake".to_vec()),
("secrets.conf", BINARY.to_vec()),
(".aws/credentials", BINARY.to_vec()),
("terraform.tfvars", BINARY.to_vec()),
] {
let p = project("", name, &content);
for out in [p.pre_read(name), p.pre_cat(name)] {
assert_eq!(out["hookSpecificOutput"]["permissionDecision"], "deny", "{name}: {out}");
}
let out = p.post_bash("output");
assert!(!replaced(&out), "{name}: {out}");
assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains(name), "{name}: {out}");
let p = project(DENY, name, &content);
for out in [p.pre_read(name), p.pre_cat(name)] {
assert_eq!(out["hookSpecificOutput"]["permissionDecision"], "deny", "{name}: {out}");
}
let out = p.post_bash("output");
assert!(out["hookSpecificOutput"]["updatedToolOutput"]["stdout"].as_str().unwrap().contains("withheld"), "{name}: {out}");
assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains(name), "{name}: {out}");
}
}
#[test]
fn a_file_with_lines_and_no_value_is_stopped() {
let files = [
text(".env", format!("{VALUE} with no sign in it\n")),
text("secrets.conf", format!("{VALUE} with no sign in it\n")),
text(".aws/credentials", "[default]\n".to_string()),
];
row(&files, VALUE, Read::Stopped, Elsewhere::NotMasked);
}
// ---------------------------------------------------------------------------
// Inside the rows
// ---------------------------------------------------------------------------
#[test]
fn a_utf8_bom_is_no_part_of_the_file() {
let bom = |text: String| [b"\xef\xbb\xbf".as_slice(), text.as_bytes()].concat();
let files = [
("secrets.json", bom(format!("{{\"api_token\": \"{VALUE}\"}}"))),
(".env", bom(format!("API_TOKEN={VALUE}\n"))),
("secrets.yaml", bom(format!("api_token: {VALUE}\n"))),
("secrets.toml", bom(format!("api_token = \"{VALUE}\"\n"))),
];
row(&files, VALUE, Read::Passes, Elsewhere::Masked);
// A mark and a comment are no line a value could be missing from.
let p = project("", ".env", &bom("# only a comment\n".to_string()));
assert_eq!(p.pre_read(".env"), json!({}));
}
const LINE_1: &str = "FAKEFAKEpemBODYlineONExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const LINE_2: &str = "FAKEFAKEpemBODYlineTWOyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
#[test]
fn a_pem_body_is_masked_whole_and_by_line_and_its_armor_stays() {
for end in ["\n", "\r\n"] {
let body = format!("{LINE_1}{end}{LINE_2}");
let content = format!("-----BEGIN PRIVATE KEY-----{end}{body}{end}-----END PRIVATE KEY-----{end}");
let p = project("", "id_rsa", content.as_bytes());
let out = p.post_bash(&content);
let shown = out["hookSpecificOutput"]["updatedToolOutput"]["stdout"].as_str().unwrap();
assert_eq!(shown, format!("-----BEGIN PRIVATE KEY-----{end}{MASK}{end}-----END PRIVATE KEY-----{end}"));
let out = p.post_bash(&format!("3: {LINE_2}\n"));
assert_eq!(out["hookSpecificOutput"]["updatedToolOutput"]["stdout"], "3: *****\n");
}
}
/// Only the private block is a secret: a chain's certificate in the same file stays readable.
#[test]
fn a_certificate_beside_a_private_block_is_not_masked() {
let content = format!("{}{}", pem("CERTIFICATE", "fake-certificate-body"), private_pem());
let p = project("", "both.pem", content.as_bytes());
assert!(!replaced(&p.post_bash("fake-certificate-body")));
}
/// A key file's entry has no key name a filter would know, and a project that filters
/// keys narrowly still gets it.
#[test]
fn an_opaque_entry_passes_the_key_filter() {
let p = project("[keys]\nexclude = [\"*PRIVATE_KEY*\", \"*SECRET*\"]\n", "server.key", private_pem().as_bytes());
assert!(replaced(&p.post_bash(VALUE)));
}
/// An override can name the format of a file with an unknown name.
#[test]
fn a_file_override_can_say_opaque() {
let config = "[files]\npatterns = []\n[[file]]\npath = \"deploy.bin\"\nformat = \"opaque\"\n";
let p = project(config, "deploy.bin", private_pem().as_bytes());
assert!(replaced(&p.post_bash(VALUE)));
fs::write(p.path("deploy.bin"), BINARY).unwrap();
assert!(!replaced(&p.post_bash(VALUE)));
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");
}