repotoire 0.9.0

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
//! NoSQL Injection Detector
//!
//! Graph-enhanced detection of NoSQL injection:
//! - Trace user input to MongoDB queries
//! - Detect dangerous operators ($where, $regex, etc.)
//! - Check for sanitization/validation in call chain

// Phase 2i dual-branch submodules. Wired through `detect()` in
// commit 5 of the dual-branch migration stack. Scaffolded in
// commit 3 (predict + annotation) and commit 4 (evidence) with
// `#![allow(dead_code)]` so they compile without integration.
mod annotation;
mod evidence;
mod predict;

use crate::detectors::base::{Detector, DetectorConfig};
use crate::detectors::security::dangerous_sinks::SinkKind;
use crate::graph::GraphQueryExt;
use crate::models::{deterministic_finding_id, Evidence, Finding, Severity, SourceSpan, Tier};
use anyhow::Result;
use regex::Regex;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use tracing::info;

static NOSQL_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)(\.find\(|\.findOne\(|\.findById\(|\.updateOne\(|\.updateMany\(|\.deleteOne\(|\.deleteMany\(|\.aggregate\(|\.countDocuments\(|db\.\w+\.)").expect("valid regex")
});
static DANGEROUS_OPS: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(\$where|\$regex|\$expr|\$function|\$accumulator)").expect("valid regex")
});
static USER_INPUT: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(req\.(body|query|params|headers)|request\.(body|query)|ctx\.(request|body)|input|JSON\.parse)").expect("valid regex")
});

/// MongoDB / NoSQL query execution method names that constitute a dangerous sink
/// when tainted (user-controlled) data flows into them without sanitization.
///
/// These are recognized by `classify_nosql_sink` to produce
/// `SinkKind::NosqlQuery` findings. They are intentionally NOT in the shared
/// `dangerous_sinks::classify_sink` tables (which are language-keyed by
/// receiver+name); the NoSQL detector handles the terminus classification here
/// because MongoDB call shapes vary (`collection.find`, `Model.findOne`,
/// `db.users.findOne`, etc.) and the receiver text is not stable.
const NOSQL_QUERY_METHODS: &[&str] = &[
    "find",
    "findOne",
    "findById",
    "findOneAndUpdate",
    "findOneAndDelete",
    "findOneAndReplace",
    "updateOne",
    "updateMany",
    "deleteOne",
    "deleteMany",
    "replaceOne",
    "aggregate",
    "countDocuments",
    "estimatedDocumentCount",
    "distinct",
    // pymongo equivalents
    "find_one",
    "find_one_and_update",
    "find_one_and_delete",
    "find_one_and_replace",
    "update_one",
    "update_many",
    "delete_one",
    "delete_many",
    "count_documents",
];

/// Classify a taint-path's sink callee text as `SinkKind::NosqlQuery` if
/// it matches a known MongoDB/NoSQL query method name. Returns `None` for
/// non-MongoDB callee texts so the caller can decide whether to promote.
fn classify_nosql_sink(sink_callee_text: &str) -> Option<SinkKind> {
    // The callee text may be the bare method name ("findOne"), a dotted chain
    // ("db.users.findOne"), or a pattern string from the heuristic engine
    // ("findOne"). We check the last segment after the final dot, or the whole
    // string if there is no dot.
    let method = sink_callee_text
        .rsplit('.')
        .next()
        .unwrap_or(sink_callee_text)
        .trim_end_matches('('); // strip trailing `(` if present from pattern strings
    if NOSQL_QUERY_METHODS.contains(&method) {
        Some(SinkKind::NosqlQuery)
    } else {
        None
    }
}

/// Categorize the type of NoSQL injection risk
fn categorize_risk(line: &str) -> (&'static str, &'static str) {
    if line.contains("$where") {
        return ("where", "$where allows JavaScript execution");
    }
    if line.contains("$regex") {
        return ("regex", "$regex with user input enables ReDoS");
    }
    if line.contains("$ne") || line.contains("$gt") || line.contains("$lt") {
        return ("operator", "Operator injection can bypass authentication");
    }
    if line.contains("$expr") || line.contains("$function") {
        return ("eval", "Expression evaluation can execute arbitrary code");
    }
    ("query", "Query injection")
}

pub struct NosqlInjectionDetector {
    repository_path: PathBuf,
    max_findings: usize,
    precomputed_cross: std::sync::OnceLock<Vec<crate::detectors::taint::TaintPath>>,
    precomputed_intra: std::sync::OnceLock<Vec<crate::detectors::taint::TaintPath>>,
}

impl NosqlInjectionDetector {
    pub fn new(repository_path: impl Into<PathBuf>) -> Self {
        Self {
            repository_path: repository_path.into(),
            max_findings: 50,
            precomputed_cross: std::sync::OnceLock::new(),
            precomputed_intra: std::sync::OnceLock::new(),
        }
    }

    /// Check if this is actually an Array method, not MongoDB
    fn is_array_method(line: &str) -> bool {
        // Common array variable patterns
        let array_vars = [
            "items.find(",
            "list.find(",
            "array.find(",
            "results.find(",
            "data.find(",
            "options.find(",
            "elements.find(",
            "entries.find(",
            "records.find(",
            "rows.find(",
            "values.find(",
            "keys.find(",
        ];

        if array_vars.iter().any(|v| line.contains(v)) {
            return true;
        }

        // Check for array method chains
        if line.contains(".filter(")
            || line.contains(".map(")
            || line.contains(".some(")
            || line.contains(".every(")
            || line.contains("Array.")
            || line.contains("[].")
        {
            return true;
        }

        false
    }

    /// Check for sanitization in surrounding context
    fn has_sanitization(lines: &[&str], current_line: usize) -> bool {
        let start = current_line.saturating_sub(10);
        let context = lines[start..current_line].join(" ").to_lowercase();

        context.contains("sanitize")
            || context.contains("validate")
            || context.contains("escape")
            || context.contains("clean")
            || context.contains("tostring()")
            || context.contains("parseint")
            || context.contains("number(")
            || context.contains("boolean(")
            || context.contains("mongo-sanitize")
            || context.contains("express-mongo-sanitize")
    }

    /// Check if function is a route handler (directly receives user input)
    fn is_route_handler(func_name: &str, file_path: &str) -> bool {
        let name_lower = func_name.to_lowercase();
        let path_lower = file_path.to_lowercase();

        name_lower.contains("handler")
            || name_lower.contains("controller")
            || name_lower.contains("route")
            || name_lower.contains("api")
            || name_lower.starts_with("get")
            || name_lower.starts_with("post")
            || name_lower.starts_with("put")
            || name_lower.starts_with("delete")
            || path_lower.contains("route")
            || path_lower.contains("controller")
            || path_lower.contains("handler")
    }

    /// Phase 2i dual-branch AST-driven Python scan.
    ///
    /// Parses the file once, collects every recognized pymongo / motor
    /// call site via [`evidence::collect_python_nosql_sites`] (already
    /// array-method-filtered and structurally classified), extracts
    /// evidence, runs [`predict::predict`], and builds a dual-branch
    /// finding per site. Replaces the legacy line-regex pass for `.py`
    /// files when the `nosql-injection` dual-branch flag is on.
    ///
    /// Returns an empty vec if the file has no recognized pymongo
    /// calls (fast path inside the collector) or fails to parse.
    ///
    /// Mirrors `insecure_deserialize::scan_python_file_dual_branch`
    /// (Phase 2h, commit `b2a98e25`) and the 2g xxe predecessor.
    fn scan_python_file_dual_branch(&self, path: &Path, content: &str) -> Vec<Finding> {
        if content.contains('\0') {
            return Vec::new();
        }
        let Some(tree) = crate::detectors::ast_fingerprint::parse_root_ext(
            content,
            crate::parsers::lightweight::Language::Python,
            "py",
        ) else {
            return Vec::new();
        };
        let root = tree.root_node();
        let source = content.as_bytes();
        let lines: Vec<&str> = content.lines().collect();

        let mut findings = Vec::new();
        for site in evidence::collect_python_nosql_sites(root, source) {
            let line_idx = site.call_node.start_position().row;

            // Honor `# repotoire: ignore` / inline suppressions same
            // as the legacy path. Without this, users who suppressed
            // the legacy finding would see a new dual-branch finding
            // appear when they flip the flag on — a regression.
            if let Some(line) = lines.get(line_idx) {
                let prev = if line_idx > 0 {
                    Some(lines[line_idx - 1])
                } else {
                    None
                };
                if crate::detectors::is_line_suppressed(line, prev) {
                    continue;
                }
            }

            let snippet = lines.get(line_idx).map(|s| s.trim()).unwrap_or("");
            let line_num = (line_idx + 1) as u32;

            findings.push(self.build_dual_branch_finding(
                path,
                line_num,
                site.api,
                site.callee_label.clone(),
                snippet,
                site.call_node,
                root,
                source,
                &lines,
            ));
        }
        findings
    }

    /// Build a dual-branch Finding for a single Python pymongo call site.
    ///
    /// Mirrors `insecure_deserialize::build_dual_branch_finding`
    /// (Phase 2h): pull evidence, run the predictor, pick a
    /// title/description/fix per branch label, attach the alternative
    /// branch + every prediction reason + every resolution signal.
    /// The result is a single `Finding` with the dual-branch shape that
    /// `--show-alternatives` knows how to render.
    #[allow(clippy::too_many_arguments)]
    fn build_dual_branch_finding(
        &self,
        path: &Path,
        line_num: u32,
        api: predict::NosqlApi,
        callee_label: String,
        snippet: &str,
        call_node: tree_sitter::Node<'_>,
        module_root: tree_sitter::Node<'_>,
        source: &[u8],
        lines: &[&str],
    ) -> Finding {
        let file_path_str = path.to_string_lossy().to_string();
        let ev = evidence::extract_python_evidence(
            call_node,
            module_root,
            source,
            lines,
            Some(file_path_str),
            api,
            callee_label.clone(),
        );
        let prediction = predict::predict(&ev);

        let predicted_label = prediction.predicted;
        let predicted_severity = prediction.predicted_severity;
        let predicted_title = match predicted_label {
            crate::dual_branch::BranchLabel::RealBug => {
                format!("Potential NoSQL injection via `{callee_label}`")
            }
            crate::dual_branch::BranchLabel::Benign => {
                format!("Safe pymongo query via `{callee_label}` (informational)")
            }
        };
        let predicted_description = format!(
            "**NoSQL Injection (dual-branch, CWE-943)**\n\n\
             **API**: `{}`\n\n\
             **Location**: {}:{}\n\n\
             **Code**:\n```python\n{}\n```\n\n\
             {}",
            callee_label,
            path.display(),
            line_num,
            snippet,
            match predicted_label {
                crate::dual_branch::BranchLabel::RealBug => format!(
                    "The `{callee_label}` call site appears to construct a \
                     MongoDB query with attacker-reachable input flowing \
                     into a dangerous server-side operator (`$where` / \
                     `$function` / `$expr` / `$accumulator`), via dict-\
                     expansion of raw user input, or under weighted \
                     signals indicating operator-injection exposure. \
                     The predictor leans RealBug (see `prediction_reasons`)."
                ),
                crate::dual_branch::BranchLabel::Benign => format!(
                    "The `{callee_label}` call site appears to use a \
                     structurally-typed pymongo query (no dangerous \
                     operators, no `**`-expansion, user-input values \
                     cast via `str` / `ObjectId` / `int` / pydantic), \
                     or developer-written operator filters without user \
                     input. The predictor leans Benign (see \
                     `prediction_reasons`); the alternative RealBug \
                     interpretation is carried in `alternative_branch` \
                     for users who want to inspect the call regardless."
                ),
            },
        );
        let predicted_fix = match predicted_label {
            crate::dual_branch::BranchLabel::RealBug => Some(
                "Sanitize the MongoDB query construction:\n\
                 ```python\n\
                 # Instead of:\n\
                 users.find_one({\"$where\": f\"this.name=='{req.form['n']}'\"})\n\
                 users.find_one({**request.get_json()})\n\
                 \n\
                 # Use typed-value queries:\n\
                 users.find_one({\"name\": str(request.form['n'])})\n\
                 users.find_one({\"_id\": ObjectId(request.form['id'])})\n\
                 \n\
                 # Or pydantic-validate the payload first:\n\
                 class Query(BaseModel):\n\
                 \x20   name: str\n\
                 q = Query.model_validate(request.get_json())\n\
                 users.find_one({\"name\": q.name})\n\
                 ```\n\n\
                 If the call is intentionally constructing a complex \
                 query that the predictor cannot trace (cross-statement \
                 assembly, helper-built filter, etc.), annotate the call \
                 site with `# repotoire: nosql-safe[<reason>]` to collapse \
                 the finding to Info."
                    .to_string(),
            ),
            crate::dual_branch::BranchLabel::Benign => Some(
                "If you need the predictor to surface this site (e.g. \
                 you're auditing every pymongo query regardless), \
                 annotate the line with \
                 `# repotoire: nosql-vulnerable[<source>]` where \
                 `<source>` is the rationale (e.g. \
                 `helper-assembled-query`)."
                    .to_string(),
            ),
        };

        let mut finding = Finding {
            id: String::new(),
            detector: "NosqlInjectionDetector".to_string(),
            severity: predicted_severity,
            title: predicted_title,
            description: predicted_description,
            affected_files: vec![path.to_path_buf()],
            line_start: Some(line_num),
            line_end: Some(line_num),
            suggested_fix: predicted_fix,
            estimated_effort: Some("30 minutes".to_string()),
            category: Some("security".to_string()),
            cwe_id: Some("CWE-943".to_string()),
            why_it_matters: Some(
                "NoSQL injection can allow attackers to:\n\
                 • Bypass authentication ({ password: { $ne: '' } })\n\
                 • Extract data through $regex probing\n\
                 • Execute arbitrary JavaScript ($where)\n\
                 • Denial of service through ReDoS"
                    .to_string(),
            ),
            ..Default::default()
        };

        finding = finding.with_alternative_branch(prediction.alternative_branch);
        for reason in prediction.reasons {
            finding = finding.with_prediction_reason(reason);
        }
        for resolution in prediction.resolutions {
            finding = finding.with_resolution_signal(resolution);
        }
        finding
    }
}

impl Detector for NosqlInjectionDetector {
    fn name(&self) -> &'static str {
        "nosql-injection"
    }
    fn description(&self) -> &'static str {
        "Detects NoSQL injection risks"
    }

    fn bypass_postprocessor(&self) -> bool {
        true
    }

    crate::detectors::impl_taint_precompute!();

    fn taint_category(&self) -> Option<crate::detectors::taint::TaintCategory> {
        Some(crate::detectors::taint::TaintCategory::SqlInjection)
    }

    fn file_extensions(&self) -> &'static [&'static str] {
        &["py", "js", "ts", "jsx", "tsx", "rb", "php", "java", "go"]
    }

    fn content_requirements(&self) -> crate::detectors::detector_context::ContentFlags {
        crate::detectors::detector_context::ContentFlags::HAS_SQL
    }

    fn detect(
        &self,
        ctx: &crate::detectors::analysis_context::AnalysisContext,
    ) -> Result<Vec<Finding>> {
        let graph = ctx.graph;
        let files = &ctx.as_file_provider();
        let mut findings = vec![];

        // Phase 2i dual-branch gate. When `true`, Python `.py` files
        // go through the AST-driven predictor path
        // (`scan_python_file_dual_branch`) and skip the legacy line
        // scanner. Other languages and the flag-off path are
        // unchanged. Symmetric with insecure-deserialize (Phase 2h),
        // xxe (Phase 2g), command-injection.
        let flag_on = ctx.dual_branch.is_enabled_for("nosql-injection");

        for path in files.files_with_extensions(&["js", "ts", "py", "rb", "php"]) {
            if findings.len() >= self.max_findings {
                break;
            }

            let path_str = path.to_string_lossy().to_string();

            // Skip test files
            if crate::detectors::base::is_test_path(&path_str) {
                continue;
            }

            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");

            // Phase 2i: AST-driven predictor path for Python when the
            // dual-branch flag is on. Replaces the legacy regex pass
            // for `.py` files; other languages and the flag-off path
            // fall through to the regex scanner below.
            if flag_on && ext == "py" {
                if let Some(content) = files.content(path) {
                    let dual = self.scan_python_file_dual_branch(path, &content);
                    for finding in dual {
                        findings.push(finding);
                        if findings.len() >= self.max_findings {
                            break;
                        }
                    }
                }
                continue;
            }

            if let Some(content) = files.content(path) {
                let lines: Vec<&str> = content.lines().collect();

                // Check if file has MongoDB context
                let has_mongo = content.contains("mongoose")
                    || content.contains("mongodb")
                    || content.contains("MongoClient")
                    || content.contains("pymongo")
                    || content.contains("Collection");

                if !has_mongo {
                    continue;
                }

                for (i, line) in lines.iter().enumerate() {
                    let prev_line = if i > 0 { Some(lines[i - 1]) } else { None };
                    if crate::detectors::is_line_suppressed(line, prev_line) {
                        continue;
                    }

                    if !NOSQL_PATTERN.is_match(line) {
                        continue;
                    }
                    if Self::is_array_method(line) {
                        continue;
                    }

                    // Check for user input
                    let has_input = USER_INPUT.is_match(line);
                    let start = i.saturating_sub(5);
                    let context = lines[start..i].join(" ");
                    let has_input_nearby = USER_INPUT.is_match(&context);

                    if !has_input && !has_input_nearby {
                        continue;
                    }

                    // Check for sanitization
                    let is_sanitized = Self::has_sanitization(&lines, i);
                    if is_sanitized {
                        continue;
                    }

                    // Check for dangerous operators
                    let has_dangerous = DANGEROUS_OPS.is_match(line);
                    let (risk_type, risk_desc) = categorize_risk(line);

                    // Get function context
                    let containing_func =
                        graph.find_function_at(&path_str, (i + 1) as u32).map(|f| {
                            let callers = graph
                                .get_callers(f.qn(crate::graph::interner::global_interner()))
                                .len();
                            (
                                f.node_name(crate::graph::interner::global_interner())
                                    .to_string(),
                                callers,
                            )
                        });
                    let is_handler = containing_func
                        .as_ref()
                        .map(|(name, _)| Self::is_route_handler(name, &path_str))
                        .unwrap_or(false);

                    // Calculate severity
                    let severity = if has_dangerous || (is_handler && has_input) {
                        Severity::Critical // dangerous operator or direct user input in route handler
                    } else if has_input {
                        Severity::High
                    } else {
                        Severity::Medium
                    };

                    // Build notes
                    let mut notes = Vec::new();
                    notes.push(format!("🔍 Risk type: {}", risk_desc));
                    if has_dangerous {
                        notes.push("⚠️ Uses dangerous operator".to_string());
                    }
                    if is_handler {
                        notes.push("🌐 In route handler (direct user input)".to_string());
                    }
                    if let Some((func_name, callers)) = &containing_func {
                        notes.push(format!(
                            "📦 In function: `{}` ({} callers)",
                            func_name, callers
                        ));
                    }

                    let context_notes = format!("\n\n**Analysis:**\n{}", notes.join("\n"));

                    let suggestion = match risk_type {
                        "where" =>
                            "**Never use $where with user input** - it executes JavaScript.\n\n\
                             ```javascript\n\
                             // Instead of:\n\
                             db.users.find({ $where: `this.name == '${userInput}'` });\n\
                             \n\
                             // Use:\n\
                             db.users.find({ name: userInput });  // Still sanitize!\n\
                             ```".to_string(),
                        "regex" =>
                            "Escape regex special characters or use literal match:\n\n\
                             ```javascript\n\
                             // Escape regex\n\
                             const escaped = userInput.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\
                             db.users.find({ name: { $regex: escaped } });\n\
                             \n\
                             // Or use literal string match when possible\n\
                             db.users.find({ name: userInput });\n\
                             ```".to_string(),
                        "operator" =>
                            "Prevent operator injection by validating input types:\n\n\
                             ```javascript\n\
                             // User could send: { \"$ne\": \"\" } to bypass auth\n\
                             // Always validate/convert to expected type:\n\
                             const username = String(req.body.username);\n\
                             const password = String(req.body.password);\n\
                             \n\
                             // Or use mongo-sanitize\n\
                             const sanitize = require('mongo-sanitize');\n\
                             db.users.find({ username: sanitize(req.body.username) });\n\
                             ```".to_string(),
                        _ =>
                            "Sanitize all user input before using in queries:\n\n\
                             ```javascript\n\
                             const sanitize = require('mongo-sanitize');\n\
                             const cleanInput = sanitize(req.body);\n\
                             db.collection.find(cleanInput);\n\
                             ```".to_string(),
                    };

                    findings.push(Finding {
                        id: String::new(),
                        detector: "NosqlInjectionDetector".to_string(),
                        severity,
                        title: format!("NoSQL injection: {}", risk_desc),
                        description: format!(
                            "MongoDB query with user-controlled input can be exploited.{}",
                            context_notes
                        ),
                        affected_files: vec![path.to_path_buf()],
                        line_start: Some((i + 1) as u32),
                        line_end: Some((i + 1) as u32),
                        suggested_fix: Some(suggestion),
                        estimated_effort: Some("30 minutes".to_string()),
                        category: Some("security".to_string()),
                        cwe_id: Some("CWE-943".to_string()),
                        why_it_matters: Some(
                            "NoSQL injection can allow attackers to:\n\
                             • Bypass authentication ({ password: { $ne: '' } })\n\
                             • Extract data through $regex probing\n\
                             • Execute arbitrary JavaScript ($where)\n\
                             • Denial of service through ReDoS"
                                .to_string(),
                        ),
                        ..Default::default()
                    });
                }
            }
        }

        // Supplement with intra-function taint analysis (precomputed or fallback).
        //
        // The live analyzer is extended with MongoDB-specific query methods as
        // sinks for the SqlInjection category, so the heuristic engine can match
        // them. They are intentionally NOT in the shared `add_sql_patterns` list
        // (which treats `findOne`/`findById` as ORM sanitizers); this detector
        // owns the NoSQL query terminus classification.
        // The centralized taint engine (which pre-populates `precomputed_intra`)
        // uses the default `TaintAnalyzer` — it does NOT include MongoDB query
        // methods as sinks (those methods are actually listed as SQL *sanitizers*
        // in the shared patterns, to suppress false positives for ORM calls). So
        // we always run a dedicated MongoDB-aware analyzer here, regardless of
        // whether precomputed results exist.
        //
        // This is intentionally NOT the `if precomputed else live` pattern used by
        // other taint detectors: those detectors share the centralized sink catalog,
        // but our sinks (findOne, aggregate, etc.) are NoSQL-specific and absent
        // from that catalog. We DO still fold in `precomputed_intra` when present —
        // the centralized engine may have produced paths that are relevant here, and
        // tests inject paths through that hook (`set_precomputed_taint`) — but we
        // always additionally run the MongoDB-aware analyzer below.
        let mut taint_analyzer = crate::detectors::taint::TaintAnalyzer::new();
        for method in NOSQL_QUERY_METHODS {
            // Add as sink so the heuristic engine can match it.
            taint_analyzer.add_sink(
                crate::detectors::taint::TaintCategory::SqlInjection,
                method.to_string(),
            );
            // Remove from sanitizers: the shared SQL patterns include `findOne`
            // and `findById` as ORM sanitizers, which would prevent the sink-match
            // step from firing on assignment lines containing these calls.
            taint_analyzer
                .remove_sanitizer(crate::detectors::taint::TaintCategory::SqlInjection, method);
        }
        let mut intra_paths = crate::detectors::taint::run_intra_function_taint(
            &taint_analyzer,
            graph,
            crate::detectors::taint::TaintCategory::SqlInjection,
            &self.repository_path,
        );
        if let Some(precomputed) = self.precomputed_intra.get() {
            intra_paths.extend(precomputed.iter().cloned());
        }
        // Build a map from (file, sink_line) → index in `findings` for the
        // line-heuristic results so SSA taint paths can upgrade them in-place.
        let mut loc_to_idx: std::collections::HashMap<(String, u32), usize> = findings
            .iter()
            .enumerate()
            .filter_map(|(i, f)| {
                f.affected_files.first().map(|p| {
                    (
                        (p.to_string_lossy().to_string(), f.line_start.unwrap_or(0)),
                        i,
                    )
                })
            })
            .collect();
        let mut seen: std::collections::HashSet<(String, u32)> =
            loc_to_idx.keys().cloned().collect();
        for path in intra_paths.iter().filter(|p| !p.is_sanitized) {
            let loc = (path.sink_file.clone(), path.sink_line);
            let is_nosql_sink = classify_nosql_sink(&path.sink_callee_text).is_some();

            if let Some(&idx) = loc_to_idx.get(&loc) {
                // A line-heuristic finding already exists at this location.
                // If the SSA taint path identifies this as a known NoSQL sink,
                // upgrade the existing Advisory finding to Blocking in-place —
                // rather than dropping the SSA evidence entirely.
                if is_nosql_sink {
                    let f = &mut findings[idx];
                    f.tier = Tier::Blocking;
                    f.deterministic = true;
                    f.confidence = Some(0.95);
                    f.evidence = Some(Evidence::TaintPath {
                        source: SourceSpan {
                            file: PathBuf::from(&path.source_file),
                            line_start: path.source_line,
                            line_end: path.source_line,
                            snippet: None,
                        },
                        sink: SourceSpan {
                            file: PathBuf::from(&path.sink_file),
                            line_start: path.sink_line,
                            line_end: path.sink_line,
                            snippet: None,
                        },
                        sink_kind: SinkKind::NosqlQuery.as_str().to_string(),
                        flow: vec![],
                        sanitizers_seen: path.sanitizers_on_path.clone(),
                    });
                }
                continue;
            }

            if !seen.insert(loc.clone()) {
                continue;
            }

            let mut finding = crate::detectors::taint::taint_path_to_finding(
                path,
                "NosqlInjectionDetector",
                "NoSQL Injection",
            );
            // Gate on the sink being a known NoSQL query method. We do NOT additionally
            // gate on `sanitizers_on_path.is_empty()` because the intra-function heuristic
            // engine reports only `is_sanitized: bool` — `sanitizers_on_path` is always
            // empty for intra paths even when sanitized, so `is_sanitized` is the
            // authoritative signal (already filtered above).
            if is_nosql_sink {
                finding.tier = Tier::Blocking;
                finding.deterministic = true;
                finding.confidence = Some(0.95);
                finding.evidence = Some(Evidence::TaintPath {
                    source: SourceSpan {
                        file: PathBuf::from(&path.source_file),
                        line_start: path.source_line,
                        line_end: path.source_line,
                        snippet: None,
                    },
                    sink: SourceSpan {
                        file: PathBuf::from(&path.sink_file),
                        line_start: path.sink_line,
                        line_end: path.sink_line,
                        snippet: None,
                    },
                    sink_kind: SinkKind::NosqlQuery.as_str().to_string(),
                    flow: vec![],
                    sanitizers_seen: path.sanitizers_on_path.clone(),
                });
            }
            loc_to_idx.insert(loc, findings.len());
            findings.push(finding);
            if findings.len() >= self.max_findings {
                break;
            }
        }

        info!(
            "NosqlInjectionDetector found {} findings (graph-aware + taint)",
            findings.len()
        );
        Ok(findings)
    }
}

impl crate::detectors::RegisteredDetector for NosqlInjectionDetector {
    fn create(init: &crate::detectors::DetectorInit) -> std::sync::Arc<dyn Detector> {
        std::sync::Arc::new(Self::new(init.repo_path))
    }

    fn max_tier() -> crate::models::Tier {
        crate::models::Tier::Blocking
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::builder::GraphBuilder;

    #[test]
    fn test_detects_where_with_user_input() {
        let store = GraphBuilder::new().freeze();
        let detector = NosqlInjectionDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("routes.js", "const mongoose = require('mongoose');\nconst User = mongoose.model('User');\n\nasync function findUser(req, res) {\n    const name = req.body.name;\n    const result = await User.find({ $where: `this.name == '${name}'` });\n    res.json(result);\n}\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect $where with user input from req.body"
        );
        assert!(
            findings.iter().any(|f| f.title.contains("$where")),
            "Finding should mention $where. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_safe_query() {
        let store = GraphBuilder::new().freeze();
        let detector = NosqlInjectionDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("routes.js", "const mongoose = require('mongoose');\nconst User = mongoose.model('User');\n\nasync function findUser() {\n    const result = await User.find({ active: true });\n    return result;\n}\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Safe MongoDB query without user input should produce no findings, but got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_detects_find_with_req_body_in_js() {
        let store = GraphBuilder::new().freeze();
        let detector = NosqlInjectionDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("controller.js", "const mongoose = require('mongoose');\nconst User = mongoose.model('User');\n\nasync function login(req, res) {\n    const user = await User.findOne(req.body);\n    if (user) res.json(user);\n}\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect MongoDB findOne with unsanitized req.body"
        );
        assert!(
            findings
                .iter()
                .any(|f| f.cwe_id.as_deref() == Some("CWE-943")),
            "Finding should have CWE-943"
        );
    }

    #[test]
    fn test_detects_aggregate_with_user_input_ts() {
        let store = GraphBuilder::new().freeze();
        let detector = NosqlInjectionDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("analytics.ts", "import mongoose from 'mongoose';\nconst Order = mongoose.model('Order');\n\nasync function getStats(req: Request, res: Response) {\n    const pipeline = req.body.pipeline;\n    const results = await Order.aggregate(req.body.pipeline);\n    res.json(results);\n}\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect MongoDB aggregate with user-controlled pipeline from req.body"
        );
    }

    #[test]
    fn test_no_finding_for_sanitized_query() {
        let store = GraphBuilder::new().freeze();
        let detector = NosqlInjectionDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("safe_controller.js", "const mongoose = require('mongoose');\nconst sanitize = require('mongo-sanitize');\nconst User = mongoose.model('User');\n\nasync function login(req, res) {\n    const clean = sanitize(req.body);\n    const user = await User.findOne(clean);\n    res.json(user);\n}\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Sanitized MongoDB query should not produce findings, but got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_array_find() {
        let store = GraphBuilder::new().freeze();
        let detector = NosqlInjectionDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("utils.js", "const mongoose = require('mongoose');\n\nfunction findItem(items, id) {\n    return items.find(item => item.id === id);\n}\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Array.find() should not be flagged as NoSQL injection, but got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    // ─────────────────────────────────────────────────────────────────
    // Phase 2i dual-branch integration tests.
    //
    // Mirror insecure-deserialize's flag-off / flag-on pattern (Phase 2h):
    //
    //   1. flag_off_nosql_injection_emits_single_branch_unchanged
    //   2. flag_on_case_a_unstructured_json_in_handler_realbug_high
    //   3. flag_on_case_b_typed_query_str_cast_collapses_benign
    //   4. flag_on_case_c_where_with_user_input_collapses_realbug_critical
    //   5. flag_on_case_d_developer_written_ne_predicts_benign  (FP fix)
    //   6. flag_on_case_e_dict_expansion_collapses_realbug_critical
    //   7. flag_on_case_f_objectid_cast_typed_query_collapses_benign
    //   8. flag_on_nosql_safe_annotation_collapses_benign
    //   9. flag_on_nosql_vulnerable_annotation_collapses_realbug
    //  10. flag_on_non_python_unchanged_per_d5_scope
    // ─────────────────────────────────────────────────────────────────

    fn run_dual_branch(file: &str, content: &str) -> Vec<Finding> {
        use crate::config::DualBranchConfig;
        use std::collections::HashMap;

        let store = GraphBuilder::new().freeze();
        let detector = NosqlInjectionDetector::new("/mock/repo");
        let mut detectors = HashMap::new();
        detectors.insert("nosql-injection".to_string(), true);
        let cfg = DualBranchConfig {
            enabled: true,
            detectors,
        };
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(file, content)],
        )
        .with_dual_branch(cfg);
        detector.detect(&ctx).expect("detection should succeed")
    }

    #[test]
    fn flag_off_nosql_injection_emits_single_branch_unchanged() {
        // Sanity: with flag off (default), Python pymongo sites emit
        // no `alternative_branch` and no predictor-contributed
        // (weight ≠ 0) reasons. Pins the opt-in promise — flipping
        // the flag must not change byte-output for users who haven't
        // turned it on.
        let store = GraphBuilder::new().freeze();
        let detector = NosqlInjectionDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "vuln.py",
                "import pymongo\n\
                 from flask import request\n\
                 def handler():\n\
                 \x20   users = pymongo.MongoClient().db.users\n\
                 \x20   return users.find_one({\"$where\": f\"this.x == '{request.form['x']}'\"})\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        for f in &findings {
            assert!(
                f.alternative_branch.is_none(),
                "no alternative_branch when flag off: {:?}",
                f.title
            );
            assert!(
                f.prediction_reasons.iter().all(|r| r.weight == 0.0),
                "no weight-bearing predictor reasons when flag off; \
                 graph-enrichment weight-0 reasons are allowed. reasons: {:?}",
                f.prediction_reasons
                    .iter()
                    .map(|r| (&r.kind, r.weight))
                    .collect::<Vec<_>>()
            );
        }
    }

    #[test]
    fn flag_on_case_a_unstructured_json_in_handler_realbug_high() {
        // Case A from decisions §6: users.find_one with request.json
        // (UnstructuredJson source) inside a route handler. The
        // operator-injection vector is present even without explicit
        // `$where` because pymongo will faithfully serialize any dict
        // value as a query operator. Expected: RealBug High (weighted
        // -0.30 - 0.20 = -0.50).
        //
        // Note: we inline `request.get_json()["user"]` directly in the
        // dict value rather than going through an intermediate variable
        // — the v0 evidence extractor's typed-value-query classifier
        // only inspects each dict value's text for user-input
        // substrings (D5.3 cross-statement-flow limitation). When the
        // user-input identifier is the immediate value expression, the
        // dict-value scan correctly reclassifies the query as
        // Ambiguous → weighted scoring fires → -0.30 (UnstructuredJson)
        // - 0.20 (handler) = -0.50 → RealBug High.
        let findings = run_dual_branch(
            "case_a.py",
            "import pymongo\n\
             from flask import request\n\
             @app.route('/login', methods=['POST'])\n\
             def login_handler():\n\
             \x20   users = pymongo.MongoClient().db.users\n\
             \x20   return users.find_one({\"username\": request.get_json()[\"user\"], \"password\": request.get_json()[\"pw\"]})\n",
        );
        let f = findings
            .iter()
            .find(|f| f.is_dual_branch())
            .expect("must have a dual-branch finding for Case A");
        assert_eq!(
            f.severity,
            Severity::High,
            "Case A: UnstructuredJson + handler should weight to High; got {:?}, reasons={:?}",
            f.severity,
            f.prediction_reasons
                .iter()
                .map(|r| (&r.kind, r.weight))
                .collect::<Vec<_>>()
        );
        let alt = f.alternative_branch.as_ref().unwrap();
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::Benign);
    }

    #[test]
    fn flag_on_case_b_typed_query_str_cast_collapses_benign() {
        // Case B from decisions §6: str() cast on request.form value.
        // Should classify as TypedValueQuery → D1.a Benign collapse → Info.
        let findings = run_dual_branch(
            "case_b.py",
            "import pymongo\n\
             from flask import request\n\
             def login():\n\
             \x20   users = pymongo.MongoClient().db.users\n\
             \x20   return users.find_one({\"username\": str(request.form[\"user\"])})\n",
        );
        let f = findings
            .iter()
            .find(|f| f.is_dual_branch())
            .expect("must have a dual-branch finding for Case B");
        assert_eq!(
            f.severity,
            Severity::Info,
            "Case B: TypedValueQuery must collapse to Benign Info; got {:?}",
            f.severity
        );
        let alt = f.alternative_branch.as_ref().unwrap();
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::RealBug);
    }

    #[test]
    fn flag_on_case_c_where_with_user_input_collapses_realbug_critical() {
        // Case C from decisions §6: $where with f-string interpolation
        // of user input. Should classify as OperatorInjection → D1.b
        // RealBug collapse → Critical.
        let findings = run_dual_branch(
            "case_c.py",
            "import pymongo\n\
             from flask import request\n\
             def login_handler():\n\
             \x20   users = pymongo.MongoClient().db.users\n\
             \x20   return users.find_one({\"$where\": f\"this.username == '{request.form['user']}'\"})\n",
        );
        let f = findings
            .iter()
            .find(|f| f.is_dual_branch())
            .expect("must have a dual-branch finding for Case C");
        assert_eq!(
            f.severity,
            Severity::Critical,
            "Case C: OperatorInjection ($where) must collapse to RealBug Critical; got {:?}",
            f.severity
        );
        let alt = f.alternative_branch.as_ref().unwrap();
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::Benign);
    }

    #[test]
    fn flag_on_case_d_developer_written_ne_predicts_benign() {
        // Case D from decisions §6 (THE HEADLINE FP REDUCTION):
        // developer-written $ne operator with no user input. The legacy
        // line scanner fires on $ne; the dual-branch predictor recognizes
        // this is a normal MongoDB query and collapses to Benign Info.
        let findings = run_dual_branch(
            "case_d.py",
            "import pymongo\n\
             def list_non_admins():\n\
             \x20   users = pymongo.MongoClient().db.users\n\
             \x20   return list(users.find({\"role\": {\"$ne\": \"admin\"}}))\n",
        );
        let f = findings
            .iter()
            .find(|f| f.is_dual_branch())
            .expect("must have a dual-branch finding for Case D");
        assert_eq!(
            f.severity,
            Severity::Info,
            "Case D (FP fix): developer-written $ne with no user input \
             must predict Benign Info; got {:?}, reasons={:?}",
            f.severity,
            f.prediction_reasons
                .iter()
                .map(|r| (&r.kind, r.weight))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn flag_on_case_e_dict_expansion_collapses_realbug_critical() {
        // Case E from decisions §6: `**request.get_json()` expansion.
        // Attacker controls every key — textbook NoSQL auth-bypass.
        // Should classify as DictExpansion → D1.c RealBug collapse → Critical.
        let findings = run_dual_branch(
            "case_e.py",
            "import pymongo\n\
             from flask import request\n\
             @app.route('/find', methods=['POST'])\n\
             def find_handler():\n\
             \x20   users = pymongo.MongoClient().db.users\n\
             \x20   return users.find_one({**request.get_json()})\n",
        );
        let f = findings
            .iter()
            .find(|f| f.is_dual_branch())
            .expect("must have a dual-branch finding for Case E");
        assert_eq!(
            f.severity,
            Severity::Critical,
            "Case E: DictExpansion of request.get_json() must collapse to RealBug Critical; got {:?}",
            f.severity
        );
    }

    #[test]
    fn flag_on_case_f_objectid_cast_typed_query_collapses_benign() {
        // Case F from decisions §6: ObjectId() cast on user input.
        // ObjectId raises if the input isn't a valid 24-hex string —
        // structural type narrowing → TypedValueQuery → Benign collapse.
        let findings = run_dual_branch(
            "case_f.py",
            "import pymongo\n\
             from bson import ObjectId\n\
             from flask import request\n\
             def get_user():\n\
             \x20   users = pymongo.MongoClient().db.users\n\
             \x20   return users.find_one({\"_id\": ObjectId(request.form['id'])})\n",
        );
        let f = findings
            .iter()
            .find(|f| f.is_dual_branch())
            .expect("must have a dual-branch finding for Case F");
        assert_eq!(
            f.severity,
            Severity::Info,
            "Case F: ObjectId cast typed-value query must collapse to Benign Info; got {:?}",
            f.severity
        );
    }

    #[test]
    fn flag_on_nosql_safe_annotation_collapses_benign() {
        // Annotation > Step-1.5: $where with annotation → Benign Info.
        let findings = run_dual_branch(
            "annotated.py",
            "import pymongo\n\
             def f():\n\
             \x20   users = pymongo.MongoClient().db.users\n\
             \x20   return users.find_one({\"$where\": \"this.role == 'admin'\"})  # repotoire: nosql-safe[admin-literal]\n",
        );
        let f = findings
            .iter()
            .find(|f| f.is_dual_branch())
            .expect("must have a dual-branch finding (annotated)");
        assert_eq!(f.severity, Severity::Info);
        let alt = f.alternative_branch.as_ref().unwrap();
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::RealBug);
    }

    #[test]
    fn flag_on_nosql_vulnerable_annotation_collapses_realbug() {
        // Annotation > Step-1.5: TypedValueQuery with nosql-vulnerable
        // annotation → RealBug Critical.
        let findings = run_dual_branch(
            "annotated.py",
            "import pymongo\n\
             def f(q):\n\
             \x20   users = pymongo.MongoClient().db.users\n\
             \x20   return users.find_one({\"name\": \"alice\"})  # repotoire: nosql-vulnerable[helper-assembled]\n",
        );
        let f = findings
            .iter()
            .find(|f| f.is_dual_branch())
            .expect("must have a dual-branch finding (vuln annotated)");
        assert_eq!(f.severity, Severity::Critical);
        let alt = f.alternative_branch.as_ref().unwrap();
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::Benign);
    }

    #[test]
    fn flag_on_non_python_unchanged_per_d5_scope() {
        // D5.1 scope: Non-Python files go through the legacy regex
        // scanner regardless of the flag. Mongoose / pymongo-via-JS
        // sites still fire single-branch (no `alternative_branch`).
        let findings = run_dual_branch(
            "routes.js",
            "const mongoose = require('mongoose');\n\
             const User = mongoose.model('User');\n\
             async function findUser(req, res) {\n\
             \x20   const name = req.body.name;\n\
             \x20   const result = await User.find({ $where: `this.name == '${name}'` });\n\
             \x20   res.json(result);\n\
             }\n",
        );
        assert!(!findings.is_empty(), "JS still fires legacy scan");
        for f in &findings {
            assert!(
                f.alternative_branch.is_none(),
                "no dual-branch shape for non-Python: {:?}",
                f.title
            );
        }
    }

    // ─────────────────────────────────────────────────────────────────
    // Phase 2i real-world signature pins.
    //
    // Pin the predictor's verdicts against minimized-but-realistic
    // shapes from real Python codebases. Mirrors the 2e/2f/2g/2h real-
    // world tests: catch the day when an evidence-extractor refactor
    // accidentally breaks a known-correct verdict on a real-world
    // idiom.
    //
    // Four signatures pinned (per decisions doc §6 worked examples
    // and §4 architectural framing as the FP-reduction phase):
    //
    //   1. `real_typed_pymongo_login` — the canonical Flask login
    //      shape where the dev cast `request.form` via `str(...)`.
    //      Must Benign Info via D1.a TypedValueQuery collapse.
    //   2. `real_naked_request_json_query` — `**request.get_json()`
    //      expansion. The textbook auth-bypass shape from every
    //      OWASP MongoDB cheat-sheet writeup. Must RealBug Critical
    //      via D1.c DictExpansion collapse.
    //   3. `real_where_clause_with_user_input` — f-string of user
    //      input interpolated into `$where`. The classic CWE-943
    //      RCE shape (mongo-express, Rocket.Chat historical CVEs).
    //      Must RealBug Critical via D1.b OperatorInjection collapse.
    //   4. `real_developer_written_ne_operator` — developer-written
    //      `$ne` query with literal value, no user input. The
    //      headline FP-reduction case for Phase 2i. The legacy line
    //      scanner flags this as a Medium operator-injection finding;
    //      the dual-branch predictor correctly classifies it as
    //      Benign Info.
    //
    // The shapes are simplified to fit a single-file mock context.
    // The minimization is documented inline so a future contributor
    // can re-validate against upstream when the API drifts.
    // Citations point to upstream tutorials / OWASP guidance the
    // shape was distilled from.
    // ─────────────────────────────────────────────────────────────────

    #[test]
    fn real_typed_pymongo_login() {
        // Real shape from Flask-PyMongo tutorials and the
        // pymongo "Authentication Tutorial" page. Excerpt:
        //
        //   from flask import Flask, request
        //   from pymongo import MongoClient
        //   app = Flask(__name__)
        //   users = MongoClient().db.users
        //   @app.route('/login', methods=['POST'])
        //   def login():
        //       user = users.find_one({"username": str(request.form["user"])})
        //       return jsonify({"ok": user is not None})
        //
        // `request.form` is the Flask werkzeug-MultiDict which returns
        // Python `str` (TypedString source). The developer additionally
        // wraps in `str(...)` — defensive, but the dual cast doesn't
        // hurt. pymongo serializes a Python `str` to BSON String; there
        // is no operator-interpretation path. The query is safe by
        // structural construction.
        //
        // D1.a TypedValueQuery collapse must fire: Benign Info.
        let findings = run_dual_branch(
            "real_flask_login.py",
            "from flask import Flask, request\n\
             from pymongo import MongoClient\n\
             app = Flask(__name__)\n\
             users = MongoClient().db.users\n\
             @app.route('/login', methods=['POST'])\n\
             def login():\n\
             \x20   user = users.find_one({\"username\": str(request.form[\"user\"])})\n\
             \x20   return {\"ok\": user is not None}\n",
        );
        let f = findings
            .iter()
            .find(|f| f.is_dual_branch())
            .expect("dual-branch finding expected for typed pymongo login");
        assert_eq!(
            f.severity,
            Severity::Info,
            "str(request.form[...]) is a TypedValueQuery — must collapse \
             to Benign Info via D1.a even with @app.route handler signal; \
             got {:?}, reasons={:?}",
            f.severity,
            f.prediction_reasons
                .iter()
                .map(|r| (&r.kind, r.weight))
                .collect::<Vec<_>>()
        );
        let alt = f.alternative_branch.as_ref().unwrap();
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::RealBug);
    }

    #[test]
    fn real_naked_request_json_query() {
        // Real shape from the OWASP MongoDB Cheat Sheet's "NoSQL
        // Injection — Operator Injection" worked example, also the
        // shape mongo-express historically shipped (CVE-2019-10758
        // family). Excerpt:
        //
        //   from flask import Flask, request
        //   from pymongo import MongoClient
        //   app = Flask(__name__)
        //   users = MongoClient().db.users
        //   @app.route('/find', methods=['POST'])
        //   def find():
        //       return users.find_one({**request.get_json()})
        //
        // The `**`-expansion of `request.get_json()` into the query
        // dict gives the attacker total control over every key/value.
        // The textbook auth-bypass payload `{"username": {"$ne": null}}`
        // bypasses login when the developer expects `{"username": "alice"}`.
        //
        // D1.c DictExpansion collapse must fire: RealBug Critical.
        let findings = run_dual_branch(
            "real_naked_json_query.py",
            "from flask import Flask, request\n\
             from pymongo import MongoClient\n\
             app = Flask(__name__)\n\
             users = MongoClient().db.users\n\
             @app.route('/find', methods=['POST'])\n\
             def find():\n\
             \x20   return users.find_one({**request.get_json()})\n",
        );
        let f = findings
            .iter()
            .find(|f| f.is_dual_branch())
            .expect("dual-branch finding expected for **request.get_json()");
        assert_eq!(
            f.severity,
            Severity::Critical,
            "{{**request.get_json()}} is a DictExpansion — must collapse \
             to RealBug Critical via D1.c; got {:?}, reasons={:?}",
            f.severity,
            f.prediction_reasons
                .iter()
                .map(|r| (&r.kind, r.weight))
                .collect::<Vec<_>>()
        );
        let alt = f.alternative_branch.as_ref().unwrap();
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::Benign);
        assert_eq!(alt.severity, Severity::Info);
    }

    #[test]
    fn real_where_clause_with_user_input() {
        // Real shape from the OWASP "NoSQL Injection" attack pattern
        // page and the Rocket.Chat historical CVE-2020-25988 family.
        // Variant of the shape that mongo-shell tutorials use to
        // demonstrate $where's danger. Excerpt:
        //
        //   from flask import Flask, request
        //   from pymongo import MongoClient
        //   users = MongoClient().db.users
        //   @app.route('/search')
        //   def search():
        //       q = request.form['q']
        //       return users.find_one({"$where": f"this.name == '{q}'"})
        //
        // `$where` executes JavaScript on the MongoDB server. The
        // f-string interpolation of `q` (a TypedString source — but
        // for $where, every source is unsafe because the value is
        // interpolated into JS code) gives the attacker arbitrary JS
        // execution on the DB server (`'; while(1){}; '` for DoS,
        // `'; return db.collection.drop()' ` for data loss).
        //
        // D1.b OperatorInjection collapse must fire: RealBug Critical.
        let findings = run_dual_branch(
            "real_where_clause.py",
            "from flask import Flask, request\n\
             from pymongo import MongoClient\n\
             users = MongoClient().db.users\n\
             @app.route('/search')\n\
             def search():\n\
             \x20   q = request.form['q']\n\
             \x20   return users.find_one({\"$where\": f\"this.name == '{request.form['q']}'\"})\n",
        );
        let f = findings
            .iter()
            .find(|f| f.is_dual_branch())
            .expect("dual-branch finding expected for $where with user input");
        assert_eq!(
            f.severity,
            Severity::Critical,
            "$where with user-input f-string is OperatorInjection — must \
             collapse to RealBug Critical via D1.b; got {:?}, reasons={:?}",
            f.severity,
            f.prediction_reasons
                .iter()
                .map(|r| (&r.kind, r.weight))
                .collect::<Vec<_>>()
        );
        let alt = f.alternative_branch.as_ref().unwrap();
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::Benign);
        assert_eq!(alt.severity, Severity::Info);
    }

    #[test]
    fn real_developer_written_ne_operator() {
        // The headline FP-reduction case for Phase 2i.
        //
        // Real shape from any Flask/FastAPI/Django app's admin-list-
        // users endpoint. Distilled from the standard "list everything
        // except admins" pattern that appears in countless tutorials.
        // Excerpt:
        //
        //   from pymongo import MongoClient
        //   users = MongoClient().db.users
        //   def list_non_admin_users():
        //       # List every user whose role is not "admin".
        //       return list(users.find({"role": {"$ne": "admin"}}))
        //
        // `$ne` is a legitimate MongoDB operator. The developer wrote
        // the query intentionally — the operator's semantics ARE the
        // intended behavior. There is no user input. There is no
        // operator-injection vector. The legacy line-regex scanner
        // flags every `$ne` as a Medium operator-injection finding
        // (because it matches `DANGEROUS_OPS`); the dual-branch
        // predictor recognizes "developer-written $ne with literal
        // value, no user input → +0.10 weight → Benign Info."
        //
        // This is the architectural justification for Phase 2i:
        // dual-branch wiring as PRIMARY FP-REDUCTION rather than new-
        // bug-discovery.
        let findings = run_dual_branch(
            "real_admin_list.py",
            "from pymongo import MongoClient\n\
             users = MongoClient().db.users\n\
             def list_non_admin_users():\n\
             \x20   # List every user whose role is not 'admin'.\n\
             \x20   return list(users.find({\"role\": {\"$ne\": \"admin\"}}))\n",
        );
        let f = findings
            .iter()
            .find(|f| f.is_dual_branch())
            .expect("dual-branch finding expected for $ne literal query");
        assert_eq!(
            f.severity,
            Severity::Info,
            "Developer-written $ne with literal value and no user input \
             must predict Benign Info — this is the headline FP-reduction \
             signal for Phase 2i; got {:?}, reasons={:?}",
            f.severity,
            f.prediction_reasons
                .iter()
                .map(|r| (&r.kind, r.weight))
                .collect::<Vec<_>>()
        );
        let alt = f.alternative_branch.as_ref().unwrap();
        assert_eq!(alt.label, crate::dual_branch::BranchLabel::RealBug);
    }

    // ─────────────────────────────────────────────────────────────────
    // Task 8h: Blocking-tier tests — SSA TaintPath → Tier::Blocking
    //
    // Pre-inject a mock TaintPath via set_precomputed_taint (the
    // detector's OnceLock shortcut) so the test exercises the
    // finding-construction path without needing a real graph with
    // parsed functions and on-disk files.
    //
    // The mock file is designed so the line/regex heuristic does NOT
    // fire on the query site (req.body is more than 5 lines above
    // the findOne call), ensuring the only findings produced are
    // from the injected TaintPath.
    // ─────────────────────────────────────────────────────────────────

    /// JS file where req.body is assigned early in the function and
    /// used in a findOne call 8 lines later — outside the 5-line
    /// nearby-input window, so the line-regex heuristic is silent.
    /// The SSA TaintPath (pre-injected) represents the real flow.
    const MOCK_JS_NOSQL: &str = "\
const mongoose = require('mongoose');\n\
async function login(req, res) {\n\
    const username = req.body.username;\n\
    // line 4\n\
    // line 5\n\
    // line 6\n\
    // line 7\n\
    // line 8\n\
    const user = await db.collection('users').findOne({ user: username });\n\
    res.json(user);\n\
}\n";

    fn make_taint_path(
        is_sanitized: bool,
        sink_callee: &str,
    ) -> crate::detectors::security::taint::TaintPath {
        crate::detectors::security::taint::TaintPath {
            source_function: "login".to_string(),
            source_file: "routes.js".to_string(),
            source_line: 3,
            sink_function: sink_callee.to_string(),
            sink_file: "routes.js".to_string(),
            sink_line: 9,
            category: crate::detectors::security::taint::TaintCategory::SqlInjection,
            call_chain: vec![format!("username → {}", sink_callee)],
            is_sanitized,
            sanitizer: None,
            confidence: 0.95,
            sink_callee_text: sink_callee.to_string(),
            sanitizers_on_path: Vec::new(),
        }
    }

    /// Unsanitized tainted flow into a MongoDB query → Tier::Blocking
    /// with Evidence::TaintPath { sink_kind: "nosql_query", .. }.
    #[test]
    fn taint_to_nosql_query_is_blocking() {
        let store = crate::graph::builder::GraphBuilder::new().freeze();
        let detector = NosqlInjectionDetector::new("/mock/repo");
        // Pre-inject an unsanitized findOne taint path.
        detector.set_precomputed_taint(vec![], vec![make_taint_path(false, "findOne")]);

        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("routes.js", MOCK_JS_NOSQL)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");

        let blocking: Vec<_> = findings
            .iter()
            .filter(|f| f.tier == crate::models::Tier::Blocking)
            .collect();
        assert!(
            !blocking.is_empty(),
            "expected a Blocking finding from SSA taint path; all findings: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, &f.tier))
                .collect::<Vec<_>>()
        );
        let f = blocking[0];
        assert!(
            f.severity >= crate::models::Severity::High,
            "Blocking finding must be High or Critical; got {:?}",
            f.severity
        );
        assert!(
            matches!(
                f.evidence,
                Some(crate::models::Evidence::TaintPath {
                    ref sink_kind,
                    ..
                }) if sink_kind == "nosql_query"
            ),
            "evidence must be TaintPath with sink_kind=nosql_query; got {:?}",
            f.evidence
        );
        assert!(f.deterministic, "Blocking finding must be deterministic");
        assert!(
            f.confidence.unwrap_or(0.0) >= 0.90,
            "Blocking finding confidence must be >= 0.90; got {:?}",
            f.confidence
        );
    }

    /// Tainted flow where the sanitizer flag is set → stays Advisory,
    /// no TaintPath evidence attached.
    #[test]
    fn string_coerced_is_advisory() {
        let store = crate::graph::builder::GraphBuilder::new().freeze();
        let detector = NosqlInjectionDetector::new("/mock/repo");
        // is_sanitized = true simulates String(req.body.name) coercion on the path.
        detector.set_precomputed_taint(vec![], vec![make_taint_path(true, "findOne")]);

        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("routes.js", MOCK_JS_NOSQL)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");

        // Sanitized paths are dropped before finding construction; none should be Blocking.
        for f in &findings {
            assert_ne!(
                f.tier,
                crate::models::Tier::Blocking,
                "sanitized path must not produce Blocking; got tier={:?} evidence={:?}",
                f.tier,
                f.evidence
            );
            assert!(
                f.evidence.is_none(),
                "sanitized path must not carry TaintPath evidence; got {:?}",
                f.evidence
            );
        }
    }

    /// A finding produced by the line/regex heuristic (no SSA TaintPath
    /// pre-injected) must stay Advisory with no evidence.
    #[test]
    fn line_heuristic_match_is_advisory() {
        let store = crate::graph::builder::GraphBuilder::new().freeze();
        let detector = NosqlInjectionDetector::new("/mock/repo");
        // No pre-injected taint paths — only the line-regex path fires.
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "routes.js",
                "const mongoose = require('mongoose');\n\
                 async function login(req, res) {\n\
                 \x20   const user = await db.collection('users').find({ name: req.body.name });\n\
                 \x20   res.json(user);\n\
                 }\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        for f in &findings {
            assert_ne!(
                f.tier,
                crate::models::Tier::Blocking,
                "line-heuristic finding must not be Blocking; got tier={:?}",
                f.tier
            );
            assert!(
                f.evidence.is_none(),
                "line-heuristic finding must not carry TaintPath evidence; got {:?}",
                f.evidence
            );
        }
    }
}