redact-secret 0.1.0-beta.15

Deterministic secret detection and redaction for runtime data and AI context: scans text locally before it reaches logs, storage, telemetry, tools, or model context. Side-effect free: no runtime network, filesystem, environment, telemetry, secret storage, or UI.
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
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
//! Keyword-gated API keys for Mistral, Cohere, AI21 and Deepgram (issue #868).
//!
//! None of the four providers documents a prefix, length or alphabet for its
//! API key, and none of the provider SDKs validates one (`Mistral`,
//! `cohere.ClientV2`, `AI21Client` and `DeepgramClient` all accept any
//! string). The shapes below come only from scanner rules and maintainer
//! observation recorded in the research comments of issues #781, #782, #784
//! and #789, so this is **not** a T1 contract. It is a contextual,
//! unqualified, T2-at-best claim: a bare run of the right length is
//! indistinguishable from a hash, a session id or another vendor's key, so a
//! value is a finding only when provider context is adjacent to it.
//!
//! | Detector | Shape (scanner-inferred) | Provider keywords |
//! | --- | --- | --- |
//! | `mistral-api-key` | exactly 32 `[A-Za-z0-9]` | `mistral` |
//! | `cohere-api-key` | exactly 40 `[A-Za-z0-9]` | `cohere`, `CO_API_KEY` |
//! | `ai21-api-key` | exactly 32 `[A-Za-z0-9]` | `ai21` |
//! | `deepgram-api-key` | exactly 40 `[0-9a-z]` | `deepgram` |
//!
//! Deepgram's alphabet is the wider of the two scanner readings
//! (trufflehog `[0-9a-z]`, betterleaks `[a-f0-9]`); its own documentation
//! example (32 hex) contradicts both, and is read as a placeholder.
//!
//! Exa (#787) has no detector here: no source states any shape for its key
//! (only the key *id* is documented as a UUID), so any contract would be
//! invented. It stays with `generic-token`.
//!
//! ## Adjacency contract
//!
//! Context is read on the value's own line only (the incremental sanitizer's
//! processing unit), immediately before the value. One two-line layout is
//! the exception (issue #1016): the `value:` key of a Kubernetes-style `env`
//! entry takes the name of its sibling `name:` key on the adjacent line
//! (`text::list_item_paired_name`), which the incremental session holds in
//! one unit (`has_open_list_item_pair`).
//!
//! 1. **Named assignment** (High): the value is assigned to a key whose
//!    normalized name carries the provider keyword and whose last segment is
//!    a credential word (`key`, `token`, `secret`, `apikey`, `credential`):
//!    `MISTRAL_API_KEY=`, `CO_API_KEY=`, `"deepgramApiKey":`.
//! 2. **SDK constructor** (High): the value is a keyword argument of a call
//!    whose callee name carries the provider keyword and whose key is a
//!    credential word (`Mistral(api_key="...")`,
//!    `cohere.ClientV2(api_key=...)`, `new CohereClient({ token: "..." })`),
//!    or the sole positional string (`DeepgramClient("...")`). Since issue
//!    #932 also a quoted string that is the last positional argument of a
//!    call on a provider-named callee, past closed argument groups
//!    (`deepgram.NewRESTWithDefaults(context.Background(), "...")`), and the
//!    sole quoted argument of a credential-named method on a provider
//!    builder chain (`Cohere.builder().token("...")`).
//! 3. **Keyword-adjacent key** (Medium): a credential-word key
//!    (`api_key:`) within 32 bytes after the provider keyword with only
//!    name-like bytes between them (`# Mistral API key: ...`).
//! 4. **Header** (Deepgram only): `Authorization: Token <value>` on a line
//!    that also names `deepgram`, with or without a space after the colon
//!    (`HTTPie`'s `'Authorization:Token <value>'`, issue #932). High when the
//!    line names a host under the Deepgram API domain (`api.deepgram.com`,
//!    `api.eu.deepgram.com`; issue #936): the value is in the key's
//!    documented slot of a request to the provider, as specific as a
//!    provider-named key. Medium when `deepgram` is only a word on the line
//!    (`# deepgram: Authorization: Token <value>`). `Bearer` forms are
//!    already `bearer-token`'s.
//!
//! 5. **Model route** (High, issue #1018): a credential-named key on a line
//!    that names a `LiteLLM`-style provider route, the keyword directly
//!    followed by `/` and a model name (`cohere/command-r-plus`). This
//!    covers a proxy debug line that logs the key under `masked_api_key=`
//!    without masking it. A key led by `masked_`/`redacted_`/`hashed_` (or
//!    another value-checked lead) qualifies only when the value does not
//!    show masking or hashing (a 40-hex run under `hashed_` is a digest),
//!    and a `publishable_` key never does; the masked display
//!    (`9ctA****...lwCk`) is never a run of the key's shape anyway.
//! 6. **Deepgram forms of issue #1017** (High unless noted): the
//!    `createClient` factory of `@deepgram/sdk` on a line that names
//!    `deepgram`; the WebSocket `token` subprotocol
//!    (`Sec-WebSocket-Protocol: token, <v>`, `["token", "<v>"]`) under the
//!    token-header host rule (medium with `deepgram` only as a word); and a
//!    token header or subprotocol whose request line or `Host:` header names
//!    the API host up to [`MAX_HTTP_BLOCK_LINES`] header lines above.
//! 7. **Provider field** (High, every family, issue #1017): a credential key
//!    or `auth` beside a `provider: <keyword>` field on the same line, or up
//!    to [`MAX_SIBLING_LINES`] keys above it in the same YAML mapping.
//!
//! The two multi-line windows are held open in a stream by
//! [`has_open_deepgram_request`] and [`has_open_provider_sibling`], which
//! read back exactly the lines the detector reads.
//!
//! A key ending in an identifier or location segment (`_id`, `_url`,
//! `_org`, ...) never qualifies (`MISTRAL_KEY_ID=`, `DEEPGRAM_PROJECT_ID=`),
//! and a non-credential key (`Mistral(model="...")`) is not context at all.
//!
//! ## Trade-offs
//!
//! - False negatives: a constructor argument on a different line from the
//!   constructor, a value whose keyword is far from it, a key that differs
//!   from the inferred length or alphabet, and any provider key under a name
//!   with no keyword (`API_KEY=`). Under a provider-named assignment
//!   `generic-token` still redacts a wrong-length value; this detector only
//!   adds the typed, exact-length, constructor-aware claim.
//! - False positives: a 32/40-byte hash or id assigned to a keyword-named
//!   credential key. Filler runs and hash-labelled values are excluded.
//! - Overlap: the finding is `Provider` specificity, so overlap resolution
//!   keeps one finding for a span that `generic-token` also matches.
//!
//! Types are confidence-gated (not in `ALWAYS_REDACT_TYPES`), like Twilio.

use super::text::lines;
use crate::detectors::generic_token::{masking_lead_hides_value, normalize_name};
use crate::detectors::pattern::{self, Alphabet};
use crate::detectors::text;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};

/// Last key-name segments that name the credential itself.
const CREDENTIAL_SEGMENTS: &[&str] = &["key", "token", "secret", "apikey", "credential"];

/// Longest gap between a provider keyword and the key that follows it, for
/// the keyword-adjacent (prose) form.
const KEYWORD_WINDOW: usize = 32;

/// Furthest an opening call parenthesis is searched for before a value, so
/// per-candidate work stays constant on a line packed with candidates.
const CALL_WINDOW: usize = 256;

/// Bytes of text before a value read for an `Authorization: Token` scheme.
const HEADER_WINDOW: usize = 48;

/// Most lines above a header line read for the request line or `Host:`
/// header of the same HTTP request (issue #1017).
pub(super) const MAX_HTTP_BLOCK_LINES: usize = 8;

/// Most sibling lines above a credential key read for a `provider:` key of
/// the same YAML mapping (issue #1017).
pub(super) const MAX_SIBLING_LINES: usize = 6;

/// Every provider keyword, for the incremental retention hints, which do not
/// know which keyword-gated detector will read the lines they hold.
const ALL_KEYWORDS: &[&str] = &["mistral", "cohere", "ai21", "deepgram"];

/// The Deepgram API domain, for the request-block retention hint.
const DEEPGRAM_API_DOMAIN: &str = "deepgram.com";

/// Static description of one keyword-gated provider key.
struct Spec {
    type_name: &'static str,
    len: usize,
    alphabet: Alphabet,
    /// Lowercase; matched as a substring of a normalized name or callee.
    keywords: &'static [&'static str],
    /// Lowercase normalized names matched only as whole `_` segments runs
    /// (`co_api_key`, so `pico_api_key` does not qualify).
    exact_names: &'static [&'static str],
    named_signal: &'static str,
    constructor_signal: &'static str,
    adjacent_signal: &'static str,
    route_signal: &'static str,
    sibling_signal: &'static str,
    /// Lowercase factory names that are the provider's constructor only when
    /// the line names the provider (`createClient`, issue #1017).
    factory_callees: &'static [&'static str],
    /// Accepts an `Authorization: Token <value>` header on a keyword line.
    token_header: bool,
    /// The provider's API host domain (lowercase). A token header on a line
    /// that names a host under it is high, not medium (issue #936).
    api_host_domain: Option<&'static str>,
}

/// What a value's line offers an `Authorization: Token` header.
#[derive(Clone, Copy, PartialEq, Eq)]
enum HeaderContext {
    /// The provider is not named on the line: the header is no context.
    Absent,
    /// The provider keyword is somewhere on the line (medium).
    Keyword,
    /// The line names a host under the provider's API domain (high).
    ProviderHost,
}

/// What a value's line (and, for bounded layouts, the lines above it) offers
/// as provider context, computed once per line.
#[derive(Clone, Copy)]
struct LineContext<'a> {
    header: HeaderContext,
    /// A provider keyword appears on the line.
    keyword_on_line: bool,
    /// A `LiteLLM`-style `<keyword>/<model>` route on the line (#1018).
    model_route: bool,
    /// A sibling `provider: <keyword>` field on the line or above it in the
    /// same YAML mapping (#1017).
    provider_sibling: bool,
    /// The name a Kubernetes-style `env` entry gives a `value:` key (#1016).
    paired_name: Option<&'a str>,
}

const MISTRAL: Spec = Spec {
    type_name: "mistral_api_key",
    len: 32,
    alphabet: pattern::is_alnum,
    keywords: &["mistral"],
    exact_names: &[],
    named_signal: "mistral-named-assignment",
    constructor_signal: "mistral-sdk-constructor",
    adjacent_signal: "mistral-keyword-adjacent",
    route_signal: "mistral-model-route",
    sibling_signal: "mistral-provider-field",
    factory_callees: &[],
    token_header: false,
    api_host_domain: None,
};

const COHERE: Spec = Spec {
    type_name: "cohere_api_key",
    len: 40,
    alphabet: pattern::is_alnum,
    keywords: &["cohere"],
    exact_names: &["co_api_key"],
    named_signal: "cohere-named-assignment",
    constructor_signal: "cohere-sdk-constructor",
    adjacent_signal: "cohere-keyword-adjacent",
    route_signal: "cohere-model-route",
    sibling_signal: "cohere-provider-field",
    factory_callees: &[],
    token_header: false,
    api_host_domain: None,
};

const AI21: Spec = Spec {
    type_name: "ai21_api_key",
    len: 32,
    alphabet: pattern::is_alnum,
    keywords: &["ai21"],
    exact_names: &[],
    named_signal: "ai21-named-assignment",
    constructor_signal: "ai21-sdk-constructor",
    adjacent_signal: "ai21-keyword-adjacent",
    route_signal: "ai21-model-route",
    sibling_signal: "ai21-provider-field",
    factory_callees: &[],
    token_header: false,
    api_host_domain: None,
};

const DEEPGRAM: Spec = Spec {
    type_name: "deepgram_api_key",
    len: 40,
    alphabet: pattern::is_lower_alnum,
    keywords: &["deepgram"],
    exact_names: &[],
    named_signal: "deepgram-named-assignment",
    constructor_signal: "deepgram-sdk-constructor",
    adjacent_signal: "deepgram-keyword-adjacent",
    route_signal: "deepgram-model-route",
    sibling_signal: "deepgram-provider-field",
    factory_callees: &["createclient"],
    token_header: true,
    api_host_domain: Some("deepgram.com"),
};

/// `[A-Za-z0-9_-]`: a run is never a slice of a wider identifier.
fn is_boundary_byte(byte: u8) -> bool {
    pattern::is_alnum(byte) || matches!(byte, b'_' | b'-')
}

/// Every non-overlapping, boundary-checked bare run of exactly `spec.len`
/// `spec.alphabet` bytes. A longer or shorter run is skipped whole.
fn scan_runs(line: &str, spec: &Spec) -> Vec<(usize, usize)> {
    let bytes = line.as_bytes();
    let mut matches = Vec::new();
    let mut start = 0;
    while start < bytes.len() {
        if !(spec.alphabet)(bytes[start]) {
            start += 1;
            continue;
        }
        let run_end = pattern::run_end(bytes, start, spec.alphabet);
        if run_end - start == spec.len
            && pattern::boundary_ok(bytes, start, run_end, is_boundary_byte)
        {
            matches.push((start, run_end));
        }
        start = run_end;
    }
    matches
}

fn name_has_provider(spec: &Spec, normalized: &str) -> bool {
    spec.keywords
        .iter()
        .any(|keyword| normalized.contains(keyword))
        || spec.exact_names.iter().any(|name| {
            normalized == *name
                || normalized.starts_with(&format!("{name}_"))
                || normalized.ends_with(&format!("_{name}"))
                || normalized.contains(&format!("_{name}_"))
        })
}

fn is_credential_name(normalized: &str) -> bool {
    normalized
        .rsplit('_')
        .next()
        .is_some_and(|segment| CREDENTIAL_SEGMENTS.contains(&segment))
}

/// `true` when an unclosed call opens before `end` whose callee name carries
/// a provider keyword: `Mistral(`, `cohere.ClientV2(`, `new Exa({`.
fn inside_provider_call(line: &str, spec: &Spec, end: usize, keyword_on_line: bool) -> bool {
    let bytes = line.as_bytes();
    let end = end.min(bytes.len());
    let floor = end.saturating_sub(CALL_WINDOW);
    let mut cursor = end;
    while cursor > floor {
        cursor -= 1;
        match bytes[cursor] {
            b')' => return false,
            b'(' => {
                let mut start = cursor;
                while start > 0
                    && (bytes[start - 1].is_ascii_alphanumeric()
                        || matches!(bytes[start - 1], b'_' | b'.'))
                {
                    start -= 1;
                }
                let callee = &line[start..cursor];
                if spec
                    .keywords
                    .iter()
                    .any(|keyword| text::contains_ci(callee, keyword))
                {
                    return true;
                }
                // Issue #1017: a provider SDK factory with a generic name
                // (`createClient` from `@deepgram/sdk`) on a line that names
                // the provider, as its import or receiving variable does.
                if keyword_on_line
                    && callee.rsplit('.').next().is_some_and(|name| {
                        spec.factory_callees
                            .iter()
                            .any(|listed| name.eq_ignore_ascii_case(listed))
                    })
                {
                    return true;
                }
            }
            _ => {}
        }
    }
    false
}

/// `true` when `bytes[start..end]` is a whole quoted string literal that is
/// the last argument of a call: an opening `"`/`'` right before it, the same
/// quote right after it, then optional horizontal whitespace and `)`.
fn is_closed_string_argument(bytes: &[u8], start: usize, end: usize) -> bool {
    let Some(&quote) = start.checked_sub(1).and_then(|at| bytes.get(at)) else {
        return false;
    };
    if !matches!(quote, b'"' | b'\'') || bytes.get(end) != Some(&quote) {
        return false;
    }
    let after = end + 1 + ascii_space_len(&bytes[end + 1..]);
    bytes.get(after) == Some(&b')')
}

fn ascii_space_len(bytes: &[u8]) -> usize {
    bytes
        .iter()
        .take_while(|&&byte| matches!(byte, b' ' | b'\t'))
        .count()
}

/// The `(` of the innermost call still open at `end`, skipping balanced
/// `(...)` groups (`context.Background()`), within [`CALL_WINDOW`] bytes.
fn enclosing_call_open(bytes: &[u8], end: usize) -> Option<usize> {
    let floor = end.saturating_sub(CALL_WINDOW);
    let mut depth = 0usize;
    let mut cursor = end;
    while cursor > floor {
        cursor -= 1;
        match bytes[cursor] {
            b')' => depth += 1,
            b'(' if depth == 0 => return Some(cursor),
            b'(' => depth -= 1,
            _ => {}
        }
    }
    None
}

/// The callee expression before the `(` at `open`, with the contents of any
/// call group removed: identifier bytes and `.`, plus the balanced `(...)`
/// groups of a method chain (`Cohere.builder().token` reads
/// `Cohere.builder().token`, `load("x").token` reads `load().token`), within
/// [`CALL_WINDOW`] bytes. The flag is `true` when the chain crosses at least
/// one call group. Group contents are dropped so a provider name inside an
/// argument never counts as the callee.
fn callee_chain(line: &str, open: usize) -> (String, bool) {
    let bytes = line.as_bytes();
    let floor = open.saturating_sub(CALL_WINDOW);
    let mut start = open;
    let mut pieces: Vec<&str> = Vec::new();
    let mut piece_end = open;
    let mut crossed_call = false;
    while start > floor {
        let byte = bytes[start - 1];
        if byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.') {
            start -= 1;
        } else if byte == b')' {
            // Only a group that follows a chain segment continues the chain.
            let Some(group_open) = enclosing_call_open(bytes, start - 1) else {
                break;
            };
            if group_open == 0 || !is_chain_byte(bytes[group_open - 1]) {
                break;
            }
            pieces.push(&line[start..piece_end]);
            pieces.push("()");
            start = group_open;
            piece_end = group_open;
            crossed_call = true;
        } else {
            break;
        }
    }
    pieces.push(&line[start..piece_end]);
    pieces.reverse();
    (pieces.concat(), crossed_call)
}

fn is_chain_byte(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || byte == b'_'
}

/// `true` when `line` names a host under `domain` (lowercase): a
/// case-insensitive `.<domain>` (`api.deepgram.com`, `api.eu.deepgram.com`)
/// that ends the hostname, so `api.deepgram.com.example.test` and
/// `api.deepgram.company` do not count.
fn names_host_under(line: &str, domain: &str) -> bool {
    let bytes = line.as_bytes();
    any_match_ci(bytes, domain, |at| {
        let end = at + domain.len();
        let after_ends_host = match bytes.get(end) {
            None => true,
            Some(b'.') => !bytes.get(end + 1).is_some_and(u8::is_ascii_alphanumeric),
            Some(&byte) => !(byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')),
        };
        at > 0 && bytes[at - 1] == b'.' && after_ends_host
    })
}

/// `true` when `line` names a `LiteLLM`-style provider route: a keyword
/// that does not continue a wider identifier on its left, then `/` and an
/// alphanumeric model-name byte (`cohere/command-r-plus`,
/// `mistral/mistral-large-latest`). Issue #1018.
fn names_model_route(line: &str, spec: &Spec) -> bool {
    let bytes = line.as_bytes();
    spec.keywords.iter().any(|keyword| {
        any_match_ci(bytes, keyword, |at| {
            let end = at + keyword.len();
            (at == 0 || !is_boundary_byte(bytes[at - 1]))
                && bytes.get(end) == Some(&b'/')
                && bytes.get(end + 1).is_some_and(u8::is_ascii_alphanumeric)
        })
    })
}

/// `true` when the value at `start` is the key half of the WebSocket token
/// subprotocol pair (issue #1017): the header form
/// `Sec-WebSocket-Protocol: token, <value>` or the browser API's
/// `["token", "<value>"]` protocols array. Browsers cannot set an
/// `Authorization` header on a WebSocket, so Deepgram's streaming API takes
/// the key there.
fn is_token_subprotocol(bytes: &[u8], start: usize) -> bool {
    let window = &bytes[start.saturating_sub(HEADER_WINDOW)..start];
    let Ok(window) = std::str::from_utf8(window) else {
        return false;
    };
    let before = window.as_bytes();
    let spaces: &[u8] = b" \t";
    let trim = |bytes: &'_ [u8]| -> usize {
        bytes
            .iter()
            .rposition(|byte| !spaces.contains(byte))
            .map_or(0, |last| last + 1)
    };
    let strip = |bytes: &'_ [u8], suffix: &str| -> Option<usize> {
        let suffix = suffix.as_bytes();
        let start = bytes.len().checked_sub(suffix.len())?;
        bytes[start..].eq_ignore_ascii_case(suffix).then_some(start)
    };
    // `["token", "<value>"]`: the value's opening quote, `,`, the quoted
    // `token`, and the `[` that opens the array.
    if matches!(before.last(), Some(b'"' | b'\'')) {
        let head = &before[..before.len() - 1];
        let head = &head[..trim(head)];
        if head.last() == Some(&b',') {
            let head = &head[..head.len() - 1];
            let head = &head[..trim(head)];
            return ["\"token\"", "'token'"].iter().any(|quoted| {
                strip(head, quoted).is_some_and(|open| {
                    let open = &head[..open];
                    open[..trim(open)].ends_with(b"[")
                })
            });
        }
    }
    // `Sec-WebSocket-Protocol: token, <value>`.
    let head = &before[..trim(before)];
    if head.last() != Some(&b',') {
        return false;
    }
    let head = &head[..head.len() - 1];
    let head = &head[..trim(head)];
    let Some(at) = strip(head, "token") else {
        return false;
    };
    let head = &head[..at];
    let head = &head[..trim(head)];
    if head.last() != Some(&b':') {
        return false;
    }
    let head = &head[..head.len() - 1];
    let Some(at) = strip(head, "sec-websocket-protocol") else {
        return false;
    };
    !head[..at]
        .last()
        .is_some_and(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
}

/// `true` when `line` holds a `provider` field whose value is one of the
/// spec's keywords, in JSON, YAML flow or assignment form:
/// `"provider":"deepgram"`, `provider: deepgram`, `provider='cohere'`
/// (issue #1017). The field name must not continue a wider identifier on
/// either side, and the keyword must be the whole value.
fn names_provider_field(line: &str, keywords: &[&str]) -> bool {
    let bytes = line.as_bytes();
    let is_ident = |byte: u8| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-');
    any_match_ci(bytes, "provider", |at| {
        if at > 0 && is_ident(bytes[at - 1]) {
            return false;
        }
        let mut cursor = at + "provider".len();
        cursor += ascii_run(bytes, cursor, |byte| matches!(byte, b'"' | b'\'' | b'\\'));
        cursor += ascii_run(bytes, cursor, |byte| matches!(byte, b' ' | b'\t'));
        if !matches!(bytes.get(cursor), Some(b':' | b'=')) {
            return false;
        }
        cursor += 1;
        cursor += ascii_run(bytes, cursor, |byte| {
            matches!(byte, b' ' | b'\t' | b'"' | b'\'' | b'\\')
        });
        keywords.iter().any(|keyword| {
            text::starts_with_ci(line, cursor, keyword)
                && !bytes
                    .get(cursor + keyword.len())
                    .is_some_and(|&byte| is_ident(byte))
        })
    })
}

/// `true` when `visit` accepts the start of any case-insensitive occurrence
/// of the lowercase ASCII, non-empty `needle` in `bytes`. Occurrences are the
/// non-overlapping, left-to-right ones, the ones `str::match_indices` yields
/// over an ASCII-lowercased copy, without building that copy.
fn any_match_ci(bytes: &[u8], needle: &str, mut visit: impl FnMut(usize) -> bool) -> bool {
    debug_assert!(!needle.is_empty());
    let mut from = 0;
    while let Some(at) = text::find_ci(bytes, from, needle.as_bytes()) {
        if visit(at) {
            return true;
        }
        from = at + needle.len();
    }
    false
}

fn ascii_run(bytes: &[u8], start: usize, pred: fn(u8) -> bool) -> usize {
    bytes.get(start..).map_or(0, |rest| {
        rest.iter().take_while(|&&byte| pred(byte)).count()
    })
}

/// `true` when the YAML mapping key line at `line` (a `key:` at `column`,
/// not opening a sequence item) has a sibling `provider: <keyword>` key
/// above it in the same mapping: within [`MAX_SIBLING_LINES`] lines, every
/// line between being another key of the same mapping at the same column
/// (issue #1017). A line at another column, a new sequence item, a blank or
/// any other line ends the mapping. A sequence item that opens with the
/// `provider:` key itself (`- provider: deepgram`) counts.
fn yaml_sibling_names_provider(
    input: &str,
    line_start: usize,
    column: usize,
    keywords: &[&str],
) -> bool {
    let mut start = line_start;
    for _ in 0..MAX_SIBLING_LINES {
        let Some((above_start, above_end)) = text::previous_line(input, start) else {
            return false;
        };
        match sibling_line(&input[above_start..above_end], column, keywords) {
            SiblingLine::Provider => return true,
            SiblingLine::Sibling => start = above_start,
            SiblingLine::End => return false,
        }
    }
    false
}

/// How one line above a credential key reads for
/// [`yaml_sibling_names_provider`].
enum SiblingLine {
    /// `provider: <keyword>` at the key's column.
    Provider,
    /// Another key of the same mapping.
    Sibling,
    /// Not part of the mapping.
    End,
}

fn sibling_line(line: &str, column: usize, keywords: &[&str]) -> SiblingLine {
    let Some(parsed) = text::item_key_line(line) else {
        return SiblingLine::End;
    };
    if parsed.column != column {
        return SiblingLine::End;
    }
    if parsed.key == "provider"
        && text::item_name_scalar(line, parsed.rest).is_some_and(|value| {
            keywords
                .iter()
                .any(|keyword| value.eq_ignore_ascii_case(keyword))
        })
    {
        return SiblingLine::Provider;
    }
    if parsed.item_start {
        SiblingLine::End
    } else {
        SiblingLine::Sibling
    }
}

/// Internal retention hint for [`yaml_sibling_names_provider`] (issue
/// #1017): `true` while the last complete lines of `input` are a
/// `provider: <keyword>` key followed only by keys of the same mapping, at
/// most [`MAX_SIBLING_LINES`] lines in all, so a credential key on the next
/// line can still read it. Every provider keyword is accepted.
#[cfg(test)]
pub(crate) fn has_open_provider_sibling(input: &str) -> bool {
    has_open_provider_sibling_in(&super::lookback_tail(input))
}

/// [`has_open_provider_sibling`] over a [`super::lookback_tail`].
pub(crate) fn has_open_provider_sibling_in(tail: &[&str]) -> bool {
    let tail = text::tail_lines(tail, MAX_SIBLING_LINES);
    let Some(column) = tail
        .last()
        .and_then(|line| text::item_key_line(line))
        .map(|parsed| parsed.column)
    else {
        return false;
    };
    for line in tail.iter().rev() {
        match sibling_line(line, column, ALL_KEYWORDS) {
            SiblingLine::Provider => return true,
            SiblingLine::Sibling => {}
            SiblingLine::End => return false,
        }
    }
    false
}

/// How one line of an HTTP request reads for [`http_block_names_host`].
enum HttpLine {
    /// The request line; whether its target names a host under the domain.
    Request(bool),
    /// A header line; whether it is a `Host:` header naming such a host.
    Header(bool),
    /// Anything else ends the request.
    Other,
}

/// `METHOD <target> HTTP/<version>`, the target returned.
fn request_line_target(line: &str) -> Option<&str> {
    let (method, rest) = line.split_once(' ')?;
    if method.is_empty() || !method.bytes().all(|byte| byte.is_ascii_uppercase()) {
        return None;
    }
    let (target, version) = rest.split_once(' ')?;
    (!target.is_empty() && version.starts_with("HTTP/")).then_some(target)
}

/// A request line or header indented by spaces or tabs, as in an indented
/// Markdown code block, a YAML block scalar or a nested log dump, reads as
/// the same line unindented (issue #1046).
fn strip_indent(line: &str) -> &str {
    line.trim_start_matches([' ', '\t'])
}

/// `^[ \t]*[A-Za-z0-9-]+:` the name of an HTTP header line.
fn http_header_name(line: &str) -> Option<&str> {
    let line = strip_indent(line);
    let name_len = line
        .bytes()
        .take_while(|&byte| byte.is_ascii_alphanumeric() || byte == b'-')
        .count();
    (name_len > 0 && line.as_bytes().get(name_len) == Some(&b':')).then(|| &line[..name_len])
}

fn http_line(line: &str, domain: &str) -> HttpLine {
    let line = strip_indent(line.strip_suffix('\r').unwrap_or(line));
    if let Some(target) = request_line_target(line) {
        return HttpLine::Request(names_host_under(target, domain));
    }
    match http_header_name(line) {
        Some(name) => {
            HttpLine::Header(name.eq_ignore_ascii_case("host") && names_host_under(line, domain))
        }
        None => HttpLine::Other,
    }
}

/// `true` when the header line starting at `line_start` belongs to an HTTP
/// request whose request line or `Host:` header names a host under
/// `domain`: walking up at most [`MAX_HTTP_BLOCK_LINES`] lines over header
/// lines only, to the request line (issue #1017). Any other line ends the
/// request. This is the multi-line form of the #936 same-line host rule
/// (`POST /v1/listen HTTP/1.1` / `Host: api.deepgram.com` /
/// `Authorization: Token <key>`).
fn http_block_names_host(input: &str, line_start: usize, domain: &str) -> bool {
    let mut start = line_start;
    for _ in 0..MAX_HTTP_BLOCK_LINES {
        let Some((above_start, above_end)) = text::previous_line(input, start) else {
            return false;
        };
        match http_line(&input[above_start..above_end], domain) {
            HttpLine::Request(names_host) => return names_host,
            HttpLine::Header(true) => return true,
            HttpLine::Header(false) => start = above_start,
            HttpLine::Other => return false,
        }
    }
    false
}

/// Internal retention hint for [`http_block_names_host`] over the Deepgram
/// API domain (issue #1017): `true` while the last complete lines of
/// `input` are an HTTP request line or headers, at most
/// [`MAX_HTTP_BLOCK_LINES`] of them, among which the request line or a
/// `Host:` header names a host under `deepgram.com`, so a header on the next
/// line can still read it.
#[cfg(test)]
pub(crate) fn has_open_deepgram_request(input: &str) -> bool {
    has_open_deepgram_request_in(&super::lookback_tail(input))
}

/// [`has_open_deepgram_request`] over a [`super::lookback_tail`].
pub(crate) fn has_open_deepgram_request_in(tail: &[&str]) -> bool {
    for line in text::tail_lines(tail, MAX_HTTP_BLOCK_LINES).iter().rev() {
        match http_line(line, DEEPGRAM_API_DOMAIN) {
            HttpLine::Request(names_host) => return names_host,
            HttpLine::Header(true) => return true,
            HttpLine::Header(false) => {}
            HttpLine::Other => return false,
        }
    }
    false
}

fn contains_keyword_ci(window: &str, spec: &Spec) -> Option<usize> {
    let lowered = window.to_ascii_lowercase();
    spec.keywords
        .iter()
        .filter_map(|keyword| lowered.rfind(keyword).map(|at| at + keyword.len()))
        .max()
}

/// Classifies the context immediately before the value at `start`.
fn context(
    line: &str,
    spec: &Spec,
    start: usize,
    end: usize,
    line_context: &LineContext<'_>,
) -> Option<(Confidence, &'static str)> {
    let header_context = line_context.header;
    let bytes = line.as_bytes();
    // Issue #1038: `os.environ["NAME"] = "<v>"` and its sibling keyed stores
    // are the assignment `NAME = "<v>"`.
    let key = text::assignment_key(bytes, start)
        .and_then(|key| std::str::from_utf8(key).ok())
        .or_else(|| text::keyed_store_name(line, start));
    if let Some(key) = key {
        let key_start = key.as_ptr() as usize - bytes.as_ptr() as usize;
        // Issue #1016: a Kubernetes-style `env` entry's `value:` is assigned
        // to the name of its sibling `name:` key.
        let key = match line_context.paired_name {
            Some(paired) if key == "value" => paired,
            _ => key,
        };
        let normalized = normalize_name(key);
        // Issue #1017: a sibling `provider: <keyword>` field names the
        // record's provider, so its credential field is the key; `auth` is
        // one (`{"provider":"deepgram","auth":"..."}`).
        if line_context.provider_sibling
            && (is_credential_name(&normalized) || normalized == "auth")
            && !masking_lead_hides_value(&normalized, &line[start..end])
        {
            return Some((Confidence::High, spec.sibling_signal));
        }
        if !is_credential_name(&normalized) {
            return None;
        }
        if name_has_provider(spec, &normalized) {
            return Some((Confidence::High, spec.named_signal));
        }
        if inside_provider_call(line, spec, key_start, line_context.keyword_on_line) {
            return Some((Confidence::High, spec.constructor_signal));
        }
        if line_context.model_route && !masking_lead_hides_value(&normalized, &line[start..end]) {
            return Some((Confidence::High, spec.route_signal));
        }
        let window =
            String::from_utf8_lossy(&bytes[key_start.saturating_sub(KEYWORD_WINDOW)..key_start])
                .into_owned();
        let keyword_end = contains_keyword_ci(&window, spec)?;
        let gap = window.get(keyword_end..)?;
        if gap
            .bytes()
            .all(|byte| !matches!(byte, b';' | b',' | b'=' | b')' | b'(' | b'{'))
        {
            return Some((Confidence::Medium, spec.adjacent_signal));
        }
        return None;
    }

    // No assignment key: a sole positional constructor argument, or an
    // `Authorization: Token` header.
    let mut cursor = start;
    while cursor > 0 && matches!(bytes[cursor - 1], b' ' | b'\t' | b'"' | b'\'') {
        cursor -= 1;
    }
    if cursor > 0
        && bytes[cursor - 1] == b'('
        && inside_provider_call(line, spec, cursor, line_context.keyword_on_line)
    {
        return Some((Confidence::High, spec.constructor_signal));
    }
    if is_closed_string_argument(bytes, start, end) {
        // A builder method named for the credential on a provider chain:
        // `Cohere.builder().token("...")` (issue #932).
        if cursor > 0 && bytes[cursor - 1] == b'(' {
            let (chain, crossed_call) = callee_chain(line, cursor - 1);
            if crossed_call
                && contains_keyword_ci(&chain, spec).is_some()
                && chain
                    .rsplit('.')
                    .next()
                    .is_some_and(|method| is_credential_name(&normalize_name(method)))
            {
                return Some((Confidence::High, spec.constructor_signal));
            }
        }
        // The last positional argument of a provider call:
        // `deepgram.NewRESTWithDefaults(ctx, "...")` (issue #932).
        if cursor > 0
            && bytes[cursor - 1] == b','
            && let Some(open) = enclosing_call_open(bytes, cursor - 1)
        {
            let (chain, _) = callee_chain(line, open);
            if contains_keyword_ci(&chain, spec).is_some() {
                return Some((Confidence::High, spec.constructor_signal));
            }
        }
    }
    if spec.token_header {
        token_header_context(bytes, start, cursor, header_context)
    } else {
        None
    }
}

/// The Deepgram token slots: the browser WebSocket token subprotocol
/// (`Sec-WebSocket-Protocol: token, <key>` or `["token", "<key>"]`, issue
/// #1017) and the `Authorization: Token <key>` header, each high on a
/// request to the provider's API host and medium where the provider is only
/// a word on the line. `cursor` is `start` less the quotes and blanks
/// before the value.
fn token_header_context(
    bytes: &[u8],
    start: usize,
    cursor: usize,
    header_context: HeaderContext,
) -> Option<(Confidence, &'static str)> {
    if is_token_subprotocol(bytes, start) {
        match header_context {
            HeaderContext::ProviderHost => {
                return Some((Confidence::High, "deepgram-host-token-subprotocol"));
            }
            HeaderContext::Keyword => {
                return Some((Confidence::Medium, "deepgram-token-subprotocol"));
            }
            HeaderContext::Absent => {}
        }
    }
    if cursor < start {
        let before = String::from_utf8_lossy(&bytes[cursor.saturating_sub(HEADER_WINDOW)..cursor])
            .to_ascii_lowercase();
        let scheme = before.trim_end();
        // `Authorization: Token <key>`, or HTTPie's `Header:value` form
        // with no space after the colon, `'Authorization:Token <key>'`
        // (issue #932).
        if let Some(head) = scheme.strip_suffix("token")
            && head.ends_with([' ', '\t', '"', '\'', ':', '='])
        {
            let head = head.trim_end_matches([' ', '\t', '"', '\'']);
            let header = head
                .strip_suffix(':')
                .or_else(|| head.strip_suffix('='))
                .map(|name| name.trim_end_matches([' ', '\t', '"', '\'']));
            if header.is_some_and(|name| name.ends_with("authorization")) {
                match header_context {
                    // Issue #936: the header on a request to the provider's
                    // own API host is the key's documented slot, as specific
                    // as a provider-named key, so it is redacted.
                    HeaderContext::ProviderHost => {
                        return Some((Confidence::High, "deepgram-host-token-header"));
                    }
                    HeaderContext::Keyword => {
                        return Some((Confidence::Medium, "deepgram-token-header"));
                    }
                    HeaderContext::Absent => {}
                }
            }
        }
    }
    None
}

/// `true` when `haystack` holds `needle` (lowercase ASCII, non-empty) under
/// ASCII case folding.
///
/// Scans for the needle's first byte (either case) with a straight-line
/// linear scan the compiler can auto-vectorize, and verifies the full needle
/// only at each candidate position. The provider keywords and name segments
/// this is called with are short (3-8 bytes) and rare in ordinary text, so
/// candidate positions are infrequent; measured against the four provider
/// keywords and `key` (the shortest `exact_names` segment) on the
/// `scale-logs-small-whole` performance workload, this is 1.3-3x faster than
/// a Boyer-Moore-Horspool shift-table scan (the shorter the needle, the
/// smaller a skip-based scan's average skip, so the branchy, data-dependent
/// table lookup stops paying for itself -- a plain byte scan a vectorizing
/// compiler already knows how to accelerate does not have that floor).
fn contains_ascii_ci(haystack: &[u8], needle: &[u8]) -> bool {
    let len = needle.len();
    if len == 0 {
        return true;
    }
    if haystack.len() < len {
        return false;
    }
    let first_lower = needle[0].to_ascii_lowercase();
    let first_upper = needle[0].to_ascii_uppercase();
    let last_start = haystack.len() - len;
    let mut at = 0;
    while at <= last_start {
        let Some(offset) = haystack[at..=last_start]
            .iter()
            .position(|&byte| byte == first_lower || byte == first_upper)
        else {
            return false;
        };
        let candidate = at + offset;
        if haystack[candidate..candidate + len].eq_ignore_ascii_case(needle) {
            return true;
        }
        at = candidate + 1;
    }
    false
}

/// `true` when `text` can hold a provider context for `spec`: a keyword, or
/// every `_` segment of an exact name (`co_api_key`), under ASCII case
/// folding.
///
/// Every context [`context`] accepts needs one of these on the value's own
/// line: a key whose normalized name contains a keyword or exact name, a call
/// whose callee contains a keyword, a keyword within [`KEYWORD_WINDOW`] bytes
/// before the key, or (Deepgram header) the keyword on the line.
/// [`normalize_name`] only lowercases, maps `.`/`-` to `_` and inserts `_`
/// before an uppercase letter, so a segment contiguous in the normalized name
/// is contiguous, modulo case, in the original. A text without any of them
/// therefore yields no candidate, and the run scan can be skipped.
fn may_have_provider_context(text: &str, spec: &Spec) -> bool {
    let bytes = text.as_bytes();
    spec.keywords
        .iter()
        .any(|keyword| contains_ascii_ci(bytes, keyword.as_bytes()))
        || spec.exact_names.iter().any(|name| {
            name.rsplit('_')
                .all(|segment| contains_ascii_ci(bytes, segment.as_bytes()))
        })
}

/// Bit of each provider word the four specs gate on, in
/// [`provider_word_mask`]: the keywords and the segments of `co_api_key`.
/// `None` for a word outside the set, so a spec that names a new word falls
/// back to its own scans.
fn provider_word_bit(word: &str) -> Option<u8> {
    Some(match word {
        "mistral" => 1,
        "cohere" => 2,
        "ai21" => 4,
        "deepgram" => 8,
        "co" => 16,
        "api" => 32,
        "key" => 64,
        _ => return None,
    })
}

/// Every provider word of [`provider_word_bit`], one bit each.
const PROVIDER_WORDS: [(&[u8], u8); 7] = [
    (b"mistral", 1),
    (b"cohere", 2),
    (b"ai21", 4),
    (b"deepgram", 8),
    (b"co", 16),
    (b"api", 32),
    (b"key", 64),
];

/// Which [`PROVIDER_WORDS`] occur in `bytes` under ASCII case folding, in
/// one pass shared by every spec: a byte that cannot begin any word costs a
/// table lookup, and the pass stops once every word has been seen.
fn provider_word_mask(bytes: &[u8]) -> u8 {
    const FIRST: [u8; 256] = {
        let mut first = [0u8; 256];
        let mut word = 0;
        while word < PROVIDER_WORDS.len() {
            let (text, bit) = PROVIDER_WORDS[word];
            first[text[0] as usize] |= bit;
            first[text[0].to_ascii_uppercase() as usize] |= bit;
            word += 1;
        }
        first
    };
    const ALL: u8 = 127;
    let mut found = 0u8;
    for (at, &byte) in bytes.iter().enumerate() {
        let candidates = FIRST[usize::from(byte)] & !found;
        if candidates == 0 {
            continue;
        }
        for (word, bit) in PROVIDER_WORDS {
            if candidates & bit != 0
                && bytes
                    .get(at..at + word.len())
                    .is_some_and(|window| window.eq_ignore_ascii_case(word))
            {
                found |= bit;
            }
        }
        if found == ALL {
            break;
        }
    }
    found
}

/// [`may_have_provider_context`] for the whole `input` of [`detect_spec`],
/// answered from the provider-word mask built once per scan copy and shared
/// by the four specs (issue #1092); the spec's own scans when `input` is not
/// the active scan copy or the spec names a word the mask does not hold.
fn may_have_provider_context_whole(input: &str, spec: &Spec) -> bool {
    let Some(mask) = super::prefilter::provider_word_mask(input, provider_word_mask) else {
        return may_have_provider_context(input, spec);
    };
    let bit = |word: &str| provider_word_bit(word).map(|bit| mask & bit != 0);
    let mut answer = false;
    for keyword in spec.keywords {
        match bit(keyword) {
            Some(found) => answer |= found,
            None => return may_have_provider_context(input, spec),
        }
    }
    for name in spec.exact_names {
        let mut all = true;
        for segment in name.rsplit('_') {
            match bit(segment) {
                Some(found) => all &= found,
                None => return may_have_provider_context(input, spec),
            }
        }
        answer |= all;
    }
    #[cfg(debug_assertions)]
    assert_eq!(answer, may_have_provider_context(input, spec));
    answer
}

fn detect_spec(input: &str, spec: &Spec) -> Vec<Candidate> {
    let mut candidates = Vec::new();
    // Every context this detector accepts needs a keyword or exact name
    // somewhere in the input: on the value's line, or for the bounded
    // multi-line layouts (#1016, #1017) on a line above it. Checking the
    // input once also covers the incremental sanitizer's usual single-line
    // unit, whose one line is then not checked again.
    if !may_have_provider_context_whole(input, spec) {
        return candidates;
    }
    let multi_line = input.contains(['\n', '\r']);
    let provider_word = multi_line && contains_ascii_ci(input.as_bytes(), b"provider");
    for (line_start, line_end) in lines(input) {
        let line = &input[line_start..line_end];
        let on_line = !multi_line || may_have_provider_context(line, spec);
        // The bounded multi-line layouts, gated by their line shape first.
        let key_line = if multi_line {
            text::item_key_line(line)
        } else {
            None
        };
        let pair_line = key_line
            .as_ref()
            .is_some_and(|parsed| parsed.key == "value");
        let sibling_line =
            provider_word && key_line.as_ref().is_some_and(|parsed| !parsed.item_start);
        let header_line =
            multi_line && spec.api_host_domain.is_some() && http_header_name(line).is_some();
        if !on_line && !pair_line && !sibling_line && !header_line {
            continue;
        }
        let runs = scan_runs(line, spec);
        if runs.is_empty() {
            continue;
        }
        let paired_name = if pair_line {
            text::list_item_paired_name(input, (line_start, line_end))
        } else {
            None
        };
        let provider_sibling = names_provider_field(line, spec.keywords)
            || (sibling_line
                && key_line.as_ref().is_some_and(|parsed| {
                    yaml_sibling_names_provider(input, line_start, parsed.column, spec.keywords)
                }));
        let block_host = header_line
            && spec
                .api_host_domain
                .is_some_and(|domain| http_block_names_host(input, line_start, domain));
        if !on_line
            && !block_host
            && !provider_sibling
            && !paired_name.is_some_and(|name| may_have_provider_context(name, spec))
        {
            continue;
        }
        let keyword_on_line = on_line && contains_keyword_ci(line, spec).is_some();
        let header = if !spec.token_header {
            HeaderContext::Absent
        } else if block_host
            || (keyword_on_line
                && spec
                    .api_host_domain
                    .is_some_and(|domain| names_host_under(line, domain)))
        {
            HeaderContext::ProviderHost
        } else if keyword_on_line {
            HeaderContext::Keyword
        } else {
            HeaderContext::Absent
        };
        let line_context = LineContext {
            header,
            keyword_on_line,
            model_route: on_line && names_model_route(line, spec),
            provider_sibling,
            paired_name,
        };
        for (start, end) in runs {
            if text::is_repeated_character_filler(&line[start..end])
                || text::is_labelled_digest(line, start)
            {
                continue;
            }
            let Some((confidence, signal)) = context(line, spec, start, end, &line_context) else {
                continue;
            };
            let Some(range) = ByteRange::new(line_start + start, line_start + end) else {
                continue;
            };
            candidates.push(
                Candidate::built_in(spec.type_name, confidence, range)
                    .with_specificity(Specificity::Provider)
                    .with_signals([signal]),
            );
        }
    }
    candidates
}

macro_rules! keyword_gated_detector {
    ($struct_name:ident, $id:literal, $spec:expr) => {
        pub(super) struct $struct_name;

        impl Detector for $struct_name {
            fn id(&self) -> &'static str {
                $id
            }

            fn detect(
                &self,
                input: &str,
                _context: &DetectorContext,
            ) -> Result<Vec<Candidate>, DetectorFailure> {
                Ok(detect_spec(input, &$spec))
            }
        }
    };
}

keyword_gated_detector!(MistralApiKeyDetector, "mistral-api-key", MISTRAL);
keyword_gated_detector!(CohereApiKeyDetector, "cohere-api-key", COHERE);
keyword_gated_detector!(Ai21ApiKeyDetector, "ai21-api-key", AI21);
keyword_gated_detector!(DeepgramApiKeyDetector, "deepgram-api-key", DEEPGRAM);

#[cfg(test)]
mod tests {
    use super::*;

    /// Synthetic bodies built at test time; none is or derives from a real key.
    fn body(len: usize, seed: &str) -> String {
        seed.chars().cycle().take(len).collect()
    }

    fn alnum32() -> String {
        body(32, "aB3dE5gH7jK9mN1pQ3sT5vW7yZ9xC2")
    }

    fn alnum40() -> String {
        body(40, "zY9xW7vU5tS3rQ1pO9nM7lK5jI3hG1fE")
    }

    fn lower40() -> String {
        body(40, "q7w3e9r1t5y8u2i4o6p0a")
    }

    fn run(spec: &Spec, input: &str) -> Vec<Candidate> {
        detect_spec(input, spec)
    }

    fn assert_exact(spec: &Spec, input: &str, value: &str, confidence: Confidence) {
        let found = run(spec, input);
        assert_eq!(found.len(), 1, "{input}");
        let range = found[0].range();
        assert_eq!(&input[range.start()..range.end()], value, "{input}");
        assert_eq!(found[0].confidence(), confidence, "{input}");
        assert_eq!(found[0].type_name(), spec.type_name);
    }

    #[test]
    fn fixture_lengths_are_the_inferred_lengths() {
        assert_eq!(alnum32().len(), 32);
        assert_eq!(alnum40().len(), 40);
        assert_eq!(lower40().len(), 40);
    }

    #[test]
    fn named_assignments_are_high_confidence_exact_spans() {
        let m = alnum32();
        let c = alnum40();
        let d = lower40();
        for input in [
            format!("MISTRAL_API_KEY={m}"),
            format!("export MISTRAL_API_KEY=\"{m}\""),
            format!("{{\"mistralApiKey\": \"{m}\"}}"),
            format!("mistral_api_key: {m}"),
        ] {
            assert_exact(&MISTRAL, &input, &m, Confidence::High);
        }
        for input in [
            format!("CO_API_KEY={c}"),
            format!("COHERE_API_KEY='{c}'"),
            format!("cohere.token: {c}"),
        ] {
            assert_exact(&COHERE, &input, &c, Confidence::High);
        }
        assert_exact(&AI21, &format!("AI21_API_KEY={m}"), &m, Confidence::High);
        for input in [
            format!("DEEPGRAM_API_KEY={d}"),
            format!("deepgram_api_key = \"{d}\""),
        ] {
            assert_exact(&DEEPGRAM, &input, &d, Confidence::High);
        }
    }

    #[test]
    fn sdk_constructor_arguments_are_high_confidence() {
        let m = alnum32();
        let c = alnum40();
        let d = lower40();
        assert_exact(
            &MISTRAL,
            &format!("client = Mistral(api_key=\"{m}\")"),
            &m,
            Confidence::High,
        );
        assert_exact(
            &MISTRAL,
            &format!("const c = new Mistral({{ apiKey: \"{m}\" }});"),
            &m,
            Confidence::High,
        );
        assert_exact(
            &COHERE,
            &format!("co = cohere.ClientV2(api_key=\"{c}\")"),
            &c,
            Confidence::High,
        );
        assert_exact(
            &COHERE,
            &format!("co = cohere.Client(\"{c}\")"),
            &c,
            Confidence::High,
        );
        assert_exact(
            &COHERE,
            &format!("new CohereClient({{ token: \"{c}\" }})"),
            &c,
            Confidence::High,
        );
        assert_exact(
            &AI21,
            &format!("AI21Client(api_key='{m}')"),
            &m,
            Confidence::High,
        );
        assert_exact(
            &DEEPGRAM,
            &format!("dg = DeepgramClient(api_key=\"{d}\")"),
            &d,
            Confidence::High,
        );
        assert_exact(
            &DEEPGRAM,
            &format!("dg = DeepgramClient(\"{d}\")"),
            &d,
            Confidence::High,
        );
    }

    #[test]
    fn issue_932_same_line_forms_are_recognized() {
        let c = alnum40();
        let d = lower40();
        // HTTPie `Header:value`, no space after the colon.
        assert_exact(
            &DEEPGRAM,
            &format!(
                "http --verbose POST https://api.deepgram.com/v1/listen 'Authorization:Token {d}' < a.wav"
            ),
            &d,
            Confidence::High,
        );
        // Go: the last positional argument of a call on the provider alias,
        // past a closed `context.Background()` group.
        assert_exact(
            &DEEPGRAM,
            &format!("var client = deepgram.NewRESTWithDefaults(context.Background(), \"{d}\")"),
            &d,
            Confidence::High,
        );
        assert_exact(
            &DEEPGRAM,
            &format!("c := deepgram.New(ctx, `x`, \"{d}\" )"),
            &d,
            Confidence::High,
        );
        // Java: a credential-named builder method on a provider chain.
        assert_exact(
            &COHERE,
            &format!(
                "Cohere cohere = Cohere.builder().token(\"{c}\").clientName(\"search-api\").build();"
            ),
            &c,
            Confidence::High,
        );
        assert_exact(
            &COHERE,
            &format!("var co = CohereClient.builder().apiKey('{c}').build();"),
            &c,
            Confidence::High,
        );
    }

    #[test]
    fn issue_1018_a_model_route_qualifies_an_unmasked_credential_key() {
        let c = alnum40();
        for input in [
            format!(
                "18:22:04 - LiteLLM Proxy:DEBUG: router.py:1841 - cohere/command-r-plus call failed; masked_api_key={c} reason=AuthenticationError"
            ),
            format!("cohere/command-r-plus call failed; api_key={c}"),
            format!("model=cohere/command-r redacted_api_key=\"{c}\""),
        ] {
            assert_exact(&COHERE, &input, &c, Confidence::High);
        }
        let m = alnum32();
        assert_exact(
            &MISTRAL,
            &format!("mistral/mistral-large-latest failed; masked_api_key={m}"),
            &m,
            Confidence::High,
        );
        // A masked display is never a run of the key's shape.
        let masked = format!("{}{}{}", &c[..4], "*".repeat(32), &c[36..]);
        assert!(
            run(
                &COHERE,
                &format!("cohere/command-r masked_api_key={masked}")
            )
            .is_empty()
        );
    }

    #[test]
    fn issue_1017_the_retention_hints_hold_exactly_the_windows_the_detector_reads() {
        for open in [
            "GET wss://api.deepgram.com/v1/listen HTTP/1.1\n",
            "POST /v1/chat HTTP/1.1\nHost: api.deepgram.com\n",
            "POST /v1/chat HTTP/1.1\r\nHost: api.deepgram.com\r\nAccept: */*\r\n",
        ] {
            assert!(has_open_deepgram_request(open), "{open:?}");
        }
        let long_request = format!(
            "GET /v1/listen HTTP/1.1\nHost: api.deepgram.com\n{}",
            "X-Pad: 1\n".repeat(MAX_HTTP_BLOCK_LINES)
        );
        for closed in [
            "",
            "GET wss://api.example.invalid/v1/listen HTTP/1.1\n",
            "POST /v1/chat HTTP/1.1\nHost: api.example.invalid\n",
            "POST /v1/chat HTTP/1.1\nHost: api.deepgram.com\n\n",
            "Host: api.deepgram.com\nsome body text\n",
            long_request.as_str(),
        ] {
            assert!(!has_open_deepgram_request(closed), "{closed:?}");
        }
        for open in [
            "stt:\n  provider: deepgram\n",
            "stt:\n  provider: cohere\n  model: x\n",
            "- provider: mistral\n",
        ] {
            assert!(has_open_provider_sibling(open), "{open:?}");
        }
        let long_mapping = format!(
            "stt:\n  provider: deepgram\n{}",
            "  pad: 1\n".repeat(MAX_SIBLING_LINES)
        );
        for closed in [
            "",
            "stt:\n  provider: whisper\n",
            "stt:\n  provider: deepgram\n\n",
            "stt:\n  provider: deepgram\n    nested: 1\n",
            "- provider: deepgram\n- other: 1\n",
            long_mapping.as_str(),
        ] {
            assert!(!has_open_provider_sibling(closed), "{closed:?}");
        }
    }

    #[test]
    fn issue_1017_forms_are_recognized_and_their_twins_are_not() {
        let d = lower40();
        assert_exact(
            &DEEPGRAM,
            &format!("const deepgram = createClient(\"{d}\");"),
            &d,
            Confidence::High,
        );
        assert_exact(
            &DEEPGRAM,
            &format!(
                "GET /v1/listen HTTP/1.1\nHost: api.deepgram.com\nSec-WebSocket-Protocol: token, {d}"
            ),
            &d,
            Confidence::High,
        );
        assert_exact(
            &DEEPGRAM,
            &format!("{{\"provider\": \"deepgram\", \"api_key\": \"{d}\"}}"),
            &d,
            Confidence::High,
        );
        assert_exact(
            &COHERE,
            &format!("llm:\n  provider: cohere\n  api_key: {}", alnum40()),
            &alnum40(),
            Confidence::High,
        );
        for input in [
            format!("const widget = createClient(\"{d}\");"),
            format!("Sec-WebSocket-Protocol: token, {d}"),
            format!("X-Sec-WebSocket-Protocol-Other: token, {d} deepgram"),
            format!("{{\"provider\":\"deepgram\",\"request_id\":\"{d}\"}}"),
            format!("stt:\n  provider: deepgram\n  project_id: {d}"),
        ] {
            assert!(run(&DEEPGRAM, &input).is_empty(), "{input}");
        }
    }

    #[test]
    fn issue_932_benign_twins_stay_silent() {
        let c = alnum40();
        let d = lower40();
        for input in [
            // Another host, and the Bearer scheme (bearer-token's).
            format!(
                "http POST https://api.example-speech.test/v1/listen 'Authorization:Token {d}'"
            ),
            format!("http POST https://api.deepgram.com/v1/listen 'Authorization:Bearer {d}'"),
            // Not the last argument, a call on another package, an unquoted
            // argument, and a 39-byte value.
            format!("deepgram.NewRESTWithDefaults(ctx, \"{d}\", opts)"),
            format!("speech.NewRESTWithDefaults(context.Background(), \"{d}\")"),
            format!("deepgram.NewRESTWithDefaults(ctx, {d})"),
            format!("deepgram.NewRESTWithDefaults(ctx, \"{}\")", &d[..39]),
            // A non-credential builder method, another provider's builder,
            // and a provider name only inside an argument group.
            format!("Cohere.builder().clientName(\"{d}\").build();"),
            format!("Other.builder().token(\"{d}\").build();"),
            format!("load(\"cohere\").token(\"{d}\")"),
            // Issue #1018: a model route only qualifies a credential-named
            // key, and a hash-led key over a hex digest stays a digest.
            format!("DEBUG: cohere/command-r-plus call failed; request_id={c}"),
            format!("DEBUG: mycohere/command-r call failed; api_key={c}"),
            format!("DEBUG: cohere/ call failed; api_key={c}"),
            format!(
                "DEBUG: cohere/command-r-plus call failed on retry; hashed_api_key={}",
                "0123456789abcdef".repeat(3).get(..40).unwrap_or_default()
            ),
        ] {
            assert!(run(&DEEPGRAM, &input).is_empty(), "{input}");
            assert!(run(&COHERE, &input).is_empty(), "{input}");
        }
    }

    #[test]
    fn a_keyword_adjacent_key_and_a_keyword_only_deepgram_token_header_are_medium() {
        let m = alnum32();
        let d = lower40();
        assert_exact(
            &MISTRAL,
            &format!("# Mistral API key: {m}"),
            &m,
            Confidence::Medium,
        );
        // `deepgram` only as a word, or a host that is not under the
        // Deepgram API domain, keeps the header at medium (issue #936).
        for input in [
            format!("# deepgram smoke test: Authorization: Token {d}"),
            format!("curl -H 'Authorization: Token {d}' https://deepgram.example.test/v1"),
            format!("curl -H 'Authorization: Token {d}' https://api.deepgram.com.example.test/"),
            format!("curl -H 'Authorization: Token {d}' https://api.deepgram.company/v1 deepgram"),
        ] {
            assert_exact(&DEEPGRAM, &input, &d, Confidence::Medium);
        }
    }

    #[test]
    fn a_deepgram_token_header_on_a_request_to_the_deepgram_api_host_is_high() {
        // Issue #936: the header on a request to the provider's own API host
        // is the key's documented slot, so the default policy redacts it.
        let d = lower40();
        for input in [
            format!("curl -H 'Authorization: Token {d}' https://api.deepgram.com/v1/projects"),
            format!("curl -H \"Authorization: Token {d}\" https://API.Deepgram.com/v1/listen"),
            format!("http POST https://api.eu.deepgram.com/v1/listen 'Authorization:Token {d}'"),
            format!(
                "headers = {{\"Authorization\": \"Token {d}\", \"host\": \"api.deepgram.com\"}}"
            ),
        ] {
            assert_exact(&DEEPGRAM, &input, &d, Confidence::High);
        }
        // The host alone is not context for a value outside the header.
        assert!(
            run(
                &DEEPGRAM,
                &format!("GET https://api.deepgram.com/v1/x?id={d}")
            )
            .is_empty()
        );
    }

    #[test]
    fn bare_values_and_unrelated_keys_are_not_findings() {
        let m = alnum32();
        let c = alnum40();
        let d = lower40();
        for input in [
            m.clone(),
            format!("hash {m}"),
            format!("API_KEY={m}"),
            format!("OPENAI_API_KEY={m}"),
            format!("mistral is fine, id {m}"),
            format!("Client(api_key=\"{m}\")"),
            format!("Authorization: Token {m}"),
        ] {
            assert!(run(&MISTRAL, &input).is_empty(), "{input}");
            assert!(run(&AI21, &input).is_empty(), "{input}");
        }
        assert!(run(&COHERE, &c).is_empty());
        assert!(run(&COHERE, &format!("PICO_API_KEY={c}")).is_empty());
        assert!(run(&COHERE, &format!("cohere_api_key value {c}")).is_empty());
        assert!(run(&DEEPGRAM, &format!("Authorization: Token {d}")).is_empty());
        assert!(run(&DEEPGRAM, &format!("Authorization: Bearer {d} deepgram")).is_empty());
    }

    #[test]
    fn id_like_and_non_credential_siblings_are_not_findings() {
        let m = alnum32();
        let c = alnum40();
        let d = lower40();
        for input in [
            format!("MISTRAL_KEY_ID={m}"),
            format!("MISTRAL_MODEL={m}"),
            format!("Mistral(model=\"{m}\")"),
            format!("AI21_ORG_ID={m}"),
            format!("AI21_TEAM_ID={m}"),
        ] {
            assert!(run(&MISTRAL, &input).is_empty(), "{input}");
            assert!(run(&AI21, &input).is_empty(), "{input}");
        }
        assert!(run(&COHERE, &format!("COHERE_ORG_ID={c}")).is_empty());
        assert!(run(&COHERE, &format!("cohere.ClientV2(base_url=\"{c}\")")).is_empty());
        assert!(run(&DEEPGRAM, &format!("DEEPGRAM_PROJECT_ID={d}")).is_empty());
        assert!(run(&DEEPGRAM, &format!("DEEPGRAM_API_KEY_ID={d}")).is_empty());
    }

    #[test]
    fn placeholders_fillers_and_digests_are_not_findings() {
        let m = alnum32();
        for input in [
            "MISTRAL_API_KEY=your_api_key_here".to_owned(),
            "MISTRAL_API_KEY=<your-mistral-key>".to_owned(),
            "MISTRAL_API_KEY=${MISTRAL_API_KEY}".to_owned(),
            format!("MISTRAL_API_KEY={}", "x".repeat(32)),
            format!("MISTRAL_API_KEY={}", "0".repeat(32)),
            format!("MISTRAL_API_KEY=md5:{m}"),
            "Mistral(api_key=os.environ[\"MISTRAL_API_KEY\"])".to_owned(),
        ] {
            assert!(run(&MISTRAL, &input).is_empty(), "{input}");
        }
        assert!(run(&DEEPGRAM, &format!("DEEPGRAM_API_KEY={}", "a".repeat(40))).is_empty());
    }

    #[test]
    fn twins_with_the_wrong_length_or_alphabet_are_not_findings() {
        let m = alnum32();
        let c = alnum40();
        let d = lower40();
        for value in [
            body(31, &m),
            body(33, &m),
            format!("{}_{}", &m[..15], &m[16..]),
            format!("{}-{}", &m[..15], &m[16..]),
            format!("{m}{m}"),
        ] {
            let input = format!("MISTRAL_API_KEY={value}");
            assert!(run(&MISTRAL, &input).is_empty(), "{input}");
        }
        assert!(run(&COHERE, &format!("CO_API_KEY={}", body(39, &c))).is_empty());
        assert!(run(&COHERE, &format!("CO_API_KEY={}", body(41, &c))).is_empty());
        assert!(
            run(
                &DEEPGRAM,
                &format!("DEEPGRAM_API_KEY={}", d.to_ascii_uppercase())
            )
            .is_empty()
        );
        assert!(run(&DEEPGRAM, &format!("DEEPGRAM_API_KEY={}", body(39, &d))).is_empty());
        assert!(run(&AI21, &format!("AI21_API_KEY={}", body(40, &m))).is_empty());
    }

    #[test]
    fn a_value_is_not_reported_for_the_wrong_provider() {
        let m = alnum32();
        assert!(run(&AI21, &format!("MISTRAL_API_KEY={m}")).is_empty());
        assert!(run(&MISTRAL, &format!("AI21_API_KEY={m}")).is_empty());
        assert!(run(&MISTRAL, &format!("Cohere(api_key=\"{m}\")")).is_empty());
    }

    #[test]
    fn context_on_a_different_line_is_not_adjacent() {
        let m = alnum32();
        let input = format!("Mistral(\n    api_key=\"{m}\"\n)");
        assert!(run(&MISTRAL, &input).is_empty());
        let input = format!("MISTRAL_API_KEY=\n{m}");
        assert!(run(&MISTRAL, &input).is_empty());
    }

    #[test]
    fn every_value_on_a_line_is_judged_alone_and_scanning_is_deterministic() {
        let m = alnum32();
        let other = body(32, "Zz9Yy8Xx7Ww6Vv5Uu4Tt3Ss2Rr1Qq0");
        let input = format!("MISTRAL_API_KEY={m} SECOND={other}\r\nMISTRAL_API_KEY={other}");
        let first = run(&MISTRAL, &input);
        assert_eq!(first.len(), 2);
        assert_eq!(first, run(&MISTRAL, &input));
    }

    #[test]
    fn a_unicode_prefix_keeps_byte_offsets_exact() {
        let m = alnum32();
        let input = format!("한글 MISTRAL_API_KEY={m}");
        assert_exact(&MISTRAL, &input, &m, Confidence::High);
    }

    #[test]
    fn a_long_line_of_near_misses_stays_bounded() {
        let input = format!("MISTRAL_API_KEY={}", "a".repeat(200_000));
        assert!(run(&MISTRAL, &input).is_empty());
        let input = "Mistral(".repeat(20_000);
        assert!(run(&MISTRAL, &input).is_empty());
    }
}

/// Differential tests for #1086: each check compares the line in place
/// instead of a lowercased copy of it. The `old_*` functions are the
/// implementations before that change.
#[cfg(test)]
mod case_insensitive_differential_tests {
    use super::*;
    use crate::test_rng::{BOUNDARY_PIECES, XorShift32};

    const SPECS: [&Spec; 4] = [&MISTRAL, &COHERE, &AI21, &DEEPGRAM];

    fn old_names_host_under(line: &str, domain: &str) -> bool {
        let lowered = line.to_ascii_lowercase();
        let bytes = lowered.as_bytes();
        lowered.match_indices(domain).any(|(at, _)| {
            let end = at + domain.len();
            let after_ends_host = match bytes.get(end) {
                None => true,
                Some(b'.') => !bytes.get(end + 1).is_some_and(u8::is_ascii_alphanumeric),
                Some(&byte) => !(byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')),
            };
            at > 0 && bytes[at - 1] == b'.' && after_ends_host
        })
    }

    fn old_names_model_route(line: &str, spec: &Spec) -> bool {
        let lowered = line.to_ascii_lowercase();
        let bytes = lowered.as_bytes();
        spec.keywords.iter().any(|keyword| {
            lowered.match_indices(keyword).any(|(at, _)| {
                let end = at + keyword.len();
                (at == 0 || !is_boundary_byte(bytes[at - 1]))
                    && bytes.get(end) == Some(&b'/')
                    && bytes.get(end + 1).is_some_and(u8::is_ascii_alphanumeric)
            })
        })
    }

    fn old_names_provider_field(line: &str, keywords: &[&str]) -> bool {
        let lowered = line.to_ascii_lowercase();
        let bytes = lowered.as_bytes();
        let is_ident = |byte: u8| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-');
        lowered.match_indices("provider").any(|(at, field)| {
            if at > 0 && is_ident(bytes[at - 1]) {
                return false;
            }
            let mut cursor = at + field.len();
            cursor += ascii_run(bytes, cursor, |byte| matches!(byte, b'"' | b'\'' | b'\\'));
            cursor += ascii_run(bytes, cursor, |byte| matches!(byte, b' ' | b'\t'));
            if !matches!(bytes.get(cursor), Some(b':' | b'=')) {
                return false;
            }
            cursor += 1;
            cursor += ascii_run(bytes, cursor, |byte| {
                matches!(byte, b' ' | b'\t' | b'"' | b'\'' | b'\\')
            });
            keywords.iter().any(|keyword| {
                lowered[cursor..].starts_with(keyword)
                    && !bytes
                        .get(cursor + keyword.len())
                        .is_some_and(|&byte| is_ident(byte))
            })
        })
    }

    fn old_is_token_subprotocol(bytes: &[u8], start: usize) -> bool {
        let window = &bytes[start.saturating_sub(HEADER_WINDOW)..start];
        let Ok(window) = std::str::from_utf8(window) else {
            return false;
        };
        let before = window.to_ascii_lowercase();
        let spaces: &[char] = &[' ', '\t'];
        if let Some(head) = before.strip_suffix(['"', '\''])
            && let Some(head) = head.trim_end_matches(spaces).strip_suffix(',')
        {
            let head = head.trim_end_matches(spaces);
            return ["\"token\"", "'token'"].iter().any(|quoted| {
                head.strip_suffix(quoted)
                    .is_some_and(|open| open.trim_end_matches(spaces).ends_with('['))
            });
        }
        before
            .trim_end_matches(spaces)
            .strip_suffix(',')
            .and_then(|head| head.trim_end_matches(spaces).strip_suffix("token"))
            .and_then(|head| head.trim_end_matches(spaces).strip_suffix(':'))
            .and_then(|head| head.strip_suffix("sec-websocket-protocol"))
            .is_some_and(|lead| {
                !lead
                    .bytes()
                    .last()
                    .is_some_and(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
            })
    }

    /// `inside_provider_call` before #1086.
    fn old_inside_provider_call(
        line: &str,
        spec: &Spec,
        end: usize,
        keyword_on_line: bool,
    ) -> bool {
        let bytes = line.as_bytes();
        let end = end.min(bytes.len());
        let floor = end.saturating_sub(CALL_WINDOW);
        let mut cursor = end;
        while cursor > floor {
            cursor -= 1;
            match bytes[cursor] {
                b')' => return false,
                b'(' => {
                    let mut start = cursor;
                    while start > 0
                        && (bytes[start - 1].is_ascii_alphanumeric()
                            || matches!(bytes[start - 1], b'_' | b'.'))
                    {
                        start -= 1;
                    }
                    let callee = line[start..cursor].to_ascii_lowercase();
                    if spec.keywords.iter().any(|keyword| callee.contains(keyword)) {
                        return true;
                    }
                    if keyword_on_line
                        && callee
                            .rsplit('.')
                            .next()
                            .is_some_and(|name| spec.factory_callees.contains(&name))
                    {
                        return true;
                    }
                }
                _ => {}
            }
        }
        false
    }

    const WORDS: &[&str] = &[
        "deepgram",
        "DeepGram",
        "DEEPGRAM",
        "deepgram.com",
        "API.DEEPGRAM.COM",
        ".deepgram.com",
        "mistral",
        "Mistral",
        "cohere",
        "COHERE",
        "ai21",
        "AI21",
        "provider",
        "Provider",
        "PROVIDER",
        "\"provider\":",
        "provider=",
        "/",
        "model",
        "createClient",
        "createclient",
        "CREATECLIENT",
        "(",
        ")",
        "new ",
        "Sec-WebSocket-Protocol",
        "sec-websocket-protocol",
        "token",
        "TOKEN",
        "\"token\"",
        "'Token'",
        "HOST: ",
        "GET ",
        "https://",
        "\u{212a}",
    ];

    fn lines() -> Vec<String> {
        let mut rng = XorShift32::new(0x1086_0003);
        let mut pieces: Vec<&str> = BOUNDARY_PIECES.to_vec();
        pieces.extend_from_slice(WORDS);
        let mut out = vec![String::new()];
        out.extend(WORDS.iter().map(|word| (*word).to_owned()));
        for _ in 0..5000 {
            out.push(rng.text(&pieces, 9));
        }
        out
    }

    #[test]
    fn host_route_and_provider_field_match_the_lowercasing_implementation() {
        for line in lines() {
            assert_eq!(
                names_host_under(&line, DEEPGRAM_API_DOMAIN),
                old_names_host_under(&line, DEEPGRAM_API_DOMAIN),
                "{line:?}"
            );
            for spec in SPECS {
                assert_eq!(
                    names_model_route(&line, spec),
                    old_names_model_route(&line, spec),
                    "{line:?}"
                );
                assert_eq!(
                    names_provider_field(&line, spec.keywords),
                    old_names_provider_field(&line, spec.keywords),
                    "{line:?}"
                );
            }
        }
    }

    #[test]
    fn token_subprotocol_matches_the_lowercasing_implementation() {
        for line in lines() {
            let bytes = line.as_bytes();
            // Every start offset, including ones inside a multi-byte
            // character, where the window is not valid UTF-8.
            for start in 0..=bytes.len() {
                assert_eq!(
                    is_token_subprotocol(bytes, start),
                    old_is_token_subprotocol(bytes, start),
                    "{line:?} at {start}"
                );
            }
        }
    }

    #[test]
    fn provider_call_matches_the_lowercasing_implementation() {
        for line in lines() {
            let len = line.len();
            for spec in SPECS {
                for end in [0, len / 2, len, len + 3] {
                    for keyword_on_line in [false, true] {
                        assert_eq!(
                            inside_provider_call(&line, spec, end, keyword_on_line),
                            old_inside_provider_call(&line, spec, end, keyword_on_line),
                            "{line:?} end {end}"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn positive_shapes_in_any_case_match_the_lowercasing_implementation() {
        let shapes: [(&str, usize, bool); 8] = [
            ("Sec-WebSocket-Protocol: token, ", 0, true),
            ("SEC-WEBSOCKET-PROTOCOL:\tTOKEN ,\t", 0, true),
            ("x-Sec-WebSocket-Protocol: token, ", 0, false),
            ("[\"token\", \"", 0, true),
            ("[ 'TOKEN' ,  '", 0, true),
            ("\u{e9}[\"Token\", \"", 0, true),
            ("\"token\", \"", 0, false),
            ("Sec-WebSocket-Protocol: token ", 0, false),
        ];
        for (text, _, expected) in shapes {
            let bytes = text.as_bytes();
            let start = bytes.len();
            assert_eq!(old_is_token_subprotocol(bytes, start), expected, "{text:?}");
            assert_eq!(is_token_subprotocol(bytes, start), expected, "{text:?}");
        }
        for (line, expected) in [
            ("API.Deepgram.COM/v1", true),
            ("api.deepgram.com.example.test", false),
            ("Deepgram.com", false),
        ] {
            assert_eq!(old_names_host_under(line, DEEPGRAM_API_DOMAIN), expected);
            assert_eq!(names_host_under(line, DEEPGRAM_API_DOMAIN), expected);
        }
        for (line, keywords, expected) in [
            ("\"Provider\": \"DeepGram\"", DEEPGRAM.keywords, true),
            ("PROVIDER = 'cohere'", COHERE.keywords, true),
            ("provider: deepgramx", DEEPGRAM.keywords, false),
        ] {
            assert_eq!(old_names_provider_field(line, keywords), expected);
            assert_eq!(names_provider_field(line, keywords), expected);
        }
        assert!(names_model_route("COHERE/command-r", &COHERE));
        assert!(old_names_model_route("COHERE/command-r", &COHERE));
    }

    #[test]
    fn the_needles_the_helpers_rely_on_are_lowercase_ascii() {
        for spec in SPECS {
            for needle in spec.keywords.iter().chain(spec.factory_callees) {
                assert!(!needle.is_empty());
                assert!(
                    needle
                        .bytes()
                        .all(|b| !b.is_ascii_uppercase() && b.is_ascii())
                );
            }
        }
        assert!(
            DEEPGRAM_API_DOMAIN
                .bytes()
                .all(|b| b.is_ascii() && !b.is_ascii_uppercase())
        );
    }

    /// The shared provider-word mask and the whole-input gate built on it
    /// agree with each spec's own scans (issue #1092), inside and outside a
    /// scan copy, on random text of provider words in every case spelling,
    /// truncated words, non-ASCII and invisible pieces.
    #[test]
    fn the_shared_provider_word_mask_matches_the_per_spec_gates() {
        use crate::detectors::prefilter::ScanScope;
        let pieces: Vec<&str> = [
            "mistral",
            "MISTRAL",
            "Mistra",
            "cohere",
            "Cohere",
            "COHERE",
            "coher",
            "co",
            "Co",
            "api",
            "API",
            "ap",
            "key",
            "KEY",
            "ke",
            "ai21",
            "AI21",
            "ai2",
            "deepgram",
            "DeepGram",
            "deepgra",
            "co_api_key",
            "CO_API_KEY",
            "coApiKey",
            "co.api.key",
            "co-api-key",
            "\u{212a}ey",
            "\u{200b}",
            "é",
            " ",
            "\n",
            "=",
            "x",
        ]
        .into_iter()
        .chain(BOUNDARY_PIECES.iter().copied())
        .collect();
        let mut rng = XorShift32::new(0x1092);
        for _ in 0..6000 {
            let text = rng.text(&pieces, 8);
            let bytes = text.as_bytes();
            let oracle = PROVIDER_WORDS.iter().fold(0u8, |mask, (word, bit)| {
                if contains_ascii_ci(bytes, word) {
                    mask | bit
                } else {
                    mask
                }
            });
            assert_eq!(provider_word_mask(bytes), oracle, "{text:?}");
            let _scope = ScanScope::enter(&text);
            for spec in SPECS {
                assert_eq!(
                    may_have_provider_context_whole(&text, spec),
                    may_have_provider_context(&text, spec),
                    "{text:?}"
                );
            }
            // A different slice of the same bytes is not the scan copy.
            let other = text.clone();
            for spec in SPECS {
                assert_eq!(
                    may_have_provider_context_whole(&other, spec),
                    may_have_provider_context(&other, spec)
                );
            }
        }
        for spec in SPECS {
            for word in spec
                .keywords
                .iter()
                .copied()
                .chain(spec.exact_names.iter().flat_map(|name| name.rsplit('_')))
            {
                assert!(provider_word_bit(word).is_some(), "{word}");
            }
        }
    }
}