CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m13s
CI / Deploy Dashboard (push) Successful in 5m50s
CI / Deploy Agent (push) Successful in 8m4s
991 lines
33 KiB
Rust
991 lines
33 KiB
Rust
//! Connections between workspaces (#1028) against a fake tenant registry
|
|
//! (tenant-registry#138): the client lists a tenant's active connections and
|
|
//! checks one, and the workspace's list shows only each connection's id and
|
|
//! the other side's name. Needs a live Mongo for the agent itself; skips
|
|
//! cleanly without one.
|
|
|
|
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
|
|
|
mod common;
|
|
|
|
use std::sync::Arc;
|
|
|
|
use axum::body::Body;
|
|
use axum::extract::{Path, Request};
|
|
use axum::http::StatusCode;
|
|
use axum::middleware::{from_fn, Next};
|
|
use axum::routing::{get, post};
|
|
use axum::{Extension, Json, Router};
|
|
use tower::ServiceExt;
|
|
|
|
use compliance_agent::agent::ComplianceAgent;
|
|
use compliance_agent::api::handlers::connections::list_connections;
|
|
use compliance_agent::api::handlers::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, publish_version, version_draft,
|
|
};
|
|
use compliance_agent::api::handlers::supply_chain::get_supply_chain;
|
|
use compliance_agent::database::DatabasePool;
|
|
use compliance_core::models::{OnboardedTarget, TargetType};
|
|
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, `t-unknown`
|
|
/// is not known (404); `t-3` does not
|
|
/// hold Prüfwerk.
|
|
async fn fake_registry() -> String {
|
|
let app = Router::new()
|
|
.route(
|
|
"/v1/internal/tenants/{id}/connections",
|
|
get(|Path(id): Path<String>| async move {
|
|
match id.as_str() {
|
|
"t-1" => Ok(Json(serde_json::json!({ "items": [
|
|
{ "id": "c-2", "peer_tenant_id": "t-3", "peer_name": "Muster Anlagenbau" },
|
|
{ "id": "c-1", "peer_tenant_id": "t-2", "peer_name": "beispiel Maschinenbau" },
|
|
] }))),
|
|
"t-down" => Err(StatusCode::INTERNAL_SERVER_ERROR),
|
|
"t-unknown" => Err(StatusCode::NOT_FOUND),
|
|
_ => Ok(Json(serde_json::json!({ "items": [] }))),
|
|
}
|
|
}),
|
|
)
|
|
.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),
|
|
}
|
|
}),
|
|
);
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
let addr = listener.local_addr().unwrap();
|
|
tokio::spawn(async move { axum::serve(listener, app).await.ok() });
|
|
format!("http://{addr}")
|
|
}
|
|
|
|
/// An agent whose registry is `registry`, or `None` without Mongo.
|
|
async fn agent(registry: &str) -> Option<Arc<ComplianceAgent>> {
|
|
let uri = std::env::var("TEST_MONGODB_URI")
|
|
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
|
let db_name = format!("con_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
|
|
let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else {
|
|
eprintln!("SKIP connections: no MongoDB reachable at {uri}");
|
|
return None;
|
|
};
|
|
let mut config = dev_config(uri, db_name);
|
|
config.tenant_registry_url = Some(registry.to_string());
|
|
Some(Arc::new(ComplianceAgent::new(config, pool)))
|
|
}
|
|
|
|
fn member(tenant: &str) -> TenantContext {
|
|
TenantContext {
|
|
tenant_id: tenant.into(),
|
|
tenant_slug: "acme".into(),
|
|
org_roles: vec![OrgRole::ItAdmin],
|
|
products: vec!["compliance-scanner".into()],
|
|
plan: "starter".into(),
|
|
status: TenantStatus::Active,
|
|
user_id: "u-1".into(),
|
|
user_name: None,
|
|
staff: None,
|
|
api_key: None,
|
|
}
|
|
}
|
|
|
|
/// `GET /api/v1/connections` as a member of `tenant`.
|
|
async fn list(agent: Arc<ComplianceAgent>, tenant: &str) -> (StatusCode, serde_json::Value) {
|
|
let ctx = member(tenant);
|
|
let inject = move |mut req: Request, next: Next| {
|
|
let ctx = ctx.clone();
|
|
async move {
|
|
req.extensions_mut().insert(ctx);
|
|
next.run(req).await
|
|
}
|
|
};
|
|
let app = Router::new()
|
|
.route("/api/v1/connections", get(list_connections))
|
|
.layer(Extension(agent))
|
|
.layer(from_fn(inject));
|
|
let resp = app
|
|
.oneshot(
|
|
Request::builder()
|
|
.uri("/api/v1/connections")
|
|
.body(Body::empty())
|
|
.unwrap(),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
let status = resp.status();
|
|
let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16)
|
|
.await
|
|
.unwrap();
|
|
(status, serde_json::from_slice(&bytes).unwrap_or_default())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_client_lists_and_checks_connections() {
|
|
let base = fake_registry().await;
|
|
let Some(agent) = agent(&base).await else {
|
|
return;
|
|
};
|
|
let registry = agent.registry.clone().unwrap();
|
|
|
|
let listed = registry.active_connections("t-1").await.unwrap();
|
|
assert_eq!(listed.len(), 2);
|
|
assert_eq!(listed[1].peer_tenant_id, "t-2");
|
|
assert!(registry.active_connections("t-down").await.is_err());
|
|
assert!(
|
|
registry
|
|
.active_connections("t-unknown")
|
|
.await
|
|
.unwrap()
|
|
.is_empty(),
|
|
"a 404 lists none"
|
|
);
|
|
|
|
let c1 = registry.connection("c-1").await.unwrap().unwrap();
|
|
assert_eq!(c1.peer_of("t-1"), Some("t-2"));
|
|
assert_eq!(c1.peer_of("t-9"), None, "a third workspace gets nothing");
|
|
let ended = registry.connection("c-ended").await.unwrap().unwrap();
|
|
assert_eq!(
|
|
ended.peer_of("t-1"),
|
|
None,
|
|
"an ended connection delivers nothing"
|
|
);
|
|
assert_eq!(registry.connection("c-unknown").await.unwrap(), None);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_workspace_sees_each_connection_by_name_only() {
|
|
let base = fake_registry().await;
|
|
let Some(agent) = agent(&base).await else {
|
|
return;
|
|
};
|
|
|
|
let (status, body) = list(agent.clone(), "t-1").await;
|
|
|
|
assert_eq!(status, StatusCode::OK);
|
|
assert_eq!(
|
|
body["data"],
|
|
serde_json::json!([
|
|
{ "id": "c-1", "peer_name": "beispiel Maschinenbau" },
|
|
{ "id": "c-2", "peer_name": "Muster Anlagenbau" },
|
|
]),
|
|
"by name, without the other tenant's id"
|
|
);
|
|
assert!(!body.to_string().contains("t-2"));
|
|
|
|
let (status, _) = list(agent, "t-down").await;
|
|
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
|
|
}
|
|
|
|
/// `method` `uri` with JSON `body` through the release handlers, as a member
|
|
/// of `tenant`.
|
|
async fn release_call(
|
|
agent: Arc<ComplianceAgent>,
|
|
tenant: &str,
|
|
uri: &str,
|
|
body: serde_json::Value,
|
|
) -> (StatusCode, serde_json::Value) {
|
|
let ctx = member(tenant);
|
|
let inject = move |mut req: Request, next: Next| {
|
|
let ctx = ctx.clone();
|
|
async move {
|
|
req.extensions_mut().insert(ctx);
|
|
next.run(req).await
|
|
}
|
|
};
|
|
let app = Router::new()
|
|
.route(
|
|
"/api/v1/targets/{id}/releases",
|
|
post(create_release).get(list_releases),
|
|
)
|
|
.route(
|
|
"/api/v1/targets/{id}/releases/{release}/end",
|
|
post(end_release),
|
|
)
|
|
.route("/api/v1/targets/{id}/versions", post(publish_version))
|
|
.route("/api/v1/targets/{id}/versions/draft", get(version_draft))
|
|
.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))
|
|
.route("/api/v1/supply-chain", get(get_supply_chain))
|
|
.layer(Extension(agent))
|
|
.layer(from_fn(inject));
|
|
// 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
|
|
.unwrap();
|
|
(status, serde_json::from_slice(&bytes).unwrap_or_default())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_target_is_released_once_over_an_active_connection() {
|
|
let base = fake_registry().await;
|
|
let Some(agent) = agent(&base).await else {
|
|
return;
|
|
};
|
|
let db = agent.db_pool.for_tenant_id("t-1").await.unwrap();
|
|
let id = db
|
|
.onboarded_targets()
|
|
.insert_one(OnboardedTarget::new(
|
|
"DR-4 Firmware".into(),
|
|
TargetType::FirmwareRtos,
|
|
))
|
|
.await
|
|
.unwrap()
|
|
.inserted_id
|
|
.as_object_id()
|
|
.unwrap()
|
|
.to_hex();
|
|
let uri = format!("/api/v1/targets/{id}/releases");
|
|
|
|
let (status, body) = release_call(
|
|
agent.clone(),
|
|
"t-1",
|
|
&uri,
|
|
serde_json::json!({ "connection_id": "c-1" }),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::CREATED, "{body}");
|
|
assert_eq!(body["data"]["peer_name"], "beispiel Maschinenbau");
|
|
assert_eq!(body["data"]["active"], true);
|
|
assert!(
|
|
!body.to_string().contains("t-2"),
|
|
"never the other tenant's id"
|
|
);
|
|
let release = body["data"]["id"].as_str().unwrap().to_string();
|
|
|
|
let (status, body) = release_call(
|
|
agent.clone(),
|
|
"t-1",
|
|
&uri,
|
|
serde_json::json!({ "connection_id": "c-1" }),
|
|
)
|
|
.await;
|
|
assert_eq!(
|
|
(status, body["error"].as_str()),
|
|
(StatusCode::CONFLICT, Some("released"))
|
|
);
|
|
let (status, body) = release_call(
|
|
agent.clone(),
|
|
"t-1",
|
|
&uri,
|
|
serde_json::json!({ "connection_id": "c-unknown" }),
|
|
)
|
|
.await;
|
|
assert_eq!(
|
|
(status, body["error"].as_str()),
|
|
(StatusCode::UNPROCESSABLE_ENTITY, Some("unknown_connection"))
|
|
);
|
|
|
|
let end = format!("{uri}/{release}/end");
|
|
let (status, body) = release_call(agent.clone(), "t-1", &end, serde_json::json!({})).await;
|
|
assert_eq!(status, StatusCode::OK);
|
|
assert_eq!(body["data"]["active"], false);
|
|
let ended_at = body["data"]["ended_at"].clone();
|
|
let (_, again) = release_call(agent.clone(), "t-1", &end, serde_json::json!({})).await;
|
|
assert_eq!(again["data"]["ended_at"], ended_at, "the first end is kept");
|
|
|
|
// Ended, it can be released again over the same connection.
|
|
let (status, _) = release_call(
|
|
agent.clone(),
|
|
"t-1",
|
|
&uri,
|
|
serde_json::json!({ "connection_id": "c-1" }),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::CREATED);
|
|
|
|
// Another workspace cannot reach this target's releases.
|
|
let (status, _) = release_call(
|
|
agent.clone(),
|
|
"t-2",
|
|
&uri,
|
|
serde_json::json!({ "connection_id": "c-1" }),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::NOT_FOUND);
|
|
|
|
agent.db_pool.drop_tenant("t-1").await.ok();
|
|
agent.db_pool.drop_tenant("t-2").await.ok();
|
|
}
|
|
|
|
/// 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,
|
|
delivered_hash: None,
|
|
delivered_label: None,
|
|
delivered_at: None,
|
|
offered_label: None,
|
|
offered_components: 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();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn accepted_releases_receive_each_published_version() {
|
|
use compliance_core::models::{ArtifactKind, SbomEntry};
|
|
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 supplier_db = agent.db_pool.for_tenant_id("t-1").await.unwrap();
|
|
supplier_db
|
|
.sbom_entries()
|
|
.insert_one(SbomEntry::new(
|
|
product.clone(),
|
|
"lwip".into(),
|
|
"2.1.2".into(),
|
|
"generic".into(),
|
|
))
|
|
.await
|
|
.unwrap();
|
|
let versions = format!("/api/v1/targets/{product}/versions");
|
|
let releases = format!("/api/v1/targets/{product}/releases");
|
|
|
|
// Published before anyone accepted: it arrives on acceptance.
|
|
let (status, _) =
|
|
release_call(agent.clone(), "t-1", &versions, json!({ "label": "1.4.0" })).await;
|
|
assert_eq!(status, StatusCode::CREATED);
|
|
let (_, body) = release_call(
|
|
agent.clone(),
|
|
"t-1",
|
|
&releases,
|
|
json!({ "connection_id": "c-1" }),
|
|
)
|
|
.await;
|
|
let release = body["data"]["id"].as_str().unwrap().to_string();
|
|
let offer = first_offer(&agent, "t-2").await;
|
|
assert_eq!(
|
|
(
|
|
offer["offered_label"].as_str(),
|
|
offer["offered_components"].as_i64()
|
|
),
|
|
(Some("1.4.0"), Some(1)),
|
|
"the offer names what accepting delivers"
|
|
);
|
|
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}");
|
|
assert_eq!(body["data"]["delivered_label"], "1.4.0");
|
|
let component = body["data"]["target_id"].as_str().unwrap().to_string();
|
|
|
|
let customer_db = agent.db_pool.for_tenant_id("t-2").await.unwrap();
|
|
let read_component = || async {
|
|
let oid = mongodb::bson::oid::ObjectId::parse_str(&component).unwrap();
|
|
customer_db
|
|
.onboarded_targets()
|
|
.find_one(mongodb::bson::doc! { "_id": oid })
|
|
.await
|
|
.unwrap()
|
|
.unwrap()
|
|
};
|
|
let sboms = |t: &OnboardedTarget| {
|
|
t.artifacts
|
|
.iter()
|
|
.filter(|a| a.kind == ArtifactKind::SupplierSbom)
|
|
.count()
|
|
};
|
|
let received = read_component().await;
|
|
assert_eq!(sboms(&received), 1);
|
|
assert_eq!(
|
|
received.supplier.as_ref().unwrap().version.as_deref(),
|
|
Some("1.4.0")
|
|
);
|
|
|
|
// Published after: delivered at once, replacing the one before.
|
|
let (status, _) =
|
|
release_call(agent.clone(), "t-1", &versions, json!({ "label": "1.5.0" })).await;
|
|
assert_eq!(status, StatusCode::CREATED);
|
|
let received = read_component().await;
|
|
assert_eq!(sboms(&received), 1, "a new version replaces the one before");
|
|
assert_eq!(
|
|
received.supplier.as_ref().unwrap().version.as_deref(),
|
|
Some("1.5.0")
|
|
);
|
|
assert_eq!(first_offer(&agent, "t-2").await["delivered_label"], "1.5.0");
|
|
let delivery = |chain: serde_json::Value| {
|
|
chain["data"]["edges"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.find(|e| e["to"] == format!("target:{component}"))
|
|
.map(|e| e["delivery"].clone())
|
|
.unwrap()
|
|
};
|
|
let (status, chain) = release_call(
|
|
agent.clone(),
|
|
"t-2",
|
|
"/api/v1/supply-chain",
|
|
serde_json::Value::Null,
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::OK, "{chain}");
|
|
let live = delivery(chain);
|
|
assert_eq!(
|
|
(live["how"].as_str(), live["version"].as_str()),
|
|
(Some("release"), Some("1.5.0")),
|
|
"the Lieferkette draws the release"
|
|
);
|
|
let (_, listed) = release_call(agent.clone(), "t-1", &releases, serde_json::Value::Null).await;
|
|
assert_eq!(
|
|
listed["data"]["releases"][0]["delivered_label"], "1.5.0",
|
|
"the supplier sees it"
|
|
);
|
|
let customers = |listed: &serde_json::Value| {
|
|
listed["data"]["versions"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.map(|v| {
|
|
(
|
|
v["label"].as_str().unwrap().to_string(),
|
|
v["customers"].as_u64().unwrap(),
|
|
)
|
|
})
|
|
.collect::<Vec<_>>()
|
|
};
|
|
assert_eq!(
|
|
customers(&listed),
|
|
[("1.5.0".to_string(), 1), ("1.4.0".to_string(), 1)],
|
|
"each version counts the customer it reached"
|
|
);
|
|
|
|
// Ended, nothing more arrives.
|
|
let (status, _) = release_call(
|
|
agent.clone(),
|
|
"t-1",
|
|
&format!("{releases}/{release}/end"),
|
|
json!({}),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::OK);
|
|
let (status, _) =
|
|
release_call(agent.clone(), "t-1", &versions, json!({ "label": "1.6.0" })).await;
|
|
assert_eq!(status, StatusCode::CREATED);
|
|
let received = read_component().await;
|
|
assert_eq!(
|
|
received.supplier.as_ref().unwrap().version.as_deref(),
|
|
Some("1.5.0")
|
|
);
|
|
let (_, listed) = release_call(agent.clone(), "t-1", &releases, serde_json::Value::Null).await;
|
|
assert_eq!(customers(&listed)[0], ("1.6.0".to_string(), 0));
|
|
let (_, chain) = release_call(
|
|
agent.clone(),
|
|
"t-2",
|
|
"/api/v1/supply-chain",
|
|
serde_json::Value::Null,
|
|
)
|
|
.await;
|
|
let ended = delivery(chain);
|
|
assert_eq!(
|
|
(ended["how"].as_str(), ended["version"].as_str()),
|
|
(Some("release_ended"), Some("1.5.0")),
|
|
"an ended release leaves its version"
|
|
);
|
|
|
|
// The next version's draft, against 1.6.0.
|
|
supplier_db
|
|
.sbom_entries()
|
|
.insert_one(SbomEntry::new(
|
|
product.clone(),
|
|
"mbedtls".into(),
|
|
"3.6.2".into(),
|
|
"generic".into(),
|
|
))
|
|
.await
|
|
.unwrap();
|
|
let (status, draft) = release_call(
|
|
agent.clone(),
|
|
"t-1",
|
|
&format!("{versions}/draft"),
|
|
serde_json::Value::Null,
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::OK, "{draft}");
|
|
assert_eq!(draft["data"]["components"], 2);
|
|
assert!(draft["data"]["blocked"].is_null());
|
|
let changes = &draft["data"]["changes"];
|
|
assert_eq!(changes["against"], "1.6.0");
|
|
assert_eq!(
|
|
(changes["added"].as_u64(), changes["unchanged"].as_u64()),
|
|
(Some(1), Some(1))
|
|
);
|
|
assert_eq!(changes["added_names"], json!(["mbedtls 3.6.2"]));
|
|
|
|
agent.db_pool.drop_tenant("t-1").await.ok();
|
|
agent.db_pool.drop_tenant("t-2").await.ok();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn an_open_offer_learns_each_published_version() {
|
|
use compliance_core::models::SbomEntry;
|
|
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 = format!("/api/v1/targets/{product}/releases");
|
|
let versions = format!("/api/v1/targets/{product}/versions");
|
|
let (status, _) = release_call(
|
|
agent.clone(),
|
|
"t-1",
|
|
&releases,
|
|
json!({ "connection_id": "c-1" }),
|
|
)
|
|
.await;
|
|
assert_eq!(status, StatusCode::CREATED);
|
|
assert!(
|
|
first_offer(&agent, "t-2").await["offered_label"].is_null(),
|
|
"nothing published yet"
|
|
);
|
|
|
|
agent
|
|
.db_pool
|
|
.for_tenant_id("t-1")
|
|
.await
|
|
.unwrap()
|
|
.sbom_entries()
|
|
.insert_one(SbomEntry::new(
|
|
product.clone(),
|
|
"lwip".into(),
|
|
"2.1.2".into(),
|
|
"generic".into(),
|
|
))
|
|
.await
|
|
.unwrap();
|
|
let (status, _) =
|
|
release_call(agent.clone(), "t-1", &versions, json!({ "label": "1.5.0" })).await;
|
|
assert_eq!(status, StatusCode::CREATED);
|
|
|
|
let offer = first_offer(&agent, "t-2").await;
|
|
assert_eq!(offer["state"], "offered", "announced, not delivered");
|
|
assert_eq!(offer["offered_label"], "1.5.0");
|
|
assert!(offer["delivered_label"].is_null());
|
|
agent.db_pool.drop_tenant("t-1").await.ok();
|
|
agent.db_pool.drop_tenant("t-2").await.ok();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_draft_without_components_says_why() {
|
|
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 (status, draft) = release_call(
|
|
agent.clone(),
|
|
"t-1",
|
|
&format!("/api/v1/targets/{product}/versions/draft"),
|
|
serde_json::Value::Null,
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(status, StatusCode::OK, "{draft}");
|
|
assert_eq!(draft["data"]["blocked"], "empty");
|
|
assert_eq!(draft["data"]["components"], 0);
|
|
assert!(draft["data"]["changes"].is_null());
|
|
agent.db_pool.drop_tenant("t-1").await.ok();
|
|
}
|