grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
// 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"));
    // Digits of other scripts are digits, as the patterns read them.
    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"));
}

/// The decimal digits of every script are runs of ten from a zero, which is
/// how a digit's value is read from its place.
#[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:?}");
    }
}

/// A card and each national id read the same in the digits and spaces of
/// other scripts as in ASCII ones, in the pattern and in the check.
#[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);
        }
    }
    // A group of mixed scripts is a number all the same, a dash groups too,
    // and letters in a group are not digits.
    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);
    // Combining marks don't count toward the 30, so decomposed text reads as composed text does.
    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);
    // The window reads at most 120 characters, whatever they are.
    let marks = format!("tfn e{}123 456 782", "\u{301}".repeat(120));
    assert_eq!(scrub_one(tfn, &marks), marks);
}

/// An AU number or an IBAN set straight after or before a word of a script
/// written without spaces is found, as a card is, and an ASCII letter beside
/// one still keeps it out.
#[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}");
    }
}

/// An address whose domain is parted by a dot IDNA reads as one, an
/// ideographic or full-width full stop, is masked. A last label with no
/// letter in it, combining marks alone, isn't a domain.
#[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:?}");
    }
}

/// A card word joined to a letter with case, accented or not, is part of a
/// longer word, and one beside a letter of a script with no case still counts.
#[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);
}

/// 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);

    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());
            // A text the quick check rules out holds nothing any validator keeps.
            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;
            // 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);
}

/// The fewest digits and bytes a match holds, read from each pattern.
#[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(&regex_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(&regex_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}");
    }
}

/// A plain `email_candidates`: 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);
    }
}

/// A card as digit runs between word boundaries, which the pattern read before it
/// matched across other scripts.
const CARD_BASELINE: &str = r"\b(?:\d[\p{Zs}\p{Pd}]?){12,18}\d\b";

/// The card validator as it read before it matched across other scripts: its
/// pattern, the search that skips past a candidate that fails, and a check of
/// the raw candidate.
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()
    }
}

/// Every card the older reading masks is inside a span the card validator masks.
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()
}

/// A wider run of digits that fails to validate doesn't hide the valid card inside it.
#[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();
}

/// Every line of the scrub corpus and the naughty strings keeps each card it had masked.
#[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}");
}

/// What `card` masks in `text`, in order.
fn masked_spans(card: &Pii, text: &str) -> Vec<Range<usize>> {
    let mut spans = Vec::new();
    card.confirmed(text, |m| spans.push(m));
    spans
}

/// Every card either pass could confirm on its own, found by trying each start
/// and end in turn: a span the pattern reads whole, with no digit beside either
/// end, that passes the validator's anchor and check.
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;
            }
            // A card has 13 to 19 digits, however many separators and invisible characters sit between them.
            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
}

/// Every card the pattern can read and the validator accepts is inside a masked span.
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:?}"
        );
    }
}

/// A card read whole beats a shorter one it overlaps: the digits past the shorter
/// card's end are masked with it, not left in the clear.
#[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);
    }
}

/// A card whose wider candidate ends inside a run of digits is still found in its prefix.
#[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);
    }
}

/// Every card either pass can confirm is masked, in text of digits of every script,
/// invisible characters, spaces and neighbours in other scripts.
#[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();
}

/// Every card either pass confirms on a corpus line or a naughty string is masked.
#[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}");
}

/// A scrubber over the default rules with `allow` as the credit card's allowlist.
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()
}

/// The production scrubber masks every card the pattern can read that no allowlist
/// exempts on its own, whatever it overlaps: `stopwords` exempt the cards holding one.
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:?}"
        );
    }
}

/// Every card the pattern can read is masked through the production scrubber, with and
/// without an allowlist that exempts the cards holding one of a few groups.
#[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();
}

/// The same over every corpus line and naughty string, with no allowlist.
#[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}");
}

/// Cards inside a longer card each reach the caller: the longest, and the shorter
/// ones that end a run of digits, the one the older reading couldn't see included.
#[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()]);
    // Merged for a caller that exempts none, they are the outer span alone.
    assert_eq!(masked_spans(&card, text), [outer]);
    // The same card ends a run of digits in the older reading too.
    let plain = "card 4111 1111 1111 1111\u{200b}3";
    assert_eq!(card.confirmed_each(plain), [5..24, 5..plain.len()]);
}