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.