fix(vex): keep the alert's purl for components that left the SBOM (#532)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Agent (push) Canceled after 0s
CI / Deploy Dashboard (push) Canceled after 0s
CI / Deploy Docs (push) Successful in 1m17s
CI / Deploy MCP (push) Successful in 2m38s

This commit was merged in pull request #532.
This commit is contained in:
sharang committed 2026-10-08 21:45:37 +00:00
1 parent a22b4497a5
commit 1f02a89226
11 files changed
+148 -19

No files matched your search

@@ -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);
}
+25 -12
View File
@@ -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<String> = lookup.alerts.iter().map(|a| a.cve_id.clone()).collect();
let details = self.osv_details(ids).await;
let purls: HashMap<(String, String), Option<String>> = 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 {
@@ -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(),
+13 -1
View File
@@ -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
+18 -1
View File
@@ -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();
}
+7
View File
@@ -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<String>,
pub source: CveSource,
pub severity: Option<String>,
pub cvss_score: Option<f64>,
@@ -159,6 +165,7 @@ impl CveAlert {
repo_id,
affected_package,
affected_version,
purl: None,
source,
severity: None,
cvss_score: None,
+7 -2
View File
@@ -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);
+43
View File
@@ -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::<String>::new());
assert_eq!(cyclonedx_errors(&cdx), Vec::<String>::new());
assert_eq!(csaf_errors(&csaf), Vec::<String>::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
);
}
}
+5 -1
View File
@@ -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/<name>@<version>`. CycloneDX names the statuses
differently:
| OpenVEX | CycloneDX `analysis.state` / `justification` |
+2 -1
View File
@@ -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";
+2 -1
View File
@@ -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“;