diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index 50e9450..0486ea6 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -31,6 +31,7 @@ pub mod sbom; pub mod sbom_ecosystems; pub mod scan_changes; pub mod scans; +pub mod supplier; pub mod support; pub mod target_input; pub mod vex; diff --git a/compliance-agent/src/api/handlers/supplier.rs b/compliance-agent/src/api/handlers/supplier.rs new file mode 100644 index 0000000..e5fcad3 --- /dev/null +++ b/compliance-agent/src/api/handlers/supplier.rs @@ -0,0 +1,90 @@ +//! What Prüfwerk knows of a bought-in component's supplier (#1025): how many +//! of its CSAF advisories are kept for the workspace, and when its provider +//! was last read. + +use axum::extract::{Extension, Path}; +use axum::http::StatusCode; +use axum::Json; +use mongodb::bson::{doc, oid::ObjectId}; +use serde::Serialize; + +use compliance_core::tenant_ctx::TenantCtx; + +use super::dto::{tenant_db, AgentExt}; +use super::ApiResponse; +use crate::pipeline::csaf_feed::{supplier_key, MongoAdvisoryStore, SupplierProviderStatus}; + +/// The advisories of a target's supplier, as the target editor shows them. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct SupplierAdvisories { + /// The supplier's advisories kept for the workspace. + pub advisories: u64, + /// When its provider was last read; none before the first refresh. + pub checked_at: Option>, + /// Whether its metadata and feeds could be read then; none before the + /// first refresh. + pub reachable: Option, +} + +/// Count the target's supplier advisories, with their provider's last read. +/// +/// `data` holds `advisories`, `checked_at` and `reachable` (both null before +/// the first refresh), or is null when the target names no supplier CSAF +/// provider. The +/// advisories are the workspace's own: a provider is read for the workspaces +/// that name it, daily and right after it is set. +#[utoipa::path( + get, + path = "/api/v1/targets/{id}/supplier-advisories", + tag = "Targets", + params(("id" = String, Path, description = "The target's id")), + responses( + (status = 200, description = "The supplier's advisories, or null without a provider"), + (status = 400, description = "Not an id"), + (status = 404, description = "No such target"), + (status = 401, description = "No valid bearer token"), + ) +)] +#[tracing::instrument(skip_all, fields(target_id = %id))] +pub async fn get_supplier_advisories( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, +) -> Result>>, StatusCode> { + let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?; + let db = tenant_db(&agent, &tenant).await?; + let target = db + .onboarded_targets() + .find_one(doc! { "_id": oid }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + let Some(url) = target.supplier.and_then(|s| s.csaf_provider) else { + return Ok(Json(ApiResponse { + data: None, + total: None, + page: None, + })); + }; + let key = supplier_key(&url); + let advisories = MongoAdvisoryStore::supplier(db.inner()) + .collection() + .count_documents(doc! { "provider": &key }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let status = db + .inner() + .collection::(SupplierProviderStatus::COLLECTION) + .find_one(doc! { "_id": &key }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(ApiResponse { + data: Some(SupplierAdvisories { + advisories, + checked_at: status.as_ref().map(|s| s.checked_at.to_chrono()), + reachable: status.map(|s| s.reachable), + }), + total: None, + page: None, + })) +} diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index fdb99a7..48f1176 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -87,6 +87,7 @@ fn described_routes() -> OpenApiRouter { crate::pipeline::sbom::supplied::MAX_BYTES as usize + MULTIPART_OVERHEAD, )), ) + .routes(routes!(handlers::supplier::get_supplier_advisories)) .routes(routes!(handlers::onboarding::set_archive_password)) .routes(routes!(handlers::onboarding::applicable_scans_for_target)) .routes(routes!(handlers::onboarding::detect_target)) diff --git a/compliance-agent/src/pipeline/csaf_feed.rs b/compliance-agent/src/pipeline/csaf_feed.rs index f22cf79..cb47adc 100644 --- a/compliance-agent/src/pipeline/csaf_feed.rs +++ b/compliance-agent/src/pipeline/csaf_feed.rs @@ -106,6 +106,26 @@ impl Provider { } } +/// When a supplier's provider was last read, and whether it could be +/// (#1025): kept per tenant in [`SupplierProviderStatus::COLLECTION`], so the +/// target editor can tell a provider without advisories from one never or no +/// longer read. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub(crate) struct SupplierProviderStatus { + /// The provider's key ([`supplier_key`]). + #[serde(rename = "_id")] + pub provider: String, + /// When the last refresh read it. + pub checked_at: mongodb::bson::DateTime, + /// Whether its metadata and feeds could be read then. + pub reachable: bool, +} + +impl SupplierProviderStatus { + /// The collection, in the tenant's own database. + pub(crate) const COLLECTION: &'static str = "supplier_csaf_providers"; +} + /// The prefix of a supplier provider's key, which tells its advisories from /// the shared providers' ([`Provider::supplier`]). pub(crate) const SUPPLIER_PREFIX: &str = "supplier:"; @@ -349,6 +369,8 @@ pub(crate) struct Counts { pub failed: usize, /// Left for a later run (over the limits). pub deferred: usize, + /// The provider's metadata or feeds could not be read at all. + pub unreachable: bool, } /// One advisory a feed lists. @@ -489,6 +511,7 @@ pub(crate) async fn refresh( Err(e) => { tracing::warn!(provider = %provider.name, "CSAF provider not read: {e}"); counts.failed = 1; + counts.unreachable = true; out.insert(provider.name.clone(), counts); continue; } @@ -663,6 +686,24 @@ pub(crate) async fn refresh_supplier_advisories( }; let store = MongoAdvisoryStore::supplier(db.inner()); let counts = refresh(&fetch, &store, &providers, supplier_limits()).await; + let statuses = db + .inner() + .collection::(SupplierProviderStatus::COLLECTION); + let checked_at = mongodb::bson::DateTime::now(); + for (provider, c) in &counts { + let status = SupplierProviderStatus { + provider: provider.clone(), + checked_at, + reachable: !c.unreachable, + }; + if let Err(e) = statuses + .replace_one(doc! { "_id": provider }, &status) + .upsert(true) + .await + { + tracing::warn!(tenant_id, provider, "supplier CSAF status not kept: {e}"); + } + } let stored: usize = counts.values().map(|c| c.stored).sum(); let failed: usize = counts.values().map(|c| c.failed).sum(); tracing::info!( diff --git a/compliance-agent/tests/integration/api/onboarding.rs b/compliance-agent/tests/integration/api/onboarding.rs index 822b944..c76c7ea 100644 --- a/compliance-agent/tests/integration/api/onboarding.rs +++ b/compliance-agent/tests/integration/api/onboarding.rs @@ -491,6 +491,63 @@ async fn a_new_supplier_sbom_replaces_the_one_before_it() { server.cleanup().await; } +#[tokio::test] +async fn a_targets_supplier_advisories_are_counted_with_their_last_read() { + let server = TestServer::start().await; + let id = firmware_target(&server, "bought-in-motor").await; + let path = format!("/api/v1/targets/{id}/supplier-advisories"); + let advisories = || async { + let resp = server.get(&path).await; + assert_eq!(resp.status(), 200); + resp.json::().await.unwrap()["data"].clone() + }; + // Without a provider there is nothing to count. + assert!(advisories().await.is_null()); + + // `.invalid` never resolves: the background refresh reaches no network. + let url = "https://motor.invalid/.well-known/csaf/provider-metadata.json"; + let resp = server + .patch( + &format!("/api/v1/targets/{id}"), + &json!({ "supplier": { "name": "Example GmbH", "csaf_provider": url } }), + ) + .await; + assert_eq!(resp.status(), 200); + assert_eq!(advisories().await["advisories"], 0); + + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let db = mongodb::Client::with_uri_str(&uri) + .await + .unwrap() + .database(&server.tenant_db_name()); + let key = format!("supplier:{url}"); + db.collection::("supplier_csaf_advisories") + .insert_one(mongodb::bson::doc! { "_id": format!("{key}:SA-1"), "provider": &key }) + .await + .unwrap(); + // As the refresh keeps it: a provider that could not be read. + db.collection::("supplier_csaf_providers") + .replace_one( + mongodb::bson::doc! { "_id": &key }, + mongodb::bson::doc! { + "_id": &key, + "checked_at": mongodb::bson::DateTime::now(), + "reachable": false, + }, + ) + .upsert(true) + .await + .unwrap(); + + let data = advisories().await; + assert_eq!(data["advisories"], 1, "{data}"); + assert_eq!(data["reachable"], false, "{data}"); + assert!(data["checked_at"].is_string(), "{data}"); + + server.cleanup().await; +} + #[tokio::test] async fn a_targets_supplier_is_set_checked_and_removed() { let server = TestServer::start().await; diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index b2aff93..db98e38 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -129,7 +129,9 @@ go through the same CVE groups, VEX statements and ENISA drafts. workspace's components. A scan matches them against the product itself by the supplier's name and version for it, and against its components by purl. A matching advisory raises a CVE alert with the supplier's remediation and - fixed versions. + fixed versions. `GET /api/v1/targets/{id}/supplier-advisories` returns how + many of the supplier's advisories are kept, when its provider was last + read, and whether it could be read then. - **What the supplier states about a vulnerability:** a CycloneDX SBOM can carry the supplier's VEX (`vulnerabilities[].analysis`: state, justification, detail, response). Prüfwerk reads it for each component and