fix(offers): claim before creating, live releases, entitled peers, deletes on both sides (#1028)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m54s
CI / Check (pull_request) Failing after 7m23s

- 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-11-19 13:36:45 +01:00
1 parent 4ee36f7c5a
commit 79dd08977d
5 files changed
+417 -39

No files matched your search

+202 -35
View File
@@ -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>(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<bool, StatusCode> {
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<SbomRelease> = match db
.inner()
.collection::<SbomRelease>(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<SbomOffer> = 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,
@@ -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;
@@ -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 },
+198 -2
View File
@@ -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<serde_json::Value>| 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<String>| 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<ComplianceAgent>, 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();
}
+7 -1
View File
@@ -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