kingfisher-rules 3.2.1

Rule definitions and database for Kingfisher secret scanner
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
//! This module defines rule syntax and evaluation types for secret detection.
//!
//! It provides structures and methods to represent validation configurations,
//! HTTP requests for validation, rule syntax (with support for comment stripping),
//! and associated metadata such as confidence and fingerprints.

use std::{
    borrow::Cow,
    cmp::Ordering,
    collections::{BTreeMap, BTreeSet},
    fmt,
    hash::Hash,
    path::Path,
    str::FromStr,
    sync::{LazyLock, OnceLock},
};

use anyhow::{Context, Result, anyhow};
use liquid::{ParserBuilder, model::Value, object};
use regex::Regex;
use schemars::{JsonSchema, Schema, SchemaGenerator};
use serde::{Deserialize, Serialize};
use tracing::debug;
use xxhash_rust::xxh3::xxh3_64;

use crate::liquid_filters;

/// Returns false as the default value.
fn default_false() -> bool {
    false
}

/// Returns true as the default value.
fn default_true() -> bool {
    true
}

/// TLS certificate validation mode for secret validation requests.
///
/// Controls how TLS certificates are validated when connecting to endpoints
/// during credential validation (e.g., database connections, API calls).
#[derive(
    Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Default,
)]
#[serde(rename_all = "lowercase")]
pub enum TlsMode {
    /// Full WebPKI certificate validation: trusted CA chain, hostname match, not expired.
    /// This is the default and most secure mode.
    #[default]
    Strict,

    /// Permit certificate-verification bypass when both the global policy and
    /// the rule opt into lax mode. Validators configure their own transports;
    /// hostname and expiry checks are not guaranteed in this mode.
    Lax,

    /// Disable all TLS certificate validation. Use with extreme caution.
    Off,
}

/// Represents various types of validation that a rule can perform.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(tag = "type", content = "content")]
pub enum Validation {
    /// Mark a high-signal match as not attempted without performing network validation.
    Assumed,
    AWS,
    AzureStorage,
    Coinbase,
    GCP,
    MongoDB,
    MySQL,
    Postgres,
    Jdbc,
    /// Dispatch a captured credential URI to an HTTPS Basic Auth or database validator.
    ///
    /// Scan rules can provide a named `URI` capture; otherwise `TOKEN` is used. Keeping `TOKEN`
    /// separate lets broad URI detectors report only the embedded password while validation uses
    /// the complete connection string.
    CredentialUri,
    JWT,
    /// Deterministic, network-free Ethereum key-material validation.
    Ethereum(EthereumValidation),
    Raw(String),
    /// A pre-parsed Betterleaks validation expression. The Expr parser is used only by the
    /// snapshot generator; production builds evaluate this portable AST directly.
    Betterleaks(BetterleaksValidation),
    Http(HttpValidation),
    Grpc(GrpcValidation),
}

impl Validation {
    /// Return an inspection copy with literal OAuth2 operator credentials redacted.
    ///
    /// Environment variable names, client IDs and other validation metadata are
    /// preserved. This does not resolve environment variables or mutate the
    /// executable configuration; ordinary `Serialize` remains lossless.
    pub fn redacted_for_inspection(&self) -> Self {
        let mut inspected = self.clone();
        if let Self::Http(http) = &mut inspected {
            redact_http_auth(http);
        }
        inspected
    }
}

fn redact_http_auth(http: &mut HttpValidation) {
    if let Some(auth) = &mut http.auth {
        let credentials = &mut auth.oauth2.ropc;
        for value in
            [&mut credentials.username, &mut credentials.password, &mut credentials.client_secret]
                .into_iter()
                .flatten()
        {
            *value = "[REDACTED]".into();
        }
    }
}

/// A Betterleaks validation expression parsed at snapshot-generation time.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct BetterleaksValidation {
    /// Original Betterleaks expression retained for development-time inspection.
    #[cfg(debug_assertions)]
    #[serde(default)]
    pub source: String,
    #[serde(deserialize_with = "deserialize_betterleaks_expression")]
    pub expression: BetterleaksExpr,
    /// Optional Betterleaks analysis program, evaluated only by explicit access mapping.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_optional_betterleaks_expression"
    )]
    pub analyze: Option<BetterleaksExpr>,
    /// Betterleaks component rule ID to the Kingfisher dependency variable populated at runtime.
    #[serde(default)]
    pub components: BTreeMap<String, String>,
    /// Kingfisher-only operational capabilities joined to this Betterleaks detector at build time.
    #[serde(default)]
    pub capabilities: BetterleaksCapabilities,
}

/// Operational metadata that is intentionally kept separate from Betterleaks detection rules.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Default)]
pub struct BetterleaksCapabilities {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub access_map: Option<BetterleaksAccessMap>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revocation_bindings: Option<BetterleaksRevocationBindings>,
}

/// Access-map collector selected for a Betterleaks detector.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct BetterleaksAccessMap {
    pub handler: BetterleaksAccessMapHandler,
    /// Handler input name to `finding.secret` or `components.<betterleaks-rule-id>`.
    #[serde(default)]
    pub inputs: BTreeMap<String, String>,
    /// Permit access mapping for a reachable 2xx validation response even if it was inconclusive.
    #[serde(default)]
    pub reachable_2xx: bool,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum BetterleaksAccessMapHandler {
    Aws,
    Gcp,
    GcpApiKey,
    AzureClientSecret,
    AzureStorage,
    Algolia,
    Alibaba,
    Artifactory,
    Salesforce,
    Airtable,
    Anthropic,
    Auth0,
    Buildkite,
    Circleci,
    Fastly,
    Github,
    Gitlab,
    Harness,
    Huggingface,
    IbmCloud,
    Monday,
    Openai,
    Paypal,
    Pinecone,
    Sendinblue,
    Stripe,
    WeightsAndBiases,
}

/// Remaps a Betterleaks finding and its components into an existing revocation action.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct BetterleaksRevocationBindings {
    /// Value passed as the positional secret to `kingfisher revoke`.
    #[serde(default = "default_finding_secret_source")]
    pub secret: String,
    /// Revocation template variable to a Betterleaks finding/component source.
    #[serde(default)]
    pub variables: BTreeMap<String, String>,
}

fn default_finding_secret_source() -> String {
    "finding.secret".to_string()
}

/// Portable subset of expr-lang's AST used by Betterleaks validation rules.
///
/// Keeping the parsed representation in the generated rule snapshot means neither Go nor the
/// expr parser is present in a production Kingfisher build.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum BetterleaksExpr {
    Nil,
    Identifier {
        value: String,
    },
    Integer {
        value: i64,
    },
    Float {
        /// Decimal spelling retained from the source to keep this type Eq/Ord/Hash.
        value: String,
    },
    Bool {
        value: bool,
    },
    String {
        value: String,
    },
    Unary {
        operator: String,
        node: Box<BetterleaksExpr>,
    },
    Binary {
        operator: String,
        left: Box<BetterleaksExpr>,
        right: Box<BetterleaksExpr>,
    },
    Chain {
        node: Box<BetterleaksExpr>,
    },
    Member {
        node: Box<BetterleaksExpr>,
        property: Box<BetterleaksExpr>,
        #[serde(default)]
        optional: bool,
        #[serde(default)]
        method: bool,
    },
    Slice {
        node: Box<BetterleaksExpr>,
        from: Box<BetterleaksExpr>,
        to: Box<BetterleaksExpr>,
    },
    Call {
        callee: Box<BetterleaksExpr>,
        #[serde(default)]
        arguments: Vec<BetterleaksExpr>,
    },
    Builtin {
        name: String,
        #[serde(default)]
        arguments: Vec<BetterleaksExpr>,
    },
    Conditional {
        cond: Box<BetterleaksExpr>,
        exp1: Box<BetterleaksExpr>,
        exp2: Box<BetterleaksExpr>,
    },
    VariableDeclarator {
        name: String,
        value: Box<BetterleaksExpr>,
        expr: Box<BetterleaksExpr>,
    },
    Sequence {
        #[serde(default)]
        nodes: Vec<BetterleaksExpr>,
    },
    Array {
        #[serde(default)]
        nodes: Vec<BetterleaksExpr>,
    },
    Map {
        #[serde(default)]
        pairs: Vec<BetterleaksExpr>,
    },
    Pair {
        key: Box<BetterleaksExpr>,
        value: Box<BetterleaksExpr>,
    },
    Predicate {
        node: Box<BetterleaksExpr>,
    },
    Pointer {
        name: String,
    },
}

impl BetterleaksExpr {
    /// Collect literal variable names from `env.get("NAME")` calls in this AST.
    ///
    /// Names retain their spelling and are sorted and deduplicated. This does not read
    /// the environment, evaluate branches, or determine whether an input is mandatory.
    /// Dynamic arguments and `env.getOrDefault` names are not included.
    pub fn env_input_vars(&self) -> BTreeSet<String> {
        let mut vars = BTreeSet::new();
        let mut nodes = vec![self];
        while let Some(node) = nodes.pop() {
            match node {
                Self::Call { callee, arguments } => {
                    if let Self::Member { node, property, .. } = callee.as_ref()
                        && matches!(node.as_ref(), Self::Identifier { value } if value == "env")
                        && matches!(property.as_ref(), Self::String { value } if value == "get")
                        && let [Self::String { value }] = arguments.as_slice()
                    {
                        vars.insert(value.clone());
                    }
                    nodes.push(callee);
                    nodes.extend(arguments);
                }
                Self::Unary { node, .. } | Self::Chain { node } | Self::Predicate { node } => {
                    nodes.push(node);
                }
                Self::Binary { left, right, .. } => {
                    nodes.extend([left.as_ref(), right.as_ref()]);
                }
                Self::Member { node, property, .. } => {
                    nodes.extend([node.as_ref(), property.as_ref()]);
                }
                Self::Slice { node, from, to } => {
                    nodes.extend([node.as_ref(), from.as_ref(), to.as_ref()]);
                }
                Self::Builtin { arguments, .. } => nodes.extend(arguments),
                Self::Conditional { cond, exp1, exp2 } => {
                    nodes.extend([cond.as_ref(), exp1.as_ref(), exp2.as_ref()]);
                }
                Self::VariableDeclarator { value, expr, .. } => {
                    nodes.extend([value.as_ref(), expr.as_ref()]);
                }
                Self::Sequence { nodes: children }
                | Self::Array { nodes: children }
                | Self::Map { pairs: children } => nodes.extend(children),
                Self::Pair { key, value } => {
                    nodes.extend([key.as_ref(), value.as_ref()]);
                }
                Self::Nil
                | Self::Identifier { .. }
                | Self::Integer { .. }
                | Self::Float { .. }
                | Self::Bool { .. }
                | Self::String { .. }
                | Self::Pointer { .. } => {}
            }
        }
        vars
    }
}

/// Ethereum key material that can be validated and mapped to a public address locally.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum EthereumValidation {
    PrivateKey,
    PublicKey,
    Mnemonic,
}

/// Represents revocation actions that a rule can perform.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(tag = "type", content = "content")]
pub enum Revocation {
    AWS,
    GCP,
    /// Explicit Betterleaks revocation program; never evaluated by scanning or validation.
    Betterleaks(BetterleaksValidation),
    Http(#[serde(deserialize_with = "deserialize_http_revocation")] HttpValidation),
    /// Multi-step HTTP revocation (up to 2 steps).
    /// Some services require looking up an ID before deletion.
    HttpMultiStep(HttpMultiStepRevocation),
}

impl Revocation {
    /// Redact literal OAuth2 credentials even in programmatically built actions.
    /// Loading rule files rejects revocation auth; inspection must also be safe
    /// for Rust callers that construct `Revocation::Http` directly.
    pub fn redacted_for_inspection(&self) -> Self {
        let mut inspected = self.clone();
        if let Self::Http(http) = &mut inspected {
            redact_http_auth(http);
        }
        inspected
    }
}

fn deserialize_betterleaks_expression<'de, D>(
    deserializer: D,
) -> std::result::Result<BetterleaksExpr, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Expression {
        Ast(BetterleaksExpr),
        Source(String),
    }

    match Expression::deserialize(deserializer)? {
        Expression::Ast(expression) => Ok(expression),
        Expression::Source(source) => {
            let expression = crate::betterleaks::parse_custom_expression(&source)
                .map_err(serde::de::Error::custom)?;
            serde_json::from_value(expression).map_err(serde::de::Error::custom)
        }
    }
}

fn deserialize_optional_betterleaks_expression<'de, D>(
    deserializer: D,
) -> std::result::Result<Option<BetterleaksExpr>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    struct Expression(
        #[serde(deserialize_with = "deserialize_betterleaks_expression")] BetterleaksExpr,
    );
    Option::<Expression>::deserialize(deserializer).map(|value| value.map(|value| value.0))
}

fn deserialize_http_revocation<'de, D>(
    deserializer: D,
) -> std::result::Result<HttpValidation, D::Error>
where
    D: serde::Deserializer<'de>,
{
    // Ignore auth's contents rather than parse operator credentials for an
    // unsupported action. Even malformed auth must produce a credential-free error.
    #[derive(Deserialize)]
    struct HttpRevocation {
        request: HttpRequest,
        multipart: Option<MultipartConfig>,
        #[serde(default)]
        auth: Option<serde::de::IgnoredAny>,
    }
    let http = HttpRevocation::deserialize(deserializer)?;
    if http.auth.is_some() {
        return Err(serde::de::Error::custom("OAuth2 auth is supported for validation only"));
    }
    Ok(HttpValidation { request: http.request, multipart: http.multipart, auth: None })
}

/// Configuration for multi-step HTTP revocation.
///
/// This allows up to 2 steps where the first step can extract values
/// (e.g., an ID) from its response, which are then used in the second step.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct HttpMultiStepRevocation {
    /// Sequential steps to execute (minimum 1, maximum 2).
    pub steps: Vec<RevocationStep>,
}

/// A single step in a multi-step revocation process.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct RevocationStep {
    /// Human-readable name for this step (e.g., "lookup_id", "delete").
    #[serde(default)]
    pub name: Option<String>,

    /// HTTP request configuration for this step.
    pub request: HttpRequest,

    /// Optional multipart configuration for this step.
    #[serde(default)]
    pub multipart: Option<MultipartConfig>,

    /// Variables to extract from the response for use in subsequent steps.
    /// Keys are variable names (uppercase), values are extraction patterns.
    #[serde(default)]
    pub extract: Option<BTreeMap<String, ResponseExtractor>>,
}

/// Describes how to extract a value from an HTTP response.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(tag = "type")]
pub enum ResponseExtractor {
    /// Extract from JSON response using a JSONPath-like syntax.
    /// Example: `$.data.id` or `$.items[0].token_id`
    JsonPath { path: String },

    /// Extract using a regex pattern with a capture group.
    /// The first capture group is used as the extracted value.
    Regex { pattern: String },

    /// Extract an HTTP response header value.
    Header { name: String },

    /// Extract the entire response body as-is.
    Body,

    /// Extract the HTTP status code as a string.
    StatusCode,
}

/// Specifies that a rule depends on a variable from another rule.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct DependsOnRule {
    /// Try ranked credential candidates against an explicitly supported fixed-endpoint validator.
    /// Endpoint dependencies must never opt in. Defaults to strict association.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub verify_candidates: bool,
    pub rule_id: String,
    pub variable: String,
    /// Whether the dependency may be absent without preventing validation.
    #[serde(default)]
    pub optional: bool,
    /// Betterleaks proximity expression retained for association and parity diagnostics.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub within: Option<String>,
}

/// Specifies character type requirements for matched secrets.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct PatternRequirements {
    /// Minimum number of digits required (0-9)
    #[serde(default)]
    pub min_digits: Option<usize>,
    /// Minimum number of uppercase letters required (A-Z)
    #[serde(default)]
    pub min_uppercase: Option<usize>,
    /// Minimum number of lowercase letters required (a-z)
    #[serde(default)]
    pub min_lowercase: Option<usize>,
    /// Minimum number of special characters required
    #[serde(default)]
    pub min_special_chars: Option<usize>,
    /// Custom set of characters to consider as "special" (defaults to common punctuation)
    #[serde(default)]
    pub special_chars: Option<String>,
    /// Words that should cause the match to be excluded when present (case-insensitive)
    #[serde(default)]
    pub ignore_if_contains: Option<Vec<String>>,
    /// Optional checksum validation configuration.
    #[serde(default)]
    pub checksum: Option<ChecksumRequirement>,
}

/// Defines a checksum validation strategy for a matched pattern.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct ChecksumRequirement {
    /// Template describing how to extract the checksum from the match.
    pub actual: ChecksumActual,
    /// Template describing how to compute the expected checksum.
    pub expected: String,
    /// When true, checksum evaluation is skipped if the required capture is missing.
    #[serde(default)]
    pub skip_if_missing: bool,
}

/// Describes how to extract the checksum value from a match.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct ChecksumActual {
    /// Liquid template used to compute the checksum from the match.
    pub template: String,
    /// Optional capture group that must be present before evaluating the checksum.
    #[serde(default)]
    pub requires_capture: Option<String>,
}

/// Contextual information available when validating pattern requirements.
#[derive(Clone, Copy)]
pub struct PatternRequirementContext<'a> {
    /// Compiled regex associated with the rule.
    pub regex: &'a regex::bytes::Regex,
    /// Captures for the current match.
    pub captures: &'a regex::bytes::Captures<'a>,
    /// Full bytes matched by the rule (capture group 0).
    pub full_match: &'a [u8],
}

impl PatternRequirements {
    /// Default special characters if none are specified
    const DEFAULT_SPECIAL_CHARS: &'static str = "!@#$%^&*()_+-=[]{}|;:'\",.<>?/\\`~";

    /// Validates whether the given byte slice meets the character requirements.
    /// Returns the validation outcome, including whether the match should be ignored
    /// due to `ignore_if_contains` entries when that behaviour is enabled.
    pub fn validate(
        &self,
        input: &[u8],
        context: Option<PatternRequirementContext<'_>>,
        respect_ignore_if_contains: bool,
    ) -> PatternValidationResult {
        // Convert to string (lossy for non-UTF8)
        let s = String::from_utf8_lossy(input);

        // Check digit requirement
        if let Some(min_digits) = self.min_digits {
            let digit_count = s.chars().filter(|c| c.is_ascii_digit()).count();
            if digit_count < min_digits {
                return PatternValidationResult::Failed;
            }
        }

        // Check uppercase requirement
        if let Some(min_uppercase) = self.min_uppercase {
            let uppercase_count = s.chars().filter(|c| c.is_ascii_uppercase()).count();
            if uppercase_count < min_uppercase {
                return PatternValidationResult::Failed;
            }
        }

        // Check lowercase requirement
        if let Some(min_lowercase) = self.min_lowercase {
            let lowercase_count = s.chars().filter(|c| c.is_ascii_lowercase()).count();
            if lowercase_count < min_lowercase {
                return PatternValidationResult::Failed;
            }
        }

        // Check special character requirement
        if let Some(min_special) = self.min_special_chars {
            let special_chars =
                self.special_chars.as_deref().unwrap_or(Self::DEFAULT_SPECIAL_CHARS);
            let special_count = s.chars().filter(|c| special_chars.contains(*c)).count();
            if special_count < min_special {
                return PatternValidationResult::Failed;
            }
        }

        // Check ignore-if-contains requirement
        if respect_ignore_if_contains && let Some(ignore_terms) = self.ignore_if_contains.as_ref() {
            let lowercase_input = s.to_lowercase();
            if let Some(matched_term) = ignore_terms
                .iter()
                .filter_map(|term| {
                    let trimmed = term.trim();
                    if trimmed.is_empty() { None } else { Some((trimmed, trimmed.to_lowercase())) }
                })
                .find_map(|(original, lowered)| {
                    if lowercase_input.contains(&lowered) {
                        Some(original.to_string())
                    } else {
                        None
                    }
                })
            {
                return PatternValidationResult::IgnoredBySubstring { matched_term };
            }
        }

        if let Some(checksum) = &self.checksum {
            let Some(ctx) = context else {
                return if checksum.skip_if_missing {
                    PatternValidationResult::Passed
                } else {
                    PatternValidationResult::Failed
                };
            };

            if let Some(required) = checksum.actual.requires_capture.as_deref()
                && ctx.captures.name(required).is_none()
            {
                return if checksum.skip_if_missing {
                    PatternValidationResult::Passed
                } else {
                    PatternValidationResult::Failed
                };
            }

            let mut globals = object!({
                "MATCH": s.to_string(),
                "FULL_MATCH": String::from_utf8_lossy(ctx.full_match).to_string(),
            });

            for name in ctx.regex.capture_names().flatten() {
                if let Some(capture) = ctx.captures.name(name) {
                    let value = String::from_utf8_lossy(capture.as_bytes()).to_string();
                    globals.insert(name.to_owned().into(), Value::scalar(value.clone()));
                    globals.insert(name.to_ascii_uppercase().into(), Value::scalar(value));
                }
            }

            let actual =
                match render_pattern_requirement_template(&checksum.actual.template, &globals) {
                    Ok(rendered) => rendered,
                    Err(err) => {
                        debug!(
                            "Failed to render checksum actual template '{}': {}",
                            checksum.actual.template, err
                        );
                        return PatternValidationResult::Failed;
                    }
                };
            let expected = match render_pattern_requirement_template(&checksum.expected, &globals) {
                Ok(rendered) => rendered,
                Err(err) => {
                    debug!(
                        "Failed to render checksum expected template '{}': {}",
                        checksum.expected, err
                    );
                    return PatternValidationResult::Failed;
                }
            };

            if actual != expected {
                let actual_len = actual.chars().count();
                let expected_len = expected.chars().count();
                return PatternValidationResult::FailedChecksum { actual_len, expected_len };
            }
        }

        PatternValidationResult::Passed
    }
}

fn render_pattern_requirement_template(
    template: &str,
    globals: &liquid::Object,
) -> Result<String, String> {
    PATTERN_REQUIREMENTS_TEMPLATE_PARSER
        .parse(template)
        .map_err(|e| e.to_string())
        .and_then(|parsed| parsed.render(globals).map_err(|e| e.to_string()))
}

/// Result of validating [`PatternRequirements`] against a potential match.
#[derive(Debug, PartialEq, Eq)]
pub enum PatternValidationResult {
    /// All requirements are satisfied and the match should be kept.
    Passed,
    /// Requirements were not satisfied.
    Failed,
    /// Checksum requirements were not satisfied; captures basic mismatch details for debugging.
    FailedChecksum { actual_len: usize, expected_len: usize },
    /// The match contains one of the `ignore_if_contains` substrings and should be skipped.
    IgnoredBySubstring { matched_term: String },
}

/// Configuration for HTTP validation. This contains a request configuration
/// and an optional multipart configuration.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct HttpValidation {
    pub request: HttpRequest,
    pub multipart: Option<MultipartConfig>,
    /// Authentication for a configured verification service, separate from the candidate secret.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth: Option<Box<HttpValidationAuth>>,
}

/// Maximum additional HTTP environments attempted after the primary.
pub const MAX_HTTP_FALLBACKS: usize = 2;

/// An explicit alternative environment. Validation and revocation reuse are independent opt-ins.
#[derive(Debug, Serialize, Deserialize, PartialEq, PartialOrd, Clone)]
#[serde(deny_unknown_fields)]
pub struct HttpFallback {
    /// Unique environment identifier; `primary` is reserved.
    pub id: String,
    /// False by default. Reuse primary method/auth/headers/body/matchers, not its target URL.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub reuse_primary_validation_logic: bool,
    /// Required replacement URL when reusing validation logic; the primary URL is not inherited.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Complete independent HTTP validation; required unless reuse is explicitly true.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub validation: Option<Validation>,
    /// False by default. Reuse primary action logic, with explicit replacement URL(s).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub reuse_primary_revocation_logic: bool,
    /// Required replacement URL for reused single-request HTTP revocation logic.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revocation_url: Option<String>,
    /// One replacement URL per existing multi-step action step; never alternative mutation targets.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub revocation_urls: Vec<String>,
    /// Independent action. Omission is unavailable unless primary revocation reuse is explicit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revocation: Option<Revocation>,
}

impl HttpFallback {
    fn resolved_revocation<'a>(
        &'a self,
        primary: Option<&Revocation>,
    ) -> Result<Option<Cow<'a, Revocation>>> {
        use anyhow::{bail, ensure};
        if !self.reuse_primary_revocation_logic {
            ensure!(
                self.revocation_url.is_none() && self.revocation_urls.is_empty(),
                "Revocation URL overrides require reuse_primary_revocation_logic: true"
            );
            return Ok(self.revocation.as_ref().map(Cow::Borrowed));
        }
        ensure!(
            self.revocation.is_none(),
            "reuse_primary_revocation_logic: true cannot include revocation"
        );
        let mut action = primary
            .context("reuse_primary_revocation_logic: true requires primary revocation")?
            .clone();
        match &mut action {
            Revocation::Http(http) => {
                ensure!(
                    self.revocation_urls.is_empty(),
                    "Single-request revocation logic reuse requires revocation_url, not revocation_urls"
                );
                http.request.url = self
                    .revocation_url
                    .as_ref()
                    .filter(|url| !url.trim().is_empty())
                    .context(
                        "Single-request revocation logic reuse requires a nonblank revocation_url",
                    )?
                    .clone();
                http.request.fallback_urls.clear();
            }
            Revocation::HttpMultiStep(multi) => {
                ensure!(
                    self.revocation_url.is_none(),
                    "Multi-step revocation logic reuse requires revocation_urls, not revocation_url"
                );
                ensure!(
                    (1..=2).contains(&multi.steps.len())
                        && self.revocation_urls.len() == multi.steps.len()
                        && self.revocation_urls.iter().all(|url| !url.trim().is_empty()),
                    "Multi-step revocation logic reuse requires one nonblank revocation_urls entry per step (one or two steps)"
                );
                for (step, url) in multi.steps.iter_mut().zip(&self.revocation_urls) {
                    step.request.url = url.clone();
                    step.request.fallback_urls.clear();
                }
            }
            _ => bail!(
                "Primary revocation logic reuse supports only HTTP and HTTP multi-step actions"
            ),
        }
        Ok(Some(Cow::Owned(action)))
    }
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(deny_unknown_fields)]
pub struct HttpValidationAuth {
    pub oauth2: OAuth2Config,
}

/// OAuth2 password-grant authentication for an explicitly configured verifier.
/// Values are operator configuration, never templates populated from findings.
#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(deny_unknown_fields)]
pub struct OAuth2Config {
    pub token_endpoint: String,
    #[serde(default = "default_token_header")]
    pub token_header: String,
    pub ropc: OAuth2PasswordCredentials,
}

fn default_token_header() -> String {
    "Authorization".into()
}

#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(deny_unknown_fields)]
pub struct OAuth2PasswordCredentials {
    #[serde(default)]
    pub username: Option<String>,
    #[serde(default)]
    pub username_env: Option<String>,
    #[serde(default)]
    pub password: Option<String>,
    #[serde(default)]
    pub password_env: Option<String>,
    pub client_id: String,
    #[serde(default)]
    pub client_secret: Option<String>,
    #[serde(default)]
    pub client_secret_env: Option<String>,
    #[serde(default)]
    pub scope: Option<String>,
}

impl fmt::Debug for OAuth2Config {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OAuth2Config").finish_non_exhaustive()
    }
}

impl fmt::Debug for OAuth2PasswordCredentials {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OAuth2PasswordCredentials").finish_non_exhaustive()
    }
}

/// Configuration for gRPC validation.
///
/// This is intended for services that are gRPC-only (HTTP/2 + trailers),
/// such as Modal's control plane.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct GrpcValidation {
    pub request: GrpcRequest,
}

/// Configuration for a single gRPC unary request.
///
/// Notes:
/// - `url` should include the full gRPC method path, e.g.
///   `https://api.modal.com/modal.client.ModalClientModal/ContainerHello`
/// - `headers` can include custom auth headers, content-type, etc.
/// - `body` is sent as raw bytes; YAML `\u0000` escapes are supported.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct GrpcRequest {
    pub url: String,
    #[serde(default)]
    pub headers: BTreeMap<String, String>,
    #[serde(default)]
    pub body: Option<String>,
    #[serde(default)]
    pub response_matcher: Option<Vec<ResponseMatcher>>,
}

/// Configuration for an HTTP request used for validation.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(try_from = "HttpRequestDefinition", into = "HttpRequestDefinition")]
pub struct HttpRequest {
    pub method: String,
    /// Primary URL template. YAML also accepts an ordered, nonempty list of URLs.
    pub url: String,
    /// Additional URL templates, attempted in order after `url` for validation.
    /// Revocation selects exactly one URL using the accepted validation endpoint index.
    pub fallback_urls: Vec<String>,
    pub headers: BTreeMap<String, String>,
    pub body: Option<String>,
    pub response_matcher: Option<Vec<ResponseMatcher>>,
    pub multipart: Option<MultipartConfig>,
    // allow HTML only when explicitly set true
    pub response_is_html: bool,
}

impl HttpRequest {
    /// URL templates in their configured order, including the primary URL.
    pub fn urls(&self) -> impl Iterator<Item = &str> {
        std::iter::once(self.url.as_str()).chain(self.fallback_urls.iter().map(String::as_str))
    }
}

#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum HttpRequestUrls {
    Single(String),
    Multiple(Vec<String>),
}

#[derive(Serialize, Deserialize)]
struct HttpRequestDefinition {
    method: String,
    url: HttpRequestUrls,
    #[serde(default)]
    headers: BTreeMap<String, String>,
    #[serde(default)]
    body: Option<String>,
    #[serde(default)]
    response_matcher: Option<Vec<ResponseMatcher>>,
    #[serde(default)]
    multipart: Option<MultipartConfig>,
    #[serde(default = "default_false")]
    response_is_html: bool,
}

impl TryFrom<HttpRequestDefinition> for HttpRequest {
    type Error = &'static str;

    fn try_from(definition: HttpRequestDefinition) -> std::result::Result<Self, Self::Error> {
        let (url, fallback_urls) = match definition.url {
            HttpRequestUrls::Single(url) => (url, Vec::new()),
            HttpRequestUrls::Multiple(mut urls) => {
                if urls.is_empty() {
                    return Err("HTTP url list must contain at least one endpoint");
                }
                if urls.iter().any(|url| url.trim().is_empty()) {
                    return Err("HTTP url list cannot contain an empty endpoint");
                }
                let url = urls.remove(0);
                (url, urls)
            }
        };
        Ok(Self {
            method: definition.method,
            url,
            fallback_urls,
            headers: definition.headers,
            body: definition.body,
            response_matcher: definition.response_matcher,
            multipart: definition.multipart,
            response_is_html: definition.response_is_html,
        })
    }
}

impl From<HttpRequest> for HttpRequestDefinition {
    fn from(request: HttpRequest) -> Self {
        let url = if request.fallback_urls.is_empty() {
            HttpRequestUrls::Single(request.url)
        } else {
            HttpRequestUrls::Multiple(
                std::iter::once(request.url).chain(request.fallback_urls).collect(),
            )
        };
        Self {
            method: request.method,
            url,
            headers: request.headers,
            body: request.body,
            response_matcher: request.response_matcher,
            multipart: request.multipart,
            response_is_html: request.response_is_html,
        }
    }
}

/// Configuration for multipart HTTP requests.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct MultipartConfig {
    pub parts: Vec<MultipartPart>,
}

/// Configuration for a single multipart part.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct MultipartPart {
    pub name: String,
    #[serde(rename = "type")]
    pub part_type: String,
    pub content: String,
    #[serde(default)]
    pub content_type: Option<String>,
}

// ── wrapper with deny_unknown_fields ───────────────────────────
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(deny_unknown_fields)]
pub struct ReportResponseData {
    #[serde(default = "default_true")]
    report_response: bool,
}

/// Describes how to match HTTP responses.
/// This is an untagged enum to allow for different matching strategies.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(untagged)]
pub enum ResponseMatcher {
    WordMatch {
        r#type: String,
        words: Vec<String>,
        #[serde(default = "default_false")]
        match_all_words: bool,
        #[serde(default = "default_false")]
        negative: bool, // true = “fail if the pattern *does* appear”
    },
    StatusMatch {
        r#type: String,
        status: Vec<u16>,
        #[serde(default = "default_false")]
        match_all_status: bool,
        #[serde(default = "default_false")]
        negative: bool, // true = “fail if the status *does* match”
    },
    HeaderMatch {
        r#type: String,        // "HeaderMatch"
        header: String,        // e.g. "content-type"
        expected: Vec<String>, // one or more acceptable tokens
        #[serde(default = "default_false")]
        match_all_values: bool,
    },
    JsonValid {
        // "JsonValid"
        r#type: String,
    },
    XmlValid {
        // "XmlValid"
        r#type: String,
    },
    ReportResponse(ReportResponseData),
}

/// The confidence level associated with a rule.
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, Default)]
pub enum Confidence {
    Low,
    #[default]
    Medium,
    High,
}

impl PartialOrd for Confidence {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Confidence {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self, other) {
            (Confidence::Low, Confidence::Low) => Ordering::Equal,
            (Confidence::Low, _) => Ordering::Less,
            (Confidence::Medium, Confidence::Low) => Ordering::Greater,
            (Confidence::Medium, Confidence::Medium) => Ordering::Equal,
            (Confidence::Medium, Confidence::High) => Ordering::Less,
            (Confidence::High, Confidence::High) => Ordering::Equal,
            (Confidence::High, _) => Ordering::Greater,
        }
    }
}

impl Confidence {
    /// Returns true if the current confidence is at least as high as `other`.
    pub fn is_at_least(&self, other: &Confidence) -> bool {
        self >= other
    }
}

impl fmt::Display for Confidence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Confidence::Low => "low",
            Confidence::Medium => "medium",
            Confidence::High => "high",
        };
        write!(f, "{}", s)
    }
}

impl FromStr for Confidence {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "low" => Ok(Confidence::Low),
            "medium" => Ok(Confidence::Medium),
            "high" => Ok(Confidence::High),
            _ => Err(anyhow!("Invalid confidence level: {}", s)),
        }
    }
}

impl JsonSchema for Confidence {
    fn schema_name() -> Cow<'static, str> {
        "Confidence".into()
    }

    fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
        schemars::json_schema!({
            "enum": ["Low", "Medium", "High"]
        })
    }
}

// Custom serialization/deserialization for case-insensitive handling.
impl Serialize for Confidence {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for Confidence {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.parse().map_err(serde::de::Error::custom)
    }
}

/// The syntactic representation of a rule.
#[derive(Serialize, Deserialize, Debug, PartialEq, PartialOrd, Clone)]
pub struct RuleSyntax {
    /// Human-readable name of the rule.
    pub name: String,
    /// Globally unique identifier for the rule.
    pub id: String,
    /// The regex pattern used by the rule.
    pub pattern: String,
    /// Higher values take precedence when imported Betterleaks findings overlap.
    #[serde(default)]
    pub specificity: i64,
    /// Optional metadata labels retained from custom YAML and Betterleaks TOML.
    #[serde(default)]
    pub tags: Vec<String>,
    /// Case-insensitive candidate keywords; at least one must occur in the source fragment.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub keywords: Vec<String>,
    /// A Betterleaks path-only rule reports its matching path without content matching.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub betterleaks_path_only: bool,
    /// Optional source-path predicate. The content pattern is evaluated only for matching paths.
    #[serde(default)]
    pub path: Option<String>,
    /// Betterleaks expression that returns true when a candidate should be discarded.
    #[serde(default)]
    pub betterleaks_filter: Option<BetterleaksExpr>,
    /// Betterleaks capture-selection semantics.
    ///
    /// `Some(0)` selects the first non-empty capture, while `Some(n)` selects capture `n`.
    /// `None` uses the capture-selection behavior of the Kingfisher rule format.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub betterleaks_secret_group: Option<usize>,
    /// Whether a successful validator may establish that this finding is an active credential.
    #[serde(default = "default_true")]
    pub authoritative: bool,
    /// Legacy v1 matching-engine hint.
    ///
    /// Kingfisher v2 retains this field for custom-rule deserialization compatibility but ignores
    /// its value: every rule uses Vectorscan for candidate detection and is then confirmed by the
    /// exact Rust regex for capture extraction.
    #[serde(default = "default_true")]
    pub vectorscan_compatible: bool,
    /// Minimum Shannon entropy required.
    #[serde(default)]
    pub min_entropy: f32,
    /// Confidence level of the rule.
    #[serde(default)]
    pub confidence: Confidence,
    /// Whether the rule is visible to end-users.
    #[serde(default = "default_true")]
    pub visible: bool,
    /// Example inputs that should match.
    #[serde(default)]
    pub examples: Vec<String>,
    /// Example inputs that should not match.
    #[serde(default)]
    pub negative_examples: Vec<String>,
    /// References (e.g., URLs) for further context.
    #[serde(default)]
    pub references: Vec<String>,
    /// Optional validation configuration.
    #[serde(default)]
    pub validation: Option<Validation>,
    /// Optional revocation configuration.
    #[serde(default)]
    pub revocation: Option<Revocation>,
    /// Optional named HTTP environments; execution requires explicit opt-in.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub fallbacks: Vec<HttpFallback>,
    /// Optional dependencies on other rules.
    #[serde(default)]
    pub depends_on_rule: Vec<Option<DependsOnRule>>,
    /// Optional character type requirements for matched secrets.
    #[serde(default)]
    pub pattern_requirements: Option<PatternRequirements>,
    /// Optional TLS mode for validation connections.
    #[serde(default)]
    pub tls_mode: Option<TlsMode>,
}

/// Regex pattern used to remove vectorscan-style comments from rule patterns.
pub static RULE_COMMENTS_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?m)(\(\?#[^)]*\))|(\s\#[\sa-zA-Z]*$)")
        .expect("comment-stripping regex should compile")
});

static PATTERN_REQUIREMENTS_TEMPLATE_PARSER: LazyLock<liquid::Parser> = LazyLock::new(|| {
    liquid_filters::register_all(ParserBuilder::with_stdlib())
        .build()
        .expect("pattern requirement template parser should compile")
});

impl RuleSyntax {
    /// Inspection copy with literal OAuth2 operator credentials redacted in every environment.
    pub fn redacted_for_inspection(&self) -> Self {
        let mut inspected = self.clone();
        inspected.validation =
            inspected.validation.as_ref().map(Validation::redacted_for_inspection);
        inspected.revocation =
            inspected.revocation.as_ref().map(Revocation::redacted_for_inspection);
        for fallback in &mut inspected.fallbacks {
            fallback.validation =
                fallback.validation.as_ref().map(Validation::redacted_for_inspection);
            fallback.revocation =
                fallback.revocation.as_ref().map(Revocation::redacted_for_inspection);
        }
        inspected
    }

    /// Creates a visible custom rule with no validators, filters, or entropy threshold.
    ///
    /// The pattern is compiled by `RulesDatabase`; construction itself performs no I/O.
    pub fn new(id: impl Into<String>, name: impl Into<String>, pattern: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            pattern: pattern.into(),
            specificity: 0,
            tags: Vec::new(),
            keywords: Vec::new(),
            betterleaks_path_only: false,
            path: None,
            betterleaks_filter: None,
            betterleaks_secret_group: None,
            authoritative: true,
            vectorscan_compatible: true,
            min_entropy: 0.0,
            confidence: Confidence::default(),
            visible: true,
            examples: Vec::new(),
            negative_examples: Vec::new(),
            references: Vec::new(),
            validation: None,
            revocation: None,
            fallbacks: Vec::new(),
            depends_on_rule: Vec::new(),
            pattern_requirements: None,
            tls_mode: None,
        }
    }

    /// Validate only the new optional capability; legacy rules need no migration.
    pub fn check_http_fallbacks(&self) -> Result<()> {
        use anyhow::{bail, ensure};
        if self.fallbacks.is_empty() {
            return Ok(());
        }
        ensure!(
            self.fallbacks.len() <= MAX_HTTP_FALLBACKS,
            "At most two HTTP fallbacks are allowed"
        );
        let Some(Validation::Http(primary)) = &self.validation else {
            bail!("HTTP fallbacks require primary HTTP validation");
        };
        ensure!(
            primary.request.fallback_urls.is_empty(),
            "Do not mix named fallbacks with legacy URL lists"
        );
        let mut ids = std::collections::BTreeSet::new();
        for fallback in &self.fallbacks {
            ensure!(
                !fallback.id.is_empty()
                    && fallback.id != "primary"
                    && fallback
                        .id
                        .bytes()
                        .all(|c| c.is_ascii_alphanumeric() || b"_.-".contains(&c))
                    && ids.insert(&fallback.id),
                "Fallback IDs must be unique, nonempty identifiers other than primary"
            );
            if fallback.reuse_primary_validation_logic {
                ensure!(
                    fallback.validation.is_none(),
                    "reuse_primary_validation_logic: true cannot include validation"
                );
                ensure!(
                    fallback.url.as_ref().is_some_and(|url| !url.trim().is_empty()),
                    "reuse_primary_validation_logic: true requires a nonblank url (only the logic is reused)"
                );
            } else {
                ensure!(
                    fallback.url.is_none(),
                    "Fallback url requires reuse_primary_validation_logic: true"
                );
                let Some(Validation::Http(http)) = &fallback.validation else {
                    bail!(
                        "reuse_primary_validation_logic defaults to false and requires complete HTTP validation"
                    );
                };
                ensure!(
                    http.request.fallback_urls.is_empty() && !http.request.url.trim().is_empty(),
                    "Fallback validation must have one nonblank scalar URL"
                );
                ensure!(
                    http.request.response_matcher.as_ref().is_some_and(|m| !m.is_empty()),
                    "Fallback HTTP validation requires response_matcher"
                );
            }
            if let Some(action) = fallback.resolved_revocation(self.revocation.as_ref())? {
                let requests: Vec<_> = match action.as_ref() {
                    Revocation::Http(http) => vec![&http.request],
                    Revocation::HttpMultiStep(multi) => {
                        ensure!(
                            (1..=2).contains(&multi.steps.len()),
                            "Fallback revocation requires one or two steps"
                        );
                        multi.steps.iter().map(|step| &step.request).collect()
                    }
                    _ => bail!("Fallback revocation must be HTTP or HTTP multi-step"),
                };
                ensure!(
                    requests.iter().all(|r| r.fallback_urls.is_empty()),
                    "Named fallback revocation must use scalar URLs"
                );
                ensure!(
                    requests.last().is_some_and(|r| r
                        .response_matcher
                        .as_ref()
                        .is_some_and(|m| !m.is_empty())),
                    "Fallback revocation requires a final response_matcher"
                );
            }
        }
        Ok(())
    }

    /// Resolve HTTP configurations without rendering templates or performing I/O.
    /// The primary is always first. Disabled alternatives impose no input requirements.
    pub fn http_validations(&self, enabled: bool) -> Result<Vec<(Option<&str>, HttpValidation)>> {
        self.check_http_fallbacks()?;
        let Some(Validation::Http(primary)) = &self.validation else { return Ok(Vec::new()) };
        let mut first = primary.clone();
        first.request.fallback_urls.clear();
        let mut configurations = vec![(None, first)];
        if !enabled {
            return Ok(configurations);
        }
        if self.fallbacks.is_empty() {
            // Legacy lists must remain loadable and must still try the primary
            // when alternatives are enabled. Keep the same bounded execution
            // policy as named fallbacks instead of rejecting the whole rule.
            if primary.request.fallback_urls.len() > MAX_HTTP_FALLBACKS {
                static WARN_LEGACY_URL_LIMIT: std::sync::Once = std::sync::Once::new();
                WARN_LEGACY_URL_LIMIT.call_once(|| {
                    tracing::warn!("HTTP validation uses only the first three URLs in legacy URL lists (primary and two fallbacks); additional URLs are ignored");
                });
            }
            for url in primary.request.fallback_urls.iter().take(MAX_HTTP_FALLBACKS) {
                let mut http = primary.clone();
                http.request.url = url.clone();
                http.request.fallback_urls.clear();
                configurations.push((None, http));
            }
        } else {
            for fallback in &self.fallbacks {
                let mut http = if fallback.reuse_primary_validation_logic {
                    primary.clone()
                } else if let Some(Validation::Http(http)) = &fallback.validation {
                    http.clone()
                } else {
                    unreachable!("checked HTTP fallback")
                };
                if fallback.reuse_primary_validation_logic {
                    http.request.url = fallback.url.clone().expect("checked fallback URL");
                }
                configurations.push((Some(fallback.id.as_str()), http));
            }
        }
        Ok(configurations)
    }

    /// Select one environment's action. Primary revocation is reused only on explicit opt-in.
    pub fn selected_revocation(
        &self,
        fallback_id: Option<&str>,
    ) -> Result<Option<Cow<'_, Revocation>>> {
        match fallback_id {
            None => Ok(self.revocation.as_ref().map(Cow::Borrowed)),
            Some(id) => self
                .fallbacks
                .iter()
                .find(|fallback| fallback.id == id)
                .ok_or_else(|| anyhow!("Unknown validated fallback ID"))?
                .resolved_revocation(self.revocation.as_ref()),
        }
    }

    /// Maximum allowed regex size.
    const REGEX_SIZE_LIMIT: usize = 16 * 1024 * 1024;

    /// Returns the rule pattern with comments removed.
    pub fn uncommented_pattern(&self) -> Cow<'_, str> {
        RULE_COMMENTS_PATTERN.replace_all(&self.pattern, "")
    }

    /// Helper to build a regex from a pattern string.
    fn build_regex(pattern: &str) -> Result<regex::bytes::Regex> {
        regex::bytes::RegexBuilder::new(pattern)
            .unicode(false)
            .size_limit(Self::REGEX_SIZE_LIMIT)
            .build()
            .context("Failed to build regex")
    }

    /// Compile the rule pattern into a regex.
    pub fn as_regex(&self) -> Result<regex::bytes::Regex> {
        Self::build_regex(&self.uncommented_pattern())
    }

    /// Return whether this rule is eligible for the supplied source path.
    pub fn matches_path(&self, path: &str) -> bool {
        self.path
            .as_deref()
            .is_none_or(|pattern| Regex::new(pattern).is_ok_and(|regex| regex.is_match(path)))
    }

    /// Return the imported Betterleaks filter expression, if present.
    pub fn betterleaks_filter(&self) -> Option<&BetterleaksExpr> {
        self.betterleaks_filter.as_ref()
    }

    /// Return the Betterleaks capture selector, if this is an imported Betterleaks rule.
    pub fn betterleaks_secret_group(&self) -> Option<usize> {
        self.betterleaks_secret_group
    }

    /// Whether validation may authoritatively classify this rule as active.
    pub fn is_authoritative(&self) -> bool {
        self.authoritative
    }

    /// Return whether Vectorscan is used as the rule's candidate prefilter.
    pub fn vectorscan_compatible(&self) -> bool {
        true
    }

    /// Compile the rule pattern into an anchored regex (matching end-of-input).
    ///
    /// # Example
    ///
    /// ```
    /// # use kingfisher_rules::RuleSyntax;
    /// let r = RuleSyntax {
    ///     name: "Test rule".to_string(),
    ///     id: "test.1".to_string(),
    ///     pattern: r"hello\s*world".to_string(),
    ///     specificity: 0,
    ///     tags: vec![],
    ///     keywords: vec![],
    ///     betterleaks_path_only: false,
    ///     path: None,
    ///     betterleaks_filter: None,
    ///     betterleaks_secret_group: None,
    ///     vectorscan_compatible: true,
    ///     fallbacks: Vec::new(),
    ///     examples: vec![],
    ///     negative_examples: vec![],
    ///     references: vec![],
    ///     min_entropy: 0.0,
    ///     confidence: Default::default(),
    ///     visible: true,
    ///     validation: None,
    ///     revocation: None,
    ///     depends_on_rule: vec![],
    ///     pattern_requirements: None,
    ///     tls_mode: None,
    ///     authoritative: true,
    /// };
    /// assert_eq!(r.as_anchored_regex().unwrap().as_str(), r"hello\s*world$");
    /// ```
    pub fn as_anchored_regex(&self) -> Result<regex::bytes::Regex> {
        Self::build_regex(&format!("{}$", self.uncommented_pattern()))
    }

    /// Compile a regex constrained to the actual end of a candidate window.
    /// Grouping preserves alternatives; `\z` remains exact in multiline mode.
    pub fn as_endpoint_regex(&self) -> Result<regex::bytes::Regex> {
        Self::build_regex(&format!(r"(?:{})\z", self.uncommented_pattern()))
    }

    /// Computes a content-based fingerprint of the rule's pattern.
    pub fn finding_sha1_fingerprint(&self) -> String {
        let hash = xxh3_64(self.pattern.as_bytes());
        format!("{:x}", hash)
    }

    /// Serializes the rule syntax to JSON.
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).expect("Serialization of rule syntax should succeed")
    }

    /// Loads rule syntax definitions from a YAML file.
    pub fn from_yaml_file<P: AsRef<Path>>(path: P) -> Result<Vec<Self>> {
        let path = path.as_ref();
        let contents = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read file: {}", path.display()))?;
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum RuleSyntaxDocument {
            Sequence(Vec<RuleSyntax>),
            Mapped { rules: Vec<RuleSyntax> },
        }

        let parsed: RuleSyntaxDocument = yaml_serde::from_str(&contents).map_err(|e| {
            let context = e.location().map_or(String::new(), |loc| {
                format!(" at line {} column {}", loc.line(), loc.column())
            });
            anyhow!("Failed to parse YAML from {}{}: {}", path.display(), context, e)
        })?;

        Ok(match parsed {
            RuleSyntaxDocument::Sequence(rules) => rules,
            RuleSyntaxDocument::Mapped { rules } => rules,
        })
    }
}

/// A rule combines its syntactic definition with computed metadata.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Rule {
    pub syntax: RuleSyntax,
    finding_sha1_fingerprint: String,
    min_entropy: f32,
    visible: bool,
    #[serde(skip, default = "default_runtime_minimum_confidence")]
    runtime_minimum_confidence: Confidence,
    #[serde(skip)]
    runtime_dependency_helper: bool,
    /// Original runtime and syntax visibility while a static helper threshold hides this rule.
    #[serde(skip)]
    runtime_helper_visibility: Option<(bool, bool)>,
    #[serde(skip)]
    path_regex: OnceLock<(String, Option<Regex>)>,
    #[serde(skip)]
    keyword_regex: OnceLock<(Vec<String>, Option<regex::bytes::Regex>)>,
}

impl PartialEq for Rule {
    fn eq(&self, other: &Self) -> bool {
        self.syntax == other.syntax
            && self.finding_sha1_fingerprint == other.finding_sha1_fingerprint
            && self.min_entropy == other.min_entropy
            && self.visible == other.visible
            && self.runtime_minimum_confidence == other.runtime_minimum_confidence
            && self.runtime_dependency_helper == other.runtime_dependency_helper
            && self.runtime_helper_visibility == other.runtime_helper_visibility
    }
}

fn default_runtime_minimum_confidence() -> Confidence {
    Confidence::Low
}

impl Rule {
    /// Constructs a new rule from its syntax.
    pub fn new(syntax: RuleSyntax) -> Self {
        Self {
            finding_sha1_fingerprint: syntax.finding_sha1_fingerprint(),
            min_entropy: syntax.min_entropy,
            visible: syntax.visible,
            runtime_minimum_confidence: Confidence::Low,
            runtime_dependency_helper: false,
            runtime_helper_visibility: None,
            path_regex: OnceLock::new(),
            keyword_regex: OnceLock::new(),
            syntax,
        }
    }

    /// Returns a reference to the rule's syntax.
    pub fn syntax(&self) -> &RuleSyntax {
        &self.syntax
    }

    /// Return whether this source fragment meets the rule's optional keyword gate.
    pub fn matches_keywords(&self, bytes: &[u8]) -> bool {
        // Most captures contain their own provider keyword. Keep that short check
        // cheap; searching a whole source byte by byte for every candidate is not.
        if bytes.len() <= 256 || self.syntax.keywords.is_empty() {
            return self.matches_keywords_uncached(bytes);
        }
        let (keywords, ascii_regex) = self.keyword_regex.get_or_init(|| {
            let patterns = self
                .syntax
                .keywords
                .iter()
                .filter(|keyword| keyword.is_ascii())
                .map(|keyword| regex::escape(keyword))
                .collect::<Vec<_>>();
            let compiled = (!patterns.is_empty())
                .then(|| {
                    regex::bytes::RegexBuilder::new(&patterns.join("|"))
                        .case_insensitive(true)
                        .unicode(false)
                        .build()
                        .ok()
                })
                .flatten();
            (self.syntax.keywords.clone(), compiled)
        });
        if keywords == &self.syntax.keywords
            && let Some(regex) = ascii_regex
        {
            // Preserve the existing Unicode lowercase/lossy-UTF-8 semantics rather
            // than letting regex Unicode folding widen ASCII-only keyword matches.
            return regex.is_match(bytes)
                || keywords.iter().filter(|keyword| !keyword.is_ascii()).any(|keyword| {
                    String::from_utf8_lossy(bytes).to_lowercase().contains(&keyword.to_lowercase())
                });
        }
        // Public syntax can change after the cache is initialized. Compilation
        // limits and mutated keywords must retain the original matching behavior.
        self.matches_keywords_uncached(bytes)
    }

    fn matches_keywords_uncached(&self, bytes: &[u8]) -> bool {
        self.syntax.keywords.is_empty()
            || self.syntax.keywords.iter().any(|keyword| {
                if keyword.is_empty() {
                    return true;
                }
                if keyword.is_ascii() {
                    bytes
                        .windows(keyword.len())
                        .any(|window| window.eq_ignore_ascii_case(keyword.as_bytes()))
                } else {
                    String::from_utf8_lossy(bytes).to_lowercase().contains(&keyword.to_lowercase())
                }
            })
    }

    /// Returns the JSON representation of the rule's syntax.
    pub fn json_syntax(&self) -> String {
        self.syntax.to_json()
    }

    /// Returns the rule's computed fingerprint.
    pub fn finding_sha1_fingerprint(&self) -> &str {
        &self.finding_sha1_fingerprint
    }

    /// Returns the human-readable name of the rule.
    pub fn name(&self) -> &str {
        &self.syntax.name
    }

    /// Returns the unique identifier of the rule.
    pub fn id(&self) -> &str {
        &self.syntax.id
    }

    /// Returns the rule's minimum entropy requirement.
    pub fn min_entropy(&self) -> f32 {
        self.min_entropy
    }

    /// Updates the rule's minimum entropy value.
    ///
    /// Returns an error if the new value is negative.
    pub fn set_entropy(&mut self, new_entropy: f32) -> Result<()> {
        if new_entropy < 0.0 {
            return Err(anyhow!("Entropy value cannot be negative"));
        }
        self.min_entropy = new_entropy;
        self.syntax.min_entropy = new_entropy;
        Ok(())
    }

    /// Returns whether the rule is visible.
    pub fn visible(&self) -> bool {
        self.visible
    }

    /// Returns the confidence level of the rule.
    pub fn confidence(&self) -> Confidence {
        self.syntax.confidence
    }

    /// Configure a static confidence threshold after rule selection has resolved helpers.
    ///
    /// Helper-only hiding is reversed when reconfigured; explicit reporting suppression is not.
    pub fn set_runtime_confidence_filter(
        &mut self,
        minimum_confidence: Confidence,
        dependency_helper: bool,
    ) {
        if let Some((visible, syntax_visible)) = self.runtime_helper_visibility.take() {
            self.visible = visible;
            self.syntax.visible = syntax_visible;
        }
        self.runtime_minimum_confidence = minimum_confidence;
        self.runtime_dependency_helper = dependency_helper;
        if dependency_helper && !self.confidence().is_at_least(&minimum_confidence) {
            self.runtime_helper_visibility = Some((self.visible, self.syntax.visible));
            self.visible = false;
            self.syntax.visible = false;
        }
    }

    /// Compatibility wrapper using only the rule's configured confidence.
    ///
    /// The supplied legacy effective confidence is ignored.
    #[deprecated(
        note = "Confidence is static; use confidence(), runtime_minimum_confidence(), and is_runtime_dependency_helper()"
    )]
    pub fn accepts_effective_confidence(&self, _confidence: Confidence) -> bool {
        self.runtime_dependency_helper
            || self.confidence().is_at_least(&self.runtime_minimum_confidence)
    }

    /// Compatibility wrapper using only the rule's configured reporting threshold.
    ///
    /// The supplied legacy effective confidence is ignored.
    #[deprecated(
        note = "Confidence is static; compare confidence() with runtime_minimum_confidence()"
    )]
    pub fn reports_effective_confidence(&self, _confidence: Confidence) -> bool {
        self.confidence().is_at_least(&self.runtime_minimum_confidence)
    }

    /// Return whether this rule was included to support another selected rule.
    pub fn is_runtime_dependency_helper(&self) -> bool {
        self.runtime_dependency_helper
    }

    /// Return the scan-time minimum confidence configured by the rule loader.
    pub fn runtime_minimum_confidence(&self) -> Confidence {
        self.runtime_minimum_confidence
    }

    /// Permanently keep a match available for association without reporting it as a finding.
    pub fn suppress_runtime_reporting(&mut self) {
        self.runtime_helper_visibility = None;
        self.visible = false;
        self.syntax.visible = false;
    }

    /// Returns the character requirements for this rule, if any.
    pub fn pattern_requirements(&self) -> Option<&PatternRequirements> {
        self.syntax.pattern_requirements.as_ref()
    }

    /// Return whether this rule is eligible for the supplied source path.
    pub fn matches_path(&self, path: &str) -> bool {
        let Some(pattern) = self.syntax.path.as_deref() else {
            return true;
        };
        let (cached_pattern, regex) =
            self.path_regex.get_or_init(|| (pattern.to_owned(), Regex::new(pattern).ok()));
        if cached_pattern != pattern {
            // Syntax is public and can be changed after the cache is initialized.
            // Preserve that behavior rather than using a stale compiled restriction.
            return self.syntax.matches_path(path);
        }
        regex.as_ref().is_some_and(|regex| regex.is_match(path))
    }

    /// Return the imported Betterleaks filter expression, if present.
    pub fn betterleaks_filter(&self) -> Option<&BetterleaksExpr> {
        self.syntax.betterleaks_filter()
    }

    /// Return the Betterleaks capture selector, if this is an imported Betterleaks rule.
    pub fn betterleaks_secret_group(&self) -> Option<usize> {
        self.syntax.betterleaks_secret_group()
    }

    /// Return whether Vectorscan is used as the rule's candidate prefilter.
    pub fn vectorscan_compatible(&self) -> bool {
        self.syntax.vectorscan_compatible()
    }

    /// Returns the TLS mode for this rule, if specified.
    pub fn tls_mode(&self) -> Option<TlsMode> {
        self.syntax.tls_mode
    }
}

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

    #[test]
    #[allow(deprecated, reason = "the compatibility wrappers must remain callable")]
    fn legacy_confidence_wrappers_use_only_configured_confidence() {
        for configured in [Confidence::Low, Confidence::Medium, Confidence::High] {
            let mut syntax = RuleSyntax::new("acme.static", "Static confidence fixture", "token");
            syntax.confidence = configured;
            let mut rule = Rule::new(syntax);
            rule.set_runtime_confidence_filter(Confidence::Medium, false);
            for legacy in [Confidence::Low, Confidence::Medium, Confidence::High] {
                let selected = configured.is_at_least(&Confidence::Medium);
                assert_eq!(rule.accepts_effective_confidence(legacy), selected);
                assert_eq!(rule.reports_effective_confidence(legacy), selected);
                assert_eq!(rule.confidence(), configured);
            }
        }
    }

    #[test]
    fn below_threshold_helpers_are_hidden_without_changing_configured_confidence() {
        let mut syntax = RuleSyntax::new("acme.helper", "Helper fixture", "token");
        syntax.confidence = Confidence::Low;
        let mut rule = Rule::new(syntax);
        rule.set_runtime_confidence_filter(Confidence::Medium, true);
        assert_eq!(rule.confidence(), Confidence::Low);
        assert_eq!(rule.runtime_minimum_confidence(), Confidence::Medium);
        assert!(rule.is_runtime_dependency_helper());
        assert!(!rule.visible());
        assert!(!rule.syntax().visible);
        assert!(!rule.confidence().is_at_least(&rule.runtime_minimum_confidence()));
        assert_eq!(rule.clone(), rule);
    }

    #[test]
    fn reportable_helpers_keep_their_configured_visibility() {
        for visible in [false, true] {
            let mut syntax = RuleSyntax::new("acme.helper", "Helper fixture", "token");
            syntax.confidence = Confidence::High;
            syntax.visible = visible;
            let mut rule = Rule::new(syntax);
            rule.set_runtime_confidence_filter(Confidence::High, true);
            assert_eq!(rule.visible(), visible);
            assert_eq!(rule.syntax().visible, visible);
            assert_eq!(rule.confidence(), Confidence::High);
            assert!(rule.confidence().is_at_least(&rule.runtime_minimum_confidence()));
        }
    }

    #[test]
    fn helper_reconfiguration_restores_both_original_visibility_flags() {
        for visible in [false, true] {
            for syntax_visible in [false, true] {
                let mut syntax = RuleSyntax::new("acme.helper", "Helper fixture", "token");
                syntax.confidence = Confidence::Low;
                syntax.visible = visible;
                let mut original = Rule::new(syntax);
                original.syntax.visible = syntax_visible;
                for (minimum, helper) in
                    [(Confidence::Low, false), (Confidence::Low, true), (Confidence::High, false)]
                {
                    let mut rule = original.clone();
                    rule.set_runtime_confidence_filter(Confidence::High, true);
                    assert!(!rule.visible());
                    assert!(!rule.syntax().visible);
                    rule.set_runtime_confidence_filter(minimum, helper);
                    assert_eq!(rule.visible(), visible);
                    assert_eq!(rule.syntax().visible, syntax_visible);
                    assert_eq!(rule.confidence(), Confidence::Low);
                    assert_eq!(rule.runtime_minimum_confidence(), minimum);
                    assert_eq!(rule.is_runtime_dependency_helper(), helper);
                    assert!(rule.runtime_helper_visibility.is_none());
                }
            }
        }
    }

    #[test]
    fn repeated_helper_configuration_preserves_original_visibility() {
        let mut syntax = RuleSyntax::new("acme.helper", "Helper fixture", "token");
        syntax.confidence = Confidence::Low;
        let mut rule = Rule::new(syntax);
        let original = rule.clone();
        for minimum in [Confidence::High, Confidence::Medium, Confidence::Medium, Confidence::High]
        {
            rule.set_runtime_confidence_filter(minimum, true);
            assert!(!rule.visible());
            assert!(!rule.syntax().visible);
        }
        rule.set_runtime_confidence_filter(Confidence::Low, false);
        assert_eq!(rule, original);
        assert!(rule.visible());
        assert!(rule.syntax().visible);
    }

    #[test]
    fn permanent_suppression_survives_helper_reconfiguration() {
        for helper_first in [false, true] {
            let mut syntax = RuleSyntax::new("acme.helper", "Helper fixture", "token");
            syntax.confidence = Confidence::Low;
            let mut rule = Rule::new(syntax);
            if helper_first {
                rule.set_runtime_confidence_filter(Confidence::High, true);
            }
            rule.suppress_runtime_reporting();
            assert!(rule.runtime_helper_visibility.is_none());
            for (minimum, helper) in
                [(Confidence::Low, false), (Confidence::High, true), (Confidence::Low, false)]
            {
                rule.set_runtime_confidence_filter(minimum, helper);
                assert!(!rule.visible());
                assert!(!rule.syntax().visible);
            }
        }
    }

    #[test]
    fn cloned_hidden_helpers_restore_visibility_independently() {
        let mut syntax = RuleSyntax::new("acme.helper", "Helper fixture", "token");
        syntax.confidence = Confidence::Low;
        let mut rule = Rule::new(syntax);
        rule.set_runtime_confidence_filter(Confidence::High, true);
        let mut cloned = rule.clone();
        assert_eq!(rule, cloned);
        cloned.set_runtime_confidence_filter(Confidence::Low, false);
        assert!(cloned.visible());
        assert!(cloned.syntax().visible);
        assert!(!rule.visible());
        assert!(!rule.syntax().visible);
        assert!(rule.is_runtime_dependency_helper());
        cloned.suppress_runtime_reporting();
        rule.set_runtime_confidence_filter(Confidence::Low, false);
        assert!(rule.visible());
        assert!(rule.syntax().visible);
        assert!(!cloned.visible());
        assert!(!cloned.syntax().visible);
    }

    #[test]
    fn helper_visibility_snapshot_affects_equality_but_not_serialization() {
        let mut syntax = RuleSyntax::new("acme.helper", "Helper fixture", "token");
        syntax.confidence = Confidence::Low;
        let original = Rule::new(syntax);
        assert!(original.runtime_helper_visibility.is_none());
        let mut temporary = original.clone();
        temporary.set_runtime_confidence_filter(Confidence::High, true);
        let mut permanent = original.clone();
        permanent.suppress_runtime_reporting();
        permanent.set_runtime_confidence_filter(Confidence::High, true);
        assert_eq!(temporary.syntax(), permanent.syntax());
        assert_eq!(temporary.visible(), permanent.visible());
        assert_ne!(temporary, permanent);
        let serialized = serde_json::to_value(&temporary).unwrap();
        assert_eq!(serialized, serde_json::to_value(&permanent).unwrap());
        assert!(serialized.get("runtime_helper_visibility").is_none());
        let mut restored: Rule = serde_json::from_value(serialized).unwrap();
        assert!(restored.runtime_helper_visibility.is_none());
        let mut expected = original;
        expected.suppress_runtime_reporting();
        assert_eq!(restored, expected);
        restored.set_runtime_confidence_filter(Confidence::Low, false);
        assert!(!restored.visible());
        assert!(!restored.syntax().visible);
    }

    #[test]
    fn runtime_path_regex_is_cached_without_changing_serialization_or_equality() {
        let mut syntax = RuleSyntax::new("acme.path", "Path fixture", "token");
        syntax.path = Some(r"(?i)\.pem$".into());
        let rule = Rule::new(syntax);
        let cold = rule.clone();
        let serialized = serde_json::to_value(&rule).unwrap();
        assert!(rule.path_regex.get().is_none());
        for _ in 0..1000 {
            assert!(rule.matches_path("private.PEM"));
            assert!(!rule.matches_path("source.rs"));
        }
        let (pattern, compiled) = rule.path_regex.get().expect("path regex was cached");
        assert_eq!(pattern, r"(?i)\.pem$");
        assert!(compiled.is_some());
        assert_eq!(rule, cold);
        assert_eq!(rule, rule.clone());
        assert_eq!(serde_json::to_value(&rule).unwrap(), serialized);
        let restored: Rule = serde_json::from_value(serialized).unwrap();
        assert_eq!(rule, restored);
        assert!(restored.path_regex.get().is_none());
        assert!(restored.matches_path("private.pem"));
    }

    #[test]
    fn runtime_path_cache_preserves_invalid_and_mutated_path_restrictions() {
        let mut rule = Rule::new(RuleSyntax::new("acme.path", "Path fixture", "token"));
        assert!(rule.matches_path("anywhere"));
        assert!(rule.path_regex.get().is_none());
        rule.syntax.path = Some("[".into());
        assert!(!rule.matches_path("anywhere"));
        assert!(!rule.matches_path("another"));
        assert!(rule.path_regex.get().unwrap().1.is_none());
        rule.syntax.path = Some(r"\.key$".into());
        assert!(rule.matches_path("private.key"));
        assert!(!rule.matches_path("source.rs"));
        rule.syntax.path = None;
        assert!(rule.matches_path("anywhere"));
    }

    #[test]
    fn candidate_keywords_support_ascii_and_unicode_case_folding() {
        let mut syntax = RuleSyntax::new("acme.keyword", "Keyword", "token");
        assert!(Rule::new(syntax.clone()).matches_keywords(b""));
        syntax.keywords = vec!["Provider".into(), "CAFÉ".into()];
        let rule = Rule::new(syntax);
        assert!(rule.matches_keywords(b"pRoViDeR"));
        assert!(rule.matches_keywords("café".as_bytes()));
        assert!(!rule.matches_keywords(b"unrelated"));
    }

    #[test]
    fn large_source_keyword_search_preserves_literal_and_case_folding_semantics() {
        for keywords in [
            vec!["Provider", "CAFÉ"],
            vec!["[literal]+.*", "k"],
            vec!["�", "ASCII"],
            vec![""],
            vec!["CAFÉ"],
        ] {
            let mut syntax = RuleSyntax::new("acme.keyword", "Keyword", "token");
            syntax.keywords = keywords.into_iter().map(str::to_owned).collect();
            let rule = Rule::new(syntax);
            for value in [
                b"pRoViDeR".as_slice(),
                "café".as_bytes(),
                b"[LITERAL]+.*",
                b"LITERALxxxxx",
                "K".as_bytes(),
                b"\xffASCII",
                b"\xff",
                b"unrelated",
            ] {
                let bytes = [vec![b' '; 4096], value.to_vec()].concat();
                assert_eq!(rule.matches_keywords(&bytes), rule.matches_keywords_uncached(&bytes));
            }
        }
    }

    #[test]
    fn runtime_keyword_cache_preserves_serialization_equality_and_mutated_keywords() {
        let mut syntax = RuleSyntax::new("acme.keyword", "Keyword", "token");
        syntax.keywords = vec!["provider".into()];
        let mut rule = Rule::new(syntax);
        let cold = rule.clone();
        let serialized = serde_json::to_value(&rule).unwrap();
        let bytes = [vec![b' '; 4096], b"PROVIDER".to_vec()].concat();
        assert!(rule.matches_keywords(&bytes));
        assert!(rule.keyword_regex.get().unwrap().1.is_some());
        assert_eq!(rule, cold);
        assert_eq!(rule, rule.clone());
        assert_eq!(serde_json::to_value(&rule).unwrap(), serialized);
        let restored: Rule = serde_json::from_value(serialized).unwrap();
        assert!(restored.keyword_regex.get().is_none());
        assert!(restored.matches_keywords(&bytes));
        rule.syntax.keywords = vec!["replacement".into()];
        assert!(!rule.matches_keywords(&bytes));
        let replacement = [vec![b' '; 4096], b"REPLACEMENT".to_vec()].concat();
        assert!(rule.matches_keywords(&replacement));
        rule.syntax.keywords.clear();
        assert!(rule.matches_keywords(&bytes));
    }

    #[test]
    fn betterleaks_env_inputs_collect_only_literal_get_calls() {
        let program: BetterleaksValidation = serde_json::from_value(serde_json::json!({
            "expression": r#"
                let dynamic = "DYNAMIC";
                [env.get("Z_ADMIN"), env.get("A_ID"), env.get("Z_ADMIN"),
                 env.get(dynamic), env.get("COMPUTED" + "_NAME"),
                 env.getOrDefault("OPTIONAL", "fallback"), other.get("OTHER"),
                 "env.get(\"STRING_ONLY\")", false ? env.get("BRANCH_INPUT") : ""]
            "#,
            "analyze": "env.get('ANALYZE_ONLY')"
        }))
        .unwrap();
        assert_eq!(
            program.expression.env_input_vars().into_iter().collect::<Vec<_>>(),
            ["A_ID", "BRANCH_INPUT", "Z_ADMIN"]
        );
    }

    #[test]
    fn betterleaks_env_inputs_traverse_nested_expression_nodes() {
        let cases: &[(&str, &[&str])] = &[
            (
                "let admin = env.get('LET'); !env.get('UNARY') && (env.get('COND') ? env.get('YES') : env.get('NO'))",
                &["COND", "LET", "NO", "UNARY", "YES"],
            ),
            ("{'entry': [env.get('ARRAY')]}[env.get('MEMBER')]", &["ARRAY", "MEMBER"]),
            ("env.get('NODE')[env.get('FROM'):env.get('TO')]", &["FROM", "NODE", "TO"]),
            ("map([1], env.get('PREDICATE'))", &["PREDICATE"]),
            ("http.get(env.get('CALL_ARGUMENT'))", &["CALL_ARGUMENT"]),
            ("env.get(env.get('DYNAMIC_ARGUMENT'))", &["DYNAMIC_ARGUMENT"]),
            ("env.get('CHAIN')?.field", &["CHAIN"]),
        ];
        for (source, expected) in cases {
            let program: BetterleaksValidation =
                serde_json::from_value(serde_json::json!({"expression": source})).unwrap();
            assert_eq!(
                program.expression.env_input_vars().into_iter().collect::<Vec<_>>(),
                *expected,
                "{source}"
            );
        }
    }

    #[test]
    fn custom_yaml_betterleaks_programs_accept_source_and_round_trip_as_ast() {
        let yaml = r#"
type: Betterleaks
content:
  expression: 'let r = http.get("https://example.invalid"); r.status == 200 ? {"result": "valid"} : validate.unknown(r)'
  analyze: 'analysis.capabilities({"read": true})'
"#;
        let validation: Validation = yaml_serde::from_str(yaml).unwrap();
        let Validation::Betterleaks(program) = &validation else { panic!("wrong validator") };
        assert!(matches!(program.expression, BetterleaksExpr::VariableDeclarator { .. }));
        assert!(program.analyze.is_some());
        let ast_yaml = yaml_serde::to_string(&validation).unwrap();
        assert_eq!(yaml_serde::from_str::<Validation>(&ast_yaml).unwrap(), validation);
        let revocation: Revocation = yaml_serde::from_str("type: Betterleaks\ncontent:\n  expression: 'let r = http.delete(\"https://example.invalid\"); r.status == 204 ? {\"result\": \"revoked\"} : revoke.unknown(r)'\n").unwrap();
        assert!(matches!(revocation, Revocation::Betterleaks(_)));
        assert!(
            yaml_serde::from_str::<Validation>(
                "type: Betterleaks\ncontent:\n  expression: 'let broken ='\n"
            )
            .is_err()
        );
    }

    #[test]
    fn http_url_strings_and_fallback_lists_round_trip_without_changing_other_request_fields() {
        for url in [
            serde_json::json!("https://primary.example/identity"),
            serde_json::json!([
                "https://primary.example/identity",
                "https://secondary.example/identity",
                "{{ THIRD_ENDPOINT }}/identity"
            ]),
        ] {
            let definition = serde_json::json!({
                "method": "POST", "url": url,
                "headers": {"Authorization": "Bearer {{ TOKEN }}"},
                "body": "{{ TOKEN }}", "multipart": null,
                "response_matcher": [{"type": "StatusMatch", "status": [200],
                    "match_all_status": false, "negative": false}],
                "response_is_html": true
            });
            let request: HttpRequest = serde_json::from_value(definition.clone()).unwrap();
            assert_eq!(serde_json::to_value(&request).unwrap(), definition);
            let yaml = yaml_serde::to_string(&request).unwrap();
            assert_eq!(yaml_serde::from_str::<HttpRequest>(&yaml).unwrap(), request);
        }
    }

    #[test]
    fn http_url_lists_reject_empty_non_string_and_blank_endpoints() {
        for url in [
            serde_json::json!([]),
            serde_json::json!(["https://primary.example", "  "]),
            serde_json::json!(["https://primary.example", 42]),
        ] {
            assert!(
                serde_json::from_value::<HttpRequest>(serde_json::json!({
                    "method": "GET", "url": url
                }))
                .is_err()
            );
        }
    }

    #[test]
    fn http_url_list_with_one_endpoint_preserves_scalar_request_behavior() {
        let request: HttpRequest =
            yaml_serde::from_str("method: GET\nurl:\n  - https://primary.example/identity\n")
                .unwrap();
        assert_eq!(request.url, "https://primary.example/identity");
        assert!(request.fallback_urls.is_empty());
        assert_eq!(request.urls().collect::<Vec<_>>(), ["https://primary.example/identity"]);
        assert!(serde_json::to_value(&request).unwrap()["url"].is_string());
    }
    use regex::bytes::Regex as BytesRegex;

    #[test]
    fn http_revocation_rejects_oauth2_auth_during_deserialization() {
        let password = "operator-password-secret";
        let client_secret = "operator-client-secret";
        for auth in [
            serde_json::json!({"oauth2": {
                "token_endpoint": "https://idp.example.com/token",
                "ropc": {"username": "operator", "password": password,
                         "client_id": "scanner", "client_secret": client_secret}
            }}),
            // Malformed auth must be rejected without reporting any of its values.
            serde_json::json!({"oauth2": {"ropc": {
                "password": [password], "client_secret": {"secret": client_secret}
            }}}),
        ] {
            let definition = serde_json::json!({"type": "Http", "content": {
                "auth": auth,
                "request": {"method": "DELETE", "url": "https://api.example.com/token",
                    "response_matcher": [{"type": "StatusMatch", "status": [204]}]}
            }});
            let json_error = serde_json::from_value::<Revocation>(definition.clone()).unwrap_err();
            let yaml = yaml_serde::to_string(&definition).unwrap();
            let yaml_error = yaml_serde::from_str::<Revocation>(&yaml).unwrap_err();
            for error in [json_error.to_string(), yaml_error.to_string()] {
                assert!(error.contains("OAuth2 auth is supported for validation only"));
                assert!(!error.contains(password));
                assert!(!error.contains(client_secret));
            }
            let document = serde_json::json!({"rules": [{
                "id": "acme.revocation-auth", "name": "Revocation auth fixture",
                "pattern": "(synthetic-secret)", "revocation": definition
            }]});
            let yaml = yaml_serde::to_string(&document).unwrap();
            let error = crate::Rules::from_paths_and_contents(
                [(Path::new("revocation-auth.yml"), yaml.as_bytes())],
                Confidence::Low,
            )
            .err()
            .expect("unsupported auth must fail during rule loading");
            assert!(!error.to_string().contains(password));
            assert!(!error.to_string().contains(client_secret));
        }
    }

    #[test]
    fn supported_revocation_definitions_preserve_defaults_and_round_trip() {
        for definition in [
            serde_json::json!({"type": "AWS"}),
            serde_json::json!({"type": "GCP"}),
            serde_json::json!({"type": "Http", "content": {
                "request": {"method": "DELETE", "url": "https://api.example.com/token"}
            }}),
            serde_json::json!({"type": "Http", "content": {
                "auth": null,
                "request": {"method": "DELETE", "url": "https://api.example.com/token"}
            }}),
            serde_json::json!({"type": "HttpMultiStep", "content": {"steps": [{
                "request": {"method": "DELETE", "url": "https://api.example.com/token"}
            }]}}),
        ] {
            let revocation: Revocation = serde_json::from_value(definition).unwrap();
            let serialized = serde_json::to_value(&revocation).unwrap();
            assert_eq!(serde_json::from_value::<Revocation>(serialized).unwrap(), revocation);
            let yaml = yaml_serde::to_string(&revocation).unwrap();
            assert_eq!(yaml_serde::from_str::<Revocation>(&yaml).unwrap(), revocation);
            if let Revocation::Http(http) = revocation {
                assert!(http.auth.is_none());
                assert!(http.multipart.is_none());
                assert!(http.request.headers.is_empty());
                assert!(!http.request.response_is_html);
            }
        }
    }

    #[test]
    fn oauth2_inspection_redacts_literals_without_changing_lossless_serialization() {
        for credentials in [
            serde_json::json!({"username": "operator-user-secret", "password": "operator-password-secret",
                "client_id": "scanner", "client_secret": "operator-client-secret"}),
            serde_json::json!({"username_env": "KF_OPERATOR_USERNAME", "password_env": "KF_OPERATOR_PASSWORD",
                "client_id": "scanner", "client_secret_env": "KF_OPERATOR_CLIENT_SECRET"}),
        ] {
            let validation: Validation = serde_json::from_value(serde_json::json!({
                "type": "Http", "content": {
                    "auth": {"oauth2": {"token_endpoint": "https://idp.example.com/token", "ropc": credentials}},
                    "request": {"method": "GET", "url": "https://verifier.example.com/verify"}
                }
            })).unwrap();
            let original = serde_json::to_value(&validation).unwrap();
            let inspected = validation.redacted_for_inspection();
            let redacted = serde_json::to_value(&inspected).unwrap();
            let credentials = &redacted["content"]["auth"]["oauth2"]["ropc"];
            for field in ["username", "password", "client_secret"] {
                let expected = if original["content"]["auth"]["oauth2"]["ropc"][field].is_null() {
                    serde_json::Value::Null
                } else {
                    serde_json::json!("[REDACTED]")
                };
                assert_eq!(credentials[field], expected);
            }
            for field in ["username_env", "password_env", "client_secret_env", "client_id", "scope"]
            {
                assert_eq!(
                    credentials[field],
                    original["content"]["auth"]["oauth2"]["ropc"][field]
                );
            }
            assert_eq!(redacted["content"]["auth"]["oauth2"]["token_header"], "Authorization");
            assert_eq!(serde_json::to_value(&validation).unwrap(), original);
            assert_eq!(serde_json::from_value::<Validation>(original).unwrap(), validation);
        }
    }

    #[test]
    fn test_pattern_requirements_digits() {
        let reqs = PatternRequirements {
            min_digits: Some(2),
            min_uppercase: None,
            min_lowercase: None,
            min_special_chars: None,
            special_chars: None,
            ignore_if_contains: None,
            checksum: None,
        };

        // Should pass: has 3 digits
        assert!(matches!(reqs.validate(b"abc123def", None, true), PatternValidationResult::Passed));

        // Should fail: only 1 digit
        assert!(matches!(reqs.validate(b"abc1def", None, true), PatternValidationResult::Failed));

        // Should fail: no digits
        assert!(matches!(reqs.validate(b"abcdef", None, true), PatternValidationResult::Failed));
    }

    #[test]
    fn test_pattern_requirements_checksum() {
        let reqs = PatternRequirements {
            min_digits: None,
            min_uppercase: None,
            min_lowercase: None,
            min_special_chars: None,
            special_chars: None,
            ignore_if_contains: None,
            checksum: Some(ChecksumRequirement {
                actual: ChecksumActual {
                    template: "{{ MATCH | suffix: 6 }}".to_string(),
                    requires_capture: Some("checksum".to_string()),
                },
                expected: "{{ BODY | crc32 | base62: 6 }}".to_string(),
                skip_if_missing: true,
            }),
        };

        let token = b"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";
        let regex =
            BytesRegex::new(r"(?x) ghp_(?P<body>[A-Za-z0-9]{30})(?P<checksum>[A-Za-z0-9]{6})")
                .unwrap();
        let captures = regex.captures(token).expect("token should match");
        assert!(matches!(
            reqs.validate(
                token,
                Some(PatternRequirementContext {
                    regex: &regex,
                    captures: &captures,
                    full_match: token
                }),
                true
            ),
            PatternValidationResult::Passed
        ));

        let mut invalid = token.to_vec();
        *invalid.last_mut().unwrap() = b'0';
        let captures_invalid =
            regex.captures(&invalid).expect("invalid token should still match pattern");
        assert!(matches!(
            reqs.validate(
                &invalid,
                Some(PatternRequirementContext {
                    regex: &regex,
                    captures: &captures_invalid,
                    full_match: &invalid,
                }),
                true
            ),
            PatternValidationResult::FailedChecksum { .. }
        ));

        let legacy = b"ghp_legacy_token";
        assert!(matches!(reqs.validate(legacy, None, true), PatternValidationResult::Passed));
    }

    #[test]
    fn test_pattern_requirements_uppercase() {
        let reqs = PatternRequirements {
            min_digits: None,
            min_uppercase: Some(2),
            min_lowercase: None,
            min_special_chars: None,
            special_chars: None,
            ignore_if_contains: None,
            checksum: None,
        };

        // Should pass: has 3 uppercase
        assert!(matches!(reqs.validate(b"ABCdef", None, true), PatternValidationResult::Passed));

        // Should fail: only 1 uppercase
        assert!(matches!(reqs.validate(b"Adef", None, true), PatternValidationResult::Failed));

        // Should fail: no uppercase
        assert!(matches!(reqs.validate(b"abcdef", None, true), PatternValidationResult::Failed));
    }

    #[test]
    fn test_pattern_requirements_lowercase() {
        let reqs = PatternRequirements {
            min_digits: None,
            min_uppercase: None,
            min_lowercase: Some(2),
            min_special_chars: None,
            special_chars: None,
            ignore_if_contains: None,
            checksum: None,
        };

        // Should pass: has 3 lowercase
        assert!(matches!(reqs.validate(b"ABCdef", None, true), PatternValidationResult::Passed));

        // Should fail: only 1 lowercase
        assert!(matches!(reqs.validate(b"ABCd", None, true), PatternValidationResult::Failed));

        // Should fail: no lowercase
        assert!(matches!(reqs.validate(b"ABC123", None, true), PatternValidationResult::Failed));
    }

    #[test]
    fn test_pattern_requirements_special_chars() {
        let reqs = PatternRequirements {
            min_digits: None,
            min_uppercase: None,
            min_lowercase: None,
            min_special_chars: Some(2),
            special_chars: None, // uses default
            ignore_if_contains: None,
            checksum: None,
        };

        // Should pass: has 2 special chars
        assert!(matches!(reqs.validate(b"abc!@def", None, true), PatternValidationResult::Passed));

        // Should fail: only 1 special char
        assert!(matches!(reqs.validate(b"abc!def", None, true), PatternValidationResult::Failed));

        // Should fail: no special chars
        assert!(matches!(reqs.validate(b"abcdef", None, true), PatternValidationResult::Failed));
    }

    #[test]
    fn test_pattern_requirements_custom_special_chars() {
        let reqs = PatternRequirements {
            min_digits: None,
            min_uppercase: None,
            min_lowercase: None,
            min_special_chars: Some(2),
            special_chars: Some("$%^".to_string()),
            ignore_if_contains: None,
            checksum: None,
        };

        // Should pass: has 2 custom special chars
        assert!(matches!(reqs.validate(b"abc$%def", None, true), PatternValidationResult::Passed));

        // Should fail: has special chars but not the custom ones
        assert!(matches!(reqs.validate(b"abc!@def", None, true), PatternValidationResult::Failed));

        // Should fail: only 1 custom special char
        assert!(matches!(reqs.validate(b"abc$def", None, true), PatternValidationResult::Failed));
    }

    #[test]
    fn test_pattern_requirements_combined() {
        let reqs = PatternRequirements {
            min_digits: Some(1),
            min_uppercase: Some(1),
            min_lowercase: Some(1),
            min_special_chars: Some(1),
            special_chars: None,
            ignore_if_contains: None,
            checksum: None,
        };

        // Should pass: has all requirements
        assert!(matches!(reqs.validate(b"Abc1!", None, true), PatternValidationResult::Passed));

        // Should fail: missing digit
        assert!(matches!(reqs.validate(b"Abc!", None, true), PatternValidationResult::Failed));

        // Should fail: missing uppercase
        assert!(matches!(reqs.validate(b"abc1!", None, true), PatternValidationResult::Failed));

        // Should fail: missing lowercase
        assert!(matches!(reqs.validate(b"ABC1!", None, true), PatternValidationResult::Failed));

        // Should fail: missing special
        assert!(matches!(reqs.validate(b"Abc1", None, true), PatternValidationResult::Failed));
    }

    #[test]
    fn test_pattern_requirements_ignore_if_contains() {
        let reqs = PatternRequirements {
            min_digits: None,
            min_uppercase: None,
            min_lowercase: None,
            min_special_chars: None,
            special_chars: None,
            ignore_if_contains: Some(vec!["test".to_string(), "Demo".to_string()]),
            checksum: None,
        };

        // Should fail: contains "test" (case-insensitive)
        assert!(matches!(
            reqs.validate(b"MyTestToken", None, true),
            PatternValidationResult::IgnoredBySubstring { .. }
        ));

        // Should fail: contains "demo" (case-insensitive)
        assert!(matches!(
            reqs.validate(b"example-demo-value", None, true),
            PatternValidationResult::IgnoredBySubstring { .. }
        ));

        // Should pass: does not contain excluded words
        assert!(matches!(
            reqs.validate(b"example-value", None, true),
            PatternValidationResult::Passed
        ));
    }

    #[test]
    fn test_pattern_requirements_ignore_if_contains_ignores_empty_entries() {
        let reqs = PatternRequirements {
            min_digits: None,
            min_uppercase: None,
            min_lowercase: None,
            min_special_chars: None,
            special_chars: None,
            ignore_if_contains: Some(vec![" ".to_string(), "".to_string(), "BLOCK".to_string()]),
            checksum: None,
        };

        // Should fail only when non-empty exclusion matches
        assert!(matches!(
            reqs.validate(b"needs-blocking", None, true),
            PatternValidationResult::IgnoredBySubstring { .. }
        ));
        assert!(matches!(reqs.validate(b"allowed", None, true), PatternValidationResult::Passed));
    }

    #[test]
    fn test_pattern_requirements_ignore_if_contains_can_be_disabled() {
        let reqs = PatternRequirements {
            min_digits: None,
            min_uppercase: None,
            min_lowercase: None,
            min_special_chars: None,
            special_chars: None,
            ignore_if_contains: Some(vec!["ignoreme".to_string()]),
            checksum: None,
        };

        // With ignoring enabled, the match is skipped
        assert!(matches!(
            reqs.validate(b"value-ignoreme", None, true),
            PatternValidationResult::IgnoredBySubstring { .. }
        ));

        // With ignoring disabled, the same input passes requirements
        assert!(matches!(
            reqs.validate(b"value-ignoreme", None, false),
            PatternValidationResult::Passed
        ));
    }

    #[test]
    fn test_pattern_requirements_none() {
        let reqs = PatternRequirements {
            min_digits: None,
            min_uppercase: None,
            min_lowercase: None,
            min_special_chars: None,
            special_chars: None,
            ignore_if_contains: None,
            checksum: None,
        };

        // Should pass: no requirements
        assert!(matches!(reqs.validate(b"anything", None, true), PatternValidationResult::Passed));
        assert!(matches!(reqs.validate(b"123", None, true), PatternValidationResult::Passed));
        assert!(matches!(reqs.validate(b"!@#", None, true), PatternValidationResult::Passed));
    }
}