use std::collections::BTreeMap;
use std::io::Read;
use std::sync::Arc;
use base64::Engine;
use serde::Deserialize;
use super::rule::{entropy, from_re2};
use super::*;
#[derive(Deserialize)]
struct Fixture {
gitleaks_version: String,
data: Vec<String>,
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct Vectors {
tp: Vec<String>,
fp: Vec<String>,
}
fn vectors() -> BTreeMap<String, Vectors> {
let fixture: Fixture = serde_json::from_str(include_str!(
"../../tests/fixtures/scrub/gitleaks_vectors.json"
))
.unwrap();
assert_eq!(fixture.gitleaks_version, "v8.30.1");
let packed: Vec<u8> = base64::engine::general_purpose::STANDARD
.decode(fixture.data.concat())
.unwrap();
let mut json = String::new();
flate2::read::ZlibDecoder::new(packed.as_slice())
.read_to_string(&mut json)
.unwrap();
serde_json::from_str(&json).unwrap()
}
#[test]
fn gitleaks_parity_over_every_vector() {
let config = RuleConfig::from_toml(GITLEAKS).unwrap();
let mut failures: Vec<String> = Vec::new();
let (mut tps, mut fps) = (0, 0);
for (id, v) in vectors() {
let want = id.clone();
let scrubber = Scrubber::builder()
.allow_marker(AllowMarker::Honour)
.keep(move |r| r.id == want)
.build(&config)
.unwrap();
if scrubber.is_empty() {
failures.push(format!("{id}: no such rule in the config"));
continue;
}
let mut scratch = scrubber.scratch();
for tp in &v.tp {
tps += 1;
if scrubber.find(tp.as_bytes(), &mut scratch).is_empty() {
failures.push(format!("{id}: tp missed: {tp:?}"));
}
}
for fp in &v.fp {
fps += 1;
let found = scrubber.find(fp.as_bytes(), &mut scratch);
if !found.is_empty() {
failures.push(format!("{id}: fp found {:?}: {fp:?}", found[0].secret));
}
}
}
assert!(
failures.is_empty(),
"{} of {} vectors ({tps} tp, {fps} fp) disagree with gitleaks:\n{}",
failures.len(),
tps + fps,
failures.join("\n")
);
assert!(tps + fps > 6_000, "only {} vectors decoded", tps + fps);
}
#[test]
fn whole_default_set_builds() {
let s = Scrubber::gitleaks().unwrap();
assert_eq!(s.len(), 217);
assert_eq!(s.skipped().len(), 5);
assert!(
s.skipped()
.iter()
.all(|k| k.reason == SkipReason::PathGated)
);
eprintln!(
"gitleaks set: {} KiB of compiled regex",
s.memory_usage() / 1024
);
let strict = Scrubber::builder()
.strictness(Strictness::Strict)
.build(&RuleConfig::from_toml(GITLEAKS).unwrap());
assert!(matches!(
strict,
Err(ScrubError::Skipped {
reason: SkipReason::PathGated,
..
})
));
}
fn scrub(s: &Scrubber, text: &str) -> (Option<String>, Report) {
let mut scratch = s.scratch();
let mut report = s.report();
let out = s
.scrub_text(text.as_bytes(), &mut scratch, &mut report)
.map(|b| String::from_utf8(b).unwrap());
(out, report)
}
const EMAIL: &str = r#"
[[rules]]
id = "email"
regex = '''[a-z]+@[a-z]+\.com'''
"#;
#[test]
fn hash_tokens_match_the_known_answers() {
let config = RuleConfig::from_toml(EMAIL).unwrap();
for (key, token) in [
(
b"fleet-key".to_vec(),
"[EMAIL_9743fab4ac082f3864e0dbb56f8a2115]",
),
(vec![b'x'; 200], "[EMAIL_2639fb8ba04dbc722f378b163b660d7e]"),
] {
let s = Scrubber::builder()
.redaction(Redaction::Hash(HashKey::new(key).unwrap()))
.build(&config)
.unwrap();
let (out, report) = scrub(&s, "to alice@example.com.");
assert_eq!(out.as_deref(), Some(&*format!("to {token}.")));
assert!(report.changed());
}
assert!(HashKey::new(Vec::new()).is_none());
let key = HashKey::new(b"fleet-key".to_vec()).unwrap();
assert_eq!(format!("{key:?}"), "HashKey(9 bytes)");
}
#[test]
fn hash_token_is_hmac_sha384_cut_to_32_hex() {
let config = RuleConfig::from_toml(
r#"
[[rules]]
id = "password"
regex = '''hunter2'''
"#,
)
.unwrap();
let s = Scrubber::builder()
.redaction(Redaction::Hash(
HashKey::new(b"grippo-test-key".to_vec()).unwrap(),
))
.build(&config)
.unwrap();
let (out, _) = scrub(&s, "hunter2");
assert_eq!(
out.as_deref(),
Some("[PASSWORD_da89a6cbe8515e1d3d60e426007c8421]")
);
assert_eq!(
crate::scrub::HASH_ALGORITHM,
"hmac-sha384-keyed-truncated-to-32-hex"
);
}
#[test]
fn mask_observe_and_report_kinds() {
let config = RuleConfig::from_toml(
r#"
[[rules]]
id = "api-key"
regex = '''key=([a-z0-9]+)'''
entropy = 1.0
[[rules.allowlists]]
stopwords = ["example"]
"#,
)
.unwrap();
let text = "key=ab key=x9q2 key=myexample key=z7k1";
let mask = Scrubber::new(&config).unwrap();
let (out, report) = scrub(&mask, text);
assert_eq!(
out.as_deref(),
Some("key=ab key=[API_KEY_REDACTED] key=myexample key=[API_KEY_REDACTED]")
);
assert_eq!(report.count("api-key", Kind::Redacted), 2);
assert_eq!(report.count("api-key", Kind::LowEntropy), 1);
assert_eq!(report.count("api-key", Kind::AllowlistedValue), 1);
let entries: Vec<(&str, &str, &str, u32)> = report
.entries()
.map(|e| (e.rule, e.layer.as_str(), e.kind.as_str(), e.count))
.collect();
assert_eq!(
entries,
[
("api-key", "secret", "redacted", 2),
("api-key", "secret", "allowlisted_value", 1),
("api-key", "secret", "low_entropy", 1),
]
);
let observe = Scrubber::builder()
.redaction(Redaction::Observe)
.build(&config)
.unwrap();
let (out, report) = scrub(&observe, text);
assert_eq!(out, None);
assert!(!report.changed());
assert_eq!(report.count("api-key", Kind::Observed), 2);
assert_eq!(report.count("api-key", Kind::Redacted), 0);
let (out, mut report) = scrub(&mask, "nothing here");
assert_eq!(out, None);
assert!(report.is_empty());
report.clear();
assert!(report.is_empty() && !report.changed());
}
#[test]
fn overlapping_secrets_become_one_token() {
let s = one_rule(
r#"
[[rules]]
id = "long"
regex = '''tok_[a-z]{6}'''
[[rules]]
id = "short"
regex = '''_[a-z]{3}'''
"#,
);
let (out, report) = scrub(&s, "a tok_abcdef b");
assert_eq!(out.as_deref(), Some("a [LONG_REDACTED] b"));
assert_eq!(report.count("short", Kind::Redacted), 1);
}
#[test]
fn a_secret_takes_the_combining_marks_after_it() {
let s = one_rule(
r#"
[[rules]]
id = "t"
regex = '''tok_[a-z]+'''
"#,
);
for (text, want) in [
("a tok_cafe\u{301} b", "a [T_REDACTED] b"),
("a tok_cafe\u{301}\u{323}\u{20dd}", "a [T_REDACTED]"),
("a tok_cafe\u{e9} b", "a [T_REDACTED]\u{e9} b"),
("a tok_cafe \u{301}", "a [T_REDACTED] \u{301}"),
] {
assert_eq!(scrub(&s, text).0.as_deref(), Some(want), "{text:?}");
}
}
#[test]
fn a_rule_reads_white_space_of_any_script_as_white_space() {
let config = RuleConfig::from_toml(GITLEAKS).unwrap();
let only = |id: &'static str| {
Scrubber::builder()
.keep(move |r| r.id == id)
.build(&config)
.unwrap()
};
let (adobe, algolia) = (only("adobe-client-secret"), only("algolia-api-key"));
let run: String = (0..32_u8).map(|i| char::from(b'a' + i * 7 % 26)).collect();
let spaces = [
' ', '\u{85}', '\u{a0}', '\u{2009}', '\u{2028}', '\u{202f}', '\u{3000}',
];
for space in spaces {
let text = format!("id p8e-{run}{space}next \u{e9}");
let want = format!("id [ADOBE_CLIENT_SECRET_REDACTED]{space}next \u{e9}");
assert_eq!(scrub(&adobe, &text).0, Some(want), "{space:?}");
let text = format!("algolia_key{space}={space}{run}{space}next");
let want = format!("algolia_key{space}={space}[ALGOLIA_API_KEY_REDACTED]{space}next");
assert_eq!(scrub(&algolia, &text).0, Some(want), "{space:?}");
}
let text = [b"id p8e-", run.as_bytes(), b"\xa0next"].concat();
let mut scratch = adobe.scratch();
assert_eq!(adobe.find(&text, &mut scratch), [] as [Finding<'_>; 0]);
}
#[test]
fn strict_fails_and_lenient_lists_a_bad_rule() {
let config = RuleConfig::from_toml(
r#"
[[rules]]
id = "bad"
regex = '''(unclosed'''
[[rules]]
id = "good"
regex = '''x'''
"#,
)
.unwrap();
let lenient = Scrubber::new(&config).unwrap();
assert_eq!(lenient.len(), 1);
assert_eq!(lenient.skipped()[0].target, SkipTarget::Rule("bad".into()));
assert!(matches!(
lenient.skipped()[0].reason,
SkipReason::BadRegex(_)
));
let strict = Scrubber::builder()
.strictness(Strictness::Strict)
.build(&config);
match strict {
Err(ScrubError::Skipped { target, .. }) => {
assert_eq!(target, SkipTarget::Rule("bad".into()));
}
other => panic!("a strict build fails on the bad rule: {other:?}"),
}
}
const NONE: [&str; 0] = [];
fn one_rule(toml: &str) -> Scrubber {
Scrubber::new(&RuleConfig::from_toml(toml).unwrap()).unwrap()
}
fn secrets(s: &Scrubber, text: &str) -> Vec<String> {
let mut scratch = s.scratch();
s.find(text.as_bytes(), &mut scratch)
.into_iter()
.map(|f| text[f.secret].to_owned())
.collect()
}
#[test]
fn secret_is_the_first_non_empty_group_else_the_named_one() {
let first = one_rule(
r#"
[[rules]]
id = "t"
regex = '''(x)?key=([a-z]+)'''
keywords = ["key="]
"#,
);
assert_eq!(secrets(&first, "key=abc"), ["abc"]);
assert_eq!(secrets(&first, "xkey=abc"), ["x"]);
let named = one_rule(
r#"
[[rules]]
id = "t"
regex = '''(x)?key=([a-z]+)'''
secretGroup = 2
"#,
);
assert_eq!(secrets(&named, "xkey=abc"), ["abc"]);
}
#[test]
fn keywords_gate_the_regex_without_case() {
let s = one_rule(
r#"
[[rules]]
id = "t"
regex = '''[0-9]{4}'''
keywords = ["PIN"]
"#,
);
assert_eq!(secrets(&s, "pin 1234"), ["1234"]);
assert_eq!(secrets(&s, "Pin 1234"), ["1234"]);
assert_eq!(secrets(&s, "code 1234"), NONE);
}
#[test]
fn entropy_at_the_threshold_is_dropped() {
let s = one_rule(
r#"
[[rules]]
id = "t"
regex = '''k=([a-z]+)'''
entropy = 1.0
"#,
);
assert_eq!(secrets(&s, "k=ab"), NONE);
assert_eq!(secrets(&s, "k=abc"), ["abc"]);
}
#[test]
fn entropy_counts_characters_over_bytes() {
assert!((entropy("éé".as_bytes()) - 0.5).abs() < 1e-12);
assert!((entropy(b"abcd") - 2.0).abs() < 1e-12);
assert!(entropy(b"").abs() < f64::EPSILON);
}
#[test]
fn gitleaks_allow_skips_only_its_own_line() {
let config = RuleConfig::from_toml(
r#"
[[rules]]
id = "t"
regex = '''tok_[a-z]+'''
"#,
)
.unwrap();
let ignored = Scrubber::new(&config).unwrap();
assert_eq!(secrets(&ignored, "tok_abc # gitleaks:allow"), ["tok_abc"]);
let s = Scrubber::builder()
.allow_marker(AllowMarker::Honour)
.build(&config)
.unwrap();
assert_eq!(secrets(&s, "tok_abc # gitleaks:allow"), NONE);
assert_eq!(
secrets(&s, "tok_abc # gitleaks:allow\ntok_def"),
["tok_def"]
);
}
#[test]
fn allowlists_by_target_and_condition() {
let s = one_rule(
r#"
[allowlist]
stopwords = ["EXAMPLE"]
[[rules]]
id = "t"
regex = '''(?:k|key)=([a-z]+)'''
[[rules.allowlists]]
regexTarget = "match"
regexes = ['''^key=''']
[[rules.allowlists]]
regexTarget = "line"
condition = "AND"
regexes = ['''test''']
stopwords = ["dummy"]
[[rules.allowlists]]
condition = "AND"
regexes = ['''.''']
paths = ['''.*''']
"#,
);
assert_eq!(secrets(&s, "k=myexamplething"), NONE);
assert_eq!(secrets(&s, "key=abc"), NONE);
assert_eq!(secrets(&s, "test k=abc"), ["abc"]);
assert_eq!(secrets(&s, "test k=dummyabc"), NONE);
assert_eq!(secrets(&s, "k=zzz"), ["zzz"]);
}
#[test]
fn path_gated_rules_are_left_out() {
let s = one_rule(
r#"
[[rules]]
id = "p"
path = '''\.pem$'''
regex = '''x'''
"#,
);
assert!(s.is_empty());
}
#[test]
fn re2_braces_that_open_no_repeat_are_literals() {
for (re2, ours) in [
(r"a{2}", r"a{2}"),
(r"a{2,}", r"a{2,}"),
(r"a{2,5}", r"a{2,5}"),
(r"\${{[^}]+}}", r"\$\{\{[^}]+}}"),
(r"^\$(?:\d+|{\d+})$", r"^\$(?:\d+|\{\d+})$"),
(r"a{,5}", r"a\{,5}"),
(r"a\{x", r"a\{x"),
(r"[{]x", r"[{]x"),
(r"[]{]x", r"[]{]x"),
(r"[^]{]x", r"[^]{]x"),
(r"[[:alpha:]{]x{", r"[[:alpha:]{]x\{"),
(r"é{", r"é\{"),
] {
assert_eq!(from_re2(re2), ours, "{re2}");
}
}
#[test]
fn rules_run_ascii_only_as_re2_does() {
let s = one_rule(
r#"
[[rules]]
id = "t"
regex = '''k=(\w+)'''
"#,
);
assert_eq!(secrets(&s, "k=abcé"), ["abc"]);
}
#[test]
fn scrub_field_redacts_credential_names_and_honours_exceptions() {
let config = RuleConfig::from_toml(
r#"
[[rules]]
id = "tok"
regex = '''tok_[a-z0-9]{6}'''
"#,
)
.unwrap();
let s = Scrubber::builder()
.except_fields([
"event_data.TokenElevationType",
"audit.*",
r#"labels["app.password"]"#,
r#"["vault.x"].*"#,
])
.build(&config)
.unwrap();
let mut scratch = s.scratch();
let mut report = s.report();
let mut field = |path: &[&str], value: &str, report: &mut Report| {
s.scrub_field(path, value.as_bytes(), &mut scratch, report)
.map(|b| String::from_utf8(b).unwrap())
};
let mask = Some("[CREDENTIAL_FIELD_REDACTED]");
assert_eq!(
field(&["labels", "app.password"], "hunter2", &mut report),
None
);
assert_eq!(
field(&["vault.x", "password"], "hunter2", &mut report),
None
);
assert_eq!(
field(&["labels", "app", "password"], "hunter2", &mut report).as_deref(),
mask
);
assert_eq!(
field(&["vault", "x", "password"], "hunter2", &mut report).as_deref(),
mask
);
report.clear();
assert_eq!(
field(&["db", "password"], "hunter2", &mut report).as_deref(),
Some("[CREDENTIAL_FIELD_REDACTED]")
);
assert_eq!(report.count(FIELD_RULE, Kind::Redacted), 1);
assert!(report.changed());
report.clear();
assert!(field(&["tls", "key"], "abc", &mut report).is_some());
assert_eq!(field(&["kafka", "key"], "abc", &mut report), None);
report.clear();
assert_eq!(field(&["audit", "password"], "hunter2", &mut report), None);
assert_eq!(report.count(FIELD_RULE, Kind::ExceptedField), 1);
report.clear();
assert_eq!(
field(&["event_data", "PasswordLastSet"], "%%1794", &mut report),
None
);
assert_eq!(report.count(FIELD_RULE, Kind::ExceptedField), 0);
report.clear();
assert_eq!(field(&["audit", "msg"], "tok_abc123", &mut report), None);
assert_eq!(report.count("tok", Kind::ExceptedField), 1);
assert_eq!(
field(&["audit"], "tok_abc123", &mut report).as_deref(),
Some("[TOK_REDACTED]")
);
report.clear();
assert_eq!(
field(&["message"], "x tok_abc123 y", &mut report).as_deref(),
Some("x [TOK_REDACTED] y")
);
assert_eq!(field(&["message"], "nothing", &mut report), None);
assert_eq!(field(&["password"], "", &mut report), None);
}
#[test]
fn layers_switch_off_one_at_a_time() {
let config = RuleConfig::from_toml(
r#"
[[rules]]
id = "tok"
regex = '''tok_[a-z0-9]{6}'''
"#,
)
.unwrap();
let field_only = Scrubber::builder()
.layers(Layers::FIELD)
.build(&config)
.unwrap();
assert!(field_only.is_empty());
let mut scratch = field_only.scratch();
let mut report = field_only.report();
assert!(
field_only
.scrub_field(&["password"], b"x", &mut scratch, &mut report)
.is_some()
);
assert_eq!(
field_only.scrub_field(&["m"], b"tok_abc123", &mut scratch, &mut report),
None
);
let secret_only = Scrubber::builder()
.layers(Layers::SECRET)
.build(&config)
.unwrap();
let mut scratch = secret_only.scratch();
let mut report = secret_only.report();
assert_eq!(
secret_only.scrub_field(&["password"], b"x", &mut scratch, &mut report),
None
);
assert_eq!(
Layers::SECRET
.with(Layers::FIELD)
.with(Layers::PII)
.with(Layers::TEXT),
Layers::ALL
);
}
#[test]
fn a_scrubber_is_shared_across_threads() {
fn shared<T: Send + Sync>() {}
shared::<Scrubber>();
}
#[cfg(feature = "scrub-json")]
#[test]
fn scrub_value_walks_a_record_with_its_key_paths() {
let config = RuleConfig::from_toml(
r#"
[[rules]]
id = "tok"
regex = '''tok_[a-z0-9]{6}'''
"#,
)
.unwrap();
let s = Scrubber::builder()
.except_fields(["event_data.SubjectPassword"])
.build(&config)
.unwrap();
let mut scratch = s.scratch();
let mut report = s.report();
let mut record = serde_json::json!({
"message": "login tok_abc123 from alice@example.com",
"user": { "password": "hunter2", "pin": 1234, "admin": true },
"passwords": ["a", "b"],
"event_data": { "TokenElevationType": "%%1936", "SubjectPassword": "-" },
"ts": 1_764_116_553_123_u64,
"card": 4_111_111_111_111_111_u64,
"count": 7,
"none": null
});
assert!(s.scrub_value(&mut record, &mut scratch, &mut report));
assert_eq!(
record,
serde_json::json!({
"message": "login [TOK_REDACTED] from [EMAIL_REDACTED]",
"user": {
"password": "[CREDENTIAL_FIELD_REDACTED]",
"pin": "[CREDENTIAL_FIELD_REDACTED]",
"admin": true
},
"passwords": "[CREDENTIAL_FIELD_REDACTED]",
"event_data": { "TokenElevationType": "%%1936", "SubjectPassword": "-" },
"ts": 1_764_116_553_123_u64,
"card": 4_111_111_111_111_111_u64,
"count": 7,
"none": null
})
);
assert_eq!(report.count(FIELD_RULE, Kind::Redacted), 3);
assert_eq!(report.count(FIELD_RULE, Kind::ExceptedField), 1);
assert_eq!(report.count("email", Kind::Redacted), 1);
report.clear();
let mut clean = serde_json::json!({ "n": 1, "s": "nothing here" });
assert!(!s.scrub_value(&mut clean, &mut scratch, &mut report));
assert!(report.is_empty());
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Shape {
PrefixRun,
KeyValue,
Other,
}
fn shape(re: &str) -> Shape {
use regex_syntax::hir::{Hir, HirKind};
fn unwrap(h: &Hir) -> &Hir {
match h.kind() {
HirKind::Capture(c) => unwrap(&c.sub),
_ => h,
}
}
fn is_boundary(h: &Hir) -> bool {
match unwrap(h).kind() {
HirKind::Look(_) | HirKind::Empty => true,
HirKind::Alternation(alts) => alts
.iter()
.any(|a| matches!(unwrap(a).kind(), HirKind::Look(_))),
_ => false,
}
}
fn is_literals(h: &Hir) -> bool {
match unwrap(h).kind() {
HirKind::Literal(_) => true,
HirKind::Alternation(alts) => alts.iter().all(is_literals),
HirKind::Concat(parts) => parts.iter().all(|p| {
is_literals(p) || matches!(unwrap(p).kind(), HirKind::Class(c) if class_len(c) <= 2)
}),
HirKind::Class(c) => class_len(c) <= 2,
_ => false,
}
}
fn class_len(c: ®ex_syntax::hir::Class) -> usize {
match c {
regex_syntax::hir::Class::Bytes(b) => b
.ranges()
.iter()
.map(|r| usize::from(r.end() - r.start()) + 1)
.sum(),
regex_syntax::hir::Class::Unicode(u) => u
.ranges()
.iter()
.map(regex_syntax::hir::ClassUnicodeRange::len)
.sum(),
}
}
fn is_run(h: &Hir) -> bool {
match unwrap(h).kind() {
HirKind::Repetition(r) => matches!(unwrap(&r.sub).kind(), HirKind::Class(_)),
HirKind::Class(_) => true,
HirKind::Concat(parts) => parts.iter().all(is_run),
_ => false,
}
}
let Ok(hir) = regex_syntax::ParserBuilder::new()
.unicode(false)
.utf8(false)
.build()
.parse(&super::rule::from_re2(re))
else {
return Shape::Other;
};
let parts: Vec<&Hir> = match unwrap(&hir).kind() {
HirKind::Concat(parts) => parts.iter().collect(),
_ => vec![unwrap(&hir)],
};
let core: Vec<&Hir> = parts.into_iter().filter(|p| !is_boundary(p)).collect();
let flat: Vec<&Hir> = core
.iter()
.flat_map(|p| match unwrap(p).kind() {
HirKind::Concat(inner) => inner.iter().collect::<Vec<_>>(),
_ => vec![*p],
})
.collect();
let lazy_prefix = flat.first().is_some_and(
|p| matches!(unwrap(p).kind(), HirKind::Repetition(r) if !r.greedy && r.min == 0),
);
if lazy_prefix {
return Shape::KeyValue;
}
match flat.split_first() {
Some((head, rest))
if is_literals(head) && !rest.is_empty() && rest.iter().all(|p| is_run(p)) =>
{
Shape::PrefixRun
}
_ => Shape::Other,
}
}
#[test]
#[ignore = "a report, run by hand"]
fn rule_shape_histogram() {
let config = RuleConfig::from_toml(GITLEAKS).unwrap();
let mut counts = BTreeMap::new();
let mut other = Vec::new();
for r in config.rules.iter().filter(|r| r.path.is_none()) {
let Some(re) = r.regex.as_deref() else {
continue;
};
let s = shape(re);
*counts.entry(s).or_insert(0) += 1;
if s == Shape::Other {
other.push(format!("{}: {re}", r.id));
}
}
eprintln!("{counts:?}");
for o in other.iter().take(40) {
eprintln!(" {o}");
}
}
#[test]
fn the_text_layer_masks_credential_pairs_in_free_text() {
let config = RuleConfig::default();
let all = Scrubber::new(&config).unwrap();
let (out, report) = scrub(
&all,
"connect password=hunter2 to db, Authorization: Bearer abc.def",
);
assert_eq!(
out.as_deref(),
Some(
"connect password=[CREDENTIAL_FIELD_REDACTED] to db, Authorization: [CREDENTIAL_FIELD_REDACTED]"
)
);
assert_eq!(report.count(FIELD_RULE, Kind::Redacted), 2);
assert!(report.entries().all(|e| e.layer == Layer::Text));
let (out, report) = scrub(&all, "Illegal header value b'hunter2 '");
assert_eq!(
out.as_deref(),
Some("Illegal header value b'[CREDENTIAL_FIELD_REDACTED]'")
);
assert_eq!(report.count(FIELD_RULE, Kind::Redacted), 1);
let off = Scrubber::builder()
.layers(Layers::SECRET.with(Layers::FIELD).with(Layers::PII))
.build(&config)
.unwrap();
assert_eq!(scrub(&off, "password=hunter2").0, None);
}
#[test]
fn a_value_runs_on_through_invalid_utf8() {
const TOKEN: &str = "[CREDENTIAL_FIELD_REDACTED]";
let text_only = Scrubber::builder()
.layers(Layers::TEXT)
.build(&RuleConfig::default())
.unwrap();
let run = |s: &Scrubber, text: &[u8]| {
let mut scratch = s.scratch();
let mut report = s.report();
let out = s.scrub_text(text, &mut scratch, &mut report);
(out, report)
};
let cases: &[(&[u8], Option<&[u8]>)] = &[
(
b"password=\xed\xa0\x80hunter2",
Some(b"password=[CREDENTIAL_FIELD_REDACTED]"),
),
(
b"password=hun\xffter2 next",
Some(b"password=[CREDENTIAL_FIELD_REDACTED] next"),
),
(
b"token: \xc0\x80abc",
Some(b"token: [CREDENTIAL_FIELD_REDACTED]"),
),
(
b"{\"secret\": \"x\xed\xb3\xbfy\"}",
Some(b"{\"secret\": \"[CREDENTIAL_FIELD_REDACTED]\"}"),
),
(
b"\xffpassword=hunter2",
Some(b"\xffpassword=[CREDENTIAL_FIELD_REDACTED]"),
),
(
b"\xed\xa0\x80 password=x \xe2\x82",
Some(b"\xed\xa0\x80 password=[CREDENTIAL_FIELD_REDACTED] \xe2\x82"),
),
(
b"https://u:p\xffw@db/app",
Some(b"https://u:[CREDENTIAL_FIELD_REDACTED]@db/app"),
),
(b"plain \xff text", None),
(b"\xed\xa0\x80", None),
];
for (text, want) in cases {
let (out, report) = run(&text_only, text);
assert_eq!(out.as_deref(), *want, "{:?}", String::from_utf8_lossy(text));
assert_eq!(report.changed(), want.is_some());
}
let invalid: [&[u8]; 4] = [b"\xff", b"\xed\xa0\x80", b"\xed\xbf\xbf", b"\xe2\x82"];
for value in ["hunter2", "s3cr3tvalue9"] {
for bad in invalid {
for at in 0..=value.len() {
let mut text = b"password=".to_vec();
text.extend_from_slice(&value.as_bytes()[..at]);
text.extend_from_slice(bad);
text.extend_from_slice(&value.as_bytes()[at..]);
let (out, _) = run(&text_only, &text);
assert_eq!(
out,
Some(format!("password={TOKEN}").into_bytes()),
"{text:?}"
);
}
}
}
let all = Scrubber::new(&RuleConfig::default()).unwrap();
let (out, _) = run(&all, b"user=bob password=\xed\xa0\x80hunter2 ok");
assert_eq!(
out.as_deref(),
Some(&b"user=bob password=[CREDENTIAL_FIELD_REDACTED] ok"[..])
);
let (out, _) = run(&all, "caf\u{e9} password=x".as_bytes());
assert_eq!(
out.as_deref(),
Some("caf\u{e9} password=[CREDENTIAL_FIELD_REDACTED]".as_bytes())
);
}
#[test]
fn a_token_already_in_the_text_never_breaks_the_count() {
let s = Scrubber::new(&RuleConfig::default()).unwrap();
for text in [
"password=[CREDENTIAL_FIELD_REDACTED][CREDENTIAL_FIELD_REDACTED]",
"password=x[CREDENTIAL_FIELD_REDACTED]",
] {
let (out, report) = scrub(&s, text);
assert_eq!(report.changed(), out.is_some(), "{text}");
if out.is_some() {
assert!(report.count(FIELD_RULE, Kind::Redacted) >= 1, "{text}");
}
}
}
#[test]
fn a_scrubbed_line_scrubbed_again_is_unchanged() {
const T: &str = "[CREDENTIAL_FIELD_REDACTED]";
let s = Scrubber::gitleaks().unwrap();
let written = [
format!("SessionID={T}++\\\",LocalIP=10.0.0.1 next"),
format!("auth: {T}: unknown user"),
format!("--header='Authorization: {T} http://host/x -O /dev/null"),
format!("--header=\"Authorization: {T} http://host/x\" -O /dev/null"),
format!("token={T}++ password={T}: x"),
];
for text in &written {
let (out, _) = scrub(&s, text);
assert_eq!(out, None, "{text}");
}
let raw = [
"SessionID=abc123++\\\",LocalIP=10.0.0.1 next",
"auth: abc123: unknown user",
"auth: \"abc123\": unknown user",
"--header='Authorization: Basic abc123' http://host/x -O /dev/null",
"--header='Authorization: abc123 http://host/x -O /dev/null",
"token=abc123++ password=abc123: x",
];
for text in raw {
let once = text_scrubbed(&s, text);
assert_eq!(text_scrubbed(&s, &once), once, "{text}");
}
}
#[test]
fn adversarial_lines_scan_in_linear_time() {
use std::time::{Duration, Instant};
let s = Scrubber::gitleaks().unwrap();
let best = |line: &str| {
(0..9)
.map(|_| {
let started = Instant::now();
let _ = scrub(&s, line);
started.elapsed()
})
.min()
.unwrap_or(Duration::ZERO)
};
let dense = ["key=", "Ab3dE5", "fG7hQ9 "].concat();
for (unit, tail, n) in [
("a.", "@", 4096),
("a%2B", "%40", 2048),
(dense.as_str(), "", 256),
] {
let times: Vec<Duration> = (0..4u32)
.map(|k| best(&(unit.repeat(n << k) + tail)))
.collect();
let quadratic = times.windows(2).all(|w| w[1] > w[0] * 3);
assert!(
!quadratic,
"{unit}: {times:?} for {n} doubling to {} repeats",
n << 3
);
}
}
#[test]
fn debug_output_never_holds_the_text() {
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let mut scratch = s.scratch();
let mut report = s.report();
let _ = s.scrub_text(
b"password=HunterTwoSecretValue99",
&mut scratch,
&mut report,
);
let shown = format!("{scratch:?}");
assert!(!shown.to_lowercase().contains("huntertwo"), "{shown}");
}
#[test]
fn malformed_field_paths_are_refused() {
let bad = ["*", "", "a.*.b", "x..y", ".*", "a.b*"];
let strict = Scrubber::builder()
.strictness(Strictness::Strict)
.except_fields(["audit.*"])
.except_fields(bad)
.build(&RuleConfig::default());
assert!(matches!(
strict,
Err(ScrubError::Skipped {
reason: SkipReason::BadFieldPath,
..
})
));
let lenient = Scrubber::builder()
.except_fields(["audit.*"])
.except_fields(bad)
.build(&RuleConfig::default())
.unwrap();
assert_eq!(lenient.skipped().len(), bad.len());
let mut scratch = lenient.scratch();
let mut report = lenient.report();
assert!(
lenient
.scrub_field(&["db", "password"], b"x", &mut scratch, &mut report)
.is_some()
);
assert!(
lenient
.scrub_field(&["audit", "password"], b"x", &mut scratch, &mut report)
.is_none()
);
}
#[test]
fn an_excepted_field_counts_its_text_pairs() {
let s = Scrubber::builder()
.except_fields(["msg"])
.build(&RuleConfig::default())
.unwrap();
let mut scratch = s.scratch();
let mut report = s.report();
let out = s.scrub_field(&["msg"], b"password=hunter2xyz", &mut scratch, &mut report);
assert_eq!(out, None);
assert_eq!(report.count(FIELD_RULE, Kind::ExceptedField), 1);
}
#[test]
fn a_report_from_another_scrubber_is_replaced() {
let a = Scrubber::new(&RuleConfig::default()).unwrap();
let b = Scrubber::gitleaks().unwrap();
let mut scratch = b.scratch();
let mut foreign = a.report();
let out = b.scrub_text(b"password=hunter2", &mut scratch, &mut foreign);
assert!(out.is_some());
assert_eq!(foreign.count(FIELD_RULE, Kind::Redacted), 1);
}
#[test]
fn a_secret_never_splits_a_character() {
let s = one_rule(
r#"
[[rules]]
id = "t"
regex = '''k=(\S{3})'''
"#,
);
let (out, _) = scrub(&s, "k=ab\u{20ac}x");
assert_eq!(out.as_deref(), Some("k=[T_REDACTED]x"));
}
#[cfg(feature = "scrub-json")]
#[test]
fn deep_json_and_name_value_pairs() {
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let mut scratch = s.scratch();
let mut report = s.report();
let mut deep = serde_json::json!("password=hunter2");
for _ in 0..10_000 {
deep = serde_json::Value::Array(vec![deep]);
}
assert!(s.scrub_value(&mut deep, &mut scratch, &mut report));
while let serde_json::Value::Array(mut v) = deep {
deep = v.pop().unwrap_or_default();
}
let mut pairs = serde_json::json!({
"headers": [["Authorization", "Basic dXNlcjpwYXNz"], ["Accept", "json"]],
"list": ["password", "hunter2"]
});
assert!(s.scrub_value(&mut pairs, &mut scratch, &mut report));
assert_eq!(
pairs,
serde_json::json!({
"headers": [["Authorization", "[CREDENTIAL_FIELD_REDACTED]"], ["Accept", "json"]],
"list": ["password", "hunter2"]
})
);
}
#[test]
fn a_marker_on_an_earlier_line_never_reaches_a_later_match() {
let config = RuleConfig::from_toml(
r#"
[[rules]]
id = "t"
regex = '''tok_a\ntok_b|tok_c'''
"#,
)
.unwrap();
let s = Scrubber::builder()
.allow_marker(AllowMarker::Honour)
.build(&config)
.unwrap();
assert_eq!(secrets(&s, "gitleaks:allow tok_a\ntok_b tok_c"), ["tok_c"]);
}
#[test]
fn the_global_allowlist_spares_a_pii_match_too() {
let config = RuleConfig::from_toml(
r"
[allowlist]
regexes = ['''@example\.com$''']
",
)
.unwrap();
let s = Scrubber::builder()
.layers(Layers::PII)
.build(&config)
.unwrap();
let (out, report) = scrub(&s, "from a@example.com to b@corp.io");
assert_eq!(
out.as_deref(),
Some("from a@example.com to [EMAIL_REDACTED]")
);
assert_eq!(report.count("email", Kind::AllowlistedValue), 1);
assert_eq!(report.count("email", Kind::Redacted), 1);
}
#[test]
fn a_rule_is_left_out_by_id_in_any_layer() {
let text = "mail a@corp.io password=hunter2 card 4111 1111 1111 1111";
let all = Scrubber::new(&RuleConfig::default()).unwrap();
let (out, _) = scrub(&all, text);
assert_eq!(
out.as_deref(),
Some(
"mail [EMAIL_REDACTED] password=[CREDENTIAL_FIELD_REDACTED] card [CREDIT_CARD_REDACTED]"
)
);
let no_email = Scrubber::builder()
.without_rules(["email"])
.build(&RuleConfig::default())
.unwrap();
let (out, report) = scrub(&no_email, text);
assert_eq!(
out.as_deref(),
Some("mail a@corp.io password=[CREDENTIAL_FIELD_REDACTED] card [CREDIT_CARD_REDACTED]")
);
assert!(report.entries().all(|e| e.rule != "email"));
let no_field = Scrubber::builder()
.without_rules([FIELD_RULE])
.build(&RuleConfig::default())
.unwrap();
assert_eq!(
scrub(&no_field, text).0.as_deref(),
Some("mail [EMAIL_REDACTED] password=hunter2 card [CREDIT_CARD_REDACTED]")
);
}
#[test]
fn every_known_id_is_accepted_by_each_list() {
let config = RuleConfig::from_toml(GITLEAKS).unwrap();
let known: Vec<RuleId> = known_rules(&config).collect();
let secret: Vec<&str> = known
.iter()
.filter(|r| r.layer == Layer::Secret)
.map(|r| r.id)
.collect();
assert_eq!(secret.len(), 222);
assert_eq!(known.len(), secret.len() + PII_RULES.len() + 2);
assert!(known.contains(&RuleId {
id: FIELD_RULE,
layer: Layer::Field
}));
assert!(known.contains(&RuleId {
id: FIELD_RULE,
layer: Layer::Text
}));
let ids: Vec<&str> = known.iter().map(|r| r.id).collect();
let allowed: Vec<&str> = ids.iter().copied().filter(|&id| id != FIELD_RULE).collect();
Scrubber::builder()
.without_rules(ids.clone())
.observe_rules(ids.clone())
.allow_rules(allowed, AllowlistConfig::default())
.build(&config)
.unwrap();
let field_allow = Scrubber::builder()
.layers(Layers::FIELD)
.allow_rules([FIELD_RULE], AllowlistConfig::default())
.build(&config);
assert!(matches!(field_allow, Err(ScrubError::FieldRuleAllowlist)));
let only = Scrubber::builder()
.only_rules(secret)
.build(&config)
.unwrap();
assert_eq!(only.len(), 217);
let by_layer = Scrubber::builder()
.layers(Layers::PII)
.without_rules(["github-pat"])
.observe_rules(["github-pat", FIELD_RULE])
.only_rules(["gcp-api-key"])
.build(&config)
.unwrap();
assert!(by_layer.is_empty());
let by_keep = Scrubber::builder()
.keep(|_| false)
.observe_rules(["github-pat"])
.build(&config)
.unwrap();
assert!(by_keep.is_empty());
}
#[test]
fn an_unknown_id_is_named_with_its_list() {
let config = RuleConfig::from_toml(GITLEAKS).unwrap();
let err = Scrubber::builder()
.only_rules(["github-pat", "github-pta", "email"])
.without_rules(["credit-cards", "gcp-api-key"])
.allow_rules(["au-tfn", "au-tfn-x"], AllowlistConfig::default())
.observe_rules(["credential_field", FIELD_RULE, "github-pat", "github-pta"])
.build(&config)
.unwrap_err();
let unknown = |list, id: &str| UnknownRule {
list,
id: id.to_owned(),
};
let want = vec![
unknown(RuleList::Only, "github-pta"),
unknown(RuleList::Only, "email"),
unknown(RuleList::Without, "credit-cards"),
unknown(RuleList::Allow, "au-tfn-x"),
unknown(RuleList::Observe, "credential_field"),
unknown(RuleList::Observe, "github-pta"),
];
let ScrubError::UnknownRules { unknown: got } = &err else {
panic!("expected UnknownRules: {err:?}");
};
assert_eq!(*got, want);
assert_eq!(
err.to_string(),
"scrub: unknown rule ids: only_rules names \"github-pta\", only_rules names \"email\", \
without_rules names \"credit-cards\", allow_rules names \"au-tfn-x\", \
observe_rules names \"credential_field\", observe_rules names \"github-pta\""
);
let err = Scrubber::builder()
.strictness(Strictness::Strict)
.without_rules(["github-pta", "github-pta"])
.build(&config)
.unwrap_err();
assert_eq!(
err.to_string(),
"scrub: unknown rule ids: without_rules names \"github-pta\""
);
let email_only = RuleConfig::from_toml(EMAIL).unwrap();
assert!(
Scrubber::builder()
.only_rules(["email"])
.build(&email_only)
.is_ok()
);
assert!(
Scrubber::builder()
.only_rules(["github-pat"])
.build(&email_only)
.is_err()
);
}
#[test]
fn a_scrubber_lists_the_rules_it_runs() {
let s = Scrubber::gitleaks().unwrap();
let config = RuleConfig::from_toml(GITLEAKS).unwrap();
let known: Vec<RuleId> = known_rules(&config).collect();
let count = |s: &Scrubber, layer: Layer| s.rules().filter(|r| r.layer == layer).count();
assert_eq!(count(&s, Layer::Secret), 217);
assert_eq!(count(&s, Layer::Pii), PII_RULES.len());
assert_eq!((count(&s, Layer::Field), count(&s, Layer::Text)), (1, 1));
assert!(s.rules().all(|r| known.contains(&r)));
for skipped in s.skipped() {
assert!(s.rules().all(|r| r.id != skipped.target.name()));
}
let text = "mail a@corp.io password=hunter2 card 4111 1111 1111 1111";
let (_, report) = scrub(&s, text);
assert!(!report.is_empty());
for e in report.entries() {
let id = RuleId {
id: e.rule,
layer: e.layer,
};
assert!(s.rules().any(|r| r == id), "{id:?}");
}
let trimmed = Scrubber::builder()
.without_rules(["email", FIELD_RULE])
.build(&RuleConfig::default())
.unwrap();
let ids: Vec<&str> = trimmed.rules().map(|r| r.id).collect();
let want: Vec<&str> = PII_RULES
.iter()
.copied()
.filter(|&p| p != "email")
.collect();
assert_eq!(ids, want);
let pii = Scrubber::builder()
.layers(Layers::PII)
.build(&config)
.unwrap();
assert!(pii.rules().all(|r| r.layer == Layer::Pii));
assert_eq!(pii.rules().count(), PII_RULES.len());
}
#[test]
fn an_unknown_id_fails_at_the_level_that_names_it() {
let config = RuleConfig::from_toml(GITLEAKS).unwrap();
let err = ScrubRules::builder()
.only_rules(["github-pta"])
.without_rules(["credit-cards"])
.build(&config)
.unwrap_err();
assert_eq!(
err.to_string(),
"scrub: unknown rule ids: only_rules names \"github-pta\", without_rules names \"credit-cards\""
);
let rules = ScrubRules::builder()
.layers(Layers::PII)
.build(&config)
.unwrap();
let err = rules
.policy()
.observe_rules(["email", "github-pta"])
.allow_rules(["credit-cards"], AllowlistConfig::default())
.build()
.unwrap_err();
assert_eq!(
err.to_string(),
"scrub: unknown rule ids: allow_rules names \"credit-cards\", observe_rules names \"github-pta\""
);
rules
.policy()
.observe_rules(["github-pat"])
.allow_rules(["gcp-api-key"], AllowlistConfig::default())
.build()
.unwrap();
let field_allow = rules
.policy()
.allow_rules([FIELD_RULE], AllowlistConfig::default())
.build();
assert!(matches!(field_allow, Err(ScrubError::FieldRuleAllowlist)));
}
#[test]
fn a_policy_runs_a_subset_of_the_compiled_layers() {
let run: String = (0..36_u8).map(|i| char::from(b'a' + i * 7 % 26)).collect();
let text = format!("used ghp_{run} by a@corp.io password=hunter2");
let rules = ScrubRules::gitleaks().unwrap();
let (mut scratch, mut report) = (rules.scratch(), rules.report());
let secret = "[GITHUB_PAT_REDACTED]";
let (email, field) = ("[EMAIL_REDACTED]", "[CREDENTIAL_FIELD_REDACTED]");
let token = format!("ghp_{run}");
let rows = [
(
Layers::ALL,
format!("used {secret} by {email} password={field}"),
),
(
Layers::SECRET,
format!("used {secret} by a@corp.io password=hunter2"),
),
(
Layers::PII,
format!("used {token} by {email} password=hunter2"),
),
(
Layers::FIELD.with(Layers::TEXT),
format!("used {token} by a@corp.io password={field}"),
),
];
for (layers, want) in rows {
let s = rules.policy().layers(layers).build().unwrap();
assert_eq!(s.layers(), layers);
report.clear();
let got = s.scrub_text(text.as_bytes(), &mut scratch, &mut report);
assert_eq!(got.as_deref(), Some(want.as_bytes()), "{layers:?}");
let found = s.find(text.as_bytes(), &mut scratch);
assert_eq!(!found.is_empty(), layers.runs(Layer::Secret), "{layers:?}");
assert!(s.rules().all(|r| layers.runs(r.layer)), "{layers:?}");
}
let secret_only = ScrubRules::builder()
.layers(Layers::SECRET)
.build(&RuleConfig::from_toml(GITLEAKS).unwrap())
.unwrap();
assert_eq!(secret_only.layers(), Layers::SECRET);
let asked = secret_only.policy().layers(Layers::PII).build();
assert!(matches!(
asked,
Err(ScrubError::LayersNotCompiled {
asked: Layers::PII,
compiled: Layers::SECRET
})
));
secret_only.policy().layers(Layers::SECRET).build().unwrap();
}
#[test]
fn one_scratch_and_report_serve_every_policy_over_the_rules() {
let rules = ScrubRules::new(&RuleConfig::default()).unwrap();
let enforce = rules.policy().build().unwrap();
let observe = rules.policy().observe_all().build().unwrap();
assert!(Arc::ptr_eq(&enforce.scrub_rules().0, &rules.0));
assert!(Arc::ptr_eq(&observe.scrub_rules().0, &rules.0));
let (mut scratch, mut report) = (rules.scratch(), rules.report());
let text = b"mail a@corp.io";
let out = enforce.scrub_text(text, &mut scratch, &mut report);
assert_eq!(out.as_deref(), Some(&b"mail [EMAIL_REDACTED]"[..]));
assert_eq!(observe.scrub_text(text, &mut scratch, &mut report), None);
assert_eq!(report.count("email", Kind::Redacted), 1);
assert_eq!(report.count("email", Kind::Observed), 1);
assert_eq!(enforce.report().owner(), report.owner());
let other = ScrubRules::new(&RuleConfig::default()).unwrap();
assert_ne!(other.report().owner(), report.owner());
let bare = ScrubRules::builder()
.layers(Layers::FIELD)
.build(&RuleConfig::default())
.unwrap();
let (mut foreign, mut foreign_report) = (bare.scratch(), bare.report());
let pii_only = rules.policy().layers(Layers::PII).build().unwrap();
let out = pii_only.scrub_text(text, &mut foreign, &mut foreign_report);
assert_eq!(out.as_deref(), Some(&b"mail [EMAIL_REDACTED]"[..]));
assert_eq!(foreign_report.count("email", Kind::Redacted), 1);
}
#[derive(Default)]
#[allow(clippy::struct_excessive_bools, reason = "one flag a policy option")]
struct Case {
name: &'static str,
redaction: Redaction,
layers: Option<Layers>,
terms: bool,
except: &'static [&'static str],
only: &'static [&'static str],
allow: bool,
allow_rules: bool,
observe: &'static [&'static str],
honour: bool,
}
fn global_allow() -> AllowlistConfig {
AllowlistConfig {
regexes: vec!["example".to_owned()],
..AllowlistConfig::default()
}
}
fn rule_allow() -> AllowlistConfig {
AllowlistConfig {
stopwords: vec!["test".to_owned()],
..AllowlistConfig::default()
}
}
fn hashed() -> Redaction {
Redaction::Hash(HashKey::new(b"fleet-key".to_vec()).unwrap())
}
fn cases() -> Vec<Case> {
let base = Case::default;
vec![
Case {
name: "default",
..base()
},
Case {
name: "observe",
redaction: Redaction::Observe,
..base()
},
Case {
name: "hash",
redaction: hashed(),
..base()
},
Case {
name: "secret layer",
layers: Some(Layers::SECRET),
..base()
},
Case {
name: "pii layer",
layers: Some(Layers::PII),
..base()
},
Case {
name: "field and text",
layers: Some(Layers::FIELD.with(Layers::TEXT)),
..base()
},
Case {
name: "terms",
terms: true,
..base()
},
Case {
name: "except",
except: &["event.user", "auth.*"],
..base()
},
Case {
name: "scope",
only: &["event"],
..base()
},
Case {
name: "allow",
allow: true,
..base()
},
Case {
name: "allow rules",
allow_rules: true,
..base()
},
Case {
name: "observe rules",
observe: &["email", "credit-card", FIELD_RULE, "github-pat"],
..base()
},
Case {
name: "marker",
honour: true,
..base()
},
Case {
name: "all",
redaction: hashed(),
layers: Some(Layers::ALL.without(Layers::FIELD)),
terms: true,
except: &["event.user"],
only: &["event", "auth"],
allow: true,
allow_rules: true,
observe: &["email"],
honour: true,
},
]
}
const RULES_WITH_ALLOWLISTS: [&str; 3] = ["email", "github-pat", "au-tfn"];
fn one_step(c: &Case, config: &RuleConfig) -> Scrubber {
let mut b = Scrubber::builder()
.redaction(c.redaction.clone())
.except_fields(c.except)
.only_fields(c.only)
.observe_rules(c.observe.iter().copied());
if let Some(layers) = c.layers {
b = b.layers(layers);
}
if c.terms {
b = b.credential_terms(field::CredentialMatcher::new(["tenant"]).unwrap());
}
if c.allow {
b = b.allow(global_allow());
}
if c.allow_rules {
b = b.allow_rules(RULES_WITH_ALLOWLISTS, rule_allow());
}
if c.honour {
b = b.allow_marker(AllowMarker::Honour);
}
b.build(config).unwrap()
}
fn policy_over(c: &Case, rules: &ScrubRules) -> Scrubber {
let mut b = rules
.policy()
.redaction(c.redaction.clone())
.except_fields(c.except)
.only_fields(c.only)
.observe_rules(c.observe.iter().copied());
if let Some(layers) = c.layers {
b = b.layers(layers);
}
if c.terms {
b = b.credential_terms(field::CredentialMatcher::new(["tenant"]).unwrap());
}
if c.allow {
b = b.allow(global_allow());
}
if c.allow_rules {
b = b.allow_rules(RULES_WITH_ALLOWLISTS, rule_allow());
}
if c.honour {
b = b.allow_marker(AllowMarker::Honour);
}
b.build().unwrap()
}
type Rows = Vec<(String, Layer, Kind, u32)>;
fn rows(report: &Report) -> Rows {
(report.entries())
.map(|e| (e.rule.to_owned(), e.layer, e.kind, e.count))
.collect()
}
#[test]
fn a_policy_over_shared_rules_scrubs_as_the_one_step_scrubber_does() {
use crate::shared_tests::corpus::for_each_record_of;
let config = RuleConfig::from_toml(GITLEAKS).unwrap();
let rules = ScrubRules::new(&config).unwrap();
let mut pairs: Vec<(&str, Scrubber, Scrubber, ScrubScratch, Report)> = cases()
.iter()
.map(|c| {
let one = one_step(c, &config);
let (scratch, report) = (one.scratch(), one.report());
(c.name, one, policy_over(c, &rules), scratch, report)
})
.collect();
let (mut scratch, mut report) = (rules.scratch(), rules.report());
let paths: [&[&str]; 5] = [
&["event", "message"],
&["event", "user"],
&["auth", "password"],
&["auth", "tenant_key"],
&["other", "note"],
];
let tags = [
"syslog", "cef", "leef", "kv", "mixed", "access", "text", "csv", "tsv", "json", "ndjson",
"naughty", "xml", "http",
];
let mut n = 0_usize;
for_each_record_of(&tags, |r| {
n += 1;
if !n.is_multiple_of(4) {
return;
}
for (name, one, policy, one_scratch, one_report) in &mut pairs {
report.clear();
one_report.clear();
let want = one.scrub_text(r.bytes, one_scratch, one_report);
let got = policy.scrub_text(r.bytes, &mut scratch, &mut report);
assert_eq!(got, want, "{name}: text of {}", r.at());
assert_eq!(
rows(&report),
rows(one_report),
"{name}: counts of {}",
r.at()
);
assert_eq!(report.changed(), one_report.changed(), "{name}: {}", r.at());
if !n.is_multiple_of(32) {
continue;
}
for path in paths {
report.clear();
one_report.clear();
let want = one.scrub_field(path, r.bytes, one_scratch, one_report);
let got = policy.scrub_field(path, r.bytes, &mut scratch, &mut report);
assert_eq!(got, want, "{name}: {path:?} of {}", r.at());
assert_eq!(
rows(&report),
rows(one_report),
"{name}: {path:?} counts of {}",
r.at()
);
}
}
});
assert!(n > 1_000, "{n} records");
}
#[test]
fn a_policy_builds_far_faster_than_the_rules() {
use std::hint::black_box;
use std::time::Instant;
let config = RuleConfig::from_toml(GITLEAKS).unwrap();
let start = Instant::now();
let rules = black_box(ScrubRules::new(&config).unwrap());
let compile = start.elapsed();
let runs = 100_u32;
let start = Instant::now();
for _ in 0..runs {
let policy = rules
.policy()
.credential_terms(field::CredentialMatcher::new(["tenant"]).unwrap())
.except_fields(["event.user"])
.observe_rules(["email"])
.build()
.unwrap();
black_box(policy);
}
let policy = start.elapsed() / runs;
eprintln!("rules build {compile:?}, policy build {policy:?}");
assert!(
policy * 20 < compile,
"rules {compile:?}, policy {policy:?}"
);
}
#[test]
fn a_non_ascii_keyword_gates_the_text_it_names() {
let bytes = crate::shared_tests::corpus::file_bytes("naughty-strings", "blns.txt");
let alphabet = crate::shared_tests::corpus::lines(&bytes)
.map(|(_, line)| String::from_utf8_lossy(line).into_owned())
.find(|line| line.contains("\u{416}\u{417}\u{418}\u{419}"))
.expect("the Cyrillic alphabet");
assert!(alphabet.contains("\u{436}\u{437}\u{438}\u{439}"));
for (keyword, upper) in [
("\u{c9}tat", "\u{c9}TAT"),
(
"\u{43f}\u{430}\u{440}\u{43e}\u{43b}\u{44c}",
"\u{41f}\u{410}\u{420}\u{41e}\u{41b}\u{42c}",
),
("\u{436}\u{437}", "\u{416}\u{417}"),
("stra\u{df}e", "STRA\u{df}E"),
] {
let config = RuleConfig::from_toml(&format!(
"[[rules]]\nid = \"custom\"\nregex = \'\'\'{upper}=([a-z0-9]+)\'\'\'\nkeywords = [\"{keyword}\"]\n"
))
.unwrap();
let s = Scrubber::builder()
.layers(Layers::SECRET)
.build(&config)
.unwrap();
for text in [
format!("{upper}=abc123def"),
format!("log: {upper}=abc123def end"),
] {
let (out, report) = scrub(&s, &text);
assert_eq!(
out.as_deref(),
Some(text.replace("abc123def", "[CUSTOM_REDACTED]").as_str()),
"{keyword}"
);
assert_eq!(report.count("custom", Kind::Redacted), 1, "{keyword}");
}
}
let s = Scrubber::new(&RuleConfig::from_toml(GITLEAKS).unwrap()).unwrap();
let (out, _) = scrub(&s, &alphabet);
assert_eq!(out, None);
}
#[test]
fn a_redaction_leaves_invalid_bytes_outside_the_value_as_they_were() {
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let bytes = crate::shared_tests::corpus::file_bytes(
"quick-xml-documents",
"tests/documents/encoding/windows-1258.xml",
);
let table = crate::shared_tests::corpus::lines(&bytes)
.map(|(_, l)| l)
.find(|l| std::str::from_utf8(l).is_err())
.expect("a line that isn't UTF-8")
.to_vec();
for (name, before, after) in [
("head", &b"password=hunter2 "[..], &b""[..]),
("tail", &b""[..], &b" password=hunter2"[..]),
("both", &b"token=a1 "[..], &b" secret: b2 end"[..]),
] {
let mut text = before.to_vec();
text.extend_from_slice(&table);
text.extend_from_slice(after);
let out = s
.scrub_text(&text, &mut scratch, &mut report)
.unwrap_or_else(|| panic!("{name}: a credential was found"));
let mut want = before.to_vec();
want.extend_from_slice(&table);
want.extend_from_slice(after);
for (from, to) in [
(&b"hunter2"[..], &b"[CREDENTIAL_FIELD_REDACTED]"[..]),
(&b"a1"[..], &b"[CREDENTIAL_FIELD_REDACTED]"[..]),
(&b"b2"[..], &b"[CREDENTIAL_FIELD_REDACTED]"[..]),
] {
if let Some(at) = want.windows(from.len()).position(|w| w == from) {
want.splice(at..at + from.len(), to.iter().copied());
}
}
assert_eq!(out, want, "{name}");
assert!(
out.windows(table.len()).any(|w| w == table.as_slice()),
"{name}"
);
}
let text = b"password=abc\xffdef next \xe9";
let out = s.scrub_text(text, &mut scratch, &mut report).unwrap();
assert_eq!(out, b"password=[CREDENTIAL_FIELD_REDACTED] next \xe9");
let text = "password=abc\u{f0000}def \u{fffd}".as_bytes();
let mut text = text.to_vec();
text.push(0xff);
let out = s.scrub_text(&text, &mut scratch, &mut report).unwrap();
assert!(out.starts_with(b"password=[CREDENTIAL_FIELD_REDACTED] "));
}
#[test]
fn pii_in_other_digits_and_spaces_is_found_end_to_end() {
let s = Scrubber::builder()
.layers(Layers::PII)
.build(&RuleConfig::default())
.unwrap();
for zero in ['0', '\u{660}', '\u{ff10}', '\u{966}', '\u{1d7ce}'] {
for space in [' ', '\u{a0}', '\u{202f}', '\u{3000}'] {
let script = |text: &str| -> String {
text.chars()
.map(|c| match c.to_digit(10) {
Some(d) => char::from_u32(u32::from(zero) + d).unwrap(),
None if c == ' ' => space,
None => c,
})
.collect()
};
for (text, token) in [
("card 4111 1111 1111 1111 end", "[CREDIT_CARD_REDACTED]"),
("tfn 123 456 782 end", "[AU_TFN_REDACTED]"),
("abn 53 004 085 616 end", "[AU_ABN_REDACTED]"),
("acn 004 085 616 end", "[AU_ACN_REDACTED]"),
("medicare 2428 77813 2 end", "[AU_MEDICARE_REDACTED]"),
] {
let written = script(text);
let (out, _) = scrub(&s, &written);
let kind = text.split(' ').next().unwrap();
let want = script(&format!("{kind} {token} end"));
assert_eq!(out.as_deref(), Some(want.as_str()), "{written:?}");
}
let (out, _) = scrub(&s, &script("card 4111 1111 1111 1112 end"));
assert_eq!(out, None);
}
}
}
const REGEX_PIECES: &[&str] = &[
"\\",
"\\\\",
"[",
"]",
"[:",
":]",
"^",
"{",
"}",
"{2,3}",
"(",
")",
"(?i)",
"*",
"+",
"?",
"|",
".",
"a",
"Z",
"0",
"-",
"\u{e9}",
"\u{5bc6}",
"\u{1f600}",
"\u{a0}",
"'",
"\"",
"=",
"$",
"\\d",
"\\s",
"[a-z]",
"\\\u{e9}",
"\\\u{1f600}",
"[\\\u{e9}]",
"{\u{e9}}",
];
proptest::proptest! {
#![proptest_config(proptest::prelude::ProptestConfig::with_cases(1024))]
#[test]
fn a_regex_of_any_text_builds_or_is_refused_never_a_panic(
parts in proptest::collection::vec(proptest::sample::select(REGEX_PIECES.to_vec()), 0..12)
) {
let re = parts.concat();
let rule = RuleSpec {
id: "r".to_owned(),
regex: Some(re.clone()),
keywords: vec!["a".to_owned()],
allowlists: vec![AllowlistConfig { regexes: vec![re.clone()], ..AllowlistConfig::default() }],
..RuleSpec::default()
};
let config = RuleConfig {
allowlist: Some(AllowlistConfig { regexes: vec![re], ..AllowlistConfig::default() }),
rules: vec![rule],
..RuleConfig::default()
};
let built = ScrubRules::builder().layers(Layers::SECRET).build(&config);
proptest::prop_assert!(built.is_ok() || built.is_err());
}
}
#[test]
fn a_backslash_before_a_non_ascii_character_leaves_the_rule_out() {
for regex in ["sekret=\\\u{e9}", "a\\\u{1f600}b", "\\\u{5bc6}\u{5bc6}"] {
let config = RuleConfig::from_toml(&format!(
"[[rules]]\nid = \"r\"\nregex = \'\'\'{regex}\'\'\'\nkeywords = [\"a\"]\n"
))
.unwrap();
let rules = ScrubRules::builder()
.layers(Layers::SECRET)
.build(&config)
.unwrap();
assert!(rules.is_empty(), "{regex}");
let [skipped] = rules.skipped() else {
panic!("{regex}: {:?}", rules.skipped());
};
assert!(matches!(skipped.reason, SkipReason::BadRegex(_)), "{regex}");
let strict = ScrubRules::builder()
.layers(Layers::SECRET)
.strictness(Strictness::Strict)
.build(&config);
assert!(matches!(strict, Err(ScrubError::Skipped { .. })), "{regex}");
}
let config = RuleConfig::from_toml(
"[[rules]]\nid = \"r\"\nregex = \'\'\'sekret=\u{e9}[a-z]+\'\'\'\nkeywords = [\"sekret\"]\n",
)
.unwrap();
let rules = ScrubRules::builder()
.layers(Layers::SECRET)
.build(&config)
.unwrap();
assert_eq!(rules.len(), 1);
}
#[test]
fn look_alike_field_names_are_credentials_as_fields_and_json_keys() {
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
for name in [
"p\u{430}ssword",
"\u{ff50}\u{ff41}\u{ff53}\u{ff53}\u{ff57}\u{ff4f}\u{ff52}\u{ff44}",
"pass\u{200b}word",
"pass\u{ad}word",
"p\u{e4}ssword",
] {
let out = s.scrub_field(&[name], b"hunter2secret", &mut scratch, &mut report);
assert_eq!(
out.as_deref(),
Some(&b"[CREDENTIAL_FIELD_REDACTED]"[..]),
"{name:?}"
);
#[cfg(feature = "record")]
{
let json = format!("{{\"{name}\":\"hunter2secret\",\"user\":\"alice\"}}");
let out = s
.scrub_json_bytes(json.as_bytes(), &mut scratch, &mut report)
.unwrap()
.unwrap();
let want = format!("{{\"{name}\":\"[CREDENTIAL_FIELD_REDACTED]\",\"user\":\"alice\"}}");
assert_eq!(String::from_utf8(out).unwrap(), want, "{name:?}");
}
}
let out = s.scrub_field(
&["\u{43a}\u{43b}\u{44e}\u{447}"],
b"value",
&mut scratch,
&mut report,
);
assert_eq!(out, None);
}
#[test]
fn a_callers_allowlist_sits_beside_the_configs() {
let config = RuleConfig::from_toml(
r"
[allowlist]
regexes = ['''@example\.com$''']
",
)
.unwrap();
let mine = AllowlistConfig {
regexes: vec![r"@corp\.io$".to_owned()],
..AllowlistConfig::default()
};
let s = Scrubber::builder()
.layers(Layers::PII)
.allow(mine)
.build(&config)
.unwrap();
let (out, report) = scrub(&s, "a@example.com b@corp.io c@other.net");
assert_eq!(
out.as_deref(),
Some("a@example.com b@corp.io [EMAIL_REDACTED]")
);
assert_eq!(report.count("email", Kind::AllowlistedValue), 2);
}
#[test]
fn one_rule_observes_while_the_rest_redact() {
let text = "mail a@corp.io password=hunter2 card 4111 1111 1111 1111";
let s = Scrubber::builder()
.observe_rules(["email", FIELD_RULE])
.build(&RuleConfig::default())
.unwrap();
let (out, report) = scrub(&s, text);
assert_eq!(
out.as_deref(),
Some("mail a@corp.io password=hunter2 card [CREDIT_CARD_REDACTED]")
);
assert_eq!(report.count("email", Kind::Observed), 1);
assert_eq!(report.count(FIELD_RULE, Kind::Observed), 1);
assert_eq!(report.count("credit-card", Kind::Redacted), 1);
}
#[test]
fn an_allowlist_can_name_the_rules_it_covers() {
let domain = AllowlistConfig {
regexes: vec![r"@example\.com$".to_owned()],
..AllowlistConfig::default()
};
let s = Scrubber::builder()
.layers(Layers::PII)
.allow_rules(["email"], domain)
.build(&RuleConfig::default())
.unwrap();
let (out, report) = scrub(&s, "a@example.com b@corp.io 4111 1111 1111 1111");
assert_eq!(
out.as_deref(),
Some("a@example.com [EMAIL_REDACTED] [CREDIT_CARD_REDACTED]")
);
assert_eq!(report.count("email", Kind::AllowlistedValue), 1);
let config = RuleConfig::from_toml(
r"
[[rules]]
id = 'a'
regex = '''ka=([a-z]+)'''
[[rules]]
id = 'b'
regex = '''kb=([a-z]+)'''
",
)
.unwrap();
let skip = AllowlistConfig {
stopwords: vec!["skip".to_owned()],
..AllowlistConfig::default()
};
let s = Scrubber::builder()
.layers(Layers::SECRET)
.allow_rules(["a"], skip)
.build(&config)
.unwrap();
let (out, report) = scrub(&s, "ka=skipme kb=skipme");
assert_eq!(out.as_deref(), Some("ka=skipme kb=[B_REDACTED]"));
assert_eq!(report.count("a", Kind::AllowlistedValue), 1);
}
fn without_looks(hir: ®ex_syntax::hir::Hir) -> regex_syntax::hir::Hir {
use regex_syntax::hir::{Hir, HirKind, Repetition};
let each = |parts: &[Hir]| parts.iter().map(without_looks).collect();
match hir.kind() {
HirKind::Look(_) => Hir::empty(),
HirKind::Capture(c) => without_looks(&c.sub),
HirKind::Repetition(r) => Hir::repetition(Repetition {
sub: Box::new(without_looks(&r.sub)),
..r.clone()
}),
HirKind::Concat(parts) => Hir::concat(each(parts)),
HirKind::Alternation(parts) => Hir::alternation(each(parts)),
_ => hir.clone(),
}
}
const START_PIECES: &[&str] = &[
"a",
"Z",
"0",
"9",
"_",
".",
"-",
" ",
"\t",
"=",
":",
":=",
"=>",
"|",
",",
"?",
"\"",
"'",
"`",
";",
"\n",
"\\n",
"x7f",
"abcdef0123456789",
"ABCDEFGHIJKLMNOP",
"+/",
"==",
];
#[test]
fn keyword_starts_give_the_matches_the_whole_search_gives() {
use proptest::strategy::{Strategy, ValueTree};
use proptest::test_runner::{Config, RngAlgorithm, TestRng, TestRunner};
let config = RuleConfig::from_toml(GITLEAKS).unwrap();
let mut runner = TestRunner::new_with_rng(
Config::default(),
TestRng::from_seed(RngAlgorithm::ChaCha, &[11; 32]),
);
let (mut rules, mut matched) = (0, 0);
for spec in &config.rules {
let Some(re) = &spec.regex else { continue };
let Some(starts) = rule::KeywordStarts::new(re, &spec.keywords) else {
continue;
};
rules += 1;
let regex = rule::compile(re).unwrap();
let mut pieces: Vec<String> = START_PIECES.iter().map(|p| (*p).to_owned()).collect();
for k in &spec.keywords {
pieces.push(k.clone());
pieces.push(k.to_ascii_uppercase());
}
let around = proptest::collection::vec(proptest::sample::select(pieces), 0..8)
.prop_map(|parts| parts.concat().into_bytes());
let hir = regex_syntax::ParserBuilder::new()
.unicode(false)
.utf8(false)
.build()
.parse(&from_re2(re))
.unwrap();
let drawn = proptest::string::bytes_regex_parsed(&without_looks(&hir)).unwrap();
for i in 0..60 {
let mut text = around.new_tree(&mut runner).unwrap().current();
for _ in 0..=(i % 3) {
let hit = drawn.new_tree(&mut runner).unwrap().current();
let keep = if i % 5 == 4 { hit.len() / 2 } else { hit.len() };
text.extend_from_slice(&hit[..keep]);
text.extend(around.new_tree(&mut runner).unwrap().current());
}
let mut got = Vec::new();
starts.matches(®ex, &text, &mut got);
let want: Vec<_> = regex.find_iter(&text).map(|m| m.range()).collect();
assert_eq!(
got,
want,
"{} on {:?}",
spec.id,
String::from_utf8_lossy(&text)
);
matched += want.len();
}
}
assert!(rules >= 80, "only {rules} rules search from their keywords");
eprintln!("{rules} rules, {matched} matches");
assert!(matched > 2_000, "only {matched} matches");
}
#[cfg(all(
feature = "scrub-json",
feature = "record",
feature = "parse-syslog",
feature = "parse-cef"
))]
fn rendered(fields: &crate::parse::Fields<'_>) -> serde_json::Value {
use crate::record::{Record, Typed};
let mut out = serde_json::Map::new();
for (name, _) in fields.as_slice() {
let key = name.split('.').next().unwrap_or(name);
if out.contains_key(key) {
continue;
}
let at = fields.find(&[key]).unwrap();
let value = match fields.typed(at).unwrap() {
Typed::Str(s) => serde_json::Value::String(s.into_owned()),
_ => serde_json::from_str(&fields.text(at).unwrap()).unwrap(),
};
out.insert(key.to_owned(), value);
}
serde_json::Value::Object(out)
}
#[cfg(all(feature = "scrub-json", feature = "record"))]
fn counts(report: &Report) -> Vec<(String, String)> {
let mut rows: Vec<(String, String)> = report
.entries()
.map(|e| {
(
e.rule.to_owned(),
format!("{:?} {:?} {}", e.layer, e.kind, e.count),
)
})
.collect();
rows.sort();
rows
}
#[cfg(all(feature = "scrub-json", feature = "record"))]
fn scrubbed_three_ways(
s: &Scrubber,
value: &serde_json::Value,
) -> (serde_json::Value, Vec<(String, String)>) {
let (mut scratch, mut report) = (s.scratch(), s.report());
let mut want = value.clone();
let changed = s.scrub_value(&mut want, &mut scratch, &mut report);
let want_counts = counts(&report);
report.clear();
let Ok(copy) = s.scrub(value, &mut scratch, &mut report);
assert_eq!((&*copy, matches!(copy, Cow::Owned(_))), (&want, changed));
assert_eq!(counts(&report), want_counts);
for text in [
serde_json::to_string(value).unwrap(),
serde_json::to_string_pretty(value).unwrap(),
] {
report.clear();
let out = s
.scrub_json_bytes(text.as_bytes(), &mut scratch, &mut report)
.unwrap();
let got: serde_json::Value =
serde_json::from_slice(out.as_deref().unwrap_or(text.as_bytes())).unwrap();
assert_eq!(got, want, "{text}");
assert_eq!(counts(&report), want_counts, "{text}");
report.clear();
let mut line = JsonBytes(text.clone().into_bytes());
let changed = s.scrub_in_place(&mut line, &mut scratch, &mut report);
assert_eq!(changed, Ok(out.is_some()), "{text}");
assert_eq!(
line.0,
out.unwrap_or_else(|| text.clone().into_bytes()),
"{text}"
);
assert_eq!(counts(&report), want_counts, "{text}");
}
(want, want_counts)
}
#[cfg(all(
feature = "scrub-json",
feature = "record",
feature = "parse-syslog",
feature = "parse-cef"
))]
#[test]
fn a_record_scrubs_the_same_from_every_source() {
use crate::format;
use crate::parse::{FieldSink, FieldValue, Fields, Hint, ParsePlan, Parsers};
type Row<'r> = (&'r str, &'r [u8], Hint);
let mut registry = Parsers::new();
format::register_stock(&mut registry).unwrap();
let plan = ParsePlan::chain("syslog > cef", ®istry).unwrap();
let line = b"<134>Oct 30 16:05:55 fw01 CEF:0|Acme|Gate|1.0|100|login ok|5|src=10.0.0.1 \
suser=bob msg=paid with 4111 1111 1111 1111 from alice@example.com";
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let mask = "[CREDENTIAL_FIELD_REDACTED]";
let cases: &[(&str, &[Row<'_>], &[(&str, serde_json::Value)])] = &[
(
"chain only: PII in a CEF value",
&[],
&[
(
"/cef/msg",
"paid with [CREDIT_CARD_REDACTED] from [EMAIL_REDACTED]".into(),
),
("/cef/suser", "bob".into()),
],
),
(
"credentials",
&[
("db.password", b"hunter2", Hint::Text),
("api.key", b"k1", Hint::Text),
("note", b"login password=hunter2 ok", Hint::Text),
],
&[
("/db/password", mask.into()),
("/api/key", mask.into()),
(
"/note",
"login password=[CREDENTIAL_FIELD_REDACTED] ok".into(),
),
],
),
(
"a number or bool keeps its type unless its name is a credential",
&[
("login.pin", b"1234", Hint::Int),
("login.enabled", b"true", Hint::Bool),
("login.token", b"false", Hint::Bool),
("stats.max_tokens", b"4096", Hint::Int),
("ts", b"1764116553123", Hint::Int),
("card", b"4111111111111111", Hint::Int),
("ratio", b"1.5e3", Hint::Float),
],
&[
("/login/pin", mask.into()),
("/login/enabled", true.into()),
("/login/token", mask.into()),
("/stats/max_tokens", 4096.into()),
("/ts", 1_764_116_553_123_u64.into()),
("/card", 4_111_111_111_111_111_u64.into()),
("/ratio", 1500.0.into()),
],
),
(
"a container under a credential name goes whole",
&[
("secrets", br#"["a", {"b": 1}]"#, Hint::Json),
("passwords", b"a", Hint::Text),
("passwords", b"b", Hint::Text),
("api_key.v", b"x", Hint::Text),
("api_key.w", b"y", Hint::Text),
(
"doc",
br#"{"user": {"password": {"old": "x"}, "n": 5}}"#,
Hint::Json,
),
],
&[
("/secrets", mask.into()),
("/passwords", mask.into()),
("/api_key", mask.into()),
("/doc/user/password", mask.into()),
("/doc/user/n", 5.into()),
],
),
(
"pairs",
&[(
"headers",
br#"[["Authorization", "Basic dXNlcjpwYXNz"], ["Accept", "json"], ["password", 7]]"#,
Hint::Json,
)],
&[
("/headers/0", serde_json::json!(["Authorization", mask])),
("/headers/1", serde_json::json!(["Accept", "json"])),
("/headers/2", serde_json::json!(["password", mask])),
],
),
];
for (name, rows, checks) in cases {
let mut fields = Fields::new();
plan.parse_stateless(line, &mut fields);
for (field, bytes, hint) in *rows {
fields.field(field, FieldValue::borrowed(bytes, *hint));
}
let original = rendered(&fields);
let (want, want_counts) = scrubbed_three_ways(&s, &original);
for (pointer, value) in *checks {
assert_eq!(
want.pointer(pointer),
Some(value),
"{name}: {pointer} in {want}"
);
}
let (mut scratch, mut report) = (s.scratch(), s.report());
let changed = s.scrub_fields(&mut fields, &mut scratch, &mut report);
assert_eq!(changed, Ok(true), "{name}");
assert_eq!(rendered(&fields), want, "{name}");
assert_eq!(counts(&report), want_counts, "{name}");
}
}
#[cfg(all(feature = "record", feature = "parse-ndjson"))]
#[test]
fn an_exception_reads_a_dotted_key_apart_from_a_nested_one() {
use crate::format::ndjson::Ndjson;
use crate::parse::{Fields, Parser};
let s = Scrubber::builder()
.except_fields([r#"labels["app.password"]"#])
.build(&RuleConfig::default())
.unwrap();
let record = br#"{"labels":{"app.password":"keep","app":{"password":"drop"}}}"#;
let mut fields = Fields::new();
assert!(Ndjson::new().parse(record, &mut fields).is_ok());
let (mut scratch, mut report) = (s.scratch(), s.report());
assert_eq!(
s.scrub_fields(&mut fields, &mut scratch, &mut report),
Ok(true)
);
let got: Vec<(&str, &[u8])> = fields
.as_slice()
.iter()
.map(|(n, v)| (n.as_str(), &*v.bytes))
.collect();
assert_eq!(
got,
[
(r#"labels["app.password"]"#, &b"keep"[..]),
("labels.app.password", b"[CREDENTIAL_FIELD_REDACTED]"),
]
);
assert_eq!(report.count(FIELD_RULE, Kind::ExceptedField), 1);
}
#[cfg(all(feature = "record", feature = "parse"))]
#[test]
fn fields_are_written_back_in_place() {
use crate::parse::{FieldSink, FieldValue, Fields, Hint};
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let mut fields = Fields::new();
let rows: &[(&str, &[u8], Hint)] = &[
("tokens", b"a", Hint::Text),
("api_key.v", b"x", Hint::Text),
("keep", b"1", Hint::Int),
("tokens", b"b", Hint::Text),
("api_key.w", b"y", Hint::Text),
("j", br#" {"password": "x", "n": 1} "#, Hint::Json),
("bad", b"\xffpassword=hunter2", Hint::Text),
];
for (name, bytes, hint) in rows {
fields.field(name, FieldValue::borrowed(bytes, *hint));
}
let changed = s.scrub_fields(&mut fields, &mut scratch, &mut report);
assert_eq!(changed, Ok(true));
let mask = b"[CREDENTIAL_FIELD_REDACTED]";
let got: Vec<(&str, &[u8], Hint)> = fields
.as_slice()
.iter()
.map(|(n, v)| (n.as_str(), &*v.bytes, v.hint))
.collect();
let json = br#" {"password": "[CREDENTIAL_FIELD_REDACTED]", "n": 1} "#;
let bad = b"\xffpassword=[CREDENTIAL_FIELD_REDACTED]";
let want: Vec<(&str, &[u8], Hint)> = vec![
("tokens", mask, Hint::Text),
("api_key", mask, Hint::Text),
("keep", b"1", Hint::Int),
("j", json, Hint::Json),
("bad", bad, Hint::Text),
];
assert_eq!(got, want);
let shared: &[u8] = br#"{"password":"x"}"#;
let mut both = Fields::new();
both.field("body", FieldValue::borrowed(shared, Hint::Text));
both.field("j", FieldValue::borrowed(shared, Hint::Json));
let changed = s.scrub_fields(&mut both, &mut scratch, &mut report);
assert_eq!(changed, Ok(true));
let j = both.get("j").unwrap();
assert_eq!(
(&*j.bytes, j.hint),
(
&br#"{"password":"[CREDENTIAL_FIELD_REDACTED]"}"#[..],
Hint::Json
)
);
assert_eq!(both.get("body").unwrap().hint, Hint::Text);
let mut clean = Fields::new();
clean.field("n", FieldValue::borrowed(b"1", Hint::Int));
report.clear();
let changed = s.scrub_fields(&mut clean, &mut scratch, &mut report);
assert_eq!(changed, Ok(false));
assert!(report.is_empty());
}
#[cfg(feature = "record")]
#[test]
fn a_raw_record_that_is_not_json_fails_closed() {
use crate::record::Line;
const M: &str = "\"[CREDENTIAL_FIELD_REDACTED]\"";
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
for (bytes, want, masks) in [
(&br#"{"password": "x",}"#[..], format!("{{{M}: {M},}}"), 2),
(br#"{"a": "\ud800"}"#, format!("{{{M}: {M}}}"), 2),
] {
report.clear();
let got = s
.scrub_json_bytes(bytes, &mut scratch, &mut report)
.unwrap();
assert_eq!(
got.map(|b| String::from_utf8(b).unwrap()),
Some(want),
"{bytes:?}"
);
assert_eq!(
report.count(FIELD_RULE, Kind::Malformed),
masks,
"{bytes:?}"
);
}
let mut masked = Vec::new();
let line = Line::new(b"password=hunter2");
let done = s.scrub_record(line, &mut scratch, &mut report, |(), out| {
masked.push(out);
});
assert_eq!(done, Ok(()));
assert_eq!(masked, [b"password=[CREDENTIAL_FIELD_REDACTED]".to_vec()]);
}
#[cfg(all(feature = "scrub-json", feature = "record"))]
mod record_props {
use proptest::prelude::*;
use serde_json::Value;
use super::{HashKey, Redaction, RuleConfig, Scrubber, scrubbed_three_ways};
const KEYS: &[&str] = &[
"password",
"tokens",
"max_tokens",
"user",
"key",
"client_auth",
"headers",
"msg",
"a",
"pin",
"Authorization",
"e\"sc",
"",
];
const TEXTS: &[&str] = &[
"hunter2",
"password",
"Authorization",
"alice@example.com",
"4111 1111 1111 1111",
"password=hunter2",
"Bearer abcdefghijklmnop",
"plain",
"tab\tand \"quote\"",
"",
];
fn record() -> impl Strategy<Value = Value> {
let leaf = prop_oneof![
Just(Value::Null),
any::<bool>().prop_map(Value::Bool),
any::<i64>().prop_map(Value::from),
any::<u64>().prop_map(Value::from),
(-1e21_f64..1e21).prop_map(Value::from),
prop::sample::select(TEXTS).prop_map(Value::from),
];
leaf.prop_recursive(5, 48, 5, |inner| {
prop_oneof![
prop::collection::vec(inner.clone(), 0..4).prop_map(Value::Array),
prop::collection::vec((prop::sample::select(KEYS), inner.clone()), 0..5)
.prop_map(|kv| kv.into_iter().map(|(k, v)| (k.to_owned(), v)).collect()),
(prop::sample::select(KEYS), inner)
.prop_map(|(k, v)| Value::Array(vec![k.into(), v])),
]
})
}
proptest! {
#[test]
fn raw_json_scrubs_as_a_value_does(value in record()) {
let text = serde_json::to_string(&value).unwrap();
let value: Value = serde_json::from_str(&text).unwrap();
let key = HashKey::new(*b"k").unwrap();
for redaction in [Redaction::Mask, Redaction::Hash(key)] {
let s = Scrubber::builder()
.redaction(redaction)
.build(&RuleConfig::default())
.unwrap();
scrubbed_three_ways(&s, &value);
}
}
}
}
#[cfg(all(
feature = "scrub-json",
feature = "record",
feature = "xml",
feature = "parse-syslog",
feature = "parse-cef"
))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Expect {
Clean,
Finds,
Malformed,
}
#[cfg(all(
feature = "scrub-json",
feature = "record",
feature = "xml",
feature = "parse-syslog",
feature = "parse-cef"
))]
fn check_pair<T, V>(
s: &Scrubber,
name: &str,
target: &T,
want: &Result<Option<T>, T::Error>,
want_counts: &[(String, String)],
view: impl Fn(&T) -> V,
) where
T: Scrub + std::fmt::Debug,
T::Error: PartialEq + std::fmt::Debug,
V: PartialEq + std::fmt::Debug,
{
let (mut scratch, mut report) = (s.scratch(), s.report());
let copy = s.scrub(target, &mut scratch, &mut report);
match (©, want) {
(Ok(Cow::Borrowed(got)), Ok(None)) => assert!(std::ptr::eq(*got, target), "{name}"),
(Ok(Cow::Owned(got)), Ok(Some(w))) => assert_eq!(view(got), view(w), "{name}"),
(Err(got), Err(w)) => assert_eq!(got, w, "{name}"),
(got, w) => panic!("{name}: copy {got:?}, want {w:?}"),
}
assert_eq!(counts(&report), want_counts, "{name}: copy counts");
let mut in_place = target.clone();
report.clear();
let changed = s.scrub_in_place(&mut in_place, &mut scratch, &mut report);
let want_view = match want {
Ok(Some(w)) => view(w),
Ok(None) | Err(_) => view(target),
};
assert_eq!(view(&in_place), want_view, "{name}: in place");
let want_changed = want.as_ref().map(Option::is_some);
assert_eq!(changed.as_ref().copied(), want_changed, "{name}: in place");
assert_eq!(counts(&report), want_counts, "{name}: in place counts");
}
#[cfg(all(
feature = "scrub-json",
feature = "record",
feature = "xml",
feature = "parse-syslog",
feature = "parse-cef"
))]
fn answer<T: std::fmt::Debug, E: std::fmt::Debug>(
s: &Scrubber,
name: &str,
expect: Expect,
run: impl FnOnce(&mut ScrubScratch, &mut Report) -> Result<Option<T>, E>,
) -> (Result<Option<T>, E>, Vec<(String, String)>) {
let (mut scratch, mut report) = (s.scratch(), s.report());
let got = run(&mut scratch, &mut report);
let seen = match &got {
Ok(None) => Expect::Clean,
Ok(Some(_)) if report.count(FIELD_RULE, Kind::Malformed) > 0 => Expect::Malformed,
Ok(Some(_)) => Expect::Finds,
Err(e) => panic!("{name}: {e:?}, where a record that doesn't read is masked"),
};
assert_eq!(seen, expect, "{name}: {got:?}");
(got, counts(&report))
}
#[cfg(all(
feature = "scrub-json",
feature = "record",
feature = "xml",
feature = "parse-syslog",
feature = "parse-cef"
))]
#[test]
fn scrub_in_place_and_scrub_agree_with_each_source_function() {
use std::convert::Infallible;
use crate::format;
use crate::parse::{Fields, ParsePlan, Parsers};
use crate::record::{LayerPlan, Miss};
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let json_rows: &[(&str, Expect)] = &[
(
r#"{"level":"info","msg":"flushed","rows":4096}"#,
Expect::Clean,
),
(
r#"{"user":"bob","password":"hunter2","note":"mail alice@example.com","n":1}"#,
Expect::Finds,
),
(r#"{"user":"bob","password":"hunter2",}"#, Expect::Malformed),
];
for &(text, expect) in json_rows {
let (want, want_counts) = answer(&s, text, expect, |scratch, report| {
s.scrub_json_bytes(text.as_bytes(), scratch, report)
});
let want = want.map(|o| o.map(JsonBytes));
let target = JsonBytes(text.as_bytes().to_vec());
check_pair(&s, text, &target, &want, &want_counts, |t| t.0.clone());
if expect == Expect::Malformed {
continue;
}
let value: serde_json::Value = serde_json::from_str(text).unwrap();
let (want, want_counts) = answer(&s, text, expect, |scratch, report| {
let mut v = value.clone();
let changed = s.scrub_value(&mut v, scratch, report);
Ok::<_, Infallible>(changed.then_some(v))
});
check_pair(&s, text, &value, &want, &want_counts, Clone::clone);
}
let xml_rows: &[(&str, Expect)] = &[
("<r><keep>plain</keep></r>", Expect::Clean),
(
"<r><password>hunter2</password><note>alice@example.com</note></r>",
Expect::Finds,
),
("<r><a></r>", Expect::Malformed),
];
for &(text, expect) in xml_rows {
let (want, want_counts) = answer(&s, text, expect, |scratch, report| {
s.scrub_xml_bytes(text.as_bytes(), scratch, report)
});
let want = want.map(|o| o.map(XmlBytes));
let target = XmlBytes(text.as_bytes().to_vec());
check_pair(&s, text, &target, &want, &want_counts, |t| t.0.clone());
}
let text_rows: &[(&str, Expect)] = &[
("flushed 4096 rows", Expect::Clean),
(
"login password=hunter2 from alice@example.com",
Expect::Finds,
),
];
for &(text, expect) in text_rows {
let (want, want_counts) = answer(&s, text, expect, |scratch, report| {
Ok::<_, Infallible>(s.scrub_text(text.as_bytes(), scratch, report))
});
let want = want.map(|o| o.map(TextBytes));
let target = TextBytes(text.as_bytes().to_vec());
check_pair(&s, text, &target, &want, &want_counts, |t| t.0.clone());
}
let mut registry = Parsers::new();
format::register_stock(&mut registry).unwrap();
let chain = "syslog > cef";
let layers = LayerPlan::chain(chain, ®istry).unwrap();
let parse = ParsePlan::chain(chain, ®istry).unwrap();
let head = "<134>Oct 30 16:05:55 fw01 CEF:0|Acme|Gate|1.0|100|login ok|5|src=10.0.0.1 ";
let layered_rows: &[(String, Expect)] = &[
(format!("{head}suser=bob msg=flushed"), Expect::Clean),
(
format!("{head}suser=bob msg=paid with 4111 1111 1111 1111 from alice@example.com"),
Expect::Finds,
),
("\u{ff}".to_owned(), Expect::Malformed),
];
let field_view = |f: &Fields<'_>| -> Vec<(String, Vec<u8>)> {
f.as_slice()
.iter()
.map(|(n, v)| (n.as_str().to_owned(), v.bytes.to_vec()))
.collect()
};
for (text, expect) in layered_rows {
let name = format!("{chain}: {text}");
let (want, want_counts) = answer(&s, &name, *expect, |scratch, report| {
s.scrub_layered_bytes(&layers, text.as_bytes(), scratch, report)
});
let want = want.map(|o| {
o.map(|bytes| LayeredBytes {
plan: &layers,
bytes,
})
});
let target = LayeredBytes {
plan: &layers,
bytes: text.as_bytes().to_vec(),
};
check_pair(&s, &name, &target, &want, &want_counts, |t| t.bytes.clone());
if *expect == Expect::Malformed {
continue;
}
let mut fields = Fields::new();
parse.parse_stateless(text.as_bytes(), &mut fields);
let (want, want_counts) = answer(&s, &name, *expect, |scratch, report| {
let mut f = fields.clone();
let changed = s.scrub_fields(&mut f, scratch, report)?;
Ok::<_, Miss>(changed.then_some(f))
});
check_pair(&s, &name, &fields, &want, &want_counts, field_view);
}
}
#[cfg(feature = "record")]
#[test]
fn a_clean_line_in_place_keeps_every_buffer() {
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let text =
br#"{"ts":"2026-12-01T10:00:00Z","level":"info","msg":"flushed","rows":4096,"ok":true}"#;
let mut line = JsonBytes(Vec::with_capacity(1024));
line.0.extend_from_slice(text);
assert_eq!(
s.scrub_in_place(&mut line, &mut scratch, &mut report),
Ok(false)
);
let held = (
scratch.events.as_ptr(),
scratch.path.as_ptr(),
scratch.stack.as_ptr(),
);
assert!(scratch.events.capacity() > 0 && scratch.path.capacity() > 0);
let (ptr, cap) = (line.0.as_ptr(), line.0.capacity());
for _ in 0..3 {
report.clear();
assert_eq!(
s.scrub_in_place(&mut line, &mut scratch, &mut report),
Ok(false)
);
assert_eq!((line.0.as_ptr(), line.0.capacity()), (ptr, cap));
assert_eq!(line.0, text);
let now = (
scratch.events.as_ptr(),
scratch.path.as_ptr(),
scratch.stack.as_ptr(),
);
assert_eq!(now, held);
assert!(report.is_empty());
}
line.0.clear();
line.0
.extend_from_slice(br#"{"msg":"login","password":"hunter2"}"#);
assert_eq!(
s.scrub_in_place(&mut line, &mut scratch, &mut report),
Ok(true)
);
assert_eq!(
line.0,
br#"{"msg":"login","password":"[CREDENTIAL_FIELD_REDACTED]"}"#
);
assert_eq!((line.0.as_ptr(), line.0.capacity()), (ptr, cap));
assert_eq!(report.count(FIELD_RULE, Kind::Redacted), 1);
}
#[cfg(all(
feature = "record",
feature = "xml",
feature = "parse-syslog",
feature = "parse-cef",
feature = "parse-kv",
feature = "parse-ndjson"
))]
#[test]
fn a_scope_scrubs_one_layer() {
use crate::format;
use crate::parse::Parsers;
use crate::record::LayerPlan;
type Case<'c> = (
&'c str,
&'c str,
&'c [&'c str],
&'c [&'c str],
&'c str,
u32,
u32,
);
let mut registry = Parsers::new();
format::register_stock(&mut registry).unwrap();
let xml = r#"ndjson > field("doc"):xml"#;
let doc = r#"{"password":"hunter2","doc":"<e><password>hunter2</password><n>alice@example.com</n></e>"}"#;
let kv = r#"syslog > cef > field("msg"):kv"#;
let cef = r"CEF:0|Acme|Gate|1.0|100|login|5|suser=alice@example.com msg=password\=hunter2";
let plain = format!("<134>Oct 30 16:05:55 fw01 app: {cef}");
let host = format!("<134>Oct 30 16:05:55 bob@example.com app: {cef}");
let masked = r"CEF:0|Acme|Gate|1.0|100|login|5|suser=[EMAIL_REDACTED] msg=password\=[CREDENTIAL_FIELD_REDACTED]";
let msg_only = r"CEF:0|Acme|Gate|1.0|100|login|5|suser=alice@example.com msg=password\=[CREDENTIAL_FIELD_REDACTED]";
let cases: &[Case<'_>] = &[
(
xml,
doc,
&[],
&[],
r#"{"password":"[CREDENTIAL_FIELD_REDACTED]","doc":"<e><password>[CREDENTIAL_FIELD_REDACTED]</password><n>[EMAIL_REDACTED]</n></e>"}"#,
2,
1,
),
(
xml,
doc,
&["doc"],
&[],
r#"{"password":"hunter2","doc":"<e><password>[CREDENTIAL_FIELD_REDACTED]</password><n>[EMAIL_REDACTED]</n></e>"}"#,
1,
1,
),
(
xml,
doc,
&["doc.e.n"],
&[],
r#"{"password":"hunter2","doc":"<e><password>hunter2</password><n>[EMAIL_REDACTED]</n></e>"}"#,
0,
1,
),
(
xml,
doc,
&["doc"],
&["doc.e.n"],
r#"{"password":"hunter2","doc":"<e><password>[CREDENTIAL_FIELD_REDACTED]</password><n>alice@example.com</n></e>"}"#,
1,
0,
),
(xml, doc, &["nope"], &[], doc, 0, 0),
(
kv,
&plain,
&[],
&[],
&format!("<134>Oct 30 16:05:55 fw01 app: {masked}"),
1,
1,
),
(
kv,
&host,
&["cef"],
&[],
&format!("<134>Oct 30 16:05:55 bob@example.com app: {masked}"),
1,
1,
),
(
kv,
&host,
&["cef.msg"],
&[],
&format!("<134>Oct 30 16:05:55 bob@example.com app: {msg_only}"),
1,
0,
),
(
kv,
&host,
&["cef"],
&["cef.suser"],
&format!("<134>Oct 30 16:05:55 bob@example.com app: {msg_only}"),
1,
0,
),
];
for &(chain, record, only, except, want, fields, emails) in cases {
let name = format!("{chain} only {only:?} except {except:?}");
let s = Scrubber::builder()
.only_fields(only)
.except_fields(except)
.build(&RuleConfig::default())
.unwrap();
let layers = LayerPlan::chain(chain, ®istry).unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let target = LayeredBytes {
plan: &layers,
bytes: record.as_bytes().to_vec(),
};
let got = s.scrub(&target, &mut scratch, &mut report).unwrap();
assert_eq!(String::from_utf8_lossy(&got.bytes), want, "{name}");
assert_eq!(matches!(got, Cow::Owned(_)), want != record, "{name}");
assert_eq!(report.count(FIELD_RULE, Kind::Redacted), fields, "{name}");
assert_eq!(report.count("email", Kind::Redacted), emails, "{name}");
let excepted = report.count("email", Kind::ExceptedField);
assert_eq!(excepted, u32::from(!except.is_empty()), "{name}");
if only == ["nope"] {
assert!(report.is_empty(), "{name}");
}
}
}
#[test]
fn a_malformed_scope_is_refused() {
let lenient = Scrubber::builder()
.only_fields(["a..b", "ok"])
.build(&RuleConfig::default())
.unwrap();
let bad: Vec<&SkipTarget> = lenient.skipped().iter().map(|s| &s.target).collect();
assert_eq!(bad, [&SkipTarget::FieldPath("a..b".into())]);
let strict = Scrubber::builder()
.only_fields(["*"])
.strictness(Strictness::Strict)
.build(&RuleConfig::default());
assert!(matches!(
strict,
Err(ScrubError::Skipped {
reason: SkipReason::BadFieldPath,
..
})
));
let (mut scratch, mut report) = (lenient.scratch(), lenient.report());
let out = lenient.scrub_field(&["password"], b"hunter2", &mut scratch, &mut report);
assert_eq!((out, report.is_empty()), (None, true));
let out = lenient.scrub_field(&["ok", "password"], b"hunter2", &mut scratch, &mut report);
assert_eq!(out.as_deref(), Some(&b"[CREDENTIAL_FIELD_REDACTED]"[..]));
}
#[test]
fn a_scope_reaches_a_key_in_any_normal_form_and_an_exception_does_not() {
let (nfc, nfd, cyrillic) = ("caf\u{e9}", "cafe\u{301}", "c\u{430}f\u{e9}");
let mail = b"bob@example.com";
let scoped = Scrubber::builder()
.only_fields([nfc])
.build(&RuleConfig::default())
.unwrap();
let (mut scratch, mut report) = (scoped.scratch(), scoped.report());
for key in [nfc, nfd, cyrillic] {
let out = scoped.scrub_field(&[key, "mail"], mail, &mut scratch, &mut report);
assert!(out.is_some(), "{key:?}");
}
let out = scoped.scrub_field(&["other", "mail"], mail, &mut scratch, &mut report);
assert_eq!(out, None);
let excepted = Scrubber::builder()
.except_fields([nfc])
.build(&RuleConfig::default())
.unwrap();
for (key, kept) in [(nfc, true), (nfd, false), (cyrillic, false)] {
let out = excepted.scrub_field(&[key], mail, &mut scratch, &mut report);
assert_eq!(out.is_none(), kept, "{key:?}");
}
}
#[test]
fn a_star_scope_leaves_its_own_field_alone() {
let s = Scrubber::builder()
.only_fields(["user.*"])
.build(&RuleConfig::default())
.unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let own = s.scrub_field(&["user"], b"bob@example.com", &mut scratch, &mut report);
assert_eq!((own, report.is_empty()), (None, true));
let below = s.scrub_field(
&["user", "mail"],
b"bob@example.com",
&mut scratch,
&mut report,
);
assert!(below.is_some());
assert_eq!(report.count("email", Kind::Redacted), 1);
}
#[cfg(all(feature = "record", feature = "xml"))]
#[test]
fn a_document_that_breaks_after_a_find_comes_back_masked() {
use crate::scrub::XmlBytes;
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let mut good = XmlBytes(b"<r><password>hunter2</password></r>".to_vec());
assert_eq!(
s.scrub_in_place(&mut good, &mut scratch, &mut report),
Ok(true)
);
let broken = XmlBytes(b"<r><password>hunter2</password><a></r>".to_vec());
let m = "[CREDENTIAL_FIELD_REDACTED]";
let want = format!("<{m}><{m}>{m}</{m}><{m}></{m}>").into_bytes();
let mut line = broken.clone();
assert_eq!(
s.scrub_in_place(&mut line, &mut scratch, &mut report),
Ok(true)
);
assert_eq!(line.0, want);
let copy = s.scrub(&broken, &mut scratch, &mut report).unwrap();
assert_eq!(copy.0, want);
assert_eq!(report.count(FIELD_RULE, Kind::Redacted), 1);
assert_eq!(report.count(FIELD_RULE, Kind::Malformed), 12);
}
#[cfg(feature = "record")]
#[test]
fn a_json_record_that_does_not_parse_fails_closed_and_masks_every_token() {
const M: &str = "\"[CREDENTIAL_FIELD_REDACTED]\"";
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let secret = "hunter2secret";
let shape = |t: &str| t.replace('~', M).into_bytes();
let cases: Vec<(&str, Vec<u8>, Vec<u8>)> = vec![
(
"lone high surrogate escape",
br#"{"msg":"\ud83d","password":"hunter2secret"}"#.to_vec(),
shape("{~:~,~:~}"),
),
(
"lone low surrogate escape",
br#"{"msg":"\udc80","password":"hunter2secret"}"#.to_vec(),
shape("{~:~,~:~}"),
),
(
"invalid UTF-8 byte",
b"{\"msg\":\"caf\xE9\",\"password\":\"hunter2secret\"}".to_vec(),
shape("{~:~,~:~}"),
),
(
"truncated UTF-8 at the end of a value",
b"{\"msg\":\"caf\xC3\",\"password\":\"hunter2secret\"}".to_vec(),
shape("{~:~,~:~}"),
),
(
"byte order mark first",
b"\xEF\xBB\xBF{\"password\":\"hunter2secret\"}".to_vec(),
[&b"\xEF\xBB\xBF"[..], &shape("{~:~}")].concat(),
),
(
"a number, a bare key and bare words",
br#"{pin: 123456, "n": -1.5e3, "ok": true, "x": null, "w": hunter2secret, "m": "\ud800"}"#.to_vec(),
shape("{~: ~, ~: ~, ~: ~, ~: ~, ~: ~, ~: ~}"),
),
(
"nested and in a list",
br#"{"a":{"b":["hunter2secret",{"password":"x"}],"c":"\udc00"}}"#.to_vec(),
shape("{~:{~:[~,{~:~}],~:~}}"),
),
(
"a secret in the key position",
br#"{"hunter2secret": "v", "m": "\ud800"}"#.to_vec(),
shape("{~: ~, ~: ~}"),
),
(
"a bare secret in the key position",
br#"{hunter2secret: 1, "m": "\ud800"}"#.to_vec(),
shape("{~: ~, ~: ~}"),
),
(
"a colon in a list",
br#"["hunter2secret":1, "\ud800"]"#.to_vec(),
shape("[~:~, ~]"),
),
(
"a colon after a token that follows another with no colon",
br#"{"a" "hunter2secret": 1}"#.to_vec(),
shape("{~ ~: ~}"),
),
(
"an object truncated below the root",
br#"{"a":{"hunter2secret":"x""#.to_vec(),
shape("{~:{~:~"),
),
(
"a list truncated after a colon",
br#"{"a":["hunter2secret":"#.to_vec(),
shape("{~:[~:"),
),
(
"a string that never closes is the whole record",
br#"{"password":"hunter2secret"#.to_vec(),
M.as_bytes().to_vec(),
),
(
"an escape that ends the record",
br#"{"password":"hunter2secret\"#.to_vec(),
M.as_bytes().to_vec(),
),
(
"no token at all is the whole record",
b"{".to_vec(),
M.as_bytes().to_vec(),
),
(
"delimiters alone are the whole record",
b"{,}".to_vec(),
M.as_bytes().to_vec(),
),
(
"a colon alone is the whole record",
b":".to_vec(),
M.as_bytes().to_vec(),
),
(
"a closing bracket alone is the whole record",
b" ]\n".to_vec(),
M.as_bytes().to_vec(),
),
];
for (name, input, want) in cases {
report.clear();
let got = s
.scrub_json_bytes(&input, &mut scratch, &mut report)
.unwrap()
.unwrap_or_else(|| panic!("{name}: the original bytes came back"));
assert_eq!(
String::from_utf8_lossy(&got),
String::from_utf8_lossy(&want),
"{name}"
);
assert!(
!got.windows(secret.len()).any(|w| w == secret.as_bytes()),
"{name}"
);
assert!(report.changed(), "{name}");
let masks = String::from_utf8_lossy(&want).matches(M).count();
assert_eq!(
usize::try_from(report.count(FIELD_RULE, Kind::Malformed)).unwrap(),
masks,
"{name}"
);
let mut line = JsonBytes(input.clone());
report.clear();
assert_eq!(
s.scrub_in_place(&mut line, &mut scratch, &mut report),
Ok(true),
"{name}"
);
assert_eq!(line.0, want, "{name}");
assert_eq!(
usize::try_from(report.count(FIELD_RULE, Kind::Malformed)).unwrap(),
masks,
"{name}"
);
assert_eq!(
s.scrub(&JsonBytes(input), &mut scratch, &mut report)
.unwrap()
.0,
want,
"{name}"
);
}
}
#[cfg(feature = "record")]
#[test]
fn a_json_record_that_parses_is_scrubbed_with_no_malformed_count() {
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let ok = s
.scrub_json_bytes(
br#"{"msg":"\ud83d\ude00","password":"hunter2secret"}"#,
&mut scratch,
&mut report,
)
.unwrap()
.unwrap();
assert_eq!(report.count(FIELD_RULE, Kind::Malformed), 0);
assert_eq!(
String::from_utf8(ok).unwrap(),
r#"{"msg":"\ud83d\ude00","password":"[CREDENTIAL_FIELD_REDACTED]"}"#
);
}
#[cfg(feature = "record")]
#[test]
fn an_observing_scrub_counts_a_record_that_does_not_parse_and_leaves_it() {
let s = Scrubber::builder()
.redaction(Redaction::Observe)
.build(&RuleConfig::default())
.unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
for (input, masks) in [
(&br#"{"msg":"\ud83d","password":"hunter2secret"}"#[..], 4),
(br#"{"password":"hunter2secret"#, 1),
(b"{,}", 1),
] {
report.clear();
assert_eq!(
s.scrub_json_bytes(input, &mut scratch, &mut report),
Ok(None),
"{input:?}"
);
assert_eq!(
report.count(FIELD_RULE, Kind::Malformed),
masks,
"{input:?}"
);
assert!(!report.changed(), "{input:?}");
let mut line = JsonBytes(input.to_vec());
report.clear();
assert_eq!(
s.scrub_in_place(&mut line, &mut scratch, &mut report),
Ok(false),
"{input:?}"
);
assert_eq!(line.0, input, "{input:?}");
assert_eq!(
report.count(FIELD_RULE, Kind::Malformed),
masks,
"{input:?}"
);
}
}
#[cfg(feature = "record")]
#[test]
fn corpus_records_that_do_not_parse_come_back_with_every_token_masked() {
use crate::shared_tests::corpus;
const M: &str = "\"[CREDENTIAL_FIELD_REDACTED]\"";
const SECRET: &str = "hunter2secret";
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let mut rejected = 0_usize;
let mut check = |name: &str, input: &[u8]| {
report.clear();
let got = s
.scrub_json_bytes(input, &mut scratch, &mut report)
.unwrap();
if report.count(FIELD_RULE, Kind::Malformed) == 0 {
return;
}
rejected += 1;
let got = got.unwrap_or_else(|| panic!("{name}: the original bytes came back"));
assert!(report.changed(), "{name}");
let mut rest = Vec::new();
let mut at = 0;
while at < got.len() {
if got[at..].starts_with(M.as_bytes()) {
at += M.len();
} else {
rest.push(got[at]);
at += 1;
}
}
let rest = rest.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(&rest);
assert!(
rest.iter().all(|b| b"{}[],: \t\n\r".contains(b)),
"{name}: {:?} kept in {:?}",
String::from_utf8_lossy(rest),
String::from_utf8_lossy(&got)
);
assert!(
!got.windows(SECRET.len()).any(|w| w == SECRET.as_bytes()),
"{name}"
);
};
for (_, file, bytes) in corpus::files("json-suite") {
if file.path.contains("/n_") {
check(&file.path, &bytes);
}
}
let list = corpus::file_bytes("naughty-strings", "blns.txt");
for (n, line) in corpus::lines(&list) {
let line = String::from_utf8_lossy(line);
for (what, record) in [
(
"value",
format!("{{\"password\":\"{SECRET}\",\"n\":{line}}}"),
),
("key", format!("{{{line}:\"{SECRET}\"}}")),
("list", format!("[{line}:\"{SECRET}\"")),
] {
check(&format!("blns:{n} as a {what}"), record.as_bytes());
}
}
assert!(rejected > 200, "only {rejected} records were rejected");
}
#[cfg(all(feature = "record", feature = "xml"))]
#[test]
fn an_xml_document_that_does_not_read_fails_closed_and_masks_every_token() {
const M: &str = "[CREDENTIAL_FIELD_REDACTED]";
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let shape = |t: &str| t.replace('~', M).into_bytes();
let cases: Vec<(&str, Vec<u8>, Vec<u8>)> = vec![
(
"a close tag that doesn't match",
b"<r><password>hunter2secret</password><a></r>".to_vec(),
shape("<~><~>~</~><~></~>"),
),
(
"attribute values in either quote",
br#"<r a="hunter2secret x" b = 'y'><c/>"#.to_vec(),
shape(r#"<~ ~="~" ~ = '~'><~/>"#),
),
(
"a quote in a comment is part of its run",
b"<r><!-- don't hunter2secret --></r".to_vec(),
shape("<~><~ ~ ~ ~></~"),
),
(
"a > in text",
b"<r>a > hunter2secret</r".to_vec(),
shape("<~>~</~"),
),
(
"white space between elements stays",
b"<r>\n <a>hunter2secret</a>\n</r".to_vec(),
shape("<~>\n <~>~</~>\n</~"),
),
(
"a byte order mark stays",
b"\xEF\xBB\xBF<r>hunter2secret</r".to_vec(),
[&b"\xEF\xBB\xBF"[..], &shape("<~>~</~")].concat(),
),
(
"a document in an encoding the walk doesn't read",
b"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><r>caf\xe9 hunter2secret</r>".to_vec(),
shape(r#"<~ ~="~" ~="~"~><~>~</~>"#),
),
(
"UTF-16",
b"\xff\xfe<\x00r\x00>\x00h\x00".to_vec(),
shape("~<~>~"),
),
(
"a value that never closes is the whole document",
br#"<r a="hunter2secret"#.to_vec(),
M.as_bytes().to_vec(),
),
(
"no token at all is the whole document",
b"<>".to_vec(),
M.as_bytes().to_vec(),
),
(
"an empty document is the mask",
Vec::new(),
M.as_bytes().to_vec(),
),
(
"white space alone is the mask",
b" \n".to_vec(),
M.as_bytes().to_vec(),
),
];
for (name, input, want) in cases {
report.clear();
let got = s
.scrub_xml_bytes(&input, &mut scratch, &mut report)
.unwrap()
.unwrap_or_else(|| panic!("{name}: the original bytes came back"));
assert_eq!(
String::from_utf8_lossy(&got),
String::from_utf8_lossy(&want),
"{name}"
);
let masks = String::from_utf8_lossy(&want).matches(M).count();
assert_eq!(
usize::try_from(report.count(FIELD_RULE, Kind::Malformed)).unwrap(),
masks,
"{name}"
);
let mut doc = XmlBytes(input);
report.clear();
assert_eq!(
s.scrub_in_place(&mut doc, &mut scratch, &mut report),
Ok(true),
"{name}"
);
assert_eq!(doc.0, want, "{name}");
}
}
#[cfg(feature = "record")]
fn left_by_masks(got: &[u8], mask: &[u8]) -> Vec<u8> {
let got = got.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(got);
let mut rest = Vec::new();
let mut at = 0;
while at < got.len() {
if got[at..].starts_with(mask) {
at += mask.len();
} else {
rest.push(got[at]);
at += 1;
}
}
rest
}
#[cfg(feature = "record")]
fn only_masks(got: &[u8], mask: &str) -> bool {
let json = left_by_masks(got, format!("\"{mask}\"").as_bytes());
let xml = left_by_masks(got, mask.as_bytes());
json.iter().all(|b| b"{}[],: \t\n\r".contains(b))
|| xml.iter().all(|b| b"<>/=\"' \t\n\r".contains(b))
}
#[cfg(all(feature = "record", feature = "xml", feature = "parse"))]
#[test]
fn every_entry_point_fails_closed_on_corpus_records_that_do_not_read() {
use crate::parse::{FieldSink, FieldValue, Fields, Hint, Parsers};
use crate::record::LayerPlan;
use crate::shared_tests::corpus;
const M: &str = "[CREDENTIAL_FIELD_REDACTED]";
const LINES_PER_FILE: usize = 100;
fn held(
rejected: &mut BTreeMap<String, usize>,
entry: &str,
input: &[u8],
got: Option<Vec<u8>>,
place: &[u8],
report: &Report,
) {
if report.count(FIELD_RULE, Kind::Malformed) == 0 {
return;
}
*rejected.entry(entry.to_owned()).or_default() += 1;
let at = String::from_utf8_lossy(&input[..input.len().min(80)]);
let got = got.unwrap_or_else(|| panic!("{entry} {at:?}: the original bytes came back"));
assert!(
only_masks(&got, M),
"{entry} {at:?}: {:?}",
String::from_utf8_lossy(&got)
);
assert!(!got.windows(7).any(|w| w == b"hunter2"), "{entry} {at:?}");
assert_eq!(place, got, "{entry} {at:?}: in place");
}
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let registry = Parsers::new();
let plan = |chain: &str| LayerPlan::chain(chain, ®istry).unwrap();
let plans = [
("layers ndjson", plan("ndjson"), false),
("layers xml", plan("xml"), false),
(
"layers ndjson > xml",
plan(r#"ndjson > field("doc"):xml"#),
true,
),
(
"layers ndjson > ndjson",
plan(r#"ndjson > field("doc"):ndjson"#),
true,
),
];
let mut inputs: Vec<(String, Vec<u8>)> = Vec::new();
for (_, file, bytes) in corpus::files("json-suite") {
if file.path.contains("/n_") {
inputs.push((file.path.clone(), bytes));
}
}
for (_, file, bytes) in corpus::files("xml")
.into_iter()
.chain(corpus::files("xml-lines"))
{
match file.unit {
corpus::Unit::File => inputs.push((file.path.clone(), bytes)),
corpus::Unit::Line => {
for (n, line) in corpus::lines(&bytes).take(LINES_PER_FILE) {
inputs.push((format!("{}:{n}", file.path), line.to_vec()));
}
}
}
}
for i in 0..inputs.len() {
let (name, bytes) = inputs[i].clone();
let mid = bytes.len() / 2;
let mut bad = bytes.clone();
bad.insert(mid, 0xff);
inputs.push((format!("{name} with 0xff"), bad));
inputs.push((format!("{name} cut"), bytes[..mid].to_vec()));
}
let (mut scratch, mut report) = (s.scratch(), s.report());
let mut ignored = s.report();
let mut rejected: BTreeMap<String, usize> = BTreeMap::new();
let deep = vec!["k"; 66].join(".");
for (name, input) in &inputs {
report.clear();
let got = s
.scrub_json_bytes(input, &mut scratch, &mut report)
.unwrap();
let mut line = JsonBytes(input.clone());
s.scrub_in_place(&mut line, &mut scratch, &mut ignored)
.unwrap();
held(&mut rejected, "json", input, got, &line.0, &report);
report.clear();
let got = s.scrub_xml_bytes(input, &mut scratch, &mut report).unwrap();
let mut doc = XmlBytes(input.clone());
s.scrub_in_place(&mut doc, &mut scratch, &mut ignored)
.unwrap();
held(&mut rejected, "xml", input, got, &doc.0, &report);
let doc = serde_json::to_string(&String::from_utf8_lossy(input)).unwrap();
let wrapped = format!(r#"{{"password":"hunter2","doc":{doc}}}"#).into_bytes();
for (chain, layers, inside) in &plans {
let record = if *inside { &wrapped } else { input };
report.clear();
let got = s
.scrub_layered_bytes(layers, record, &mut scratch, &mut report)
.unwrap();
let mut target = LayeredBytes {
plan: layers,
bytes: record.clone(),
};
s.scrub_in_place(&mut target, &mut scratch, &mut ignored)
.unwrap();
held(&mut rejected, chain, record, got, &target.bytes, &report);
}
let mut fields = Fields::new();
fields.field(deep.as_str(), FieldValue::borrowed(input, Hint::Text));
fields.field("password", FieldValue::borrowed(b"hunter2", Hint::Text));
fields.field("msg", FieldValue::borrowed(input, Hint::Json));
report.clear();
let copy = s
.scrub(&fields, &mut scratch, &mut report)
.unwrap()
.into_owned();
assert_eq!(
report.count(FIELD_RULE, Kind::Malformed),
3,
"fields {name}"
);
s.scrub_fields(&mut fields, &mut scratch, &mut ignored)
.unwrap();
let want = [deep.as_str(), "password", "msg"].map(|n| (n, M.as_bytes(), Hint::Text));
for f in [©, &fields] {
let values: Vec<(&str, &[u8], Hint)> = f
.as_slice()
.iter()
.map(|(n, v)| (n.as_str(), &*v.bytes, v.hint))
.collect();
assert_eq!(values, want, "fields {name}");
}
*rejected.entry("fields".to_owned()).or_default() += 1;
}
println!("records each entry point failed closed on: {rejected:?}");
for (entry, floor) in [
("json", 2_500),
("xml", 2_100),
("layers ndjson", 2_500),
("layers xml", 2_100),
("layers ndjson > xml", 900),
("layers ndjson > ndjson", 110),
("fields", inputs.len()),
] {
let n = rejected.get(entry).copied().unwrap_or(0);
assert!(n >= floor, "{entry}: only {n} records failed closed");
}
}
#[cfg(all(feature = "record", feature = "xml", feature = "parse"))]
#[test]
fn an_observing_scrub_counts_every_record_that_does_not_read_and_leaves_it() {
use crate::parse::{FieldSink, FieldValue, Fields, Hint, Parsers};
use crate::record::LayerPlan;
let s = Scrubber::builder()
.redaction(Redaction::Observe)
.build(&RuleConfig::default())
.unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let broken = b"<r><password>hunter2secret</password><a></r>";
assert_eq!(
s.scrub_xml_bytes(broken, &mut scratch, &mut report),
Ok(None)
);
assert_eq!(report.count(FIELD_RULE, Kind::Malformed), 6);
let mut doc = XmlBytes(broken.to_vec());
assert_eq!(
s.scrub_in_place(&mut doc, &mut scratch, &mut report),
Ok(false)
);
assert_eq!(doc.0, broken);
let layers = LayerPlan::chain(r#"ndjson > field("doc"):xml"#, &Parsers::new()).unwrap();
let record = br#"{"doc":"<r><password>hunter2secret</password><a></r>"}"#;
report.clear();
assert_eq!(
s.scrub_layered_bytes(&layers, record, &mut scratch, &mut report),
Ok(None)
);
assert_eq!(report.count(FIELD_RULE, Kind::Malformed), 2);
assert!(!report.changed());
let deep = vec!["k"; 66].join(".");
let mut fields = Fields::new();
fields.field(&deep, FieldValue::borrowed(b"hunter2secret", Hint::Text));
let before = fields.clone();
report.clear();
assert_eq!(
s.scrub_fields(&mut fields, &mut scratch, &mut report),
Ok(false)
);
assert_eq!(report.count(FIELD_RULE, Kind::Malformed), 1);
assert_eq!(fields.as_slice(), before.as_slice());
}
#[cfg(all(feature = "record", feature = "parse"))]
#[test]
fn fields_with_a_json_field_that_does_not_parse_fail_closed() {
use crate::parse::{FieldSink, FieldValue, Fields, Hint};
use crate::shared_tests::corpus;
const M: &[u8] = b"[CREDENTIAL_FIELD_REDACTED]";
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let mut ran = 0;
for (_, file, bytes) in corpus::files("json-suite") {
let mut bad = bytes.clone();
bad.insert(bytes.len() / 2, 0xff);
let mut fields = Fields::new();
fields.field("doc", FieldValue::borrowed(&bad, Hint::Json));
fields.field("password", FieldValue::borrowed(b"hunter2", Hint::Text));
fields.field("note", FieldValue::borrowed(b"flushed", Hint::Text));
report.clear();
let copy = s
.scrub(&fields, &mut scratch, &mut report)
.unwrap()
.into_owned();
assert_eq!(
report.count(FIELD_RULE, Kind::Malformed),
3,
"{}",
file.path
);
assert_eq!(
s.scrub_fields(&mut fields, &mut scratch, &mut report),
Ok(true)
);
for f in [©, &fields] {
let values: Vec<(&[u8], Hint)> = f
.as_slice()
.iter()
.map(|(_, v)| (&*v.bytes, v.hint))
.collect();
assert_eq!(values, [(M, Hint::Text); 3], "{}", file.path);
}
ran += 1;
}
assert!(ran > 300, "only {ran} files");
}
#[cfg(all(feature = "record", feature = "xml", feature = "parse"))]
#[test]
fn scrub_record_refuses_a_layered_record_whose_layer_does_not_walk() {
use crate::parse::Parsers;
use crate::record::{LayerCache, LayerPlan, Miss};
use crate::shared_tests::corpus;
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let layers = LayerPlan::chain(r#"ndjson > field("doc"):xml"#, &Parsers::new()).unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let mut ran = 0;
for (_, file, bytes) in corpus::files("xml") {
let text = String::from_utf8_lossy(&bytes);
if !text
.trim_start_matches(|c: char| c.is_ascii_whitespace())
.starts_with('<')
{
continue;
}
let doc = serde_json::to_string(&format!("{text}<")).unwrap();
let record = format!(r#"{{"password":"hunter2","doc":{doc}}}"#).into_bytes();
let cache = LayerCache::new();
let layered = layers.open(&record, &cache).unwrap();
let mut replaced = 0;
let done = s.scrub_record(layered, &mut scratch, &mut report, |_, _| replaced += 1);
assert_eq!((done, replaced), (Err(Miss::Malformed), 0), "{}", file.path);
report.clear();
let got = s
.scrub_layered_bytes(&layers, &record, &mut scratch, &mut report)
.unwrap()
.unwrap_or_else(|| panic!("{}: the original bytes came back", file.path));
assert!(
only_masks(&got, "[CREDENTIAL_FIELD_REDACTED]"),
"{}",
file.path
);
assert_eq!(
report.count(FIELD_RULE, Kind::Malformed),
4,
"{}",
file.path
);
ran += 1;
}
assert!(ran > 50, "only {ran} documents");
}
#[cfg(all(
feature = "record",
feature = "parse",
feature = "parse-syslog",
feature = "parse-cef"
))]
#[test]
fn a_refused_body_is_plain_unless_its_format_named_it() {
use crate::format;
use crate::format::cef::Cef;
use crate::format::syslog::Syslog;
use crate::parse::{Fields, Parsed, Parser, Parsers};
use crate::record::{LayerCache, LayerPlan, Miss, Record};
use crate::shared_tests::corpus;
const M: &[u8] = b"[CREDENTIAL_FIELD_REDACTED]";
let mut registry = Parsers::new();
format::register_stock(&mut registry).unwrap();
let layers = LayerPlan::chain("syslog > cef", ®istry).unwrap();
let in_json = LayerPlan::chain(r#"ndjson > field("msg"):cef"#, ®istry).unwrap();
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let scoped = Scrubber::builder()
.only_fields(["cef"])
.build(&RuleConfig::default())
.unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let (mut plain, mut broken, mut opened) = (0_usize, 0_usize, 0_usize);
corpus::for_each_record_of(&["syslog", "cef"], |r| {
let mut fields = Fields::new();
let Ok(Parsed::Body { span, .. }) = Syslog::new().parse(r.bytes, &mut fields) else {
return;
};
let body = &r.bytes[span.clone()];
let with_body = |body: &[u8]| [&r.bytes[..span.start], body, &r.bytes[span.end..]].concat();
let as_json = |body: &[u8]| {
let msg = serde_json::to_string(&String::from_utf8_lossy(body)).unwrap();
format!(r#"{{"password":"hunter2","msg":{msg}}}"#).into_bytes()
};
let line = with_body(&[body, b" password=hunter2"].concat());
let cache = LayerCache::new();
let Ok(layered) = layers.open(&line, &cache) else {
return;
};
if layered.find(&["cef"]).is_ok() {
opened += 1;
} else if !body.starts_with(b"CEF:") {
plain += 1;
report.clear();
let got = s
.scrub_layered_bytes(&layers, &line, &mut scratch, &mut report)
.unwrap()
.unwrap_or_else(|| panic!("{}: the password came back", r.at()));
assert_eq!(report.count(FIELD_RULE, Kind::Malformed), 0, "{}", r.at());
assert!(
got.ends_with(b"password=[CREDENTIAL_FIELD_REDACTED]"),
"{}",
r.at()
);
report.clear();
let got = s
.scrub_layered_bytes(&in_json, &as_json(body), &mut scratch, &mut report)
.unwrap();
assert_eq!(report.count(FIELD_RULE, Kind::Malformed), 0, "{}", r.at());
assert!(got.is_some(), "{}: the password came back", r.at());
}
let short = [&b"CEF:0|"[..], body, b" password=hunter2"].concat();
if Cef::new()
.parse(&short, &mut Fields::new())
.is_ok_and(|p| p != Parsed::NoMatch)
{
return;
}
broken += 1;
let line = with_body(&short);
for (who, scrubber) in [("all", &s), ("scoped to cef", &scoped)] {
report.clear();
let got = scrubber
.scrub_layered_bytes(&layers, &line, &mut scratch, &mut report)
.unwrap();
assert_eq!(got.as_deref(), Some(M), "{} {who}", r.at());
assert_eq!(
report.count(FIELD_RULE, Kind::Malformed),
1,
"{} {who}",
r.at()
);
}
let cache = LayerCache::new();
let layered = layers.open(&line, &cache).unwrap();
let mut replaced = 0;
let done = s.scrub_record(layered, &mut scratch, &mut report, |_, _| replaced += 1);
assert_eq!((done, replaced), (Err(Miss::Malformed), 0), "{}", r.at());
report.clear();
let got = s
.scrub_layered_bytes(&in_json, &as_json(&short), &mut scratch, &mut report)
.unwrap()
.unwrap_or_else(|| panic!("{}: the original bytes came back", r.at()));
assert!(
only_masks(&got, "[CREDENTIAL_FIELD_REDACTED]"),
"{}",
r.at()
);
assert_eq!(report.count(FIELD_RULE, Kind::Malformed), 4, "{}", r.at());
});
println!("syslog lines: CEF opened {opened}, plain {plain}, broken {broken}");
assert!(
plain > 1_000 && broken > 1_000 && opened > 0,
"{plain} plain, {broken} broken, {opened} opened"
);
}
#[cfg(all(
feature = "record",
feature = "parse",
feature = "parse-syslog",
feature = "parse-cef"
))]
#[test]
fn a_mounted_field_named_by_its_marker_fails_closed_utf8_or_not() {
use crate::format;
use crate::format::cef::Cef;
use crate::format::syslog::Syslog;
use crate::parse::{Fields, Parsed, Parser, Parsers};
use crate::record::{LayerCache, LayerPlan};
use crate::shared_tests::corpus;
const M: &[u8] = b"[CREDENTIAL_FIELD_REDACTED]";
let mut registry = Parsers::new();
format::register_stock(&mut registry).unwrap();
let layers = LayerPlan::chain(r#"syslog > field("message"):cef"#, ®istry).unwrap();
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let below = Scrubber::builder()
.only_fields(["message.*"])
.build(&RuleConfig::default())
.unwrap();
let observe = Scrubber::builder()
.redaction(Redaction::Observe)
.build(&RuleConfig::default())
.unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let mut ran = 0_usize;
corpus::for_each_record_of(&["syslog", "cef"], |r| {
let Ok(Parsed::Body { span, .. }) = Syslog::new().parse(r.bytes, &mut Fields::new()) else {
return;
};
let body = &r.bytes[span.clone()];
for tail in [&b"\xff"[..], b""] {
let message = [&b"CEF:0|"[..], body, tail, b" password=hunter2"].concat();
if Cef::new()
.parse(&message, &mut Fields::new())
.is_ok_and(|p| p != Parsed::NoMatch)
{
continue;
}
let line = [&r.bytes[..span.start], &message, &r.bytes[span.end..]].concat();
let cache = LayerCache::new();
assert!(layers.open(&line, &cache).is_ok(), "{} {tail:?}", r.at());
for (who, scrubber) in [("all", &s), ("scoped below cef", &below)] {
report.clear();
let got = scrubber
.scrub_layered_bytes(&layers, &line, &mut scratch, &mut report)
.unwrap();
assert_eq!(got.as_deref(), Some(M), "{} {who} {tail:?}", r.at());
let malformed = report.count(FIELD_RULE, Kind::Malformed);
assert_eq!(malformed, 1, "{} {who} {tail:?}", r.at());
}
report.clear();
let got = observe
.scrub_layered_bytes(&layers, &line, &mut scratch, &mut report)
.unwrap();
assert_eq!(got, None, "{} observe {tail:?}", r.at());
let malformed = report.count(FIELD_RULE, Kind::Malformed);
assert_eq!(malformed, 1, "{} observe {tail:?}", r.at());
ran += 1;
}
});
assert!(ran > 2_000, "only {ran} lines");
}
#[cfg(all(
feature = "record",
feature = "parse",
feature = "parse-syslog",
feature = "parse-cef"
))]
#[test]
fn a_lookup_opens_a_mounted_field_as_the_walk_does() {
use std::borrow::Cow;
use crate::format;
use crate::format::cef::Cef;
use crate::format::syslog::Syslog;
use crate::parse::{Fields, Parsed, Parser, Parsers};
use crate::record::{LayerCache, LayerPlan, Miss, Record};
use crate::shared_tests::corpus;
const M: &[u8] = b"[CREDENTIAL_FIELD_REDACTED]";
let mut registry = Parsers::new();
format::register_stock(&mut registry).unwrap();
let layers = LayerPlan::chain(r#"syslog > field("message"):cef"#, ®istry).unwrap();
let s = Scrubber::new(&RuleConfig::default()).unwrap();
let observe = Scrubber::builder()
.redaction(Redaction::Observe)
.build(&RuleConfig::default())
.unwrap();
let (mut read, mut broken) = (0_usize, 0_usize);
corpus::for_each_record_of(&["syslog", "cef"], |r| {
let Ok(Parsed::Body { span, .. }) = Syslog::new().parse(r.bytes, &mut Fields::new()) else {
return;
};
let body = &r.bytes[span.clone()];
let mut valid = b"CEF:0|grippo|test|1|100|login|5|msg=".to_vec();
for &b in body {
if matches!(b, b'\\' | b'=') {
valid.push(b'\\');
}
valid.push(b);
}
valid.extend_from_slice(b"\xff password=hunter2");
let short = [&b"CEF:0|"[..], body, b"\xff password=hunter2"].concat();
for (message, reads) in [(valid, true), (short, false)] {
let parsed = Cef::new()
.parse(&message, &mut Fields::new())
.is_ok_and(|p| p != Parsed::NoMatch);
if parsed != reads {
continue;
}
let line = [&r.bytes[..span.start], &message, &r.bytes[span.end..]].concat();
for (who, scrubber) in [("redact", &s), ("observe", &observe)] {
let run = |lookup_first: bool| {
let cache = LayerCache::new();
let layered = layers.open(&line, &cache).unwrap();
let find = || {
let at = layered.find(&["message", "password"])?;
layered.text(at).map(Cow::into_owned)
};
let before = lookup_first.then(find);
let (mut scratch, mut report) = (scrubber.scratch(), scrubber.report());
let mut masked = Vec::new();
let done =
scrubber.scrub_record(layered, &mut scratch, &mut report, |_, out| {
masked.push(out);
});
let found = before.unwrap_or_else(find);
let counts: Vec<_> = report
.entries()
.map(|e| (e.rule.to_owned(), e.kind, e.count))
.collect();
(done, masked, counts, found)
};
let (lookup, walk) = (run(true), run(false));
assert_eq!(lookup, walk, "{} {who} reads {reads}", r.at());
let (done, masked, counts, found) = walk;
if reads {
assert_eq!(done, Ok(()), "{} {who}", r.at());
assert_eq!(found.as_deref(), Ok("hunter2"), "{} {who}", r.at());
assert!(!counts.is_empty(), "{} {who}", r.at());
assert!(
who == "observe" || masked.contains(&M.to_vec()),
"{}",
r.at()
);
} else {
assert_eq!(done, Err(Miss::Malformed), "{} {who}", r.at());
assert!(masked.is_empty(), "{} {who}", r.at());
}
}
if reads {
read += 1;
} else {
broken += 1;
}
}
});
assert!(
read > 1_000 && broken > 1_000,
"{read} read, {broken} broken"
);
}
#[cfg(feature = "record")]
#[test]
fn a_find_after_a_long_clean_run_is_masked() {
let s = Scrubber::gitleaks().unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let run: String = (0..36_u8).map(|i| char::from(b'a' + i * 7 % 26)).collect();
let pat = format!("ghp_{run}");
let rows: [(&str, &str, &str); 6] = [
("secret", &pat, "[GITHUB_PAT_REDACTED]"),
("pair", "password=hunter2", "[CREDENTIAL_FIELD_REDACTED]"),
(
"bearer",
"Authorization: Bearer abc.def",
"[CREDENTIAL_FIELD_REDACTED]",
),
(
"url",
"postgres://svc:hunter2@db:5432/app",
"[CREDENTIAL_FIELD_REDACTED]",
),
("email", "mail alice@example.com", "[EMAIL_REDACTED]"),
("card", "card 4111 1111 1111 1111", "[CREDIT_CARD_REDACTED]"),
];
let clean = "flushed batch to the sink ok ".repeat(36);
for (name, find, token) in rows {
let message = format!("{clean}{find}");
report.clear();
let text = s
.scrub_text(message.as_bytes(), &mut scratch, &mut report)
.unwrap_or_else(|| panic!("{name}: text missed"));
let text = String::from_utf8(text).unwrap();
assert!(
text.starts_with(&clean) && text.contains(token),
"{name}: {text}"
);
let mut fields = serde_json::Map::new();
for n in 0..24 {
fields.insert(format!("attr_{n}"), format!("value {n} ok").into());
}
fields.insert("zz_msg".to_owned(), message.into());
let line = serde_json::to_vec(&fields).unwrap();
assert!(line.len() > 1024, "{name}: {}", line.len());
report.clear();
let copy = s
.scrub_json_bytes(&line, &mut scratch, &mut report)
.unwrap()
.unwrap_or_else(|| panic!("{name}: line missed"));
let mut in_place = JsonBytes(line.clone());
report.clear();
assert_eq!(
s.scrub_in_place(&mut in_place, &mut scratch, &mut report),
Ok(true),
"{name}"
);
assert_eq!(in_place.0, copy, "{name}");
let got: serde_json::Value = serde_json::from_slice(©).unwrap();
let masked = got["zz_msg"].as_str().unwrap();
assert!(
masked.starts_with(&clean) && masked.contains(token),
"{name}: {masked}"
);
assert!(!masked.contains(find), "{name}: {masked}");
assert_eq!(got["attr_23"], "value 23 ok", "{name}");
}
}
fn text_scrubbed(s: &Scrubber, input: &str) -> String {
let (mut scratch, mut report) = (s.scratch(), s.report());
s.scrub_text(input.as_bytes(), &mut scratch, &mut report)
.map_or_else(|| input.to_owned(), |b| String::from_utf8(b).unwrap())
}
#[test]
fn a_card_is_found_after_cjk_text_and_through_zero_width_characters() {
const CARD: &str = "[CREDIT_CARD_REDACTED]";
let s = Scrubber::gitleaks().unwrap();
let in_script = |zero: u32, text: &str| -> String {
text.chars()
.map(|c| {
c.to_digit(10)
.map_or(c, |d| char::from_u32(zero + d).unwrap())
})
.collect()
};
let mut rows: Vec<(String, String)> = vec![
("card 4111 1111 1111 1111".into(), format!("card {CARD}")),
(
"\u{5361}\u{53f7}4111111111111111".into(),
format!("\u{5361}\u{53f7}{CARD}"),
),
(
"\u{5361}\u{53f7}4111 1111 1111 1111".into(),
format!("\u{5361}\u{53f7}{CARD}"),
),
(
"\u{4fe1}\u{7528}\u{5361} 4111111111111111".into(),
format!("\u{4fe1}\u{7528}\u{5361} {CARD}"),
),
(
"\u{41a}\u{430}\u{440}\u{442}\u{430} 4111111111111111".into(),
format!("\u{41a}\u{430}\u{440}\u{442}\u{430} {CARD}"),
),
(
"card 4111\u{200b}1111\u{200b}1111\u{200b}1111".into(),
format!("card {CARD}"),
),
(
"card 41\u{200b}11111111111111".into(),
format!("card {CARD}"),
),
(
"card 4111\u{ad} 1111\u{200e}-1111 \u{2066}1111".into(),
format!("card {CARD}"),
),
("\u{e9}4111 1111 1111 1111".into(), format!("\u{e9}{CARD}")),
(
"4111 1111 1111 1111\u{3067}\u{3059}".into(),
format!("{CARD}\u{3067}\u{3059}"),
),
];
for zero in [0xff10, 0x660, 0x6f0] {
rows.push((
format!("card {}", in_script(zero, "4111 1111 1111 1111")),
format!("card {CARD}"),
));
}
for (text, want) in rows {
assert_eq!(text_scrubbed(&s, &text), want, "{text:?}");
}
for text in [
"4111\u{200b}1111\u{200b}1111\u{200b}1111",
"\u{5361}\u{53f7}4111111111111112",
"ab4111 1111 1111 1111",
"card 4111 1111 1111 1111a",
"\u{5361}4111111111111111",
] {
assert_eq!(text_scrubbed(&s, text), text, "{text:?}");
}
}
#[test]
fn a_carriage_return_after_a_find_ends_it_in_every_layer() {
let s = Scrubber::gitleaks().unwrap();
let run: String = (0..36_u8).map(|i| char::from(b'a' + i * 7 % 26)).collect();
let pat = format!("ghp_{run}");
let mask = "[CREDENTIAL_FIELD_REDACTED]";
for end in ["\r", "\r\r", "\r\n", "\r\r\n"] {
let rows = [
(
format!("token {pat}{end}"),
format!("token [GITHUB_PAT_REDACTED]{end}"),
),
(
format!("password=hunter2{end}"),
format!("password={mask}{end}"),
),
(
format!("password: hunter2{end}"),
format!("password: {mask}{end}"),
),
(
format!("{{\"password\": \"hunter2\"}}{end}"),
format!("{{\"password\": \"{mask}\"}}{end}"),
),
(
format!("Authorization: Bearer abc.def{end}"),
format!("Authorization: {mask}{end}"),
),
(
format!("card 4111 1111 1111 1111{end}"),
format!("card [CREDIT_CARD_REDACTED]{end}"),
),
(
format!("mail alice@example.com{end}"),
format!("mail [EMAIL_REDACTED]{end}"),
),
];
for (text, want) in rows {
assert_eq!(text_scrubbed(&s, &text), want, "{text:?}");
let (mut scratch, mut report) = (s.scratch(), s.report());
let field = s.scrub_field(&["msg"], text.as_bytes(), &mut scratch, &mut report);
assert_eq!(
field.map(|b| String::from_utf8(b).unwrap()),
Some(want),
"field {text:?}"
);
}
let (mut scratch, mut report) = (s.scratch(), s.report());
let value = format!("hunter2{end}");
let got = s.scrub_field(&["password"], value.as_bytes(), &mut scratch, &mut report);
assert_eq!(got, Some(mask.as_bytes().to_vec()), "{end:?}");
}
}
#[test]
fn credential_terms_in_any_script_and_escaped_keys_mask_in_every_layer() {
let mask = "[CREDENTIAL_FIELD_REDACTED]";
let terms = field::CredentialMatcher::new([
"\u{43f}\u{430}\u{440}\u{43e}\u{43b}\u{44c}",
"\u{5bc6}\u{7801}",
"geheim",
])
.unwrap();
let custom = Scrubber::builder()
.credential_terms(terms)
.build(&RuleConfig::default())
.unwrap();
let (mut scratch, mut report) = (custom.scratch(), custom.report());
for name in [
"\u{43f}\u{430}\u{440}\u{43e}\u{43b}\u{44c}",
"\u{41f}\u{410}\u{420}\u{41e}\u{41b}\u{42c}",
"\u{5bc6}\u{7801}",
"geheim",
"GEHEIM",
] {
assert_eq!(
text_scrubbed(&custom, &format!("{name}=hunter2Zx9 end")),
format!("{name}={mask} end"),
"{name}"
);
let got = custom.scrub_field(&[name], b"hunter2Zx9", &mut scratch, &mut report);
assert_eq!(got, Some(mask.as_bytes().to_vec()), "{name}");
#[cfg(feature = "scrub-json")]
{
let mut record = serde_json::Map::new();
record.insert(name.to_owned(), "hunter2Zx9".into());
let mut value = serde_json::Value::Object(record);
assert!(
custom.scrub_value(&mut value, &mut scratch, &mut report),
"{name}"
);
assert_eq!(value[name], mask, "{name}");
}
}
let s = Scrubber::gitleaks().unwrap();
let escaped = "p\\u0061ssword";
assert_eq!(
text_scrubbed(&s, "{\"p\\u0061ssword\": \"hunter2Zx9\"}"),
format!("{{\"p\\u0061ssword\": \"{mask}\"}}")
);
let got = s.scrub_field(&[escaped], b"hunter2Zx9", &mut scratch, &mut report);
assert_eq!(got, Some(mask.as_bytes().to_vec()));
}
#[cfg(feature = "record")]
#[test]
fn a_raw_json_record_with_an_escaped_key_masks_its_value() {
let s = Scrubber::gitleaks().unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
let got = s
.scrub_json_bytes(
b"{\"p\\u0061ssword\": \"hunter2Zx9\", \"n\": 1}",
&mut scratch,
&mut report,
)
.unwrap()
.unwrap();
assert_eq!(
String::from_utf8(got).unwrap(),
"{\"p\\u0061ssword\": \"[CREDENTIAL_FIELD_REDACTED]\", \"n\": 1}"
);
}
#[cfg(feature = "record")]
#[test]
fn a_plain_record_leaves_no_word_that_later_text_is_plain() {
let s = Scrubber::gitleaks().unwrap();
let (mut scratch, mut report) = (s.scratch(), s.report());
for record in [
&br#"{"msg":"ok"}"#[..],
br#"{"password":"hunter2Zx9"}"#,
b"not json",
] {
let _ = s.scrub_json_bytes(record, &mut scratch, &mut report);
for (text, secret) in [
("password\u{ff1a}hunter2Zx9 end", "hunter2Zx9"),
("p\\u0061ssword=hunter2Zx9 end", "hunter2Zx9"),
("pass\x1b[1mword=hunter2Zx9 end", "hunter2Zx9"),
("card 4111 1111 1111 1111", "1111"),
] {
let out = s
.scrub_text(text.as_bytes(), &mut scratch, &mut report)
.map(String::from_utf8)
.transpose()
.unwrap();
assert!(out.is_some_and(|o| !o.contains(secret)), "{text:?}");
}
}
let got = s
.scrub_json_bytes(
"{\"msg\":\"password\u{ff1a}hunter2Zx9 end\"}".as_bytes(),
&mut scratch,
&mut report,
)
.unwrap()
.unwrap();
assert!(!String::from_utf8(got).unwrap().contains("hunter2Zx9"));
}
#[cfg(feature = "record")]
mod plain_paths {
use std::sync::LazyLock;
use proptest::prelude::*;
use super::*;
use crate::scrub::field::with_plain_off;
static SCRUBBER: LazyLock<Scrubber> = LazyLock::new(|| Scrubber::gitleaks().unwrap());
#[derive(Debug, PartialEq, Eq)]
struct Seen {
out: Result<Option<Vec<u8>>, crate::record::Miss>,
changed: bool,
counts: Vec<String>,
}
fn seen(out: Result<Option<Vec<u8>>, crate::record::Miss>, report: &Report) -> Seen {
Seen {
out,
changed: report.changed(),
counts: report
.entries()
.map(|e| format!("{} {:?} {:?} {}", e.rule, e.layer, e.kind, e.count))
.collect(),
}
}
thread_local! {
static RIG: std::cell::RefCell<(ScrubScratch, Report)> = std::cell::RefCell::new({
let s = &*SCRUBBER;
(s.scratch(), s.report())
});
}
fn text(input: &[u8]) -> Seen {
RIG.with_borrow_mut(|(scratch, report)| {
report.clear();
let out = SCRUBBER.scrub_text(input, scratch, report);
seen(Ok(out), report)
})
}
fn json(input: &[u8]) -> Seen {
RIG.with_borrow_mut(|(scratch, report)| {
report.clear();
let out = SCRUBBER.scrub_json_bytes(input, scratch, report);
seen(out, report)
})
}
fn same_both_ways(input: &[u8]) {
for (name, run) in [("text", text as fn(&[u8]) -> Seen), ("json", json)] {
let fast = run(input);
let general = with_plain_off(|| run(input));
assert_eq!(
fast,
general,
"{name}: {:?}",
String::from_utf8_lossy(input)
);
}
}
const PIECES: &[&str] = &[
"password",
"token",
"api_key",
"Authorization",
"=",
":",
" ",
" ",
"\"",
"{",
"}",
",",
"hunter2Zx9",
"ghp_",
"abcdefghijklmnopqrstuvwxyz0123456789",
"4111 1111 1111 1111",
"card ",
"alice@example.com",
"%3D",
"=>",
":=",
"\\",
"\\\\",
"\\u0061",
"\x1b[1m",
"\x1b[0m",
"\u{e9}",
"\u{ff1a}",
"\u{200b}",
"\u{5bc6}\u{7801}",
"Bearer ",
"?sig=",
"&",
"://u:p@h/",
"\r",
"\n",
];
const LENGTHS: &[usize] = &[0, 1, 8, 9, 31, 32, 33, 63, 64, 65, 66, 127, 128, 129, 130];
proptest! {
#![proptest_config(ProptestConfig::with_cases(6_000))]
#[test]
fn arbitrary_bytes_scrub_the_same(input in proptest::collection::vec(any::<u8>(), 0..300)) {
same_both_ways(&input);
}
#[test]
fn pieces_of_a_log_line_scrub_the_same(
pieces in proptest::collection::vec(proptest::sample::select(PIECES.to_vec()), 0..40)
) {
same_both_ways(pieces.concat().as_bytes());
}
#[test]
fn json_records_whose_names_and_values_differ_in_plainness_scrub_the_same(
members in proptest::collection::vec(
(
proptest::sample::select(vec![
"msg", "password", "token", "api_key", "note", "attr_1", "caf\u{e9}",
"p\u{e4}ssword", "password\u{200b}", "\u{5bc6}\u{7801}",
"p\\u0061ssword", "a\\\\b", "x\\\"y",
]),
proptest::sample::select(vec![
"\"hunter2Zx9\"", "\"ok\"", "\"2026-12-01T10:00:00Z\"",
"\"password=hunter2Zx9 end\"", "\"caf\\u00e9\"", "\"caf\u{e9}\"",
"\"x\\ty\"", "\"\\u001b[1mpassword=hunter2Zx9\"", "\"p\\u0061ssword: x\"",
"\"card 4111 1111 1111 1111\"", "\"\\u5bc6\\u7801=hunter2Zx9\"",
"1", "true", "null", "[1,\"a\"]", "{\"a\":\"b\"}", "\"\"",
]),
),
0..12,
)
) {
let body: Vec<String> = members.iter().map(|(k, v)| format!("\"{k}\":{v}")).collect();
same_both_ways(format!("{{{}}}", body.join(",")).as_bytes());
}
}
#[test]
fn one_odd_byte_at_every_place_scrubs_the_same() {
let filler = "password=hunter2Zx9 card 4111 1111 1111 1111 mail a@b.co token: abc ";
let odd: &[&[u8]] = &[
b"\\",
b"\x1b",
b"\xc3\xa9",
b"\xef\xbc\x9a",
b"\x80",
b"\xff",
b"%",
b":",
b"\"",
b"\xe2\x80\x8b",
];
let mut cases = 0;
for &len in LENGTHS {
let base: Vec<u8> = filler.bytes().cycle().take(len).collect();
for at in 0..=len {
for bytes in odd {
let mut line = base[..at].to_vec();
line.extend_from_slice(bytes);
line.extend_from_slice(&base[at..]);
same_both_ways(&line);
if let Ok(line) = String::from_utf8(line) {
let escaped = serde_json::to_string(&line).unwrap();
same_both_ways(format!("{{\"msg\":{escaped},\"n\":1}}").as_bytes());
same_both_ways(format!("{{{escaped}:\"hunter2Zx9\"}}").as_bytes());
let raw = line.replace(['\\', '"'], "_");
same_both_ways(format!("{{\"msg\":\"{raw}\"}}").as_bytes());
}
cases += 6;
}
}
}
assert!(cases > 40_000, "{cases}");
}
#[test]
fn corpus_lines_scrub_the_same() {
use crate::shared_tests::corpus::for_each_record_of;
let tags = [
"syslog", "cef", "leef", "kv", "mixed", "access", "text", "csv", "tsv", "json",
"ndjson", "naughty", "xml", "http",
];
let n = for_each_record_of(&tags, |r| same_both_ways(r.bytes));
assert!(n > 100, "{n}");
}
}
#[test]
fn an_allowlist_for_one_of_two_overlapping_cards_leaves_the_other_masked() {
let text = "card 3340 9124 0063 4548 9800";
for (allow, exempt_first) in [
(
AllowlistConfig {
stopwords: vec!["3340".to_owned()],
..AllowlistConfig::default()
},
true,
),
(
AllowlistConfig {
regexes: vec!["^3340".to_owned()],
..AllowlistConfig::default()
},
true,
),
(
AllowlistConfig {
stopwords: vec!["9800".to_owned()],
..AllowlistConfig::default()
},
false,
),
] {
let s = Scrubber::builder()
.allow_rules(["credit-card"], allow)
.build(&RuleConfig::default())
.unwrap();
let out = text_scrubbed(&s, text);
assert!(out.contains("[CREDIT_CARD_REDACTED]"), "{out}");
let masked: &[&str] = if exempt_first {
&["9124", "0063", "4548", "9800"]
} else {
&["3340", "9124", "0063", "4548"]
};
for group in masked {
assert!(!out.contains(group), "{group}: {out}");
}
}
}
fn card_scrubber(allow: AllowlistConfig, observe: bool) -> Scrubber {
let mut b = Scrubber::builder().allow_rules(["credit-card"], allow);
if observe {
b = b.observe_rules(["credit-card"]);
}
b.build(&RuleConfig::default()).unwrap()
}
#[test]
fn a_card_inside_an_exempt_longer_card_is_masked() {
let exempt_long = AllowlistConfig {
stopwords: vec!["\u{200b}".to_owned()],
..AllowlistConfig::default()
};
let s = card_scrubber(exempt_long, false);
for text in [
"card 4111 1111 1111 1111\u{200b}3",
"\u{5361}\u{53f7}4111 1111 1111 1111\u{200b}3",
"\u{e9}4111 1111 1111 1111\u{200b}3 card",
] {
let out = text_scrubbed(&s, text);
assert!(out.contains("[CREDIT_CARD_REDACTED]"), "{text:?}: {out:?}");
assert!(!out.contains("4111"), "{text:?}: {out:?}");
}
}
#[test]
fn observe_counts_an_exempt_card_inside_an_observed_span() {
let exempt_short = AllowlistConfig {
regexes: vec!["^4111 1111 1111 1111$".to_owned()],
..AllowlistConfig::default()
};
let s = card_scrubber(exempt_short, true);
let (mut scratch, mut report) = (s.scratch(), s.report());
let out = s.scrub_text(
"card 4111 1111 1111 1111\u{200b}3".as_bytes(),
&mut scratch,
&mut report,
);
assert_eq!(out, None);
assert_eq!(report.count("credit-card", Kind::Observed), 1);
assert_eq!(report.count("credit-card", Kind::AllowlistedValue), 1);
}
fn scrubs_in_linear_time(s: &Scrubber, make: impl Fn(usize) -> String) {
use std::time::{Duration, Instant};
const FACTOR: usize = 32;
const BOUND: u32 = 256;
const FLOOR: Duration = Duration::from_millis(5);
let (short, long) = (make(250), make(250 * FACTOR));
let (mut scratch, mut report) = (s.scratch(), s.report());
let mut time = |text: &str| {
report.clear();
let start = Instant::now();
let _ = s.scrub_text(text.as_bytes(), &mut scratch, &mut report);
start.elapsed()
};
let (mut fast, mut slow) = (Duration::MAX, Duration::MAX);
for _ in 0..5 {
fast = fast.min(time(&short));
slow = slow.min(time(&long));
}
assert!(
slow < fast.max(FLOOR) * BOUND,
"{FACTOR}x the input took {slow:?} against {fast:?}"
);
}
#[test]
fn many_cards_on_one_line_scrub_in_linear_time() {
let s = card_scrubber(
AllowlistConfig {
stopwords: vec!["zzzz".to_owned()],
..AllowlistConfig::default()
},
false,
);
scrubs_in_linear_time(&s, |n| "card 4111 1111 1111 1111 ".repeat(n));
scrubs_in_linear_time(&s, |n| {
"card 4111\u{200b}1111 1111 1111\u{200b}1 ".repeat(n)
});
}
#[test]
fn many_exempt_cards_inside_masked_ones_scrub_in_linear_time() {
let s = card_scrubber(
AllowlistConfig {
regexes: vec!["^4111 1111 1111 1111$".to_owned()],
..AllowlistConfig::default()
},
false,
);
scrubs_in_linear_time(&s, |n| "card 4111 1111 1111 1111\u{200b}3\n".repeat(n));
}
#[test]
fn many_cards_on_one_line_with_a_line_regex_scrub_in_linear_time() {
let s = card_scrubber(
AllowlistConfig {
regexes: vec!["nevermatches[0-9]{9}".to_owned()],
regex_target: Some("line".to_owned()),
..AllowlistConfig::default()
},
false,
);
scrubs_in_linear_time(&s, |n| "card 4111 1111 1111 1111 ".repeat(n));
}