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
pub mod apex;
pub mod apex_taint;
pub mod bash;
pub mod bash_taint;
pub mod c;
pub mod c_taint;
pub mod common;
pub mod config;
pub mod cross_file;
pub mod csharp;
pub mod csharp_taint;
pub mod generic_mode;
pub mod go;
pub mod go_taint;
pub mod java;
pub mod java_taint;
pub mod javascript;
pub mod javascript_taint;
pub mod kotlin;
pub mod kotlin_taint;
pub mod manifest;
pub mod php;
pub mod php_taint;
pub mod pq;
pub mod python;
pub mod python_aliases;
pub mod python_taint;
pub mod ruby;
pub mod ruby_taint;
pub mod rust_lang;
pub mod scala;
pub mod scala_taint;
pub mod semgrep_compat;
pub mod semgrep_taint;
pub mod solidity;
pub mod solidity_taint;
pub mod swift;
pub mod swift_taint;
pub mod taint_engine;

use crate::{Finding, Language, Severity};
use std::path::Path;

/// YAML rule packs that ship inside the `foxguard` binary.
///
/// These are loaded by [`RuleRegistry::new`] on the same footing as the
/// hand-written Rust rules: no CLI flag required. The `queries/` subtrees
/// hold CodeQL `.ql` files and pack lockfiles that have nothing to do with
/// Semgrep matching, so they are skipped at load time (see
/// `walk_embedded_dir` in `semgrep_compat.rs`).
///
/// See `rules/README.md` for the on-disk layout.
static BUNDLED_RULES: include_dir::Dir<'_> = include_dir::include_dir!("$CARGO_MANIFEST_DIR/rules");

/// Languages with built-in taint specs wired into the scanner.
///
/// Taint support is intentionally narrower than syntax-only AST rules: each
/// language here has source/sink specs plus scanner dispatch in
/// `builtin_taint_specs_for_language` and `engine/scanner.rs`. When adding a
/// new taint-backed language, start with `docs/taint-tracking.md` so the
/// engine choice, source model, and sanitizer behavior stay consistent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaintEngine {
    Apex,
    Bash,
    C,
    CSharp,
    Go,
    Java,
    JavaScript,
    Kotlin,
    Php,
    Python,
    Ruby,
    Scala,
    Solidity,
    Swift,
}

#[derive(Debug, Clone)]
pub struct RegistryTaintSpec {
    pub rule_id: &'static str,
    pub language: Language,
    pub engine: TaintEngine,
    pub spec: taint_engine::TaintSpec,
}

pub struct AnalysisPlan<'a> {
    pub ast_rules: Vec<&'a dyn Rule>,
    pub taint_specs: Vec<RegistryTaintSpec>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AstAnalysisRequirement {
    SyntaxTree,
    FileContext,
}

/// Macro to reduce boilerplate in `impl Rule for …` blocks.
///
/// # Variant 1 — rules that only implement `check`:
///
/// ```ignore
/// impl_rule! {
///     SomeRule,
///     id = "py/some-rule",
///     severity = Severity::High,
///     cwe = Some("CWE-123"),
///     description = "Some description",
///     language = Language::Python,
///     fn check(&self, source, tree) {
///         // …body using `self`, `source`, `tree`…
///     }
/// }
/// ```
///
/// # Variant 2 — rules that implement `check_with_context` (auto-generates
///   a delegating `check`):
///
/// ```ignore
/// impl_rule! {
///     SomeRule,
///     id = "py/some-rule",
///     severity = Severity::High,
///     cwe = Some("CWE-123"),
///     description = "Some description",
///     language = Language::Python,
///     fn check_with_context(&self, source, tree, ctx) {
///         // …body using `self`, `source`, `tree`, `ctx`…
///     }
/// }
/// ```
///
/// Optional declarative metadata:
///   * `cnsa2_deadline = "YYYY"` — sets [`Rule::cnsa2_deadline`] for
///     quantum-related rules.
///   * `applies_to_filename = "NAME"` — restricts the rule to files whose
///     basename equals `NAME` (e.g. `"Cargo.lock"`, `"requirements.txt"`).
///     Useful for manifest/lockfile rules that parse the source themselves
///     rather than relying on tree-sitter.
#[macro_export]
macro_rules! impl_rule {
    // ── Variant 1: check only ──────────────────────────────────────────────
    (
        $struct:ty,
        id = $id:expr,
        severity = $sev:expr,
        cwe = $cwe:expr,
        description = $desc:expr,
        language = $lang:expr,
        fn check($self_:ident, $src:ident, $tree:ident) { $($check_body:tt)* }
    ) => {
        impl $crate::rules::Rule for $struct {
            fn id(&self) -> &str { $id }
            fn severity(&self) -> $crate::Severity { $sev }
            fn cwe(&self) -> Option<&str> { $cwe }
            fn description(&self) -> &str { $desc }
            fn language(&self) -> $crate::Language { $lang }
            fn check(&self, $src: &str, $tree: &tree_sitter::Tree) -> Vec<$crate::Finding> {
                let $self_ = self;
                $($check_body)*
            }
        }
    };

    // ── Variant 1b: check only, with cnsa2_deadline ──────────────────────
    (
        $struct:ty,
        id = $id:expr,
        severity = $sev:expr,
        cwe = $cwe:expr,
        description = $desc:expr,
        language = $lang:expr,
        cnsa2_deadline = $deadline:expr,
        fn check($self_:ident, $src:ident, $tree:ident) { $($check_body:tt)* }
    ) => {
        impl $crate::rules::Rule for $struct {
            fn id(&self) -> &str { $id }
            fn severity(&self) -> $crate::Severity { $sev }
            fn cwe(&self) -> Option<&str> { $cwe }
            fn description(&self) -> &str { $desc }
            fn language(&self) -> $crate::Language { $lang }
            fn cnsa2_deadline(&self) -> Option<&'static str> { Some($deadline) }
            fn check(&self, $src: &str, $tree: &tree_sitter::Tree) -> Vec<$crate::Finding> {
                let $self_ = self;
                $($check_body)*
            }
        }
    };

    // ── Variant 1c: check only, with cnsa2_deadline + applies_to_filename ──
    //
    // For rules that only fire on files with a specific basename (e.g.
    // `Cargo.lock`, `requirements.txt`). The check body typically ignores
    // the `tree` argument and parses `source` itself with a format-specific
    // parser (TOML, line-oriented, …). Use this arm instead of writing the
    // trait impl by hand so metadata (cwe, severity, cnsa2_deadline) stays
    // declarative and consistent with every other rule.
    (
        $struct:ty,
        id = $id:expr,
        severity = $sev:expr,
        cwe = $cwe:expr,
        description = $desc:expr,
        language = $lang:expr,
        cnsa2_deadline = $deadline:expr,
        applies_to_filename = $filename:expr,
        fn check($self_:ident, $src:ident, $tree:ident) { $($check_body:tt)* }
    ) => {
        impl $crate::rules::Rule for $struct {
            fn id(&self) -> &str { $id }
            fn severity(&self) -> $crate::Severity { $sev }
            fn cwe(&self) -> Option<&str> { $cwe }
            fn description(&self) -> &str { $desc }
            fn language(&self) -> $crate::Language { $lang }
            fn cnsa2_deadline(&self) -> Option<&'static str> { Some($deadline) }
            fn applies_to_path(&self, path: &std::path::Path) -> bool {
                path.file_name().and_then(|f| f.to_str()) == Some($filename)
            }
            fn check(&self, $src: &str, $tree: &tree_sitter::Tree) -> Vec<$crate::Finding> {
                let $self_ = self;
                $($check_body)*
            }
        }
    };

    // ── Variant 1d: check only, with applies_to_filename (no cnsa2) ──────
    //
    // For informational manifest rules (e.g. the post-quantum-ready dep
    // detectors) that fire on a specific basename but declare no CNSA 2.0
    // deadline — a quantum-resistant dependency is not on a transition clock.
    (
        $struct:ty,
        id = $id:expr,
        severity = $sev:expr,
        cwe = $cwe:expr,
        description = $desc:expr,
        language = $lang:expr,
        applies_to_filename = $filename:expr,
        fn check($self_:ident, $src:ident, $tree:ident) { $($check_body:tt)* }
    ) => {
        impl $crate::rules::Rule for $struct {
            fn id(&self) -> &str { $id }
            fn severity(&self) -> $crate::Severity { $sev }
            fn cwe(&self) -> Option<&str> { $cwe }
            fn description(&self) -> &str { $desc }
            fn language(&self) -> $crate::Language { $lang }
            fn applies_to_path(&self, path: &std::path::Path) -> bool {
                path.file_name().and_then(|f| f.to_str()) == Some($filename)
            }
            fn check(&self, $src: &str, $tree: &tree_sitter::Tree) -> Vec<$crate::Finding> {
                let $self_ = self;
                $($check_body)*
            }
        }
    };

    // ── Variant 2: check_with_context (auto-generates delegating check) ──
    (
        $struct:ty,
        id = $id:expr,
        severity = $sev:expr,
        cwe = $cwe:expr,
        description = $desc:expr,
        language = $lang:expr,
        fn check_with_context($self_:ident, $src:ident, $tree:ident, $ctx:ident) { $($check_body:tt)* }
    ) => {
        impl $crate::rules::Rule for $struct {
            fn id(&self) -> &str { $id }
            fn severity(&self) -> $crate::Severity { $sev }
            fn cwe(&self) -> Option<&str> { $cwe }
            fn description(&self) -> &str { $desc }
            fn language(&self) -> $crate::Language { $lang }
            fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<$crate::Finding> {
                self.check_with_context(source, tree, &$crate::rules::FileContext::default())
            }
            fn ast_analysis_requirement(&self) -> $crate::rules::AstAnalysisRequirement {
                $crate::rules::AstAnalysisRequirement::FileContext
            }
            fn check_with_context(
                &self,
                $src: &str,
                $tree: &tree_sitter::Tree,
                $ctx: &$crate::rules::FileContext<'_>,
            ) -> Vec<$crate::Finding> {
                let $self_ = self;
                $($check_body)*
            }
        }
    };

    // ── Variant 2b: check_with_context, with cnsa2_deadline ──────────────
    (
        $struct:ty,
        id = $id:expr,
        severity = $sev:expr,
        cwe = $cwe:expr,
        description = $desc:expr,
        language = $lang:expr,
        cnsa2_deadline = $deadline:expr,
        fn check_with_context($self_:ident, $src:ident, $tree:ident, $ctx:ident) { $($check_body:tt)* }
    ) => {
        impl $crate::rules::Rule for $struct {
            fn id(&self) -> &str { $id }
            fn severity(&self) -> $crate::Severity { $sev }
            fn cwe(&self) -> Option<&str> { $cwe }
            fn description(&self) -> &str { $desc }
            fn language(&self) -> $crate::Language { $lang }
            fn cnsa2_deadline(&self) -> Option<&'static str> { Some($deadline) }
            fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<$crate::Finding> {
                self.check_with_context(source, tree, &$crate::rules::FileContext::default())
            }
            fn ast_analysis_requirement(&self) -> $crate::rules::AstAnalysisRequirement {
                $crate::rules::AstAnalysisRequirement::FileContext
            }
            fn check_with_context(
                &self,
                $src: &str,
                $tree: &tree_sitter::Tree,
                $ctx: &$crate::rules::FileContext<'_>,
            ) -> Vec<$crate::Finding> {
                let $self_ = self;
                $($check_body)*
            }
        }
    };
}

macro_rules! register_rules {
    ($registry:expr, [$($rule:path),+ $(,)?]) => {
        $(
            $registry.register(Box::new($rule));
        )+
    };
}

/// Per-file analysis context shared across all rules running on a single file.
///
/// Computed once after parsing in the scanner and handed to each rule via
/// `check_with_context`. Rules that need nothing from it can continue to
/// implement `check` directly and rely on the default trait method.
#[derive(Default)]
pub struct FileContext<'a> {
    /// Python import alias table. `None` for non-Python files.
    pub python_aliases: Option<&'a common::AliasTable>,
    /// JavaScript/TypeScript import alias table. `None` for non-JS files.
    pub javascript_aliases: Option<&'a common::AliasTable>,
    /// Go import alias table. `None` for non-Go files.
    pub go_aliases: Option<&'a common::AliasTable>,
    /// Cross-file taint summaries from pass 1. Keyed by canonical file path.
    /// `None` when cross-file analysis is not available (e.g. single-file scan).
    pub cross_file_summaries: Option<&'a cross_file::CrossFileSummaryMap>,
    /// Python import-to-file-path resolution map for the current file.
    /// Maps local import names to resolved file paths on disk.
    pub python_import_paths: Option<&'a std::collections::HashMap<String, std::path::PathBuf>>,
    /// JavaScript import-to-file-path resolution map for the current file.
    /// Maps local import names / module specifiers to resolved file paths on disk.
    pub javascript_import_paths: Option<&'a std::collections::HashMap<String, std::path::PathBuf>>,
    /// Go same-package file paths. All `.go` files in the same directory
    /// share the same package and can call each other's functions.
    /// Excludes the current file itself.
    pub go_same_package_paths: Option<Vec<std::path::PathBuf>>,
    /// Java same-package file paths (same-directory proxy). Used to resolve
    /// cross-file helper-method calls by name. Excludes the current file.
    pub java_same_package_paths: Option<Vec<std::path::PathBuf>>,
    /// Ruby same-package file paths (same-directory proxy). Used to resolve
    /// cross-file helper-method calls by name+arity. Excludes the current file.
    pub ruby_same_package_paths: Option<Vec<std::path::PathBuf>>,
    /// PHP same-package file paths (same-directory proxy). Used to resolve
    /// cross-file helper-function/method calls by name. Excludes the current
    /// file. PHP has no compiler-enforced package boundary, so sibling files
    /// in the same directory are treated as the resolution scope (the same
    /// over-approximation used for Go and Java).
    pub php_same_package_paths: Option<Vec<std::path::PathBuf>>,
    /// C# same-namespace file paths (same-directory proxy). Used to resolve
    /// cross-file helper-method calls by name. Excludes the current file.
    pub csharp_same_package_paths: Option<Vec<std::path::PathBuf>>,
    /// Kotlin same-package file paths (same-directory proxy). Used to resolve
    /// cross-file helper-function calls by name+arity. Excludes the current
    /// file. Kotlin has package declarations, but the engine treats
    /// sibling files in the same directory as the resolution scope (the same
    /// over-approximation used for Go/Java/C#).
    pub kotlin_same_package_paths: Option<Vec<std::path::PathBuf>>,
    /// Per-scan hardcoded-secret thresholds captured from the registry.
    pub secret_thresholds: common::SecretScanThresholds,
}

/// A security rule that checks parsed source code for vulnerabilities.
pub trait Rule: Send + Sync {
    fn id(&self) -> &str;
    fn severity(&self) -> Severity;
    fn cwe(&self) -> Option<&str>;
    fn description(&self) -> &str;
    fn language(&self) -> Language;
    fn applies_to_path(&self, _path: &Path) -> bool {
        true
    }
    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding>;

    fn ast_analysis_requirement(&self) -> AstAnalysisRequirement {
        AstAnalysisRequirement::SyntaxTree
    }

    /// Context-aware variant. Defaults to calling `check` so every existing
    /// rule works unchanged. Rules that need the per-file context (e.g.
    /// Python import aliases) override this instead of `check`.
    fn check_with_context(
        &self,
        source: &str,
        tree: &tree_sitter::Tree,
        _ctx: &FileContext<'_>,
    ) -> Vec<Finding> {
        self.check(source, tree)
    }

    /// Apply per-rule options from config. Rules that support tuning override
    /// this to parse their options from the YAML value. Returns an error
    /// message if the options are invalid.
    fn configure(&mut self, _opts: &serde_yaml_ng::Value) -> Result<(), String> {
        Ok(())
    }

    /// CNSA 2.0 transition deadline for findings from this rule, as a
    /// `"YYYY"` string (e.g. `"2030"`, `"2033"`), or `None` for rules that
    /// are not quantum-related. Consumed by [`crate::compliance`] at
    /// finding emission / post-processing time to populate
    /// `Finding.cnsa2_deadline`. See that module for the per-class
    /// mapping and NSA source citations. Rules must declare their own
    /// deadline via the `cnsa2_deadline = "..."` arm of [`impl_rule!`]
    /// so this trait stays the single source of truth (no substring
    /// matching on rule IDs in a central module — see PR #231 review).
    fn cnsa2_deadline(&self) -> Option<&'static str> {
        None
    }
}

/// Registry holding all available rules.
pub struct RuleRegistry {
    rules: Vec<Box<dyn Rule>>,
    /// Rule IDs that are opt-in only (not active unless explicitly enabled).
    opt_in_ids: std::collections::HashSet<String>,
    secret_thresholds: common::SecretScanThresholds,
}

impl Default for RuleRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl RuleRegistry {
    pub fn empty() -> Self {
        Self {
            rules: Vec::new(),
            opt_in_ids: std::collections::HashSet::new(),
            secret_thresholds: common::SecretScanThresholds::default(),
        }
    }

    pub fn new() -> Self {
        let mut registry = Self::empty();

        register_rules!(
            registry,
            [
                javascript::NoEval,
                javascript::NoHardcodedSecret,
                javascript::NoSqlInjection,
                javascript::NoXssInnerHtml,
                javascript::NoCommandInjection,
                javascript::NoDocumentWrite,
                javascript::NoOpenRedirect,
                javascript::NoWeakCrypto,
                javascript::PqVulnerableCrypto,
                javascript::NoPathTraversal,
                javascript::NoSsrf,
                javascript::NoPrototypePollution,
                javascript::NoUnsafeRegex,
                javascript::NoCorsStar,
                javascript::ExpressNoHardcodedSessionSecret,
                javascript::ExpressCookieNoSecure,
                javascript::ExpressCookieNoHttpOnly,
                javascript::ExpressCookieNoSameSite,
                javascript::ExpressSessionSaveUninitializedTrue,
                javascript::ExpressSessionResaveTrue,
                javascript::ExpressDirectResponseWrite,
                javascript::JwtHardcodedSecret,
                javascript::JwtNoneAlgorithm,
                javascript::JwtIgnoreExpiration,
                javascript::JwtDecodeWithoutVerify,
                javascript::JwtVerifyMissingAlgorithms,
                javascript::NoUnsafeFormatString,
                javascript::TaintXssInnerHtml,
                javascript::TaintSqlInjection,
                javascript::TaintEval,
                javascript::TaintCommandInjection,
                javascript::TaintSsrf,
                javascript::TaintSsti,
                javascript::TaintXpathInjection,
                javascript::TaintLdapInjection,
                javascript::TaintLogInjection,
                javascript::TaintXxe,
                javascript::NoUnsafeDeserialization,
            ]
        );
        registry.register_opt_in(Box::new(javascript::HardcodedCryptoAlgorithm));
        registry.register_opt_in(Box::new(javascript::PqReadyCrypto));
        register_rules!(registry, [javascript::TaintNosqlInjection]);

        register_rules!(
            registry,
            [
                python::NoEval,
                python::NoHardcodedSecret,
                python::NoSqlInjection,
                python::NoCommandInjection,
                python::NoPathTraversal,
                python::NoSsrf,
                python::NoWeakCrypto,
                python::PqVulnerableCrypto,
                python::NoPickle,
                python::NoYamlLoad,
                python::NoDebugTrue,
                python::NoOpenRedirect,
                python::NoCorsStar,
                python::FlaskDebugMode,
                python::DjangoSecretKeyHardcoded,
                python::FlaskSecretKeyHardcoded,
                python::SessionCookieSecureDisabled,
                python::SessionCookieHttpOnlyDisabled,
                python::SessionCookieSameSiteDisabled,
                python::CsrfCookieSecureDisabled,
                python::CsrfCookieHttpOnlyDisabled,
                python::CsrfCookieSameSiteDisabled,
                python::CsrfExempt,
                python::WtfCsrfDisabled,
                python::WtfCsrfCheckDefaultDisabled,
                python::DjangoAllowedHostsWildcard,
                python::SecureSslRedirectDisabled,
                python::TaintPickleDeserialization,
                python::TaintEvalFromRequest,
                python::TaintCommandInjectionFromRequest,
                python::TaintSsrfFromRequest,
                python::TaintYamlLoadFromRequest,
                python::TaintSqlInjectionFromRequest,
                python::TaintSsti,
                python::TaintXpathInjection,
                python::TaintLdapInjection,
                python::TaintLogInjection,
                python::TaintXxe,
                python::JwtNoVerify,
                python::JwtHardcodedSecret,
            ]
        );
        registry.register_opt_in(Box::new(python::HardcodedCryptoAlgorithm));
        registry.register_opt_in(Box::new(python::PqReadyCrypto));
        register_rules!(registry, [python::TaintNosqlInjection]);

        register_rules!(
            registry,
            [
                go::NoSqlInjection,
                go::NoCommandInjection,
                go::NoHardcodedSecret,
                go::NoWeakCrypto,
                go::PqVulnerableCrypto,
                go::NoSsrf,
                go::InsecureTlsSkipVerify,
                go::MissingSslMinVersion,
                go::CookieMissingSecure,
                go::CookieMissingHttpOnly,
                go::MathRandomUsed,
                go::GinNoTrustedProxies,
                go::NetHttpNoTimeout,
                go::TaintCommandInjection,
                go::TaintSqlInjection,
                go::TaintSsrf,
                go::TaintSsti,
                go::TaintXpathInjection,
                go::TaintLdapInjection,
                go::TaintLogInjection,
                go::NoUnsafeDeserialization,
                go::JwtNoVerify,
                go::JwtHardcodedSecret,
                go::TaintNosqlInjection,
                go::TaintPathTraversal,
            ]
        );
        registry.register_opt_in(Box::new(go::PqReadyCrypto));

        register_rules!(
            registry,
            [
                java::NoSqlInjection,
                java::NoCommandInjection,
                java::NoUnsafeDeserialization,
                java::NoSsrf,
                java::NoPathTraversal,
                java::NoWeakCrypto,
                java::PqVulnerableCrypto,
                java::NoHardcodedSecret,
                java::NoXxe,
                java::SpringCsrfDisabled,
                java::SpringCorsPermissive,
                java::NoXss,
                java::TaintSqlInjection,
                java::TaintCommandInjection,
                java::TaintSsrf,
                java::TaintUnsafeDeserialization,
            ]
        );
        registry.register_opt_in(Box::new(java::HardcodedCryptoAlgorithm));
        registry.register_opt_in(Box::new(java::PqReadyCrypto));

        register_rules!(
            registry,
            [
                php::NoEval,
                php::NoCommandInjection,
                php::NoSqlInjection,
                php::NoUnserialize,
                php::NoFileInclusion,
                php::NoWeakCrypto,
                php::NoHardcodedSecret,
                php::NoSsrf,
                php::NoExtract,
                php::NoPregEval,
            ]
        );

        register_rules!(
            registry,
            [
                ruby::NoEval,
                ruby::NoCommandInjection,
                ruby::NoSqlInjection,
                ruby::NoMassAssignment,
                ruby::NoUnsafeDeserialization,
                ruby::NoOpenRedirect,
                ruby::NoCsrfSkip,
                ruby::NoHtmlSafe,
                ruby::NoHardcodedSecret,
                ruby::NoWeakCrypto,
                ruby::NoSsrf,
                ruby::NoPathTraversal,
                ruby::TaintCommandInjection,
                ruby::TaintSqlInjection,
                ruby::TaintXss,
                ruby::TaintUnsafeDeserialization,
                ruby::TaintOpenRedirect,
            ]
        );

        register_rules!(
            registry,
            [
                csharp::NoSqlInjection,
                csharp::NoCommandInjection,
                csharp::NoUnsafeDeserialization,
                csharp::NoSsrf,
                csharp::NoPathTraversal,
                csharp::NoWeakCrypto,
                csharp::NoHardcodedSecret,
                csharp::NoXxe,
                csharp::NoLdapInjection,
                csharp::NoCorsStar,
                csharp::TaintSqlInjection,
                csharp::TaintCommandInjection,
                csharp::TaintXss,
                csharp::TaintOpenRedirect,
                csharp::TaintXxe,
                csharp::TaintUnsafeLoad,
            ]
        );

        register_rules!(
            registry,
            [
                swift::NoHardcodedSecret,
                swift::NoCommandInjection,
                swift::NoWeakCrypto,
                swift::NoInsecureTransport,
                swift::NoEvalJs,
                swift::NoSqlInjection,
                swift::NoInsecureKeychain,
                swift::NoTlsDisabled,
                swift::NoPathTraversal,
                swift::NoSsrf,
                swift::TaintSqlInjection,
                swift::TaintCommandInjection,
                swift::TaintJsInjection,
                swift::TaintNsexpressionInjection,
            ]
        );

        register_rules!(
            registry,
            [
                kotlin::NoSqlInjection,
                kotlin::NoCommandInjection,
                kotlin::NoUnsafeDeserialization,
                kotlin::NoSsrf,
                kotlin::NoPathTraversal,
                kotlin::NoWeakCrypto,
                kotlin::NoHardcodedSecret,
                kotlin::NoXxe,
                kotlin::NoCorsStar,
                kotlin::NoEval,
                kotlin::TaintSqlInjection,
                kotlin::TaintCommandInjection,
                kotlin::TaintSsrf,
            ]
        );

        register_rules!(
            registry,
            [
                solidity::TaintArbitraryDelegatecall,
                solidity::TaintUnprotectedSelfdestruct,
                solidity::TaintUncheckedCall,
            ]
        );

        register_rules!(
            registry,
            [
                c::TaintFormatString,
                c::TaintCommandInjection,
                c::TaintBufferOverflow,
                c::TaintSqlInjection,
            ]
        );

        register_rules!(
            registry,
            [apex::TaintSoqlInjection, apex::TaintSoslInjection]
        );

        register_rules!(
            registry,
            [
                bash::TaintCommandInjection,
                bash::TaintPathTraversal,
                bash::TaintSsrf,
            ]
        );

        register_rules!(
            registry,
            [
                scala::TaintSqlInjection,
                scala::TaintCommandInjection,
                scala::TaintXss,
                scala::TaintPathTraversal,
                scala::TaintSsrf,
            ]
        );

        register_rules!(
            registry,
            [
                php::TaintCommandInjection,
                php::TaintSqlInjection,
                php::TaintXss,
                php::TaintFileInclusion,
                php::TaintUnsafeDeserialization,
            ]
        );

        register_rules!(
            registry,
            [
                rust_lang::UnsafeBlock,
                rust_lang::TransmuteUsage,
                rust_lang::NoCommandInjection,
                rust_lang::NoSqlInjection,
                rust_lang::NoWeakHash,
                rust_lang::PqVulnerableCrypto,
                rust_lang::NoHardcodedSecret,
                rust_lang::TlsVerifyDisabled,
                rust_lang::NoSsrf,
                rust_lang::NoPathTraversal,
                rust_lang::NoUnwrapInLib,
            ]
        );
        registry.register_opt_in(Box::new(rust_lang::PqReadyCrypto));

        register_rules!(
            registry,
            [
                config::NginxPqVulnerableTls,
                config::ApachePqVulnerableTls,
                config::HAProxyPqVulnerableTls,
                config::DockerfileInsecureTlsEnv,
                manifest::OsvVulnerableDependency,
                manifest::CargoLockPqCrypto,
                manifest::RequirementsTxtPqCrypto,
                manifest::PoetryLockPqCrypto,
                manifest::PipfileLockPqCrypto,
                manifest::PnpmLockPqCrypto,
                manifest::PackageLockPqCrypto,
            ]
        );
        // Informational post-quantum-ready detectors (opt-in; activated by the
        // `foxguard pqc` audit via the PQ rule allowlist). Kept out of the
        // default scan so a repository already using ML-KEM is not flagged.
        registry.register_opt_in(Box::new(config::NginxPqReadyTls));
        registry.register_opt_in(Box::new(config::ApachePqReadyTls));
        registry.register_opt_in(Box::new(config::HAProxyPqReadyTls));
        registry.register_opt_in(Box::new(manifest::CargoLockPqReadyCrypto));
        registry.register_opt_in(Box::new(manifest::RequirementsTxtPqReadyCrypto));

        // Register bundled YAML rule packs (currently the kernel
        // dirty-frag-class pack). These ship inside the binary via the
        // `include_dir!` blob above; they are treated as built-in rules so
        // `--no-builtins` suppresses them too. Users who want the kernel
        // pack but not the Rust rules can lean on `--rules <path>` against
        // an external clone — `--no-builtins` means "no foxguard-shipped
        // rules at all".
        for rule in semgrep_compat::load_semgrep_rules_from_embedded(&BUNDLED_RULES) {
            registry.register(rule);
        }

        registry
    }

    pub fn register(&mut self, rule: Box<dyn Rule>) {
        self.rules.push(rule);
    }

    pub fn set_secret_thresholds(&mut self, thresholds: common::SecretScanThresholds) {
        self.secret_thresholds = thresholds;
    }

    pub fn secret_thresholds(&self) -> common::SecretScanThresholds {
        self.secret_thresholds
    }

    /// Register a rule that is opt-in only (not active by default).
    /// Users enable it via `scan.enable_rules` in config.
    pub fn register_opt_in(&mut self, rule: Box<dyn Rule>) {
        self.opt_in_ids.insert(rule.id().to_string());
        self.rules.push(rule);
    }

    pub fn rules_for_language(&self, language: Language) -> Vec<&dyn Rule> {
        self.rules
            .iter()
            .filter(|r| r.language() == language)
            .map(|r| r.as_ref())
            .collect()
    }

    pub fn taint_specs_for_language(&self, language: Language) -> Vec<RegistryTaintSpec> {
        let enabled_rule_ids: std::collections::HashSet<&str> = self
            .rules
            .iter()
            .filter(|rule| rule.language() == language)
            .map(|rule| rule.id())
            .collect();

        builtin_taint_specs_for_language(language)
            .into_iter()
            .filter(|spec| enabled_rule_ids.contains(spec.rule_id))
            .collect()
    }

    pub fn analysis_plan_for_path<'a>(
        &'a self,
        language: Language,
        path: &Path,
    ) -> AnalysisPlan<'a> {
        let taint_specs = self.taint_specs_for_language(language);
        let taint_rule_ids: std::collections::HashSet<&str> =
            taint_specs.iter().map(|spec| spec.rule_id).collect();

        let ast_rules = self
            .rules
            .iter()
            .filter(|rule| {
                rule.language() == language
                    && rule.applies_to_path(path)
                    && !taint_rule_ids.contains(rule.id())
            })
            .map(|rule| rule.as_ref())
            .collect();

        let taint_specs = taint_specs
            .into_iter()
            .filter(|spec| {
                self.rules.iter().any(|rule| {
                    rule.id() == spec.rule_id
                        && rule.language() == language
                        && rule.applies_to_path(path)
                })
            })
            .collect();

        AnalysisPlan {
            ast_rules,
            taint_specs,
        }
    }

    /// Apply per-rule options from config. Warns on stderr for unknown rule IDs
    /// and returns errors for invalid option values.
    pub fn configure_rules(
        &mut self,
        rule_options: &std::collections::HashMap<String, serde_yaml_ng::Value>,
    ) -> Result<Vec<String>, String> {
        let mut warnings = Vec::new();
        for (rule_id, opts) in rule_options {
            let Some(rule) = self.rules.iter_mut().find(|r| r.id() == rule_id) else {
                warnings.push(format!("rule_options: unknown rule '{}'", rule_id));
                continue;
            };
            rule.configure(opts)
                .map_err(|e| format!("rule_options: invalid config for '{}': {}", rule_id, e))?;
        }
        Ok(warnings)
    }

    pub fn all_rules(&self) -> &[Box<dyn Rule>] {
        &self.rules
    }

    /// Apply `scan.enable_rules` (allowlist) and `scan.disable_rules`
    /// (denylist) from the loaded config to the active rule set.
    ///
    /// Semantics:
    /// - If `enable` is non-empty, only rules whose id is in `enable` are
    ///   retained (intersection with the full registry).
    /// - If `disable` is non-empty, rules whose id is in `disable` are
    ///   removed. Applied after `enable`, so IDs appearing in both lists
    ///   are disabled.
    /// - Both empty → no change.
    ///
    /// Returns the set of IDs from `enable` or `disable` that do not
    /// correspond to any registered rule. Callers should surface these
    /// as a single warning so users catch typos without failing the scan.
    pub fn apply_rule_filter(&mut self, enable: &[String], disable: &[String]) -> Vec<String> {
        self.apply_rule_filter_with_known(enable, disable, &std::collections::HashSet::new())
    }

    pub fn apply_rule_filter_with_known(
        &mut self,
        enable: &[String],
        disable: &[String],
        additional_known: &std::collections::HashSet<String>,
    ) -> Vec<String> {
        let known: std::collections::HashSet<&str> = self.rules.iter().map(|r| r.id()).collect();

        let mut unknown: Vec<String> = Vec::new();
        let mut seen_unknown: std::collections::HashSet<&str> = std::collections::HashSet::new();
        for id in enable.iter().chain(disable.iter()) {
            if !known.contains(id.as_str())
                && !additional_known.contains(id.as_str())
                && seen_unknown.insert(id.as_str())
            {
                unknown.push(id.clone());
            }
        }

        if !enable.is_empty() {
            // Explicit allowlist: keep only these rules (overrides opt-in).
            let enable_set: std::collections::HashSet<&str> =
                enable.iter().map(|s| s.as_str()).collect();
            self.rules.retain(|r| enable_set.contains(r.id()));
        } else {
            // No explicit allowlist: strip opt-in-only rules.
            self.rules.retain(|r| !self.opt_in_ids.contains(r.id()));
        }

        if !disable.is_empty() {
            let disable_set: std::collections::HashSet<&str> =
                disable.iter().map(|s| s.as_str()).collect();
            self.rules.retain(|r| !disable_set.contains(r.id()));
        }

        unknown
    }
}

fn builtin_taint_specs_for_language(language: Language) -> Vec<RegistryTaintSpec> {
    match language {
        Language::Apex => apex_taint::apex_taint_rule_specs()
            .into_iter()
            .map(|(rule_id, spec)| RegistryTaintSpec {
                rule_id,
                language,
                engine: TaintEngine::Apex,
                spec,
            })
            .collect(),
        Language::Bash => bash_taint::bash_taint_rule_specs()
            .into_iter()
            .map(|(rule_id, spec)| RegistryTaintSpec {
                rule_id,
                language,
                engine: TaintEngine::Bash,
                spec,
            })
            .collect(),
        Language::C => c_taint::c_taint_rule_specs()
            .into_iter()
            .map(|(rule_id, spec)| RegistryTaintSpec {
                rule_id,
                language,
                engine: TaintEngine::C,
                spec,
            })
            .collect(),
        Language::CSharp => csharp_taint::csharp_taint_rule_specs()
            .into_iter()
            .map(|(rule_id, spec)| RegistryTaintSpec {
                rule_id,
                language,
                engine: TaintEngine::CSharp,
                spec,
            })
            .collect(),
        Language::Go => go::go_taint_rule_specs()
            .into_iter()
            .map(|(rule_id, spec)| RegistryTaintSpec {
                rule_id,
                language,
                engine: TaintEngine::Go,
                spec,
            })
            .collect(),
        Language::Java => java_taint::java_taint_rule_specs()
            .into_iter()
            .map(|(rule_id, spec)| RegistryTaintSpec {
                rule_id,
                language,
                engine: TaintEngine::Java,
                spec,
            })
            .collect(),
        Language::JavaScript => javascript::js_taint_rule_specs()
            .into_iter()
            .map(|(rule_id, spec)| RegistryTaintSpec {
                rule_id,
                language,
                engine: TaintEngine::JavaScript,
                spec,
            })
            .collect(),
        Language::Python => python::python_taint_rule_specs()
            .into_iter()
            .map(|(rule_id, spec)| RegistryTaintSpec {
                rule_id,
                language,
                engine: TaintEngine::Python,
                spec,
            })
            .collect(),
        Language::Kotlin => kotlin_taint::kotlin_taint_rule_specs()
            .into_iter()
            .map(|(rule_id, spec)| RegistryTaintSpec {
                rule_id,
                language,
                engine: TaintEngine::Kotlin,
                spec,
            })
            .collect(),
        Language::Ruby => ruby_taint::ruby_taint_rule_specs()
            .into_iter()
            .map(|(rule_id, spec)| RegistryTaintSpec {
                rule_id,
                language,
                engine: TaintEngine::Ruby,
                spec,
            })
            .collect(),
        Language::Php => php_taint::php_taint_rule_specs()
            .into_iter()
            .map(|(rule_id, spec)| RegistryTaintSpec {
                rule_id,
                language,
                engine: TaintEngine::Php,
                spec,
            })
            .collect(),
        Language::Scala => scala_taint::scala_taint_rule_specs()
            .into_iter()
            .map(|(rule_id, spec)| RegistryTaintSpec {
                rule_id,
                language,
                engine: TaintEngine::Scala,
                spec,
            })
            .collect(),
        Language::Solidity => solidity_taint::solidity_taint_rule_specs()
            .into_iter()
            .map(|(rule_id, spec)| RegistryTaintSpec {
                rule_id,
                language,
                engine: TaintEngine::Solidity,
                spec,
            })
            .collect(),
        Language::Swift => swift_taint::swift_taint_rule_specs()
            .into_iter()
            .map(|(rule_id, spec)| RegistryTaintSpec {
                rule_id,
                language,
                engine: TaintEngine::Swift,
                spec,
            })
            .collect(),
        _ => Vec::new(),
    }
}

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

    #[allow(dead_code)]
    fn rule_ids(registry: &RuleRegistry) -> Vec<String> {
        registry.rules.iter().map(|r| r.id().to_string()).collect()
    }

    fn has_rule(registry: &RuleRegistry, id: &str) -> bool {
        registry.rules.iter().any(|r| r.id() == id)
    }

    #[test]
    fn apply_rule_filter_strips_opt_in_when_both_lists_empty() {
        let mut registry = RuleRegistry::new();
        let before_count = registry.rules.len();
        let unknown = registry.apply_rule_filter(&[], &[]);
        assert!(unknown.is_empty());
        // Opt-in rules are stripped when no explicit enable list is given.
        assert!(registry.rules.len() < before_count);
        assert!(!has_rule(&registry, "js/hardcoded-crypto-algorithm"));
        assert!(!has_rule(&registry, "py/hardcoded-crypto-algorithm"));
        assert!(!has_rule(&registry, "java/hardcoded-crypto-algorithm"));
    }

    #[test]
    fn apply_rule_filter_allowlist_keeps_only_listed_ids() {
        let mut registry = RuleRegistry::new();
        let unknown =
            registry.apply_rule_filter(&["py/no-eval".to_string(), "js/no-eval".to_string()], &[]);
        assert!(unknown.is_empty());
        assert_eq!(registry.rules.len(), 2);
        assert!(has_rule(&registry, "py/no-eval"));
        assert!(has_rule(&registry, "js/no-eval"));
    }

    #[test]
    fn apply_rule_filter_denylist_removes_listed_ids() {
        let mut registry = RuleRegistry::new();
        let opt_in_count = registry.opt_in_ids.len();
        let before_count = registry.rules.len();
        let unknown = registry.apply_rule_filter(&[], &["py/no-eval".to_string()]);
        assert!(unknown.is_empty());
        // Denylist removes py/no-eval, and opt-in rules are also stripped.
        assert_eq!(registry.rules.len(), before_count - 1 - opt_in_count);
        assert!(!has_rule(&registry, "py/no-eval"));
    }

    #[test]
    fn apply_rule_filter_both_intersects_then_subtracts() {
        // enable = {py/no-eval, py/no-sql-injection}; disable = {py/no-eval}
        // Expected: only py/no-sql-injection remains.
        let mut registry = RuleRegistry::new();
        let unknown = registry.apply_rule_filter(
            &["py/no-eval".to_string(), "py/no-sql-injection".to_string()],
            &["py/no-eval".to_string()],
        );
        assert!(unknown.is_empty());
        assert_eq!(registry.rules.len(), 1);
        assert!(has_rule(&registry, "py/no-sql-injection"));
        assert!(!has_rule(&registry, "py/no-eval"));
    }

    #[test]
    fn apply_rule_filter_reports_unknown_rule_ids() {
        let mut registry = RuleRegistry::new();
        let unknown = registry.apply_rule_filter(
            &["py/no-eval".to_string(), "py/does-not-exist".to_string()],
            &["another/typo".to_string()],
        );
        assert_eq!(unknown.len(), 2);
        assert!(unknown.contains(&"py/does-not-exist".to_string()));
        assert!(unknown.contains(&"another/typo".to_string()));
        // Real rule still applies (allowlist kept py/no-eval, denylist had no matches).
        assert!(has_rule(&registry, "py/no-eval"));
    }

    #[test]
    fn apply_rule_filter_deduplicates_unknown_ids() {
        let mut registry = RuleRegistry::new();
        let unknown = registry.apply_rule_filter(
            &["py/typo".to_string(), "py/typo".to_string()],
            &["py/typo".to_string()],
        );
        assert_eq!(unknown, vec!["py/typo".to_string()]);
    }

    #[test]
    fn registry_exposes_enabled_taint_specs() {
        let mut registry = RuleRegistry::new();
        let unknown = registry.apply_rule_filter(
            &[
                "py/taint-eval".to_string(),
                "py/taint-sql-injection".to_string(),
                "py/no-eval".to_string(),
            ],
            &[],
        );
        assert!(unknown.is_empty());

        let specs = registry.taint_specs_for_language(Language::Python);
        let ids: std::collections::BTreeSet<&str> = specs.iter().map(|spec| spec.rule_id).collect();
        assert_eq!(ids.len(), 2);
        assert!(ids.contains("py/taint-eval"));
        assert!(ids.contains("py/taint-sql-injection"));
        assert!(specs.iter().all(|spec| spec.language == Language::Python
            && spec.engine == TaintEngine::Python
            && !spec.spec.sinks.is_empty()));
    }

    #[test]
    fn analysis_plan_splits_taint_specs_from_ast_rules() {
        let mut registry = RuleRegistry::new();
        let unknown = registry.apply_rule_filter(
            &["py/taint-eval".to_string(), "py/no-eval".to_string()],
            &[],
        );
        assert!(unknown.is_empty());

        let plan = registry.analysis_plan_for_path(Language::Python, Path::new("app.py"));
        assert_eq!(plan.ast_rules.len(), 1);
        assert_eq!(plan.ast_rules[0].id(), "py/no-eval");
        assert_eq!(plan.taint_specs.len(), 1);
        assert_eq!(plan.taint_specs[0].rule_id, "py/taint-eval");
    }

    #[test]
    fn configure_rules_warns_on_unknown_rule_id() {
        let mut registry = RuleRegistry::new();
        let mut opts = std::collections::HashMap::new();
        opts.insert("py/does-not-exist".to_string(), serde_yaml_ng::Value::Null);
        let warnings = registry.configure_rules(&opts).unwrap();
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("py/does-not-exist"));
    }

    #[test]
    fn configure_rules_no_warning_for_known_rule() {
        let mut registry = RuleRegistry::new();
        let mut opts = std::collections::HashMap::new();
        opts.insert("py/no-eval".to_string(), serde_yaml_ng::Value::Null);
        let warnings = registry.configure_rules(&opts).unwrap();
        assert!(warnings.is_empty());
    }

    #[test]
    fn configure_rules_empty_options_is_no_op() {
        let mut registry = RuleRegistry::new();
        let opts = std::collections::HashMap::new();
        let warnings = registry.configure_rules(&opts).unwrap();
        assert!(warnings.is_empty());
    }

    /// Proves the kernel dirty-frag YAML pack is loaded by default — i.e.
    /// without the user passing `--rules rules/kernel/dirty-frag-class/`.
    /// Before this change the pack only fired when explicitly opted into;
    /// now it ships inside the binary via `include_dir!` and registers on
    /// the same `RuleRegistry::new()` call as the Rust rules.
    ///
    /// The CodeQL-engine rule
    /// (`kernel/dirty-frag/esp-shared-frag-decrypt-guard-codeql`) is
    /// intentionally skipped by the Semgrep loader — Agent B's CodeQL
    /// bridge owns that one.
    #[test]
    fn bundled_kernel_dirty_frag_rules_load_by_default() {
        let registry = RuleRegistry::new();
        let ids: std::collections::HashSet<&str> = registry.rules.iter().map(|r| r.id()).collect();

        // Five Semgrep-engine rules in the pack (the sixth is CodeQL).
        let expected = [
            "semgrep/kernel/dirty-frag/skb-inplace-skcipher-no-cow",
            "semgrep/kernel/dirty-frag/skb-inplace-aead-no-cow",
            "semgrep/kernel/dirty-frag/scatterwalk-store-on-shared-sgl",
            "semgrep/kernel/dirty-frag/scatterwalk-store-on-shared-sgl-authencesn",
            "semgrep/kernel/dirty-frag/rxrpc-verify-response-dispatch",
        ];
        for id in expected {
            assert!(
                ids.contains(id),
                "expected bundled rule {} to be registered by default, got: {:?}",
                id,
                ids.iter()
                    .filter(|i| i.starts_with("semgrep/kernel"))
                    .collect::<Vec<_>>()
            );
        }

        // CodeQL-engine rule must NOT be picked up by the Semgrep loader.
        assert!(
            !ids.contains("semgrep/kernel/dirty-frag/esp-shared-frag-decrypt-guard-codeql"),
            "CodeQL rule leaked into the Semgrep registry"
        );
    }

    /// `--no-builtins` must suppress the bundled YAML pack too, not just
    /// the Rust rules. This is the explicit design decision documented in
    /// `build_registry` in `src/app.rs`.
    #[test]
    fn empty_registry_does_not_load_bundled_rules() {
        let registry = RuleRegistry::empty();
        assert!(registry.rules.is_empty());
    }
}