diff --git a/README.md b/README.md index 25391dd..3761fe9 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,10 @@ gives up after 10 hours; override with `CORGEA_SCAN_TIMEOUT_SECONDS`. evaluated; override with `CORGEA_BLOCKING_RULES_TIMEOUT_SECONDS`. When the scan finishes, `scan` and `wait` print a results summary: open issues -by severity, every finding by status, and the results link. By default it +by severity, the scan's dependency findings, every code finding by status, and +the results link. A `Malware:` line counts the malicious packages among the +dependencies. If the dependency findings cannot be read, the summary says so +and does not count them as zero. By default it prints tables for a person. `--format` picks a format for a program instead: `agent` (tab-separated records for coding agents), `json` (one document on stdout) or `quiet` (no summary). With `--format`, progress goes to stderr, so diff --git a/skills/corgea/SKILL.md b/skills/corgea/SKILL.md index 53f51db..b6be828 100644 --- a/skills/corgea/SKILL.md +++ b/skills/corgea/SKILL.md @@ -101,12 +101,12 @@ Removing, disabling or editing a project ignore rule (scan settings → File Ign When the scan finishes, `scan` and `wait` print one results summary. Pass `--format agent` when you are a coding agent reading the output: -- no `--format`: tables of open issues by severity and of every finding by status (open, fix in progress, fixed, accepted risk, false positive, duplicate), then the results link. Colors only on a terminal without `NO_COLOR`; no spinners or `\r` redraws on a pipe. -- `agent`: tab-separated records, each kind under its own `record` header row: `gate` first (result `pass|fail|none`, exit code, condition, tripped count), then `scan`, open counts by `severity`, counts by `status` with what each status means, and up to five open `issue` rows (critical first) to fix first. `Hint: Run ...` lines for `corgea ls --issues --scan-id --json` and `corgea inspect --issue ` go to stderr, as does every progress line, `CORGEA_SCAN_SKIPPED=` included, so stdout holds only the records. -- `json`: one document with `schema_version: 1`, `scan`, `gate`, `total_findings`, `by_status` (each with `critical`, `high`, `medium`, `low`, `total`), `unrecognized`, `fix_first` and `results_url`; `scan.reused_recent_scan` appears with `--skip-if-commit-scanned-recently`. Every other line the run prints, `CORGEA_SCAN_SKIPPED=` included, goes to stderr. +- no `--format`: tables of open issues by severity, of dependency findings (malicious and vulnerable packages), and of every code finding by status (open, fix in progress, fixed, accepted risk, false positive, duplicate), then the results link. A `Malware: N malicious packages` line follows the counts when the dependencies hold malware. When the dependency findings cannot be read, the summary prints `dependencies not fetched` and the error instead of a dependency table. Colors only on a terminal without `NO_COLOR`; no spinners or `\r` redraws on a pipe. +- `agent`: tab-separated records, each kind under its own `record` header row: `gate` first (result `pass|fail|none`, exit code, condition, tripped count), then `scan`, open counts by `severity`, counts by `status` with what each status means, `dependency` rows for `malicious` and `vulnerable` packages (counts by severity, `unrated`, `total`) or one `dependency_error` record when they could not be read, and up to five open `issue` rows (critical first) to fix first. `Hint: Run ...` lines for `corgea ls --issues --scan-id --json` and `corgea inspect --issue ` go to stderr, as does every progress line, `CORGEA_SCAN_SKIPPED=` included, so stdout holds only the records. +- `json`: one document with `schema_version: 2`, `scan`, `gate`, `total_findings` (code and dependency findings; `null` when the dependency findings could not be read), `by_status` (code findings, each with `critical`, `high`, `medium`, `low`, `total`), `dependencies` (`malicious` and `vulnerable`, each with the four severities, `unrated` and `total`, plus `total` and `error`), `unrecognized`, `fix_first` and `results_url`. When the dependency findings could not be read, `dependencies.error` holds the error and its counts are `null`. `scan.reused_recent_scan` appears with `--skip-if-commit-scanned-recently`. Every other line the run prints, `CORGEA_SCAN_SKIPPED=` included, goes to stderr. - `quiet`: no summary. -There is no `--format human`: omit the flag for tables. Agent environments are not detected for `scan` and `wait` (unlike `deps`), so an agent must pass `--format agent` or `--format json`. Open counts only findings with status `open` that are not held as false positives; `--fail-on` still counts every finding except false positives, as before, so its exit code is unchanged. Exit codes are the same in every format, and `--format` is independent of `--out-format`/`--out-file` and `--sbom`. +There is no `--format human`: omit the flag for tables. Agent environments are not detected for `scan` and `wait` (unlike `deps`), so an agent must pass `--format agent` or `--format json`. Open counts only findings with status `open` that are not held as false positives. Dependency findings count in every status, because the dependency endpoint does not report a status. `unrated` counts dependency findings whose severity is missing or not one of the four. `--fail-on` still counts every finding except false positives, as before, so its exit code is unchanged. Exit codes are the same in every format, and `--format` is independent of `--out-format`/`--out-file` and `--sbom`. `--only-uncommitted` and `--target` are mutually exclusive. `--fail-on`, `--fail`, and `--block-on` are mutually exclusive. diff --git a/src/scanners/blast.rs b/src/scanners/blast.rs index 2ba67cf..dc62ca1 100644 --- a/src/scanners/blast.rs +++ b/src/scanners/blast.rs @@ -212,6 +212,7 @@ pub fn run( &project_name, &scan_id, &counts_excluding_false_positives, + issues.dependencies(), out_format.as_deref(), out_file.as_deref(), ); @@ -222,10 +223,10 @@ pub fn run( let gate = evaluate_gate( config, - &project_name, &scan_id, &gate_request, &counts_excluding_false_positives, + issues.dependencies(), ); let summary = ScanSummary::build( @@ -259,10 +260,10 @@ pub enum GateRequest { fn evaluate_gate( config: &Config, - project_name: &str, scan_id: &str, request: &GateRequest, counts_excluding_false_positives: &HashMap, + dependencies: Result<&[SCAIssue], &str>, ) -> Gate { let fail_on = match request { GateRequest::NotRequested => return Gate::NotRequested, @@ -311,11 +312,7 @@ fn evaluate_gate( }; let sca_issues = if tokens.iter().any(|t| t == "malicious") { - match utils::api::get_all_sca_issues( - &config.get_url(), - project_name, - Some(scan_id.to_string()), - ) { + match dependencies { Ok(issues) => issues, Err(e) => { log::error!( @@ -326,11 +323,11 @@ fn evaluate_gate( } } } else { - Vec::new() + &[] }; let condition = format!("--fail-on {fail_on} (findings in any status, not only open)"); - match fail_on_tripped_count(&tokens, counts_excluding_false_positives, &sca_issues) { + match fail_on_tripped_count(&tokens, counts_excluding_false_positives, sca_issues) { 0 => Gate::Passed { condition }, tripped => Gate::Failed { condition, tripped }, } @@ -945,6 +942,7 @@ fn write_scan_report( project_name: &str, scan_id: &str, classifications: &HashMap, + dependencies: Result<&[SCAIssue], &str>, out_format: Option<&str>, out_file: Option<&str>, ) { @@ -979,11 +977,7 @@ fn write_scan_report( std::process::exit(1); } }; - let sca_issues = match utils::api::get_all_sca_issues( - &config.get_url(), - project_name, - Some(scan_id.into()), - ) { + let sca_issues = match dependencies { Ok(issues) => issues, Err(e) => { stop_spinner(); @@ -1992,10 +1986,10 @@ mod tests { .unwrap(); let gate = evaluate_gate( &config, - "goof", "scan-1", &GateRequest::FailOn("HI".into()), &summary::legacy_urgency_counts(&issues), + Ok(&[]), ); assert_eq!( gate, diff --git a/src/scanners/summary.rs b/src/scanners/summary.rs index 3323ca5..f6450f5 100644 --- a/src/scanners/summary.rs +++ b/src/scanners/summary.rs @@ -1,4 +1,4 @@ -use crate::utils::api::{get_all_issues, FalsePositives, Issue}; +use crate::utils::api::{get_all_issues, get_all_sca_issues, FalsePositives, Issue, SCAIssue}; use serde_json::{json, Map, Value}; use std::collections::{BTreeSet, HashMap}; @@ -28,6 +28,13 @@ impl Severity { } } + fn parse_dependency(severity: Option<&str>) -> Option { + let severity = severity?; + Self::ALL + .into_iter() + .find(|candidate| candidate.key().eq_ignore_ascii_case(severity)) + } + fn key(self) -> &'static str { match self { Self::Critical => "critical", @@ -174,6 +181,80 @@ impl SeverityCounts { } } +impl std::ops::AddAssign for SeverityCounts { + fn add_assign(&mut self, other: Self) { + for (slot, count) in self.0.iter_mut().zip(other.0) { + *slot += count; + } + } +} + +/// Counts by severity, plus the findings whose severity is missing or unknown, +/// which count in the total only. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Tally { + pub rated: SeverityCounts, + pub unrated: usize, +} + +impl Tally { + pub fn total(&self) -> usize { + self.rated.total() + self.unrated + } + + fn add(&mut self, severity: Option) { + match severity { + Some(severity) => self.rated.add(severity), + None => self.unrated += 1, + } + } + + fn json(&self) -> Value { + let mut json = self.rated.json(); + json["unrated"] = self.unrated.into(); + json["total"] = self.total().into(); + json + } +} + +impl From for Tally { + fn from(rated: SeverityCounts) -> Self { + Tally { rated, unrated: 0 } + } +} + +/// The scan's dependency findings in any status: the dependency endpoint +/// does not report a finding's status. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DependencyCounts { + pub malicious: Tally, + pub vulnerable: Tally, +} + +impl DependencyCounts { + fn count(issues: &[SCAIssue]) -> Self { + let mut counts = DependencyCounts::default(); + for issue in issues { + let tally = if issue.classification.as_deref() == Some("malicious") { + &mut counts.malicious + } else { + &mut counts.vulnerable + }; + tally.add(Severity::parse_dependency(issue.severity.as_deref())); + } + counts + } + + fn all(&self) -> Tally { + let mut rated = self.malicious.rated; + rated += self.vulnerable.rated; + Tally { + rated, + unrated: self.malicious.unrated + self.vulnerable.unrated, + } + } +} + #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum RecentScanReuse { #[default] @@ -251,6 +332,7 @@ pub struct ScanSummary { pub gate: Gate, by_status: [SeverityCounts; STATUSES.len()], pub unrecognized: Unrecognized, + pub dependencies: Result, pub fix_first: Vec, pub results_url: String, } @@ -294,24 +376,47 @@ pub fn legacy_urgency_counts(issues: &[Issue]) -> HashMap { counts } -pub struct ScanIssues(Vec); +pub struct ScanIssues { + code: Vec, + dependencies: Result, String>, +} impl ScanIssues { + /// A failed dependency read is kept, not raised: the summary reports it + /// and the code issues still print. pub fn fetch( url: &str, project: &str, scan_id: &str, ) -> Result> { - get_all_issues(url, project, Some(scan_id.into()), FalsePositives::Include).map(Self) + let code = get_all_issues(url, project, Some(scan_id.into()), FalsePositives::Include)?; + let dependencies = + get_all_sca_issues(url, project, Some(scan_id.into())).map_err(|e| e.to_string()); + Ok(Self { code, dependencies }) } #[cfg(test)] pub fn including_false_positives(issues: Vec) -> Self { - Self(issues) + Self { + code: issues, + dependencies: Ok(Vec::new()), + } + } + + #[cfg(test)] + pub fn with_dependencies(self, dependencies: Result, String>) -> Self { + Self { + dependencies, + ..self + } } pub fn as_slice(&self) -> &[Issue] { - &self.0 + &self.code + } + + pub fn dependencies(&self) -> Result<&[SCAIssue], &str> { + self.dependencies.as_deref().map_err(String::as_str) } } @@ -350,6 +455,10 @@ impl ScanSummary { gate, by_status, unrecognized, + dependencies: issues + .dependencies() + .map(DependencyCounts::count) + .map_err(str::to_string), fix_first: open, results_url, } @@ -359,7 +468,14 @@ impl ScanSummary { self.by_status[status.index()] } - pub fn total_findings(&self) -> usize { + /// `None` when the dependency read failed: the total is unknown, and a + /// count without dependencies would read as clean for a malware-only scan. + pub fn total_findings(&self) -> Option { + let dependencies = self.dependencies.as_ref().ok()?.all().total(); + Some(self.code_findings() + dependencies) + } + + fn code_findings(&self) -> usize { self.by_status .iter() .map(SeverityCounts::total) @@ -370,9 +486,7 @@ impl ScanSummary { fn all_statuses(&self) -> SeverityCounts { let mut all = SeverityCounts::default(); for counts in &self.by_status { - for (slot, count) in all.0.iter_mut().zip(counts.0) { - *slot += count; - } + all += *counts; } all } @@ -387,6 +501,7 @@ const BOLD: &str = "1"; const DIM: &str = "2"; const GREEN: &str = "32"; const RED: &str = "31"; +const MALWARE: &str = "1;31"; const LINK: &str = "38;5;75;4"; struct Ledger { @@ -437,10 +552,10 @@ impl Ledger { out } - fn row(&self, label: &str, label_sgr: &str, counts: &SeverityCounts) -> String { + fn row(&self, label: &str, label_sgr: &str, counts: &Tally) -> String { let mut out = self.label(label, label_sgr); for severity in Severity::ALL { - let count = counts.get(severity); + let count = counts.rated.get(severity); let sgr = if count == 0 { DIM } else { severity.sgr() }; out.push_str(&self.cell(severity.label(), &count.to_string(), sgr)); } @@ -449,12 +564,7 @@ impl Ledger { out } - fn table( - &self, - title: &str, - rows: &[(&str, SeverityCounts)], - total: (&str, SeverityCounts), - ) -> String { + fn table(&self, title: &str, rows: &[(&str, Tally)], total: (&str, Tally)) -> String { let mut out = self.header(title); out.push_str(&self.rule()); for (label, counts) in rows { @@ -469,25 +579,42 @@ impl Ledger { pub fn render_human(summary: &ScanSummary, color: bool) -> String { const OPEN_TITLE: &str = "Open issues"; const OPEN_TOTAL: &str = "Total open"; - const STATUS_TITLE: &str = "All findings by status"; + const DEPENDENCY_TITLE: &str = "Dependencies, any status"; + const DEPENDENCY_TOTAL: &str = "Total dependencies"; + const STATUS_TITLE: &str = "Code findings by status"; const STATUS_TOTAL: &str = "Total"; - let open_rows = vec![(CODE_ROW_LABEL, summary.counts(Status::Open))]; - let status_rows: Vec<(&str, SeverityCounts)> = STATUSES + let open_rows = vec![(CODE_ROW_LABEL, summary.counts(Status::Open).into())]; + let dependency_rows: Vec<(&str, Tally)> = match &summary.dependencies { + Ok(counts) => vec![ + ("Malicious packages", counts.malicious), + ("Vulnerable packages", counts.vulnerable), + ], + Err(_) => Vec::new(), + }; + let status_rows: Vec<(&str, Tally)> = STATUSES .iter() - .map(|info| (info.label, summary.counts(info.status))) + .map(|info| (info.label, summary.counts(info.status).into())) .collect(); - let longest_label = [OPEN_TITLE, OPEN_TOTAL, STATUS_TITLE, STATUS_TOTAL] - .into_iter() - .chain( - open_rows - .iter() - .chain(&status_rows) - .map(|(label, _)| *label), - ) - .map(str::len) - .max() - .unwrap_or(0); + let longest_label = [ + OPEN_TITLE, + OPEN_TOTAL, + DEPENDENCY_TITLE, + DEPENDENCY_TOTAL, + STATUS_TITLE, + STATUS_TOTAL, + ] + .into_iter() + .chain( + open_rows + .iter() + .chain(&dependency_rows) + .chain(&status_rows) + .map(|(label, _)| *label), + ) + .map(str::len) + .max() + .unwrap_or(0); let ledger = Ledger { color, label_width: (longest_label + 1).max(LABEL_MIN_WIDTH), @@ -495,7 +622,7 @@ pub fn render_human(summary: &ScanSummary, color: bool) -> String { let scan = &summary.scan; let open = summary.counts(Status::Open).total(); - let total = summary.total_findings(); + let code = summary.code_findings(); let mut title = format!("Scan complete: {}", scan.project); if let Some(branch) = &scan.branch { title.push_str(&format!(", branch {branch}")); @@ -511,23 +638,75 @@ pub fn render_human(summary: &ScanSummary, color: bool) -> String { } else { String::new() }; + // Without the dependency findings the total is unknown: name the count + // as code findings so it never reads as the scan's total. + let (total, kind, dependency_note) = match &summary.dependencies { + Ok(counts) => { + let dependencies = counts.all().total(); + ( + code + dependencies, + "", + format!(", {dependencies} in dependencies"), + ) + } + Err(_) => (code, "code ", ", dependencies not fetched".to_string()), + }; out.push_str(&format!( - "{total} {} in this scan: {}, {} in other states{unrecognized_note}.\n\n", + "{total} {kind}{} in this scan: {}, {} in other states{unrecognized_note}{dependency_note}.\n", if total == 1 { "finding" } else { "findings" }, ledger.paint(&format!("{open} open"), BOLD), - total - open - unrecognized + code - open - unrecognized )); + if let Ok(counts) = &summary.dependencies { + let malicious = counts.malicious.total(); + if malicious > 0 { + out.push_str(&format!( + "{} {malicious} malicious {} in this scan's dependencies.\n", + ledger.paint("Malware:", MALWARE), + if malicious == 1 { + "package" + } else { + "packages" + } + )); + } + } + out.push('\n'); out.push_str(&ledger.table( OPEN_TITLE, &open_rows, - (OPEN_TOTAL, summary.counts(Status::Open)), + (OPEN_TOTAL, summary.counts(Status::Open).into()), )); out.push('\n'); + match &summary.dependencies { + Ok(counts) => { + let all = counts.all(); + out.push_str(&ledger.table( + DEPENDENCY_TITLE, + &dependency_rows, + (DEPENDENCY_TOTAL, all), + )); + match all.unrated { + 0 => {} + 1 => out.push_str( + "1 dependency finding has no severity this CLI recognizes. It counts in Total only.\n", + ), + unrated => out.push_str(&format!( + "{unrated} dependency findings have no severity this CLI recognizes. They count in Total only.\n" + )), + } + } + Err(error) => out.push_str(&format!( + "{} {error}\n", + ledger.paint("Dependency findings could not be fetched:", RED) + )), + } + out.push('\n'); out.push_str(&ledger.table( STATUS_TITLE, &status_rows, - (STATUS_TOTAL, summary.all_statuses()), + (STATUS_TOTAL, summary.all_statuses().into()), )); if summary.unrecognized.count > 0 { @@ -617,6 +796,25 @@ pub fn render_agent(summary: &ScanSummary) -> String { } out.push_str(&format!("\t{}\t{}\n", counts.total(), info.meaning)); } + match &summary.dependencies { + Ok(counts) => { + out.push_str("record\tkind\tcritical\thigh\tmedium\tlow\tunrated\ttotal\n"); + for (kind, tally) in [ + ("malicious", counts.malicious), + ("vulnerable", counts.vulnerable), + ] { + out.push_str(&format!("dependency\t{kind}")); + for severity in Severity::ALL { + out.push_str(&format!("\t{}", tally.rated.get(severity))); + } + out.push_str(&format!("\t{}\t{}\n", tally.unrated, tally.total())); + } + } + Err(error) => { + out.push_str("record\terror\n"); + out.push_str(&format!("dependency_error\t{}\n", tsv_cell(error))); + } + } if summary.unrecognized.count > 0 { out.push_str("record\tcount\tvalues\n"); out.push_str(&format!( @@ -689,7 +887,7 @@ pub fn render_json(summary: &ScanSummary) -> String { }) .collect(); let document = json!({ - "schema_version": 1, + "schema_version": 2, "scan": scan_json, "gate": { "result": gate.result(), @@ -702,6 +900,20 @@ pub fn render_json(summary: &ScanSummary) -> String { }, "total_findings": summary.total_findings(), "by_status": by_status, + "dependencies": match &summary.dependencies { + Ok(counts) => json!({ + "malicious": counts.malicious.json(), + "vulnerable": counts.vulnerable.json(), + "total": counts.all().total(), + "error": null, + }), + Err(error) => json!({ + "malicious": null, + "vulnerable": null, + "total": null, + "error": error, + }), + }, "unrecognized": { "count": summary.unrecognized.count, "values": summary.unrecognized.values, @@ -720,6 +932,7 @@ mod tests { use super::*; use crate::utils::api::{ AutoTriage, Classification, CorgeaFile, FalsePositiveDetection, Location, Project, + SCALocation, SCAPackage, }; fn issue(id: &str, status: &str, urgency: &str, path: &str, line: u32) -> Issue { @@ -760,6 +973,48 @@ mod tests { } } + fn dependency(name: &str, severity: Option<&str>, classification: Option<&str>) -> SCAIssue { + SCAIssue { + id: format!("sca-{name}"), + created_at: String::new(), + description: None, + details: None, + severity: severity.map(str::to_string), + classification: classification.map(str::to_string), + cve: None, + package: SCAPackage { + name: name.into(), + version: "1.0.0".into(), + ecosystem: "npm".into(), + fix_version: None, + }, + location: SCALocation { + path: "package-lock.json".into(), + }, + } + } + + /// The production case: no code issues, lockfiles pinning malware. + fn malware_dependencies() -> Vec { + vec![ + dependency("flatmap-stream", Some("CRITICAL"), Some("malicious")), + dependency("rustdecimal", None, Some("malicious")), + dependency("lodash", Some("high"), None), + ] + } + + fn summary_with_dependencies( + dependencies: Result, String>, + issues: Vec, + ) -> ScanSummary { + ScanSummary::build( + scan_info(), + Gate::NotRequested, + &ScanIssues::including_false_positives(issues).with_dependencies(dependencies), + "https://corgea.test/scan".into(), + ) + } + fn held_false_positive(id: &str, urgency: &str) -> Issue { let mut issue = issue(id, "open", urgency, "src/held.js", 1); issue.auto_triage.false_positive_detection.status = "false_positive".into(); @@ -817,7 +1072,7 @@ mod tests { assert_eq!(open.total(), 2); assert_eq!(summary.counts(Status::FalsePositive).total(), 2); assert_eq!(summary.counts(Status::AcceptedRisk).total(), 1); - assert_eq!(summary.total_findings(), 8); + assert_eq!(summary.total_findings(), Some(8)); } #[test] @@ -839,11 +1094,13 @@ mod tests { let summary = summary_of(issues, Gate::NotRequested); assert_eq!(summary.counts(Status::Open).total(), 1); assert_eq!(summary.unrecognized.count, 2); - assert_eq!(summary.total_findings(), 3); + assert_eq!(summary.total_findings(), Some(3)); let human = render_human(&summary, false); assert!(human.contains("status=snoozed, urgency=IN")); assert!( - human.contains("3 findings in this scan: 1 open, 0 in other states, 2 unrecognized."), + human.contains( + "3 findings in this scan: 1 open, 0 in other states, 2 unrecognized, 0 in dependencies." + ), "{human}" ); assert!(render_agent(&summary).contains("unrecognized\t2\tstatus=snoozed, urgency=IN\n")); @@ -873,7 +1130,7 @@ mod tests { let out = render_human(&summary_of(issues, Gate::NotRequested), false); let expected = " Scan complete: goof, branch main, scan scan-1 -1 finding in this scan: 1 open, 0 in other states. +1 finding in this scan: 1 open, 0 in other states, 0 in dependencies. Open issues Critical High Medium Low Total ---------------------------------------------------------------- @@ -881,7 +1138,14 @@ SAST, Logic & Auth, Secrets 0 1 0 0 1 ---------------------------------------------------------------- Total open 0 1 0 0 1 -All findings by status Critical High Medium Low Total +Dependencies, any status Critical High Medium Low Total +---------------------------------------------------------------- +Malicious packages 0 0 0 0 0 +Vulnerable packages 0 0 0 0 0 +---------------------------------------------------------------- +Total dependencies 0 0 0 0 0 + +Code findings by status Critical High Medium Low Total ---------------------------------------------------------------- Open 0 1 0 0 1 Fix in Progress 0 0 0 0 0 @@ -941,6 +1205,9 @@ status\tfixed\t1\t0\t0\t0\t1\tresolved status\taccepted_risk\t0\t0\t1\t0\t1\trisk accepted by your team status\tfalse_positive\t0\t1\t1\t0\t2\tnot a real security issue status\tduplicate\t0\t0\t0\t1\t1\tsame as another finding +record\tkind\tcritical\thigh\tmedium\tlow\tunrated\ttotal +dependency\tmalicious\t0\t0\t0\t0\t0\t0 +dependency\tvulnerable\t0\t0\t0\t0\t0\t0 record\tid\tseverity\tcwe\ttitle\tlocation issue\to2\tcritical\tCWE-89\tSQL Injection\tsrc/z.js:1 issue\to1\thigh\tCWE-89\tSQL Injection\tsrc/b.js:9 @@ -962,7 +1229,7 @@ issue\to1\thigh\tCWE-89\tSQL Injection\tsrc/b.js:9 "https://corgea.test/scan".into(), ); let json: Value = serde_json::from_str(&render_json(&summary)).unwrap(); - assert_eq!(json["schema_version"], 1); + assert_eq!(json["schema_version"], 2); assert_eq!(json["scan"]["reused_recent_scan"], true); assert_eq!(json["gate"]["result"], "pass"); assert_eq!(json["gate"]["exit_code"], 0); @@ -973,6 +1240,107 @@ issue\to1\thigh\tCWE-89\tSQL Injection\tsrc/b.js:9 assert_eq!(json["total_findings"], 8); } + #[test] + fn human_calls_out_malicious_dependencies() { + let out = render_human( + &summary_with_dependencies(Ok(malware_dependencies()), vec![]), + false, + ); + let expected = " +Scan complete: goof, branch main, scan scan-1 +3 findings in this scan: 0 open, 0 in other states, 3 in dependencies. +Malware: 2 malicious packages in this scan's dependencies. + +Open issues Critical High Medium Low Total +---------------------------------------------------------------- +SAST, Logic & Auth, Secrets 0 0 0 0 0 +---------------------------------------------------------------- +Total open 0 0 0 0 0 + +Dependencies, any status Critical High Medium Low Total +---------------------------------------------------------------- +Malicious packages 1 0 0 0 2 +Vulnerable packages 0 1 0 0 1 +---------------------------------------------------------------- +Total dependencies 1 1 0 0 3 +1 dependency finding has no severity this CLI recognizes. It counts in Total only. + +Code findings by status Critical High Medium Low Total +---------------------------------------------------------------- +Open 0 0 0 0 0 +Fix in Progress 0 0 0 0 0 +Fixed 0 0 0 0 0 +Accepted Risk 0 0 0 0 0 +False Positive 0 0 0 0 0 +Duplicate 0 0 0 0 0 +---------------------------------------------------------------- +Total 0 0 0 0 0 + +Go to https://corgea.test/scan to see results. +"; + assert_eq!(out, expected); + } + + #[test] + fn agent_and_json_count_malicious_dependencies() { + let summary = summary_with_dependencies(Ok(malware_dependencies()), vec![]); + let agent = render_agent(&summary); + assert!( + agent.contains( + "record\tkind\tcritical\thigh\tmedium\tlow\tunrated\ttotal\n\ + dependency\tmalicious\t1\t0\t0\t0\t1\t2\n\ + dependency\tvulnerable\t0\t1\t0\t0\t0\t1\n" + ), + "{agent}" + ); + let json: Value = serde_json::from_str(&render_json(&summary)).unwrap(); + assert_eq!(json["total_findings"], 3); + assert_eq!(json["dependencies"]["total"], 3); + assert_eq!(json["dependencies"]["malicious"]["total"], 2); + assert_eq!(json["dependencies"]["malicious"]["critical"], 1); + assert_eq!(json["dependencies"]["malicious"]["unrated"], 1); + assert_eq!(json["dependencies"]["vulnerable"]["high"], 1); + assert_eq!(json["dependencies"]["error"], Value::Null); + } + + #[test] + fn a_failed_dependency_read_is_reported_never_counted_as_zero() { + let error = "Failed to get SCA issues: Request failed with status: 403 Forbidden"; + let summary = summary_with_dependencies( + Err(error.into()), + vec![issue("o1", "open", "HI", "src/a.js", 1)], + ); + assert_eq!(summary.total_findings(), None); + + let human = render_human(&summary, false); + assert!( + human.contains( + "1 code finding in this scan: 1 open, 0 in other states, dependencies not fetched.\n" + ), + "{human}" + ); + assert!( + human.contains(&format!( + "Dependency findings could not be fetched: {error}\n" + )), + "{human}" + ); + assert!(!human.contains("Malicious packages"), "{human}"); + + let agent = render_agent(&summary); + assert!( + agent.contains(&format!("record\terror\ndependency_error\t{error}\n")), + "{agent}" + ); + assert!(!agent.contains("dependency\t"), "{agent}"); + + let json: Value = serde_json::from_str(&render_json(&summary)).unwrap(); + assert_eq!(json["dependencies"]["error"], error); + assert_eq!(json["dependencies"]["total"], Value::Null); + assert_eq!(json["dependencies"]["malicious"], Value::Null); + assert_eq!(json["total_findings"], Value::Null); + } + #[test] fn json_omits_reuse_when_the_flag_was_not_passed() { let json: Value = diff --git a/tests/cloud_commands_e2e/common/mod.rs b/tests/cloud_commands_e2e/common/mod.rs index 101ab61..fb807c2 100644 --- a/tests/cloud_commands_e2e/common/mod.rs +++ b/tests/cloud_commands_e2e/common/mod.rs @@ -1008,6 +1008,22 @@ pub(crate) fn append_wait_plan( }, json_response(regular_issue_page(scan_id, project)), )); + expected.push(sca_issues_request(scan_id, empty_issue_page())); +} + +/// The summary's read of the scan's dependency findings, which follows the +/// code-issue read on every `scan` and `wait`. +pub(crate) fn sca_issues_request(scan_id: &str, page: Value) -> ExpectedRequest { + let path = format!("/api/v1/scan/{scan_id}/issues/sca"); + expected_request( + "read SCA issues", + move |request| { + assert_authenticated_request(request, Method::GET, &path)?; + assert_query(request, "page", "1")?; + assert_query(request, "page_size", "30") + }, + json_response(page), + ) } pub(crate) fn assert_issue_summary(stdout: &str, context: &str) { @@ -1015,7 +1031,7 @@ pub(crate) fn assert_issue_summary(stdout: &str, context: &str) { .unwrap() .replace_all(stdout, ""); for line in [ - "4 findings in this scan: 4 open, 0 in other states.", + "4 findings in this scan: 4 open, 0 in other states, 0 in dependencies.", "Total open 1 2 1 0 4", "Open 1 2 1 0 4", ] { @@ -1047,9 +1063,14 @@ pub(crate) fn blast_plan(sha: &str) -> Vec { blast_upload_plan(sha, false, true) } -/// BLAST upload contract. `include_sca` covers `--fail-on malicious` (SCA fetch). -pub(crate) fn blast_upload_plan(sha: &str, dirty: bool, include_sca: bool) -> Vec { - blast_plan_for(sha, dirty, include_sca, true) +/// BLAST upload contract. `malicious_dependency` makes the scan's dependency +/// findings hold one malicious package; otherwise it has none. +pub(crate) fn blast_upload_plan( + sha: &str, + dirty: bool, + malicious_dependency: bool, +) -> Vec { + blast_plan_for(sha, dirty, malicious_dependency, true) } /// The same contract for `--target`, which names the files to upload and so @@ -1070,7 +1091,7 @@ pub(crate) fn blast_excluded_upload_plan(sha: &str) -> Vec { fn blast_plan_for( sha: &str, dirty: bool, - include_sca: bool, + malicious_dependency: bool, look_for_baseline: bool, ) -> Vec { let patch_sha = sha.to_string(); @@ -1143,19 +1164,15 @@ fn blast_plan_for( }, json_response(empty_issue_page()), ), - ]); - if include_sca { - let sca_path = "/api/v1/scan/blast-scan-123/issues/sca".to_string(); - plan.push(expected_request( - "read malicious SCA issues", - move |request| { - assert_authenticated_request(request, Method::GET, &sca_path)?; - assert_query(request, "page", "1")?; - assert_query(request, "page_size", "30") + sca_issues_request( + "blast-scan-123", + if malicious_dependency { + malicious_sca_issue_page() + } else { + empty_issue_page() }, - json_response(malicious_sca_issue_page()), - )); - } + ), + ]); plan } diff --git a/tests/cloud_commands_e2e/scan_incremental.rs b/tests/cloud_commands_e2e/scan_incremental.rs index b077c05..eb642d4 100644 --- a/tests/cloud_commands_e2e/scan_incremental.rs +++ b/tests/cloud_commands_e2e/scan_incremental.rs @@ -199,6 +199,7 @@ fn scan_tail() -> Vec { }, json_response(empty_issue_page()), ), + sca_issues_request("blast-scan-123", empty_issue_page()), ] } diff --git a/tests/cloud_commands_e2e/scan_list.rs b/tests/cloud_commands_e2e/scan_list.rs index 359aae0..5269d26 100644 --- a/tests/cloud_commands_e2e/scan_list.rs +++ b/tests/cloud_commands_e2e/scan_list.rs @@ -24,7 +24,7 @@ fn scan_format_json_prints_only_the_document_on_stdout() { let context = output_context(&output, &transcript); assert_eq!(output.status.code(), Some(1), "{context}"); let document = parse_output_json(&output, &transcript); - assert_eq!(document["schema_version"], 1, "{context}"); + assert_eq!(document["schema_version"], 2, "{context}"); assert_eq!(document["gate"]["result"], "fail", "{context}"); assert_eq!(document["gate"]["exit_code"], 1, "{context}"); assert_eq!(document["gate"]["tripped"], 1, "{context}"); @@ -34,6 +34,126 @@ fn scan_format_json_prints_only_the_document_on_stdout() { assert!(stderr.contains("Scan has started with ID"), "{context}"); } +/// A lockfile that pins a malicious package shows in the summary of a plain +/// scan, with no gate: the code issues alone read "0 findings". +#[test] +fn scan_summary_reports_malicious_dependencies_without_a_gate() { + let project = git_project(); + let api = ApiStub::start(blast_plan(&project.sha)); + let (mut command, _home) = cloud_command(&api, project.path()); + command.args(["scan", "blast", "--project-name", "cloud-e2e"]); + + let output = run_with_timeout(command, &api); + let transcript = api.assert_finished(); + let context = output_context(&output, &transcript); + assert_eq!(output.status.code(), Some(0), "{context}"); + let stdout = String::from_utf8_lossy(&output.stdout); + for line in [ + "1 finding in this scan: 0 open, 0 in other states, 1 in dependencies.", + "Malware: 1 malicious package in this scan's dependencies.", + "Malicious packages 1 0 0 0 1", + ] { + assert!(stdout.contains(line), "missing {line:?}\n{context}"); + } +} + +/// A dependency read that fails is reported as failed, never as zero. +#[test] +fn scan_summary_says_when_dependency_findings_could_not_be_read() { + let project = git_project(); + let plan = answer_with( + blast_plan(&project.sha), + "read SCA issues", + json_response_with_status(StatusCode::FORBIDDEN, json!({"status": "error"})), + ); + let api = ApiStub::start(plan); + let (mut command, _home) = cloud_command(&api, project.path()); + command.args([ + "scan", + "blast", + "--format", + "json", + "--project-name", + "cloud-e2e", + ]); + + let output = run_with_timeout(command, &api); + let transcript = api.assert_finished(); + let context = output_context(&output, &transcript); + assert_eq!(output.status.code(), Some(0), "{context}"); + let document = parse_output_json(&output, &transcript); + let dependencies = &document["dependencies"]; + assert!(dependencies["total"].is_null(), "{context}"); + assert!(dependencies["malicious"].is_null(), "{context}"); + assert!( + dependencies["error"] + .as_str() + .is_some_and(|error| error.contains("403 Forbidden")), + "{context}" + ); +} + +/// The summary, the `--fail-on malicious` gate and the JSON report share one +/// read of the dependency findings: the plan holds a single SCA request. +#[test] +fn scan_reads_dependency_findings_once_for_summary_gate_and_report() { + let project = git_project(); + let out_dir = TempDir::new().expect("create output directory"); + let out_file = out_dir.path().join("results.json"); + let mut plan = blast_plan(&project.sha); + plan.push(expected_request( + "read issues for the JSON report", + |request| { + assert_authenticated_request( + request, + Method::GET, + "/api/v1/scan/blast-scan-123/issues", + )?; + match query_value(request, "show_false_positives") { + Ok(value) => Err(format!("unexpected show_false_positives={value}")), + Err(_) => Ok(()), + } + }, + json_response(empty_issue_page()), + )); + let api = ApiStub::start(plan); + let (mut command, _home) = cloud_command(&api, project.path()); + command.args([ + "scan", + "blast", + "--fail-on", + "malicious", + "--out-format", + "json", + "--out-file", + out_file.to_str().expect("UTF-8 report path"), + "--project-name", + "cloud-e2e", + ]); + + let output = run_with_timeout(command, &api); + let transcript = api.assert_finished(); + let context = output_context(&output, &transcript); + assert_eq!(output.status.code(), Some(1), "{context}"); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + stdout.contains("Malware: 1 malicious package in this scan's dependencies."), + "{context}" + ); + assert!( + stdout.contains("--fail-on malicious (findings in any status, not only open) matched 1"), + "{context}" + ); + let report: serde_json::Value = serde_json::from_str( + &std::fs::read_to_string(&out_file).expect("JSON report should exist"), + ) + .expect("JSON report"); + assert_eq!( + report["sca_issues"][0]["classification"], "malicious", + "{context}" + ); +} + #[test] fn scan_fail_on_severity_and_malicious_counts_both_when_severity_already_trips() { let project = git_project(); diff --git a/tests/cloud_commands_e2e/scan_skip.rs b/tests/cloud_commands_e2e/scan_skip.rs index b06d9cf..63d13fd 100644 --- a/tests/cloud_commands_e2e/scan_skip.rs +++ b/tests/cloud_commands_e2e/scan_skip.rs @@ -123,6 +123,7 @@ fn skipped_scan_still_fails_the_build_on_the_prior_scans_blocking_rules() { commit_lookup(&project.sha, vec![prior_scan(&project.sha, &ago(3))]), clean_detail(&project.sha), reused_scan_issues(), + sca_issues_request(PRIOR_SCAN, empty_issue_page()), reused_scan_sarif_report(), reused_scan_blocking_rules(true), ]); @@ -175,6 +176,7 @@ fn skipped_scan_reports_the_prior_findings() { commit_lookup(&project.sha, vec![prior_scan(&project.sha, &ago(3))]), clean_detail(&project.sha), reused_scan_issues(), + sca_issues_request(PRIOR_SCAN, empty_issue_page()), reused_scan_blocking_rules(false), ]); let (mut command, _home) = cloud_command(&api, project.path()); @@ -315,6 +317,7 @@ fn a_file_hidden_from_git_status_reuses_the_commits_scan() { commit_lookup(&project.sha, vec![prior_scan(&project.sha, &ago(3))]), clean_detail(&project.sha), reused_scan_issues(), + sca_issues_request(PRIOR_SCAN, empty_issue_page()), reused_scan_blocking_rules(false), ]); let (mut command, _home) = cloud_command(&api, project.path()); @@ -359,6 +362,7 @@ fn ignore_dirty_worktree_reuses_a_scan_a_dirty_tree_would_otherwise_run() { commit_lookup(&project.sha, vec![prior_scan(&project.sha, &ago(3))]), clean_detail(&project.sha), reused_scan_issues(), + sca_issues_request(PRIOR_SCAN, empty_issue_page()), reused_scan_blocking_rules(false), ]); let (mut command, _home) = cloud_command(&api, project.path()); @@ -412,6 +416,7 @@ fn ignore_dirty_worktree_reuses_a_prior_dirty_scan() { json_response(detail), ), reused_scan_issues(), + sca_issues_request(PRIOR_SCAN, empty_issue_page()), reused_scan_blocking_rules(false), ]); let (mut command, _home) = cloud_command(&api, project.path()); @@ -628,6 +633,7 @@ fn excluding_files_warns_but_still_reuses_the_commits_scan() { commit_lookup(&project.sha, vec![prior_scan(&project.sha, &ago(3))]), clean_detail(&project.sha), reused_scan_issues(), + sca_issues_request(PRIOR_SCAN, empty_issue_page()), ]); let (mut command, _home) = cloud_command(&api, project.path()); command.args([