feat(offers): the customer is offered a supplier's release and answers it (#1028) (#1064)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m18s
CI / Deploy Agent (push) Successful in 7m39s

This commit was merged in pull request #1064.
This commit is contained in:
sharang committed 2026-11-19 13:10:21 +00:00
1 parent c8a13fecad
commit 20d56d2301
7 files changed
+1185 -21

No files matched your search

+1
View File
@@ -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;
+651
View File
@@ -0,0 +1,651 @@
//! 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<String>,
pub offered_at: BsonDateTime,
#[serde(default)]
pub decided_at: Option<BsonDateTime>,
#[serde(default)]
pub decided_by: Option<String>,
#[serde(default)]
pub ended_at: Option<BsonDateTime>,
}
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<String>,
pub offered_at: DateTime<Utc>,
pub decided_at: Option<DateTime<Utc>>,
pub ended_at: Option<DateTime<Utc>>,
}
impl From<SbomOffer> 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<String>,
/// The new component's name; the product's name when left out.
#[serde(default)]
pub name: Option<String>,
/// The new component's projects.
#[serde(default)]
pub project_ids: Vec<String>,
}
fn offers(db: &Database) -> mongodb::Collection<SbomOffer> {
db.inner().collection(SbomOffer::COLLECTION)
}
fn internal<E: std::fmt::Display>(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>(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 `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_open(
agent: &ComplianceAgent,
tenant: &str,
offer: &SbomOffer,
) -> Result<bool, StatusCode> {
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
})?;
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 {
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
/// 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<SbomOffer, StatusCode> {
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<Json<ApiResponse<Vec<OfferView>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let mut listed: Vec<SbomOffer> = 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<String>,
Json(body): Json<AcceptOffer>,
) -> Result<axum::response::Response, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let offer = find(&db, &id).await?;
if offer.state != OfferState::Offered {
return Ok(not_open(offer.state));
}
if !still_open(&agent, &tenant.0.tenant_id, &offer).await? {
mark_ended(&db, offer.id).await?;
return Ok(refused(StatusCode::CONFLICT, "ended"));
}
// 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(chosen) => {
let oid = ObjectId::parse_str(chosen).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",
));
}
Destination::Existing(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;
Destination::New(target)
}
};
// 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": chosen_id.as_deref(),
"decided_at": BsonDateTime::now(),
"decided_by": &tenant.0.user_id,
} },
)
.await
.map_err(internal)?;
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,
&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<String>,
) -> Result<axum::response::Response, StatusCode> {
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())
}
@@ -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<ComplianceAgent>,
db: &crate::database::Database,
tenant_id: &str,
mut target: OnboardedTarget,
) -> Result<OnboardedTarget, StatusCode> {
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.
@@ -678,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;
+65 -1
View File
@@ -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<super::offers::OfferState>,
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<DateTime<Utc>>,
/// Not ended.
pub active: bool,
/// The other workspace's answer: `accepted` or `declined`; `None` while
/// it is open.
pub answer: Option<super::offers::OfferState>,
}
impl From<SbomRelease> for ReleaseView {
@@ -102,6 +113,7 @@ impl From<SbomRelease> 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,
}
}
}
@@ -344,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"),
@@ -378,6 +390,29 @@ 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",
));
}
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 },
@@ -392,12 +427,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 +518,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 +681,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,
+4
View File
@@ -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!(
+407 -12
View File
@@ -20,7 +20,9 @@ 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::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};
use compliance_core::{OrgRole, TenantContext, TenantStatus};
@@ -28,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(
@@ -44,11 +47,23 @@ 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": [] })) }),
)
.route(
"/v1/internal/connections/{id}",
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),
}
@@ -185,22 +200,32 @@ 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/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));
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, `"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")
.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 +324,373 @@ 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>(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();
}
/// 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();
}
+29
View File
@@ -221,6 +221,35 @@ 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. 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
An SBOM without components does not mean the software uses no libraries: