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:
@@ -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)]);
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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:?}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -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"]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user