domain-status 0.2.1

Concurrent URL status checker that captures comprehensive metadata in SQLite.
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
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
//! Exposed secret detection in HTML content.
//!
//! Uses the gitleaks default config (see `config/gitleaks.toml`) as the source
//! of rules. Each rule's regex is run over the HTML body; entropy and allowlist
//! filters reduce false positives.
//!
//! Each finding includes:
//! - **`secret_type`**: gitleaks rule id (e.g. `aws-access-token`)
//! - **severity**: critical / high / medium / low (mapped from rule id or default High)
//! - **location**: heuristic for where in the HTML the secret was found
//! - **context**: ~80 chars before + match + ~80 chars after for analyst triage

use std::borrow::Cow;
use std::fmt;

use base64::Engine;

/// Number of context characters to capture before and after a match.
const CONTEXT_CHARS: usize = 80;

/// Maximum total bytes stored in the per-secret `context` column.
///
/// Without a cap, a private-key match (~3-10 KB) plus 160 chars of context
/// produces a row that essentially duplicates the full secret in two columns.
/// Pages with many such matches bloat the `SQLite` WAL file. 1 KB is comfortable
/// for analyst triage (line of code + ~40 chars on each side of a typical
/// secret) while bounded enough to keep row sizes predictable.
const MAX_CONTEXT_BYTES: usize = 1024;

/// Severity levels for exposed secrets.
///
/// Marked `#[non_exhaustive]` so adding new tiers (e.g. `Informational`) is not
/// a breaking change.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SecretSeverity {
    /// Can directly compromise systems or charge money (e.g., AWS secret key, Stripe secret key, private keys).
    Critical,
    /// Significant access but may need pairing or have limits (e.g., AWS access key alone, `OpenAI` key).
    High,
    /// Potentially sensitive but often restricted or scoped (e.g., Google API key, Slack webhook).
    Medium,
    /// Intentionally public or low-impact (e.g., Stripe publishable key, Firebase URL, Mapbox public token).
    Low,
}

impl SecretSeverity {
    pub fn as_str(self) -> &'static str {
        match self {
            SecretSeverity::Critical => "critical",
            SecretSeverity::High => "high",
            SecretSeverity::Medium => "medium",
            SecretSeverity::Low => "low",
        }
    }
}

impl fmt::Display for SecretSeverity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// An exposed secret detected in HTML content.
#[derive(Debug, Clone)]
pub struct ExposedSecret {
    /// Gitleaks rule id (e.g. `aws-access-token`).
    pub secret_type: String,
    /// Full matched value as found on the public page.
    pub matched_value: String,
    /// Surrounding text for context (~80 chars before + match + ~80 chars after).
    pub context: String,
    /// Severity classification (critical / high / medium / low).
    pub severity: SecretSeverity,
    /// Heuristic location hint (`inline_script`, `html_comment`, `url_parameter`, etc.).
    ///
    /// Stored as `Cow<'static, str>` so the heuristic can return `&'static str`
    /// literals without allocating per match. `Cow<'static, str>` derefs to
    /// `&str` and implements `PartialEq<&str>` and `Display`, so most
    /// downstream usages don't notice the difference.
    pub location: Cow<'static, str>,
    /// Decoded JWT claims (populated only for `secret_type` "jwt" or "jwt-base64").
    pub decoded_jwt: Option<crate::parse::jwt::DecodedJwt>,
}

/// Shannon entropy (log2) of the string, over byte frequencies.
/// Used to filter low-entropy matches when a gitleaks rule sets an entropy threshold.
fn shannon_entropy(s: &str) -> f64 {
    if s.is_empty() {
        return 0.0;
    }
    let mut counts = [0u64; 256];
    for b in s.bytes() {
        counts[usize::from(b)] += 1;
    }
    #[allow(clippy::cast_precision_loss)] // secret substrings are short; f64 mantissa sufficient
    let len = s.len() as f64;
    let mut entropy = 0.0;
    for &c in &counts {
        if c > 0 {
            #[allow(clippy::cast_precision_loss)]
            let p = c as f64 / len;
            entropy -= p * p.log2();
        }
    }
    entropy
}

/// Minimum Shannon entropy required for non-hex `generic-api-key` matches.
///
/// Upstream gitleaks uses 3.5; that lets through short JS identifiers and
/// low-variety CMS keys. 4.0 cuts most camelCase / dictionary noise while
/// remaining reachable for mixed base64-ish tokens.
const GENERIC_API_KEY_MIN_ENTROPY: f64 = 4.0;

/// Hex-only tokens have an alphabet of 16 symbols, so Shannon entropy cannot
/// exceed 4.0 and typically lands slightly under it. Use the upstream floor
/// for long hex blobs instead of rejecting every Maps/CMS-style hex id.
const GENERIC_API_KEY_HEX_MIN_ENTROPY: f64 = 3.5;

/// Minimum length for a plausible `generic-api-key` match.
const GENERIC_API_KEY_MIN_LEN: usize = 16;

/// Minimum length for hex-only `generic-api-key` matches (CMS `_key`s are shorter).
const GENERIC_API_KEY_HEX_MIN_LEN: usize = 32;

/// Returns true if `s` looks like a `camelCase` / `PascalCase` JS identifier
/// (has a lowercase→uppercase transition). Used to reject minified-JS noise.
fn looks_like_camel_case_identifier(s: &str) -> bool {
    let bytes = s.as_bytes();
    for window in bytes.windows(2) {
        if window[0].is_ascii_lowercase() && window[1].is_ascii_uppercase() {
            return true;
        }
    }
    false
}

/// Hyphenated 8-4-4-4-12 hex (UUID-shaped).
///
/// CMS and `MediaWiki` IDs use this layout without a valid RFC 4122 version
/// nibble, so this does not require v1–v8. Vendor rules (e.g. `HubSpot`) still
/// match UUIDs when that is the product format.
fn looks_like_hyphenated_uuid(s: &str) -> bool {
    let b = s.as_bytes();
    if b.len() != 36 {
        return false;
    }
    if b[8] != b'-' || b[13] != b'-' || b[18] != b'-' || b[23] != b'-' {
        return false;
    }
    b.iter()
        .enumerate()
        .all(|(i, c)| matches!(i, 8 | 13 | 18 | 23) || c.is_ascii_hexdigit())
}

/// Web-specific plausibility filter for the catch-all `generic-api-key` rule.
///
/// Upstream's regex captures `[\w.=-]{10,150}`, which matches JS expressions
/// (`iframe.tabIndex=-1`), property names (`deprecatedApiDoNotUse`), and CMS
/// document keys. This filter keeps only secret-shaped opaque tokens.
fn generic_api_key_is_plausible(value: &str) -> bool {
    if value.len() < GENERIC_API_KEY_MIN_LEN {
        return false;
    }
    // JSON `"key":"<uuid>"` (MediaWiki, React, CMS document ids) is an
    // identifier, not a catch-all API key. Vendor UUID rules are unchanged.
    if looks_like_hyphenated_uuid(value) {
        return false;
    }
    // Assignment / member-expression noise from minified JS.
    if value.contains('.') || value.contains('=') {
        return false;
    }
    if looks_like_camel_case_identifier(value) {
        return false;
    }
    // Opaque tokens are hex/base64-ish; reject anything outside that charset.
    if !value
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'+' || b == b'/')
    {
        return false;
    }
    // Pure alphabetic strings are almost always dictionary / i18n keys.
    if value.bytes().all(|b| b.is_ascii_alphabetic()) {
        return false;
    }

    let hex_digits = value.bytes().filter(|b| b.is_ascii_hexdigit()).count();
    let predominantly_hex = hex_digits * 5 >= value.len() * 4; // >= 80% hex
    if predominantly_hex {
        if value.len() < GENERIC_API_KEY_HEX_MIN_LEN {
            return false;
        }
        return shannon_entropy(value) >= GENERIC_API_KEY_HEX_MIN_ENTROPY;
    }

    shannon_entropy(value) >= GENERIC_API_KEY_MIN_ENTROPY
}

/// Post-match filters for rules whose upstream patterns are too broad on HTML/JS.
///
/// Returns `true` when the finding should be **kept**.
fn web_rule_match_is_plausible(rule_id: &str, matched_value: &str) -> bool {
    match rule_id {
        "generic-api-key" => generic_api_key_is_plausible(matched_value),
        // Upstream also matches bare 40-hex when the keyword "sourcegraph" appears
        // anywhere nearby; require the real `sgp_` token prefix.
        "sourcegraph-access-token" => matched_value.starts_with("sgp_"),
        // Legacy `s.` vault tokens are 24 random base62 chars. CamelCase identifiers
        // like `s.typographyH300FontWeight` (CSS tokens in minified bundles) must go.
        "vault-service-token" => {
            if let Some(rest) = matched_value.strip_prefix("s.") {
                !looks_like_camel_case_identifier(rest)
            } else {
                true
            }
        }
        // LinkedIn client id/secret rules match short alnum near "linkedin".
        // JS property names (thumbnailWidth) start lowercase and camelCase;
        // random opaque secrets typically do not.
        "linkedin-client-id" | "linkedin-client-secret" => {
            let starts_lower = matched_value
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_lowercase());
            !(starts_lower && looks_like_camel_case_identifier(matched_value))
        }
        "private-key" => private_key_body_is_plausible(matched_value),
        "http-basic-auth" => http_basic_auth_is_plausible(matched_value),
        _ => true,
    }
}

/// Context-aware plausibility filter, run once the surrounding text (context window
/// or containing line) is available for the match.
///
/// Some rules can't be disambiguated from `matched_value` alone because the tell is
/// in a variable/property name that sits *before* the captured value, outside the
/// rule's capture group. `datadog-access-token`'s regex still matches bare
/// `apiKey`/`appKey` assignments of 32-40 hex (many third-party SDKs use that shape). Keep
/// the finding only when nearby text identifies Datadog — not by denylisting every
/// other product (Bugsnag, Amplitude, Cookie Control, Algolia, …).
fn web_rule_match_is_plausible_in_context(
    rule_id: &str,
    matched_value: &str,
    nearby_text: &str,
    full_match: &str,
    line_content: &str,
) -> bool {
    match rule_id {
        "datadog-access-token" => nearby_text_looks_like_datadog(nearby_text),
        "credential-bearing-url" => {
            credential_bearing_url_is_plausible(matched_value, full_match, line_content)
        }
        _ => true,
    }
}

/// Datadog identity markers that must appear near a candidate `apiKey`/`appKey` hex.
fn nearby_text_looks_like_datadog(nearby_text: &str) -> bool {
    let lower = nearby_text.to_ascii_lowercase();
    const MARKERS: &[&str] = &[
        "datadog",
        "dd_api",
        "dd_app",
        "ddapikey",
        "ddappkey",
        "dd_rum",
        "dd_logs",
        "dd_client",
        "dd_site",
    ];
    MARKERS.iter().any(|m| lower.contains(m))
}

/// Distinctive token prefixes that make userinfo a credential even without a colon,
/// and that keep a mailbox-shaped `user:pass@host` finding.
const DISTINCTIVE_USERINFO_PREFIXES: &[&str] = &["ghp_", "glpat-", "sk_", "xox", "AKIA"];

fn captured_has_distinctive_userinfo_prefix(value: &str) -> bool {
    DISTINCTIVE_USERINFO_PREFIXES
        .iter()
        .any(|prefix| value.starts_with(prefix))
}

/// Mailbox / mailto userinfo is not a credential URL unless the captured secret
/// is a distinctive prefixed token (`ghp_…`, `xoxb-…`, …).
fn credential_bearing_url_is_plausible(
    matched_value: &str,
    full_match: &str,
    line_content: &str,
) -> bool {
    if captured_has_distinctive_userinfo_prefix(matched_value) {
        return true;
    }
    if line_content.to_ascii_lowercase().contains("mailto:") {
        return false;
    }
    if userinfo_user_is_mailbox_shaped(full_match) {
        return false;
    }
    // Email-only `https://name@host` (no colon) must not become a finding.
    if !full_match_userinfo_has_colon(full_match) {
        return false;
    }
    true
}

fn full_match_userinfo_has_colon(full_match: &str) -> bool {
    let Some((_, rest)) = full_match.split_once("://") else {
        return false;
    };
    rest.split('@')
        .next()
        .is_some_and(|userinfo| userinfo.contains(':'))
}

/// Percent-encoded mailbox (`local%40domain.tld`) as the userinfo username.
fn userinfo_user_is_mailbox_shaped(full_match: &str) -> bool {
    let Some((_, rest)) = full_match.split_once("://") else {
        return false;
    };
    let Some(userinfo) = rest.split('@').next() else {
        return false;
    };
    let user = userinfo.split(':').next().unwrap_or(userinfo);
    let lower = user.to_ascii_lowercase();
    let Some(at) = lower.find("%40") else {
        return false;
    };
    let local = &lower[..at];
    let domain = &lower[at + 3..];
    !local.is_empty()
        && domain.contains('.')
        && domain
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-')
}

/// Minimum decoded PKCS body (bytes) for `private-key`. Header-only / crumb
/// PEMs are not a usable RSA/EC key.
const PRIVATE_KEY_MIN_DECODED_BODY: usize = 64;

fn private_key_body_is_plausible(pem: &str) -> bool {
    pem_decoded_body_len(pem) >= PRIVATE_KEY_MIN_DECODED_BODY
}

fn pem_decoded_body_len(pem: &str) -> usize {
    let Some(b64) = pem_base64_body(pem) else {
        return 0;
    };
    match base64::engine::general_purpose::STANDARD.decode(b64.as_bytes()) {
        Ok(bytes) => bytes.len(),
        // Long but non-canonical padding: 4 base64 chars ≈ 3 bytes.
        Err(_) if b64.len() >= 86 => b64.len().saturating_mul(3) / 4,
        Err(_) => 0,
    }
}

fn pem_base64_body(pem: &str) -> Option<String> {
    let begin = pem.find("-----BEGIN")?;
    let after_first_dashes = pem.get(begin + 5..)?;
    let header_end_rel = after_first_dashes.find("-----")?;
    let body_start = begin + 5 + header_end_rel + 5;
    let rest = pem.get(body_start..)?;
    let body_end = rest
        .find("-----END")
        .or_else(|| rest.rfind("KEY-----"))
        .unwrap_or(rest.len());
    let raw = rest.get(..body_end)?;
    let b64: String = raw
        .chars()
        .filter(|c| c.is_ascii_alphanumeric() || matches!(*c, '+' | '/' | '='))
        .collect();
    if b64.is_empty() {
        None
    } else {
        Some(b64)
    }
}

/// Textbook `user:pass` is 8 decoded bytes / 12 Base64 chars. Require more.
const HTTP_BASIC_MIN_DECODED_LEN: usize = 10;

fn http_basic_auth_is_plausible(matched_value: &str) -> bool {
    let Some(bytes) = decode_http_basic(matched_value) else {
        return false;
    };
    if bytes.len() < HTTP_BASIC_MIN_DECODED_LEN {
        return false;
    }
    let Ok(decoded) = std::str::from_utf8(&bytes) else {
        return true;
    };
    let Some((user, pass)) = decoded.split_once(':') else {
        return false;
    };
    !http_basic_pair_is_placeholder(user, pass)
}

fn decode_http_basic(value: &str) -> Option<Vec<u8>> {
    let trimmed = value.trim();
    base64::engine::general_purpose::STANDARD
        .decode(trimmed.as_bytes())
        .ok()
        .or_else(|| {
            base64::engine::general_purpose::STANDARD_NO_PAD
                .decode(trimmed.as_bytes())
                .ok()
        })
}

fn http_basic_pair_is_placeholder(user: &str, pass: &str) -> bool {
    const USERS: &[&str] = &["user", "foo", "bar", "beep", "admin"];
    const PASSES: &[&str] = &["pass", "password", "foo", "bar", "beep", "boop"];
    let user = user.to_ascii_lowercase();
    let pass = pass.to_ascii_lowercase();
    USERS.contains(&user.as_str()) && PASSES.contains(&pass.as_str())
}

/// Severity for a gitleaks rule id.
///
/// Three-step classification:
/// 1. Explicit allowlists for rules we've manually triaged (Critical/High/Medium/Low).
/// 2. Heuristic classification for unknown rule IDs based on naming conventions
///    (`-secret*` => High, `-token*`/`-key*`/`-pat*`/`-cred*` => Medium, else Low).
/// 3. Default Low for anything else (e.g. very generic patterns whose impact
///    can't be inferred from the rule ID alone).
///
/// Why default `Low` rather than `High`: gitleaks ships ~250 rules and most are
/// not in our explicit allowlist. The previous "default High" choice meant
/// every unclassified rule produced a High-severity row, which both inflated
/// apparent risk and degraded the signal value of "true" High findings (a
/// real `aws-access-token` looked the same as `generic-api-key` matching a
/// random hex blob). Conservative-by-default makes High mean "we deliberately
/// said this is High."
fn severity_for_rule_id(rule_id: &str) -> SecretSeverity {
    match rule_id {
        // Critical: direct compromise or financial
        "private-key"
        | "database-connection-uri"
        | "jdbc-connection-string"
        | "credential-bearing-url"
        | "slack-bot-token"
        | "slack-user-token"
        | "slack-legacy-token"
        | "slack-legacy-bot-token"
        | "github-pat"
        | "github-fine-grained-pat"
        | "gitlab-pat"
        | "vault-batch-token"
        | "vault-service-token" => SecretSeverity::Critical,
        // High
        "aws-access-token"
        | "http-basic-auth"
        | "mailchimp-api-key"
        | "openai-api-key"
        | "anthropic-api-key"
        | "anthropic-admin-api-key"
        | "sendgrid-api-token"
        | "twilio-api-key"
        | "npm-access-token"
        | "pypi-upload-token"
        | "digitalocean-access-token"
        | "digitalocean-pat"
        | "heroku-api-key"
        | "heroku-api-key-v2"
        | "flyio-access-token"
        | "shopify-access-token"
        | "shopify-private-app-access-token"
        | "shopify-shared-secret"
        | "bitbucket-client-secret"
        | "mailgun-private-api-token"
        | "cloudflare-api-key"
        | "doppler-api-token"
        | "plaid-secret-key"
        | "plaid-api-token"
        | "fastly-api-token" => SecretSeverity::High,
        // Medium
        "azure-ad-client-secret"
        | "slack-webhook-url"
        | "slack-app-token"
        | "algolia-api-key"
        | "datadog-access-token"
        | "grafana-api-key"
        | "grafana-cloud-api-token"
        | "sentry-access-token"
        | "linear-api-key"
        // Generic catch-all rule: matches a wide pattern with low specificity,
        // so we treat it as Medium-by-default to keep High meaningful.
        | "generic-api-key" => SecretSeverity::Medium,
        // Low: intentionally public client identifiers (Maps/Firebase embeds,
        // Mapbox public tokens, Contentful Delivery API tokens). Still recorded
        // for inventory, but not triage-urgent. Algolia search keys are Medium
        // here and demoted to Low in `severity_for_finding` unless the
        // assignment is an admin/write key.
        "gcp-api-key" | "mapbox-api-token" | "contentful-delivery-api-token" => {
            SecretSeverity::Low
        }
        // Low: JWTs on the web are usually CDN/session/buyer tokens, not private
        // API credentials. Keep for inventory; do not treat as triage-urgent.
        "jwt" | "jwt-base64" => SecretSeverity::Low,
        _ => severity_for_unknown_rule_id(rule_id),
    }
}

/// Assignment names that identify an Algolia **admin/write** key.
/// Search keys share the same 32-alnum shape; only the identifier distinguishes them.
fn algolia_assignment_is_admin(nearby_text: &str) -> bool {
    let lower = nearby_text.to_ascii_lowercase();
    const MARKERS: &[&str] = &[
        "admin_key",
        "adminkey",
        "adminapikey",
        "admin_api_key",
        "algolia_admin",
        "algoliaadmin",
    ];
    MARKERS.iter().any(|m| lower.contains(m))
}

/// Severity for a finding, with context-aware demotion for known public-temp shapes.
///
/// AWS access key IDs embedded in `X-Amz-Credential=` pre-signed URL query params
/// are real IDs but temporary/public URL material — record as Low, not High.
/// Algolia search keys shipped next to an App ID are public-by-design; admin
/// assignments stay Medium.
fn severity_for_finding(rule_id: &str, line_content: &str, nearby_text: &str) -> SecretSeverity {
    let severity = severity_for_rule_id(rule_id);
    if rule_id == "aws-access-token"
        && line_content
            .to_ascii_lowercase()
            .contains("x-amz-credential=")
    {
        return SecretSeverity::Low;
    }
    if rule_id == "algolia-api-key" && !algolia_assignment_is_admin(nearby_text) {
        return SecretSeverity::Low;
    }
    severity
}

/// Heuristic classification for gitleaks rule IDs we haven't explicitly mapped.
///
/// The rule-id naming convention in gitleaks is consistent enough to give us a
/// reasonable guess: anything containing `secret`/`password`/`private-key`
/// indicates direct compromise, whereas tokens/keys/credentials are usually
/// scoped or rate-limited. Anything else falls to Low.
fn severity_for_unknown_rule_id(rule_id: &str) -> SecretSeverity {
    let lower = rule_id;
    if lower.contains("private-key")
        || lower.contains("password")
        || lower.contains("client-secret")
        || lower.contains("client_secret")
    {
        SecretSeverity::High
    } else if lower.contains("token")
        || lower.contains("api-key")
        || lower.contains("api_key")
        || lower.contains("access-key")
        || lower.contains("access_key")
        || lower.contains("secret")
        || lower.contains("pat")
        || lower.contains("cred")
    {
        SecretSeverity::Medium
    } else {
        SecretSeverity::Low
    }
}

/// Returns true if the match should be skipped by the global allowlist (regex or stopword).
///
/// Tests only the matched secret value, matching upstream gitleaks semantics for the
/// global allowlist (default `regexTarget` = secret). Testing the surrounding context
/// window would let benign nearby tokens (e.g. `debug:false` next to a real API key)
/// suppress genuine findings for every rule.
fn global_allowlist_skips(
    global: &crate::parse::gitleaks::CompiledGlobalAllowlist,
    matched_value: &str,
) -> bool {
    for re in &global.regexes {
        if re.is_match(matched_value) {
            return true;
        }
    }
    for word in &global.stopwords {
        if matched_value.contains(word) {
            return true;
        }
    }
    false
}

/// Maximum bytes of "line" kept on each side of a match for `regexTarget = "line"`
/// allowlists. Minified HTML/JS often has no newlines at all; without this cap the
/// "line" would be the entire document, and one benign allowlist token anywhere on
/// the page (e.g. a Cloudflare `data-cfemail=` widget) would suppress every real
/// finding of that rule across the whole body.
const MAX_LINE_WINDOW_BYTES: usize = 512;

/// Returns the line containing the byte range [start, end) in body, capped to
/// [`MAX_LINE_WINDOW_BYTES`] on each side of the match. Line = span between \n
/// (or start/end of body), truncated to the window when the physical line is longer.
fn line_containing(body: &str, start: usize, end: usize) -> &str {
    let mut window_start = start.saturating_sub(MAX_LINE_WINDOW_BYTES);
    while !body.is_char_boundary(window_start) {
        window_start += 1;
    }
    let mut window_end = (end + MAX_LINE_WINDOW_BYTES).min(body.len());
    while !body.is_char_boundary(window_end) {
        window_end -= 1;
    }
    let line_start = body[window_start..start]
        .rfind('\n')
        .map_or(window_start, |i| window_start + i + 1);
    let line_end = body[end..window_end]
        .find('\n')
        .map_or(window_end, |i| end + i);
    &body[line_start..line_end]
}

/// Extracts the secret from a regex match.
///
/// Order of preference:
/// 1. If `secretGroup` (1-based) is set and the capture exists, use it. This is
///    the upstream Gitleaks-recommended way to point at the secret precisely.
/// 2. Otherwise, return the **first non-empty capture group**. Most bundled
///    Gitleaks rules wrap the secret in a single capture group with surrounding
///    anchoring text (e.g. `(?i)hubspot.*=\s*"([0-9A-F-]{36})"`). The full
///    match includes the keyword and quotes; group 1 is the clean secret.
/// 3. Fallback: full match.
///
/// Note on Gitleaks parity: Gitleaks v8 (Go) defaults to `matches[0]` (full
/// match) when `secretGroup` is unset. We deliberately differ because the
/// rules shipped in `config/gitleaks.toml` rarely declare `secretGroup` even
/// when the regex has anchoring context, and returning the full match would
/// store `window.API_KEY="<uuid>"` instead of `<uuid>`. The `(rule_id,
/// matched_value)` dedupe and the analyst-facing report both want the clean
/// secret. If a future rule needs the literal full match, it must declare
/// `secretGroup = 0` explicitly (we treat 0 as "unset" today; that's the
/// only edge worth flagging in a future change).
fn extract_secret(
    captures: Option<regex::Captures>,
    full_match: &str,
    secret_group: Option<u32>,
) -> String {
    let Some(caps) = captures else {
        return full_match.to_string();
    };
    if let Some(n) = secret_group {
        if n > 0 {
            if let Some(m) = caps.get(n as usize) {
                return m.as_str().to_string();
            }
        }
    }
    for i in 1..caps.len() {
        if let Some(m) = caps.get(i) {
            if !m.as_str().is_empty() {
                return m.as_str().to_string();
            }
        }
    }
    full_match.to_string()
}

/// Returns true if the match should be skipped by a per-rule allowlist.
/// Respects condition: OR = any criterion skips; AND = all must match (path is N/A for single-blob, so AND with paths never skips).
pub(crate) fn rule_allowlist_skips(
    allowlists: &[crate::parse::gitleaks::CompiledRuleAllowlist],
    matched_value: &str,
    line_content: &str,
    full_match: &str,
) -> bool {
    for list in allowlists {
        let target = match list.regex_target.as_deref() {
            Some("line") => line_content,
            Some("match") => full_match,
            _ => matched_value,
        };
        if list.condition_and {
            // AND: all criteria must match. Path is N/A for single-blob (we never have a file path).
            if list.has_paths {
                continue; // path never matches, so AND never succeeds; do not skip
            }
            let all_regex =
                list.regexes.is_empty() || list.regexes.iter().all(|re| re.is_match(target));
            let all_stop =
                list.stopwords.is_empty() || list.stopwords.iter().all(|w| target.contains(w));
            if all_regex && all_stop {
                return true;
            }
        } else {
            // OR: any match skips
            for re in &list.regexes {
                if re.is_match(target) {
                    return true;
                }
            }
            for word in &list.stopwords {
                if target.contains(word) {
                    return true;
                }
            }
        }
    }
    false
}

/// Extracts surrounding context for a match within the body text.
///
/// The full window is `[match_start - CONTEXT_CHARS, match_end + CONTEXT_CHARS]`,
/// snapped to valid UTF-8 char boundaries. If the result would exceed
/// [`MAX_CONTEXT_BYTES`] (a private-key match alone can be ~3-10 KB), the
/// long match in the middle is replaced with `<head>...<tail>` so the
/// context still reflects the surrounding code without duplicating the full
/// secret value in this column.
fn extract_context(body: &str, start: usize, end: usize) -> String {
    let ctx_start = start.saturating_sub(CONTEXT_CHARS);
    let ctx_end = (end + CONTEXT_CHARS).min(body.len());

    // Snap to valid char boundaries without slicing at potentially invalid offsets.
    // Walk backwards from ctx_start to find the previous char boundary.
    let safe_start = (0..=ctx_start)
        .rev()
        .find(|&i| body.is_char_boundary(i))
        .unwrap_or(0);
    // Walk forwards from ctx_end to find the next char boundary.
    let safe_end = (ctx_end..=body.len())
        .find(|&i| body.is_char_boundary(i))
        .unwrap_or(body.len());

    let raw = &body[safe_start..safe_end];
    if raw.len() <= MAX_CONTEXT_BYTES {
        return raw.to_string();
    }

    // Long: keep the surrounding code by truncating the match in the middle.
    // Allocate the budget as: prefix-context + head-of-match + ELLIPSIS + tail-of-match + suffix-context.
    const ELLIPSIS: &str = "...[truncated]...";
    let prefix = match_safe_slice(body, safe_start, start);
    let suffix = match_safe_slice(body, end, safe_end);
    let prefix_len = prefix.len();
    let suffix_len = suffix.len();

    // Reserve characters for ellipsis + prefix/suffix; remaining budget split between match-head and match-tail.
    let overhead = prefix_len + suffix_len + ELLIPSIS.len();
    if overhead >= MAX_CONTEXT_BYTES {
        // Pathological: even the surrounding context exceeds the cap.
        // Fall back to the raw window truncated to MAX_CONTEXT_BYTES at the
        // nearest char boundary.
        return truncate_at_char_boundary(raw, MAX_CONTEXT_BYTES);
    }
    let match_budget = MAX_CONTEXT_BYTES - overhead;
    let half = match_budget / 2;
    let match_text = &body[start..end];
    let head = truncate_at_char_boundary(match_text, half);
    let tail_start = match_text
        .len()
        .saturating_sub(match_budget - head.len())
        .max(head.len());
    // Snap tail_start to a char boundary going forward.
    let tail_start = (tail_start..=match_text.len())
        .find(|&i| match_text.is_char_boundary(i))
        .unwrap_or(match_text.len());
    let tail = &match_text[tail_start..];

    format!("{prefix}{head}{ELLIPSIS}{tail}{suffix}")
}

/// Slice safely between two byte indices that are already on char boundaries.
fn match_safe_slice(body: &str, start: usize, end: usize) -> &str {
    if start <= end
        && end <= body.len()
        && body.is_char_boundary(start)
        && body.is_char_boundary(end)
    {
        &body[start..end]
    } else {
        ""
    }
}

/// Truncate a `&str` to at most `max_bytes`, snapping back to the nearest
/// preceding char boundary so the returned slice is always valid UTF-8.
fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> String {
    if s.len() <= max_bytes {
        return s.to_string();
    }
    let mut idx = max_bytes;
    while idx > 0 && !s.is_char_boundary(idx) {
        idx -= 1;
    }
    s[..idx].to_string()
}

/// Infers location hint from the surrounding context string.
fn infer_location(context: &str) -> &'static str {
    let ctx = context.to_lowercase();
    if ctx.contains("<script") || ctx.contains("</script") {
        "inline_script"
    } else if ctx.contains("<!--") {
        "html_comment"
    } else if ctx.contains("data-") {
        "data_attribute"
    } else if ctx.contains("?key=")
        || ctx.contains("&key=")
        || ctx.contains("&token=")
        || ctx.contains("?token=")
    {
        "url_parameter"
    } else if ctx.contains("content=\"") || ctx.contains("content='") {
        "meta_tag"
    } else {
        "html_body"
    }
}

/// Returns true when `pos` lies inside a `<script type="application/ld+json">` block.
///
/// Walks backward from `pos` to the nearest preceding `<script` (ASCII tag, so
/// byte indices on a lowercased prefix align) and requires `application/ld+json`
/// in the opening tag with no intervening `</script>`.
fn is_inside_json_ld_script(body: &str, pos: usize) -> bool {
    let before = &body[..pos.min(body.len())];
    let lower_before = before.to_ascii_lowercase();
    let Some(script_start) = lower_before.rfind("<script") else {
        return false;
    };
    let region = &lower_before[script_start..];
    if let Some(close) = region.find("</script") {
        if script_start + close < pos {
            return false;
        }
    }
    let tag_end = region.find('>').unwrap_or(region.len().min(200));
    region[..tag_end].contains("application/ld+json")
}

/// Location for a body match: prefer `json_ld` when inside LD+JSON script.
fn infer_location_for_body_match(body: &str, match_start: usize, context: &str) -> &'static str {
    if is_inside_json_ld_script(body, match_start) {
        return "json_ld";
    }
    infer_location(context)
}

/// Detects exposed secrets in raw HTML body text using gitleaks rules.
///
/// Loads rules from the bundled `config/gitleaks.toml`, runs each regex over the body,
/// applies entropy and allowlist filters, and returns findings with gitleaks rule id
/// as `secret_type` and derived severity.
///
/// The keyword prefilter (Aho-Corasick automaton built once at config-load
/// time) runs once over the body and produces the set of pattern IDs that
/// appear in it. Each rule then checks that set in `O(rule_keywords)` instead
/// of re-scanning the body — making total work `O(body_len + sum(rule_keywords))`
/// rather than `O(body_len * sum(rule_keywords))`.
pub fn detect_exposed_secrets(body: &str) -> Vec<ExposedSecret> {
    detect_exposed_secrets_inner(body, true)
}

/// Detects exposed secrets in serialized HTTP response headers.
///
/// `header_block` is expected to be newline-separated `Name: value` lines
/// (including `Set-Cookie` values). Real secrets routinely appear in
/// `Authorization`, `X-Api-Key`, `X-Amz-Security-Token`, and `Set-Cookie`
/// (session/JWT) headers, which the HTML-body scan never sees. Findings are
/// retagged with `location = "set_cookie"` when on a Set-Cookie line, otherwise
/// `response_header`.
pub fn detect_exposed_secrets_in_headers(header_block: &str) -> Vec<ExposedSecret> {
    let mut found = detect_exposed_secrets_inner(header_block, true);
    for secret in &mut found {
        let ctx_lc = secret.context.to_ascii_lowercase();
        // Prefer the header line around the match (context includes nearby lines).
        if ctx_lc.contains("set-cookie:") {
            secret.location = Cow::Borrowed("set_cookie");
        } else {
            secret.location = Cow::Borrowed("response_header");
        }
    }
    found
}

/// Test-only variant that bypasses the Aho-Corasick keyword prefilter.
///
/// Used by the prefilter-equivalence regression test: the prefilter is meant
/// to be a pure perf shortcut, so for any body its findings must match the
/// findings produced when every rule's regex runs unconditionally. Any
/// divergence is a correctness bug in the prefilter (a missing keyword for
/// some rule, an automaton that doesn't see a substring, etc.).
#[cfg(test)]
pub(crate) fn detect_exposed_secrets_unfiltered(body: &str) -> Vec<ExposedSecret> {
    detect_exposed_secrets_inner(body, false)
}

fn detect_exposed_secrets_inner(body: &str, use_prefilter: bool) -> Vec<ExposedSecret> {
    let config = crate::parse::gitleaks::gitleaks();
    let mut results = Vec::new();
    let mut seen = std::collections::HashSet::new();

    // One-pass keyword scan. Rules without keywords skip this gate entirely
    // and always run their regex. The unfiltered variant ignores this set
    // entirely (use_prefilter == false) so every rule's regex runs.
    let matched_keyword_ids = if use_prefilter {
        config
            .keyword_prefilter
            .as_ref()
            .map(|p| p.matched_pattern_ids(body))
    } else {
        None
    };

    for rule in &config.rules {
        // Rules restricted to specific file paths (e.g. .tf, .hcl) are for repo scanning; skip when scanning a single blob (HTML) with no path.
        if rule.path.is_some() {
            continue;
        }
        // Aho-Corasick prefilter: skip the rule if it has keywords AND none of
        // them were observed in the body. Rules without `keyword_pattern_ids`
        // run unconditionally (matches gitleaks "no keywords -> always run").
        if let (Some(ids), Some(matched)) = (
            rule.keyword_pattern_ids.as_ref(),
            matched_keyword_ids.as_ref(),
        ) {
            if !ids.is_empty()
                && !crate::parse::gitleaks::KeywordPrefilter::any_id_present(ids, matched)
            {
                continue;
            }
        }

        // Use captures_iter directly (avoids redundant find_iter + re-capture per match)
        for cap in rule.regex.captures_iter(body) {
            let Some(mat) = cap.get(0) else { continue };
            let full_match = mat.as_str();
            let matched_value = extract_secret(Some(cap), full_match, rule.secret_group);

            if let Some(entropy_threshold) = rule.entropy {
                if shannon_entropy(&matched_value) < entropy_threshold {
                    continue;
                }
            }

            if global_allowlist_skips(&config.global_allowlist, &matched_value) {
                continue;
            }
            if !web_rule_match_is_plausible(&rule.id, &matched_value) {
                continue;
            }
            let context = extract_context(body, mat.start(), mat.end());
            let line_content = line_containing(body, mat.start(), mat.end());
            if !web_rule_match_is_plausible_in_context(
                &rule.id,
                &matched_value,
                &context,
                full_match,
                line_content,
            ) {
                continue;
            }
            if rule_allowlist_skips(&rule.allowlists, &matched_value, line_content, full_match) {
                continue;
            }

            let key = (rule.id.clone(), matched_value.clone());
            if !seen.insert(key) {
                continue;
            }

            let location: Cow<'static, str> =
                Cow::Borrowed(infer_location_for_body_match(body, mat.start(), &context));
            let severity = severity_for_finding(&rule.id, line_content, &context);
            let decoded_jwt = match rule.id.as_str() {
                "jwt" => crate::parse::jwt::decode_jwt(&matched_value),
                "jwt-base64" => crate::parse::jwt::decode_jwt_base64(&matched_value),
                _ => None,
            };
            results.push(ExposedSecret {
                secret_type: rule.id.clone(),
                matched_value,
                context,
                severity,
                location,
                decoded_jwt,
            });
        }
    }

    results
}

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

    // === Cloud Providers ===

    // AWS key: gitleaks uses [A-Z2-7]{16} (no 0,1,8,9); must not end in EXAMPLE (allowlisted)
    const AWS_KEY: &str = "AKIAIOSFODNN7EXAMPL2";

    #[test]
    fn test_detect_aws_access_key() {
        let body = format!(r#"var key = "{}";"#, AWS_KEY);
        let secrets = detect_exposed_secrets(&body);
        // The body must trigger the dedicated `aws-access-token` rule. It may
        // ALSO trigger the broader `generic-api-key` rule (the latter started
        // catching this same value once we raised the gitleaks regex size
        // limit and the previously-skipped rule began compiling). Assert on
        // the dedicated rule's presence rather than the total count.
        let aws = secrets
            .iter()
            .find(|s| s.secret_type == "aws-access-token")
            .unwrap_or_else(|| panic!("expected an aws-access-token secret in {secrets:?}"));
        assert_eq!(aws.matched_value, AWS_KEY);
        assert_eq!(aws.severity, SecretSeverity::High);
    }

    #[test]
    fn test_aws_example_allowlisted() {
        let body = r#"var key = "AKIAIOSFODNN7EXAMPLE";"#;
        let secrets = detect_exposed_secrets(body);
        let aws = secrets.iter().find(|s| s.secret_type == "aws-access-token");
        assert!(
            aws.is_none(),
            "EXAMPLE key should be allowlisted; got {:?}",
            secrets
        );
    }

    #[test]
    fn test_secret_detected_next_to_boolean_literal() {
        // Regression: the global allowlist regex `^(?i:true|false|null)$` used to be
        // mis-anchored (`(?i)^true|false|null$`) AND tested against the context window,
        // so any secret near the token `false` was silently suppressed.
        let body = format!(r#"<script>var c={{apiKey:"{AWS_KEY}",debug:false}};</script>"#);
        let secrets = detect_exposed_secrets(&body);
        assert!(
            secrets.iter().any(|s| s.secret_type == "aws-access-token"),
            "AWS key next to `debug:false` must still be detected; got {secrets:?}"
        );
    }

    #[test]
    fn test_minified_page_allowlist_does_not_suppress_whole_body() {
        // Regression: on newline-free (minified) pages, `line_containing` returned the
        // entire body, so a benign line-target allowlist token anywhere on the page
        // (e.g. Cloudflare's `data-cfemail=`) suppressed real findings of that rule.
        let body = format!(
            r#"<span data-cfemail="a1b2c3"></span>{}<script>var k="{AWS_KEY}";</script>"#,
            " ".repeat(2000)
        );
        assert!(!body.contains('\n'), "test body must be newline-free");
        let secrets = detect_exposed_secrets(&body);
        assert!(
            secrets.iter().any(|s| s.secret_type == "aws-access-token"),
            "secret on a minified page with a distant allowlist token must be detected; got {secrets:?}"
        );
    }

    #[test]
    fn test_line_containing_capped_on_minified_body() {
        let body = "x".repeat(5000);
        let line = line_containing(&body, 2500, 2520);
        assert!(
            line.len() <= 2 * MAX_LINE_WINDOW_BYTES + 20,
            "line window must be capped, got {} bytes",
            line.len()
        );
    }

    #[test]
    fn test_detect_secret_in_response_header_block() {
        // Regression: JWTs/keys in response headers (incl. Set-Cookie) were never
        // scanned. A JWT in a Set-Cookie line must be detected and tagged.
        let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.\
                   eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.\
                   dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U";
        let header_block = format!("Content-Type: text/html\nSet-Cookie: session={jwt}; Path=/\n");
        let secrets = detect_exposed_secrets_in_headers(&header_block);
        assert!(
            secrets.iter().any(|s| s.secret_type == "jwt"),
            "JWT in Set-Cookie must be detected; got {secrets:?}"
        );
        assert!(
            secrets.iter().all(|s| s.location == "set_cookie"),
            "header findings must be tagged set_cookie"
        );
    }

    #[test]
    fn test_detect_aws_session_token() {
        // ASIA + 16 chars from [A-Z2-7]; may be filtered by entropy
        let body = "token=ASIA2BCDEF34567ZYXW";
        let secrets = detect_exposed_secrets(body);
        if secrets.len() == 1 {
            assert_eq!(secrets[0].secret_type, "aws-access-token");
            assert_eq!(secrets[0].severity, SecretSeverity::High);
        }
    }

    #[test]
    fn test_detect_google_api_key() {
        let body = r#"var apiKey = "AIzaSyA1234567890abcdefghijklmnopqrstuv";"#;
        let secrets = detect_exposed_secrets(body);
        assert!(!secrets.is_empty());
        assert!(secrets.iter().any(|s| s.secret_type == "gcp-api-key"));
    }

    #[test]
    fn test_detect_google_api_key_in_url_with_trailing_param() {
        // Regression: upstream rules require quote/space/semicolon/EOL after the
        // secret, so a Maps key followed by `&` in a script URL was never matched.
        // The load-time boundary relaxation must catch it.
        let body = r#"<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA1234567890abcdefghijklmnopqrstuv&libraries=places"></script>"#;
        let secrets = detect_exposed_secrets(body);
        let gcp = secrets.iter().find(|s| s.secret_type == "gcp-api-key");
        assert!(
            gcp.is_some(),
            "GCP key followed by `&` in a URL must be detected; got {secrets:?}"
        );
        assert_eq!(
            gcp.map(|s| s.matched_value.as_str()),
            Some("AIzaSyA1234567890abcdefghijklmnopqrstuv"),
            "capture must be the key alone, not include the delimiter"
        );
    }

    #[test]
    fn test_detect_openai_api_key() {
        // gitleaks openai-api-key: sk- + 20 alnum + T3BlbkFJ + 20 alnum (built at runtime to avoid secret-scanning false positives)
        let a: String = (0..20)
            .map(|i| (b'a' + u8::try_from(i % 26).unwrap()) as char)
            .collect();
        let b: String = (0..20)
            .map(|i| (b'A' + u8::try_from(i % 26).unwrap()) as char)
            .collect();
        let body = format!(r#"key = "sk-{}T3BlbkFJ{}""#, a, b);
        let secrets = detect_exposed_secrets(&body);
        assert!(!secrets.is_empty());
        assert!(secrets.iter().any(|s| s.secret_type == "openai-api-key"));
    }

    /// Build a 93-char Anthropic mid-segment without embedding a full key literal in source.
    ///
    /// Digits-first / uppercase-only so the mid never contains the global allowlist
    /// stopword `abcdefghijklmnopqrstuvwxyz`.
    fn anthropic_key_mid() -> String {
        (0..93)
            .map(|i| {
                let n = u8::try_from(i % 36).unwrap();
                match n {
                    0..=9 => (b'0' + n) as char,
                    _ => (b'A' + (n - 10)) as char,
                }
            })
            .collect()
    }

    #[test]
    fn test_detect_anthropic_api_key() {
        // gitleaks: sk-ant-api03- + 93 [A-Za-z0-9_-] + AA
        let key = format!("sk-ant-api03-{}AA", anthropic_key_mid());
        let body = format!(r#"<script>const ANTHROPIC_API_KEY = "{key}";</script>"#);
        let secrets = detect_exposed_secrets(&body);
        let found = secrets
            .iter()
            .find(|s| s.secret_type == "anthropic-api-key")
            .unwrap_or_else(|| panic!("expected anthropic-api-key; got {secrets:?}"));
        assert_eq!(found.matched_value, key);
        assert_eq!(found.severity, SecretSeverity::High);
    }

    #[test]
    fn test_detect_anthropic_admin_api_key() {
        // gitleaks: sk-ant-admin01- + 93 [A-Za-z0-9_-] + AA
        let key = format!("sk-ant-admin01-{}AA", anthropic_key_mid());
        let body = format!(r#"window.__cfg = {{ adminKey: "{key}" }};"#);
        let secrets = detect_exposed_secrets(&body);
        let found = secrets
            .iter()
            .find(|s| s.secret_type == "anthropic-admin-api-key")
            .unwrap_or_else(|| panic!("expected anthropic-admin-api-key; got {secrets:?}"));
        assert_eq!(found.matched_value, key);
        assert_eq!(found.severity, SecretSeverity::High);
    }

    #[test]
    fn test_detect_slack_bot_token() {
        let body = r#"token: "xoxb-123456789012-1234567890123-ABCDEFabcdef123456789012""#;
        let secrets = detect_exposed_secrets(body);
        assert!(!secrets.is_empty());
        assert!(secrets.iter().any(|s| s.secret_type == "slack-bot-token"));
    }

    #[test]
    fn test_detect_rsa_private_key() {
        // Decoded-body floor rejects header-only crumbs; this block is large
        // enough to be a key (3 × 64-char lines ≈ 144 decoded bytes).
        let body = "-----BEGIN RSA PRIVATE KEY-----\n\
                    MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC7VJTUt9Us8cKj\n\
                    MzEfYyjiWA4R4/M2bS1GB4t7NXp98C3SC6dVMvDuictGeurT8jNbvJZHtCSuYEvu\n\
                    MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC7VJTUt9Us8cKj\n\
                    -----END RSA PRIVATE KEY-----";
        let secrets = detect_exposed_secrets(body);
        assert_eq!(secrets.len(), 1);
        assert_eq!(secrets[0].secret_type, "private-key");
        assert_eq!(secrets[0].severity, SecretSeverity::Critical);
    }

    #[test]
    fn test_detect_vault_token() {
        // gitleaks vault-service-token: hvs.[\w-]{90,120} with entropy=3.5
        let suffix: String = (0..95)
            .map(|i| (b'a' + u8::try_from(i % 26).unwrap()) as char)
            .collect();
        let body = format!(r#"VAULT_TOKEN="hvs.{}""#, suffix);
        let secrets = detect_exposed_secrets(&body);
        if !secrets.is_empty() {
            assert!(secrets
                .iter()
                .any(|s| s.secret_type == "vault-service-token"
                    || s.secret_type == "vault-batch-token"));
        }
    }

    #[test]
    fn test_shannon_entropy() {
        assert!((shannon_entropy("") - 0.0).abs() < 1e-9);
        assert!(shannon_entropy("aaaaaaaa") < shannon_entropy("abcd1234"));
    }

    #[test]
    fn test_severity_for_rule_id_explicit_classifications() {
        assert_eq!(
            severity_for_rule_id("private-key"),
            SecretSeverity::Critical
        );
        assert_eq!(
            severity_for_rule_id("aws-access-token"),
            SecretSeverity::High
        );
        assert_eq!(
            severity_for_rule_id("gcp-api-key"),
            SecretSeverity::Low,
            "Maps/Firebase client keys are public-by-design"
        );
        assert_eq!(
            severity_for_rule_id("generic-api-key"),
            SecretSeverity::Medium,
            "catch-all generic rule must not be High by default"
        );
        assert_eq!(
            severity_for_rule_id("mapbox-api-token"),
            SecretSeverity::Low
        );
        assert_eq!(
            severity_for_rule_id("contentful-delivery-api-token"),
            SecretSeverity::Low,
            "Contentful Delivery tokens are public-by-design client keys"
        );
        assert_eq!(
            severity_for_rule_id("algolia-api-key"),
            SecretSeverity::Medium,
            "Algolia admin stays Medium; search keys demote in severity_for_finding"
        );
    }

    /// Walk every rule id shipped in the bundled gitleaks config and assert
    /// the severity classifier returns a sensible value for each. This is a
    /// no-panic / no-default-High guarantee: when upstream gitleaks adds a
    /// new rule, our M-1 classifier must place it somewhere reasonable.
    ///
    /// The guarantee being tested:
    /// - No rule id collapses to `High` *unless* it's in the explicit map
    ///   or its name contains a credential keyword (the regression is the
    ///   pre-M-1 default of "anything unknown -> High" producing noise).
    /// - The classifier never panics on any production rule id.
    /// - Every classification is reproducible (calling twice on the same
    ///   id returns the same severity).
    #[test]
    fn test_severity_classifies_every_shipped_rule_id() {
        let cfg = crate::parse::gitleaks::try_gitleaks().expect("config loads");

        // The explicit High allowlist - hardcoded here so a future
        // refactor of severity_for_rule_id can't silently change which
        // ids are blessed.
        let explicit_high: std::collections::HashSet<&str> = [
            "aws-access-token",
            "http-basic-auth",
            "mailchimp-api-key",
            "openai-api-key",
            "anthropic-api-key",
            "anthropic-admin-api-key",
            "sendgrid-api-token",
            "twilio-api-key",
            "npm-access-token",
            "pypi-upload-token",
            "digitalocean-access-token",
            "digitalocean-pat",
            "heroku-api-key",
            "heroku-api-key-v2",
            "flyio-access-token",
            "shopify-access-token",
            "shopify-private-app-access-token",
            "shopify-shared-secret",
            "bitbucket-client-secret",
            "mailgun-private-api-token",
            "cloudflare-api-key",
            "doppler-api-token",
            "plaid-secret-key",
            "plaid-api-token",
            "fastly-api-token",
        ]
        .into_iter()
        .collect();

        for rule in &cfg.rules {
            let sev = severity_for_rule_id(&rule.id);

            // 1. Determinism: calling twice is identical.
            assert_eq!(
                sev,
                severity_for_rule_id(&rule.id),
                "non-deterministic for {}",
                rule.id
            );

            // 2. Anything that's `High` must either be in the explicit map
            //    OR have a name containing a "this is dangerous" keyword.
            //    Catches the "default High" regression: a rule id we don't
            //    recognise must NOT be High.
            if matches!(sev, SecretSeverity::High) {
                let id = &rule.id;
                let allowed_high = explicit_high.contains(id.as_str())
                    || id.contains("private-key")
                    || id.contains("password")
                    || id.contains("client-secret")
                    || id.contains("client_secret");
                assert!(
                    allowed_high,
                    "rule '{id}' classified as High but not in the explicit map and \
                     doesn't contain a 'high-impact' substring; either add it to the \
                     explicit list or rethink the heuristic so it lands at Medium"
                );
            }
        }
    }

    /// Heuristic for unknown rule IDs: sensitive-sounding ID -> Medium/High,
    /// nothing recognisable -> Low.
    #[test]
    fn test_severity_for_unknown_rule_id_heuristic() {
        // password / private-key / client-secret -> High
        assert_eq!(
            severity_for_rule_id("acme-private-key"),
            SecretSeverity::High
        );
        assert_eq!(
            severity_for_rule_id("foobar-password"),
            SecretSeverity::High
        );
        assert_eq!(
            severity_for_rule_id("zilch-client-secret"),
            SecretSeverity::High
        );
        // token/api-key/access-key/secret/pat/cred -> Medium
        assert_eq!(
            severity_for_rule_id("acme-access-token"),
            SecretSeverity::Medium
        );
        assert_eq!(severity_for_rule_id("foo-api-key"), SecretSeverity::Medium);
        assert_eq!(severity_for_rule_id("foo-pat"), SecretSeverity::Medium);
        assert_eq!(
            severity_for_rule_id("foo-credentials"),
            SecretSeverity::Medium
        );
        // Anything else -> Low (the new conservative default)
        assert_eq!(severity_for_rule_id("nonsense-rule"), SecretSeverity::Low);
        assert_eq!(severity_for_rule_id("totally-random"), SecretSeverity::Low);
    }

    #[test]
    fn test_location_inline_script() {
        let body = format!(r#"<script>var key = "{}";</script>"#, AWS_KEY);
        let secrets = detect_exposed_secrets(&body);
        assert_eq!(secrets[0].location, "inline_script");
    }

    #[test]
    fn test_location_html_comment() {
        let body = format!(r#"<!-- {} -->"#, AWS_KEY);
        let secrets = detect_exposed_secrets(&body);
        assert_eq!(secrets[0].location, "html_comment");
    }

    #[test]
    fn test_location_url_parameter() {
        let body = r#"https://example.com?key=AIzaSyA1234567890abcdefghijklmnopqrstuv"#;
        let secrets = detect_exposed_secrets(body);
        assert!(!secrets.is_empty());
        assert_eq!(secrets[0].location, "url_parameter");
    }

    #[test]
    fn test_location_data_attribute() {
        let body = format!(r#"<div data-api-key="{}">"#, AWS_KEY);
        let secrets = detect_exposed_secrets(&body);
        assert_eq!(secrets[0].location, "data_attribute");
    }

    #[test]
    fn test_location_default_html_body() {
        let body = format!("just plain text {} in body", AWS_KEY);
        let secrets = detect_exposed_secrets(&body);
        assert_eq!(secrets[0].location, "html_body");
    }

    #[test]
    fn test_location_json_ld() {
        let body = format!(
            r#"<html><script type="application/ld+json">{{"apiKey":"{}"}}</script></html>"#,
            AWS_KEY
        );
        let secrets = detect_exposed_secrets(&body);
        assert!(
            !secrets.is_empty(),
            "expected secret in json-ld; got {secrets:?}"
        );
        assert_eq!(secrets[0].location, "json_ld");
    }

    #[test]
    fn test_location_set_cookie_vs_other_header() {
        let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U";
        let set_cookie = format!("Set-Cookie: session={jwt}; Path=/\n");
        let sc = detect_exposed_secrets_in_headers(&set_cookie);
        assert!(
            sc.iter().any(|s| s.location == "set_cookie"),
            "Set-Cookie must be set_cookie; got {sc:?}"
        );

        let auth = format!("Authorization: Bearer {jwt}\n");
        let ah = detect_exposed_secrets_in_headers(&auth);
        assert!(
            ah.iter().any(|s| s.location == "response_header"),
            "Authorization must stay response_header; got {ah:?}"
        );
    }

    #[test]
    fn test_detect_no_secrets() {
        let body = "<html><body><p>Just regular HTML content</p></body></html>";
        let secrets = detect_exposed_secrets(body);
        assert!(secrets.is_empty());
    }

    #[test]
    fn test_detect_deduplicates() {
        let body = format!("first: {} second: {}", AWS_KEY, AWS_KEY);
        let secrets = detect_exposed_secrets(&body);
        assert_eq!(secrets.len(), 1);
    }

    #[test]
    fn test_full_value_stored_not_redacted() {
        let body = AWS_KEY;
        let secrets = detect_exposed_secrets(body);
        assert_eq!(secrets[0].matched_value, AWS_KEY);
        assert!(!secrets[0].matched_value.contains("***"));
    }

    #[test]
    fn test_context_80_chars() {
        // Word boundary before key: use space so \b matches
        let prefix = "A".repeat(100);
        let suffix = "B".repeat(100);
        let body = format!("{} {} {}", prefix, AWS_KEY, suffix);
        let secrets = detect_exposed_secrets(&body);
        assert_eq!(secrets.len(), 1);
        assert!(secrets[0].context.contains("AAAA"));
        assert!(secrets[0].context.contains("BBBB"));
    }

    /// L-6 regression: when the match itself is longer than [`MAX_CONTEXT_BYTES`]
    /// (e.g. a 4 KB private key), the context column stays bounded by replacing
    /// the middle of the match with `...[truncated]...`. The surrounding code
    /// context is preserved.
    #[test]
    fn test_context_cap_truncates_long_matches() {
        let huge_key = format!(
            "-----BEGIN RSA PRIVATE KEY-----\n{}\n-----END RSA PRIVATE KEY-----",
            "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC7".repeat(80)
        );
        let body = format!("// before\n{huge_key}\n// after");
        let secrets = detect_exposed_secrets(&body);
        assert_eq!(secrets.len(), 1);
        let ctx = &secrets[0].context;
        assert!(
            ctx.len() <= MAX_CONTEXT_BYTES,
            "context len {} must be <= MAX_CONTEXT_BYTES {}",
            ctx.len(),
            MAX_CONTEXT_BYTES
        );
        assert!(
            ctx.contains("...[truncated]..."),
            "context should mark truncation; got: {ctx:?}"
        );
        // Keep the surrounding signal even though the middle is gone.
        assert!(ctx.contains("BEGIN RSA PRIVATE KEY"));
        assert!(ctx.contains("END RSA PRIVATE KEY"));
    }

    /// Sanity: short matches still get the full surrounding context (no
    /// truncation marker, full match preserved).
    #[test]
    fn test_context_cap_preserves_short_matches() {
        let body = format!(r#"var key = "{AWS_KEY}";"#);
        let secrets = detect_exposed_secrets(&body);
        let aws = secrets
            .iter()
            .find(|s| s.secret_type == "aws-access-token")
            .unwrap();
        assert!(!aws.context.contains("...[truncated]..."));
        assert!(aws.context.contains(AWS_KEY));
        assert!(aws.context.len() < MAX_CONTEXT_BYTES);
    }

    /// Regression test: `extract_context` must not panic when the context window
    /// (start - 80 bytes or end + 80 bytes) lands inside a multi-byte UTF-8
    /// character. This reproduces the crash from a Polish page containing 'Ä™'
    /// (2-byte UTF-8) where byte arithmetic fell between the two bytes.
    #[test]
    fn test_context_multibyte_boundary_no_panic() {
        // Build a prefix of exactly 79 ASCII bytes followed by a 2-byte char 'Ä™'.
        // The AWS key match starts right after 'Ä™', so start - 80 = byte 79,
        // which is the second byte of 'Ä™' (not a char boundary).
        let prefix = format!("{}\u{0119}", "X".repeat(79)); // 79 + 2 = 81 bytes
        assert_eq!(prefix.len(), 81);
        assert!(!prefix.is_char_boundary(80)); // byte 80 is inside 'Ä™'

        // Same trick for suffix: 79 ASCII bytes preceded by a 2-byte char.
        let suffix = format!("\u{0119}{}", "Y".repeat(79)); // 2 + 79 = 81 bytes

        let body = format!("{} {} {}", prefix, AWS_KEY, suffix);
        let secrets = detect_exposed_secrets(&body);
        assert_eq!(secrets.len(), 1, "should detect the AWS key");
        // Context should include parts of both prefix and suffix without panicking.
        assert!(secrets[0].context.contains("XXXX"));
        assert!(secrets[0].context.contains("YYYY"));
    }

    #[test]
    fn test_gitleaks_config_loads() {
        let config = crate::parse::gitleaks::gitleaks();
        assert!(config.rules.len() > 200, "expected 200+ gitleaks rules");
        assert!(!config.global_allowlist.regexes.is_empty());
    }

    /// Helper: reduce findings to the dedupe-relevant (`rule_id`, `matched_value`) tuples.
    fn finding_keys(secrets: &[ExposedSecret]) -> std::collections::BTreeSet<(String, String)> {
        secrets
            .iter()
            .map(|s| (s.secret_type.clone(), s.matched_value.clone()))
            .collect()
    }

    /// Critical regression: the Aho-Corasick keyword prefilter is meant to be
    /// a pure perf shortcut. For any input body, the filtered detector and
    /// the unfiltered detector must produce the **same** set of
    /// `(rule_id, matched_value)` tuples. Any divergence is a correctness bug
    /// in the prefilter (a missing keyword for some rule, an automaton that
    /// doesn't see a substring, ASCII-only matching when the regex would
    /// match non-ASCII, etc.).
    ///
    /// The body distribution intentionally includes:
    /// - All printable ASCII (the dominant content type on the public web)
    /// - Strings with `=void`, `=t.`, key-like prefixes that exercise our
    ///   stopwords / overlay rules
    /// - Plausible AWS / Google / Stripe shapes so the regexes actually fire
    ///   often enough to find a divergence if one exists
    ///
    /// 256 cases gives high confidence at minor compile-time cost.
    #[test]
    fn test_prefilter_equivalence_on_random_bodies() {
        use proptest::prelude::*;

        // Make sure the bundled config is loaded once before proptest spins
        // up its iterations - avoids races on the lazy OnceLock under -j.
        let _ = crate::parse::gitleaks::try_gitleaks().expect("gitleaks loads");

        let body_strategy = prop_oneof![
            // Pure printable ASCII: the dominant production case.
            "[\\x20-\\x7e]{0,2048}",
            // Non-ASCII bytes embedded in HTML (charset edge cases).
            "[\\x20-\\xff]{0,1024}",
            // Realistic gitleaks-shaped strings - ensures we exercise the
            // actual rules, not just the prefilter on noise.
            r#"var (key|token|api_key|apiKey) ?= ?"[A-Za-z0-9_-]{20,80}";"#,
            r#"AKIA[A-Z2-7]{16}"#,
            r#"AIzaSy[A-Za-z0-9_-]{33}"#,
            r#"sk-[a-zA-Z0-9]{20}T3BlbkFJ[a-zA-Z0-9]{20}"#,
            // Edge: stopword-ish patterns that should NOT fire either way.
            r#"[a-z][a-zA-Z]+\.[a-z]+=void"#,
        ];

        proptest!(ProptestConfig::with_cases(256), |(body in body_strategy)| {
            let with_prefilter = detect_exposed_secrets(&body);
            let without_prefilter = detect_exposed_secrets_unfiltered(&body);
            let with_keys = finding_keys(&with_prefilter);
            let without_keys = finding_keys(&without_prefilter);
            prop_assert_eq!(
                with_keys.clone(),
                without_keys.clone(),
                "Prefilter divergence!\n\
                 body (first 200 chars): {}\n\
                 with_prefilter:    {:?}\n\
                 without_prefilter: {:?}",
                body.chars().take(200).collect::<String>(),
                with_keys,
                without_keys
            );
        });
    }

    /// Gitleaks keyword prefilter: sourcegraph-access-token has keywords ["sgp_", "sourcegraph"].
    /// Without either in the body, a plain 40-char hex (e.g. Git SHA) must not be reported.
    #[test]
    fn test_sourcegraph_no_fire_without_keyword() {
        let sha_like = "9c02de5c56d82f105252bb92478c88114ab41dce";
        let body = format!(r#"<span>commit {} </span>"#, sha_like);
        let secrets = detect_exposed_secrets(&body);
        let sourcegraph = secrets
            .iter()
            .find(|s| s.secret_type == "sourcegraph-access-token");
        assert!(
            sourcegraph.is_none(),
            "sourcegraph-access-token must not fire without keyword in body; got {:?}",
            secrets
        );
    }

    /// With "sourcegraph" in the body, a 40-char hex can be reported as sourcegraph-access-token.
    #[test]
    fn test_sourcegraph_fires_with_keyword() {
        // Real tokens use the sgp_ prefix; bare 40-hex is intentionally rejected.
        let token = format!(
            "sgp_{}_{}",
            "0123456789abcdef", "a1b2c3d4e5f6789012345678901234567890abcd"
        );
        let body = format!(r#"<script>window.SOURCEGRAPH = "{token}";</script>"#);
        let secrets = detect_exposed_secrets(&body);
        let sourcegraph = secrets
            .iter()
            .find(|s| s.secret_type == "sourcegraph-access-token");
        assert!(
            sourcegraph.is_some(),
            "sourcegraph-access-token should fire for sgp_ tokens; got {secrets:?}"
        );
        assert_eq!(sourcegraph.unwrap().matched_value, token);
    }

    /// Per-rule allowlist: 40-char hex in html id="..." (e.g. Wix build ID) must not be reported as sourcegraph-access-token.
    #[test]
    fn test_sourcegraph_allowlist_html_id_skipped() {
        let build_id = "1ccd1dddac2890afd4e9eb54f87f22008b1ed114";
        let body = format!(
            r#"<html id="{}" class="StudioLegacy Legacy">sourcegraph integration</html>"#,
            build_id
        );
        let secrets = detect_exposed_secrets(&body);
        let sourcegraph = secrets
            .iter()
            .find(|s| s.secret_type == "sourcegraph-access-token");
        assert!(
            sourcegraph.is_none(),
            "40-char hex in html id= should be allowlisted; got {:?}",
            secrets
        );
    }

    /// Cloudflare email obfuscation: 40-char hex in email-protection# or data-cfemail= must be allowlisted.
    #[test]
    fn test_sourcegraph_allowlist_cloudflare_email_skipped() {
        let hex = "3f565159507f5e53545e52564b5a5c57115c5052";
        let body = format!(
            r#"<a href="/cdn-cgi/l/email-protection#{}">Contact</a> sourcegraph"#,
            hex
        );
        let secrets = detect_exposed_secrets(&body);
        let sourcegraph = secrets
            .iter()
            .find(|s| s.secret_type == "sourcegraph-access-token");
        assert!(
            sourcegraph.is_none(),
            "40-char hex in Cloudflare email-protection# should be allowlisted; got {:?}",
            secrets
        );
        let body2 = format!(
            r#"<span class="__cf_email__" data-cfemail="{}">[email protected]</span> sourcegraph"#,
            "cca5a2aaa38cada0a7ada1a5b8a9afa4e2afa3a1"
        );
        let secrets2 = detect_exposed_secrets(&body2);
        let sg2 = secrets2
            .iter()
            .find(|s| s.secret_type == "sourcegraph-access-token");
        assert!(
            sg2.is_none(),
            "40-char hex in data-cfemail= should be allowlisted; got {:?}",
            secrets2
        );
    }

    /// Per-rule allowlist: data-hubspot-form="uuid" is a form/embed ID, not an API key; must not be reported as hubspot-api-key.
    #[test]
    fn test_hubspot_allowlist_form_id_skipped() {
        // Rule matches uppercase hex UUID; use uppercase so the rule fires, then allowlist skips.
        let form_id = "AC4D982E-062E-4795-B5E5-718351F44BB9";
        let body = format!(
            r#"<div data-hubspot-form="{}" class="hs-form"></div>"#,
            form_id
        );
        let secrets = detect_exposed_secrets(&body);
        let hubspot = secrets.iter().find(|s| s.secret_type == "hubspot-api-key");
        assert!(
            hubspot.is_none(),
            "data-hubspot-form= UUID should be allowlisted (form ID, not API key); got {:?}",
            secrets
        );
    }

    /// `HubSpot` API key in script context (no data-hubspot-form on line) must still be reported.
    #[test]
    fn test_hubspot_api_key_in_script_still_reported() {
        let uuid = "AC4D982E-062E-4795-B5E5-718351F44BB9";
        let body = format!(r#"<script>window.HUBSPOT_API_KEY="{}";</script>"#, uuid);
        let secrets = detect_exposed_secrets(&body);
        let hubspot = secrets.iter().find(|s| s.secret_type == "hubspot-api-key");
        assert!(
            hubspot.is_some(),
            "hubspot UUID in script (no data-hubspot-form) should still be reported; got {:?}",
            secrets
        );
        assert_eq!(hubspot.unwrap().matched_value, uuid);
        assert!(
            secrets
                .iter()
                .all(|s| s.secret_type != "generic-api-key" || s.matched_value != uuid),
            "UUID-shaped values are not generic-api-key; HubSpot keeps its own rule; got {:?}",
            secrets
        );
    }

    /// Response-header correlation IDs must not be reported as `HubSpot` API keys.
    #[test]
    fn test_hubspot_correlation_id_header_skipped() {
        let uuid = "019F9044-75EC-7F8C-9A70-F99ED4ECC4BD";
        let headers = format!("x-hubspot-correlation-id: {uuid}\nserver: cloudflare\n");
        let secrets = detect_exposed_secrets_in_headers(&headers);
        let hubspot = secrets.iter().find(|s| s.secret_type == "hubspot-api-key");
        assert!(
            hubspot.is_none(),
            "x-hubspot-correlation-id should be allowlisted; got {:?}",
            secrets
        );
    }

    /// Public `HubSpot` form widget IDs in env/config blobs must be skipped.
    #[test]
    fn test_hubspot_form_id_config_skipped() {
        let form_id = "7EA134CD-6DBC-482C-B7C2-576FBF09725E";
        let cases = [
            format!(r#"PUBLIC_HUBSPOT_CONTACT_FORM_ID:"{form_id}""#),
            format!(r#""hubspotFormIdProd":"{form_id}""#),
            format!(r#"REACT_APP_HUBSPOT_FORM_ID_EN:"{form_id}""#),
            format!(r#""hubspot_button_id":"{form_id}""#),
            format!(r#"hubspotSignupguid:"{form_id}""#),
            format!(r#"hubspotID:"{form_id}""#),
        ];
        for body in cases {
            let secrets = detect_exposed_secrets(&body);
            let hubspot = secrets.iter().find(|s| s.secret_type == "hubspot-api-key");
            assert!(
                hubspot.is_none(),
                "HubSpot form ID config should be allowlisted; body={body:?} got={secrets:?}"
            );
        }
    }

    /// Power BI embed tokens share Grafana's eyJrIjoi prefix and must be skipped.
    #[test]
    fn test_grafana_api_key_powerbi_embed_skipped() {
        let token = "eyJrIjoiNTc5MmJjODMtYTM1NS00MWZlLWE1N2EtN2IyNThiOTk3MjI1IiwidCI6IjlkZjk0OWY4LWE2ZWItNDE5ZC05Y2FhLTFmOGM4M2RiNjc0ZiJ9";
        let body = format!(r#"href="https://app.powerbi.com/view?r={token}" target="_blank""#);
        let secrets = detect_exposed_secrets(&body);
        let grafana = secrets.iter().find(|s| s.secret_type == "grafana-api-key");
        assert!(
            grafana.is_none(),
            "Power BI embed token should not be grafana-api-key; got {:?}",
            secrets
        );
    }

    /// A bare Grafana-shaped eyJrIjoi token (no Power BI host) must still be reported.
    #[test]
    fn test_grafana_api_key_without_powerbi_still_reported() {
        let token = "eyJrIjoiNTc5MmJjODMtYTM1NS00MWZlLWE1N2EtN2IyNThiOTk3MjI1IiwidCI6IjlkZjk0OWY4LWE2ZWItNDE5ZC05Y2FhLTFmOGM4M2RiNjc0ZiJ9";
        let body = format!(r#"const grafanaApiKey = "{token}";"#);
        let secrets = detect_exposed_secrets(&body);
        let grafana = secrets.iter().find(|s| s.secret_type == "grafana-api-key");
        assert!(
            grafana.is_some(),
            "Grafana eyJrIjoi token without powerbi.com should still be reported; got {:?}",
            secrets
        );
        assert_eq!(grafana.unwrap().matched_value, token);
    }

    /// Upstream dropbox-api-token (15-char near "dropbox") is disabled for web.
    #[test]
    fn test_dropbox_short_identifier_near_dropbox_skipped() {
        let body = r#"{"dropbox":true,"theChampSiteUrl":"abcde1234567890"}"#;
        let secrets = detect_exposed_secrets(body);
        let dropbox = secrets
            .iter()
            .find(|s| s.secret_type == "dropbox-api-token");
        assert!(
            dropbox.is_none(),
            "15-char near dropbox must not fire dropbox-api-token; got {:?}",
            secrets
        );
    }

    /// Disabling dropbox-api-token must not break distinctive long/short-lived rules.
    #[test]
    fn test_dropbox_long_and_short_lived_still_detected() {
        // Long-lived: [a-z0-9]{11}AAAAAAAAAA[a-z0-9\-_=]{43} (letters must be lowercase).
        let prefix11 = "abcdefghijk";
        let mid = "AAAAAAAAAA";
        let suffix43 = "0123456789_-x7km2pq9vl4nr8wy1st6ua3bc5de0fg";
        assert_eq!(suffix43.len(), 43);
        let long_tok = format!("{prefix11}{mid}{suffix43}");
        let body_long = format!(r#"dropbox_token = "{long_tok}""#);
        let secrets_long = detect_exposed_secrets(&body_long);
        assert!(
            secrets_long
                .iter()
                .any(|s| s.secret_type == "dropbox-long-lived-api-token"),
            "long-lived Dropbox token must still match; got {secrets_long:?}"
        );

        // Short-lived: sl.[a-z0-9\-=_]{135} (letters must be lowercase).
        let short_rest = "x7km2pq9vl4nr8wy1st6ua3bc5de0fg2hj4km6np8qs0tv2wx4yz6ab8cd0ef2gh4jx7km2pq9vl4nr8wy1st6ua3bc5de0fg2hj4km6np8qs0tv2wx4yz6ab8cd0ef2gh4jxxx";
        assert_eq!(short_rest.len(), 135);
        let short_tok = format!("sl.{short_rest}");
        let body_short = format!(r#"dropbox_api = "{short_tok}""#);
        let secrets_short = detect_exposed_secrets(&body_short);
        assert!(
            secrets_short
                .iter()
                .any(|s| s.secret_type == "dropbox-short-lived-api-token"),
            "short-lived Dropbox token must still match; got {secrets_short:?}"
        );
    }

    /// Square EAAA… (binary collision) must not match; sq0atp- still does.
    #[test]
    fn test_square_eaaa_skipped_sq0atp_kept() {
        let eaaa = "EAAA".to_string() + &"A".repeat(40);
        let body_eaaa = format!(r#"binary blob {eaaa} noise"#);
        let secrets_eaaa = detect_exposed_secrets(&body_eaaa);
        assert!(
            secrets_eaaa
                .iter()
                .all(|s| s.secret_type != "square-access-token"),
            "EAAA must not match square-access-token; got {:?}",
            secrets_eaaa
        );

        // Avoid global allowlist stopwords like "abcdefghijklmnopqrstuvwxyz".
        let sq = "sq0atp-9fK2mP7xQ4nR8wL1sT6uA3bC5dE0";
        let body_sq = format!(r#"const token = "{sq}";"#);
        let secrets_sq = detect_exposed_secrets(&body_sq);
        let square = secrets_sq
            .iter()
            .find(|s| s.secret_type == "square-access-token");
        assert!(
            square.is_some(),
            "sq0atp- Square PAT should still be reported; got {:?}",
            secrets_sq
        );
        assert_eq!(square.unwrap().matched_value, sq);
    }

    /// datadogVersion build hash must not match; `DD_API_KEY` assignment must.
    #[test]
    fn test_datadog_version_skipped_api_key_kept() {
        let hash = "e561f43f1a2b3c4d5e6f708192a3b4c5d6e7f809";
        let body_ver = format!(r#"{{"datadogVersion":"{hash}"}}"#);
        let secrets_ver = detect_exposed_secrets(&body_ver);
        assert!(
            secrets_ver
                .iter()
                .all(|s| s.secret_type != "datadog-access-token"),
            "datadogVersion hash must not match; got {:?}",
            secrets_ver
        );

        let body_key = format!(r#"DD_API_KEY={hash}"#);
        let secrets_key = detect_exposed_secrets(&body_key);
        let dd = secrets_key
            .iter()
            .find(|s| s.secret_type == "datadog-access-token");
        assert!(
            dd.is_some(),
            "DD_API_KEY assignment should still be reported; got {:?}",
            secrets_key
        );
        assert_eq!(dd.unwrap().matched_value, hash);
    }

    /// Bare `apiKey`/`appKey` hex assignments collide with many third-party SDKs. Keep
    /// `datadog-access-token` only when nearby text identifies Datadog; Algolia /
    /// Bugsnag / etc. must not match. `DD_API_KEY` (contains `dd_api`) still matches.
    #[test]
    fn test_datadog_requires_datadog_context() {
        let hash = "e561f43f1a2b3c4d5e6f708192a3b4c5d6e7f809";

        let body_algolia_camel = format!(r#"var algoliaApiKey = "{hash}";"#);
        let secrets_algolia_camel = detect_exposed_secrets(&body_algolia_camel);
        assert!(
            secrets_algolia_camel
                .iter()
                .all(|s| s.secret_type != "datadog-access-token"),
            "algoliaApiKey assignment must not match datadog-access-token; got {:?}",
            secrets_algolia_camel
        );

        let body_al_apikey = format!(r#"var al_apiKey = "{hash}";"#);
        let secrets_al_apikey = detect_exposed_secrets(&body_al_apikey);
        assert!(
            secrets_al_apikey
                .iter()
                .all(|s| s.secret_type != "datadog-access-token"),
            "al_apiKey assignment must not match datadog-access-token; got {:?}",
            secrets_al_apikey
        );

        let body_nearby = format!(r#"algolia config: apiKey: "{hash}", appId: "ABC123XYZ""#);
        let secrets_nearby = detect_exposed_secrets(&body_nearby);
        assert!(
            secrets_nearby
                .iter()
                .all(|s| s.secret_type != "datadog-access-token"),
            "apiKey near 'algolia' context must not match datadog-access-token; got {:?}",
            secrets_nearby
        );

        let body_bugsnag = format!(r#"Bugsnag.start({{ apiKey: "{hash}" }});"#);
        let secrets_bugsnag = detect_exposed_secrets(&body_bugsnag);
        assert!(
            secrets_bugsnag
                .iter()
                .all(|s| s.secret_type != "datadog-access-token"),
            "Bugsnag apiKey must not match datadog-access-token; got {:?}",
            secrets_bugsnag
        );

        let body_bare = format!(r#"const apiKey = "{hash}";"#);
        let secrets_bare = detect_exposed_secrets(&body_bare);
        assert!(
            secrets_bare
                .iter()
                .all(|s| s.secret_type != "datadog-access-token"),
            "bare apiKey without Datadog context must not match; got {:?}",
            secrets_bare
        );

        // Real Datadog assignment (DD_API_KEY embeds dd_api identity).
        let body_key = format!(r#"DD_API_KEY={hash}"#);
        let secrets_key = detect_exposed_secrets(&body_key);
        let dd = secrets_key
            .iter()
            .find(|s| s.secret_type == "datadog-access-token");
        assert!(
            dd.is_some(),
            "DD_API_KEY assignment should still be reported; got {:?}",
            secrets_key
        );
        assert_eq!(dd.unwrap().matched_value, hash);

        let body_rum = format!(
            r#"window.DD_RUM.init({{ clientToken: "pubxxx", site: "datadoghq.com", apiKey: "{hash}" }});"#
        );
        let secrets_rum = detect_exposed_secrets(&body_rum);
        assert!(
            secrets_rum
                .iter()
                .any(|s| s.secret_type == "datadog-access-token" && s.matched_value == hash),
            "apiKey near datadog RUM context should be reported; got {:?}",
            secrets_rum
        );
    }

    /// Bare EAAC… without `access_token` assignment must not match; assignment must.
    #[test]
    fn test_facebook_page_token_requires_assignment() {
        // High-entropy EAAC token; need ≥100 chars after EAAC for the rule.
        let token = format!(
            "EAAC{}",
            "x7Km2pQ9vL4nR8wY1sT6uA3bC5dE0fG2hJ4kM6nP8qS0tV2wX4yZ6aB8cD0eF2gH4j".repeat(2)
        );
        assert!(token.len() >= 104);
        let body_bare = format!(r#"noise {token} more"#);
        let secrets_bare = detect_exposed_secrets(&body_bare);
        assert!(
            secrets_bare
                .iter()
                .all(|s| s.secret_type != "facebook-page-access-token"),
            "bare EAAC must not match facebook-page-access-token; got {:?}",
            secrets_bare
        );

        let body_assign = format!(r#"access_token="{token}""#);
        let secrets_assign = detect_exposed_secrets(&body_assign);
        let fb = secrets_assign
            .iter()
            .find(|s| s.secret_type == "facebook-page-access-token");
        assert!(
            fb.is_some(),
            "access_token= EAAC should still be reported; got {:?}",
            secrets_assign
        );
        assert_eq!(fb.unwrap().matched_value, token);
    }

    /// Lowercase camelCase near linkedin (JS property) must be skipped.
    #[test]
    fn test_linkedin_camelcase_property_skipped() {
        let body = r#"{"linkedin":"share","thumbnailWidth":"abcdefghijklmn"}"#;
        let secrets = detect_exposed_secrets(body);
        assert!(
            secrets
                .iter()
                .all(|s| s.secret_type != "linkedin-client-id"),
            "thumbnailWidth must not match linkedin-client-id; got {:?}",
            secrets
        );
    }

    /// Lowercase camelCase 16-char property must not match linkedin-client-secret.
    #[test]
    fn test_linkedin_client_secret_camelcase_skipped() {
        let body = r#"linkedin_client_secret = "thumbnailWidthab""#;
        let secrets = detect_exposed_secrets(body);
        assert!(
            secrets
                .iter()
                .all(|s| s.secret_type != "linkedin-client-secret"),
            "camelCase property must not be reported as linkedin-client-secret; got {secrets:?}"
        );
    }

    /// Opaque non-camel `LinkedIn` client id assignment must still be reported.
    #[test]
    fn test_linkedin_opaque_client_id_still_reported() {
        // 14-char opaque token: no lowercase→uppercase camelCase transition.
        let client_id = "ab12cd34ef56gh";
        let body = format!(r#"linkedin_client_id = "{client_id}""#);
        let secrets = detect_exposed_secrets(&body);
        let linkedin = secrets
            .iter()
            .find(|s| s.secret_type == "linkedin-client-id");
        assert!(
            linkedin.is_some(),
            "opaque linkedin client id should still be reported; got {:?}",
            secrets
        );
        assert_eq!(linkedin.unwrap().matched_value, client_id);
    }

    /// Opaque 16-char `LinkedIn` client secret must still be reported.
    #[test]
    fn test_linkedin_opaque_client_secret_still_reported() {
        let secret = "a1b2c3d4e5f6g7h8";
        assert_eq!(secret.len(), 16);
        let body = format!(r#"linkedin_client_secret = "{secret}""#);
        let secrets = detect_exposed_secrets(&body);
        let linkedin = secrets
            .iter()
            .find(|s| s.secret_type == "linkedin-client-secret");
        assert!(
            linkedin.is_some(),
            "opaque linkedin client secret should still be reported; got {:?}",
            secrets
        );
        assert_eq!(linkedin.unwrap().matched_value, secret);
    }

    /// X-Amz-Credential= AWS key IDs are Low; bare AKIA in HTML remains High.
    #[test]
    fn test_aws_amz_credential_severity_demoted() {
        // AKIA + 16 chars from [A-Z2-7] (no 0/1/8/9); must not end in EXAMPLE.
        let akia = "AKIAYCQ2ABCD2EFGHJKL";
        assert_eq!(akia.len(), 20);

        let signed = format!(
            r#"href="https://bucket.s3.amazonaws.com/x?X-Amz-Credential={akia}%2F20260101%2Fus-east-1%2Fs3%2Faws4_request""#
        );
        let secrets_signed = detect_exposed_secrets(&signed);
        let aws_signed = secrets_signed
            .iter()
            .find(|s| s.secret_type == "aws-access-token");
        assert!(
            aws_signed.is_some(),
            "Amz-Credential AKIA should still be recorded; got {:?}",
            secrets_signed
        );
        assert_eq!(
            aws_signed.unwrap().severity,
            SecretSeverity::Low,
            "Amz-Credential should be Low severity"
        );

        let comment = format!(r#"<!-- {akia} VFvFrZXsecretlooking -->"#);
        let secrets_comment = detect_exposed_secrets(&comment);
        let aws_comment = secrets_comment
            .iter()
            .find(|s| s.secret_type == "aws-access-token");
        assert!(
            aws_comment.is_some(),
            "bare AKIA in comment should still be reported; got {:?}",
            secrets_comment
        );
        assert_eq!(
            aws_comment.unwrap().severity,
            SecretSeverity::High,
            "bare AKIA should remain High"
        );
    }

    /// Weglot / App Insights / Prismic public IDs must not fire generic-api-key.
    #[test]
    fn test_generic_public_product_ids_skipped() {
        let weglot_key = "wg_0123456789abcdef0123456789abcdef";
        let body_wg = format!(r#"Weglot.initialize({{ api_key: '{weglot_key}' }});"#);
        let secrets_wg = detect_exposed_secrets(&body_wg);
        assert!(
            secrets_wg
                .iter()
                .all(|s| !(s.secret_type == "generic-api-key"
                    && s.matched_value.eq_ignore_ascii_case(weglot_key))),
            "Weglot wg_ key should be allowlisted; got {:?}",
            secrets_wg
        );

        // Observed leftover format is wg_ + 33 hex (36 chars), not 32.
        let weglot_33 = "wg_0123456789abcdef0123456789abcdef0";
        assert_eq!(weglot_33.len(), 36);
        let body_wg33 = format!(r#"Weglot.initialize({{ api_key: '{weglot_33}' }});"#);
        let secrets_wg33 = detect_exposed_secrets(&body_wg33);
        assert!(
            secrets_wg33
                .iter()
                .all(|s| !(s.secret_type == "generic-api-key"
                    && s.matched_value.eq_ignore_ascii_case(weglot_33))),
            "Weglot wg_ + 33 hex should be allowlisted; got {:?}",
            secrets_wg33
        );

        let uuid = "12345678-1234-1234-1234-123456789abc";
        let body_ai = format!(r#"instrumentationKey:'{uuid}'"#);
        let secrets_ai = detect_exposed_secrets(&body_ai);
        assert!(
            secrets_ai
                .iter()
                .all(|s| !(s.secret_type == "generic-api-key" && s.matched_value == uuid)),
            "App Insights instrumentationKey should be allowlisted; got {:?}",
            secrets_ai
        );

        let body_prismic = format!(
            r#"{{"link":{{"link_type":"Document","key":"{uuid}","url":"https://example.com"}}}}"#
        );
        let secrets_prismic = detect_exposed_secrets(&body_prismic);
        assert!(
            secrets_prismic
                .iter()
                .all(|s| !(s.secret_type == "generic-api-key" && s.matched_value == uuid)),
            "Prismic link_type+key should be allowlisted; got {:?}",
            secrets_prismic
        );

        let hex40 = "000f0192a841c56389c0ea2bff307ee1f771334f";
        let body_minified_prismic =
            format!(r#"last_publication_date:"2026-07-10",uid:aM,link_type:c,key:"{hex40}""#);
        let secrets_minified = detect_exposed_secrets(&body_minified_prismic);
        assert!(
            secrets_minified
                .iter()
                .all(|s| !(s.secret_type == "generic-api-key" && s.matched_value == hex40)),
            "minified link_type:c,key should be allowlisted; got {:?}",
            secrets_minified
        );

        let body_react_key = format!(r#"return eb(ev,{{key:"{hex40}",role:this.getRole()}})"#);
        let secrets_react = detect_exposed_secrets(&body_react_key);
        assert!(
            secrets_react
                .iter()
                .all(|s| !(s.secret_type == "generic-api-key" && s.matched_value == hex40)),
            "React key:\"<40hex>\" should be allowlisted; got {:?}",
            secrets_react
        );

        let body_bot = format!(r#""botSignalToken":"{hex40}","botSignalTimestamp":"6a89f8b7""#);
        let secrets_bot = detect_exposed_secrets(&body_bot);
        assert!(
            secrets_bot
                .iter()
                .all(|s| !(s.secret_type == "generic-api-key" && s.matched_value == hex40)),
            "botSignalToken should be allowlisted; got {:?}",
            secrets_bot
        );

        // Bare apiKey assignment of hex must still be eligible for generic-api-key
        // (not caught by the key: allowlist).
        let body_api = format!(r#"const apiKey = "{hex40}";"#);
        let secrets_api = detect_exposed_secrets(&body_api);
        assert!(
            secrets_api
                .iter()
                .any(|s| s.secret_type == "generic-api-key" && s.matched_value == hex40),
            "apiKey assignment should still match generic-api-key; got {:?}",
            secrets_api
        );

        // CMS JSON `"key":"<uuid>"` is a document id, not a catch-all credential.
        let doc_uuid = "01234567-89ab-cdef-0123-456789abcdef";
        let body_cms = format!(r#"{{"id":"doc","key":"{doc_uuid}"}}"#);
        let secrets_cms = detect_exposed_secrets(&body_cms);
        assert!(
            secrets_cms
                .iter()
                .all(|s| !(s.secret_type == "generic-api-key" && s.matched_value == doc_uuid)),
            "CMS JSON key UUID must not be generic-api-key; got {secrets_cms:?}"
        );
        let body_api_uuid = format!(r#"const apiKey = "{doc_uuid}";"#);
        let secrets_api_uuid = detect_exposed_secrets(&body_api_uuid);
        assert!(
            secrets_api_uuid
                .iter()
                .all(|s| !(s.secret_type == "generic-api-key" && s.matched_value == doc_uuid)),
            "UUID-shaped values are not generic-api-key even on apiKey=; got {secrets_api_uuid:?}"
        );
    }

    #[test]
    fn test_looks_like_hyphenated_uuid() {
        assert!(looks_like_hyphenated_uuid(
            "01234567-89ab-cdef-0123-456789abcdef"
        ));
        assert!(looks_like_hyphenated_uuid(
            "AC4D982E-062E-4795-B5E5-718351F44BB9"
        ));
        assert!(!looks_like_hyphenated_uuid(
            "a7f3c9e2b81d4056f9e4a1c8b7d60352e1f90a4b"
        ));
        assert!(!looks_like_hyphenated_uuid("not-a-uuid"));
    }

    /// Discord client secret requires discord*client*secret assignment, not URL/CSS noise.
    #[test]
    fn test_discord_client_secret_requires_assignment() {
        let body_fp = r#"{"platforms-subtitle1-image2":"https://assets.example.com/ai-live-captions-google-meet-discord-voov.webp","platforms-subtitle1-image2-title":"Online meeting"}"#;
        let secrets_fp = detect_exposed_secrets(body_fp);
        assert!(
            secrets_fp
                .iter()
                .all(|s| s.secret_type != "discord-client-secret"),
            "discord in URL/CSS must not fire discord-client-secret; got {:?}",
            secrets_fp
        );

        let secret = "a1b2c3d4e5f6789012345678abcdef01";
        let body_ok = format!(r#"discord_client_secret = "{secret}""#);
        let secrets_ok = detect_exposed_secrets(&body_ok);
        let hit = secrets_ok
            .iter()
            .find(|s| s.secret_type == "discord-client-secret");
        assert!(
            hit.is_some(),
            "discord_client_secret assignment should be reported; got {:?}",
            secrets_ok
        );
        assert_eq!(hit.unwrap().matched_value, secret);
    }

    /// `ImageBoss` `bossToken=` and YouTube/Vimeo embed `key=` are public CDN
    /// params, not credentials. A first-party `api_key=` query must still fire.
    #[test]
    fn test_generic_cdn_embed_product_ids_skipped() {
        let hex64 = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
        assert_eq!(hex64.len(), 64);
        let body_boss = format!(
            r#"<img src="https://img.ibosscdn.com/assets/hero.jpg?bossToken={hex64}&w=800">"#
        );
        let secrets_boss = detect_exposed_secrets(&body_boss);
        assert!(
            secrets_boss
                .iter()
                .all(|s| !(s.secret_type == "generic-api-key" && s.matched_value == hex64)),
            "ImageBoss bossToken should be allowlisted; got {:?}",
            secrets_boss
        );

        let hex32 = "0123456789abcdef0123456789abcdef";
        assert_eq!(hex32.len(), 32);
        let body_yt = format!(
            r#"<img src="https://i.ytimg.com/vi/abcdefghijk/hqdefault.jpg?sqp=-o&key={hex32}">"#
        );
        let secrets_yt = detect_exposed_secrets(&body_yt);
        assert!(
            secrets_yt
                .iter()
                .all(|s| !(s.secret_type == "generic-api-key" && s.matched_value == hex32)),
            "ytimg.com embed key= should be allowlisted; got {:?}",
            secrets_yt
        );

        let body_vimeo = format!(
            r#"<iframe src="https://player.vimeo.com/video/123456789?key={hex32}"></iframe>"#
        );
        let secrets_vimeo = detect_exposed_secrets(&body_vimeo);
        assert!(
            secrets_vimeo
                .iter()
                .all(|s| !(s.secret_type == "generic-api-key" && s.matched_value == hex32)),
            "vimeo.com embed key= should be allowlisted; got {:?}",
            secrets_vimeo
        );

        let body_first_party = format!(r#"fetch("https://example.com/api?api_key={hex32}")"#);
        let secrets_fp = detect_exposed_secrets(&body_first_party);
        assert!(
            secrets_fp
                .iter()
                .any(|s| s.secret_type == "generic-api-key" && s.matched_value == hex32),
            "first-party api_key= must still match generic-api-key; got {:?}",
            secrets_fp
        );
    }

    /// Algolia search keys are Low inventory; admin assignments stay Medium.
    #[test]
    fn test_algolia_search_demoted_admin_stays_medium() {
        let key = "a1b2c3d4e5f6789012345678abcdef01";
        assert_eq!(key.len(), 32);

        let body_search =
            format!(r#"const cfg = {{ algoliaApiKey: "{key}", algoliaAppId: "ABC123XYZ0" }};"#);
        let secrets_search = detect_exposed_secrets(&body_search);
        let search = secrets_search
            .iter()
            .find(|s| s.secret_type == "algolia-api-key");
        assert!(
            search.is_some(),
            "Algolia search key should still be recorded; got {:?}",
            secrets_search
        );
        assert_eq!(
            search.unwrap().severity,
            SecretSeverity::Low,
            "Algolia search key should be Low inventory"
        );

        let body_admin = format!(r#"const ALGOLIA_ADMIN_KEY = "{key}";"#);
        let secrets_admin = detect_exposed_secrets(&body_admin);
        let admin = secrets_admin
            .iter()
            .find(|s| s.secret_type == "algolia-api-key");
        assert!(
            admin.is_some(),
            "Algolia admin key should be recorded; got {:?}",
            secrets_admin
        );
        assert_eq!(
            admin.unwrap().severity,
            SecretSeverity::Medium,
            "Algolia admin assignment must stay Medium"
        );

        // Admin next to an App ID must not be demoted (pairing is not a suppress).
        let body_both =
            format!(r#"ALGOLIA_APPLICATION_ID="ABC123XYZ0"; ALGOLIA_ADMIN_KEY="{key}";"#);
        let secrets_both = detect_exposed_secrets(&body_both);
        let both = secrets_both
            .iter()
            .find(|s| s.secret_type == "algolia-api-key");
        assert!(
            both.is_some(),
            "Algolia admin+appId should still be recorded; got {:?}",
            secrets_both
        );
        assert_eq!(
            both.unwrap().severity,
            SecretSeverity::Medium,
            "Algolia admin next to App ID must stay Medium"
        );
    }

    /// Contentful Delivery API tokens are Low inventory (browser-embeddable).
    #[test]
    fn test_contentful_delivery_token_is_low() {
        let token = "9f3k2m8q1p7n4t6w0x5z8b2c7d1h4j9l3s6v0y2a8fq";
        assert_eq!(token.len(), 43);
        let body = format!(r#"contentfulAccessToken="{token}""#);
        let secrets = detect_exposed_secrets(&body);
        let cda = secrets
            .iter()
            .find(|s| s.secret_type == "contentful-delivery-api-token");
        assert!(
            cda.is_some(),
            "Contentful delivery token should be recorded; got {:?}",
            secrets
        );
        assert_eq!(
            cda.unwrap().severity,
            SecretSeverity::Low,
            "Contentful CDA should be Low inventory"
        );
    }

    /// JWT rule severity is explicitly Low (inventory, not triage-urgent).
    #[test]
    fn test_jwt_severity_is_low() {
        assert_eq!(severity_for_rule_id("jwt"), SecretSeverity::Low);
        assert_eq!(severity_for_rule_id("jwt-base64"), SecretSeverity::Low);
    }

    /// `LinkedIn` client-id rule: line with extensionPointId / pageJsonFileName (block IDs) must be allowlisted.
    #[test]
    fn test_linkedin_client_id_allowlist_structure_skipped() {
        let body = r#"{"blockId":"uselectrical.b2bstore@4.x:menu-item#footer-linkedin","extensionPointId":"menu-item#footer-linkedin"}"#;
        let secrets = detect_exposed_secrets(body);
        let linkedin = secrets
            .iter()
            .find(|s| s.secret_type == "linkedin-client-id");
        assert!(
            linkedin.is_none(),
            "linkedin-client-id with extensionPointId/footer-linkedin should be allowlisted; got {:?}",
            secrets
        );
    }

    /// `Sumologic`: sumoSiteId in embed script is public site ID, not access token.
    #[test]
    fn test_sumologic_allowlist_site_id_skipped() {
        let site_id = "38d92200f6b3d700b2eb2e0069250000108b3e00a638e0004c77b700ec8ea400";
        let body = format!(
            r#"j.dataset.sumoSiteId='{}';j.dataset.sumoPlatform='wordpress';"#,
            site_id
        );
        let secrets = detect_exposed_secrets(&body);
        let sumo = secrets
            .iter()
            .find(|s| s.secret_type == "sumologic-access-token");
        assert!(
            sumo.is_none(),
            "sumologic sumoSiteId (public site ID) should be allowlisted; got {:?}",
            secrets
        );
    }

    /// Path-restricted rules (e.g. hashicorp-tf-password for .tf/.hcl) are skipped when scanning a single blob (HTML) with no file path.
    #[test]
    fn test_path_restricted_rule_skipped_on_html() {
        let body = r#"<script>p_lt_ctl13_AFI_CustomRegistrationForm_plcUp_formUser_UserPassword_rfvConfirmPassword.validationGroup = "ConfirmRegForm";</script>"#;
        let secrets = detect_exposed_secrets(body);
        let tf_password = secrets
            .iter()
            .find(|s| s.secret_type == "hashicorp-tf-password");
        assert!(
            tf_password.is_none(),
            "hashicorp-tf-password (path-restricted) must be skipped when scanning HTML; got {:?}",
            secrets
        );
    }

    /// sonar-api-token has secretGroup = 2; extracted secret must be group 2 (the token), not group 1 (login|token).
    #[test]
    fn test_sonar_secret_group_2() {
        // Regex group 1 = (login|token), group 2 = 40-char token. secretGroup=2 => we store group 2.
        let token = "squ_abcdefghij0123456789abcdefghij012345"; // 40 chars
        let body = format!(r#"sonar_token="{}""#, token);
        let secrets = detect_exposed_secrets(&body);
        let sonar = secrets.iter().find(|s| s.secret_type == "sonar-api-token");
        assert!(
            sonar.is_some(),
            "expected sonar-api-token finding: {:?}",
            secrets
        );
        assert_eq!(
            sonar.unwrap().matched_value,
            token,
            "secretGroup=2 should yield the token (group 2), not 'token' (group 1)"
        );
    }

    /// Condition AND with `has_paths`: for single-blob we never have a file path, so AND never succeeds and we must not skip.
    #[test]
    fn test_rule_allowlist_condition_and_with_paths_does_not_skip() {
        use crate::parse::gitleaks::CompiledRuleAllowlist;
        use regex::Regex;

        let re = Regex::new("EXAMPLE").unwrap();
        let list = CompiledRuleAllowlist {
            regexes: vec![re],
            stopwords: vec![],
            regex_target: None,
            condition_and: true,
            has_paths: true,
        };
        // Target matches the regex, but AND requires all criteria; path is N/A so we treat as not matched -> do not skip.
        let skips = rule_allowlist_skips(
            &[list],
            "AKIAIOSFODNN7EXAMPLE",
            "line content",
            "full match",
        );
        assert!(
            !skips,
            "AND with has_paths must not skip (path never matches in single-blob)"
        );
    }

    // === Database Connection URIs ===

    #[test]
    fn test_detect_mongodb_connection_uri() {
        let body = r#"<script>var dbUrl = "mongodb+srv://admin:s3cretP4ss@cluster0.mongodb.net/mydb";</script>"#;
        let secrets = detect_exposed_secrets(body);
        let db = secrets
            .iter()
            .find(|s| s.secret_type == "database-connection-uri");
        assert!(db.is_some(), "should detect MongoDB URI; got {:?}", secrets);
        let db = db.unwrap();
        // M-4: matched_value is now the full URI so analysts see host/db,
        // not just the bare password.
        assert_eq!(
            db.matched_value,
            "mongodb+srv://admin:s3cretP4ss@cluster0.mongodb.net/mydb"
        );
        assert_eq!(db.severity, SecretSeverity::Critical);
    }

    #[test]
    fn test_detect_postgres_connection_uri() {
        let body = r#"<!-- config: postgres://appuser:hunter2@db.example.com:5432/production -->"#;
        let secrets = detect_exposed_secrets(body);
        let db = secrets
            .iter()
            .find(|s| s.secret_type == "database-connection-uri");
        assert!(
            db.is_some(),
            "should detect PostgreSQL URI; got {:?}",
            secrets
        );
        assert_eq!(
            db.unwrap().matched_value,
            "postgres://appuser:hunter2@db.example.com:5432/production"
        );
    }

    #[test]
    fn test_detect_redis_connection_uri() {
        let body = r#"REDIS_URL=redis://default:myP4ssword@cache.example.com:6379/0"#;
        let secrets = detect_exposed_secrets(body);
        let db = secrets
            .iter()
            .find(|s| s.secret_type == "database-connection-uri");
        assert!(db.is_some(), "should detect Redis URI; got {:?}", secrets);
        assert_eq!(
            db.unwrap().matched_value,
            "redis://default:myP4ssword@cache.example.com:6379/0"
        );
    }

    #[test]
    fn test_detect_mysql_connection_uri() {
        let body = r#"mysql://root:Str0ngP@ss@mysql.internal:3306/appdb"#;
        let secrets = detect_exposed_secrets(body);
        let db = secrets
            .iter()
            .find(|s| s.secret_type == "database-connection-uri");
        assert!(db.is_some(), "should detect MySQL URI; got {:?}", secrets);
    }

    #[test]
    fn test_no_detect_mongodb_without_credentials() {
        let body = r#"mongodb://localhost/testdb"#;
        let secrets = detect_exposed_secrets(body);
        let db = secrets
            .iter()
            .find(|s| s.secret_type == "database-connection-uri");
        assert!(
            db.is_none(),
            "should NOT detect URI without credentials; got {:?}",
            secrets
        );
    }

    // === HTTP Basic Auth ===

    #[test]
    fn test_detect_http_basic_auth() {
        let body = r#"<script>xhr.setRequestHeader("Authorization", "Basic dXNlcjpzM2NyZXRQNHNz");</script>"#;
        let secrets = detect_exposed_secrets(body);
        let auth = secrets.iter().find(|s| s.secret_type == "http-basic-auth");
        assert!(
            auth.is_some(),
            "should detect HTTP Basic Auth; got {:?}",
            secrets
        );
        assert_eq!(auth.unwrap().severity, SecretSeverity::High);
    }

    #[test]
    fn test_no_detect_http_basic_auth_too_short() {
        // "Og==" is base64 for ":" — too short (< 6 base64 chars)
        let body = r#"Authorization: Basic Og=="#;
        let secrets = detect_exposed_secrets(body);
        let auth = secrets.iter().find(|s| s.secret_type == "http-basic-auth");
        assert!(
            auth.is_none(),
            "trivially short Basic auth should not match; got {:?}",
            secrets
        );
    }

    // === Credential-bearing URLs (https://user:pass@host) ===

    #[test]
    fn test_detect_credential_url() {
        let body =
            r#"fetch("https://deploy:ghp_x7K9mQ2vL8nR3pW1234567890ab@api.internal.com/v1/data")"#;
        let secrets = detect_exposed_secrets(body);
        let url = secrets
            .iter()
            .find(|s| s.secret_type == "credential-bearing-url");
        assert!(
            url.is_some(),
            "should detect credential URL; got {:?}",
            secrets
        );
        assert_eq!(url.unwrap().severity, SecretSeverity::Critical);
    }

    // === Mailchimp API keys ===

    #[test]
    fn test_detect_mailchimp_api_key() {
        // Build at runtime to avoid GitHub push protection flagging the test fixture
        let key = format!("{}-us14", "abcdef1234567890abcdef1234567890");
        let body = format!(r#"<script>var mc_key = "mailchimp {key}";</script>"#);
        let secrets = detect_exposed_secrets(&body);
        let mc = secrets
            .iter()
            .find(|s| s.secret_type == "mailchimp-api-key");
        assert!(
            mc.is_some(),
            "should detect Mailchimp API key; got {:?}",
            secrets
        );
        assert_eq!(mc.unwrap().severity, SecretSeverity::High);
    }

    // === SendGrid API keys ===

    #[test]
    fn test_detect_sendgrid_api_key() {
        // Build at runtime to avoid GitHub push protection flagging the test fixture
        let key = format!(
            "SG.{}.{}",
            "ngeVfQFYQlKU0ufo8x5d1A", "TwL2iGABf9DHoTf09kqeF8tAmbihYzrnopKc1s5cr3t"
        );
        let body = format!(r#"apiKey: "{key}""#);
        let secrets = detect_exposed_secrets(&body);
        let sg = secrets
            .iter()
            .find(|s| s.secret_type == "sendgrid-api-token");
        assert!(
            sg.is_some(),
            "should detect SendGrid API key; got {:?}",
            secrets
        );
    }

    // === Placeholder filtering ===

    #[test]
    fn test_no_detect_placeholder_password_in_db_uri() {
        let body = r#"mongodb://admin:$PASSWORD@cluster.mongodb.net/db"#;
        let secrets = detect_exposed_secrets(body);
        let db = secrets
            .iter()
            .find(|s| s.secret_type == "database-connection-uri");
        assert!(
            db.is_none(),
            "variable placeholder $PASSWORD should not be flagged; got {:?}",
            secrets
        );
    }

    #[test]
    fn test_no_detect_placeholder_xxx_in_db_uri() {
        let body = r#"postgres://user:xxxxxxxx@db.example.com/app"#;
        let secrets = detect_exposed_secrets(body);
        let db = secrets
            .iter()
            .find(|s| s.secret_type == "database-connection-uri");
        assert!(
            db.is_none(),
            "redacted xxxxxxxx should not be flagged; got {:?}",
            secrets
        );
    }

    #[test]
    fn test_no_detect_placeholder_template_token_in_db_uri() {
        // `<password>` template token between : and @ should be allowlisted.
        let body = r#"<script>db = "mongodb://admin:<password>@cluster.local/db";</script>"#;
        let secrets = detect_exposed_secrets(body);
        let db = secrets
            .iter()
            .find(|s| s.secret_type == "database-connection-uri");
        assert!(
            db.is_none(),
            "<password> template token should be allowlisted; got {:?}",
            secrets
        );
    }

    #[test]
    fn test_no_detect_placeholder_literal_password_in_db_uri() {
        // Literal `password` as the password value should be allowlisted.
        let body = r#"redis://default:password@cache.example.com:6379/0"#;
        let secrets = detect_exposed_secrets(body);
        let db = secrets
            .iter()
            .find(|s| s.secret_type == "database-connection-uri");
        assert!(
            db.is_none(),
            "literal 'password' value should be allowlisted; got {:?}",
            secrets
        );
    }

    #[test]
    fn test_no_detect_placeholder_in_jdbc_connection_string() {
        // JDBC string with <password> template token must be allowlisted.
        let body = "jdbc:mysql://localhost/db?user=admin&password=<password>";
        let secrets = detect_exposed_secrets(body);
        let db = secrets
            .iter()
            .find(|s| s.secret_type == "jdbc-connection-string");
        assert!(
            db.is_none(),
            "<password> in JDBC string should be allowlisted; got {:?}",
            secrets
        );
    }
}