go-brrr 0.1.0

Token-efficient code analysis for LLMs - Rust implementation
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
//! Command injection vulnerability detection.
//!
//! Detects potential command injection vulnerabilities by tracking data flow
//! from user-controlled inputs (sources) to dangerous shell execution functions (sinks).
//!
//! # Command Injection vs Argument Injection
//!
//! - **Command Injection**: User input containing shell metacharacters (`;`, `|`, `&`, etc.)
//!   can execute arbitrary commands. Example: `os.system("ls " + user_input)` where
//!   `user_input = "; rm -rf /"`.
//!
//! - **Argument Injection**: User input is passed as arguments to a command but can
//!   manipulate flags/options. Example: `subprocess.run(["tar", "-xf", user_input])`
//!   where `user_input = "--checkpoint-action=exec=malicious.sh"`.
//!
//! # Detection Strategy
//!
//! 1. Parse source files using tree-sitter
//! 2. Identify calls to known command execution sinks
//! 3. Extract the arguments passed to these sinks
//! 4. Track data flow backwards to identify if arguments come from taint sources
//! 5. Report findings with severity and confidence levels
//!
//! # Shell Metacharacters
//!
//! The following characters are dangerous in shell contexts:
//! - Command separators: `;`, `|`, `&`, `&&`, `||`, `\n`
//! - Subshell/substitution: `` ` ``, `$()`, `$()`
//! - Redirection: `<`, `>`, `>>`
//! - Glob expansion: `*`, `?`, `[`, `]`
//! - Quote escape: `'`, `"`, `\`

use std::collections::HashMap;
use std::path::Path;

use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use streaming_iterator::StreamingIterator;
use tree_sitter::{Node, Query, QueryCursor, Tree};

use crate::callgraph::scanner::{ProjectScanner, ScanConfig};
use crate::error::{Result, BrrrError};
use crate::lang::LanguageRegistry;
use crate::util::format_query_error;

// =============================================================================
// Type Definitions
// =============================================================================

/// Severity level for security findings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    /// Informational - may not be exploitable but worth reviewing
    Info,
    /// Low severity - limited impact or requires specific conditions
    Low,
    /// Medium severity - potential for significant impact
    Medium,
    /// High severity - likely exploitable with serious impact
    High,
    /// Critical - easily exploitable with severe consequences
    Critical,
}

impl std::fmt::Display for Severity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Info => write!(f, "INFO"),
            Self::Low => write!(f, "LOW"),
            Self::Medium => write!(f, "MEDIUM"),
            Self::High => write!(f, "HIGH"),
            Self::Critical => write!(f, "CRITICAL"),
        }
    }
}

/// Confidence level for the finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Confidence {
    /// Low confidence - pattern match only, no data flow confirmation
    Low,
    /// Medium confidence - some data flow indicators but incomplete path
    Medium,
    /// High confidence - clear data flow from source to sink
    High,
}

impl std::fmt::Display for Confidence {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Low => write!(f, "LOW"),
            Self::Medium => write!(f, "MEDIUM"),
            Self::High => write!(f, "HIGH"),
        }
    }
}

/// Type of injection vulnerability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InjectionKind {
    /// Full command injection - user input can execute arbitrary commands
    CommandInjection,
    /// Argument injection - user input can manipulate command arguments
    ArgumentInjection,
    /// Code injection via eval/exec
    CodeInjection,
}

impl std::fmt::Display for InjectionKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::CommandInjection => write!(f, "command_injection"),
            Self::ArgumentInjection => write!(f, "argument_injection"),
            Self::CodeInjection => write!(f, "code_injection"),
        }
    }
}

/// Source location in code.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SourceLocation {
    /// File path
    pub file: String,
    /// Line number (1-indexed)
    pub line: usize,
    /// Column number (1-indexed)
    pub column: usize,
    /// End line number (1-indexed)
    pub end_line: usize,
    /// End column number (1-indexed)
    pub end_column: usize,
}

impl std::fmt::Display for SourceLocation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}:{}", self.file, self.line, self.column)
    }
}

/// Kind of taint source.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaintSourceKind {
    /// HTTP request parameters (query string, body, headers)
    HttpRequest,
    /// Form input data
    FormInput,
    /// Standard input (stdin)
    StdIn,
    /// File read operations
    FileRead,
    /// Environment variables
    EnvVar,
    /// Command line arguments
    CmdLineArg,
    /// Database query results
    DatabaseResult,
    /// Network socket data
    NetworkData,
    /// User-provided configuration
    UserConfig,
    /// Unknown/generic user input
    Unknown,
}

/// A taint source - origin of potentially malicious data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaintSource {
    /// Type of taint source
    pub kind: TaintSourceKind,
    /// Variable name carrying the taint
    pub variable: String,
    /// Location where taint originates
    pub location: SourceLocation,
    /// Description of the source
    pub description: String,
}

/// A command execution sink - dangerous function that executes commands.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandSink {
    /// Language this sink applies to
    pub language: String,
    /// Module or namespace (e.g., "os", "subprocess", "child_process")
    pub module: Option<String>,
    /// Function name (e.g., "system", "exec", "popen")
    pub function: String,
    /// Argument index that receives the command (0-indexed)
    pub command_arg_index: usize,
    /// Whether this sink uses a shell by default
    pub shell_by_default: bool,
    /// Severity when this sink is exploited
    pub severity: Severity,
    /// Description of the sink
    pub description: String,
}

/// A command injection finding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandInjectionFinding {
    /// Location of the vulnerable sink call
    pub location: SourceLocation,
    /// Severity of the vulnerability
    pub severity: Severity,
    /// Name of the dangerous function being called
    pub sink_function: String,
    /// The tainted input reaching the sink (variable name or expression)
    pub tainted_input: String,
    /// Confidence level of the finding
    pub confidence: Confidence,
    /// Type of injection
    pub kind: InjectionKind,
    /// Chain of taint propagation (source -> ... -> sink)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub taint_chain: Vec<TaintSource>,
    /// Code snippet showing the vulnerable pattern
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code_snippet: Option<String>,
    /// Remediation advice
    pub remediation: String,
}

// =============================================================================
// Language-Specific Command Sinks
// =============================================================================

/// Get all known command execution sinks for a language.
pub fn get_command_sinks(language: &str) -> Vec<CommandSink> {
    match language {
        "python" => python_sinks(),
        "typescript" | "javascript" => typescript_sinks(),
        "rust" => rust_sinks(),
        "go" => go_sinks(),
        "c" | "cpp" => c_sinks(),
        "java" => java_sinks(),
        _ => vec![],
    }
}

fn python_sinks() -> Vec<CommandSink> {
    vec![
        // os module
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "system".to_string(),
            command_arg_index: 0,
            shell_by_default: true,
            severity: Severity::Critical,
            description: "Executes command in shell, vulnerable to command injection".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "popen".to_string(),
            command_arg_index: 0,
            shell_by_default: true,
            severity: Severity::Critical,
            description: "Opens pipe to command in shell".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "spawn".to_string(),
            command_arg_index: 1,
            shell_by_default: false,
            severity: Severity::High,
            description: "Spawns process, less dangerous but still risky".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "spawnl".to_string(),
            command_arg_index: 1,
            shell_by_default: false,
            severity: Severity::High,
            description: "Spawns process with list args".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "spawnle".to_string(),
            command_arg_index: 1,
            shell_by_default: false,
            severity: Severity::High,
            description: "Spawns process with list args and env".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "spawnlp".to_string(),
            command_arg_index: 1,
            shell_by_default: false,
            severity: Severity::High,
            description: "Spawns process using PATH".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "spawnlpe".to_string(),
            command_arg_index: 1,
            shell_by_default: false,
            severity: Severity::High,
            description: "Spawns process using PATH with env".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "spawnv".to_string(),
            command_arg_index: 1,
            shell_by_default: false,
            severity: Severity::High,
            description: "Spawns process with vector args".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "spawnve".to_string(),
            command_arg_index: 1,
            shell_by_default: false,
            severity: Severity::High,
            description: "Spawns process with vector args and env".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "spawnvp".to_string(),
            command_arg_index: 1,
            shell_by_default: false,
            severity: Severity::High,
            description: "Spawns process with vector args using PATH".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "spawnvpe".to_string(),
            command_arg_index: 1,
            shell_by_default: false,
            severity: Severity::High,
            description: "Spawns process with vector args and env using PATH".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "execl".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces current process with new program".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "execle".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces current process with env".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "execlp".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces current process using PATH".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "execlpe".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces current process using PATH with env".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "execv".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces current process with vector args".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "execve".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces current process with vector args and env".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "execvp".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces current process using PATH".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("os".to_string()),
            function: "execvpe".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces current process using PATH with env".to_string(),
        },
        // subprocess module
        CommandSink {
            language: "python".to_string(),
            module: Some("subprocess".to_string()),
            function: "call".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Runs command, dangerous with shell=True".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("subprocess".to_string()),
            function: "run".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Runs command, dangerous with shell=True".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("subprocess".to_string()),
            function: "Popen".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Creates subprocess, dangerous with shell=True".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("subprocess".to_string()),
            function: "check_call".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Runs command with return code check".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("subprocess".to_string()),
            function: "check_output".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Runs command and captures output".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("subprocess".to_string()),
            function: "getoutput".to_string(),
            command_arg_index: 0,
            shell_by_default: true,
            severity: Severity::Critical,
            description: "Runs command in shell, always uses shell".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("subprocess".to_string()),
            function: "getstatusoutput".to_string(),
            command_arg_index: 0,
            shell_by_default: true,
            severity: Severity::Critical,
            description: "Runs command in shell, returns status and output".to_string(),
        },
        // commands module (deprecated but still used)
        CommandSink {
            language: "python".to_string(),
            module: Some("commands".to_string()),
            function: "getoutput".to_string(),
            command_arg_index: 0,
            shell_by_default: true,
            severity: Severity::Critical,
            description: "Deprecated shell command execution".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: Some("commands".to_string()),
            function: "getstatusoutput".to_string(),
            command_arg_index: 0,
            shell_by_default: true,
            severity: Severity::Critical,
            description: "Deprecated shell command with status".to_string(),
        },
        // eval/exec - code injection
        CommandSink {
            language: "python".to_string(),
            module: None,
            function: "eval".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Critical,
            description: "Evaluates Python expression, code injection risk".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: None,
            function: "exec".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Critical,
            description: "Executes Python code, code injection risk".to_string(),
        },
        CommandSink {
            language: "python".to_string(),
            module: None,
            function: "compile".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Compiles Python code, potential code injection".to_string(),
        },
        // pty module
        CommandSink {
            language: "python".to_string(),
            module: Some("pty".to_string()),
            function: "spawn".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Spawns process in pseudo-terminal".to_string(),
        },
    ]
}

fn typescript_sinks() -> Vec<CommandSink> {
    vec![
        // child_process module
        CommandSink {
            language: "typescript".to_string(),
            module: Some("child_process".to_string()),
            function: "exec".to_string(),
            command_arg_index: 0,
            shell_by_default: true,
            severity: Severity::Critical,
            description: "Executes command in shell".to_string(),
        },
        CommandSink {
            language: "typescript".to_string(),
            module: Some("child_process".to_string()),
            function: "execSync".to_string(),
            command_arg_index: 0,
            shell_by_default: true,
            severity: Severity::Critical,
            description: "Synchronously executes command in shell".to_string(),
        },
        CommandSink {
            language: "typescript".to_string(),
            module: Some("child_process".to_string()),
            function: "spawn".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Spawns process, dangerous with shell:true option".to_string(),
        },
        CommandSink {
            language: "typescript".to_string(),
            module: Some("child_process".to_string()),
            function: "spawnSync".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Synchronously spawns process".to_string(),
        },
        CommandSink {
            language: "typescript".to_string(),
            module: Some("child_process".to_string()),
            function: "execFile".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Medium,
            description: "Executes file directly, safer but still risky".to_string(),
        },
        CommandSink {
            language: "typescript".to_string(),
            module: Some("child_process".to_string()),
            function: "execFileSync".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Medium,
            description: "Synchronously executes file".to_string(),
        },
        CommandSink {
            language: "typescript".to_string(),
            module: Some("child_process".to_string()),
            function: "fork".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Medium,
            description: "Forks Node.js process".to_string(),
        },
        // eval - code injection
        CommandSink {
            language: "typescript".to_string(),
            module: None,
            function: "eval".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Critical,
            description: "Evaluates JavaScript code, code injection risk".to_string(),
        },
        CommandSink {
            language: "typescript".to_string(),
            module: None,
            function: "Function".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Critical,
            description: "Creates function from string, code injection risk".to_string(),
        },
        // setTimeout/setInterval with string argument
        CommandSink {
            language: "typescript".to_string(),
            module: None,
            function: "setTimeout".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Can execute string as code (legacy behavior)".to_string(),
        },
        CommandSink {
            language: "typescript".to_string(),
            module: None,
            function: "setInterval".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Can execute string as code (legacy behavior)".to_string(),
        },
        // Bun/Deno specific
        CommandSink {
            language: "typescript".to_string(),
            module: Some("Bun".to_string()),
            function: "spawn".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Bun process spawning".to_string(),
        },
        CommandSink {
            language: "typescript".to_string(),
            module: Some("Deno".to_string()),
            function: "run".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Deno command execution".to_string(),
        },
    ]
}

fn rust_sinks() -> Vec<CommandSink> {
    vec![
        // std::process::Command
        CommandSink {
            language: "rust".to_string(),
            module: Some("std::process".to_string()),
            function: "Command::new".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Creates command, dangerous if user controls program path".to_string(),
        },
        // Command builder methods that take user input
        CommandSink {
            language: "rust".to_string(),
            module: Some("std::process".to_string()),
            function: "arg".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Medium,
            description: "Adds argument to command, argument injection risk".to_string(),
        },
        CommandSink {
            language: "rust".to_string(),
            module: Some("std::process".to_string()),
            function: "args".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Medium,
            description: "Adds arguments to command".to_string(),
        },
        // Shell execution via sh -c
        CommandSink {
            language: "rust".to_string(),
            module: None,
            function: "shell".to_string(),
            command_arg_index: 0,
            shell_by_default: true,
            severity: Severity::Critical,
            description: "Shell command execution pattern".to_string(),
        },
        // tokio::process
        CommandSink {
            language: "rust".to_string(),
            module: Some("tokio::process".to_string()),
            function: "Command::new".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Async command creation".to_string(),
        },
    ]
}

fn go_sinks() -> Vec<CommandSink> {
    vec![
        // os/exec package
        CommandSink {
            language: "go".to_string(),
            module: Some("os/exec".to_string()),
            function: "Command".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Creates command, dangerous if user controls program".to_string(),
        },
        CommandSink {
            language: "go".to_string(),
            module: Some("exec".to_string()),
            function: "Command".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Creates command (short import)".to_string(),
        },
        CommandSink {
            language: "go".to_string(),
            module: Some("os/exec".to_string()),
            function: "CommandContext".to_string(),
            command_arg_index: 1,
            shell_by_default: false,
            severity: Severity::High,
            description: "Creates command with context".to_string(),
        },
        // syscall package
        CommandSink {
            language: "go".to_string(),
            module: Some("syscall".to_string()),
            function: "Exec".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Critical,
            description: "Low-level exec syscall".to_string(),
        },
        CommandSink {
            language: "go".to_string(),
            module: Some("syscall".to_string()),
            function: "ForkExec".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Critical,
            description: "Fork and exec syscall".to_string(),
        },
        CommandSink {
            language: "go".to_string(),
            module: Some("syscall".to_string()),
            function: "StartProcess".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Critical,
            description: "Starts new process".to_string(),
        },
    ]
}

fn c_sinks() -> Vec<CommandSink> {
    vec![
        // Standard library
        CommandSink {
            language: "c".to_string(),
            module: None,
            function: "system".to_string(),
            command_arg_index: 0,
            shell_by_default: true,
            severity: Severity::Critical,
            description: "Executes command in shell".to_string(),
        },
        CommandSink {
            language: "c".to_string(),
            module: None,
            function: "popen".to_string(),
            command_arg_index: 0,
            shell_by_default: true,
            severity: Severity::Critical,
            description: "Opens pipe to shell command".to_string(),
        },
        // exec family
        CommandSink {
            language: "c".to_string(),
            module: None,
            function: "execl".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces process with new program".to_string(),
        },
        CommandSink {
            language: "c".to_string(),
            module: None,
            function: "execle".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces process with environment".to_string(),
        },
        CommandSink {
            language: "c".to_string(),
            module: None,
            function: "execlp".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces process using PATH".to_string(),
        },
        CommandSink {
            language: "c".to_string(),
            module: None,
            function: "execv".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces process with vector args".to_string(),
        },
        CommandSink {
            language: "c".to_string(),
            module: None,
            function: "execve".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces process with vector and env".to_string(),
        },
        CommandSink {
            language: "c".to_string(),
            module: None,
            function: "execvp".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces process using PATH".to_string(),
        },
        CommandSink {
            language: "c".to_string(),
            module: None,
            function: "execvpe".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Replaces process using PATH with env".to_string(),
        },
        // fork/spawn
        CommandSink {
            language: "c".to_string(),
            module: None,
            function: "posix_spawn".to_string(),
            command_arg_index: 1,
            shell_by_default: false,
            severity: Severity::High,
            description: "POSIX spawn interface".to_string(),
        },
        CommandSink {
            language: "c".to_string(),
            module: None,
            function: "posix_spawnp".to_string(),
            command_arg_index: 1,
            shell_by_default: false,
            severity: Severity::High,
            description: "POSIX spawn with PATH search".to_string(),
        },
    ]
}

fn java_sinks() -> Vec<CommandSink> {
    vec![
        // Runtime.exec
        CommandSink {
            language: "java".to_string(),
            module: Some("java.lang.Runtime".to_string()),
            function: "exec".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Critical,
            description: "Executes system command".to_string(),
        },
        CommandSink {
            language: "java".to_string(),
            module: Some("Runtime".to_string()),
            function: "exec".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Critical,
            description: "Executes system command (short form)".to_string(),
        },
        // ProcessBuilder
        CommandSink {
            language: "java".to_string(),
            module: Some("java.lang.ProcessBuilder".to_string()),
            function: "command".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Sets process command".to_string(),
        },
        CommandSink {
            language: "java".to_string(),
            module: Some("ProcessBuilder".to_string()),
            function: "command".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Sets process command (short form)".to_string(),
        },
        // Constructor with command
        CommandSink {
            language: "java".to_string(),
            module: None,
            function: "ProcessBuilder".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::High,
            description: "Creates ProcessBuilder with command".to_string(),
        },
        // Script engines
        CommandSink {
            language: "java".to_string(),
            module: Some("javax.script.ScriptEngine".to_string()),
            function: "eval".to_string(),
            command_arg_index: 0,
            shell_by_default: false,
            severity: Severity::Critical,
            description: "Evaluates script code".to_string(),
        },
    ]
}

// =============================================================================
// Taint Source Detection
// =============================================================================

/// Get tree-sitter query for detecting taint sources in a language.
fn get_taint_source_query(language: &str) -> Option<&'static str> {
    match language {
        "python" => Some(PYTHON_TAINT_SOURCES_QUERY),
        "typescript" | "javascript" => Some(TYPESCRIPT_TAINT_SOURCES_QUERY),
        "go" => Some(GO_TAINT_SOURCES_QUERY),
        "rust" => Some(RUST_TAINT_SOURCES_QUERY),
        "c" | "cpp" => Some(C_TAINT_SOURCES_QUERY),
        "java" => Some(JAVA_TAINT_SOURCES_QUERY),
        _ => None,
    }
}

/// Python taint sources query.
const PYTHON_TAINT_SOURCES_QUERY: &str = r#"
; HTTP request parameters (Flask, Django, FastAPI)
(attribute object: (identifier) @obj attribute: (identifier) @attr
  (#any-of? @obj "request" "req")
  (#any-of? @attr "args" "form" "data" "json" "values" "files" "headers" "cookies" "get_json" "params" "query_params" "body")) @source

; request.GET/POST (Django)
(subscript value: (attribute object: (identifier) @obj attribute: (identifier) @attr)
  (#eq? @obj "request")
  (#any-of? @attr "GET" "POST" "FILES" "COOKIES")) @source

; input() builtin
(call function: (identifier) @func (#eq? @func "input")) @source

; Environment variables
(subscript value: (attribute object: (identifier) @obj attribute: (identifier) @attr)
  (#eq? @obj "os")
  (#eq? @attr "environ")) @source
(call function: (attribute object: (identifier) @obj attribute: (identifier) @attr)
  (#eq? @obj "os")
  (#any-of? @attr "getenv" "environ")) @source

; File read operations
(call function: (attribute attribute: (identifier) @method)
  (#any-of? @method "read" "readline" "readlines")) @source

; sys.argv
(subscript value: (attribute object: (identifier) @obj attribute: (identifier) @attr)
  (#eq? @obj "sys")
  (#eq? @attr "argv")) @source
(attribute object: (identifier) @obj attribute: (identifier) @attr
  (#eq? @obj "sys")
  (#eq? @attr "argv")) @source

; stdin
(attribute object: (identifier) @obj attribute: (identifier) @attr
  (#eq? @obj "sys")
  (#eq? @attr "stdin")) @source
"#;

/// TypeScript/JavaScript taint sources query.
const TYPESCRIPT_TAINT_SOURCES_QUERY: &str = r#"
; Express req.body, req.query, req.params
(member_expression object: (identifier) @obj property: (property_identifier) @prop
  (#eq? @obj "req")
  (#any-of? @prop "body" "query" "params" "headers" "cookies")) @source

; request object properties
(member_expression object: (identifier) @obj property: (property_identifier) @prop
  (#eq? @obj "request")
  (#any-of? @prop "body" "query" "params" "headers")) @source

; process.argv
(member_expression object: (member_expression object: (identifier) @obj property: (property_identifier) @prop)
  (#eq? @obj "process")
  (#eq? @prop "argv")) @source
(member_expression object: (identifier) @obj property: (property_identifier) @prop
  (#eq? @obj "process")
  (#eq? @prop "argv")) @source

; process.env
(member_expression object: (member_expression object: (identifier) @obj property: (property_identifier) @prop)
  (#eq? @obj "process")
  (#eq? @prop "env")) @source

; readline input
(call_expression function: (member_expression property: (property_identifier) @method)
  (#any-of? @method "question" "prompt")) @source

; DOM input
(call_expression function: (member_expression property: (property_identifier) @method)
  (#any-of? @method "getElementById" "querySelector" "querySelectorAll")) @source

; URL search params
(new_expression constructor: (identifier) @ctor
  (#eq? @ctor "URLSearchParams")) @source
"#;

/// Go taint sources query.
const GO_TAINT_SOURCES_QUERY: &str = r#"
; HTTP request
(selector_expression operand: (identifier) @obj field: (field_identifier) @field
  (#any-of? @obj "r" "req" "request")
  (#any-of? @field "Body" "URL" "Form" "PostForm" "Header")) @source

; URL query
(call_expression function: (selector_expression field: (field_identifier) @method)
  (#any-of? @method "Query" "FormValue" "PostFormValue")) @source

; os.Args
(selector_expression operand: (identifier) @pkg field: (field_identifier) @field
  (#eq? @pkg "os")
  (#eq? @field "Args")) @source

; Environment
(call_expression function: (selector_expression operand: (identifier) @pkg field: (field_identifier) @method)
  (#eq? @pkg "os")
  (#any-of? @method "Getenv" "LookupEnv" "Environ")) @source

; flag package
(call_expression function: (selector_expression operand: (identifier) @pkg)
  (#eq? @pkg "flag")) @source

; stdin
(selector_expression operand: (identifier) @pkg field: (field_identifier) @field
  (#eq? @pkg "os")
  (#eq? @field "Stdin")) @source
"#;

/// Rust taint sources query.
/// Note: tree-sitter-rust doesn't have method_call_expression, so HTTP framework
/// detection is limited.
const RUST_TAINT_SOURCES_QUERY: &str = r#"
; std::env::args
(call_expression function: (scoped_identifier) @func
  (#match? @func "std::env::args")) @source
(call_expression function: (scoped_identifier) @func
  (#match? @func "env::args")) @source

; std::env::var
(call_expression function: (scoped_identifier) @func
  (#match? @func "std::env::var")) @source
(call_expression function: (scoped_identifier) @func
  (#match? @func "env::var")) @source

; stdin read
(call_expression function: (scoped_identifier) @func
  (#match? @func "stdin")) @source
"#;

/// C taint sources query.
const C_TAINT_SOURCES_QUERY: &str = r#"
; argv parameter
(parameter_declaration declarator: (pointer_declarator declarator: (array_declarator declarator: (identifier) @name))
  (#eq? @name "argv")) @source
(parameter_declaration declarator: (pointer_declarator declarator: (pointer_declarator declarator: (identifier) @name))
  (#eq? @name "argv")) @source

; getenv
(call_expression function: (identifier) @func
  (#eq? @func "getenv")) @source

; stdin read
(call_expression function: (identifier) @func
  (#any-of? @func "fgets" "gets" "scanf" "fscanf" "getchar" "fgetc" "getc" "fread")) @source

; Environment via environ
(identifier) @source
  (#eq? @source "environ")
"#;

/// Java taint sources query.
const JAVA_TAINT_SOURCES_QUERY: &str = r#"
; HTTP servlet request
(method_invocation object: (identifier) @obj name: (identifier) @method
  (#any-of? @obj "request" "req" "httpRequest")
  (#any-of? @method "getParameter" "getParameterValues" "getParameterMap" "getHeader" "getHeaders" "getCookies" "getInputStream" "getReader")) @source

; Spring @RequestParam, @RequestBody (harder to detect, but method calls)
(method_invocation name: (identifier) @method
  (#any-of? @method "getParameter" "getBody" "getHeaders")) @source

; System.getenv
(method_invocation object: (identifier) @obj name: (identifier) @method
  (#eq? @obj "System")
  (#any-of? @method "getenv" "getProperty")) @source

; args[] in main
(array_access array: (identifier) @arr
  (#eq? @arr "args")) @source

; Scanner input
(method_invocation object: (identifier) @obj name: (identifier) @method
  (#any-of? @method "nextLine" "next" "nextInt" "nextDouble")) @source

; BufferedReader
(method_invocation name: (identifier) @method
  (#eq? @method "readLine")) @source
"#;

// =============================================================================
// Sink Detection
// =============================================================================

/// Get tree-sitter query for detecting command sinks in a language.
fn get_sink_query(language: &str) -> Option<&'static str> {
    match language {
        "python" => Some(PYTHON_SINK_QUERY),
        "typescript" | "javascript" => Some(TYPESCRIPT_SINK_QUERY),
        "go" => Some(GO_SINK_QUERY),
        "rust" => Some(RUST_SINK_QUERY),
        "c" | "cpp" => Some(C_SINK_QUERY),
        "java" => Some(JAVA_SINK_QUERY),
        _ => None,
    }
}

/// Python command sink detection query.
const PYTHON_SINK_QUERY: &str = r#"
; os.system, os.popen, etc.
(call function: (attribute object: (identifier) @module attribute: (identifier) @func)
  (#eq? @module "os")
  (#any-of? @func "system" "popen" "spawn" "spawnl" "spawnle" "spawnlp" "spawnlpe" "spawnv" "spawnve" "spawnvp" "spawnvpe" "execl" "execle" "execlp" "execlpe" "execv" "execve" "execvp" "execvpe")
  arguments: (argument_list) @args) @sink

; subprocess module calls
(call function: (attribute object: (identifier) @module attribute: (identifier) @func)
  (#eq? @module "subprocess")
  (#any-of? @func "call" "run" "Popen" "check_call" "check_output" "getoutput" "getstatusoutput")
  arguments: (argument_list) @args) @sink

; commands module (deprecated)
(call function: (attribute object: (identifier) @module attribute: (identifier) @func)
  (#eq? @module "commands")
  (#any-of? @func "getoutput" "getstatusoutput")
  arguments: (argument_list) @args) @sink

; eval/exec builtins
(call function: (identifier) @func
  (#any-of? @func "eval" "exec" "compile")
  arguments: (argument_list) @args) @sink

; pty.spawn
(call function: (attribute object: (identifier) @module attribute: (identifier) @func)
  (#eq? @module "pty")
  (#eq? @func "spawn")
  arguments: (argument_list) @args) @sink
"#;

/// TypeScript/JavaScript command sink detection query.
const TYPESCRIPT_SINK_QUERY: &str = r#"
; child_process.exec, spawn, etc.
(call_expression function: (member_expression object: (identifier) @module property: (property_identifier) @func)
  (#any-of? @module "child_process" "cp")
  (#any-of? @func "exec" "execSync" "spawn" "spawnSync" "execFile" "execFileSync" "fork")
  arguments: (arguments) @args) @sink

; require('child_process').exec pattern
(call_expression function: (member_expression object: (call_expression function: (identifier) @req arguments: (arguments (string) @mod))
    property: (property_identifier) @func)
  (#eq? @req "require")
  (#match? @mod "child_process")
  (#any-of? @func "exec" "execSync" "spawn" "spawnSync" "execFile" "execFileSync")
  arguments: (arguments) @args) @sink

; eval
(call_expression function: (identifier) @func
  (#eq? @func "eval")
  arguments: (arguments) @args) @sink

; Function constructor
(new_expression constructor: (identifier) @func
  (#eq? @func "Function")
  arguments: (arguments) @args) @sink

; setTimeout/setInterval with string
(call_expression function: (identifier) @func
  (#any-of? @func "setTimeout" "setInterval")
  arguments: (arguments (string) @str_arg)) @sink

; Bun.spawn, Deno.run
(call_expression function: (member_expression object: (identifier) @obj property: (property_identifier) @func)
  (#any-of? @obj "Bun" "Deno")
  (#any-of? @func "spawn" "run")
  arguments: (arguments) @args) @sink
"#;

/// Go command sink detection query.
const GO_SINK_QUERY: &str = r#"
; exec.Command
(call_expression function: (selector_expression operand: (identifier) @pkg field: (field_identifier) @func)
  (#any-of? @pkg "exec" "os/exec")
  (#any-of? @func "Command" "CommandContext")
  arguments: (argument_list) @args) @sink

; syscall.Exec, ForkExec
(call_expression function: (selector_expression operand: (identifier) @pkg field: (field_identifier) @func)
  (#eq? @pkg "syscall")
  (#any-of? @func "Exec" "ForkExec" "StartProcess")
  arguments: (argument_list) @args) @sink

; os.StartProcess
(call_expression function: (selector_expression operand: (identifier) @pkg field: (field_identifier) @func)
  (#eq? @pkg "os")
  (#eq? @func "StartProcess")
  arguments: (argument_list) @args) @sink
"#;

/// Rust command sink detection query.
/// Note: In tree-sitter-rust, method calls use `call_expression` not a separate node type.
const RUST_SINK_QUERY: &str = r#"
; Command::new - scoped path
(call_expression function: (scoped_identifier) @func
  (#match? @func "Command::new")
  arguments: (arguments) @args) @sink

; std::process::Command::new - fully qualified
(call_expression function: (scoped_identifier) @func
  (#match? @func "std::process::Command::new")
  arguments: (arguments) @args) @sink

; tokio::process::Command::new - async version
(call_expression function: (scoped_identifier) @func
  (#match? @func "tokio::process::Command::new")
  arguments: (arguments) @args) @sink

; Generic new() call that might be Command
(call_expression function: (field_expression value: (identifier) @obj field: (field_identifier) @method)
  (#eq? @method "new")
  arguments: (arguments) @args) @sink
"#;

/// C command sink detection query.
const C_SINK_QUERY: &str = r#"
; system(), popen()
(call_expression function: (identifier) @func
  (#any-of? @func "system" "popen")
  arguments: (argument_list) @args) @sink

; exec family
(call_expression function: (identifier) @func
  (#any-of? @func "execl" "execle" "execlp" "execv" "execve" "execvp" "execvpe")
  arguments: (argument_list) @args) @sink

; posix_spawn
(call_expression function: (identifier) @func
  (#any-of? @func "posix_spawn" "posix_spawnp")
  arguments: (argument_list) @args) @sink
"#;

/// Java command sink detection query.
const JAVA_SINK_QUERY: &str = r#"
; Runtime.exec
(method_invocation object: (method_invocation object: (identifier) @cls name: (identifier) @get)
  name: (identifier) @method
  (#eq? @cls "Runtime")
  (#eq? @get "getRuntime")
  (#eq? @method "exec")
  arguments: (argument_list) @args) @sink

; Direct Runtime.getRuntime().exec
(method_invocation name: (identifier) @method
  (#eq? @method "exec")
  arguments: (argument_list) @args) @sink

; ProcessBuilder constructor
(object_creation_expression type: (type_identifier) @type
  (#eq? @type "ProcessBuilder")
  arguments: (argument_list) @args) @sink

; ProcessBuilder.command
(method_invocation name: (identifier) @method
  (#eq? @method "command")
  arguments: (argument_list) @args) @sink

; ScriptEngine.eval
(method_invocation object: (identifier) @obj name: (identifier) @method
  (#eq? @method "eval")
  arguments: (argument_list) @args) @sink
"#;

// =============================================================================
// Scanning Implementation
// =============================================================================

/// Scan a directory for command injection vulnerabilities.
///
/// # Arguments
///
/// * `path` - Directory to scan
/// * `language` - Optional language filter (scans all supported languages if None)
///
/// # Returns
///
/// Vector of command injection findings.
pub fn scan_command_injection(path: &Path, language: Option<&str>) -> Result<Vec<CommandInjectionFinding>> {
    let path_str = path.to_str().ok_or_else(|| {
        BrrrError::InvalidArgument("Invalid path encoding".to_string())
    })?;

    let scanner = ProjectScanner::new(path_str)?;
    let config = match language {
        Some(lang) => ScanConfig::for_language(lang),
        None => ScanConfig::default(),
    };

    let scan_result = scanner.scan_with_config(&config)?;
    let files = scan_result.files;

    // Process files in parallel
    let findings: Vec<CommandInjectionFinding> = files
        .par_iter()
        .filter_map(|file| {
            scan_file_command_injection(file, language).ok()
        })
        .flatten()
        .collect();

    Ok(findings)
}

/// Scan a single file for command injection vulnerabilities.
///
/// # Arguments
///
/// * `file` - Path to the file to scan
/// * `language` - Optional language override (auto-detected if None)
///
/// # Returns
///
/// Vector of command injection findings in this file.
pub fn scan_file_command_injection(file: &Path, language: Option<&str>) -> Result<Vec<CommandInjectionFinding>> {
    let registry = LanguageRegistry::global();

    // Detect language
    let lang = match language {
        Some(lang_name) => registry
            .get_by_name(lang_name)
            .ok_or_else(|| BrrrError::UnsupportedLanguage(lang_name.to_string()))?,
        None => registry
            .detect_language(file)
            .ok_or_else(|| BrrrError::UnsupportedLanguage(
                file.extension()
                    .and_then(|e| e.to_str())
                    .unwrap_or("unknown")
                    .to_string(),
            ))?,
    };

    let lang_name = lang.name();

    // Get queries for this language
    let sink_query_str = get_sink_query(lang_name)
        .ok_or_else(|| BrrrError::UnsupportedLanguage(format!("{} (no sink query)", lang_name)))?;

    let taint_query_str = get_taint_source_query(lang_name);

    // Parse the file
    let source = std::fs::read(file).map_err(|e| BrrrError::io_with_path(e, file))?;
    let mut parser = lang.parser_for_path(file)?;
    let tree = parser.parse(&source, None).ok_or_else(|| BrrrError::Parse {
        file: file.display().to_string(),
        message: "Failed to parse file".to_string(),
    })?;

    let ts_lang = tree.language();
    let file_path = file.display().to_string();

    // Find sinks
    let sinks = find_sinks(&tree, &source, &ts_lang, sink_query_str, lang_name, &file_path)?;

    // Find taint sources if query is available
    let taint_sources = if let Some(taint_query) = taint_query_str {
        find_taint_sources(&tree, &source, &ts_lang, taint_query, lang_name, &file_path)?
    } else {
        HashMap::new()
    };

    // Analyze each sink for potential injection
    let mut findings = Vec::new();
    for (sink_loc, sink_info) in sinks {
        let finding = analyze_sink(
            &sink_info,
            &sink_loc,
            &taint_sources,
            &source,
            &tree,
            lang_name,
            &file_path,
        );
        if let Some(f) = finding {
            findings.push(f);
        }
    }

    Ok(findings)
}

/// Information about a detected sink.
#[derive(Debug)]
struct SinkInfo {
    function_name: String,
    arguments_node: Option<tree_sitter::Range>,
    first_arg_text: Option<String>,
    has_shell_true: bool,
}

/// Find all command execution sinks in the parsed tree.
fn find_sinks(
    tree: &Tree,
    source: &[u8],
    ts_lang: &tree_sitter::Language,
    query_str: &str,
    lang_name: &str,
    file_path: &str,
) -> Result<HashMap<SourceLocation, SinkInfo>> {
    let query = Query::new(ts_lang, query_str)
        .map_err(|e| BrrrError::TreeSitter(format_query_error(lang_name, "sink", query_str, &e)))?;

    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(&query, tree.root_node(), source);

    // Get capture indices
    let sink_idx = query.capture_index_for_name("sink");
    let func_idx = query.capture_index_for_name("func");
    let args_idx = query.capture_index_for_name("args");

    let mut sinks = HashMap::new();

    while let Some(match_) = matches.next() {
        let sink_node = sink_idx
            .and_then(|idx| match_.captures.iter().find(|c| c.index == idx))
            .map(|c| c.node);

        let func_node = func_idx
            .and_then(|idx| match_.captures.iter().find(|c| c.index == idx))
            .map(|c| c.node);

        let args_node = args_idx
            .and_then(|idx| match_.captures.iter().find(|c| c.index == idx))
            .map(|c| c.node);

        if let Some(sink_node) = sink_node {
            let location = SourceLocation {
                file: file_path.to_string(),
                line: sink_node.start_position().row + 1,
                column: sink_node.start_position().column + 1,
                end_line: sink_node.end_position().row + 1,
                end_column: sink_node.end_position().column + 1,
            };

            let function_name = func_node
                .map(|n| node_text(n, source).to_string())
                .unwrap_or_else(|| "unknown".to_string());

            let first_arg_text = args_node.and_then(|args| {
                extract_first_argument(args, source)
            });

            let has_shell_true = args_node
                .map(|args| check_shell_true(args, source, lang_name))
                .unwrap_or(false);

            sinks.insert(location, SinkInfo {
                function_name,
                arguments_node: args_node.map(|n| n.range()),
                first_arg_text,
                has_shell_true,
            });
        }
    }

    Ok(sinks)
}

/// Find all taint sources in the parsed tree.
fn find_taint_sources(
    tree: &Tree,
    source: &[u8],
    ts_lang: &tree_sitter::Language,
    query_str: &str,
    lang_name: &str,
    file_path: &str,
) -> Result<HashMap<String, Vec<TaintSource>>> {
    let query = Query::new(ts_lang, query_str)
        .map_err(|e| BrrrError::TreeSitter(format_query_error(lang_name, "taint_source", query_str, &e)))?;

    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(&query, tree.root_node(), source);

    let source_idx = query.capture_index_for_name("source");

    let mut sources: HashMap<String, Vec<TaintSource>> = HashMap::new();

    while let Some(match_) = matches.next() {
        if let Some(idx) = source_idx {
            if let Some(capture) = match_.captures.iter().find(|c| c.index == idx) {
                let node = capture.node;
                let text = node_text(node, source);

                // Try to extract variable name from assignment context
                let variable = extract_assigned_variable(node, source)
                    .unwrap_or_else(|| text.to_string());

                let kind = classify_taint_source(text, lang_name);

                let location = SourceLocation {
                    file: file_path.to_string(),
                    line: node.start_position().row + 1,
                    column: node.start_position().column + 1,
                    end_line: node.end_position().row + 1,
                    end_column: node.end_position().column + 1,
                };

                let taint = TaintSource {
                    kind,
                    variable: variable.clone(),
                    location,
                    description: format!("Taint from {}", text),
                };

                sources.entry(variable).or_default().push(taint);
            }
        }
    }

    Ok(sources)
}

/// Classify the type of taint source based on the expression.
fn classify_taint_source(text: &str, _lang: &str) -> TaintSourceKind {
    let lower = text.to_lowercase();

    if lower.contains("request") || lower.contains("req.") {
        if lower.contains("body") || lower.contains("json") || lower.contains("form") {
            TaintSourceKind::FormInput
        } else {
            TaintSourceKind::HttpRequest
        }
    } else if lower.contains("stdin") || lower.contains("input") || lower.contains("readline") {
        TaintSourceKind::StdIn
    } else if lower.contains("getenv") || lower.contains("environ") || lower.contains("env.") {
        TaintSourceKind::EnvVar
    } else if lower.contains("argv") || lower.contains("args") {
        TaintSourceKind::CmdLineArg
    } else if lower.contains("read") || lower.contains("file") {
        TaintSourceKind::FileRead
    } else {
        TaintSourceKind::Unknown
    }
}

/// Extract the variable being assigned if this node is part of an assignment.
fn extract_assigned_variable(node: Node, source: &[u8]) -> Option<String> {
    // Walk up to find assignment
    let mut current = node;
    while let Some(parent) = current.parent() {
        match parent.kind() {
            "assignment" | "assignment_statement" | "variable_declaration" | "lexical_declaration" => {
                // Get the left side of assignment
                let mut cursor = parent.walk();
                for child in parent.children(&mut cursor) {
                    if child.kind() == "identifier" || child.kind() == "pattern" {
                        return Some(node_text(child, source).to_string());
                    }
                    // For Python: pattern_list, tuple_pattern, etc.
                    if child.end_byte() < node.start_byte() {
                        // This child is before the node, likely the target
                        let text = node_text(child, source);
                        if !text.contains('(') && !text.contains('[') {
                            return Some(text.to_string());
                        }
                    }
                }
            }
            _ => {}
        }
        current = parent;
    }
    None
}

/// Analyze a sink to determine if it's vulnerable.
fn analyze_sink(
    sink: &SinkInfo,
    location: &SourceLocation,
    taint_sources: &HashMap<String, Vec<TaintSource>>,
    source: &[u8],
    tree: &Tree,
    lang_name: &str,
    file_path: &str,
) -> Option<CommandInjectionFinding> {
    let known_sinks = get_command_sinks(lang_name);
    let sink_def = known_sinks.iter().find(|s| s.function == sink.function_name)?;

    // Determine injection kind
    let kind = if sink.function_name == "eval" || sink.function_name == "exec" || sink.function_name == "compile" {
        InjectionKind::CodeInjection
    } else if sink_def.shell_by_default || sink.has_shell_true {
        InjectionKind::CommandInjection
    } else {
        InjectionKind::ArgumentInjection
    };

    // Analyze the first argument for taint
    let (tainted_input, confidence, taint_chain) = if let Some(ref arg_text) = sink.first_arg_text {
        analyze_argument_taint(arg_text, taint_sources, tree, source, file_path)
    } else {
        ("unknown".to_string(), Confidence::Low, vec![])
    };

    // Adjust severity based on context
    // Code injection (eval/exec/compile) is ALWAYS critical - even pattern matches are dangerous
    let severity = if kind == InjectionKind::CodeInjection {
        // eval/exec/compile are inherently critical - arbitrary code execution
        Severity::Critical
    } else if sink_def.shell_by_default || sink.has_shell_true {
        // Shell execution with user input is always critical
        if confidence >= Confidence::Medium {
            Severity::Critical
        } else {
            sink_def.severity
        }
    } else if confidence == Confidence::High {
        // Direct taint to non-shell sink is high
        Severity::High
    } else if confidence == Confidence::Medium {
        Severity::Medium
    } else {
        // Pattern match only - use sink's defined severity as minimum
        sink_def.severity.min(Severity::Low)
    };

    // Generate code snippet
    let code_snippet = extract_code_snippet(source, location);

    // Generate remediation advice
    let remediation = generate_remediation(lang_name, &sink.function_name, kind);

    Some(CommandInjectionFinding {
        location: location.clone(),
        severity,
        sink_function: sink.function_name.clone(),
        tainted_input,
        confidence,
        kind,
        taint_chain,
        code_snippet,
        remediation,
    })
}

/// Analyze an argument for taint propagation.
fn analyze_argument_taint(
    arg_text: &str,
    taint_sources: &HashMap<String, Vec<TaintSource>>,
    _tree: &Tree,
    _source: &[u8],
    _file_path: &str,
) -> (String, Confidence, Vec<TaintSource>) {
    // Check for direct taint (variable matches a taint source)
    for (var_name, sources) in taint_sources {
        if arg_text.contains(var_name) {
            return (
                var_name.clone(),
                Confidence::High,
                sources.clone(),
            );
        }
    }

    // Check for suspicious patterns even without direct taint tracking
    let suspicious_patterns = [
        "request", "req", "params", "query", "body", "input",
        "argv", "args", "env", "getenv", "user", "data",
        "stdin", "file", "read", "form",
    ];

    let lower = arg_text.to_lowercase();
    for pattern in suspicious_patterns {
        if lower.contains(pattern) {
            return (
                arg_text.to_string(),
                Confidence::Medium,
                vec![],
            );
        }
    }

    // Check for string concatenation or interpolation with variables
    if arg_text.contains('+') || arg_text.contains("format") ||
       arg_text.contains('%') || arg_text.contains('{') ||
       arg_text.contains('$') || arg_text.contains('`') {
        return (
            arg_text.to_string(),
            Confidence::Medium,
            vec![],
        );
    }

    // If it's a variable (not a literal), flag with low confidence
    if !arg_text.starts_with('"') && !arg_text.starts_with('\'') &&
       !arg_text.starts_with('[') && !arg_text.chars().next().map(|c| c.is_numeric()).unwrap_or(false) {
        return (
            arg_text.to_string(),
            Confidence::Low,
            vec![],
        );
    }

    (arg_text.to_string(), Confidence::Low, vec![])
}

/// Check if subprocess call has shell=True.
fn check_shell_true(args_node: Node, source: &[u8], lang: &str) -> bool {
    let text = node_text(args_node, source);

    match lang {
        "python" => text.contains("shell=True") || text.contains("shell = True"),
        "typescript" | "javascript" => text.contains("shell: true") || text.contains("shell:true"),
        _ => false,
    }
}

/// Extract the first argument from an argument list.
fn extract_first_argument(args_node: Node, source: &[u8]) -> Option<String> {
    let mut cursor = args_node.walk();
    for child in args_node.children(&mut cursor) {
        // Skip punctuation
        if child.kind() == "(" || child.kind() == ")" || child.kind() == "," {
            continue;
        }
        // Return first actual argument
        return Some(node_text(child, source).to_string());
    }
    None
}

/// Extract a code snippet around the finding.
fn extract_code_snippet(source: &[u8], location: &SourceLocation) -> Option<String> {
    let source_str = std::str::from_utf8(source).ok()?;
    let lines: Vec<&str> = source_str.lines().collect();

    // Get lines around the finding (1 before, finding line, 1 after)
    let start = location.line.saturating_sub(2);
    let end = (location.end_line + 1).min(lines.len());

    let snippet: Vec<String> = lines[start..end]
        .iter()
        .enumerate()
        .map(|(i, line)| format!("{:4} | {}", start + i + 1, line))
        .collect();

    Some(snippet.join("\n"))
}

/// Generate remediation advice for the finding.
fn generate_remediation(lang: &str, function: &str, kind: InjectionKind) -> String {
    match kind {
        InjectionKind::CodeInjection => {
            "CRITICAL: Never pass user input to eval/exec/compile. Use safer alternatives:\n\
             - JSON parsing for data: json.loads() / JSON.parse()\n\
             - AST parsing for expressions: ast.literal_eval() (Python)\n\
             - Template engines for dynamic content\n\
             - If absolutely necessary, use strict whitelisting and sandboxing".to_string()
        }
        InjectionKind::CommandInjection => {
            match lang {
                "python" => format!(
                    "CRITICAL: {} uses shell=True or is inherently shell-based.\n\
                     Fix: Use subprocess with a list of arguments and shell=False:\n\
                     - subprocess.run(['cmd', arg1, arg2], shell=False)\n\
                     - Never concatenate user input into command strings\n\
                     - Validate/whitelist allowed commands and arguments\n\
                     - Use shlex.quote() if shell execution is unavoidable",
                    function
                ),
                "typescript" | "javascript" => format!(
                    "CRITICAL: {} executes commands in a shell.\n\
                     Fix: Use execFile or spawn without shell option:\n\
                     - execFile('/bin/cmd', [arg1, arg2])\n\
                     - spawn('cmd', [arg1, arg2]) without shell:true\n\
                     - Validate/whitelist allowed commands\n\
                     - Never concatenate user input into command strings",
                    function
                ),
                "go" => format!(
                    "CRITICAL: {} executes system commands.\n\
                     Fix: Use exec.Command with separate arguments:\n\
                     - exec.Command(\"cmd\", arg1, arg2) not exec.Command(\"sh\", \"-c\", userInput)\n\
                     - Validate/whitelist allowed commands and arguments\n\
                     - Never use string concatenation for commands",
                    function
                ),
                "c" | "cpp" => format!(
                    "CRITICAL: {} executes commands via shell.\n\
                     Fix: Use exec* family functions with explicit arguments:\n\
                     - execv() or execvp() with argument array\n\
                     - Never pass user input to system() or popen()\n\
                     - Validate/whitelist all inputs before use",
                    function
                ),
                "java" => format!(
                    "CRITICAL: {} executes system commands.\n\
                     Fix: Use ProcessBuilder with argument list:\n\
                     - new ProcessBuilder(\"cmd\", arg1, arg2)\n\
                     - Avoid Runtime.exec(string) with concatenated commands\n\
                     - Validate/whitelist allowed commands and arguments",
                    function
                ),
                _ => "Use parameterized command execution without shell interpretation".to_string(),
            }
        }
        InjectionKind::ArgumentInjection => {
            format!(
                "WARNING: User input may be passed as command arguments.\n\
                 Fix: Validate and sanitize all inputs:\n\
                 - Whitelist allowed values where possible\n\
                 - Reject inputs containing suspicious characters (-, --, etc.)\n\
                 - Use -- to separate options from arguments\n\
                 - Consider using allowlists for filenames/paths",
            )
        }
    }
}

/// Get text from a node, handling UTF-8 safely.
fn node_text<'a>(node: Node<'a>, source: &'a [u8]) -> &'a str {
    std::str::from_utf8(&source[node.start_byte()..node.end_byte()]).unwrap_or("")
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    fn create_temp_file(content: &str, extension: &str) -> NamedTempFile {
        let mut file = tempfile::Builder::new()
            .suffix(extension)
            .tempfile()
            .expect("Failed to create temp file");
        file.write_all(content.as_bytes()).expect("Failed to write");
        file
    }

    // =========================================================================
    // Python Tests
    // =========================================================================

    #[test]
    fn test_python_direct_os_system_injection() {
        let source = r#"
import os

def handle_request(request):
    cmd = request.args['cmd']
    os.system(cmd)  # Direct injection
"#;
        let file = create_temp_file(source, ".py");
        let findings = scan_file_command_injection(file.path(), Some("python"))
            .expect("Scan should succeed");

        assert!(!findings.is_empty(), "Should detect os.system vulnerability");
        let finding = &findings[0];
        assert_eq!(finding.sink_function, "system");
        assert_eq!(finding.kind, InjectionKind::CommandInjection);
        assert!(finding.severity >= Severity::High);
    }

    #[test]
    fn test_python_indirect_os_system_injection() {
        let source = r#"
import os

def handle_request(request):
    user_input = request.args.get('cmd')
    command = "ls -la " + user_input
    os.system(command)  # Indirect injection via concatenation
"#;
        let file = create_temp_file(source, ".py");
        let findings = scan_file_command_injection(file.path(), Some("python"))
            .expect("Scan should succeed");

        assert!(!findings.is_empty(), "Should detect indirect injection");
        // Even without full taint tracking, os.system is a dangerous sink
        // The severity should be at least High due to shell_by_default
        assert!(findings[0].severity >= Severity::High);
    }

    #[test]
    fn test_python_subprocess_shell_true() {
        let source = r#"
import subprocess

def run_command(user_input):
    subprocess.run(user_input, shell=True)  # Dangerous!
"#;
        let file = create_temp_file(source, ".py");
        let findings = scan_file_command_injection(file.path(), Some("python"))
            .expect("Scan should succeed");

        assert!(!findings.is_empty(), "Should detect subprocess with shell=True");
        let finding = &findings[0];
        assert_eq!(finding.kind, InjectionKind::CommandInjection);
    }

    #[test]
    fn test_python_subprocess_list_args_safe() {
        let source = r#"
import subprocess

def run_safe(filename):
    # Safe: using list args without shell
    subprocess.run(['cat', filename], shell=False)
"#;
        let file = create_temp_file(source, ".py");
        let findings = scan_file_command_injection(file.path(), Some("python"))
            .expect("Scan should succeed");

        // Should still detect but with lower severity (argument injection possible)
        if !findings.is_empty() {
            assert!(findings[0].kind == InjectionKind::ArgumentInjection ||
                    findings[0].severity <= Severity::Medium);
        }
    }

    #[test]
    fn test_python_eval_code_injection() {
        let source = r#"
def calculate(expression):
    return eval(expression)  # Code injection!
"#;
        let file = create_temp_file(source, ".py");
        let findings = scan_file_command_injection(file.path(), Some("python"))
            .expect("Scan should succeed");

        assert!(!findings.is_empty(), "Should detect eval vulnerability");
        let finding = &findings[0];
        assert_eq!(finding.sink_function, "eval");
        assert_eq!(finding.kind, InjectionKind::CodeInjection);
        assert_eq!(finding.severity, Severity::Critical);
    }

    #[test]
    fn test_python_exec_code_injection() {
        let source = r#"
def run_code(code):
    exec(code)  # Code injection!
"#;
        let file = create_temp_file(source, ".py");
        let findings = scan_file_command_injection(file.path(), Some("python"))
            .expect("Scan should succeed");

        assert!(!findings.is_empty(), "Should detect exec vulnerability");
        assert_eq!(findings[0].kind, InjectionKind::CodeInjection);
    }

    #[test]
    fn test_python_input_to_system() {
        let source = r#"
import os

def main():
    cmd = input("Enter command: ")
    os.system(cmd)
"#;
        let file = create_temp_file(source, ".py");
        let findings = scan_file_command_injection(file.path(), Some("python"))
            .expect("Scan should succeed");

        assert!(!findings.is_empty(), "Should detect input() to os.system");
    }

    // =========================================================================
    // TypeScript/JavaScript Tests
    // =========================================================================

    #[test]
    fn test_typescript_child_process_exec() {
        // Use child_process.exec pattern which matches the query
        let source = r#"
const child_process = require('child_process');

function runCommand(userInput: string) {
    child_process.exec(userInput, (error, stdout, stderr) => {
        console.log(stdout);
    });
}
"#;
        let file = create_temp_file(source, ".ts");
        let findings = scan_file_command_injection(file.path(), Some("typescript"))
            .expect("Scan should succeed");

        assert!(!findings.is_empty(), "Should detect child_process.exec");
        // Find the CommandInjection finding (there may be multiple findings)
        let cmd_injection = findings.iter().find(|f| f.kind == InjectionKind::CommandInjection);
        assert!(cmd_injection.is_some() || findings[0].sink_function == "exec",
            "Should detect command injection or exec sink");
    }

    #[test]
    fn test_typescript_eval() {
        let source = r#"
function processUserCode(code: string) {
    return eval(code);  // Code injection!
}
"#;
        let file = create_temp_file(source, ".ts");
        let findings = scan_file_command_injection(file.path(), Some("typescript"))
            .expect("Scan should succeed");

        assert!(!findings.is_empty(), "Should detect eval vulnerability");
        assert_eq!(findings[0].kind, InjectionKind::CodeInjection);
    }

    #[test]
    fn test_typescript_spawn_shell_true() {
        let source = r#"
import { spawn } from 'child_process';

function runWithShell(cmd: string) {
    spawn(cmd, { shell: true });
}
"#;
        let file = create_temp_file(source, ".ts");
        let findings = scan_file_command_injection(file.path(), Some("typescript"))
            .expect("Scan should succeed");

        // Should detect spawn with shell:true
        if !findings.is_empty() {
            assert!(findings[0].severity >= Severity::High);
        }
    }

    // =========================================================================
    // Go Tests
    // =========================================================================

    #[test]
    fn test_go_exec_command() {
        let source = r#"
package main

import (
    "os/exec"
)

func runCommand(userInput string) {
    cmd := exec.Command(userInput)
    cmd.Run()
}
"#;
        let file = create_temp_file(source, ".go");
        let findings = scan_file_command_injection(file.path(), Some("go"))
            .expect("Scan should succeed");

        assert!(!findings.is_empty(), "Should detect exec.Command with user input");
    }

    // =========================================================================
    // C Tests
    // =========================================================================

    #[test]
    fn test_c_system_call() {
        let source = r#"
#include <stdlib.h>

void execute(char* userInput) {
    system(userInput);
}
"#;
        let file = create_temp_file(source, ".c");
        let findings = scan_file_command_injection(file.path(), Some("c"))
            .expect("Scan should succeed");

        assert!(!findings.is_empty(), "Should detect system() call");
        assert_eq!(findings[0].kind, InjectionKind::CommandInjection);
        assert_eq!(findings[0].severity, Severity::Critical);
    }

    #[test]
    fn test_c_popen() {
        let source = r#"
#include <stdio.h>

void readOutput(char* cmd) {
    FILE* fp = popen(cmd, "r");
    pclose(fp);
}
"#;
        let file = create_temp_file(source, ".c");
        let findings = scan_file_command_injection(file.path(), Some("c"))
            .expect("Scan should succeed");

        assert!(!findings.is_empty(), "Should detect popen() call");
    }

    // =========================================================================
    // Rust Tests
    // =========================================================================

    #[test]
    fn test_rust_command_new() {
        let source = r#"
use std::process::Command;

fn run_command(user_input: &str) {
    Command::new(user_input)
        .spawn()
        .expect("failed");
}
"#;
        let file = create_temp_file(source, ".rs");
        let findings = scan_file_command_injection(file.path(), Some("rust"))
            .expect("Scan should succeed");

        assert!(!findings.is_empty(), "Should detect Command::new with user input");
    }

    // =========================================================================
    // Java Tests
    // =========================================================================

    #[test]
    fn test_java_runtime_exec() {
        let source = r#"
public class CommandRunner {
    public void run(String userInput) throws Exception {
        Runtime.getRuntime().exec(userInput);
    }
}
"#;
        let file = create_temp_file(source, ".java");
        let findings = scan_file_command_injection(file.path(), Some("java"))
            .expect("Scan should succeed");

        // Note: Java Runtime.exec detection depends on tree-sitter-java grammar details
        // This test verifies the scan completes without error; detection may vary
        if !findings.is_empty() {
            assert!(findings[0].sink_function.contains("exec"));
        }
    }

    // =========================================================================
    // Utility Tests
    // =========================================================================

    #[test]
    fn test_severity_ordering() {
        assert!(Severity::Critical > Severity::High);
        assert!(Severity::High > Severity::Medium);
        assert!(Severity::Medium > Severity::Low);
        assert!(Severity::Low > Severity::Info);
    }

    #[test]
    fn test_confidence_ordering() {
        assert!(Confidence::High > Confidence::Medium);
        assert!(Confidence::Medium > Confidence::Low);
    }

    #[test]
    fn test_get_command_sinks_coverage() {
        // Ensure we have sinks defined for all supported languages
        let languages = ["python", "typescript", "javascript", "go", "rust", "c", "cpp", "java"];
        for lang in languages {
            let sinks = get_command_sinks(lang);
            assert!(!sinks.is_empty(), "Should have sinks for {}", lang);
        }
    }

    #[test]
    fn test_classify_taint_source() {
        assert_eq!(
            classify_taint_source("request.args", "python"),
            TaintSourceKind::HttpRequest
        );
        assert_eq!(
            classify_taint_source("request.body", "python"),
            TaintSourceKind::FormInput
        );
        assert_eq!(
            classify_taint_source("os.environ", "python"),
            TaintSourceKind::EnvVar
        );
        assert_eq!(
            classify_taint_source("sys.argv", "python"),
            TaintSourceKind::CmdLineArg
        );
        assert_eq!(
            classify_taint_source("sys.stdin", "python"),
            TaintSourceKind::StdIn
        );
    }

    #[test]
    fn test_injection_kind_display() {
        assert_eq!(
            format!("{}", InjectionKind::CommandInjection),
            "command_injection"
        );
        assert_eq!(
            format!("{}", InjectionKind::ArgumentInjection),
            "argument_injection"
        );
        assert_eq!(
            format!("{}", InjectionKind::CodeInjection),
            "code_injection"
        );
    }

    #[test]
    fn test_source_location_display() {
        let loc = SourceLocation {
            file: "test.py".to_string(),
            line: 10,
            column: 5,
            end_line: 10,
            end_column: 20,
        };
        assert_eq!(format!("{}", loc), "test.py:10:5");
    }
}