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] 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