From da13aab408434a82e0c42707f3c860f516649f9f Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:34:06 +0100 Subject: [PATCH 1/3] feat(releases): the next version's draft and each version's customers (#1028) The supplier's release screen (mockup RL3h) shows what publishing now would change and how many customers each version reached; neither was in the API. - GET /api/v1/targets/{id}/versions/draft: the next version's component count, the scan it comes from, and its additions, updates and removals against the latest published version (component_changes::diff over both released documents), with a few names. A target that cannot be published answers 200 with `blocked` (empty, too_many_components). - Each version records the releases it was delivered over ($addToSet in deliver(), so acceptances after publishing count too); the list shows the count as `customers`. - released_entries split out of released_document; the refusal codes are an enum. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9 --- compliance-agent/src/api/handlers/delivery.rs | 12 + compliance-agent/src/api/handlers/releases.rs | 344 ++++++++++++++++-- compliance-agent/src/api/routes.rs | 1 + compliance-agent/tests/connections.rs | 75 +++- docs/guide/sbom.md | 8 +- 5 files changed, 415 insertions(+), 25 deletions(-) diff --git a/compliance-agent/src/api/handlers/delivery.rs b/compliance-agent/src/api/handlers/delivery.rs index 8a5dba7..bc75968 100644 --- a/compliance-agent/src/api/handlers/delivery.rs +++ b/compliance-agent/src/api/handlers/delivery.rs @@ -127,6 +127,18 @@ async fn deliver( if let Err(e) = shown { tracing::warn!(release = %release.id, "delivery not recorded on the release: {e}"); } + // A set: a release delivered the same version again counts once. + let counted = supplier + .inner() + .collection::(SbomVersion::COLLECTION) + .update_one( + doc! { "_id": version.id }, + doc! { "$addToSet": { "delivered_to": release.id.to_hex() } }, + ) + .await; + if let Err(e) = counted { + tracing::warn!(label = %version.label, "delivery not counted on the version: {e}"); + } let (agent, customer) = (Arc::clone(agent), customer.clone()); tokio::spawn(async move { if let Err(e) = agent diff --git a/compliance-agent/src/api/handlers/releases.rs b/compliance-agent/src/api/handlers/releases.rs index c65d581..a89f3dc 100644 --- a/compliance-agent/src/api/handlers/releases.rs +++ b/compliance-agent/src/api/handlers/releases.rs @@ -87,6 +87,10 @@ pub struct SbomVersion { pub stored_path: String, pub created_by: String, pub created_at: BsonDateTime, + /// The releases it was delivered over, by id: how many customers + /// received it. + #[serde(default)] + pub delivered_to: Vec, } impl SbomVersion { @@ -136,6 +140,8 @@ pub struct VersionView { pub components: i64, pub created_at: DateTime, pub created_by: String, + /// How many customers received it. + pub customers: usize, } impl From for VersionView { @@ -146,10 +152,66 @@ impl From for VersionView { components: v.components, created_at: v.created_at.to_chrono(), created_by: v.created_by, + customers: v.delivered_to.len(), } } } +/// What the next version would change against the latest published one. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct DraftChanges { + /// The latest published version's label. + pub against: String, + pub added: usize, + pub updated: usize, + pub removed: usize, + /// Components of the next version that are in the latest one as they + /// are: with `added` and `updated`, every component the next lists. + pub unchanged: usize, + /// A few added components, `name version`, by package type and name. + pub added_names: Vec, + /// A few updated components, `name version` (the new version). + pub updated_names: Vec, +} + +/// Why a target's next version cannot be published. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Unpublishable { + /// It has no components. + Empty, + /// More than [`MAX_EXPORT_COMPONENTS`]. + TooManyComponents, +} + +impl Unpublishable { + /// The refusal a publication or preview answers with. + fn refusal(self) -> axum::response::Response { + match self { + Self::Empty => refused(StatusCode::UNPROCESSABLE_ENTITY, "empty"), + Self::TooManyComponents => { + refused(StatusCode::PAYLOAD_TOO_LARGE, "too_many_components") + } + } + } +} + +/// The next version as publishing it now would make it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct VersionDraft { + /// How many components it would list; 0 when it cannot be published. + pub components: usize, + /// When the target's latest completed scan, which it comes from, + /// finished. + pub scanned_at: Option>, + /// Why it cannot be published now: `empty` (no components) or + /// `too_many_components`. + pub blocked: Option, + /// Against the latest published version; `None` before the first, or + /// when that version's document is no longer readable. + pub changes: Option, +} + /// A target's releases and published versions. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct Releases { @@ -253,6 +315,40 @@ async fn supplier_name(agent: &ComplianceAgent, tenant: &TenantCtx) -> String { named.unwrap_or_else(|| tenant.0.tenant_slug.clone()) } +/// The SBOM entries a version of target `id` would list, in name order, or +/// why it cannot be published. +/// +/// # Errors +/// +/// 500 when the database cannot be read. +async fn released_entries( + db: &Database, + id: &str, +) -> Result, Unpublishable>, StatusCode> { + let count = db + .sbom_entries() + .count_documents(doc! { "repo_id": id }) + .await + .map_err(internal)?; + if count > MAX_EXPORT_COMPONENTS { + return Ok(Err(Unpublishable::TooManyComponents)); + } + let entries: Vec = db + .sbom_entries() + .find(doc! { "repo_id": id }) + .sort(doc! { "name": 1, "version": 1 }) + .await + .map_err(internal)? + .try_collect() + .await + .map_err(internal)?; + Ok(if entries.is_empty() { + Err(Unpublishable::Empty) + } else { + Ok(entries) + }) +} + /// The released document of target `target` labelled `label`: its SBOM /// entries as the stripped CycloneDX, and how many components it lists. /// @@ -268,29 +364,11 @@ async fn released_document( label: &str, ) -> Result<(serde_json::Value, usize), axum::response::Response> { let id = target.id.map(|o| o.to_hex()).unwrap_or_default(); - let count = db - .sbom_entries() - .count_documents(doc! { "repo_id": &id }) - .await - .map_err(|e| internal(e).into_response())?; - if count > MAX_EXPORT_COMPONENTS { - return Err(refused( - StatusCode::PAYLOAD_TOO_LARGE, - "too_many_components", - )); - } - let entries: Vec = db - .sbom_entries() - .find(doc! { "repo_id": &id }) - .sort(doc! { "name": 1, "version": 1 }) - .await - .map_err(|e| internal(e).into_response())? - .try_collect() - .await - .map_err(|e| internal(e).into_response())?; - if entries.is_empty() { - return Err(refused(StatusCode::UNPROCESSABLE_ENTITY, "empty")); - } + let entries = match released_entries(db, &id).await { + Ok(Ok(entries)) => entries, + Ok(Err(why)) => return Err(why.refusal()), + Err(status) => return Err(status.into_response()), + }; let supplier = supplier_name(agent, tenant).await; let product = ReleasedProduct { name: &target.name, @@ -302,6 +380,79 @@ async fn released_document( Ok((document, components)) } +/// The components of the released document `document`, as the comparison +/// of versions reads them: package type (from the purl), name (with its +/// group) and version. +fn component_keys(document: &serde_json::Value) -> Vec<(String, String, String)> { + let text = |c: &serde_json::Value, key: &str| c[key].as_str().unwrap_or_default().to_string(); + document["components"] + .as_array() + .into_iter() + .flatten() + .map(|c| { + // `pkg:npm/lodash@4.17.21` is of type `npm`. + let kind = c["purl"] + .as_str() + .and_then(|p| p.strip_prefix("pkg:")) + .and_then(|p| p.split('/').next()) + .unwrap_or_default() + .to_string(); + let name = match c["group"].as_str().filter(|g| !g.is_empty()) { + Some(group) => format!("{group}/{}", text(c, "name")), + None => text(c, "name"), + }; + (kind, name, text(c, "version")) + }) + .collect() +} + +/// `keys` as the comparison borrows them. +fn borrowed( + keys: &[(String, String, String)], +) -> Vec> { + keys.iter() + .map(|(kind, name, version)| (kind.as_str(), name.as_str(), version.as_str())) + .collect() +} + +/// How many changed components a draft names, per kind. +const DRAFT_NAMES: usize = 3; + +/// What the released document `next` changes against `latest`, the +/// document of the version labelled `against`. +fn draft_changes( + latest: &serde_json::Value, + next: &serde_json::Value, + against: &str, +) -> DraftChanges { + use compliance_core::component_changes::{diff, ComponentChangeKind}; + let (before, after) = (component_keys(latest), component_keys(next)); + let changes = diff(&borrowed(&before), &borrowed(&after)); + let named = |kind| { + changes + .iter() + .filter(|c| c.kind == kind) + .take(DRAFT_NAMES) + .map(|c| format!("{} {}", c.name, c.to.as_deref().unwrap_or_default())) + .collect::>() + }; + let count = |kind| changes.iter().filter(|c| c.kind == kind).count(); + let (added, updated) = ( + count(ComponentChangeKind::Added), + count(ComponentChangeKind::Updated), + ); + DraftChanges { + against: against.to_string(), + added, + updated, + removed: count(ComponentChangeKind::Removed), + // Each addition and update is one component of the next version. + unchanged: after.len().saturating_sub(added + updated), + added_names: named(ComponentChangeKind::Added), + updated_names: named(ComponentChangeKind::Updated), + } +} + /// A target's releases to connected workspaces and its published versions. #[utoipa::path( get, @@ -610,6 +761,7 @@ pub async fn publish_version( stored_path: stored.to_string_lossy().into_owned(), created_by: tenant.0.user_id.clone(), created_at: BsonDateTime::now(), + delivered_to: Vec::new(), }; versions(&db).insert_one(&version).await.map_err(internal)?; super::delivery::deliver_published(&agent, &tenant.0.tenant_id, &db, &id, &version).await; @@ -631,6 +783,92 @@ pub async fn publish_version( .into_response()) } +/// The next version of a target, before publishing it. +/// +/// How many components publishing now would list, from which scan, and +/// what it changes against the latest published version. Nothing is stored. +#[utoipa::path( + get, + path = "/api/v1/targets/{id}/versions/draft", + tag = "Targets", + params(("id" = String, Path, description = "The target's id")), + responses( + (status = 200, description = "The draft (`data`); `blocked` says why it cannot be published"), + (status = 404, description = "No such target"), + (status = 401, description = "No valid bearer token"), + ) +)] +#[tracing::instrument(skip_all, fields(target_id = %id))] +pub async fn version_draft( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, +) -> Result>, StatusCode> { + let db = tenant_db(&agent, &tenant).await?; + let drafted = target(&db, &id).await?; + let scanned_at = db + .scan_runs() + .find_one(doc! { "repo_id": &id, "status": "completed" }) + .sort(doc! { "completed_at": -1 }) + .await + .map_err(internal)? + .and_then(|run| run.completed_at); + let entries = match released_entries(&db, &id).await? { + Ok(entries) => entries, + Err(why) => { + return Ok(Json(ApiResponse { + data: VersionDraft { + components: 0, + scanned_at, + blocked: Some(why), + changes: None, + }, + total: None, + page: None, + })) + } + }; + // Only the components are compared; the label and supplier do not + // matter here. + let product = ReleasedProduct { + name: &drafted.name, + version: "", + supplier: "", + }; + let next = released_cyclonedx(&entries, &product); + let latest = versions(&db) + .find_one(doc! { "target_id": &id }) + .sort(doc! { "created_at": -1, "_id": -1 }) + .await + .map_err(internal)?; + let changes = match latest { + Some(version) => match tokio::fs::read(&version.stored_path).await { + Ok(bytes) => match serde_json::from_slice::(&bytes) { + Ok(document) => Some(draft_changes(&document, &next, &version.label)), + Err(e) => { + tracing::warn!(label = %version.label, "published document unreadable: {e}"); + None + } + }, + Err(e) => { + tracing::warn!(label = %version.label, "published document not read: {e}"); + None + } + }, + None => None, + }; + Ok(Json(ApiResponse { + data: VersionDraft { + components: next["components"].as_array().map_or(0, Vec::len), + scanned_at, + blocked: None, + changes, + }, + total: None, + page: None, + })) +} + /// Preview a version before publishing it. /// /// The document a version labelled `label` would hold, as a download. @@ -690,6 +928,66 @@ mod tests { ); } + #[test] + fn a_draft_counts_every_component_of_the_next_version_once() { + let document = + |components: serde_json::Value| serde_json::json!({ "components": components }); + let latest = document(serde_json::json!([ + { "name": "lodash", "version": "4.17.20", "purl": "pkg:npm/lodash@4.17.20" }, + { "name": "left-pad", "version": "1.3.0", "purl": "pkg:npm/left-pad@1.3.0" }, + { "name": "zlib", "version": "1.3", "purl": "pkg:generic/zlib@1.3" }, + // Two copies, one stays. + { "name": "minimist", "version": "1.2.5", "purl": "pkg:npm/minimist@1.2.5" }, + { "name": "minimist", "version": "1.2.8", "purl": "pkg:npm/minimist@1.2.8" }, + ])); + let next = document(serde_json::json!([ + { "name": "lodash", "version": "4.17.21", "purl": "pkg:npm/lodash@4.17.21" }, + { "name": "zlib", "version": "1.3", "purl": "pkg:generic/zlib@1.3" }, + { "name": "minimist", "version": "1.2.8", "purl": "pkg:npm/minimist@1.2.8" }, + { "name": "core", "group": "@angular", "version": "17.0.0", + "purl": "pkg:npm/%40angular/core@17.0.0" }, + { "name": "openssl", "version": "3.0.15" }, + ])); + + let changes = draft_changes(&latest, &next, "1.4.0"); + + assert_eq!(changes.against, "1.4.0"); + assert_eq!( + ( + changes.added, + changes.updated, + changes.removed, + changes.unchanged + ), + (2, 1, 2, 2) + ); + assert_eq!(changes.added + changes.updated + changes.unchanged, 5); + assert_eq!( + changes.added_names, + ["openssl 3.0.15", "@angular/core 17.0.0"] + ); + assert_eq!(changes.updated_names, ["lodash 4.17.21"]); + } + + #[test] + fn an_unchanged_version_changes_nothing() { + let next = serde_json::json!({ "components": [ + { "name": "zlib", "version": "1.3", "purl": "pkg:generic/zlib@1.3" }, + ] }); + + let changes = draft_changes(&next, &next, "1.4.0"); + + assert_eq!( + ( + changes.added, + changes.updated, + changes.removed, + changes.unchanged + ), + (0, 0, 0, 1) + ); + } + #[test] fn a_release_reads_as_active_until_it_is_ended() { let mut r = SbomRelease { diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index cbbdc61..19413ae 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -60,6 +60,7 @@ fn described_routes() -> OpenApiRouter { .routes(routes!(handlers::releases::end_release)) .routes(routes!(handlers::releases::publish_version)) .routes(routes!(handlers::releases::preview_version)) + .routes(routes!(handlers::releases::version_draft)) // What connected suppliers offer, the customer's side (#1028). .routes(routes!(handlers::offers::list_offers)) .routes(routes!(handlers::offers::accept_offer)) diff --git a/compliance-agent/tests/connections.rs b/compliance-agent/tests/connections.rs index 584cb8d..8c57d76 100644 --- a/compliance-agent/tests/connections.rs +++ b/compliance-agent/tests/connections.rs @@ -23,7 +23,7 @@ use compliance_agent::api::handlers::connections::list_connections; use compliance_agent::api::handlers::offers::{accept_offer, decline_offer, list_offers}; use compliance_agent::api::handlers::onboarding::delete_target; use compliance_agent::api::handlers::releases::{ - create_release, end_release, list_releases, publish_version, + create_release, end_release, list_releases, publish_version, version_draft, }; use compliance_agent::database::DatabasePool; use compliance_core::models::{OnboardedTarget, TargetType}; @@ -211,6 +211,7 @@ async fn release_call( post(end_release), ) .route("/api/v1/targets/{id}/versions", post(publish_version)) + .route("/api/v1/targets/{id}/versions/draft", get(version_draft)) .route("/api/v1/sbom-offers", get(list_offers)) .route("/api/v1/targets/{id}", axum::routing::delete(delete_target)) .route("/api/v1/sbom-offers/{id}/accept", post(accept_offer)) @@ -785,6 +786,24 @@ async fn accepted_releases_receive_each_published_version() { listed["data"]["releases"][0]["delivered_label"], "1.5.0", "the supplier sees it" ); + let customers = |listed: &serde_json::Value| { + listed["data"]["versions"] + .as_array() + .unwrap() + .iter() + .map(|v| { + ( + v["label"].as_str().unwrap().to_string(), + v["customers"].as_u64().unwrap(), + ) + }) + .collect::>() + }; + assert_eq!( + customers(&listed), + [("1.5.0".to_string(), 1), ("1.4.0".to_string(), 1)], + "each version counts the customer it reached" + ); // Ended, nothing more arrives. let (status, _) = release_call( @@ -803,7 +822,61 @@ async fn accepted_releases_receive_each_published_version() { received.supplier.as_ref().unwrap().version.as_deref(), Some("1.5.0") ); + let (_, listed) = release_call(agent.clone(), "t-1", &releases, serde_json::Value::Null).await; + assert_eq!(customers(&listed)[0], ("1.6.0".to_string(), 0)); + + // The next version's draft, against 1.6.0. + supplier_db + .sbom_entries() + .insert_one(SbomEntry::new( + product.clone(), + "mbedtls".into(), + "3.6.2".into(), + "generic".into(), + )) + .await + .unwrap(); + let (status, draft) = release_call( + agent.clone(), + "t-1", + &format!("{versions}/draft"), + serde_json::Value::Null, + ) + .await; + assert_eq!(status, StatusCode::OK, "{draft}"); + assert_eq!(draft["data"]["components"], 2); + assert!(draft["data"]["blocked"].is_null()); + let changes = &draft["data"]["changes"]; + assert_eq!(changes["against"], "1.6.0"); + assert_eq!( + (changes["added"].as_u64(), changes["unchanged"].as_u64()), + (Some(1), Some(1)) + ); + assert_eq!(changes["added_names"], json!(["mbedtls 3.6.2"])); agent.db_pool.drop_tenant("t-1").await.ok(); agent.db_pool.drop_tenant("t-2").await.ok(); } + +#[tokio::test] +async fn a_draft_without_components_says_why() { + let base = fake_registry().await; + let Some(agent) = agent(&base).await else { + return; + }; + let product = stored_target(&agent, "t-1", "DR-4 Firmware", false).await; + + let (status, draft) = release_call( + agent.clone(), + "t-1", + &format!("/api/v1/targets/{product}/versions/draft"), + serde_json::Value::Null, + ) + .await; + + assert_eq!(status, StatusCode::OK, "{draft}"); + assert_eq!(draft["data"]["blocked"], "empty"); + assert_eq!(draft["data"]["components"], 0); + assert!(draft["data"]["changes"].is_null()); + agent.db_pool.drop_tenant("t-1").await.ok(); +} diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index 6ba8940..b0df8e6 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -216,8 +216,14 @@ customer follow. answers `422` (`empty`). - `GET …/versions/preview?label=…` returns that document without publishing it. +- `GET …/versions/draft` describes the next version without publishing it: + how many components it would list, when the scan it comes from finished, + and how many components it adds, updates and removes compared with the + latest published version, with a few of their names. When it cannot be + published, `blocked` says why (`empty` or `too_many_components`). - `GET /api/v1/targets/{id}/releases` lists the releases (active ones first) - and the published versions. + and the published versions. Each version counts the customers it was + delivered to (`customers`). Releasing, ending and publishing are recorded in your workspace's audit log. -- 2.54.1 From b05154adcec2444814aa3b3f2ed8df71d15ff7d6 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:02:15 +0100 Subject: [PATCH 2/3] fix(registry): a 404 for a tenant's connections lists none (#1028) Before tenant-registry#138 the registry has no connections route; the release screen would warn on every visit that connections cannot be read. A 404 now lists no connections; other errors still answer 503. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9 --- compliance-agent/src/registry.rs | 8 +++++++- compliance-agent/tests/connections.rs | 12 +++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/compliance-agent/src/registry.rs b/compliance-agent/src/registry.rs index 59c95af..e9e9267 100644 --- a/compliance-agent/src/registry.rs +++ b/compliance-agent/src/registry.rs @@ -631,7 +631,8 @@ impl RegistryClient { /// /// # Errors /// - /// The registry could not be asked, or answered with an error. + /// The registry could not be asked, or answered with an error other than + /// 404. pub async fn active_connections(&self, tenant_id: &str) -> Result, String> { #[derive(Deserialize)] struct Page { @@ -650,6 +651,11 @@ impl RegistryClient { .send() .await .map_err(|e| format!("connection list failed: {e}"))?; + // A registry without connections for the tenant (or, before + // tenant-registry#138, without the route) has none to list. + if resp.status() == reqwest::StatusCode::NOT_FOUND { + return Ok(Vec::new()); + } if !resp.status().is_success() { return Err(format!("connection list returned {}", resp.status())); } diff --git a/compliance-agent/tests/connections.rs b/compliance-agent/tests/connections.rs index 8c57d76..d190ab0 100644 --- a/compliance-agent/tests/connections.rs +++ b/compliance-agent/tests/connections.rs @@ -32,7 +32,8 @@ use compliance_core::{OrgRole, TenantContext, TenantStatus}; use common::dev_config; /// A registry where tenant `t-1` is connected to two workspaces and -/// connection `c-ended` has ended; `t-down` cannot be listed; `t-3` does not +/// connection `c-ended` has ended; `t-down` cannot be listed, `t-unknown` +/// is not known (404); `t-3` does not /// hold Prüfwerk. async fn fake_registry() -> String { let app = Router::new() @@ -45,6 +46,7 @@ async fn fake_registry() -> String { { "id": "c-1", "peer_tenant_id": "t-2", "peer_name": "beispiel Maschinenbau" }, ] }))), "t-down" => Err(StatusCode::INTERNAL_SERVER_ERROR), + "t-unknown" => Err(StatusCode::NOT_FOUND), _ => Ok(Json(serde_json::json!({ "items": [] }))), } }), @@ -148,6 +150,14 @@ async fn the_client_lists_and_checks_connections() { assert_eq!(listed.len(), 2); assert_eq!(listed[1].peer_tenant_id, "t-2"); assert!(registry.active_connections("t-down").await.is_err()); + assert!( + registry + .active_connections("t-unknown") + .await + .unwrap() + .is_empty(), + "a 404 lists none" + ); let c1 = registry.connection("c-1").await.unwrap().unwrap(); assert_eq!(c1.peer_of("t-1"), Some("t-2")); -- 2.54.1 From 1ca85ca8590a80b648343fd8f4da945593d3e4f3 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:05:08 +0100 Subject: [PATCH 3/3] fix(sbom): a released SBOM's purls name no download or VCS address (#1028) Yocto recipes give pkg:generic purls a download_url or vcs_url qualifier, which can name the supplier's own git server or feed. The released document passed them on in purl and bom-ref. They are now left out (download_url, vcs_url, repository_url); other qualifiers and the subpath stay. A bom-ref that becomes a duplicate gets " (2)" appended. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9 --- compliance-core/src/sbom_docs.rs | 132 ++++++++++++++++++++++++++++++- 1 file changed, 130 insertions(+), 2 deletions(-) diff --git a/compliance-core/src/sbom_docs.rs b/compliance-core/src/sbom_docs.rs index e91f050..337ba30 100644 --- a/compliance-core/src/sbom_docs.rs +++ b/compliance-core/src/sbom_docs.rs @@ -456,19 +456,84 @@ pub fn released_cyclonedx( let mut doc = cdx_frame(product.name, entries); doc["metadata"]["component"]["version"] = serde_json::json!(product.version); doc["metadata"]["component"]["supplier"] = serde_json::json!({ "name": product.supplier }); - let components: Vec = cdx_components(entries) + let mut components: Vec = cdx_components(entries) .into_iter() .map(released_component) .collect(); + unique_refs(&mut components); cdx_dependencies(&mut doc, &components); doc["components"] = serde_json::Value::Array(components); doc } -/// `component` with only [`RELEASED_COMPONENT_KEYS`], and no licence text. +/// Purl qualifiers that say where a component was fetched from. A released +/// SBOM leaves them out: they can name the supplier's own servers (a Yocto +/// recipe's `vcs_url`, an internal feed). +const ADDRESS_QUALIFIERS: [&str; 3] = ["download_url", "vcs_url", "repository_url"]; + +/// `purl` without its [`ADDRESS_QUALIFIERS`]; anything that is not a purl +/// as it is. +fn without_addresses(purl: &str) -> String { + if !purl.starts_with("pkg:") { + return purl.to_string(); + } + let (body, subpath) = match purl.split_once('#') { + Some((body, subpath)) => (body, Some(subpath)), + None => (purl, None), + }; + let Some((base, qualifiers)) = body.split_once('?') else { + return purl.to_string(); + }; + let kept: Vec<&str> = qualifiers + .split('&') + .filter(|q| { + let key = q.split_once('=').map_or(*q, |(key, _)| key); + !ADDRESS_QUALIFIERS.contains(&key) + }) + .collect(); + let mut out = base.to_string(); + if !kept.is_empty() { + out.push('?'); + out.push_str(&kept.join("&")); + } + if let Some(subpath) = subpath { + out.push('#'); + out.push_str(subpath); + } + out +} + +/// Make each component's `bom-ref` unique again: two components can differ +/// only in a qualifier [`without_addresses`] removed. A repeated one gets +/// ` (2)`, ` (3)`, ... appended. +fn unique_refs(components: &mut [serde_json::Value]) { + let mut seen: std::collections::HashMap = std::collections::HashMap::new(); + for component in components { + let Some(reference) = component["bom-ref"].as_str().map(str::to_string) else { + continue; + }; + let count = seen.entry(reference.clone()).or_insert(0); + *count += 1; + if *count > 1 { + component["bom-ref"] = serde_json::json!(format!("{reference} ({count})")); + } + } +} + +/// `component` with only [`RELEASED_COMPONENT_KEYS`], no licence text and +/// no addresses in its purl. fn released_component(mut component: serde_json::Value) -> serde_json::Value { if let Some(fields) = component.as_object_mut() { fields.retain(|key, _| RELEASED_COMPONENT_KEYS.contains(&key.as_str())); + for key in ["purl", "bom-ref"] { + if let Some(stripped) = fields + .get(key) + .and_then(|v| v.as_str()) + .map(without_addresses) + { + fields.insert(key.to_string(), serde_json::Value::String(stripped)); + } + } let licenses = fields .get_mut("licenses") .and_then(serde_json::Value::as_array_mut); @@ -808,6 +873,69 @@ mod tests { assert_eq!(doc["dependencies"][0]["dependsOn"][0], component["bom-ref"]); } + #[test] + fn a_released_purl_names_no_address() { + let entry = |purl: &str| { + let mut e = SbomEntry::new("t".into(), "pump-fw".into(), "1.0".into(), "yocto".into()); + e.purl = Some(purl.into()); + e + }; + let entries = [ + entry("pkg:generic/pump-fw@1.0?vcs_url=git%2Bhttps%3A%2F%2Fgit.internal.example%2Fpump-fw.git"), + entry("pkg:generic/pump-fw@1.0?download_url=http%3A%2F%2Fdl.internal.example%2Fpump.tgz&arch=arm"), + ]; + let product = ReleasedProduct { + name: "DR-4 Firmware", + version: "1.4.0", + supplier: "Test Antriebstechnik", + }; + + let doc = released_cyclonedx(&entries, &product); + + assert!(!doc.to_string().contains("internal.example"), "{doc}"); + let purls: Vec<&str> = doc["components"] + .as_array() + .unwrap() + .iter() + .map(|c| c["purl"].as_str().unwrap()) + .collect(); + assert_eq!( + purls, + [ + "pkg:generic/pump-fw@1.0", + "pkg:generic/pump-fw@1.0?arch=arm" + ] + ); + assert_eq!( + without_addresses("pkg:npm/lodash@4.17.21"), + "pkg:npm/lodash@4.17.21" + ); + assert_eq!( + without_addresses("pkg:generic/a@1?vcs_url=x#src/lib"), + "pkg:generic/a@1#src/lib" + ); + } + + #[test] + fn released_bom_refs_stay_unique() { + let mut components = vec![ + serde_json::json!({ "bom-ref": "pkg:generic/a@1" }), + serde_json::json!({ "bom-ref": "pkg:generic/a@1" }), + serde_json::json!({ "bom-ref": "pkg:generic/b@1" }), + ]; + + unique_refs(&mut components); + + let refs: Vec<&str> = components + .iter() + .map(|c| c["bom-ref"].as_str().unwrap()) + .collect(); + assert_eq!( + refs, + ["pkg:generic/a@1", "pkg:generic/a@1 (2)", "pkg:generic/b@1"] + ); + } + #[test] fn both_formats_list_every_component() { let mut e = SbomEntry::new("t".into(), "lwIP".into(), "2.1.2".into(), "embedded".into()); -- 2.54.1