repotoire 0.9.0

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
//! Insecure-cookie detector (CWE-1004, CWE-614).
//!
//! Detects HTTP `Set-Cookie` issuance without `HttpOnly`, `Secure`, or
//! `SameSite` flags. Distinguishes server-side issuance (Flask, Django,
//! FastAPI, Starlette, aiohttp.web, ...) from client-side cookie-jar
//! storage (`http.cookiejar.CookieJar`, `requests.cookies.RequestsCookieJar`,
//! `httpx.Cookies`, ...) using a protocol-driven call-shape invariant:
//!
//! - **Server issuance**: `set_cookie(name: str, value: str, **flags)` —
//!   2+ positional args or any kwargs. Every server framework follows
//!   this shape because the caller has just named the cookie it's
//!   issuing.
//! - **Client storage**: `set_cookie(cookie: Cookie)` — exactly 1
//!   positional arg, no kwargs. Every stdlib / requests / httpx / aiohttp
//!   client jar follows this shape because the cookie's name is already
//!   baked into the `Cookie` instance.
//!
//! No server framework exposes a 1-arg `set_cookie`. Conversely, no
//! client jar takes a name+value pair. That asymmetry falls out of HTTP
//! itself, so this is an invariant rather than a heuristic.
//!
//! # Architecture
//!
//! Two scan paths, picked by file language (mirrors `insecure_crypto.rs`):
//!
//! 1. **AST path** (Python): walks the tree-sitter parse tree, finds
//!    every `set_cookie` / `set_signed_cookie` / `add_cookie_header` /
//!    `extract_cookies` call, classifies it via the shape invariant
//!    above, and only emits findings on server-issuance shapes.
//!    Stdlib-only methods (`add_cookie_header`, `extract_cookies`) are
//!    unconditionally suppressed; they have no equivalent on any server
//!    response object.
//!
//!    A per-file pre-pass (`class_attr_constructors_of` from
//!    `python_imports`) builds `class_jar_attrs: HashMap<class_name,
//!    HashSet<attr_name>>` from `self.<attr> = CookieJar()` style
//!    assignments. At each call site, if the receiver is `self.<attr>`
//!    and `<attr>` is in `class_jar_attrs[enclosing_class]`, the call is
//!    suppressed regardless of shape. This catches composition patterns
//!    like `httpx.Cookies` whose class doesn't inherit from `CookieJar`
//!    but holds one as `self.jar`.
//!
//! 2. **Line path** (JS, TS, JSX, TSX, PHP, Ruby, Java, Go): existing
//!    regex-based scanner kept as the fallback for languages that don't
//!    yet have AST coverage in this detector. The Python AST path
//!    handles the FP class identified in batch 1; JS/TS will get a
//!    similar migration in a later batch once OSS validation data exists
//!    for them.
//!
//! See:
//! - `docs/superpowers/specs/2026-05-09-detector-precision-batch1-design.md` §4
//! - `docs/plans/2026-05-08-security-detector-ast-architecture.md`

use crate::detectors::ast_fingerprint::parse_root_ext;
use crate::detectors::base::{Detector, DetectorConfig};
use crate::detectors::security::ast_helpers::{collect_named_args, node_text, unwrap_callee};
use crate::detectors::security::python_imports::{
    class_attr_constructors_of, collect_python_from_imports, collect_python_module_aliases,
    PythonAliases,
};
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, HashSet};
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use tracing::info;

// ---------------------------------------------------------------------------
// Supported file extensions
// ---------------------------------------------------------------------------

/// Extensions this detector processes. Python flows through
/// `scan_file_ast`; the rest fall through to the line scanner.
const SUPPORTED_EXTS: &[&str] = &["py", "js", "ts", "jsx", "tsx", "rb", "php", "java", "go"];

/// Subset of `SUPPORTED_EXTS` that uses the AST path.
const AST_EXTS: &[&str] = &["py"];

// ---------------------------------------------------------------------------
// Regex (line path only)
// ---------------------------------------------------------------------------

/// Line-path matcher for non-Python languages. Python is handled by the
/// AST path and never reaches this regex.
static COOKIE_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)(\.set_cookie\s*\(|response\.set_cookie\s*\(|res\.cookie\s*\(|response\.cookie\s*\(|setcookie\s*\()",
    )
    .expect("valid regex")
});

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

pub struct InsecureCookieDetector {
    repository_path: PathBuf,
    max_findings: usize,
}

impl InsecureCookieDetector {
    crate::detectors::detector_new!(50);

    fn relative_path(&self, path: &Path) -> PathBuf {
        crate::detectors::detector_relative_path(&self.repository_path, path)
    }

    /// Decide whether `(line, surrounding)` looks like a sensitive
    /// cookie (session, auth, token, ...). Severity matrix below uses
    /// this signal verbatim from the original implementation.
    fn is_sensitive_cookie(line: &str, surrounding: &str) -> (bool, String) {
        let combined = format!("{} {}", line, surrounding).to_lowercase();
        if combined.contains("session") {
            return (true, "session".to_string());
        }
        if combined.contains("auth") || combined.contains("token") {
            return (true, "authentication".to_string());
        }
        if combined.contains("jwt") || combined.contains("bearer") {
            return (true, "JWT/bearer token".to_string());
        }
        if combined.contains("csrf") || combined.contains("xsrf") {
            return (true, "CSRF token".to_string());
        }
        if combined.contains("remember") || combined.contains("login") {
            return (true, "remember-me/login".to_string());
        }
        if combined.contains("user") || combined.contains("account") {
            return (true, "user data".to_string());
        }
        (false, "general".to_string())
    }

    /// Inspect surrounding lines (a few before and ~15 after) to decide
    /// which cookie flags are present. This is a multi-line text
    /// inspection because Python's `response.set_cookie(...)` calls are
    /// often broken over many lines for readability. The flag-string
    /// detection is independent of how the call site itself was located
    /// (regex or AST).
    fn check_cookie_flags(lines: &[&str], cookie_line: usize) -> CookieFlags {
        let start = cookie_line.saturating_sub(3);
        let end = (cookie_line + 15).min(lines.len());
        let context = lines[start..end].join(" ").to_lowercase();
        CookieFlags {
            has_httponly: context.contains("httponly"),
            has_secure: context.contains("secure") && !context.contains("insecure"),
            has_samesite: context.contains("samesite"),
            samesite_value: if context.contains("samesite=strict")
                || context.contains("samesite='strict'")
            {
                Some("Strict".to_string())
            } else if context.contains("samesite=lax") || context.contains("samesite='lax'") {
                Some("Lax".to_string())
            } else if context.contains("samesite=none") || context.contains("samesite='none'") {
                Some("None".to_string())
            } else {
                None
            },
        }
    }

    /// Build a finding from a located cookie call site (Python AST or
    /// non-Python line). Severity logic preserved verbatim from the
    /// pre-migration code.
    #[allow(clippy::too_many_arguments)]
    fn build_finding_from_site(
        &self,
        path: &Path,
        line_num: u32,
        line_text: &str,
        surrounding: &str,
        flags: &CookieFlags,
        ext: &str,
        graph: &dyn crate::graph::GraphQuery,
    ) -> Option<Finding> {
        let (is_sensitive, cookie_type) = Self::is_sensitive_cookie(line_text, surrounding);

        let mut missing = Vec::new();
        if !flags.has_httponly {
            missing.push("HttpOnly");
        }
        if !flags.has_secure {
            missing.push("Secure");
        }
        if !flags.has_samesite {
            missing.push("SameSite");
        }
        if missing.is_empty() {
            return None;
        }

        let severity = if is_sensitive && !flags.has_httponly {
            Severity::Critical
        } else if is_sensitive {
            Severity::High
        } else if !flags.has_httponly {
            Severity::Medium
        } else {
            Severity::Low
        };

        let path_str = path.to_string_lossy().to_string();
        let containing_func = graph
            .find_function_at(&path_str, line_num)
            .map(|f| f.node_name(graph.interner()).to_string());

        let mut notes = Vec::new();
        if is_sensitive {
            notes.push(format!("🔐 {} cookie - high value target", cookie_type));
        }
        notes.push(format!("❌ Missing: {}", missing.join(", ")));
        if let Some(ss) = &flags.samesite_value {
            notes.push(format!("✓ SameSite={}", ss));
            if ss == "None" && !flags.has_secure {
                notes.push("⚠️ SameSite=None requires Secure flag!".to_string());
            }
        }
        if let Some(func) = containing_func {
            notes.push(format!("📦 In function: `{}`", func));
        }

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

        let suggestion = match ext {
            "py" => "```python\n\
                 response.set_cookie(\n\
                     'cookie_name',\n\
                     value,\n\
                     httponly=True,   # Prevents JavaScript access\n\
                     secure=True,     # HTTPS only\n\
                     samesite='Lax'   # CSRF protection\n\
                 )\n\
                 ```"
            .to_string(),
            "js" | "ts" => "```javascript\n\
                 res.cookie('cookie_name', value, {\n\
                     httpOnly: true,  // Prevents JavaScript access\n\
                     secure: true,    // HTTPS only\n\
                     sameSite: 'lax'  // CSRF protection\n\
                 });\n\
                 ```"
            .to_string(),
            "php" => "```php\n\
                 setcookie('cookie_name', $value, [\n\
                     'httponly' => true,\n\
                     'secure' => true,\n\
                     'samesite' => 'Lax'\n\
                 ]);\n\
                 ```"
            .to_string(),
            _ => "Add httponly, secure, and samesite flags.".to_string(),
        };

        Some(Finding {
            id: String::new(),
            detector: "InsecureCookieDetector".to_string(),
            severity,
            title: format!(
                "Cookie missing {} flag{}",
                missing[0],
                if missing.len() > 1 { "s" } else { "" }
            ),
            description: format!(
                "Cookie is missing security flags that protect against common attacks.{}",
                context_notes
            ),
            affected_files: vec![self.relative_path(path)],
            line_start: Some(line_num),
            line_end: Some(line_num),
            suggested_fix: Some(suggestion),
            estimated_effort: Some("5 minutes".to_string()),
            category: Some("security".to_string()),
            cwe_id: Some(if !flags.has_httponly {
                "CWE-1004".to_string()
            } else {
                "CWE-614".to_string()
            }),
            why_it_matters: Some(
                "• **HttpOnly** prevents XSS attacks from stealing cookies via JavaScript\n\
                 • **Secure** ensures cookies are only sent over HTTPS\n\
                 • **SameSite** prevents CSRF attacks by controlling cross-site requests"
                    .to_string(),
            ),
            ..Default::default()
        })
    }

    /// AST scanner for Python. Walks the tree once collecting cookie
    /// call sites (filtered by shape and receiver-class), then per-site
    /// applies the same severity matrix as the line scanner.
    fn scan_file_ast(
        &self,
        inputs: &ScanAstInputs<'_>,
        graph: &dyn crate::graph::GraphQuery,
    ) -> 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();

        // Build per-file Python alias maps (mirrors `insecure_crypto`).
        let alias_map = collect_python_from_imports(root, bytes);
        let module_aliases = collect_python_module_aliases(root, bytes);
        let aliases = PythonAliases::new(&alias_map, &module_aliases);

        // Pre-pass: which `self.<attr>` slots are jar instances?
        let jar_ctor_names: HashSet<&str> = HashSet::from([
            "CookieJar",
            "RequestsCookieJar",
            "LWPCookieJar",
            "MozillaCookieJar",
            "FileCookieJar",
            "http.cookiejar.CookieJar",
            "requests.cookies.RequestsCookieJar",
            "aiohttp.CookieJar",
        ]);
        let class_jar_attrs = class_attr_constructors_of(root, bytes, &aliases, &jar_ctor_names);

        // Recursive walk to collect emit-worthy cookie call sites. We
        // only push sites that pass classification (suppressed shapes
        // are filtered at collection time, not emission time).
        let mut sites: Vec<CookieSite<'_>> = Vec::new();
        collect_cookie_sites(root, bytes, &class_jar_attrs, &mut sites);

        for site in sites {
            if findings.len() >= self.max_findings {
                break;
            }
            let line_idx = site.line;
            // Per-line suppression comment (`# repotoire:ignore`).
            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 line_text = lines.get(line_idx).copied().unwrap_or("");
            let start = line_idx.saturating_sub(5);
            let end = (line_idx + 5).min(lines.len());
            let surrounding = lines[start..end].join(" ");
            let flags = Self::check_cookie_flags(&lines, line_idx);
            let line_num = (line_idx + 1) as u32;
            if let Some(finding) = self.build_finding_from_site(
                path,
                line_num,
                line_text,
                &surrounding,
                &flags,
                ext,
                graph,
            ) {
                findings.push(finding);
            }
        }

        findings
    }

    /// Legacy line scanner — preserved for non-Python languages.
    fn scan_file_line(
        &self,
        inputs: &ScanInputs<'_>,
        graph: &dyn crate::graph::GraphQuery,
    ) -> 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;
            }
            if !COOKIE_PATTERN.is_match(line) {
                continue;
            }
            let start = i.saturating_sub(5);
            let end = (i + 5).min(lines.len());
            let surrounding = lines[start..end].join(" ");
            let flags = Self::check_cookie_flags(&lines, i);
            let line_num = (i + 1) as u32;
            if let Some(finding) =
                self.build_finding_from_site(path, line_num, line, &surrounding, &flags, ext, graph)
            {
                findings.push(finding);
            }
        }
        findings
    }
}

struct CookieFlags {
    has_httponly: bool,
    has_secure: bool,
    has_samesite: bool,
    samesite_value: Option<String>,
}

// ---------------------------------------------------------------------------
// Cookie call-site collection (Python AST)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CookieSiteKind {
    /// Server-issuance `set_cookie(...)` / `set_signed_cookie(...)` —
    /// 2+ positional args, or any kwargs.
    ServerSetCookie,
}

struct CookieSite<'a> {
    #[allow(dead_code)] // kept for future analyzer extensions; kind discriminates emit shape
    call_node: tree_sitter::Node<'a>,
    #[allow(dead_code)]
    kind: CookieSiteKind,
    line: usize,
}

/// Walk the tree recursively pushing every emit-worthy cookie call
/// site. Suppressed shapes (client-jar 1-arg, stdlib-only method names,
/// receiver-class type-aware) are filtered HERE, not at emit time.
fn collect_cookie_sites<'a>(
    node: tree_sitter::Node<'a>,
    source: &[u8],
    class_jar_attrs: &HashMap<String, HashSet<String>>,
    out: &mut Vec<CookieSite<'a>>,
) {
    if node.kind() == "call" {
        if let Some(site) = classify_cookie_call(node, source, class_jar_attrs) {
            out.push(site);
        }
    }
    let mut c = node.walk();
    for child in node.children(&mut c) {
        collect_cookie_sites(child, source, class_jar_attrs, out);
    }
}

/// Cookie-method names that flow through the call-shape classifier.
/// `set_cookie` is the dual-shape one (server vs client). `set_signed_cookie`
/// is the Django signed variant — server-only; the shape check still applies
/// (always 2+ args in practice). `add_cookie_header` and `extract_cookies`
/// are stdlib-only and are SUPPRESSED unconditionally below.
const SHAPE_CLASSIFIED_METHODS: &[&str] = &["set_cookie", "set_signed_cookie"];
const STDLIB_ONLY_METHODS: &[&str] = &["add_cookie_header", "extract_cookies"];

fn classify_cookie_call<'a>(
    call: tree_sitter::Node<'a>,
    source: &[u8],
    class_jar_attrs: &HashMap<String, HashSet<String>>,
) -> Option<CookieSite<'a>> {
    let func = call.child_by_field_name("function")?;
    let func = unwrap_callee(func);

    // We only care about attribute callees (`receiver.method(...)`).
    // A bare `set_cookie(...)` would be a from-import shape; not a real
    // cookie call in any framework we care about (Flask/Django/etc all
    // expose set_cookie as an instance method). Skip.
    if func.kind() != "attribute" {
        return None;
    }
    let attr_node = func.child_by_field_name("attribute")?;
    let receiver = func.child_by_field_name("object")?;
    let method_name = node_text(attr_node, source)?;

    // Stdlib-only methods: SUPPRESS unconditionally.
    if STDLIB_ONLY_METHODS.contains(&method_name) {
        return None;
    }
    // Anything that isn't a recognized cookie-setter: not a cookie call.
    if !SHAPE_CLASSIFIED_METHODS.contains(&method_name) {
        return None;
    }

    // Receiver-type pre-pass suppression: if the receiver is `self.<attr>`
    // and `<attr>` was assigned to a known jar constructor inside the
    // enclosing class body, suppress regardless of call shape. This is
    // what catches httpx.Cookies.
    if let Some(attr) = self_attr_text(receiver, source) {
        if let Some(class_name) = enclosing_class_name(call, source) {
            if let Some(jar_attrs) = class_jar_attrs.get(&class_name) {
                if jar_attrs.contains(&attr) {
                    return None;
                }
            }
        }
    }

    // Call-shape classification: count positional + kwargs.
    let args_node = call.child_by_field_name("arguments")?;
    let arg_nodes = collect_named_args(args_node);
    let mut positional = 0usize;
    let mut kwargs = 0usize;
    for a in &arg_nodes {
        if a.kind() == "keyword_argument" {
            kwargs += 1;
        } else {
            positional += 1;
        }
    }

    // Client-jar shape: ≤1 positional, 0 kwargs → SUPPRESS.
    if positional <= 1 && kwargs == 0 {
        return None;
    }

    Some(CookieSite {
        call_node: call,
        kind: CookieSiteKind::ServerSetCookie,
        line: call.start_position().row,
    })
}

/// If `node` is `self.<attr>`, return `<attr>` as a String.
fn self_attr_text(node: tree_sitter::Node<'_>, source: &[u8]) -> Option<String> {
    if node.kind() != "attribute" {
        return None;
    }
    let obj = node.child_by_field_name("object")?;
    if node_text(obj, source)? != "self" {
        return None;
    }
    let attr = node.child_by_field_name("attribute")?;
    Some(node_text(attr, source)?.to_string())
}

/// Walk parent links to find the enclosing `class_definition` and
/// return its name.
fn enclosing_class_name(node: tree_sitter::Node<'_>, source: &[u8]) -> Option<String> {
    let mut cur = node.parent();
    while let Some(p) = cur {
        if p.kind() == "class_definition" {
            let name = p.child_by_field_name("name")?;
            return Some(node_text(name, source)?.to_string());
        }
        cur = p.parent();
    }
    None
}

// ---------------------------------------------------------------------------
// Detector trait impl
// ---------------------------------------------------------------------------

impl Detector for InsecureCookieDetector {
    fn name(&self) -> &'static str {
        "insecure-cookie"
    }
    fn description(&self) -> &'static str {
        "Detects cookies without security flags"
    }

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

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

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

    fn detect(
        &self,
        ctx: &crate::detectors::analysis_context::AnalysisContext,
    ) -> Result<Vec<Finding>> {
        let graph = ctx.graph;
        let files = &ctx.as_file_provider();
        let mut findings: Vec<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 crate::detectors::base::is_test_path(&path_str) {
                continue;
            }
            let raw = match files.content(path) {
                Some(c) => c,
                None => continue,
            };
            // Cheap pre-filter: skip files with no cookie-setting method
            // names. (The same set the regex would have keyed on, but
            // explicit so the AST path doesn't waste time parsing.)
            if !raw.contains("set_cookie")
                && !raw.contains("set_signed_cookie")
                && !raw.contains("setCookie")
                && !raw.contains("setcookie")
                && !raw.contains(".cookie(")
                && !raw.contains("res.cookie")
            {
                continue;
            }

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

        info!(
            "InsecureCookieDetector found {} findings (AST-aware Python, regex fallback for JS/PHP/...)",
            findings.len()
        );
        Ok(findings)
    }
}

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

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

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

    fn run(file: &str, content: &str) -> Vec<Finding> {
        let store = GraphBuilder::new().freeze();
        let detector = InsecureCookieDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(file, content)],
        );
        detector.detect(&ctx).expect("detection should succeed")
    }

    // -----------------------------------------------------------------
    // Pre-existing tests (preserved through migration). These exercise
    // the AST path on Python sources.
    // -----------------------------------------------------------------

    #[test]
    fn test_detects_insecure_cookie() {
        let findings = run(
            "app.py",
            "from flask import make_response\n\
             \n\
             def set_session(user_id):\n\
             \x20   resp = make_response(\"OK\")\n\
             \x20   resp.set_cookie('session_id', user_id)\n\
             \x20   return resp\n",
        );
        assert!(
            !findings.is_empty(),
            "Should detect cookie without security flags"
        );
        assert!(
            findings.iter().any(|f| f.title.contains("HttpOnly")
                || f.title.contains("Secure")
                || f.title.contains("SameSite")),
            "Finding should mention missing flag. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_secure_cookie() {
        let findings = run(
            "app.py",
            "from flask import make_response\n\
             \n\
             def set_session(user_id):\n\
             \x20   resp = make_response(\"OK\")\n\
             \x20   resp.set_cookie('session_id', user_id, httponly=True, secure=True, samesite='Lax')\n\
             \x20   return resp\n",
        );
        assert!(
            findings.is_empty(),
            "Should not detect anything for secure cookie. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_enum_cookie_value() {
        // Enum class fields named "cookie" — no `set_cookie` call at all,
        // so the AST path never produces a site.
        let findings = run(
            "params.py",
            "from enum import Enum\n\
             \n\
             class ParamTypes(Enum):\n\
             \x20   query = \"query\"\n\
             \x20   header = \"header\"\n\
             \x20   cookie = \"cookie\"\n",
        );
        assert!(
            findings.is_empty(),
            "Should not flag enum values containing 'cookie'. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_cookie_class_field() {
        let findings = run(
            "models.py",
            "class SecurityScheme:\n\
             \x20   cookie = \"apiKeyCookie\"\n\
             \x20   header = \"apiKeyHeader\"\n",
        );
        assert!(
            findings.is_empty(),
            "Should not flag class field assignments. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_cookie_attribute_access() {
        // `def set_cookie(self, key, value): self.cookies[key] = value`
        // — the body has no `.set_cookie(...)` CALL, only subscript
        // assignments. The AST classifier never produces a site.
        let findings = run(
            "response.py",
            "def set_cookie(self, key, value):\n\
             \x20   self.cookies[key] = value\n\
             \x20   self.cookies[key][\"secure\"] = True\n\
             \x20   self.cookies[key][\"httponly\"] = True\n",
        );
        assert!(
            findings.is_empty(),
            "Should not flag self.cookies[] attribute access. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_multiline_set_cookie_with_flags() {
        let findings = run(
            "middleware.py",
            "def process_response(self, request, response):\n\
             \x20   response.set_cookie(\n\
             \x20       settings.SESSION_COOKIE_NAME,\n\
             \x20       request.session.session_key,\n\
             \x20       max_age=max_age,\n\
             \x20       expires=expires,\n\
             \x20       domain=settings.SESSION_COOKIE_DOMAIN,\n\
             \x20       path=settings.SESSION_COOKIE_PATH,\n\
             \x20       secure=settings.SESSION_COOKIE_SECURE or None,\n\
             \x20       httponly=settings.SESSION_COOKIE_HTTPONLY or None,\n\
             \x20       samesite=settings.SESSION_COOKIE_SAMESITE,\n\
             \x20   )\n",
        );
        assert!(
            findings.is_empty(),
            "Should detect flags in multi-line set_cookie() call. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    // -----------------------------------------------------------------
    // New tests for the AST migration (§4 of the design doc).
    // 10 tests covering each branch of the new classifier.
    // -----------------------------------------------------------------

    /// Test 1: `jar.set_cookie(cookie)` — 1 positional, 0 kwargs.
    /// Client-jar shape; must NOT fire.
    #[test]
    fn test_no_finding_for_jar_set_cookie_single_arg() {
        let findings = run(
            "client.py",
            "from http.cookiejar import CookieJar\n\
             \n\
             def store(jar, cookie):\n\
             \x20   jar.set_cookie(cookie)\n",
        );
        assert!(
            findings.is_empty(),
            "Single-arg jar.set_cookie must not fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Test 2: full httpx-style FP. Class composes a CookieJar and calls
    /// `self.jar.set_cookie(cookie)`. Receiver-type-aware suppression
    /// catches this regardless of call shape.
    #[test]
    fn test_no_finding_for_self_jar_set_cookie_in_cookies_class() {
        let findings = run(
            "_models.py",
            "from http.cookiejar import CookieJar\n\
             \n\
             class Cookies:\n\
             \x20   def __init__(self):\n\
             \x20       self.jar = CookieJar()\n\
             \x20   def set(self, cookie):\n\
             \x20       self.jar.set_cookie(cookie)\n",
        );
        assert!(
            findings.is_empty(),
            "self.jar.set_cookie inside Cookies-with-self.jar=CookieJar() must not fire. \
             This is the httpx FP. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Test 3: `jar.add_cookie_header(req)` — stdlib-only method,
    /// unconditional suppress.
    #[test]
    fn test_no_finding_for_add_cookie_header() {
        let findings = run(
            "client.py",
            "def f(jar, req):\n\
             \x20   jar.add_cookie_header(req)\n",
        );
        assert!(
            findings.is_empty(),
            "add_cookie_header must not fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Test 4: `jar.extract_cookies(resp, req)` — stdlib-only method,
    /// unconditional suppress.
    #[test]
    fn test_no_finding_for_extract_cookies() {
        let findings = run(
            "client.py",
            "def f(jar, resp, req):\n\
             \x20   jar.extract_cookies(resp, req)\n",
        );
        assert!(
            findings.is_empty(),
            "extract_cookies must not fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Test 5: Flask `response.set_cookie('sid', value)` — 2 positional
    /// args, 0 kwargs. Server-issuance shape; MUST fire. This is the
    /// canonical regression test that proves we didn't kill server-side
    /// detection.
    #[test]
    fn test_finding_for_flask_set_cookie_string_kwargs() {
        let findings = run(
            "app.py",
            "def view(response, value):\n\
             \x20   response.set_cookie('sid', value)\n",
        );
        assert!(
            !findings.is_empty(),
            "Flask 2-arg response.set_cookie must fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Test 6: same as test_no_finding_for_secure_cookie — all flags
    /// present, no finding. Pinned again to ensure the new classifier
    /// doesn't produce an over-eager site.
    #[test]
    fn test_finding_for_flask_set_cookie_with_kwargs() {
        let findings = run(
            "app.py",
            "def view(response, value):\n\
             \x20   response.set_cookie('sid', value, httponly=True, secure=True, samesite='Lax')\n",
        );
        assert!(
            findings.is_empty(),
            "set_cookie with all flags must not fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Test 7: variable args — `response.set_cookie(key, value)`. Two
    /// positional args (regardless of whether they're literals or
    /// variables), so server shape; MUST fire.
    #[test]
    fn test_finding_for_flask_set_cookie_variable_args() {
        let findings = run(
            "app.py",
            "def view(response, key, value):\n\
             \x20   response.set_cookie(key, value)\n",
        );
        assert!(
            !findings.is_empty(),
            "set_cookie(key, value) (2 variables) must fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Test 8: `jar.set_cookie(cookies[0])` — 1 positional (a subscript
    /// expression). Client-jar shape; must NOT fire.
    #[test]
    fn test_no_finding_for_jar_set_cookie_with_subscript() {
        let findings = run(
            "client.py",
            "def f(jar, cookies):\n\
             \x20   jar.set_cookie(cookies[0])\n",
        );
        assert!(
            findings.is_empty(),
            "1-arg jar.set_cookie(cookies[0]) must not fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Test 9: `self.jar.set_cookie(self.cookie)` — 1 positional, no
    /// kwargs. Client-jar shape; must NOT fire. This is shape-based
    /// suppression (would also be caught by receiver-class suppression
    /// if the class defined `self.jar = CookieJar()`, but here we're
    /// pinning the shape rule alone).
    #[test]
    fn test_no_finding_for_jar_set_cookie_with_attr() {
        let findings = run(
            "client.py",
            "class Wrapper:\n\
             \x20   def store(self):\n\
             \x20       self.jar.set_cookie(self.cookie)\n",
        );
        assert!(
            findings.is_empty(),
            "self.jar.set_cookie(self.cookie) must not fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Test 10: Django `response.set_signed_cookie('sid', value)` —
    /// `set_signed_cookie` is in the SHAPE_CLASSIFIED_METHODS list.
    /// 2 positional → server shape; MUST fire.
    #[test]
    fn test_finding_for_django_set_signed_cookie() {
        let findings = run(
            "views.py",
            "def view(response, value):\n\
             \x20   response.set_signed_cookie('sid', value)\n",
        );
        assert!(
            !findings.is_empty(),
            "Django set_signed_cookie must fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }
}