From c8a13fecad01607b7c9f3cc98816a14cadb53bac Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Thu, 19 Nov 2026 12:35:08 +0000 Subject: [PATCH] feat(releases): release a target to a connected workspace and publish versions (#1028) (#1063) --- compliance-agent/src/api/handlers/mod.rs | 1 + .../src/api/handlers/onboarding.rs | 2 + compliance-agent/src/api/handlers/releases.rs | 631 ++++++++++++++++++ compliance-agent/src/api/routes.rs | 8 + compliance-agent/tests/connections.rs | 136 +++- compliance-agent/tests/integration/api/mod.rs | 1 + .../tests/integration/api/releases.rs | 143 ++++ docs/guide/sbom.md | 29 + 8 files changed, 950 insertions(+), 1 deletion(-) create mode 100644 compliance-agent/src/api/handlers/releases.rs create mode 100644 compliance-agent/tests/integration/api/releases.rs diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index 5a8f856..4466474 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -28,6 +28,7 @@ pub mod oscal; pub mod pentest_handlers; pub mod platform; pub mod projects; +pub mod releases; pub use pentest_handlers as pentest; pub mod sbom; pub mod sbom_ecosystems; diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index f2b980d..7ab70fc 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -708,6 +708,8 @@ pub async fn delete_target( for collection in [ super::supplier_invites::SupplierInvite::COLLECTION, super::supplier_invites::SupplierUpload::COLLECTION, + super::releases::SbomRelease::COLLECTION, + super::releases::SbomVersion::COLLECTION, ] { let _ = db .raw_collection(collection) diff --git a/compliance-agent/src/api/handlers/releases.rs b/compliance-agent/src/api/handlers/releases.rs new file mode 100644 index 0000000..6a90447 --- /dev/null +++ b/compliance-agent/src/api/handlers/releases.rs @@ -0,0 +1,631 @@ +//! SBOM releases, the supplier's side (#1028): a workspace releases one of +//! its targets to a connected workspace (tenant-registry#138) and publishes +//! versions of it. +//! +//! A release names the connection it goes over; a version is the target's +//! SBOM at the time, as the stripped CycloneDX a customer may see +//! ([`compliance_core::sbom_docs::released_cyclonedx`]): what identifies each +//! component, its licences and hashes, nothing of the findings. Both stay in +//! the supplier's own database and artifact store; delivering a version to +//! the customers who accepted the release is the customer side's work. + +use axum::extract::{Extension, Path, Query}; +use axum::http::{header, StatusCode}; +use axum::response::IntoResponse; +use axum::Json; +use chrono::{DateTime, Utc}; +use futures_util::TryStreamExt; +use mongodb::bson::{doc, oid::ObjectId, DateTime as BsonDateTime}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use compliance_core::models::{OnboardedTarget, SbomEntry}; +use compliance_core::sbom_docs::{released_cyclonedx, ReleasedProduct}; +use compliance_core::tenant_ctx::TenantCtx; + +use super::dto::{tenant_db, AgentExt}; +use super::sbom::MAX_EXPORT_COMPONENTS; +use super::ApiResponse; +use crate::agent::ComplianceAgent; +use crate::database::Database; + +/// The longest version label accepted. +const MAX_LABEL_CHARS: usize = 64; + +/// A release of a target to a connected workspace, as stored. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SbomRelease { + #[serde(rename = "_id")] + pub id: ObjectId, + /// The target released. + pub target_id: String, + /// The connection it goes over. + pub connection_id: String, + /// The other workspace's display name when it was released. + pub peer_name: String, + pub created_by: String, + pub created_at: BsonDateTime, + /// When it was ended; `None` while it is not. + #[serde(default)] + pub ended_at: Option, + #[serde(default)] + pub ended_by: Option, +} + +impl SbomRelease { + /// The collection, in the supplier's own database. + pub const COLLECTION: &'static str = "sbom_releases"; +} + +/// A published version of a target's SBOM, as stored. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SbomVersion { + #[serde(rename = "_id")] + pub id: ObjectId, + pub target_id: String, + /// The supplier's label for it, such as `1.4.0`. + pub label: String, + /// How many components it lists. + pub components: i64, + /// The SHA-256 of the document: a version with the same content is + /// never delivered twice. + pub content_hash: String, + /// Where the document is, in the target's upload folder. + pub stored_path: String, + pub created_by: String, + pub created_at: BsonDateTime, +} + +impl SbomVersion { + /// The collection, in the supplier's own database. + pub const COLLECTION: &'static str = "sbom_versions"; +} + +/// A release as the supplier reads it. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct ReleaseView { + pub id: String, + pub connection_id: String, + pub peer_name: String, + pub created_at: DateTime, + pub ended_at: Option>, + /// Not ended. + pub active: bool, +} + +impl From for ReleaseView { + fn from(r: SbomRelease) -> Self { + Self { + active: r.ended_at.is_none(), + id: r.id.to_hex(), + connection_id: r.connection_id, + peer_name: r.peer_name, + created_at: r.created_at.to_chrono(), + ended_at: r.ended_at.map(BsonDateTime::to_chrono), + } + } +} + +/// A version as the supplier reads it. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct VersionView { + pub id: String, + pub label: String, + pub components: i64, + pub created_at: DateTime, + pub created_by: String, +} + +impl From for VersionView { + fn from(v: SbomVersion) -> Self { + Self { + id: v.id.to_hex(), + label: v.label, + components: v.components, + created_at: v.created_at.to_chrono(), + created_by: v.created_by, + } + } +} + +/// A target's releases and published versions. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Releases { + /// Active ones first, each group newest first. + pub releases: Vec, + /// Newest first. + pub versions: Vec, +} + +/// The body of a release. +#[derive(Debug, Deserialize, utoipa::ToSchema)] +pub struct CreateRelease { + /// The connection to release over (`GET /api/v1/connections`). + pub connection_id: String, +} + +/// The body of a publication, and the query of its preview. +#[derive(Debug, Deserialize, utoipa::ToSchema, utoipa::IntoParams)] +pub struct VersionLabel { + /// The version's label, such as `1.4.0`. + pub label: String, +} + +fn releases(db: &Database) -> mongodb::Collection { + db.inner().collection(SbomRelease::COLLECTION) +} + +fn versions(db: &Database) -> mongodb::Collection { + db.inner().collection(SbomVersion::COLLECTION) +} + +fn internal(e: E) -> StatusCode { + tracing::error!("release endpoint failed: {e}"); + StatusCode::INTERNAL_SERVER_ERROR +} + +/// A refusal with its code, as `{"error": …}`. +fn refused(status: StatusCode, code: &str) -> axum::response::Response { + (status, Json(serde_json::json!({ "error": code }))).into_response() +} + +/// `label` trimmed, or `None` when it is empty, too long or holds a control +/// character. +fn checked_label(label: &str) -> Option<&str> { + let label = label.trim(); + let usable = !label.is_empty() + && label.chars().count() <= MAX_LABEL_CHARS + && !label.chars().any(char::is_control); + usable.then_some(label) +} + +/// Target `id` of the tenant behind `db`. +/// +/// # Errors +/// +/// 404 when it is not an id or there is no such target. +async fn target(db: &Database, id: &str) -> Result { + let oid = ObjectId::parse_str(id).map_err(|_| StatusCode::NOT_FOUND)?; + db.onboarded_targets() + .find_one(doc! { "_id": oid }) + .await + .map_err(internal)? + .ok_or(StatusCode::NOT_FOUND) +} + +/// Record `action` about `target` in the platform's audit log, in the +/// background; the registry being down never fails the change itself. +fn audit( + agent: &ComplianceAgent, + tenant: &TenantCtx, + action: &str, + target: &OnboardedTarget, + metadata: serde_json::Value, +) { + let Some(registry) = agent.registry.clone() else { + return; + }; + let id = target.id.map(|o| o.to_hex()).unwrap_or_default(); + let entry = crate::registry::AuditEntry::by(&tenant.0, action, metadata) + .about_target(&id, &target.name); + tokio::spawn(async move { + if let Err(e) = registry.append_audit(&entry).await { + tracing::warn!(target_id = %entry.target_id, "release not audited: {e}"); + } + }); +} + +/// The workspace's name as its releases name the supplier: the registry's +/// display name, else (development, or the registry down) its slug. +async fn supplier_name(agent: &ComplianceAgent, tenant: &TenantCtx) -> String { + let named = match agent.registry.as_ref() { + Some(registry) => registry + .get_tenant(&tenant.0.tenant_id) + .await + .ok() + .flatten() + .map(|t| t.name) + .filter(|n| !n.trim().is_empty()), + None => None, + }; + named.unwrap_or_else(|| tenant.0.tenant_slug.clone()) +} + +/// The released document of target `target` labelled `label`: its SBOM +/// entries as the stripped CycloneDX, and how many components it lists. +/// +/// # Errors +/// +/// 413 past [`MAX_EXPORT_COMPONENTS`]; 422 for a target without +/// components. +async fn released_document( + agent: &ComplianceAgent, + tenant: &TenantCtx, + db: &Database, + target: &OnboardedTarget, + 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 supplier = supplier_name(agent, tenant).await; + let product = ReleasedProduct { + name: &target.name, + version: label, + supplier: &supplier, + }; + let document = released_cyclonedx(&entries, &product); + let components = document["components"].as_array().map_or(0, Vec::len); + Ok((document, components)) +} + +/// A target's releases to connected workspaces and its published versions. +#[utoipa::path( + get, + path = "/api/v1/targets/{id}/releases", + tag = "Targets", + params(("id" = String, Path, description = "The target's id")), + responses( + (status = 200, description = "Its releases and versions (`data`)"), + (status = 404, description = "No such target"), + (status = 401, description = "No valid bearer token"), + ) +)] +#[tracing::instrument(skip_all, fields(target_id = %id))] +pub async fn list_releases( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, +) -> Result>, StatusCode> { + let db = tenant_db(&agent, &tenant).await?; + target(&db, &id).await?; + let mut listed: Vec = releases(&db) + .find(doc! { "target_id": &id }) + .sort(doc! { "created_at": -1, "_id": -1 }) + .await + .map_err(internal)? + .try_collect() + .await + .map_err(internal)?; + // Active ones first; the sort keeps each group newest first. + listed.sort_by_key(|r| r.ended_at.is_some()); + let published: Vec = versions(&db) + .find(doc! { "target_id": &id }) + .sort(doc! { "created_at": -1, "_id": -1 }) + .await + .map_err(internal)? + .try_collect() + .await + .map_err(internal)?; + Ok(Json(ApiResponse { + data: Releases { + releases: listed.into_iter().map(ReleaseView::from).collect(), + versions: published.into_iter().map(VersionView::from).collect(), + }, + total: None, + page: None, + })) +} + +/// Release a target to a connected workspace. +/// +/// The connection must be one of the workspace's active connections +/// (`GET /api/v1/connections`). A target is released over a connection once +/// at a time. The other workspace is offered the release; versions reach it +/// once it accepts. +#[utoipa::path( + post, + path = "/api/v1/targets/{id}/releases", + tag = "Targets", + params(("id" = String, Path, description = "The target's id")), + request_body = CreateRelease, + responses( + (status = 201, description = "Released"), + (status = 404, description = "No such target"), + (status = 409, description = "Already released over this connection (`released`)"), + (status = 422, description = "Not an active connection of the workspace (`unknown_connection`)"), + (status = 503, description = "The registry cannot be asked"), + (status = 401, description = "No valid bearer token"), + (status = 403, description = "A read-only role"), + ) +)] +#[tracing::instrument(skip_all, fields(target_id = %id))] +pub async fn create_release( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, + Json(body): Json, +) -> Result { + let db = tenant_db(&agent, &tenant).await?; + let released = target(&db, &id).await?; + let connections = match agent.registry.as_ref() { + Some(registry) => registry + .active_connections(&tenant.0.tenant_id) + .await + .map_err(|e| { + tracing::error!("connections unavailable: {e}"); + StatusCode::SERVICE_UNAVAILABLE + })?, + None => Vec::new(), + }; + let Some(connection) = connections + .into_iter() + .find(|c| c.id == body.connection_id.trim()) + else { + return Ok(refused( + StatusCode::UNPROCESSABLE_ENTITY, + "unknown_connection", + )); + }; + let open = releases(&db) + .count_documents( + doc! { "target_id": &id, "connection_id": &connection.id, "ended_at": null }, + ) + .await + .map_err(internal)?; + if open > 0 { + return Ok(refused(StatusCode::CONFLICT, "released")); + } + let release = SbomRelease { + id: ObjectId::new(), + target_id: id, + connection_id: connection.id, + peer_name: connection.peer_name, + created_by: tenant.0.user_id.clone(), + created_at: BsonDateTime::now(), + ended_at: None, + ended_by: None, + }; + releases(&db).insert_one(&release).await.map_err(internal)?; + audit( + &agent, + &tenant, + "pruefwerk.sbom_release_created", + &released, + serde_json::json!({ "peer_name": release.peer_name }), + ); + Ok(( + StatusCode::CREATED, + Json(ApiResponse { + data: ReleaseView::from(release), + total: None, + page: None, + }), + ) + .into_response()) +} + +/// End a release. +/// +/// No new version goes over it. What the other workspace already received +/// stays with it. Ending one already ended keeps the first end. +#[utoipa::path( + post, + path = "/api/v1/targets/{id}/releases/{release}/end", + tag = "Targets", + params( + ("id" = String, Path, description = "The target's id"), + ("release" = String, Path, description = "The release's id"), + ), + responses( + (status = 200, description = "The release, ended"), + (status = 404, description = "No such target or release"), + (status = 401, description = "No valid bearer token"), + (status = 403, description = "A read-only role"), + ) +)] +#[tracing::instrument(skip_all, fields(target_id = %id))] +pub async fn end_release( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path((id, release)): Path<(String, String)>, +) -> Result>, StatusCode> { + let db = tenant_db(&agent, &tenant).await?; + let released = target(&db, &id).await?; + let rid = ObjectId::parse_str(&release).map_err(|_| StatusCode::NOT_FOUND)?; + let changed = releases(&db) + .update_one( + doc! { "_id": rid, "target_id": &id, "ended_at": null }, + doc! { "$set": { "ended_at": BsonDateTime::now(), "ended_by": &tenant.0.user_id } }, + ) + .await + .map_err(internal)?; + let ended = releases(&db) + .find_one(doc! { "_id": rid, "target_id": &id }) + .await + .map_err(internal)? + .ok_or(StatusCode::NOT_FOUND)?; + if changed.modified_count > 0 { + audit( + &agent, + &tenant, + "pruefwerk.sbom_release_ended", + &released, + serde_json::json!({ "peer_name": ended.peer_name }), + ); + } + Ok(Json(ApiResponse { + data: ReleaseView::from(ended), + total: None, + page: None, + })) +} + +/// Publish a version of a target's SBOM. +/// +/// Built from the target's components now, as the stripped CycloneDX a +/// customer may see: what identifies each component, its licences and +/// hashes, no vulnerabilities, findings, paths or internal ids. The +/// workspace's name is its supplier, the label its version. Labels are +/// unique per target. +#[utoipa::path( + post, + path = "/api/v1/targets/{id}/versions", + tag = "Targets", + params(("id" = String, Path, description = "The target's id")), + request_body = VersionLabel, + responses( + (status = 201, description = "Published"), + (status = 404, description = "No such target"), + (status = 409, description = "The label is taken (`label_taken`)"), + (status = 413, description = "Too many components (`too_many_components`)"), + (status = 422, description = "No usable label (`label`), or no components (`empty`)"), + (status = 401, description = "No valid bearer token"), + (status = 403, description = "A read-only role"), + ) +)] +#[tracing::instrument(skip_all, fields(target_id = %id))] +pub async fn publish_version( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, + Json(body): Json, +) -> Result { + let Some(label) = checked_label(&body.label) else { + return Ok(refused(StatusCode::UNPROCESSABLE_ENTITY, "label")); + }; + let db = tenant_db(&agent, &tenant).await?; + let published = target(&db, &id).await?; + let taken = versions(&db) + .count_documents(doc! { "target_id": &id, "label": label }) + .await + .map_err(internal)?; + if taken > 0 { + return Ok(refused(StatusCode::CONFLICT, "label_taken")); + } + let (document, components) = + match released_document(&agent, &tenant, &db, &published, label).await { + Ok(built) => built, + Err(refusal) => return Ok(refusal), + }; + let bytes = serde_json::to_vec_pretty(&document).map_err(internal)?; + let content_hash = hex::encode(Sha256::digest(&bytes)); + let stored = + crate::targets::store_upload(&agent, &id, &format!("release-{label}.cdx.json"), &bytes) + .map_err(internal)?; + let version = SbomVersion { + id: ObjectId::new(), + target_id: id, + label: label.to_string(), + components: i64::try_from(components).unwrap_or(i64::MAX), + content_hash, + stored_path: stored.to_string_lossy().into_owned(), + created_by: tenant.0.user_id.clone(), + created_at: BsonDateTime::now(), + }; + versions(&db).insert_one(&version).await.map_err(internal)?; + audit( + &agent, + &tenant, + "pruefwerk.sbom_version_published", + &published, + serde_json::json!({ "label": version.label, "components": version.components }), + ); + Ok(( + StatusCode::CREATED, + Json(ApiResponse { + data: VersionView::from(version), + total: None, + page: None, + }), + ) + .into_response()) +} + +/// Preview a version before publishing it. +/// +/// The document a version labelled `label` would hold, as a download. +/// Nothing is stored. +#[utoipa::path( + get, + path = "/api/v1/targets/{id}/versions/preview", + tag = "Targets", + params(("id" = String, Path, description = "The target's id"), VersionLabel), + responses( + (status = 200, description = "The CycloneDX document"), + (status = 404, description = "No such target"), + (status = 413, description = "Too many components (`too_many_components`)"), + (status = 422, description = "No usable label (`label`), or no components (`empty`)"), + (status = 401, description = "No valid bearer token"), + ) +)] +#[tracing::instrument(skip_all, fields(target_id = %id))] +pub async fn preview_version( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, + Query(query): Query, +) -> Result { + let Some(label) = checked_label(&query.label) else { + return Ok(refused(StatusCode::UNPROCESSABLE_ENTITY, "label")); + }; + let db = tenant_db(&agent, &tenant).await?; + let previewed = target(&db, &id).await?; + let document = match released_document(&agent, &tenant, &db, &previewed, label).await { + Ok((document, _)) => document, + Err(refusal) => return Ok(refusal), + }; + Ok(( + [( + header::CONTENT_DISPOSITION, + "attachment; filename=\"release-preview.cdx.json\"", + )], + Json(document), + ) + .into_response()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_label_is_trimmed_and_bounded() { + assert_eq!(checked_label(" 1.4.0 "), Some("1.4.0")); + assert_eq!(checked_label(" "), None); + assert_eq!(checked_label(&"9".repeat(65)), None); + assert_eq!(checked_label("1.4\n0"), None); + assert_eq!( + checked_label(&"ä".repeat(64)), + Some("ä".repeat(64).as_str()) + ); + } + + #[test] + fn a_release_reads_as_active_until_it_is_ended() { + let mut r = SbomRelease { + id: ObjectId::new(), + target_id: "t1".into(), + connection_id: "c1".into(), + peer_name: "Beispiel Maschinenbau".into(), + created_by: "u1".into(), + created_at: BsonDateTime::now(), + ended_at: None, + ended_by: None, + }; + assert!(ReleaseView::from(r.clone()).active); + r.ended_at = Some(BsonDateTime::now()); + assert!(!ReleaseView::from(r).active); + } +} diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 3d1a7d7..bcb8ac5 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -52,6 +52,14 @@ fn described_routes() -> OpenApiRouter { .routes(routes!(handlers::machine::machine_scan_changes)) .routes(routes!(handlers::supply_chain::get_supply_chain)) .routes(routes!(handlers::connections::list_connections)) + // SBOM releases to connected workspaces, the supplier's side (#1028). + .routes(routes!( + handlers::releases::list_releases, + handlers::releases::create_release + )) + .routes(routes!(handlers::releases::end_release)) + .routes(routes!(handlers::releases::publish_version)) + .routes(routes!(handlers::releases::preview_version)) .routes(routes!(handlers::supply_chain::project_documents)) // The customer's arrangement of the supply chain (#1052). .routes(routes!( diff --git a/compliance-agent/tests/connections.rs b/compliance-agent/tests/connections.rs index d9de413..1a49221 100644 --- a/compliance-agent/tests/connections.rs +++ b/compliance-agent/tests/connections.rs @@ -14,13 +14,15 @@ use axum::body::Body; use axum::extract::{Path, Request}; use axum::http::StatusCode; use axum::middleware::{from_fn, Next}; -use axum::routing::get; +use axum::routing::{get, post}; use axum::{Extension, Json, Router}; use tower::ServiceExt; use compliance_agent::agent::ComplianceAgent; use compliance_agent::api::handlers::connections::list_connections; +use compliance_agent::api::handlers::releases::{create_release, end_release}; use compliance_agent::database::DatabasePool; +use compliance_core::models::{OnboardedTarget, TargetType}; use compliance_core::{OrgRole, TenantContext, TenantStatus}; use common::dev_config; @@ -165,3 +167,135 @@ async fn the_workspace_sees_each_connection_by_name_only() { let (status, _) = list(agent, "t-down").await; assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); } + +/// `method` `uri` with JSON `body` through the release handlers, as a member +/// of `tenant`. +async fn release_call( + agent: Arc, + tenant: &str, + uri: &str, + body: serde_json::Value, +) -> (StatusCode, serde_json::Value) { + let ctx = member(tenant); + let inject = move |mut req: Request, next: Next| { + let ctx = ctx.clone(); + async move { + req.extensions_mut().insert(ctx); + next.run(req).await + } + }; + let app = Router::new() + .route("/api/v1/targets/{id}/releases", post(create_release)) + .route( + "/api/v1/targets/{id}/releases/{release}/end", + post(end_release), + ) + .layer(Extension(agent)) + .layer(from_fn(inject)); + let resp = app + .oneshot( + Request::post(uri) + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + let status = resp.status(); + let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16) + .await + .unwrap(); + (status, serde_json::from_slice(&bytes).unwrap_or_default()) +} + +#[tokio::test] +async fn a_target_is_released_once_over_an_active_connection() { + let base = fake_registry().await; + let Some(agent) = agent(&base).await else { + return; + }; + let db = agent.db_pool.for_tenant_id("t-1").await.unwrap(); + let id = db + .onboarded_targets() + .insert_one(OnboardedTarget::new( + "DR-4 Firmware".into(), + TargetType::FirmwareRtos, + )) + .await + .unwrap() + .inserted_id + .as_object_id() + .unwrap() + .to_hex(); + let uri = format!("/api/v1/targets/{id}/releases"); + + let (status, body) = release_call( + agent.clone(), + "t-1", + &uri, + serde_json::json!({ "connection_id": "c-1" }), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + assert_eq!(body["data"]["peer_name"], "beispiel Maschinenbau"); + assert_eq!(body["data"]["active"], true); + assert!( + !body.to_string().contains("t-2"), + "never the other tenant's id" + ); + let release = body["data"]["id"].as_str().unwrap().to_string(); + + let (status, body) = release_call( + agent.clone(), + "t-1", + &uri, + serde_json::json!({ "connection_id": "c-1" }), + ) + .await; + assert_eq!( + (status, body["error"].as_str()), + (StatusCode::CONFLICT, Some("released")) + ); + let (status, body) = release_call( + agent.clone(), + "t-1", + &uri, + serde_json::json!({ "connection_id": "c-unknown" }), + ) + .await; + assert_eq!( + (status, body["error"].as_str()), + (StatusCode::UNPROCESSABLE_ENTITY, Some("unknown_connection")) + ); + + let end = format!("{uri}/{release}/end"); + let (status, body) = release_call(agent.clone(), "t-1", &end, serde_json::json!({})).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["data"]["active"], false); + let ended_at = body["data"]["ended_at"].clone(); + let (_, again) = release_call(agent.clone(), "t-1", &end, serde_json::json!({})).await; + assert_eq!(again["data"]["ended_at"], ended_at, "the first end is kept"); + + // Ended, it can be released again over the same connection. + let (status, _) = release_call( + agent.clone(), + "t-1", + &uri, + serde_json::json!({ "connection_id": "c-1" }), + ) + .await; + assert_eq!(status, StatusCode::CREATED); + + // Another workspace cannot reach this target's releases. + let (status, _) = release_call( + agent.clone(), + "t-2", + &uri, + serde_json::json!({ "connection_id": "c-1" }), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + + agent.db_pool.drop_tenant("t-1").await.ok(); + agent.db_pool.drop_tenant("t-2").await.ok(); +} diff --git a/compliance-agent/tests/integration/api/mod.rs b/compliance-agent/tests/integration/api/mod.rs index ff3a203..0333611 100644 --- a/compliance-agent/tests/integration/api/mod.rs +++ b/compliance-agent/tests/integration/api/mod.rs @@ -5,6 +5,7 @@ mod health; mod machine; mod onboarding; mod openapi; +mod releases; mod sbom; mod stats; mod supply_chain; diff --git a/compliance-agent/tests/integration/api/releases.rs b/compliance-agent/tests/integration/api/releases.rs new file mode 100644 index 0000000..6977f69 --- /dev/null +++ b/compliance-agent/tests/integration/api/releases.rs @@ -0,0 +1,143 @@ +use crate::common::TestServer; +use compliance_core::models::{SbomEntry, VulnRef}; +use serde_json::json; + +/// A target's id, created through the API. +async fn target(server: &TestServer, name: &str) -> String { + let resp = server + .post( + "/api/v1/targets", + &json!({ "name": name, "target_type": "firmware_rtos" }), + ) + .await; + assert_eq!(resp.status(), 200); + let body: serde_json::Value = resp.json().await.unwrap(); + body["data"]["_id"]["$oid"].as_str().unwrap().to_string() +} + +#[tokio::test] +async fn a_supplier_publishes_versions_of_a_stripped_sbom() { + let server = TestServer::start().await; + let id = target(&server, "DR-4 Firmware").await; + let publish = |label: &str| { + let (server, id, label) = (&server, id.clone(), label.to_string()); + async move { + server + .post( + &format!("/api/v1/targets/{id}/versions"), + &json!({ "label": label }), + ) + .await + } + }; + + // Nothing to publish before a scan found components. + let resp = publish("1.4.0").await; + assert_eq!(resp.status(), 422); + assert_eq!( + resp.json::().await.unwrap()["error"], + "empty" + ); + + 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 mut lwip = SbomEntry::new(id.clone(), "lwip".into(), "2.1.2".into(), "generic".into()); + lwip.purl = Some("pkg:generic/lwip@2.1.2".into()); + lwip.known_vulnerabilities = vec![VulnRef { + id: "CVE-2026-0001".into(), + source: "osv".into(), + severity: Some("HIGH".into()), + url: None, + exploitation: None, + aliases: Vec::new(), + }]; + let mbedtls = SbomEntry::new( + id.clone(), + "mbedtls".into(), + "3.6.2".into(), + "generic".into(), + ); + db.collection::("sbom_entries") + .insert_many([lwip, mbedtls]) + .await + .unwrap(); + + let resp = publish(" 1.4.0 ").await; + assert_eq!(resp.status(), 201); + let body: serde_json::Value = resp.json().await.unwrap(); + assert_eq!(body["data"]["label"], "1.4.0"); + assert_eq!(body["data"]["components"], 2); + + let resp = publish("1.4.0").await; + assert_eq!(resp.status(), 409); + assert_eq!( + resp.json::().await.unwrap()["error"], + "label_taken" + ); + assert_eq!(publish(" ").await.status(), 422); + + // The stored document is the stripped one. + let stored = db + .collection::("sbom_versions") + .find_one(mongodb::bson::doc! { "label": "1.4.0" }) + .await + .unwrap() + .unwrap(); + let text = std::fs::read_to_string(stored.get_str("stored_path").unwrap()).unwrap(); + let doc: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(doc["metadata"]["component"]["name"], "DR-4 Firmware"); + assert_eq!(doc["metadata"]["component"]["version"], "1.4.0"); + assert!(doc["metadata"]["component"]["supplier"]["name"].is_string()); + assert!(doc.get("vulnerabilities").is_none()); + assert!(!text.contains("CVE-2026-0001"), "no vulnerability crosses"); + + // A preview stores nothing. + let resp = server + .get(&format!( + "/api/v1/targets/{id}/versions/preview?label=1.5.0" + )) + .await; + assert_eq!(resp.status(), 200); + let preview: serde_json::Value = resp.json().await.unwrap(); + assert_eq!(preview["metadata"]["component"]["version"], "1.5.0"); + assert_eq!(preview["components"].as_array().unwrap().len(), 2); + + let body: serde_json::Value = server + .get(&format!("/api/v1/targets/{id}/releases")) + .await + .json() + .await + .unwrap(); + let labels: Vec<&str> = body["data"]["versions"] + .as_array() + .unwrap() + .iter() + .map(|v| v["label"].as_str().unwrap()) + .collect(); + assert_eq!(labels, ["1.4.0"], "the preview was not published"); + assert_eq!(body["data"]["releases"], json!([])); + + // Without a registry there is no connection to release over. + let resp = server + .post( + &format!("/api/v1/targets/{id}/releases"), + &json!({ "connection_id": "c-1" }), + ) + .await; + assert_eq!(resp.status(), 422); + assert_eq!( + resp.json::().await.unwrap()["error"], + "unknown_connection" + ); + assert_eq!( + server + .get("/api/v1/targets/nonsense/releases") + .await + .status(), + 404 + ); + + server.cleanup().await; +} diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index dd24982..395de71 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -192,6 +192,35 @@ form, and it is stored only when you save it as your own statement. but it is not your statement: it settles no alert, closes no issue and is not exported as yours. Your own VEX status stays yours to state. +### Releasing an SBOM to a connected workspace + +A supplier that uses Breakpilot itself can release the SBOM of one of its +targets to a customer's workspace once the two are connected (in the portal, +by code). This is the supplier's side; offering and delivering to the +customer follow. + +- `GET /api/v1/connections` lists your active connections, each by its id and + the other workspace's name. Nothing else of the other workspace is shown. +- `POST /api/v1/targets/{id}/releases` with `{"connection_id"}` releases the + target over a connection. It is released once per connection at a time + (`409` `released`). A connection that is not active answers `422` + (`unknown_connection`). +- `POST …/releases/{release}/end` ends a release. What the customer already + received stays with them. +- `POST /api/v1/targets/{id}/versions` with `{"label"}` publishes a version. + It is built from the target's components at that moment, as a CycloneDX + document with what identifies each component, its licences and its hashes. + Your workspace is named as the supplier and the label as the version. No + vulnerabilities, findings, paths or internal ids are included. Labels are + unique per target (`409` `label_taken`). A target without components + answers `422` (`empty`). +- `GET …/versions/preview?label=…` returns that document without publishing + it. +- `GET /api/v1/targets/{id}/releases` lists the releases (active ones first) + and the published versions. + +Releasing, ending and publishing are recorded in your workspace's audit log. + ### When the SBOM is empty or incomplete An SBOM without components does not mean the software uses no libraries: