kingfisher-bin 2.8.0

MongoDB's blazingly fast and accurate secret scanning and validation tool
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
use std::{
    collections::{BTreeMap, BTreeSet},
    fmt::Write,
    path::PathBuf,
    sync::{Arc, Mutex},
};

use anyhow::Result;
use chrono::{Local, Utc};
#[cfg(test)]
use http::StatusCode;
use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode};
use schemars::JsonSchema;
use serde::Serialize;
use url::Url;

use kingfisher_scanner::validation::http_validation::is_auto_provided_request_var;

use crate::{
    access_map::{
        AccessSummary, AccessTokenDetails, PermissionSummary, ProviderMetadata, ResourceExposure,
        RoleBinding,
    },
    alerts::AlertAccessMapEntry,
    blob::BlobMetadata,
    bstring_escape::Escaped,
    cli,
    cli::global::GlobalArgs,
    finding_data, findings_store,
    matcher::{Match, compute_finding_fingerprint},
    origin::{Origin, OriginSet},
    rules::Revocation,
    rules::rule::Confidence,
    template_vars::extract_template_vars,
    validation_body::{self, ValidationResponseBody},
};
mod bson_format;
mod html_format;
mod json_format;
mod pretty_format;
mod sarif_format;
pub mod styles;
mod toon_format;
use std::io::IsTerminal;

use styles::{StyledObject, Styles};

use crate::{
    cli::commands::output::ReportOutputFormat,
    location::SourceSpan,
    origin::{GitRepoOrigin, get_repo_url},
};

/// Shell-escape a string for safe command-line usage using single quotes.
fn escape_for_shell(s: &str) -> String {
    format!("'{}'", s.replace('\'', "'\\''"))
}

fn display_rule_id(rule_id: &str) -> String {
    rule_id
        .strip_prefix("betterleaks.")
        .or_else(|| rule_id.strip_prefix("veles."))
        .unwrap_or(rule_id)
        .to_string()
}

fn finding_title(rule_id: &str) -> String {
    format!("{} => [{}]", display_rule_id(rule_id).to_uppercase(), rule_id.to_uppercase())
}

fn required_vars_for_validation(validation: &crate::rules::Validation) -> BTreeSet<String> {
    use crate::rules::Validation;
    let mut vars = BTreeSet::new();

    match validation {
        Validation::Assumed => {}
        Validation::Ethereum(_) => {
            vars.insert("TOKEN".to_string());
        }
        Validation::Http(http) => {
            vars.extend(extract_template_vars(&http.request.url));
            for (k, v) in &http.request.headers {
                vars.extend(extract_template_vars(k));
                vars.extend(extract_template_vars(v));
            }
            if let Some(body) = &http.request.body {
                vars.extend(extract_template_vars(body));
            }
        }
        Validation::Grpc(grpc) => {
            vars.extend(extract_template_vars(&grpc.request.url));
            for (k, v) in &grpc.request.headers {
                vars.extend(extract_template_vars(k));
                vars.extend(extract_template_vars(v));
            }
            if let Some(body) = &grpc.request.body {
                vars.extend(extract_template_vars(body));
            }
        }
        Validation::Betterleaks(validation) => {
            vars.insert("TOKEN".to_string());
            vars.extend(validation.components.values().cloned());
        }
        Validation::AWS => {
            vars.insert("AKID".to_string());
            vars.insert("TOKEN".to_string());
        }
        Validation::GCP => {
            vars.insert("TOKEN".to_string());
        }
        Validation::MongoDB
        | Validation::MySQL
        | Validation::Postgres
        | Validation::Jdbc
        | Validation::CredentialUri
        | Validation::JWT => {
            vars.insert("TOKEN".to_string());
        }
        Validation::AzureStorage => {
            vars.insert("TOKEN".to_string());
            vars.insert("AZURENAME".to_string());
        }
        Validation::Coinbase => {
            vars.insert("TOKEN".to_string());
            vars.insert("CRED_NAME".to_string());
        }
        Validation::Raw(raw) => {
            vars.extend(kingfisher_scanner::validation::raw::required_vars(raw));
        }
    }

    vars.retain(|var| !is_auto_provided_request_var(var));

    vars
}

fn is_sensitive_arg_key(key: &str) -> bool {
    let normalized = key.trim_start_matches('-').to_ascii_lowercase();
    let exact = [
        "arg",
        "var",
        "token",
        "secret",
        "password",
        "pass",
        "key",
        "api-key",
        "apikey",
        "auth",
        "oauth-token",
        "pat",
        "credential",
        "credentials",
    ];
    if exact.iter().any(|candidate| *candidate == normalized) {
        return true;
    }

    let contains =
        ["token", "secret", "password", "apikey", "api-key", "auth", "credential", "webhook"];
    contains.iter().any(|candidate| normalized.contains(candidate))
}

fn sanitize_command_line_args(args: &[String]) -> Vec<String> {
    let mut sanitized = Vec::with_capacity(args.len());
    let mut redact_next = false;

    for arg in args {
        if redact_next {
            sanitized.push("***REDACTED***".to_string());
            redact_next = false;
            continue;
        }

        let Some(stripped) = arg.strip_prefix('-') else {
            sanitized.push(arg.clone());
            continue;
        };

        if stripped.is_empty() {
            sanitized.push(arg.clone());
            continue;
        }

        let key_value_split = arg.split_once('=');
        if let Some((key, _)) = key_value_split {
            if is_sensitive_arg_key(key) {
                sanitized.push(format!("{key}=***REDACTED***"));
            } else {
                sanitized.push(arg.clone());
            }
            continue;
        }

        if is_sensitive_arg_key(arg) {
            sanitized.push(arg.clone());
            redact_next = true;
            continue;
        }

        sanitized.push(arg.clone());
    }

    sanitized
}

fn format_validation_response(validation_body: &str, redact: bool, full_response: bool) -> String {
    if redact {
        // Validation errors can include a rendered request URL, whose query
        // string may contain the finding's secret. Redact the entire body so
        // report formats cannot expose it through an error path.
        return crate::util::redact_value(validation_body);
    }

    if full_response {
        return validation_body.to_string();
    }

    const MAX_RESPONSE_LENGTH: usize = 512;
    let mut chars = validation_body.chars();
    let truncated_body: String = chars.by_ref().take(MAX_RESPONSE_LENGTH).collect();
    let ellipsis = if chars.next().is_some() { "..." } else { "" };
    format!("{truncated_body}{ellipsis}")
}

fn required_vars_for_revocation(revocation: &Revocation) -> BTreeSet<String> {
    let mut vars = BTreeSet::new();

    match revocation {
        Revocation::AWS => {
            vars.insert("AKID".to_string());
            vars.insert("TOKEN".to_string());
        }
        Revocation::GCP => {
            vars.insert("TOKEN".to_string());
        }
        Revocation::Http(http) => {
            vars.extend(extract_template_vars(&http.request.url));
            for (k, v) in &http.request.headers {
                vars.extend(extract_template_vars(k));
                vars.extend(extract_template_vars(v));
            }
            if let Some(body) = &http.request.body {
                vars.extend(extract_template_vars(body));
            }
        }
        Revocation::HttpMultiStep(multi) => {
            for step in &multi.steps {
                vars.extend(extract_template_vars(&step.request.url));
                for (k, v) in &step.request.headers {
                    vars.extend(extract_template_vars(k));
                    vars.extend(extract_template_vars(v));
                }
                if let Some(body) = &step.request.body {
                    vars.extend(extract_template_vars(body));
                }
            }
        }
    }

    vars
}

/// Build the --var arguments string from dependent captures, but only for variables that are
/// required by the validation/revocation templates.
fn build_var_args(
    dependent_captures: &std::collections::BTreeMap<String, String>,
    akid_from_captures: Option<&str>,
    akid_from_validation_body: Option<&str>,
    required_vars: &BTreeSet<String>,
) -> String {
    let mut var_args = Vec::new();

    // Add AKID if available (for AWS)
    let dependent_akid_is_present =
        dependent_captures.get("AKID").is_some_and(|value| !value.is_empty());
    if let Some(akid) = akid_from_captures.or(akid_from_validation_body)
        && !akid.is_empty()
        && required_vars.contains("AKID")
        && !dependent_akid_is_present
    {
        var_args.push(format!("--var AKID={}", escape_for_shell(akid)));
    }

    // Add dependent captures only when required by the templates.
    // This avoids generating commands like `--var BODY=...` for tokens whose named captures
    // are just internal parsing aids (e.g., checksum payloads).
    for (name, value) in dependent_captures {
        let name_upper = name.to_ascii_uppercase();
        if required_vars.contains(&name_upper)
            && !name.eq_ignore_ascii_case("TOKEN")
            && !value.is_empty()
        {
            var_args.push(format!("--var {}={}", name, escape_for_shell(value)));
        }
    }

    if var_args.is_empty() { String::new() } else { format!("{} ", var_args.join(" ")) }
}

/// Build rule-loading flags for a direct command emitted from a scan result.
fn build_rule_loading_args(rules_path: &[PathBuf], load_builtins: bool) -> Option<String> {
    let mut args = rules_path
        .iter()
        .map(|path| path.to_str().map(|path| format!("--rules-path {}", escape_for_shell(path))))
        .collect::<Option<Vec<_>>>()?;
    if !load_builtins {
        args.push("--no-builtins".to_string());
    }

    Some(if args.is_empty() { String::new() } else { format!("{} ", args.join(" ")) })
}

/// Generate a kingfisher revoke command for an active credential if the rule supports revocation.
///
/// Returns `None` if:
/// - The credential is not active
/// - The rule doesn't have revocation configured
/// - Required data (like AWS AKID) cannot be determined
fn build_revoke_command(
    rule_id: &str,
    revocation: &Revocation,
    snippet: &str,
    dependent_captures: &std::collections::BTreeMap<String, String>,
    akid_from_captures: Option<&str>,
    akid_from_validation_body: Option<&str>,
) -> Option<String> {
    let required_vars = required_vars_for_revocation(revocation);

    let var_args = build_var_args(
        dependent_captures,
        akid_from_captures,
        akid_from_validation_body,
        &required_vars,
    );

    match revocation {
        Revocation::AWS => {
            // AWS needs the access key ID (AKID) in addition to the secret
            // Try to get it from captures first, then from validation response body
            let akid = dependent_captures
                .get("AKID")
                .map(String::as_str)
                .or(akid_from_captures)
                .or(akid_from_validation_body)?;
            if akid.is_empty() {
                return None;
            }
            Some(format!(
                "kingfisher revoke --rule {} {}{}",
                escape_for_shell(rule_id),
                var_args,
                escape_for_shell(snippet)
            ))
        }
        Revocation::GCP => {
            // GCP revocation uses the service account JSON key (which is the snippet)
            Some(format!(
                "kingfisher revoke --rule {} {}{}",
                escape_for_shell(rule_id),
                var_args,
                escape_for_shell(snippet)
            ))
        }
        Revocation::Http(_) => {
            // HTTP-based revocation with dependent variables
            Some(format!(
                "kingfisher revoke --rule {} {}{}",
                escape_for_shell(rule_id),
                var_args,
                escape_for_shell(snippet)
            ))
        }
        Revocation::HttpMultiStep(_) => {
            // Multi-step HTTP revocation with dependent variables
            Some(format!(
                "kingfisher revoke --rule {} {}{}",
                escape_for_shell(rule_id),
                var_args,
                escape_for_shell(snippet)
            ))
        }
    }
}

fn resolve_betterleaks_capability_source<'a>(
    source: &str,
    finding_secret: &'a str,
    validation: &crate::rules::BetterleaksValidation,
    dependent_captures: &'a BTreeMap<String, String>,
) -> Option<&'a str> {
    if source == "finding.secret" {
        return Some(finding_secret);
    }
    let component_id = source.strip_prefix("components.")?;
    let variable = validation.components.get(component_id)?;
    dependent_captures.get(variable).map(String::as_str)
}

/// Generate a kingfisher validate command for a finding.
///
/// Returns `None` if the rule doesn't have validation configured or required data is missing.
fn build_validate_command(
    rule_id: &str,
    validation: &crate::rules::Validation,
    snippet: &str,
    dependent_captures: &std::collections::BTreeMap<String, String>,
    akid_from_captures: Option<&str>,
    akid_from_validation_body: Option<&str>,
) -> Option<String> {
    use crate::rules::Validation;

    let mut required_vars = required_vars_for_validation(validation);
    let is_aws_session_token = matches!(validation, Validation::AWS)
        && dependent_captures.get("AWS_SECRET_ACCESS_KEY").is_some_and(|value| !value.is_empty());
    if is_aws_session_token {
        required_vars.insert("AWS_SECRET_ACCESS_KEY".to_string());
    }

    let var_args = build_var_args(
        dependent_captures,
        akid_from_captures,
        akid_from_validation_body,
        &required_vars,
    );

    match validation {
        Validation::Assumed => None,
        Validation::AWS => {
            // AWS needs the access key ID (AKID) in addition to the secret
            dependent_captures
                .get("AKID")
                .map(String::as_str)
                .filter(|value| !value.is_empty())
                .or(akid_from_captures.filter(|value| !value.is_empty()))
                .or(akid_from_validation_body.filter(|value| !value.is_empty()))?;
            Some(format!(
                "kingfisher validate --rule {} {}{}",
                escape_for_shell(rule_id),
                var_args,
                escape_for_shell(snippet)
            ))
        }
        Validation::GCP | Validation::Ethereum(_) => {
            // Both validators use the captured token directly.
            Some(format!(
                "kingfisher validate --rule {} {}{}",
                escape_for_shell(rule_id),
                var_args,
                escape_for_shell(snippet)
            ))
        }
        Validation::Betterleaks(_) => Some(format!(
            "kingfisher validate --rule {} {}{}",
            escape_for_shell(rule_id),
            var_args,
            escape_for_shell(snippet)
        )),
        Validation::Http(_) => {
            // HTTP-based validation with dependent variables
            Some(format!(
                "kingfisher validate --rule {} {}{}",
                escape_for_shell(rule_id),
                var_args,
                escape_for_shell(snippet)
            ))
        }
        Validation::Grpc(_) => {
            // gRPC-based validation with dependent variables
            Some(format!(
                "kingfisher validate --rule {} {}{}",
                escape_for_shell(rule_id),
                var_args,
                escape_for_shell(snippet)
            ))
        }
        Validation::CredentialUri => {
            let uri = dependent_captures
                .get("URI")
                .map(String::as_str)
                .filter(|uri| !uri.is_empty())
                .unwrap_or(snippet);
            Some(format!(
                "kingfisher validate --rule {} {}{}",
                escape_for_shell(rule_id),
                var_args,
                escape_for_shell(uri)
            ))
        }
        Validation::MongoDB
        | Validation::MySQL
        | Validation::Postgres
        | Validation::Jdbc
        | Validation::JWT
        | Validation::AzureStorage
        | Validation::Coinbase
        | Validation::Raw(_) => {
            // These validators with dependent variables
            Some(format!(
                "kingfisher validate --rule {} {}{}",
                escape_for_shell(rule_id),
                var_args,
                escape_for_shell(snippet)
            ))
        }
    }
}

struct BlastRadiusCommandContext<'a> {
    dependent_captures: &'a BTreeMap<String, String>,
    akid_from_captures: Option<&'a str>,
    akid_from_validation_body: Option<&'a str>,
    rules_path: &'a [PathBuf],
    load_builtins: bool,
}

/// Generate a direct blast-radius command when the finding can be mapped by a known handler.
fn build_blast_radius_command(
    rule_id: &str,
    validation: &crate::rules::Validation,
    is_aws_session_token: bool,
    snippet: &str,
    context: &BlastRadiusCommandContext<'_>,
) -> Option<String> {
    use crate::rules::Validation;

    let BlastRadiusCommandContext {
        dependent_captures,
        akid_from_captures,
        akid_from_validation_body,
        rules_path,
        load_builtins,
    } = context;

    let mut required_vars = BTreeSet::new();
    let command_secret = match validation {
        Validation::CredentialUri => {
            let uri = dependent_captures
                .get("URI")
                .map(String::as_str)
                .filter(|uri| !uri.is_empty())
                .unwrap_or(snippet);
            let scheme = dependent_captures.get("SCHEME").map(String::as_str);
            match crate::validation::classify_credential_uri(uri, scheme) {
                crate::validation::CredentialUriTarget::Postgres(_)
                | crate::validation::CredentialUriTarget::MongoDB(_)
                | crate::validation::CredentialUriTarget::MySQL(_) => uri,
                crate::validation::CredentialUriTarget::Http(_)
                | crate::validation::CredentialUriTarget::Jdbc(_)
                | crate::validation::CredentialUriTarget::Unsupported(_) => return None,
            }
        }
        _ => snippet,
    };
    match validation {
        Validation::Betterleaks(validation) => {
            let mapping = validation.capabilities.access_map.as_ref()?;
            for source in mapping.inputs.values() {
                if let Some(component) = source.strip_prefix("components.") {
                    let variable = validation.components.get(component)?.to_ascii_uppercase();
                    if dependent_captures.get(&variable).is_none_or(String::is_empty) {
                        return None;
                    }
                    required_vars.insert(variable);
                }
            }
        }
        Validation::AWS => {
            required_vars.insert("AKID".to_string());
            let akid_from_dependencies = dependent_captures
                .get("AKID")
                .map(String::as_str)
                .filter(|value| !value.is_empty());
            let has_secret_access_key = dependent_captures
                .get("AWS_SECRET_ACCESS_KEY")
                .is_some_and(|value| !value.is_empty());
            if is_aws_session_token && !has_secret_access_key {
                return None;
            }
            if has_secret_access_key {
                required_vars.insert("AWS_SECRET_ACCESS_KEY".to_string());
            }
            akid_from_dependencies
                .or(akid_from_captures.filter(|value| !value.is_empty()))
                .or(akid_from_validation_body.filter(|value| !value.is_empty()))?;
        }
        Validation::GCP => {}
        Validation::AzureStorage => {
            required_vars.insert("AZURENAME".to_string());
            if dependent_captures.get("AZURENAME").is_none_or(String::is_empty) {
                return None;
            }
        }
        Validation::CredentialUri
        | Validation::Postgres
        | Validation::MongoDB
        | Validation::MySQL => {}
        _ => return None,
    }
    let var_args = build_var_args(
        dependent_captures,
        *akid_from_captures,
        *akid_from_validation_body,
        &required_vars,
    );
    let rule_loading_args = build_rule_loading_args(rules_path, *load_builtins)?;
    Some(format!(
        "kingfisher blast-radius --rule {} {}{}{}",
        escape_for_shell(rule_id),
        rule_loading_args,
        var_args,
        escape_for_shell(command_secret)
    ))
}

/// Extract AWS Access Key ID from validation response body if present.
fn extract_akid_from_validation_body(body: &ValidationResponseBody) -> Option<String> {
    static AKID_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
        regex::Regex::new(
            r"(?xi)\b(?:A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[0-9A-Z]{16}\b",
        )
        .expect("AKID regex should compile")
    });

    let text = validation_body::clone_as_string(body);
    AKID_RE.find(&text).map(|m| m.as_str().to_string())
}

const BITBUCKET_FRAGMENT_ENCODE_SET: &AsciiSet = &CONTROLS
    .add(b' ')
    .add(b'"')
    .add(b'#')
    .add(b'%')
    .add(b'<')
    .add(b'>')
    .add(b'?')
    .add(b'`')
    .add(b'{')
    .add(b'}')
    .add(b'|');

const AZURE_QUERY_ENCODE_SET: &AsciiSet = &CONTROLS
    .add(b' ')
    .add(b'"')
    .add(b'#')
    .add(b'%')
    .add(b'<')
    .add(b'>')
    .add(b'?')
    .add(b'`')
    .add(b'{')
    .add(b'}')
    .add(b'|');

/// GitHub gist file anchors lowercase filenames, collapse runs of non-alphanumeric
/// characters (except `_`) to `-`, and omit leading/trailing separators.
fn gist_file_anchor(file_path: &str) -> String {
    let normalized = file_path.replace('\\', "/");
    let name = normalized.rsplit('/').next().unwrap_or(normalized.as_str());
    let slug = name
        .split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
        .filter(|part| !part.is_empty())
        .map(str::to_ascii_lowercase)
        .collect::<Vec<_>>()
        .join("-");
    format!("file-{slug}")
}

pub(crate) fn build_git_urls(
    repo_url: &str,
    commit_id: &str,
    file_path: &str,
    line: usize,
) -> (String, String, String) {
    let repo_url = repo_url.trim_end_matches('/');
    let mut repository_url = repo_url.to_string();
    let mut commit_url = format!("{repo_url}/commit/{commit_id}");
    let mut file_url = format!("{repo_url}/blob/{commit_id}/{file_path}#L{line}",);

    if let Ok(parsed) = Url::parse(repo_url) {
        let scheme = parsed.scheme();
        let host = parsed.host_str().unwrap_or_default();
        let segments: Vec<&str> = parsed
            .path_segments()
            .map(|segments| segments.filter(|s| !s.is_empty()).collect())
            .unwrap_or_default();

        let format_anchor = |path: &str| {
            let normalized = path.replace('\\', "/");
            utf8_percent_encode(normalized.trim_start_matches('/'), BITBUCKET_FRAGMENT_ENCODE_SET)
                .to_string()
        };

        if host.eq_ignore_ascii_case("gist.github.com") {
            // Gists do not use /blob/ or /commit/ paths. Point at the revision
            // page and use GitHub's #file-...-L{line} fragment for the match.
            repository_url = repo_url.to_string();
            commit_url = format!("{repo_url}/{commit_id}");
            let anchor = gist_file_anchor(file_path);
            if line > 0 {
                file_url = format!("{repo_url}/{commit_id}#{anchor}-L{line}");
            } else {
                file_url = format!("{repo_url}/{commit_id}#{anchor}");
            }
        } else if host.eq_ignore_ascii_case("bitbucket.org") {
            let joined = segments.join("/");
            let base = if joined.is_empty() {
                format!("{scheme}://{host}")
            } else {
                format!("{scheme}://{host}/{joined}")
            };
            let anchor = format_anchor(file_path);
            repository_url = base.clone();
            commit_url = format!("{base}/commits/{commit_id}");
            file_url = format!("{base}/commits/{commit_id}#L{anchor}F{line}");
        } else if host.contains("bitbucket") {
            if segments.len() >= 3 && segments[0].eq_ignore_ascii_case("scm") {
                let project = segments[1];
                let repo = segments[2];
                let base = format!("{scheme}://{host}/projects/{project}/repos/{repo}");
                let anchor = format_anchor(file_path);
                repository_url = base.clone();
                commit_url = format!("{base}/commits/{commit_id}");
                file_url = format!("{base}/commits/{commit_id}#L{anchor}F{line}");
            }
        } else if host.eq_ignore_ascii_case("dev.azure.com") || host.ends_with(".visualstudio.com")
        {
            let normalized = file_path.replace('\\', "/");
            let trimmed = normalized.trim_start_matches('/');
            let encoded_path = utf8_percent_encode(trimmed, AZURE_QUERY_ENCODE_SET).to_string();
            repository_url = repo_url.to_string();
            commit_url = format!("{repo_url}/commit/{commit_id}");
            if line > 0 {
                file_url =
                    format!("{repo_url}/commit/{commit_id}?path=/{}&line={line}", encoded_path);
            } else {
                file_url = format!("{repo_url}/commit/{commit_id}?path=/{}", encoded_path);
            }
        }
    }

    (repository_url, commit_url, file_url)
}

pub fn run(
    global_args: &GlobalArgs,
    ds: Arc<Mutex<findings_store::FindingsStore>>,
    args: &cli::commands::scan::ScanArgs,
    audit_context: Option<ScanAuditContext>,
) -> Result<()> {
    let writer = args.output_args.get_writer()?;
    run_with_writer(global_args, ds, args, audit_context, writer)
}

/// Same as [`run`], but writes into a caller-provided `Write` instead of
/// constructing one from `args.output_args`. Useful when the caller wants
/// to render into an in-memory buffer first (e.g. so a stdout lock can be
/// held only around the final atomic emit, not around the report's CPU
/// work).
pub fn run_with_writer<W: std::io::Write>(
    global_args: &GlobalArgs,
    ds: Arc<Mutex<findings_store::FindingsStore>>,
    args: &cli::commands::scan::ScanArgs,
    audit_context: Option<ScanAuditContext>,
    writer: W,
) -> Result<()> {
    global_args.use_color(std::io::stdout());
    let stdout_is_tty = std::io::stdout().is_terminal();
    let use_color = stdout_is_tty && !args.output_args.has_output();
    let styles = Styles::new(use_color);

    let ds_clone = Arc::clone(&ds);
    let reporter = DetailsReporter {
        datastore: ds_clone,
        styles,
        validation_filter: args.effective_validation_filter(),
        audit_context,
    };
    reporter.report(args.output_args.format, writer, args)
}
pub struct DetailsReporter {
    pub datastore: Arc<Mutex<findings_store::FindingsStore>>,
    pub styles: Styles,
    pub validation_filter: cli::commands::scan::ValidationFilter,
    pub audit_context: Option<ScanAuditContext>,
}

#[derive(Clone, Debug)]
pub struct ScanAuditContext {
    pub scan_timestamp: Option<String>,
    pub scan_duration_seconds: Option<f64>,
    pub rules_applied: Option<usize>,
    pub successful_validations: Option<usize>,
    pub failed_validations: Option<usize>,
    pub skipped_validations: Option<usize>,
    pub blobs_scanned: Option<u64>,
    pub bytes_scanned: Option<u64>,
    pub running_version: Option<String>,
    pub latest_version: Option<String>,
    pub update_check_status: Option<String>,
}

impl DetailsReporter {
    pub fn extract_git_metadata(
        &self,
        prov: &GitRepoOrigin,
        source_span: &SourceSpan,
    ) -> Option<serde_json::Value> {
        let repo_url = self
            .repo_artifact_url(prov.repo_path.as_ref())
            .or_else(|| get_repo_url(&prov.repo_path).ok().map(|url| url.to_string()))
            .unwrap_or_else(|| prov.repo_path.to_string_lossy().to_string());
        let repo_url = repo_url.trim_end_matches(".git").to_string();
        if let Some(cs) = &prov.first_commit {
            let cmd = &cs.commit_metadata;
            let commit_id = cmd.commit_id.to_string();
            let (repository_url, commit_url, file_url) =
                build_git_urls(&repo_url, &commit_id, &cs.blob_path, source_span.start.line);
            // let msg =
            //     String::from_utf8_lossy(cmd.message.lines().next().unwrap_or(&[],),).
            // into_owned();

            let atime = cmd
                .committer_timestamp
                .format(gix::date::time::format::SHORT)
                .unwrap_or_else(|_| cmd.committer_timestamp.seconds.to_string());

            let git_metadata = serde_json::json!({
                "repository_url": repository_url,
                "commit": {
                    "id": commit_id,
                    "url": commit_url,
                    "date": atime,
                    "committer": {
                        "name": &cmd.committer_name,
                        "email": &cmd.committer_email,
                    },
                    "author": cmd.author_name.as_ref().or(cmd.author_email.as_ref()).map(|_| serde_json::json!({
                        "name": &cmd.author_name,
                        "email": &cmd.author_email,
                    })),
                    // "message": msg,
                },
                "file": {
                    "path": &cs.blob_path,
                    "url": file_url,
                    "git_command": format!(
                        "git -C {} show {}:{}",
                        prov.repo_path.display(),
                        cmd.commit_id,
                        &cs.blob_path
                    )
                }
            });
            Some(git_metadata)
        } else {
            None
        }
    }

    /// If the given file path corresponds to a Jira issue downloaded to disk,
    /// return the online Jira URL for that issue.
    fn jira_issue_url(
        &self,
        path: &std::path::Path,
        args: &cli::commands::scan::ScanArgs,
    ) -> Option<String> {
        // drop any trailing slash so we don’t end up with “//browse/…”
        let jira_url = args.input_specifier_args.jira_url.as_ref()?.as_str().trim_end_matches('/');

        let ds = self.datastore.lock().ok()?;
        let root = ds.clone_root();
        let jira_dir = root.join("jira_issues");
        if path.starts_with(&jira_dir) {
            let relative = path.strip_prefix(&jira_dir).ok()?;
            let mut components = relative.components();
            let key = if components.clone().count() > 1 {
                components
                    .next()
                    .and_then(|component| component.as_os_str().to_str())
                    .filter(|segment| !segment.is_empty())
                    .map(std::borrow::Cow::from)
            } else {
                None
            }
            .or_else(|| path.file_stem().map(|stem| stem.to_string_lossy()))?;
            Some(format!("{}/browse/{}", jira_url, key))
        } else {
            None
        }
    }

    fn normalized_finding_fingerprint(m: &Match, origin: &OriginSet) -> u64 {
        // EXTERNAL FINGERPRINT: Use get(1).or_else(get(0)) for backward compatibility.
        //
        // This indexing is intentionally different from the internal `validation_dedup_key()`
        // (which uses get(0)) to maintain stable external fingerprints and consistent
        // reporting output. Changing this would break historical baselines and alter
        // finding appearance.
        let finding_value = m
            .groups
            .captures
            .get(1)
            .or_else(|| m.groups.captures.first())
            .map(|capture| capture.raw_value())
            .unwrap_or("");
        let offset_start = m.location.offset_span.start as u64;
        let offset_end = m.location.offset_span.end as u64;
        let has_file = origin.iter().any(|o| matches!(o, Origin::File(_)));
        let has_git = origin.iter().any(|o| matches!(o, Origin::GitRepo(_)));
        let origin_key = if has_file || has_git { "file_git" } else { "ext" };
        compute_finding_fingerprint(finding_value, origin_key, offset_start, offset_end)
    }

    fn origin_set_contains_git(origin: &OriginSet) -> bool {
        origin.iter().any(|o| matches!(o, Origin::GitRepo(_)))
    }

    fn merge_origins_for_dedup(mut existing: ReportMatch, incoming: ReportMatch) -> ReportMatch {
        let existing_has_git = Self::origin_set_contains_git(&existing.origin);
        let incoming_has_git = Self::origin_set_contains_git(&incoming.origin);
        let prefer_git = existing_has_git || incoming_has_git;

        if incoming_has_git && !existing_has_git {
            existing = incoming.clone();
        }

        let mut origins = Vec::new();
        let mut push_unique = |origin: &Origin| {
            if !origins.iter().any(|existing| existing == origin) {
                origins.push(origin.clone());
            }
        };

        for origin in existing.origin.iter().chain(incoming.origin.iter()) {
            push_unique(origin);
        }

        if prefer_git {
            origins.retain(|origin| matches!(origin, Origin::GitRepo(_)));
        }

        if let Some(origin_set) = OriginSet::try_from_iter(origins) {
            existing.origin = origin_set;
        }

        existing
    }

    /// If the given file path corresponds to a Confluence page downloaded to disk,
    /// return the URL for that page.
    fn confluence_page_url(&self, path: &std::path::Path) -> Option<String> {
        let ds = self.datastore.lock().ok()?;
        ds.confluence_links().get(path).cloned()
    }

    /// If the given path corresponds to a Slack message or file downloaded to disk,
    /// return its permalink.
    fn slack_message_url(&self, path: &std::path::Path) -> Option<String> {
        let ds = self.datastore.lock().ok()?;
        ds.slack_links().get(path).cloned()
    }

    fn teams_message_url(&self, path: &std::path::Path) -> Option<String> {
        let ds = self.datastore.lock().ok()?;
        ds.teams_links().get(path).cloned()
    }

    fn postman_resource_url(&self, path: &std::path::Path) -> Option<String> {
        let ds = self.datastore.lock().ok()?;
        ds.postman_links().get(path).cloned()
    }

    fn repo_artifact_url(&self, path: &std::path::Path) -> Option<String> {
        let ds = self.datastore.lock().ok()?;
        ds.repo_links().get(path).cloned()
    }

    fn s3_display_path(&self, path: &std::path::Path) -> Option<String> {
        let ds = self.datastore.lock().ok()?;
        for (dir, bucket) in ds.s3_buckets().iter() {
            if path.starts_with(dir) {
                let rel = path.strip_prefix(dir).ok()?;
                return Some(format!("s3://{}/{}", bucket, rel.display()));
            }
        }
        None
    }

    fn docker_display_path(&self, path: &std::path::Path) -> Option<String> {
        let ds = self.datastore.lock().ok()?;
        for (dir, image) in ds.docker_images().iter() {
            if path.starts_with(dir) {
                let rel = path.strip_prefix(dir).ok()?;
                let mut rel_str = rel.display().to_string();
                rel_str = rel_str.replace(".decomp.tar!", ".tar.gz | ");
                rel_str = rel_str.replace(".tar!", ".tar | ");
                rel_str = rel_str.replace('!', " | ");
                return Some(format!("{} | {}", image, rel_str));
            }
        }
        None
    }

    fn process_matches(
        &self,
        validation_filter: cli::commands::scan::ValidationFilter,
        filter_visible: bool,
    ) -> Result<Vec<ReportMatch>> {
        let datastore = self.datastore.lock().unwrap();
        Ok(datastore
            .get_matches()
            .iter()
            .filter(|msg| {
                let (_origin, _blob_metadata, match_item) = &***msg;
                let outcome = if !match_item.rule.syntax().is_authoritative() {
                    kingfisher_core::ValidationOutcome::NotAttempted
                } else {
                    match_item.validation_outcome
                };
                let outcome_matches = match validation_filter {
                    cli::commands::scan::ValidationFilter::All => true,
                    cli::commands::scan::ValidationFilter::Active => outcome.is_verified_active(),
                    cli::commands::scan::ValidationFilter::Actionable => outcome.is_actionable(),
                };
                outcome_matches && (!filter_visible || match_item.visible)
            })
            .map(|msg| {
                let (origin, blob_metadata, match_item) = &**msg;
                let non_authoritative = !match_item.rule.syntax().is_authoritative();
                let mut sanitized_match = match_item.clone();
                if non_authoritative {
                    sanitized_match.validation_response_body = None;
                    sanitized_match.validation_response_status = 100;
                    sanitized_match.validation_success = false;
                    sanitized_match.validation_outcome =
                        kingfisher_core::ValidationOutcome::NotAttempted;
                }
                let sanitized_validation_body = sanitized_match.validation_response_body.clone();
                let sanitized_validation_status = sanitized_match.validation_response_status;
                let sanitized_validation_success = sanitized_match.validation_success;
                let sanitized_validation_outcome = sanitized_match.validation_outcome;
                ReportMatch {
                    origin: (**origin).clone(),
                    blob_metadata: (**blob_metadata).clone(),
                    m: sanitized_match,
                    comment: None,
                    visible: match_item.visible,
                    match_confidence: match_item.rule.confidence(),
                    validation_response_body: sanitized_validation_body,
                    validation_response_status: sanitized_validation_status,
                    validation_success: sanitized_validation_success,
                    validation_outcome: sanitized_validation_outcome,
                }
            })
            .collect())
    }

    pub fn get_filtered_matches(&self, include_hidden_findings: bool) -> Result<Vec<ReportMatch>> {
        self.process_matches(self.validation_filter, !include_hidden_findings)
    }

    pub fn get_unfiltered_matches(
        &self,
        validation_filter: Option<cli::commands::scan::ValidationFilter>,
    ) -> Result<Vec<ReportMatch>> {
        self.process_matches(validation_filter.unwrap_or(self.validation_filter), false)
    }

    pub fn deduplicate_matches(
        &self,
        matches: Vec<ReportMatch>,
        no_dedup: bool,
    ) -> Vec<ReportMatch> {
        if no_dedup {
            return matches;
        }

        use std::collections::HashMap;
        let mut by_fp: HashMap<(u64, String, String), ReportMatch> = HashMap::new();

        for rm in matches {
            let key = (
                Self::normalized_finding_fingerprint(&rm.m, &rm.origin),
                rm.m.rule.id().to_string(),
                serde_json::to_string(&(
                    &rm.m.dependent_captures,
                    &rm.m.ambiguous_dependencies,
                    &rm.m.dependency_candidates,
                ))
                .expect("dependency maps serialize"),
            );
            if let Some(existing) = by_fp.get_mut(&key) {
                *existing = Self::merge_origins_for_dedup(existing.clone(), rm);
                continue;
            }
            by_fp.insert(key, rm);
        }
        by_fp.into_values().collect()
    }

    fn matches_for_output(&self, args: &cli::commands::scan::ScanArgs) -> Result<Vec<ReportMatch>> {
        let mut matches = self.get_filtered_matches(args.include_hidden_findings)?;
        if !args.no_dedup {
            matches = self.deduplicate_matches(matches, args.no_dedup);
        }
        if args.no_dedup {
            let mut expanded = Vec::new();
            for rm in matches {
                if rm.origin.len() > 1 {
                    for origin in rm.origin.iter() {
                        let mut single = rm.clone();
                        single.origin = OriginSet::new(origin.clone(), Vec::new());
                        expanded.push(single);
                    }
                } else {
                    expanded.push(rm);
                }
            }
            matches = expanded;
        }
        matches.sort_by(|a, b| {
            let path_a = a
                .origin
                .first()
                .full_path()
                .map(|p| p.to_string_lossy().to_string())
                .unwrap_or_default();
            let path_b = b
                .origin
                .first()
                .full_path()
                .map(|p| p.to_string_lossy().to_string())
                .unwrap_or_default();
            path_a
                .cmp(&path_b)
                .then_with(|| {
                    a.m.location
                        .resolved_source_span()
                        .start
                        .line
                        .cmp(&b.m.location.resolved_source_span().start.line)
                })
                .then_with(|| {
                    a.m.location
                        .resolved_source_span()
                        .start
                        .column
                        .cmp(&b.m.location.resolved_source_span().start.column)
                })
        });
        Ok(matches)
    }

    pub fn build_finding_record(
        &self,
        rm: &ReportMatch,
        args: &cli::commands::scan::ScanArgs,
    ) -> FindingReporterRecord {
        let source_span = rm.m.location.resolved_source_span();
        let line_num = source_span.start.line;

        // Prefer the named TOKEN capture (when present) for display + validate/revoke commands.
        // This avoids cases like Modal CLI pairs where capture(0) is an ID and TOKEN is the secret.
        let snippet_capture =
            rm.m.groups
                .captures
                .iter()
                .find(|c| c.name.map(|n| n.eq_ignore_ascii_case("TOKEN")).unwrap_or(false))
                .or_else(|| rm.m.groups.captures.first());

        // Get raw snippet value (for revoke/validate command) and display snippet (for output)
        let (raw_snippet, snippet) = if let Some(capture) = snippet_capture {
            let raw = capture.raw_value().to_string();
            let displayed = capture.display_value();
            (raw, Escaped(displayed.as_ref().as_bytes()).to_string())
        } else {
            (String::new(), String::new())
        };

        let validation_status = if rm.validation_outcome
            == kingfisher_core::ValidationOutcome::Skipped
            && validation_body::as_str(&rm.validation_response_body)
                .starts_with("(skip list entry)")
        {
            "Canary Token (Skipped)".to_string()
        } else {
            rm.validation_outcome.display_name().to_string()
        };

        let raw_validation_body = validation_body::as_str(&rm.validation_response_body);
        let sanitized_local_body = match rm.m.rule.syntax().validation.as_ref() {
            Some(crate::rules::Validation::Ethereum(kind)) => {
                kingfisher_scanner::validation::ethereum::sanitized_report_body(
                    *kind,
                    rm.validation_outcome,
                    raw_validation_body,
                )
            }
            _ => Some(raw_validation_body.to_string()),
        };
        const SANITIZATION_FAILURE_PLACEHOLDER: &str =
            "[validation response omitted: local evidence failed sanitization]";
        let response_body = format_validation_response(
            sanitized_local_body.as_deref().unwrap_or(SANITIZATION_FAILURE_PLACEHOLDER),
            args.redact,
            args.full_validation_response,
        );

        let git_metadata_val = rm
            .origin
            .iter()
            .filter_map(|origin| {
                if let Origin::GitRepo(e) = origin {
                    self.extract_git_metadata(e, &source_span)
                } else {
                    None
                }
            })
            .next();

        let file_path = rm
            .origin
            .iter()
            .find_map(|origin| self.origin_display_path(origin, args))
            .or_else(|| {
                rm.origin.iter().find_map(|origin| {
                    origin
                        .blob_path()
                        .map(|p| p.display().to_string())
                        .and_then(Self::non_empty_string)
                })
            })
            .or_else(|| self.git_object_fallback_path(rm))
            .unwrap_or_else(|| format!("blob:{}", rm.blob_metadata.id.hex()));

        // Generate validate/revoke/blast-radius commands only if not redacting (they contain the secret)
        let (validate_command, revoke_command, blast_radius_command) = if args.redact
            || !rm.m.ambiguous_dependencies.is_empty()
        {
            (None, None, None)
        } else {
            // Try to find AKID from captures (for AWS)
            let akid_from_captures: Option<String> =
                rm.m.groups
                    .captures
                    .iter()
                    .find(|c| c.name == Some("AKID") || c.name == Some("akid"))
                    .map(|c| c.raw_value().to_string());

            // Try to extract AKID from validation response body (fallback for AWS)
            let akid_from_body = extract_akid_from_validation_body(&rm.validation_response_body);

            // Generate validate command for findings with validation support
            let validate_cmd = if let Some(validation) = &rm.m.rule.syntax().validation {
                // Merge dependent captures with named regex captures so the generated command is runnable.
                // (E.g., Modal needs TOKEN_ID, which is a named capture on the same rule.)
                let mut merged_vars = rm.m.dependent_captures.clone();
                for cap in rm.m.groups.captures.iter() {
                    let Some(name) = cap.name else { continue };
                    if name.eq_ignore_ascii_case("TOKEN") {
                        continue;
                    }
                    merged_vars
                        .entry(name.to_uppercase())
                        .or_insert_with(|| cap.raw_value().to_string());
                }

                build_validate_command(
                    rm.m.rule.id(),
                    validation,
                    &raw_snippet,
                    &merged_vars,
                    akid_from_captures.as_deref(),
                    akid_from_body.as_deref(),
                )
            } else {
                None
            };

            let blast_radius_cmd = rm.m.rule.syntax().validation.as_ref().and_then(|validation| {
                let mut merged_vars = rm.m.dependent_captures.clone();
                for cap in rm.m.groups.captures.iter() {
                    let Some(name) = cap.name else { continue };
                    if name.eq_ignore_ascii_case("TOKEN") {
                        continue;
                    }
                    merged_vars
                        .entry(name.to_uppercase())
                        .or_insert_with(|| cap.raw_value().to_string());
                }
                build_blast_radius_command(
                    rm.m.rule.id(),
                    validation,
                    crate::validation::is_aws_session_token_rule(&rm.m.rule),
                    &raw_snippet,
                    &BlastRadiusCommandContext {
                        dependent_captures: &merged_vars,
                        akid_from_captures: akid_from_captures.as_deref(),
                        akid_from_validation_body: akid_from_body.as_deref(),
                        rules_path: &args.rules.rules_path,
                        load_builtins: args.rules.load_builtins,
                    },
                )
            });

            // Generate revoke command for active credentials with revocation support
            let revoke_cmd = if rm.validation_outcome.is_verified_active() {
                if let Some(revocation) = &rm.m.rule.syntax().revocation {
                    // Merge dependent captures with named regex captures so the generated command is runnable.
                    // (Some rules capture required revocation parameters directly in the match.)
                    let mut merged_vars = rm.m.dependent_captures.clone();
                    for cap in rm.m.groups.captures.iter() {
                        let Some(name) = cap.name else { continue };
                        if name.eq_ignore_ascii_case("TOKEN") {
                            continue;
                        }
                        merged_vars
                            .entry(name.to_uppercase())
                            .or_insert_with(|| cap.raw_value().to_string());
                    }
                    let mut revoke_secret = raw_snippet.clone();
                    let mut bindings_complete = true;
                    if let Some(crate::rules::Validation::Betterleaks(validation)) =
                        &rm.m.rule.syntax().validation
                        && let Some(bindings) = &validation.capabilities.revocation_bindings
                    {
                        if let Some(value) = resolve_betterleaks_capability_source(
                            &bindings.secret,
                            &raw_snippet,
                            validation,
                            &merged_vars,
                        ) {
                            revoke_secret = value.to_string();
                        } else {
                            bindings_complete = false;
                        }
                        for (name, source) in &bindings.variables {
                            let Some(value) = resolve_betterleaks_capability_source(
                                source,
                                &raw_snippet,
                                validation,
                                &merged_vars,
                            ) else {
                                bindings_complete = false;
                                break;
                            };
                            merged_vars.insert(name.to_ascii_uppercase(), value.to_string());
                        }
                    }
                    bindings_complete
                        .then(|| {
                            build_revoke_command(
                                rm.m.rule.id(),
                                revocation,
                                &revoke_secret,
                                &merged_vars,
                                akid_from_captures.as_deref(),
                                akid_from_body.as_deref(),
                            )
                        })
                        .flatten()
                } else {
                    None
                }
            } else {
                None
            };

            (validate_cmd, revoke_cmd, blast_radius_cmd)
        };

        FindingReporterRecord {
            rule: RuleMetadata {
                name: display_rule_id(rm.m.rule.id()),
                id: rm.m.rule.id().to_string(),
                description: rm.m.rule.name().to_string(),
                title: finding_title(rm.m.rule.id()),
            },
            finding: FindingRecordData {
                dependent_captures: if args.redact {
                    BTreeMap::new()
                } else {
                    rm.m.dependent_captures.clone()
                },
                ambiguous_dependencies: rm.m.ambiguous_dependencies.clone(),
                snippet,
                fingerprint: rm.m.finding_fingerprint.to_string(),
                confidence: rm.match_confidence.to_string(),
                entropy: format!("{:.2}", rm.m.calculated_entropy),
                validation: ValidationInfo {
                    outcome: rm.validation_outcome,
                    status: validation_status,
                    response: response_body,
                },
                language: rm
                    .blob_metadata
                    .language
                    .clone()
                    .unwrap_or_else(|| "Unknown".to_string()),
                line: line_num as u32,
                column_start: source_span.start.column as u32,
                column_end: source_span.end.column as u32,
                path: file_path,
                encoding: if rm.m.is_base64 { Some("base64".to_string()) } else { None },
                git_metadata: git_metadata_val,
                validate_command,
                revoke_command,
                blast_radius_command,
            },
        }
    }

    fn origin_display_path(
        &self,
        origin: &Origin,
        args: &cli::commands::scan::ScanArgs,
    ) -> Option<String> {
        match origin {
            Origin::File(e) => self
                .repo_artifact_url(&e.path)
                .and_then(Self::non_empty_string)
                .or_else(|| self.jira_issue_url(&e.path, args).and_then(Self::non_empty_string))
                .or_else(|| self.confluence_page_url(&e.path).and_then(Self::non_empty_string))
                .or_else(|| self.slack_message_url(&e.path).and_then(Self::non_empty_string))
                .or_else(|| self.teams_message_url(&e.path).and_then(Self::non_empty_string))
                .or_else(|| self.postman_resource_url(&e.path).and_then(Self::non_empty_string))
                .or_else(|| self.s3_display_path(&e.path).and_then(Self::non_empty_string))
                .or_else(|| self.docker_display_path(&e.path).and_then(Self::non_empty_string))
                .or_else(|| Self::non_empty_string(e.path.display().to_string())),
            Origin::GitRepo(e) => {
                e.first_commit.as_ref().and_then(|c| Self::non_empty_string(c.blob_path.clone()))
            }
            Origin::Extended(e) => {
                e.path().map(|p| p.display().to_string()).and_then(Self::non_empty_string)
            }
        }
    }

    fn git_object_fallback_path(&self, rm: &ReportMatch) -> Option<String> {
        let blob_hex = rm.blob_metadata.id.hex();
        rm.origin.iter().find_map(|origin| {
            if let Origin::GitRepo(repo_origin) = origin {
                let (prefix, suffix) = blob_hex.split_at(2);
                let repo_path = repo_origin.repo_path.as_ref();
                let git_dir_objects = repo_path.join(".git").join("objects");
                let objects_dir = if git_dir_objects.is_dir() {
                    git_dir_objects
                } else {
                    repo_path.join("objects")
                };
                let fallback_path = objects_dir.join(prefix).join(suffix);
                Self::non_empty_string(fallback_path.display().to_string())
            } else {
                None
            }
        })
    }

    fn non_empty_string(value: String) -> Option<String> {
        if value.trim().is_empty() { None } else { Some(value) }
    }

    pub fn build_finding_records(
        &self,
        args: &cli::commands::scan::ScanArgs,
    ) -> Result<Vec<FindingReporterRecord>> {
        let matches = self.matches_for_output(args)?;
        Ok(matches.iter().map(|rm| self.build_finding_record(rm, args)).collect())
    }

    pub fn build_report_envelope(
        &self,
        args: &cli::commands::scan::ScanArgs,
    ) -> Result<ReportEnvelope> {
        let findings = self.build_finding_records(args)?;
        let access_map = self.build_access_map_records(args);
        let audit = self.datastore.lock().unwrap().scan_audit().cloned();
        let metadata = self.build_report_metadata(args, &findings, access_map.as_ref());

        Ok(ReportEnvelope { findings, access_map, audit, metadata: Some(metadata) })
    }

    fn build_report_metadata(
        &self,
        args: &cli::commands::scan::ScanArgs,
        findings: &[FindingReporterRecord],
        access_map: Option<&Vec<AccessMapEntry>>,
    ) -> ScanReportMetadata {
        let mut active_findings = 0usize;
        let mut inactive_findings = 0usize;
        let mut locally_derived_findings = 0usize;
        let mut invalid_material_findings = 0usize;
        let mut unknown_validation_findings = 0usize;

        for record in findings {
            match record.finding.validation.outcome {
                kingfisher_core::ValidationOutcome::VerifiedActive => active_findings += 1,
                kingfisher_core::ValidationOutcome::VerifiedInactive => inactive_findings += 1,
                kingfisher_core::ValidationOutcome::LocallyDerived => locally_derived_findings += 1,
                kingfisher_core::ValidationOutcome::InvalidMaterial => {
                    invalid_material_findings += 1
                }
                _ => unknown_validation_findings += 1,
            }
        }

        let command_line_args: Vec<String> = std::env::args().collect();
        let sanitized_command_line_args = sanitize_command_line_args(&command_line_args);
        let scan_timestamp = self.audit_context.as_ref().and_then(|ctx| ctx.scan_timestamp.clone());
        let generated_at = generated_at_for_scan_timezone(scan_timestamp.as_deref());
        let scan_timestamp = scan_timestamp.unwrap_or_else(|| generated_at.clone());

        ScanReportMetadata {
            generated_at: generated_at.clone(),
            scan_timestamp,
            target: derive_scan_target(args),
            command_line_args: sanitized_command_line_args,
            kingfisher_version: self
                .audit_context
                .as_ref()
                .and_then(|ctx| ctx.running_version.clone())
                .unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string()),
            latest_version_available: self
                .audit_context
                .as_ref()
                .and_then(|ctx| ctx.latest_version.clone()),
            update_check_status: self
                .audit_context
                .as_ref()
                .and_then(|ctx| ctx.update_check_status.clone()),
            summary: ScanReportSummary {
                findings: findings.len(),
                active_findings,
                inactive_findings,
                locally_derived_findings,
                invalid_material_findings,
                unknown_validation_findings,
                access_map_identities: access_map.map_or(0, Vec::len),
                rules_applied: self.audit_context.as_ref().and_then(|ctx| ctx.rules_applied),
                confidence_level: args.confidence.to_string(),
                custom_rules_used: !args.rules.rules_path.is_empty() || !args.rules.load_builtins,
                successful_validations: self
                    .audit_context
                    .as_ref()
                    .and_then(|ctx| ctx.successful_validations),
                failed_validations: self
                    .audit_context
                    .as_ref()
                    .and_then(|ctx| ctx.failed_validations),
                skipped_validations: self
                    .audit_context
                    .as_ref()
                    .and_then(|ctx| ctx.skipped_validations),
                blobs_scanned: self.audit_context.as_ref().and_then(|ctx| ctx.blobs_scanned),
                bytes_scanned: self.audit_context.as_ref().and_then(|ctx| ctx.bytes_scanned),
                scan_duration_seconds: self
                    .audit_context
                    .as_ref()
                    .and_then(|ctx| ctx.scan_duration_seconds),
            },
        }
    }

    pub(crate) fn build_access_map_records(
        &self,
        args: &cli::commands::scan::ScanArgs,
    ) -> Option<Vec<AccessMapEntry>> {
        if !args.access_map {
            return None;
        }

        let ds = self.datastore.lock().unwrap();
        let non_authoritative_fingerprints: BTreeSet<String> = ds
            .get_matches()
            .iter()
            .filter(|message| !message.2.rule.syntax().is_authoritative())
            .map(|message| message.2.finding_fingerprint.to_string())
            .collect();
        let raw_results = ds.access_map_results();

        if raw_results.is_empty() {
            return None;
        }

        let mut entries = Vec::new();
        for mapped in raw_results.iter().filter(|mapped| {
            !mapped
                .finding_fingerprints
                .iter()
                .any(|fingerprint| non_authoritative_fingerprints.contains(fingerprint))
        }) {
            entries.push(access_map_entry_from_result(&mapped.result));
        }

        (!entries.is_empty()).then_some(entries)
    }

    #[doc(hidden)]
    pub fn build_alert_access_map_entries(
        &self,
        args: &cli::commands::scan::ScanArgs,
    ) -> Vec<AlertAccessMapEntry> {
        if !args.access_map {
            return Vec::new();
        }

        let ds = self.datastore.lock().unwrap();
        let non_authoritative_fingerprints: BTreeSet<String> = ds
            .get_matches()
            .iter()
            .filter(|message| !message.2.rule.syntax().is_authoritative())
            .map(|message| message.2.finding_fingerprint.to_string())
            .collect();
        ds.access_map_results()
            .iter()
            .filter(|mapped| {
                !mapped
                    .finding_fingerprints
                    .iter()
                    .any(|fingerprint| non_authoritative_fingerprints.contains(fingerprint))
            })
            .map(|mapped| AlertAccessMapEntry {
                finding_fingerprints: mapped.finding_fingerprints.clone(),
                // Report output represents a mapped identity as one resource when the provider
                // returns no child resources, so alert impact follows the same convention.
                impacted_resources: mapped.result.resources.len().max(1),
                mapping_succeeded: mapped.mapping_succeeded,
            })
            .collect()
    }

    fn style_finding_heading<D>(&self, val: D) -> StyledObject<D> {
        self.styles.style_finding_heading.apply_to(val)
    }

    fn style_finding_active_heading<D>(&self, val: D) -> StyledObject<D> {
        self.styles.style_finding_active_heading.apply_to(val)
    }

    #[expect(dead_code)]
    fn style_rule<D>(&self, val: D) -> StyledObject<D> {
        self.styles.style_rule.apply_to(val)
    }

    fn style_heading<D>(&self, val: D) -> StyledObject<D> {
        self.styles.style_heading.apply_to(val)
    }

    fn style_match<D>(&self, val: D) -> StyledObject<D> {
        self.styles.style_match.apply_to(val)
    }

    fn style_metadata<D>(&self, val: D) -> StyledObject<D> {
        self.styles.style_metadata.apply_to(val)
    }

    fn style_active_creds<D>(&self, val: D) -> StyledObject<D> {
        self.styles.style_active_creds.apply_to(val)
    }
}

fn normalize_permissions(cloud: &str, permissions: &[String]) -> Vec<String> {
    if cloud.eq_ignore_ascii_case("aws") {
        return Vec::new();
    }

    let mut set = BTreeSet::new();
    for perm in permissions {
        let normalized = perm.trim();
        if !normalized.is_empty() {
            set.insert(normalized.to_string());
        }
    }

    set.into_iter().collect()
}

fn summarize_account(identity: &AccessSummary) -> Option<String> {
    identity
        .account_id
        .clone()
        .filter(|s| !s.trim().is_empty())
        .or_else(|| identity.project.clone().filter(|s| !s.trim().is_empty()))
        .or_else(|| identity.tenant.clone().filter(|s| !s.trim().is_empty()))
        .or_else(|| Some(identity.id.clone()).filter(|s| !s.trim().is_empty()))
}

fn format_resource(resource: &ResourceExposure) -> String {
    let name = resource.name.trim();
    if name.is_empty() {
        return resource.resource_type.clone();
    }

    let resource_type = resource.resource_type.trim();
    if resource_type.is_empty() { name.to_string() } else { format!("{}:{}", resource_type, name) }
}
/// A trait for things that can be output as a document.
///
/// This trait is used to factor output-related code, such as friendly handling
/// of buffering, into one place.
pub trait Reportable {
    type Format;
    fn report<W: std::io::Write>(
        &self,
        format: Self::Format,
        writer: W,
        args: &cli::commands::scan::ScanArgs,
    ) -> Result<()>;
}
impl Reportable for DetailsReporter {
    type Format = ReportOutputFormat;

    fn report<W: std::io::Write>(
        &self,
        format: Self::Format,
        writer: W,
        args: &cli::commands::scan::ScanArgs,
    ) -> Result<()> {
        match format {
            ReportOutputFormat::Pretty => self.pretty_format(writer, args),
            ReportOutputFormat::Json => self.json_format(writer, args),
            ReportOutputFormat::Jsonl => self.jsonl_format(writer, args),
            ReportOutputFormat::Bson => self.bson_format(writer, args),
            ReportOutputFormat::Toon => self.toon_format(writer, args),
            ReportOutputFormat::Sarif => self.sarif_format(writer, args.no_dedup, args),
            ReportOutputFormat::Html => self.html_format(writer, args),
        }
    }
}

fn generated_at_for_scan_timezone(scan_timestamp: Option<&str>) -> String {
    if let Some(scan_timestamp) = scan_timestamp
        && let Ok(scan_dt) = chrono::DateTime::parse_from_rfc3339(scan_timestamp)
    {
        return Utc::now().with_timezone(scan_dt.offset()).to_rfc3339();
    }
    Local::now().to_rfc3339()
}

fn derive_scan_target(args: &cli::commands::scan::ScanArgs) -> Option<String> {
    let mut targets = Vec::new();
    let input_args = &args.input_specifier_args;

    for path in &input_args.path_inputs {
        targets.push(path.display().to_string());
    }
    for git in &input_args.git_url {
        targets.push(git.to_string());
    }
    if let Some(bucket) = &input_args.s3_bucket {
        targets.push(format!("s3://{bucket}"));
    }
    if let Some(bucket) = &input_args.gcs_bucket {
        targets.push(format!("gcs://{bucket}"));
    }
    for image in &input_args.docker_image {
        targets.push(format!("docker://{image}"));
    }
    for archive in &input_args.docker_archive {
        targets.push(format!("docker-archive://{}", archive.display()));
    }
    if input_args.jira_url.is_some() {
        targets.push("jira".to_string());
    }
    if input_args.confluence_url.is_some() {
        targets.push("confluence".to_string());
    }
    if input_args.slack_query.is_some() {
        targets.push("slack".to_string());
    }

    if targets.is_empty() {
        return None;
    }
    if targets.len() == 1 {
        return targets.pop();
    }
    Some(format!("{} targets", targets.len()))
}

/// A match produced by one of kingfisher's rules.
/// This corresponds to a single location.
#[derive(Serialize, JsonSchema, Clone)]
pub struct ReportMatch {
    pub origin: OriginSet,

    #[serde(rename = "blob_metadata")]
    pub blob_metadata: BlobMetadata,

    #[serde(flatten)]
    pub m: Match,

    /// An optional comment assigned to the match
    pub comment: Option<String>,

    /// The confidence level of the match
    pub match_confidence: Confidence,

    /// Whether the match is visible in the output
    pub visible: bool,

    /// Validation Body
    #[serde(
        default,
        serialize_with = "validation_body::serialize",
        deserialize_with = "validation_body::deserialize"
    )]
    #[schemars(schema_with = "validation_body::schema")]
    pub validation_response_body: ValidationResponseBody,

    /// Validation Status Code
    pub validation_response_status: u16,

    /// Validation Success
    pub validation_success: bool,

    /// Semantic validation outcome used for filtering and reporting.
    pub validation_outcome: kingfisher_core::ValidationOutcome,
}

#[derive(Serialize, JsonSchema, Clone, Debug)]
pub struct FindingReporterRecord {
    pub rule: RuleMetadata,
    pub finding: FindingRecordData,
}

#[derive(Serialize, JsonSchema, Clone, Debug)]
pub struct AccessMapEntry {
    pub provider: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub account: Option<String>,
    pub groups: Vec<AccessMapResourceGroup>,
    /// Direct and reachable roles associated with the credential.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub roles: Vec<RoleBinding>,
    #[serde(default)]
    pub token_details: Option<AccessTokenDetails>,
    #[serde(default)]
    pub provider_metadata: Option<ProviderMetadata>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fingerprint: Option<String>,
    /// Permissions classified by severity (admin / privilege_escalation / risky / read_only).
    /// Same shape as PermissionSummary; aggregated across all groups for this identity.
    /// Absent when the underlying provider didn't classify (e.g., imported reports).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permissions_by_severity: Option<PermissionSummary>,
    /// Discriminator context to tell duplicate-named identities apart in the UI.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<AccessIdentityContext>,
}

/// Convert a provider result into the access-map shape consumed by report viewers.
pub fn access_map_entry_from_result(result: &crate::access_map::AccessMapResult) -> AccessMapEntry {
    let account = summarize_account(&result.identity);
    let mut grouped: BTreeMap<Vec<String>, Vec<String>> = BTreeMap::new();

    if result.resources.is_empty() {
        grouped.insert(Vec::new(), vec![result.identity.id.clone()]);
    } else {
        for resource in &result.resources {
            let resource_name = format_resource(resource);
            let permissions = normalize_permissions(&result.cloud, &resource.permissions);
            grouped.entry(permissions).or_default().push(resource_name);
        }
    }

    let mut groups: Vec<AccessMapResourceGroup> = grouped
        .into_iter()
        .map(|(permissions, mut resources)| {
            resources.sort();
            AccessMapResourceGroup { resources, permissions }
        })
        .collect();
    groups.sort_by(|a, b| a.resources.cmp(&b.resources));

    let permissions_by_severity =
        if result.permissions.is_empty() { None } else { Some(result.permissions.clone()) };

    AccessMapEntry {
        provider: result.cloud.clone(),
        account,
        groups,
        roles: result.roles.clone(),
        token_details: result.token_details.clone(),
        provider_metadata: result.provider_metadata.clone(),
        fingerprint: result.fingerprint.clone(),
        permissions_by_severity,
        context: AccessIdentityContext::from_summary(&result.identity),
    }
}

#[derive(Serialize, JsonSchema, Clone, Debug)]
pub struct AccessMapResourceGroup {
    pub resources: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub permissions: Vec<String>,
}

/// Optional identity context (project, tenant, account, host) used by the
/// viewer to disambiguate duplicate-named identities.
#[derive(Serialize, JsonSchema, Clone, Debug, Default)]
pub struct AccessIdentityContext {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tenant: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub account_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub identity_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub access_type: Option<String>,
}

impl AccessIdentityContext {
    fn from_summary(identity: &AccessSummary) -> Option<Self> {
        let project = identity.project.clone().filter(|s| !s.trim().is_empty());
        let tenant = identity.tenant.clone().filter(|s| !s.trim().is_empty());
        let account_id = identity.account_id.clone().filter(|s| !s.trim().is_empty());
        let id = identity.id.clone();
        let identity_id = if id.trim().is_empty() { None } else { Some(id) };
        let access_type = if identity.access_type.trim().is_empty() {
            None
        } else {
            Some(identity.access_type.clone())
        };

        if project.is_none()
            && tenant.is_none()
            && account_id.is_none()
            && identity_id.is_none()
            && access_type.is_none()
        {
            return None;
        }

        Some(Self { project, tenant, account_id, identity_id, access_type })
    }
}

#[derive(Serialize, JsonSchema, Clone, Debug)]
pub struct ReportEnvelope {
    pub findings: Vec<FindingReporterRecord>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub access_map: Option<Vec<AccessMapEntry>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audit: Option<crate::scan_audit::ScanAuditManifest>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<ScanReportMetadata>,
}

#[derive(Serialize, JsonSchema, Clone, Debug)]
pub struct ScanReportMetadata {
    pub generated_at: String,
    pub scan_timestamp: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
    pub command_line_args: Vec<String>,
    pub kingfisher_version: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub latest_version_available: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub update_check_status: Option<String>,
    pub summary: ScanReportSummary,
}

#[derive(Serialize, JsonSchema, Clone, Debug)]
pub struct ScanReportSummary {
    pub findings: usize,
    pub active_findings: usize,
    pub inactive_findings: usize,
    pub locally_derived_findings: usize,
    pub invalid_material_findings: usize,
    pub unknown_validation_findings: usize,
    pub access_map_identities: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rules_applied: Option<usize>,
    pub confidence_level: String,
    pub custom_rules_used: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub successful_validations: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failed_validations: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub skipped_validations: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blobs_scanned: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bytes_scanned: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scan_duration_seconds: Option<f64>,
}

#[derive(Serialize, JsonSchema, Clone, Debug)]
pub struct RuleMetadata {
    /// The display title combining the short and fully qualified rule IDs.
    pub title: String,
    /// The short display ID, with a built-in rule namespace removed.
    pub name: String,
    /// The globally unique rule identifier.
    pub id: String,
    /// The human-readable description declared by the rule.
    pub description: String,
}

#[derive(Serialize, JsonSchema, Clone, Debug)]
pub struct ValidationInfo {
    pub outcome: kingfisher_core::ValidationOutcome,
    pub status: String,
    pub response: String,
}

#[derive(Serialize, JsonSchema, Clone, Debug)]
pub struct FindingRecordData {
    /// Resolved validation context, omitted from redacted reports.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub dependent_captures: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub ambiguous_dependencies: BTreeMap<String, usize>,
    pub snippet: String,
    pub fingerprint: String,
    pub confidence: String,
    pub entropy: String,
    pub validation: ValidationInfo,
    pub language: String,
    pub line: u32,
    pub column_start: u32,
    pub column_end: u32,
    pub path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encoding: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub git_metadata: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub validate_command: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revoke_command: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blast_radius_command: Option<String>,
}

#[cfg(test)]
#[allow(clippy::items_after_test_module)]
mod tests {
    use super::*;
    use crate::{
        blob::{BlobId, BlobMetadata},
        cli::commands::inputs::{ContentFilteringArgs, InputSpecifierArgs},
        cli::commands::output::OutputArgs,
        cli::commands::scan::{ConfidenceLevel, ScanArgs},
        cli::commands::{
            azure::AzureRepoType,
            bitbucket::{BitbucketAuthArgs, BitbucketRepoType},
            gitea::GiteaRepoType,
            github::{GitCloneMode, GitHistoryMode, GitHubRepoType},
            gitlab::GitLabRepoType,
            rules::{RuleCacheArgs, RuleSpecifierArgs},
        },
        findings_store,
        git_commit_metadata::CommitMetadata,
        location::{Location, OffsetSpan, SourcePoint, SourceSpan},
        matcher::{SerializableCapture, SerializableCaptures},
        origin::{Origin, OriginSet},
        rules::rule::{Confidence, Rule, RuleSyntax},
    };
    use gix::{ObjectId, date::Time};
    use smallvec::SmallVec;
    use std::collections::BTreeMap;
    use std::path::PathBuf;
    use std::sync::{Arc, Mutex};
    use tempfile::tempdir;

    fn default_blast_radius_context(
        dependent_captures: &BTreeMap<String, String>,
    ) -> BlastRadiusCommandContext<'_> {
        BlastRadiusCommandContext {
            dependent_captures,
            akid_from_captures: None,
            akid_from_validation_body: None,
            rules_path: &[],
            load_builtins: true,
        }
    }

    #[test]
    fn build_var_args_ignores_unrequired_named_captures() {
        let dependent = BTreeMap::from([
            ("BODY".to_string(), "payload-part".to_string()),
            ("CHECKSUM".to_string(), "abc123".to_string()),
        ]);
        let required = BTreeSet::from(["TOKEN".to_string()]);

        let args = build_var_args(&dependent, None, None, &required);
        assert_eq!(args, "");
    }

    #[test]
    fn build_validate_command_omits_body_checksum_vars_for_vercel_like_http_rule() {
        let validation = crate::rules::Validation::Http(crate::rules::HttpValidation {
            request: crate::rules::HttpRequest {
                method: "GET".to_string(),
                url: "https://api.vercel.com/v2/user".to_string(),
                headers: BTreeMap::from([(
                    "Authorization".to_string(),
                    "Bearer {{TOKEN}}".to_string(),
                )]),
                body: None,
                response_matcher: None,
                multipart: None,
                response_is_html: false,
            },
            multipart: None,
        });
        let dependent = BTreeMap::from([
            ("BODY".to_string(), "payload-part".to_string()),
            ("CHECKSUM".to_string(), "abc123".to_string()),
        ]);

        let cmd = build_validate_command(
            "custom.vercel.token",
            &validation,
            "vcp_testtoken",
            &dependent,
            None,
            None,
        )
        .expect("validate command should be generated");

        assert!(!cmd.contains("--var BODY="), "command should not include BODY var: {}", cmd);
        assert!(
            !cmd.contains("--var CHECKSUM="),
            "command should not include CHECKSUM var: {}",
            cmd
        );
        assert!(cmd.contains("kingfisher validate --rule 'custom.vercel.token'"));
    }

    #[test]
    fn credential_uri_validate_command_uses_uri_instead_of_reported_password() {
        let uri = "postgresql://alice:hunter2@db.internal/app";
        let dependent = BTreeMap::from([("URI".to_string(), uri.to_string())]);

        let command = build_validate_command(
            "betterleaks.generic-credential-uri",
            &crate::rules::Validation::CredentialUri,
            "hunter2",
            &dependent,
            None,
            None,
        )
        .expect("validate command should be generated");

        assert!(command.contains(uri));
        assert!(!command.ends_with("'hunter2'"));
    }

    #[test]
    fn credential_uri_blast_radius_command_requires_supported_database_target() {
        let database_uri = "postgresql://alice:hunter2@db.internal/app";
        let database_captures = BTreeMap::from([
            ("URI".to_string(), database_uri.to_string()),
            ("SCHEME".to_string(), "postgresql".to_string()),
        ]);
        let database_command = build_blast_radius_command(
            "betterleaks.generic-credential-uri",
            &crate::rules::Validation::CredentialUri,
            false,
            "hunter2",
            &default_blast_radius_context(&database_captures),
        )
        .expect("database credential URI should support blast-radius mapping");
        assert!(database_command.contains(database_uri));

        let http_captures = BTreeMap::from([
            ("URI".to_string(), "https://alice:hunter2@service.example/api".to_string()),
            ("SCHEME".to_string(), "https".to_string()),
        ]);
        assert!(
            build_blast_radius_command(
                "betterleaks.generic-credential-uri",
                &crate::rules::Validation::CredentialUri,
                false,
                "hunter2",
                &default_blast_radius_context(&http_captures),
            )
            .is_none()
        );
    }

    #[test]
    fn build_validate_command_includes_static_secret_for_aws_session_token() {
        let dependent = BTreeMap::from([(
            "AWS_SECRET_ACCESS_KEY".to_string(),
            "aws-static-secret".to_string(),
        )]);

        let cmd = build_validate_command(
            "custom.aws.session-token",
            &crate::rules::Validation::AWS,
            "session-token",
            &dependent,
            Some("ASIAIOSFODNN7EXAMPLE"),
            None,
        )
        .expect("validate command should be generated");

        assert!(cmd.contains("--var AKID='ASIAIOSFODNN7EXAMPLE'"), "{cmd}");
        assert!(cmd.contains("--var AWS_SECRET_ACCESS_KEY='aws-static-secret'"), "{cmd}");
        assert!(cmd.ends_with("'session-token'"), "{cmd}");
    }

    #[test]
    fn aws_session_token_blast_radius_command_requires_static_secret() {
        assert!(
            build_blast_radius_command(
                "betterleaks.aws-session-token",
                &crate::rules::Validation::AWS,
                true,
                "session-token",
                &BlastRadiusCommandContext {
                    dependent_captures: &BTreeMap::new(),
                    akid_from_captures: Some("ASIAIOSFODNN7EXAMPLE"),
                    akid_from_validation_body: None,
                    rules_path: &[],
                    load_builtins: true,
                },
            )
            .is_none()
        );

        let dependent = BTreeMap::from([(
            "AWS_SECRET_ACCESS_KEY".to_string(),
            "aws-static-secret".to_string(),
        )]);
        let command = build_blast_radius_command(
            "betterleaks.aws-session-token",
            &crate::rules::Validation::AWS,
            true,
            "session-token",
            &BlastRadiusCommandContext {
                dependent_captures: &dependent,
                akid_from_captures: Some("ASIAIOSFODNN7EXAMPLE"),
                akid_from_validation_body: None,
                rules_path: &[],
                load_builtins: true,
            },
        )
        .expect("complete session credentials should produce a blast-radius command");
        assert!(command.contains("--var AWS_SECRET_ACCESS_KEY='aws-static-secret'"));
    }

    #[test]
    fn aws_session_token_commands_accept_dependency_only_access_key_id() {
        let dependent = BTreeMap::from([
            ("AKID".to_string(), "ASIAIOSFODNN7EXAMPLE".to_string()),
            ("AWS_SECRET_ACCESS_KEY".to_string(), "aws-static-secret".to_string()),
        ]);

        let validate_command = build_validate_command(
            "betterleaks.aws-session-token",
            &crate::rules::Validation::AWS,
            "session-token",
            &dependent,
            None,
            None,
        )
        .expect("dependency-only credentials should produce a validate command");
        assert!(validate_command.contains("--var AKID='ASIAIOSFODNN7EXAMPLE'"));

        let blast_radius_command = build_blast_radius_command(
            "betterleaks.aws-session-token",
            &crate::rules::Validation::AWS,
            true,
            "session-token",
            &default_blast_radius_context(&dependent),
        )
        .expect("dependency-only credentials should produce a blast-radius command");
        assert!(blast_radius_command.contains("--var AKID='ASIAIOSFODNN7EXAMPLE'"));
        assert!(blast_radius_command.contains("--var AWS_SECRET_ACCESS_KEY='aws-static-secret'"));
    }

    #[test]
    fn aws_commands_ignore_empty_dependency_values() {
        let dependent = BTreeMap::from([
            ("AKID".to_string(), String::new()),
            ("AWS_SECRET_ACCESS_KEY".to_string(), "aws-static-secret".to_string()),
        ]);

        let command = build_blast_radius_command(
            "betterleaks.aws-session-token",
            &crate::rules::Validation::AWS,
            true,
            "session-token",
            &BlastRadiusCommandContext {
                dependent_captures: &dependent,
                akid_from_captures: Some("ASIAIOSFODNN7EXAMPLE"),
                akid_from_validation_body: None,
                rules_path: &[],
                load_builtins: true,
            },
        )
        .expect("a non-empty captured access key ID should be used as a fallback");

        assert!(command.contains("--var AKID='ASIAIOSFODNN7EXAMPLE'"));
        assert!(!command.contains("--var AKID=''"));
    }

    #[test]
    fn blast_radius_command_preserves_custom_rule_loading_flags() {
        let rules_path = PathBuf::from("/tmp/team's rules");
        let command = build_blast_radius_command(
            "custom.example",
            &crate::rules::Validation::GCP,
            false,
            "credential",
            &BlastRadiusCommandContext {
                dependent_captures: &BTreeMap::new(),
                akid_from_captures: None,
                akid_from_validation_body: None,
                rules_path: &[rules_path],
                load_builtins: false,
            },
        )
        .expect("custom rule should produce a blast-radius command");

        assert!(command.contains("--rule 'custom.example'"), "{command}");
        assert!(command.contains("--rules-path '/tmp/team'\\''s rules'"), "{command}");
        assert!(command.contains("--no-builtins"), "{command}");
    }

    #[test]
    fn generated_commands_quote_custom_rule_ids() {
        let rule_id = "custom.example; echo unsafe";
        let validation = crate::rules::Validation::GCP;
        let validate = build_validate_command(
            rule_id,
            &validation,
            "credential",
            &BTreeMap::new(),
            None,
            None,
        )
        .expect("custom rule should produce a validate command");
        let blast_radius = build_blast_radius_command(
            rule_id,
            &validation,
            false,
            "credential",
            &default_blast_radius_context(&BTreeMap::new()),
        )
        .expect("custom rule should produce a blast-radius command");

        assert!(validate.contains("--rule 'custom.example; echo unsafe'"), "{validate}");
        assert!(blast_radius.contains("--rule 'custom.example; echo unsafe'"), "{blast_radius}");
    }

    #[test]
    fn extract_template_vars_includes_filter_argument_vars() {
        let text = "Basic {{ NEXT_PUBLIC_VERCEL_APP_CLIENT_ID | default: VERCEL_APP_CLIENT_ID | append: ':' | append: VERCEL_APP_CLIENT_SECRET | b64enc }}";
        let vars = extract_template_vars(text);

        assert!(vars.contains("NEXT_PUBLIC_VERCEL_APP_CLIENT_ID"));
        assert!(vars.contains("VERCEL_APP_CLIENT_ID"));
        assert!(vars.contains("VERCEL_APP_CLIENT_SECRET"));
        assert!(!vars.contains("APPEND"));
        assert!(!vars.contains("DEFAULT"));
        assert!(!vars.contains("B64ENC"));
    }

    #[test]
    fn build_revoke_command_is_emitted_when_required_vars_missing() {
        // Revocation template requires ACCOUNTIDENTIFIER, but the finding doesn't have it.
        let revocation = Revocation::Http(crate::rules::HttpValidation {
            request: crate::rules::HttpRequest {
                method: "DELETE".to_string(),
                url: "https://example.com/revoke?accountIdentifier={{ ACCOUNTIDENTIFIER }}&token={{ TOKEN }}"
                    .to_string(),
                headers: BTreeMap::new(),
                body: None,
                response_matcher: None,
                multipart: None,
                response_is_html: false,
            },
            multipart: None,
        });

        let cmd = build_revoke_command(
            "custom.example.token",
            &revocation,
            "secret",
            &BTreeMap::new(),
            None,
            None,
        );

        let cmd = cmd.expect("command should still be emitted when vars are missing");
        assert!(cmd.contains("kingfisher revoke --rule 'custom.example.token'"));
        assert!(cmd.contains("'secret'"));
    }

    #[test]
    fn betterleaks_aws_revocation_binding_uses_component_as_secret() {
        let mut rules = crate::defaults::get_builtin_rules(Some(Confidence::Low)).unwrap();
        let syntax = rules.rules.remove("betterleaks.aws-access-token").unwrap();
        let Some(crate::rules::Validation::Betterleaks(validation)) = &syntax.validation else {
            panic!("AWS should use Betterleaks validation");
        };
        let bindings = validation.capabilities.revocation_bindings.as_ref().unwrap();
        let component_variable = validation.components["aws-secret-access-key"].clone();
        let mut variables = BTreeMap::from([(
            component_variable,
            "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_string(),
        )]);
        let finding_secret = "AKIAIOSFODNN7EXAMPLE";
        let revocation_secret = resolve_betterleaks_capability_source(
            &bindings.secret,
            finding_secret,
            validation,
            &variables,
        )
        .unwrap()
        .to_string();
        for (name, source) in &bindings.variables {
            let value = resolve_betterleaks_capability_source(
                source,
                finding_secret,
                validation,
                &variables,
            )
            .unwrap()
            .to_string();
            variables.insert(name.clone(), value);
        }

        let cmd = build_revoke_command(
            &syntax.id,
            syntax.revocation.as_ref().unwrap(),
            &revocation_secret,
            &variables,
            None,
            None,
        )
        .unwrap();

        assert!(cmd.contains("--var AKID='AKIAIOSFODNN7EXAMPLE'"), "{cmd}");
        assert!(cmd.ends_with("'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'"), "{cmd}");
    }

    fn sample_scan_args() -> ScanArgs {
        ScanArgs {
            num_jobs: 1,
            rules: RuleSpecifierArgs::default(),
            rule_cache: RuleCacheArgs::default(),
            input_specifier_args: InputSpecifierArgs {
                path_inputs: Vec::new(),
                git_url: Vec::new(),
                git_clone_dir: None,
                keep_clones: false,
                repo_clone_limit: None,
                include_contributors: false,
                github_user: Vec::new(),
                github_include_gists: false,
                github_organization: Vec::new(),
                github_exclude: Vec::new(),
                all_github_organizations: false,
                github_api_url: Url::parse("https://api.github.com/").unwrap(),
                github_repo_type: GitHubRepoType::Source,
                github_event_user: Vec::new(),
                github_event_lookback_hours: 24,
                gitlab_user: Vec::new(),
                gitlab_include_snippets: false,
                gitlab_group: Vec::new(),
                gitlab_exclude: Vec::new(),
                all_gitlab_groups: false,
                gitlab_api_url: Url::parse("https://gitlab.com/").unwrap(),
                gitlab_repo_type: GitLabRepoType::All,
                gitlab_include_subgroups: false,
                huggingface_user: Vec::new(),
                huggingface_organization: Vec::new(),
                huggingface_model: Vec::new(),
                huggingface_dataset: Vec::new(),
                huggingface_space: Vec::new(),
                huggingface_bucket: Vec::new(),
                huggingface_exclude: Vec::new(),
                gitea_user: Vec::new(),
                gitea_organization: Vec::new(),
                gitea_exclude: Vec::new(),
                all_gitea_organizations: false,
                gitea_api_url: Url::parse("https://gitea.com/api/v1/").unwrap(),
                gitea_repo_type: GiteaRepoType::Source,
                bitbucket_user: Vec::new(),
                bitbucket_include_snippets: false,
                bitbucket_workspace: Vec::new(),
                bitbucket_project: Vec::new(),
                bitbucket_exclude: Vec::new(),
                all_bitbucket_workspaces: false,
                bitbucket_api_url: Url::parse("https://api.bitbucket.org/2.0/").unwrap(),
                bitbucket_repo_type: BitbucketRepoType::Source,
                bitbucket_auth: BitbucketAuthArgs::default(),
                azure_organization: Vec::new(),
                azure_project: Vec::new(),
                azure_exclude: Vec::new(),
                all_azure_projects: false,
                azure_base_url: Url::parse("https://dev.azure.com/").unwrap(),
                azure_repo_type: AzureRepoType::Source,
                jira_url: None,
                jql: None,
                jira_include_comments: false,
                jira_include_changelog: false,
                confluence_url: None,
                cql: None,
                slack_query: None,
                slack_api_url: Url::parse("https://slack.com/api/").unwrap(),
                teams_query: None,
                teams_api_url: Url::parse("https://graph.microsoft.com/").unwrap(),
                postman_workspaces: Vec::new(),
                postman_collections: Vec::new(),
                postman_environments: Vec::new(),
                postman_all: false,
                postman_include_mocks_monitors: false,
                postman_api_url: Url::parse("https://api.getpostman.com/").unwrap(),
                max_results: 100,
                s3_bucket: None,
                s3_prefix: None,
                role_arn: None,
                aws_local_profile: None,
                gcs_bucket: None,
                gcs_prefix: None,
                gcs_service_account: None,
                docker_image: Vec::new(),
                docker_archive: Vec::new(),
                git_clone: GitCloneMode::Bare,
                git_history: GitHistoryMode::Full,
                commit_metadata: true,
                repo_artifacts: false,
                scan_nested_repos: true,
                since_commit: None,
                branch: None,
                branch_root: false,
                branch_root_commit: None,
                staged: false,
            },
            extra_ignore_comments: Vec::new(),
            content_filtering_args: ContentFilteringArgs {
                max_file_size_mb: 256.0,
                exclude: Vec::new(),
                no_extract_archives: false,
                extraction_depth: 2,
                no_binary: false,
            },
            confidence: ConfidenceLevel::Medium,
            disk_offload: false,
            no_validate: false,
            access_map: false,
            only_valid: false,
            validation_filter: None,
            include_hidden_findings: false,
            min_entropy: None,
            rule_stats: false,
            no_dedup: false,
            view_report: false,
            redact: false,
            no_base64: false,
            turbo: false,
            git_repo_timeout: 1_800,
            audit_log: None,
            output_args: OutputArgs { output: None, format: ReportOutputFormat::Pretty },
            baseline_file: None,
            manage_baseline: false,
            skip_regex: Vec::new(),
            skip_word: Vec::new(),
            skip_aws_account: Vec::new(),
            skip_aws_account_file: None,
            no_inline_ignore: false,
            no_ignore_if_contains: false,
            view_report_port: 7890,
            view_report_address: "127.0.0.1".to_string(),
            validation_timeout: 10,
            validation_retries: 1,
            validation_rps: None,
            validation_rps_rule: Vec::new(),
            full_validation_response: false,
            max_validation_response_length: 2048,
            alert_webhook: Vec::new(),
            alert_format: None,
            alert_on: crate::alerts::AlertOn::Findings,
            alert_min_confidence: cli::commands::scan::ConfidenceLevel::Medium,
            alert_include_secret: false,
            alert_report_url: None,
            alert_detail: crate::alerts::AlertDetail::Auto,
            alert_finding_filter: crate::alerts::AlertFindingFilter::All,
            alert_prevent_empty: false,
            alert_dry_run: false,
            config_webhook_overrides: Vec::new(),
        }
    }

    fn sample_report_match(
        validation_body: &str,
        validation_status: u16,
        validation_success: bool,
    ) -> (ReportMatch, String) {
        let repo_path = Arc::new(PathBuf::from("/tmp/repo"));
        let commit_metadata = Arc::new(CommitMetadata {
            commit_id: ObjectId::from_hex(b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap(),
            author_name: None,
            author_email: None,
            committer_name: "Alice".into(),
            committer_email: "alice@exmple.com".into(),
            committer_timestamp: Time::new(0, 0),
        });
        let blob_path = "path/in/history.txt".to_string();
        let origin = OriginSet::new(
            Origin::from_git_repo_with_first_commit(repo_path, commit_metadata, blob_path.clone()),
            vec![],
        );

        let rule = Arc::new(Rule::new(RuleSyntax {
            name: "Test Rule".into(),
            id: "test.rule".into(),
            pattern: ".*".into(),
            min_entropy: 0.0,
            confidence: Confidence::Medium,
            visible: true,
            examples: vec![],
            negative_examples: vec![],
            references: vec![],
            validation: None,
            revocation: None,
            depends_on_rule: vec![],
            pattern_requirements: None,
            tls_mode: None,
            path: None,
            betterleaks_filter: None,
            betterleaks_secret_group: None,
            authoritative: true,
            vectorscan_compatible: true,
        }));

        let blob_id = BlobId::new(b"blob-data");
        let validation_body_stored = validation_body::from_string(validation_body);
        let report_match = ReportMatch {
            origin,
            blob_metadata: BlobMetadata {
                id: blob_id,
                num_bytes: 42,
                mime_essence: None,
                language: Some("Unknown".into()),
            },
            m: Match {
                location: Location::with_source_span(
                    OffsetSpan { start: 0, end: 10 },
                    Some(SourceSpan {
                        start: SourcePoint { line: 19, column: 0 },
                        end: SourcePoint { line: 19, column: 10 },
                    }),
                ),
                groups: SerializableCaptures {
                    captures: SmallVec::<[SerializableCapture; 2]>::new(),
                },
                blob_id,
                finding_fingerprint: 123,
                rule: Arc::clone(&rule),
                validation_response_body: validation_body_stored.clone(),
                validation_response_status: validation_status,
                validation_success,
                validation_outcome: if validation_success {
                    kingfisher_core::ValidationOutcome::VerifiedActive
                } else if validation_status == StatusCode::PRECONDITION_REQUIRED.as_u16() {
                    kingfisher_core::ValidationOutcome::Skipped
                } else {
                    kingfisher_core::ValidationOutcome::VerifiedInactive
                },
                calculated_entropy: 5.29,
                visible: true,
                is_base64: false,
                dependent_captures: std::collections::BTreeMap::new(),
                ambiguous_dependencies: Default::default(),
                dependency_candidates: Default::default(),
            },
            comment: None,
            match_confidence: Confidence::Medium,
            visible: true,
            validation_response_body: validation_body_stored,
            validation_response_status: validation_status,
            validation_success,
            validation_outcome: if validation_success {
                kingfisher_core::ValidationOutcome::VerifiedActive
            } else if validation_status == StatusCode::PRECONDITION_REQUIRED.as_u16() {
                kingfisher_core::ValidationOutcome::Skipped
            } else {
                kingfisher_core::ValidationOutcome::VerifiedInactive
            },
        };

        (report_match, blob_path)
    }

    fn build_validation_response(
        validation_body: &str,
        redact: bool,
        full_response: bool,
    ) -> String {
        let temp = tempdir().unwrap();
        let datastore =
            Arc::new(Mutex::new(findings_store::FindingsStore::new(temp.path().to_path_buf())));
        let reporter = DetailsReporter {
            datastore,
            styles: Styles::new(false),
            validation_filter: cli::commands::scan::ValidationFilter::All,
            audit_context: None,
        };

        let (report_match, _) = sample_report_match(validation_body, StatusCode::OK.as_u16(), true);
        let mut scan_args = sample_scan_args();
        scan_args.redact = redact;
        scan_args.full_validation_response = full_response;

        let record = reporter.build_finding_record(&report_match, &scan_args);
        record.finding.validation.response
    }

    #[test]
    fn validation_filters_use_semantic_outcomes() {
        use kingfisher_core::ValidationOutcome;

        let outcomes = [
            ValidationOutcome::VerifiedActive,
            ValidationOutcome::Assumed,
            ValidationOutcome::LocallyDerived,
            ValidationOutcome::InvalidMaterial,
            ValidationOutcome::VerifiedInactive,
            ValidationOutcome::Unavailable,
            ValidationOutcome::Skipped,
            ValidationOutcome::NotAttempted,
        ];
        let temp = tempdir().unwrap();
        let mut store = findings_store::FindingsStore::new(temp.path().to_path_buf());
        let mut batch = Vec::new();
        for (index, outcome) in outcomes.into_iter().enumerate() {
            let (mut report_match, _) = sample_report_match("", StatusCode::OK.as_u16(), false);
            report_match.m.finding_fingerprint = index as u64;
            report_match.m.validation_outcome = outcome;
            batch.push((
                Arc::new(report_match.origin),
                Arc::new(report_match.blob_metadata),
                report_match.m,
            ));
        }
        store.record(batch, false);

        let mut reporter = DetailsReporter {
            datastore: Arc::new(Mutex::new(store)),
            styles: Styles::new(false),
            validation_filter: cli::commands::scan::ValidationFilter::All,
            audit_context: None,
        };
        assert_eq!(reporter.get_filtered_matches(false).unwrap().len(), 8);

        reporter.validation_filter = cli::commands::scan::ValidationFilter::Active;
        assert_eq!(reporter.get_filtered_matches(false).unwrap().len(), 1);

        reporter.validation_filter = cli::commands::scan::ValidationFilter::Actionable;
        let actionable = reporter.get_filtered_matches(false).unwrap();
        assert_eq!(actionable.len(), 3);
        assert!(actionable.iter().all(|finding| finding.validation_outcome.is_actionable()));
    }

    #[test]
    fn report_preserves_declared_custom_yaml_rule_name() {
        let temp = tempdir().unwrap();
        let reporter = DetailsReporter {
            datastore: Arc::new(Mutex::new(findings_store::FindingsStore::new(
                temp.path().to_path_buf(),
            ))),
            styles: Styles::new(false),
            validation_filter: cli::commands::scan::ValidationFilter::All,
            audit_context: None,
        };
        let (mut report_match, _) = sample_report_match("", StatusCode::OK.as_u16(), false);
        let rule = Arc::get_mut(&mut report_match.m.rule).expect("sample rule should be unique");
        rule.syntax.name = "Legacy Custom YAML Rule Name".to_string();
        rule.syntax.id = "private.legacy-rule.1234".to_string();

        let record = reporter.build_finding_record(&report_match, &sample_scan_args());

        assert_eq!(record.rule.name, "private.legacy-rule.1234");
        assert_eq!(record.rule.id, "private.legacy-rule.1234");
        assert_eq!(record.rule.description, "Legacy Custom YAML Rule Name");
    }

    #[test]
    fn report_titles_strip_builtin_rule_namespaces() {
        assert_eq!(display_rule_id("betterleaks.gcp-api-key"), "gcp-api-key");
        assert_eq!(display_rule_id("veles.secrets/npmjsaccesstoken"), "secrets/npmjsaccesstoken");
        assert_eq!(display_rule_id("custom.gcp-api-key"), "custom.gcp-api-key");
    }

    #[test]
    fn report_uses_rule_id_title_and_rule_name_description_for_veles() {
        let temp = tempdir().unwrap();
        let reporter = DetailsReporter {
            datastore: Arc::new(Mutex::new(findings_store::FindingsStore::new(
                temp.path().to_path_buf(),
            ))),
            styles: Styles::new(false),
            validation_filter: cli::commands::scan::ValidationFilter::All,
            audit_context: None,
        };
        let (mut report_match, _) = sample_report_match("", StatusCode::OK.as_u16(), false);
        let rule = Arc::get_mut(&mut report_match.m.rule).expect("sample rule should be unique");
        rule.syntax.name = "npm Access Token".to_string();
        rule.syntax.id = "veles.secrets/npmjsaccesstoken".to_string();

        let record = reporter.build_finding_record(&report_match, &sample_scan_args());

        assert_eq!(record.rule.name, "secrets/npmjsaccesstoken");
        assert_eq!(record.rule.description, "npm Access Token");
    }

    #[test]
    fn build_finding_record_uses_git_blob_path() {
        let temp = tempdir().unwrap();
        let datastore =
            Arc::new(Mutex::new(findings_store::FindingsStore::new(temp.path().to_path_buf())));
        let reporter = DetailsReporter {
            datastore,
            styles: Styles::new(false),
            validation_filter: cli::commands::scan::ValidationFilter::All,
            audit_context: None,
        };

        let (report_match, blob_path) =
            sample_report_match("Bad credentials", StatusCode::UNAUTHORIZED.as_u16(), false);

        let scan_args = sample_scan_args();

        let record = reporter.build_finding_record(&report_match, &scan_args);
        assert_eq!(record.finding.path, blob_path);
        let git_file_path = record
            .finding
            .git_metadata
            .as_ref()
            .and_then(|git| git.get("file"))
            .and_then(|file| file.get("path"))
            .and_then(|path| path.as_str())
            .unwrap();
        assert_eq!(git_file_path, "path/in/history.txt");
    }

    #[test]
    fn skip_list_matches_surface_skip_reason() {
        let temp = tempdir().unwrap();
        let datastore =
            Arc::new(Mutex::new(findings_store::FindingsStore::new(temp.path().to_path_buf())));
        let reporter = DetailsReporter {
            datastore,
            styles: Styles::new(false),
            validation_filter: cli::commands::scan::ValidationFilter::All,
            audit_context: None,
        };

        let (report_match, _) = sample_report_match(
            "(skip list entry) AWS validation not attempted for account 111122223333.",
            StatusCode::PRECONDITION_REQUIRED.as_u16(),
            false,
        );
        let scan_args = sample_scan_args();

        let record = reporter.build_finding_record(&report_match, &scan_args);
        assert_eq!(record.finding.validation.status, "Canary Token (Skipped)");
        assert_eq!(
            record.finding.validation.response,
            "(skip list entry) AWS validation not attempted for account 111122223333."
        );
    }

    #[test]
    fn unavailable_validation_surfaces_as_inconclusive_validation() {
        let temp = tempdir().unwrap();
        let datastore =
            Arc::new(Mutex::new(findings_store::FindingsStore::new(temp.path().to_path_buf())));
        let reporter = DetailsReporter {
            datastore,
            styles: Styles::new(false),
            validation_filter: cli::commands::scan::ValidationFilter::All,
            audit_context: None,
        };

        let (mut report_match, _) = sample_report_match(
            "validator unavailable",
            StatusCode::SERVICE_UNAVAILABLE.as_u16(),
            false,
        );
        report_match.validation_outcome = kingfisher_core::ValidationOutcome::Unavailable;

        let record = reporter.build_finding_record(&report_match, &sample_scan_args());
        assert_eq!(record.finding.validation.status, "Inconclusive Validation");
    }

    #[test]
    fn malformed_local_evidence_uses_safe_placeholder() {
        let temp = tempdir().unwrap();
        let datastore =
            Arc::new(Mutex::new(findings_store::FindingsStore::new(temp.path().to_path_buf())));
        let reporter = DetailsReporter {
            datastore,
            styles: Styles::new(false),
            validation_filter: cli::commands::scan::ValidationFilter::All,
            audit_context: None,
        };

        let (mut report_match, _) = sample_report_match("{}", StatusCode::OK.as_u16(), false);
        Arc::get_mut(&mut report_match.m.rule)
            .expect("sample rule must be uniquely owned")
            .syntax
            .validation = Some(crate::rules::Validation::Ethereum(
            crate::rules::rule::EthereumValidation::PrivateKey,
        ));
        report_match.validation_outcome = kingfisher_core::ValidationOutcome::LocallyDerived;

        let record = reporter.build_finding_record(&report_match, &sample_scan_args());
        assert_eq!(
            record.finding.validation.response,
            "[validation response omitted: local evidence failed sanitization]"
        );
    }

    #[test]
    fn validation_response_truncates_when_flag_off() {
        let body = "a".repeat(513);
        let response = build_validation_response(&body, false, false);
        assert_eq!(response, format!("{}...", "a".repeat(512)));
    }

    #[test]
    fn validation_response_full_when_flag_on() {
        let body = "a".repeat(513);
        let response = build_validation_response(&body, false, true);
        assert_eq!(response, body);
    }

    #[test]
    fn validation_response_truncation_counts_chars() {
        let body = "é".repeat(513);
        let response = build_validation_response(&body, false, false);

        assert!(response.ends_with("..."));
        assert_eq!(response.chars().count(), 515);
        assert!(response.chars().take(512).all(|ch| ch == 'é'));
    }

    #[test]
    fn sanitize_command_line_args_redacts_secret_values() {
        let input = vec![
            "kingfisher".to_string(),
            "scan".to_string(),
            "--token".to_string(),
            "abcd".to_string(),
            "--output=report.html".to_string(),
            "--arg=TOP_SECRET".to_string(),
            "--var".to_string(),
            "TOKEN=inline".to_string(),
            "--alert-webhook".to_string(),
            "https://hooks.slack.com/services/T000/B000/webhook-secret".to_string(),
            "--alert-webhook=https://example.test/hook-secret".to_string(),
            "--path".to_string(),
            "./repo".to_string(),
        ];
        let sanitized = sanitize_command_line_args(&input);

        assert_eq!(sanitized[2], "--token");
        assert_eq!(sanitized[3], "***REDACTED***");
        assert_eq!(sanitized[4], "--output=report.html");
        assert_eq!(sanitized[5], "--arg=***REDACTED***");
        assert_eq!(sanitized[6], "--var");
        assert_eq!(sanitized[7], "***REDACTED***");
        assert_eq!(sanitized[8], "--alert-webhook");
        assert_eq!(sanitized[9], "***REDACTED***");
        assert_eq!(sanitized[10], "--alert-webhook=***REDACTED***");
    }

    #[test]
    fn validation_errors_are_redacted_when_report_redaction_is_enabled() {
        let secret = "validation-secret-should-not-appear";
        let body =
            format!("Validation endpoint resolution failed: https://example.test/?token={secret}");

        let response = build_validation_response(&body, true, true);

        assert!(!response.contains(secret));
        assert!(response.starts_with("[REDACTED:"));
    }

    #[test]
    fn report_envelope_contains_audit_metadata() {
        let temp = tempdir().unwrap();
        let datastore =
            Arc::new(Mutex::new(findings_store::FindingsStore::new(temp.path().to_path_buf())));
        let reporter = DetailsReporter {
            datastore,
            styles: Styles::new(false),
            validation_filter: cli::commands::scan::ValidationFilter::All,
            audit_context: None,
        };

        let mut args = sample_scan_args();
        args.input_specifier_args.path_inputs.push(PathBuf::from("/tmp/project"));

        let envelope = reporter.build_report_envelope(&args).expect("build envelope");
        let metadata = envelope.metadata.expect("metadata should be present");

        assert_eq!(metadata.summary.findings, 0);
        assert_eq!(metadata.summary.active_findings, 0);
        assert_eq!(metadata.summary.inactive_findings, 0);
        assert_eq!(metadata.summary.access_map_identities, 0);
        assert_eq!(metadata.target.as_deref(), Some("/tmp/project"));
        assert_eq!(metadata.kingfisher_version, env!("CARGO_PKG_VERSION"));
    }

    use super::{build_git_urls, gist_file_anchor};

    #[test]
    fn azure_commit_links_use_query_paths() {
        let (repo_url, commit_url, file_url) = build_git_urls(
            "https://dev.azure.com/org/project/_git/repo",
            "0123456789abcdef",
            "dir/file.txt",
            7,
        );

        assert_eq!(repo_url, "https://dev.azure.com/org/project/_git/repo");
        assert_eq!(
            commit_url,
            "https://dev.azure.com/org/project/_git/repo/commit/0123456789abcdef"
        );
        assert_eq!(
            file_url,
            "https://dev.azure.com/org/project/_git/repo/commit/0123456789abcdef?path=/dir/file.txt&line=7"
        );
    }

    #[test]
    fn gist_file_anchor_slugifies_filename() {
        assert_eq!(gist_file_anchor("README.md"), "file-readme-md");
        assert_eq!(gist_file_anchor("dir/hello_world.rb"), "file-hello_world-rb");
        assert_eq!(gist_file_anchor(".git_commit.sh"), "file-git_commit-sh");
        assert_eq!(gist_file_anchor("uniTerm .md"), "file-uniterm-md");
        assert_eq!(gist_file_anchor(".env"), "file-env");
        assert_eq!(gist_file_anchor("token.env."), "file-token-env");
        assert_eq!(gist_file_anchor(r"dir\.env"), "file-env");
    }

    #[test]
    fn gist_dotfile_links_use_normalized_anchors() {
        let (repo_url, commit_url, file_url) =
            build_git_urls("https://gist.github.com/abc/", "def", ".git_commit.sh", 12);
        assert_eq!(repo_url, "https://gist.github.com/abc");
        assert_eq!(commit_url, "https://gist.github.com/abc/def");
        assert_eq!(file_url, "https://gist.github.com/abc/def#file-git_commit-sh-L12");

        let (_, _, file_url) =
            build_git_urls("https://gist.github.com/abc", "def", "uniTerm .md", 0);
        assert_eq!(file_url, "https://gist.github.com/abc/def#file-uniterm-md");
    }

    #[test]
    fn gist_links_skip_blob_paths() {
        let (repo_url, commit_url, file_url) = build_git_urls(
            "https://gist.github.com/alice/0123456789abcdef0123456789abcdef",
            "aabbccddeeff00112233445566778899aabbccdd",
            "secrets/token.env",
            12,
        );

        assert_eq!(repo_url, "https://gist.github.com/alice/0123456789abcdef0123456789abcdef");
        assert_eq!(
            commit_url,
            "https://gist.github.com/alice/0123456789abcdef0123456789abcdef/aabbccddeeff00112233445566778899aabbccdd"
        );
        assert_eq!(
            file_url,
            "https://gist.github.com/alice/0123456789abcdef0123456789abcdef/aabbccddeeff00112233445566778899aabbccdd#file-token-env-L12"
        );
    }

    #[test]
    fn extract_git_metadata_uses_registered_repo_permalink_after_cleanup() {
        let store_root = tempdir().unwrap();
        let datastore = Arc::new(Mutex::new(findings_store::FindingsStore::new(
            store_root.path().to_path_buf(),
        )));

        let repo_root = tempdir().unwrap();
        let repo_path = repo_root.path().to_path_buf();
        drop(repo_root);
        assert!(!repo_path.exists());

        let repo_url = "https://github.com/mongodb/kingfisher.git";
        datastore.lock().unwrap().register_repo_link(repo_path.clone(), repo_url.to_string());

        let reporter = DetailsReporter {
            datastore,
            styles: Styles::new(false),
            validation_filter: cli::commands::scan::ValidationFilter::All,
            audit_context: None,
        };

        let commit_metadata = Arc::new(CommitMetadata {
            commit_id: ObjectId::from_hex(b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap(),
            author_name: Some("Original Author".into()),
            author_email: Some("original@example.invalid".into()),
            committer_name: "Alice".into(),
            committer_email: "alice@exmple.com".into(),
            committer_timestamp: Time::new(0, 0),
        });
        let origin = Origin::from_git_repo_with_first_commit(
            Arc::new(repo_path),
            commit_metadata,
            "tests/smoke_branch.rs".to_string(),
        );
        let source_span = SourceSpan {
            start: SourcePoint { line: 29, column: 0 },
            end: SourcePoint { line: 29, column: 0 },
        };

        let git = match &origin {
            Origin::GitRepo(repo_origin) => reporter
                .extract_git_metadata(repo_origin, &source_span)
                .expect("expected git metadata"),
            _ => unreachable!("expected git origin"),
        };

        assert_eq!(git["commit"]["author"]["name"], "Original Author");
        assert_eq!(git["commit"]["author"]["email"], "original@example.invalid");
        assert_eq!(git["repository_url"].as_str(), Some("https://github.com/mongodb/kingfisher"));
        assert_eq!(
            git["commit"]["url"].as_str(),
            Some(
                "https://github.com/mongodb/kingfisher/commit/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
            )
        );
        assert_eq!(
            git["file"]["url"].as_str(),
            Some(
                "https://github.com/mongodb/kingfisher/blob/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/tests/smoke_branch.rs#L29"
            )
        );
    }
}

impl From<finding_data::FindingDataEntry> for ReportMatch {
    fn from(e: finding_data::FindingDataEntry) -> Self {
        let mut match_val = e.match_val;
        let non_authoritative = !match_val.rule.syntax().is_authoritative();
        if non_authoritative {
            match_val.validation_response_body = None;
            match_val.validation_response_status = 100;
            match_val.validation_success = false;
            match_val.validation_outcome = kingfisher_core::ValidationOutcome::NotAttempted;
        }
        let validation_response_body = match_val.validation_response_body.clone();
        let validation_response_status = match_val.validation_response_status;
        let validation_success = match_val.validation_success;
        let validation_outcome = match_val.validation_outcome;
        ReportMatch {
            origin: e.origin,
            blob_metadata: e.blob_metadata,
            m: match_val,
            comment: e.match_comment,
            visible: e.visible,
            match_confidence: e.match_confidence,
            validation_response_body,
            validation_response_status,
            validation_success,
            validation_outcome,
        }
    }
}