From f15d1e5066a68d5c5e6a1e52767bf5978f96f6af Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 9 Oct 2026 18:27:20 +0200 Subject: [PATCH 1/3] fix(cve): notifications and tracker issues respect VEX not_affected and fixed A CVE alert whose VEX statement is not_affected or fixed (by a person, by the scan from Yocto CVE_STATUS / CVE: patches, or imported OpenVEX) still raised a notification and opened or kept a tracker issue. - core: CveAlert::is_resolved_by_vex (via VexStatus::resolves), plus OpenVEX names for statuses and justifications. - vex_lifecycle::attach_stored_vex gives the scan's alerts (which carry no VEX) the statement stored on the alert. - cve_notify::notify_new_cves: one notification path for the scans (code and PLC control-app) and the hourly CVE monitor; skips settled alerts. - The code pipeline now notifies after the Yocto statements are applied, so a recipe's not_affected suppresses the notification on the first scan too. - cve_issues: no issue for a settled CVE; an open one is closed with a comment naming the VEX status and justification (not gated on a complete scan); a withdrawn statement reopens the same issue. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/pipeline/cve_issues.rs | 171 +++++++++++++++++- compliance-agent/src/pipeline/cve_notify.rs | 78 ++++++++ compliance-agent/src/pipeline/mod.rs | 1 + compliance-agent/src/pipeline/orchestrator.rs | 91 ++++------ .../src/pipeline/vex_lifecycle.rs | 40 ++++ compliance-agent/src/scheduler.rs | 48 +---- compliance-agent/tests/vex_lifecycle.rs | 96 +++++++++- compliance-core/src/models/cve.rs | 34 ++++ compliance-core/src/models/vex.rs | 62 +++++++ docs/guide/issues.md | 2 +- docs/guide/vex-en.md | 7 + docs/guide/vex.md | 8 + 12 files changed, 534 insertions(+), 104 deletions(-) create mode 100644 compliance-agent/src/pipeline/cve_notify.rs diff --git a/compliance-agent/src/pipeline/cve_issues.rs b/compliance-agent/src/pipeline/cve_issues.rs index fa47435..909b5bc 100644 --- a/compliance-agent/src/pipeline/cve_issues.rs +++ b/compliance-agent/src/pipeline/cve_issues.rs @@ -7,6 +7,11 @@ //! updated or removed), the issue is closed with a comment; when it comes back, //! it is reopened. //! +//! A CVE a VEX statement settles (`not_affected` or `fixed`, by a person, the +//! scan or an imported VEX document) gets no issue, and its open issue is +//! closed with a comment naming the status and the reason. When the statement +//! is withdrawn, the issue is reopened (or opened) as for a CVE found again. +//! //! What is known about a CVE's exploitation (#493) moves the threshold: a CVE //! in CISA's KEV catalog always gets an issue, rated at least high, and one //! whose EPSS percentile reaches [`epss_percentile`] is rated one step higher @@ -17,7 +22,7 @@ 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 compliance_core::models::{CveAlert, IssueStatus, TrackerIssue, VexAssessment}; use crate::database::Database; use crate::error::AgentError; @@ -136,7 +141,9 @@ fn issue_worthy(alert: &CveAlert, epss_percentile: Option) -> bool { /// # Arguments /// /// * `target` - where the issues go -/// * `alerts` - every CVE the scan found in the target's components +/// * `alerts` - every CVE the scan found in the target's components, with +/// its stored VEX statement +/// ([`crate::pipeline::vex_lifecycle::attach_stored_vex`]) /// * `complete` - whether every component was matched; only then is a CVE /// that is missing from `alerts` known to be gone, and its issue closed /// @@ -171,7 +178,7 @@ pub(crate) async fn sync_cve_issues( for (key, alert) in present .iter() - .filter(|(_, a)| issue_worthy(a, target.epss_percentile)) + .filter(|(_, a)| !a.is_resolved_by_vex() && issue_worthy(a, target.epss_percentile)) { match existing.get(key) { Some(issue) if is_closed(&issue.status) => { @@ -190,6 +197,20 @@ pub(crate) async fn sync_cve_issues( } } + // A VEX statement settles the CVE whether or not the scan was complete. + for (key, alert) in present.iter().filter(|(_, a)| a.is_resolved_by_vex()) { + let (Some(vex), Some(issue)) = (alert.vex.as_ref(), existing.get(key)) else { + continue; + }; + if is_closed(&issue.status) { + continue; + } + if set_state(target, issue, &vex_comment(vex), "closed").await { + record(target.db, issue, IssueStatus::Closed).await?; + counts.closed += 1; + } + } + if complete { for (key, issue) in &existing { if present.contains_key(key) || is_closed(&issue.status) { @@ -205,6 +226,22 @@ pub(crate) async fn sync_cve_issues( Ok(counts) } +/// The comment an issue is closed with when a VEX statement settles its CVE: +/// the status and the justification, or the reason in words. +fn vex_comment(vex: &VexAssessment) -> String { + let reason = match (vex.justification, vex.impact_statement.as_deref()) { + (Some(justification), _) => format!(" ({})", justification.as_str()), + (None, Some(statement)) if !statement.trim().is_empty() => { + format!(": {}", statement.trim()) + } + (None, _) => String::new(), + }; + let status = vex.status.as_str(); + format!( + "**Prüfwerk:** VEX-Status `{status}`{reason}. Geschlossen, solange diese Aussage gilt.\n\nVEX status `{status}`{reason}. Closed while this statement stands." + ) +} + /// Whether an issue is closed. fn is_closed(status: &IssueStatus) -> bool { matches!(status, IssueStatus::Closed | IssueStatus::Resolved) @@ -411,7 +448,7 @@ mod tests { use axum::extract::{Path, State}; use axum::routing::{get, patch, post}; use axum::{Json, Router}; - use compliance_core::models::CveSource; + use compliance_core::models::{CveSource, VexJustification, VexStatus}; use compliance_core::NetGuard; use secrecy::SecretString; @@ -461,8 +498,12 @@ mod tests { async fn comment( State(calls): State, Path((_o, _r, n)): Path<(String, String, String)>, + Json(body): Json, ) -> axum::http::StatusCode { - calls.lock().unwrap().push(format!("comment {n}")); + calls.lock().unwrap().push(format!( + "comment {n}: {}", + body["body"].as_str().unwrap_or_default() + )); axum::http::StatusCode::CREATED } async fn state( @@ -661,4 +702,124 @@ mod tests { pool.drop_tenant("cve-issues").await.ok(); } + + fn vex(status: VexStatus) -> VexAssessment { + VexAssessment { + status, + justification: (status == VexStatus::NotAffected) + .then_some(VexJustification::VulnerableCodeNotInExecutePath), + impact_statement: None, + action_statement: None, + by: "u1".into(), + by_name: None, + at: chrono::Utc::now(), + by_scan: false, + } + } + + #[test] + fn the_vex_comment_names_the_status_and_the_reason() { + let comment = vex_comment(&vex(VexStatus::NotAffected)); + assert!( + comment.contains("VEX status `not_affected` (vulnerable_code_not_in_execute_path)."), + "{comment}" + ); + let mut stated = vex(VexStatus::NotAffected); + stated.justification = None; + stated.impact_statement = Some(" The parser is not built. ".into()); + assert!(vex_comment(&stated).contains("`not_affected`: The parser is not built.")); + assert!(vex_comment(&vex(VexStatus::Fixed)).contains("VEX status `fixed`. Closed")); + } + + #[tokio::test] + async fn a_vex_not_affected_or_fixed_closes_the_issue_until_it_is_withdrawn() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!( + "cvevex_{}", + &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-vex").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: "", + epss_percentile: None, + }; + let mut okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH"); + let mut settled = alert("log4j-core", "2.14.1", "GHSA-jfh8-c2jp-5v3q", "CRITICAL"); + settled.aliases = vec!["CVE-2021-44228".into()]; + settled.vex = Some(vex(VexStatus::Fixed)); + + // A settled CVE opens no issue; the unsettled one opens one. + let counts = sync_cve_issues(&target, &[okhttp.clone(), settled.clone()], true) + .await + .unwrap(); + assert_eq!( + counts, + CveIssueCounts { + created: 1, + ..Default::default() + } + ); + assert!(calls.lock().unwrap()[0].contains("okhttp@3.12.0")); + + // Stated not_affected: closed with the status and the reason, even + // after an incomplete scan, and only once. + okhttp.vex = Some(vex(VexStatus::NotAffected)); + let both = [okhttp.clone(), settled.clone()]; + assert_eq!( + sync_cve_issues(&target, &both, false).await.unwrap(), + CveIssueCounts { + closed: 1, + ..Default::default() + } + ); + { + let calls = calls.lock().unwrap(); + let comment = &calls[calls.len() - 2]; + assert!(comment.starts_with("comment 100: "), "{comment}"); + assert!( + comment.contains("`not_affected` (vulnerable_code_not_in_execute_path)"), + "{comment}" + ); + assert_eq!(calls.last().unwrap(), "state 100: \"closed\""); + } + assert_eq!( + sync_cve_issues(&target, &both, true).await.unwrap(), + CveIssueCounts::default() + ); + + // Withdrawn (back under investigation): the same issue is reopened, + // not opened twice. + okhttp.vex = Some(vex(VexStatus::UnderInvestigation)); + assert_eq!( + sync_cve_issues(&target, &[okhttp.clone(), settled], true) + .await + .unwrap(), + CveIssueCounts { + reopened: 1, + ..Default::default() + } + ); + assert_eq!(calls.lock().unwrap().last().unwrap(), "state 100: \"open\""); + assert_eq!( + db.tracker_issues().count_documents(doc! {}).await.unwrap(), + 1 + ); + + pool.drop_tenant("cve-issues-vex").await.ok(); + } } diff --git a/compliance-agent/src/pipeline/cve_notify.rs b/compliance-agent/src/pipeline/cve_notify.rs new file mode 100644 index 0000000..9cfe3a2 --- /dev/null +++ b/compliance-agent/src/pipeline/cve_notify.rs @@ -0,0 +1,78 @@ +//! A notification for every CVE a target's components newly carry, shared by +//! the scans (every SBOM source: source, firmware, CODESYS libraries and +//! runtime) and the hourly CVE monitor. +//! +//! One notification per CVE, target, package and version. An alert a VEX +//! statement settles (`not_affected` or `fixed`, see +//! [`CveAlert::is_resolved_by_vex`]) raises none; once the statement is +//! withdrawn, the next scan or monitor run raises it as for any new CVE. + +use mongodb::bson::doc; + +use compliance_core::models::notification::{parse_severity, CveNotification}; +use compliance_core::models::CveAlert; + +use crate::database::Database; + +/// Create the notifications `alerts` of the target `repo_id` (named +/// `repo_name`) do not have yet. The alerts carry their stored VEX statement +/// ([`crate::pipeline::vex_lifecycle::attach_stored_vex`]). +/// +/// # Returns +/// +/// How many notifications were created. A notification that cannot be stored +/// is logged and skipped. +pub async fn notify_new_cves( + db: &Database, + repo_id: &str, + repo_name: &str, + alerts: &[CveAlert], +) -> u32 { + let mut created = 0; + for alert in alerts.iter().filter(|a| !a.is_resolved_by_vex()) { + let filter = doc! { + "cve_id": &alert.cve_id, + "repo_id": &alert.repo_id, + "package_name": &alert.affected_package, + "package_version": &alert.affected_version, + }; + let severity = parse_severity(alert.severity.as_deref(), alert.cvss_score); + let mut notification = CveNotification::new( + alert.cve_id.clone(), + repo_id.to_string(), + repo_name.to_string(), + alert.affected_package.clone(), + alert.affected_version.clone(), + severity, + ); + notification.cvss_score = alert.cvss_score; + notification.summary = alert.summary.clone(); + notification.url = Some(format!("https://osv.dev/vulnerability/{}", alert.cve_id)); + let notification = match mongodb::bson::to_bson(¬ification) { + Ok(n) => n, + Err(e) => { + tracing::warn!( + cve = alert.cve_id, + "could not encode the CVE notification: {e}" + ); + continue; + } + }; + // Inserted only when missing (`$setOnInsert`), so a notification + // that was read or dismissed stays as it is. + match db + .cve_notifications() + .update_one(filter, doc! { "$setOnInsert": notification }) + .upsert(true) + .await + { + Ok(result) if result.upserted_id.is_some() => created += 1, + Ok(_) => {} + Err(e) => tracing::warn!( + cve = alert.cve_id, + "could not store the CVE notification: {e}" + ), + } + } + created +} diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 0000eb0..3a21512 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -11,6 +11,7 @@ pub(crate) mod csaf_match; pub mod cve; pub(crate) mod cve_enrichment; pub(crate) mod cve_issues; +pub mod cve_notify; pub mod dedup; pub mod devskim; pub mod dotnet; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index c629ecc..a63ac5b 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -945,15 +945,12 @@ impl PipelineOrchestrator { .await?; } - // Persist CVE alerts and create notifications (shared with the PLC path). - let new_notif_count = self - .persist_cve_alerts(&repo_id, &repo.name, &cve_alerts) - .await?; - if new_notif_count > 0 { - tracing::info!("[{repo_id}] Created {new_notif_count} CVE notification(s)"); - } + // Persist CVE alerts (shared with the PLC path). + self.persist_cve_alerts(&cve_alerts).await?; // What the recipes say about their CVEs (CVE_STATUS, `CVE:` patches), - // stated again after the alerts were stored, never over a person's. + // stated again after the alerts were stored, never over a person's, + // and before the notifications, which a `not_affected` or `fixed` + // suppresses. let statements = yocto_inventory::vex_statements(&yocto_recipes, &cve_alerts); if !statements.is_empty() { match crate::pipeline::vex_lifecycle::apply_scan_statements( @@ -967,6 +964,12 @@ impl PipelineOrchestrator { Err(e) => tracing::warn!("[{repo_id}] VEX statements from Yocto recipes: {e}"), } } + let new_notif_count = self + .notify_cves(&repo_id, &repo.name, &mut cve_alerts) + .await?; + if new_notif_count > 0 { + tracing::info!("[{repo_id}] Created {new_notif_count} CVE notification(s)"); + } // Stage 6: Issue Creation tracing::info!("[{repo_id}] Stage 6: Issue Creation"); @@ -1717,8 +1720,9 @@ impl PipelineOrchestrator { .await?; } } + self.persist_cve_alerts(&alerts).await?; let new_notifs = self - .persist_cve_alerts(target_id, &target.name, &alerts) + .notify_cves(target_id, &target.name, &mut alerts) .await?; // What the code pipeline does at its end: a complete lookup resolves // the alerts it no longer reports, and a managed repository's CVE @@ -1769,57 +1773,32 @@ impl PipelineOrchestrator { } } - /// Upsert CVE alerts for a target and create dedup'd CVE notifications; - /// returns the number of newly-created notifications. Shared by the SAST - /// pipeline and the PLC control-app SBOM path, so every SBOM source (source, - /// firmware, CODESYS libraries/runtime) raises the same notifications. - async fn persist_cve_alerts( + /// Store the CVE alerts a scan of a target found. Shared by the SAST + /// pipeline and the PLC control-app SBOM path. + async fn persist_cve_alerts(&self, alerts: &[CveAlert]) -> Result<(), AgentError> { + for alert in alerts { + crate::pipeline::vex_lifecycle::upsert_reported(&self.db, alert).await?; + } + Ok(()) + } + + /// Give the stored alerts' VEX statements to `alerts` and create the CVE + /// notifications that are new (none for an alert `not_affected` or + /// `fixed`); returns how many were created. Run after + /// [`Self::persist_cve_alerts`] and the scan's own VEX statements, so + /// every SBOM source (source, firmware, CODESYS libraries/runtime) raises + /// the same notifications and the issue sync sees the statements. + async fn notify_cves( &self, repo_id: &str, repo_name: &str, - alerts: &[CveAlert], + alerts: &mut [CveAlert], ) -> Result { - use compliance_core::models::notification::{parse_severity, CveNotification}; - - let mut new_notif = 0u32; - for alert in alerts { - crate::pipeline::vex_lifecycle::upsert_reported(&self.db, alert).await?; - - // Dedup notifications by cve + repo + package + version. - let notif_filter = doc! { - "cve_id": &alert.cve_id, - "repo_id": &alert.repo_id, - "package_name": &alert.affected_package, - "package_version": &alert.affected_version, - }; - let severity = parse_severity(alert.severity.as_deref(), alert.cvss_score); - let mut notification = CveNotification::new( - alert.cve_id.clone(), - repo_id.to_string(), - repo_name.to_string(), - alert.affected_package.clone(), - alert.affected_version.clone(), - severity, - ); - notification.cvss_score = alert.cvss_score; - notification.summary = alert.summary.clone(); - notification.url = Some(format!("https://osv.dev/vulnerability/{}", alert.cve_id)); - let notif_update = doc! { - "$setOnInsert": mongodb::bson::to_bson(¬ification).unwrap_or_default() - }; - if let Ok(result) = self - .db - .cve_notifications() - .update_one(notif_filter, notif_update) - .upsert(true) - .await - { - if result.upserted_id.is_some() { - new_notif += 1; - } - } - } - Ok(new_notif) + crate::pipeline::vex_lifecycle::attach_stored_vex(&self.db, repo_id, alerts).await?; + Ok( + crate::pipeline::cve_notify::notify_new_cves(&self.db, repo_id, repo_name, alerts) + .await, + ) } /// Ingest the target's artifacts, classify (Firmwerk for firmware/RTOS/Yocto, diff --git a/compliance-agent/src/pipeline/vex_lifecycle.rs b/compliance-agent/src/pipeline/vex_lifecycle.rs index f571723..74a1df9 100644 --- a/compliance-agent/src/pipeline/vex_lifecycle.rs +++ b/compliance-agent/src/pipeline/vex_lifecycle.rs @@ -209,6 +209,46 @@ fn scan_may_state(repo_id: &str, cve_id: &str) -> mongodb::bson::Document { } } +/// Give the alerts a scan found (which carry no VEX statement) the statement +/// stored on `repo_id`'s alert of the same CVE, or none, so that +/// [`CveAlert::is_resolved_by_vex`] tells whether they notify and keep an +/// issue. Run after the alerts were stored and the scan's own statements set +/// ([`upsert_reported`], [`apply_scan_statements`]). +/// +/// # Errors +/// +/// A database error. +pub async fn attach_stored_vex( + db: &Database, + repo_id: &str, + alerts: &mut [CveAlert], +) -> Result<(), AgentError> { + if alerts.is_empty() { + return Ok(()); + } + let ids: Vec<&str> = alerts.iter().map(|a| a.cve_id.as_str()).collect(); + let stored: Vec = db + .cve_alerts() + .find(doc! { + "repo_id": repo_id, + "cve_id": { "$in": ids }, + "vex": { "$exists": true }, + }) + .await? + .try_collect() + .await?; + let statements: std::collections::HashMap = stored + .into_iter() + .filter_map(|alert| Some((alert.cve_id, alert.vex?))) + .collect(); + for alert in alerts { + // Cloned, not taken: one CVE can be listed for two versions of a + // package. + alert.vex = statements.get(&alert.cve_id).cloned(); + } + Ok(()) +} + /// Mark resolved the stored alerts of `repo_id` a complete lookup /// (`complete`) no longer reports in `current`. /// diff --git a/compliance-agent/src/scheduler.rs b/compliance-agent/src/scheduler.rs index a6f66cb..555627b 100644 --- a/compliance-agent/src/scheduler.rs +++ b/compliance-agent/src/scheduler.rs @@ -242,7 +242,6 @@ async fn scan_all_repos(agent: &ComplianceAgent, tenant_id: &str) { } async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) { - use compliance_core::models::notification::{parse_severity, CveNotification}; use compliance_core::models::SbomEntry; use futures_util::StreamExt; @@ -382,46 +381,15 @@ async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) { } } - // Create notifications for NEW CVEs (dedup against existing notifications) - for alert in &alerts { - let filter = doc! { - "cve_id": &alert.cve_id, - "repo_id": &alert.repo_id, - "package_name": &alert.affected_package, - "package_version": &alert.affected_version, - }; - // Only insert if not already exists (upsert with $setOnInsert) - let severity = parse_severity(alert.severity.as_deref(), alert.cvss_score); - let mut notification = CveNotification::new( - alert.cve_id.clone(), - repo_id.clone(), - repo_name.clone(), - alert.affected_package.clone(), - alert.affected_version.clone(), - severity, - ); - notification.cvss_score = alert.cvss_score; - notification.summary = alert.summary.clone(); - notification.url = Some(format!("https://osv.dev/vulnerability/{}", alert.cve_id)); - - let update = doc! { - "$setOnInsert": mongodb::bson::to_bson(¬ification).unwrap_or_default() - }; - match db - .cve_notifications() - .update_one(filter, update) - .upsert(true) - .await - { - Ok(result) if result.upserted_id.is_some() => { - new_notifications += 1; - } - Err(e) => { - tracing::warn!("CVE monitor: failed to create notification: {e}"); - } - _ => {} // Already exists - } + // Notifications for new CVEs, none for one a VEX statement settles. + if let Err(e) = + crate::pipeline::vex_lifecycle::attach_stored_vex(&db, &repo_id, &mut alerts).await + { + tracing::warn!("CVE monitor: failed to read the VEX statements of {repo_name}: {e}"); + continue; } + new_notifications += + crate::pipeline::cve_notify::notify_new_cves(&db, &repo_id, &repo_name, &alerts).await; } if new_notifications > 0 { diff --git a/compliance-agent/tests/vex_lifecycle.rs b/compliance-agent/tests/vex_lifecycle.rs index 71d8eac..9e040a5 100644 --- a/compliance-agent/tests/vex_lifecycle.rs +++ b/compliance-agent/tests/vex_lifecycle.rs @@ -1,15 +1,18 @@ //! #498: a CVE alert's VEX status follows the scans. Gone after a complete //! lookup, an unassessed or affected alert is `fixed` by the scan, a //! person's `not_affected` stays; reported again, the scan's `fixed` is -//! withdrawn. A stored alert gets its component's purl on a later scan. +//! withdrawn. A stored alert gets its component's purl on a later scan. An +//! alert `not_affected` or `fixed` raises no notification until the +//! statement is withdrawn. //! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips //! cleanly without one. #![allow(clippy::expect_used, clippy::unwrap_used)] use compliance_agent::database::{Database, DatabasePool}; +use compliance_agent::pipeline::cve_notify::notify_new_cves; use compliance_agent::pipeline::vex_lifecycle::{ - apply_scan_statements, backfill_purls, resolve_gone, upsert_reported, + apply_scan_statements, attach_stored_vex, backfill_purls, resolve_gone, upsert_reported, }; use compliance_agent::pipeline::yocto_inventory::{self, CveStatus, Patch, Recipe}; use compliance_core::models::{ @@ -376,3 +379,92 @@ async fn a_recipe_states_vex_each_scan_but_never_over_a_person() { pool.drop_tenant(tenant).await.ok(); } + +/// What a scan does: store the alerts, set its own statements, then give the +/// alerts their stored statements and notify. +async fn scan_and_notify( + db: &Database, + found: &[CveAlert], + statements: &[(String, VexAssessment)], +) -> u32 { + for alert in found { + upsert_reported(db, alert).await.unwrap(); + } + apply_scan_statements(db, TARGET, statements).await.unwrap(); + let mut found = found.to_vec(); + attach_stored_vex(db, TARGET, &mut found).await.unwrap(); + notify_new_cves(db, TARGET, "app", &found).await +} + +#[tokio::test] +async fn not_affected_and_fixed_raise_no_notification_until_withdrawn() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!( + "vexnotif_{}", + &uuid::Uuid::new_v4().simple().to_string()[..10] + ); + let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP vex_lifecycle: no MongoDB reachable at {uri}"); + return; + }; + let tenant = "vex-notifications"; + let Ok(db) = pool.for_tenant_id(tenant).await else { + eprintln!("SKIP vex_lifecycle: MongoDB at {uri} not usable"); + return; + }; + let found: Vec = ["CVE-1", "CVE-2", "CVE-3", "CVE-4", "CVE-5"] + .into_iter() + .map(alert) + .collect(); + for alert in &found { + upsert_reported(&db, alert).await.unwrap(); + } + // A person settles CVE-2 and CVE-3 and confirms CVE-4; a recipe says + // CVE-5 is not affected. + for (id, status) in [ + ("CVE-2", VexStatus::NotAffected), + ("CVE-3", VexStatus::Fixed), + ("CVE-4", VexStatus::Affected), + ] { + let vex = mongodb::bson::to_bson(&by_person(status)).unwrap(); + db.cve_alerts() + .update_one(doc! { "cve_id": id }, doc! { "$set": { "vex": vex } }) + .await + .unwrap(); + } + let mut recipe_says = by_person(VexStatus::NotAffected); + recipe_says.by_scan = true; + let recipe = vec![("CVE-5".to_string(), recipe_says)]; + + // Only the unsettled CVEs notify, and only once. + assert_eq!(scan_and_notify(&db, &found, &recipe).await, 2); + assert_eq!(scan_and_notify(&db, &found, &recipe).await, 0); + let mut notified: Vec = db + .cve_notifications() + .distinct("cve_id", doc! {}) + .await + .unwrap() + .into_iter() + .filter_map(|id| id.as_str().map(str::to_owned)) + .collect(); + notified.sort(); + assert_eq!(notified, ["CVE-1", "CVE-4"]); + + // The person withdraws CVE-2's statement and the recipe no longer + // assesses CVE-5: both notify now; CVE-3 stays fixed and silent. + db.cve_alerts() + .update_one(doc! { "cve_id": "CVE-2" }, doc! { "$unset": { "vex": "" } }) + .await + .unwrap(); + assert_eq!(scan_and_notify(&db, &found, &[]).await, 2); + assert_eq!( + db.cve_notifications() + .count_documents(doc! { "cve_id": "CVE-3" }) + .await + .unwrap(), + 0 + ); + + pool.drop_tenant(tenant).await.ok(); +} diff --git a/compliance-core/src/models/cve.rs b/compliance-core/src/models/cve.rs index 119fd5d..c68a240 100644 --- a/compliance-core/src/models/cve.rs +++ b/compliance-core/src/models/cve.rs @@ -203,6 +203,15 @@ impl CveAlert { ids } + /// Whether a VEX statement settles the alert: `not_affected` or `fixed`, + /// stated by a person, by the scan or in an imported VEX document. Such an + /// alert raises no notification and keeps no open tracker issue; once the + /// statement is withdrawn (back to `affected`, `under_investigation` or + /// none) it counts again. + pub fn is_resolved_by_vex(&self) -> bool { + self.vex.as_ref().is_some_and(|vex| vex.status.resolves()) + } + pub fn new( cve_id: String, repo_id: String, @@ -251,6 +260,31 @@ mod tests { a } + #[test] + fn only_not_affected_and_fixed_resolve_an_alert() { + use crate::models::vex::{VexAssessment, VexStatus}; + let mut a = alert("CVE-2021-44228", &[]); + assert!(!a.is_resolved_by_vex()); + for (status, resolved) in [ + (VexStatus::UnderInvestigation, false), + (VexStatus::Affected, false), + (VexStatus::NotAffected, true), + (VexStatus::Fixed, true), + ] { + a.vex = Some(VexAssessment { + status, + justification: None, + impact_statement: None, + action_statement: None, + by: "u1".into(), + by_name: None, + at: Utc::now(), + by_scan: false, + }); + assert_eq!(a.is_resolved_by_vex(), resolved, "{status:?}"); + } + } + #[test] fn a_cve_is_strictly_recognised() { assert!(is_cve("CVE-2021-44228")); diff --git a/compliance-core/src/models/vex.rs b/compliance-core/src/models/vex.rs index af6a2df..20908c7 100644 --- a/compliance-core/src/models/vex.rs +++ b/compliance-core/src/models/vex.rs @@ -24,6 +24,27 @@ pub enum VexStatus { Fixed, } +impl VexStatus { + /// Whether the status settles the vulnerability for the product: + /// `not_affected` or `fixed`. + pub fn resolves(self) -> bool { + match self { + Self::NotAffected | Self::Fixed => true, + Self::UnderInvestigation | Self::Affected => false, + } + } + + /// The status as OpenVEX names it (`not_affected`). + pub fn as_str(self) -> &'static str { + match self { + Self::UnderInvestigation => "under_investigation", + Self::Affected => "affected", + Self::NotAffected => "not_affected", + Self::Fixed => "fixed", + } + } +} + /// Why the product is not affected (OpenVEX's five justifications). #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] @@ -35,6 +56,21 @@ pub enum VexJustification { InlineMitigationsAlreadyExist, } +impl VexJustification { + /// The justification as OpenVEX names it (`vulnerable_code_not_present`). + pub fn as_str(self) -> &'static str { + match self { + Self::ComponentNotPresent => "component_not_present", + Self::VulnerableCodeNotPresent => "vulnerable_code_not_present", + Self::VulnerableCodeNotInExecutePath => "vulnerable_code_not_in_execute_path", + Self::VulnerableCodeCannotBeControlledByAdversary => { + "vulnerable_code_cannot_be_controlled_by_adversary" + } + Self::InlineMitigationsAlreadyExist => "inline_mitigations_already_exist", + } + } +} + /// One VEX statement on an alert: the status, its reasons, and who made it. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct VexAssessment { @@ -133,4 +169,30 @@ mod tests { )) ); } + + #[test] + fn the_names_are_openvex_s() { + use VexJustification as J; + use VexStatus as S; + for status in [S::UnderInvestigation, S::Affected, S::NotAffected, S::Fixed] { + assert_eq!( + serde_json::to_value(status).ok(), + Some(serde_json::json!(status.as_str())) + ); + } + for justification in [ + J::ComponentNotPresent, + J::VulnerableCodeNotPresent, + J::VulnerableCodeNotInExecutePath, + J::VulnerableCodeCannotBeControlledByAdversary, + J::InlineMitigationsAlreadyExist, + ] { + assert_eq!( + serde_json::to_value(justification).ok(), + Some(serde_json::json!(justification.as_str())) + ); + } + assert!(S::NotAffected.resolves() && S::Fixed.resolves()); + assert!(!S::Affected.resolves() && !S::UnderInvestigation.resolves()); + } } diff --git a/docs/guide/issues.md b/docs/guide/issues.md index 6e8d731..d3d8957 100644 --- a/docs/guide/issues.md +++ b/docs/guide/issues.md @@ -19,7 +19,7 @@ A scan opens issues only for the findings it finds new, so a finding whose issue ### CVE issues (managed repositories) -For a repository from a managed git source, known vulnerabilities in its dependencies become issues too: one per package and CVE, labelled `cve`. A critical or high CVE opens one, and so does any CVE in CISA's Known Exploited Vulnerabilities catalog (rated at least high). A CVE whose EPSS percentile reaches `CVE_ISSUE_EPSS_PERCENTILE` (default `0.95`) is rated one step higher, so a medium one opens an issue as high. The issue names the KEV entry, the EPSS score with its attribution, and CISA's SSVC exploitation where known. When a complete scan no longer finds the CVE, the issue is closed; when it comes back, it is reopened. +For a repository from a managed git source, known vulnerabilities in its dependencies become issues too: one per package and CVE, labelled `cve`. A critical or high CVE opens one, and so does any CVE in CISA's Known Exploited Vulnerabilities catalog (rated at least high). A CVE whose EPSS percentile reaches `CVE_ISSUE_EPSS_PERCENTILE` (default `0.95`) is rated one step higher, so a medium one opens an issue as high. The issue names the KEV entry, the EPSS score with its attribution, and CISA's SSVC exploitation where known. When a complete scan no longer finds the CVE, the issue is closed; when it comes back, it is reopened. A CVE with the VEX status `not_affected` or `fixed` gets no issue, and its open issue is closed with a comment naming the status and the justification; when the statement is withdrawn, the issue is reopened. ## Issues List diff --git a/docs/guide/vex-en.md b/docs/guide/vex-en.md index 206f24f..4711598 100644 --- a/docs/guide/vex-en.md +++ b/docs/guide/vex-en.md @@ -48,6 +48,13 @@ removed or updated), it is marked fixed and "Stated by" shows **Scan**. A "Not affected" or "Fixed" stated by a person is never changed by a scan. If the vulnerability comes back, the scan withdraws its "Fixed". +A vulnerability that is "Not affected" or "Fixed" (stated by a person, by the +scan or in an imported VEX document) raises no notification and gets no issue +in the repository's tracker; an open issue for it is closed with a comment +naming the status and the reason. If the statement is withdrawn, it notifies +and its issue is reopened as before. Notifications raised before the +statement stay in the list until they are dismissed. + ## Downloading **Download OpenVEX** and **Download CycloneDX VEX** save the target's diff --git a/docs/guide/vex.md b/docs/guide/vex.md index fc65382..08b6d32 100644 --- a/docs/guide/vex.md +++ b/docs/guide/vex.md @@ -50,6 +50,14 @@ zeigt dann **Prüfung**. Eine Aussage „Nicht betroffen“ oder „Behoben“, eine Person gemacht hat, ändert die Prüfung nie. Taucht die Schwachstelle wieder auf, nimmt die Prüfung ihr „Behoben“ zurück. +Eine Schwachstelle mit „Nicht betroffen“ oder „Behoben“ (von einer Person, +der Prüfung oder aus einem importierten VEX-Dokument) löst keine +Benachrichtigung aus und bekommt kein Issue im Tracker des Repositorys; ein +offenes Issue dazu wird mit einem Kommentar geschlossen, der Status und +Begründung nennt. Wird die Aussage zurückgenommen, benachrichtigt sie wieder +und ihr Issue wird wieder geöffnet. Benachrichtigungen von vor der Aussage +bleiben in der Liste, bis sie verworfen werden. + ## Herunterladen **OpenVEX herunterladen** und **CycloneDX VEX herunterladen** speichern die -- 2.54.1 From f552a6a72aff0c2abf9b993c11889592c4fc35fc Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 9 Oct 2026 18:42:25 +0200 Subject: [PATCH 2/3] feat(cve): closing CVE issues settled by VEX behind ISSUE_AUTOCLOSE (off by default) No new notification or issue for a not_affected/fixed CVE stays always on. Closing an issue that is already open now depends on ISSUE_AUTOCLOSE (off | dry_run | on, unknown -> off with a warning), like ISSUE_CATCHUP: dry_run logs one line per target with the counts per VEX status and makes no tracker call; on closes at most 20 per target and scan (every Gitea request waits for its instance's slot) and logs closed/deferred/failed. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- .env.example | 4 + compliance-agent/src/config.rs | 13 +- compliance-agent/src/pipeline/cve_issues.rs | 306 +++++++++++++++--- .../src/pipeline/issue_creation.rs | 2 + compliance-core/src/config.rs | 63 ++++ docs/guide/issues.md | 2 +- docs/guide/vex-en.md | 4 +- docs/guide/vex.md | 6 +- 8 files changed, 347 insertions(+), 53 deletions(-) diff --git a/.env.example b/.env.example index b5ec417..86cf27f 100644 --- a/.env.example +++ b/.env.example @@ -54,6 +54,10 @@ CVE_MONITOR_SCHEDULE=0 0 0 * * * # that never got an issue are linked to their existing issue or get a new one, # at most 20 new per target and scan. off (default) | dry_run (log counts only) | on # ISSUE_CATCHUP=off +# Closing CVE issues a VEX statement settles (not_affected or fixed), with a +# comment, at most 20 per target and scan; no new issue is opened for such a +# CVE either way. off (default) | dry_run (log counts per VEX status) | on +# ISSUE_AUTOCLOSE=off GIT_CLONE_BASE_PATH=/tmp/compliance-scanner/repos # NuGet licenses (#467): look up licenses the tree's .nuspec files do not give # on api.nuget.org (package id and version only; never for ids a nuget.config diff --git a/compliance-agent/src/config.rs b/compliance-agent/src/config.rs index cb6aaf8..0e31633 100644 --- a/compliance-agent/src/config.rs +++ b/compliance-agent/src/config.rs @@ -1,4 +1,6 @@ -use compliance_core::config::{AppEnv, BreakpilotConfig, Features, IssueCatchup, PlcRuntimeConfig}; +use compliance_core::config::{ + AppEnv, BreakpilotConfig, Features, IssueAutoclose, IssueCatchup, PlcRuntimeConfig, +}; use compliance_core::AgentConfig; use secrecy::SecretString; @@ -128,6 +130,15 @@ fn build_config(app_env: AppEnv) -> Result { features: Features::parse(&env_var_opt("PW_FEATURES").unwrap_or_default()), app_env, issue_catchup: load_issue_catchup(), + issue_autoclose: load_issue_autoclose(), + }) +} + +/// `ISSUE_AUTOCLOSE`; an unknown value is logged and leaves closing off. +fn load_issue_autoclose() -> IssueAutoclose { + IssueAutoclose::parse(&env_var_opt("ISSUE_AUTOCLOSE").unwrap_or_default()).unwrap_or_else(|e| { + tracing::warn!("{e}; CVE issues settled by VEX stay open"); + IssueAutoclose::Off }) } diff --git a/compliance-agent/src/pipeline/cve_issues.rs b/compliance-agent/src/pipeline/cve_issues.rs index 909b5bc..d0b8608 100644 --- a/compliance-agent/src/pipeline/cve_issues.rs +++ b/compliance-agent/src/pipeline/cve_issues.rs @@ -8,8 +8,10 @@ //! it is reopened. //! //! A CVE a VEX statement settles (`not_affected` or `fixed`, by a person, the -//! scan or an imported VEX document) gets no issue, and its open issue is -//! closed with a comment naming the status and the reason. When the statement +//! scan or an imported VEX document) gets no issue. Its open issue is closed +//! with a comment naming the status and the reason when `ISSUE_AUTOCLOSE` is +//! `on` (at most [`AUTOCLOSE_PER_SCAN`] per target and scan), only counted +//! with `dry_run`, and left open with `off`, the default. When the statement //! is withdrawn, the issue is reopened (or opened) as for a CVE found again. //! //! What is known about a CVE's exploitation (#493) moves the threshold: a CVE @@ -21,8 +23,9 @@ use std::collections::{BTreeMap, HashMap}; use mongodb::bson::doc; +use compliance_core::config::IssueAutoclose; use compliance_core::models::notification::{parse_severity, NotificationSeverity}; -use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue, VexAssessment}; +use compliance_core::models::{CveAlert, IssueStatus, TrackerIssue, VexAssessment, VexStatus}; use crate::database::Database; use crate::error::AgentError; @@ -35,6 +38,8 @@ 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, + /// The tenant, for the log lines. + pub tenant_id: &'a str, pub tracker: &'a TrackerDispatch, pub owner: &'a str, pub repo: &'a str, @@ -45,6 +50,9 @@ pub(crate) struct CveIssueTarget<'a> { /// From this EPSS percentile (0 to 1) on a CVE is rated one step higher; /// `None` leaves EPSS out (see [`epss_percentile`]). pub epss_percentile: Option, + /// Whether open issues a VEX statement settles are closed + /// (`ISSUE_AUTOCLOSE`). + pub autoclose: IssueAutoclose, } /// The EPSS percentile from which a CVE is rated one step higher. @@ -198,18 +206,15 @@ pub(crate) async fn sync_cve_issues( } // A VEX statement settles the CVE whether or not the scan was complete. - for (key, alert) in present.iter().filter(|(_, a)| a.is_resolved_by_vex()) { - let (Some(vex), Some(issue)) = (alert.vex.as_ref(), existing.get(key)) else { - continue; - }; - if is_closed(&issue.status) { - continue; - } - if set_state(target, issue, &vex_comment(vex), "closed").await { - record(target.db, issue, IssueStatus::Closed).await?; - counts.closed += 1; - } - } + let settled: Vec<(&TrackerIssue, &VexAssessment)> = present + .iter() + .filter_map(|(key, alert)| { + let vex = alert.vex.as_ref().filter(|_| alert.is_resolved_by_vex())?; + let issue = existing.get(key).filter(|i| !is_closed(&i.status))?; + Some((issue, vex)) + }) + .collect(); + counts.closed += autoclose(target, &settled).await?; if complete { for (key, issue) in &existing { @@ -226,6 +231,72 @@ pub(crate) async fn sync_cve_issues( Ok(counts) } +/// Open issues closed per target and scan because a VEX statement settles +/// their CVE; the rest follow in the next scans. +const AUTOCLOSE_PER_SCAN: usize = 20; + +/// Close the open issues in `settled` (each with the VEX statement that +/// settles its CVE) as `ISSUE_AUTOCLOSE` says: not at all, only counted, or +/// at most [`AUTOCLOSE_PER_SCAN`] with a comment. Every Gitea request waits +/// for its instance's slot ([`crate::trackers::gitea_limit`]). Logs one line +/// per target with counts only. +/// +/// # Returns +/// +/// How many issues were closed. +/// +/// # Errors +/// +/// A database error. +async fn autoclose( + target: &CveIssueTarget<'_>, + settled: &[(&TrackerIssue, &VexAssessment)], +) -> Result { + if settled.is_empty() { + return Ok(0); + } + let tenant_id = target.tenant_id; + let target_id = target.target_id; + match target.autoclose { + IssueAutoclose::Off => Ok(0), + IssueAutoclose::DryRun => { + let not_affected = settled + .iter() + .filter(|(_, vex)| vex.status == VexStatus::NotAffected) + .count(); + tracing::info!( + tenant_id, + target_id, + would_close = settled.len(), + not_affected, + fixed = settled.len() - not_affected, + "CVE issues settled by VEX (dry run, nothing changed)" + ); + Ok(0) + } + IssueAutoclose::On => { + let (mut closed, mut failed) = (0u32, 0u32); + for (issue, vex) in settled.iter().take(AUTOCLOSE_PER_SCAN) { + if set_state(target, issue, &vex_comment(vex), "closed").await { + record(target.db, issue, IssueStatus::Closed).await?; + closed += 1; + } else { + failed += 1; + } + } + tracing::info!( + tenant_id, + target_id, + closed, + deferred = settled.len().saturating_sub(AUTOCLOSE_PER_SCAN), + failed, + "CVE issues settled by VEX closed" + ); + Ok(closed) + } + } +} + /// The comment an issue is closed with when a VEX statement settles its CVE: /// the status and the justification, or the reason in words. fn vex_comment(vex: &VexAssessment) -> String { @@ -457,22 +528,22 @@ mod tests { /// The calls a fake Gitea received. type Calls = Arc>>; - async fn fake_gitea(calls: Calls) -> String { - async fn labels( - axum::extract::Query(page): axum::extract::Query< - std::collections::HashMap, - >, - ) -> Json { - // One page of labels: a later page is empty, as Gitea ends a list. - if page.get("page").map(String::as_str) != Some("1") { - return Json(serde_json::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::>())) + /// The Prüfwerk labels, all present. + async fn labels( + axum::extract::Query(page): axum::extract::Query>, + ) -> Json { + // One page of labels: a later page is empty, as Gitea ends a list. + if page.get("page").map(String::as_str) != Some("1") { + return Json(serde_json::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 fake_gitea(calls: Calls) -> String { async fn create( State(calls): State, Json(body): Json, @@ -529,6 +600,27 @@ mod tests { format!("http://{addr}") } + /// A Gitea that lists its labels and refuses (and records) every other + /// call: a dry run must not write. + async fn read_only_gitea(calls: Calls) -> String { + async fn refuse( + State(calls): State, + method: axum::http::Method, + uri: axum::http::Uri, + ) -> axum::http::StatusCode { + calls.lock().unwrap().push(format!("{method} {uri}")); + axum::http::StatusCode::INTERNAL_SERVER_ERROR + } + let app = Router::new() + .route("/api/v1/repos/{o}/{r}/labels", get(labels)) + .fallback(refuse) + .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 exploited(kev: bool, percentile: Option) -> compliance_core::models::Exploitation { compliance_core::models::Exploitation { kev: kev.then(|| compliance_core::models::KevEntry { @@ -634,12 +726,14 @@ mod tests { let tracker = TrackerDispatch::Gitea(gitea); let target = CveIssueTarget { db: &db, + tenant_id: "cve-issues", tracker: &tracker, owner: "kunde", repo: "app", target_id: "target-1", dashboard: "https://pruefwerk.example", epss_percentile: Some(0.95), + autoclose: IssueAutoclose::Off, }; let okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH"); let minor = alert("gson", "2.8.8", "GHSA-4jrv-ppp4-jm57", "MODERATE"); @@ -731,8 +825,9 @@ mod tests { assert!(vex_comment(&vex(VexStatus::Fixed)).contains("VEX status `fixed`. Closed")); } - #[tokio::test] - async fn a_vex_not_affected_or_fixed_closes_the_issue_until_it_is_withdrawn() { + /// A tenant database for one test, or `None` (the test skips) without + /// MongoDB. + async fn test_db(tenant: &str) -> Option<(crate::database::DatabasePool, Database)> { let uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let prefix = format!( @@ -741,23 +836,51 @@ mod tests { ); let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else { eprintln!("SKIP cve_issues: no MongoDB reachable at {uri}"); - return; + return None; }; - let db = pool.for_tenant_id("cve-issues-vex").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, + let db = pool.for_tenant_id(tenant).await.unwrap(); + Some((pool, db)) + } + + fn tracker_at(base: String) -> TrackerDispatch { + TrackerDispatch::Gitea( + GiteaTracker::new(base, SecretString::from("t"), NetGuard::allow_private()).unwrap(), + ) + } + + fn vex_target<'a>( + db: &'a Database, + tracker: &'a TrackerDispatch, + autoclose: IssueAutoclose, + ) -> CveIssueTarget<'a> { + CveIssueTarget { + db, + tenant_id: "cve-issues-vex", + tracker, owner: "kunde", repo: "app", target_id: "target-1", dashboard: "", epss_percentile: None, + autoclose, + } + } + + fn closed(n: u32) -> CveIssueCounts { + CveIssueCounts { + closed: n, + ..Default::default() + } + } + + #[tokio::test] + async fn a_vex_not_affected_or_fixed_closes_the_issue_until_it_is_withdrawn() { + let Some((pool, db)) = test_db("cve-issues-vex").await else { + return; }; + let calls: Calls = Arc::default(); + let tracker = tracker_at(fake_gitea(calls.clone()).await); + let target = vex_target(&db, &tracker, IssueAutoclose::On); let mut okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH"); let mut settled = alert("log4j-core", "2.14.1", "GHSA-jfh8-c2jp-5v3q", "CRITICAL"); settled.aliases = vec!["CVE-2021-44228".into()]; @@ -782,10 +905,7 @@ mod tests { let both = [okhttp.clone(), settled.clone()]; assert_eq!( sync_cve_issues(&target, &both, false).await.unwrap(), - CveIssueCounts { - closed: 1, - ..Default::default() - } + closed(1) ); { let calls = calls.lock().unwrap(); @@ -822,4 +942,98 @@ mod tests { pool.drop_tenant("cve-issues-vex").await.ok(); } + + #[tokio::test] + async fn autoclose_off_and_dry_run_leave_the_issue_open() { + let Some((pool, db)) = test_db("cve-issues-vex-off").await else { + return; + }; + let calls: Calls = Arc::default(); + let tracker = tracker_at(fake_gitea(calls.clone()).await); + let mut okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH"); + let open = vex_target(&db, &tracker, IssueAutoclose::Off); + assert_eq!( + sync_cve_issues(&open, std::slice::from_ref(&okhttp), true) + .await + .unwrap() + .created, + 1 + ); + let before = calls.lock().unwrap().len(); + + // Off: the settled CVE's issue stays open, nothing is called. + okhttp.vex = Some(vex(VexStatus::Fixed)); + let found = std::slice::from_ref(&okhttp); + assert_eq!( + sync_cve_issues(&open, found, true).await.unwrap(), + CveIssueCounts::default() + ); + assert_eq!(calls.lock().unwrap().len(), before); + + // Dry run, against a Gitea that refuses every write: only counted. + let writes: Calls = Arc::default(); + let read_only = tracker_at(read_only_gitea(writes.clone()).await); + let dry = vex_target(&db, &read_only, IssueAutoclose::DryRun); + assert_eq!( + sync_cve_issues(&dry, found, true).await.unwrap(), + CveIssueCounts::default() + ); + assert!(writes.lock().unwrap().is_empty(), "{:?}", writes.lock()); + assert_eq!( + db.tracker_issues() + .count_documents(doc! { "status": "open" }) + .await + .unwrap(), + 1 + ); + + pool.drop_tenant("cve-issues-vex-off").await.ok(); + } + + #[tokio::test] + async fn autoclose_closes_at_most_twenty_per_scan() { + let Some((pool, db)) = test_db("cve-issues-vex-many").await else { + return; + }; + let calls: Calls = Arc::default(); + let tracker = tracker_at(fake_gitea(calls.clone()).await); + let target = vex_target(&db, &tracker, IssueAutoclose::On); + let mut alerts: Vec = (0..22) + .map(|i| { + let mut a = alert( + &format!("lib{i:02}"), + "1.0", + &format!("CVE-2026-{i:04}"), + "HIGH", + ); + a.aliases.clear(); + a + }) + .collect(); + assert_eq!( + sync_cve_issues(&target, &alerts, true) + .await + .unwrap() + .created, + 22 + ); + + for a in &mut alerts { + a.vex = Some(vex(VexStatus::NotAffected)); + } + assert_eq!( + sync_cve_issues(&target, &alerts, true).await.unwrap(), + closed(20) + ); + assert_eq!( + sync_cve_issues(&target, &alerts, true).await.unwrap(), + closed(2) + ); + assert_eq!( + sync_cve_issues(&target, &alerts, true).await.unwrap(), + CveIssueCounts::default() + ); + + pool.drop_tenant("cve-issues-vex-many").await.ok(); + } } diff --git a/compliance-agent/src/pipeline/issue_creation.rs b/compliance-agent/src/pipeline/issue_creation.rs index a535579..ed595ec 100644 --- a/compliance-agent/src/pipeline/issue_creation.rs +++ b/compliance-agent/src/pipeline/issue_creation.rs @@ -43,6 +43,7 @@ impl PipelineOrchestrator { let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default(); let target = crate::pipeline::cve_issues::CveIssueTarget { db: &self.db, + tenant_id: &self.tenant_id, tracker: &tracker, owner, repo: name, @@ -51,6 +52,7 @@ impl PipelineOrchestrator { epss_percentile: crate::pipeline::cve_issues::epss_percentile( std::env::var("CVE_ISSUE_EPSS_PERCENTILE").ok().as_deref(), ), + autoclose: self.config.issue_autoclose, }; let counts = crate::pipeline::cve_issues::sync_cve_issues(&target, alerts, complete).await?; diff --git a/compliance-core/src/config.rs b/compliance-core/src/config.rs index abd2258..811b08c 100644 --- a/compliance-core/src/config.rs +++ b/compliance-core/src/config.rs @@ -98,6 +98,52 @@ pub struct AgentConfig { /// Whether a scan files the missing Gitea issues of a target's older /// open findings (`ISSUE_CATCHUP`, default off). pub issue_catchup: IssueCatchup, + /// Whether a scan closes the open CVE issues a VEX statement settles + /// (`ISSUE_AUTOCLOSE`, default off). + pub issue_autoclose: IssueAutoclose, +} + +/// Closing open CVE issues whose CVE a VEX statement settles +/// (`ISSUE_AUTOCLOSE`): `not_affected` or `fixed`. Opening no new issue for +/// such a CVE does not depend on it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum IssueAutoclose { + /// Leave the open issues open. + #[default] + Off, + /// Count the issues it would close, per VEX status; change nothing. + DryRun, + /// Close them with a comment, a few per target and scan. + On, +} + +impl IssueAutoclose { + /// Parse `ISSUE_AUTOCLOSE`: `off`, `dry_run` or `on`, any case. Empty is + /// [`IssueAutoclose::Off`]. + /// + /// # Errors + /// + /// Any other value, with a message naming it (the caller falls back to + /// off). + pub fn parse(raw: &str) -> Result { + match raw.trim().to_ascii_lowercase().as_str() { + "" | "off" => Ok(Self::Off), + "dry_run" => Ok(Self::DryRun), + "on" => Ok(Self::On), + other => Err(format!( + "unknown ISSUE_AUTOCLOSE '{other}' (expected off, dry_run or on)" + )), + } + } + + /// The value as `ISSUE_AUTOCLOSE` spells it. + pub fn as_str(self) -> &'static str { + match self { + Self::Off => "off", + Self::DryRun => "dry_run", + Self::On => "on", + } + } } /// The issue catch-up (`ISSUE_CATCHUP`): after a scan's own issues, a Gitea @@ -321,6 +367,7 @@ impl Default for AgentConfig { features: Features::default(), app_env: AppEnv::Dev, issue_catchup: IssueCatchup::Off, + issue_autoclose: IssueAutoclose::Off, } } } @@ -357,6 +404,22 @@ mod app_env_tests { assert_eq!(IssueCatchup::DryRun.as_str(), "dry_run"); } + #[test] + fn issue_autoclose_is_off_unless_named() { + use super::IssueAutoclose; + assert_eq!(IssueAutoclose::parse("").unwrap(), IssueAutoclose::Off); + assert_eq!(IssueAutoclose::parse("OFF").unwrap(), IssueAutoclose::Off); + assert_eq!( + IssueAutoclose::parse(" dry_run ").unwrap(), + IssueAutoclose::DryRun + ); + assert_eq!(IssueAutoclose::parse("on").unwrap(), IssueAutoclose::On); + assert!(IssueAutoclose::parse("true").is_err()); + assert!(IssueAutoclose::parse("dry-run").is_err()); + assert_eq!(AgentConfig::default().issue_autoclose, IssueAutoclose::Off); + assert_eq!(IssueAutoclose::DryRun.as_str(), "dry_run"); + } + #[test] fn dev_needs_nothing() { assert!(AgentConfig::default().validate_deployment().is_ok()); diff --git a/docs/guide/issues.md b/docs/guide/issues.md index d3d8957..b97630c 100644 --- a/docs/guide/issues.md +++ b/docs/guide/issues.md @@ -19,7 +19,7 @@ A scan opens issues only for the findings it finds new, so a finding whose issue ### CVE issues (managed repositories) -For a repository from a managed git source, known vulnerabilities in its dependencies become issues too: one per package and CVE, labelled `cve`. A critical or high CVE opens one, and so does any CVE in CISA's Known Exploited Vulnerabilities catalog (rated at least high). A CVE whose EPSS percentile reaches `CVE_ISSUE_EPSS_PERCENTILE` (default `0.95`) is rated one step higher, so a medium one opens an issue as high. The issue names the KEV entry, the EPSS score with its attribution, and CISA's SSVC exploitation where known. When a complete scan no longer finds the CVE, the issue is closed; when it comes back, it is reopened. A CVE with the VEX status `not_affected` or `fixed` gets no issue, and its open issue is closed with a comment naming the status and the justification; when the statement is withdrawn, the issue is reopened. +For a repository from a managed git source, known vulnerabilities in its dependencies become issues too: one per package and CVE, labelled `cve`. A critical or high CVE opens one, and so does any CVE in CISA's Known Exploited Vulnerabilities catalog (rated at least high). A CVE whose EPSS percentile reaches `CVE_ISSUE_EPSS_PERCENTILE` (default `0.95`) is rated one step higher, so a medium one opens an issue as high. The issue names the KEV entry, the EPSS score with its attribution, and CISA's SSVC exploitation where known. When a complete scan no longer finds the CVE, the issue is closed; when it comes back, it is reopened. A CVE with the VEX status `not_affected` or `fixed` gets no new issue. Its issue that is already open is closed only with `ISSUE_AUTOCLOSE=on`: with a comment naming the status and the justification, at most 20 per target and scan (the rest follow in the next scans). `ISSUE_AUTOCLOSE=dry_run` only logs, per target, how many issues it would close per VEX status, and changes nothing; the default is `off`. When the statement is withdrawn, a closed issue is reopened. ## Issues List diff --git a/docs/guide/vex-en.md b/docs/guide/vex-en.md index 4711598..4fcdedb 100644 --- a/docs/guide/vex-en.md +++ b/docs/guide/vex-en.md @@ -50,8 +50,8 @@ the vulnerability comes back, the scan withdraws its "Fixed". A vulnerability that is "Not affected" or "Fixed" (stated by a person, by the scan or in an imported VEX document) raises no notification and gets no issue -in the repository's tracker; an open issue for it is closed with a comment -naming the status and the reason. If the statement is withdrawn, it notifies +in the repository's tracker; with `ISSUE_AUTOCLOSE=on` an open issue for +it is closed with a comment naming the status and the reason. If the statement is withdrawn, it notifies and its issue is reopened as before. Notifications raised before the statement stay in the list until they are dismissed. diff --git a/docs/guide/vex.md b/docs/guide/vex.md index 08b6d32..c54ec49 100644 --- a/docs/guide/vex.md +++ b/docs/guide/vex.md @@ -52,9 +52,9 @@ wieder auf, nimmt die Prüfung ihr „Behoben“ zurück. Eine Schwachstelle mit „Nicht betroffen“ oder „Behoben“ (von einer Person, der Prüfung oder aus einem importierten VEX-Dokument) löst keine -Benachrichtigung aus und bekommt kein Issue im Tracker des Repositorys; ein -offenes Issue dazu wird mit einem Kommentar geschlossen, der Status und -Begründung nennt. Wird die Aussage zurückgenommen, benachrichtigt sie wieder +Benachrichtigung aus und bekommt kein Issue im Tracker des Repositorys; mit +`ISSUE_AUTOCLOSE=on` wird ein offenes Issue dazu mit einem Kommentar +geschlossen, der Status und Begründung nennt. Wird die Aussage zurückgenommen, benachrichtigt sie wieder und ihr Issue wird wieder geöffnet. Benachrichtigungen von vor der Aussage bleiben in der Liste, bis sie verworfen werden. -- 2.54.1 From e0b9ebee75fc72d4cb8fa51fc7f41b9205ae27b6 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 9 Oct 2026 18:57:43 +0200 Subject: [PATCH 3/3] fix(cve): the ISSUE_AUTOCLOSE summary line is logged on every scan, also with nothing to close Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/pipeline/cve_issues.rs | 69 +++++++++++++++++++-- 1 file changed, 63 insertions(+), 6 deletions(-) diff --git a/compliance-agent/src/pipeline/cve_issues.rs b/compliance-agent/src/pipeline/cve_issues.rs index d0b8608..8ebdcd8 100644 --- a/compliance-agent/src/pipeline/cve_issues.rs +++ b/compliance-agent/src/pipeline/cve_issues.rs @@ -238,8 +238,9 @@ const AUTOCLOSE_PER_SCAN: usize = 20; /// Close the open issues in `settled` (each with the VEX statement that /// settles its CVE) as `ISSUE_AUTOCLOSE` says: not at all, only counted, or /// at most [`AUTOCLOSE_PER_SCAN`] with a comment. Every Gitea request waits -/// for its instance's slot ([`crate::trackers::gitea_limit`]). Logs one line -/// per target with counts only. +/// for its instance's slot ([`crate::trackers::gitea_limit`]). Unless off, +/// logs one line per target and scan with counts only, also when there is +/// nothing to close, so "ran, nothing to close" shows in the log. /// /// # Returns /// @@ -252,9 +253,6 @@ async fn autoclose( target: &CveIssueTarget<'_>, settled: &[(&TrackerIssue, &VexAssessment)], ) -> Result { - if settled.is_empty() { - return Ok(0); - } let tenant_id = target.tenant_id; let target_id = target.target_id; match target.autoclose { @@ -943,11 +941,46 @@ mod tests { pool.drop_tenant("cve-issues-vex").await.ok(); } + /// Log lines written while the returned guard lives (on this thread; a + /// `#[tokio::test]` runs on one). + fn capture_logs() -> (Arc>>, tracing::subscriber::DefaultGuard) { + let buffer: Arc>> = Arc::default(); + let writer = buffer.clone(); + let subscriber = tracing_subscriber::fmt() + .with_ansi(false) + .with_max_level(tracing::Level::INFO) + .with_writer(move || LogWriter(writer.clone())) + .finish(); + (buffer, tracing::subscriber::set_default(subscriber)) + } + + struct LogWriter(Arc>>); + + impl std::io::Write for LogWriter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + /// The autoclose summary lines logged into `logs`. + fn summaries(logs: &Mutex>) -> Vec { + String::from_utf8_lossy(&logs.lock().unwrap()) + .lines() + .filter(|l| l.contains("CVE issues settled by VEX")) + .map(str::to_owned) + .collect() + } + #[tokio::test] async fn autoclose_off_and_dry_run_leave_the_issue_open() { let Some((pool, db)) = test_db("cve-issues-vex-off").await else { return; }; + let (logs, _guard) = capture_logs(); let calls: Calls = Arc::default(); let tracker = tracker_at(fake_gitea(calls.clone()).await); let mut okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH"); @@ -969,8 +1002,11 @@ mod tests { CveIssueCounts::default() ); assert_eq!(calls.lock().unwrap().len(), before); + // Off logs no summary. + assert!(summaries(&logs).is_empty()); - // Dry run, against a Gitea that refuses every write: only counted. + // Dry run, against a Gitea that refuses every write: only counted, + // and a target with nothing to close says so too. let writes: Calls = Arc::default(); let read_only = tracker_at(read_only_gitea(writes.clone()).await); let dry = vex_target(&db, &read_only, IssueAutoclose::DryRun); @@ -979,6 +1015,27 @@ mod tests { CveIssueCounts::default() ); assert!(writes.lock().unwrap().is_empty(), "{:?}", writes.lock()); + let other = CveIssueTarget { + target_id: "target-2", + ..vex_target(&db, &read_only, IssueAutoclose::DryRun) + }; + sync_cve_issues(&other, &[], true).await.unwrap(); + let lines = summaries(&logs); + assert_eq!(lines.len(), 2, "{lines:?}"); + assert!( + lines[0].contains("tenant_id=\"cve-issues-vex\"") + && lines[0].contains("target_id=\"target-1\"") + && lines[0].contains("would_close=1 not_affected=0 fixed=1"), + "{}", + lines[0] + ); + assert!( + lines[1].contains("target_id=\"target-2\"") && lines[1].contains("would_close=0"), + "{}", + lines[1] + ); + // No title or path in the line. + assert!(!lines[0].contains("okhttp"), "{}", lines[0]); assert_eq!( db.tracker_issues() .count_documents(doc! { "status": "open" }) -- 2.54.1