fix(vex): alerts stored before purls get their component's purl #537

Merged
sharang merged 1 commits from fix/a4-purl-migration into main 2026-10-08 22:55:23 +00:00
4 changed files with 183 additions and 4 deletions

No files matched your search

+9 -1
View File
@@ -1,5 +1,6 @@
use compliance_agent::{
agent, api, config, database, finding_migrations, lifecycle, scheduler, secrets, webhooks,
agent, api, config, database, finding_migrations, lifecycle, pipeline, scheduler, secrets,
webhooks,
};
use compliance_core::shutdown;
@@ -43,6 +44,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
),
Err(e) => tracing::error!("migrating stored findings failed: {e}"),
}
// Open CVE alerts stored before purls were recorded (#532) get their
// component's purl, before a scan can resolve them.
match pipeline::vex_lifecycle::backfill_purls_everywhere(&agent.db_pool).await {
Ok(0) => {}
Ok(alerts) => tracing::info!(alerts, "CVE alerts got their component's purl"),
Err(e) => tracing::error!("backfilling CVE alert purls failed: {e}"),
}
// Before anything can start a new run, close the runs the previous agent
// process left open when it stopped.
@@ -1072,6 +1072,13 @@ impl PipelineOrchestrator {
trigger: &ScanTrigger,
) -> Result<u32, AgentError> {
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
// Alerts stored before purls were recorded get theirs while the
// stored SBOM still lists the component this scan may remove (#532).
if let Err(e) =
crate::pipeline::vex_lifecycle::backfill_purls(&self.db, Some(&target_id)).await
{
tracing::warn!(target_id = %target_id, error = %e, "CVE alert purls not backfilled");
}
// Uploaded files the last completed scan already read, with the same
// Prüfwerk build: a scheduled scan has nothing new to find (#465).
let has_git = target
+83 -1
View File
@@ -8,14 +8,96 @@
//! person's `not_affected` or `fixed` is never changed by a scan. The first
//! scan that finds it actively exploited records when (`exploited_seen_at`),
//! the start of the CRA's reporting deadlines.
//!
//! An alert keeps the purl of its component (#532), so a VEX export still
//! names it once the component has left the SBOM. Alerts stored before that
//! get it from the stored SBOM ([`backfill_purls`]) at agent start and before
//! every scan of their target, while the component is still listed.
use futures_util::TryStreamExt;
use mongodb::bson::doc;
use compliance_core::models::{CveAlert, StatusChange, VexAssessment, VexStatus};
use crate::database::Database;
use crate::database::{Database, DatabasePool};
use crate::error::AgentError;
/// Give the open alerts that have no purl the purl of their component in the
/// stored SBOM (same name, case aside, and version, as the VEX exports match
/// it), before a scan replaces that SBOM. Only `repo_id`'s alerts, or every
/// target's with `None`.
///
/// # Returns
///
/// How many alerts got a purl.
///
/// # Errors
///
/// A database error.
pub async fn backfill_purls(db: &Database, repo_id: Option<&str>) -> Result<u64, AgentError> {
let mut filter = doc! {
"resolved_at": { "$exists": false },
"purl": { "$exists": false },
};
if let Some(repo_id) = repo_id {
filter.insert("repo_id", repo_id);
}
let alerts: Vec<CveAlert> = db.cve_alerts().find(filter).await?.try_collect().await?;
let mut set = 0;
for alert in alerts {
let Some(id) = alert.id else {
continue;
};
let component = db
.sbom_entries()
.find_one(doc! {
"repo_id": &alert.repo_id,
"name": {
"$regex": format!("^{}$", regex::escape(&alert.affected_package)),
"$options": "i",
},
"version": &alert.affected_version,
"purl": { "$type": "string", "$ne": "" },
})
.await?;
let Some(purl) = component.and_then(|entry| entry.purl) else {
continue;
};
db.cve_alerts()
.update_one(
doc! { "_id": id, "purl": { "$exists": false } },
doc! { "$set": { "purl": purl } },
)
.await?;
set += 1;
}
Ok(set)
}
/// [`backfill_purls`] for every target of every tenant, at agent start. A
/// tenant that fails is logged and skipped.
///
/// # Returns
///
/// How many alerts got a purl.
///
/// # Errors
///
/// Listing the tenant databases failed.
pub async fn backfill_purls_everywhere(pool: &DatabasePool) -> Result<u64, AgentError> {
let mut total = 0;
for db in pool.existing_tenant_dbs().await? {
match backfill_purls(&db, None).await {
Ok(n) => total += n,
Err(e) => tracing::error!(
database = db.inner().name(),
"giving CVE alerts their component's purl failed: {e}"
),
}
}
Ok(total)
}
/// Store `alert` as reported by this scan.
///
/// # Errors
+84 -2
View File
@@ -8,8 +8,11 @@
#![allow(clippy::expect_used, clippy::unwrap_used)]
use compliance_agent::database::{Database, DatabasePool};
use compliance_agent::pipeline::vex_lifecycle::{resolve_gone, upsert_reported};
use compliance_core::models::{CveAlert, CveSource, VexAssessment, VexJustification, VexStatus};
use compliance_agent::pipeline::vex_lifecycle::{backfill_purls, resolve_gone, upsert_reported};
use compliance_core::models::{
CveAlert, CveSource, SbomEntry, VexAssessment, VexJustification, VexStatus,
};
use compliance_core::{csaf_docs, vex_docs};
use mongodb::bson::doc;
const TARGET: &str = "target-1";
@@ -158,3 +161,82 @@ async fn vex_status_follows_the_scans_but_never_overrides_a_person() {
pool.drop_tenant(tenant).await.ok();
}
/// #532: an alert stored before purls were recorded gets its component's
/// purl from the stored SBOM before a scan removes the component, so once
/// resolved it still names the real package in every VEX export.
#[tokio::test]
async fn an_alert_from_before_keeps_its_purl_after_the_component_is_gone() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"vexpurl_{}",
&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-purl";
let Ok(db) = pool.for_tenant_id(tenant).await else {
eprintln!("SKIP vex_lifecycle: MongoDB at {uri} not usable");
return;
};
let purl = "pkg:maven/com.google.code.gson/gson@2.8.8";
// Arrange: an open alert stored without a purl, its component in the
// stored SBOM (name in another case), and one already resolved.
let gson = CveAlert::new(
"GHSA-4jrv-ppp4-jm57".into(),
TARGET.into(),
"gson".into(),
"2.8.8".into(),
CveSource::Osv,
);
upsert_reported(&db, &gson).await.unwrap();
upsert_reported(&db, &alert("CVE-OLD")).await.unwrap();
resolve_gone(&db, TARGET, std::slice::from_ref(&gson), true)
.await
.unwrap();
let mut entry = SbomEntry::new(TARGET.into(), "Gson".into(), "2.8.8".into(), "maven".into());
entry.purl = Some(purl.into());
db.sbom_entries().insert_one(&entry).await.unwrap();
assert_eq!(stored(&db, "GHSA-4jrv-ppp4-jm57").await.purl, None);
// Act: the backfill before the next scan, then that scan: gson updated,
// its old version gone from the SBOM and the alert resolved.
assert_eq!(backfill_purls(&db, Some(TARGET)).await.unwrap(), 1);
assert_eq!(backfill_purls(&db, Some(TARGET)).await.unwrap(), 0, "once");
db.sbom_entries()
.delete_many(doc! { "repo_id": TARGET })
.await
.unwrap();
resolve_gone(&db, TARGET, &[], true).await.unwrap();
// Assert: resolved, with the purl, and every export names it.
let resolved = stored(&db, "GHSA-4jrv-ppp4-jm57").await;
assert!(resolved.resolved_at.is_some());
assert_eq!(resolved.purl.as_deref(), Some(purl));
assert_eq!(stored(&db, "CVE-OLD").await.purl, None, "already resolved");
let alerts = [resolved];
let input = vex_docs::VexInput {
subject: "app",
author: "ws",
tooling: "Prüfwerk test",
alerts: &alerts,
sbom: &[],
now: chrono::Utc::now(),
};
for doc in [
vex_docs::openvex(&input),
vex_docs::cyclonedx_vex(&input),
csaf_docs::csaf_vex(&input, "https://example.invalid/ws", "de"),
] {
let text = doc.to_string();
assert!(text.contains(purl), "{text}");
// The product itself (the target) is a generic purl; the component is not.
assert!(!text.contains("pkg:generic/gson"), "{text}");
}
pool.drop_tenant(tenant).await.ok();
}