use serde_json::Value;
use super::super::redact::Redactor;
use super::super::report::{Layer, RuleMeta};
use super::*;
fn scrub_one(v: &Pii, text: &str) -> String {
let token = RuleMeta::new(v.id, Layer::Pii).token;
let mut out = String::new();
let mut copied = 0;
v.confirmed(text, |m| {
out.push_str(&text[copied..m.start]);
Redactor::Mask.write_str(&mut out, &token, b"");
copied = m.end;
});
out.push_str(&text[copied..]);
out
}
fn narrowing() -> toml::Table {
include_str!("../../tests/fixtures/scrub/narrowing_fixtures.toml")
.parse()
.unwrap()
}
fn strings<'a>(table: &'a toml::Value, key: &str) -> Vec<&'a str> {
table[key]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_str().unwrap())
.collect()
}
#[test]
fn a_card_needs_its_grouping_or_a_card_word() {
let narrowing = narrowing();
let cards = &narrowing["credit_card"];
let v = defaults().unwrap();
let card = v.iter().find(|v| v.id == "credit-card").unwrap();
for text in strings(cards, "redact") {
assert!(
scrub_one(card, text).contains("[CREDIT_CARD_REDACTED]"),
"{text}"
);
}
for text in strings(cards, "unchanged") {
assert_eq!(scrub_one(card, text), text);
}
let start = cards["epoch_ms_start"].as_integer().unwrap();
let count = cards["epoch_ms_count"].as_integer().unwrap();
let luhn_valid = (start..start + count)
.map(|ms| ms.to_string())
.filter(|ms| {
assert_eq!(scrub_one(card, ms), *ms);
luhn(ms)
})
.count();
assert!(
luhn_valid > 50,
"the run must hold Luhn-valid values to prove anything"
);
}
#[test]
fn every_fixture_sample_matches_the_recorded_output() {
let narrowing = narrowing();
let unchanged = strings(&narrowing["supersedes"]["credit_card"], "unchanged");
let expected: Value =
serde_json::from_str(include_str!("../../tests/fixtures/scrub/pii_expected.json")).unwrap();
let validators = defaults().unwrap();
let mut wrong = Vec::new();
let mut checked = 0;
for (section, kinds) in expected.as_object().unwrap() {
if section.starts_with('_') {
continue;
}
let id = section.replace('_', "-");
if section == "phone" && cfg!(not(feature = "scrub-phone")) {
continue;
}
let v = validators
.iter()
.find(|v| v.id == id)
.unwrap_or_else(|| panic!("no validator for {section}"));
for (kind, pairs) in kinds.as_object().unwrap() {
for pair in pairs.as_array().unwrap() {
let input = pair[0].as_str().unwrap();
let narrowed = section == "credit_card" && unchanged.contains(&input);
let want = if narrowed {
input
} else {
pair[1].as_str().unwrap()
};
let got = scrub_one(v, input);
checked += 1;
if got != want {
wrong.push(format!(
"{section}.{kind}: {input:?} -> {got:?}, want {want:?}"
));
}
}
}
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
assert_eq!(
checked,
if cfg!(feature = "scrub-phone") {
69
} else {
60
}
);
}
#[test]
fn checksums_reject_one_digit_off() {
assert!(luhn("4111 1111 1111 1111"));
assert!(!luhn("4111 1111 1111 1112"));
assert!(!luhn("4111"));
assert!(au_abn("53 004 085 616") && !au_abn("53 004 085 617"));
assert!(au_acn("004 085 616") && !au_acn("004 085 617"));
assert!(au_tfn("123 456 782") && !au_tfn("123 456 783"));
assert!(au_tfn("87654321") && !au_tfn("12345678"));
assert!(au_medicare("2428 77813 2") && !au_medicare("2428 77814 2"));
assert!(!au_medicare("1428778132"));
assert!(!au_medicare("24287781320"));
assert!(iban("GB82 WEST 1234 5698 7654 32"));
assert!(!iban("GB82 WEST 1234 5698 7654 33"));
assert!(luhn(
"\u{664}\u{661}\u{661}\u{661}\u{661}\u{661}\u{661}\u{661}\u{661}\u{661}\u{661}\u{661}\u{661}\u{661}\u{661}\u{661}"
));
assert!(!luhn("\u{664}111111111111112"));
}
#[test]
fn decimal_digits_read_by_their_place_in_a_run_of_ten() {
assert!(!DECIMALS.is_empty());
for &(lo, hi) in DECIMALS.iter() {
assert_eq!((hi - lo + 1) % 10, 0, "{lo:x}..{hi:x}");
}
for (c, d) in [
('0', 0),
('9', 9),
('\u{660}', 0),
('\u{663}', 3),
('\u{ff19}', 9),
('\u{966}', 0),
('\u{1d7ce}', 0),
('\u{1d7d9}', 1),
('\u{1d7ff}', 9),
] {
assert_eq!(decimal(c), Some(d), "{c:?}");
}
for c in [
'a', ' ', '\u{bd}', '\u{b2}', '\u{2167}', '\u{4e00}', '\u{e9}',
] {
assert_eq!(decimal(c), None, "{c:?}");
}
}
#[test]
fn digits_and_spaces_of_other_scripts_are_confirmed_as_ascii_ones_are() {
let v = defaults().unwrap();
let find = |id: &str| v.iter().find(|v| v.id == id).unwrap();
for zero in ['0', '\u{660}', '\u{ff10}', '\u{966}', '\u{1d7ce}'] {
for space in [' ', '\u{a0}', '\u{202f}', '\u{3000}', '\u{2009}'] {
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 (id, text) in [
("credit-card", "card 4111 1111 1111 1111"),
("credit-card", "4111 1111 1111 1111"),
("credit-card", "5500 000000 00004"),
("au-tfn", "tfn 123 456 782"),
("au-abn", "abn 53 004 085 616"),
("au-acn", "acn 004 085 616"),
("au-medicare", "medicare 2428 77813 2"),
] {
let out = scrub_one(find(id), &script(text));
assert!(out.contains("_REDACTED]"), "{id}: {out:?}");
}
let off = script("card 4111 1111 1111 1112");
assert_eq!(scrub_one(find("credit-card"), &off), off);
}
}
for space in [' ', '\u{a0}', '\u{202f}', '\u{2009}'] {
let text = format!("GB82{space}WEST{space}1234{space}5698{space}7654{space}32");
assert!(
scrub_one(find("iban"), &text).contains("REDACTED"),
"{space:?}"
);
}
let card = find("credit-card");
assert!(scrub_one(card, "card \u{ff14}111-1111-1111-1111").contains("REDACTED"));
for dash in ['-', '\u{2010}', '\u{2011}', '\u{2013}', '\u{ff0d}'] {
let text = format!("4111{dash}1111{dash}1111{dash}1111");
assert!(scrub_one(card, &text).contains("REDACTED"), "{dash:?}");
}
let letters = "card 4111 1111 11a1 1111";
assert_eq!(scrub_one(card, letters), letters);
}
#[test]
fn a_keyword_counts_only_within_30_characters() {
let near = format!("tfn {}123 456 782", " ".repeat(25));
let far = format!("tfn {}123 456 782", " ".repeat(27));
let v = defaults().unwrap();
let tfn = v.iter().find(|v| v.id == "au-tfn").unwrap();
assert!(scrub_one(tfn, &near).contains("[AU_TFN_REDACTED]"));
assert_eq!(scrub_one(tfn, &far), far);
for text in [
format!("tfn {}123 456 782", "e\u{301}".repeat(25)),
format!("tfn {}123 456 782", "\u{e9}".repeat(25)),
format!("tfn \u{200b}{}123 456 782", "a\u{301}\u{323}".repeat(24)),
] {
assert!(
scrub_one(tfn, &text).contains("[AU_TFN_REDACTED]"),
"{text:?}"
);
}
let far = format!("tfn {}123 456 782", "e\u{301}".repeat(27));
assert_eq!(scrub_one(tfn, &far), far);
let marks = format!("tfn e{}123 456 782", "\u{301}".repeat(120));
assert_eq!(scrub_one(tfn, &marks), marks);
}
#[test]
fn an_id_beside_a_word_of_a_script_without_spaces_is_found() {
let v = defaults().unwrap();
let find = |id: &str| v.iter().find(|v| v.id == id).unwrap();
for (id, text) in [
("au-abn", "ABN\u{53f7}\u{7801}53004085616"),
("au-abn", "abn 53 004 085 616\u{53f7}"),
("au-acn", "ACN\u{756a}\u{53f7}004085616"),
("au-tfn", "TFN\u{756a}\u{53f7}123456782"),
("au-medicare", "medicare\u{756a}\u{53f7}2428778132"),
("iban", "\u{8d26}\u{6237}GB82WEST12345698765432"),
("iban", "GB82WEST12345698765432\u{53f7}"),
] {
assert!(
scrub_one(find(id), text).contains("_REDACTED]"),
"{id}: {text}"
);
}
for (id, text) in [
("au-abn", "abn x53004085616"),
("au-tfn", "tfn 123456782x"),
("iban", "xGB82WEST12345698765432"),
] {
assert_eq!(scrub_one(find(id), text), text, "{id}");
}
}
#[test]
fn an_address_with_any_idna_dot_is_masked() {
let v = defaults().unwrap();
let email = v.iter().find(|v| v.id == "email").unwrap();
for dot in ['.', '\u{3002}', '\u{ff0e}', '\u{ff61}'] {
let text = format!("mail alice@mail{dot}example{dot}com today");
assert_eq!(
scrub_one(email, &text),
"mail [EMAIL_REDACTED] today",
"{dot:?}"
);
}
let japanese = "mail user@\u{4f8b}\u{3048}.\u{30c6}\u{30b9}\u{30c8} today";
assert_eq!(scrub_one(email, japanese), "mail [EMAIL_REDACTED] today");
for text in ["x@y.\u{301}", "x@y.\u{301}\u{302}", "x@y.1\u{301}"] {
assert_eq!(scrub_one(email, text), text, "{text:?}");
}
}
#[test]
fn a_card_word_inside_an_accented_word_does_not_count() {
let v = defaults().unwrap();
let card = v.iter().find(|v| v.id == "credit-card").unwrap();
for (text, masked) in [
("pan\u{e9} 4111111111111111", false),
("\u{e9}card 4111111111111111", false),
("panel 4111111111111111", false),
("pan 4111111111111111", true),
("cc_number 4111111111111111", true),
("visa\u{5361}4111111111111111", true),
("\u{652f}\u{4ed8}card 4111111111111111", true),
] {
let out = scrub_one(card, text);
assert_eq!(
out.contains("[CREDIT_CARD_REDACTED]"),
masked,
"{text:?}: {out}"
);
}
}
#[test]
fn email_masks_addresses_and_leaves_lookalikes() {
let v = defaults().unwrap();
let email = v.iter().find(|v| v.id == "email").unwrap();
for (input, want) in [
("q=alice%40example.com&x=1", "q=[EMAIL_REDACTED]&x=1"),
("cc o'brien@example.ie", "cc [EMAIL_REDACTED]"),
("email='user@example.com'", "email='[EMAIL_REDACTED]'"),
("'o'brien@example.ie'", "'[EMAIL_REDACTED]'"),
("d'arcy-o'neil@example.com", "[EMAIL_REDACTED]"),
("to=%22bob%2540example.com%22", "to=%22[EMAIL_REDACTED]%22"),
("q=%253Dalice%2540example.com", "q=%253D[EMAIL_REDACTED]"),
(
"q=%2522alice%2540example.com%2522",
"q=%2522[EMAIL_REDACTED]%2522",
),
("q=%253Falice@example.com", "q=%253F[EMAIL_REDACTED]"),
("q=%253dalice%40example.com", "q=%253d[EMAIL_REDACTED]"),
("pkg@1.2.3 and user@10.0.0.1", "pkg@1.2.3 and user@10.0.0.1"),
(
"_SYSTEMD_UNIT=user@1000.service",
"_SYSTEMD_UNIT=user@1000.service",
),
(
"/user-1001.slice/user@1001.service/app.slice",
"/user-1001.slice/user@1001.service/app.slice",
),
("getty@tty1.service", "getty@tty1.service"),
("ops@host.service.example.com", "[EMAIL_REDACTED]"),
("ops@corp.internal", "[EMAIL_REDACTED]"),
] {
assert_eq!(scrub_one(email, input), want, "{input}");
}
}
#[test]
fn the_exported_rule_ids_are_the_validators_in_order() {
let ids: Vec<&str> = defaults().unwrap().iter().map(|p| p.id).collect();
assert_eq!(ids, super::super::PII_RULES);
}
fn all_strings(value: &toml::Value, out: &mut Vec<String>) {
match value {
toml::Value::String(s) => out.push(s.clone()),
toml::Value::Array(items) => items.iter().for_each(|v| all_strings(v, out)),
toml::Value::Table(table) => table.values().for_each(|v| all_strings(v, out)),
_ => {}
}
}
#[test]
fn the_gate_names_a_validator_wherever_its_pattern_matches() {
let validators = defaults().unwrap();
let gate = Gate::new(&validators).unwrap();
let mut seen = gate.scratch();
let mut texts: Vec<String> = [
"",
"2026-11-28T11:00:00.123Z INFO web01 request served path=/v1/items/7 status=200 bytes=259",
"card 4111 1111 1111 1111 on file",
"IBAN GB82 WEST 1234 5698 7654 32",
"ABN 51 824 753 556",
"ACN 004 085 616",
"medicare 2123 45670 1",
"TFN 123 456 782",
"call +61 2 9374 4000 today",
"mail bob@example.com",
"epoch 1764288000123 and id 12345678",
"caf\u{e9} 51 824 753 556 na\u{ef}ve 4111-1111-1111-1111",
]
.map(str::to_owned)
.to_vec();
all_strings(&toml::Value::Table(narrowing()), &mut texts);
texts.extend(
[
"12",
"AB12",
"GB82WEST12345698765432",
"\u{663}\u{664} \u{665}",
"a@b",
"%40",
]
.map(str::to_owned),
);
let mut fired = vec![0_usize; validators.len()];
for text in &texts {
let candidates = gate.candidates(text, &mut seen);
for (k, v) in validators.iter().enumerate() {
let own = v.check == Check::Email || v.regex.is_match(text.as_bytes());
let mut kept = false;
v.confirmed(text, |_| kept = true);
let matched = v.check != Check::Email && own;
assert!(
gate.may_find(text.as_bytes()) || !(kept || matched),
"{} on {text:?}",
v.id
);
let named = candidates >> k & 1 == 1;
if text.is_ascii() {
assert_eq!(named, own, "{} on {text:?}", v.id);
} else {
assert!(named || !own, "{} on {text:?}", v.id);
}
fired[k] += usize::from(own);
}
}
for (v, n) in validators.iter().zip(fired) {
assert!(
n > 0 && n < texts.len() || v.check == Check::Email,
"{}: {n}",
v.id
);
}
let fewer = Gate::new(&validators[..2]).unwrap();
assert_eq!(fewer.candidates(&texts[2], &mut seen) & 1, 1);
}
#[test]
fn a_pattern_says_the_least_its_matches_hold() {
let rows: &[(&str, usize, usize)] = &[
(r"\d{3}[ ]?\d{3}", 6, 6),
(r"a1b2", 2, 4),
(r"[0-5]", 1, 1),
(r"[0-9a]", 0, 1),
(r"\d{2,}|x", 0, 1),
(r"(?:\d[ -]?){2}\d\b", 3, 3),
(r"\+?\d[\d .]{2,4}\d", 2, 4),
(r"[^\D]", 1, 1),
(r"\b", 0, 0),
];
for &(pattern, digits, bytes) in rows {
let least = Least::of(®ex_syntax::parse(pattern).unwrap());
assert_eq!((least.digits, least.bytes), (digits, bytes), "{pattern}");
}
let ids: Vec<(&str, usize, usize)> = defaults()
.unwrap()
.iter()
.filter(|v| v.check != Check::Email)
.map(|v| {
let least = Least::of(®ex_syntax::parse(v.pattern).unwrap());
(v.id, least.digits, least.bytes)
})
.collect();
for (id, digits, bytes) in ids {
let want = match id {
"credit-card" => (13, 13),
"iban" => (2, 15),
"phone" => (2, 8),
"au-abn" => (11, 11),
"au-acn" => (9, 9),
"au-medicare" => (10, 10),
"au-tfn" => (8, 8),
other => panic!("no row for {other}"),
};
assert_eq!((digits, bytes), want, "{id}");
}
}
fn email_candidates_by_regex(body: &Regex, text: &str, on: &mut impl FnMut(Range<usize>)) {
let mut at = 0;
while let Some((i, c)) = text[at..].char_indices().next() {
let start = at + i;
if is_local(c) && email_may_start(text, start) {
let input = Input::new(text.as_bytes())
.range(start..)
.anchored(Anchored::Yes);
if let Some(m) = body.find(input) {
on(m.range());
at = m.end();
continue;
}
at = local_part_end(text, start);
continue;
}
at = start + c.len_utf8();
}
}
const EMAIL_ALPHABET: &[&str] = &[
"a",
"bob",
"x1",
"_",
"-",
".",
"+",
"@",
"%40",
"%2540",
"%2B",
"%252b",
"%",
"25",
"40",
"example",
".com",
" ",
"\"",
":",
"é",
"\n",
"/",
"2B",
"7",
"@timestamp",
];
proptest::proptest! {
#![proptest_config(proptest::prelude::ProptestConfig::with_cases(20_000))]
#[test]
fn email_candidates_are_the_bodys_matches(
parts in proptest::collection::vec(proptest::sample::select(EMAIL_ALPHABET.to_vec()), 0..30)
) {
static EMAIL: std::sync::LazyLock<Pii> = std::sync::LazyLock::new(|| {
let validators = defaults().unwrap();
validators.into_iter().find(|v| v.check == Check::Email).unwrap()
});
let text = parts.concat();
let (mut found, mut by_regex) = (Vec::new(), Vec::new());
email_candidates(&EMAIL.regex, &text, &mut |m| found.push(m));
email_candidates_by_regex(&EMAIL.regex, &text, &mut |m| by_regex.push(m));
proptest::prop_assert_eq!(found, by_regex, "{:?}", text);
}
}
const CARD_BASELINE: &str = r"\b(?:\d[\p{Zs}\p{Pd}]?){12,18}\d\b";
struct OldCard {
regex: Regex,
}
impl OldCard {
fn new() -> Self {
Self {
regex: Regex::new(CARD_BASELINE).unwrap(),
}
}
fn confirmed(&self, text: &str) -> Vec<Range<usize>> {
self.regex
.find_iter(text.as_bytes())
.map(|m| m.range())
.filter(|m| {
let candidate = &text[m.clone()];
(card_grouped(candidate) || has_word(text, m.start, &CARD_WORDS)) && luhn(candidate)
})
.collect()
}
}
fn keeps_every_old_card(old: &OldCard, card: &Pii, text: &str) {
let mut now = Vec::new();
card.confirmed(text, |m| now.push(m));
for was in old.confirmed(text) {
assert!(
now.iter().any(|n| n.start <= was.start && was.end <= n.end),
"{text:?}: {was:?} was masked and is not in {now:?}"
);
}
}
fn the_card() -> Pii {
defaults()
.unwrap()
.into_iter()
.find(|v| v.id == "credit-card")
.unwrap()
}
#[test]
fn a_candidate_that_fails_never_hides_a_card_inside_it() {
let (old, card) = (OldCard::new(), the_card());
let cards = [
"4111 1111 1111 1111",
"5500 0000 0000 0004",
"4111-1111-1111-1111",
];
let before = [
"",
" ",
"1 ",
"12 ",
"1234 ",
"9\u{a0}",
"1\u{200b} ",
"1 \u{200b}",
"\u{5361}\u{53f7}1 ",
"\u{e9}1 ",
"\u{e9}12 ",
"\u{3} ",
"\u{663} ",
"\u{663}\u{664} ",
"\u{ff11} ",
"\u{ff11}\u{ff12}\u{ff13} ",
"7-",
"7\u{2013}",
"card 1 ",
"x1 ",
"1\u{200b}",
"\u{5361}\u{53f7}\u{663}",
];
let after = [
"",
" 1",
" 12",
"\u{200b}1",
"\u{a0}9",
" \u{663}",
"\u{3067}\u{3059}",
"x",
" x",
"-1",
"\u{ad}",
];
let mut cases = 0;
for b in before {
for c in cards {
for a in after {
keeps_every_old_card(&old, &card, &format!("{b}{c}{a}"));
keeps_every_old_card(&old, &card, &format!("card {b}{c}{a}"));
cases += 2;
}
}
}
assert!(cases > 1_000, "{cases}");
}
#[test]
fn a_card_next_to_other_digits_stays_masked_on_generated_text() {
use proptest::prelude::*;
let (old, card) = (OldCard::new(), the_card());
let pieces = [
"4111",
"1111",
"5500",
"0004",
"1",
"12",
"7",
" ",
"\u{a0}",
"-",
"\u{200b}",
"\u{ad}",
"\u{5361}",
"\u{e9}",
"x",
"card ",
"\u{663}\u{664}",
"\u{ff11}",
"4111 1111 1111 1111",
"5500 0000 0000 0004",
"\u{2013}",
"\u{3000}",
];
let mut runner = proptest::test_runner::TestRunner::new(ProptestConfig::with_cases(20_000));
runner
.run(
&proptest::collection::vec(proptest::sample::select(pieces.to_vec()), 0..16),
|parts| {
keeps_every_old_card(&old, &card, &parts.concat());
Ok(())
},
)
.unwrap();
}
#[test]
fn corpus_lines_keep_every_card_they_had_masked() {
use crate::shared_tests::corpus::for_each_record_of;
let (old, card) = (OldCard::new(), the_card());
let tags = [
"syslog", "cef", "leef", "kv", "mixed", "access", "text", "csv", "tsv", "json", "ndjson",
"naughty", "xml", "http",
];
let n = for_each_record_of(&tags, |r| {
keeps_every_old_card(&old, &card, &String::from_utf8_lossy(r.bytes));
});
assert!(n > 100, "{n}");
}
fn masked_spans(card: &Pii, text: &str) -> Vec<Range<usize>> {
let mut spans = Vec::new();
card.confirmed(text, |m| spans.push(m));
spans
}
fn independent_cards(card: &Pii, text: &str) -> Vec<Range<usize>> {
let bytes = text.as_bytes();
let is_digit = |c: char| decimal(c).is_some();
let mut found = Vec::new();
for (start, c) in text.char_indices() {
if !is_digit(c) || text[..start].chars().next_back().is_some_and(is_digit) {
continue;
}
let mut digits = 0;
for (offset, d) in text[start..].char_indices() {
let end = start + offset + d.len_utf8();
if is_digit(d) {
digits += 1;
}
if digits > 19 || !(is_digit(d) || is_group_separator(d) || is_ignorable(d)) {
break;
}
if !is_digit(d) || text[end..].chars().next().is_some_and(is_digit) {
continue;
}
let span = start..end;
let read = card.regex.find(
regex_automata::Input::new(bytes)
.range(span.clone())
.anchored(Anchored::Yes),
);
if read.is_some_and(|m| m.end() == end) && card.accepts(text, &span) {
found.push(span);
}
}
}
found
}
fn masks_every_card(card: &Pii, text: &str) {
let masked = masked_spans(card, text);
for want in independent_cards(card, text) {
assert!(
masked
.iter()
.any(|m| m.start <= want.start && want.end <= m.end),
"{text:?}: {want:?} is a card and is not inside {masked:?}"
);
}
}
#[test]
fn a_card_that_overlaps_a_shorter_card_is_masked_whole() {
let card = the_card();
for text in [
"card 4111 1111 1111 1111\u{200b}3",
"card 5500 0000 0000 0004\u{ad}6",
"card 4111 1111 1111 1111\u{2066}3",
] {
let spans = masked_spans(&card, text);
assert_eq!(spans.len(), 1, "{text:?}");
assert_eq!((spans[0].start, spans[0].end), (5, text.len()), "{text:?}");
masks_every_card(&card, text);
}
}
#[test]
fn a_wide_candidate_that_ends_inside_a_digit_run_leaves_its_prefix_card_found() {
let card = the_card();
for text in [
"\u{5361}\u{53f7}4111 1111 1111 1111\u{200b}123456789",
"\u{5361}\u{53f7}4111 1111 1111 1111\u{200b}\u{663}\u{664}\u{665}\u{666}\u{667}\u{668}",
"\u{e9}4111 1111 1111 1111\u{ad}1234567890123",
"card 4111 1111 1111 1111\u{200b}1234567890123",
] {
let spans = masked_spans(&card, text);
assert!(!spans.is_empty(), "{text:?}");
masks_every_card(&card, text);
}
}
#[test]
fn every_card_the_pattern_can_read_is_masked_on_generated_text() {
use proptest::prelude::*;
let card = the_card();
let pieces = [
"4111",
"1111",
"5500",
"0004",
"1",
"12",
"3",
"7",
"4111 1111 1111 1111",
"5500 0000 0000 0004",
" ",
"\u{a0}",
"-",
"\u{200b}",
"\u{ad}",
"\u{202e}",
"\u{2066}",
"\u{2069}",
"\u{200f}",
"\u{5361}",
"\u{5361}\u{53f7}",
"\u{e9}",
"x",
"card ",
"\u{663}\u{664}",
"\u{ff11}\u{ff12}",
"\u{2013}",
"\u{3000}",
"\u{3067}",
];
let mut runner = proptest::test_runner::TestRunner::new(ProptestConfig::with_cases(30_000));
runner
.run(
&proptest::collection::vec(proptest::sample::select(pieces.to_vec()), 0..16),
|parts| {
masks_every_card(&card, &parts.concat());
Ok(())
},
)
.unwrap();
}
#[test]
fn corpus_lines_mask_every_card_the_pattern_can_read() {
use crate::shared_tests::corpus::for_each_record_of;
let card = the_card();
let tags = [
"syslog", "cef", "leef", "kv", "mixed", "access", "text", "csv", "tsv", "json", "ndjson",
"naughty", "xml", "http",
];
let n = for_each_record_of(&tags, |r| {
masks_every_card(&card, &String::from_utf8_lossy(r.bytes));
});
assert!(n > 100, "{n}");
}
fn scrubber_allowing(stopwords: &[&str]) -> crate::scrub::Scrubber {
use crate::scrub::config::AllowlistConfig;
crate::scrub::Scrubber::builder()
.allow_rules(
["credit-card"],
AllowlistConfig {
stopwords: stopwords.iter().map(|w| (*w).to_owned()).collect(),
..AllowlistConfig::default()
},
)
.build(&crate::scrub::config::RuleConfig::default())
.unwrap()
}
fn production_masks_every_card(s: &crate::scrub::Scrubber, stopwords: &[&str], text: &str) {
let k = s
.compiled()
.pii
.iter()
.position(|v| v.id == "credit-card")
.unwrap();
let card = &s.compiled().pii[k];
let mut report = s.report();
let masked = s.pii_spans(k, text, &mut report);
for want in independent_cards(card, text) {
let lower = text[want.clone()].to_lowercase();
if stopwords.iter().any(|w| lower.contains(w)) {
continue;
}
assert!(
masked
.iter()
.any(|m| m.start <= want.start && want.end <= m.end),
"{text:?} allowing {stopwords:?}: {want:?} is a card no allowlist exempts and is not inside {masked:?}"
);
}
}
#[test]
fn the_production_scrubber_masks_every_card_no_allowlist_exempts() {
use proptest::prelude::*;
let allows: [&[&str]; 5] = [&[], &["4111"], &["5500"], &["0004"], &["3340", "9800"]];
let scrubbers: Vec<_> = allows.iter().map(|a| scrubber_allowing(a)).collect();
let pieces = [
"4111",
"1111",
"5500",
"0004",
"3340",
"9124",
"0063",
"4548",
"9800",
"1",
"12",
"3",
"4111 1111 1111 1111",
"5500 0000 0000 0004",
"3340 9124 0063 4548 9800",
" ",
"\u{a0}",
"-",
"\u{200b}",
"\u{ad}",
"\u{202e}",
"\u{2066}",
"\u{200f}",
"\u{5361}",
"\u{5361}\u{53f7}",
"\u{e9}",
"x",
"card ",
"\u{663}\u{664}",
"\u{ff11}\u{ff12}",
"\u{3000}",
];
let mut runner = proptest::test_runner::TestRunner::new(ProptestConfig::with_cases(20_000));
runner
.run(
&(
proptest::collection::vec(proptest::sample::select(pieces.to_vec()), 0..16),
0..allows.len(),
),
|(parts, which)| {
production_masks_every_card(&scrubbers[which], allows[which], &parts.concat());
Ok(())
},
)
.unwrap();
}
#[test]
fn the_production_scrubber_masks_every_card_on_corpus_lines() {
use crate::shared_tests::corpus::for_each_record_of;
let s = scrubber_allowing(&[]);
let tags = [
"syslog", "cef", "leef", "kv", "mixed", "access", "text", "csv", "tsv", "json", "ndjson",
"naughty", "xml", "http",
];
let n = for_each_record_of(&tags, |r| {
production_masks_every_card(&s, &[], &String::from_utf8_lossy(r.bytes));
});
assert!(n > 100, "{n}");
}
#[test]
fn every_card_nested_inside_a_longer_one_is_confirmed() {
let card = the_card();
let text = "\u{5361}\u{53f7}4111 1111 1111 1111\u{200b}3";
let start = "\u{5361}\u{53f7}".len();
let outer = start..text.len();
let inner = start..start + "4111 1111 1111 1111".len();
assert_eq!(card.confirmed_each(text), [inner, outer.clone()]);
assert_eq!(masked_spans(&card, text), [outer]);
let plain = "card 4111 1111 1111 1111\u{200b}3";
assert_eq!(card.confirmed_each(plain), [5..24, 5..plain.len()]);
}