repotoire 0.8.2

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
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
//! Unsafe-deserialization detector (CWE-502).
//!
//! Detects deserialization-of-untrusted-data sinks that can lead to
//! Remote Code Execution. Severity hinges on whether the input is
//! attacker-controlled, classified from the AST shape of the argument.
//!
//! # Architecture
//!
//! Two scan paths, picked by file language (mirrors `eval_detector.rs`
//! and `command_injection.rs`):
//!
//! 1. **AST path** (Python, JS, TS, JSX, TSX): walks the tree-sitter
//!    parse tree looking for **call expressions** whose callee matches
//!    a known unsafe-deserialization API.
//!
//!      - **Python**:
//!        - `pickle.loads`, `pickle.load`
//!        - `cPickle.loads`, `cPickle.load`
//!        - `_pickle.loads`, `_pickle.load`
//!        - `dill.loads`, `dill.load`
//!        - `cloudpickle.loads`, `cloudpickle.load`
//!        - `pickle.Unpickler(io).load()` and `pickle._Unpickler(io).load()`
//!        - `pandas.read_pickle`, `pd.read_pickle`
//!        - `joblib.load`
//!        - `numpy.load(file, allow_pickle=True)` / `np.load(...)`
//!        - `shelve.open`
//!        - `torch.load(...)` (without `weights_only=True`)
//!        - `yaml.load(...)` (without a Safe loader)
//!        - `marshal.load`, `marshal.loads`
//!
//!      - **JavaScript / TypeScript**:
//!        - `unserialize(...)` (bare or `nodeSerialize.unserialize(...)`)
//!        - `require('node-serialize').unserialize(userData)` — the B1
//!          require()-receiver lesson from the command-injection migration.
//!        - `serialize-javascript` deserialize forms.
//!
//!    Severity is decided by classifying the relevant argument into
//!    `PickleArgKind::{StaticLiteral, InterpolatedOrConcat, UserVariable,
//!    FunctionLike, Unknown}`:
//!
//!      | kind                   | severity |
//!      | ---------------------- | -------- |
//!      | StaticLiteral          | Low (filtered out) |
//!      | InterpolatedOrConcat   | Critical |
//!      | UserVariable           | Critical |
//!      | FunctionLike           | High     |
//!      | Unknown                | High     |
//!
//!    `numpy.load` is special-cased: it only fires when `allow_pickle=True`
//!    is passed (default is `False` in modern numpy, so the call is safe
//!    by default).
//!
//!    `torch.load` only fires when `weights_only=True` is NOT passed.
//!
//!    `yaml.load` only fires when no safe loader is supplied.
//!
//!    Route-handler boost: if the call sits inside a request-handler /
//!    route function (matched by name substring or camelCase verb-prefix),
//!    severity is bumped one tier up. Mirrors
//!    `eval_detector::HANDLER_VERB_RE`.
//!
//! 2. **Line path** (Ruby `Marshal.load`, PHP `unserialize`): for
//!    languages without a tree-sitter grammar in our dispatch list, a
//!    small line-based regex scanner matches the canonical forms.
//!    Java's `ObjectInputStream.readObject()` is out of scope per prior
//!    detectors (Java is not in the AST dispatch).
//!
//! This is the structural counterpart of the eval-detector AST migration
//! (commits `ac8400c6` / `474e6cb5`) and the command-injection AST
//! migration (commits `c67ad76f` / `3c88328e`). The previous detector
//! ran a line-based regex over raw text and could not tell
//! `pickle.loads(b'\x80...')` (safe; static bytes literal) apart from
//! `pickle.loads(user_data)` (Critical) — both fired with identical
//! `High` severity. With the AST, "is the argument a literal or a
//! variable" is a free piece of information.

use crate::detectors::ast_fingerprint::parse_root_ext;
use crate::detectors::ast_walk::AstWalkCtx;
use crate::detectors::base::{Detector, DetectorConfig};
use crate::detectors::fast_search::*;
use crate::detectors::security::ast_helpers::{
    collect_named_args, node_text, python_kwarg_truthy, python_kwarg_value,
    receiver_chain_label as receiver_chain_label_shared, unwrap_callee,
};
use crate::detectors::security::scan_inputs::{ScanAstInputs, ScanInputs};
use crate::graph::GraphQueryExt;
use crate::models::{Finding, Severity};
use crate::parsers::lightweight::Language;
use anyhow::Result;
use regex::Regex;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use tracing::{debug, info};

// ---------------------------------------------------------------------------
// Single source of truth for supported file extensions.
// ---------------------------------------------------------------------------

/// Extensions this detector processes. Mirrors `eval_detector::SUPPORTED_EXTS`
/// so AST/line dispatch lists stay aligned.
///
/// AST-eligible extensions (Python + JS/TS/JSX/TSX) flow through
/// `scan_file_ast`; the rest fall through to the legacy line scanner.
const SUPPORTED_EXTS: &[&str] = &[
    // AST path
    "py", "js", "ts", "jsx", "tsx", // Line path
    "rb", "php",
];

/// Subset of `SUPPORTED_EXTS` that has tree-sitter grammars in our
/// dispatch list.
const AST_EXTS: &[&str] = &["py", "js", "ts", "jsx", "tsx"];

/// Default file patterns to exclude.
const DEFAULT_EXCLUDE_PATTERNS: &[&str] = &[
    "tests/",
    "test_",
    "_test.py",
    "migrations/",
    "__pycache__/",
    ".git/",
    "node_modules/",
    "venv/",
    ".venv/",
];

// ---------------------------------------------------------------------------
// Argument-shape classification
// ---------------------------------------------------------------------------

/// What kind of value is being passed to an unsafe-deserialization sink.
///
/// Pickle-like sinks take a single bytes/file argument, so the enum is
/// simpler than `command_injection::CommandArgKind` (no list/argv
/// shapes). The classifier descends through transparent wrappers
/// (`await`, ternary, TS `as`/`!`/`<T>x`/`satisfies`, parentheses) so
/// `pickle.loads(await get_data())` is classified as `UserVariable`,
/// not `Unknown`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PickleArgKind {
    /// Static literal — `pickle.loads(b"\x80...")` or `unserialize("...")`.
    /// Deserializing your own constant is benign.
    StaticLiteral,
    /// Concatenation / interpolation that splices a variable in —
    /// `pickle.loads(b"prefix" + user_data)` or
    /// ``unserialize(`hdr ${data}`)``.
    InterpolatedOrConcat,
    /// Identifier / member access / subscript / call result —
    /// `pickle.loads(user_input)`, `pickle.loads(req.body)`,
    /// `pickle.loads(get())`. Highest-risk shape.
    UserVariable,
    /// Lambda / arrow function / function expression. Unusual for
    /// deserialization sinks; defensively treated as `Unknown` severity
    /// (High).
    FunctionLike,
    /// Anything we don't classify. Defaults to `High` severity.
    Unknown,
}

// ---------------------------------------------------------------------------
// Sink API enum
// ---------------------------------------------------------------------------

/// Which unsafe-deserialization API was matched.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PickleApi {
    PickleLoad,
    DillLoad,
    CloudPickleLoad,
    UnpicklerLoad,
    PandasReadPickle,
    JoblibLoad,
    NumpyLoadAllowPickle,
    ShelveOpen,
    TorchLoadUnsafe,
    YamlLoadUnsafe,
    MarshalLoad,
    /// JS `unserialize(...)` from `node-serialize` / `serialize-javascript`.
    JsUnserialize,
    /// Ruby `Marshal.load` (line path).
    RubyMarshalLoad,
    /// PHP `unserialize(...)` (line path).
    PhpUnserialize,
}

impl PickleApi {
    fn callee_label(self) -> &'static str {
        match self {
            PickleApi::PickleLoad => "pickle.load/loads",
            PickleApi::DillLoad => "dill.load/loads",
            PickleApi::CloudPickleLoad => "cloudpickle.load/loads",
            PickleApi::UnpicklerLoad => "Unpickler.load",
            PickleApi::PandasReadPickle => "pandas.read_pickle",
            PickleApi::JoblibLoad => "joblib.load",
            PickleApi::NumpyLoadAllowPickle => "numpy.load(allow_pickle=True)",
            PickleApi::ShelveOpen => "shelve.open",
            PickleApi::TorchLoadUnsafe => "torch.load (without weights_only=True)",
            PickleApi::YamlLoadUnsafe => "yaml.load (without SafeLoader)",
            PickleApi::MarshalLoad => "marshal.load/loads",
            PickleApi::JsUnserialize => "unserialize",
            PickleApi::RubyMarshalLoad => "Marshal.load",
            PickleApi::PhpUnserialize => "unserialize",
        }
    }
}

// ---------------------------------------------------------------------------
// Detector
// ---------------------------------------------------------------------------

/// Detects unsafe deserialization vulnerabilities (CWE-502).
pub struct PickleDeserializationDetector {
    config: DetectorConfig,
    #[allow(dead_code)]
    repository_path: PathBuf,
    max_findings: usize,
    exclude_patterns: Vec<String>,
    compiled_globs: Vec<Regex>,
}

impl PickleDeserializationDetector {
    /// Create a new detector with default settings.
    pub fn new() -> Self {
        Self::with_config(DetectorConfig::new(), PathBuf::from("."))
    }

    /// Create with a custom repository path.
    pub fn with_repository_path(repository_path: PathBuf) -> Self {
        Self::with_config(DetectorConfig::new(), repository_path)
    }

    /// Create with a custom config and repository path.
    pub fn with_config(config: DetectorConfig, repository_path: PathBuf) -> Self {
        let max_findings = config.get_option_or("max_findings", 100);
        let exclude_patterns = config
            .get_option::<Vec<String>>("exclude_patterns")
            .unwrap_or_else(|| {
                DEFAULT_EXCLUDE_PATTERNS
                    .iter()
                    .map(|s| s.to_string())
                    .collect()
            });

        Self {
            config,
            repository_path,
            max_findings,
            compiled_globs: crate::detectors::base::compile_glob_patterns(&exclude_patterns),
            exclude_patterns,
        }
    }

    /// Check if a path should be excluded (test paths, vendored deps, ...).
    fn should_exclude(&self, path: &str) -> bool {
        crate::detectors::base::should_exclude_path(
            path,
            &self.exclude_patterns,
            &self.compiled_globs,
        )
    }

    /// Trusted-context filter: cache and session backends only ever
    /// deserialize data they created themselves.
    fn is_trusted_serialization_context(path: &str) -> bool {
        path.contains("cache/backends/") || path.contains("sessions/backends/")
    }

    /// AST-first scanner. Walks the tree once, emitting findings for
    /// every call expression whose callee matches an unsafe-deserialization
    /// API.
    fn scan_file_ast(&self, inputs: &ScanAstInputs<'_>) -> Vec<Finding> {
        let path = inputs.path();
        let content = inputs.content();
        let ext = inputs.ext();
        let lang = inputs.lang;
        let cached_tree = inputs.cached_tree;
        let mut findings = vec![];
        if content.contains('\0') || content.len() > 500_000 {
            return findings;
        }

        let owned;
        let root = match cached_tree {
            Some(tree) => tree.root_node(),
            None => match parse_root_ext(content, lang, ext) {
                Some(t) => {
                    owned = t;
                    owned.root_node()
                }
                None => return findings,
            },
        };

        let bytes = content.as_bytes();
        let lines: Vec<&str> = content.lines().collect();
        // Per-file Python from-import alias map: resolves
        // `from pickle import loads; loads(user_data)` and similar
        // bare-call shapes that the attribute-only matcher would
        // otherwise miss. Mirrors `insecure_crypto`'s pattern.
        let alias_map = if matches!(lang, Language::Python) {
            super::python_imports::collect_python_from_imports(root, bytes)
        } else {
            HashMap::new()
        };
        // Per-file Python module-alias map: resolves
        // `import pickle as pkl; pkl.loads(...)` by mapping the
        // attribute-receiver text `pkl` back to the canonical
        // module name `pickle` before matching.
        let module_aliases = if matches!(lang, Language::Python) {
            super::python_imports::collect_python_module_aliases(root, bytes)
        } else {
            HashMap::new()
        };
        let mut sites: Vec<PickleSite> = Vec::new();
        let ctx = AstWalkCtx {
            lang,
            source: bytes,
        };
        let aliases = super::python_imports::PythonAliases::new(&alias_map, &module_aliases);
        collect_pickle_sites(&ctx, root, &aliases, &mut sites);

        for site in sites {
            if findings.len() >= self.max_findings {
                break;
            }
            let line_idx = site.call_node.start_position().row;
            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;

            let severity = severity_for(site.api, site.arg_kind);

            findings.push(self.build_finding(
                path,
                line_num,
                site.api,
                site.arg_kind,
                severity,
                snippet,
                ext,
            ));
        }

        findings
    }

    /// Legacy line scanner for non-AST languages (Ruby, PHP).
    ///
    /// **Path used by**: `.rb` (`Marshal.load`), `.php` (`unserialize`).
    /// AST-eligible extensions flow through `scan_file_ast` instead.
    fn scan_file_line(&self, inputs: &ScanInputs<'_>) -> Vec<Finding> {
        let path = inputs.path;
        let content = inputs.content;
        let ext = inputs.ext;
        let mut findings = vec![];
        if content.len() > 500_000 {
            return findings;
        }
        let lines: Vec<&str> = content.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            if findings.len() >= self.max_findings {
                break;
            }
            let prev = if i > 0 { Some(lines[i - 1]) } else { None };
            if crate::detectors::is_line_suppressed(line, prev) {
                continue;
            }
            let trimmed = line.trim_start();
            if trimmed.starts_with('#') || trimmed.starts_with("//") {
                continue;
            }
            if let Some((api, arg_kind)) = match_line_pickle(line, ext) {
                let line_num = (i + 1) as u32;
                let severity = severity_for(api, arg_kind);
                findings.push(self.build_finding(
                    path,
                    line_num,
                    api,
                    arg_kind,
                    severity,
                    line.trim(),
                    ext,
                ));
            }
        }
        findings
    }

    /// Construct a `Finding` for a detected deserialization site.
    fn build_finding(
        &self,
        path: &Path,
        line_num: u32,
        api: PickleApi,
        arg_kind: PickleArgKind,
        severity: Severity,
        snippet: &str,
        ext: &str,
    ) -> Finding {
        let api_name = api.callee_label();
        let arg_desc = match arg_kind {
            PickleArgKind::StaticLiteral => "static literal (low risk)",
            PickleArgKind::InterpolatedOrConcat => "concatenated/interpolated value (RCE risk)",
            PickleArgKind::UserVariable => "non-literal expression (RCE risk)",
            PickleArgKind::FunctionLike => "function value (unusual for deserialization)",
            PickleArgKind::Unknown => "non-static argument",
        };
        let lang_label = match ext {
            "py" => "python",
            "js" | "jsx" => "javascript",
            "ts" | "tsx" => "typescript",
            "rb" => "ruby",
            "php" => "php",
            _ => "",
        };

        let title = "Unsafe Deserialization (CWE-502)".to_string();

        let description = format!(
            "**Unsafe Deserialization Vulnerability**\n\n\
             **API**: `{}`\n\n\
             **Argument shape**: {}\n\n\
             **Location**: {}:{}\n\n\
             **Code snippet**:\n```{}\n{}\n```\n\n\
             Deserializing untrusted data can allow attackers to execute arbitrary code.\n\
             Pickle, dill, joblib, torch.load, yaml.load, and similar functions execute code\n\
             embedded in the serialized data. An attacker who controls the input can\n\
             achieve Remote Code Execution (RCE).\n\n\
             This vulnerability is classified as:\n\
             - **CWE-502**: Deserialization of Untrusted Data\n\
             - **OWASP A8:2017**: Insecure Deserialization",
            api_name,
            arg_desc,
            path.display(),
            line_num,
            lang_label,
            snippet,
        );

        let suggested_fix = self.recommend(api);

        Finding {
            id: String::new(),
            detector: "PickleDeserializationDetector".to_string(),
            severity,
            title,
            description,
            affected_files: vec![path.to_path_buf()],
            line_start: Some(line_num),
            line_end: Some(line_num),
            suggested_fix: Some(suggested_fix),
            estimated_effort: Some("Medium (2-8 hours)".to_string()),
            category: Some("security".to_string()),
            cwe_id: Some("CWE-502".to_string()),
            why_it_matters: Some(
                "Insecure deserialization can lead to Remote Code Execution, allowing attackers \
                 to take complete control of the application and server."
                    .to_string(),
            ),
            ..Default::default()
        }
    }

    /// Per-API remediation guidance.
    fn recommend(&self, api: PickleApi) -> String {
        match api {
            PickleApi::PickleLoad
            | PickleApi::DillLoad
            | PickleApi::CloudPickleLoad
            | PickleApi::UnpicklerLoad => "Avoid pickle/dill/cloudpickle on untrusted data.\n\n\
                 - For data exchange: use `json.loads`.\n\
                 - For binary data: use Protocol Buffers, msgpack (strict), or a\n\
                   signed/encrypted container.\n\
                 - If pickle is required, only load from sources you control and\n\
                   verify their integrity (checksum or signature) first."
                .to_string(),
            PickleApi::PandasReadPickle | PickleApi::JoblibLoad => {
                "Avoid loading pickle-backed model/dataframe artifacts from untrusted sources.\n\n\
                 - For ML models, prefer `safetensors`, `ONNX`, or `skops` with an\n\
                   explicit allowlist.\n\
                 - For dataframes, prefer Parquet or CSV.\n\
                 - Verify source integrity (checksum/signature) before loading."
                    .to_string()
            }
            PickleApi::NumpyLoadAllowPickle => {
                "Avoid `numpy.load(..., allow_pickle=True)` on untrusted files.\n\n\
                 - Default to `allow_pickle=False` (numpy's default since 1.16.3).\n\
                 - Use `.npz` files without object arrays.\n\
                 - If you need Python objects, verify the file source first."
                    .to_string()
            }
            PickleApi::ShelveOpen => {
                "Avoid `shelve.open` on user-controlled paths — shelve uses pickle\n\
                 internally.\n\n\
                 - Use SQLite or another safe key-value store.\n\
                 - Validate the path source before opening."
                    .to_string()
            }
            PickleApi::TorchLoadUnsafe => "Avoid `torch.load` without `weights_only=True`.\n\n\
                 - Pass `weights_only=True` (PyTorch 1.13+) — only loads tensors.\n\
                 - Prefer `safetensors` for model weights.\n\
                 - Validate the model source before loading."
                .to_string(),
            PickleApi::YamlLoadUnsafe => "Avoid `yaml.load` without a Safe loader.\n\n\
                 - Use `yaml.safe_load(content)` for untrusted data.\n\
                 - Or pass `Loader=yaml.SafeLoader`.\n\
                 - Never call `yaml.unsafe_load` on untrusted input."
                .to_string(),
            PickleApi::MarshalLoad => {
                "Avoid `marshal.load`/`marshal.loads` on untrusted data — marshal\n\
                 deserializes Python bytecode and can execute arbitrary code.\n\n\
                 - Use `json` for data exchange.\n\
                 - If marshal is unavoidable, only load signed/verified bytecode."
                    .to_string()
            }
            PickleApi::JsUnserialize => {
                "Avoid `node-serialize` / `serialize-javascript` `unserialize` on\n\
                 untrusted input — these libraries execute embedded code on load.\n\n\
                 - Use `JSON.parse` for data exchange.\n\
                 - For object graphs, use a structured-clone or a safe library."
                    .to_string()
            }
            PickleApi::RubyMarshalLoad => {
                "Avoid `Marshal.load` on untrusted data — Ruby Marshal can\n\
                 instantiate arbitrary classes and trigger code execution.\n\n\
                 - Use `JSON.parse` for data exchange.\n\
                 - If Marshal is required, only load from trusted sources."
                    .to_string()
            }
            PickleApi::PhpUnserialize => {
                "Avoid `unserialize` on untrusted data — PHP `unserialize` can\n\
                 trigger magic methods (POP-chain RCE).\n\n\
                 - Use `json_decode` for data exchange.\n\
                 - If unserialize is required, pass an `allowed_classes` allowlist\n\
                 (PHP 7+) and validate the input source."
                    .to_string()
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Severity table
// ---------------------------------------------------------------------------

/// Map `(api, arg_kind)` to a severity. All sinks share the same shape:
/// static literal is benign, anything that can carry a payload is RCE.
fn severity_for(_api: PickleApi, arg_kind: PickleArgKind) -> Severity {
    match arg_kind {
        PickleArgKind::StaticLiteral => Severity::Low,
        PickleArgKind::InterpolatedOrConcat | PickleArgKind::UserVariable => Severity::Critical,
        PickleArgKind::FunctionLike | PickleArgKind::Unknown => Severity::High,
    }
}

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

impl Detector for PickleDeserializationDetector {
    fn name(&self) -> &'static str {
        "PickleDeserializationDetector"
    }

    fn description(&self) -> &'static str {
        "Detects unsafe deserialization patterns (pickle, torch.load, yaml.load, ...)"
    }

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

    fn category(&self) -> &'static str {
        "security"
    }

    fn requires_graph(&self) -> bool {
        false
    }

    fn config(&self) -> Option<&DetectorConfig> {
        Some(&self.config)
    }

    fn file_extensions(&self) -> &'static [&'static str] {
        SUPPORTED_EXTS
    }

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

    fn detect(
        &self,
        ctx: &crate::detectors::analysis_context::AnalysisContext,
    ) -> Result<Vec<Finding>> {
        let graph = ctx.graph;
        let files = &ctx.as_file_provider();
        debug!("Starting unsafe-deserialization detection (AST-first)");

        let mut findings: Vec<Finding> = Vec::new();

        for path in files.files_with_extensions(SUPPORTED_EXTS) {
            if findings.len() >= self.max_findings {
                break;
            }
            let path_str = path.to_string_lossy().to_string();
            if self.should_exclude(&path_str) {
                continue;
            }
            if Self::is_trusted_serialization_context(&path_str) {
                continue;
            }

            let content = match files.content(path) {
                Some(c) => c,
                None => continue,
            };
            // Cheap pre-filter: skip files with no deserialization keywords.
            if !contains_any(PICKLE_KEYWORD_FINDERS, &content) {
                continue;
            }

            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            let scan = ScanInputs::new(path, &content, ext);
            let new_findings = if AST_EXTS.contains(&ext) {
                let cached = files.tree(path);
                let lang = Language::from_path(path);
                let ast_inputs = ScanAstInputs::new(scan, lang, cached.as_deref());
                self.scan_file_ast(&ast_inputs)
            } else {
                self.scan_file_line(&scan)
            };
            findings.extend(new_findings);
        }

        // Severity boost when call appears in a request-handler / route
        // function. Mirrors `eval_detector` / `command_injection`.
        static HANDLER_VERB_RE: LazyLock<Regex> = LazyLock::new(|| {
            Regex::new(r"^(get|post|put|delete|patch|head|options)[A-Z]").expect("valid regex")
        });
        for finding in &mut findings {
            if !matches!(finding.severity, Severity::High | Severity::Medium) {
                continue;
            }
            if let (Some(file_path), Some(line)) =
                (finding.affected_files.first(), finding.line_start)
            {
                let path_str = file_path.to_string_lossy().to_string();
                let i = graph.interner();
                if let Some(func) = graph.find_function_at(&path_str, line) {
                    let raw_name = func.node_name(i);
                    let name_lower = raw_name.to_lowercase();
                    let is_route = name_lower.contains("handler")
                        || name_lower.contains("route")
                        || name_lower.contains("endpoint")
                        || name_lower.contains("view")
                        || name_lower.contains("controller")
                        || name_lower.contains("middleware")
                        || name_lower.contains("request")
                        || name_lower.contains("response")
                        || HANDLER_VERB_RE.is_match(raw_name);
                    if is_route {
                        finding.severity = Severity::Critical;
                    }
                }
            }
        }

        // Drop Low findings (static literals are not actionable without
        // taint context).
        findings.retain(|f| f.severity != Severity::Low);

        info!(
            "PickleDeserializationDetector found {} potential vulnerabilities",
            findings.len()
        );
        Ok(findings)
    }
}

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

// ---------------------------------------------------------------------------
// Pre-filter
// ---------------------------------------------------------------------------

/// Cheap pre-filter: does this file contain any deserialization keyword?
///
/// Each callee name we match in `match_*_call` MUST be covered by a
/// substring here, otherwise the AST scan never runs on a file containing
/// only that callee. This is the parallel to the
/// `command_injection::COMMAND_KEYWORD_FINDERS` audit.
static PICKLE_KEYWORD_FINDERS: &[&LazyLock<memchr::memmem::Finder<'static>>] = &[
    &FIND_PICKLE,
    &FIND_CPICKLE,
    &FIND_DILL,
    &FIND_CLOUDPICKLE,
    &FIND_READ_PICKLE,
    &FIND_JOBLIB_LOAD,
    &FIND_UNPICKLER,
    &FIND_SHELVE,
    &FIND_NUMPY_LOAD_DOT,
    &FIND_NP_LOAD_DOT,
    &FIND_TORCH_LOAD_DOT,
    &FIND_YAML_LOAD_DOT,
    &FIND_YAML_UNSAFE_LOAD,
    &FIND_YAML_FULL_LOAD,
    &FIND_MARSHAL_DOT,
    &FIND_UNSERIALIZE,
    &FIND_NODE_SERIALIZE,
    &FIND_SERIALIZE_JS,
    &FIND_DESERIALIZE,
    &FIND_MARSHAL_LOAD_RB,
];

// ---------------------------------------------------------------------------
// AST walking
// ---------------------------------------------------------------------------

/// One unsafe-deserialization-shaped call site we want to emit.
struct PickleSite<'a> {
    call_node: tree_sitter::Node<'a>,
    api: PickleApi,
    arg_kind: PickleArgKind,
}

/// Walk the tree and emit a `PickleSite` for every dangerous-API call.
fn collect_pickle_sites<'a>(
    ctx: &AstWalkCtx<'a>,
    node: tree_sitter::Node<'a>,
    aliases: &super::python_imports::PythonAliases<'_>,
    out: &mut Vec<PickleSite<'a>>,
) {
    if let Some(site) = match_pickle_site(node, ctx.source, ctx.lang, aliases) {
        out.push(site);
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_pickle_sites(ctx, child, aliases, out);
    }
}

/// If `node` is an unsafe-deserialization call, return a `PickleSite`.
fn match_pickle_site<'a>(
    node: tree_sitter::Node<'a>,
    source: &'a [u8],
    lang: Language,
    aliases: &super::python_imports::PythonAliases<'_>,
) -> Option<PickleSite<'a>> {
    match (node.kind(), lang) {
        ("call", Language::Python) => match_python_pickle_call(node, source, aliases),
        ("call_expression", Language::JavaScript | Language::TypeScript) => {
            match_js_unserialize_call(node, source)
        }
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Python
// ---------------------------------------------------------------------------

/// Classify a `(module, name)` pair against the Python unsafe-deserialization
/// API table. Returns the `PickleApi` for callees that fire; `None` for
/// unrelated functions, or for callees that depend on argument shape and
/// turn out to be safe (e.g. `numpy.load(...)` without `allow_pickle=True`,
/// `torch.load(..., weights_only=True)`, `yaml.safe_load(...)`).
///
/// Used by both the attribute-call branch (`pickle.loads(...)`) and the
/// bare-identifier branch (`from pickle import loads; loads(...)`) of
/// `match_python_pickle_call`.
///
/// The `obj_for_unpickler` argument is `Some` when the callee is an
/// attribute call (so we can check for `Unpickler(io).load()`) and
/// `None` for the bare-call branch (where that pattern doesn't apply).
fn classify_python_pickle_callee(
    module: &str,
    name: &str,
    arg_nodes: &[tree_sitter::Node<'_>],
    source: &[u8],
    obj_for_unpickler: Option<tree_sitter::Node<'_>>,
) -> Option<PickleApi> {
    Some(match (module, name) {
        ("pickle" | "cpickle" | "_pickle", "load" | "loads") => PickleApi::PickleLoad,
        ("dill", "load" | "loads") => PickleApi::DillLoad,
        ("cloudpickle", "load" | "loads") => PickleApi::CloudPickleLoad,
        // Unpickler(io).load()  →  attribute.object is `call`
        // (the Unpickler(io) call), attribute.attribute is `load`.
        // Only relevant for the attribute-call branch.
        (_, "load")
            if obj_for_unpickler
                .map(|o| o.kind() == "call" && call_is_unpickler_constructor(o, source))
                .unwrap_or(false) =>
        {
            PickleApi::UnpicklerLoad
        }
        ("pandas" | "pd", "read_pickle") => PickleApi::PandasReadPickle,
        ("joblib", "load") => PickleApi::JoblibLoad,
        ("numpy" | "np", "load") if numpy_load_allow_pickle_true(arg_nodes, source) => {
            PickleApi::NumpyLoadAllowPickle
        }
        ("numpy" | "np", "load") => return None,
        ("shelve", "open") => PickleApi::ShelveOpen,
        ("torch", "load") => {
            if torch_load_weights_only_true(arg_nodes, source) {
                return None;
            }
            PickleApi::TorchLoadUnsafe
        }
        ("yaml", "load" | "unsafe_load" | "full_load") => {
            if yaml_load_safe(arg_nodes, source) {
                return None;
            }
            PickleApi::YamlLoadUnsafe
        }
        ("marshal", "load" | "loads") => PickleApi::MarshalLoad,
        _ => return None,
    })
}

/// Match a Python `call` node against the unsafe-deserialization API list.
fn match_python_pickle_call<'a>(
    node: tree_sitter::Node<'a>,
    source: &'a [u8],
    aliases: &super::python_imports::PythonAliases<'_>,
) -> Option<PickleSite<'a>> {
    let func = node.child_by_field_name("function")?;
    let func = unwrap_callee(func);
    let args = node.child_by_field_name("arguments")?;
    let arg_nodes = collect_named_args(args);

    let api = match func.kind() {
        "attribute" => {
            let obj = func.child_by_field_name("object")?;
            let attr = func.child_by_field_name("attribute")?;
            let attr_text = node_text(attr, source)?;
            let raw_label = receiver_chain_label(obj, source);
            // Resolve `import pickle as pkl; pkl.loads(...)` — see
            // `insecure_crypto::match_python_crypto_call` for the rationale.
            let obj_text = node_text(obj, source).unwrap_or("");
            let obj_label = aliases
                .modules
                .get(obj_text)
                .or_else(|| aliases.modules.get(raw_label.as_str()))
                .cloned()
                .unwrap_or(raw_label);
            classify_python_pickle_callee(
                obj_label.as_str(),
                attr_text,
                &arg_nodes,
                source,
                Some(obj),
            )?
        }
        "identifier" => {
            // Bare-call: only fires if a `from <module> import <name>`
            // bound this name to one of the known unsafe-deserialization
            // modules (pickle/cPickle/_pickle/dill/cloudpickle/joblib/...).
            let name = node_text(func, source)?;
            let module = aliases.imports.get(name)?;
            classify_python_pickle_callee(module.as_str(), name, &arg_nodes, source, None)?
        }
        _ => return None,
    };

    // Pick the first positional (non-keyword) argument as the classified
    // value. For e.g. `numpy.load(file, allow_pickle=True)` the first
    // arg is the filename which is what carries the user input.
    let target = arg_nodes
        .iter()
        .copied()
        .find(|a| a.kind() != "keyword_argument")?;
    let arg_kind = classify_pickle_arg_python(target, source);

    Some(PickleSite {
        call_node: node,
        api,
        arg_kind,
    })
}

/// Is this `call` node a `pickle.Unpickler(io)` / `pickle._Unpickler(io)` /
/// bare `Unpickler(io)` constructor invocation?
fn call_is_unpickler_constructor(node: tree_sitter::Node<'_>, source: &[u8]) -> bool {
    if node.kind() != "call" {
        return false;
    }
    let Some(func) = node.child_by_field_name("function") else {
        return false;
    };
    match func.kind() {
        "identifier" => matches!(
            node_text(func, source).unwrap_or(""),
            "Unpickler" | "_Unpickler"
        ),
        "attribute" => {
            let attr = match func.child_by_field_name("attribute") {
                Some(a) => a,
                None => return false,
            };
            matches!(
                node_text(attr, source).unwrap_or(""),
                "Unpickler" | "_Unpickler"
            )
        }
        _ => false,
    }
}

/// Inspect the args of a `numpy.load(...)` call: did the caller pass
/// `allow_pickle=True`? Non-literal values are treated as `True` to be
/// conservative (numpy.load defaults to `False`, so any explicit
/// override that isn't a `False` literal is suspicious).
fn numpy_load_allow_pickle_true(args: &[tree_sitter::Node<'_>], source: &[u8]) -> bool {
    python_kwarg_truthy(
        args,
        "allow_pickle",
        source,
        /* unknown_default = */ true,
    )
}

/// Inspect the args of a `torch.load(...)` call: did the caller pass
/// `weights_only=True` (the safe flag)? Non-literal values are treated
/// as `False` because torch.load's pre-2.6 default was `weights_only=False`,
/// and any explicit override that isn't a literal `True` cannot be
/// statically proven safe.
fn torch_load_weights_only_true(args: &[tree_sitter::Node<'_>], source: &[u8]) -> bool {
    python_kwarg_truthy(
        args,
        "weights_only",
        source,
        /* unknown_default = */ false,
    )
}

/// Inspect the args of a `yaml.load(...)` call: did the caller pass a
/// safe loader (`Loader=yaml.SafeLoader`, `BaseLoader`, `CSafeLoader`)?
fn yaml_load_safe(args: &[tree_sitter::Node<'_>], source: &[u8]) -> bool {
    let Some(value) = python_kwarg_value(args, "Loader", source) else {
        return false;
    };
    let text = node_text(value, source).unwrap_or("");
    text.contains("SafeLoader") || text.contains("BaseLoader") || text.contains("CSafeLoader")
}

/// Classify the shape of a Python deserialization-call argument.
#[allow(clippy::only_used_in_recursion)]
fn classify_pickle_arg_python(node: tree_sitter::Node<'_>, source: &[u8]) -> PickleArgKind {
    match node.kind() {
        "string" => {
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "interpolation" {
                    return PickleArgKind::InterpolatedOrConcat;
                }
            }
            PickleArgKind::StaticLiteral
        }
        "concatenated_string" => {
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if classify_pickle_arg_python(child, source) == PickleArgKind::InterpolatedOrConcat
                {
                    return PickleArgKind::InterpolatedOrConcat;
                }
            }
            PickleArgKind::StaticLiteral
        }
        "binary_operator" => {
            let mut found_var = false;
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if !child.is_named() {
                    continue;
                }
                match classify_pickle_arg_python(child, source) {
                    PickleArgKind::UserVariable
                    | PickleArgKind::InterpolatedOrConcat
                    | PickleArgKind::Unknown => found_var = true,
                    _ => {}
                }
            }
            if found_var {
                PickleArgKind::InterpolatedOrConcat
            } else {
                PickleArgKind::StaticLiteral
            }
        }
        "identifier" | "attribute" | "subscript" | "call" => PickleArgKind::UserVariable,
        "lambda" => PickleArgKind::FunctionLike,
        "parenthesized_expression" => {
            for i in 0..node.named_child_count() {
                if let Some(c) = node.named_child(i) {
                    return classify_pickle_arg_python(c, source);
                }
            }
            PickleArgKind::Unknown
        }
        // B4: descend through `await` so `pickle.loads(await get_data())`
        // sees the underlying call.
        "await" => {
            for i in 0..node.named_child_count() {
                if let Some(c) = node.named_child(i) {
                    return classify_pickle_arg_python(c, source);
                }
            }
            PickleArgKind::Unknown
        }
        // Ternary `a if cond else b`. Strongest branch wins.
        "conditional_expression" => {
            let mut strongest = PickleArgKind::StaticLiteral;
            for i in 0..node.named_child_count() {
                if let Some(c) = node.named_child(i) {
                    let k = classify_pickle_arg_python(c, source);
                    strongest = strongest_arg_kind(strongest, k);
                }
            }
            strongest
        }
        _ => PickleArgKind::Unknown,
    }
}

// ---------------------------------------------------------------------------
// JavaScript / TypeScript
// ---------------------------------------------------------------------------

/// Match a JS/TS `call_expression` against the JS unsafe-deserialization
/// API list.
fn match_js_unserialize_call<'a>(
    node: tree_sitter::Node<'a>,
    source: &'a [u8],
) -> Option<PickleSite<'a>> {
    let func = node.child_by_field_name("function")?;
    let args = node.child_by_field_name("arguments")?;
    let arg_nodes = collect_named_args(args);
    let func = unwrap_callee(func);

    let api = match func.kind() {
        "identifier" => {
            // Bare `unserialize(...)` — destructured from `node-serialize`
            // or imported by name.
            match node_text(func, source)? {
                "unserialize" => PickleApi::JsUnserialize,
                _ => return None,
            }
        }
        "member_expression" => {
            let obj = func.child_by_field_name("object")?;
            let prop = func.child_by_field_name("property")?;
            let prop_text = node_text(prop, source)?;
            let recv = receiver_chain_label(obj, source);

            // B1 (CommandInjection lesson):
            // `require('node-serialize').unserialize(...)` and the
            // `(await import('node-serialize')).unserialize(...)` shape.
            // `receiver_chain_label` resolves require()/import() callees
            // to their canonical module-name label.
            //
            // Accepted aliases / receivers:
            //   - bare identifier `nodeSerialize` / `serialize`
            //   - `node-serialize` module (require()-resolved)
            //   - `serialize-javascript` module
            let unserialize_aliases = matches!(
                recv.as_str(),
                "nodeserialize"
                    | "node-serialize"
                    | "serialize"
                    | "serialize-javascript"
                    | "serializejavascript"
            );
            if unserialize_aliases && prop_text == "unserialize" {
                PickleApi::JsUnserialize
            } else {
                return None;
            }
        }
        _ => return None,
    };

    let first = arg_nodes.first().copied()?;
    let arg_kind = classify_pickle_arg_js(first, source);
    Some(PickleSite {
        call_node: node,
        api,
        arg_kind,
    })
}

/// Classify the shape of a JS/TS deserialization-call argument.
#[allow(clippy::only_used_in_recursion)]
fn classify_pickle_arg_js(node: tree_sitter::Node<'_>, source: &[u8]) -> PickleArgKind {
    match node.kind() {
        "string" => PickleArgKind::StaticLiteral,
        "template_string" => {
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "template_substitution" {
                    return PickleArgKind::InterpolatedOrConcat;
                }
            }
            PickleArgKind::StaticLiteral
        }
        "binary_expression" => {
            let left = node.child_by_field_name("left");
            let right = node.child_by_field_name("right");
            let mut found_var = false;
            for opt in [left, right].iter().flatten() {
                match classify_pickle_arg_js(*opt, source) {
                    PickleArgKind::UserVariable
                    | PickleArgKind::InterpolatedOrConcat
                    | PickleArgKind::Unknown => {
                        found_var = true;
                    }
                    _ => {}
                }
            }
            if found_var {
                PickleArgKind::InterpolatedOrConcat
            } else {
                PickleArgKind::StaticLiteral
            }
        }
        "identifier" | "member_expression" | "subscript_expression" | "call_expression" => {
            PickleArgKind::UserVariable
        }
        "arrow_function" | "function_expression" | "function" | "function_declaration" => {
            PickleArgKind::FunctionLike
        }
        "parenthesized_expression"
        | "await_expression"
        | "as_expression"
        | "type_assertion_expression"
        | "non_null_expression"
        | "satisfies_expression" => {
            for i in 0..node.named_child_count() {
                if let Some(c) = node.named_child(i) {
                    return classify_pickle_arg_js(c, source);
                }
            }
            PickleArgKind::Unknown
        }
        "ternary_expression" => {
            let consequence = node.child_by_field_name("consequence");
            let alternative = node.child_by_field_name("alternative");
            let mut strongest = PickleArgKind::StaticLiteral;
            for opt in [consequence, alternative].iter().flatten() {
                let k = classify_pickle_arg_js(*opt, source);
                strongest = strongest_arg_kind(strongest, k);
            }
            strongest
        }
        _ => PickleArgKind::Unknown,
    }
}

/// Combine two `PickleArgKind`s and keep the strongest signal:
/// `UserVariable > InterpolatedOrConcat > Unknown > FunctionLike >
/// StaticLiteral`.
fn strongest_arg_kind(a: PickleArgKind, b: PickleArgKind) -> PickleArgKind {
    fn rank(k: PickleArgKind) -> u8 {
        match k {
            PickleArgKind::UserVariable => 4,
            PickleArgKind::InterpolatedOrConcat => 3,
            PickleArgKind::Unknown => 2,
            PickleArgKind::FunctionLike => 1,
            PickleArgKind::StaticLiteral => 0,
        }
    }
    if rank(a) >= rank(b) {
        a
    } else {
        b
    }
}

// ---------------------------------------------------------------------------
// Helpers shared with eval/command_injection — `unwrap_callee`,
// `collect_named_args`, `node_text` live in `ast_helpers`. Only
// `receiver_chain_label` (which uses this detector's
// `call_expression_module_label`) and `js_string_literal_value` are kept
// local.
// ---------------------------------------------------------------------------

/// Lowercased "receiver label" for a JS/TS or Python member-call
/// receiver. Mirrors `command_injection::receiver_chain_label`, including
/// the `require('module-name')` / `(await import('module-name'))` descent
/// (B1-class fix from the command-injection self-audit, commit
/// `3c88328e`).
///
/// Implementation: delegate to the shared
/// [`receiver_chain_label`](crate::detectors::security::ast_helpers::receiver_chain_label)
/// passing this detector's [`call_expression_module_label`] as the
/// resolver — that's the only piece that varies between detectors (it
/// names the dangerous deserialization module(s) for *this* detector,
/// e.g. `node-serialize`).
fn receiver_chain_label(node: tree_sitter::Node<'_>, source: &[u8]) -> String {
    receiver_chain_label_shared(node, source, Some(&call_expression_module_label))
}

/// If `node` is `require('MODULE')` or `import('MODULE')` for a known
/// dangerous deserialization module, return the canonical lowercased
/// module name.
fn call_expression_module_label(
    node: tree_sitter::Node<'_>,
    source: &[u8],
) -> Option<&'static str> {
    debug_assert_eq!(node.kind(), "call_expression");
    let func = node.child_by_field_name("function")?;
    let func_text = node_text(func, source)?;
    let is_require_or_import =
        matches!(func.kind(), "identifier" | "import") && matches!(func_text, "require" | "import");
    if !is_require_or_import {
        return None;
    }
    let args = node.child_by_field_name("arguments")?;
    let arg_nodes = collect_named_args(args);
    let first = arg_nodes.first()?;
    let module = js_string_literal_value(*first, source)?;
    match module.as_str() {
        "node-serialize" => Some("node-serialize"),
        "serialize-javascript" => Some("serialize-javascript"),
        _ => None,
    }
}

/// Extract the inner content of a JS/TS string literal, stripping outer
/// quotes. Returns `None` for template strings.
fn js_string_literal_value(node: tree_sitter::Node<'_>, source: &[u8]) -> Option<String> {
    if node.kind() != "string" {
        return None;
    }
    let mut cursor = node.walk();
    let mut buf = String::new();
    let mut saw_fragment = false;
    for child in node.children(&mut cursor) {
        if child.kind() == "string_fragment" {
            if let Some(t) = node_text(child, source) {
                buf.push_str(t);
                saw_fragment = true;
            }
        }
    }
    if saw_fragment {
        return Some(buf);
    }
    let raw = node_text(node, source)?;
    let inner = raw
        .strip_prefix('"')
        .and_then(|s| s.strip_suffix('"'))
        .or_else(|| raw.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))?;
    Some(inner.to_string())
}

// `node_text` lives in `ast_helpers`; imported above.

// ---------------------------------------------------------------------------
// Line scanner (Ruby, PHP)
// ---------------------------------------------------------------------------

/// Recognize Ruby `Marshal.load` and PHP `unserialize` on a line.
fn match_line_pickle(line: &str, ext: &str) -> Option<(PickleApi, PickleArgKind)> {
    static RUBY_MARSHAL_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"\bMarshal\.load\s*\(").expect("valid regex"));
    static PHP_UNSERIALIZE_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"(?:^|[^.>])\bunserialize\s*\(").expect("valid regex"));

    let (re, api): (&Regex, PickleApi) = match ext {
        "rb" => (&*RUBY_MARSHAL_RE, PickleApi::RubyMarshalLoad),
        "php" => (&*PHP_UNSERIALIZE_RE, PickleApi::PhpUnserialize),
        _ => return None,
    };
    let m = re.find(line)?;
    let after = &line[m.end()..];
    let arg_kind = classify_line_arg(after);
    Some((api, arg_kind))
}

/// Cheap line-text classification of a deserialization argument for the
/// Ruby/PHP line path.
fn classify_line_arg(after_paren: &str) -> PickleArgKind {
    let trimmed = after_paren.trim_start();
    if trimmed.starts_with('"') || trimmed.starts_with('\'') {
        let quote = trimmed.as_bytes()[0];
        let mut i = 1;
        let bytes = trimmed.as_bytes();
        let mut had_interp = false;
        while i < bytes.len() {
            let c = bytes[i];
            if c == b'\\' {
                i += 2;
                continue;
            }
            if c == quote {
                break;
            }
            if quote == b'"' && c == b'#' && bytes.get(i + 1) == Some(&b'{') {
                had_interp = true;
            }
            if quote == b'"' && c == b'$' {
                had_interp = true;
            }
            i += 1;
        }
        if had_interp {
            PickleArgKind::InterpolatedOrConcat
        } else {
            PickleArgKind::StaticLiteral
        }
    } else if trimmed.starts_with(')') {
        PickleArgKind::Unknown
    } else {
        PickleArgKind::UserVariable
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_skips_cache_backend_paths() {
        // Cache backends only deserialize data they created themselves.
        assert!(
            PickleDeserializationDetector::is_trusted_serialization_context(
                "cache/backends/redis.py"
            )
        );
        assert!(
            PickleDeserializationDetector::is_trusted_serialization_context(
                "django/core/cache/backends/db.py"
            )
        );
        assert!(
            PickleDeserializationDetector::is_trusted_serialization_context(
                "sessions/backends/db.py"
            )
        );
        assert!(!PickleDeserializationDetector::is_trusted_serialization_context("myapp/views.py"));
    }

    // -----------------------------------------------------------------
    // Audit / regression tests for the AST-first migration.
    //
    // Cohort 1 (currently-passing-shape, 5): cases the line scanner
    //   handled and the AST migration must preserve.
    // Cohort 2 (audit-shape, 4): cases the line scanner could not
    //   reliably handle that the AST migration now resolves.
    // Cohort 3 (audit-pending, 3): new-capability tests that the AST
    //   migration explicitly addresses.
    // -----------------------------------------------------------------

    // ----- Cohort 1: currently-passing-shape -----

    /// Audit-shape: `pickle.loads(user_data)` Python — canonical Critical.
    #[test]
    fn test_detects_pickle_loads_with_user_input_python() {
        let content = "import pickle\ndef handle(user_data):\n    return pickle.loads(user_data)\n";
        let store = GraphBuilder::new().freeze();
        let detector =
            PickleDeserializationDetector::with_repository_path(PathBuf::from("/mock/repo"));
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("handler.py", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings
                .iter()
                .any(|f| matches!(f.severity, Severity::Critical)),
            "pickle.loads(user_data) should be Critical. Got: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }

    /// Audit-shape: `pickle.load(open(user_path))` Python — load() form.
    #[test]
    fn test_detects_pickle_load_from_file_python() {
        let content = "import pickle\ndef handle(user_path):\n    return pickle.load(open(user_path, 'rb'))\n";
        let store = GraphBuilder::new().freeze();
        let detector =
            PickleDeserializationDetector::with_repository_path(PathBuf::from("/mock/repo"));
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("h.py", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "pickle.load(open(user_path)) must fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Audit-shape: `dill.loads(user_data)` Python — third-party pickle.
    #[test]
    fn test_detects_dill_loads_python() {
        let content = "import dill\ndef handle(user_data):\n    return dill.loads(user_data)\n";
        let store = GraphBuilder::new().freeze();
        let detector =
            PickleDeserializationDetector::with_repository_path(PathBuf::from("/mock/repo"));
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("h.py", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings
                .iter()
                .any(|f| matches!(f.severity, Severity::Critical)),
            "dill.loads(user_data) should be Critical. Got: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }

    /// Audit-shape: `pickle.loads(b'\\x80...')` — static bytes literal.
    /// AST classifier sees `string` node, severity Low → filtered out.
    #[test]
    fn test_skips_pickle_loads_with_static_bytes() {
        let content = "import pickle\nsafe = pickle.loads(b'\\x80\\x04K\\x01.')\n";
        let store = GraphBuilder::new().freeze();
        let detector =
            PickleDeserializationDetector::with_repository_path(PathBuf::from("/mock/repo"));
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("safe.py", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "pickle.loads(staticBytes) must not fire post-filter. Got: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }

    /// Audit-shape: `let msg = "use pickle.loads to deserialize"` — the
    /// AST naturally separates string-literal text from `call` nodes, so
    /// nothing fires.
    #[test]
    fn test_skips_pickle_word_in_string_literal() {
        let content = "def doc():\n    msg = \"use pickle.loads to deserialize\"\n    return msg\n";
        let store = GraphBuilder::new().freeze();
        let detector =
            PickleDeserializationDetector::with_repository_path(PathBuf::from("/mock/repo"));
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("doc.py", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "`pickle.loads` inside a string literal must not fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    // ----- Cohort 2: audit-shape -----

    /// Audit-shape (B1-class): `require('node-serialize').unserialize(userData)`
    /// — receiver_chain_label resolves the require() callee to its
    /// canonical module label. Lesson from CommandInjection commit
    /// `3c88328e`.
    #[test]
    fn test_b1_pickle_loads_via_require_alias_js() {
        let content = "function go(userData) {\n    return require('node-serialize').unserialize(userData);\n}\n";
        let store = GraphBuilder::new().freeze();
        let detector =
            PickleDeserializationDetector::with_repository_path(PathBuf::from("/mock/repo"));
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("go.js", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "B1: require('node-serialize').unserialize(userData) must fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Audit-shape: `self.pickle.loads(data)` — member-of-member receiver
    /// must resolve to `"pickle"` via receiver_chain_label.
    #[test]
    fn test_b1_member_of_member_self_pickle_loads_python() {
        let content = "class S:\n    def go(self, data):\n        return self.pickle.loads(data)\n";
        let store = GraphBuilder::new().freeze();
        let detector =
            PickleDeserializationDetector::with_repository_path(PathBuf::from("/mock/repo"));
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("s.py", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "B1: self.pickle.loads(data) must fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Audit-shape: `class Pickler: def loads(self): pass` — `loads` is a
    /// method definition, not `pickle.loads`. The AST sees a function
    /// definition, not a call, so nothing fires.
    #[test]
    fn test_skips_unpickler_method_name() {
        let content = "class Pickler:\n    def loads(self, data):\n        return data\n\np = Pickler()\nresult = p.loads(b'x')\n";
        let store = GraphBuilder::new().freeze();
        let detector =
            PickleDeserializationDetector::with_repository_path(PathBuf::from("/mock/repo"));
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("p.py", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        // `p.loads(...)` must NOT fire — receiver is `p`, not `pickle`.
        assert!(
            findings.is_empty(),
            "Method-name `loads` must not be confused with pickle.loads. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Audit-shape: `pickle.loads(b'prefix' + user_data)` — concatenation
    /// arg classifier returns InterpolatedOrConcat → Critical.
    #[test]
    fn test_detects_pickle_loads_with_concatenation() {
        let content =
            "import pickle\ndef go(user_data):\n    return pickle.loads(b'prefix' + user_data)\n";
        let store = GraphBuilder::new().freeze();
        let detector =
            PickleDeserializationDetector::with_repository_path(PathBuf::from("/mock/repo"));
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("c.py", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings
                .iter()
                .any(|f| matches!(f.severity, Severity::Critical)),
            "pickle.loads(b'prefix' + user_data) should be Critical. Got: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }

    // ----- Cohort 3: audit-pending (un-ignored as the migration lands) -----

    /// Audit-pending → resolved: `pickle.loads(await get_data())` —
    /// classifier descends through `await` to the underlying call node.
    #[test]
    fn test_b4_classify_arg_through_await_python() {
        let content = "import pickle\nasync def go():\n    return pickle.loads(await get_data())\n";
        let store = GraphBuilder::new().freeze();
        let detector =
            PickleDeserializationDetector::with_repository_path(PathBuf::from("/mock/repo"));
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("a.py", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        let f = findings
            .iter()
            .find(|f| f.line_start == Some(3))
            .expect("B4: pickle.loads(await ...) must fire");
        assert!(
            matches!(f.severity, Severity::Critical),
            "B4: pickle.loads(await get_data()) should be Critical (UserVariable), got {:?}",
            f.severity
        );
    }

    /// Audit-pending → resolved: `numpy.load(user_path, allow_pickle=True)`
    /// — keyword_argument inspection only fires the sink when
    /// `allow_pickle=True`.
    #[test]
    fn test_numpy_load_allow_pickle_true_fires() {
        let content = "import numpy as np\ndef go(user_path):\n    a = np.load(user_path, allow_pickle=True)\n    b = np.load(user_path)\n    return (a, b)\n";
        let store = GraphBuilder::new().freeze();
        let detector =
            PickleDeserializationDetector::with_repository_path(PathBuf::from("/mock/repo"));
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("n.py", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        // Line 3 (allow_pickle=True) must fire; line 4 (default) must not.
        assert!(
            findings.iter().any(|f| f.line_start == Some(3)),
            "np.load(user_path, allow_pickle=True) must fire on line 3. Got: {:?}",
            findings
                .iter()
                .map(|f| (f.line_start, &f.title))
                .collect::<Vec<_>>()
        );
        assert!(
            !findings.iter().any(|f| f.line_start == Some(4)),
            "np.load(user_path) (default allow_pickle=False) must not fire. Got: {:?}",
            findings
                .iter()
                .map(|f| (f.line_start, &f.title))
                .collect::<Vec<_>>()
        );
    }

    /// Audit-pending → resolved: per-call argument-aware severity. Two
    /// `pickle.loads` in the same function: one variable (Critical),
    /// one static bytes literal (Low → filtered).
    #[test]
    fn test_severity_critical_for_user_input_low_for_static_bytes() {
        let content = "import pickle\ndef both(user_input):\n    a = pickle.loads(user_input)\n    b = pickle.loads(b'\\x80\\x04K\\x01.')\n    return (a, b)\n";
        let store = GraphBuilder::new().freeze();
        let detector =
            PickleDeserializationDetector::with_repository_path(PathBuf::from("/mock/repo"));
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("b.py", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        let var_finding = findings.iter().find(|f| f.line_start == Some(3));
        let lit_finding = findings.iter().find(|f| f.line_start == Some(4));
        assert!(
            var_finding.is_some(),
            "Variable-arg pickle.loads on line 3 must produce a finding"
        );
        assert!(
            matches!(var_finding.unwrap().severity, Severity::Critical),
            "Variable-arg pickle.loads should be Critical, got {:?}",
            var_finding.unwrap().severity
        );
        assert!(
            lit_finding.is_none(),
            "Static-bytes pickle.loads must be filtered (Low). Got: {:?}",
            lit_finding.map(|f| (&f.title, f.severity))
        );
    }

    // ----- Python from-import alias resolution -----

    /// `from pickle import loads; loads(user_data)` — bare-call must
    /// fire Critical. Previously missed because the matcher only
    /// inspected `attribute` callees. Mirrors `insecure_crypto`'s
    /// `test_python_bare_md5_after_from_import`.
    #[test]
    fn test_python_bare_pickle_loads_after_from_import() {
        let content =
            "from pickle import loads\n\ndef parse(user_data):\n    return loads(user_data)\n";
        let store = GraphBuilder::new().freeze();
        let detector =
            PickleDeserializationDetector::with_repository_path(PathBuf::from("/mock/repo"));
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("p.py", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings
                .iter()
                .any(|f| f.line_start == Some(4) && f.severity == Severity::Critical),
            "Should fire Critical on `loads(user_data)` after `from pickle import loads`. Got: {:?}",
            findings
                .iter()
                .map(|f| (f.line_start, f.severity, &f.title))
                .collect::<Vec<_>>()
        );
    }

    /// Audit shape: `import pickle as pkl; pkl.loads(user)`.
    ///
    /// `pkl.loads(...)` is an attribute call whose object text is
    /// `"pkl"`, not `"pickle"`. Without the module-alias resolver the
    /// matcher's `obj_label == "pickle"` comparison misses. Mirrors
    /// `test_python_bare_pickle_loads_after_from_import`, but for the
    /// `import M as N` shape.
    #[test]
    fn test_python_aliased_module_pickle_loads_detected() {
        let content =
            "import pickle as pkl\n\ndef parse(user_data):\n    return pkl.loads(user_data)\n";
        let store = GraphBuilder::new().freeze();
        let detector =
            PickleDeserializationDetector::with_repository_path(PathBuf::from("/mock/repo"));
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("p.py", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings
                .iter()
                .any(|f| f.line_start == Some(4) && f.severity == Severity::Critical),
            "Should fire Critical on `pkl.loads(user_data)` after `import pickle as pkl`. Got: {:?}",
            findings
                .iter()
                .map(|f| (f.line_start, f.severity, &f.title))
                .collect::<Vec<_>>()
        );
    }
}