diff --git a/compliance-agent/src/api/handlers/machine.rs b/compliance-agent/src/api/handlers/machine.rs index 5c98e3a..ea099e0 100644 --- a/compliance-agent/src/api/handlers/machine.rs +++ b/compliance-agent/src/api/handlers/machine.rs @@ -2,20 +2,82 @@ //! the targets assigned to it, in-house ones and components bought in from //! suppliers (#1025). Its documents cover all of them. +use std::collections::HashMap; + use axum::extract::{Extension, Path}; use axum::http::StatusCode; use axum::response::IntoResponse; +use axum::Json; +use chrono::{DateTime, Utc}; +use futures_util::StreamExt; use mongodb::bson::{doc, oid::ObjectId}; +use serde::Serialize; -use compliance_core::models::{OnboardedTarget, ProjectKind, SbomEntry, TargetType}; +use compliance_core::cve_groups::{self, CveGroup, SeverityCounts}; +use compliance_core::models::{ + CveAlert, OnboardedTarget, ProjectKind, SbomEntry, SupplierComponent, TargetType, +}; use compliance_core::sbom_docs::{self, MachinePart}; use compliance_core::tenant_ctx::TenantCtx; use super::dto::{tenant_db, AgentExt}; -use super::{collect_cursor_async, projects::tenant_projects, sbom::MAX_EXPORT_COMPONENTS}; +use super::{ + collect_cursor_async, projects::tenant_projects, sbom::MAX_EXPORT_COMPONENTS, ApiResponse, +}; use crate::agent::ComplianceAgent; +use crate::database::Database; +use crate::pipeline::csaf_feed::{supplier_key, MongoAdvisoryStore, SupplierProviderStatus}; use crate::pipeline::sbom::supplied::SUPPLIER_PRODUCT_MANAGER; +/// A machine as its endpoints read it: its name, its parts (its targets that +/// are not archived, by name) and their ids, in the same order. +struct Machine { + name: String, + targets: Vec, + ids: Vec, +} + +/// Machine `id` of the tenant, and the tenant's database. +/// +/// # Errors +/// +/// As [`machine_name`]; 500 when the targets cannot be read. +async fn machine( + agent: &ComplianceAgent, + tenant: &TenantCtx, + id: &str, +) -> Result<(Machine, Database), StatusCode> { + let name = machine_name(agent, tenant, id).await?; + let db = tenant_db(agent, tenant).await?; + let targets: Vec = collect_cursor_async( + db.onboarded_targets() + .find(doc! { "project_ids": id, "archived_at": null }) + .sort(doc! { "name": 1 }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?, + ) + .await; + let ids = targets + .iter() + .filter_map(|t| t.id.map(|o: ObjectId| o.to_hex())) + .collect(); + Ok((Machine { name, targets, ids }, db)) +} + +/// The open CVE alerts of the targets `ids`. +async fn open_alerts(db: &Database, ids: &[String]) -> Result, StatusCode> { + let alerts: Vec = collect_cursor_async( + db.cve_alerts() + .find(doc! { "repo_id": { "$in": ids }, "resolved_at": null }) + .projection(doc! { "llm_impact_summary": 0 }) + .sort(doc! { "cve_id": 1 }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?, + ) + .await; + Ok(alerts.into_iter().filter(cve_groups::is_open).collect()) +} + /// The name of machine `id`: a product project of the tenant's. /// /// Without a registry (development) no project can be looked up, and the @@ -82,24 +144,11 @@ pub async fn export_machine_sbom( tenant: TenantCtx, Path(id): Path, ) -> Result { - let name = machine_name(&agent, &tenant, &id).await?; - let db = tenant_db(&agent, &tenant).await?; - let targets: Vec = collect_cursor_async( - db.onboarded_targets() - .find(doc! { "project_ids": &id, "archived_at": null }) - .sort(doc! { "name": 1 }) - .await - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?, - ) - .await; + let (Machine { name, targets, ids }, db) = machine(&agent, &tenant, &id).await?; // A machine without parts would read as one without components. if targets.is_empty() { return Err(StatusCode::UNPROCESSABLE_ENTITY); } - let ids: Vec = targets - .iter() - .filter_map(|t| t.id.map(|o: ObjectId| o.to_hex())) - .collect(); // The supplier's product is the part itself, not one of its components. let of_parts = doc! { "repo_id": { "$in": &ids }, @@ -144,3 +193,262 @@ pub async fn export_machine_sbom( let body = sbom_docs::machine_cyclonedx(&name, &id, &parts, &entries); super::vex::download(&body, &format!("sbom-machine-{id}-cyclonedx.json")) } + +/// One part of a machine in its overview. +#[derive(Debug, Serialize)] +pub struct PartOverview { + /// The target's id. + pub id: String, + pub name: String, + pub target_type: TargetType, + /// Its supplier, for a component bought in; none for one made in-house. + #[serde(skip_serializing_if = "Option::is_none")] + pub supplier: Option, + /// Its open CVEs per severity, a CVE counted once per component. + pub open: SeverityCounts, + /// When its last scan ended (or started, while it runs); none before + /// the first. + #[serde(skip_serializing_if = "Option::is_none")] + pub last_scan_at: Option>, +} + +/// The advisories of a machine's suppliers, as read for the workspace. +#[derive(Debug, Serialize)] +pub struct MachineAdvisories { + /// The advisories kept, over all its suppliers' providers. + pub advisories: u64, + /// The suppliers' providers, each once. + pub providers: usize, + /// When one of them was last read; none before the first refresh. + #[serde(skip_serializing_if = "Option::is_none")] + pub checked_at: Option>, +} + +/// A machine at a glance: its parts and what is open across them. +#[derive(Debug, Serialize)] +pub struct MachineOverview { + pub name: String, + /// Its parts, by name. + pub parts: Vec, + /// Its open CVEs per severity, a CVE counted once per component. + pub open: SeverityCounts, + /// The open alerts nobody has stated anything on yet. + pub undecided: usize, + /// Of those, the ones the supplier states something on. + pub undecided_with_supplier: usize, + /// Its components, each once, however many parts contain it. + pub components: u64, + /// Of those, the ones more than one part contains. + pub shared_components: u64, + /// Its suppliers' advisories; none when no part names a CSAF provider. + #[serde(skip_serializing_if = "Option::is_none")] + pub advisories: Option, +} + +/// How many components the parts `ids` contain, each once, and how many of +/// them more than one part contains, counted by the database. A component +/// is known by its purl, else by its package manager, name and version, as +/// the SBOM documents name it; the supplier's product is the part itself. +async fn component_counts(db: &Database, ids: &[String]) -> Result<(u64, u64), StatusCode> { + let pipeline = vec![ + doc! { "$match": { + "repo_id": { "$in": ids }, + "package_manager": { "$ne": SUPPLIER_PRODUCT_MANAGER }, + } }, + doc! { "$group": { + "_id": { "$ifNull": [ + "$purl", + { "$concat": ["$package_manager", ":", "$name", "@", "$version"] }, + ] }, + "parts": { "$addToSet": "$repo_id" }, + } }, + doc! { "$group": { + "_id": null, + "components": { "$sum": 1 }, + "shared": { "$sum": { "$cond": [{ "$gt": [{ "$size": "$parts" }, 1] }, 1, 0] } }, + } }, + ]; + let mut cursor = db + .sbom_entries() + .aggregate(pipeline) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let Some(row) = cursor.next().await else { + return Ok((0, 0)); + }; + let row = row.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let count = |key: &str| { + row.get_i32(key) + .map(i64::from) + .or_else(|_| row.get_i64(key)) + .map_or(0, |n| u64::try_from(n).unwrap_or(0)) + }; + Ok((count("components"), count("shared"))) +} + +/// The advisories of the suppliers `targets` name, read for the workspace. +async fn machine_advisories( + db: &Database, + targets: &[OnboardedTarget], +) -> Result, StatusCode> { + let mut keys: Vec = targets + .iter() + .filter_map(|t| t.supplier.as_ref()?.csaf_provider.as_deref()) + .map(supplier_key) + .collect(); + keys.sort_unstable(); + keys.dedup(); + if keys.is_empty() { + return Ok(None); + } + let advisories = MongoAdvisoryStore::supplier(db.inner()) + .collection() + .count_documents(doc! { "provider": { "$in": &keys } }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let checked_at = db + .inner() + .collection::(SupplierProviderStatus::COLLECTION) + .find_one(doc! { "_id": { "$in": &keys } }) + .sort(doc! { "checked_at": -1 }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .map(|s| s.checked_at.to_chrono()); + Ok(Some(MachineAdvisories { + advisories, + providers: keys.len(), + checked_at, + })) +} + +/// The open CVEs per severity of `alerts`, a CVE counted once per component. +fn open_counts<'a>(alerts: impl IntoIterator) -> SeverityCounts { + let alerts: Vec = alerts.into_iter().cloned().collect(); + cve_groups::group_open_alerts(&alerts) + .iter() + .fold(SeverityCounts::default(), |sum, g| sum.plus(g.counts)) +} + +/// Whether nobody has stated anything on `alert` yet: no statement of a +/// person's. +fn undecided(alert: &CveAlert) -> bool { + alert.vex.as_ref().is_none_or(|v| v.by_scan) +} + +/// A machine at a glance: its parts and what is open across them. +/// +/// Each part with its supplier, open CVEs and last scan; across them the +/// open and undecided CVEs, the components and the suppliers' advisories. +#[utoipa::path( + get, + path = "/api/v1/projects/{id}/overview", + tag = "Targets", + params(("id" = String, Path, description = "The project's id")), + responses( + (status = 200, description = "The machine at a glance (`data`)"), + (status = 404, description = "No such project"), + (status = 422, description = "The project is a topic, not a product"), + (status = 503, description = "The registry cannot be asked"), + (status = 401, description = "No valid bearer token"), + ) +)] +#[tracing::instrument(skip_all, fields(project_id = %id))] +pub async fn machine_overview( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, +) -> Result>, StatusCode> { + let (machine, db) = machine(&agent, &tenant, &id).await?; + let alerts = open_alerts(&db, &machine.ids).await?; + let (components, shared_components) = component_counts(&db, &machine.ids).await?; + let advisories = machine_advisories(&db, &machine.targets).await?; + let mut last_scans = + super::onboarding::latest_scan_runs(&db.scan_runs(), machine.ids.clone(), false).await; + let mut by_part: HashMap<&str, Vec<&CveAlert>> = HashMap::new(); + for alert in &alerts { + by_part + .entry(alert.repo_id.as_str()) + .or_default() + .push(alert); + } + let parts = machine + .targets + .into_iter() + .zip(&machine.ids) + .map(|(t, id)| PartOverview { + open: open_counts(by_part.remove(id.as_str()).unwrap_or_default()), + last_scan_at: last_scans + .remove(id) + .map(|run| run.completed_at.unwrap_or(run.started_at)), + id: id.clone(), + name: t.name, + target_type: t.target_type, + supplier: t.supplier, + }) + .collect(); + let undecided_alerts: Vec<&CveAlert> = alerts.iter().filter(|a| undecided(a)).collect(); + Ok(Json(ApiResponse { + data: MachineOverview { + name: machine.name, + parts, + open: open_counts(&alerts), + undecided: undecided_alerts.len(), + undecided_with_supplier: undecided_alerts + .iter() + .filter(|a| a.supplier_vex.is_some()) + .count(), + components, + shared_components, + advisories, + }, + total: None, + page: None, + })) +} + +/// A machine's open CVEs: grouped by component across its parts, and the +/// alerts themselves, each with its part (`repo_id`). +#[derive(Debug, Serialize)] +pub struct MachineCves { + /// The groups, the most severe first; a group's `alert_ids` may belong + /// to several parts. + pub groups: Vec, + /// The open alerts, by CVE. + pub alerts: Vec, +} + +/// A machine's open CVEs, grouped by component across its parts. +/// +/// A component in several parts is one group, with the alerts of every part +/// it is in: whether it affects the machine is stated per part, as the code +/// may be reached in one and not in another. +#[utoipa::path( + get, + path = "/api/v1/projects/{id}/cves", + tag = "CVEs", + params(("id" = String, Path, description = "The project's id")), + responses( + (status = 200, description = "The groups and the open alerts (`data`)"), + (status = 404, description = "No such project"), + (status = 422, description = "The project is a topic, not a product"), + (status = 503, description = "The registry cannot be asked"), + (status = 401, description = "No valid bearer token"), + ) +)] +#[tracing::instrument(skip_all, fields(project_id = %id))] +pub async fn machine_cves( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, +) -> Result>, StatusCode> { + let (machine, db) = machine(&agent, &tenant, &id).await?; + let alerts = open_alerts(&db, &machine.ids).await?; + Ok(Json(ApiResponse { + data: MachineCves { + groups: cve_groups::group_open_alerts(&alerts), + alerts, + }, + total: None, + page: None, + })) +} diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 97a4c63..f21667d 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -47,6 +47,8 @@ fn described_routes() -> OpenApiRouter { .routes(routes!(handlers::projects::list_projects)) // A machine: a product project and the targets it is made of (#1026). .routes(routes!(handlers::machine::export_machine_sbom)) + .routes(routes!(handlers::machine::machine_overview)) + .routes(routes!(handlers::machine::machine_cves)) .routes(routes!(handlers::metering::get_usage)) // Whether the caller may use Prüfwerk at all: answered by the // authentication and entitlement layers in front of it (a blocked diff --git a/compliance-agent/tests/integration/api/machine.rs b/compliance-agent/tests/integration/api/machine.rs index 56d547c..a284ede 100644 --- a/compliance-agent/tests/integration/api/machine.rs +++ b/compliance-agent/tests/integration/api/machine.rs @@ -103,3 +103,129 @@ async fn a_machine_without_parts_has_no_sbom() { assert_eq!(resp.status(), 422); server.cleanup().await; } + +/// A CVE alert of target `target` on `package`, as a scan stores it. +fn alert(target: &str, cve: &str, package: &str, severity: &str) -> serde_json::Value { + json!({ + "cve_id": cve, "repo_id": target, "affected_package": package, + "affected_version": "1.0", "source": "osv", "severity": severity, + "cvss_score": null, "summary": null, "llm_impact_summary": null, + "references": [], "created_at": "2026-11-16T08:00:00Z", + }) +} + +#[tokio::test] +async fn a_machine_shows_its_parts_and_their_open_cves_together() { + let server = TestServer::start().await; + let provider = "https://drives.invalid/.well-known/csaf/provider-metadata.json"; + let controller = target(&server, "Steuerung", None).await; + let drive = target( + &server, + "Antrieb", + Some( + json!({ "name": "Example Drives GmbH", "product": "Drive Control", + "version": "4.2.1", "csaf_provider": provider }), + ), + ) + .await; + let mongodb_uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap(); + let db = client.database(&server.tenant_db_name()); + let targets = db.collection::("onboarded_targets"); + for id in [&controller, &drive] { + let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap(); + targets + .update_one( + mongodb::bson::doc! { "_id": oid }, + mongodb::bson::doc! { "$set": { "project_ids": ["m1"] } }, + ) + .await + .unwrap(); + } + db.collection::("sbom_entries") + .insert_many([ + entry(&controller, "lodash", "npm", Some("pkg:npm/lodash@1.0")), + entry(&drive, "lodash", "npm", Some("pkg:npm/lodash@1.0")), + entry(&drive, "vendor-blob", "supplier", None), + entry(&drive, "Drive Control", "supplier-product", None), + ]) + .await + .unwrap(); + let mut on_product = alert(&drive, "CVE-2026-90001", "Drive Control", "critical"); + on_product["supplier_vex"] = + json!({ "status": "affected", "state": "exploitable", "source": "drive.cdx.json" }); + let mut decided = alert(&drive, "CVE-2021-23337", "lodash", "high"); + decided["vex"] = json!({ "status": "not_affected", "impact_statement": "Never called.", + "by": "ada", "at": "2026-11-16T09:00:00Z" }); + let mut gone = alert(&controller, "CVE-2020-0001", "zlib", "medium"); + gone["resolved_at"] = json!("2026-11-16T10:00:00Z"); + let alerts: Vec = [ + alert(&controller, "CVE-2021-23337", "lodash", "high"), + decided, + on_product, + gone, + ] + .into_iter() + .map(|a| serde_json::from_value(a).unwrap()) + .collect(); + db.collection::("cve_alerts") + .insert_many(alerts) + .await + .unwrap(); + let key = format!("supplier:{provider}"); + db.collection::("supplier_csaf_advisories") + .insert_many([ + mongodb::bson::doc! { "_id": format!("{key}:A-1"), "provider": &key }, + mongodb::bson::doc! { "_id": format!("{key}:A-2"), "provider": &key }, + ]) + .await + .unwrap(); + + let resp = server.get("/api/v1/projects/m1/overview").await; + + assert_eq!(resp.status(), 200); + let body: serde_json::Value = resp.json().await.unwrap(); + let data = &body["data"]; + assert_eq!(data["name"], "m1"); + let parts = data["parts"].as_array().unwrap(); + assert_eq!(parts[0]["name"], "Antrieb"); + assert_eq!(parts[0]["supplier"]["name"], "Example Drives GmbH"); + assert_eq!(parts[0]["open"]["critical"], 1); + assert_eq!(parts[0]["open"]["high"], 0, "the stated one is settled"); + assert_eq!(parts[1]["name"], "Steuerung"); + assert!(parts[1].get("supplier").is_none()); + assert_eq!(parts[1]["open"]["high"], 1); + assert_eq!(data["open"]["critical"], 1); + assert_eq!(data["open"]["high"], 1); + assert_eq!(data["open"]["medium"], 0, "a gone one is not open"); + assert_eq!(data["undecided"], 2); + assert_eq!(data["undecided_with_supplier"], 1); + assert_eq!(data["components"], 2); + assert_eq!(data["shared_components"], 1); + assert_eq!(data["advisories"]["advisories"], 2); + assert_eq!(data["advisories"]["providers"], 1); + + let resp = server.get("/api/v1/projects/m1/cves").await; + + assert_eq!(resp.status(), 200); + let body: serde_json::Value = resp.json().await.unwrap(); + let groups = body["data"]["groups"].as_array().unwrap(); + assert_eq!(groups.len(), 2); + assert_eq!( + groups[0]["package"], "Drive Control", + "the most severe first" + ); + let alerts = body["data"]["alerts"].as_array().unwrap(); + let parts_of = |cve: &str| -> Vec<&str> { + alerts + .iter() + .filter(|a| a["cve_id"] == cve) + .map(|a| a["repo_id"].as_str().unwrap()) + .collect() + }; + assert_eq!(parts_of("CVE-2021-23337"), [controller.as_str()]); + assert_eq!(parts_of("CVE-2026-90001"), [drive.as_str()]); + + server.cleanup().await; +} diff --git a/compliance-core/src/cve_groups.rs b/compliance-core/src/cve_groups.rs index 5c71628..c97090a 100644 --- a/compliance-core/src/cve_groups.rs +++ b/compliance-core/src/cve_groups.rs @@ -91,6 +91,17 @@ impl SeverityCounts { ] } + /// The counts of `self` and `other` together. + pub fn plus(self, other: Self) -> Self { + Self { + critical: self.critical + other.critical, + high: self.high + other.high, + medium: self.medium + other.medium, + low: self.low + other.low, + info: self.info + other.info, + } + } + /// The most severe severity counted, `Info` when none is. pub fn max(&self) -> CveSeverity { self.by_severity() diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index 66c65e9..7190597 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -514,6 +514,17 @@ and the components bought in from suppliers. `GET targets, has no SBOM (422). More than 100,000 components are refused (413), as for one target. +`GET /api/v1/projects/{id}/overview` shows the machine at a glance. It has +each part with its supplier, open CVEs and last scan. Across the parts it +gives the open CVEs by severity, the ones nobody has stated anything on yet +(and how many of those the supplier states something on), the components +(each once, and how many sit in more than one part) and the suppliers' +advisories. `GET /api/v1/projects/{id}/cves` lists the machine's open CVEs +grouped by component across its parts, with each alert naming its part +(`repo_id`). A component in two parts is one group. Whether it affects the +machine is still stated per part, because the vulnerable code may be reached +in one part and not in the other. + ## VEX: the status of each vulnerability For each known vulnerability (CVE alert) of a target you state whether the