feat(fermata): plain settings (true, 3600, AUTH_ENABLED) make no manifest entry; *AUTH* becomes three patterns

This commit is contained in:
2026-11-07 01:22:02 +01:00
parent 8aae653972
commit 6d2311d248
6 changed files with 200 additions and 18 deletions
+33 -15
View File
@@ -238,7 +238,9 @@ pub const BUILTIN_KEY_PATTERNS: &[&str] = &[
"*TOKEN*", "*TOKEN*",
"*ACCESS_KEY*", "*ACCESS_KEY*",
"*PRIVATE_KEY*", "*PRIVATE_KEY*",
"*AUTH*", "*AUTH",
"*AUTH[!O]*",
"*AUTHORIZATION*",
"*CREDENTIAL*", "*CREDENTIAL*",
"*CONNECTION_STRING*", "*CONNECTION_STRING*",
"*CONN_STR*", "*CONN_STR*",
@@ -618,25 +620,31 @@ impl SecretsConfig {
.collect(); .collect();
patterns.extend(self.keys.include.iter().cloned()); patterns.extend(self.keys.include.iter().cloned());
// Remove excluded patterns (exact string match). self.remove_excluded(&mut patterns);
if !self.keys.exclude.is_empty() {
let exclude_set: std::collections::HashSet<&str> =
self.keys.exclude.iter().map(|s| s.as_str()).collect();
patterns.retain(|p| !exclude_set.contains(p.as_str()));
}
patterns patterns
} }
/// Remove excluded patterns (exact string match). `*AUTH*` stands for the three
/// patterns that replaced it in the built-ins.
fn remove_excluded(&self, patterns: &mut Vec<String>) {
let mut exclude: Vec<&str> = self.keys.exclude.iter().map(String::as_str).collect();
if exclude.contains(&"*AUTH*") {
exclude.extend(["*AUTH", "*AUTH[!O]*", "*AUTHORIZATION*"]);
}
patterns.retain(|p| !exclude.contains(&p.as_str()));
}
/// The user's own `keys.include` patterns (minus `exclude`), compiled once: a key
/// they name is not judged by its last word.
pub fn explicit_key_matcher(&self) -> KeyMatcher {
let mut patterns = self.keys.include.clone();
self.remove_excluded(&mut patterns);
KeyMatcher::new(patterns)
}
/// The effective key-include patterns, compiled once. An invalid pattern is skipped. /// The effective key-include patterns, compiled once. An invalid pattern is skipped.
pub fn key_matcher(&self) -> KeyMatcher { pub fn key_matcher(&self) -> KeyMatcher {
let mut builder = GlobSetBuilder::new(); KeyMatcher::new(self.effective_key_includes())
for pat in self.effective_key_includes() {
if let Ok(glob) = Glob::new(&pat.to_ascii_uppercase()) {
builder.add(glob);
}
}
KeyMatcher(builder.build().unwrap_or_else(|_| GlobSet::empty()))
} }
/// Check whether `key` matches any of the effective key-include patterns. /// Check whether `key` matches any of the effective key-include patterns.
@@ -652,6 +660,16 @@ impl SecretsConfig {
pub struct KeyMatcher(GlobSet); pub struct KeyMatcher(GlobSet);
impl KeyMatcher { impl KeyMatcher {
fn new(patterns: Vec<String>) -> Self {
let mut builder = GlobSetBuilder::new();
for pat in patterns {
if let Ok(glob) = Glob::new(&pat.to_ascii_uppercase()) {
builder.add(glob);
}
}
Self(builder.build().unwrap_or_else(|_| GlobSet::empty()))
}
/// Whether `key` matches any pattern (both uppercased). /// Whether `key` matches any pattern (both uppercased).
pub fn is_match(&self, key: &str) -> bool { pub fn is_match(&self, key: &str) -> bool {
self.0.is_match(key.to_ascii_uppercase()) self.0.is_match(key.to_ascii_uppercase())
+4 -1
View File
@@ -12,6 +12,7 @@ use walkdir::WalkDir;
use super::config::{ParseErrorAction, SecretsConfig}; use super::config::{ParseErrorAction, SecretsConfig};
use super::parser::{self, FileFormat, ParseError, SecretEntry}; use super::parser::{self, FileFormat, ParseError, SecretEntry};
use super::value_class::is_plain_setting;
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Errors // Errors
@@ -288,6 +289,8 @@ impl Manifest {
// 3. Filter discovered entries by the effective key patterns. A key file's // 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 are keyed by its name, which no pattern is about.
entries = filter_by_key_patterns(entries, config); entries = filter_by_key_patterns(entries, config);
let explicit = config.explicit_key_matcher();
entries.retain(|e| !is_plain_setting(&e.key, &e.value, explicit.is_match(&e.key)));
entries.append(&mut opaque); entries.append(&mut opaque);
// 4. Process explicit `[[file]]` overrides — these bypass key filtering // 4. Process explicit `[[file]]` overrides — these bypass key filtering
@@ -310,7 +313,7 @@ impl Manifest {
}; };
match parser::parse_secret_file(&override_path, format, key_filter) { match parser::parse_secret_file(&override_path, format, key_filter) {
Ok(file_entries) => entries.extend(file_entries), Ok(file_entries) => entries.extend(file_entries.into_iter().filter(|e| !is_plain_setting(&e.key, &e.value, true))),
Err(e) if config.enforcement.on_parse_error == ParseErrorAction::Deny => { Err(e) if config.enforcement.on_parse_error == ParseErrorAction::Deny => {
return Err(e.into()); return Err(e.into());
} }
+1
View File
@@ -7,6 +7,7 @@ pub mod parser;
pub mod patterns; pub mod patterns;
pub mod redactor; pub mod redactor;
pub mod scanner; pub mod scanner;
pub mod value_class;
pub use config::{KeyMatcher, SecretsConfig}; pub use config::{KeyMatcher, SecretsConfig};
pub use manifest::{unmaskable_reason, Manifest, ManifestError, SecretFileSet, UnmaskableFile}; pub use manifest::{unmaskable_reason, Manifest, ManifestError, SecretFileSet, UnmaskableFile};
+50
View File
@@ -0,0 +1,50 @@
//! Values that are settings, not secrets: `AUTH_ENABLED=true`, `TOKEN_TTL=3600`.
//! A key pattern such as `*AUTH*` or `*TOKEN*` also hits these, and masking them
//! would write marks into source and break builds.
use std::sync::OnceLock;
use regex::Regex;
/// Value words that carry no secret, in any case.
const PLAIN_WORDS: &[&str] = &["true", "false", "yes", "no", "on", "off", "null", "none", "nil", "enabled", "disabled"];
/// Last words of a key that name a setting. Not `HEADER` or `URL`: those can hold the secret.
const SETTING_WORDS: &[&str] = &[
"ENABLED", "DISABLED", "TTL", "TIMEOUT", "EXPIRY", "EXPIRES", "EXPIRATION", "LIFETIME", "LENGTH", "SIZE", "COUNT",
"LIMIT", "MIN", "MAX", "RETRIES", "MS", "SECONDS", "MINUTES", "HOURS", "DAYS", "TYPE", "MODE", "ALGORITHM", "ALG",
"ISSUER", "AUDIENCE", "SCOPE", "PROVIDER", "VERSION", "PATH", "FILE", "DIR", "HOST", "PORT", "ENDPOINT", "METHOD",
"STRATEGY", "BACKEND", "DRIVER", "DOMAIN", "ROLE", "POLICY", "NAME", "USER", "USERNAME",
];
fn number() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^[+-]?\d+(\.\d+)?$").expect("static pattern"))
}
fn duration() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^\d+(ms|s|m|h|d|w)$").expect("static pattern"))
}
/// Whether `key = value` is a plain setting, so it makes no manifest entry.
///
/// 1. The value is a word of [`PLAIN_WORDS`], quoted or not, also when `explicit`.
/// 2. The value is a number under 6 characters or a duration, also when `explicit`.
/// 3. Unless `explicit`, the key's last word (split on `.`, `_`, `-`) is a [`SETTING_WORDS`] entry.
///
/// `explicit`: the user's own `keys.include` matched the key, or the value came from a `[[file]]` override.
pub fn is_plain_setting(key: &str, value: &str, explicit: bool) -> bool {
let value = value.trim().trim_matches(['"', '\'']).trim();
if PLAIN_WORDS.iter().any(|word| value.eq_ignore_ascii_case(word)) {
return true;
}
if (value.len() < 6 && number().is_match(value)) || duration().is_match(value) {
return true;
}
if explicit {
return false;
}
let last = key.rsplit(['.', '_', '-']).next().unwrap_or(key).to_ascii_uppercase();
SETTING_WORDS.contains(&last.as_str())
}
+4 -2
View File
@@ -6,6 +6,7 @@
//! stands in for its `safeParse`: a replacement that fails it would be dropped for //! stands in for its `safeParse`: a replacement that fails it would be dropped for
//! the original output. //! the original output.
use dirigent_fermata::core::secrets::value_class::is_plain_setting;
use assert_cmd::Command; use assert_cmd::Command;
use serde_json::{json, Value}; use serde_json::{json, Value};
use std::fs; use std::fs;
@@ -556,12 +557,13 @@ fn a_refusal_keeps_every_enum_value_of_every_tool() {
} }
/// A secret equal to an enum value: the value stays, the text beside it takes a mask, /// A secret equal to an enum value: the value stays, the text beside it takes a mask,
/// and nothing is refused. /// and nothing is refused. Values that are plain settings (`true`) make no secret, so
/// they are not tried.
#[test] #[test]
fn a_secret_equal_to_an_enum_value_keeps_the_value_in_every_tool() { fn a_secret_equal_to_an_enum_value_keeps_the_value_in_every_tool() {
for (tool, fields) in TOOL_ENUMS { for (tool, fields) in TOOL_ENUMS {
for (field, values) in *fields { for (field, values) in *fields {
for value in values.iter().filter(|v| v.len() >= 4) { for value in values.iter().filter(|v| v.len() >= 4 && !is_plain_setting("API_TOKEN", v, true)) {
let p = project(&format!("API_TOKEN={value}\n"), "[files]\npatterns = [\".env\"]\n"); let p = project(&format!("API_TOKEN={value}\n"), "[files]\npatterns = [\".env\"]\n");
let out = hook(&p, tool, &json!({ *field: value, "note": format!("x {value} y") })); let out = hook(&p, tool, &json!({ *field: value, "note": format!("x {value} y") }));
let output = updated(&out); let output = updated(&out);
+108
View File
@@ -0,0 +1,108 @@
//! `is_plain_setting` (three rules) and what the manifest keeps of the AUTH family.
use std::fs;
use dirigent_fermata::core::secrets::config::SecretsConfig;
use dirigent_fermata::core::secrets::manifest::Manifest;
use dirigent_fermata::core::secrets::value_class::is_plain_setting;
#[test]
fn rule_one_words_hold_also_when_explicit() {
for value in ["true", "FALSE", "Yes", "no", "on", "off", "null", "None", "nil", "enabled", "disabled", "\"true\"", "'off'", " true "] {
assert!(is_plain_setting("API_TOKEN", value, false), "{value}");
assert!(is_plain_setting("API_TOKEN", value, true), "{value} explicit");
}
assert!(!is_plain_setting("API_TOKEN", "truest", false));
}
#[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"] {
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"] {
assert!(!is_plain_setting("API_TOKEN", value, false), "{value}");
}
}
#[test]
fn rule_three_key_words_only_when_not_explicit() {
for key in ["AUTH_ENABLED", "TOKEN_TTL", "auth.timeout", "jwt-algorithm", "DB_HOST", "PASSWORD_POLICY", "SECRET_BACKEND", "AUTH_METHOD", "DB_USER", "TOKEN_PATH"] {
assert!(is_plain_setting(key, "abcdefgh", false), "{key}");
assert!(!is_plain_setting(key, "abcdefgh", true), "{key} explicit");
}
for key in ["AUTH_TOKEN", "DB_PASSWORD", "API_KEY", "AUTH_HEADER", "DB_URL", "ENABLED_TOKEN"] {
assert!(!is_plain_setting(key, "abcdefgh", false), "{key}");
}
}
fn keys_of(config: &SecretsConfig, env: &str) -> Vec<String> {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join(".env"), env).unwrap();
let manifest = Manifest::build(config, dir.path()).unwrap();
let mut keys: Vec<String> = manifest.entries().iter().map(|e| e.key.clone()).collect();
keys.dedup();
keys
}
const SETTINGS: &str = "AUTH_ENABLED=true\nAUTH_FLAG=\"true\"\nTOKEN_TTL=3600\nAUTH_TIMEOUT=15m\nPASSWORD_POLICY=strict\n\
AUTHOR=authorname\nAUTHORIZED_KEYS=ssh-keyname\n";
#[test]
fn settings_of_the_auth_family_are_not_in_the_manifest() {
assert_eq!(keys_of(&SecretsConfig::default(), SETTINGS), Vec::<String>::new());
}
#[test]
fn real_values_of_the_auth_family_stay() {
let env = "AUTH_TOKEN=tok_abcdefgh1234\nTS_AUTHKEY=tskey-abcdefgh\nDB_PASSWORD=postgres\nAUTH=hunter2hunter2\nAUTHORIZATION=Bearer-abcdefgh\n";
let keys = keys_of(&SecretsConfig::default(), env);
for key in ["AUTH_TOKEN", "TS_AUTHKEY", "DB_PASSWORD", "AUTH", "AUTHORIZATION"] {
assert!(keys.iter().any(|k| k == key), "{key} in {keys:?}");
}
}
#[test]
fn docker_auths_auth_stays() {
let dir = tempfile::tempdir().unwrap();
fs::create_dir(dir.path().join(".docker")).unwrap();
fs::write(dir.path().join(".docker/config.json"), r#"{"auths":{"registry.example.com":{"auth":"dXNlcjpwYXNzd29yZA=="}}}"#).unwrap();
let manifest = Manifest::build(&SecretsConfig::default(), dir.path()).unwrap();
assert!(manifest.entries().iter().any(|e| e.key.to_lowercase().ends_with(".auth")), "{:?}", manifest.entries());
}
#[test]
fn explicit_include_keeps_a_setting_word_key_but_not_a_rule_one_or_two_value() {
let config = SecretsConfig::from_toml("[keys]\ninclude = [\"MY_TTL\"]\n").unwrap();
assert_eq!(keys_of(&config, "MY_TTL=abcdefgh\n"), ["MY_TTL"]);
assert!(keys_of(&config, "MY_TTL=3600\n").is_empty());
assert!(keys_of(&config, "MY_TTL=true\n").is_empty());
}
#[test]
fn a_file_override_is_explicit() {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join("my.env"), "MY_TTL=abcdefgh\nOTHER=true\n").unwrap();
let config = SecretsConfig::from_toml("[[file]]\npath = \"my.env\"\nformat = \"env\"\n").unwrap();
let manifest = Manifest::build(&config, dir.path()).unwrap();
let keys: Vec<&str> = manifest.entries().iter().map(|e| e.key.as_str()).collect();
assert_eq!(keys, ["MY_TTL"]);
}
#[test]
fn excluding_auth_star_drops_all_three_patterns() {
let config = SecretsConfig::from_toml("[keys]\nexclude = [\"*AUTH*\"]\n").unwrap();
// AUTH_TOKEN stays: `*TOKEN*` still matches it.
assert_eq!(keys_of(&config, "AUTH_TOKEN=tok_abcdefgh1234\n"), ["AUTH_TOKEN"]);
assert!(keys_of(&config, "AUTH=hunter2hunter2\nTS_AUTHKEY=tskey-abcdefgh\nAUTHORIZATION=Bearer-abcdefgh\n").is_empty());
assert!(!config.effective_key_includes().iter().any(|p| ["*AUTH", "*AUTH[!O]*", "*AUTHORIZATION*"].contains(&p.as_str())));
}
#[test]
fn from_entries_skips_the_class() {
use dirigent_fermata::core::secrets::SecretEntry;
let entry = SecretEntry { key: "AUTH_ENABLED".into(), value: "enabled".into(), source: "scan".into() };
assert!(!Manifest::from_entries(vec![entry]).is_empty());
}