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
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
// Project:   grippo
// File:      src/scrub/field/mod.rs
// Purpose:   Decide which field names hold credentials and mask them in text
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Credential-name matching and text masking.
//!
//! A field name holds a credential when its last words spell a term,
//! case-insensitively, with separators and case changes splitting the words. So
//! `db_password`, `x-api-key`, `secretAccessKey` and `AWS_SECRET_ACCESS_KEY`
//! match, and `TokenElevationType`, `tokens_used` and `mapping` don't. A term of
//! six letters or more also ends a last word part-way, as in `PGPASSWORD`.
//! Letters and digits are those of any script, in a structured field's name
//! and in a key in free text alike.
//!
//! [`mask_text`] applies that rule to free text: every URL password, every
//! signed URL query parameter such as `&sig=`, every header value an error
//! quotes after `Illegal header value`, every bearer token, and the value
//! after every `key: value` or `key=value` whose key names a
//! credential. After a key naming an authorization header, an unquoted value is
//! the scheme and the credentials after it, so `Authorization: Basic ...` masks
//! whole, and after any other credential key so is one opening with an
//! authentication scheme, as in `x-api-key: Token ...`.

#![allow(
    clippy::option_if_let_else,
    reason = "a match over multi-field struct literals reads clearer than map_or_else"
)]

use std::borrow::Cow;
use std::fmt::Write as _;
use std::sync::LazyLock;

use super::ScrubError;
use super::prefix::{Fold, Prefixes};
use skeleton::{escape_before, may_escape, sgr_before, sgr_len, skeleton};
pub(super) use skeleton::{is_mark, skeleton as key_skeleton};

mod skeleton;

/// Terms that make a field name a credential when its last words spell one.
pub const SENSITIVE_FIELDS: &[&str] = &[
    // Passwords
    "password",
    "passwd",
    "pwd",
    "pass",
    "passphrase",
    "pgpass",
    // Tokens
    "token",
    "access_token",
    "refresh_token",
    "id_token",
    "session_token",
    "api_token",
    "bearer",
    "bearer_token",
    // API keys
    "api_key",
    "apikey",
    "api-key",
    "api_secret",
    // Secrets
    "secret",
    "client_secret",
    "secret_key",
    "private_key",
    "privatekey",
    "secret_access_key",
    "aws_secret_access_key",
    "aws_secret",
    "access_key",
    "access_key_id",
    // Keys a qualifying word makes a credential, where `routing_key` is not one
    "account_key",
    "azure_key",
    "client_key",
    "encryption_key",
    "gcp_key",
    "hmac_key",
    "integration_key",
    "jwt_key",
    "licence_key",
    "license_key",
    "master_key",
    "sasl_key",
    "shared_key",
    "signing_key",
    "ssh_key",
    "ssl_key",
    "tls_key",
    // Auth
    "authorization",
    "auth",
    "jaas_config",
    "header_value",
    "headers_value",
    // Session
    "session_id",
    "session_key",
    "sessionid",
    "cookie",
    "csrf",
    // Certificates
    "certificate",
    "cert",
    "ssl_cert",
    // Credentials
    "credential",
    "credentials",
    "creds",
    // Database
    "db_password",
    "database_password",
    "connection_string",
    // Personal data
    "ssn",
    "tfn",
    "medicare",
    "credit_card",
    "creditcard",
    "card_number",
    "cvv",
    "pin",
    "email",
    "phone",
];

/// Names that say nothing until their parent qualifies them, as `tls` does `key`.
const BARE_NAMES: [&str; 4] = ["key", "keys", "value", "values"];

/// The longest `Name(...)` value read as one value, in bytes. One that does not close within it is masked to the end of the text, and the bound keeps a line of unclosed parentheses linear.
const MAX_WRAPPER_LEN: usize = 4096;

/// A key holding this, in any case, names an authorization header, whose value is a scheme followed by its credentials.
const AUTHORIZATION: &[u8] = b"authorization";

/// HTTP authentication schemes: the IANA registry, then unregistered ones
/// products use.
const AUTH_SCHEMES: [&str; 23] = [
    "basic",
    "bearer",
    "concealed",
    "digest",
    "dpop",
    "gnap",
    "hoba",
    "mutual",
    "negotiate",
    "oauth",
    "privatetoken",
    "scram-sha-1",
    "scram-sha-256",
    "vapid",
    "apikey",
    "aws4-hmac-sha256",
    "ntlm",
    "sharedaccesssignature",
    "sharedkey",
    "sharedkeylite",
    "splunk",
    "ssws",
    "token",
];

/// The matcher over [`SENSITIVE_FIELDS`].
static DEFAULT_MATCHER: LazyLock<CredentialMatcher> = LazyLock::new(|| {
    let mut buf = String::new();
    CredentialMatcher::from_spelled(SENSITIVE_FIELDS.iter().map(|term| spelled(term, &mut buf)))
});

/// Last words that say how a credential is held, not what it is, so
/// `api_token_value`, `password_hash` and `ssl.key.pem` read without them.
const QUALIFIERS: [&str; 12] = [
    "value",
    "values",
    "pem",
    "hash",
    "b64",
    "base64",
    "enc",
    "encrypted",
    "raw",
    "data",
    "primary",
    "secondary",
];

/// A term this long also counts at the end of a name's last word, as
/// `password` does in `PGPASSWORD`, and with a plural `s`, as in `passwords`.
/// Shorter ones, such as `pass` in `bypass` and `token` in `tokens`, don't.
const SUFFIX_MIN: usize = 6;

/// Decides whether a field name holds a credential.
#[derive(Debug, Clone)]
pub struct CredentialMatcher {
    /// Each term's words, lower-cased and joined with nothing between them.
    terms: Vec<String>,
    /// The terms that end in each byte, so a name is compared only with the
    /// terms it could end in.
    by_last: Vec<Vec<usize>>,
    /// What each term starts with, to rule a name out before it's spelled.
    starts: Prefixes,
}

impl CredentialMatcher {
    /// Build a matcher over `terms`, each read word by word, so `api_key`,
    /// `apikey` and `api-key` are one term. A term is compared as a name is,
    /// through its skeleton, so a combining mark in it reads as the letter it
    /// sits on.
    ///
    /// # Errors
    ///
    /// [`ScrubError::CredentialTerm`] for a term with no letter or digit in
    /// it, which no name could spell.
    pub fn new<I, S>(terms: I) -> Result<Self, ScrubError>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut buf = String::new();
        let mut spelt = Vec::new();
        for term in terms {
            let words = spelled(term.as_ref(), &mut buf);
            if words.is_empty() {
                return Err(ScrubError::CredentialTerm {
                    term: term.as_ref().to_owned(),
                });
            }
            spelt.push(words);
        }
        Ok(Self::from_spelled(spelt))
    }

    /// A matcher over terms already spelled by [`spelled`], none empty.
    fn from_spelled(terms: impl IntoIterator<Item = String>) -> Self {
        let mut terms: Vec<String> = terms.into_iter().collect();
        terms.sort_unstable();
        terms.dedup();
        let mut by_last = vec![Vec::new(); 256];
        for (i, term) in terms.iter().enumerate() {
            if let Some(&last) = term.as_bytes().last() {
                by_last[usize::from(last)].push(i);
            }
        }
        let starts = Prefixes::new(terms.iter().map(String::as_bytes));
        Self {
            terms,
            by_last,
            starts,
        }
    }

    /// `false` only when no name in `text` can spell a term: the term's
    /// letters and digits would sit together in the text's, lower-cased.
    ///
    /// `plain` says the caller knows `text` is [`is_plain`]. Plain text reads
    /// in one pass. Any other text is read through its skeleton, and an escape
    /// may spell any letter, so it rules nothing out.
    fn may_name_in(&self, text: &str, plain: bool) -> bool {
        let bytes = text.as_bytes();
        if plain || is_plain(bytes) {
            return self.starts.may_hold_folded(bytes, Fold::Alnum);
        }
        self.may_name_in_unplain(text)
    }

    /// [`CredentialMatcher::may_name_in`] for text with an escape, a colour
    /// sequence or a character past ASCII in it.
    fn may_name_in_unplain(&self, text: &str) -> bool {
        if may_escape(text) {
            return true;
        }
        let spelt: String = skeleton(text)
            .chars()
            .filter(|c| c.is_alphanumeric())
            .flat_map(char::to_lowercase)
            .collect();
        self.starts.may_hold(spelt.bytes())
    }

    /// The terms that end in the last letter or digit of `name`.
    fn ending_like(&self, name: &[u8]) -> impl Iterator<Item = &[u8]> {
        let last = name.iter().rev().find(|&&b| b != b'_');
        last.map_or(&[][..], |&b| &self.by_last[usize::from(b)])
            .iter()
            .map(|&i| self.terms[i].as_bytes())
    }

    /// The matcher over the default terms.
    pub fn default_terms() -> &'static Self {
        &DEFAULT_MATCHER
    }

    /// `true` when the matcher has no terms, so nothing is a credential.
    pub const fn is_empty(&self) -> bool {
        self.terms.is_empty()
    }

    /// Whether `name`, held under `parent`, carries a term.
    ///
    /// `parent` counts only for a bare `key`, `keys`, `value` or `values`.
    pub fn matches(&self, name: &str, parent: &str) -> bool {
        self.matches_in(name, parent, &mut Spellings::default())
    }

    /// As [`CredentialMatcher::matches`], spelling the name into `buf`, so a
    /// caller that keeps one allocates nothing once it has grown.
    pub fn matches_in(&self, name: &str, parent: &str, buf: &mut Spellings) -> bool {
        self.name_match(name, parent, buf) != NameMatch::None
    }

    /// As [`CredentialMatcher::matches_in`], given the value too: a name that
    /// is only a short term's plural, such as `max_tokens`, can be a count, so
    /// it doesn't match a value that is a number.
    pub fn matches_value(
        &self,
        name: &str,
        parent: &str,
        value: &[u8],
        buf: &mut Spellings,
    ) -> bool {
        match self.name_match(name, parent, buf) {
            NameMatch::None => false,
            NameMatch::Term => true,
            NameMatch::Plural => !is_number(value),
        }
    }

    pub(crate) fn name_match(&self, name: &str, parent: &str, buf: &mut Spellings) -> NameMatch {
        // With no parent, a name spells a term from its own letters alone.
        if parent.is_empty() && !self.may_name_in(name, buf.plain()) {
            return NameMatch::None;
        }
        buf.spell(name);
        if !parent.is_empty() && BARE_NAMES.contains(&buf.joined.as_str()) {
            // A bare name under a credential, as `key` under `client_auth`.
            if self.name_match(parent, "", buf) == NameMatch::Term {
                return NameMatch::Term;
            }
            let mut qualified = std::mem::take(&mut buf.qualified);
            qualified.clear();
            qualified.push_str(parent);
            qualified.push('_');
            qualified.push_str(name);
            buf.spell(&qualified);
            buf.qualified = qualified;
        }
        let mut found = NameMatch::None;
        let mut stem = buf.joined.as_str();
        for _ in 0..MAX_STRIPPED {
            let bytes = stem.as_bytes();
            if self
                .ending_like(bytes)
                .any(|term| ends_with_term(bytes, term, term.len() >= SUFFIX_MIN))
            {
                return NameMatch::Term;
            }
            if let Some(singular) = bytes.strip_suffix(b"s") {
                for term in self.ending_like(singular) {
                    let long = term.len() >= SUFFIX_MIN;
                    if ends_with_term(singular, term, long) {
                        if long {
                            return NameMatch::Term;
                        }
                        found = NameMatch::Plural;
                    }
                }
            }
            match strip_last_word(stem) {
                Some(shorter) => stem = shorter,
                None => break,
            }
        }
        found
    }
}

/// How many trailing qualifier and version words a name may shed.
const MAX_STRIPPED: usize = 4;

/// How a name matched a term.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NameMatch {
    /// It doesn't.
    None,
    /// It ends in a term.
    Term,
    /// It ends only in a short term's plural, as `tokens` or `max_tokens` do.
    Plural,
}

/// `name` without its last word when that word is a qualifier, or a version
/// or number such as `v2`, `2` or `01`.
fn strip_last_word(name: &str) -> Option<&str> {
    let (rest, last) = name.rsplit_once('_')?;
    if QUALIFIERS.contains(&last) {
        return Some(rest);
    }
    if !last.chars().all(char::is_numeric) {
        return None;
    }
    // `v2` splits into `v` and `2`: both go.
    Some(rest.strip_suffix("_v").unwrap_or(rest)).filter(|s| *s != "v")
}

/// `true` when `value`, less spaces and quotes, is a decimal number, its
/// digits from any script.
fn is_number(value: &[u8]) -> bool {
    let v = value.trim_ascii();
    let v = v
        .strip_prefix(b"\"")
        .and_then(|v| v.strip_suffix(b"\""))
        .unwrap_or(v);
    let v = v.strip_prefix(b"-").unwrap_or(v);
    let (whole, fraction) = v.split_at(v.iter().position(|&b| b == b'.').unwrap_or(v.len()));
    let digits = |d: &[u8]| {
        !d.is_empty()
            && (d.iter().all(u8::is_ascii_digit)
                || std::str::from_utf8(d)
                    .is_ok_and(|s| s.chars().all(|c| super::pii::decimal(c).is_some())))
    };
    digits(whole) && (fraction.is_empty() || (fraction.len() > 1 && digits(&fraction[1..])))
}

/// `true` when the words at the end of `name`, joined by `_`, spell `term`
/// with the `_` left out. With `in_last_word`, `term` may also end the last
/// word part-way through it.
const fn ends_with_term(name: &[u8], term: &[u8], in_last_word: bool) -> bool {
    let mut i = name.len();
    let mut j = term.len();
    let mut crossed = false;
    while j > 0 {
        let Some(at) = i.checked_sub(1) else {
            return false;
        };
        i = at;
        if name[i] == b'_' {
            crossed = true;
            continue;
        }
        j -= 1;
        if name[i] != term[j] {
            return false;
        }
    }
    i == 0 || name[i - 1] == b'_' || (in_last_word && !crossed)
}

/// Buffers for [`CredentialMatcher::matches_in`].
#[derive(Debug, Default, Clone)]
pub struct Spellings {
    joined: String,
    qualified: String,
    /// Every text the scrub in progress reads is plain: see [`is_plain`].
    plain: bool,
}

impl Spellings {
    /// Whether every text the scrub in progress reads is [`is_plain`].
    pub(crate) const fn plain(&self) -> bool {
        self.plain
    }

    /// Say whether every text the scrub in progress reads is [`is_plain`].
    pub(crate) const fn set_plain(&mut self, plain: bool) {
        self.plain = plain;
    }

    /// `name` as its words joined by `_`: `secretAccessKey`, `x-api-key` and
    /// `ssl.key.pem` read as `secret_access_key`, `x_api_key` and `ssl_key_pem`.
    fn spell(&mut self, name: &str) {
        joined_words_into(name, &mut self.joined);
    }
}

/// The words of `name`, lower-cased and joined by `_`.
#[cfg(test)]
fn joined_words(name: &str) -> String {
    let mut out = String::new();
    joined_words_into(name, &mut out);
    out
}

/// Write the words of `name`'s skeleton into `out`, lower-cased and joined by `_`.
///
/// This is the one word model of credential names, read the same from a
/// structured field's name and from a key in free text. A name is read
/// through its [`skeleton`], so a look-alike letter, a full-width form and a
/// zero-width character spell what they imitate. A word is an
/// acronym, a capitalised or lower-case run, or a run of digits, so
/// `HTTPServer` is `http_server`. Letters and digits are those of any script,
/// and a letter with no case, such as a CJK ideograph, joins a lower-case run.
/// Anything else separates words, so a name is never normalised: `cafe` and
/// `cafe` with a combining acute are different names, and a zero-width
/// character splits the word it sits in.
fn joined_words_into(name: &str, out: &mut String) {
    spell_words(&skeleton(name), out);
}

/// The words of `term`, as [`joined_words_into`] reads them, with the `_` between them left out.
fn spelled(term: &str, buf: &mut String) -> String {
    joined_words_into(term, buf);
    buf.replace('_', "")
}

/// [`joined_words_into`] without the skeleton: the words of `name` as written.
fn spell_words(name: &str, out: &mut String) {
    out.clear();
    let mut start = 0;
    while start < name.len() {
        let end = word_end(name, start);
        if end == start {
            start += name[start..].chars().next().map_or(1, char::len_utf8);
            continue;
        }
        if !out.is_empty() {
            out.push('_');
        }
        out.extend(name[start..end].chars().flat_map(char::to_lowercase));
        start = end;
    }
}

/// What a character is to a word.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Glyph {
    Upper,
    Lower,
    Digit,
    Other,
}

fn glyph(c: char) -> Glyph {
    if c.is_uppercase() {
        Glyph::Upper
    } else if c.is_lowercase() || c.is_alphabetic() {
        Glyph::Lower
    } else if c.is_numeric() {
        Glyph::Digit
    } else {
        Glyph::Other
    }
}

/// Where the word starting at `start` ends, or `start` when no word starts there.
fn word_end(text: &str, start: usize) -> usize {
    let run = |from: usize, class: Glyph| {
        from + text[from..]
            .chars()
            .take_while(|&c| glyph(c) == class)
            .map(char::len_utf8)
            .sum::<usize>()
    };
    let Some(first) = text[start..].chars().next() else {
        return start;
    };
    match glyph(first) {
        Glyph::Upper => {
            let upper_end = run(start, Glyph::Upper);
            let lower_follows = text[upper_end..]
                .chars()
                .next()
                .is_some_and(|c| glyph(c) == Glyph::Lower);
            if !lower_follows {
                return upper_end;
            }
            // An acronym gives its last capital to the capitalised word after it.
            let last = text[start..upper_end]
                .chars()
                .next_back()
                .map_or(0, char::len_utf8);
            if upper_end - start > last {
                return upper_end - last;
            }
            run(upper_end, Glyph::Lower)
        }
        class @ (Glyph::Lower | Glyph::Digit) => run(start, class),
        Glyph::Other => start,
    }
}

/// Whether a field called `name` holds a credential.
///
/// A name is a credential when its last words spell one of the
/// [`SENSITIVE_FIELDS`], case-insensitively, so `db_password`, `PGPASSWORD`,
/// `x-api-key` and `secretAccessKey` match and `PasswordLastSet` doesn't.
///
/// `parent` is the name of the object or array holding the field. It counts only
/// for a bare `key`, `keys`, `value` or `values`, so a `key` under `tls` is a
/// credential and one under `kafka` is not. Pass `""` for a field with no parent.
///
/// # Examples
///
/// ```
/// use grippo::scrub::field::is_credential_name;
///
/// assert!(is_credential_name("secretAccessKey", ""));
/// assert!(is_credential_name("key", "tls"));
/// assert!(!is_credential_name("key", "kafka"));
/// assert!(!is_credential_name("routing_key", ""));
/// ```
#[must_use]
pub fn is_credential_name(name: &str, parent: &str) -> bool {
    CredentialMatcher::default_terms().matches(name, parent)
}

/// White space as the masking rules read it: Unicode white space and the ASCII separators U+001C to U+001F.
fn is_space(c: char) -> bool {
    c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
}

/// Blanks as the masking rules read them: [`is_space`] less `\n` and `\r`, so
/// a key and its value, or a scheme and its credentials, may be set apart by
/// a space, a tab, U+00A0, U+0085, U+2028, U+3000 and the rest, never by a
/// line end of a log.
fn is_blank(c: char) -> bool {
    is_space(c) && !matches!(c, '\n' | '\r')
}

/// Characters that print nothing: the soft hyphen, the zero-width and bidi
/// marks, the word joiner and invisible operators, variation selectors, the
/// byte order mark and tag characters.
pub(super) const fn is_ignorable(c: char) -> bool {
    matches!(
        c,
        '\u{ad}'
            | '\u{34f}'
            | '\u{61c}'
            | '\u{115f}'
            | '\u{1160}'
            | '\u{17b4}'
            | '\u{17b5}'
            | '\u{180b}'..='\u{180f}'
            | '\u{200b}'..='\u{200f}'
            | '\u{202a}'..='\u{202e}'
            | '\u{2060}'..='\u{206f}'
            | '\u{3164}'
            | '\u{fe00}'..='\u{fe0f}'
            | '\u{feff}'
            | '\u{ffa0}'
            | '\u{fff0}'..='\u{fff8}'
            | '\u{e0000}'..='\u{e0fff}'
    )
}

/// What may sit between a key and its separator, or between a separator and
/// its value, on one line: a blank or a character that prints nothing.
fn is_gap(c: char) -> bool {
    is_blank(c) || is_ignorable(c)
}

/// As [`is_gap`] where a separator may also be followed by a line end, as `:` is.
fn is_colon_gap(c: char) -> bool {
    is_space(c) || is_ignorable(c)
}

/// Whether `value` is `mask` itself, which an earlier pass wrote in place of a secret.
///
/// An empty `mask` stands for nothing, so it is never found.
fn is_mask(value: &str, mask: &str) -> bool {
    !mask.is_empty() && value == mask
}

/// The end of `mask` standing at `at` as a whole value, bare or inside one pair of quotes, or `None`.
///
/// A value an earlier pass replaced reads as the mask alone, so masking it
/// again would write the same bytes. A bare mask ends the value only when
/// what follows isn't a letter, digit or `_`, since one that is carries on a
/// longer value that is masked whole.
fn mask_end(text: &str, at: usize, mask: &str) -> Option<usize> {
    if mask.is_empty() {
        return None;
    }
    let rest = text.get(at..)?;
    let (quote, inner) = match rest.chars().next()? {
        q @ ('"' | '\'') => (Some(q), &rest[1..]),
        _ => (None, rest),
    };
    let after = inner.strip_prefix(mask)?;
    let end = text.len() - after.len();
    match quote {
        Some(q) => after.starts_with(q).then_some(end + 1),
        None => after
            .chars()
            .next()
            .is_none_or(|c| !(c.is_alphanumeric() || c == '_'))
            .then_some(end),
    }
}

/// The byte offset of the first char at or after `from` for which `stop` holds, or the text's length.
fn scan_until(text: &str, from: usize, stop: impl Fn(char) -> bool) -> usize {
    text[from..]
        .char_indices()
        .find(|&(_, c)| stop(c))
        .map_or(text.len(), |(i, _)| from + i)
}

/// `text` with the password of every `scheme://user:password@host` in it replaced by `mask`.
///
/// The password runs to the last `@` a host follows, so one holding `@`, `/`,
/// `?` or `#` is masked whole. Nothing tells such a password from an `@` later
/// in the path or query, so `https://u:p@host/x?to=ops@example.com` is masked
/// through to `example.com`, and `https://host:8443/@scope/pkg` loses its port.
/// A URL with no `:` in its userinfo, such as `ssh://git@host`, is left alone.
/// The scan stops at white space and at the next `://`, so a long line costs
/// linear time.
///
/// `keep_user` keeps the user, so the text still says whose credential it was.
/// `false` replaces the whole `user:password`. `mask` is inserted as written.
///
/// # Examples
///
/// ```
/// use grippo::scrub::field::mask_url_userinfo;
///
/// let line = "connecting to postgres://svc:p@ss/word@db:5432/app";
/// assert_eq!(
///     mask_url_userinfo(line, "***", true),
///     "connecting to postgres://svc:***@db:5432/app"
/// );
/// assert_eq!(
///     mask_url_userinfo(line, "***", false),
///     "connecting to postgres://***@db:5432/app"
/// );
/// ```
#[must_use]
pub fn mask_url_userinfo<'a>(text: &'a str, mask: &str, keep_user: bool) -> Cow<'a, str> {
    url_masked(text, mask, keep_user, &mut 0)
}

/// [`mask_url_userinfo`], adding each mask written to `n`.
fn url_masked<'a>(text: &'a str, mask: &str, keep_user: bool, n: &mut usize) -> Cow<'a, str> {
    let mut out: Option<String> = None;
    let mut copied = 0;
    for (head, colon, at) in url_userinfo(text) {
        if is_mask(&text[colon + 1..at], mask) {
            continue;
        }
        if keep_user && at > colon + 1 {
            let buf = out.get_or_insert_with(|| String::with_capacity(text.len()));
            buf.push_str(&text[copied..=colon]);
            buf.push_str(mask);
            *n += 1;
            copied = at;
        } else if !keep_user {
            let buf = out.get_or_insert_with(|| String::with_capacity(text.len()));
            buf.push_str(&text[copied..head]);
            buf.push_str("://");
            buf.push_str(mask);
            *n += 1;
            copied = at;
        }
    }
    finish(text, out, copied)
}

/// Every non-empty URL password in `text`, in order, as [`mask_url_userinfo`] masks them.
///
/// Both read the text with one scanner, so a password listed here is exactly
/// one the masker replaces. Code that checks or refuses a URL password needs
/// no pattern of its own.
///
/// # Examples
///
/// ```
/// use grippo::scrub::field::url_passwords;
///
/// let line = "a://u:p@ss/w@db/app b://v:@h c://git@h";
/// assert_eq!(url_passwords(line), ["p@ss/w"]);
/// ```
#[must_use]
pub fn url_passwords(text: &str) -> Vec<&str> {
    url_userinfo(text)
        .filter(|&(_, colon, at)| at > colon + 1)
        .map(|(_, colon, at)| &text[colon + 1..at])
        .collect()
}

/// Where the `://`, the `:` ending the user, and the `@` ending the password sit, for each URL in `text`.
///
/// The password runs from the user's `:` to the last `@` a host follows,
/// never past white space or the next `://`. The next URL is looked for from
/// that `@`.
fn url_userinfo(text: &str) -> impl Iterator<Item = (usize, usize, usize)> + '_ {
    let bytes = text.as_bytes();
    let mut from = 0;
    std::iter::from_fn(move || {
        while let Some(head) = next_scheme_end(bytes, from) {
            let colon = scan_until(text, head + 3, |c| {
                is_space(c) || matches!(c, ':' | '/' | '@')
            });
            if bytes.get(colon) != Some(&b':') {
                from = head + 1;
                continue;
            }
            let run_end = password_run_end(text, colon + 1);
            let Some(at) = last_host_at(text, colon + 1, run_end) else {
                from = head + 1;
                continue;
            };
            from = at;
            return Some((head, colon, at));
        }
        None
    })
}

/// The next `://` at or after `from`, found from its colon.
fn next_scheme_end(bytes: &[u8], from: usize) -> Option<usize> {
    memchr::memchr_iter(b':', bytes.get(from..)?)
        .map(|found| from + found)
        .find(|&at| bytes[at..].starts_with(b"://"))
}

/// Where the run that may hold a password ends: the next white space, or the next `://`.
fn password_run_end(text: &str, from: usize) -> usize {
    text[from..]
        .char_indices()
        .find(|&(i, c)| is_space(c) || text[from + i..].starts_with("://"))
        .map_or(text.len(), |(i, _)| from + i)
}

/// The last `@` in `from..to` that a host follows.
fn last_host_at(text: &str, from: usize, to: usize) -> Option<usize> {
    text[from..to]
        .rmatch_indices('@')
        .map(|(i, _)| from + i)
        .find(|&at| host_follows(text, at))
}

/// Whether a host follows the `@` at `at`: no `@` in it, ending at `/`, `?`, `#`, white space or the end.
fn host_follows(text: &str, at: usize) -> bool {
    let end = scan_until(text, at + 1, |c| {
        is_space(c) || matches!(c, '@' | '/' | '?' | '#')
    });
    text[end..]
        .chars()
        .next()
        .is_none_or(|c| is_space(c) || matches!(c, '/' | '?' | '#'))
}

/// Query parameters whose value is a signature or a session token, named in any case.
const SIGNATURE_PARAMS: [&str; 4] = [
    "sig",
    "x-amz-signature",
    "x-amz-security-token",
    "x-goog-signature",
];

/// `text` with the value of every [`SIGNATURE_PARAMS`] parameter named right after `?` or `&` replaced by `mask`.
///
/// The value runs to the next `&`, white space, quote or the end of the text.
fn mask_query_signatures<'a>(text: &'a str, mask: &str, n: &mut usize) -> Cow<'a, str> {
    let mut out: Option<String> = None;
    let mut copied = 0;
    let mut from = 0;
    while let Some(found) = memchr::memchr2(b'?', b'&', &text.as_bytes()[from..]) {
        let name_start = from + found + 1;
        from = name_start;
        let value_start = SIGNATURE_PARAMS.iter().find_map(|name| {
            let name_end = name_start + name.len();
            let named = text
                .get(name_start..name_end)
                .is_some_and(|written| written.eq_ignore_ascii_case(name));
            (named && text.as_bytes().get(name_end) == Some(&b'=')).then_some(name_end + 1)
        });
        let Some(value_start) = value_start else {
            continue;
        };
        let value_end = scan_until(text, value_start, |c| {
            is_space(c) || matches!(c, '&' | '"' | '\'')
        });
        from = value_end;
        if is_mask(&text[value_start..value_end], mask) {
            continue;
        }
        let buf = out.get_or_insert_with(|| String::with_capacity(text.len()));
        buf.push_str(&text[copied..value_start]);
        buf.push_str(mask);
        *n += 1;
        copied = value_end;
    }
    finish(text, out, copied)
}

/// The words before a header value an HTTP client's error quotes because it refused it.
const REFUSED_HEADER: &str = "illegal header value ";

/// `text` with every quoted value after [`REFUSED_HEADER`] replaced by `mask`, auth scheme and all.
///
/// The value opens with `'` or `"`, after an optional `b`, and runs past `\`
/// escapes to its closing quote, else to the end of its line. The head and
/// both quotes stay, so an unclosed value gains its closing quote.
fn mask_refused_headers<'a>(text: &'a str, mask: &str, n: &mut usize) -> Cow<'a, str> {
    let bytes = text.as_bytes();
    let mut out: Option<String> = None;
    let mut copied = 0;
    let mut from = 0;
    while let Some(head) = find_refused_header(text, from) {
        from = head + 1;
        let mut open = head + REFUSED_HEADER.len();
        if matches!(bytes.get(open), Some(b'b' | b'B')) {
            open += 1;
        }
        let Some(&quote @ (b'\'' | b'"')) = bytes.get(open) else {
            continue;
        };
        let mut end = open + 1;
        let close = loop {
            match bytes.get(end) {
                None | Some(b'\n') => break end,
                Some(&b) if b == quote => break end + 1,
                Some(b'\\') if !matches!(bytes.get(end + 1), None | Some(b'\n')) => end += 2,
                Some(b'\\') => break end,
                Some(_) => end += 1,
            }
        };
        from = close;
        if close == end + 1 && is_mask(&text[open + 1..end], mask) {
            continue;
        }
        let buf = out.get_or_insert_with(|| String::with_capacity(text.len()));
        buf.push_str(&text[copied..=open]);
        buf.push_str(mask);
        buf.push(char::from(quote));
        *n += 1;
        copied = close;
    }
    finish(text, out, copied)
}

/// Where the `v` of `value` sits in [`REFUSED_HEADER`], the search's anchor, since `v` is its rarest letter in text.
const REFUSED_HEADER_V: usize = 15;

/// The next [`REFUSED_HEADER`], in any case, at or after `from` with no word character before it.
fn find_refused_header(text: &str, from: usize) -> Option<usize> {
    let bytes = text.as_bytes();
    memchr::memchr2_iter(b'v', b'V', bytes.get(from + REFUSED_HEADER_V..)?)
        .map(|found| from + found)
        .find(|&head| {
            bytes
                .get(head..head + REFUSED_HEADER.len())
                .is_some_and(|w| w.eq_ignore_ascii_case(REFUSED_HEADER.as_bytes()))
                && text[..head]
                    .chars()
                    .next_back()
                    .is_none_or(|c| !(c.is_alphanumeric() || c == '_'))
        })
}

/// `text` with every bearer token after the word `bearer` replaced by `mask`.
fn mask_bearer<'a>(text: &'a str, mask: &str, n: &mut usize) -> Cow<'a, str> {
    let mut out: Option<String> = None;
    let mut copied = 0;
    let mut from = 0;
    while let Some(found) = find_bearer(text, from) {
        let gap_end = scan_until(text, found + 6, |c| !is_space(c));
        let token_end = scan_until(text, gap_end, is_space);
        if gap_end == found + 6 || token_end == gap_end {
            from = found + 1;
            continue;
        }
        from = token_end;
        if is_mask(&text[gap_end..token_end], mask) {
            continue;
        }
        let buf = out.get_or_insert_with(|| String::with_capacity(text.len()));
        buf.push_str(&text[copied..found]);
        buf.push_str("bearer ");
        buf.push_str(mask);
        *n += 1;
        copied = token_end;
    }
    finish(text, out, copied)
}

/// The next `bearer`, in any case, at or after `from` with no word character before it.
fn find_bearer(text: &str, from: usize) -> Option<usize> {
    let bytes = text.as_bytes();
    memchr::memchr2_iter(b'b', b'B', bytes.get(from..)?)
        .map(|found| from + found)
        .find(|&i| {
            text.get(i..i + 6)
                .is_some_and(|w| w.eq_ignore_ascii_case("bearer"))
                && text[..i]
                    .chars()
                    .next_back()
                    .is_none_or(|c| !(c.is_alphanumeric() || c == '_'))
        })
}

/// The separator between a key and its value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Separator {
    /// `key: value` (JSON, YAML, headers, Python and Rust `Debug`).
    Colon,
    /// `key=value` (env, form data, TOML, INI, `tracing` text fields).
    Equals,
}

/// One `key<separator>` found in text.
#[derive(Debug, Clone, Copy)]
struct Head {
    /// Where the key starts.
    start: usize,
    /// Where the key ends.
    key_end: usize,
    /// Where the value starts, past the separator and the space around it.
    end: usize,
}

/// Whether the `PWD=` at `head` is the working directory in a `sudo` log entry.
///
/// sudo writes `user : TTY=pts/0 ; PWD=/var/www/app ; USER=root ; COMMAND=...`,
/// the `PWD` field after `TTY` (or `CHROOT` when set) and before `USER`, each
/// field set off by ` ; `. Only that shape is read, so a connection string's
/// `Uid=sa;PWD=secret;` and a lower-case `pwd=` stay credentials.
fn is_sudo_cwd(text: &str, head: &Head) -> bool {
    if &text[head.start..head.key_end] != "PWD" {
        return false;
    }
    let Some(before) = text[..head.start].strip_suffix(" ; ") else {
        return false;
    };
    let field = before.rsplit(' ').next().unwrap_or_default();
    if !(field.starts_with("TTY=") || field.starts_with("CHROOT=")) {
        return false;
    }
    let line = text[head.end..].split('\n').next().unwrap_or_default();
    line.split_once(" ; ")
        .is_some_and(|(_, next)| next.starts_with("USER="))
}

/// A character that can be part of a key in text: a letter or digit of any
/// script, a combining mark or a character that prints nothing, which the
/// skeleton of a name drops, or one of `_`, `.` and `-`.
fn is_key_char(c: char) -> bool {
    c.is_alphanumeric() || matches!(c, '_' | '.' | '-') || is_ignorable(c) || is_mark(c)
}

/// A quote that may close a key or a value.
const fn is_closing_quote(c: char) -> bool {
    matches!(
        c,
        '"' | '\''
            | '\u{201d}'
            | '\u{2019}'
            | '\u{201c}'
            | '\u{bb}'
            | '\u{ab}'
            | '\u{203a}'
            | '\u{2039}'
            | '\u{300d}'
            | '\u{300f}'
    )
}

/// The quotes that close a value opened with the typographic quote `open`.
const fn typographic_closers(open: char) -> &'static [char] {
    match open {
        '\u{201c}' => &['\u{201d}'],
        '\u{2018}' => &['\u{2019}'],
        '\u{201e}' => &['\u{201c}', '\u{201d}'],
        '\u{201a}' => &['\u{2018}', '\u{2019}'],
        '\u{ab}' => &['\u{bb}'],
        '\u{bb}' => &['\u{ab}'],
        '\u{2039}' => &['\u{203a}'],
        '\u{203a}' => &['\u{2039}'],
        '\u{300c}' => &['\u{300d}'],
        '\u{300e}' => &['\u{300f}'],
        _ => &[],
    }
}

/// Whether the character at `from` opens a typographic-quoted value.
fn opens_typographic_quote(text: &str, from: usize) -> bool {
    text[from..]
        .chars()
        .next()
        .is_some_and(|c| !typographic_closers(c).is_empty())
}

/// The end of the typographic-quoted value opening at `from`, on one line, or `None` when no quote closes it there or the character at `from` opens none.
fn typographic_end(text: &str, from: usize) -> Option<usize> {
    let open = text[from..].chars().next()?;
    let closers = typographic_closers(open);
    if closers.is_empty() {
        return None;
    }
    let body = from + open.len_utf8();
    text[body..]
        .char_indices()
        .take_while(|&(_, c)| c != '\n')
        .find(|&(_, c)| closers.contains(&c))
        .map(|(i, c)| body + i + c.len_utf8())
}

/// Whether `key` names an authorization header, as `Authorization`, `Proxy-Authorization` and `HTTP_AUTHORIZATION` do.
fn names_authorization(key: &str) -> bool {
    key.as_bytes()
        .windows(AUTHORIZATION.len())
        .any(|window| window.eq_ignore_ascii_case(AUTHORIZATION))
}

/// Whether `word` is one of the [`AUTH_SCHEMES`], in any case.
fn is_auth_scheme(word: &str) -> bool {
    AUTH_SCHEMES
        .iter()
        .any(|scheme| word.eq_ignore_ascii_case(scheme))
}

/// The next key followed by `separator` that starts at or after `from`.
///
/// It finds each separator and reads the key back from it, the same key
/// [`separator_end`] reads forward to that separator.
fn next_head(text: &str, from: usize, separator: Separator) -> Option<Head> {
    let bytes = text.as_bytes();
    let byte = match separator {
        Separator::Colon => b':',
        Separator::Equals => b'=',
    };
    let mut search = from;
    // The other starts are the lead byte of a full-width form and the `%` of an escape.
    while let Some(found) = memchr::memchr3(byte, 0xEF, b'%', &bytes[search..]) {
        let at = search + found;
        search = at + 1;
        if separator_len(bytes, at, separator).is_none() {
            continue;
        }
        let before = &text[from..at];
        let spaced = match separator {
            Separator::Colon => trim_gap_end(before, is_colon_gap),
            Separator::Equals => trim_gap_end(before, is_gap),
        };
        let quote = spaced.chars().next_back().filter(|&c| is_closing_quote(c));
        let key_end = from + spaced.len() - quote.map_or(0, char::len_utf8);
        let key = key_len(&text[from..key_end]);
        let start = key_end - key;
        // A key cut off at `from` is the tail of a word, which is no key.
        if key == 0 || text[..start].chars().next_back().is_some_and(is_key_char) {
            continue;
        }
        if let Some(end) = separator_end(text, start, key_end, separator) {
            return Some(Head {
                start,
                key_end,
                end,
            });
        }
    }
    None
}

/// Where the value starts when `separator` follows the key at `start..key_end`.
fn separator_end(text: &str, start: usize, key_end: usize, separator: Separator) -> Option<usize> {
    let bytes = text.as_bytes();
    let mut at = key_end;
    if let Some(quote) = text[at..].chars().next().filter(|&c| is_closing_quote(c)) {
        at += quote.len_utf8();
    }
    match separator {
        Separator::Colon => {
            at = skip_gap(text, at, is_colon_gap);
            let len = separator_len(bytes, at, separator)?;
            // A key after `::` ends a path, such as the log target `app::auth:`, and is never a key.
            if start >= 2 && &bytes[start - 2..start] == b"::" {
                return None;
            }
            let mut after = at + len;
            // `key::value` separates with both colons and `key := value` with `:=`, so the value starts after the second character.
            if len == 1 && matches!(bytes.get(after), Some(b':' | b'=')) {
                after += 1;
            }
            Some(skip_gap(text, after, is_colon_gap))
        }
        Separator::Equals => {
            at = skip_gap(text, at, is_gap);
            let len = separator_len(bytes, at, separator)?;
            let mut after = at + len;
            if len == 1 {
                // `==` compares. `=>` separates a key from its value as a hash rocket does,
                // unless the key is itself what an earlier `=>` points at.
                match bytes.get(after) {
                    Some(b'=') => return None,
                    Some(b'>') if follows_rocket(&text[..start]) => return None,
                    Some(b'>') => after += 1,
                    _ => {}
                }
            }
            Some(skip_gap(text, after, is_gap))
        }
    }
}

/// Whether `before`, less the blanks and quotes at its end, ends in `=>`.
fn follows_rocket(before: &str) -> bool {
    before
        .trim_end_matches(|c| is_gap(c) || is_closing_quote(c))
        .ends_with("=>")
}

/// How many bytes the `separator` starting at `at` takes, or `None` when none starts there.
///
/// Besides ASCII `:` and `=`, a separator may be written full-width (U+FF1A,
/// U+FF1D), small (U+FE55, U+FE13, U+FE66) or URL-encoded (`%3A`, `%3D`).
fn separator_len(bytes: &[u8], at: usize, separator: Separator) -> Option<usize> {
    let rest = bytes.get(at..)?;
    match separator {
        Separator::Colon => match rest {
            [b':', ..] => Some(1),
            [0xEF, 0xBC, 0x9A, ..]
            | [0xEF, 0xB9, 0x95, ..]
            | [0xEF, 0xB8, 0x93, ..]
            | [b'%', b'3', b'A' | b'a', ..] => Some(3),
            _ => None,
        },
        Separator::Equals => match rest {
            [b'=', ..] => Some(1),
            [0xEF, 0xBC, 0x9D, ..] | [0xEF, 0xB9, 0xA6, ..] | [b'%', b'3', b'D' | b'd', ..] => {
                Some(3)
            }
            _ => None,
        },
    }
}

/// `text` without the blanks, characters that print nothing and ANSI colour sequences at its end.
fn trim_gap_end(text: &str, gap: fn(char) -> bool) -> &str {
    let mut rest = text;
    loop {
        let trimmed = rest.trim_end_matches(gap);
        let sgr = sgr_before(trimmed);
        if sgr == 0 {
            return trimmed;
        }
        rest = &trimmed[..trimmed.len() - sgr];
    }
}

/// The first byte at or after `from` that is no blank, character that prints nothing or ANSI colour sequence.
fn skip_gap(text: &str, from: usize, gap: fn(char) -> bool) -> usize {
    let mut at = from;
    loop {
        at = scan_until(text, at, |c| !gap(c));
        let sgr = sgr_len(&text[at..]);
        if sgr == 0 {
            return at;
        }
        at += sgr;
    }
}

/// The bytes of the key that ends `before`: key characters, `\uXXXX` escapes and ANSI colour sequences, read from the end.
fn key_len(before: &str) -> usize {
    let mut rest = before;
    loop {
        let escape = escape_before(rest).max(sgr_before(rest));
        if escape > 0 {
            rest = &rest[..rest.len() - escape];
        } else if let Some(c) = rest.chars().next_back().filter(|&c| is_key_char(c)) {
            rest = &rest[..rest.len() - c.len_utf8()];
        } else {
            return before.len() - rest.len();
        }
    }
}

/// The end of the quoted string opening at `from`, honouring `\` escapes.
///
/// `None` when it never closes, or when `multiline` is false and a line ends first.
fn quoted_end(text: &str, from: usize, multiline: bool) -> Option<usize> {
    let quote = char::from(text.as_bytes()[from]);
    let mut chars = text[from + 1..].char_indices();
    while let Some((i, c)) = chars.next() {
        match c {
            '\\' => match chars.next() {
                Some((_, '\n')) if !multiline => return None,
                Some(_) => {}
                None => return None,
            },
            '\n' if !multiline => return None,
            c if c == quote => return Some(from + 1 + i + 1),
            _ => {}
        }
    }
    None
}

/// The end of the quoted string opening at `from` at its next quote, escaped or not.
///
/// `None` when no quote follows, or when `multiline` is false and a line ends first.
fn plain_quoted_end(text: &str, from: usize, multiline: bool) -> Option<usize> {
    let quote = char::from(text.as_bytes()[from]);
    let rest = &text[from + 1..];
    let close = if multiline {
        rest.find(quote)
    } else {
        rest.find([quote, '\n'])
    }?;
    (rest.as_bytes()[close] != b'\n').then_some(from + 1 + close + 1)
}

/// The end of the quoted value opening at `from`: its first quote no `\` escapes, else its next quote.
///
/// The fallback keeps a value whose escape swallows its closing quote, as in
/// `"abc\"`, from masking less than a reading that ignores escapes.
fn quoted_value_end(text: &str, from: usize, multiline: bool) -> Option<usize> {
    quoted_end(text, from, multiline).or_else(|| plain_quoted_end(text, from, multiline))
}

/// The last `quote` in `text` that no backslash escapes, so a string can close at it.
fn last_closable(text: &str, quote: u8) -> Option<usize> {
    let bytes = text.as_bytes();
    let mut end = bytes.len();
    while let Some(at) = bytes[..end].iter().rposition(|&b| b == quote) {
        let escapes = bytes[..at]
            .iter()
            .rev()
            .take_while(|&&b| b == b'\\')
            .count();
        if escapes.is_multiple_of(2) {
            return Some(at);
        }
        end = at;
    }
    None
}

/// The end of the digit groups after `from`, as in `+61 412 345 678`, each a blank, an optional `(` or `+`, a digit, then non-stop characters.
///
/// A digit is any [`char::is_numeric`] character, so groups of Arabic-Indic or
/// full-width digits run on as ASCII ones do. Returns every end in turn, the
/// first being `from` itself.
fn digit_group_ends(text: &str, from: usize, stop: fn(char) -> bool) -> Vec<usize> {
    let bytes = text.as_bytes();
    let mut ends = vec![from];
    let mut at = from;
    while let Some(blank) = text[at..].chars().next().filter(|&c| is_blank(c)) {
        let mut next = at + blank.len_utf8();
        if matches!(bytes.get(next), Some(b'(' | b'+')) {
            next += 1;
        }
        let Some(digit) = text[next..].chars().next().filter(|c| c.is_numeric()) else {
            break;
        };
        at = scan_until(text, next + digit.len_utf8(), stop);
        ends.push(at);
    }
    ends
}

/// A character that ends an unquoted value after a colon.
fn ends_colon_value(c: char) -> bool {
    is_space(c) || matches!(c, ',' | '"' | '}')
}

/// A character that ends an unquoted value after an equals sign.
fn ends_equals_value(c: char) -> bool {
    is_space(c) || c == '&'
}

/// The end of the unquoted value after a colon at `from`, which must end at white space, `,`, `}` or the end of the text.
fn unquoted_colon_end(text: &str, from: usize) -> Option<usize> {
    let run_end = scan_until(text, from, ends_colon_value);
    let clean_end = |at: usize| {
        text[at..]
            .chars()
            .next()
            .is_none_or(|c| is_space(c) || matches!(c, ',' | '}'))
    };
    (run_end > from)
        .then(|| {
            digit_group_ends(text, run_end, ends_colon_value)
                .into_iter()
                .rev()
                .find(|&end| clean_end(end))
        })
        .flatten()
}

/// The end of the unquoted value after an equals sign at `from`, which may be empty.
fn unquoted_equals_end(text: &str, from: usize) -> usize {
    let run_end = scan_until(text, from, ends_equals_value);
    digit_group_ends(text, run_end, ends_equals_value)
        .last()
        .copied()
        .unwrap_or(run_end)
}

/// `mask` as the inside of a JSON string: `"`, `\` and control characters
/// escaped, so a custom mask can't end the string or break the line.
fn json_escaped(mask: &str) -> Cow<'_, str> {
    if !mask.chars().any(|c| matches!(c, '"' | '\\') || c < ' ') {
        return Cow::Borrowed(mask);
    }
    let mut out = String::with_capacity(mask.len() + 8);
    for c in mask.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if c < ' ' => {
                let _ = write!(out, "\\u{:04x}", u32::from(c));
            }
            c => out.push(c),
        }
    }
    Cow::Owned(out)
}

/// What replaces a span of text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Cover {
    /// The mask.
    Mask,
    /// The mask inside double quotes, so a JSON line stays valid JSON.
    QuotedMask,
    /// Nothing, for a run straight after a mask that already stands for it.
    Cut,
}

impl Cover {
    /// How many bytes this cover writes in place of a span.
    fn len(self, mask: &str) -> usize {
        match self {
            Self::Mask => mask.len(),
            Self::QuotedMask => json_escaped(mask).len() + 2,
            Self::Cut => 0,
        }
    }
}

/// A span of text and what replaces it.
#[derive(Debug, Clone, Copy)]
struct Span {
    start: usize,
    end: usize,
    cover: Cover,
}

/// A value as a pass reads it.
#[derive(Debug, Clone, Copy)]
struct Read {
    /// Where the pass ends the value, or `None` when it replaces nothing.
    end: Option<usize>,
    /// What replaces the value, and the run past it when the pass replaces nothing.
    cover: Cover,
    /// How far the value runs, never short of `end`.
    reach: usize,
}

impl Read {
    /// A value the pass replaces whole, up to `end`.
    const fn whole(end: usize, cover: Cover) -> Self {
        Self {
            end: Some(end),
            cover,
            reach: end,
        }
    }
}

/// Reads the value after each key in one text, keys taken in rising order of position.
///
/// A quoted value that never closes runs to the end of its line, or, when its
/// reading may cross lines, as a double-quoted value after `:` and a
/// `Name(...)` value may, to the end of the text short of a line break that
/// ends it. A `Name(...)` value runs to its close, or to the end of the text
/// when it does not close within [`MAX_WRAPPER_LEN`] bytes. An unquoted value
/// read as an authorization header's runs on past its scheme through the
/// credentials after it, and so does one whose first word is an
/// authentication scheme.
struct Values<'a> {
    text: &'a str,
    /// Where the line holding the last value read on one line ends.
    line_end: Option<usize>,
    /// The last quote of each kind, `"` then `'`, that no backslash escapes, found on first need.
    closable: Option<[Option<usize>; 2]>,
}

impl<'a> Values<'a> {
    const fn new(text: &'a str) -> Self {
        Self {
            text,
            line_end: None,
            closable: None,
        }
    }

    /// Read the value after a colon at `from`, as an authorization header's when `header` is set.
    fn colon(&mut self, from: usize, header: bool) -> Read {
        let text = self.text;
        match text.as_bytes().get(from) {
            Some(b'"') => match quoted_value_end(text, from, true) {
                Some(end) => Read::whole(end, Cover::QuotedMask),
                None => Read {
                    end: None,
                    cover: Cover::QuotedMask,
                    reach: self.text_end(),
                },
            },
            Some(b'\'') => match quoted_value_end(text, from, false) {
                Some(end) => Read::whole(end, Cover::Mask),
                None => Read {
                    end: unquoted_colon_end(text, from),
                    cover: Cover::Mask,
                    reach: self.line(from),
                },
            },
            _ if opens_typographic_quote(text, from) => match typographic_end(text, from) {
                Some(end) => Read::whole(end, Cover::Mask),
                None => Read {
                    end: unquoted_colon_end(text, from),
                    cover: Cover::Mask,
                    reach: self.line(from),
                },
            },
            _ => self.unquoted(
                from,
                unquoted_colon_end(text, from),
                header,
                Separator::Colon,
            ),
        }
    }

    /// Read the value after an equals sign at `from`, as an authorization header's when `header` is set.
    fn equals(&mut self, from: usize, header: bool) -> Read {
        let text = self.text;
        let opens_typographic = opens_typographic_quote(text, from);
        if matches!(text.as_bytes().get(from), Some(b'"' | b'\'')) || opens_typographic {
            let closed = if opens_typographic {
                typographic_end(text, from)
            } else {
                quoted_value_end(text, from, false)
            };
            return match closed {
                Some(end) => Read::whole(end, Cover::Mask),
                None => Read {
                    end: Some(unquoted_equals_end(text, from)),
                    cover: Cover::Mask,
                    reach: self.line(from),
                },
            };
        }
        self.unquoted(
            from,
            Some(unquoted_equals_end(text, from)),
            header,
            Separator::Equals,
        )
    }

    /// Read an unquoted value ending at `end`, or further when a `Name(...)` value starts at `from`.
    ///
    /// With no `Name(...)` value there, the value ending at `end` is a scheme
    /// when `header` is set or it is one of the [`AUTH_SCHEMES`], and then the
    /// credentials after it are read too, as the `separator` before them
    /// reads them.
    fn unquoted(
        &mut self,
        from: usize,
        end: Option<usize>,
        header: bool,
        separator: Separator,
    ) -> Read {
        let (wrapped, reach) = self.wrapper(from);
        let mut end = end.max(wrapped);
        if reach.is_none()
            && let Some(scheme_end) = end.filter(|&scheme_end| scheme_end > from)
            && (header || is_auth_scheme(&self.text[from..scheme_end]))
        {
            end = Some(self.credentials(scheme_end, separator));
        }
        let low = end.unwrap_or(from);
        Read {
            end,
            cover: Cover::Mask,
            reach: reach.map_or(low, |reach| reach.max(low)),
        }
    }

    /// Where a pass ends the `Name(...)` value at `from`, and how far the value runs.
    ///
    /// The name is letters and digits of any script and `_`. Parentheses nest, and a
    /// string inside, single or double quoted, may span lines. It closes at its
    /// first quote no backslash escapes or, when the text holds no such quote
    /// after it, at its next quote. A pass ends the value at its close only when
    /// the name starts with a letter or `_`, every string in it closes at a
    /// quote no backslash escapes, and it closes within [`MAX_WRAPPER_LEN`]
    /// bytes. Otherwise the first is `None`. The value runs to its close, or to
    /// the end of the text when it does not close within the window. Both are
    /// `None` when no `Name(` starts at `from`. The walk scans each byte of the
    /// window at most once, so a value costs at most the window.
    fn wrapper(&mut self, from: usize) -> (Option<usize>, Option<usize>) {
        let text = self.text;
        let bytes = text.as_bytes();
        let name_end = from
            + text[from..]
                .chars()
                .take_while(|&c| c.is_alphanumeric() || c == '_')
                .map(char::len_utf8)
                .sum::<usize>();
        if name_end == from || bytes.get(name_end) != Some(&b'(') {
            return (None, None);
        }
        let never = (None, Some(self.text_end()));
        let mut limit = text.len().min(from + MAX_WRAPPER_LEN);
        while !text.is_char_boundary(limit) {
            limit -= 1;
        }
        let window = &text[..limit];
        let mut escaped = false;
        let mut depth = 0usize;
        let mut at = name_end;
        while at < limit {
            match bytes[at] {
                b'(' => depth += 1,
                b')' => {
                    depth -= 1;
                    if depth == 0 {
                        let end = at + 1;
                        let digit = text[from..].chars().next().is_some_and(char::is_numeric);
                        let replaced = !(escaped || digit);
                        return (replaced.then_some(end), Some(end));
                    }
                }
                quote @ (b'"' | b'\'') => {
                    let close = if self.closes_after(at) {
                        quoted_end(window, at, true)
                    } else {
                        escaped = true;
                        window[at + 1..]
                            .find(char::from(quote))
                            .map(|i| at + 1 + i + 1)
                    };
                    let Some(close) = close else {
                        return never;
                    };
                    at = close - 1;
                }
                _ => {}
            }
            at += 1;
        }
        never
    }

    /// Where the credentials after a scheme ending at `scheme_end` end, or `scheme_end` when none follow.
    ///
    /// Spaces or tabs separate the scheme from its credentials, which are items
    /// separated by commas, as in `Digest username="u", response="r"`. They
    /// never cross a line.
    fn credentials(&mut self, scheme_end: usize, separator: Separator) -> usize {
        let text = self.text;
        let blanks_end = |from: usize| scan_until(text, from, |c| !is_blank(c));
        let mut at = blanks_end(scheme_end);
        if at == scheme_end {
            return scheme_end;
        }
        let mut end = scheme_end;
        loop {
            let item_end = self.credential_item(at, separator);
            if item_end == at {
                return end;
            }
            end = item_end;
            let comma = blanks_end(end);
            if text.as_bytes().get(comma) != Some(&b',') {
                return end;
            }
            at = blanks_end(comma + 1);
        }
    }

    /// Where the credential item at `from` ends, or `from` when none starts there.
    ///
    /// An item runs to white space, `,`, `}` or `"`, and after `=` also to
    /// `&`, which separates form fields there. A quoted string opens at the
    /// item's start or after `=`, and one that does not close on its line
    /// takes the item to the end of the line.
    fn credential_item(&mut self, from: usize, separator: Separator) -> usize {
        let text = self.text;
        let bytes = text.as_bytes();
        let ends_at_ampersand = separator == Separator::Equals;
        let mut at = from;
        while let Some(c) = text[at..].chars().next() {
            if c == '"' && (at == from || bytes[at - 1] == b'=') {
                match quoted_value_end(text, at, false) {
                    Some(close) => at = close,
                    None => return self.line(at),
                }
            } else if is_space(c) || matches!(c, ',' | '}' | '"') || (c == '&' && ends_at_ampersand)
            {
                break;
            } else {
                at += c.len_utf8();
            }
        }
        at
    }

    /// Whether a quote like the one at `at` that no backslash escapes lies anywhere after it.
    fn closes_after(&mut self, at: usize) -> bool {
        let text = self.text;
        let closable = *self
            .closable
            .get_or_insert_with(|| [last_closable(text, b'"'), last_closable(text, b'\'')]);
        let kind = usize::from(text.as_bytes()[at] == b'\'');
        closable[kind].is_some_and(|last| last > at)
    }

    /// Where a value whose reading may cross lines runs to: the end of the text, short of a line break that ends it.
    fn text_end(&self) -> usize {
        self.text
            .strip_suffix('\n')
            .map_or(self.text.len(), str::len)
    }

    /// Where the line holding `from` ends: its line break, or the end of the text.
    fn line(&mut self, from: usize) -> usize {
        if let Some(end) = self.line_end
            && from <= end
        {
            return end;
        }
        let end = self.text[from..]
            .find('\n')
            .map_or(self.text.len(), |i| from + i);
        self.line_end = Some(end);
        end
    }
}

/// The value after every `separator` key that `matcher` names a credential, and the run past each one.
///
/// Only a credential key's value is consumed, so a key inside another pair's
/// value, as in `config:password:x`, is still checked.
fn pair_spans(
    text: &str,
    separator: Separator,
    matcher: &CredentialMatcher,
    mask: &str,
    spellings: &mut Spellings,
) -> (Vec<Span>, Vec<Span>) {
    let mut values = Values::new(text);
    let mut spans = Vec::new();
    let mut runs = Vec::new();
    let mut copied = 0;
    let mut from = 0;
    while let Some(head) = next_head(text, from, separator) {
        from = head.end;
        let key = &text[head.start..head.key_end];
        let found = matcher.name_match(key, "", spellings);
        if head.start < copied || found == NameMatch::None {
            continue;
        }
        if let Some(end) = mask_end(text, head.end, mask) {
            from = end;
            continue;
        }
        if separator == Separator::Equals && is_sudo_cwd(text, &head) {
            continue;
        }
        let header = names_authorization(key);
        let read = match separator {
            Separator::Colon => values.colon(head.end, header),
            Separator::Equals => values.equals(head.end, header),
        };
        if found == NameMatch::Plural
            && read
                .end
                .is_some_and(|end| is_number(&text.as_bytes()[head.end..end]))
        {
            continue;
        }
        let low = read.end.unwrap_or(head.end);
        if let Some(end) = read.end {
            spans.push(Span {
                start: head.end,
                end,
                cover: read.cover,
            });
            copied = end;
        }
        if read.reach > low {
            let cover = if read.end.is_some() {
                Cover::Cut
            } else {
                read.cover
            };
            runs.push(Span {
                start: low,
                end: read.reach,
                cover,
            });
        }
    }
    (spans, runs)
}

/// `runs`, placed in the text `spans` were read from, as they sit once each span is replaced by its cover.
///
/// A run ending inside a span ends after that span's cover.
fn placed_after(runs: Vec<Span>, spans: &[Span], mask: &str) -> Vec<Span> {
    let mut cover_ends = Vec::with_capacity(spans.len());
    let mut written = 0;
    let mut copied = 0;
    for span in spans {
        written += span.start - copied + span.cover.len(mask);
        cover_ends.push(written);
        copied = span.end;
    }
    let place = |at: usize| {
        let Some(index) = spans
            .partition_point(|span| span.start <= at)
            .checked_sub(1)
        else {
            return at;
        };
        let span = spans[index];
        if at >= span.end {
            cover_ends[index] + (at - span.end)
        } else if at > span.start {
            cover_ends[index]
        } else {
            cover_ends[index] - span.cover.len(mask)
        }
    };
    runs.into_iter()
        .map(|run| Span {
            start: place(run.start),
            end: place(run.end),
            cover: run.cover,
        })
        .collect()
}

/// `text` with each span replaced by its cover, still borrowed when there are none.
///
/// Spans that overlap or touch merge, and the first of them decides the cover,
/// so a value and the run past it come out as one mask.
fn apply<'a>(text: &'a str, mut spans: Vec<Span>, mask: &str, n: &mut usize) -> Cow<'a, str> {
    if spans.is_empty() {
        return Cow::Borrowed(text);
    }
    spans.sort_by_key(|span| (span.start, span.cover == Cover::Cut));
    let mut out = String::with_capacity(text.len());
    let mut copied = 0;
    let mut spans = spans.into_iter().peekable();
    while let Some(first) = spans.next() {
        let mut end = first.end;
        while let Some(next) = spans.next_if(|next| next.start <= end) {
            end = end.max(next.end);
        }
        out.push_str(&text[copied..first.start]);
        match first.cover {
            Cover::Mask => out.push_str(mask),
            Cover::QuotedMask => {
                out.push('"');
                out.push_str(&json_escaped(mask));
                out.push('"');
            }
            Cover::Cut => {}
        }
        if first.cover != Cover::Cut {
            *n += 1;
        }
        copied = end;
    }
    out.push_str(&text[copied..]);
    Cow::Owned(out)
}

/// `text` with the value after every `key: value`, then every `key=value`, whose key `matcher` names a credential replaced by `mask`.
///
/// Each pass replaces a value only as far as its first reading goes, and the
/// equals pass reads the colon pass's output. The run past a value that never
/// closes, or past a `Name(...)` value that first reading does not take
/// whole, is masked after both passes, so a key inside a run is still read
/// and its value still masked.
fn mask_pairs<'a>(
    text: &'a str,
    matcher: &CredentialMatcher,
    mask: &str,
    spellings: &mut Spellings,
    n: &mut usize,
) -> Cow<'a, str> {
    let bytes = text.as_bytes();
    let separated = memchr::memchr3(b':', b'=', b'%', bytes).is_some()
        || (!spellings.plain() && memchr::memchr(0xEF, bytes).is_some());
    if !separated || !matcher.may_name_in(text, spellings.plain()) {
        return Cow::Borrowed(text);
    }
    let (spans, runs) = pair_spans(text, Separator::Colon, matcher, mask, spellings);
    let runs = placed_after(runs, &spans, mask);
    let colon_masked = apply(text, spans, mask, n);
    let (mut spans, more) = pair_spans(&colon_masked, Separator::Equals, matcher, mask, spellings);
    spans.extend(more);
    spans.extend(runs);
    then(colon_masked, |t| apply(t, spans, mask, n))
}

/// `text` with every credential in it replaced by `mask`.
///
/// Masks, in order: URL passwords, signed URL query parameters such as
/// `?sig=` and `&X-Amz-Signature=`, the quoted value after `Illegal header
/// value`, bearer tokens, the value after `key: value`
/// or `key::value` and the value after `key=value`, where `matcher` names the
/// key a credential. After an authorization header key the value is the scheme
/// and its credentials, so `Authorization: Basic ...` masks whole, and so is a
/// value opening with an authentication scheme after any credential key.
pub fn mask_text<'a>(text: &'a str, matcher: &CredentialMatcher, mask: &str) -> Cow<'a, str> {
    mask_text_in(text, matcher, mask, &mut Spellings::default()).0
}

/// As [`mask_text`], with the number of masks written, spelling keys into
/// `spellings` so a caller that keeps one allocates nothing for a key once it
/// has grown.
pub fn mask_text_in<'a>(
    text: &'a str,
    matcher: &CredentialMatcher,
    mask: &str,
    spellings: &mut Spellings,
) -> (Cow<'a, str>, usize) {
    let mut n = 0;
    let text = url_masked(text, mask, true, &mut n);
    let text = then(text, |t| mask_query_signatures(t, mask, &mut n));
    let text = then(text, |t| mask_refused_headers(t, mask, &mut n));
    let text = then(text, |t| mask_bearer(t, mask, &mut n));
    let text = then(text, |t| mask_pairs(t, matcher, mask, spellings, &mut n));
    (text, n)
}

/// `false` only when [`mask_text`] leaves `text` as it is: every pass needs
/// one of these bytes, `:` or `=` before a value, or the `%` of an encoded one,
/// or the lead byte `0xEF` of a full-width one, `?` or `&` before a signed
/// parameter, the `b` of `bearer` and a token after it, or the `v` of
/// [`REFUSED_HEADER`] and a quote after it.
pub(crate) fn may_mask(text: &[u8], plain: bool) -> bool {
    let bearer = "bearer ".len() < text.len() && memchr::memchr2(b'b', b'B', text).is_some();
    let refused = REFUSED_HEADER.len() < text.len() && memchr::memchr2(b'v', b'V', text).is_some();
    bearer
        || refused
        || memchr::memchr3(b':', b'=', b'?', text).is_some()
        || if plain {
            memchr::memchr2(b'&', b'%', text).is_some()
        } else {
            memchr::memchr3(b'&', b'%', 0xEF, text).is_some()
        }
}

#[cfg(test)]
thread_local! {
    static PLAIN_OFF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Whether a test has forced every text to read as not plain, so each takes the general paths.
#[cfg(test)]
pub(crate) fn plain_forced_off() -> bool {
    PLAIN_OFF.get()
}

/// Run `run` with every text read as not plain, which is how the general paths are held to the fast ones.
#[cfg(all(test, feature = "record"))]
pub(crate) fn with_plain_off<T>(run: impl FnOnce() -> T) -> T {
    /// Puts the switch back, whether `run` returns or panics.
    struct Restore;
    impl Drop for Restore {
        fn drop(&mut self) {
            PLAIN_OFF.set(false);
        }
    }
    let _restore = Restore;
    PLAIN_OFF.set(true);
    run()
}

/// Texts shorter than this are read byte by byte, where a vector scan's set-up
/// costs more than the bytes it saves.
const SHORT: usize = 64;

/// Whether `text` is plain: ASCII with no `\` and no ESC byte, so no escape,
/// colour sequence or character of another script can read in it. Plain text
/// takes none of the paths those need.
pub(crate) fn is_plain(text: &[u8]) -> bool {
    #[cfg(test)]
    if plain_forced_off() {
        return false;
    }
    if text.len() >= SHORT {
        return text.is_ascii() && memchr::memchr2(b'\\', 0x1b, text).is_none();
    }
    let (chunks, rest) = text.as_chunks::<8>();
    let whole = chunks
        .iter()
        .all(|&chunk| plain_word(u64::from_le_bytes(chunk)));
    let mut tail = [b' '; 8];
    tail[..rest.len()].copy_from_slice(rest);
    whole && plain_word(u64::from_le_bytes(tail))
}

/// Whether none of the eight bytes of `word` is past ASCII, `\` or ESC.
const fn plain_word(word: u64) -> bool {
    const ONES: u64 = 0x0101_0101_0101_0101;
    const HIGH: u64 = 0x8080_8080_8080_8080;
    // The bytes of `word` set against a byte that is zero where they match it.
    const fn none_equal(word: u64, byte: u8) -> bool {
        let x = word ^ (ONES * byte as u64);
        x.wrapping_sub(ONES) & !x & HIGH == 0
    }
    word & HIGH == 0 && none_equal(word, b'\\') && none_equal(word, 0x1b)
}

/// `text` after `step`, still borrowed when neither changed it.
fn then(text: Cow<'_, str>, step: impl FnOnce(&str) -> Cow<'_, str>) -> Cow<'_, str> {
    let changed = match step(&text) {
        Cow::Borrowed(_) => None,
        Cow::Owned(masked) => Some(masked),
    };
    changed.map_or(text, Cow::Owned)
}

/// The text built in `out` with the rest of `text` from `copied`, or `text` itself when nothing was built.
fn finish(text: &str, out: Option<String>, copied: usize) -> Cow<'_, str> {
    match out {
        None => Cow::Borrowed(text),
        Some(mut buf) => {
            buf.push_str(&text[copied..]);
            Cow::Owned(buf)
        }
    }
}

#[cfg(test)]
mod tests;