repotoire 0.8.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
//! AST-driven extraction of [`super::predict::Evidence`] for Python
//! insecure-deserialize call sites.
//!
//! # Why a separate module
//!
//! The scorer in [`super::predict`] takes plain data
//! ([`super::predict::Evidence`]) so it can be unit-tested without an
//! AST. This module's job is to populate that struct from a
//! `tree_sitter::Node` for a Python `call` expression whose callee
//! names a deserialize API.
//!
//! Splitting the two halves matches Phase 2a/2b/2c/2d/2e/2f/2g's
//! `evidence.rs` split.
//!
//! # What this module knows about
//!
//! - Walking the module AST to collect every call whose callee is a
//!   recognized Python deserialize API
//!   ([`collect_python_deserialize_sites`]).
//! - Walking up from the call node to the enclosing
//!   `function_definition` (for name) and `class_definition`
//!   (informational).
//! - Detecting the function's decorator list (for the route-handler
//!   signal) and naming-convention match.
//! - For `yaml.load`: inspecting the `Loader=` kwarg and reclassifying
//!   the API from `Ambiguous` to `Safe` (Loader=SafeLoader) or
//!   `Unsafe` (Loader=Loader/FullLoader/UnsafeLoader, or absent).
//! - Detecting user-input identifiers within ±10 lines of the call
//!   site (line-level heuristic, mirrors the legacy
//!   `has_nearby_user_input`).
//! - Detecting `open(...)` flowing to the call (for the
//!   `local_file_source` signal — argument-text inspection).
//! - Reading the source line for `# repotoire: deserialize-safe[...]`
//!   or `# repotoire: deserialize-vulnerable[...]` annotations.
//!
//! # What this module deliberately does NOT do
//!
//! - Does not look for evidence in non-Python languages (D5 #5 scope).
//! - Does not detect restricted-Unpickler subclasses (D5 #2 v0
//!   limitation — user must annotate).
//! - Does not trace cross-statement `Loader=` flow (D5 #1 v0
//!   limitation — the kwarg value must be a literal attribute
//!   reference for the reclassification to fire).
//! - Does not trace `shelve.open(path)` path provenance (D5 #3 v0
//!   limitation).
//! - Does not detect `eval(...)` — handled by EvalDetector
//!   (D5 #4 carve-out).
//!
//! # Status
//!
//! Wired in via `mod.rs::scan_python_file_dual_branch` in Phase 2h's
//! commit 5 (integration). Every public symbol below is reachable
//! from the integration path.

use super::predict::{
    classify_deserialize_callee, extract_deserialize_safe_reason,
    extract_deserialize_vulnerable_source, line_contains_user_input,
    matches_route_handler_decorator, matches_route_handler_name, matches_trust_boundary_name,
    matches_upload_like_name, yaml_loader_is_safe, yaml_loader_is_unsafe, DeserializeApi, Evidence,
};
use crate::detectors::security::ast_helpers::{enclosing_python_function, node_text};
use std::collections::HashMap;
use tree_sitter::Node;

/// A Python deserialize call site discovered by walking the module
/// AST. Returned by [`collect_python_deserialize_sites`] so the
/// integration in `mod.rs` can iterate over every potentially-relevant
/// call without re-walking.
pub(super) struct PythonDeserializeSite<'a> {
    pub call_node: Node<'a>,
    pub api: DeserializeApi,
    /// The raw callee text used for the title/description (e.g.
    /// `pickle.loads`, `yaml.safe_load`). Resolved from the call
    /// expression's `function` child.
    pub callee_label: String,
}

/// Walk a Python module AST and collect every call whose callee is a
/// recognized deserialize API.
///
/// Skips:
/// - `eval(...)` calls: handled by EvalDetector per D5 #4.
/// - Unknown APIs: not in the recognized lexicon.
///
/// The yaml.load reclassification (Loader=SafeLoader → Safe) happens
/// here so the integration layer doesn't need to inspect kwargs.
pub(super) fn collect_python_deserialize_sites<'a>(
    module_root: Node<'a>,
    source: &'a [u8],
) -> Vec<PythonDeserializeSite<'a>> {
    let mut sites = Vec::new();
    let mut stack: Vec<Node<'_>> = vec![module_root];
    while let Some(node) = stack.pop() {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            stack.push(child);
        }
        if node.kind() != "call" {
            continue;
        }
        let Some(func) = node.child_by_field_name("function") else {
            continue;
        };
        let func_text = node_text(func, source).unwrap_or("");
        if func_text.is_empty() {
            continue;
        }

        // Skip `eval(...)` — handled by EvalDetector (D5 #4 carve-out).
        if is_eval_call(func_text) {
            continue;
        }

        let mut api = classify_deserialize_callee(func_text);

        // Skip Unknown APIs entirely — the predictor only fires on
        // recognized deserialize calls.
        if !api.is_recognized() {
            continue;
        }

        // yaml.load reclassification: inspect Loader= kwarg.
        if matches!(api, DeserializeApi::Ambiguous) && is_yaml_load(func_text) {
            api = reclassify_yaml_load(node, source);
        }

        sites.push(PythonDeserializeSite {
            call_node: node,
            api,
            callee_label: func_text.to_string(),
        });
    }
    sites
}

/// True iff the callee text names the Python builtin `eval` (NOT
/// `obj.eval` method, NOT `ast.literal_eval`).
///
/// `eval(...)` is in scope of EvalDetector; the dual-branch
/// InsecureDeserialize migration skips it (D5 #4).
fn is_eval_call(func_text: &str) -> bool {
    // Bare `eval`. Method calls like `obj.eval(...)` have dotted
    // callees and don't match.
    func_text == "eval"
}

/// True iff the callee text names `yaml.load` (or an aliased version
/// like `y.load` where `y` is `yaml`).
///
/// We only check the tail; the alias-resolved API classification
/// already happened in `classify_deserialize_callee`. This helper
/// gates the Loader= reclassification step.
fn is_yaml_load(func_text: &str) -> bool {
    func_text == "yaml.load" || func_text.ends_with(".yaml.load")
    // Bare `load` after `from yaml import load` — the v0 model
    // doesn't follow this alias path; documented under D5.
}

/// For a `yaml.load(...)` call, inspect the `Loader=` kwarg to decide
/// whether to upgrade `DeserializeApi::Ambiguous` to `Safe` or
/// `Unsafe`.
///
/// Reclassification rules:
/// - `Loader=yaml.SafeLoader` / `Loader=SafeLoader` /
///   `Loader=yaml.CSafeLoader` / `Loader=CSafeLoader` → `Safe`.
/// - `Loader=yaml.Loader` / `Loader=yaml.FullLoader` /
///   `Loader=yaml.UnsafeLoader` → `Unsafe`.
/// - `Loader=` kwarg absent → `Unsafe` (the dangerous default in
///   PyYAML < 5.1, deprecated form in PyYAML ≥ 5.1).
/// - `Loader=<dynamic value>` (identifier reference the predictor
///   cannot resolve) → `Ambiguous` (fall through to weighted scoring).
fn reclassify_yaml_load<'a>(call_node: Node<'a>, source: &'a [u8]) -> DeserializeApi {
    let Some(args) = call_node.child_by_field_name("arguments") else {
        // No arguments — call is malformed, treat as Unsafe to be safe.
        return DeserializeApi::Unsafe;
    };
    let kwargs = collect_keyword_arguments(args, source);
    let Some(loader_val) = kwargs.get("Loader") else {
        // No Loader= kwarg — the unsafe default.
        return DeserializeApi::Unsafe;
    };
    if yaml_loader_is_safe(loader_val) {
        return DeserializeApi::Safe;
    }
    if yaml_loader_is_unsafe(loader_val) {
        return DeserializeApi::Unsafe;
    }
    // Dynamic value (identifier reference) — fall through to
    // weighted scoring with the Ambiguous classification.
    DeserializeApi::Ambiguous
}

/// Extract typed evidence from a Python deserialize call node.
///
/// `call_node` must be a `call` AST node whose function names a
/// recognized deserialize API (post-`collect_python_deserialize_sites`
/// filter). `module_root` is the file's module-level root node.
/// `source` is the file's raw bytes. `lines` is the pre-split
/// source-line slice the scanner already builds; used for the
/// annotation parsing and the user-input proximity check.
///
/// `file_path` is the source file path string; populated into the
/// returned `Evidence.file_path` for diagnostics. `api` is the
/// classification produced by `collect_python_deserialize_sites`
/// (post-Loader= reclassification for yaml.load).
///
/// Never panics; missing fields produce `None`/`false`/defaults.
pub(super) fn extract_python_evidence<'a>(
    call_node: Node<'a>,
    _module_root: Node<'a>,
    source: &'a [u8],
    lines: &[&str],
    file_path: Option<String>,
    api: DeserializeApi,
    callee_label: String,
) -> Evidence {
    let mut ev = Evidence {
        file_path,
        api: Some(api),
        callee_label: Some(callee_label),
        ..Default::default()
    };

    // ── Enclosing function (for name) and class. ──
    let fn_node = enclosing_python_function(call_node);
    if let Some(fn_node) = fn_node {
        if let Some(name_node) = fn_node.child_by_field_name("name") {
            if let Some(name) = node_text(name_node, source) {
                ev.enclosing_function = Some(name.to_string());
            }
        }
    }
    ev.enclosing_class = enclosing_python_class_name(call_node, source);

    // ── Function-name-based signals. ──
    if let Some(fn_name) = &ev.enclosing_function {
        ev.enclosing_upload_like = matches_upload_like_name(fn_name);
        ev.trust_boundary_name = matches_trust_boundary_name(fn_name);
        if matches_route_handler_name(fn_name) {
            ev.enclosing_route_handler = true;
        }
    }

    // ── Decorator-based route-handler detection. ──
    if !ev.enclosing_route_handler {
        if let Some(fn_node) = fn_node {
            if function_has_route_decorator(fn_node, lines) {
                ev.enclosing_route_handler = true;
            }
        }
    }

    // ── User-input proximity check (±10 lines). ──
    let call_line = call_node.start_position().row;
    ev.user_input_nearby = check_user_input_nearby(lines, call_line, 10);

    // ── Local-file source detection (argument text inspection). ──
    ev.local_file_source = call_has_local_file_source(call_node, source);

    // ── Source-line annotations. ──
    if let Some(line) = lines.get(call_line) {
        ev.deserialize_safe_annotation = extract_deserialize_safe_reason(line);
        ev.deserialize_vulnerable_annotation = extract_deserialize_vulnerable_source(line);
    }

    ev
}

// ─────────────────────────────────────────────────────────────────────────────
// Argument inspection helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Collect keyword arguments from an `argument_list` into a name→value
/// map. The value is the raw source text of the argument value
/// expression.
fn collect_keyword_arguments(args_node: Node<'_>, source: &[u8]) -> HashMap<String, String> {
    let mut map = HashMap::new();
    let mut cursor = args_node.walk();
    for child in args_node.children(&mut cursor) {
        if !child.is_named() {
            continue;
        }
        if child.kind() != "keyword_argument" {
            continue;
        }
        let name = child
            .child_by_field_name("name")
            .and_then(|n| node_text(n, source))
            .map(str::to_string);
        let value = child
            .child_by_field_name("value")
            .and_then(|n| node_text(n, source))
            .map(str::to_string);
        if let (Some(n), Some(v)) = (name, value) {
            map.insert(n, v);
        }
    }
    map
}

/// True iff the call's arguments include an `open(...)` invocation —
/// either as a direct positional arg, or as a receiver chain like
/// `open(p).read()` or `open(p, 'rb').read()`.
///
/// This is a structural check on the argument text; the v0 predictor
/// does not trace local-variable rebinding (D5 #2 v0 limitation
/// territory).
fn call_has_local_file_source(call_node: Node<'_>, source: &[u8]) -> bool {
    let Some(args) = call_node.child_by_field_name("arguments") else {
        return false;
    };
    let Some(text) = node_text(args, source) else {
        return false;
    };
    // Cheap text-level heuristic: look for `open(` in the argument list.
    text.contains("open(")
}

// ─────────────────────────────────────────────────────────────────────────────
// Decorator inspection
// ─────────────────────────────────────────────────────────────────────────────

/// True iff the `function_definition` node (Python) is preceded by a
/// `decorated_definition` whose decorator list contains a recognized
/// route-handler decorator. The check inspects the source-line text
/// because tree-sitter's grammar wraps decorated functions in a
/// `decorated_definition` node — we walk up one level to look.
fn function_has_route_decorator(fn_node: Node<'_>, lines: &[&str]) -> bool {
    let mut parent = fn_node.parent();
    while let Some(p) = parent {
        if p.kind() == "decorated_definition" {
            // Inspect each decorator child via source-line text.
            let mut cursor = p.walk();
            for child in p.children(&mut cursor) {
                if child.kind() == "decorator" {
                    let line_idx = child.start_position().row;
                    if let Some(line) = lines.get(line_idx) {
                        if matches_route_handler_decorator(line) {
                            return true;
                        }
                    }
                }
            }
            break;
        }
        if p.kind() == "module" {
            break;
        }
        parent = p.parent();
    }
    false
}

// ─────────────────────────────────────────────────────────────────────────────
// Enclosing class
// ─────────────────────────────────────────────────────────────────────────────

fn enclosing_python_class_name<'a>(node: Node<'a>, source: &'a [u8]) -> Option<String> {
    let mut cur = node.parent()?;
    loop {
        if cur.kind() == "class_definition" {
            let name = cur.child_by_field_name("name")?;
            return node_text(name, source).map(str::to_string);
        }
        if cur.kind() == "module" {
            return None;
        }
        cur = cur.parent()?;
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// User-input proximity check
// ─────────────────────────────────────────────────────────────────────────────

/// True iff any line within ±`radius` of `call_line` (0-indexed)
/// contains a user-input identifier per
/// `predict::line_contains_user_input`.
///
/// Mirrors the legacy `has_nearby_user_input` helper from
/// `detectors/user_input.rs` (which the legacy detector uses); we
/// keep the implementation here rather than importing it because:
/// (1) the legacy helper accepts a `&[&str]` over the file, same as us;
/// (2) the user-input lexicon for `deserialize` is curated specific
/// to the Phase 2h decisions doc and may diverge from the legacy
/// helper's global lexicon over time.
fn check_user_input_nearby(lines: &[&str], call_line: usize, radius: usize) -> bool {
    let start = call_line.saturating_sub(radius);
    let end = (call_line + radius + 1).min(lines.len());
    for line in &lines[start..end] {
        if line_contains_user_input(line) {
            return true;
        }
    }
    false
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::detectors::ast_fingerprint::parse_root_ext;
    use crate::parsers::lightweight::Language;

    /// Parse `source` as Python and find the first `call` node whose
    /// function chain ends with the given attribute or identifier
    /// name.
    fn first_call_with_attr<'tree>(
        tree: &'tree tree_sitter::Tree,
        source: &[u8],
        attr_name: &str,
    ) -> tree_sitter::Node<'tree> {
        fn walk<'a>(
            node: tree_sitter::Node<'a>,
            source: &[u8],
            attr_name: &str,
        ) -> Option<tree_sitter::Node<'a>> {
            if node.kind() == "call" {
                if let Some(func) = node.child_by_field_name("function") {
                    let text = node_text(func, source).unwrap_or("");
                    let last = text.rsplit('.').next().unwrap_or("");
                    if last == attr_name {
                        return Some(node);
                    }
                }
            }
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if let Some(found) = walk(child, source, attr_name) {
                    return Some(found);
                }
            }
            None
        }
        walk(tree.root_node(), source, attr_name)
            .unwrap_or_else(|| panic!("no call to {} found in source", attr_name))
    }

    fn extract(src: &str, attr: &str) -> Evidence {
        let tree = parse_root_ext(src, Language::Python, "py").expect("parse python");
        let root = tree.root_node();
        let call = first_call_with_attr(&tree, src.as_bytes(), attr);
        let lines: Vec<&str> = src.lines().collect();
        let func_text = call
            .child_by_field_name("function")
            .and_then(|f| node_text(f, src.as_bytes()))
            .unwrap_or("")
            .to_string();
        let mut api = classify_deserialize_callee(&func_text);
        if matches!(api, DeserializeApi::Ambiguous) && is_yaml_load(&func_text) {
            api = reclassify_yaml_load(call, src.as_bytes());
        }
        extract_python_evidence(call, root, src.as_bytes(), &lines, None, api, func_text)
    }

    fn collect_sites(src: &str) -> Vec<DeserializeApi> {
        let tree = parse_root_ext(src, Language::Python, "py").expect("parse python");
        let root = tree.root_node();
        collect_python_deserialize_sites(root, src.as_bytes())
            .into_iter()
            .map(|s| s.api)
            .collect()
    }

    // ─── collect_python_deserialize_sites: API classification ───
    #[test]
    fn collect_picks_up_pickle_loads() {
        let sites = collect_sites("import pickle\npickle.loads(blob)\n");
        assert_eq!(sites, vec![DeserializeApi::Unsafe]);
    }

    #[test]
    fn collect_picks_up_yaml_safe_load() {
        let sites = collect_sites("import yaml\nyaml.safe_load(blob)\n");
        assert_eq!(sites, vec![DeserializeApi::Safe]);
    }

    #[test]
    fn collect_picks_up_json_loads() {
        let sites = collect_sites("import json\njson.loads(blob)\n");
        assert_eq!(sites, vec![DeserializeApi::Safe]);
    }

    #[test]
    fn collect_picks_up_marshal_loads_as_unsafe() {
        let sites = collect_sites("import marshal\nmarshal.loads(blob)\n");
        assert_eq!(sites, vec![DeserializeApi::Unsafe]);
    }

    #[test]
    fn collect_picks_up_dill_loads_as_unsafe() {
        let sites = collect_sites("import dill\ndill.loads(blob)\n");
        assert_eq!(sites, vec![DeserializeApi::Unsafe]);
    }

    #[test]
    fn collect_skips_eval_calls() {
        // eval() is handled by EvalDetector (D5 #4); InsecureDeserialize
        // dual-branch path skips it.
        let sites = collect_sites("eval(blob)\n");
        assert!(sites.is_empty(), "eval() must be skipped, got {:?}", sites);
    }

    #[test]
    fn collect_skips_unknown_callees() {
        let sites = collect_sites("import json\njson.dumps({'a': 1})\nfoo.bar('x')\n");
        assert!(sites.is_empty());
    }

    // ─── yaml.load reclassification ───
    #[test]
    fn collect_yaml_load_without_loader_is_unsafe() {
        let sites = collect_sites("import yaml\nyaml.load(blob)\n");
        assert_eq!(sites, vec![DeserializeApi::Unsafe]);
    }

    #[test]
    fn collect_yaml_load_with_safeloader_is_safe() {
        let sites = collect_sites("import yaml\nyaml.load(blob, Loader=yaml.SafeLoader)\n");
        assert_eq!(sites, vec![DeserializeApi::Safe]);
    }

    #[test]
    fn collect_yaml_load_with_csafeloader_is_safe() {
        let sites = collect_sites("import yaml\nyaml.load(blob, Loader=yaml.CSafeLoader)\n");
        assert_eq!(sites, vec![DeserializeApi::Safe]);
    }

    #[test]
    fn collect_yaml_load_with_full_loader_is_unsafe() {
        // FullLoader was the PyYAML 5.1 "compromise" loader, but
        // CVE-2020-1747 showed it still executes code in < 5.4.
        // Per decisions doc, treat as Unsafe.
        let sites = collect_sites("import yaml\nyaml.load(blob, Loader=yaml.FullLoader)\n");
        assert_eq!(sites, vec![DeserializeApi::Unsafe]);
    }

    #[test]
    fn collect_yaml_load_with_default_loader_is_unsafe() {
        let sites = collect_sites("import yaml\nyaml.load(blob, Loader=yaml.Loader)\n");
        assert_eq!(sites, vec![DeserializeApi::Unsafe]);
    }

    #[test]
    fn collect_yaml_load_with_dynamic_loader_is_ambiguous() {
        // Loader=<identifier> is a v0 cross-statement limitation; the
        // predictor falls back to Ambiguous and weighted scoring.
        let sites = collect_sites(
            "import yaml\n\
             def f(blob, dynamic_loader):\n\
             \x20   return yaml.load(blob, Loader=dynamic_loader)\n",
        );
        assert_eq!(sites, vec![DeserializeApi::Ambiguous]);
    }

    // ─── Enclosing function detection ───
    #[test]
    fn detects_enclosing_function_name() {
        let src = "\
            import pickle\n\
            def load_cache(path):\n\
            \x20   return pickle.loads(open(path, 'rb').read())\n";
        let ev = extract(src, "loads");
        assert_eq!(ev.enclosing_function.as_deref(), Some("load_cache"));
    }

    #[test]
    fn detects_enclosing_class_name() {
        let src = "\
            import pickle\n\
            class Cache:\n\
            \x20   def load(self, path):\n\
            \x20       return pickle.loads(open(path, 'rb').read())\n";
        let ev = extract(src, "loads");
        assert_eq!(ev.enclosing_class.as_deref(), Some("Cache"));
    }

    // ─── Upload-like name detection ───
    #[test]
    fn detects_upload_like_function_name() {
        let src = "\
            import yaml\n\
            def upload_handler(blob):\n\
            \x20   return yaml.load(blob, Loader=dyn)\n";
        let ev = extract(src, "load");
        assert!(ev.enclosing_upload_like);
        // Also matches route-handler name (`_handler` suffix).
        assert!(ev.enclosing_route_handler);
    }

    #[test]
    fn detects_load_function_name_as_upload_like() {
        let src = "\
            import yaml\n\
            def load_payload(blob):\n\
            \x20   return yaml.load(blob, Loader=dyn)\n";
        let ev = extract(src, "load");
        assert!(ev.enclosing_upload_like);
    }

    // ─── Trust-boundary name detection ───
    #[test]
    fn detects_trust_boundary_name() {
        let src = "\
            import yaml\n\
            def parse_trusted_config(blob):\n\
            \x20   return yaml.load(blob, Loader=dyn)\n";
        let ev = extract(src, "load");
        assert!(ev.trust_boundary_name);
    }

    #[test]
    fn detects_admin_in_name() {
        let src = "\
            import yaml\n\
            def load_admin_settings(blob):\n\
            \x20   return yaml.load(blob, Loader=dyn)\n";
        let ev = extract(src, "load");
        assert!(ev.trust_boundary_name);
    }

    // ─── Decorator-based route-handler detection ───
    #[test]
    fn detects_flask_route_decorator() {
        let src = "\
            from flask import request\n\
            import yaml\n\
            @app.route('/config', methods=['POST'])\n\
            def update(blob):\n\
            \x20   return yaml.load(blob, Loader=dyn)\n";
        let ev = extract(src, "load");
        assert!(ev.enclosing_route_handler);
    }

    #[test]
    fn detects_fastapi_router_decorator() {
        let src = "\
            import yaml\n\
            @router.post('/config')\n\
            def update(blob):\n\
            \x20   return yaml.load(blob, Loader=dyn)\n";
        let ev = extract(src, "load");
        assert!(ev.enclosing_route_handler);
    }

    #[test]
    fn no_route_handler_for_plain_function() {
        let src = "\
            import yaml\n\
            def compute(blob):\n\
            \x20   return yaml.load(blob, Loader=dyn)\n";
        let ev = extract(src, "load");
        assert!(!ev.enclosing_route_handler);
    }

    // ─── User-input proximity ───
    #[test]
    fn detects_request_data_within_radius() {
        let src = "\
            import yaml\n\
            def f(req):\n\
            \x20   data = req.request.data\n\
            \x20   return yaml.load(data, Loader=dyn)\n";
        let ev = extract(src, "load");
        assert!(ev.user_input_nearby);
    }

    #[test]
    fn detects_request_json() {
        let src = "\
            import yaml\n\
            def f():\n\
            \x20   body = request.json\n\
            \x20   return yaml.load(body, Loader=dyn)\n";
        let ev = extract(src, "load");
        assert!(ev.user_input_nearby);
    }

    #[test]
    fn no_user_input_for_local_var() {
        let src = "\
            import yaml\n\
            def f():\n\
            \x20   data = compute()\n\
            \x20   return yaml.load(data, Loader=dyn)\n";
        let ev = extract(src, "load");
        assert!(!ev.user_input_nearby);
    }

    // ─── Local-file source detection ───
    #[test]
    fn detects_open_in_pickle_call() {
        let src = "\
            import pickle\n\
            def load_cache(path):\n\
            \x20   return pickle.loads(open(path, 'rb').read())\n";
        let ev = extract(src, "loads");
        assert!(ev.local_file_source);
    }

    #[test]
    fn no_local_file_for_plain_arg() {
        let src = "\
            import pickle\n\
            def load_cache(blob):\n\
            \x20   return pickle.loads(blob)\n";
        let ev = extract(src, "loads");
        assert!(!ev.local_file_source);
    }

    // ─── Annotation parsing ───
    #[test]
    fn extracts_deserialize_safe_annotation() {
        let src = "\
            import pickle\n\
            def f(blob):\n\
            \x20   return pickle.loads(blob)  # repotoire: deserialize-safe[hmac-verified]\n";
        let ev = extract(src, "loads");
        assert_eq!(
            ev.deserialize_safe_annotation.as_deref(),
            Some("hmac-verified")
        );
    }

    #[test]
    fn extracts_deserialize_vulnerable_annotation() {
        let src = "\
            import json\n\
            def f(blob):\n\
            \x20   return json.loads(blob)  # repotoire: deserialize-vulnerable[third-party]\n";
        let ev = extract(src, "loads");
        assert_eq!(
            ev.deserialize_vulnerable_annotation.as_deref(),
            Some("third-party")
        );
    }

    #[test]
    fn does_not_extract_unrelated_annotation() {
        let src = "\
            import pickle\n\
            def f(blob):\n\
            \x20   return pickle.loads(blob)  # repotoire: jwt-safe[verified]\n";
        let ev = extract(src, "loads");
        assert!(ev.deserialize_safe_annotation.is_none());
        assert!(ev.deserialize_vulnerable_annotation.is_none());
    }

    // ─── API classification per Evidence ───
    #[test]
    fn evidence_records_safe_api_for_yaml_safe_load() {
        let src = "import yaml\nyaml.safe_load(blob)\n";
        let ev = extract(src, "safe_load");
        assert_eq!(ev.api, Some(DeserializeApi::Safe));
    }

    #[test]
    fn evidence_records_unsafe_api_for_pickle_loads() {
        let src = "import pickle\npickle.loads(blob)\n";
        let ev = extract(src, "loads");
        assert_eq!(ev.api, Some(DeserializeApi::Unsafe));
    }

    #[test]
    fn evidence_records_callee_label() {
        let src = "import pickle\npickle.loads(blob)\n";
        let ev = extract(src, "loads");
        assert_eq!(ev.callee_label.as_deref(), Some("pickle.loads"));
    }

    // ─── End-to-end integration: full evidence for Case A ───
    #[test]
    fn case_a_full_evidence_yaml_safe_load_in_handler() {
        // Case A from decisions doc §6: yaml.safe_load(request.data)
        // in Flask handler. Evidence should mark Safe API + user input
        // + route handler. Predictor will Step 1.5 collapse to Benign.
        let src = "\
            from flask import request\n\
            import yaml\n\
            @app.route('/config', methods=['POST'])\n\
            def update_config():\n\
            \x20   return yaml.safe_load(request.data)\n";
        let ev = extract(src, "safe_load");
        assert_eq!(ev.api, Some(DeserializeApi::Safe));
        assert!(ev.user_input_nearby);
        assert!(ev.enclosing_route_handler);
        assert_eq!(ev.enclosing_function.as_deref(), Some("update_config"));
    }

    // ─── End-to-end integration: full evidence for Case B ───
    #[test]
    fn case_b_full_evidence_pickle_loads_on_local_file() {
        // Case B from decisions doc §6: pickle.loads(f.read()) on
        // local file. Evidence should mark Unsafe API + local file
        // source. Predictor will Step 1.5 collapse to RealBug Critical.
        let src = "\
            import pickle\n\
            def load_cache():\n\
            \x20   with open('/var/cache/sessions.pkl', 'rb') as f:\n\
            \x20       return pickle.loads(f.read())\n";
        let ev = extract(src, "loads");
        assert_eq!(ev.api, Some(DeserializeApi::Unsafe));
        // The `f.read()` is the direct arg; we don't trace through the
        // local-var binding. So local_file_source is false for the
        // exact arg-text inspection.
        assert!(!ev.local_file_source);
        assert_eq!(ev.enclosing_function.as_deref(), Some("load_cache"));
    }

    #[test]
    fn case_b_alt_full_evidence_pickle_loads_direct_open() {
        // The direct shape: pickle.loads(open(path, 'rb').read()).
        let src = "\
            import pickle\n\
            def load_cache(path):\n\
            \x20   return pickle.loads(open(path, 'rb').read())\n";
        let ev = extract(src, "loads");
        assert_eq!(ev.api, Some(DeserializeApi::Unsafe));
        assert!(ev.local_file_source);
    }

    // ─── End-to-end integration: full evidence for Case D ───
    #[test]
    fn case_d_full_evidence_yaml_load_with_safeloader_reclassifies() {
        let src = "\
            import yaml\n\
            def f(blob):\n\
            \x20   return yaml.load(blob, Loader=yaml.SafeLoader)\n";
        let ev = extract(src, "load");
        // Reclassified Ambiguous → Safe via Loader=yaml.SafeLoader.
        assert_eq!(ev.api, Some(DeserializeApi::Safe));
    }

    #[test]
    fn case_d_alt_full_evidence_yaml_load_without_safeloader_is_unsafe() {
        let src = "\
            import yaml\n\
            def f(blob):\n\
            \x20   return yaml.load(blob)\n";
        let ev = extract(src, "load");
        assert_eq!(ev.api, Some(DeserializeApi::Unsafe));
    }
}