From f514f34056ead24d51b97e8bfe40d97e6542769a Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:40:58 +0200 Subject: [PATCH] feat(issues): critical and high CVEs as issues in managed repositories For a target from a managed git source, every critical or high CVE in its components becomes one Gitea issue per package and CVE: "[CVE] okhttp@3.12.0: CVE-2021-0341", labelled pruefwerk, cra:annex-i, severity: and the new `cve`, with the summary, severity, the fixed version where the advisory names one, the CRA requirements (cra-ai-22, cra-ai-33) and a link to the target. Stored per target, package and CVE, so a second version of the package opens no second issue. A complete scan that no longer finds the CVE closes the issue with a comment; it reopens when the CVE comes back. A scan with a CVE gap closes nothing. So severity and the fix are known at all: OSV's batch endpoint returns only advisory ids, so every GHSA alert had no summary, severity or fix. The CVE stage now reads each advisory once (8 at a time) for its summary, GitHub severity, aliases (the CVE id of a GHSA) and the fixed versions of the matched package (by purl). NVD is asked for a CVSS score only where the advisory rates nothing, sparing its rate limit. CveAlert gains `aliases` and `fixed_versions` and `cve()`. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/pipeline/cve.rs | 185 ++++++- compliance-agent/src/pipeline/cve_issues.rs | 483 ++++++++++++++++++ .../src/pipeline/issue_creation.rs | 39 ++ compliance-agent/src/pipeline/mod.rs | 1 + compliance-agent/src/pipeline/orchestrator.rs | 14 + compliance-agent/src/trackers/gitea.rs | 15 +- compliance-core/src/models/cve.rs | 21 + docs/guide/managed-git-en.md | 8 +- docs/guide/managed-git.md | 9 +- 9 files changed, 768 insertions(+), 7 deletions(-) create mode 100644 compliance-agent/src/pipeline/cve_issues.rs diff --git a/compliance-agent/src/pipeline/cve.rs b/compliance-agent/src/pipeline/cve.rs index bb22550..3a395b8 100644 --- a/compliance-agent/src/pipeline/cve.rs +++ b/compliance-agent/src/pipeline/cve.rs @@ -1,3 +1,5 @@ +use std::collections::{BTreeSet, HashMap}; + use compliance_core::models::{CveAlert, CveSource, SbomEntry, VulnRef}; use compliance_core::CoreError; @@ -80,9 +82,42 @@ impl CveScanner { .map(|(_, e)| format!("{} {}", e.name, e.version)) .collect(); - // Enrich with NVD CVSS scores + // The batch answer names only the advisory: read each one once for + // its summary, severity, CVE alias and fixed versions. + let ids: BTreeSet = lookup.alerts.iter().map(|a| a.cve_id.clone()).collect(); + let details = self.osv_details(ids).await; + let purls: HashMap<(String, String), Option> = entries + .iter() + .map(|e| ((e.name.clone(), e.version.clone()), e.purl.clone())) + .collect(); for alert in &mut lookup.alerts { - if let Ok(Some(cvss)) = self.query_nvd(&alert.cve_id).await { + let Some(detail) = details.get(&alert.cve_id) else { + continue; + }; + let purl = purls + .get(&( + alert.affected_package.clone(), + alert.affected_version.clone(), + )) + .cloned() + .flatten(); + alert.summary = detail.summary.clone().or(alert.summary.take()); + alert.severity = detail.severity.clone(); + alert.aliases = detail.aliases.clone(); + alert.fixed_versions = detail.fixed_for(purl.as_deref(), &alert.affected_package); + } + for entry in entries.iter_mut() { + for vuln in &mut entry.known_vulnerabilities { + if let Some(detail) = details.get(&vuln.id) { + vuln.severity = detail.severity.clone().or(vuln.severity.take()); + } + } + } + + // NVD's CVSS score where the advisory itself rates nothing (NVD is + // rate-limited, so it is asked only then). + for alert in lookup.alerts.iter_mut().filter(|a| a.severity.is_none()) { + if let Ok(Some(cvss)) = self.query_nvd(alert.cve()).await { alert.cvss_score = Some(cvss); } } @@ -174,6 +209,35 @@ impl CveScanner { Ok((results, refused)) } + /// OSV's record of each advisory in `ids`, read concurrently. An + /// advisory OSV cannot return is left out: its alert keeps what the batch + /// answer said. + async fn osv_details(&self, ids: BTreeSet) -> HashMap { + use futures_util::StreamExt; + const CONCURRENT_LOOKUPS: usize = 8; + + futures_util::stream::iter(ids) + .map(|id| async move { + let url = format!("https://api.osv.dev/v1/vulns/{id}"); + let record: serde_json::Value = self + .http + .get(&url) + .send() + .await + .ok()? + .error_for_status() + .ok()? + .json() + .await + .ok()?; + Some((id, OsvDetail::parse(&record))) + }) + .buffer_unordered(CONCURRENT_LOOKUPS) + .filter_map(|detail| async move { detail }) + .collect() + .await + } + async fn query_nvd(&self, cve_id: &str) -> Result, CoreError> { if !cve_id.starts_with("CVE-") { return Ok(None); @@ -358,6 +422,79 @@ fn record_nvd( .collect() } +/// What an OSV advisory record says beyond its id. +#[derive(Debug, Default, Clone, PartialEq)] +struct OsvDetail { + summary: Option, + /// The advisory's own rating (`CRITICAL`, `HIGH`, `MODERATE`, `LOW`), as + /// GitHub's advisories carry it. + severity: Option, + aliases: Vec, + /// Per affected package (its versionless purl and name), the versions + /// that fix it. + affected: Vec<(Option, String, Vec)>, +} + +impl OsvDetail { + /// Read an OSV vulnerability record. + fn parse(record: &serde_json::Value) -> Self { + let text = |v: &serde_json::Value| v.as_str().map(str::to_string); + let affected = record["affected"] + .as_array() + .into_iter() + .flatten() + .map(|a| { + let fixed = a["ranges"] + .as_array() + .into_iter() + .flatten() + .flat_map(|r| r["events"].as_array().into_iter().flatten()) + .filter_map(|e| text(&e["fixed"])) + .collect::>(); + ( + text(&a["package"]["purl"]), + text(&a["package"]["name"]).unwrap_or_default(), + fixed, + ) + }) + .collect(); + Self { + summary: text(&record["summary"]).filter(|s| !s.is_empty()), + severity: text(&record["database_specific"]["severity"]), + aliases: record["aliases"] + .as_array() + .into_iter() + .flatten() + .filter_map(text) + .collect(), + affected, + } + } + + /// The fixed versions for the package with `purl` (or `name`), at most a + /// few: an advisory can list one per release line. + fn fixed_for(&self, purl: Option<&str>, name: &str) -> Vec { + const MAX_FIXED: usize = 3; + let base = purl.map(|p| p.split('@').next().unwrap_or(p)); + let mut out: Vec = self + .affected + .iter() + .filter(|(p, n, _)| match (base, p.as_deref()) { + (Some(base), Some(p)) => p == base, + _ => { + n == name + || n.ends_with(&format!(":{name}")) + || n.ends_with(&format!("/{name}")) + } + }) + .flat_map(|(_, _, fixed)| fixed.iter().cloned()) + .collect(); + out.dedup(); + out.truncate(MAX_FIXED); + out + } +} + /// Purl types of package managers OSV publishes no advisories for. Asking /// about them returns nothing, which must not read as "no CVEs". const PURL_TYPES_WITHOUT_OSV: &[&str] = &["pkg:cocoapods/"]; @@ -411,6 +548,50 @@ mod tests { SbomEntry::new("t".into(), name.into(), ver.into(), pm.into()) } + #[test] + fn an_osv_record_gives_severity_alias_and_the_packages_fix() { + let record = serde_json::json!({ + "id": "GHSA-3cqm-mf7h-prrj", + "summary": "Square OkHttp can accept the wrong certificate", + "aliases": ["A-171980069", "CVE-2021-0341"], + "database_specific": { "severity": "HIGH", "cwe_ids": ["CWE-295"] }, + "affected": [ + { + "package": { + "name": "com.squareup.okhttp3:okhttp", + "ecosystem": "Maven", + "purl": "pkg:maven/com.squareup.okhttp3/okhttp" + }, + "ranges": [{ "type": "ECOSYSTEM", "events": [{ "introduced": "0" }, { "fixed": "4.9.2" }] }] + }, + { + "package": { "name": "com.example:other", "ecosystem": "Maven" }, + "ranges": [{ "type": "ECOSYSTEM", "events": [{ "introduced": "0" }, { "fixed": "9.9" }] }] + } + ] + }); + let detail = OsvDetail::parse(&record); + assert_eq!(detail.severity.as_deref(), Some("HIGH")); + assert_eq!( + detail.fixed_for( + Some("pkg:maven/com.squareup.okhttp3/okhttp@3.12.0"), + "okhttp" + ), + ["4.9.2"] + ); + // Without a purl the package name decides. + assert_eq!(detail.fixed_for(None, "okhttp"), ["4.9.2"]); + let mut alert = CveAlert::new( + "GHSA-3cqm-mf7h-prrj".into(), + "t".into(), + "okhttp".into(), + "3.12.0".into(), + CveSource::Osv, + ); + alert.aliases = detail.aliases; + assert_eq!(alert.cve(), "CVE-2021-0341"); + } + #[test] fn cocoapods_components_are_not_asked_about_but_reported_unchecked() { let mut pod = entry("AFNetworking", "2.5.1", "cocoapods"); diff --git a/compliance-agent/src/pipeline/cve_issues.rs b/compliance-agent/src/pipeline/cve_issues.rs new file mode 100644 index 0000000..c4b3c4a --- /dev/null +++ b/compliance-agent/src/pipeline/cve_issues.rs @@ -0,0 +1,483 @@ +//! Known vulnerabilities in a managed repository's dependencies, as issues. +//! +//! For a target from a managed git source (#439), every critical or high CVE +//! in its components becomes one issue per package and CVE, labelled like the +//! finding issues plus `cve`, with the fixed version where the advisory names +//! one. When a later complete scan no longer finds the CVE (the dependency was +//! updated or removed), the issue is closed with a comment; when it comes back, +//! it is reopened. + +use std::collections::{BTreeMap, HashMap}; + +use mongodb::bson::doc; + +use compliance_core::models::notification::{parse_severity, NotificationSeverity}; +use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue}; + +use crate::database::Database; +use crate::error::AgentError; +use crate::pipeline::tracker_dispatch::TrackerDispatch; +use crate::trackers::gitea::{pruefwerk_labels, LABEL_CRA_ANNEX_I, LABEL_CVE, LABEL_PRUEFWERK}; + +/// The CRA requirements a known vulnerability in a component bears on. +const CVE_CONTROLS: [&str; 2] = ["cra-ai-22", "cra-ai-33"]; + +/// Where the issues of one target go. +pub(crate) struct CveIssueTarget<'a> { + pub db: &'a Database, + pub tracker: &'a TrackerDispatch, + pub owner: &'a str, + pub repo: &'a str, + /// The scanned target (`CveAlert::repo_id`). + pub target_id: &'a str, + /// The dashboard's public URL, for a link back; empty for none. + pub dashboard: &'a str, +} + +/// What [`sync_cve_issues`] did. +#[derive(Debug, Default, PartialEq, Eq)] +pub(crate) struct CveIssueCounts { + pub created: u32, + pub reopened: u32, + pub closed: u32, +} + +/// The key a CVE issue is stored under (`TrackerIssue::finding_id`): one per +/// target, package and CVE, so another version of the same package does not +/// open a second issue. +fn issue_key(target_id: &str, alert: &CveAlert) -> String { + format!("cve:{target_id}:{}:{}", alert.affected_package, alert.cve()) +} + +/// A severity as the `severity:` labels name it. +fn severity_name(severity: &NotificationSeverity) -> &'static str { + match severity { + NotificationSeverity::Critical => "critical", + NotificationSeverity::High => "high", + NotificationSeverity::Medium => "medium", + NotificationSeverity::Low => "low", + } +} + +/// Whether an alert is severe enough for an issue. +fn issue_worthy(alert: &CveAlert) -> bool { + matches!( + parse_severity(alert.severity.as_deref(), alert.cvss_score), + NotificationSeverity::Critical | NotificationSeverity::High + ) +} + +/// Open, reopen and close the CVE issues of one target to match `alerts`. +/// +/// # Arguments +/// +/// * `target` - where the issues go +/// * `alerts` - every CVE the scan found in the target's components +/// * `complete` - whether every component was matched; only then is a CVE +/// that is missing from `alerts` known to be gone, and its issue closed +/// +/// # Errors +/// +/// A database error. A tracker call that fails is logged and skipped. +pub(crate) async fn sync_cve_issues( + target: &CveIssueTarget<'_>, + alerts: &[CveAlert], + complete: bool, +) -> Result { + let prefix = format!("cve:{}:", target.target_id); + let mut existing: HashMap = HashMap::new(); + let mut cursor = target + .db + .tracker_issues() + .find(doc! { "finding_id": { "$regex": format!("^{}", regex::escape(&prefix)) } }) + .await?; + while cursor.advance().await? { + let issue = cursor.deserialize_current()?; + existing.insert(issue.finding_id.clone(), issue); + } + // Every CVE still present, and of those the ones worth an issue (the + // first version of a package stands for it). + let present: BTreeMap = alerts + .iter() + .map(|a| (issue_key(target.target_id, a), a)) + .rev() + .collect(); + let label_ids = gitea_label_ids(target).await; + let mut counts = CveIssueCounts::default(); + + for (key, alert) in present.iter().filter(|(_, a)| issue_worthy(a)) { + match existing.get(key) { + Some(issue) if is_closed(&issue.status) => { + let comment = "**Prüfwerk:** Bei der Prüfung erneut gefunden, daher wieder geöffnet.\n\nFound again by the scan, so reopened."; + if set_state(target, issue, comment, "open").await { + record(target.db, issue, IssueStatus::Open).await?; + counts.reopened += 1; + } + } + Some(_) => {} + None => { + if create(target, key, alert, label_ids.as_ref()).await? { + counts.created += 1; + } + } + } + } + + if complete { + for (key, issue) in &existing { + if present.contains_key(key) || is_closed(&issue.status) { + continue; + } + let comment = "**Prüfwerk:** Die Prüfung findet diese Schwachstelle nicht mehr: Die Abhängigkeit wurde aktualisiert oder entfernt.\n\nThe scan no longer finds this vulnerability: the dependency was updated or removed."; + if set_state(target, issue, comment, "closed").await { + record(target.db, issue, IssueStatus::Closed).await?; + counts.closed += 1; + } + } + } + Ok(counts) +} + +/// Whether an issue is closed. +fn is_closed(status: &IssueStatus) -> bool { + matches!(status, IssueStatus::Closed | IssueStatus::Resolved) +} + +/// The Prüfwerk label ids of a Gitea repository, created where missing; +/// `None` for other trackers or when Gitea refuses. +async fn gitea_label_ids(target: &CveIssueTarget<'_>) -> Option> { + let TrackerDispatch::Gitea(gitea) = target.tracker else { + return None; + }; + match gitea + .ensure_labels(target.owner, target.repo, &pruefwerk_labels()) + .await + { + Ok(ids) => Some(ids), + Err(e) => { + tracing::warn!(error = %e, "could not ensure the Prüfwerk labels for CVE issues"); + None + } + } +} + +/// Open the issue for `alert` and store it under `key`. +async fn create( + target: &CveIssueTarget<'_>, + key: &str, + alert: &CveAlert, + label_ids: Option<&HashMap>, +) -> Result { + let severity = severity_name(&parse_severity(alert.severity.as_deref(), alert.cvss_score)); + let title = format!( + "[CVE] {}@{}: {}", + alert.affected_package, + alert.affected_version, + alert.cve() + ); + let body = issue_body(alert, severity, target); + let names = [ + LABEL_PRUEFWERK.to_string(), + LABEL_CRA_ANNEX_I.to_string(), + format!("severity:{severity}"), + LABEL_CVE.to_string(), + ]; + let result = match (target.tracker, label_ids) { + (TrackerDispatch::Gitea(gitea), Some(ids)) => { + let ids: Vec = names.iter().filter_map(|n| ids.get(n).copied()).collect(); + gitea + .create_issue_with_label_ids(target.owner, target.repo, &title, &body, &ids) + .await + } + (tracker, _) => { + tracker + .create_issue(target.owner, target.repo, &title, &body, &names) + .await + } + }; + match result { + Ok(mut issue) => { + issue.finding_id = key.to_string(); + target.db.tracker_issues().insert_one(&issue).await?; + Ok(true) + } + Err(e) => { + tracing::warn!(key, error = %e, "could not open the CVE issue"); + Ok(false) + } + } +} + +/// The issue text: what is affected, how badly, what fixes it, and the CRA +/// requirements concerned. +fn issue_body(alert: &CveAlert, severity: &str, target: &CveIssueTarget<'_>) -> String { + let mut body = format!( + "**{}** betrifft / affects **{} {}**.\n", + alert.cve(), + alert.affected_package, + alert.affected_version + ); + if let Some(summary) = alert.summary.as_deref().filter(|s| !s.is_empty()) { + body.push_str(&format!("\n{summary}\n")); + } + body.push_str(&format!("\n- Schweregrad / Severity: {severity}")); + if let Some(score) = alert.cvss_score { + body.push_str(&format!(" (CVSS {score:.1})")); + } + body.push('\n'); + match alert.fixed_versions.as_slice() { + [] => body + .push_str("- Behoben in / Fixed in: keine Version bekannt / no fixed version known\n"), + fixed => body.push_str(&format!("- Behoben in / Fixed in: {}\n", fixed.join(", "))), + } + body.push_str(&format!( + "- Advisory: https://osv.dev/vulnerability/{}\n", + alert.cve_id + )); + body.push_str("\n### CRA\n\n"); + let map = control_map::ControlMap::cra().ok(); + for id in CVE_CONTROLS { + let title = map + .as_ref() + .and_then(|m| m.coverage(id)) + .map(|c| c.title.clone()) + .unwrap_or_default(); + body.push_str(&format!("- {id} — {title} (Annex I)\n")); + } + let dashboard = target.dashboard.trim_end_matches('/'); + if dashboard.starts_with("https://") { + body.push_str(&format!( + "\n[In Prüfwerk öffnen / Open in Prüfwerk]({dashboard}/targets/{})\n", + target.target_id + )); + } + body +} + +/// Comment on `issue` and set it to `state`; whether both worked. +async fn set_state( + target: &CveIssueTarget<'_>, + issue: &TrackerIssue, + comment: &str, + state: &str, +) -> bool { + let number = issue.external_id.as_str(); + let done = async { + target + .tracker + .add_comment(target.owner, target.repo, number, comment) + .await?; + target + .tracker + .update_issue_status(target.owner, target.repo, number, state) + .await + }; + match done.await { + Ok(()) => true, + Err(e) => { + tracing::warn!(issue = number, error = %e, "could not update the CVE issue"); + false + } + } +} + +/// Store an issue's new state. +async fn record( + db: &Database, + issue: &TrackerIssue, + status: IssueStatus, +) -> Result<(), AgentError> { + let Some(id) = issue.id else { + return Ok(()); + }; + let status = mongodb::bson::to_bson(&status).map_err(|e| AgentError::Other(e.to_string()))?; + db.tracker_issues() + .update_one( + doc! { "_id": id }, + doc! { "$set": { "status": status, "updated_at": mongodb::bson::DateTime::now() } }, + ) + .await?; + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + + use axum::extract::{Path, State}; + use axum::routing::{get, patch, post}; + use axum::{Json, Router}; + use compliance_core::models::CveSource; + use compliance_core::NetGuard; + use secrecy::SecretString; + + use crate::trackers::gitea::GiteaTracker; + + /// The calls a fake Gitea received. + type Calls = Arc>>; + + async fn fake_gitea(calls: Calls) -> String { + async fn labels() -> Json { + Json(serde_json::json!(pruefwerk_labels() + .iter() + .enumerate() + .map(|(i, l)| serde_json::json!({ "id": i as i64 + 1, "name": l.name, "color": "fff" })) + .collect::>())) + } + async fn create( + State(calls): State, + Json(body): Json, + ) -> (axum::http::StatusCode, Json) { + let mut calls = calls.lock().unwrap(); + let number = 100 + calls.len(); + calls.push(format!( + "create {number}: {} labels={}", + body["title"].as_str().unwrap_or_default(), + body["labels"] + )); + calls.push(format!( + "body {number}: {}", + body["body"].as_str().unwrap_or_default() + )); + ( + axum::http::StatusCode::CREATED, + Json( + serde_json::json!({ "number": number, "html_url": format!("https://git/i/{number}") }), + ), + ) + } + async fn comment( + State(calls): State, + Path((_o, _r, n)): Path<(String, String, String)>, + ) -> axum::http::StatusCode { + calls.lock().unwrap().push(format!("comment {n}")); + axum::http::StatusCode::CREATED + } + async fn state( + State(calls): State, + Path((_o, _r, n)): Path<(String, String, String)>, + Json(body): Json, + ) -> Json { + calls + .lock() + .unwrap() + .push(format!("state {n}: {}", body["state"])); + Json(serde_json::json!({})) + } + let app = Router::new() + .route("/api/v1/repos/{o}/{r}/labels", get(labels)) + .route("/api/v1/repos/{o}/{r}/issues", post(create)) + .route("/api/v1/repos/{o}/{r}/issues/{n}/comments", post(comment)) + .route("/api/v1/repos/{o}/{r}/issues/{n}", patch(state)) + .with_state(calls); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{addr}") + } + + fn alert(package: &str, version: &str, id: &str, severity: &str) -> CveAlert { + let mut a = CveAlert::new( + id.into(), + "target-1".into(), + package.into(), + version.into(), + CveSource::Osv, + ); + a.severity = Some(severity.into()); + a.aliases = vec!["CVE-2021-0341".into()]; + a.fixed_versions = vec!["4.9.2".into()]; + a.summary = Some("Square OkHttp can accept the wrong certificate".into()); + a + } + + #[tokio::test] + async fn severe_cves_open_issues_that_close_when_the_dependency_is_fixed() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!( + "cveiss_{}", + &uuid::Uuid::new_v4().simple().to_string()[..10] + ); + let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP cve_issues: no MongoDB reachable at {uri}"); + return; + }; + let db = pool.for_tenant_id("cve-issues").await.unwrap(); + let calls: Calls = Arc::default(); + let base = fake_gitea(calls.clone()).await; + let gitea = + GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap(); + let tracker = TrackerDispatch::Gitea(gitea); + let target = CveIssueTarget { + db: &db, + tracker: &tracker, + owner: "kunde", + repo: "app", + target_id: "target-1", + dashboard: "https://pruefwerk.example", + }; + let okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH"); + let minor = alert("gson", "2.8.8", "GHSA-4jrv-ppp4-jm57", "MODERATE"); + + // A high CVE opens one issue; a moderate one opens none. + let counts = sync_cve_issues(&target, &[okhttp.clone(), minor.clone()], true) + .await + .unwrap(); + assert_eq!( + counts, + CveIssueCounts { + created: 1, + ..Default::default() + } + ); + { + let calls = calls.lock().unwrap(); + assert!(calls[0].starts_with("create 100: [CVE] okhttp@3.12.0: CVE-2021-0341 labels=[")); + // pruefwerk (1), cra:annex-i (2), severity:high (4), cve (7). + assert!(calls[0].ends_with("labels=[1,2,4,7]"), "{}", calls[0]); + assert!(calls[1].contains("Fixed in: 4.9.2")); + assert!(calls[1].contains("cra-ai-22")); + assert!(calls[1].contains("https://pruefwerk.example/targets/target-1")); + } + + // The same scan again: nothing new. An incomplete scan closes nothing. + assert_eq!( + sync_cve_issues(&target, std::slice::from_ref(&okhttp), true) + .await + .unwrap(), + CveIssueCounts::default() + ); + assert_eq!( + sync_cve_issues(&target, &[], false).await.unwrap(), + CveIssueCounts::default() + ); + + // The dependency is updated: the complete scan finds it no more. + assert_eq!( + sync_cve_issues(&target, &[minor], true).await.unwrap(), + CveIssueCounts { + closed: 1, + ..Default::default() + } + ); + assert_eq!( + calls.lock().unwrap().last().unwrap(), + "state 100: \"closed\"" + ); + + // It comes back: reopened, not opened twice. + assert_eq!( + sync_cve_issues(&target, &[okhttp], true).await.unwrap(), + CveIssueCounts { + reopened: 1, + ..Default::default() + } + ); + assert_eq!(calls.lock().unwrap().last().unwrap(), "state 100: \"open\""); + + pool.drop_tenant("cve-issues").await.ok(); + } +} diff --git a/compliance-agent/src/pipeline/issue_creation.rs b/compliance-agent/src/pipeline/issue_creation.rs index 469387c..bb4d2e8 100644 --- a/compliance-agent/src/pipeline/issue_creation.rs +++ b/compliance-agent/src/pipeline/issue_creation.rs @@ -15,6 +15,45 @@ impl PipelineOrchestrator { build_tracker(&self.config, self.net_guard, repo) } + /// Open, reopen and close the CVE issues of a managed repository (see + /// [`crate::pipeline::cve_issues`]); other targets get none. + pub(super) async fn sync_cve_issues( + &self, + repo: &RepoView, + repo_id: &str, + alerts: &[CveAlert], + complete: bool, + ) -> Result<(), AgentError> { + if !repo.managed { + return Ok(()); + } + let (Some(tracker), Some(owner), Some(name)) = ( + self.build_tracker(repo), + repo.tracker_owner.as_deref(), + repo.tracker_repo.as_deref(), + ) else { + return Ok(()); + }; + let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default(); + let target = crate::pipeline::cve_issues::CveIssueTarget { + db: &self.db, + tracker: &tracker, + owner, + repo: name, + target_id: repo_id, + dashboard: &dashboard, + }; + let counts = + crate::pipeline::cve_issues::sync_cve_issues(&target, alerts, complete).await?; + tracing::info!( + "[{repo_id}] CVE issues: {} opened, {} reopened, {} closed", + counts.created, + counts.reopened, + counts.closed + ); + Ok(()) + } + /// Create tracker issues for new findings (severity >= Medium). /// Checks for duplicates via fingerprint search before creating. #[tracing::instrument(skip_all, fields(repo_id = %repo_id))] diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 1fe6278..c77b841 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -1,6 +1,7 @@ pub mod code_review; pub mod cppcheck; pub mod cve; +pub(crate) mod cve_issues; pub mod dedup; pub mod dotnet; pub mod embedded_versions; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 93b9e3a..066027c 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -349,6 +349,9 @@ impl PipelineOrchestrator { k.expose_secret().to_string() }), ); + // Whether every component was matched: only then is a CVE missing + // from this scan known to be gone (and its issue closed). + let mut cve_complete = true; let mut cve_alerts = match tokio::time::timeout( std::time::Duration::from_secs(600), async { @@ -361,17 +364,20 @@ impl PipelineOrchestrator { .await { Ok(Ok(lookup)) => { + cve_complete &= lookup.unchecked.is_empty(); self.record_osv_unchecked(scan_run_id, &lookup.unchecked) .await; lookup.alerts } Ok(Err(e)) => { + cve_complete = false; tracing::warn!("[{repo_id}] CVE scanning failed: {e}"); self.record_cve_gap(scan_run_id, "OSV", "the OSV lookup failed") .await; Vec::new() } Err(_) => { + cve_complete = false; tracing::warn!("[{repo_id}] CVE scanning timed out after 10 minutes"); self.record_cve_gap( scan_run_id, @@ -393,6 +399,7 @@ impl PipelineOrchestrator { Ok(lookup) => { cve_alerts.extend(lookup.alerts); if !lookup.unchecked.is_empty() { + cve_complete = false; self.record_cve_gap( scan_run_id, &format!("NVD: {}", lookup.unchecked.join(", ")), @@ -402,6 +409,7 @@ impl PipelineOrchestrator { } } Err(_) => { + cve_complete = false; tracing::warn!("[{repo_id}] embedded-library CVE match timed out"); self.record_cve_gap( scan_run_id, @@ -669,6 +677,12 @@ impl PipelineOrchestrator { { tracing::warn!("[{repo_id}] Issue creation failed: {e}"); } + if let Err(e) = self + .sync_cve_issues(repo, &repo_id, &cve_alerts, cve_complete) + .await + { + tracing::warn!("[{repo_id}] CVE issue sync failed: {e}"); + } // The onboarded target's findings_count and the git artifact's // last_scanned_commit watermark are persisted by `finalize_target` after diff --git a/compliance-agent/src/trackers/gitea.rs b/compliance-agent/src/trackers/gitea.rs index 2de5ae0..09209c4 100644 --- a/compliance-agent/src/trackers/gitea.rs +++ b/compliance-agent/src/trackers/gitea.rs @@ -259,6 +259,9 @@ pub const LABEL_CRA_ANNEX_I: &str = "cra:annex-i"; /// The labels of a managed repository (#439): `pruefwerk`, `cra:annex-i` and /// one `severity:*` per severity that gets an issue. +/// The label of an issue about a known vulnerability in a dependency. +pub const LABEL_CVE: &str = "cve"; + /// The label of an issue whose finding is an accepted risk (closed in /// Prüfwerk with a reason, not fixed). pub const LABEL_ACCEPTED_RISK: &str = "risk:accepted"; @@ -283,6 +286,11 @@ pub fn pruefwerk_labels() -> Vec { LabelSpec::new("severity:high", "#d93f0b", "Schweregrad hoch / high"), LabelSpec::new("severity:medium", "#fbca04", "Schweregrad mittel / medium"), LabelSpec::new("severity:low", "#0e8a16", "Schweregrad niedrig / low"), + LabelSpec::new( + LABEL_CVE, + "#d73a4a", + "Bekannte Schwachstelle in einer Abhängigkeit / known vulnerability in a dependency", + ), LabelSpec::new( LABEL_ACCEPTED_RISK, "#5319e7", @@ -564,6 +572,7 @@ mod tests { "severity:high", "severity:medium", "severity:low", + "cve", "risk:accepted" ] ); @@ -631,13 +640,13 @@ mod tests { let wanted = pruefwerk_labels(); let ids = tracker.ensure_labels("kunde", "fw", &wanted).await.unwrap(); - assert_eq!(ids.len(), 7); + assert_eq!(ids.len(), 8); assert_eq!(ids["pruefwerk"], 7); - assert_eq!(labels.lock().unwrap().len(), 7); + assert_eq!(labels.lock().unwrap().len(), 8); // A second run finds them all and creates nothing. let again = tracker.ensure_labels("kunde", "fw", &wanted).await.unwrap(); assert_eq!(again, ids); - assert_eq!(labels.lock().unwrap().len(), 7); + assert_eq!(labels.lock().unwrap().len(), 8); } } diff --git a/compliance-core/src/models/cve.rs b/compliance-core/src/models/cve.rs index ef19adc..5fb885e 100644 --- a/compliance-core/src/models/cve.rs +++ b/compliance-core/src/models/cve.rs @@ -23,11 +23,30 @@ pub struct CveAlert { pub summary: Option, pub llm_impact_summary: Option, pub references: Vec, + /// Other ids of the same advisory (a GHSA's `CVE-…`). + #[serde(default)] + pub aliases: Vec, + /// The versions of the affected package that fix it, when the advisory + /// names them. + #[serde(default)] + pub fixed_versions: Vec, #[serde(with = "super::serde_helpers::bson_datetime")] pub created_at: DateTime, } impl CveAlert { + /// The CVE id of the advisory: its own id, or a `CVE-` alias of a GHSA + /// or ecosystem advisory; otherwise its own id. + pub fn cve(&self) -> &str { + if self.cve_id.starts_with("CVE-") { + return &self.cve_id; + } + self.aliases + .iter() + .find(|a| a.starts_with("CVE-")) + .map_or(self.cve_id.as_str(), String::as_str) + } + pub fn new( cve_id: String, repo_id: String, @@ -47,6 +66,8 @@ impl CveAlert { summary: None, llm_impact_summary: None, references: Vec::new(), + aliases: Vec::new(), + fixed_versions: Vec::new(), created_at: Utc::now(), } } diff --git a/docs/guide/managed-git-en.md b/docs/guide/managed-git-en.md index 0638bc5..7a3a12b 100644 --- a/docs/guide/managed-git-en.md +++ b/docs/guide/managed-git-en.md @@ -17,8 +17,14 @@ of an organisation in that instance automatically: - **Findings as issues.** Findings of severity medium and above become issues in the repository, with location, CWE, the CRA requirement concerned, the remediation and a link into Prüfwerk. Prüfwerk creates the labels - `pruefwerk`, `cra:annex-i`, `severity:critical|high|medium|low` and + `pruefwerk`, `cra:annex-i`, `severity:critical|high|medium|low`, `cve` and `risk:accepted` in the repository for them. +- **Known vulnerabilities as issues.** A critical or high CVE in a dependency + becomes one issue per package and CVE (`[CVE] okhttp@3.12.0: CVE-2021-0341`), + labelled like the findings plus `cve`, with the fixed version where the + advisory names one. When a complete scan no longer finds it (the dependency + was updated or removed), the issue is closed with a comment; if it comes + back, it is reopened. - **The issue follows the finding.** When the finding is closed in Prüfwerk — the scan no longer finds it, or someone marks it resolved, a false alarm or ignored — Prüfwerk comments on the issue why and closes it. An accepted risk diff --git a/docs/guide/managed-git.md b/docs/guide/managed-git.md index 701744f..fcacbe2 100644 --- a/docs/guide/managed-git.md +++ b/docs/guide/managed-git.md @@ -18,8 +18,15 @@ Repository-Organisation dieser Instanz automatisch prüfen: - **Befunde als Issues.** Befunde ab Schweregrad „mittel“ erscheinen als Issue im Repository, mit Fundstelle, CWE, der betroffenen CRA-Anforderung, der Maßnahme und einem Link ins Prüfwerk. Prüfwerk legt dazu die Labels - `pruefwerk`, `cra:annex-i`, `severity:critical|high|medium|low` und + `pruefwerk`, `cra:annex-i`, `severity:critical|high|medium|low`, `cve` und `risk:accepted` im Repository an. +- **Bekannte Schwachstellen als Issues.** Eine kritische oder hohe CVE in einer + Abhängigkeit wird ein Issue je Paket und CVE + (`[CVE] okhttp@3.12.0: CVE-2021-0341`), mit denselben Labels wie die Befunde + plus `cve` und der behebenden Version, wenn die Meldung eine nennt. Findet + eine vollständige Prüfung sie nicht mehr (Abhängigkeit aktualisiert oder + entfernt), wird das Issue mit Kommentar geschlossen; taucht sie wieder auf, + wird es wieder geöffnet. - **Das Issue folgt dem Befund.** Wird der Befund im Prüfwerk geschlossen – die Prüfung findet ihn nicht mehr, oder jemand setzt ihn auf behoben, Fehlalarm oder ignoriert –, kommentiert Prüfwerk im Issue den Grund und