From 3a07768024e5c49a8d71faed871e840e1716571b Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 8 Oct 2026 23:21:51 +0200 Subject: [PATCH] fix(vex): keep the alert's purl for components that left the SBOM A resolved CVE alert (its component updated past the fix) was exported as pkg:generic/@ in OpenVEX, CycloneDX VEX, the CSAF VEX draft and the evidence pack, because the exporters looked the purl up in the current SBOM. CveAlert now stores the purl of its component (OSV, NVD/CPE incl. CODESYS and embedded, CSAF matching), a rescan backfills it on stored alerts (scan upsert and the hourly CVE monitor), and the exporters use it before the SBOM lookup and the generic fallback. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/pipeline/csaf_match.rs | 10 +++++ compliance-agent/src/pipeline/cve.rs | 37 ++++++++++------ .../src/pipeline/vex_lifecycle.rs | 16 +++++++ compliance-agent/src/scheduler.rs | 14 +++++- compliance-agent/tests/vex_lifecycle.rs | 19 +++++++- compliance-core/src/models/cve.rs | 7 +++ compliance-core/src/vex_docs.rs | 9 +++- compliance-core/tests/vex_schemas.rs | 43 +++++++++++++++++++ docs/guide/sbom.md | 6 ++- docs/guide/vex-en.md | 3 +- docs/guide/vex.md | 3 +- 11 files changed, 148 insertions(+), 19 deletions(-) diff --git a/compliance-agent/src/pipeline/csaf_match.rs b/compliance-agent/src/pipeline/csaf_match.rs index cede0ca..cec139a 100644 --- a/compliance-agent/src/pipeline/csaf_match.rs +++ b/compliance-agent/src/pipeline/csaf_match.rs @@ -205,6 +205,7 @@ pub(crate) fn apply( entry.version.clone(), CveSource::Csaf, ); + alert.purl.clone_from(&entry.purl); alert.summary = hit .vulnerability .summary @@ -216,6 +217,12 @@ pub(crate) fn apply( &mut alerts[last] } }; + if alert.purl.is_none() + && alert.affected_package == entry.name + && alert.affected_version == entry.version + { + alert.purl.clone_from(&entry.purl); + } if alert.severity.is_none() { alert.severity.clone_from(&hit.vulnerability.severity); } @@ -299,6 +306,7 @@ mod tests { assert_eq!(alert.cve_id, "CVE-2026-90001"); assert_eq!(alert.source, CveSource::Csaf); assert_eq!(alert.affected_version, "3.5.16.0"); + assert_eq!(alert.purl, entries[0].purl); assert_eq!(alert.fixed_versions, ["3.5.22.40"]); assert_eq!(alert.severity.as_deref(), Some("HIGH")); let adv = &alert.advisories[0]; @@ -341,6 +349,8 @@ mod tests { assert_eq!(alerts[0].summary.as_deref(), Some("NVD's text")); assert_eq!(alerts[0].advisories.len(), 1); assert_eq!(alerts[0].fixed_versions, ["3.5.22.40"]); + // The NVD alert had no purl; the advisory's component gives it one. + assert_eq!(alerts[0].purl, entries[0].purl); assert_eq!(entries[0].known_vulnerabilities.len(), 1); } diff --git a/compliance-agent/src/pipeline/cve.rs b/compliance-agent/src/pipeline/cve.rs index 04765c6..c66bb9d 100644 --- a/compliance-agent/src/pipeline/cve.rs +++ b/compliance-agent/src/pipeline/cve.rs @@ -87,6 +87,7 @@ impl CveScanner { entry.version.clone(), CveSource::Osv, ); + alert.purl.clone_from(&entry.purl); alert.summary = vuln.summary; lookup.alerts.push(alert); } @@ -102,25 +103,14 @@ impl CveScanner { // its summary, severity, CVE alias and fixed versions. let ids: BTreeSet = lookup.alerts.iter().map(|a| a.cve_id.clone()).collect(); let details = self.osv_details(ids).await; - let purls: HashMap<(String, String), Option> = entries - .iter() - .map(|e| ((e.name.clone(), e.version.clone()), e.purl.clone())) - .collect(); for alert in &mut lookup.alerts { let Some(detail) = details.get(&alert.cve_id) else { continue; }; - let purl = purls - .get(&( - alert.affected_package.clone(), - alert.affected_version.clone(), - )) - .cloned() - .flatten(); alert.summary = detail.summary.clone().or(alert.summary.take()); alert.severity = detail.severity.clone(); alert.aliases = detail.aliases.clone(); - alert.fixed_versions = detail.fixed_for(purl.as_deref(), &alert.affected_package); + alert.fixed_versions = detail.fixed_for(alert.purl.as_deref(), &alert.affected_package); } for entry in entries.iter_mut() { for vuln in &mut entry.known_vulnerabilities { @@ -381,6 +371,7 @@ fn record_nvd( let mut entry = entries .iter_mut() .find(|e| e.name == name && e.version == version); + let purl = entry.as_ref().and_then(|e| e.purl.clone()); cves.into_iter() .map(|cve| { if let Some(e) = entry.as_deref_mut() { @@ -399,6 +390,7 @@ fn record_nvd( version.to_string(), CveSource::Nvd, ); + alert.purl.clone_from(&purl); alert.summary = cve.summary; alert.cvss_score = cve.cvss; alert @@ -602,6 +594,27 @@ mod tests { assert_eq!(hits.load(Ordering::SeqCst), 1); assert_eq!(lookup.alerts.len(), 1); assert_eq!(lookup.alerts[0].summary.as_deref(), Some("test")); + assert_eq!( + lookup.alerts[0].purl.as_deref(), + Some("pkg:npm/left-pad@1.0.0") + ); + } + + #[test] + fn an_nvd_alert_keeps_the_purl_of_its_component() { + let mut entries = vec![ + with_purl("lwIP", "pkg:generic/lwip@1.0.0"), + entry("FreeRTOS", "1.0.0", "embedded"), + ]; + let cve = |id: &str| NvdCve { + id: id.into(), + summary: None, + cvss: None, + }; + let with = record_nvd("t", &mut entries, "lwIP", "1.0.0", vec![cve("CVE-1")]); + let without = record_nvd("t", &mut entries, "FreeRTOS", "1.0.0", vec![cve("CVE-2")]); + assert_eq!(with[0].purl.as_deref(), Some("pkg:generic/lwip@1.0.0")); + assert_eq!(without[0].purl, None); } fn entry(name: &str, ver: &str, pm: &str) -> SbomEntry { diff --git a/compliance-agent/src/pipeline/vex_lifecycle.rs b/compliance-agent/src/pipeline/vex_lifecycle.rs index 0c4f5ee..d296779 100644 --- a/compliance-agent/src/pipeline/vex_lifecycle.rs +++ b/compliance-agent/src/pipeline/vex_lifecycle.rs @@ -27,6 +27,22 @@ pub async fn upsert_reported(db: &Database, alert: &CveAlert) -> Result<(), Agen // alert carries none), and it is reported again. let found = mongodb::bson::to_document(alert) .map_err(|e| AgentError::Other(format!("encode CVE alert: {e}")))?; + // A purl is written when the scan knows one and otherwise kept (an alert + // stored before purls were recorded gets one on its next scan); kept only + // while it is the purl of the same package and version. + if alert.purl.is_none() { + let mut other_component = filter.clone(); + other_component.insert( + "$or", + mongodb::bson::bson!([ + { "affected_package": { "$ne": &alert.affected_package } }, + { "affected_version": { "$ne": &alert.affected_version } }, + ]), + ); + db.cve_alerts() + .update_one(other_component, doc! { "$unset": { "purl": "" } }) + .await?; + } db.cve_alerts() .update_one( filter.clone(), diff --git a/compliance-agent/src/scheduler.rs b/compliance-agent/src/scheduler.rs index 27cedf8..a6f66cb 100644 --- a/compliance-agent/src/scheduler.rs +++ b/compliance-agent/src/scheduler.rs @@ -346,9 +346,21 @@ async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) { } let _ = db .cve_alerts() - .update_one(filter, update) + .update_one(filter.clone(), update) .upsert(true) .await; + // An alert stored before purls were recorded gets its + // component's purl (only for the same package and version). + if let Some(purl) = &alert.purl { + let mut without_purl = filter; + without_purl.insert("affected_package", &alert.affected_package); + without_purl.insert("affected_version", &alert.affected_version); + without_purl.insert("purl", doc! { "$exists": false }); + let _ = db + .cve_alerts() + .update_one(without_purl, doc! { "$set": { "purl": purl } }) + .await; + } } // Update SBOM entries with discovered vulnerabilities diff --git a/compliance-agent/tests/vex_lifecycle.rs b/compliance-agent/tests/vex_lifecycle.rs index 35c7294..9811388 100644 --- a/compliance-agent/tests/vex_lifecycle.rs +++ b/compliance-agent/tests/vex_lifecycle.rs @@ -1,7 +1,8 @@ //! #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. Runs against a live Mongo (`TEST_MONGODB_URI`) and skips +//! withdrawn. A stored alert gets its component's purl on a later scan. +//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips //! cleanly without one. #![allow(clippy::expect_used, clippy::unwrap_used)] @@ -139,5 +140,21 @@ async fn vex_status_follows_the_scans_but_never_overrides_a_person() { upsert_reported(&db, &exploited).await.unwrap(); assert_eq!(stored(&db, "CVE-5").await.exploited_seen_at, Some(first)); + // An alert stored without a purl gets its component's on the next scan; + // a scan that knows none keeps it, unless the alert is now about another + // component. + let maven = "pkg:maven/org.example/lib@1.0"; + let mut with_purl = alert("CVE-1"); + with_purl.purl = Some(maven.into()); + assert_eq!(stored(&db, "CVE-1").await.purl, None); + upsert_reported(&db, &with_purl).await.unwrap(); + assert_eq!(stored(&db, "CVE-1").await.purl.as_deref(), Some(maven)); + upsert_reported(&db, &alert("CVE-1")).await.unwrap(); + assert_eq!(stored(&db, "CVE-1").await.purl.as_deref(), Some(maven)); + let mut other = alert("CVE-1"); + other.affected_version = "2.0".into(); + upsert_reported(&db, &other).await.unwrap(); + assert_eq!(stored(&db, "CVE-1").await.purl, None); + pool.drop_tenant(tenant).await.ok(); } diff --git a/compliance-core/src/models/cve.rs b/compliance-core/src/models/cve.rs index 6370c67..a544e70 100644 --- a/compliance-core/src/models/cve.rs +++ b/compliance-core/src/models/cve.rs @@ -89,6 +89,12 @@ pub struct CveAlert { pub repo_id: String, pub affected_package: String, pub affected_version: String, + /// The purl of the SBOM component the alert is about, kept so that the + /// VEX exports still name it once the component has left the SBOM (a + /// `fixed` statement after an update); `None` for a component without a + /// purl and for alerts stored before it was recorded. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub purl: Option, pub source: CveSource, pub severity: Option, pub cvss_score: Option, @@ -159,6 +165,7 @@ impl CveAlert { repo_id, affected_package, affected_version, + purl: None, source, severity: None, cvss_score: None, diff --git a/compliance-core/src/vex_docs.rs b/compliance-core/src/vex_docs.rs index e26b111..b1ac6bf 100644 --- a/compliance-core/src/vex_docs.rs +++ b/compliance-core/src/vex_docs.rs @@ -51,9 +51,14 @@ fn entry_of<'a>(alert: &CveAlert, sbom: &'a [SbomEntry]) -> Option<&'a SbomEntry }) } -/// The identifier of the component an alert is about: the SBOM's `bom-ref` -/// (its purl), or a generic purl of the package and version. +/// The identifier of the component an alert is about: the purl stored on +/// the alert, else the SBOM's `bom-ref` (its purl), else a generic purl of +/// the package and version. The stored purl comes first because a fixed +/// alert's component has usually left the SBOM. pub(crate) fn component_id(alert: &CveAlert, sbom: &[SbomEntry]) -> String { + if let Some(purl) = &alert.purl { + return purl.clone(); + } entry_of(alert, sbom).map_or_else( || { let mut name = product_ref(&alert.affected_package); diff --git a/compliance-core/tests/vex_schemas.rs b/compliance-core/tests/vex_schemas.rs index 06efecc..440851e 100644 --- a/compliance-core/tests/vex_schemas.rs +++ b/compliance-core/tests/vex_schemas.rs @@ -418,3 +418,46 @@ fn the_csaf_advisory_passes_the_csaf_validators() { std::fs::remove_dir_all(&dir).ok(); assert!(ran, "set CSAF_VALIDATOR and/or CSAF_VALIDATOR_LIB"); } + +#[test] +fn a_fixed_component_that_left_the_sbom_keeps_its_stored_purl() { + // Arrange: log4j-core was updated to 2.17.1, so the SBOM no longer has + // 2.14.1; its alert kept the purl. An alert stored before purls were + // recorded has none. + let mut sbom = sbom(); + sbom[0].version = "2.17.1".into(); + sbom[0].purl = Some("pkg:maven/org.apache.logging.log4j/log4j-core@2.17.1".into()); + let maven = "pkg:maven/org.apache.logging.log4j/log4j-core@2.14.1"; + let mut log4j = alert("CVE-2021-44228", "log4j-core", "2.14.1"); + log4j.purl = Some(maven.into()); + log4j.resolved_at = Some(Utc::now()); + let mut old = alert("CVE-2020-0001", "zlib", "1.2.11"); + old.resolved_at = Some(Utc::now()); + let alerts = vec![log4j, old]; + let input = vex_input(&alerts, &sbom); + + // Act + let openvex = vex_docs::openvex(&input); + let cdx = vex_docs::cyclonedx_vex(&input); + let csaf = csaf_docs::csaf_vex(&input, "https://example.invalid/pumps", "en"); + + // Assert: the stored purl, else the generic fallback, in every format. + assert_eq!(openvex_errors(&openvex), Vec::::new()); + assert_eq!(cyclonedx_errors(&cdx), Vec::::new()); + assert_eq!(csaf_errors(&csaf), Vec::::new()); + let generic = "pkg:generic/zlib@1.2.11"; + for (i, purl) in [maven, generic].into_iter().enumerate() { + let statement = &openvex["statements"][i]; + assert_eq!(statement["status"], "fixed"); + let sub = &statement["products"][0]["subcomponents"][0]; + assert_eq!(sub["@id"], purl); + assert_eq!(sub["identifiers"]["purl"], purl); + assert_eq!(cdx["vulnerabilities"][i]["affects"][0]["ref"], purl); + // The product tree's first entry is the target itself. + assert_eq!( + csaf["product_tree"]["full_product_names"][i + 1]["product_identification_helper"] + ["purl"], + purl + ); + } +} diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index 47a9946..2d0fb81 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -262,7 +262,11 @@ vulnerability comes back, the scan's `fixed` is withdrawn. The statements are exported per target as **OpenVEX 0.2.0** and as **CycloneDX 1.6 VEX** (the SBOM with each vulnerability's analysis), both checked against their official schemas, and are part of the evidence pack -(`vex.openvex.json`, `vex.cdx.json`). CycloneDX names the statuses +(`vex.openvex.json`, `vex.cdx.json`). Each statement names the component by +the purl it had when the alert was found, so a `fixed` statement still +matches the SBOM version that contained the component after it was updated +or removed. Alerts resolved before Prüfwerk recorded that purl name it +`pkg:generic/@`. CycloneDX names the statuses differently: | OpenVEX | CycloneDX `analysis.state` / `justification` | diff --git a/docs/guide/vex-en.md b/docs/guide/vex-en.md index 5284907..fefe9fc 100644 --- a/docs/guide/vex-en.md +++ b/docs/guide/vex-en.md @@ -62,7 +62,8 @@ and the API: see [SBOM](./sbom.md#vex-the-status-of-each-vulnerability). The draft - names the target as the product and each affected component as part of it - (with its purl); + (with its purl; a fixed component no longer in the SBOM with the purl it + had when the alert was found); - carries every statement: "Affected" with your action statement as the remediation, "Not affected" with its justification and statement, "Under investigation" and "Fixed"; diff --git a/docs/guide/vex.md b/docs/guide/vex.md index 57c8a63..3c2b2a3 100644 --- a/docs/guide/vex.md +++ b/docs/guide/vex.md @@ -65,7 +65,8 @@ VEX-Advisory (`csaf_vex`), dem Format, in dem Hersteller und CERTs Schwachstellen veröffentlichen. Der Entwurf - nennt das Prüfobjekt als Produkt und jede betroffene Komponente als Teil - davon (mit purl); + davon (mit purl; eine behobene Komponente, die nicht mehr in der SBOM + steht, mit der purl, die sie beim Fund hatte); - übernimmt jede Aussage: „Betroffen“ mit Ihrer Handlungsanweisung als Abhilfe, „Nicht betroffen“ mit Begründung und Freitext, „In Prüfung“ und „Behoben“;