shipsafe 0.2.1

AI-Powered Pre-Deploy Security Gate
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
pub mod exec;
pub mod sast;
pub mod sca;
pub mod secrets;

use crate::config::Config;
use anyhow::Result;
use colored::Colorize;
use serde::{Deserialize, Serialize};
use std::path::Path;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanResults {
    pub findings: Vec<Finding>,
    pub summary: ScanSummary,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Finding {
    pub id: String,
    pub scanner: String,
    pub severity: Severity,
    pub title: String,
    pub description: String,
    pub file: String,
    pub line: Option<u32>,
    pub cwe: Option<String>,
    pub cve: Option<String>,
    pub fix_suggestion: Option<String>,
    /// AI triage verdict; present only when triage ran for this finding.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ai_triage: Option<crate::ai::triage::Triage>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    Low,
    Medium,
    High,
    Critical,
}

impl std::fmt::Display for Severity {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Severity::Critical => write!(f, "CRITICAL"),
            Severity::High => write!(f, "HIGH"),
            Severity::Medium => write!(f, "MEDIUM"),
            Severity::Low => write!(f, "LOW"),
        }
    }
}

impl Severity {
    /// Localized severity label. Japanese: 重大/高/中/低.
    pub fn label(&self, lang: &str) -> &'static str {
        if lang == "ja" {
            match self {
                Severity::Critical => "重大",
                Severity::High => "",
                Severity::Medium => "",
                Severity::Low => "",
            }
        } else {
            match self {
                Severity::Critical => "CRITICAL",
                Severity::High => "HIGH",
                Severity::Medium => "MEDIUM",
                Severity::Low => "LOW",
            }
        }
    }
}

impl Finding {
    /// True when the AI triage classified this finding as a false positive.
    pub fn is_ai_false_positive(&self) -> bool {
        self.ai_triage
            .as_ref()
            .is_some_and(|t| t.verdict == crate::ai::triage::Verdict::FalsePositive)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanSummary {
    pub total: usize,
    pub critical: usize,
    pub high: usize,
    pub medium: usize,
    pub low: usize,
}

impl ScanResults {
    pub fn new() -> Self {
        Self {
            findings: vec![],
            summary: ScanSummary {
                total: 0,
                critical: 0,
                high: 0,
                medium: 0,
                low: 0,
            },
        }
    }

    pub fn merge(&mut self, other: ScanResults) {
        self.findings.extend(other.findings);
        self.recalculate_summary();
    }

    /// Remove duplicate findings keyed on `(id, file, line)`. Scanners can
    /// surface the same issue (e.g. SAST and a custom rule), so dedup after
    /// merging all results.
    pub fn deduplicate(&mut self) {
        let mut seen = std::collections::HashSet::with_capacity(self.findings.len());
        self.findings
            .retain(|f| seen.insert((f.id.clone(), f.file.clone(), f.line)));
        self.recalculate_summary();
    }

    pub(crate) fn recalculate_summary(&mut self) {
        self.summary = ScanSummary {
            total: self.findings.len(),
            critical: self
                .findings
                .iter()
                .filter(|f| f.severity == Severity::Critical)
                .count(),
            high: self
                .findings
                .iter()
                .filter(|f| f.severity == Severity::High)
                .count(),
            medium: self
                .findings
                .iter()
                .filter(|f| f.severity == Severity::Medium)
                .count(),
            low: self
                .findings
                .iter()
                .filter(|f| f.severity == Severity::Low)
                .count(),
        };
    }

    /// Findings at or above the failure threshold. SCA findings honor the
    /// stricter of the global `--fail-on` and `scanners.sca.fail-on-severity`.
    ///
    /// Findings the AI triage marked as false positives stay in the report
    /// (annotated, for auditability) but are excluded from the gate.
    pub fn failing_findings(&self, fail_on: &str, config: &Config) -> Vec<&Finding> {
        let global = parse_severity(fail_on).unwrap_or_else(|| {
            tracing::warn!(
                "unknown fail-on value '{}', defaulting to critical",
                fail_on
            );
            Severity::Critical
        });
        let sca_threshold = parse_severity(&config.scanners.sca.fail_on_severity)
            .unwrap_or_else(|| global.clone())
            .min(global.clone());

        self.findings
            .iter()
            .filter(|f| {
                if f.is_ai_false_positive() {
                    return false;
                }
                let threshold = if f.scanner == "sca" {
                    &sca_threshold
                } else {
                    &global
                };
                f.severity >= *threshold
            })
            .collect()
    }

    /// Exit code based on severity thresholds: 1 when any finding is at or
    /// above the failure threshold, 0 otherwise.
    pub fn max_severity_exit_code(&self, fail_on: &str, config: &Config) -> i32 {
        i32::from(!self.failing_findings(fail_on, config).is_empty())
    }

    /// Drop findings whose file path matches any of the glob patterns.
    /// Applies to results from every scanner, so excludes work uniformly
    /// even for tools without a native exclude flag.
    pub fn apply_excludes(&mut self, patterns: &[String]) {
        if patterns.is_empty() {
            return;
        }
        let compiled: Vec<glob::Pattern> = patterns
            .iter()
            .filter_map(|p| match glob::Pattern::new(p) {
                Ok(g) => Some(g),
                Err(e) => {
                    tracing::warn!("invalid exclude glob '{}': {}", p, e);
                    None
                }
            })
            .collect();
        self.findings.retain(|f| {
            let normalized = f.file.strip_prefix("./").unwrap_or(&f.file);
            !compiled.iter().any(|g| g.matches(normalized))
        });
        self.recalculate_summary();
    }
}

/// Globs excluded by `--exclude-tests`: common test directories and test
/// file naming conventions across ecosystems.
pub const TEST_EXCLUDE_GLOBS: &[&str] = &[
    "tests/**",
    "test/**",
    "spec/**",
    "__tests__/**",
    "**/tests/**",
    "**/test/**",
    "**/spec/**",
    "**/__tests__/**",
    "**/*_test.go",
    "**/*_test.py",
    "**/test_*.py",
    "**/*_test.rb",
    "**/*.test.js",
    "**/*.test.jsx",
    "**/*.test.ts",
    "**/*.test.tsx",
    "**/*.spec.js",
    "**/*.spec.jsx",
    "**/*.spec.ts",
    "**/*.spec.tsx",
];

/// Parse a severity string (as used in `--fail-on` and config files).
fn parse_severity(s: &str) -> Option<Severity> {
    match s {
        "critical" => Some(Severity::Critical),
        "high" => Some(Severity::High),
        "medium" => Some(Severity::Medium),
        "low" => Some(Severity::Low),
        _ => None,
    }
}

pub async fn run_all(path: &Path, scanners: &[&str], config: &Config) -> Result<ScanResults> {
    let run_sast = scanners.contains(&"sast") && config.scanners.sast.enabled;
    let run_sca = scanners.contains(&"sca") && config.scanners.sca.enabled;
    let run_secrets = scanners.contains(&"secrets") && config.scanners.secrets.enabled;

    let sast_fut = async {
        if run_sast {
            sast::run(path, config).await
        } else {
            Ok(ScanResults::new())
        }
    };

    let sca_fut = async {
        if run_sca {
            sca::run(path, config).await
        } else {
            Ok(ScanResults::new())
        }
    };

    let secrets_fut = async {
        if run_secrets {
            secrets::run(path, config).await
        } else {
            Ok(ScanResults::new())
        }
    };

    let (sast_result, sca_result, secrets_result) = tokio::join!(sast_fut, sca_fut, secrets_fut);

    let mut results = ScanResults::new();

    // Scanners run concurrently above; print each result atomically (and in a
    // stable order) here so the lines never interleave.
    if run_sast {
        let r = sast_result?;
        print_scanner_done("SAST", &r, config);
        results.merge(r);
    }
    if run_sca {
        let r = sca_result?;
        print_scanner_done("SCA", &r, config);
        results.merge(r);
    }
    if run_secrets {
        let r = secrets_result?;
        print_scanner_done("Secrets", &r, config);
        results.merge(r);
    }

    results.deduplicate();
    results.apply_excludes(&config.exclude);

    Ok(results)
}

fn print_scanner_done(name: &str, results: &ScanResults, config: &Config) {
    let ja = config.lang == "ja";
    let prefix = format!("  {} {:<10} ... ", "".cyan(), name);
    let count = results.summary.total;
    if count == 0 {
        let msg = if ja { "検出 0 件" } else { "0 findings" };
        println!("{}{}", prefix, msg.green());
    } else {
        let parts: Vec<String> = [
            (results.summary.critical, Severity::Critical),
            (results.summary.high, Severity::High),
            (results.summary.medium, Severity::Medium),
            (results.summary.low, Severity::Low),
        ]
        .iter()
        .filter(|(c, _)| *c > 0)
        .map(|(c, sev)| {
            if ja {
                format!("{} {}", sev.label("ja"), c)
            } else {
                format!("{} {}", c, sev.label("en").to_lowercase())
            }
        })
        .collect();
        if ja {
            println!("{}検出 {} 件 ({})", prefix, count, parts.join(", "));
        } else {
            println!("{}{} findings ({})", prefix, count, parts.join(", "));
        }
    }
}

pub fn check_dependencies(lang: &str) {
    let ja = lang == "ja";
    let tools = if ja {
        vec![
            ("semgrep", "SAST スキャナー"),
            ("trivy", "SCA / コンテナ / IaC スキャナー"),
            ("gitleaks", "シークレットスキャナー"),
        ]
    } else {
        vec![
            ("semgrep", "SAST scanner"),
            ("trivy", "SCA / Container / IaC scanner"),
            ("gitleaks", "Secret scanner"),
        ]
    };

    for (cmd, desc) in tools {
        let status = if which::which(cmd).is_ok() {
            let label = if ja {
                "インストール済み"
            } else {
                "Found"
            };
            format!("{} {}", "".green(), label)
        } else {
            let label = if ja {
                "未インストール"
            } else {
                "Not found"
            };
            format!("{} {}", "".red(), label)
        };
        println!("  {} {:<12} {}", status, cmd, desc.dimmed());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn finding(scanner: &str, severity: Severity) -> Finding {
        Finding {
            id: "test".into(),
            scanner: scanner.into(),
            severity,
            title: "test".into(),
            description: String::new(),
            file: "test.rs".into(),
            line: None,
            cwe: None,
            cve: None,
            fix_suggestion: None,
            ai_triage: None,
        }
    }

    fn make_finding(
        id: &str,
        scanner: &str,
        severity: Severity,
        file: &str,
        line: Option<u32>,
    ) -> Finding {
        Finding {
            id: id.to_string(),
            scanner: scanner.to_string(),
            severity,
            title: id.to_string(),
            description: String::new(),
            file: file.to_string(),
            line,
            cwe: None,
            cve: None,
            fix_suggestion: None,
            ai_triage: None,
        }
    }

    fn results_with(findings: Vec<Finding>) -> ScanResults {
        let mut r = ScanResults::new();
        r.findings = findings;
        r.recalculate_summary();
        r
    }

    #[test]
    fn test_exit_code_global_threshold() {
        let config = Config::default();
        let r = results_with(vec![finding("sast", Severity::High)]);
        assert_eq!(r.max_severity_exit_code("critical", &config), 0);
        assert_eq!(r.max_severity_exit_code("high", &config), 1);
        assert_eq!(r.max_severity_exit_code("low", &config), 1);
    }

    #[test]
    fn test_exit_code_sca_uses_config_threshold() {
        // Default ScaConfig.fail_on_severity is "high": an SCA high finding
        // fails the build even when the global threshold is critical.
        let config = Config::default();
        let r = results_with(vec![finding("sca", Severity::High)]);
        assert_eq!(r.max_severity_exit_code("critical", &config), 1);

        let r_medium = results_with(vec![finding("sca", Severity::Medium)]);
        assert_eq!(r_medium.max_severity_exit_code("critical", &config), 0);
    }

    #[test]
    fn test_exit_code_sca_honors_stricter_global() {
        // Global --fail-on low is stricter than sca fail-on-severity high.
        let config = Config::default();
        let r = results_with(vec![finding("sca", Severity::Low)]);
        assert_eq!(r.max_severity_exit_code("low", &config), 1);
    }

    #[test]
    fn test_exit_code_unknown_fail_on_defaults_to_critical() {
        let config = Config::default();
        let r = results_with(vec![finding("sast", Severity::High)]);
        assert_eq!(r.max_severity_exit_code("bogus", &config), 0);
        let r_crit = results_with(vec![finding("sast", Severity::Critical)]);
        assert_eq!(r_crit.max_severity_exit_code("bogus", &config), 1);
    }

    #[test]
    fn test_severity_labels_ja() {
        assert_eq!(Severity::Critical.label("ja"), "重大");
        assert_eq!(Severity::High.label("ja"), "");
        assert_eq!(Severity::Medium.label("ja"), "");
        assert_eq!(Severity::Low.label("ja"), "");
        assert_eq!(Severity::Critical.label("en"), "CRITICAL");
    }

    #[test]
    fn test_failing_findings_reports_only_threshold_breaches() {
        let config = Config::default();
        let r = results_with(vec![
            finding("sast", Severity::Critical),
            finding("sast", Severity::High),
            finding("sast", Severity::Low),
        ]);
        assert_eq!(r.failing_findings("critical", &config).len(), 1);
        assert_eq!(r.failing_findings("high", &config).len(), 2);
        assert_eq!(r.failing_findings("low", &config).len(), 3);
    }

    #[test]
    fn test_ai_false_positive_excluded_from_gate() {
        use crate::ai::triage::{Triage, TriageConfidence, Verdict};
        let config = Config::default();
        let mut fp = finding("sast", Severity::Critical);
        fp.ai_triage = Some(Triage {
            verdict: Verdict::FalsePositive,
            confidence: TriageConfidence::High,
            reason: "test fixture".into(),
            model: "claude-opus-4-8".into(),
        });
        let mut uncertain = finding("sast", Severity::Critical);
        uncertain.ai_triage = Some(Triage {
            verdict: Verdict::Uncertain,
            confidence: TriageConfidence::Low,
            reason: "not enough context".into(),
            model: "claude-opus-4-8".into(),
        });
        let r = results_with(vec![fp, uncertain, finding("sast", Severity::Critical)]);

        // The false positive is excluded; uncertain and untriaged still gate.
        assert_eq!(r.failing_findings("critical", &config).len(), 2);
        assert_eq!(r.max_severity_exit_code("critical", &config), 1);
        // The finding itself stays in the report.
        assert_eq!(r.findings.len(), 3);
        assert_eq!(r.summary.total, 3);
    }

    #[test]
    fn test_all_ai_false_positives_pass_the_gate() {
        use crate::ai::triage::{Triage, TriageConfidence, Verdict};
        let config = Config::default();
        let mut fp = finding("secrets", Severity::Critical);
        fp.ai_triage = Some(Triage {
            verdict: Verdict::FalsePositive,
            confidence: TriageConfidence::High,
            reason: "documented example value".into(),
            model: "claude-opus-4-8".into(),
        });
        let r = results_with(vec![fp]);
        assert_eq!(r.max_severity_exit_code("low", &config), 0);
    }

    #[test]
    fn test_parse_severity() {
        assert_eq!(parse_severity("critical"), Some(Severity::Critical));
        assert_eq!(parse_severity("high"), Some(Severity::High));
        assert_eq!(parse_severity("medium"), Some(Severity::Medium));
        assert_eq!(parse_severity("low"), Some(Severity::Low));
        assert_eq!(parse_severity("bogus"), None);
    }

    #[test]
    fn test_deduplicate_removes_duplicates() {
        let mut results = ScanResults::new();
        results.findings.push(make_finding(
            "CVE-1",
            "sast",
            Severity::High,
            "app.py",
            Some(10),
        ));
        results.findings.push(make_finding(
            "CVE-1",
            "sast",
            Severity::High,
            "app.py",
            Some(10),
        ));
        results.findings.push(make_finding(
            "CVE-2",
            "sca",
            Severity::Critical,
            "lib.py",
            None,
        ));

        results.deduplicate();

        assert_eq!(results.findings.len(), 2);
        assert_eq!(results.summary.total, 2);
        assert_eq!(results.summary.high, 1);
        assert_eq!(results.summary.critical, 1);
    }

    #[test]
    fn test_deduplicate_keeps_different_lines() {
        let mut results = ScanResults::new();
        results.findings.push(make_finding(
            "CVE-1",
            "sast",
            Severity::High,
            "app.py",
            Some(10),
        ));
        results.findings.push(make_finding(
            "CVE-1",
            "sast",
            Severity::High,
            "app.py",
            Some(20),
        ));

        results.deduplicate();

        assert_eq!(results.findings.len(), 2);
    }

    #[test]
    fn test_deduplicate_keeps_different_files() {
        let mut results = ScanResults::new();
        results.findings.push(make_finding(
            "CVE-1",
            "sast",
            Severity::High,
            "a.py",
            Some(10),
        ));
        results.findings.push(make_finding(
            "CVE-1",
            "sast",
            Severity::High,
            "b.py",
            Some(10),
        ));

        results.deduplicate();

        assert_eq!(results.findings.len(), 2);
    }

    #[test]
    fn test_deduplicate_no_duplicates() {
        let mut results = ScanResults::new();
        results.findings.push(make_finding(
            "CVE-1",
            "sast",
            Severity::High,
            "a.py",
            Some(1),
        ));
        results
            .findings
            .push(make_finding("CVE-2", "sca", Severity::Low, "b.py", Some(2)));

        results.deduplicate();

        assert_eq!(results.findings.len(), 2);
    }

    #[test]
    fn test_deduplicate_empty() {
        let mut results = ScanResults::new();
        results.deduplicate();
        assert_eq!(results.findings.len(), 0);
        assert_eq!(results.summary.total, 0);
    }

    #[test]
    fn test_apply_excludes_glob() {
        let mut results = results_with(vec![
            make_finding("a", "sast", Severity::High, "vendor/lib.py", Some(1)),
            make_finding("b", "sast", Severity::High, "src/app.py", Some(2)),
            make_finding("c", "sast", Severity::High, "./vendor/other.py", Some(3)),
        ]);
        results.apply_excludes(&["vendor/**".to_string()]);
        assert_eq!(results.findings.len(), 1);
        assert_eq!(results.findings[0].file, "src/app.py");
        assert_eq!(results.summary.total, 1);
    }

    #[test]
    fn test_apply_excludes_empty_patterns_is_noop() {
        let mut results = results_with(vec![make_finding(
            "a",
            "sast",
            Severity::High,
            "vendor/lib.py",
            Some(1),
        )]);
        results.apply_excludes(&[]);
        assert_eq!(results.findings.len(), 1);
    }

    #[test]
    fn test_apply_excludes_invalid_glob_ignored() {
        let mut results = results_with(vec![make_finding(
            "a",
            "sast",
            Severity::High,
            "src/app.py",
            Some(1),
        )]);
        results.apply_excludes(&["[bad".to_string()]);
        assert_eq!(results.findings.len(), 1);
    }

    #[test]
    fn test_exclude_tests_globs_match_common_layouts() {
        let patterns: Vec<String> = TEST_EXCLUDE_GLOBS.iter().map(|s| s.to_string()).collect();
        let mut results = results_with(vec![
            make_finding("a", "sast", Severity::High, "tests/test_app.py", Some(1)),
            make_finding("b", "sast", Severity::High, "src/__tests__/x.js", Some(2)),
            make_finding("c", "sast", Severity::High, "pkg/handler_test.go", Some(3)),
            make_finding("d", "sast", Severity::High, "src/Button.test.tsx", Some(4)),
            make_finding("e", "sast", Severity::High, "src/app.py", Some(5)),
        ]);
        results.apply_excludes(&patterns);
        assert_eq!(results.findings.len(), 1);
        assert_eq!(results.findings[0].file, "src/app.py");
    }

    #[test]
    fn test_merge_and_recalculate_summary() {
        let mut results = ScanResults::new();
        results.findings.push(make_finding(
            "CVE-1",
            "sast",
            Severity::Critical,
            "a.py",
            Some(1),
        ));

        let mut other = ScanResults::new();
        other.findings.push(make_finding(
            "CVE-2",
            "sca",
            Severity::High,
            "b.py",
            Some(2),
        ));
        other.findings.push(make_finding(
            "CVE-3",
            "sca",
            Severity::Medium,
            "c.py",
            Some(3),
        ));

        results.merge(other);

        assert_eq!(results.summary.total, 3);
        assert_eq!(results.summary.critical, 1);
        assert_eq!(results.summary.high, 1);
        assert_eq!(results.summary.medium, 1);
        assert_eq!(results.summary.low, 0);
    }
}