From 4ee36f7c5a7b84d9ffc7974c29c065529e644534 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:29:58 +0100 Subject: [PATCH 1/3] feat(offers): the customer is offered a supplier's release and answers it (#1028) The first half of phase 4's customer side (step 5 of the plan on #1028): - releasing a target (#1063) now writes an offer into the customer's database, right after the registry confirms the connection joins exactly the two workspaces (`ConnectionState::peer_of`, #1062); without the offer the release is taken back; - `GET /api/v1/sbom-offers`: the workspace's offers, open first, naming the supplier and its product only; - `POST /api/v1/sbom-offers/{id}/accept`: into an existing supplier component, or a new one (named after the product unless named, in the given projects); the connection is checked again first, and an ended one ends the offer and creates nothing; a new component goes through the same insert as `POST /api/v1/targets` (`insert_target`), so it is counted; - `POST /api/v1/sbom-offers/{id}/decline`; - the answer is written back to the supplier's release (`answer`); ending a release ends the customer's offer; accepting and declining are audited. Delivering published versions to accepted offers is the second half. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9 --- compliance-agent/src/api/handlers/mod.rs | 1 + compliance-agent/src/api/handlers/offers.rs | 484 ++++++++++++++++++ .../src/api/handlers/onboarding.rs | 33 +- compliance-agent/src/api/handlers/releases.rs | 58 +++ compliance-agent/src/api/routes.rs | 4 + compliance-agent/tests/connections.rs | 221 +++++++- docs/guide/sbom.md | 23 + 7 files changed, 805 insertions(+), 19 deletions(-) create mode 100644 compliance-agent/src/api/handlers/offers.rs diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index 4466474..0a21c23 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -23,6 +23,7 @@ pub mod mcp_servers; pub mod mcp_tokens; pub mod metering; pub mod notifications; +pub mod offers; pub mod onboarding; pub mod oscal; pub mod pentest_handlers; diff --git a/compliance-agent/src/api/handlers/offers.rs b/compliance-agent/src/api/handlers/offers.rs new file mode 100644 index 0000000..da82990 --- /dev/null +++ b/compliance-agent/src/api/handlers/offers.rs @@ -0,0 +1,484 @@ +//! SBOM releases, the customer's side (#1028): what a connected supplier +//! workspace offers, and the customer's answer. +//! +//! A supplier's release (`super::releases`) writes an offer into the +//! customer's database, after the registry confirmed the connection joins the +//! two. The customer accepts it into a supplier component (a new one, or one +//! it has) or declines it; the answer is written back to the supplier's +//! release. Accepting creates a target, which counts like any other, so it +//! is the customer's decision and never automatic. + +use axum::extract::{Extension, Path}; +use axum::http::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 compliance_core::models::{OnboardedTarget, SupplierComponent, TargetType}; +use compliance_core::tenant_ctx::TenantCtx; + +use super::dto::{tenant_db, AgentExt}; +use super::releases::SbomRelease; +use super::ApiResponse; +use crate::agent::ComplianceAgent; +use crate::database::Database; + +/// Where an offer stands. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OfferState { + /// Waiting for the customer's answer. + Offered, + /// Accepted into a supplier component. + Accepted, + /// Declined by the customer. + Declined, + /// Ended by the supplier, or the connection ended. + Ended, +} + +/// A supplier's offer, as stored in the customer's database. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SbomOffer { + #[serde(rename = "_id")] + pub id: ObjectId, + /// The supplier's release it answers. + pub release_id: String, + /// The connection it came over. + pub connection_id: String, + /// The supplier's tenant: for answering and delivering inside Prüfwerk, + /// never shown. + pub supplier_tenant_id: String, + /// The supplier workspace's display name. + pub supplier_name: String, + /// The supplier's name for the product (its target's name). + pub product_name: String, + /// The product's type, for the component it becomes. + pub product_type: TargetType, + pub state: OfferState, + /// The component it delivers into, once accepted. + #[serde(default)] + pub target_id: Option, + pub offered_at: BsonDateTime, + #[serde(default)] + pub decided_at: Option, + #[serde(default)] + pub decided_by: Option, + #[serde(default)] + pub ended_at: Option, +} + +impl SbomOffer { + /// The collection, in the customer's own database. + pub const COLLECTION: &'static str = "sbom_offers"; +} + +/// An offer as the customer reads it: nothing of the supplier's but its +/// name and the product's. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct OfferView { + pub id: String, + pub supplier_name: String, + pub product_name: String, + pub product_type: TargetType, + pub state: OfferState, + pub target_id: Option, + pub offered_at: DateTime, + pub decided_at: Option>, + pub ended_at: Option>, +} + +impl From for OfferView { + fn from(o: SbomOffer) -> Self { + Self { + id: o.id.to_hex(), + supplier_name: o.supplier_name, + product_name: o.product_name, + product_type: o.product_type, + state: o.state, + target_id: o.target_id, + offered_at: o.offered_at.to_chrono(), + decided_at: o.decided_at.map(BsonDateTime::to_chrono), + ended_at: o.ended_at.map(BsonDateTime::to_chrono), + } + } +} + +/// The body of an acceptance: into an existing supplier component, or a new +/// one with its name and projects. +#[derive(Debug, Default, Deserialize, utoipa::ToSchema)] +pub struct AcceptOffer { + /// An existing supplier component to deliver into. + #[serde(default)] + pub target_id: Option, + /// The new component's name; the product's name when left out. + #[serde(default)] + pub name: Option, + /// The new component's projects. + #[serde(default)] + pub project_ids: Vec, +} + +fn offers(db: &Database) -> mongodb::Collection { + db.inner().collection(SbomOffer::COLLECTION) +} + +fn internal(e: E) -> StatusCode { + tracing::error!("offer 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() +} + +/// Write `offer` into `customer`'s database. The supplier's release calls it +/// once the registry has confirmed the connection joins the two. +/// +/// # Errors +/// +/// 500 when it cannot be written. +pub(super) async fn offer( + agent: &ComplianceAgent, + customer: &str, + offer: &SbomOffer, +) -> Result<(), StatusCode> { + let db = agent + .db_pool + .for_tenant_id(customer) + .await + .map_err(internal)?; + offers(&db).insert_one(offer).await.map_err(internal)?; + Ok(()) +} + +/// Mark the offer of release `release` in `customer`'s database ended: the +/// supplier ended the release. Best-effort; a customer that has gone keeps +/// nothing to mark. +pub(super) async fn end(agent: &ComplianceAgent, customer: &str, release: &str) { + let db = agent.db_pool.for_existing_tenant_id(customer); + let ended = offers(&db) + .update_one( + doc! { "release_id": release, "state": { "$in": ["offered", "accepted"] } }, + doc! { "$set": { "state": "ended", "ended_at": BsonDateTime::now() } }, + ) + .await; + if let Err(e) = ended { + tracing::warn!(release, "ended release not marked at the customer: {e}"); + } +} + +/// Write the customer's answer `state` back to release `release` in the +/// supplier's database, for the supplier to see. Best-effort. +async fn answer_release(agent: &ComplianceAgent, offer: &SbomOffer, state: OfferState) { + let Ok(id) = ObjectId::parse_str(&offer.release_id) else { + return; + }; + let db = agent + .db_pool + .for_existing_tenant_id(&offer.supplier_tenant_id); + let answered = db + .inner() + .collection::(SbomRelease::COLLECTION) + .update_one( + doc! { "_id": id, "connection_id": &offer.connection_id }, + doc! { "$set": { "answer": mongodb::bson::to_bson(&state).unwrap_or_default() } }, + ) + .await; + if let Err(e) = answered { + tracing::warn!(release = %offer.release_id, "answer not written to the supplier: {e}"); + } +} + +/// Whether the connection `offer` came over still joins this workspace +/// (`tenant`) and its supplier. +/// +/// # Errors +/// +/// 503 without a registry or when it cannot be asked. +async fn still_connected( + agent: &ComplianceAgent, + tenant: &str, + offer: &SbomOffer, +) -> Result { + let registry = agent + .registry + .as_ref() + .ok_or(StatusCode::SERVICE_UNAVAILABLE)?; + let state = registry + .connection(&offer.connection_id) + .await + .map_err(|e| { + tracing::error!("connection check unavailable: {e}"); + StatusCode::SERVICE_UNAVAILABLE + })?; + Ok(state.is_some_and(|s| s.peer_of(tenant) == Some(offer.supplier_tenant_id.as_str()))) +} + +/// Record `action` about `target` in the platform's audit log, in the +/// background. +fn audit( + agent: &ComplianceAgent, + tenant: &TenantCtx, + action: &str, + target: Option<&OnboardedTarget>, + offer: &SbomOffer, +) { + let Some(registry) = agent.registry.clone() else { + return; + }; + let mut entry = crate::registry::AuditEntry::by( + &tenant.0, + action, + serde_json::json!({ "supplier_name": offer.supplier_name, "product_name": offer.product_name }), + ); + if let Some(t) = target { + entry = entry.about_target(&t.id.map(|o| o.to_hex()).unwrap_or_default(), &t.name); + } + tokio::spawn(async move { + if let Err(e) = registry.append_audit(&entry).await { + tracing::warn!("offer answer not audited: {e}"); + } + }); +} + +/// Offer `id` of the tenant behind `db`. +/// +/// # Errors +/// +/// 404 when it is not an id or there is no such offer. +async fn find(db: &Database, id: &str) -> Result { + let oid = ObjectId::parse_str(id).map_err(|_| StatusCode::NOT_FOUND)?; + offers(db) + .find_one(doc! { "_id": oid }) + .await + .map_err(internal)? + .ok_or(StatusCode::NOT_FOUND) +} + +/// The SBOM releases connected suppliers offer the workspace. +/// +/// Open offers first, then the answered and ended ones, each newest first. +/// Each names the supplier workspace and its product; nothing else of the +/// supplier's is shown. +#[utoipa::path( + get, + path = "/api/v1/sbom-offers", + tag = "Targets", + responses( + (status = 200, description = "The offers (`data`)"), + (status = 401, description = "No valid bearer token"), + ) +)] +#[tracing::instrument(skip_all)] +pub async fn list_offers( + Extension(agent): AgentExt, + tenant: TenantCtx, +) -> Result>>, StatusCode> { + let db = tenant_db(&agent, &tenant).await?; + let mut listed: Vec = offers(&db) + .find(doc! {}) + .sort(doc! { "offered_at": -1, "_id": -1 }) + .await + .map_err(internal)? + .try_collect() + .await + .map_err(internal)?; + // Open ones first; the sort keeps each group newest first. + listed.sort_by_key(|o| o.state != OfferState::Offered); + Ok(Json(ApiResponse { + data: listed.into_iter().map(OfferView::from).collect(), + total: None, + page: None, + })) +} + +/// Accept a supplier's SBOM release. +/// +/// Into an existing supplier component (`target_id`), or into a new one +/// named `name` (the product's name when left out) in `project_ids`. A new +/// component counts like any other target. The supplier sees the answer. +/// The connection must still join the two workspaces. +#[utoipa::path( + post, + path = "/api/v1/sbom-offers/{id}/accept", + tag = "Targets", + params(("id" = String, Path, description = "The offer's id")), + request_body = AcceptOffer, + responses( + (status = 200, description = "Accepted (`data`: the offer)"), + (status = 404, description = "No such offer, or no such component"), + (status = 409, description = "Already answered (`answered`), the release or connection ended (`ended`), or the component already receives another release (`target_taken`)"), + (status = 422, description = "The component is not a supplier component (`not_supplier_component`), or an unknown project"), + (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(offer_id = %id))] +pub async fn accept_offer( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, + Json(body): Json, +) -> Result { + let db = tenant_db(&agent, &tenant).await?; + let offer = find(&db, &id).await?; + if offer.state != OfferState::Offered { + let code = if offer.state == OfferState::Ended { + "ended" + } else { + "answered" + }; + return Ok(refused(StatusCode::CONFLICT, code)); + } + if !still_connected(&agent, &tenant.0.tenant_id, &offer).await? { + offers(&db) + .update_one( + doc! { "_id": offer.id }, + doc! { "$set": { "state": "ended", "ended_at": BsonDateTime::now() } }, + ) + .await + .map_err(internal)?; + return Ok(refused(StatusCode::CONFLICT, "ended")); + } + + let target = match body + .target_id + .as_deref() + .map(str::trim) + .filter(|t| !t.is_empty()) + { + Some(existing) => { + let oid = ObjectId::parse_str(existing).map_err(|_| StatusCode::NOT_FOUND)?; + let target = db + .onboarded_targets() + .find_one(doc! { "_id": oid }) + .await + .map_err(internal)? + .ok_or(StatusCode::NOT_FOUND)?; + if target.supplier.is_none() { + return Ok(refused( + StatusCode::UNPROCESSABLE_ENTITY, + "not_supplier_component", + )); + } + let taken = offers(&db) + .count_documents(doc! { "target_id": existing, "state": "accepted" }) + .await + .map_err(internal)?; + if taken > 0 { + return Ok(refused(StatusCode::CONFLICT, "target_taken")); + } + target + } + None => { + let known = super::projects::tenant_projects(&agent, &tenant.0.tenant_id).await?; + let project_ids = super::projects::validated_project_ids(&body.project_ids, &known)?; + let name = body + .name + .as_deref() + .map(str::trim) + .filter(|n| !n.is_empty()) + .unwrap_or(&offer.product_name) + .to_string(); + let mut target = OnboardedTarget::new(name, offer.product_type); + target.supplier = Some(SupplierComponent { + name: offer.supplier_name.clone(), + product: Some(offer.product_name.clone()), + version: None, + csaf_provider: None, + }); + target.project_ids = project_ids; + super::onboarding::insert_target(&agent, &db, &tenant.0.tenant_id, target).await? + } + }; + let target_id = target.id.map(|o| o.to_hex()).unwrap_or_default(); + let accepted = offers(&db) + .update_one( + doc! { "_id": offer.id, "state": "offered" }, + doc! { "$set": { + "state": "accepted", + "target_id": &target_id, + "decided_at": BsonDateTime::now(), + "decided_by": &tenant.0.user_id, + } }, + ) + .await + .map_err(internal)?; + if accepted.modified_count == 0 { + return Ok(refused(StatusCode::CONFLICT, "answered")); + } + answer_release(&agent, &offer, OfferState::Accepted).await; + audit( + &agent, + &tenant, + "pruefwerk.sbom_offer_accepted", + Some(&target), + &offer, + ); + let offer = find(&db, &id).await?; + Ok(Json(ApiResponse { + data: OfferView::from(offer), + total: None, + page: None, + }) + .into_response()) +} + +/// Decline a supplier's SBOM release. The supplier sees the answer. +#[utoipa::path( + post, + path = "/api/v1/sbom-offers/{id}/decline", + tag = "Targets", + params(("id" = String, Path, description = "The offer's id")), + responses( + (status = 200, description = "Declined (`data`: the offer)"), + (status = 404, description = "No such offer"), + (status = 409, description = "Already answered or ended (`answered`)"), + (status = 401, description = "No valid bearer token"), + (status = 403, description = "A read-only role"), + ) +)] +#[tracing::instrument(skip_all, fields(offer_id = %id))] +pub async fn decline_offer( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, +) -> Result { + let db = tenant_db(&agent, &tenant).await?; + let offer = find(&db, &id).await?; + let declined = offers(&db) + .update_one( + doc! { "_id": offer.id, "state": "offered" }, + doc! { "$set": { + "state": "declined", + "decided_at": BsonDateTime::now(), + "decided_by": &tenant.0.user_id, + } }, + ) + .await + .map_err(internal)?; + if declined.modified_count == 0 { + return Ok(refused(StatusCode::CONFLICT, "answered")); + } + answer_release(&agent, &offer, OfferState::Declined).await; + audit( + &agent, + &tenant, + "pruefwerk.sbom_offer_declined", + None, + &offer, + ); + let offer = find(&db, &id).await?; + Ok(Json(ApiResponse { + data: OfferView::from(offer), + total: None, + page: None, + }) + .into_response()) +} diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 7ab70fc..310b74c 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -387,25 +387,42 @@ pub async fn create_target( })?; let db = tenant_db(&agent, &tenant).await?; + let target = insert_target(&agent, &db, &tenant.0.tenant_id, target).await?; + Ok(Json(ApiResponse { + data: target.redacted(), + total: None, + page: None, + })) +} + +/// Store a new `target` of tenant `tenant_id` and count it: what every way +/// of adding a target does (the API, and accepting a supplier's SBOM release, +/// #1028), so each counts the same under the plan. +/// +/// # Errors +/// +/// 500 when it cannot be stored. +pub(super) async fn insert_target( + agent: &Arc, + db: &crate::database::Database, + tenant_id: &str, + mut target: OnboardedTarget, +) -> Result { let res = db .onboarded_targets() .insert_one(&target) .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; target.id = res.inserted_id.as_object_id(); - refresh_supplier_csaf(&agent, &tenant.0.tenant_id, target.supplier.as_ref()); + refresh_supplier_csaf(agent, tenant_id, target.supplier.as_ref()); let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default(); agent.emit_usage( - &tenant.0.tenant_id, + tenant_id, "target.added", - format!("target:{}:{target_id}", tenant.0.tenant_id), + format!("target:{tenant_id}:{target_id}"), serde_json::json!({ "target_id": target_id, "target_type": format!("{:?}", target.target_type) }), ); - Ok(Json(ApiResponse { - data: target.redacted(), - total: None, - page: None, - })) + Ok(target) } /// One target, credentials redacted. diff --git a/compliance-agent/src/api/handlers/releases.rs b/compliance-agent/src/api/handlers/releases.rs index 6a90447..ee2b7dc 100644 --- a/compliance-agent/src/api/handlers/releases.rs +++ b/compliance-agent/src/api/handlers/releases.rs @@ -43,6 +43,14 @@ pub struct SbomRelease { pub connection_id: String, /// The other workspace's display name when it was released. pub peer_name: String, + /// The other workspace's tenant: for offering and delivering inside + /// Prüfwerk, never shown. + #[serde(default)] + pub peer_tenant_id: String, + /// The other workspace's answer to the offer; `None` while it has not + /// answered. + #[serde(default)] + pub answer: Option, pub created_by: String, pub created_at: BsonDateTime, /// When it was ended; `None` while it is not. @@ -91,6 +99,9 @@ pub struct ReleaseView { pub ended_at: Option>, /// Not ended. pub active: bool, + /// The other workspace's answer: `accepted` or `declined`; `None` while + /// it is open. + pub answer: Option, } impl From for ReleaseView { @@ -102,6 +113,7 @@ impl From for ReleaseView { peer_name: r.peer_name, created_at: r.created_at.to_chrono(), ended_at: r.ended_at.map(BsonDateTime::to_chrono), + answer: r.answer, } } } @@ -378,6 +390,23 @@ pub async fn create_release( "unknown_connection", )); }; + // Asked again right before anything is written to the other workspace: + // the connection must join exactly this workspace and that one. + let joined = match agent.registry.as_ref() { + Some(registry) => registry.connection(&connection.id).await.map_err(|e| { + tracing::error!("connection check unavailable: {e}"); + StatusCode::SERVICE_UNAVAILABLE + })?, + None => None, + }; + if joined.as_ref().and_then(|j| j.peer_of(&tenant.0.tenant_id)) + != Some(connection.peer_tenant_id.as_str()) + { + 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 }, @@ -392,12 +421,38 @@ pub async fn create_release( target_id: id, connection_id: connection.id, peer_name: connection.peer_name, + peer_tenant_id: connection.peer_tenant_id, + answer: None, 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)?; + let offer = super::offers::SbomOffer { + id: ObjectId::new(), + release_id: release.id.to_hex(), + connection_id: release.connection_id.clone(), + supplier_tenant_id: tenant.0.tenant_id.clone(), + supplier_name: supplier_name(&agent, &tenant).await, + product_name: released.name.clone(), + product_type: released.target_type, + state: super::offers::OfferState::Offered, + target_id: None, + offered_at: BsonDateTime::now(), + decided_at: None, + decided_by: None, + ended_at: None, + }; + if let Err(status) = super::offers::offer(&agent, &release.peer_tenant_id, &offer).await { + // Without its offer the release would wait for an answer that can + // never come: take it back. + releases(&db) + .delete_one(doc! { "_id": release.id }) + .await + .map_err(internal)?; + return Err(status); + } audit( &agent, &tenant, @@ -457,6 +512,7 @@ pub async fn end_release( .map_err(internal)? .ok_or(StatusCode::NOT_FOUND)?; if changed.modified_count > 0 { + super::offers::end(&agent, &ended.peer_tenant_id, &ended.id.to_hex()).await; audit( &agent, &tenant, @@ -619,6 +675,8 @@ mod tests { target_id: "t1".into(), connection_id: "c1".into(), peer_name: "Beispiel Maschinenbau".into(), + peer_tenant_id: "t-2".into(), + answer: None, created_by: "u1".into(), created_at: BsonDateTime::now(), ended_at: None, diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index bcb8ac5..cbbdc61 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -60,6 +60,10 @@ fn described_routes() -> OpenApiRouter { .routes(routes!(handlers::releases::end_release)) .routes(routes!(handlers::releases::publish_version)) .routes(routes!(handlers::releases::preview_version)) + // What connected suppliers offer, the customer's side (#1028). + .routes(routes!(handlers::offers::list_offers)) + .routes(routes!(handlers::offers::accept_offer)) + .routes(routes!(handlers::offers::decline_offer)) .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 1a49221..2129657 100644 --- a/compliance-agent/tests/connections.rs +++ b/compliance-agent/tests/connections.rs @@ -20,7 +20,8 @@ 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::api::handlers::offers::{accept_offer, decline_offer, list_offers}; +use compliance_agent::api::handlers::releases::{create_release, end_release, list_releases}; use compliance_agent::database::DatabasePool; use compliance_core::models::{OnboardedTarget, TargetType}; use compliance_core::{OrgRole, TenantContext, TenantStatus}; @@ -44,6 +45,10 @@ async fn fake_registry() -> String { } }), ) + .route( + "/v1/tenants/{id}/projects", + get(|| async { Json(serde_json::json!({ "items": [] })) }), + ) .route( "/v1/internal/connections/{id}", get(|Path(id): Path| async move { @@ -185,22 +190,29 @@ async fn release_call( } }; let app = Router::new() - .route("/api/v1/targets/{id}/releases", post(create_release)) + .route( + "/api/v1/targets/{id}/releases", + post(create_release).get(list_releases), + ) .route( "/api/v1/targets/{id}/releases/{release}/end", post(end_release), ) + .route("/api/v1/sbom-offers", get(list_offers)) + .route("/api/v1/sbom-offers/{id}/accept", post(accept_offer)) + .route("/api/v1/sbom-offers/{id}/decline", post(decline_offer)) .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(); + // A null body reads; anything else posts. + let request = if body.is_null() { + Request::get(uri).body(Body::empty()).unwrap() + } else { + Request::post(uri) + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap() + }; + let resp = app.oneshot(request).await.unwrap(); let status = resp.status(); let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16) .await @@ -299,3 +311,190 @@ async fn a_target_is_released_once_over_an_active_connection() { agent.db_pool.drop_tenant("t-1").await.ok(); agent.db_pool.drop_tenant("t-2").await.ok(); } + +/// A target named `name` in `tenant`'s database, bought in when `supplier`. +async fn stored_target( + agent: &ComplianceAgent, + tenant: &str, + name: &str, + supplier: bool, +) -> String { + let db = agent.db_pool.for_tenant_id(tenant).await.unwrap(); + let mut target = OnboardedTarget::new(name.into(), TargetType::FirmwareRtos); + target.supplier = supplier.then(|| compliance_core::models::SupplierComponent { + name: "Beispiel".into(), + product: None, + version: None, + csaf_provider: None, + }); + db.onboarded_targets() + .insert_one(target) + .await + .unwrap() + .inserted_id + .as_object_id() + .unwrap() + .to_hex() +} + +#[tokio::test] +async fn the_customer_is_offered_the_release_and_answers_it() { + use serde_json::json; + 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 releases_uri = format!("/api/v1/targets/{product}/releases"); + let read = serde_json::Value::Null; + + // The supplier (t-1) releases over c-1 to the customer (t-2). + let (status, body) = release_call( + agent.clone(), + "t-1", + &releases_uri, + json!({ "connection_id": "c-1" }), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + let release = body["data"]["id"].as_str().unwrap().to_string(); + + let (status, offers) = + release_call(agent.clone(), "t-2", "/api/v1/sbom-offers", read.clone()).await; + assert_eq!(status, StatusCode::OK); + let offer = &offers["data"][0]; + assert_eq!(offer["product_name"], "DR-4 Firmware"); + assert_eq!(offer["state"], "offered"); + assert!(offer["supplier_name"].is_string()); + assert!( + !offers.to_string().contains("t-1"), + "never the supplier's tenant id" + ); + let offer_id = offer["id"].as_str().unwrap().to_string(); + + // Not into a component of the customer's own. + let own = stored_target(&agent, "t-2", "Steuerung", false).await; + let accept = format!("/api/v1/sbom-offers/{offer_id}/accept"); + let (status, body) = + release_call(agent.clone(), "t-2", &accept, json!({ "target_id": own })).await; + assert_eq!( + (status, body["error"].as_str()), + ( + StatusCode::UNPROCESSABLE_ENTITY, + Some("not_supplier_component") + ) + ); + + // Accepted into a new supplier component. + let (status, body) = release_call( + agent.clone(), + "t-2", + &accept, + json!({ "name": "Antriebsregler DR-4" }), + ) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(body["data"]["state"], "accepted"); + let component = body["data"]["target_id"].as_str().unwrap().to_string(); + let db = agent.db_pool.for_tenant_id("t-2").await.unwrap(); + let oid = mongodb::bson::oid::ObjectId::parse_str(&component).unwrap(); + let created = db + .onboarded_targets() + .find_one(mongodb::bson::doc! { "_id": oid }) + .await + .unwrap() + .unwrap(); + assert_eq!(created.name, "Antriebsregler DR-4"); + assert_eq!( + created.supplier.unwrap().product.as_deref(), + Some("DR-4 Firmware") + ); + let (status, body) = release_call(agent.clone(), "t-2", &accept, json!({})).await; + assert_eq!( + (status, body["error"].as_str()), + (StatusCode::CONFLICT, Some("answered")) + ); + + // The supplier sees the answer. + let (_, listed) = release_call(agent.clone(), "t-1", &releases_uri, read.clone()).await; + assert_eq!(listed["data"]["releases"][0]["answer"], "accepted"); + + // Ending the release ends the customer's offer. + let end = format!("{releases_uri}/{release}/end"); + let (status, _) = release_call(agent.clone(), "t-1", &end, json!({})).await; + assert_eq!(status, StatusCode::OK); + let (_, offers) = release_call(agent.clone(), "t-2", "/api/v1/sbom-offers", read.clone()).await; + assert_eq!(offers["data"][0]["state"], "ended"); + + // A second release is declined. + let (status, _) = release_call( + agent.clone(), + "t-1", + &releases_uri, + json!({ "connection_id": "c-1" }), + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let (_, offers) = release_call(agent.clone(), "t-2", "/api/v1/sbom-offers", read.clone()).await; + assert_eq!(offers["data"][0]["state"], "offered", "open offers first"); + let second = offers["data"][0]["id"].as_str().unwrap().to_string(); + let decline = format!("/api/v1/sbom-offers/{second}/decline"); + let (status, body) = release_call(agent.clone(), "t-2", &decline, json!({})).await; + assert_eq!( + (status, body["data"]["state"].as_str()), + (StatusCode::OK, Some("declined")) + ); + let (_, listed) = release_call(agent.clone(), "t-1", &releases_uri, read).await; + assert_eq!(listed["data"]["releases"][0]["answer"], "declined"); + + agent.db_pool.drop_tenant("t-1").await.ok(); + agent.db_pool.drop_tenant("t-2").await.ok(); +} + +#[tokio::test] +async fn an_offer_whose_connection_ended_cannot_be_accepted() { + use compliance_agent::api::handlers::offers::{OfferState, SbomOffer}; + 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 offer = SbomOffer { + id: mongodb::bson::oid::ObjectId::new(), + release_id: mongodb::bson::oid::ObjectId::new().to_hex(), + connection_id: "c-ended".into(), + supplier_tenant_id: "t-2".into(), + supplier_name: "Beispiel".into(), + product_name: "HP-7".into(), + product_type: TargetType::FirmwareRtos, + state: OfferState::Offered, + target_id: None, + offered_at: mongodb::bson::DateTime::now(), + decided_at: None, + decided_by: None, + ended_at: None, + }; + db.inner() + .collection::(SbomOffer::COLLECTION) + .insert_one(&offer) + .await + .unwrap(); + let accept = format!("/api/v1/sbom-offers/{}/accept", offer.id.to_hex()); + + let (status, body) = release_call(agent.clone(), "t-1", &accept, serde_json::json!({})).await; + + assert_eq!( + (status, body["error"].as_str()), + (StatusCode::CONFLICT, Some("ended")) + ); + let targets = db + .onboarded_targets() + .count_documents(mongodb::bson::doc! {}) + .await + .unwrap(); + assert_eq!( + targets, 0, + "no component is created over an ended connection" + ); + agent.db_pool.drop_tenant("t-1").await.ok(); +} diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index 395de71..1bd6649 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -221,6 +221,29 @@ customer follow. Releasing, ending and publishing are recorded in your workspace's audit log. +The customer's side: a release appears in the customer's workspace as an +offer, once the registry has confirmed that the connection joins the two +workspaces. The customer answers it, and the supplier sees the answer +(`answer` on the release). + +- `GET /api/v1/sbom-offers` lists the offers, open ones first. Each names + the supplier's workspace and its product, and nothing else of the + supplier's. +- `POST /api/v1/sbom-offers/{id}/accept` accepts an offer. With + `{"target_id"}` it goes into an existing supplier component; otherwise + into a new one with `{"name", "project_ids"}`, named after the product + when no name is given. A new component counts like any other target. + Refusals: + - `409` `answered`: the offer was already answered. + - `409` `ended`: the release or the connection has ended. + - `409` `target_taken`: the component already receives another release. + - `422` `not_supplier_component`: the component is not a supplier + component. +- `POST /api/v1/sbom-offers/{id}/decline` declines an offer. + +Ending a release ends the customer's offer. A connection that has ended +lets nothing be accepted, and no component is created over it. + ### When the SBOM is empty or incomplete An SBOM without components does not mean the software uses no libraries: -- 2.54.1 From 79dd08977d21317f0157a6804b63f919906f75fc Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:36:45 +0100 Subject: [PATCH 2/3] fix(offers): claim before creating, live releases, entitled peers, deletes on both sides (#1028) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - accepting claims the offer first (offered -> accepted, atomically) and only then creates the component, giving the claim back when that fails; an end that lands in between removes the still-empty component; of two acceptances into one component neither keeps it (`target_taken`), and the id is compared canonically; - an offer is acceptable only while the supplier's release still exists and has not ended, besides the connection joining the two; - a release is refused (`peer_not_entitled`) when the other workspace does not hold Prüfwerk or is halted or archived, so no database is created for it; - deleting a target ends its releases at their customers and ends offers accepted into it, with `ended` as the answer the supplier sees. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9 --- compliance-agent/src/api/handlers/offers.rs | 237 +++++++++++++++--- .../src/api/handlers/onboarding.rs | 3 + compliance-agent/src/api/handlers/releases.rs | 8 +- compliance-agent/tests/connections.rs | 200 ++++++++++++++- docs/guide/sbom.md | 8 +- 5 files changed, 417 insertions(+), 39 deletions(-) diff --git a/compliance-agent/src/api/handlers/offers.rs b/compliance-agent/src/api/handlers/offers.rs index da82990..fe2e6da 100644 --- a/compliance-agent/src/api/handlers/offers.rs +++ b/compliance-agent/src/api/handlers/offers.rs @@ -194,13 +194,15 @@ async fn answer_release(agent: &ComplianceAgent, offer: &SbomOffer, state: Offer } } -/// Whether the connection `offer` came over still joins this workspace -/// (`tenant`) and its supplier. +/// Whether `offer` can still be accepted: the connection it came over still +/// joins this workspace (`tenant`) and its supplier, and the supplier's +/// release still exists and has not ended (a supplier that deleted the +/// target, or left Prüfwerk, takes its releases with it). /// /// # Errors /// /// 503 without a registry or when it cannot be asked. -async fn still_connected( +async fn still_open( agent: &ComplianceAgent, tenant: &str, offer: &SbomOffer, @@ -216,7 +218,135 @@ async fn still_connected( tracing::error!("connection check unavailable: {e}"); StatusCode::SERVICE_UNAVAILABLE })?; - Ok(state.is_some_and(|s| s.peer_of(tenant) == Some(offer.supplier_tenant_id.as_str()))) + if !state.is_some_and(|s| s.peer_of(tenant) == Some(offer.supplier_tenant_id.as_str())) { + return Ok(false); + } + let Ok(release) = ObjectId::parse_str(&offer.release_id) else { + return Ok(false); + }; + let live = agent + .db_pool + .for_existing_tenant_id(&offer.supplier_tenant_id) + .inner() + .collection::(SbomRelease::COLLECTION) + .count_documents(doc! { + "_id": release, + "connection_id": &offer.connection_id, + "ended_at": null, + }) + .await + .map_err(internal)?; + Ok(live > 0) +} + +/// Whether workspace `peer` may be offered a release: it holds Prüfwerk and +/// is neither halted nor archived. An offer is written into its database, +/// so a workspace without the product never gets one created. Without a +/// registry (development) every workspace may. +/// +/// # Errors +/// +/// 503 when the registry cannot be asked. +pub(super) async fn takes_offers(agent: &ComplianceAgent, peer: &str) -> Result { + let Some(registry) = agent.registry.as_ref() else { + return Ok(true); + }; + let check = registry + .check_entitlement(peer, None, None) + .await + .map_err(|e| { + tracing::error!("entitlement check unavailable: {e}"); + StatusCode::SERVICE_UNAVAILABLE + })?; + let status = check + .status + .as_deref() + .and_then(compliance_core::TenantStatus::parse); + Ok(check.allowed && status.is_none_or(|s| !s.is_halted() && !s.is_archived())) +} + +/// Mark `offer` ended in `db`, from whichever state it is in. +async fn mark_ended(db: &Database, offer: ObjectId) -> Result<(), StatusCode> { + offers(db) + .update_one( + doc! { "_id": offer, "state": { "$in": ["offered", "accepted"] } }, + doc! { "$set": { "state": "ended", "ended_at": BsonDateTime::now() } }, + ) + .await + .map_err(internal)?; + Ok(()) +} + +/// Give back a claim on `offer` that could not be completed: it is open +/// again. +async fn unclaim(db: &Database, offer: ObjectId) -> Result<(), StatusCode> { + offers(db) + .update_one( + doc! { "_id": offer, "state": "accepted" }, + doc! { + "$set": { "state": "offered" }, + "$unset": { "target_id": "", "decided_at": "", "decided_by": "" }, + }, + ) + .await + .map_err(internal)?; + Ok(()) +} + +/// What an accepted offer delivers into. +enum Destination { + /// A supplier component the workspace has. + Existing(OnboardedTarget), + /// A new supplier component, not yet stored. + New(OnboardedTarget), +} + +/// The refusal for an offer that is no longer open: `ended` or `answered`. +fn not_open(state: OfferState) -> axum::response::Response { + let code = if state == OfferState::Ended { + "ended" + } else { + "answered" + }; + refused(StatusCode::CONFLICT, code) +} + +/// What deleting target `target_id` of tenant `tenant_id` (in `db`) means +/// for releases: its active releases end at their customers, and offers +/// accepted into it end, with `ended` as the answer the supplier sees, so +/// nothing is delivered into a component that has gone. Called before the +/// target's releases are deleted. Best-effort. +pub(super) async fn on_target_deleted(agent: &ComplianceAgent, db: &Database, target_id: &str) { + let active: Vec = match db + .inner() + .collection::(SbomRelease::COLLECTION) + .find(doc! { "target_id": target_id, "ended_at": null }) + .await + { + Ok(cursor) => cursor.try_collect().await.unwrap_or_default(), + Err(e) => { + tracing::warn!(target_id, "releases of a deleted target not read: {e}"); + Vec::new() + } + }; + for release in active { + end(agent, &release.peer_tenant_id, &release.id.to_hex()).await; + } + let accepted: Vec = match offers(db) + .find(doc! { "target_id": target_id, "state": "accepted" }) + .await + { + Ok(cursor) => cursor.try_collect().await.unwrap_or_default(), + Err(e) => { + tracing::warn!(target_id, "offers into a deleted target not read: {e}"); + Vec::new() + } + }; + for offer in accepted { + if mark_ended(db, offer.id).await.is_ok() { + answer_release(agent, &offer, OfferState::Ended).await; + } + } } /// Record `action` about `target` in the platform's audit log, in the @@ -329,32 +459,22 @@ pub async fn accept_offer( let db = tenant_db(&agent, &tenant).await?; let offer = find(&db, &id).await?; if offer.state != OfferState::Offered { - let code = if offer.state == OfferState::Ended { - "ended" - } else { - "answered" - }; - return Ok(refused(StatusCode::CONFLICT, code)); + return Ok(not_open(offer.state)); } - if !still_connected(&agent, &tenant.0.tenant_id, &offer).await? { - offers(&db) - .update_one( - doc! { "_id": offer.id }, - doc! { "$set": { "state": "ended", "ended_at": BsonDateTime::now() } }, - ) - .await - .map_err(internal)?; + if !still_open(&agent, &tenant.0.tenant_id, &offer).await? { + mark_ended(&db, offer.id).await?; return Ok(refused(StatusCode::CONFLICT, "ended")); } - let target = match body + // What it goes into, checked before anything is claimed or created. + let into = match body .target_id .as_deref() .map(str::trim) .filter(|t| !t.is_empty()) { - Some(existing) => { - let oid = ObjectId::parse_str(existing).map_err(|_| StatusCode::NOT_FOUND)?; + Some(chosen) => { + let oid = ObjectId::parse_str(chosen).map_err(|_| StatusCode::NOT_FOUND)?; let target = db .onboarded_targets() .find_one(doc! { "_id": oid }) @@ -367,14 +487,7 @@ pub async fn accept_offer( "not_supplier_component", )); } - let taken = offers(&db) - .count_documents(doc! { "target_id": existing, "state": "accepted" }) - .await - .map_err(internal)?; - if taken > 0 { - return Ok(refused(StatusCode::CONFLICT, "target_taken")); - } - target + Destination::Existing(target) } None => { let known = super::projects::tenant_projects(&agent, &tenant.0.tenant_id).await?; @@ -394,25 +507,79 @@ pub async fn accept_offer( csaf_provider: None, }); target.project_ids = project_ids; - super::onboarding::insert_target(&agent, &db, &tenant.0.tenant_id, target).await? + Destination::New(target) } }; - let target_id = target.id.map(|o| o.to_hex()).unwrap_or_default(); - let accepted = offers(&db) + + // Claim the offer first: of two acceptances, or an acceptance and the + // supplier's end, one wins, and nothing is created for the other. + let chosen_id = match &into { + Destination::Existing(target) => target.id.map(|o| o.to_hex()), + Destination::New(_) => None, + }; + let claimed = offers(&db) .update_one( doc! { "_id": offer.id, "state": "offered" }, doc! { "$set": { "state": "accepted", - "target_id": &target_id, + "target_id": chosen_id.as_deref(), "decided_at": BsonDateTime::now(), "decided_by": &tenant.0.user_id, } }, ) .await .map_err(internal)?; - if accepted.modified_count == 0 { - return Ok(refused(StatusCode::CONFLICT, "answered")); + if claimed.modified_count == 0 { + return Ok(not_open(find(&db, &id).await?.state)); } + + let target = match into { + Destination::Existing(target) => { + // One release per component: of two claims on it, neither keeps + // it when they raced, and the next acceptance finds it free. + let receiving = offers(&db) + .count_documents(doc! { "target_id": chosen_id.as_deref(), "state": "accepted" }) + .await + .map_err(internal)?; + if receiving > 1 { + unclaim(&db, offer.id).await?; + return Ok(refused(StatusCode::CONFLICT, "target_taken")); + } + target + } + Destination::New(target) => { + let created = + match super::onboarding::insert_target(&agent, &db, &tenant.0.tenant_id, target) + .await + { + Ok(created) => created, + Err(status) => { + unclaim(&db, offer.id).await?; + return Err(status); + } + }; + let created_id = created.id.map(|o| o.to_hex()).unwrap_or_default(); + let linked = offers(&db) + .update_one( + doc! { "_id": offer.id, "state": "accepted" }, + doc! { "$set": { "target_id": &created_id } }, + ) + .await + .map_err(internal)?; + if linked.matched_count == 0 { + // The supplier ended it meanwhile: the new component, still + // empty, goes again. + if let Some(oid) = created.id { + db.onboarded_targets() + .delete_one(doc! { "_id": oid }) + .await + .map_err(internal)?; + } + return Ok(refused(StatusCode::CONFLICT, "ended")); + } + created + } + }; answer_release(&agent, &offer, OfferState::Accepted).await; audit( &agent, diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 310b74c..0d783a0 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -695,6 +695,9 @@ pub async fn delete_target( if let Some(target) = stored { remove_target_files(&agent, &tenant.0.tenant_id, &target).await; } + // Its releases end at their customers, and offers accepted into it end, + // before the cascade deletes them (#1028). + super::offers::on_target_deleted(&agent, &db, &id).await; // Cascade all data keyed by repo_id == target id (best-effort). let db = &db; let _ = db.findings().delete_many(doc! { "repo_id": &id }).await; diff --git a/compliance-agent/src/api/handlers/releases.rs b/compliance-agent/src/api/handlers/releases.rs index ee2b7dc..83892c3 100644 --- a/compliance-agent/src/api/handlers/releases.rs +++ b/compliance-agent/src/api/handlers/releases.rs @@ -356,7 +356,7 @@ pub async fn list_releases( (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 = 422, description = "Not an active connection of the workspace (`unknown_connection`), or the other workspace does not hold Prüfwerk (`peer_not_entitled`)"), (status = 503, description = "The registry cannot be asked"), (status = 401, description = "No valid bearer token"), (status = 403, description = "A read-only role"), @@ -407,6 +407,12 @@ pub async fn create_release( "unknown_connection", )); } + if !super::offers::takes_offers(&agent, &connection.peer_tenant_id).await? { + return Ok(refused( + StatusCode::UNPROCESSABLE_ENTITY, + "peer_not_entitled", + )); + } let open = releases(&db) .count_documents( doc! { "target_id": &id, "connection_id": &connection.id, "ended_at": null }, diff --git a/compliance-agent/tests/connections.rs b/compliance-agent/tests/connections.rs index 2129657..a5ce015 100644 --- a/compliance-agent/tests/connections.rs +++ b/compliance-agent/tests/connections.rs @@ -21,6 +21,7 @@ use tower::ServiceExt; use compliance_agent::agent::ComplianceAgent; 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}; use compliance_agent::database::DatabasePool; use compliance_core::models::{OnboardedTarget, TargetType}; @@ -29,7 +30,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. +/// connection `c-ended` has ended; `t-down` cannot be listed; `t-3` does not +/// hold Prüfwerk. async fn fake_registry() -> String { let app = Router::new() .route( @@ -45,6 +47,13 @@ async fn fake_registry() -> String { } }), ) + .route( + "/v1/internal/entitlements/check", + post(|Json(body): Json| async move { + let allowed = body["tenant_id"] != "t-3"; + Json(serde_json::json!({ "allowed": allowed, "status": "active" })) + }), + ) .route( "/v1/tenants/{id}/projects", get(|| async { Json(serde_json::json!({ "items": [] })) }), @@ -54,6 +63,7 @@ async fn fake_registry() -> String { get(|Path(id): Path| async move { match id.as_str() { "c-1" => Ok(Json(serde_json::json!({ "active": true, "tenant_ids": ["t-1", "t-2"] }))), + "c-2" => Ok(Json(serde_json::json!({ "active": true, "tenant_ids": ["t-1", "t-3"] }))), "c-ended" => Ok(Json(serde_json::json!({ "active": false, "tenant_ids": ["t-1", "t-2"] }))), _ => Err(StatusCode::NOT_FOUND), } @@ -199,13 +209,16 @@ async fn release_call( post(end_release), ) .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)) .route("/api/v1/sbom-offers/{id}/decline", post(decline_offer)) .layer(Extension(agent)) .layer(from_fn(inject)); - // A null body reads; anything else posts. + // A null body reads, `"delete"` deletes; anything else posts. let request = if body.is_null() { Request::get(uri).body(Body::empty()).unwrap() + } else if body == "delete" { + Request::delete(uri).body(Body::empty()).unwrap() } else { Request::post(uri) .header("content-type", "application/json") @@ -498,3 +511,186 @@ async fn an_offer_whose_connection_ended_cannot_be_accepted() { ); agent.db_pool.drop_tenant("t-1").await.ok(); } + +/// The first offer listed for `tenant`. +async fn first_offer(agent: &Arc, tenant: &str) -> serde_json::Value { + let (_, offers) = release_call( + agent.clone(), + tenant, + "/api/v1/sbom-offers", + serde_json::Value::Null, + ) + .await; + offers["data"][0].clone() +} + +#[tokio::test] +async fn a_workspace_without_pruefwerk_is_offered_nothing() { + 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; + + // c-2 joins t-1 and t-3, which does not hold Prüfwerk. + let (status, body) = release_call( + agent.clone(), + "t-1", + &format!("/api/v1/targets/{product}/releases"), + serde_json::json!({ "connection_id": "c-2" }), + ) + .await; + + assert_eq!( + (status, body["error"].as_str()), + (StatusCode::UNPROCESSABLE_ENTITY, Some("peer_not_entitled")) + ); + let names = agent.db_pool.client().list_database_names().await.unwrap(); + let t3 = agent.db_pool.tenant_db_name("t-3"); + assert!(!names.contains(&t3), "no database is created for it"); + agent.db_pool.drop_tenant("t-1").await.ok(); +} + +#[tokio::test] +async fn deleting_either_side_ends_the_offer() { + use serde_json::json; + let base = fake_registry().await; + let Some(agent) = agent(&base).await else { + return; + }; + let releases_of = |id: &str| format!("/api/v1/targets/{id}/releases"); + + // The supplier deletes its product while the offer is open. + let product = stored_target(&agent, "t-1", "DR-4 Firmware", false).await; + let (status, _) = release_call( + agent.clone(), + "t-1", + &releases_of(&product), + json!({ "connection_id": "c-1" }), + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let offer = first_offer(&agent, "t-2").await; + let (status, _) = release_call( + agent.clone(), + "t-1", + &format!("/api/v1/targets/{product}"), + json!("delete"), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(first_offer(&agent, "t-2").await["state"], "ended"); + let accept = format!( + "/api/v1/sbom-offers/{}/accept", + offer["id"].as_str().unwrap() + ); + let (status, body) = release_call(agent.clone(), "t-2", &accept, json!({})).await; + assert_eq!( + (status, body["error"].as_str()), + (StatusCode::CONFLICT, Some("ended")) + ); + + // The customer deletes the component it accepted into. + let product = stored_target(&agent, "t-1", "HP-7 Firmware", false).await; + let (_, _) = release_call( + agent.clone(), + "t-1", + &releases_of(&product), + json!({ "connection_id": "c-1" }), + ) + .await; + let offer = first_offer(&agent, "t-2").await; + assert_eq!(offer["product_name"], "HP-7 Firmware"); + let accept = format!( + "/api/v1/sbom-offers/{}/accept", + offer["id"].as_str().unwrap() + ); + let (status, body) = release_call(agent.clone(), "t-2", &accept, json!({})).await; + assert_eq!(status, StatusCode::OK, "{body}"); + let component = body["data"]["target_id"].as_str().unwrap().to_string(); + let (status, _) = release_call( + agent.clone(), + "t-2", + &format!("/api/v1/targets/{component}"), + json!("delete"), + ) + .await; + assert_eq!(status, StatusCode::OK); + let (_, listed) = release_call( + agent.clone(), + "t-1", + &releases_of(&product), + serde_json::Value::Null, + ) + .await; + assert_eq!( + listed["data"]["releases"][0]["answer"], "ended", + "the supplier sees it" + ); + + agent.db_pool.drop_tenant("t-1").await.ok(); + agent.db_pool.drop_tenant("t-2").await.ok(); +} + +#[tokio::test] +async fn a_component_receives_one_release() { + use serde_json::json; + let base = fake_registry().await; + let Some(agent) = agent(&base).await else { + return; + }; + let component = stored_target(&agent, "t-2", "Antriebsregler", true).await; + let mut accepts = Vec::new(); + for name in ["DR-4 Firmware", "DR-5 Firmware"] { + let product = stored_target(&agent, "t-1", name, false).await; + let (status, _) = release_call( + agent.clone(), + "t-1", + &format!("/api/v1/targets/{product}/releases"), + json!({ "connection_id": "c-1" }), + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let offer = first_offer(&agent, "t-2").await; + accepts.push(format!( + "/api/v1/sbom-offers/{}/accept", + offer["id"].as_str().unwrap() + )); + } + + // The id as typed in another case is the same component. + let upper = component.to_uppercase(); + let (status, _) = release_call( + agent.clone(), + "t-2", + &accepts[0], + json!({ "target_id": component }), + ) + .await; + assert_eq!(status, StatusCode::OK); + let (status, body) = release_call( + agent.clone(), + "t-2", + &accepts[1], + json!({ "target_id": upper }), + ) + .await; + + assert_eq!( + (status, body["error"].as_str()), + (StatusCode::CONFLICT, Some("target_taken")) + ); + let (_, offers) = release_call( + agent.clone(), + "t-2", + "/api/v1/sbom-offers", + serde_json::Value::Null, + ) + .await; + assert_eq!( + offers["data"][0]["state"], "offered", + "the refused one stays open" + ); + agent.db_pool.drop_tenant("t-1").await.ok(); + agent.db_pool.drop_tenant("t-2").await.ok(); +} diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index 1bd6649..0f71fd1 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -242,7 +242,13 @@ workspaces. The customer answers it, and the supplier sees the answer - `POST /api/v1/sbom-offers/{id}/decline` declines an offer. Ending a release ends the customer's offer. A connection that has ended -lets nothing be accepted, and no component is created over it. +lets nothing be accepted, and no component is created over it. A workspace +that does not hold Prüfwerk cannot be released to (`422` +`peer_not_entitled`). + +Deleting either side ends the offer. If the supplier deletes the released +target, the customer's offer ends. If the customer deletes the component it +accepted into, the supplier sees `ended` as the answer. ### When the SBOM is empty or incomplete -- 2.54.1 From 7bd2d784e94ab178d66528cbb54afb13fa158bad Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:46:53 +0100 Subject: [PATCH 3/3] fix(offers): the release check reads as clippy 1.94 wants it (#1028) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9 --- compliance-agent/src/api/handlers/offers.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compliance-agent/src/api/handlers/offers.rs b/compliance-agent/src/api/handlers/offers.rs index fe2e6da..229bfd3 100644 --- a/compliance-agent/src/api/handlers/offers.rs +++ b/compliance-agent/src/api/handlers/offers.rs @@ -218,7 +218,7 @@ async fn still_open( tracing::error!("connection check unavailable: {e}"); StatusCode::SERVICE_UNAVAILABLE })?; - if !state.is_some_and(|s| s.peer_of(tenant) == Some(offer.supplier_tenant_id.as_str())) { + if state.is_none_or(|s| s.peer_of(tenant) != Some(offer.supplier_tenant_id.as_str())) { return Ok(false); } let Ok(release) = ObjectId::parse_str(&offer.release_id) else { -- 2.54.1