From 87d8386277b5e2a061b88a5d4ae6192daeb2fe7b Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:48:09 +0100 Subject: [PATCH] feat(sbom): a machine's SBOM, its parts with their suppliers (#1026) A machine is a registry project of kind `product`, made of its targets: in-house ones and components bought in (#1025). GET /api/v1/projects/{id}/sbom returns its CycloneDX 1.6 SBOM: the machine as a device, each part with its supplier (the workspace for one made in-house) and the supplier's version, the parts' components once each, and a graph of the machine depending on its parts and each part on its own components. Part refs are built from target ids, so names never collide. The supplier's product entry is the part, not a component of it; archived targets are left out. The vulnerability listing of the target SBOM moves into its own helper, shared by both; the CycloneDX schema test helpers move to tests/common. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9 --- compliance-agent/src/api/handlers/machine.rs | 146 ++++++++++++++++++ compliance-agent/src/api/handlers/mod.rs | 1 + compliance-agent/src/api/handlers/vex.rs | 7 +- compliance-agent/src/api/routes.rs | 2 + .../tests/integration/api/machine.rs | 105 +++++++++++++ compliance-agent/tests/integration/api/mod.rs | 1 + compliance-core/src/sbom_docs.rs | 107 ++++++++++++- compliance-core/tests/common/mod.rs | 32 ++++ compliance-core/tests/machine_sbom.rs | 125 +++++++++++++++ compliance-core/tests/vex_schemas.rs | 28 +--- docs/guide/sbom.md | 22 +++ 11 files changed, 546 insertions(+), 30 deletions(-) create mode 100644 compliance-agent/src/api/handlers/machine.rs create mode 100644 compliance-agent/tests/integration/api/machine.rs create mode 100644 compliance-core/tests/common/mod.rs create mode 100644 compliance-core/tests/machine_sbom.rs diff --git a/compliance-agent/src/api/handlers/machine.rs b/compliance-agent/src/api/handlers/machine.rs new file mode 100644 index 0000000..5c98e3a --- /dev/null +++ b/compliance-agent/src/api/handlers/machine.rs @@ -0,0 +1,146 @@ +//! A machine (#1026): a project of kind `product` in the registry, made of +//! the targets assigned to it, in-house ones and components bought in from +//! suppliers (#1025). Its documents cover all of them. + +use axum::extract::{Extension, Path}; +use axum::http::StatusCode; +use axum::response::IntoResponse; +use mongodb::bson::{doc, oid::ObjectId}; + +use compliance_core::models::{OnboardedTarget, ProjectKind, SbomEntry, 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 crate::agent::ComplianceAgent; +use crate::pipeline::sbom::supplied::SUPPLIER_PRODUCT_MANAGER; + +/// The name of machine `id`: a product project of the tenant's. +/// +/// Without a registry (development) no project can be looked up, and the +/// machine is named by its id. +/// +/// # Errors +/// +/// 404 when the tenant has no such project, 422 when it is a topic rather +/// than a product, 503 when the registry cannot be asked. +async fn machine_name( + agent: &ComplianceAgent, + tenant: &TenantCtx, + id: &str, +) -> Result { + let projects = tenant_projects(agent, &tenant.0.tenant_id).await?; + match projects.into_iter().find(|p| p.id == id) { + Some(p) if p.kind == ProjectKind::Product => Ok(p.name), + Some(_) => Err(StatusCode::UNPROCESSABLE_ENTITY), + None if agent.registry.is_none() => Ok(id.to_string()), + None => Err(StatusCode::NOT_FOUND), + } +} + +/// The CycloneDX type of a part of target type `kind`: device software is +/// firmware, a PLC program and other software an application. +fn part_kind(kind: TargetType) -> &'static str { + match kind { + TargetType::FirmwareBareMetal + | TargetType::FirmwareRtos + | TargetType::EmbeddedLinuxYocto => "firmware", + TargetType::PlcSps + | TargetType::WebApp + | TargetType::BackendService + | TargetType::DesktopApp + | TargetType::AndroidApp + | TargetType::IosApp => "application", + } +} + +/// A machine's SBOM as a CycloneDX 1.6 document to download. +/// +/// The machine is a product project; its parts are its targets that are not +/// archived, each with its supplier (the workspace for one made in-house) +/// and its components beneath it. A component bought in is named by its +/// supplier's product and version. Never truncated: a machine with more than +/// 100 000 components is refused. +#[utoipa::path( + get, + path = "/api/v1/projects/{id}/sbom", + tag = "SBOM", + params(("id" = String, Path, description = "The project's id")), + responses( + (status = 200, description = "The machine's CycloneDX SBOM"), + (status = 404, description = "No such project"), + (status = 413, description = "Too many components to export"), + (status = 422, description = "The project is a topic, not a product, or has no targets"), + (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 export_machine_sbom( + Extension(agent): AgentExt, + 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; + // 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 }, + "package_manager": { "$ne": SUPPLIER_PRODUCT_MANAGER }, + }; + let components = db + .sbom_entries() + .count_documents(of_parts.clone()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + if components > MAX_EXPORT_COMPONENTS { + tracing::warn!( + components, + "machine SBOM refused: too large to build in memory" + ); + return Err(StatusCode::PAYLOAD_TOO_LARGE); + } + let mut entries: Vec = collect_cursor_async( + db.sbom_entries() + .find(of_parts) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?, + ) + .await; + crate::license_conclusions::attach(&db, &mut entries).await; + + let workspace = super::vex::author(&tenant); + let parts: Vec> = targets + .iter() + .zip(&ids) + .map(|(t, id)| { + let supplier = t.supplier.as_ref(); + MachinePart { + id, + name: &t.name, + kind: part_kind(t.target_type), + supplier: supplier.map_or(workspace.as_str(), |s| s.name.as_str()), + version: supplier.and_then(|s| s.version.as_deref()), + } + }) + .collect(); + let body = sbom_docs::machine_cyclonedx(&name, &id, &parts, &entries); + super::vex::download(&body, &format!("sbom-machine-{id}-cyclonedx.json")) +} diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index 50e9450..71bdb77 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -16,6 +16,7 @@ pub mod help_chat; pub mod inbox; pub mod issues; pub mod licenses; +pub mod machine; pub mod manual_findings; pub mod mcp_servers; pub mod mcp_tokens; diff --git a/compliance-agent/src/api/handlers/vex.rs b/compliance-agent/src/api/handlers/vex.rs index c097f71..6686a13 100644 --- a/compliance-agent/src/api/handlers/vex.rs +++ b/compliance-agent/src/api/handlers/vex.rs @@ -253,7 +253,7 @@ async fn load_source(db: &crate::database::Database, id: &str) -> Result String { +pub(super) fn author(tenant: &TenantCtx) -> String { if tenant.0.tenant_slug.is_empty() { tenant.0.tenant_id.clone() } else { @@ -262,7 +262,10 @@ fn author(tenant: &TenantCtx) -> String { } /// `body` as a JSON file named `filename` to download. -fn download(body: &serde_json::Value, filename: &str) -> Result { +pub(super) fn download( + body: &serde_json::Value, + filename: &str, +) -> Result { let json = serde_json::to_string_pretty(body).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let disposition = HeaderValue::from_str(&format!("attachment; filename=\"{filename}\"")) .unwrap_or_else(|_| HeaderValue::from_static("attachment")); diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index fdb99a7..2c7f34f 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -45,6 +45,8 @@ fn described_routes() -> OpenApiRouter { .routes(routes!(handlers::stats_overview)) // The tenant's projects (owned by the registry), for assigning targets. .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::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 new file mode 100644 index 0000000..56d547c --- /dev/null +++ b/compliance-agent/tests/integration/api/machine.rs @@ -0,0 +1,105 @@ +use crate::common::TestServer; +use compliance_core::models::SbomEntry; +use serde_json::json; + +/// Create a target named `name`, with `supplier` when it is bought in, and +/// return its id. +async fn target(server: &TestServer, name: &str, supplier: Option) -> String { + let resp = server + .post( + "/api/v1/targets", + &json!({ "name": name, "target_type": "firmware_rtos", "supplier": supplier }), + ) + .await; + assert_eq!(resp.status(), 200); + let body: serde_json::Value = resp.json().await.unwrap(); + body["data"]["_id"]["$oid"].as_str().unwrap().to_string() +} + +/// An SBOM entry of target `target`. +fn entry(target: &str, name: &str, manager: &str, purl: Option<&str>) -> SbomEntry { + let mut e = SbomEntry::new(target.into(), name.into(), "1.0".into(), manager.into()); + e.purl = purl.map(String::from); + e +} + +#[tokio::test] +async fn a_machines_sbom_lists_its_parts_with_their_suppliers_and_components() { + let server = TestServer::start().await; + 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" })), + ) + .await; + let retired = target(&server, "Alte Steuerung", None).await; + let elsewhere = target(&server, "Andere Maschine", None).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()); + // Projects are registry-owned, so assign the targets directly. + let targets = db.collection::("onboarded_targets"); + for id in [&controller, &drive, &retired] { + let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap(); + let mut set = mongodb::bson::doc! { "project_ids": ["m1"] }; + if id == &retired { + set.insert("archived_at", mongodb::bson::DateTime::now()); + } + targets + .update_one( + mongodb::bson::doc! { "_id": oid }, + mongodb::bson::doc! { "$set": set }, + ) + .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), + // The bought-in product itself, as a scan stores it. + entry(&drive, "Drive Control", "supplier-product", None), + entry( + &retired, + "openssl", + "generic", + Some("pkg:generic/openssl@1.0"), + ), + entry(&elsewhere, "zlib", "generic", Some("pkg:generic/zlib@1.0")), + ]) + .await + .unwrap(); + + let resp = server.get("/api/v1/projects/m1/sbom").await; + + assert_eq!(resp.status(), 200); + let doc: serde_json::Value = resp.json().await.unwrap(); + assert_eq!(doc["metadata"]["component"]["type"], "device"); + let components = doc["components"].as_array().unwrap(); + let names: Vec<&str> = components + .iter() + .map(|c| c["name"].as_str().unwrap()) + .collect(); + // The parts by name, then their components once each; nothing of the + // archived target or another machine, and the product is the part. + assert_eq!(names, ["Antrieb", "Steuerung", "lodash", "vendor-blob"]); + assert_eq!(components[0]["supplier"]["name"], "Example Drives GmbH"); + assert_eq!(components[0]["version"], "4.2.1"); + // The dev tenant's workspace makes the controller. + assert_eq!(components[1]["supplier"]["name"], "dev"); + + server.cleanup().await; +} + +#[tokio::test] +async fn a_machine_without_parts_has_no_sbom() { + let server = TestServer::start().await; + + let resp = server.get("/api/v1/projects/empty/sbom").await; + + assert_eq!(resp.status(), 422); + server.cleanup().await; +} diff --git a/compliance-agent/tests/integration/api/mod.rs b/compliance-agent/tests/integration/api/mod.rs index 3b24096..904c9f4 100644 --- a/compliance-agent/tests/integration/api/mod.rs +++ b/compliance-agent/tests/integration/api/mod.rs @@ -2,6 +2,7 @@ mod cascade_delete; mod dast; mod findings; mod health; +mod machine; mod onboarding; mod openapi; mod sbom; diff --git a/compliance-core/src/sbom_docs.rs b/compliance-core/src/sbom_docs.rs index 83adcc1..0025f43 100644 --- a/compliance-core/src/sbom_docs.rs +++ b/compliance-core/src/sbom_docs.rs @@ -411,8 +411,14 @@ pub fn cyclonedx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { let components = cdx_components(entries); cdx_dependencies(&mut doc, &components); doc["components"] = serde_json::Value::Array(components); - // One vulnerability per CVE (or advisory without one), affecting every - // component it was found in, by whichever scanner and id. + cdx_known_vulnerabilities(&mut doc, entries); + doc +} + +/// The known vulnerabilities of `entries` as the document's +/// `vulnerabilities`: one per CVE (or advisory without one), affecting every +/// component it was found in, by whichever scanner and id. None, none set. +fn cdx_known_vulnerabilities(doc: &mut serde_json::Value, entries: &[SbomEntry]) { let mut vulns: Vec> = Vec::new(); for e in entries { for v in &e.known_vulnerabilities { @@ -460,6 +466,103 @@ pub fn cyclonedx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { }) .collect(); } +} + +/// One part of a machine (#1026): one of its targets, in-house or bought in. +#[derive(Debug, Clone, Copy)] +pub struct MachinePart<'a> { + /// The target's id. Its SBOM entries are the ones with this `repo_id`. + pub id: &'a str, + /// The target's name. + pub name: &'a str, + /// Its CycloneDX component type, such as `firmware` or `application`. + pub kind: &'static str, + /// Who supplies it: the supplier of a bought-in component, the + /// manufacturer (the workspace) for one made in-house. + pub supplier: &'a str, + /// Its version, where the supplier names one; else when its SBOM data + /// was last compiled, as for a target's own SBOM. + pub version: Option<&'a str>, +} + +impl MachinePart<'_> { + /// The part's `bom-ref`: by its target's id, unique in the machine + /// whatever the targets are called. + pub fn bom_ref(&self) -> String { + format!("urn:pruefwerk:target:{}", self.id) + } +} + +/// The SBOM of a machine (#1026): the machine `machine` (a product project, +/// `project_id`) made of `parts`, each listing the components of `entries` +/// with its `repo_id` beneath it. +/// +/// Every part is a component of the machine with its supplier, so the +/// document names who supplies each. A component two parts contain is listed +/// once, with both parts depending on it. The machine depends on its parts +/// and each part on its components: the top-level dependencies the CRA asks +/// for (Annex I, Part II (1)). Which of a part's components depend on which +/// is not known, so the graph is stated `incomplete`, as for a target. +/// +/// # Arguments +/// +/// * `machine` - the machine's name +/// * `project_id` - its project's id, its `bom-ref` +/// * `parts` - its parts, in the order they are listed +/// * `entries` - the SBOM entries of all parts +pub fn machine_cyclonedx( + machine: &str, + project_id: &str, + parts: &[MachinePart<'_>], + entries: &[SbomEntry], +) -> serde_json::Value { + let machine_ref = format!("urn:pruefwerk:project:{project_id}"); + let mut doc = cdx_frame(machine, entries); + doc["metadata"]["component"]["type"] = serde_json::json!("device"); + doc["metadata"]["component"]["bom-ref"] = serde_json::json!(machine_ref); + let mut components: Vec = Vec::with_capacity(parts.len()); + let mut dependencies = Vec::with_capacity(parts.len() + 1); + dependencies.push(serde_json::json!({ + "ref": machine_ref, + "dependsOn": parts.iter().map(MachinePart::bom_ref).collect::>(), + })); + for part in parts { + let own: Vec<&SbomEntry> = entries.iter().filter(|e| e.repo_id == part.id).collect(); + let version = part.version.map(str::to_string).or_else(|| { + own.iter() + .map(|e| e.updated_at) + .max() + .map(|at| at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)) + }); + let mut component = serde_json::json!({ + "type": part.kind, + "bom-ref": part.bom_ref(), + "name": part.name, + "supplier": { "name": part.supplier }, + }); + if let Some(version) = version { + component["version"] = serde_json::Value::String(version); + } + components.push(component); + let mut refs: Vec = own.iter().map(|e| component_ref(e)).collect(); + refs.sort_unstable(); + refs.dedup(); + dependencies.push(serde_json::json!({ "ref": part.bom_ref(), "dependsOn": refs })); + } + let parts_of_machine = components.len(); + components.extend(cdx_components(entries)); + dependencies.extend( + components[parts_of_machine..] + .iter() + .map(|c| serde_json::json!({ "ref": c["bom-ref"] })), + ); + doc["components"] = serde_json::Value::Array(components); + doc["dependencies"] = serde_json::Value::Array(dependencies); + doc["compositions"] = serde_json::json!([{ + "aggregate": "incomplete", + "dependencies": [machine_ref], + }]); + cdx_known_vulnerabilities(&mut doc, entries); doc } diff --git a/compliance-core/tests/common/mod.rs b/compliance-core/tests/common/mod.rs new file mode 100644 index 0000000..073c644 --- /dev/null +++ b/compliance-core/tests/common/mod.rs @@ -0,0 +1,32 @@ +//! What the schema tests share: the vendored schemas and the CycloneDX +//! validation. + +#![allow(clippy::expect_used, clippy::unwrap_used, dead_code)] + +/// The vendored schema `name` (in `schemas/`). +pub fn schema(name: &str) -> serde_json::Value { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("schemas") + .join(name); + serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() +} + +/// The errors of `doc` against CycloneDX 1.6 (with the SPDX and JSF schemas +/// it refers to). +pub fn cyclonedx_errors(doc: &serde_json::Value) -> Vec { + let validator = jsonschema::options() + .with_resource( + "http://cyclonedx.org/schema/spdx.schema.json", + jsonschema::Resource::from_contents(schema("spdx.schema.json")).unwrap(), + ) + .with_resource( + "http://cyclonedx.org/schema/jsf-0.82.schema.json", + jsonschema::Resource::from_contents(schema("jsf-0.82.schema.json")).unwrap(), + ) + .build(&schema("bom-1.6.schema.json")) + .unwrap(); + validator + .iter_errors(doc) + .map(|e| format!("{} at {}", e, e.instance_path)) + .collect() +} diff --git a/compliance-core/tests/machine_sbom.rs b/compliance-core/tests/machine_sbom.rs new file mode 100644 index 0000000..80911f0 --- /dev/null +++ b/compliance-core/tests/machine_sbom.rs @@ -0,0 +1,125 @@ +//! The SBOM of a machine (#1026): its parts, in-house and bought in, with +//! their suppliers and components, valid against CycloneDX 1.6. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +mod common; + +use std::collections::HashSet; + +use compliance_core::models::{SbomEntry, VulnRef}; +use compliance_core::sbom_docs::{self, MachinePart}; + +/// An SBOM entry of target `target`. +fn entry(target: &str, name: &str, version: &str, purl: Option<&str>) -> SbomEntry { + let mut e = SbomEntry::new(target.into(), name.into(), version.into(), "npm".into()); + e.purl = purl.map(String::from); + e +} + +/// A controller made in-house (`t1`) and a drive bought in (`t2`), sharing +/// lodash; the drive's vendor blob has no purl. +fn machine() -> (Vec>, Vec) { + let parts = vec![ + MachinePart { + id: "t1", + name: "Steuerung", + kind: "firmware", + supplier: "Example Maschinenbau", + version: None, + }, + // Named like the machine: the refs must still be unique. + MachinePart { + id: "t2", + name: "Packing Line", + kind: "firmware", + supplier: "Example Drives GmbH", + version: Some("4.2.1"), + }, + ]; + let mut lodash = entry("t1", "lodash", "4.17.20", Some("pkg:npm/lodash@4.17.20")); + lodash.known_vulnerabilities = vec![VulnRef { + id: "CVE-2021-23337".into(), + source: "osv".into(), + severity: Some("high".into()), + url: None, + exploitation: None, + aliases: Vec::new(), + }]; + let entries = vec![ + lodash, + entry("t1", "zlib", "1.2.11", Some("pkg:generic/zlib@1.2.11")), + entry("t2", "lodash", "4.17.20", Some("pkg:npm/lodash@4.17.20")), + entry("t2", "vendor-blob", "2.0", None), + ]; + (parts, entries) +} + +#[test] +fn a_machines_sbom_names_its_parts_with_their_suppliers_and_is_valid() { + let (parts, entries) = machine(); + + let doc = sbom_docs::machine_cyclonedx("Packing Line", "p1", &parts, &entries); + + let errors = common::cyclonedx_errors(&doc); + assert!(errors.is_empty(), "{errors:#?}"); + assert_eq!(doc["metadata"]["component"]["type"], "device"); + assert_eq!(doc["metadata"]["component"]["name"], "Packing Line"); + let components = doc["components"].as_array().unwrap(); + // The parts first, each with its supplier; the drive with its version. + assert_eq!(components[0]["name"], "Steuerung"); + assert_eq!(components[0]["supplier"]["name"], "Example Maschinenbau"); + assert!(components[0]["version"].is_string()); + assert_eq!(components[1]["supplier"]["name"], "Example Drives GmbH"); + assert_eq!(components[1]["version"], "4.2.1"); + // lodash, in both parts, is listed once. + let lodash = components + .iter() + .filter(|c| c["purl"] == "pkg:npm/lodash@4.17.20") + .count(); + assert_eq!(lodash, 1); + assert_eq!(components.len(), 2 + 3); +} + +#[test] +fn every_ref_of_a_machines_sbom_is_unique_and_every_dependency_resolves() { + let (parts, entries) = machine(); + + let doc = sbom_docs::machine_cyclonedx("Packing Line", "p1", &parts, &entries); + + let machine_ref = doc["metadata"]["component"]["bom-ref"].as_str().unwrap(); + let mut refs = HashSet::from([machine_ref]); + for c in doc["components"].as_array().unwrap() { + assert!(refs.insert(c["bom-ref"].as_str().unwrap()), "{c}"); + } + let depends = |r: &str| -> Vec<&str> { + doc["dependencies"] + .as_array() + .unwrap() + .iter() + .find(|d| d["ref"] == r) + .and_then(|d| d["dependsOn"].as_array()) + .map(|list| list.iter().map(|v| v.as_str().unwrap()).collect()) + .unwrap_or_default() + }; + for d in doc["dependencies"].as_array().unwrap() { + assert!(refs.contains(d["ref"].as_str().unwrap()), "{d}"); + for on in d["dependsOn"].as_array().into_iter().flatten() { + assert!(refs.contains(on.as_str().unwrap()), "{on}"); + } + } + // The machine depends on its parts, each part on its own components. + assert_eq!( + depends(machine_ref), + ["urn:pruefwerk:target:t1", "urn:pruefwerk:target:t2"] + ); + assert_eq!( + depends("urn:pruefwerk:target:t2"), + ["npm:vendor-blob@2.0", "pkg:npm/lodash@4.17.20"] + ); + // A vulnerability points at the shared component. + assert_eq!( + doc["vulnerabilities"][0]["affects"][0]["ref"], + "pkg:npm/lodash@4.17.20" + ); +} diff --git a/compliance-core/tests/vex_schemas.rs b/compliance-core/tests/vex_schemas.rs index 6c385c9..a3a2696 100644 --- a/compliance-core/tests/vex_schemas.rs +++ b/compliance-core/tests/vex_schemas.rs @@ -12,32 +12,8 @@ use compliance_core::models::{ use compliance_core::sbom_docs; use compliance_core::vex_docs::{self, VexInput}; -fn schema(name: &str) -> serde_json::Value { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("schemas") - .join(name); - serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() -} - -/// The errors of `doc` against CycloneDX 1.6 (with the SPDX and JSF schemas -/// it refers to). -fn cyclonedx_errors(doc: &serde_json::Value) -> Vec { - let validator = jsonschema::options() - .with_resource( - "http://cyclonedx.org/schema/spdx.schema.json", - jsonschema::Resource::from_contents(schema("spdx.schema.json")).unwrap(), - ) - .with_resource( - "http://cyclonedx.org/schema/jsf-0.82.schema.json", - jsonschema::Resource::from_contents(schema("jsf-0.82.schema.json")).unwrap(), - ) - .build(&schema("bom-1.6.schema.json")) - .unwrap(); - validator - .iter_errors(doc) - .map(|e| format!("{} at {}", e, e.instance_path)) - .collect() -} +mod common; +use common::{cyclonedx_errors, schema}; /// The errors of `doc` against CSAF 2.0 (with the CVSS schemas it refers to). fn csaf_errors(doc: &serde_json::Value) -> Vec { diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index b2aff93..8b8caba 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -481,6 +481,28 @@ Prüfwerk has the data, BSI TR-03183-2 v2.1: (`source` NVD) when one is known, with its GitHub advisory under `references`; one without a CVE under the advisory's id. +### A machine's SBOM + +A machine is a project of kind **product** (projects are managed in the +portal). Its parts are the targets assigned to it, the ones made in-house +and the components bought in from suppliers. `GET +/api/v1/projects/{id}/sbom` returns the machine's SBOM as CycloneDX 1.6: + +- The machine is `metadata.component`, of type `device`. +- Each part is a component of the machine with its `supplier`: the supplier + of a bought-in component, the workspace for a part made in-house. A + bought-in part's version is the supplier's version of the product; a part + made in-house carries the time its SBOM data was last compiled, as for a + target. +- Each part's components follow. One that two parts contain is listed once. + The supplier's product itself is the part, not one of its components. +- The dependency graph has the machine depending on its parts and each part + on its own components. Which of a part's components depend on which is not + known, so `compositions` states it `incomplete`. +- Archived targets are left out. A topic project, or a product without + targets, has no SBOM (422). More than 100,000 components are refused (413), + as for one target. + ## VEX: the status of each vulnerability For each known vulnerability (CVE alert) of a target you state whether the