use std::collections::HashMap;
use crate::json::JsonValue;
const SENSITIVE_SUBSTRINGS: &[&str] = &[
"password",
"passwd",
"secret",
"token",
"authorization",
"api_key",
"apikey",
"api-key",
"private_key",
"credential",
"credit_card",
"card_number",
"cvv",
"ssn",
];
pub fn is_sensitive_key(key: &str) -> bool {
let lower = key.to_ascii_lowercase();
SENSITIVE_SUBSTRINGS
.iter()
.any(|needle| lower.contains(needle))
}
pub fn redact_value(s: &str) -> String {
let chars: Vec<char> = s.chars().collect();
match chars.len() {
0 => "****".to_string(),
n @ 1..=2 => "*".repeat(n),
n @ 3..=6 => format!("{}{}", chars[0], "*".repeat(n - 1)),
n => format!("{}{}{}", chars[0], "*".repeat(n - 2), chars[n - 1]),
}
}
pub(crate) fn redact_field(key: &str, value: JsonValue) -> JsonValue {
if !is_sensitive_key(key) {
return value;
}
let plain = match &value {
JsonValue::String(s) => s.clone(),
other => other.to_string(),
};
JsonValue::String(redact_value(&plain))
}
pub fn redact_map<V>(map: &HashMap<String, V>) -> HashMap<String, JsonValue>
where
V: Into<JsonValue> + Clone,
{
map.iter()
.map(|(key, value)| {
let value = redact_field(key, value.clone().into());
(key.clone(), value)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::json;
#[test]
fn detects_sensitive_keys() {
for key in [
"password",
"Password",
"user_password",
"secret",
"access_token",
"refresh_token",
"Authorization",
"api_key",
"X-Api-Key",
"credit_card",
"ssn",
] {
assert!(is_sensitive_key(key), "expected {key} to be sensitive");
}
}
#[test]
fn ignores_ordinary_keys() {
for key in ["username", "email", "host", "port", ""] {
assert!(!is_sensitive_key(key), "expected {key} to be safe");
}
}
#[test]
fn masks_by_length() {
assert_eq!(redact_value(""), "****");
assert_eq!(redact_value("a"), "*");
assert_eq!(redact_value("ab"), "**");
assert_eq!(redact_value("abc"), "a**");
assert_eq!(redact_value("abcdef"), "a*****");
assert_eq!(redact_value("abcdefg"), "a*****g");
assert_eq!(redact_value("abcdefghij"), "a********j");
}
#[test]
fn masking_is_utf8_safe() {
assert_eq!(redact_value("héllo"), "h****");
assert_eq!(redact_value("naïveté"), "n*****é");
}
#[test]
fn redact_field_only_touches_sensitive_keys() {
assert_eq!(redact_field("username", json!("john")), json!("john"));
let masked = redact_field("password", json!("secret123"));
assert_eq!(masked, json!("s*******3"));
}
#[test]
fn redact_map_masks_selectively() {
let mut map = HashMap::new();
map.insert("username".to_string(), "john".to_string());
map.insert("password".to_string(), "secret123".to_string());
let result = redact_map(&map);
assert_eq!(result["username"], json!("john"));
assert_eq!(result["password"], json!("s*******3"));
}
}