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
//! Insecure TLS/Certificate Validation Detector (CWE-295)
//!
//! Detects disabled certificate verification across languages:
//! - Python: `verify=False`, disabled SSL context, urllib3 warning suppression
//! - JavaScript/Node: `rejectUnauthorized: false`, `NODE_TLS_REJECT_UNAUTHORIZED=0`
//! - Go: `InsecureSkipVerify: true`
//! - Java: Trust-all TrustManager, permissive HostnameVerifier
//! - Rust: danger_accept_invalid_certs(true)
//!
//! ## Blocking-tier promotion (0.9.0)
//!
//! A small set of *exact* syntactic anti-patterns are promoted to `Tier::Blocking`
//! (config-fact evidence, `rule` = one of `tls_verify_disabled` / `tls_skip_verify`).
//! Only **literal** values qualify — dynamic references (`rejectUnauthorized: opts.strict`,
//! `verify=cfg.verify`) stay `Advisory`. Commented-out code is never flagged.
//! Files in a test/fixture context remain `Advisory` (severity downgraded as before).

use crate::detectors::base::{is_test_file, Detector, DetectorConfig};
use crate::models::{deterministic_finding_id, Evidence, Finding, Severity, SourceSpan, Tier};
use anyhow::Result;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use tracing::{debug, info};

/// Patterns that indicate insecure TLS/certificate validation
const PYTHON_PATTERNS: &[(&str, &str, Severity)] = &[
    (
        "verify=False",
        "requests/urllib call with certificate verification disabled",
        Severity::High,
    ),
    (
        "verify = False",
        "requests/urllib call with certificate verification disabled",
        Severity::High,
    ),
    (
        "CERT_NONE",
        "SSL context with no certificate verification",
        Severity::Critical,
    ),
    (
        "check_hostname = False",
        "SSL hostname verification disabled",
        Severity::High,
    ),
    (
        "check_hostname=False",
        "SSL hostname verification disabled",
        Severity::High,
    ),
    (
        "InsecureRequestWarning",
        "urllib3 insecure request warning suppressed",
        Severity::Medium,
    ),
    (
        "create_default_context",
        "Custom SSL context (verify usage)",
        Severity::Low,
    ), // only if combined with CERT_NONE
];

const JS_PATTERNS: &[(&str, &str, Severity)] = &[
    (
        "rejectUnauthorized: false",
        "TLS certificate verification disabled",
        Severity::High,
    ),
    (
        "rejectUnauthorized:false",
        "TLS certificate verification disabled",
        Severity::High,
    ),
    (
        "rejectUnauthorized : false",
        "TLS certificate verification disabled",
        Severity::High,
    ),
    (
        "NODE_TLS_REJECT_UNAUTHORIZED",
        "Environment variable to disable TLS verification",
        Severity::Critical,
    ),
    (
        "process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'",
        "TLS verification disabled via environment",
        Severity::Critical,
    ),
    (
        "process.env.NODE_TLS_REJECT_UNAUTHORIZED = \"0\"",
        "TLS verification disabled via environment",
        Severity::Critical,
    ),
    (
        "agent: new https.Agent",
        "Custom HTTPS agent (check rejectUnauthorized)",
        Severity::Low,
    ),
];

const GO_PATTERNS: &[(&str, &str, Severity)] = &[
    (
        "InsecureSkipVerify: true",
        "TLS certificate verification skipped",
        Severity::High,
    ),
    (
        "InsecureSkipVerify:true",
        "TLS certificate verification skipped",
        Severity::High,
    ),
];

const JAVA_PATTERNS: &[(&str, &str, Severity)] = &[
    (
        "TrustAllCerts",
        "Trust-all certificate manager (no validation)",
        Severity::Critical,
    ),
    (
        "X509TrustManager",
        "Custom trust manager (may bypass validation)",
        Severity::Medium,
    ),
    (
        "ALLOW_ALL_HOSTNAME_VERIFIER",
        "Hostname verification disabled",
        Severity::High,
    ),
    (
        "NoopHostnameVerifier",
        "Hostname verification disabled",
        Severity::High,
    ),
    (
        "setHostnameVerifier(allHostsValid)",
        "Hostname verification disabled",
        Severity::High,
    ),
    (
        "SSLContext.getInstance(\"SSL\")",
        "Outdated SSL protocol (use TLS)",
        Severity::Medium,
    ),
];

const RUST_PATTERNS: &[(&str, &str, Severity)] = &[
    (
        "danger_accept_invalid_certs(true)",
        "Certificate validation disabled (reqwest)",
        Severity::High,
    ),
    (
        "danger_accept_invalid_hostnames(true)",
        "Hostname validation disabled (reqwest)",
        Severity::High,
    ),
    (
        "set_verify(SslVerifyMode::NONE)",
        "OpenSSL verification disabled",
        Severity::High,
    ),
];

/// Returns `true` when `pattern` appears in `line` and the character immediately
/// after the match is not alphanumeric or `_` (i.e. the match ends at a word
/// boundary).  Used to guard against `rejectUnauthorized: falseSomething` etc.
/// The caller has already confirmed `line.contains(pattern)`, so `find` always
/// succeeds; the `unwrap_or` is just defensive.
fn ends_at_word_boundary(line: &str, pattern: &str) -> bool {
    let after = line
        .find(pattern)
        .map(|i| &line[i + pattern.len()..])
        .unwrap_or("");
    after
        .chars()
        .next()
        .is_none_or(|c| !c.is_alphanumeric() && c != '_')
}

/// Classify whether a line containing a blocking-tier pattern is an *exact*
/// literal anti-pattern or merely a near-miss (dynamic value / metadata etc.).
///
/// Returns `Some(rule)` when the line qualifies for `Tier::Blocking`.
fn classify_blocking_rule(ext: &str, line: &str, pattern: &str) -> Option<&'static str> {
    match ext {
        "js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" => {
            if (pattern == "rejectUnauthorized: false"
                || pattern == "rejectUnauthorized:false"
                || pattern == "rejectUnauthorized : false")
                && ends_at_word_boundary(line, pattern)
            {
                return Some("tls_verify_disabled");
            }
            None
        }

        "py" | "pyi" => {
            if (pattern == "verify=False" || pattern == "verify = False")
                && ends_at_word_boundary(line, pattern)
            {
                return Some("tls_verify_disabled");
            }
            None
        }

        "go" => {
            if (pattern == "InsecureSkipVerify: true" || pattern == "InsecureSkipVerify:true")
                && ends_at_word_boundary(line, pattern)
            {
                return Some("tls_skip_verify");
            }
            None
        }

        _ => None,
    }
}

pub struct InsecureTlsDetector {
    max_findings: usize,
}

impl InsecureTlsDetector {
    pub fn new(_repository_path: impl Into<PathBuf>) -> Self {
        Self { max_findings: 50 }
    }

    fn get_patterns_for_ext(&self, ext: &str) -> Vec<(&'static str, &'static str, Severity)> {
        match ext {
            "py" | "pyi" => PYTHON_PATTERNS.to_vec(),
            "js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" => JS_PATTERNS.to_vec(),
            "go" => GO_PATTERNS.to_vec(),
            "java" | "kt" | "kts" => JAVA_PATTERNS.to_vec(),
            "rs" => RUST_PATTERNS.to_vec(),
            _ => vec![],
        }
    }

    fn scan_files(&self, file_list: &[(&Path, &str)]) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut seen: HashSet<(String, u32)> = HashSet::new();

        for (path, content) in file_list {
            if findings.len() >= self.max_findings {
                break;
            }

            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            let patterns = self.get_patterns_for_ext(ext);
            if patterns.is_empty() {
                continue;
            }

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

            // Downgrade severity in test files; also keep findings Advisory (never Blocking)
            let is_test = is_test_file(Path::new(&rel_path));

            if content.len() > 500_000 {
                continue;
            }

            let lines: Vec<&str> = content.lines().collect();
            for (line_no, line) in lines.iter().enumerate() {
                let line_num = (line_no + 1) as u32;
                let trimmed = line.trim();

                // Skip comments
                if trimmed.starts_with('#') || trimmed.starts_with("//") || trimmed.starts_with('*')
                {
                    continue;
                }

                // Check suppression
                let prev_line = if line_no > 0 {
                    Some(lines[line_no - 1])
                } else {
                    None
                };
                if crate::detectors::is_line_suppressed(line, prev_line) {
                    continue;
                }

                for (pattern, description, severity) in &patterns {
                    if !line.contains(pattern) {
                        continue;
                    }

                    // Skip matches inside string literals (e.g., pattern definitions in detector source)
                    if ext == "rs"
                        && (trimmed.starts_with('"')
                            || trimmed.starts_with("&\"")
                            || trimmed.starts_with("r#\"")
                            || trimmed.starts_with("r\""))
                    {
                        continue;
                    }

                    // Skip low-confidence patterns unless combined with other signals
                    if *severity == Severity::Low {
                        continue; // Only flag direct insecure patterns
                    }

                    // For "InsecureRequestWarning", only flag if it's being suppressed
                    if *pattern == "InsecureRequestWarning"
                        && !line.contains("disable")
                        && !line.contains("filter")
                        && !line.contains("suppress")
                    {
                        continue;
                    }

                    // For X509TrustManager, only flag if it's implementing a custom one
                    if *pattern == "X509TrustManager"
                        && !line.contains("implements")
                        && !line.contains("new")
                        && !line.contains("class")
                    {
                        continue;
                    }

                    // For create_default_context, skip (low confidence alone)
                    if *pattern == "create_default_context" {
                        continue;
                    }

                    let loc = (rel_path.clone(), line_num);
                    if seen.contains(&loc) {
                        continue;
                    }
                    seen.insert(loc);

                    let effective_severity = if is_test {
                        // Downgrade in tests — might be intentional for testing
                        match severity {
                            Severity::Critical => Severity::Medium,
                            Severity::High => Severity::Low,
                            _ => Severity::Low,
                        }
                    } else {
                        *severity
                    };

                    let language = match ext {
                        "py" | "pyi" => "python",
                        "js" | "jsx" | "mjs" | "cjs" => "javascript",
                        "ts" | "tsx" => "typescript",
                        "go" => "go",
                        "java" => "java",
                        "kt" | "kts" => "kotlin",
                        "rs" => "rust",
                        _ => "unknown",
                    };

                    let blocking_rule = if is_test {
                        None
                    } else {
                        classify_blocking_rule(ext, line, pattern)
                    };

                    let (tier, final_confidence, deterministic, evidence) =
                        if let Some(rule) = blocking_rule {
                            let span = SourceSpan {
                                file: PathBuf::from(&rel_path),
                                line_start: line_num,
                                line_end: line_num,
                                snippet: Some(trimmed.chars().take(120).collect()),
                            };
                            (
                                Tier::Blocking,
                                Some(1.0_f64),
                                true,
                                Some(Evidence::ConfigFact {
                                    span,
                                    rule: rule.to_string(),
                                }),
                            )
                        } else {
                            (
                                Tier::Advisory,
                                Some(if is_test { 0.7 } else { 0.95 }),
                                false,
                                None,
                            )
                        };

                    // For blocking findings, always use at-least-High severity.
                    let final_severity = if tier == Tier::Blocking {
                        effective_severity.max(Severity::High)
                    } else {
                        effective_severity
                    };

                    findings.push(Finding {
                        id: deterministic_finding_id(
                            "InsecureTlsDetector",
                            &rel_path,
                            line_num,
                            description,
                        ),
                        detector: "InsecureTlsDetector".to_string(),
                        title: format!("Insecure TLS/Certificate Validation ({})", language),
                        description: format!(
                            "**{}** (CWE-295)\n\n\
                             Disabled certificate or hostname verification detected.\n\n\
                             **Pattern**: `{}`\n\
                             **File**: {}:{}\n\
                             **Code**: `{}`\n\n\
                             This allows man-in-the-middle attacks. An attacker on the network \
                             can intercept and modify traffic without detection.{}",
                            description,
                            pattern,
                            rel_path,
                            line_num,
                            trimmed.chars().take(120).collect::<String>(),
                            if is_test {
                                "\n\n*Note: Found in test file — severity reduced.*"
                            } else {
                                ""
                            },
                        ),
                        severity: final_severity,
                        affected_files: vec![PathBuf::from(&rel_path)],
                        line_start: Some(line_num),
                        line_end: None,
                        suggested_fix: Some(self.get_fix_suggestion(pattern, language)),
                        cwe_id: Some("CWE-295".to_string()),
                        confidence: final_confidence,
                        category: Some("security".to_string()),
                        tier,
                        evidence,
                        deterministic,
                        ..Default::default()
                    });

                    if findings.len() >= self.max_findings {
                        return findings;
                    }
                }
            }
        }

        findings
    }

    fn get_fix_suggestion(&self, pattern: &str, language: &str) -> String {
        match language {
            "python" => {
                if pattern.contains("verify") {
                    "Remove `verify=False` or set `verify=True` (default). For self-signed certs in dev, \
                     use `verify='/path/to/ca-bundle.crt'` instead.".to_string()
                } else if pattern.contains("CERT_NONE") {
                    "Use `ssl.CERT_REQUIRED` instead of `ssl.CERT_NONE`.".to_string()
                } else if pattern.contains("check_hostname") {
                    "Set `check_hostname = True` (default in Python 3.4+).".to_string()
                } else {
                    "Enable certificate verification. Never disable TLS validation in production."
                        .to_string()
                }
            }
            "javascript" | "typescript" => {
                if pattern.contains("rejectUnauthorized") {
                    "Remove `rejectUnauthorized: false`. For self-signed certs, provide the CA cert \
                     via `ca` option instead.".to_string()
                } else if pattern.contains("NODE_TLS") {
                    "Remove `NODE_TLS_REJECT_UNAUTHORIZED=0`. This disables TLS for the entire process.".to_string()
                } else {
                    "Enable certificate verification on HTTPS connections.".to_string()
                }
            }
            "go" => "Remove `InsecureSkipVerify: true` from tls.Config. For self-signed certs, \
                     provide a custom CA pool via `RootCAs`."
                .to_string(),
            "java" | "kotlin" => {
                "Use the default TrustManager and HostnameVerifier. For self-signed certs, \
                     add the CA to your trust store."
                    .to_string()
            }
            "rust" => {
                "Remove `danger_accept_invalid_certs(true)`. For self-signed certs, add the CA \
                     to the client builder via `add_root_certificate()`."
                    .to_string()
            }
            _ => "Enable certificate verification. Never disable TLS validation in production."
                .to_string(),
        }
    }
}

impl Detector for InsecureTlsDetector {
    fn name(&self) -> &'static str {
        "InsecureTlsDetector"
    }
    fn description(&self) -> &'static str {
        "Detects disabled TLS/certificate verification (CWE-295)"
    }
    fn bypass_postprocessor(&self) -> bool {
        true
    }
    fn detect(
        &self,
        ctx: &crate::detectors::analysis_context::AnalysisContext,
    ) -> Result<Vec<Finding>> {
        debug!("Starting insecure TLS detection");
        let fp = ctx.as_file_provider();
        let extensions: &[&str] = &[
            "py", "pyi", "js", "jsx", "ts", "tsx", "mjs", "cjs", "go", "java", "kt", "kts", "rs",
        ];
        let paths = fp.files_with_extensions(extensions);
        let mut file_list: Vec<(&Path, String)> = Vec::new();
        for path in &paths {
            if let Some(content) = fp.content(path) {
                file_list.push((path, content.as_ref().clone()));
            }
        }
        let file_refs: Vec<(&Path, &str)> =
            file_list.iter().map(|(p, c)| (*p, c.as_str())).collect();
        let findings = self.scan_files(&file_refs);
        info!("InsecureTlsDetector found {} findings", findings.len());
        Ok(findings)
    }
    fn category(&self) -> &'static str {
        "security"
    }
    fn requires_graph(&self) -> bool {
        false
    }

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

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

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

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::{Evidence, Tier};
    use std::path::Path;

    #[test]
    fn test_python_verify_false() {
        let detector = InsecureTlsDetector::new(Path::new("."));
        let path = Path::new("client.py");
        let content = "response = requests.get(url, verify=False)\n";
        let findings = detector.scan_files(&[(path, content)]);
        assert!(!findings.is_empty(), "Should detect verify=False");
        assert_eq!(findings[0].severity, Severity::High);
    }

    #[test]
    fn test_js_reject_unauthorized() {
        let detector = InsecureTlsDetector::new(Path::new("."));
        let path = Path::new("client.js");
        let content = "const agent = new https.Agent({ rejectUnauthorized: false });\n";
        let findings = detector.scan_files(&[(path, content)]);
        assert!(
            !findings.is_empty(),
            "Should detect rejectUnauthorized: false"
        );
    }

    #[test]
    fn test_go_insecure_skip_verify() {
        let detector = InsecureTlsDetector::new(Path::new("."));
        let path = Path::new("client.go");
        let content = "tlsConfig := &tls.Config{InsecureSkipVerify: true}\n";
        let findings = detector.scan_files(&[(path, content)]);
        assert!(!findings.is_empty(), "Should detect InsecureSkipVerify");
    }

    #[test]
    fn test_rust_danger_accept() {
        let detector = InsecureTlsDetector::new(Path::new("."));
        let path = Path::new("client.rs");
        let content =
            "let client = reqwest::Client::builder().danger_accept_invalid_certs(true).build()?;\n";
        let findings = detector.scan_files(&[(path, content)]);
        assert!(
            !findings.is_empty(),
            "Should detect danger_accept_invalid_certs"
        );
    }

    #[test]
    fn test_java_trust_all() {
        let detector = InsecureTlsDetector::new(Path::new("."));
        let path = Path::new("Client.java");
        let content = "TrustManager[] trustAllCerts = new TrustAllCerts();\n";
        let findings = detector.scan_files(&[(path, content)]);
        assert!(!findings.is_empty(), "Should detect TrustAllCerts");
    }

    #[test]
    fn test_test_file_downgraded() {
        let detector = InsecureTlsDetector::new(Path::new("."));
        let path = Path::new("tests/test_client.py");
        let content = "response = requests.get(url, verify=False)\n";
        let findings = detector.scan_files(&[(path, content)]);
        assert!(!findings.is_empty(), "Should still detect in test files");
        assert_eq!(
            findings[0].severity,
            Severity::Low,
            "Should be downgraded in tests"
        );
    }

    #[test]
    fn test_clean_code_no_findings() {
        let detector = InsecureTlsDetector::new(Path::new("."));
        let path = Path::new("client.py");
        let content = "response = requests.get(url)\nprint(response.status_code)\n";
        let findings = detector.scan_files(&[(path, content)]);
        assert!(findings.is_empty(), "Clean code should have no findings");
    }

    #[test]
    fn test_python_cert_none() {
        let detector = InsecureTlsDetector::new(Path::new("."));
        let path = Path::new("server.py");
        let content = "ctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n";
        let findings = detector.scan_files(&[(path, content)]);
        assert!(
            findings.len() >= 2,
            "Should detect both check_hostname and CERT_NONE. Found: {}",
            findings.len()
        );
    }

    // ── Blocking-tier tests (Task 11a) ───────────────────────────────────────

    /// Exact anti-patterns must be promoted to `Tier::Blocking` with the right `Evidence::ConfigFact`.
    #[test]
    fn exact_antipattern_is_blocking() {
        let det = InsecureTlsDetector::new(Path::new("."));

        // JS: rejectUnauthorized: false → blocking, tls_verify_disabled
        {
            let path = Path::new("client.js");
            let content = "const agent = new https.Agent({ rejectUnauthorized: false });\n";
            let findings = det.scan_files(&[(path, content)]);
            assert!(
                !findings.is_empty(),
                "JS anti-pattern must produce a finding"
            );
            let f = &findings[0];
            assert_eq!(
                f.tier,
                Tier::Blocking,
                "rejectUnauthorized: false must be Blocking"
            );
            assert!(f.deterministic, "Blocking finding must be deterministic");
            assert_eq!(
                f.confidence.unwrap(),
                1.0,
                "Blocking finding must have confidence = 1.0"
            );
            assert!(
                matches!(
                    &f.evidence,
                    Some(Evidence::ConfigFact { rule, .. }) if rule == "tls_verify_disabled"
                ),
                "Must carry ConfigFact {{ rule: tls_verify_disabled }}, got: {:?}",
                f.evidence
            );
            assert!(
                f.severity >= Severity::High,
                "Blocking severity must be >= High"
            );
        }

        // Python: verify=False → blocking, tls_verify_disabled
        {
            let path = Path::new("app.py");
            let content = "resp = requests.get(url, verify=False)\n";
            let findings = det.scan_files(&[(path, content)]);
            assert!(
                !findings.is_empty(),
                "Python anti-pattern must produce a finding"
            );
            let f = &findings[0];
            assert_eq!(f.tier, Tier::Blocking, "verify=False must be Blocking");
            assert!(f.deterministic, "Blocking finding must be deterministic");
            assert_eq!(f.confidence.unwrap(), 1.0);
            assert!(
                matches!(
                    &f.evidence,
                    Some(Evidence::ConfigFact { rule, .. }) if rule == "tls_verify_disabled"
                ),
                "Must carry ConfigFact {{ rule: tls_verify_disabled }}, got: {:?}",
                f.evidence
            );
        }

        // Python: verify = False (with spaces) → blocking, tls_verify_disabled
        {
            let path = Path::new("app.py");
            let content = "resp = requests.post(url, verify = False)\n";
            let findings = det.scan_files(&[(path, content)]);
            assert!(
                !findings.is_empty(),
                "Python anti-pattern (spaces) must produce a finding"
            );
            let f = &findings[0];
            assert_eq!(f.tier, Tier::Blocking, "verify = False must be Blocking");
            assert!(
                matches!(
                    &f.evidence,
                    Some(Evidence::ConfigFact { rule, .. }) if rule == "tls_verify_disabled"
                ),
                "Must carry ConfigFact {{ rule: tls_verify_disabled }}"
            );
        }

        // Go: InsecureSkipVerify: true → blocking, tls_skip_verify
        {
            let path = Path::new("client.go");
            let content = "cfg := &tls.Config{InsecureSkipVerify: true}\n";
            let findings = det.scan_files(&[(path, content)]);
            assert!(
                !findings.is_empty(),
                "Go anti-pattern must produce a finding"
            );
            let f = &findings[0];
            assert_eq!(
                f.tier,
                Tier::Blocking,
                "InsecureSkipVerify: true must be Blocking"
            );
            assert!(f.deterministic, "Blocking finding must be deterministic");
            assert_eq!(f.confidence.unwrap(), 1.0);
            assert!(
                matches!(
                    &f.evidence,
                    Some(Evidence::ConfigFact { rule, .. }) if rule == "tls_skip_verify"
                ),
                "Must carry ConfigFact {{ rule: tls_skip_verify }}, got: {:?}",
                f.evidence
            );
        }
    }

    /// Near-misses (dynamic values, `verify=True`, etc.) must NOT be Blocking.
    #[test]
    fn near_miss_is_advisory_or_absent() {
        let det = InsecureTlsDetector::new(Path::new("."));

        // Dynamic JS value → Advisory (or not flagged at all)
        {
            let path = Path::new("client.js");
            // `rejectUnauthorized: opts.strict` — the substring "rejectUnauthorized: " is present,
            // but the value is a variable, not the literal `false`.
            let content = "const agent = new https.Agent({ rejectUnauthorized: opts.strict });\n";
            let findings = det.scan_files(&[(path, content)]);
            // None of the findings should be Blocking
            for f in &findings {
                assert_ne!(
                    f.tier,
                    Tier::Blocking,
                    "Dynamic JS value must not be Blocking: {:?}",
                    f
                );
            }
        }

        // Python verify=True → not flagged at all
        {
            let path = Path::new("app.py");
            let content = "resp = requests.get(url, verify=True)\n";
            let findings = det.scan_files(&[(path, content)]);
            assert!(findings.is_empty(), "verify=True must not be flagged");
        }

        // Python dynamic verify → Advisory (or not flagged)
        {
            let path = Path::new("app.py");
            let content = "resp = requests.get(url, verify=cfg.verify)\n";
            let findings = det.scan_files(&[(path, content)]);
            for f in &findings {
                assert_ne!(
                    f.tier,
                    Tier::Blocking,
                    "Dynamic Python verify must not be Blocking"
                );
            }
        }
    }

    /// Commented-out code must never be flagged.
    #[test]
    fn commented_out_is_not_flagged() {
        let det = InsecureTlsDetector::new(Path::new("."));

        // Python comment
        {
            let path = Path::new("app.py");
            let content = "# resp = requests.get(url, verify=False)\n";
            let findings = det.scan_files(&[(path, content)]);
            assert!(findings.is_empty(), "Python comment must not be flagged");
        }

        // JS comment
        {
            let path = Path::new("client.js");
            let content = "// const agent = new https.Agent({ rejectUnauthorized: false });\n";
            let findings = det.scan_files(&[(path, content)]);
            assert!(findings.is_empty(), "JS line-comment must not be flagged");
        }

        // Go comment
        {
            let path = Path::new("client.go");
            let content = "// cfg := &tls.Config{InsecureSkipVerify: true}\n";
            let findings = det.scan_files(&[(path, content)]);
            assert!(findings.is_empty(), "Go line-comment must not be flagged");
        }
    }

    /// In test / fixture files the finding must be `Advisory`, never `Blocking`.
    #[test]
    fn in_test_fixture_is_advisory() {
        let det = InsecureTlsDetector::new(Path::new("."));

        // tests/fixtures/x.py
        {
            let path = Path::new("tests/fixtures/x.py");
            let content = "resp = requests.get(url, verify=False)\n";
            let findings = det.scan_files(&[(path, content)]);
            assert!(
                !findings.is_empty(),
                "verify=False in test fixture must still produce a finding"
            );
            for f in &findings {
                assert_eq!(
                    f.tier,
                    Tier::Advisory,
                    "Findings in test fixtures must be Advisory, not {:?}",
                    f.tier
                );
            }
        }

        // test/client.js
        {
            let path = Path::new("test/client.js");
            let content = "const agent = new https.Agent({ rejectUnauthorized: false });\n";
            let findings = det.scan_files(&[(path, content)]);
            assert!(!findings.is_empty(), "Still detect in test directory");
            for f in &findings {
                assert_eq!(
                    f.tier,
                    Tier::Advisory,
                    "Findings in test directory must be Advisory"
                );
            }
        }

        // conftest.py at the repo root: is_test_file doesn't cover it (no /tests/ segment),
        // so we skip asserting tier — real conftest.py files live inside tests/ which is covered.
        {
            let path = Path::new("conftest.py");
            let content = "resp = requests.get(url, verify=False)\n";
            let _findings = det.scan_files(&[(path, content)]);
        }

        // __tests__/client.js
        {
            let path = Path::new("__tests__/client.js");
            let content = "const agent = new https.Agent({ rejectUnauthorized: false });\n";
            let findings = det.scan_files(&[(path, content)]);
            assert!(!findings.is_empty(), "Still detect in __tests__");
            for f in &findings {
                assert_eq!(
                    f.tier,
                    Tier::Advisory,
                    "Findings in __tests__ must be Advisory"
                );
            }
        }
    }
}