use crate::config::secret::REDACTION;
pub const SENSITIVE_NAMES: [&str; 9] = [
"password",
"passwd",
"secret",
"token",
"credential",
"private_key",
"privatekey",
"certificate",
"ssl_key",
];
#[must_use]
pub fn is_sensitive(name: &str) -> bool {
let folded = name.to_ascii_lowercase();
SENSITIVE_NAMES
.iter()
.any(|candidate| folded.contains(candidate))
}
#[must_use]
pub fn parameter(name: &str, value: &str) -> String {
if is_sensitive(name) {
return REDACTION.to_owned();
}
value.to_owned()
}
#[must_use]
pub fn scrub(text: &str) -> String {
let without_certificates = scrub_certificates(text);
let without_destinations = scrub_destinations(&without_certificates);
let without_clauses = scrub_credential_clauses(&without_destinations);
scrub_assignments(&without_clauses)
}
const BLOCK_OPEN: &str = "-----BEGIN";
const BLOCK_CLOSE: &str = "-----END";
const BLOCK_EDGE: &str = "-----";
fn scrub_certificates(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(start) = rest.find(BLOCK_OPEN) {
out.push_str(&rest[..start]);
out.push_str(REDACTION);
let after_open = &rest[start + BLOCK_OPEN.len()..];
let Some(close) = after_open.find(BLOCK_CLOSE) else {
return out;
};
let after_close = &after_open[close + BLOCK_CLOSE.len()..];
let Some(edge) = after_close.find(BLOCK_EDGE) else {
return out;
};
rest = &after_close[edge + BLOCK_EDGE.len()..];
}
out.push_str(rest);
out
}
fn scrub_destinations(text: &str) -> String {
const SCHEME_END: &str = "://";
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(mark) = rest.find(SCHEME_END) {
let start = mark + SCHEME_END.len();
out.push_str(&rest[..start]);
let after = &rest[start..];
let end = after
.find(|character: char| character.is_whitespace() || character == '/')
.unwrap_or(after.len());
let authority = &after[..end];
match split_credential(authority) {
Some((colon, at)) => {
out.push_str(&authority[..=colon]);
out.push_str(REDACTION);
out.push_str(&authority[at..]);
}
None => out.push_str(authority),
}
rest = &after[end..];
}
out.push_str(rest);
out
}
fn split_credential(authority: &str) -> Option<(usize, usize)> {
let at = authority.find('@')?;
let colon = authority[..at].find(':')?;
Some((colon, at))
}
const CREDENTIAL_CLAUSE: &str = "identified by";
fn scrub_credential_clauses(text: &str) -> String {
let folded = text.to_ascii_lowercase();
let mut out = String::with_capacity(text.len());
let mut from = 0_usize;
while let Some(found) = folded[from..].find(CREDENTIAL_CLAUSE) {
let clause_end = from + found + CREDENTIAL_CLAUSE.len();
let Some(open) = quoted_value_start(&text[clause_end..]).map(|at| clause_end + at) else {
break;
};
let quote = text[open..].chars().next().unwrap_or('\'');
out.push_str(&text[from..=open]);
out.push_str(REDACTION);
match text[open + quote.len_utf8()..].find(quote) {
Some(close) => from = open + quote.len_utf8() + close,
None => return out,
}
}
out.push_str(&text[from..]);
out
}
fn quoted_value_start(after: &str) -> Option<usize> {
after.char_indices().find_map(|(at, character)| {
match character {
'\'' | '"' => Some(Some(at)),
_ if character.is_whitespace() || character.is_alphanumeric() || character == '_' => {
None
}
_ => Some(None),
}
})?
}
const VALUE_END: [char; 10] = [' ', '\t', '\n', ',', ';', '&', ')', '}', '"', '\''];
fn scrub_assignments(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some((at, length)) = earliest_name(rest) {
let name_end = at + length;
out.push_str(&rest[..name_end]);
let after = &rest[name_end..];
let Some(value_start) = value_start(after) else {
rest = after;
continue;
};
out.push_str(&after[..value_start]);
out.push_str(REDACTION);
let value = &after[value_start..];
let end = value.find(VALUE_END).unwrap_or(value.len());
rest = &value[end..];
}
out.push_str(rest);
out
}
fn earliest_name(haystack: &str) -> Option<(usize, usize)> {
let folded = haystack.to_ascii_lowercase();
SENSITIVE_NAMES
.iter()
.filter_map(|name| folded.find(name).map(|at| (at, name.len())))
.min_by_key(|(at, _)| *at)
}
fn value_start(after: &str) -> Option<usize> {
let bytes = after.as_bytes();
let mut cursor = skip_spaces(bytes, 0);
if matches!(bytes.get(cursor), Some(b'"' | b'\'')) {
cursor = skip_spaces(bytes, cursor + 1);
}
match bytes.get(cursor) {
Some(b'=' | b':') => cursor += 1,
_ => return None,
}
cursor = skip_spaces(bytes, cursor);
if matches!(bytes.get(cursor), Some(b'"' | b'\'')) {
cursor += 1;
}
Some(cursor)
}
fn skip_spaces(bytes: &[u8], from: usize) -> usize {
let mut cursor = from;
while matches!(bytes.get(cursor), Some(b' ' | b'\t')) {
cursor += 1;
}
cursor
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_password_inside_a_destination_never_survives() {
let scrubbed = scrub("mysql://app:hunter2@db.internal:3306/shop");
assert!(!scrubbed.contains("hunter2"));
assert!(scrubbed.contains("app:"), "the user is not a secret");
assert!(scrubbed.contains("@db.internal:3306/shop"));
}
#[test]
fn a_destination_without_a_password_is_left_alone() {
let text = "mysql://app@db.internal:3306/shop";
assert_eq!(scrub(text), text);
}
#[test]
fn a_sensitive_parameter_never_shows_its_value() {
let scrubbed = scrub("connecting with password=hunter2 and user=app");
assert!(!scrubbed.contains("hunter2"));
assert!(scrubbed.contains("user=app"), "an ordinary value survives");
}
#[test]
fn a_quoted_sensitive_value_never_survives_either() {
let scrubbed = scrub("{\"token\": \"abc.def.ghi\"}");
assert!(!scrubbed.contains("abc.def.ghi"));
}
#[test]
fn a_certificate_body_never_survives() {
let text = concat!(
"cert is -----BEGIN CERTIFICATE-----\n",
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\n",
"-----END CERTIFICATE----- and that is all"
);
let scrubbed = scrub(text);
assert!(!scrubbed.contains("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A"));
assert!(scrubbed.contains("and that is all"));
}
#[test]
fn an_unterminated_certificate_never_leaks_its_tail() {
let scrubbed = scrub("-----BEGIN PRIVATE KEY-----\nMIIEvQIBADAN");
assert!(!scrubbed.contains("MIIEvQIBADAN"));
}
#[test]
fn the_mark_never_grows_with_the_secret() {
let short = scrub("password=a");
let long = scrub("password=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
assert_eq!(short, long);
}
#[test]
fn a_sensitive_name_is_recognised_however_it_is_written() {
assert!(is_sensitive("DB_PASSWORD"));
assert!(is_sensitive("ssl_key_file"));
assert!(!is_sensitive("host"));
assert!(!is_sensitive("database"));
}
#[test]
fn a_parameter_that_is_not_sensitive_keeps_its_value() {
assert_eq!(parameter("host", "db.internal"), "db.internal");
assert_eq!(parameter("password", "hunter2"), REDACTION);
}
#[test]
fn text_carrying_no_secret_comes_back_unchanged() {
let text = "opening the connection to db.internal:3306";
assert_eq!(scrub(text), text);
}
#[test]
fn a_credential_set_by_a_statement_never_survives() {
for statement in [
"CREATE USER 'app'@'%' IDENTIFIED BY 'hunter2'",
"create user app identified by \"hunter2\"",
"ALTER USER 'app'@'%' IDENTIFIED BY PASSWORD 'hunter2'",
"GRANT ALL ON shop.* TO 'app'@'%' IDENTIFIED BY 'hunter2'",
] {
let scrubbed = scrub(statement);
assert!(
!scrubbed.contains("hunter2"),
"input {statement:?} gave {scrubbed:?}"
);
assert!(scrubbed.contains("app"), "the account name is not a secret");
}
}
#[test]
fn an_unterminated_credential_literal_never_leaks_its_tail() {
let scrubbed = scrub("IDENTIFIED BY 'hunter2 and whatever followed");
assert!(!scrubbed.contains("hunter2"));
assert!(!scrubbed.contains("whatever"));
}
#[test]
fn a_quotation_that_belongs_to_something_else_is_left_alone() {
let text = "identified by nobody; SELECT 'keep me' FROM t";
assert_eq!(scrub(text), text);
}
#[test]
fn several_secrets_in_one_line_are_all_removed() {
let scrubbed = scrub("password=one token=two user=app");
assert!(!scrubbed.contains("one"));
assert!(!scrubbed.contains("two"));
assert!(scrubbed.contains("app"));
}
}