use std::borrow::Cow;
use std::sync::{Arc, Mutex};
use crate::value::{SECRET_MASK, Value};
pub const MIN_SCRUB_LEN: usize = 4;
pub fn redact_secrets<'a, S: AsRef<str>>(text: &'a str, secrets: &[S]) -> Cow<'a, str> {
let mut candidates: Vec<&str> =
secrets.iter().map(AsRef::as_ref).filter(|s| s.len() >= MIN_SCRUB_LEN && text.contains(*s)).collect();
if candidates.is_empty() {
return Cow::Borrowed(text);
}
candidates.sort_by_key(|s| std::cmp::Reverse(s.len()));
let mut scrubbed = text.to_owned();
for secret in candidates {
if scrubbed.contains(secret) {
scrubbed = scrubbed.replace(secret, SECRET_MASK);
}
}
Cow::Owned(scrubbed)
}
#[derive(Default)]
pub struct SecretSet {
values: Mutex<Vec<Arc<str>>>,
}
impl std::fmt::Debug for SecretSet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let count = self.values.lock().map(|v| v.len()).unwrap_or_default();
f.debug_struct("SecretSet").field("values", &count).finish()
}
}
impl SecretSet {
pub fn new() -> Self {
Self::default()
}
pub fn observe(&self, value: &Value) {
match value {
Value::Secret(plaintext) => self.insert(plaintext),
Value::Array(items) => items.iter().for_each(|item| self.observe(item)),
Value::Object(map) => map.values().for_each(|item| self.observe(item)),
_ => {}
}
}
fn insert(&self, plaintext: &Arc<str>) {
if plaintext.len() < MIN_SCRUB_LEN {
return;
}
if let Ok(mut values) = self.values.lock() {
if !values.iter().any(|known| known == plaintext) {
values.push(Arc::clone(plaintext));
}
}
}
pub fn is_empty(&self) -> bool {
self.values.lock().map(|v| v.is_empty()).unwrap_or(true)
}
pub fn scrub<'a>(&self, text: &'a str) -> Cow<'a, str> {
match self.values.lock() {
Ok(values) => redact_secrets(text, &values),
Err(_) => Cow::Borrowed(SECRET_MASK),
}
}
pub fn scrub_in_place(&self, message: &mut String) {
if let Cow::Owned(scrubbed) = self.scrub(message) {
*message = scrubbed;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn replaces_every_occurrence_longest_first() {
let text = "key=sk-abcdef, again sk-abcdef, prefix sk-abc";
assert_eq!(redact_secrets(text, &["sk-abc", "sk-abcdef"]), "key=******, again ******, prefix ******");
}
#[test]
fn short_values_and_misses_borrow() {
assert!(matches!(redact_secrets("abc and xyz", &["abc"]), Cow::Borrowed(_)));
assert!(matches!(redact_secrets("nothing here", &["sk-live"]), Cow::Borrowed(_)));
}
#[test]
fn set_observes_nested_secrets_and_hides_them_in_debug() {
let set = SecretSet::new();
set.observe(&Value::from_json(serde_json::json!({"a": [1, 2]})));
assert!(set.is_empty());
set.observe(&Value::array([Value::Secret(Arc::from("tok-1234")), Value::Secret(Arc::from("no"))]));
set.observe(&Value::Secret(Arc::from("tok-1234")));
assert_eq!(set.scrub("Bearer tok-1234 rejected; no"), "Bearer ****** rejected; no");
assert!(!format!("{set:?}").contains("tok-1234"));
}
}