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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
This commit is contained in:
1 parent
c8a13fecad
commit
4ee36f7c5a
7 files changed
+805
-19
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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<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 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<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
|
||||
})?;
|
||||
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<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 {
|
||||
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<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.
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -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<String>| 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>(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();
|
||||
}
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user