grippo 0.1.0

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/scrub/pii_tests.rs
// Purpose:   The PII validators against the recorded output for the shared fixture
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use serde_json::Value;

use super::super::redact::Redactor;
use super::super::report::{Layer, RuleMeta};
use super::*;

/// `text` with every candidate `v` confirms replaced by its mask token.
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"));
    // An 8-digit TFN takes the first eight weights.
    assert!(au_tfn("87654321") && !au_tfn("12345678"));
    assert!(au_medicare("2428 77813 2") && !au_medicare("2428 77814 2"));
    // A leading 1 isn't a card type, and issue 0 isn't an issue.
    assert!(!au_medicare("1428778132"));
    assert!(!au_medicare("24287781320"));
    assert!(iban("GB82 WEST 1234 5698 7654 32"));
    assert!(!iban("GB82 WEST 1234 5698 7654 33"));
    // Non-ASCII digits are never a number, as in stdnum.
    assert!(!luhn("٤١١١١١١١١١١١١١١١"));
}

#[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);
}

#[test]
fn encoded_addresses_keep_their_escapes() {
    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"),
        ("to=%22bob%2540example.com%22", "to=%22[EMAIL_REDACTED]%22"),
        ("pkg@1.2.3 and user@10.0.0.1", "pkg@1.2.3 and user@10.0.0.1"),
    ] {
        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);
}

/// Every string anywhere in `value`.
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)),
        _ => {}
    }
}

/// The gate skips a validator only where that validator's own pattern finds
/// nothing, so skipping it changes no result. Past ASCII it reads no word
/// boundary, so it may name one whose pattern a boundary rules 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);

    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 named = candidates >> k & 1 == 1;
            // Exact on ASCII text, never short past it.
            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
        );
    }
    // A set sized for another gate is replaced, not indexed past its end.
    let fewer = Gate::new(&validators[..2]).unwrap();
    assert_eq!(fewer.candidates(&texts[2], &mut seen) & 1, 1);
}

/// `email_candidates` as it read before: the body tried from every
/// permitted start.
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))]

    /// A word with no at sign after it is skipped, and the addresses found
    /// are the ones the body finds from every start.
    #[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);
    }
}