foxguard 0.12.0

A security scanner as fast as a linter, written in Rust. 200+ built-in rules across 12 source languages.
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
//! Intraprocedural, flow-insensitive taint analysis for C.
//!
//! Fifth sibling to `python_taint`, `javascript_taint`, `go_taint`,
//! and `kotlin_taint`. Exposes the same public surface -- `TaintSpec`,
//! `NodeMatcher`, `TaintFinding`, `analyze_tree` -- so callers can write
//! declarative `(sources, sinks, sanitizers)` specs the same way they
//! do for the other languages.
//!
//! # Scope (mirrors the other engines)
//!
//! - **Per function.** Each `function_definition` body is analyzed
//!   independently.
//! - **Per file.** No cross-file analysis (v1).
//! - **Flow-insensitive.** Two propagation passes; sources seed a name
//!   set, the analyzer transitively taints any declaration or assignment
//!   whose initializer/RHS references a tainted name or a tainted
//!   source expression.
//! - **String concat propagation** -- binary `+` or function calls
//!   that wrap tainted arguments propagate taint.
//! - **No alias table.** C has no import system; `#include` is textual.
//!   All callee names are matched as-is.
//!
//! # Target vulnerability classes
//!
//! - **Format string** -- `printf(user_input)` where the format argument
//!   is tainted.
//! - **Command injection** -- `system()`, `popen()`, `exec*()` family.
//! - **Buffer overflow** -- `strcpy()`, `strcat()`, `memcpy()` with
//!   tainted source or tainted length.
//! - **SQL injection** -- string-building that flows into `sqlite3_exec`
//!   or `mysql_query`.
//!
//! # Sources
//!
//! `read()`, `recv()`, `fgets()`, `scanf()`, `getenv()`, `fread()`,
//! `recvfrom()`, `recvmsg()`, `fgetc()`, `getchar()`, `gets()`.
//! The `argv` parameter name is also treated as a source.
//!
//! # Sanitizers
//!
//! Bounds-checking patterns (`snprintf`, `strlcpy`, `strlcat`,
//! `strncpy`, `strncat`) collapse taint to clean.

use crate::rules::common::{walk_tree, AliasTable};
pub use crate::rules::taint_engine::{NodeMatcher, TaintFinding, TaintSpec};
use std::collections::HashSet;
use tree_sitter::Node;

// -- Public API --------------------------------------------------------------

/// Run the C taint engine over every function body inside `root` and
/// return one [`TaintFinding`] per source->sink flow.
///
/// The `aliases` argument is unused for C (no import system) but kept
/// for shape parity with the other engines.
pub fn analyze_tree(
    root: Node<'_>,
    source: &str,
    spec: &TaintSpec,
    _aliases: Option<&AliasTable>,
) -> Vec<TaintFinding> {
    let mut findings = Vec::new();
    walk_tree(root, source, &mut |node, src| {
        if node.kind() == "function_definition" {
            analyze_scope(node, src, spec, &mut findings);
        }
    });
    findings
}

/// All C taint rule IDs paired with their specs.
///
/// Consumed by [`crate::rules::builtin_taint_specs_for_language`].
pub fn c_taint_rule_specs() -> Vec<(&'static str, TaintSpec)> {
    vec![
        ("c/taint-format-string", format_string_spec()),
        ("c/taint-command-injection", command_injection_spec()),
        ("c/taint-buffer-overflow", buffer_overflow_spec()),
        ("c/taint-sql-injection", sql_injection_spec()),
    ]
}

/// Shared sources for every C taint rule.
pub fn c_taint_sources() -> Vec<NodeMatcher> {
    vec![
        // POSIX / libc input functions
        NodeMatcher::Call {
            canonical: "read".into(),
            description: "read() — POSIX file/socket read".into(),
        },
        NodeMatcher::Call {
            canonical: "recv".into(),
            description: "recv() — socket receive".into(),
        },
        NodeMatcher::Call {
            canonical: "recvfrom".into(),
            description: "recvfrom() — socket receive with address".into(),
        },
        NodeMatcher::Call {
            canonical: "recvmsg".into(),
            description: "recvmsg() — socket message receive".into(),
        },
        NodeMatcher::Call {
            canonical: "fgets".into(),
            description: "fgets() — buffered input".into(),
        },
        NodeMatcher::Call {
            canonical: "fread".into(),
            description: "fread() — binary file read".into(),
        },
        NodeMatcher::Call {
            canonical: "fgetc".into(),
            description: "fgetc() — single character read".into(),
        },
        NodeMatcher::Call {
            canonical: "getchar".into(),
            description: "getchar() — stdin character read".into(),
        },
        NodeMatcher::Call {
            canonical: "gets".into(),
            description: "gets() — unsafe stdin read".into(),
        },
        NodeMatcher::Call {
            canonical: "scanf".into(),
            description: "scanf() — formatted stdin input".into(),
        },
        NodeMatcher::Call {
            canonical: "fscanf".into(),
            description: "fscanf() — formatted file input".into(),
        },
        NodeMatcher::Call {
            canonical: "getenv".into(),
            description: "getenv() — environment variable".into(),
        },
        // `argv` parameter -- main(int argc, char **argv)
        NodeMatcher::ParamName {
            names: vec!["argv".into()],
            description: "argv — command-line arguments".into(),
        },
    ]
}

// -- Rule specs --------------------------------------------------------------

fn format_string_spec() -> TaintSpec {
    TaintSpec {
        sources: c_taint_sources(),
        sinks: vec![
            NodeMatcher::Call {
                canonical: "printf".into(),
                description: "printf() with tainted format string".into(),
            },
            NodeMatcher::Call {
                canonical: "fprintf".into(),
                description: "fprintf() with tainted format string".into(),
            },
            // NOTE: sprintf()/snprintf() are intentionally NOT
            // format-string sinks (T15). sprintf() doubles as a
            // buffer-writing call (it propagates taint into its
            // destination buffer for the buffer-overflow / SQL-injection
            // rules); treating it as a format-string sink as well caused
            // a tainted format to both fire here and re-trigger
            // downstream off the destination buffer. snprintf() is
            // additionally bounds-safe (truncates to its size argument),
            // so a tainted format there does not warrant a Critical
            // finding. Real format-string vulnerabilities still surface
            // through printf()/fprintf()/syslog().
            NodeMatcher::Call {
                canonical: "syslog".into(),
                description: "syslog() with tainted format string".into(),
            },
        ],
        sanitizers: vec![],
    }
}

fn command_injection_spec() -> TaintSpec {
    TaintSpec {
        sources: c_taint_sources(),
        sinks: vec![
            NodeMatcher::Call {
                canonical: "system".into(),
                description: "system() with tainted argument".into(),
            },
            NodeMatcher::Call {
                canonical: "popen".into(),
                description: "popen() with tainted argument".into(),
            },
            NodeMatcher::Call {
                canonical: "execl".into(),
                description: "execl() with tainted argument".into(),
            },
            NodeMatcher::Call {
                canonical: "execlp".into(),
                description: "execlp() with tainted argument".into(),
            },
            NodeMatcher::Call {
                canonical: "execle".into(),
                description: "execle() with tainted argument".into(),
            },
            NodeMatcher::Call {
                canonical: "execv".into(),
                description: "execv() with tainted argument".into(),
            },
            NodeMatcher::Call {
                canonical: "execvp".into(),
                description: "execvp() with tainted argument".into(),
            },
            NodeMatcher::Call {
                canonical: "execve".into(),
                description: "execve() with tainted argument".into(),
            },
        ],
        sanitizers: vec![],
    }
}

fn buffer_overflow_spec() -> TaintSpec {
    TaintSpec {
        sources: c_taint_sources(),
        sinks: vec![
            NodeMatcher::Call {
                canonical: "strcpy".into(),
                description: "strcpy() with tainted source — use strlcpy or strncpy".into(),
            },
            NodeMatcher::Call {
                canonical: "strcat".into(),
                description: "strcat() with tainted source — use strlcat or strncat".into(),
            },
            NodeMatcher::Call {
                canonical: "memcpy".into(),
                description: "memcpy() with tainted argument".into(),
            },
            NodeMatcher::Call {
                canonical: "memmove".into(),
                description: "memmove() with tainted argument".into(),
            },
            NodeMatcher::Call {
                canonical: "gets".into(),
                description: "gets() — always a buffer overflow risk".into(),
            },
        ],
        sanitizers: vec![
            NodeMatcher::Call {
                canonical: "strlcpy".into(),
                description: "strlcpy() — bounds-checked copy".into(),
            },
            NodeMatcher::Call {
                canonical: "strlcat".into(),
                description: "strlcat() — bounds-checked concatenation".into(),
            },
            NodeMatcher::Call {
                canonical: "strncpy".into(),
                description: "strncpy() — length-limited copy".into(),
            },
            NodeMatcher::Call {
                canonical: "strncat".into(),
                description: "strncat() — length-limited concatenation".into(),
            },
            NodeMatcher::Call {
                canonical: "snprintf".into(),
                description: "snprintf() — bounds-checked format".into(),
            },
        ],
    }
}

fn sql_injection_spec() -> TaintSpec {
    TaintSpec {
        sources: c_taint_sources(),
        sinks: vec![
            NodeMatcher::Call {
                canonical: "sqlite3_exec".into(),
                description: "sqlite3_exec() with tainted query".into(),
            },
            NodeMatcher::Call {
                canonical: "mysql_query".into(),
                description: "mysql_query() with tainted query".into(),
            },
            NodeMatcher::Call {
                canonical: "mysql_real_query".into(),
                description: "mysql_real_query() with tainted query".into(),
            },
            NodeMatcher::Call {
                canonical: "PQexec".into(),
                description: "PQexec() with tainted query".into(),
            },
        ],
        sanitizers: vec![
            // Parameterized query APIs act as sanitizers for the SQL
            // injection rule because they separate data from query
            // structure.
            NodeMatcher::Call {
                canonical: "sqlite3_prepare_v2".into(),
                description: "sqlite3_prepare_v2() — parameterized query".into(),
            },
            NodeMatcher::Call {
                canonical: "mysql_stmt_prepare".into(),
                description: "mysql_stmt_prepare() — parameterized query".into(),
            },
            NodeMatcher::Call {
                canonical: "PQexecParams".into(),
                description: "PQexecParams() — parameterized query".into(),
            },
        ],
    }
}

// -- Internals ---------------------------------------------------------------

/// Describes a taint source matched inside a function body.
struct TaintSource {
    var_name: Option<String>,
    description: String,
    line: usize,
}

/// Describes a taint sink match.
struct TaintSink {
    start_byte: usize,
    end_byte: usize,
    description: String,
}

fn analyze_scope(
    scope_node: Node<'_>,
    source: &str,
    spec: &TaintSpec,
    out: &mut Vec<TaintFinding>,
) {
    let body = scope_node.child_by_field_name("body").unwrap_or(scope_node);

    // Collect sources from the body (call expressions that are sources)
    // and from the function's parameter list (argv).
    let mut sources = collect_body_sources(body, source, spec);
    collect_param_sources(scope_node, source, spec, &mut sources);

    if sources.is_empty() {
        return;
    }

    let tainted = build_tainted_set(body, source, &sources, spec);
    if tainted.is_empty() {
        return;
    }

    let sinks = find_sinks(body, source, spec, &tainted);
    if sinks.is_empty() {
        return;
    }

    let (source_desc, source_line) = sources
        .first()
        .map(|s| (s.description.clone(), s.line))
        .unwrap_or_else(|| ("user input".to_string(), 0));

    for sink in sinks {
        let start = byte_to_position(source, sink.start_byte);
        let end = byte_to_position(source, sink.end_byte);
        out.push(TaintFinding {
            sink_start_byte: sink.start_byte,
            sink_end_byte: sink.end_byte,
            sink_line: start.0,
            sink_column: start.1,
            sink_end_line: end.0,
            sink_end_column: end.1,
            source_description: source_desc.clone(),
            sink_description: sink.description,
            source_line,
            source_range: None,
            rule_id_hint: None,
            hops: 0,
        });
    }
}

/// Walk the function body and collect taint sources: call expressions
/// whose callee matches one of the spec's `Call` sources, where the
/// result is assigned to a variable.
fn collect_body_sources(scope: Node<'_>, source: &str, spec: &TaintSpec) -> Vec<TaintSource> {
    let mut sources = Vec::new();
    walk_tree(scope, source, &mut |n, s| {
        // `type var = source_call(...);` -- declaration
        if n.kind() == "declaration" {
            if let Some((var_name, init_node)) = extract_declarator_init(n, s) {
                if let Some(desc) = classify_source_expr(init_node, s, spec) {
                    sources.push(TaintSource {
                        var_name: Some(var_name),
                        description: desc,
                        line: n.start_position().row + 1,
                    });
                }
            }
        }
        // `var = source_call(...);` -- expression_statement with assignment
        if n.kind() == "expression_statement" {
            if let Some(expr) = n.child(0) {
                if expr.kind() == "assignment_expression" {
                    if let (Some(left), Some(right)) = (
                        expr.child_by_field_name("left"),
                        expr.child_by_field_name("right"),
                    ) {
                        if left.kind() == "identifier" {
                            let var_name = &s[left.byte_range()];
                            if let Some(desc) = classify_source_expr(right, s, spec) {
                                sources.push(TaintSource {
                                    var_name: Some(var_name.to_string()),
                                    description: desc,
                                    line: n.start_position().row + 1,
                                });
                            }
                        }
                    }
                }
            }
        }
        // Bare call as a statement: `read(fd, buf, sizeof(buf));`
        // Here, for read/recv/fgets/scanf, the *buffer* parameter is the tainted one.
        if n.kind() == "call_expression" {
            if let Some(callee) = call_function_name(n, s) {
                let buf_param_callee = matches!(
                    callee,
                    "read" | "recv" | "recvfrom" | "recvmsg" | "fgets" | "fread"
                );
                let scan_callee = matches!(callee, "scanf" | "fscanf");
                if buf_param_callee || scan_callee {
                    if let Some(args) = n.child_by_field_name("arguments") {
                        let arg_names = collect_arg_identifiers(args, s);
                        // For read/recv: second argument is the buffer
                        // For fgets: first argument is the buffer
                        // For scanf/fscanf: arguments after the format string
                        let target_args = if matches!(callee, "fgets") {
                            arg_names.first().cloned().into_iter().collect::<Vec<_>>()
                        } else if matches!(callee, "read" | "recv" | "recvfrom" | "recvmsg") {
                            arg_names.get(1).cloned().into_iter().collect::<Vec<_>>()
                        } else if matches!(callee, "fread") {
                            arg_names.first().cloned().into_iter().collect::<Vec<_>>()
                        } else if scan_callee {
                            // All args after the format string
                            let start = if callee == "fscanf" { 2 } else { 1 };
                            arg_names.get(start..).unwrap_or_default().to_vec()
                        } else {
                            vec![]
                        };
                        let desc_text = spec
                            .sources
                            .iter()
                            .find_map(|m| {
                                if let NodeMatcher::Call {
                                    canonical,
                                    description,
                                } = m
                                {
                                    if canonical == callee {
                                        return Some(description.clone());
                                    }
                                }
                                None
                            })
                            .unwrap_or_else(|| format!("{}()", callee));
                        for arg_name in target_args {
                            sources.push(TaintSource {
                                var_name: Some(arg_name),
                                description: desc_text.clone(),
                                line: n.start_position().row + 1,
                            });
                        }
                    }
                }
            }
        }
    });
    sources
}

/// Classify an expression node as a taint source if it matches a
/// `Call` source in the spec. Returns the source description.
fn classify_source_expr(node: Node<'_>, src: &str, spec: &TaintSpec) -> Option<String> {
    if node.kind() == "call_expression" {
        let callee = call_function_name(node, src)?;
        for matcher in &spec.sources {
            if let NodeMatcher::Call {
                canonical,
                description,
            } = matcher
            {
                if callee == canonical.as_str() {
                    return Some(description.clone());
                }
            }
        }
    }
    // Subscript on argv: `argv[1]`
    if node.kind() == "subscript_expression" {
        if let Some(arg) = node.child_by_field_name("argument") {
            let text = &src[arg.byte_range()];
            if text == "argv" {
                return Some("argv — command-line arguments".to_string());
            }
        }
    }
    None
}

/// Collect parameter taint sources. Matches `argv` parameter names and
/// any other `ParamName` matchers in the spec.
fn collect_param_sources(
    func_node: Node<'_>,
    source: &str,
    spec: &TaintSpec,
    out: &mut Vec<TaintSource>,
) {
    let Some(declarator) = func_node.child_by_field_name("declarator") else {
        return;
    };
    // The declarator is a `function_declarator` containing a `parameter_list`.
    let Some(params) = declarator.child_by_field_name("parameters") else {
        return;
    };

    let mut cursor = params.walk();
    for child in params.children(&mut cursor) {
        if child.kind() != "parameter_declaration" {
            continue;
        }
        // The parameter declarator may be an identifier or a pointer_declarator.
        let param_name = extract_param_name(child, source);
        if let Some(name) = param_name {
            for matcher in &spec.sources {
                if let NodeMatcher::ParamName { names, description } = matcher {
                    if names.iter().any(|n| n == &name)
                        || crate::rules::taint_engine::param_names_are_wildcard(names)
                    {
                        out.push(TaintSource {
                            var_name: Some(name.clone()),
                            description: description.clone(),
                            line: child.start_position().row + 1,
                        });
                        break;
                    }
                }
            }
        }
    }
}

/// Extract the parameter name from a `parameter_declaration`.
/// Handles both `int x` and `char **argv` (pointer declarator chains).
fn extract_param_name(param: Node<'_>, source: &str) -> Option<String> {
    let decl = param.child_by_field_name("declarator")?;
    Some(innermost_identifier(decl, source)?.to_string())
}

/// Drill into pointer_declarator / array_declarator chains to find the
/// innermost identifier.
fn innermost_identifier<'a>(mut node: Node<'_>, source: &'a str) -> Option<&'a str> {
    loop {
        match node.kind() {
            "identifier" => return Some(&source[node.byte_range()]),
            "pointer_declarator" | "array_declarator" | "parenthesized_declarator" => {
                node = node.child_by_field_name("declarator")?;
            }
            _ => return None,
        }
    }
}

/// Build the tainted set by transitively propagating taint through
/// declarations and assignments. Two passes to handle chained
/// assignments like `char *a = source; char *b = a; f(b);`.
fn build_tainted_set(
    scope: Node<'_>,
    source: &str,
    sources: &[TaintSource],
    spec: &TaintSpec,
) -> HashSet<String> {
    let mut tainted: HashSet<String> = HashSet::new();
    for s in sources {
        if let Some(ref name) = s.var_name {
            tainted.insert(name.clone());
        }
    }
    if tainted.is_empty() {
        return tainted;
    }

    for _ in 0..2 {
        walk_tree(scope, source, &mut |n, s| {
            // Declaration: `type var = expr;`
            if n.kind() == "declaration" {
                if let Some((var_name, init_node)) = extract_declarator_init(n, s) {
                    if !tainted.contains(&var_name)
                        && expr_uses_tainted(init_node, s, &tainted, spec)
                    {
                        tainted.insert(var_name);
                    }
                }
            }
            // Assignment expression: `var = expr;`
            if n.kind() == "expression_statement" {
                if let Some(expr) = n.child(0) {
                    if expr.kind() == "assignment_expression" {
                        if let (Some(left), Some(right)) = (
                            expr.child_by_field_name("left"),
                            expr.child_by_field_name("right"),
                        ) {
                            if left.kind() == "identifier" {
                                let left_text = s[left.byte_range()].to_string();
                                if !tainted.contains(&left_text)
                                    && expr_uses_tainted(right, s, &tainted, spec)
                                {
                                    tainted.insert(left_text);
                                }
                            }
                        }
                    }
                }
            }
            // Buffer-writing calls: `sprintf(dest, fmt, tainted)`,
            // `strcpy(dest, tainted)`, `memcpy(dest, tainted, n)`, etc.
            // If any non-destination argument is tainted, the destination
            // buffer name becomes tainted. Sanitizer calls are excluded:
            // `strncpy`/`strlcpy`/etc. are safe-copy functions that
            // collapse taint rather than propagating it.
            if n.kind() == "call_expression" {
                if let Some(callee) = call_function_name(n, s) {
                    let is_sanitizer = spec.sanitizers.iter().any(|san| {
                        if let NodeMatcher::Call { canonical, .. } = san {
                            callee == canonical.as_str()
                        } else {
                            false
                        }
                    });
                    if is_buffer_writing_call(callee) && !is_sanitizer {
                        if let Some(args) = n.child_by_field_name("arguments") {
                            // T15: for sprintf/snprintf only propagate the
                            // *data* arguments into the destination buffer
                            // when the format string is a literal. A
                            // tainted format string is a format-string
                            // concern, not a clean data-into-buffer flow,
                            // and propagating it would let it re-trigger
                            // downstream off the destination buffer.
                            if matches!(callee, "sprintf" | "snprintf")
                                && !printf_like_format_is_literal(callee, args)
                            {
                                return;
                            }
                            let arg_names = collect_arg_identifiers(args, s);
                            // The first argument is the destination buffer.
                            if let Some(dest_name) = arg_names.first() {
                                if !dest_name.is_empty() && !tainted.contains(dest_name) {
                                    // Check if any argument after the destination is tainted.
                                    let non_dest_tainted = arg_names
                                        .iter()
                                        .skip(1)
                                        .any(|name| !name.is_empty() && tainted.contains(name));
                                    if non_dest_tainted {
                                        tainted.insert(dest_name.clone());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
    }
    tainted
}

/// Recursively check whether `node` references any tainted variable
/// or is itself a taint source expression. Also handles string concat
/// via `strcat`/`sprintf` wrapping patterns, and passes through
/// non-sanitizer call wrappers.
fn expr_uses_tainted(
    node: Node<'_>,
    src: &str,
    tainted: &HashSet<String>,
    spec: &TaintSpec,
) -> bool {
    if node.kind() == "identifier" {
        let name = &src[node.byte_range()];
        return tainted.contains(name);
    }
    // `argv[N]` subscript
    if node.kind() == "subscript_expression" {
        if let Some(arg) = node.child_by_field_name("argument") {
            let text = &src[arg.byte_range()];
            if tainted.contains(text) {
                return true;
            }
        }
    }
    // String literal with embedded tainted variable (rare in C, but
    // handle concatenation operators).
    if node.kind() == "concatenated_string" {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if expr_uses_tainted(child, src, tainted, spec) {
                return true;
            }
        }
        return false;
    }
    // Call expression: if it's a sanitizer, stop propagation.
    if node.kind() == "call_expression" {
        if let Some(callee) = call_function_name(node, src) {
            for san in &spec.sanitizers {
                if let NodeMatcher::Call { canonical, .. } = san {
                    if callee == canonical.as_str() {
                        return false;
                    }
                }
            }
        }
        // Non-sanitizer call: if any argument is tainted, the result is.
        if let Some(args) = node.child_by_field_name("arguments") {
            let mut cursor = args.walk();
            for child in args.named_children(&mut cursor) {
                if expr_uses_tainted(child, src, tainted, spec) {
                    return true;
                }
            }
        }
        return false;
    }
    // Binary expression (e.g., pointer arithmetic, though string concat
    // in C usually happens through function calls).
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if expr_uses_tainted(child, src, tainted, spec) {
            return true;
        }
    }
    false
}

/// Walk `scope` and emit a sink for every call expression whose callee
/// matches the spec's sink list AND whose arguments reference a tainted
/// variable.
///
/// For format-string sinks (`printf`, `fprintf`, `sprintf`, `snprintf`,
/// `syslog`), only the *format argument* is checked (the first
/// non-file-descriptor argument). If the format argument is a string
/// literal, the call is safe even if later arguments are tainted.
fn find_sinks(
    scope: Node<'_>,
    source: &str,
    spec: &TaintSpec,
    tainted: &HashSet<String>,
) -> Vec<TaintSink> {
    let mut sinks = Vec::new();
    walk_tree(scope, source, &mut |n, s| {
        if n.kind() != "call_expression" {
            return;
        }
        let Some(callee) = call_function_name(n, s) else {
            return;
        };
        let Some(args) = n.child_by_field_name("arguments") else {
            return;
        };

        for matcher in &spec.sinks {
            if let NodeMatcher::Call {
                canonical,
                description,
            } = matcher
            {
                if callee != canonical.as_str() {
                    continue;
                }

                // Format-string sinks: only flag when the FORMAT arg is tainted
                if is_format_string_sink(callee) {
                    let fmt_idx = format_arg_index(callee);
                    let mut cursor = args.walk();
                    let arg_nodes: Vec<Node<'_>> = args.named_children(&mut cursor).collect();
                    if let Some(fmt_arg) = arg_nodes.get(fmt_idx) {
                        // If the format argument is a string literal, it's safe.
                        if fmt_arg.kind() == "string_literal" {
                            continue;
                        }
                        if expr_uses_tainted_simple(*fmt_arg, s, tainted) {
                            sinks.push(TaintSink {
                                start_byte: n.start_byte(),
                                end_byte: n.end_byte(),
                                description: description.clone(),
                            });
                        }
                    }
                } else if is_exec_call(callee) {
                    // T13: exec*() command injection — only the *pathname*
                    // (first argument) controls which program runs. A
                    // tainted data argument (argv[N] passed to the child)
                    // is not command injection, so only flag when the
                    // first argument is tainted.
                    let mut cursor = args.walk();
                    let arg_nodes: Vec<Node<'_>> = args.named_children(&mut cursor).collect();
                    if let Some(path_arg) = arg_nodes.first() {
                        if expr_uses_tainted_simple(*path_arg, s, tainted) {
                            sinks.push(TaintSink {
                                start_byte: n.start_byte(),
                                end_byte: n.end_byte(),
                                description: description.clone(),
                            });
                        }
                    }
                } else if is_sized_buffer_call(callee) {
                    // T14: memcpy/memmove — a constant or sizeof() size
                    // argument means the copy is bounded and not a
                    // buffer overflow, even if src/dest are tainted.
                    // Suppress unless the size argument is itself tainted
                    // or a non-constant (dynamic) expression.
                    let mut cursor = args.walk();
                    let arg_nodes: Vec<Node<'_>> = args.named_children(&mut cursor).collect();
                    // A numeric literal, `sizeof(...)`, or constant
                    // arithmetic evaluates to a compile-time constant
                    // regardless of any tainted buffer it textually names
                    // (e.g. `sizeof(buf)`), so it bounds the copy. A
                    // tainted length is an `identifier`/dynamic expression,
                    // which `is_constant_size_expr` rejects.
                    let size_constant = arg_nodes
                        .get(2)
                        .map(|size_arg| is_constant_size_expr(*size_arg, s))
                        .unwrap_or(false);
                    if !size_constant && expr_uses_tainted_simple(args, s, tainted) {
                        sinks.push(TaintSink {
                            start_byte: n.start_byte(),
                            end_byte: n.end_byte(),
                            description: description.clone(),
                        });
                    }
                } else {
                    // General sinks: any tainted argument triggers.
                    if expr_uses_tainted_simple(args, s, tainted) {
                        sinks.push(TaintSink {
                            start_byte: n.start_byte(),
                            end_byte: n.end_byte(),
                            description: description.clone(),
                        });
                    }
                }
                return;
            }
        }
    });
    sinks
}

/// Simplified taint check that only looks at identifier references
/// (no sanitizer awareness). Used in sink detection where we've
/// already propagated taint with sanitizer handling.
fn expr_uses_tainted_simple(node: Node<'_>, src: &str, tainted: &HashSet<String>) -> bool {
    if node.kind() == "identifier" {
        let name = &src[node.byte_range()];
        return tainted.contains(name);
    }
    if node.kind() == "subscript_expression" {
        if let Some(arg) = node.child_by_field_name("argument") {
            let text = &src[arg.byte_range()];
            if tainted.contains(text) {
                return true;
            }
        }
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if expr_uses_tainted_simple(child, src, tainted) {
            return true;
        }
    }
    false
}

/// Whether a callee is a format-string function where only the format
/// argument should be checked (not arbitrary arguments).
///
/// `sprintf`/`snprintf` are intentionally excluded (T15): see the note in
/// [`format_string_spec`].
fn is_format_string_sink(callee: &str) -> bool {
    matches!(callee, "printf" | "fprintf" | "syslog")
}

/// Whether a callee is an `exec*` family call where command injection is
/// only meaningful when the pathname (first argument) is tainted (T13).
fn is_exec_call(callee: &str) -> bool {
    matches!(
        callee,
        "execl" | "execlp" | "execle" | "execv" | "execvp" | "execve"
    )
}

/// Whether a callee is a fixed-size buffer copy whose third argument is
/// the byte count (T14).
fn is_sized_buffer_call(callee: &str) -> bool {
    matches!(callee, "memcpy" | "memmove")
}

/// Whether the format argument of a `sprintf`/`snprintf` call is a string
/// literal. For `sprintf(dest, fmt, ...)` the format is arg index 1; for
/// `snprintf(dest, size, fmt, ...)` it is arg index 2.
fn printf_like_format_is_literal(callee: &str, args: Node<'_>) -> bool {
    let fmt_idx = match callee {
        "snprintf" => 2,
        _ => 1,
    };
    let mut cursor = args.walk();
    let arg_nodes: Vec<Node<'_>> = args.named_children(&mut cursor).collect();
    arg_nodes
        .get(fmt_idx)
        .map(|fmt| fmt.kind() == "string_literal")
        .unwrap_or(false)
}

/// Whether a size-argument expression is a compile-time constant: a
/// numeric literal or a `sizeof(...)` expression (possibly combined with
/// constant arithmetic, e.g. `sizeof(buf) - 1`). Such bounds make the
/// copy safe regardless of source taint.
#[allow(clippy::only_used_in_recursion)]
fn is_constant_size_expr(node: Node<'_>, src: &str) -> bool {
    match node.kind() {
        "number_literal" => true,
        // `sizeof buf` / `sizeof(buf)`
        "sizeof_expression" => true,
        // Parenthesised: `(sizeof(buf) - 1)`
        "parenthesized_expression" => node
            .named_child(0)
            .map(|c| is_constant_size_expr(c, src))
            .unwrap_or(false),
        // Constant arithmetic: both operands must be constant.
        "binary_expression" => {
            let left = node.child_by_field_name("left");
            let right = node.child_by_field_name("right");
            match (left, right) {
                (Some(l), Some(r)) => {
                    is_constant_size_expr(l, src) && is_constant_size_expr(r, src)
                }
                _ => false,
            }
        }
        // Unary on a constant (e.g. `-1`).
        "unary_expression" => node
            .named_child(0)
            .map(|c| is_constant_size_expr(c, src))
            .unwrap_or(false),
        _ => false,
    }
}

/// Index of the format argument for format-string sinks.
/// - `printf(fmt, ...)` -> 0
/// - `fprintf(stream, fmt, ...)` -> 1
/// - `sprintf(buf, fmt, ...)` -> 1
/// - `snprintf(buf, size, fmt, ...)` -> 2
/// - `syslog(priority, fmt, ...)` -> 1
fn format_arg_index(callee: &str) -> usize {
    match callee {
        "printf" => 0,
        "fprintf" | "sprintf" | "syslog" => 1,
        "snprintf" => 2,
        _ => 0,
    }
}

/// Whether a call writes into its first argument (destination buffer).
/// Used by `build_tainted_set` to propagate taint through calls like
/// `sprintf(dest, fmt, tainted)`.
fn is_buffer_writing_call(callee: &str) -> bool {
    matches!(
        callee,
        "sprintf"
            | "snprintf"
            | "strcpy"
            | "strncpy"
            | "strcat"
            | "strncat"
            | "strlcpy"
            | "strlcat"
            | "memcpy"
            | "memmove"
    )
}

// -- C AST helpers -----------------------------------------------------------

/// Extract the callee name from a `call_expression`. Only handles bare
/// identifier callees (no function pointers or member access).
fn call_function_name<'a>(node: Node<'a>, src: &'a str) -> Option<&'a str> {
    if node.kind() != "call_expression" {
        return None;
    }
    let func = node.child_by_field_name("function")?;
    if func.kind() == "identifier" {
        return Some(&src[func.byte_range()]);
    }
    None
}

/// Collect identifier names from an argument list.
fn collect_arg_identifiers(args: Node<'_>, src: &str) -> Vec<String> {
    let mut names = Vec::new();
    let mut cursor = args.walk();
    for child in args.named_children(&mut cursor) {
        if child.kind() == "identifier" {
            names.push(src[child.byte_range()].to_string());
        } else if child.kind() == "pointer_expression" || child.kind() == "cast_expression" {
            // `&buf` or `(char *)buf` — drill into the operand
            if let Some(inner) = find_innermost_identifier(child, src) {
                names.push(inner.to_string());
            }
        } else {
            // Push an empty placeholder to keep positional indexing correct.
            names.push(String::new());
        }
    }
    names
}

/// Find the innermost identifier in a unary/cast expression chain.
fn find_innermost_identifier<'a>(node: Node<'_>, src: &'a str) -> Option<&'a str> {
    if node.kind() == "identifier" {
        return Some(&src[node.byte_range()]);
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if let Some(id) = find_innermost_identifier(child, src) {
            return Some(id);
        }
    }
    None
}

/// Extract `(var_name, init_expression_node)` from a `declaration` node.
/// Handles `type *var = expr;` patterns.
fn extract_declarator_init<'a>(decl: Node<'a>, src: &'a str) -> Option<(String, Node<'a>)> {
    let mut cursor = decl.walk();
    for child in decl.children(&mut cursor) {
        if child.kind() == "init_declarator" {
            let declarator = child.child_by_field_name("declarator")?;
            let value = child.child_by_field_name("value")?;
            let name = innermost_identifier(declarator, src)?;
            return Some((name.to_string(), value));
        }
    }
    None
}

/// Convert a byte offset into the source to a `(line, column)` pair.
fn byte_to_position(source: &str, byte: usize) -> (usize, usize) {
    let byte = byte.min(source.len());
    let line = source[..byte].bytes().filter(|b| *b == b'\n').count() + 1;
    let line_start = source[..byte].rfind('\n').map_or(0, |idx| idx + 1);
    let column = source[line_start..byte].chars().count() + 1;
    (line, column)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::parser::parse_file;
    use crate::Language;

    fn analyze(src: &str, spec: &TaintSpec) -> Vec<TaintFinding> {
        let tree = parse_file(src, Language::C).expect("parse");
        analyze_tree(tree.root_node(), src, spec, None)
    }

    #[test]
    fn format_string_via_getenv() {
        let src = r#"
#include <stdio.h>
#include <stdlib.h>

void handler() {
    char *input = getenv("USER_INPUT");
    printf(input);
}
"#;
        let findings = analyze(src, &format_string_spec());
        assert!(
            !findings.is_empty(),
            "should detect printf with tainted format string: {:?}",
            findings
        );
    }

    #[test]
    fn format_string_safe_literal() {
        let src = r#"
#include <stdio.h>
#include <stdlib.h>

void handler() {
    char *input = getenv("USER_INPUT");
    printf("%s", input);
}
"#;
        let findings = analyze(src, &format_string_spec());
        assert!(
            findings.is_empty(),
            "printf with literal format string should be safe: {:?}",
            findings
        );
    }

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

void handler() {
    char *cmd = getenv("CMD");
    system(cmd);
}
"#;
        let findings = analyze(src, &command_injection_spec());
        assert!(
            !findings.is_empty(),
            "should detect system() with tainted argument: {:?}",
            findings
        );
    }

    #[test]
    fn buffer_overflow_via_strcpy() {
        let src = r#"
#include <string.h>
#include <stdio.h>

void handler() {
    char buf[256];
    char dest[64];
    fgets(buf, sizeof(buf), stdin);
    strcpy(dest, buf);
}
"#;
        let findings = analyze(src, &buffer_overflow_spec());
        assert!(
            !findings.is_empty(),
            "should detect strcpy with tainted source: {:?}",
            findings
        );
    }

    #[test]
    fn buffer_overflow_sanitized_by_strncpy() {
        let src = r#"
#include <string.h>
#include <stdio.h>

void handler() {
    char buf[256];
    char dest[64];
    fgets(buf, sizeof(buf), stdin);
    char *safe = strncpy(dest, buf, sizeof(dest) - 1);
    strcpy(dest, safe);
}
"#;
        let findings = analyze(src, &buffer_overflow_spec());
        assert!(
            findings.is_empty(),
            "strncpy should sanitize the taint: {:?}",
            findings
        );
    }

    #[test]
    fn sql_injection_via_sprintf() {
        let src = r#"
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>

void handler(sqlite3 *db) {
    char *input = getenv("QUERY");
    char query[512];
    sprintf(query, "SELECT * FROM users WHERE name = '%s'", input);
    sqlite3_exec(db, query, NULL, NULL, NULL);
}
"#;
        let findings = analyze(src, &sql_injection_spec());
        assert!(
            !findings.is_empty(),
            "should detect sqlite3_exec with tainted query: {:?}",
            findings
        );
    }

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

int main(int argc, char **argv) {
    system(argv[1]);
}
"#;
        let findings = analyze(src, &command_injection_spec());
        assert!(
            !findings.is_empty(),
            "should detect system() with argv: {:?}",
            findings
        );
    }

    #[test]
    fn recv_to_execv() {
        let src = r#"
#include <unistd.h>
#include <sys/socket.h>

void handler(int sockfd) {
    char buf[1024];
    recv(sockfd, buf, sizeof(buf), 0);
    execv(buf, NULL);
}
"#;
        let findings = analyze(src, &command_injection_spec());
        assert!(
            !findings.is_empty(),
            "should detect execv() with socket data: {:?}",
            findings
        );
    }

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

void handler() {
    system("ls -la");
}
"#;
        let findings = analyze(src, &command_injection_spec());
        assert!(
            findings.is_empty(),
            "literal command should not trigger taint: {:?}",
            findings
        );
    }

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

void handler() {
    char *input = getenv("CMD");
    char *cmd = input;
    system(cmd);
}
"#;
        let findings = analyze(src, &command_injection_spec());
        assert!(
            !findings.is_empty(),
            "should detect transitive taint: {:?}",
            findings
        );
    }

    // -- T13: exec* command injection is path-argument-driven ---------------

    #[test]
    fn execv_literal_path_tainted_arg_is_safe() {
        let src = r#"
#include <unistd.h>
#include <stdlib.h>

void handler() {
    char *arg = getenv("ARG");
    char *argv[] = {"cat", arg, NULL};
    execv("/bin/cat", argv);
}
"#;
        let findings = analyze(src, &command_injection_spec());
        assert!(
            findings.is_empty(),
            "execv with a literal path is safe even with a tainted data arg: {:?}",
            findings
        );
    }

    #[test]
    fn execl_tainted_path_still_flags() {
        let src = r#"
#include <unistd.h>
#include <stdlib.h>

void handler() {
    char *path = getenv("PATH_INPUT");
    execl(path, "x", NULL);
}
"#;
        let findings = analyze(src, &command_injection_spec());
        assert!(
            !findings.is_empty(),
            "execl with a tainted pathname must still flag: {:?}",
            findings
        );
    }

    // -- T14: memcpy with a constant/sizeof size is bounded -----------------

    #[test]
    fn memcpy_literal_size_is_safe() {
        let src = r#"
#include <string.h>
#include <stdlib.h>

void handler() {
    char *src = getenv("DATA");
    char buf[64];
    memcpy(buf, src, 64);
}
"#;
        let findings = analyze(src, &buffer_overflow_spec());
        assert!(
            findings.is_empty(),
            "memcpy with a constant size should not flag: {:?}",
            findings
        );
    }

    #[test]
    fn memcpy_sizeof_size_is_safe() {
        let src = r#"
#include <string.h>
#include <stdlib.h>

void handler() {
    char *src = getenv("DATA");
    char buf[64];
    memcpy(buf, src, sizeof(buf));
}
"#;
        let findings = analyze(src, &buffer_overflow_spec());
        assert!(
            findings.is_empty(),
            "memcpy with a sizeof() size should not flag: {:?}",
            findings
        );
    }

    #[test]
    fn memcpy_tainted_size_still_flags() {
        let src = r#"
#include <string.h>
#include <stdlib.h>

void handler() {
    char *input = getenv("DATA");
    char dest[64];
    memcpy(dest, input, strlen(input));
}
"#;
        let findings = analyze(src, &buffer_overflow_spec());
        assert!(
            !findings.is_empty(),
            "memcpy with a tainted/dynamic length must still flag: {:?}",
            findings
        );
    }

    // -- T15: sprintf/snprintf format-string collision ----------------------

    #[test]
    fn sprintf_untrusted_format_no_double_fire() {
        let src = r#"
#include <stdio.h>
#include <stdlib.h>

void handler() {
    char *fmt = getenv("FMT");
    char dest[64];
    sprintf(dest, fmt, "x");
    printf("%s", dest);
}
"#;
        let findings = analyze(src, &format_string_spec());
        assert!(
            findings.is_empty(),
            "tainted sprintf format must not re-fire via the dest buffer: {:?}",
            findings
        );
    }

    #[test]
    fn snprintf_untrusted_format_not_flagged() {
        let src = r#"
#include <stdio.h>
#include <stdlib.h>

void handler() {
    char *fmt = getenv("FMT");
    char buf[64];
    snprintf(buf, sizeof(buf), fmt, "x");
}
"#;
        let findings = analyze(src, &format_string_spec());
        assert!(
            findings.is_empty(),
            "snprintf is bounds-safe and not a format-string sink: {:?}",
            findings
        );
    }

    #[test]
    fn printf_tainted_format_still_flags() {
        let src = r#"
#include <stdio.h>
#include <stdlib.h>

void handler() {
    char *fmt = getenv("FMT");
    printf(fmt);
}
"#;
        let findings = analyze(src, &format_string_spec());
        assert!(
            !findings.is_empty(),
            "printf with a tainted format must still flag: {:?}",
            findings
        );
    }

    #[test]
    fn scanf_to_system() {
        let src = r#"
#include <stdio.h>
#include <stdlib.h>

void handler() {
    char buf[256];
    scanf("%s", buf);
    system(buf);
}
"#;
        let findings = analyze(src, &command_injection_spec());
        assert!(
            !findings.is_empty(),
            "should detect scanf input flowing to system(): {:?}",
            findings
        );
    }
}