grippo 0.1.0

Parse, match and scrub data at scale.
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
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
// Project:   grippo
// File:      src/scrub/tests.rs
// Purpose:   gitleaks parity over its own test vectors, and the edge rules
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use std::collections::BTreeMap;
use std::io::Read;

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>,
}

/// The vectors by rule id: joined, base64-decoded, zlib-inflated JSON.
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();
    // 222 rules, 5 of them gated on a file path.
    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_a8a30ba0507c619c]"),
        // Longer than the 64-byte block, so HMAC hashes the key first.
        (vec![b'x'; 200], "[EMAIL_cf3f1d8a636a15d6]"),
    ] {
        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 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 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].rule, "bad");
    assert!(matches!(
        lenient.skipped()[0].reason,
        SkipReason::BadRegex(_)
    ));
    let strict = Scrubber::builder()
        .strictness(Strictness::Strict)
        .build(&config);
    assert!(matches!(strict, Err(ScrubError::Skipped { rule, .. }) if rule == "bad"));
}

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() {
    // "ab" has entropy exactly 1.0.
    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() {
    // Two characters in four bytes: -(2/4) * log2(2/4) = 0.5, not 0.
    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();
    // By default the marker is text like any other: a log writer controls it.
    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 = ['''.*''']
        "#,
    );
    // The global stopword, matched without case.
    assert_eq!(secrets(&s, "k=myexamplething"), NONE);
    // The match target.
    assert_eq!(secrets(&s, "key=abc"), NONE);
    // AND: the line regex alone isn't enough, the stopword must hold too.
    assert_eq!(secrets(&s, "test k=abc"), ["abc"]);
    assert_eq!(secrets(&s, "test k=dummyabc"), NONE);
    // AND with a path check never allows log text.
    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+)'''
        "#,
    );
    // \w stops at the first non-ASCII byte.
    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.*"])
        .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())
    };

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

    // A bare `key` counts only under a parent that qualifies it.
    assert!(field(&["tls", "key"], "abc", &mut report).is_some());
    assert_eq!(field(&["kafka", "key"], "abc", &mut report), None);
    report.clear();

    // The exception beats the credential name.
    assert_eq!(field(&["audit", "password"], "hunter2", &mut report), None);
    assert_eq!(report.count(FIELD_RULE, Kind::ExceptedField), 1);
    report.clear();

    // A name that only starts with a term isn't a credential.
    assert_eq!(
        field(&["event_data", "PasswordLastSet"], "%%1794", &mut report),
        None
    );
    assert_eq!(report.count(FIELD_RULE, Kind::ExceptedField), 0);
    report.clear();

    // A secret under an excepted path is counted, not redacted.
    assert_eq!(field(&["audit", "msg"], "tok_abc123", &mut report), None);
    assert_eq!(report.count("tok", Kind::ExceptedField), 1);
    // `audit.*` covers fields below `audit`, not `audit` itself.
    assert_eq!(
        field(&["audit"], "tok_abc123", &mut report).as_deref(),
        Some("[TOK_REDACTED]")
    );
    report.clear();

    // Any other field goes through the secret layer.
    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);
    // An empty credential value has nothing to hide.
    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
            },
            // A container under a credential name goes whole.
            "passwords": "[CREDENTIAL_FIELD_REDACTED]",
            "event_data": { "TokenElevationType": "%%1936", "SubjectPassword": "-" },
            // A number keeps its type: Luhn never runs over one.
            "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());
}

/// What a rule's regex reduces to once its capture groups and the boundary
/// assertions around it are set aside.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Shape {
    /// Literal prefixes, then character-class runs.
    PrefixRun,
    /// A key name, an assignment operator, then the value.
    KeyValue,
    /// Anything else.
    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: &regex_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,
    }
}

/// Prints how the default rules split by shape: the case for lowering them.
#[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.map(|b| String::from_utf8(b).unwrap()), report)
    };
    let cases: &[(&[u8], Option<&str>)] = &[
        (
            b"password=\xed\xa0\x80hunter2",
            Some("password=[CREDENTIAL_FIELD_REDACTED]"),
        ),
        (
            b"password=hun\xffter2 next",
            Some("password=[CREDENTIAL_FIELD_REDACTED] next"),
        ),
        (
            b"token: \xc0\x80abc",
            Some("token: [CREDENTIAL_FIELD_REDACTED]"),
        ),
        (
            b"{\"secret\": \"x\xed\xb3\xbfy\"}",
            Some("{\"secret\": \"[CREDENTIAL_FIELD_REDACTED]\"}"),
        ),
        (
            b"\xffpassword=hunter2",
            Some("\u{FFFD}password=[CREDENTIAL_FIELD_REDACTED]"),
        ),
        (
            b"https://u:p\xffw@db/app",
            Some("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());
    }

    // An invalid sequence anywhere in a value leaves none of the value.
    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}")), "{text:?}");
            }
        }
    }

    // Every layer, and valid text keeps its bytes as before.
    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("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]")
    );
}

#[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 adversarial_lines_scan_in_linear_time() {
    use std::time::{Duration, Instant};
    let s = Scrubber::gitleaks().unwrap();
    // The best of three, so a busy host slows every run alike.
    let best = |line: &str| {
        (0..3)
            .map(|_| {
                let started = Instant::now();
                let _ = scrub(&s, line);
                started.elapsed()
            })
            .min()
            .unwrap_or(Duration::ZERO)
    };
    // Built at run time, so the repo holds no key-shaped literal.
    let dense = ["key=", "Ab3dE5", "fG7hQ9 "].concat();
    for (unit, tail, n) in [
        ("a.", "@", 4096),
        ("a%2B", "%40", 2048),
        (dense.as_str(), "", 512),
    ] {
        let small = best(&(unit.repeat(n) + tail));
        let large = best(&(unit.repeat(4 * n) + tail));
        // Four times the input costs about 4x when linear and 16x when quadratic.
        assert!(
            large < small * 10,
            "{unit}: {small:?} at {n}, {large:?} at {}",
            4 * n
        );
    }
}

#[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));
    // Dropping a 10,000-deep Value recurses in serde_json, so flatten it first.
    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();
    // The first match spans both lines and its first holds the marker. The
    // second sits on the last line alone, which has none.
    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 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);
}

/// `hir` with every look-around taken out, which the string generator can't
/// draw from.
fn without_looks(hir: &regex_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(),
    }
}

/// Pieces a text is made of for the keyword-start test: each rule's own
/// keywords join them.
const START_PIECES: &[&str] = &[
    "a",
    "Z",
    "0",
    "9",
    "_",
    ".",
    "-",
    " ",
    "\t",
    "=",
    ":",
    ":=",
    "=>",
    "|",
    ",",
    "?",
    "\"",
    "'",
    "`",
    ";",
    "\n",
    "\\n",
    "x7f",
    "abcdef0123456789",
    "ABCDEFGHIJKLMNOP",
    "+/",
    "==",
];

/// A rule searched from its keywords finds the matches `find_iter` finds,
/// on texts built from its keywords and the bytes around a secret.
#[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());
        // Strings the rule's own regex matches, read as it compiles them, set
        // among the pieces and sometimes cut short.
        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(&regex, &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");
    // The texts reach the rules' matches, not only their misses.
    eprintln!("{rules} rules, {matched} matches");
    assert!(matched > 2_000, "only {matched} matches");
}