foxguard 0.6.2

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

fn foxguard_cmd() -> Command {
    Command::new(env!("CARGO_BIN_EXE_foxguard"))
}

fn fixture_path(name: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join(name)
}

fn write_secrets_fixture(dir: &Path) -> PathBuf {
    let aws = ["AKIA", "1234567890ABCDEF"].concat();
    let aws_secret = ["ABCD1234+/", "wxyz5678+/", "MNOP9012+/", "qrst3456+/"].concat();
    let github = ["ghp_", "abcdefghijklmnopqrstuvwxyz1234567890"].concat();
    let gitlab = ["gl", "pat-abcdefghijklmnopqrstuvwx123456"].concat();
    let npm = ["npm_", "abcdefghijklmnopqrstuvwxyz1234567890"].concat();
    let slack = ["xoxb", "123456789012", "123456789012", "abcdefghijklmnop"].join("-");
    let stripe = ["sk", "live", "1234567890abcdefghijklmnop"].join("_");
    let private_key = ["-----BEGIN ", "PRIVATE KEY-----"].concat();

    let content = format!(
        "AWS_ACCESS_KEY_ID={aws}\nAWS_SECRET_ACCESS_KEY={aws_secret}\nGITHUB_TOKEN={github}\nGITLAB_TOKEN={gitlab}\nNPM_TOKEN={npm}\nSLACK_TOKEN={slack}\nSTRIPE_SECRET_KEY={stripe}\nPRIVATE_KEY_HEADER={private_key}\n"
    );

    let path = dir.join("secrets.txt");
    fs::write(&path, content).expect("failed to write secrets fixture");
    path
}

fn write_binary_secrets_fixture(dir: &Path) -> PathBuf {
    let secret = ["ghp_", "abcdefghijklmnopqrstuvwxyz1234567890"].concat();
    let path = dir.join("binary-secrets.bin");
    let mut bytes = b"\0BINARY\0".to_vec();
    bytes.extend_from_slice(secret.as_bytes());
    fs::write(&path, bytes).expect("failed to write binary secrets fixture");
    path
}

fn write_secret_file(dir: &Path, relative_path: &str) -> PathBuf {
    let github = ["ghp_", "abcdefghijklmnopqrstuvwxyz1234567890"].concat();
    let path = dir.join(relative_path);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("failed to create secret fixture directory");
    }
    fs::write(&path, format!("GITHUB_TOKEN={github}\n")).expect("failed to write secret file");
    path
}

fn setup_git_repo(files: &[&str]) -> TempDir {
    let repo = TempDir::new().expect("failed to create temp repo");

    Command::new("git")
        .args(["init"])
        .current_dir(repo.path())
        .output()
        .expect("failed to initialize git repo");

    for file in files {
        let src = fixture_path(file);
        let dest = repo.path().join(file);
        fs::copy(src, dest).expect("failed to copy fixture");
    }

    repo
}

fn write_config_file(dir: &Path, relative_path: &str, content: &str) -> PathBuf {
    let path = dir.join(relative_path);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("failed to create config directory");
    }
    fs::write(&path, content).expect("failed to write config file");
    path
}

fn copy_fixture_to(dir: &Path, fixture_name: &str, relative_path: &str) -> PathBuf {
    let src = fixture_path(fixture_name);
    let dest = dir.join(relative_path);
    if let Some(parent) = dest.parent() {
        fs::create_dir_all(parent).expect("failed to create fixture directory");
    }
    fs::copy(src, &dest).expect("failed to copy fixture to target path");
    dest
}

// ─── Python ─────────────────────────────────────────────────────────────────

mod python {
    use super::*;

    #[test]
    fn test_vulnerable_py_finds_all_rules() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable.py", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        // Count grew to 31 when `input()` became a taint source (issues
        // #29/#30): `dangerous()` now additionally fires py/taint-eval on
        // `eval(input("Enter code: "))` alongside the conservative
        // py/no-eval finding.
        assert_eq!(
            findings.len(),
            34,
            "vulnerable.py should have 34 findings, got {}",
            findings.len()
        );

        let rule_ids: std::collections::HashSet<&str> = findings
            .iter()
            .filter_map(|f| f["rule_id"].as_str())
            .collect();

        let expected_rules = [
            "py/no-eval",
            "py/no-hardcoded-secret",
            "py/no-sql-injection",
            "py/no-command-injection",
            "py/no-path-traversal",
            "py/no-ssrf",
            "py/no-weak-crypto",
            "py/no-pickle",
            "py/no-yaml-load",
            "py/no-debug-true",
            "py/no-open-redirect",
            "py/no-cors-star",
            "py/flask-debug-mode",
            "py/django-secret-key-hardcoded",
            "py/flask-secret-key-hardcoded",
            "py/session-cookie-secure-disabled",
            "py/session-cookie-httponly-disabled",
            "py/session-cookie-samesite-disabled",
            "py/csrf-cookie-secure-disabled",
            "py/csrf-cookie-httponly-disabled",
            "py/csrf-cookie-samesite-disabled",
            "py/csrf-exempt",
            "py/wtf-csrf-disabled",
            "py/wtf-csrf-check-default-disabled",
            "py/django-allowed-hosts-wildcard",
            "py/secure-ssl-redirect-disabled",
            "py/jwt-no-verify",
            "py/jwt-hardcoded-secret",
        ];

        for rule in &expected_rules {
            assert!(rule_ids.contains(rule), "missing expected rule: {}", rule);
        }
    }

    /// Regression test for issue #7: Python rules used to string-match callee
    /// text against a fixed sink list, so `import pickle as p; p.loads(x)` and
    /// every other aliased form slipped past. With the per-file import alias
    /// table, each call site should resolve back to its canonical dotted path
    /// and fire.
    #[test]
    fn test_vulnerable_py_aliases_catches_all_bypass_forms() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable_py_aliases.py", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(
            findings.len(),
            18,
            "vulnerable_py_aliases.py should have 18 findings, got {}",
            findings.len()
        );

        let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
        for f in &findings {
            if let Some(rule) = f["rule_id"].as_str() {
                *counts.entry(rule).or_insert(0) += 1;
            }
        }

        // One row per rule that should be exercised by the aliased fixture,
        // with the exact number of bypass forms we expect it to catch.
        let expected: &[(&str, usize)] = &[
            ("py/no-pickle", 4),
            ("py/no-yaml-load", 2),
            ("py/no-weak-crypto", 4),
            ("py/no-ssrf", 2),
            ("py/no-command-injection", 4),
            ("py/no-path-traversal", 2),
        ];

        for (rule, want) in expected {
            let got = counts.get(rule).copied().unwrap_or(0);
            assert_eq!(
                got, *want,
                "rule {} caught {} bypass forms, expected {}",
                rule, got, want
            );
        }
    }

    /// POC for issue #10 intraprocedural taint tracking. Every function in
    /// `vulnerable_py_taint.py` shows a different shape of untrusted Flask
    /// input reaching `pickle.loads`. The taint rule must catch each flow,
    /// and the existing conservative `py/no-pickle` rule must keep firing
    /// alongside it (the two rules coexist by design).
    #[test]
    fn test_vulnerable_py_taint_catches_every_flow() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable_py_taint.py", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
        for f in &findings {
            if let Some(rule) = f["rule_id"].as_str() {
                *counts.entry(rule).or_insert(0) += 1;
            }
        }

        // Sixteen pickle handlers (10 original + 4 added by #15 for nested
        // subscripts and tuple/list destructuring + 2 added by #19 for
        // same-file interprocedural return propagation). Each has one flow:
        // one py/taint-pickle-deserialization finding per handler. The
        // conservative py/no-pickle rule coexists on the same sixteen calls.
        assert_eq!(
            counts.get("py/taint-pickle-deserialization").copied(),
            Some(16),
            "pickle taint rule should fire sixteen times. counts={:?}",
            counts
        );
        assert_eq!(
            counts.get("py/no-pickle").copied(),
            Some(16),
            "NoPickle should still fire sixteen times alongside the taint rule. counts={:?}",
            counts
        );

        // Each py/taint-* rule has one or more dedicated positive handlers
        // and must fire the expected number of times. Its conservative
        // py/no-* counterpart must coexist and keep firing on the same call.
        // Counts bumped by issues #27/#28: command-injection and eval each
        // gain a `request.args.get("...")` handler; sql-injection gains an
        // f-string handler.
        for (taint_rule, conservative_rule, expected) in [
            ("py/taint-eval", "py/no-eval", 2usize),
            // command-injection: 2 original + 1 os.environ.get() source handler
            ("py/taint-command-injection", "py/no-command-injection", 3),
            ("py/taint-ssrf", "py/no-ssrf", 1),
            ("py/taint-yaml-load", "py/no-yaml-load", 1),
            ("py/taint-sql-injection", "py/no-sql-injection", 2),
        ] {
            assert_eq!(
                counts.get(taint_rule).copied(),
                Some(expected),
                "{} should fire exactly {} time(s) on vulnerable_py_taint.py. counts={:?}",
                taint_rule,
                expected,
                counts
            );
            assert!(
                counts.get(conservative_rule).copied().unwrap_or(0) >= 1,
                "conservative {} must coexist with {}. counts={:?}",
                conservative_rule,
                taint_rule,
                counts
            );
        }

        // New taint-only rules (no conservative counterpart).
        for (taint_rule, expected) in [
            ("py/taint-ssti", 1usize),
            ("py/taint-xpath-injection", 1),
            ("py/taint-ldap-injection", 1),
            ("py/taint-log-injection", 1),
            ("py/taint-xxe", 1),
            ("py/taint-nosql-injection", 1),
        ] {
            assert_eq!(
                counts.get(taint_rule).copied(),
                Some(expected),
                "{} should fire exactly {} time(s) on vulnerable_py_taint.py. counts={:?}",
                taint_rule,
                expected,
                counts
            );
        }
    }

    /// Negative counterpart for the taint POC. Every pickle.loads call in
    /// `safe_py_taint.py` receives a non-tainted argument (static literal,
    /// reassignment kills taint, local variable named `request`, cross-function
    /// taint that the engine intentionally does not track). The taint rule
    /// must not fire at all. NoPickle still fires on every call — that's the
    /// intended division of labor between the conservative and precision
    /// rules.
    #[test]
    fn test_safe_py_taint_has_no_taint_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/safe_py_taint.py", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        for taint_rule in [
            "py/taint-pickle-deserialization",
            "py/taint-eval",
            "py/taint-command-injection",
            "py/taint-ssrf",
            "py/taint-yaml-load",
            "py/taint-sql-injection",
            "py/taint-ssti",
            "py/taint-xpath-injection",
            "py/taint-ldap-injection",
            "py/taint-log-injection",
            "py/taint-xxe",
            "py/taint-nosql-injection",
        ] {
            let n = findings
                .iter()
                .filter(|f| f["rule_id"].as_str() == Some(taint_rule))
                .count();
            assert_eq!(
                n, 0,
                "{} should not fire on safe_py_taint.py, got {} findings",
                taint_rule, n
            );
        }
    }

    /// Positive Django fixture for issues #29/#30: every handler flows an
    /// untrusted `HttpRequest` attribute into a taint sink via subscript
    /// access. Each taint rule must fire exactly once.
    #[test]
    fn test_vulnerable_django_taint_catches_flows() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable_django_taint.py", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
        for f in &findings {
            if let Some(rule) = f["rule_id"].as_str() {
                *counts.entry(rule).or_insert(0) += 1;
            }
        }

        for rule in [
            "py/taint-pickle-deserialization",
            "py/taint-command-injection",
            "py/taint-eval",
            "py/taint-yaml-load",
            "py/taint-ssrf",
        ] {
            assert_eq!(
                counts.get(rule).copied(),
                Some(1),
                "{} should fire exactly once on vulnerable_django_taint.py. counts={:?}",
                rule,
                counts
            );
        }
    }

    /// Negative Django fixture for issue #29: every sink gets a trusted
    /// argument, so no `py/taint-*` rule may fire.
    #[test]
    fn test_safe_django_taint_has_no_taint_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/safe_django_taint.py", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        for taint_rule in [
            "py/taint-pickle-deserialization",
            "py/taint-eval",
            "py/taint-command-injection",
            "py/taint-ssrf",
            "py/taint-yaml-load",
            "py/taint-sql-injection",
        ] {
            let n = findings
                .iter()
                .filter(|f| f["rule_id"].as_str() == Some(taint_rule))
                .count();
            assert_eq!(
                n, 0,
                "{} should not fire on safe_django_taint.py, got {} findings",
                taint_rule, n
            );
        }
    }

    /// Positive FastAPI/Starlette fixture for issue #29. Covers attribute
    /// sources (`query_params`, `path_params`) and the handler-parameter
    /// name widening that recognizes `req: Request`.
    #[test]
    fn test_vulnerable_fastapi_taint_catches_flows() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable_fastapi_taint.py", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
        for f in &findings {
            if let Some(rule) = f["rule_id"].as_str() {
                *counts.entry(rule).or_insert(0) += 1;
            }
        }

        for rule in [
            "py/taint-pickle-deserialization",
            "py/taint-command-injection",
            "py/taint-eval",
        ] {
            assert_eq!(
                counts.get(rule).copied(),
                Some(1),
                "{} should fire exactly once on vulnerable_fastapi_taint.py. counts={:?}",
                rule,
                counts
            );
        }
    }

    /// Negative FastAPI/Starlette fixture for issue #29.
    #[test]
    fn test_safe_fastapi_taint_has_no_taint_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/safe_fastapi_taint.py", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        for taint_rule in [
            "py/taint-pickle-deserialization",
            "py/taint-eval",
            "py/taint-command-injection",
            "py/taint-ssrf",
            "py/taint-yaml-load",
            "py/taint-sql-injection",
        ] {
            let n = findings
                .iter()
                .filter(|f| f["rule_id"].as_str() == Some(taint_rule))
                .count();
            assert_eq!(
                n, 0,
                "{} should not fire on safe_fastapi_taint.py, got {} findings",
                taint_rule, n
            );
        }
    }

    /// Positive CLI fixture for issue #30: `sys.argv`, `os.getenv`,
    /// `os.environ[...]`, `input()`, and `sys.stdin.read()` flowing into
    /// command-injection and eval sinks. Expects three
    /// command-injection findings (argv, getenv, environ subscript) and
    /// two eval findings (input, stdin.read).
    #[test]
    fn test_vulnerable_cli_taint_catches_flows() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable_cli_taint.py", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
        for f in &findings {
            if let Some(rule) = f["rule_id"].as_str() {
                *counts.entry(rule).or_insert(0) += 1;
            }
        }

        assert_eq!(
            counts.get("py/taint-command-injection").copied(),
            Some(3),
            "py/taint-command-injection should fire three times on vulnerable_cli_taint.py. counts={:?}",
            counts
        );
        assert_eq!(
            counts.get("py/taint-eval").copied(),
            Some(2),
            "py/taint-eval should fire twice on vulnerable_cli_taint.py. counts={:?}",
            counts
        );
    }

    /// Negative CLI fixture for issue #30.
    #[test]
    fn test_safe_cli_taint_has_no_taint_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/safe_cli_taint.py", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        for taint_rule in [
            "py/taint-pickle-deserialization",
            "py/taint-eval",
            "py/taint-command-injection",
            "py/taint-ssrf",
            "py/taint-yaml-load",
            "py/taint-sql-injection",
        ] {
            let n = findings
                .iter()
                .filter(|f| f["rule_id"].as_str() == Some(taint_rule))
                .count();
            assert_eq!(
                n, 0,
                "{} should not fire on safe_cli_taint.py, got {} findings",
                taint_rule, n
            );
        }
    }

    /// Negative regression for issue #7: aliased imports of the *same* sensitive
    /// modules, but called in safe shapes (static literals, SafeLoader, sha256,
    /// write-only pickle methods). Alias resolution must not silently widen the
    /// match surface — this file should still produce zero findings.
    #[test]
    fn test_safe_py_aliases_no_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/safe_py_aliases.py", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(
            output.status.success(),
            "safe_py_aliases.py should exit zero"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(
            findings.len(),
            0,
            "safe_py_aliases.py should have 0 findings, got {:?}",
            findings
        );
    }

    #[test]
    fn test_safe_py_no_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/safe.py", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(output.status.success(), "safe.py should exit zero");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(findings.len(), 0, "safe.py should have 0 findings");
    }
}

// ─── JavaScript ─────────────────────────────────────────────────────────────

mod javascript {
    use super::*;

    #[test]
    fn test_vulnerable_js_finds_all_rules() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable.js", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(
            !output.status.success(),
            "should exit non-zero when findings exist"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(
            findings.len(),
            32,
            "vulnerable.js should have 32 findings, got {}",
            findings.len()
        );

        // Verify all unique rule IDs are present
        let rule_ids: std::collections::HashSet<&str> = findings
            .iter()
            .filter_map(|f| f["rule_id"].as_str())
            .collect();

        let expected_rules = [
            "js/no-eval",
            "js/no-hardcoded-secret",
            "js/no-sql-injection",
            "js/no-xss-innerhtml",
            "js/no-command-injection",
            "js/no-document-write",
            "js/no-open-redirect",
            "js/no-weak-crypto",
            "js/no-path-traversal",
            "js/no-ssrf",
            "js/no-prototype-pollution",
            "js/no-unsafe-regex",
            "js/no-cors-star",
            "js/express-no-hardcoded-session-secret",
            "js/express-cookie-no-secure",
            "js/express-cookie-no-httponly",
            "js/express-cookie-no-samesite",
            "js/express-session-saveuninitialized-true",
            "js/express-direct-response-write",
            "js/jwt-hardcoded-secret",
            "js/jwt-none-algorithm",
            "js/jwt-ignore-expiration",
            "js/jwt-decode-without-verify",
            "js/jwt-verify-missing-algorithms",
            "js/no-unsafe-deserialization",
        ];

        for rule in &expected_rules {
            assert!(rule_ids.contains(rule), "missing expected rule: {}", rule);
        }
    }

    /// POC for issue #18 intraprocedural JS/TS taint tracking. Every handler
    /// in `vulnerable_js_taint.js` shows a different shape of untrusted
    /// Express input reaching an innerHTML/document.write sink. The taint
    /// rule must catch each flow, and the existing conservative
    /// `js/no-xss-innerhtml` / `js/no-document-write` rules must keep firing
    /// alongside it (the two rule classes coexist by design).
    #[test]
    fn test_vulnerable_js_taint_catches_every_flow() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable_js_taint.js", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
        for f in &findings {
            if let Some(rule) = f["rule_id"].as_str() {
                *counts.entry(rule).or_insert(0) += 1;
            }
        }

        // Ten handlers, each with exactly one source->sink flow (six
        // original + two added by #19 for same-file interprocedural return
        // propagation + one added by #27 for method-call propagation on a
        // tainted root `req.body.toString()` + one added by #119 for spread
        // element taint propagation `[...req.body]`).
        assert_eq!(
            counts.get("js/taint-xss-innerhtml").copied(),
            Some(10),
            "js/taint-xss-innerhtml should fire exactly ten times. counts={:?}",
            counts
        );
        // The conservative rules must still coexist on the same fixture.
        assert!(
            counts.get("js/no-xss-innerhtml").copied().unwrap_or(0) >= 1,
            "js/no-xss-innerhtml must coexist with the taint rule. counts={:?}",
            counts
        );
        assert!(
            counts.get("js/no-document-write").copied().unwrap_or(0) >= 1,
            "js/no-document-write must coexist with the taint rule. counts={:?}",
            counts
        );

        // LDAP injection test added for issue #133.
        assert_eq!(
            counts.get("js/taint-ldap-injection").copied(),
            Some(1),
            "js/taint-ldap-injection should fire exactly once. counts={:?}",
            counts
        );
    }

    /// Negative counterpart for the JS/TS taint POC. Every innerHTML/
    /// document.write sink call here receives a non-tainted argument (static
    /// literal, reassignment kills taint, local variable named `request`,
    /// cross-function taint the engine intentionally does not track). The
    /// taint rule must not fire at all.
    #[test]
    fn test_safe_js_taint_has_no_taint_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/safe_js_taint.js", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        for taint_rule in [
            "js/taint-xss-innerhtml",
            "js/taint-sql-injection",
            "js/taint-command-injection",
            "js/taint-ldap-injection",
            "js/taint-nosql-injection",
        ] {
            let n = findings
                .iter()
                .filter(|f| f["rule_id"].as_str() == Some(taint_rule))
                .count();
            assert_eq!(
                n, 0,
                "{} should not fire on safe_js_taint.js, got {} findings",
                taint_rule, n
            );
        }
    }

    /// Issue #32 — Next.js App Router taint sources. `request` is the
    /// ParamName-seeded handler input and `request.nextUrl` is a Next.js
    /// specific Attribute source. Both handlers must fire exactly once.
    #[test]
    fn test_vulnerable_nextjs_taint_catches_flow() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable_nextjs_taint.ts", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let n = findings
            .iter()
            .filter(|f| f["rule_id"].as_str() == Some("js/taint-xss-innerhtml"))
            .count();
        assert_eq!(
            n, 2,
            "js/taint-xss-innerhtml should fire exactly twice on vulnerable_nextjs_taint.ts, got {} findings: {:?}",
            n, findings
        );
    }

    #[test]
    fn test_safe_nextjs_taint_has_no_taint_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/safe_nextjs_taint.ts", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let n = findings
            .iter()
            .filter(|f| f["rule_id"].as_str() == Some("js/taint-xss-innerhtml"))
            .count();
        assert_eq!(
            n, 0,
            "js/taint-xss-innerhtml should not fire on safe_nextjs_taint.ts, got {} findings",
            n
        );
    }

    /// Issue #32 — Hono taint sources. `c` is intentionally NOT a ParamName
    /// matcher; the engine must pick up `c.req.query(...)` / `c.req.param(...)`
    /// through the explicit `Call` matchers.
    #[test]
    fn test_vulnerable_hono_taint_catches_flow() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable_hono_taint.ts", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let n = findings
            .iter()
            .filter(|f| f["rule_id"].as_str() == Some("js/taint-xss-innerhtml"))
            .count();
        assert_eq!(
            n, 2,
            "js/taint-xss-innerhtml should fire exactly twice on vulnerable_hono_taint.ts, got {} findings: {:?}",
            n, findings
        );
    }

    #[test]
    fn test_safe_hono_taint_has_no_taint_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/safe_hono_taint.ts", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let n = findings
            .iter()
            .filter(|f| f["rule_id"].as_str() == Some("js/taint-xss-innerhtml"))
            .count();
        assert_eq!(
            n, 0,
            "js/taint-xss-innerhtml should not fire on safe_hono_taint.ts, got {} findings",
            n
        );
    }

    /// Issue #32 — Deno taint sources. `Deno.args` is an Attribute source,
    /// `Deno.env.get(...)` is a Call source. The engine only analyzes
    /// function bodies, so the fixture wraps its sinks accordingly.
    #[test]
    fn test_vulnerable_deno_taint_catches_flow() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable_deno_taint.ts", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let n = findings
            .iter()
            .filter(|f| f["rule_id"].as_str() == Some("js/taint-xss-innerhtml"))
            .count();
        assert_eq!(
            n, 2,
            "js/taint-xss-innerhtml should fire exactly twice on vulnerable_deno_taint.ts, got {} findings: {:?}",
            n, findings
        );
    }

    #[test]
    fn test_safe_deno_taint_has_no_taint_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/safe_deno_taint.ts", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let n = findings
            .iter()
            .filter(|f| f["rule_id"].as_str() == Some("js/taint-xss-innerhtml"))
            .count();
        assert_eq!(
            n, 0,
            "js/taint-xss-innerhtml should not fire on safe_deno_taint.ts, got {} findings",
            n
        );
    }

    #[test]
    fn test_safe_js_no_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/safe.js", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(output.status.success(), "safe.js should exit zero");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(findings.len(), 0, "safe.js should have 0 findings");
    }
}

// ─── Go ─────────────────────────────────────────────────────────────────────

mod go {
    use super::*;

    #[test]
    fn test_vulnerable_go_finds_all_rules() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable.go", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(
            findings.len(),
            15,
            "vulnerable.go should have 15 findings, got {}",
            findings.len()
        );

        let rule_ids: std::collections::HashSet<&str> = findings
            .iter()
            .filter_map(|f| f["rule_id"].as_str())
            .collect();

        let expected_rules = [
            "go/no-sql-injection",
            "go/no-command-injection",
            "go/no-hardcoded-secret",
            "go/no-weak-crypto",
            "go/no-ssrf",
            "go/insecure-tls-skip-verify",
            "go/net-http-no-timeout",
            "go/no-unsafe-deserialization",
            "go/jwt-no-verify",
            "go/jwt-hardcoded-secret",
        ];

        for rule in &expected_rules {
            assert!(rule_ids.contains(rule), "missing expected rule: {}", rule);
        }
    }

    /// Positive fixture for the Go taint engine: each handler flows an
    /// untrusted source (Gin/net/http/Echo/Fiber/env) into a
    /// command-injection, SQL-injection, or SSRF sink. Each go/taint-*
    /// rule must fire the expected number of times and its conservative
    /// go/no-* counterpart must coexist.
    #[test]
    fn test_vulnerable_go_taint_catches_every_flow() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable_go_taint.go", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
        for f in &findings {
            if let Some(rule) = f["rule_id"].as_str() {
                *counts.entry(rule).or_insert(0) += 1;
            }
        }

        // Five command-injection handlers, three SQL, three SSRF,
        // one SSTI, one XPath, one LDAP.
        for (taint_rule, conservative_rule, expected) in [
            (
                "go/taint-command-injection",
                "go/no-command-injection",
                5usize,
            ),
            ("go/taint-sql-injection", "go/no-sql-injection", 3),
            ("go/taint-ssrf", "go/no-ssrf", 3),
        ] {
            assert_eq!(
                counts.get(taint_rule).copied(),
                Some(expected),
                "{} should fire exactly {} time(s) on vulnerable_go_taint.go. counts={:?}",
                taint_rule,
                expected,
                counts
            );
            assert!(
                counts.get(conservative_rule).copied().unwrap_or(0) >= 1,
                "conservative {} must coexist with {}. counts={:?}",
                conservative_rule,
                taint_rule,
                counts
            );
        }

        // New taint rules without conservative counterparts.
        for (taint_rule, expected) in [
            ("go/taint-ssti", 1usize),
            ("go/taint-xpath-injection", 1),
            ("go/taint-ldap-injection", 1),
            ("go/taint-log-injection", 1),
            ("go/taint-nosql-injection", 1),
            ("go/taint-path-traversal", 3),
        ] {
            assert_eq!(
                counts.get(taint_rule).copied(),
                Some(expected),
                "{} should fire exactly {} time(s) on vulnerable_go_taint.go. counts={:?}",
                taint_rule,
                expected,
                counts
            );
        }
    }

    /// Negative counterpart for the Go taint engine. Every handler in
    /// `safe_go_taint.go` either uses a literal argument, has its
    /// taint killed by reassignment, or relies on cross-function
    /// isolation. No go/taint-* rule may fire.
    #[test]
    fn test_safe_go_taint_has_no_taint_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/safe_go_taint.go", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        for taint_rule in [
            "go/taint-command-injection",
            "go/taint-sql-injection",
            "go/taint-ssrf",
            "go/taint-ssti",
            "go/taint-xpath-injection",
            "go/taint-ldap-injection",
            "go/taint-log-injection",
            "go/taint-nosql-injection",
            "go/taint-path-traversal",
        ] {
            let n = findings
                .iter()
                .filter(|f| f["rule_id"].as_str() == Some(taint_rule))
                .count();
            assert_eq!(
                n, 0,
                "{} should not fire on safe_go_taint.go, got {} findings",
                taint_rule, n
            );
        }
    }

    #[test]
    fn test_safe_go_no_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/safe.go", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(output.status.success(), "safe.go should exit zero");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(findings.len(), 0, "safe.go should have 0 findings");
    }
}

// ─── Java ───────────────────────────────────────────────────────────────────

mod java {
    use super::*;

    #[test]
    fn test_vulnerable_java_finds_all_rules() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable.java", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(
            findings.len(),
            22,
            "vulnerable.java should have 22 findings, got {}",
            findings.len()
        );

        let rule_ids: std::collections::HashSet<&str> = findings
            .iter()
            .filter_map(|f| f["rule_id"].as_str())
            .collect();

        let expected_rules = [
            "java/no-sql-injection",
            "java/no-command-injection",
            "java/no-unsafe-deserialization",
            "java/no-ssrf",
            "java/no-path-traversal",
            "java/no-weak-crypto",
            "java/no-hardcoded-secret",
            "java/no-xxe",
            "java/spring-csrf-disabled",
            "java/spring-cors-permissive",
            "java/no-xss",
        ];

        for rule in &expected_rules {
            assert!(rule_ids.contains(rule), "missing expected rule: {}", rule);
        }
    }
}

// ─── PHP ────────────────────────────────────────────────────────────────────

mod php {
    use super::*;

    #[test]
    fn test_vulnerable_php_finds_all_rules() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable.php", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(
            findings.len(),
            20,
            "vulnerable.php should have 20 findings, got {}",
            findings.len()
        );

        let rule_ids: std::collections::HashSet<&str> = findings
            .iter()
            .filter_map(|f| f["rule_id"].as_str())
            .collect();

        let expected_rules = [
            "php/no-eval",
            "php/no-command-injection",
            "php/no-sql-injection",
            "php/no-unserialize",
            "php/no-file-inclusion",
            "php/no-weak-crypto",
            "php/no-hardcoded-secret",
            "php/no-ssrf",
            "php/no-extract",
            "php/no-preg-eval",
        ];

        for rule in &expected_rules {
            assert!(rule_ids.contains(rule), "missing expected rule: {}", rule);
        }
    }
}

// ─── Ruby ───────────────────────────────────────────────────────────────────

mod ruby {
    use super::*;

    #[test]
    fn test_vulnerable_ruby_finds_all_rules() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable.rb", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(
            findings.len(),
            30,
            "vulnerable.rb should have 30 findings, got {}",
            findings.len()
        );

        let rule_ids: std::collections::HashSet<&str> = findings
            .iter()
            .filter_map(|f| f["rule_id"].as_str())
            .collect();

        let expected_rules = [
            "rb/no-eval",
            "rb/no-command-injection",
            "rb/no-sql-injection",
            "rb/no-mass-assignment",
            "rb/no-unsafe-deserialization",
            "rb/no-open-redirect",
            "rb/no-csrf-skip",
            "rb/no-html-safe",
            "rb/no-hardcoded-secret",
            "rb/no-weak-crypto",
            "rb/no-ssrf",
            "rb/no-path-traversal",
        ];

        for rule in &expected_rules {
            assert!(rule_ids.contains(rule), "missing expected rule: {}", rule);
        }
    }

    #[test]
    fn test_safe_ruby_no_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/safe.rb", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(output.status.success());

        let stdout = String::from_utf8_lossy(&output.stdout);
        if !stdout.trim().is_empty() {
            let findings: Vec<serde_json::Value> =
                serde_json::from_str(stdout.trim()).unwrap_or_default();
            assert_eq!(
                findings.len(),
                0,
                "safe.rb should have 0 findings, got {}",
                findings.len()
            );
        }
    }
}

// ─── C# ─────────────────────────────────────────────────────────────────────

mod csharp {
    use super::*;

    #[test]
    fn test_vulnerable_csharp_finds_all_rules() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable.cs", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(
            findings.len(),
            17,
            "vulnerable.cs should have 17 findings, got {}",
            findings.len()
        );

        let rule_ids: std::collections::HashSet<&str> = findings
            .iter()
            .filter_map(|f| f["rule_id"].as_str())
            .collect();

        let expected_rules = [
            "cs/no-sql-injection",
            "cs/no-command-injection",
            "cs/no-unsafe-deserialization",
            "cs/no-ssrf",
            "cs/no-path-traversal",
            "cs/no-weak-crypto",
            "cs/no-hardcoded-secret",
            "cs/no-xxe",
            "cs/no-ldap-injection",
            "cs/no-cors-star",
        ];

        for rule in &expected_rules {
            assert!(rule_ids.contains(rule), "missing expected rule: {}", rule);
        }
    }
}

// ─── Swift ──────────────────────────────────────────────────────────────────

mod swift {
    use super::*;

    #[test]
    fn test_vulnerable_swift_finds_all_rules() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable.swift", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(
            findings.len(),
            19,
            "vulnerable.swift should have 19 findings, got {}",
            findings.len()
        );

        let rule_ids: std::collections::HashSet<&str> = findings
            .iter()
            .filter_map(|f| f["rule_id"].as_str())
            .collect();

        let expected_rules = [
            "swift/no-hardcoded-secret",
            "swift/no-command-injection",
            "swift/no-weak-crypto",
            "swift/no-insecure-transport",
            "swift/no-eval-js",
            "swift/no-sql-injection",
            "swift/no-insecure-keychain",
            "swift/no-tls-disabled",
            "swift/no-path-traversal",
            "swift/no-ssrf",
        ];

        for rule in &expected_rules {
            assert!(rule_ids.contains(rule), "missing expected rule: {}", rule);
        }
    }
}

// ─── Rust ───────────────────────────────────────────────────────────────────

mod rust_lang {
    use super::*;

    #[test]
    fn test_vulnerable_rust_finds_all_rules() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable.rs", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(
            findings.len(),
            18,
            "vulnerable.rs should have 18 findings, got {}",
            findings.len()
        );

        let rule_ids: std::collections::HashSet<&str> = findings
            .iter()
            .filter_map(|f| f["rule_id"].as_str())
            .collect();

        let expected_rules = [
            "rs/unsafe-block",
            "rs/transmute-usage",
            "rs/no-command-injection",
            "rs/no-sql-injection",
            "rs/no-weak-hash",
            "rs/no-hardcoded-secret",
            "rs/tls-verify-disabled",
            "rs/no-ssrf",
            "rs/no-path-traversal",
            "rs/no-unwrap-in-lib",
        ];

        for rule in &expected_rules {
            assert!(rule_ids.contains(rule), "missing expected rule: {}", rule);
        }
    }
}

// ─── Cross-file / realistic fixture tests ───────────────────────────────────

mod cross_file {
    use super::*;

    /// End-to-end validation: a small realistic Gin service with three
    /// planted vulnerabilities (command injection, SQL injection, SSRF)
    /// must produce exactly one finding per go/taint-* rule.
    #[test]
    fn test_realistic_gin_app_findings() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/realistic/gin_app.go", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
        for f in &findings {
            if let Some(rule) = f["rule_id"].as_str() {
                *counts.entry(rule).or_insert(0) += 1;
            }
        }

        for rule in [
            "go/taint-command-injection",
            "go/taint-sql-injection",
            "go/taint-ssrf",
        ] {
            assert_eq!(
                counts.get(rule).copied(),
                Some(1),
                "{} should fire exactly once on realistic/gin_app.go. counts={:?}",
                rule,
                counts
            );
        }
    }

    /// Semgrep-compatible `mode: taint` YAML rules should load via `--rules`
    /// and fire on the same flows as the native `py/taint-pickle-deserialization`
    /// rule. See issue #17.
    #[test]
    fn test_semgrep_taint_yaml_bridge_vulnerable() {
        let output = foxguard_cmd()
            .args([
                "tests/fixtures/vulnerable_py_taint.py",
                "-f",
                "json",
                "--no-builtins",
                "--rules",
                "tests/fixtures/semgrep_taint/pickle_taint.yml",
            ])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let lines: Vec<u64> = findings
            .iter()
            .filter(|f| f["rule_id"].as_str() == Some("semgrep/semgrep-pickle-taint"))
            .filter_map(|f| f["line"].as_u64())
            .collect();

        assert!(
            !lines.is_empty(),
            "semgrep taint rule should fire at least once on vulnerable_py_taint.py, got: {:?}",
            findings
        );

        // Every pickle handler in the fixture (16 flows, matching the native
        // py/taint-pickle-deserialization rule) should be caught by the YAML
        // bridge. Asserting the exact count keeps the bridge honest: regressions
        // in pattern translation or the taint engine will flip this number.
        assert_eq!(
            lines.len(),
            16,
            "semgrep taint rule should fire on all 16 pickle flows, got {} (lines: {:?})",
            lines.len(),
            lines
        );
    }

    #[test]
    fn test_semgrep_taint_yaml_bridge_safe() {
        let output = foxguard_cmd()
            .args([
                "tests/fixtures/safe_py_taint.py",
                "-f",
                "json",
                "--no-builtins",
                "--rules",
                "tests/fixtures/semgrep_taint/pickle_taint.yml",
            ])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let n = findings
            .iter()
            .filter(|f| f["rule_id"].as_str() == Some("semgrep/semgrep-pickle-taint"))
            .count();

        assert_eq!(
            n, 0,
            "semgrep taint rule should not fire on safe_py_taint.py, got {} findings",
            n
        );
    }

    /// The Semgrep taint bridge must accept `pattern-either:` blocks inside
    /// `pattern-sources` / `pattern-sinks` (issue #33). The
    /// `pickle_taint_either.yml` fixture expresses the same sources and sinks
    /// as `pickle_taint.yml`, just using `pattern-either:` to group them, and
    /// must produce the same 16 findings on `vulnerable_py_taint.py`.
    #[test]
    fn test_semgrep_taint_yaml_bridge_pattern_either_vulnerable() {
        let output = foxguard_cmd()
            .args([
                "tests/fixtures/vulnerable_py_taint.py",
                "-f",
                "json",
                "--no-builtins",
                "--rules",
                "tests/fixtures/semgrep_taint/pickle_taint_either.yml",
            ])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let lines: Vec<u64> = findings
            .iter()
            .filter(|f| f["rule_id"].as_str() == Some("semgrep/semgrep-pickle-taint-either"))
            .filter_map(|f| f["line"].as_u64())
            .collect();

        assert_eq!(
            lines.len(),
            16,
            "semgrep pattern-either taint rule should fire on all 16 pickle flows, got {} (lines: {:?})",
            lines.len(),
            lines
        );
    }

    #[test]
    fn test_semgrep_taint_yaml_bridge_pattern_either_safe() {
        let output = foxguard_cmd()
            .args([
                "tests/fixtures/safe_py_taint.py",
                "-f",
                "json",
                "--no-builtins",
                "--rules",
                "tests/fixtures/semgrep_taint/pickle_taint_either.yml",
            ])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let n = findings
            .iter()
            .filter(|f| f["rule_id"].as_str() == Some("semgrep/semgrep-pickle-taint-either"))
            .count();

        assert_eq!(
            n, 0,
            "semgrep pattern-either taint rule should not fire on safe_py_taint.py, got {} findings",
            n
        );
    }

    /// The Semgrep taint YAML bridge should fire on JavaScript files when the
    /// rule targets `languages: [javascript]`. This test uses a minimal
    /// req.query/body/params -> eval() rule.
    #[test]
    fn test_semgrep_taint_yaml_bridge_js_vulnerable() {
        let output = foxguard_cmd()
            .args([
                "tests/fixtures/semgrep_taint/vulnerable_js_eval.js",
                "-f",
                "json",
                "--no-builtins",
                "--rules",
                "tests/fixtures/semgrep_taint/js_taint_eval.yml",
            ])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let lines: Vec<u64> = findings
            .iter()
            .filter(|f| f["rule_id"].as_str() == Some("semgrep/semgrep-js-taint-eval"))
            .filter_map(|f| f["line"].as_u64())
            .collect();

        assert_eq!(
            lines.len(),
            3,
            "semgrep JS taint rule should fire on all 3 eval flows, got {} (lines: {:?})",
            lines.len(),
            lines
        );
    }

    #[test]
    fn test_semgrep_taint_yaml_bridge_js_safe() {
        let output = foxguard_cmd()
            .args([
                "tests/fixtures/semgrep_taint/safe_js_eval.js",
                "-f",
                "json",
                "--no-builtins",
                "--rules",
                "tests/fixtures/semgrep_taint/js_taint_eval.yml",
            ])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let n = findings
            .iter()
            .filter(|f| f["rule_id"].as_str() == Some("semgrep/semgrep-js-taint-eval"))
            .count();

        assert_eq!(
            n, 0,
            "semgrep JS taint rule should not fire on safe_js_eval.js, got {} findings",
            n
        );
    }

    /// The Semgrep taint YAML bridge should fire on Go files when the rule
    /// targets `languages: [go]`. This test uses a c.Query/c.Param/r.URL ->
    /// exec.Command() rule.
    #[test]
    fn test_semgrep_taint_yaml_bridge_go_vulnerable() {
        let output = foxguard_cmd()
            .args([
                "tests/fixtures/semgrep_taint/vulnerable_go_exec.go",
                "-f",
                "json",
                "--no-builtins",
                "--rules",
                "tests/fixtures/semgrep_taint/go_taint_exec.yml",
            ])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let lines: Vec<u64> = findings
            .iter()
            .filter(|f| f["rule_id"].as_str() == Some("semgrep/semgrep-go-taint-exec"))
            .filter_map(|f| f["line"].as_u64())
            .collect();

        assert_eq!(
            lines.len(),
            3,
            "semgrep Go taint rule should fire on all 3 exec.Command flows, got {} (lines: {:?})",
            lines.len(),
            lines
        );
    }

    #[test]
    fn test_semgrep_taint_yaml_bridge_go_safe() {
        let output = foxguard_cmd()
            .args([
                "tests/fixtures/semgrep_taint/safe_go_exec.go",
                "-f",
                "json",
                "--no-builtins",
                "--rules",
                "tests/fixtures/semgrep_taint/go_taint_exec.yml",
            ])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let n = findings
            .iter()
            .filter(|f| f["rule_id"].as_str() == Some("semgrep/semgrep-go-taint-exec"))
            .count();

        assert_eq!(
            n, 0,
            "semgrep Go taint rule should not fire on safe_go_exec.go, got {} findings",
            n
        );
    }
}

// ─── Output formats ─────────────────────────────────────────────────────────

mod output_formats {
    use super::*;

    #[test]
    fn test_json_output_structure() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable.js", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert!(!findings.is_empty());

        let first = &findings[0];

        // Verify all expected fields exist
        assert!(first["rule_id"].is_string(), "missing rule_id");
        assert!(first["severity"].is_string(), "missing severity");
        assert!(first["description"].is_string(), "missing description");
        assert!(first["file"].is_string(), "missing file");
        assert!(first["line"].is_number(), "missing line");
        assert!(first["column"].is_number(), "missing column");
        assert!(first["end_line"].is_number(), "missing end_line");
        assert!(first["end_column"].is_number(), "missing end_column");
        assert!(first["snippet"].is_string(), "missing snippet");
    }

    #[test]
    fn test_sarif_output_valid() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable.js", "-f", "sarif"])
            .output()
            .expect("failed to execute foxguard");

        let sarif: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("invalid SARIF JSON");

        assert_eq!(sarif["version"].as_str(), Some("2.1.0"));
        assert!(sarif["runs"].is_array());
        assert!(sarif["$schema"].is_string());

        let results = sarif["runs"][0]["results"]
            .as_array()
            .expect("missing results array");
        assert!(!results.is_empty(), "SARIF results should not be empty");
    }
}

// ─── Features ───────────────────────────────────────────────────────────────

mod features {
    use super::*;

    #[test]
    fn test_invalid_path_exits_nonzero() {
        let output = foxguard_cmd()
            .args(["not_a_real_path_foxguard_test", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(
            !output.status.success(),
            "invalid paths should exit non-zero"
        );

        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("does not exist"),
            "expected missing path error, got: {}",
            stderr
        );
    }

    #[test]
    fn test_no_builtins_without_external_rules_finds_nothing() {
        let output = foxguard_cmd()
            .args([
                "tests/fixtures/vulnerable.js",
                "-f",
                "json",
                "--no-builtins",
            ])
            .output()
            .expect("failed to execute foxguard");

        assert!(
            output.status.success(),
            "no built-ins and no external rules should exit zero"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(findings.len(), 0, "expected no findings without any rules");
    }

    #[test]
    fn test_no_builtins_with_external_rules_still_finds_matches() {
        let output = foxguard_cmd()
            .args([
                "tests/fixtures/vulnerable.py",
                "-f",
                "json",
                "--no-builtins",
                "--rules",
                "tests/semgrep_rules",
            ])
            .output()
            .expect("failed to execute foxguard");

        assert!(
            !output.status.success(),
            "external rules should still report findings"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert!(
            !findings.is_empty(),
            "expected findings from external rules when built-ins are disabled"
        );
    }

    #[test]
    fn test_external_rules_respect_semgrep_paths_filters() {
        let repo = TempDir::new().expect("failed to create temp repo");
        copy_fixture_to(repo.path(), "vulnerable.py", "src/vulnerable.py");
        copy_fixture_to(repo.path(), "vulnerable.py", "tests/vulnerable.py");

        let rules_dir = repo.path().join("rules");
        fs::create_dir_all(&rules_dir).expect("failed to create rules directory");
        fs::write(
            rules_dir.join("path-filter.yaml"),
            r#"
rules:
  - id: path-filtered-eval
    pattern: eval(...)
    message: eval usage
    severity: ERROR
    languages: [python]
    paths:
      include:
        - src/**/*.py
"#,
        )
        .expect("failed to write rules file");

        let output = foxguard_cmd()
            .current_dir(repo.path())
            .args([".", "-f", "json", "--no-builtins", "--rules", "rules"])
            .output()
            .expect("failed to execute foxguard with path-filtered rules");

        assert!(
            !output.status.success(),
            "path-filtered external rule should still report findings"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert!(
            findings.iter().all(|finding| finding["file"]
                .as_str()
                .unwrap_or_default()
                .contains("/src/")),
            "expected path filters to restrict findings to src/"
        );
    }

    #[test]
    fn test_write_and_apply_baseline() {
        let repo = TempDir::new().expect("failed to create temp dir");
        let source = fixture_path("vulnerable.js");
        let target = repo.path().join("vulnerable.js");
        fs::copy(source, &target).expect("failed to copy fixture");
        let baseline = repo.path().join("baseline.json");

        let initial = foxguard_cmd()
            .args([
                target.to_str().expect("non-utf8 path"),
                "-f",
                "json",
                "--write-baseline",
                baseline.to_str().expect("non-utf8 path"),
            ])
            .output()
            .expect("failed to execute foxguard");

        assert!(
            !initial.status.success(),
            "writing a baseline should still report current findings"
        );
        assert!(baseline.exists(), "baseline file should be created");

        let suppressed = foxguard_cmd()
            .args([
                target.to_str().expect("non-utf8 path"),
                "-f",
                "json",
                "--baseline",
                baseline.to_str().expect("non-utf8 path"),
            ])
            .output()
            .expect("failed to execute foxguard");

        assert!(
            suppressed.status.success(),
            "baseline should suppress the existing findings"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&suppressed.stdout).expect("invalid JSON output");
        assert_eq!(findings.len(), 0, "expected no findings after baseline");
    }

    #[test]
    fn test_scan_uses_discovered_config_baseline() {
        let repo = TempDir::new().expect("failed to create temp dir");
        fs::copy(
            fixture_path("vulnerable.js"),
            repo.path().join("vulnerable.js"),
        )
        .expect("failed to copy vulnerable fixture");

        let baseline = repo.path().join(".foxguard").join("baseline.json");
        fs::create_dir_all(baseline.parent().expect("missing baseline parent"))
            .expect("failed to create baseline directory");

        let initial = foxguard_cmd()
            .current_dir(repo.path())
            .args([
                "vulnerable.js",
                "-f",
                "json",
                "--write-baseline",
                baseline.to_str().expect("non-utf8 path"),
            ])
            .output()
            .expect("failed to execute foxguard");

        assert!(
            !initial.status.success(),
            "writing the baseline should still report findings"
        );

        write_config_file(
            repo.path(),
            ".foxguard.yml",
            "scan:\n  baseline: .foxguard/baseline.json\n",
        );

        let suppressed = foxguard_cmd()
            .current_dir(repo.path())
            .args(["vulnerable.js", "-f", "json"])
            .output()
            .expect("failed to execute foxguard with config");

        assert!(
            suppressed.status.success(),
            "configured baseline should suppress the existing findings"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&suppressed.stdout).expect("invalid JSON output");
        assert_eq!(
            findings.len(),
            0,
            "expected no findings after config baseline"
        );
    }

    #[test]
    fn test_inline_ignore_suppresses_same_line_js_finding() {
        let repo = TempDir::new().expect("failed to create temp dir");
        let target = repo.path().join("ignored.js");
        fs::write(
            &target,
            "const user_input = process.argv[2];\neval(user_input); // foxguard: ignore[js/no-eval]\n",
        )
        .expect("failed to write fixture");

        let output = foxguard_cmd()
            .args([target.to_str().expect("non-utf8 path"), "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(
            output.status.success(),
            "same-line ignore should suppress the matching finding"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");
        assert!(
            findings.is_empty(),
            "expected no findings after same-line ignore"
        );
    }

    #[test]
    fn test_inline_ignore_suppresses_next_python_line_after_blank_lines() {
        let repo = TempDir::new().expect("failed to create temp dir");
        let target = repo.path().join("ignored.py");
        fs::write(&target, "# foxguard: ignore[py/no-eval]\n\neval(input())\n")
            .expect("failed to write fixture");

        let output = foxguard_cmd()
            .args([target.to_str().expect("non-utf8 path"), "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(
            output.status.success(),
            "comment-only ignore should suppress the next code-line finding"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");
        assert!(
            findings.is_empty(),
            "expected no findings after next-line ignore"
        );
    }

    #[test]
    fn test_inline_ignore_remains_rule_specific() {
        let repo = TempDir::new().expect("failed to create temp dir");
        let target = repo.path().join("not-ignored.js");
        fs::write(
            &target,
            "const user_input = process.argv[2];\neval(user_input); // foxguard: ignore[js/no-sql-injection]\n",
        )
        .expect("failed to write fixture");

        let output = foxguard_cmd()
            .args([target.to_str().expect("non-utf8 path"), "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(
            !output.status.success(),
            "mismatched rule ID should not suppress the finding"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");
        assert_eq!(findings.len(), 1, "expected the finding to remain");
        assert_eq!(findings[0]["rule_id"], "js/no-eval");
    }

    #[test]
    fn test_inline_ignore_without_rule_list_suppresses_all_findings_on_line() {
        let repo = TempDir::new().expect("failed to create temp dir");
        let target = repo.path().join("ignored-all.js");
        fs::write(
            &target,
            "const user_input = process.argv[2];\neval(user_input); // foxguard: ignore\n",
        )
        .expect("failed to write fixture");

        let output = foxguard_cmd()
            .args([target.to_str().expect("non-utf8 path"), "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(
            output.status.success(),
            "ignore without rule list should suppress all findings on the line"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");
        assert!(findings.is_empty(), "expected no findings after ignore-all");
    }

    #[test]
    fn test_inline_ignore_suppresses_multiline_finding_when_directive_is_on_end_line() {
        let repo = TempDir::new().expect("failed to create temp dir");
        let target = repo.path().join("multiline-ignored.js");
        fs::write(
            &target,
            "const user_input = process.argv[2];\neval(\n  user_input // foxguard: ignore[js/no-eval]\n);\n",
        )
        .expect("failed to write fixture");

        let output = foxguard_cmd()
            .args([target.to_str().expect("non-utf8 path"), "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(
            output.status.success(),
            "directive on the end line of a multiline finding should still suppress it"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");
        assert!(
            findings.is_empty(),
            "expected no findings after multiline inline ignore"
        );
    }

    #[test]
    fn test_changed_mode_scans_only_staged_files() {
        let repo = setup_git_repo(&["vulnerable.js", "safe.py"]);

        Command::new("git")
            .args(["add", "vulnerable.js"])
            .current_dir(repo.path())
            .output()
            .expect("failed to stage vulnerable.js");

        let output = foxguard_cmd()
            .args(["--changed", "-f", "json", "."])
            .current_dir(repo.path())
            .output()
            .expect("failed to execute foxguard");

        assert!(
            !output.status.success(),
            "changed-mode scan should report findings from staged vulnerable.js"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");
        assert!(
            findings.iter().all(|finding| finding["file"]
                .as_str()
                .unwrap_or_default()
                .ends_with("vulnerable.js")),
            "changed mode should only scan the staged file"
        );
    }

    #[test]
    fn test_init_installs_hook_and_baseline() {
        let repo = setup_git_repo(&["vulnerable.js"]);

        let output = foxguard_cmd()
            .args(["init", "--path", ".", "--force"])
            .current_dir(repo.path())
            .output()
            .expect("failed to execute foxguard init");

        assert!(output.status.success(), "init should succeed");
        assert!(
            repo.path().join(".git/hooks/pre-commit").exists(),
            "pre-commit hook should be installed"
        );
        assert!(
            repo.path().join(".foxguard/baseline.json").exists(),
            "baseline should be created by default"
        );
        assert!(
            repo.path().join(".foxguard/secrets-baseline.json").exists(),
            "secrets baseline should be created by default"
        );
        assert!(
            repo.path().join(".foxguard.yml").exists(),
            "starter config should be created by default"
        );

        let hook = fs::read_to_string(repo.path().join(".git/hooks/pre-commit"))
            .expect("failed to read pre-commit hook");
        assert!(
            hook.contains("foxguard --config \".foxguard.yml\" --changed"),
            "hook should use the generated config"
        );
        assert!(
            hook.contains("foxguard secrets --config \".foxguard.yml\" --changed"),
            "hook should run the secrets scanner"
        );

        let config = fs::read_to_string(repo.path().join(".foxguard.yml"))
            .expect("failed to read generated config");
        assert!(
            config.contains("scan:\n  baseline: .foxguard/baseline.json"),
            "generated config should include the code baseline"
        );
        assert!(
            config.contains("secrets:\n  baseline: .foxguard/secrets-baseline.json"),
            "generated config should include the secrets baseline"
        );
    }

    #[test]
    fn test_init_preserves_existing_config_and_keeps_baseline_flags_when_needed() {
        let repo = setup_git_repo(&["vulnerable.js"]);
        write_config_file(
            repo.path(),
            ".foxguard.yml",
            "secrets:\n  exclude_paths:\n    - fixtures\n",
        );

        let output = foxguard_cmd()
            .args(["init", "--path", ".", "--force"])
            .current_dir(repo.path())
            .output()
            .expect("failed to execute foxguard init");

        assert!(output.status.success(), "init should succeed");

        let hook = fs::read_to_string(repo.path().join(".git/hooks/pre-commit"))
            .expect("failed to read pre-commit hook");
        assert!(
            hook.contains("--config \".foxguard.yml\""),
            "hook should still use the existing config"
        );
        assert!(
            hook.contains("--baseline \".foxguard/baseline.json\""),
            "hook should keep explicit code baseline flags when existing config lacks them"
        );
        assert!(
            hook.contains("--baseline \".foxguard/secrets-baseline.json\""),
            "hook should keep explicit secrets baseline flags when existing config lacks them"
        );

        let config = fs::read_to_string(repo.path().join(".foxguard.yml"))
            .expect("failed to read preserved config");
        assert!(
            config.contains("exclude_paths:\n    - fixtures"),
            "existing config should be preserved"
        );
    }

    #[test]
    fn test_severity_filter_high() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable.js", "-f", "json", "-s", "high"])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        // High and Critical only
        assert_eq!(
            findings.len(),
            21,
            "high severity filter on vulnerable.js should yield 21 findings, got {}",
            findings.len()
        );

        // All findings should be High or Critical
        for finding in &findings {
            let severity = finding["severity"].as_str().unwrap();
            assert!(
                severity == "high" || severity == "critical",
                "expected high or critical, got: {}",
                severity
            );
        }
    }

    #[test]
    fn test_severity_filter_critical() {
        let output = foxguard_cmd()
            .args([
                "tests/fixtures/vulnerable.js",
                "-f",
                "json",
                "-s",
                "critical",
            ])
            .output()
            .expect("failed to execute foxguard");

        assert!(!output.status.success());

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        // All findings should be Critical
        for finding in &findings {
            let severity = finding["severity"].as_str().unwrap();
            assert_eq!(severity, "critical", "expected critical, got: {}", severity);
        }
    }

    #[test]
    fn test_secrets_mode_finds_common_credentials() {
        let repo = TempDir::new().expect("failed to create temp dir");
        let path = write_secrets_fixture(repo.path());

        let output = foxguard_cmd()
            .args([
                "secrets",
                path.to_str().expect("non-utf8 path"),
                "-f",
                "json",
            ])
            .output()
            .expect("failed to execute foxguard secrets");

        assert!(
            !output.status.success(),
            "secrets mode should exit non-zero when findings exist"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(
            findings.len(),
            8,
            "secrets fixture should yield 8 findings, got {}",
            findings.len()
        );

        let rule_ids: std::collections::HashSet<&str> = findings
            .iter()
            .filter_map(|f| f["rule_id"].as_str())
            .collect();

        let expected_rules = [
            "secret/aws-access-key-id",
            "secret/aws-secret-access-key",
            "secret/github-token",
            "secret/gitlab-token",
            "secret/npm-token",
            "secret/slack-token",
            "secret/stripe-live-key",
            "secret/private-key",
        ];

        for rule in &expected_rules {
            assert!(
                rule_ids.contains(rule),
                "missing expected secret rule: {}",
                rule
            );
        }
    }

    #[test]
    fn test_secrets_mode_changed_scans_only_staged_files() {
        let repo = setup_git_repo(&["safe.py"]);
        write_secrets_fixture(repo.path());

        Command::new("git")
            .args(["add", "secrets.txt"])
            .current_dir(repo.path())
            .output()
            .expect("failed to stage secrets fixture");

        let output = foxguard_cmd()
            .args(["secrets", "--changed", "-f", "json", "."])
            .current_dir(repo.path())
            .output()
            .expect("failed to execute foxguard secrets --changed");

        assert!(
            !output.status.success(),
            "changed secrets scan should report staged secrets"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");
        assert!(
            findings.iter().all(|finding| finding["file"]
                .as_str()
                .unwrap_or_default()
                .ends_with("secrets.txt")),
            "changed secrets scan should only scan the staged secret fixture"
        );
    }

    #[test]
    fn test_secrets_mode_skips_binary_files() {
        let repo = TempDir::new().expect("failed to create temp dir");
        let path = write_binary_secrets_fixture(repo.path());

        let output = foxguard_cmd()
            .args([
                "secrets",
                path.to_str().expect("non-utf8 path"),
                "-f",
                "json",
            ])
            .output()
            .expect("failed to execute foxguard secrets");

        assert!(output.status.success(), "binary file should be skipped");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");
        assert_eq!(
            findings.len(),
            0,
            "binary secrets fixture should be skipped"
        );
    }

    #[test]
    fn test_write_and_apply_secrets_baseline() {
        let repo = TempDir::new().expect("failed to create temp dir");
        let target = write_secrets_fixture(repo.path());
        let baseline = repo.path().join("secrets-baseline.json");

        let initial = foxguard_cmd()
            .args([
                "secrets",
                target.to_str().expect("non-utf8 path"),
                "-f",
                "json",
                "--write-baseline",
                baseline.to_str().expect("non-utf8 path"),
            ])
            .output()
            .expect("failed to execute foxguard secrets");

        assert!(
            !initial.status.success(),
            "writing a secrets baseline should still report current findings"
        );
        assert!(baseline.exists(), "secrets baseline file should be created");

        let suppressed = foxguard_cmd()
            .args([
                "secrets",
                target.to_str().expect("non-utf8 path"),
                "-f",
                "json",
                "--baseline",
                baseline.to_str().expect("non-utf8 path"),
            ])
            .output()
            .expect("failed to execute foxguard secrets with baseline");

        assert!(
            suppressed.status.success(),
            "secrets baseline should suppress the existing findings"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&suppressed.stdout).expect("invalid JSON output");
        assert_eq!(
            findings.len(),
            0,
            "expected no findings after applying the secrets baseline"
        );

        let baseline_content =
            fs::read_to_string(&baseline).expect("failed to read secrets baseline");
        assert!(
            !baseline_content.contains("\"snippet\""),
            "secrets baseline should not persist snippets"
        );
        assert!(
            !baseline_content.contains("[REDACTED]"),
            "secrets baseline should only store suppression metadata"
        );
    }

    #[test]
    fn test_secrets_mode_redacts_snippets() {
        let repo = TempDir::new().expect("failed to create temp dir");
        let path = write_secrets_fixture(repo.path());

        let output = foxguard_cmd()
            .args([
                "secrets",
                path.to_str().expect("non-utf8 path"),
                "-f",
                "json",
            ])
            .output()
            .expect("failed to execute foxguard secrets");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        for finding in findings {
            let snippet = finding["snippet"].as_str().expect("missing snippet");
            assert!(
                snippet.contains("[REDACTED]"),
                "secrets snippet should be redacted"
            );
            assert!(
                !snippet.contains("1234567890ABCDEF")
                    && !snippet.contains("abcdefghijklmnopqrstuvwxyz1234567890"),
                "secrets snippet should not contain raw secrets"
            );
        }
    }

    #[test]
    fn test_secrets_mode_exclude_path_skips_matching_files() {
        let repo = TempDir::new().expect("failed to create temp dir");
        write_secret_file(repo.path(), "included.txt");
        write_secret_file(repo.path(), "fixtures/ignored.txt");

        let output = foxguard_cmd()
            .args([
                "secrets",
                "--exclude-path",
                "fixtures",
                repo.path().to_str().expect("non-utf8 path"),
                "-f",
                "json",
            ])
            .output()
            .expect("failed to execute foxguard secrets");

        assert!(
            !output.status.success(),
            "non-excluded secrets should still produce findings"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(findings.len(), 1, "expected only one non-excluded finding");
        assert!(
            findings[0]["file"]
                .as_str()
                .is_some_and(|file| file.ends_with("included.txt")),
            "expected only the included file to be scanned"
        );
    }

    #[test]
    fn test_secrets_mode_exclude_path_file_skips_matching_files() {
        let repo = TempDir::new().expect("failed to create temp dir");
        write_secret_file(repo.path(), "fixtures/ignored.txt");
        let ignore_file = repo.path().join(".foxguard").join("secrets.ignore");
        fs::create_dir_all(ignore_file.parent().expect("missing ignore directory"))
            .expect("failed to create ignore directory");
        fs::write(&ignore_file, "# comment\nfixtures\n").expect("failed to write ignore file");

        let output = foxguard_cmd()
            .args([
                "secrets",
                "--exclude-path-file",
                ignore_file.to_str().expect("non-utf8 path"),
                repo.path().to_str().expect("non-utf8 path"),
                "-f",
                "json",
            ])
            .output()
            .expect("failed to execute foxguard secrets");

        assert!(
            output.status.success(),
            "excluded secrets should not produce findings"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");
        assert!(findings.is_empty(), "expected excluded file to be skipped");
    }

    #[test]
    fn test_secrets_mode_ignore_rule_skips_specific_patterns() {
        let repo = TempDir::new().expect("failed to create temp dir");
        write_secrets_fixture(repo.path());

        let output = foxguard_cmd()
            .args([
                "secrets",
                "--ignore-rule",
                "secret/github-token",
                repo.path().to_str().expect("non-utf8 path"),
                "-f",
                "json",
            ])
            .output()
            .expect("failed to execute foxguard secrets");

        assert!(
            !output.status.success(),
            "remaining secrets should still produce findings"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        assert_eq!(
            findings.len(),
            7,
            "expected github token finding to be ignored"
        );
        assert!(
            findings
                .iter()
                .all(|finding| finding["rule_id"].as_str() != Some("secret/github-token")),
            "ignored rule should be absent from findings"
        );
    }

    #[test]
    fn test_secrets_mode_uses_explicit_config_file() {
        let repo = TempDir::new().expect("failed to create temp dir");
        write_secret_file(repo.path(), "fixtures/ignored.txt");

        let config = write_config_file(
            repo.path(),
            "config/foxguard.yml",
            "secrets:\n  exclude_paths:\n    - ../fixtures\n",
        );

        let output = foxguard_cmd()
            .current_dir(repo.path())
            .args([
                "secrets",
                "--config",
                config.to_str().expect("non-utf8 path"),
                ".",
                "-f",
                "json",
            ])
            .output()
            .expect("failed to execute foxguard secrets with config");

        assert!(
            output.status.success(),
            "configured excludes should suppress matching secret findings"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");
        assert!(
            findings.is_empty(),
            "expected no findings after config excludes"
        );
    }

    /// With --explain, taint findings show source/sink trace lines.
    #[test]
    fn test_explain_flag_shows_trace_on_taint_findings() {
        let output = foxguard_cmd()
            .args(["--explain", "tests/fixtures/realistic/flask_app.py"])
            .output()
            .expect("failed to execute foxguard");

        let stdout = String::from_utf8_lossy(&output.stdout);
        // Taint findings should have source/sink trace lines
        assert!(
            stdout.contains("source"),
            "expected 'source' trace line in --explain output"
        );
        assert!(
            stdout.contains("sink"),
            "expected 'sink' trace line in --explain output"
        );
        // Check that source arrow points to a file:line pattern
        assert!(
            stdout.contains("flask_app.py:"),
            "expected file:line in trace output"
        );
    }

    /// Without --explain, taint findings must NOT show source/sink trace lines.
    #[test]
    fn test_no_explain_flag_hides_trace() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/realistic/flask_app.py"])
            .output()
            .expect("failed to execute foxguard");

        let stdout = String::from_utf8_lossy(&output.stdout);
        // The "source ->" trace line should not appear
        assert!(
            !stdout.contains("source \u{2192}"),
            "trace lines should not appear without --explain"
        );
        assert!(
            !stdout.contains("sink   \u{2192}"),
            "trace lines should not appear without --explain"
        );
    }

    /// JSON output with --explain includes source/sink fields on taint findings.
    #[test]
    fn test_explain_json_includes_trace_fields() {
        let output = foxguard_cmd()
            .args([
                "--explain",
                "-f",
                "json",
                "tests/fixtures/realistic/flask_app.py",
            ])
            .output()
            .expect("failed to execute foxguard");

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let taint_findings: Vec<&serde_json::Value> = findings
            .iter()
            .filter(|f| f["rule_id"].as_str().is_some_and(|r| r.contains("taint")))
            .collect();

        assert!(
            !taint_findings.is_empty(),
            "should have at least one taint finding"
        );

        for f in &taint_findings {
            assert!(
                f["source_line"].is_number(),
                "taint finding {} should have source_line",
                f["rule_id"]
            );
            assert!(
                f["source_description"].is_string(),
                "taint finding {} should have source_description",
                f["rule_id"]
            );
            assert!(
                f["sink_line"].is_number(),
                "taint finding {} should have sink_line",
                f["rule_id"]
            );
            assert!(
                f["sink_description"].is_string(),
                "taint finding {} should have sink_description",
                f["rule_id"]
            );
        }

        // Non-taint findings should NOT have trace fields
        let nontaint_findings: Vec<&serde_json::Value> = findings
            .iter()
            .filter(|f| f["rule_id"].as_str().is_some_and(|r| !r.contains("taint")))
            .collect();

        for f in &nontaint_findings {
            assert!(
                f.get("source_line").is_none() || f["source_line"].is_null(),
                "non-taint finding {} should not have source_line",
                f["rule_id"]
            );
        }
    }

    #[test]
    fn test_taint_findings_include_fix_suggestion_in_json() {
        // Scan the Python taint fixture in JSON mode and verify that taint
        // findings carry a non-empty fix_suggestion field.
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable_py_taint.py", "-f", "json"])
            .output()
            .expect("failed to execute foxguard");

        assert!(
            !output.status.success(),
            "should exit non-zero with findings"
        );

        let findings: Vec<serde_json::Value> =
            serde_json::from_slice(&output.stdout).expect("invalid JSON output");

        let taint_findings: Vec<&serde_json::Value> = findings
            .iter()
            .filter(|f| f["rule_id"].as_str().is_some_and(|id| id.contains("taint")))
            .collect();

        assert!(
            !taint_findings.is_empty(),
            "should have at least one taint finding"
        );

        for f in &taint_findings {
            let fix = f.get("fix_suggestion");
            assert!(
                fix.is_some()
                    && fix.unwrap().is_string()
                    && !fix.unwrap().as_str().unwrap().is_empty(),
                "taint finding {} should have a non-empty fix_suggestion",
                f["rule_id"]
            );
        }

        // Non-taint findings should NOT have fix_suggestion
        let nontaint_findings: Vec<&serde_json::Value> = findings
            .iter()
            .filter(|f| {
                f["rule_id"]
                    .as_str()
                    .is_some_and(|id| !id.contains("taint"))
            })
            .collect();

        for f in &nontaint_findings {
            assert!(
                f.get("fix_suggestion").is_none() || f["fix_suggestion"].is_null(),
                "non-taint finding {} should not have fix_suggestion",
                f["rule_id"]
            );
        }
    }

    #[test]
    fn test_fix_suggestion_appears_in_sarif_output() {
        let output = foxguard_cmd()
            .args(["tests/fixtures/vulnerable_py_taint.py", "-f", "sarif"])
            .output()
            .expect("failed to execute foxguard");

        let sarif: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("invalid SARIF output");

        let results = sarif["runs"][0]["results"]
            .as_array()
            .expect("results array");

        let taint_results: Vec<&serde_json::Value> = results
            .iter()
            .filter(|r| r["ruleId"].as_str().is_some_and(|id| id.contains("taint")))
            .collect();

        assert!(
            !taint_results.is_empty(),
            "should have at least one taint result in SARIF"
        );

        for r in &taint_results {
            let fixes = r.get("fixes");
            assert!(
                fixes.is_some() && fixes.unwrap().is_array(),
                "taint SARIF result {} should have a fixes array",
                r["ruleId"]
            );
            let fix_text = fixes.unwrap()[0]["description"]["text"].as_str();
            assert!(
                fix_text.is_some() && !fix_text.unwrap().is_empty(),
                "SARIF fix description should be non-empty for {}",
                r["ruleId"]
            );
        }
    }
}