feat(fermata): the default secret list gets its formats; key files mask a private body or one long token

tfstate and its backup parse as JSON and stay stopped on Read. tfvars, credentials and
sh, bash, zsh, ini, conf, cfg parse as Env. Key files are OpaqueText: only a private PEM
block's body or a single token of 16 or more characters enters the manifest, past the
key filter, and such a file never fails, so a binary .key refuses nothing under deny.
A certificate-only PEM passes Read with no entries. A UTF-8 BOM is stripped in
parse_content.
This commit is contained in:
2026-11-07 01:14:07 +01:00
parent caa13ae654
commit 246f714a51
7 changed files with 579 additions and 22 deletions
+1
View File
@@ -213,6 +213,7 @@ pub(crate) fn default_file_patterns() -> Vec<String> {
"*.auto.tfvars",
"terraform.tfstate",
"*.tfstate",
"*.tfstate.backup",
".docker/config.json",
"config/master.key",
"config/credentials/*.key",
+17 -6
View File
@@ -109,9 +109,16 @@ fn is_source_named_secret(path: &Path) -> bool {
/// says nothing. A failed parse of text holding `{{` or `{%` is a template, whose values
/// live elsewhere: it passes, and the output carries the note about skipped files.
pub fn unmaskable_reason(path: &Path, format: Option<FileFormat>) -> Option<UnmaskableFile> {
if path.file_name().and_then(|n| n.to_str()).is_some_and(parser::is_terraform_state) {
return Some(UnmaskableFile::StatePositions);
}
let Some(format) = format.or_else(|| FileFormat::from_path(path)) else {
return (!is_source_named_secret(path)).then_some(UnmaskableFile::NoParser);
};
if format == FileFormat::OpaqueText {
let text = std::fs::read_to_string(path).unwrap_or_default();
return (!parser::is_certificate_only(&text)).then_some(UnmaskableFile::WholeFile);
}
// NUL is valid UTF-8: UTF-16 without a BOM would "parse" into keys no filter knows.
let Some(text) = std::fs::read_to_string(path).ok().filter(|text| !text.contains('\0')) else {
return Some(UnmaskableFile::ParseFailed);
@@ -123,7 +130,7 @@ pub fn unmaskable_reason(path: &Path, format: Option<FileFormat>) -> Option<Unma
};
let is_text = |line: &str| !line.is_empty() && !line.starts_with('#') && !(format == FileFormat::Properties && line.starts_with('!'));
let reads_every_line = matches!(format, FileFormat::Env | FileFormat::Properties);
(reads_every_line && entries.is_empty() && text.lines().map(str::trim).any(is_text)).then_some(UnmaskableFile::NothingFound)
(reads_every_line && entries.is_empty() && text.trim_start_matches('\u{feff}').lines().map(str::trim).any(is_text)).then_some(UnmaskableFile::NothingFound)
}
// ---------------------------------------------------------------------------
@@ -235,7 +242,7 @@ fn is_vim_swap(name: &str) -> bool {
///
/// Only names [`FileFormat::from_path`] gives a format reach the parser, in practice
/// `.env*`. `secrets.toml~` or emacs' `#secrets.toml#` have no format, so they are
/// opaque: never read, never a refusal, not redacted, like a `.pem`.
/// skipped: never read, never a refusal, not redacted, like a `.p12`.
fn is_editor_artefact(path: &Path) -> bool {
path.file_name()
.and_then(|n| n.to_str())
@@ -250,6 +257,7 @@ impl Manifest {
/// `root`.
pub fn build(config: &SecretsConfig, root: &Path) -> Result<Self, ManifestError> {
let mut entries = Vec::new();
let mut opaque = Vec::new();
let mut skipped = Vec::new();
// 1. Discover files matching `config.files.patterns`.
@@ -258,6 +266,7 @@ impl Manifest {
// 2. Parse each discovered file.
for path in &discovered {
match parse_discovered_file(path) {
Ok(file_entries) if FileFormat::from_path(path) == Some(FileFormat::OpaqueText) => opaque.extend(file_entries),
Ok(file_entries) => entries.extend(file_entries),
Err(_) if is_editor_artefact(path) => {}
Err(e) => match config.enforcement.on_parse_error {
@@ -276,8 +285,10 @@ impl Manifest {
}
}
// 3. Filter discovered entries by the effective key patterns.
// 3. Filter discovered entries by the effective key patterns. A key file's
// entries are keyed by its name, which no pattern is about.
entries = filter_by_key_patterns(entries, config);
entries.append(&mut opaque);
// 4. Process explicit `[[file]]` overrides — these bypass key filtering
// because the user declared them intentionally.
@@ -408,12 +419,12 @@ fn discover_files(patterns: &[String], root: &Path) -> Result<Vec<PathBuf>, Mani
// ---------------------------------------------------------------------------
/// Parse a single discovered file. Auto-detects format from extension.
/// Returns an empty `Vec` if the format cannot be determined (e.g. `.key`,
/// `.pem` — opaque/binary files).
/// Returns an empty `Vec` if the format cannot be determined (e.g. `.p12`,
/// `.netrc`).
fn parse_discovered_file(path: &Path) -> Result<Vec<SecretEntry>, ParseError> {
let format = match FileFormat::from_path(path) {
Some(fmt) => fmt,
None => return Ok(Vec::new()), // opaque file — skip
None => return Ok(Vec::new()), // no parser — skip
};
parser::parse_secret_file(path, Some(format), None)
}
+55 -9
View File
@@ -90,6 +90,13 @@ pub enum FileFormat {
PythonAssignments,
/// Java `.properties` files: `key=value` or `key: value`.
Properties,
/// Key files with no structure to read. See [`parse_opaque`].
OpaqueText,
}
/// Terraform state, and the backup of it that sits beside it.
pub(crate) fn is_terraform_state(name: &str) -> bool {
name.ends_with(".tfstate") || name.ends_with(".tfstate.backup")
}
impl FileFormat {
@@ -99,9 +106,15 @@ impl FileFormat {
let ext = path.extension().and_then(|e| e.to_str());
// .env, .env.local, .env.production, etc.
if name.starts_with(".env") || name.ends_with(".env") {
if name.starts_with(".env") || name.ends_with(".env") || name == "credentials" {
return Some(Self::Env);
}
if is_terraform_state(name) {
return Some(Self::Json);
}
if matches!(name, "id_rsa" | "id_ed25519" | "id_ecdsa") {
return Some(Self::OpaqueText);
}
match ext {
Some("toml") => Some(Self::Toml),
@@ -109,7 +122,10 @@ impl FileFormat {
Some("yaml" | "yml") => Some(Self::Yaml),
Some("py") => Some(Self::PythonAssignments),
Some("properties") => Some(Self::Properties),
// .key, .pem, etc. are binary/opaque — not parseable as key-value.
// The `Env` parser takes `key = "value"` and skips `[section]`.
Some("tfvars" | "sh" | "bash" | "zsh" | "ini" | "conf" | "cfg") => Some(Self::Env),
Some("key" | "pem") => Some(Self::OpaqueText),
// .netrc, .p12, etc. have no parser.
_ => None,
}
}
@@ -117,12 +133,13 @@ impl FileFormat {
/// Parse from the `format` string used in `.botsecrets` `[[file]]` overrides.
pub fn from_hint(hint: &str) -> Option<Self> {
match hint {
"env" | "dotenv" => Some(Self::Env),
"env" | "dotenv" | "tfvars" | "credentials" | "sh" | "bash" | "zsh" | "ini" | "conf" | "cfg" => Some(Self::Env),
"toml" => Some(Self::Toml),
"json" => Some(Self::Json),
"json" | "tfstate" => Some(Self::Json),
"yaml" | "yml" => Some(Self::Yaml),
"python-assignments" | "python" => Some(Self::PythonAssignments),
"properties" | "java-properties" => Some(Self::Properties),
"opaque" => Some(Self::OpaqueText),
_ => None,
}
}
@@ -142,11 +159,6 @@ pub fn parse_secret_file(
format: Option<FileFormat>,
key_filter: Option<&[String]>,
) -> Result<Vec<SecretEntry>, ParseError> {
let content = std::fs::read_to_string(path).map_err(|e| ParseError::Io {
path: path.to_path_buf(),
source: e,
})?;
let fmt = format
.or_else(|| FileFormat::from_path(path))
.ok_or_else(|| ParseError::Format {
@@ -154,6 +166,13 @@ pub fn parse_secret_file(
message: "cannot determine file format".into(),
})?;
let content = match std::fs::read_to_string(path) {
Ok(content) => content,
// A binary key file holds nothing to read, and must not refuse every output.
Err(_) if fmt == FileFormat::OpaqueText => String::new(),
Err(source) => return Err(ParseError::Io { path: path.to_path_buf(), source }),
};
let entries = parse_content(&content, fmt, path)?;
match key_filter {
@@ -168,6 +187,7 @@ pub fn parse_content(
format: FileFormat,
source: &Path,
) -> Result<Vec<SecretEntry>, ParseError> {
let content = content.strip_prefix('\u{feff}').unwrap_or(content);
match format {
FileFormat::Env => parse_env(content, source),
FileFormat::Toml => parse_toml(content, source),
@@ -175,6 +195,7 @@ pub fn parse_content(
FileFormat::Yaml => parse_yaml(content, source),
FileFormat::PythonAssignments => parse_python_assignments(content, source),
FileFormat::Properties => parse_properties(content, source),
FileFormat::OpaqueText => Ok(parse_opaque(content, source)),
}
}
@@ -236,6 +257,31 @@ fn parse_env(content: &str, source: &Path) -> Result<Vec<SecretEntry>, ParseErro
Ok(entries)
}
/// Shortest single token of a key file that counts as a secret: a word such as `localhost`
/// must not be masked in every output.
const MIN_OPAQUE_TOKEN_LEN: usize = 16;
/// The body of each private PEM block, or a file's one long token, keyed by the file's
/// name. Any other text gives nothing: a whole licence or a word is no value to mask
/// everywhere, and the read gate stops a Read of such a file.
fn parse_opaque(content: &str, source: &Path) -> Vec<SecretEntry> {
let block = regex::Regex::new(r"(?s)-----BEGIN [A-Z0-9 ]*PRIVATE KEY[A-Z0-9 ]*-----(.*?)(?:-----END|\z)").expect("valid regex");
let mut values: Vec<&str> = block.captures_iter(content).filter_map(|caps| Some(caps.get(1)?.as_str().trim())).collect();
let token = content.trim();
if token.chars().count() >= MIN_OPAQUE_TOKEN_LEN && !token.contains(char::is_whitespace) {
values.push(token);
}
let key = source.file_name().unwrap_or_default().to_string_lossy();
values.into_iter().map(|value| SecretEntry { key: key.to_string(), value: value.to_string(), source: source.to_path_buf() }).collect()
}
/// Whether `content` is PEM holding only certificates and public keys, which are no secret.
pub(crate) fn is_certificate_only(content: &str) -> bool {
let armor = regex::Regex::new(r"-----BEGIN ([A-Z0-9 ]+)-----").expect("valid regex");
let mut labels = armor.captures_iter(content).map(|caps| caps[1].to_string()).peekable();
labels.peek().is_some() && labels.all(|label| label.contains("CERTIFICATE") || label.contains("PUBLIC KEY"))
}
/// A quoted `.env` value: the text between the quotes, as written.
struct QuotedEnvValue {
quote: char,
+3 -3
View File
@@ -72,8 +72,8 @@ fn reason(out: &Value) -> &str {
out["hookSpecificOutput"]["permissionDecisionReason"].as_str().unwrap()
}
/// What each row of the secret list that stays stopped holds. `.tfvars`, `.aws/credentials`
/// and `secrets.sh` get a parser next and leave this list then, so they are not on it.
/// What each row of the secret list that stays stopped holds. Row by row, with what each
/// masks elsewhere: `tests/cli_hook_secret_formats.rs`.
fn unmaskable_files() -> Vec<(&'static str, Vec<u8>)> {
let private_pem = format!("-----BEGIN PRIVATE KEY-----\n{VALUE}\n-----END PRIVATE KEY-----\n").into_bytes();
vec![
@@ -95,7 +95,7 @@ fn unmaskable_files() -> Vec<(&'static str, Vec<u8>)> {
}
#[test]
fn a_read_of_a_file_with_no_parser_is_stopped_under_every_on_parse_error() {
fn a_read_of_a_file_it_cannot_mask_is_stopped_under_every_on_parse_error() {
for setting in SETTINGS {
for (name, content) in unmaskable_files() {
let p = project(setting, &[(name, &content)]);
+399
View File
@@ -0,0 +1,399 @@
//! 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);
}
/// 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");
}
+2 -1
View File
@@ -312,7 +312,7 @@ fn a_root_named_like_a_skipped_directory_is_still_read() {
#[test]
fn opaque_file_formats_are_skipped_gracefully() {
let dir = tempfile::tempdir().unwrap();
// .pem and .key files match default patterns but have no parseable format.
// A key file of plain words has nothing to mask: only a private block or one long token does.
fs::write(dir.path().join("server.key"), "binary-ish key data here\n").unwrap();
fs::write(
dir.path().join(".env"),
@@ -326,6 +326,7 @@ fn opaque_file_formats_are_skipped_gracefully() {
// Should not error, should still find the .env entry.
let keys: Vec<&str> = manifest.entries().iter().map(|e| e.key.as_str()).collect();
assert!(keys.contains(&"PASSWORD"));
assert!(!keys.contains(&"server.key"), "{keys:?}");
}
// ---------------------------------------------------------------------------
+102 -3
View File
@@ -1,7 +1,7 @@
//! Integration tests for the multi-format secret file parser.
use dirigent_fermata::core::secrets::parser::{
parse_content, parse_secret_file, FileFormat, SecretEntry,
parse_content, parse_secret_file, FileFormat, ParseError, SecretEntry,
};
use std::path::Path;
use tempfile::NamedTempFile;
@@ -270,8 +270,26 @@ fn format_from_path_extensions() {
#[test]
fn format_from_path_unknown() {
assert_eq!(FileFormat::from_path(p("a.key")), None);
assert_eq!(FileFormat::from_path(p("a.pem")), None);
for name in ["a.xyz", "a.p12", "a.pfx", ".netrc", ".htpasswd", "secrets.txt", "secrets.toml~", "tfstate", "id_rsa.pub"] {
assert_eq!(FileFormat::from_path(p(name)), None, "{name}");
}
}
#[test]
fn format_from_path_key_files_are_opaque() {
for name in ["a.key", "a.pem", "id_rsa", "id_ed25519", "id_ecdsa", "config/master.key"] {
assert_eq!(FileFormat::from_path(p(name)), Some(FileFormat::OpaqueText), "{name}");
}
}
#[test]
fn format_from_path_state_and_settings_files() {
for name in ["terraform.tfstate", "a.tfstate", "a.tfstate.backup"] {
assert_eq!(FileFormat::from_path(p(name)), Some(FileFormat::Json), "{name}");
}
for name in ["terraform.tfvars", "a.auto.tfvars", ".aws/credentials", "credentials", "secrets.sh", "secrets.bash", "secrets.zsh", "secrets.ini", "secrets.conf", "secrets.cfg"] {
assert_eq!(FileFormat::from_path(p(name)), Some(FileFormat::Env), "{name}");
}
}
// ---------------------------------------------------------------------------
@@ -290,6 +308,11 @@ fn format_from_hint() {
assert_eq!(FileFormat::from_hint("python"), Some(FileFormat::PythonAssignments));
assert_eq!(FileFormat::from_hint("properties"), Some(FileFormat::Properties));
assert_eq!(FileFormat::from_hint("java-properties"), Some(FileFormat::Properties));
for hint in ["tfvars", "credentials", "sh", "bash", "zsh", "ini", "conf", "cfg"] {
assert_eq!(FileFormat::from_hint(hint), Some(FileFormat::Env), "{hint}");
}
assert_eq!(FileFormat::from_hint("tfstate"), Some(FileFormat::Json));
assert_eq!(FileFormat::from_hint("opaque"), Some(FileFormat::OpaqueText));
assert_eq!(FileFormat::from_hint("unknown"), None);
}
@@ -424,3 +447,79 @@ fn a_format_error_names_the_line_and_never_quotes_it() {
assert!(!format!("{error:?}").contains(value), "{format:?}");
}
}
// ---------------------------------------------------------------------------
// Key files
// ---------------------------------------------------------------------------
fn opaque_values(content: &str) -> Vec<String> {
let entries = parse_content(content, FileFormat::OpaqueText, p("dir/server.key")).unwrap();
assert!(entries.iter().all(|e| e.key == "server.key"), "{entries:?}");
entries.into_iter().map(|e| e.value).collect()
}
#[test]
fn an_opaque_file_gives_a_private_block_body_or_one_long_token() {
let body = "FAKEbodyONE\nFAKEbodyTWO";
for label in ["PRIVATE KEY", "RSA PRIVATE KEY", "OPENSSH PRIVATE KEY", "ENCRYPTED PRIVATE KEY", "PGP PRIVATE KEY BLOCK"] {
assert_eq!(opaque_values(&format!("-----BEGIN {label}-----\n{body}\n-----END {label}-----\n")), [body], "{label}");
}
// Text before it, two blocks, a block nobody closed.
let two = format!("Bag Attributes\n-----BEGIN PRIVATE KEY-----\na-first-body\n-----END PRIVATE KEY-----\n-----BEGIN EC PRIVATE KEY-----\nb-second-body\n");
assert_eq!(opaque_values(&two), ["a-first-body", "b-second-body"]);
// The token starts at 16 characters, counted as characters.
assert_eq!(opaque_values("fake0123456789ab\n"), ["fake0123456789ab"]);
assert_eq!(opaque_values("äääääääääääääää\n"), Vec::<String>::new());
}
#[test]
fn an_opaque_file_gives_nothing_for_any_other_text() {
for content in [
"",
"localhost\n",
"fake0123456789a\n",
"two fake0123456789abcdef tokens\n",
"fake0123456789abcdef\nfake0123456789abcdef\n",
"-----BEGIN CERTIFICATE-----\nfake-certificate-body\n-----END CERTIFICATE-----\n",
"-----BEGIN PUBLIC KEY-----\nfake-public-body\n-----END PUBLIC KEY-----\n",
] {
assert_eq!(opaque_values(content), Vec::<String>::new(), "{content:?}");
}
}
/// Only an opaque file gets past a read that fails. `.env.gpg` bytes stay a failure.
#[test]
fn a_binary_opaque_file_is_empty_and_any_other_binary_file_fails() {
let dir = tempfile::tempdir().unwrap();
for name in ["a.key", "a.pem", "id_rsa"] {
let path = dir.path().join(name);
std::fs::write(&path, b"\x30\x82\xff\xfe\x00fake").unwrap();
assert_eq!(parse_secret_file(&path, None, None).unwrap(), vec![], "{name}");
}
for name in [".env.gpg", "credentials", "secrets.conf", "a.tfstate"] {
let path = dir.path().join(name);
std::fs::write(&path, b"\x85\x02\xff\xfe\x00fake").unwrap();
assert!(matches!(parse_secret_file(&path, None, None), Err(ParseError::Io { .. })), "{name}");
}
}
// ---------------------------------------------------------------------------
// A byte-order mark
// ---------------------------------------------------------------------------
#[test]
fn a_utf8_bom_is_stripped_for_every_format() {
for (format, content, key) in [
(FileFormat::Env, "\u{feff}API_KEY=fake-value", "API_KEY"),
(FileFormat::Toml, "\u{feff}api_key = \"fake-value\"", "api_key"),
(FileFormat::Json, "\u{feff}{\"api_key\": \"fake-value\"}", "api_key"),
(FileFormat::Yaml, "\u{feff}api_key: fake-value", "api_key"),
(FileFormat::PythonAssignments, "\u{feff}API_KEY = \"fake-value\"", "API_KEY"),
(FileFormat::Properties, "\u{feff}api_key=fake-value", "api_key"),
] {
let entries = parse_content(content, format, p("x")).unwrap();
assert!(entries.iter().any(|e| e.key == key && e.value == "fake-value"), "{format:?}: {entries:?}");
}
assert_eq!(opaque_values("\u{feff}fake0123456789ab\n"), ["fake0123456789ab"]);
}