Compare commits

..
Author SHA1 Message Date
sharang 4f231632ea Merge branch 'main' into chore/release-0.4.16
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 4m21s
CI / Check (pull_request) Successful in 20m47s
2026-11-16 17:44:08 +00:00
Sharang ParnerkarandClaude Opus 5.5 045746488c chore(release): workspace crates at 0.4.16
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Canceled after 8s
CI / Check (pull_request) Canceled after 9s
The crate versions follow the release, as for 0.4.15 (#992). Bumping them
changes Cargo.toml and Cargo.lock, so the main build after merging
rebuilds the agent, dashboard and MCP images together for v0.4.16.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-16 18:42:28 +01:00
111 changed files with 566 additions and 20707 deletions

No files matched your search

Generated
+11 -11
View File
@@ -601,7 +601,7 @@ dependencies = [
[[package]]
name = "compliance-agent"
version = "0.4.17"
version = "0.4.16"
dependencies = [
"axum",
"base64 0.22.1",
@@ -657,7 +657,7 @@ dependencies = [
[[package]]
name = "compliance-core"
version = "0.4.17"
version = "0.4.16"
dependencies = [
"aes-gcm",
"axum",
@@ -689,7 +689,7 @@ dependencies = [
[[package]]
name = "compliance-dashboard"
version = "0.4.17"
version = "0.4.16"
dependencies = [
"async-trait",
"axum",
@@ -727,7 +727,7 @@ dependencies = [
[[package]]
name = "compliance-dast"
version = "0.4.17"
version = "0.4.16"
dependencies = [
"axum",
"base64 0.22.1",
@@ -749,7 +749,7 @@ dependencies = [
[[package]]
name = "compliance-graph"
version = "0.4.17"
version = "0.4.16"
dependencies = [
"bson",
"chrono",
@@ -774,7 +774,7 @@ dependencies = [
[[package]]
name = "compliance-mcp"
version = "0.4.17"
version = "0.4.16"
dependencies = [
"axum",
"bson",
@@ -797,7 +797,7 @@ dependencies = [
[[package]]
name = "compliance-smoke"
version = "0.4.17"
version = "0.4.16"
dependencies = [
"axum",
"compliance-core",
@@ -932,7 +932,7 @@ dependencies = [
[[package]]
name = "control-map"
version = "0.4.17"
version = "0.4.16"
dependencies = [
"serde",
"serde_json",
@@ -3383,9 +3383,9 @@ dependencies = [
[[package]]
name = "libz-sys"
version = "1.1.33"
version = "1.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fee3f59f4321dab0c78d828942e7aa09d0bd8ad6e78a501977e6bf3d02938045"
checksum = "ff20308ecabd635a2dc1dd5834a86c462cca20efba1d5d3ddab1f8aea3455cb2"
dependencies = [
"cc",
"libc",
@@ -7127,7 +7127,7 @@ dependencies = [
[[package]]
name = "werkbank-exec"
version = "0.4.17"
version = "0.4.16"
dependencies = [
"compliance-core",
"compliance-dast",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-agent"
version = "0.4.17"
version = "0.4.16"
edition = "2021"
[lints]
@@ -1,69 +0,0 @@
//! The workspace's connections to other workspaces (#1028), held by the
//! tenant registry (tenant-registry#138): whom a supplier can release an SBOM
//! to. A connection shows only its id and the other workspace's display
//! name, never the other tenant's id.
use axum::extract::Extension;
use axum::http::StatusCode;
use axum::Json;
use serde::Serialize;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::AgentExt;
use super::ApiResponse;
/// A connection as the workspace sees it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ConnectionView {
/// The connection's id.
pub id: String,
/// The other workspace's display name.
pub peer_name: String,
}
/// The workspace's active connections to other workspaces.
///
/// Each by its id and the other workspace's display name, by name; nothing
/// else of the other workspace. Connections are made and ended in the
/// portal. Without a registry (development) there are none.
#[utoipa::path(
get,
path = "/api/v1/connections",
tag = "Targets",
responses(
(status = 200, description = "The active connections (`data`)"),
(status = 503, description = "The registry cannot be asked"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn list_connections(
Extension(agent): AgentExt,
tenant: TenantCtx,
) -> Result<Json<ApiResponse<Vec<ConnectionView>>>, StatusCode> {
let connections = match agent.registry.as_ref() {
None => Vec::new(),
Some(registry) => registry
.active_connections(&tenant.0.tenant_id)
.await
.map_err(|e| {
tracing::error!(tenant_id = %tenant.0.tenant_id, "connections unavailable: {e}");
StatusCode::SERVICE_UNAVAILABLE
})?,
};
let mut views: Vec<ConnectionView> = connections
.into_iter()
.map(|c| ConnectionView {
id: c.id,
peer_name: c.peer_name,
})
.collect();
// One lowercase name per connection, not one per comparison.
views.sort_by_cached_key(|v| v.peer_name.to_lowercase());
Ok(Json(ApiResponse {
data: views,
total: None,
page: None,
}))
}
@@ -1,280 +0,0 @@
//! Delivering published SBOM versions to the customers who accepted a
//! release (#1028), the second half of phase 4's customer side.
//!
//! A version reaches a customer's supplier component the way a supplier's
//! upload does (`onboarding::attach_upload`): it replaces the component's
//! supplier SBOM and a scan starts. Publishing delivers to every accepted
//! release of the target, accepting delivers the latest version at once. The
//! connection is asked again right before each write into the customer's
//! workspace, and the version last delivered is not delivered again. (Each
//! publication is its own document, with its own serial number and time,
//! so a new version is delivered even when its components are unchanged.)
use std::sync::Arc;
use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, DateTime as BsonDateTime};
use compliance_core::models::{ArtifactKind, ScanTrigger};
use super::offers::{OfferState, SbomOffer};
use super::onboarding::{attach_upload, StoredUpload};
use super::releases::{SbomRelease, SbomVersion};
use crate::agent::ComplianceAgent;
use crate::database::Database;
/// What became of one delivery.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Outcome {
/// Attached to the customer's component; a scan started.
Delivered,
/// The customer already has this content.
Unchanged,
/// Not delivered: the offer is not accepted, its component has gone, or
/// the connection no longer joins the two workspaces.
Skipped,
/// It could not be written; the next publication tries again.
Failed,
}
/// Whether `release`'s connection still joins `supplier` and the customer it
/// was released to. Without a registry (development) it does not.
async fn joined(agent: &ComplianceAgent, supplier: &str, release: &SbomRelease) -> bool {
let Some(registry) = agent.registry.as_ref() else {
return false;
};
match registry.connection(&release.connection_id).await {
Ok(state) => {
state.is_some_and(|s| s.peer_of(supplier) == Some(release.peer_tenant_id.as_str()))
}
Err(e) => {
tracing::warn!(release = %release.id, "connection not checked, nothing delivered: {e}");
false
}
}
}
/// Deliver `version` of `release` to the customer the release went to, into
/// the component its accepted offer names. The caller has checked the
/// connection.
async fn deliver(
agent: &Arc<ComplianceAgent>,
release: &SbomRelease,
version: &SbomVersion,
) -> Outcome {
let customer = &release.peer_tenant_id;
let db = agent.db_pool.for_existing_tenant_id(customer);
let offers = db.inner().collection::<SbomOffer>(SbomOffer::COLLECTION);
let offer = match offers
.find_one(doc! { "release_id": release.id.to_hex(), "state": "accepted" })
.await
{
Ok(Some(offer)) => offer,
Ok(None) => return Outcome::Skipped,
Err(e) => {
tracing::error!(release = %release.id, "offer not read: {e}");
return Outcome::Failed;
}
};
if offer.delivered_hash.as_deref() == Some(version.content_hash.as_str()) {
return Outcome::Unchanged;
}
let Some(target_id) = offer.target_id.clone() else {
return Outcome::Skipped;
};
let Ok(oid) = ObjectId::parse_str(&target_id) else {
return Outcome::Skipped;
};
let target = match db.onboarded_targets().find_one(doc! { "_id": oid }).await {
Ok(Some(target)) => target,
Ok(None) => return Outcome::Skipped,
Err(e) => {
tracing::error!(target_id, "component not read: {e}");
return Outcome::Failed;
}
};
match attach(agent, &db, &target, version).await {
Ok(()) => {}
Err(e) => {
tracing::error!(target_id, label = %version.label, "version not delivered: {e}");
return Outcome::Failed;
}
}
let now = BsonDateTime::now();
let marked = offers
.update_one(
doc! { "_id": offer.id, "state": "accepted" },
doc! { "$set": {
"delivered_hash": &version.content_hash,
"delivered_label": &version.label,
"delivered_at": now,
} },
)
.await;
if let Err(e) = marked {
tracing::warn!(target_id, "delivery not recorded on the offer: {e}");
}
let supplier = agent
.db_pool
.for_existing_tenant_id(&offer.supplier_tenant_id);
let shown = supplier
.inner()
.collection::<SbomRelease>(SbomRelease::COLLECTION)
.update_one(
doc! { "_id": release.id },
doc! { "$set": { "delivered_label": &version.label, "delivered_at": now } },
)
.await;
if let Err(e) = shown {
tracing::warn!(release = %release.id, "delivery not recorded on the release: {e}");
}
// A set: a release delivered the same version again counts once.
let counted = supplier
.inner()
.collection::<SbomVersion>(SbomVersion::COLLECTION)
.update_one(
doc! { "_id": version.id },
doc! { "$addToSet": { "delivered_to": release.id.to_hex() } },
)
.await;
if let Err(e) = counted {
tracing::warn!(label = %version.label, "delivery not counted on the version: {e}");
}
let (agent, customer) = (Arc::clone(agent), customer.clone());
tokio::spawn(async move {
if let Err(e) = agent
.run_target_scan(&customer, &target_id, ScanTrigger::NewContent)
.await
{
tracing::error!(target_id, "scan after a delivered SBOM failed: {e}");
}
});
Outcome::Delivered
}
/// Copy `version`'s document into `target`'s upload folder in the
/// customer's workspace and attach it as the component's supplier SBOM,
/// labelled with the version.
async fn attach(
agent: &ComplianceAgent,
db: &Database,
target: &compliance_core::models::OnboardedTarget,
version: &SbomVersion,
) -> Result<(), String> {
let target_id = target.id.map(|o| o.to_hex()).unwrap_or_default();
let bytes = tokio::fs::read(&version.stored_path)
.await
.map_err(|e| format!("the published document is not readable: {e}"))?;
let name = format!("release-{}.cdx.json", version.label);
let path = crate::targets::store_upload(agent, &target_id, &name, &bytes)
.map_err(|e| format!("not stored: {e}"))?;
let mut upload = StoredUpload::new(path, name);
upload.size = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
attach_upload(db, target, ArtifactKind::SupplierSbom, None, upload)
.await
.map_err(|refusal| format!("refused ({})", refusal.code().unwrap_or("unreadable")))?;
if let Some(mut supplier) = target.supplier.clone() {
supplier.version = Some(version.label.clone());
let set = mongodb::bson::to_bson(&supplier).map_err(|e| e.to_string())?;
db.onboarded_targets()
.update_one(
doc! { "_id": target.id },
doc! { "$set": { "supplier": set } },
)
.await
.map_err(|e| e.to_string())?;
}
Ok(())
}
/// Deliver `version` of target `target_id`, just published by `supplier`
/// (its database `db`), to every customer that accepted a release of it,
/// and tell every customer whose offer is still open that it is now what
/// accepting delivers.
///
/// # Returns
///
/// How many customers it was delivered to.
pub(super) async fn deliver_published(
agent: &Arc<ComplianceAgent>,
supplier: &str,
db: &Database,
target_id: &str,
version: &SbomVersion,
) -> usize {
let live: 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::error!(target_id, "releases not read, nothing delivered: {e}");
return 0;
}
};
let mut delivered = 0;
for release in &live {
let open = matches!(release.answer, None | Some(OfferState::Offered));
if !(open || release.answer == Some(OfferState::Accepted))
|| !joined(agent, supplier, release).await
{
continue;
}
if open {
let id = release.id.to_hex();
super::offers::announce(
agent,
&release.peer_tenant_id,
&id,
&version.label,
version.components,
)
.await;
} else if deliver(agent, release, version).await == Outcome::Delivered {
delivered += 1;
}
}
delivered
}
/// Deliver the latest published version of the release `offer` answers, if
/// there is one, right after the customer accepted it. The caller has
/// checked the connection and that the release is live.
pub(super) async fn deliver_latest(agent: &Arc<ComplianceAgent>, offer: &SbomOffer) -> Outcome {
debug_assert_eq!(offer.state, OfferState::Accepted);
let Ok(id) = ObjectId::parse_str(&offer.release_id) else {
return Outcome::Skipped;
};
let supplier = agent
.db_pool
.for_existing_tenant_id(&offer.supplier_tenant_id);
let release = match supplier
.inner()
.collection::<SbomRelease>(SbomRelease::COLLECTION)
.find_one(doc! { "_id": id, "ended_at": null })
.await
{
Ok(Some(release)) => release,
Ok(None) => return Outcome::Skipped,
Err(e) => {
tracing::error!(release = %offer.release_id, "release not read: {e}");
return Outcome::Failed;
}
};
let latest = supplier
.inner()
.collection::<SbomVersion>(SbomVersion::COLLECTION)
.find_one(doc! { "target_id": &release.target_id })
.sort(doc! { "created_at": -1, "_id": -1 })
.await;
match latest {
Ok(Some(version)) => deliver(agent, &release, &version).await,
Ok(None) => Outcome::Skipped,
Err(e) => {
tracing::error!(release = %offer.release_id, "versions not read: {e}");
Outcome::Failed
}
}
}
+2 -8
View File
@@ -141,26 +141,20 @@ impl TicketState {
}
/// The query of the tickets list (`GET /api/v1/issues`).
#[derive(Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Deserialize)]
pub struct IssuesFilter {
/// A word of the title or the ticket number (`913`, `#913`, `PROJ-913`).
#[serde(default)]
pub q: Option<String>,
/// `open` or `closed`; an unknown value is refused (400).
/// Only open or only closed tickets; an unknown value is refused (400).
#[serde(default)]
#[param(value_type = Option<String>, example = "open")]
pub status: Option<TicketState>,
/// Only the tickets of one target: of its findings and its CVEs.
#[serde(default)]
pub repo_id: Option<String>,
/// The page, from 1 (default 1, at most 100 000).
#[serde(default = "default_page", deserialize_with = "de_page")]
#[param(minimum = 1, maximum = 100_000)]
pub page: u64,
/// Entries per page (default 50, at most 200).
#[serde(default = "default_limit", deserialize_with = "de_limit")]
#[param(minimum = 1, maximum = 200)]
pub limit: i64,
}
+11 -63
View File
@@ -112,19 +112,9 @@ fn state_counts(controls: &[crate::evidence::compliance::ControlStatus]) -> serd
/// Targets whose CRA status is computed at the same time for the summary.
const SUMMARY_CONCURRENCY: usize = 4;
/// Every target's CRA control counts per state, for the overview.
///
/// A target too large to evaluate in memory is listed with `counts: null`
/// rather than failing the whole summary.
#[utoipa::path(
get,
path = "/api/v1/compliance/summary",
tag = "Compliance",
responses(
(status = 200, description = "The counts per target"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/compliance/summary — every target's CRA state counts, for the
/// overview. A target too large to evaluate in memory is listed with
/// `counts: null` rather than failing the whole summary.
#[tracing::instrument(skip_all)]
pub async fn compliance_summary(
Extension(agent): AgentExt,
@@ -168,22 +158,8 @@ pub async fn compliance_summary(
Ok(Json(serde_json::json!({ "data": rows })))
}
/// A target's state against every CRA Annex I control.
///
/// With the findings against each and the last scan.
#[utoipa::path(
get,
path = "/api/v1/targets/{id}/compliance",
tag = "Compliance",
params(("id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The state per control"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such target"),
(status = 413, description = "Too large to evaluate in memory"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/targets/{id}/compliance — the target's state against every CRA
/// Annex I control, with the findings against each and the last scan.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn compliance_view(
Extension(agent): AgentExt,
@@ -209,22 +185,8 @@ pub async fn compliance_view(
})))
}
/// A target's evidence pack to download.
///
/// 404 for an unknown target, 413 when it is too large to build in memory.
#[utoipa::path(
get,
path = "/api/v1/targets/{id}/evidence-pack",
tag = "Compliance",
params(("id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The evidence pack"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such target"),
(status = 413, description = "Too large to build in memory"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/targets/{id}/evidence-pack — 404 for an unknown target, 413
/// when it is too large to build in memory.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn evidence_pack(
Extension(agent): AgentExt,
@@ -269,28 +231,14 @@ pub async fn evidence_pack(
const MAX_CONTROL_LOOKUP: usize = 50;
/// The query of [`describe_controls`]: comma-separated control ids.
#[derive(Debug, serde::Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Debug, serde::Deserialize)]
pub struct ControlIdsQuery {
/// The master control ids, comma-separated, at most 50.
#[param(example = "mc-1,mc-2")]
ids: String,
}
/// What the master controls stamped on a finding require.
///
/// For the finding page. Unknown ids are left out; at most
/// [`MAX_CONTROL_LOOKUP`] are described.
#[utoipa::path(
get,
path = "/api/v1/controls",
tag = "Compliance",
params(ControlIdsQuery),
responses(
(status = 200, description = "The controls"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/controls?ids=mc-1,mc-2 — what the master controls stamped on
/// a finding require, for the finding page. Unknown ids are left out; at
/// most [`MAX_CONTROL_LOOKUP`] are described.
#[tracing::instrument(skip_all)]
pub async fn describe_controls(
Extension(agent): AgentExt,
@@ -18,22 +18,11 @@ fn open_findings_of(target_id: &str) -> mongodb::bson::Document {
doc! { "repo_id": target_id, "status": { "$in": open } }
}
/// A target's open findings, counted by type and severity and by folder.
///
/// Tenant-scoped like the findings list, and read-only, so every
/// The open findings of target `id`, counted by type and severity and by
/// folder. Tenant-scoped like the findings list, and read-only, so every
/// role that may read findings may read it. A target without open findings
/// (or of another tenant, whose findings are not in this tenant's database)
/// gets an empty breakdown.
#[utoipa::path(
get,
path = "/api/v1/targets/{id}/finding-breakdown",
tag = "Findings",
params(("id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The breakdown"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn finding_breakdown(
Extension(agent): AgentExt,
@@ -17,20 +17,8 @@ fn may_view(tenant: &TenantCtx) -> bool {
tenant.0.staff.is_some() || tenant.0.is_admin()
}
/// The workspace's managed git source, without secrets.
///
/// Plus the webhook URL; `data: null` when the workspace has none. For
/// administrators (IT_ADMIN, OWNER) and support.
#[utoipa::path(
get,
path = "/api/v1/git-source",
tag = "Workspace",
responses(
(status = 200, description = "The source, or null"),
(status = 403, description = "Not an administrator or support"),
(status = 401, description = "No valid bearer token"),
)
)]
/// The source without secrets, plus the webhook URL; `data: null` when the
/// workspace has none.
pub async fn get_git_source(
axum::extract::Extension(agent): AgentExt,
tenant: TenantCtx,
+6 -39
View File
@@ -5,21 +5,9 @@ use super::dto::*;
use compliance_core::models::ScanRun;
use compliance_core::tenant_ctx::TenantCtx;
/// Whether the caller may use Prüfwerk at all.
///
/// Reached only when the authentication, entitlement and role layers let the
/// caller through; they answer the refusals (a blocked member gets 403
/// `MEMBER_BLOCKED`).
#[utoipa::path(
get,
path = "/api/v1/access",
tag = "Workspace",
responses(
(status = 200, description = "The caller may use Prüfwerk"),
(status = 403, description = "Not entitled, or a blocked member"),
(status = 401, description = "No valid bearer token"),
)
)]
/// `GET /api/v1/access`: reached only when the authentication, entitlement
/// and role layers let the caller through; they answer the refusals (a
/// blocked member gets 403 `MEMBER_BLOCKED`).
#[tracing::instrument(skip_all)]
pub async fn access() -> Json<serde_json::Value> {
Json(serde_json::json!({ "access": true }))
@@ -28,21 +16,10 @@ pub async fn access() -> Json<serde_json::Value> {
/// How long the health check waits for MongoDB before it reports it down.
const DB_PING_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
/// Whether the agent can serve: MongoDB answers a ping.
///
/// 200 `{"status":"ok"}` when MongoDB answers, 503
/// `{"status":"degraded","mongo":"unreachable"}` when it does not, so a load
/// balancer and the container health check stop sending traffic to an
/// `GET /api/v1/health`: 200 `{"status":"ok"}` when MongoDB answers a ping,
/// 503 `{"status":"degraded","mongo":"unreachable"}` when it does not, so a
/// load balancer and the container health check stop sending traffic to an
/// instance that cannot serve it (#60). Public, untraced, no tenant.
#[utoipa::path(
get,
path = "/api/v1/health",
tag = "Health",
responses(
(status = 200, description = "MongoDB answers"),
(status = 503, description = "MongoDB is unreachable"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn health(
axum::extract::Extension(agent): AgentExt,
@@ -116,16 +93,6 @@ pub(crate) async fn open_findings_by_severity(
.collect()
}
/// The counts the overview page shows for the tenant.
#[utoipa::path(
get,
path = "/api/v1/stats/overview",
tag = "Workspace",
responses(
(status = 200, description = "The counts"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn stats_overview(
axum::extract::Extension(agent): AgentExt,
+23 -92
View File
@@ -55,20 +55,16 @@ fn store_error(e: mongodb::error::Error) -> Refusal {
}
/// The query of [`get_inbox`].
#[derive(Debug, Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Debug, Deserialize)]
pub struct InboxQuery {
/// Only this target's cards, counts and Erstbewertung.
#[serde(default)]
pub target: Option<String>,
/// The bucket whose cards to list: `today` (default), `this_week`,
/// `later` or `likely_false_positive`.
/// The bucket whose cards to list (default `today`).
#[serde(default)]
#[param(value_type = Option<String>, example = "this_week")]
pub bucket: Option<Bucket>,
/// The most cards to list (default 100, at most 500).
#[serde(default)]
#[param(minimum = 1, maximum = 500)]
pub limit: Option<usize>,
}
@@ -178,24 +174,13 @@ async fn progress(
})
}
/// The open decisions in urgency buckets, most urgent first.
///
/// The bucket counts, the Erstbewertung, the targets with cards, and the
/// cards of one bucket (default `today`).
/// GET /api/v1/inbox[?target=<id>&bucket=<bucket>&limit=<n>] — the bucket
/// counts, the Erstbewertung, the targets with cards, and the cards of one
/// bucket (default `today`), most urgent first.
///
/// Cards: one per finding, one per target, package and version for CVE
/// alerts. Cards put off until a date are left out until then and come back
/// under `later`.
#[utoipa::path(
get,
path = "/api/v1/inbox",
tag = "Inbox",
params(InboxQuery),
responses(
(status = 200, description = "The buckets and cards"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(target = ?query.target, bucket = ?query.bucket))]
pub async fn get_inbox(
Extension(agent): AgentExt,
@@ -339,27 +324,13 @@ async fn set_vex(
Ok(())
}
/// Decide on every item of a card.
///
/// `{key, action, reason?, justification?, statement?}`: apply `action`
/// through the findings' and the VEX endpoints' code, and answer what each
/// item was before (for `POST /api/v1/inbox/undo`). The card's resubmission,
/// if any, is dropped. 409 when nothing on the card waits any more, 422 for an
/// action the card does not offer or without the reason, justification or
/// statement it needs.
#[utoipa::path(
post,
path = "/api/v1/inbox/decide",
tag = "Inbox",
request_body(content = Object, description = "`key`, `action`, and the `reason`, `justification` or `statement` the action needs"),
responses(
(status = 200, description = "Decided, with what each item was before"),
(status = 400, description = "A malformed key"),
(status = 409, description = "Nothing on the card waits for a decision"),
(status = 422, description = "An action the card does not offer, or what it needs is missing"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/inbox/decide `{key, action, reason?, justification?,
/// statement?}` — apply `action` to every item of card `key`, through the
/// findings' and the VEX endpoints' code, and answer what each item was
/// before (for `POST /api/v1/inbox/undo`). The card's resubmission, if any,
/// is dropped. 409 when nothing on the card waits any more, 422 for an action
/// the card does not offer or without the reason, justification or statement
/// it needs.
#[tracing::instrument(skip_all, fields(key = %req.key, action = ?req.action))]
pub async fn decide(
agent: AgentExt,
@@ -460,26 +431,12 @@ async fn belongs_to(db: &Database, key: &str, previous: &[PreviousState]) -> Res
}
}
/// Undo a decision on a card.
///
/// `{key, previous}`: put the items back through the same code the decision
/// went through. A finding gets its previous status (a new entry in its
/// history, which keeps the decision on record), an alert
/// `under_investigation` (also when it had no statement before; both leave
/// it open). 422 when an item does not belong to the card or its previous
/// state was not an open one.
#[utoipa::path(
post,
path = "/api/v1/inbox/undo",
tag = "Inbox",
request_body(content = Object, description = "`key`, and `previous` as the decision answered it"),
responses(
(status = 200, description = "Put back"),
(status = 400, description = "A malformed key or id"),
(status = 422, description = "An item not of the card, or not open before"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/inbox/undo `{key, previous}` — put the items of a decision
/// on card `key` back, through the same code the decision went through: a
/// finding gets its previous status (a new entry in its history, which keeps
/// the decision on record), an alert `under_investigation` (also when it had
/// no statement before; both leave it open). 422 when an item does not
/// belong to the card or its previous state was not an open one.
#[tracing::instrument(skip_all, fields(key = %req.key))]
pub async fn undo(
agent: AgentExt,
@@ -529,27 +486,13 @@ pub async fn undo(
Ok(Json(serde_json::json!({ "status": "restored" })))
}
/// Put a card off: one week, one month, or until a date.
///
/// `{key, for}`, `for` as `{"kind": "week"}`, `{"kind": "month"}` or
/// `{"kind": "date", "date": "2026-12-01"}`. It is hidden until then and comes back in its own bucket, or earlier when a new
/// POST /api/v1/inbox/snooze `{key, for}` — put card `key` off: one week, one
/// month, or until a date (`{"kind": "date", "date": "2026-12-01"}`). It is
/// hidden until then and comes back in its own bucket, or earlier when a new
/// CVE or a KEV entry joins it: the snooze records the card's items and
/// whether it was KEV. A second snooze replaces the first. 400 for a
/// malformed key, 409 when nothing on the card waits for a decision, 422 for
/// a date that is not in the future.
#[utoipa::path(
post,
path = "/api/v1/inbox/snooze",
tag = "Inbox",
request_body(content = Object, description = "`key`, and `for`: a week, a month or a date"),
responses(
(status = 200, description = "When the card comes back"),
(status = 400, description = "A malformed key"),
(status = 409, description = "Nothing on the card waits for a decision"),
(status = 422, description = "A date that is not in the future"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(key = %req.key))]
pub async fn snooze(
Extension(agent): AgentExt,
@@ -589,20 +532,8 @@ pub async fn snooze(
}))
}
/// Take a card's resubmission back (the undo of a snooze).
///
/// Nothing to take back is no error.
#[utoipa::path(
delete,
path = "/api/v1/inbox/snooze/{key}",
tag = "Inbox",
params(("key" = String, Path, description = "The card's key")),
responses(
(status = 200, description = "The resubmission is gone"),
(status = 400, description = "A malformed key"),
(status = 401, description = "No valid bearer token"),
)
)]
/// DELETE /api/v1/inbox/snooze/{key} — take card `key`'s resubmission back
/// (the undo of a snooze); nothing to take back is no error.
#[tracing::instrument(skip_all, fields(key = %key))]
pub async fn unsnooze(
Extension(agent): AgentExt,
+1 -12
View File
@@ -7,21 +7,10 @@ use compliance_core::models::issue::cve_issue_prefix;
use compliance_core::models::TrackerIssue;
use compliance_core::tenant_ctx::TenantCtx;
/// The tenant's tickets, newest first, searched and filtered.
/// The tenant's tickets, newest first, searched and filtered by `filter`.
///
/// A ticket stores no target, only the finding it is about: the target filter
/// first looks up the ids of the target's findings that have a ticket.
#[utoipa::path(
get,
path = "/api/v1/issues",
tag = "Tickets",
params(IssuesFilter),
responses(
(status = 200, description = "A page of tickets"),
(status = 400, description = "An unknown status"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(repo_id = ?filter.repo_id, status = ?filter.status))]
pub async fn list_issues(
Extension(agent): AgentExt,
@@ -1,527 +0,0 @@
//! A machine (#1026): a project of kind `product` in the registry, made of
//! the targets assigned to it, in-house ones and components bought in from
//! suppliers (#1025). Its documents cover all of them.
use std::collections::HashMap;
use axum::extract::{Extension, Path, Query};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::Json;
use chrono::{DateTime, Utc};
use futures_util::StreamExt;
use mongodb::bson::{doc, oid::ObjectId};
use serde::Serialize;
use compliance_core::cve_groups::{self, CveGroup, SeverityCounts};
use compliance_core::models::{
CveAlert, OnboardedTarget, ProjectKind, SbomEntry, SupplierComponent, TargetType,
};
use compliance_core::sbom_docs::{self, MachinePart};
use compliance_core::scan_changes::ScanChange;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{tenant_db, AgentExt};
use super::{
collect_cursor_async, projects::tenant_projects, sbom::MAX_EXPORT_COMPONENTS, ApiResponse,
};
use crate::agent::ComplianceAgent;
use crate::database::Database;
use crate::pipeline::csaf_feed::{supplier_key, MongoAdvisoryStore, SupplierProviderStatus};
use crate::pipeline::sbom::supplied::SUPPLIER_PRODUCT_MANAGER;
/// A machine as its endpoints read it: its name, its parts (its targets that
/// are not archived, by name) and their ids, in the same order.
struct Machine {
name: String,
targets: Vec<OnboardedTarget>,
ids: Vec<String>,
}
/// Machine `id` of the tenant, and the tenant's database.
///
/// # Errors
///
/// As [`machine_name`]; 500 when the targets cannot be read.
async fn machine(
agent: &ComplianceAgent,
tenant: &TenantCtx,
id: &str,
) -> Result<(Machine, Database), StatusCode> {
let name = machine_name(agent, tenant, id).await?;
let db = tenant_db(agent, tenant).await?;
let targets: Vec<OnboardedTarget> = collect_cursor_async(
db.onboarded_targets()
.find(doc! { "project_ids": id, "archived_at": null })
.sort(doc! { "name": 1 })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
)
.await;
let ids = targets
.iter()
.filter_map(|t| t.id.map(|o: ObjectId| o.to_hex()))
.collect();
Ok((Machine { name, targets, ids }, db))
}
/// The open CVE alerts of the targets `ids`.
pub(super) async fn open_alerts(
db: &Database,
ids: &[String],
) -> Result<Vec<CveAlert>, StatusCode> {
let alerts: Vec<CveAlert> = collect_cursor_async(
db.cve_alerts()
.find(doc! { "repo_id": { "$in": ids }, "resolved_at": null })
.projection(doc! { "llm_impact_summary": 0 })
.sort(doc! { "cve_id": 1 })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
)
.await;
Ok(alerts.into_iter().filter(cve_groups::is_open).collect())
}
/// The name of machine `id`: a product project of the tenant's.
///
/// Without a registry (development) no project can be looked up, and the
/// machine is named by its id.
///
/// # Errors
///
/// 404 when the tenant has no such project, 422 when it is a topic rather
/// than a product, 503 when the registry cannot be asked.
async fn machine_name(
agent: &ComplianceAgent,
tenant: &TenantCtx,
id: &str,
) -> Result<String, StatusCode> {
let projects = tenant_projects(agent, &tenant.0.tenant_id).await?;
match projects.into_iter().find(|p| p.id == id) {
Some(p) if p.kind == ProjectKind::Product => Ok(p.name),
Some(_) => Err(StatusCode::UNPROCESSABLE_ENTITY),
None if agent.registry.is_none() => Ok(id.to_string()),
None => Err(StatusCode::NOT_FOUND),
}
}
/// The CycloneDX type of a part of target type `kind`: device software is
/// firmware, a PLC program and other software an application.
fn part_kind(kind: TargetType) -> &'static str {
match kind {
TargetType::FirmwareBareMetal
| TargetType::FirmwareRtos
| TargetType::EmbeddedLinuxYocto => "firmware",
TargetType::PlcSps
| TargetType::WebApp
| TargetType::BackendService
| TargetType::DesktopApp
| TargetType::AndroidApp
| TargetType::IosApp => "application",
}
}
/// A machine's SBOM as a CycloneDX 1.6 document to download.
///
/// The machine is a product project; its parts are its targets that are not
/// archived, each with its supplier (the workspace for one made in-house)
/// and its components beneath it. A component bought in is named by its
/// supplier's product and version. Never truncated: a machine with more than
/// 100 000 components is refused.
#[utoipa::path(
get,
path = "/api/v1/projects/{id}/sbom",
tag = "SBOM",
params(("id" = String, Path, description = "The project's id")),
responses(
(status = 200, description = "The machine's CycloneDX SBOM"),
(status = 404, description = "No such project"),
(status = 413, description = "Too many components to export"),
(status = 422, description = "The project is a topic, not a product, or has no targets"),
(status = 503, description = "The registry cannot be asked"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(project_id = %id))]
pub async fn export_machine_sbom(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> Result<impl IntoResponse, StatusCode> {
let (Machine { name, targets, ids }, db) = machine(&agent, &tenant, &id).await?;
// A machine without parts would read as one without components.
if targets.is_empty() {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
// The supplier's product is the part itself, not one of its components.
let of_parts = doc! {
"repo_id": { "$in": &ids },
"package_manager": { "$ne": SUPPLIER_PRODUCT_MANAGER },
};
let components = db
.sbom_entries()
.count_documents(of_parts.clone())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if components > MAX_EXPORT_COMPONENTS {
tracing::warn!(
components,
"machine SBOM refused: too large to build in memory"
);
return Err(StatusCode::PAYLOAD_TOO_LARGE);
}
let mut entries: Vec<SbomEntry> = collect_cursor_async(
db.sbom_entries()
.find(of_parts)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
)
.await;
crate::license_conclusions::attach(&db, &mut entries).await;
let workspace = super::vex::author(&tenant);
let parts: Vec<MachinePart<'_>> = targets
.iter()
.zip(&ids)
.map(|(t, id)| {
let supplier = t.supplier.as_ref();
MachinePart {
id,
name: &t.name,
kind: part_kind(t.target_type),
supplier: supplier.map_or(workspace.as_str(), |s| s.name.as_str()),
version: supplier.and_then(|s| s.version.as_deref()),
}
})
.collect();
let body = sbom_docs::machine_cyclonedx(&name, &id, &parts, &entries);
super::vex::download(&body, &format!("sbom-machine-{id}-cyclonedx.json"))
}
/// One part of a machine in its overview.
#[derive(Debug, Serialize)]
pub struct PartOverview {
/// The target's id.
pub id: String,
pub name: String,
pub target_type: TargetType,
/// Its supplier, for a component bought in; none for one made in-house.
#[serde(skip_serializing_if = "Option::is_none")]
pub supplier: Option<SupplierComponent>,
/// Its open CVEs per severity, a CVE counted once per component.
pub open: SeverityCounts,
/// When its last scan ended (or started, while it runs); none before
/// the first.
#[serde(skip_serializing_if = "Option::is_none")]
pub last_scan_at: Option<DateTime<Utc>>,
}
/// The advisories of a machine's suppliers, as read for the workspace.
#[derive(Debug, Serialize)]
pub struct MachineAdvisories {
/// The advisories kept, over all its suppliers' providers.
pub advisories: u64,
/// The suppliers' providers, each once.
pub providers: usize,
/// When one of them was last read; none before the first refresh.
#[serde(skip_serializing_if = "Option::is_none")]
pub checked_at: Option<DateTime<Utc>>,
}
/// A machine at a glance: its parts and what is open across them.
#[derive(Debug, Serialize)]
pub struct MachineOverview {
pub name: String,
/// Its parts, by name.
pub parts: Vec<PartOverview>,
/// Its open CVEs per severity: its parts' together, as each part
/// decides on its own.
pub open: SeverityCounts,
/// The open alerts nobody has stated anything on yet.
pub undecided: usize,
/// Of those, the ones the supplier states something on.
pub undecided_with_supplier: usize,
/// Its components, each once, however many parts contain it.
pub components: u64,
/// Of those, the ones more than one part contains.
pub shared_components: u64,
/// Its suppliers' advisories; none when no part names a CSAF provider.
#[serde(skip_serializing_if = "Option::is_none")]
pub advisories: Option<MachineAdvisories>,
}
/// How many components the parts `ids` contain, each once, and how many of
/// them more than one part contains, counted by the database. A component
/// is known by its purl, else by its package manager, name and version, as
/// the SBOM documents name it; the supplier's product is the part itself.
async fn component_counts(db: &Database, ids: &[String]) -> Result<(u64, u64), StatusCode> {
let pipeline = vec![
doc! { "$match": {
"repo_id": { "$in": ids },
"package_manager": { "$ne": SUPPLIER_PRODUCT_MANAGER },
} },
doc! { "$group": {
"_id": { "$ifNull": [
"$purl",
{ "$concat": ["$package_manager", ":", "$name", "@", "$version"] },
] },
"parts": { "$addToSet": "$repo_id" },
} },
doc! { "$group": {
"_id": null,
"components": { "$sum": 1 },
"shared": { "$sum": { "$cond": [{ "$gt": [{ "$size": "$parts" }, 1] }, 1, 0] } },
} },
];
let mut cursor = db
.sbom_entries()
.aggregate(pipeline)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let Some(row) = cursor.next().await else {
return Ok((0, 0));
};
let row = row.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let count = |key: &str| {
row.get_i32(key)
.map(i64::from)
.or_else(|_| row.get_i64(key))
.map_or(0, |n| u64::try_from(n).unwrap_or(0))
};
Ok((count("components"), count("shared")))
}
/// The advisories of the suppliers `targets` name, read for the workspace.
async fn machine_advisories(
db: &Database,
targets: &[OnboardedTarget],
) -> Result<Option<MachineAdvisories>, StatusCode> {
let mut keys: Vec<String> = targets
.iter()
.filter_map(|t| t.supplier.as_ref()?.csaf_provider.as_deref())
.map(supplier_key)
.collect();
keys.sort_unstable();
keys.dedup();
if keys.is_empty() {
return Ok(None);
}
let advisories = MongoAdvisoryStore::supplier(db.inner())
.collection()
.count_documents(doc! { "provider": { "$in": &keys } })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let checked_at = db
.inner()
.collection::<SupplierProviderStatus>(SupplierProviderStatus::COLLECTION)
.find_one(doc! { "_id": { "$in": &keys } })
.sort(doc! { "checked_at": -1 })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.map(|s| s.checked_at.to_chrono());
Ok(Some(MachineAdvisories {
advisories,
providers: keys.len(),
checked_at,
}))
}
/// The open CVEs per severity of `alerts`, a CVE counted once per component.
pub(super) fn open_counts<'a>(alerts: impl IntoIterator<Item = &'a CveAlert>) -> SeverityCounts {
let alerts: Vec<CveAlert> = alerts.into_iter().cloned().collect();
cve_groups::group_open_alerts(&alerts)
.iter()
.fold(SeverityCounts::default(), |sum, g| sum.plus(g.counts))
}
/// Whether nobody has stated anything on `alert` yet: no statement of a
/// person's.
fn undecided(alert: &CveAlert) -> bool {
alert.vex.as_ref().is_none_or(|v| v.by_scan)
}
/// A machine at a glance: its parts and what is open across them.
///
/// Each part with its supplier, open CVEs and last scan; across them the
/// open and undecided CVEs, the components and the suppliers' advisories.
#[utoipa::path(
get,
path = "/api/v1/projects/{id}/overview",
tag = "Targets",
params(("id" = String, Path, description = "The project's id")),
responses(
(status = 200, description = "The machine at a glance (`data`)"),
(status = 404, description = "No such project"),
(status = 422, description = "The project is a topic, not a product"),
(status = 503, description = "The registry cannot be asked"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(project_id = %id))]
pub async fn machine_overview(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> Result<Json<ApiResponse<MachineOverview>>, StatusCode> {
let (machine, db) = machine(&agent, &tenant, &id).await?;
let alerts = open_alerts(&db, &machine.ids).await?;
let (components, shared_components) = component_counts(&db, &machine.ids).await?;
let advisories = machine_advisories(&db, &machine.targets).await?;
let mut last_scans =
super::onboarding::latest_scan_runs(&db.scan_runs(), machine.ids.clone(), false).await;
let mut by_part: HashMap<&str, Vec<&CveAlert>> = HashMap::new();
for alert in &alerts {
by_part
.entry(alert.repo_id.as_str())
.or_default()
.push(alert);
}
let parts: Vec<PartOverview> = machine
.targets
.into_iter()
.zip(&machine.ids)
.map(|(t, id)| PartOverview {
open: open_counts(by_part.remove(id.as_str()).unwrap_or_default()),
last_scan_at: last_scans
.remove(id)
.map(|run| run.completed_at.unwrap_or(run.started_at)),
id: id.clone(),
name: t.name,
target_type: t.target_type,
supplier: t.supplier,
})
.collect();
let undecided_alerts: Vec<&CveAlert> = alerts.iter().filter(|a| undecided(a)).collect();
Ok(Json(ApiResponse {
data: MachineOverview {
open: parts
.iter()
.fold(SeverityCounts::default(), |sum, p| sum.plus(p.open)),
parts,
name: machine.name,
undecided: undecided_alerts.len(),
undecided_with_supplier: undecided_alerts
.iter()
.filter(|a| a.supplier_vex.is_some())
.count(),
components,
shared_components,
advisories,
},
total: None,
page: None,
}))
}
/// A machine's open CVEs: grouped by component across its parts, and the
/// alerts themselves, each with its part (`repo_id`).
#[derive(Debug, Serialize)]
pub struct MachineCves {
/// The groups, the most severe first; a group's `alert_ids` may belong
/// to several parts.
pub groups: Vec<CveGroup>,
/// The open alerts, by CVE.
pub alerts: Vec<CveAlert>,
}
/// A machine's open CVEs, grouped by component across its parts.
///
/// A component in several parts is one group, with the alerts of every part
/// it is in: whether it affects the machine is stated per part, as the code
/// may be reached in one and not in another.
#[utoipa::path(
get,
path = "/api/v1/projects/{id}/cves",
tag = "CVEs",
params(("id" = String, Path, description = "The project's id")),
responses(
(status = 200, description = "The groups and the open alerts (`data`)"),
(status = 404, description = "No such project"),
(status = 422, description = "The project is a topic, not a product"),
(status = 503, description = "The registry cannot be asked"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(project_id = %id))]
pub async fn machine_cves(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> Result<Json<ApiResponse<MachineCves>>, StatusCode> {
let (machine, db) = machine(&agent, &tenant, &id).await?;
let alerts = open_alerts(&db, &machine.ids).await?;
Ok(Json(ApiResponse {
data: MachineCves {
groups: cve_groups::group_open_alerts(&alerts),
alerts,
},
total: None,
page: None,
}))
}
/// One scan of one of a machine's parts, with what it changed.
#[derive(Debug, Serialize)]
pub struct MachineChange {
/// The part (its target's id).
pub part: String,
#[serde(flatten)]
pub change: ScanChange,
}
/// What changed in a machine: the last scans of its parts, the newest first.
///
/// Each scan comes with the CVEs it found new and gone and the components
/// it added, updated and removed, as a target's own history (`limit`, 20
/// when not given, at most 50, over all parts). A supplier's new version
/// shows as its product updated (`from` → `to`) in a part bought in.
#[utoipa::path(
get,
path = "/api/v1/projects/{id}/scan-changes",
tag = "CVEs",
params(
("id" = String, Path, description = "The project's id"),
("limit" = Option<usize>, Query, description = "The scans to show, 1 to 50"),
),
responses(
(status = 200, description = "The parts' scans, each with its part (`data`)"),
(status = 404, description = "No such project"),
(status = 422, description = "The project is a topic, not a product"),
(status = 503, description = "The registry cannot be asked"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(project_id = %id))]
pub async fn machine_scan_changes(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
Query(query): Query<super::scan_changes::ChangesQuery>,
) -> Result<Json<ApiResponse<Vec<MachineChange>>>, StatusCode> {
let (machine, db) = machine(&agent, &tenant, &id).await?;
let per_part = futures_util::future::try_join_all(
machine
.ids
.iter()
.map(|part| super::scan_changes::target_changes(&db, part, query.limit)),
)
.await?;
let mut data: Vec<MachineChange> = machine
.ids
.iter()
.zip(per_part)
.flat_map(|(part, changes)| {
changes.into_iter().map(|change| MachineChange {
part: part.clone(),
change,
})
})
.collect();
data.sort_by_key(|c| std::cmp::Reverse(c.change.started_at));
data.truncate(query.limit);
Ok(Json(ApiResponse {
total: Some(data.len() as u64),
data,
page: None,
}))
}
@@ -46,11 +46,9 @@ impl From<ManualKind> for ScanType {
}
}
/// The body of [`create_finding`]: a finding from a manual test.
#[derive(Debug, Deserialize, utoipa::ToSchema)]
/// `POST /api/v1/targets/{id}/findings`.
#[derive(Debug, Deserialize)]
pub struct CreateFindingRequest {
/// `dast` or `pentest`: the manual test the finding comes from.
#[schema(value_type = String, example = "pentest")]
pub kind: ManualKind,
/// The tool used, if any; `manual` otherwise.
#[serde(default)]
@@ -68,14 +66,9 @@ pub enum ImportFormat {
}
/// `?format=&kind=` of an import.
#[derive(Debug, Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Debug, Deserialize)]
pub struct ImportParams {
/// `sarif` or `zap`.
#[param(value_type = String, example = "sarif")]
pub format: ImportFormat,
/// `dast` or `pentest`.
#[param(value_type = String, example = "dast")]
pub kind: ManualKind,
}
@@ -131,26 +124,8 @@ async fn insert_new(db: &Database, finding: &mut Finding) -> Result<bool, Status
Ok(true)
}
/// Add a finding from a manual DAST run or penetration test.
///
/// 409 when the same finding (tool, title, location) is already on the
/// target. Only an organisation's administrator (IT_ADMIN, OWNER).
#[utoipa::path(
post,
path = "/api/v1/targets/{id}/findings",
tag = "Findings",
params(("id" = String, Path, description = "The target's id")),
request_body = CreateFindingRequest,
responses(
(status = 201, description = "The finding"),
(status = 400, description = "Not an id"),
(status = 403, description = "Only an administrator adds findings by hand"),
(status = 404, description = "No such target"),
(status = 409, description = "The same finding is already on the target"),
(status = 422, description = "A malformed finding"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/targets/{id}/findings — add one finding by hand. 409 when the
/// same finding (tool, title, location) is already on the target.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn create_finding(
Extension(agent): AgentExt,
@@ -189,26 +164,9 @@ pub async fn create_finding(
))
}
/// Import the findings of a SARIF or ZAP report; the body is the report.
///
/// Findings already on the target are skipped, so importing a report again
/// adds nothing. Only an organisation's administrator (IT_ADMIN, OWNER).
#[utoipa::path(
post,
path = "/api/v1/targets/{id}/findings/import",
tag = "Findings",
params(("id" = String, Path, description = "The target's id"), ImportParams),
request_body(content = Object, description = "The SARIF or ZAP JSON report"),
responses(
(status = 200, description = "What the import did"),
(status = 400, description = "Not an id"),
(status = 403, description = "Only an administrator imports findings"),
(status = 404, description = "No such target"),
(status = 413, description = "The report is larger than 20 MiB"),
(status = 422, description = "The report cannot be read"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/targets/{id}/findings/import?format=sarif|zap&kind=dast|pentest
/// — the body is the report itself. Findings already on the target are
/// skipped, so importing a report again adds nothing.
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn import_findings(
Extension(agent): AgentExt,
@@ -49,9 +49,7 @@ const ALL_TOOLS: [&str; 7] = [
"dast_scan_summary",
];
/// The query of [`list_mcp_servers`].
#[derive(Debug, serde::Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Debug, serde::Deserialize)]
pub struct ListQuery {
/// Where the deployment's MCP server answers (the dashboard's
/// `MCP_ENDPOINT_URL`), for the default cards of a tenant that has none.
@@ -59,26 +57,18 @@ pub struct ListQuery {
pub default_endpoint: Option<String>,
}
/// The body of [`create_mcp_server`].
#[derive(Debug, serde::Deserialize, utoipa::ToSchema)]
#[derive(Debug, serde::Deserialize)]
pub struct CreateRequest {
/// The card's name.
pub name: String,
/// Where the MCP server answers.
pub endpoint_url: String,
/// The transport, such as `streamable-http`.
#[serde(default)]
pub transport: String,
/// The port, when not in the URL.
#[serde(default)]
pub port: Option<u16>,
/// A description.
#[serde(default)]
pub description: Option<String>,
/// The MongoDB URI the server reads, for a server of its own.
#[serde(default)]
pub mongodb_uri: Option<String>,
/// The MongoDB database the server reads.
#[serde(default)]
pub mongodb_database: Option<String>,
}
@@ -136,19 +126,8 @@ async fn seed_defaults(db: &Database, endpoint: &str) -> Result<(), mongodb::err
Ok(())
}
/// The tenant's MCP server cards, newest first.
///
/// The access tokens only for roles that may change things.
#[utoipa::path(
get,
path = "/api/v1/mcp-servers",
tag = "MCP",
params(ListQuery),
responses(
(status = 200, description = "The cards"),
(status = 401, description = "No valid bearer token"),
)
)]
/// `GET /api/v1/mcp-servers` — the tenant's cards, newest first; the access
/// tokens only for roles that may change things.
#[tracing::instrument(skip_all)]
pub async fn list_mcp_servers(
Extension(agent): AgentExt,
@@ -176,18 +155,7 @@ pub async fn list_mcp_servers(
Ok(Json(serde_json::json!({ "data": servers })))
}
/// Add an MCP server card.
#[utoipa::path(
post,
path = "/api/v1/mcp-servers",
tag = "MCP",
request_body = CreateRequest,
responses(
(status = 200, description = "The new card"),
(status = 400, description = "No name or no endpoint URL"),
(status = 401, description = "No valid bearer token"),
)
)]
/// `POST /api/v1/mcp-servers` — add a card to the tenant.
#[tracing::instrument(skip_all)]
pub async fn create_mcp_server(
Extension(agent): AgentExt,
@@ -226,19 +194,8 @@ pub async fn create_mcp_server(
Ok(Json(serde_json::json!({ "id": inserted.inserted_id })))
}
/// Remove an MCP server card.
#[utoipa::path(
delete,
path = "/api/v1/mcp-servers/{id}",
tag = "MCP",
params(("id" = String, Path, description = "The card's id")),
responses(
(status = 204, description = "Removed"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such card"),
(status = 401, description = "No valid bearer token"),
)
)]
/// `DELETE /api/v1/mcp-servers/{id}` — remove one of the tenant's cards; 404
/// for an id the tenant has not.
#[tracing::instrument(skip_all, fields(server_id = %id))]
pub async fn delete_mcp_server(
Extension(agent): AgentExt,
@@ -258,19 +215,8 @@ pub async fn delete_mcp_server(
Ok(StatusCode::NO_CONTENT)
}
/// Give an MCP server card a new access token.
#[utoipa::path(
post,
path = "/api/v1/mcp-servers/{id}/token",
tag = "MCP",
params(("id" = String, Path, description = "The card's id")),
responses(
(status = 200, description = "The new token"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such card"),
(status = 401, description = "No valid bearer token"),
)
)]
/// `POST /api/v1/mcp-servers/{id}/token` — give one of the tenant's cards a
/// new access token; 404 for an id the tenant has not.
#[tracing::instrument(skip_all, fields(server_id = %id))]
pub async fn regenerate_mcp_server_token(
Extension(agent): AgentExt,
@@ -33,10 +33,8 @@ const TOKEN_PREFIX: &str = "mcpt_";
/// Combined with `mcpt_` → 48-char tokens.
const TOKEN_RAND_BYTES: usize = 32;
/// The body of [`create_mcp_token`].
#[derive(serde::Deserialize, utoipa::ToSchema)]
#[derive(serde::Deserialize)]
pub struct CreateMcpTokenRequest {
/// What the token is for.
pub name: String,
}
@@ -48,18 +46,7 @@ pub struct CreateMcpTokenResponse {
pub view: McpTokenView,
}
/// Mint an MCP token for the tenant; it is shown only in this answer.
#[utoipa::path(
post,
path = "/api/v1/mcp-tokens",
tag = "MCP",
request_body = CreateMcpTokenRequest,
responses(
(status = 200, description = "The token, once"),
(status = 400, description = "No name"),
(status = 401, description = "No valid bearer token"),
)
)]
/// `POST /api/v1/mcp-tokens` — mint a new token for the caller's tenant.
#[tracing::instrument(skip_all)]
pub async fn create_mcp_token(
Extension(agent): AgentExt,
@@ -98,19 +85,9 @@ pub async fn create_mcp_token(
}))
}
/// The tenant's MCP tokens, without the tokens.
///
/// The hash is never returned; only metadata and the 12-character prefix,
/// so the user can tell which row is which.
#[utoipa::path(
get,
path = "/api/v1/mcp-tokens",
tag = "MCP",
responses(
(status = 200, description = "The tokens"),
(status = 401, description = "No valid bearer token"),
)
)]
/// `GET /api/v1/mcp-tokens` — list tokens for the caller's tenant.
/// Hash is never returned; only metadata + the 12-char prefix so the
/// user can identify which row is which.
#[tracing::instrument(skip_all)]
pub async fn list_mcp_tokens(
Extension(agent): AgentExt,
@@ -142,22 +119,9 @@ pub async fn list_mcp_tokens(
}))
}
/// Revoke an MCP token.
///
/// `DELETE /api/v1/mcp-tokens/{id}` — revoke (soft delete).
/// Scoped to the caller's tenant: a user can't revoke another tenant's
/// token even if they guess its id.
#[utoipa::path(
delete,
path = "/api/v1/mcp-tokens/{id}",
tag = "MCP",
params(("id" = String, Path, description = "The token's id")),
responses(
(status = 200, description = "Revoked"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such token"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(id = %id))]
pub async fn revoke_mcp_token(
Extension(agent): AgentExt,
+2 -13
View File
@@ -27,23 +27,12 @@ struct UsageView {
prueftag_cap: Option<u32>,
}
/// The tenant's usage this month, with the plan's limits.
///
/// Prüfungen, Prüftage and extra targets this month (Europe/Berlin).
/// GET /api/v1/metering/usage — the tenant's Prüfungen, Prüftage and extra
/// targets this month (Europe/Berlin), with the plan's limits.
///
/// # Errors
///
/// `500` when the counters cannot be read.
#[utoipa::path(
get,
path = "/api/v1/metering/usage",
tag = "Workspace",
responses(
(status = 200, description = "The usage"),
(status = 500, description = "The counters cannot be read"),
(status = 401, description = "No valid bearer token"),
)
)]
pub async fn get_usage(
Extension(agent): AgentExt,
tenant: TenantCtx,
-9
View File
@@ -1,10 +1,8 @@
pub mod admin;
pub mod chat;
pub mod connections;
pub mod cve_history;
pub mod cve_matrix;
pub mod dast;
mod delivery;
pub mod demo_seed;
pub mod dto;
pub mod evidence;
@@ -18,28 +16,21 @@ pub mod help_chat;
pub mod inbox;
pub mod issues;
pub mod licenses;
pub mod machine;
pub mod manual_findings;
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;
pub mod platform;
pub mod projects;
pub mod releases;
pub use pentest_handlers as pentest;
pub mod sbom;
pub mod sbom_ecosystems;
pub mod scan_changes;
pub mod scans;
pub mod supplier;
pub mod supplier_invites;
pub mod supply_chain;
pub mod supply_chain_layout;
pub mod support;
pub mod target_input;
pub mod vex;
@@ -9,17 +9,7 @@ use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{tenant_db, AgentExt, ApiResponse};
/// The tenant's CVE notifications, newest first, a page at a time.
#[utoipa::path(
get,
path = "/api/v1/notifications",
tag = "Notifications",
params(NotificationFilter),
responses(
(status = 200, description = "A page of notifications"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/notifications — List CVE notifications (newest first)
#[tracing::instrument(skip_all)]
pub async fn list_notifications(
Extension(agent): AgentExt,
@@ -95,16 +85,7 @@ pub async fn list_notifications(
}))
}
/// The number of unread notifications.
#[utoipa::path(
get,
path = "/api/v1/notifications/count",
tag = "Notifications",
responses(
(status = 200, description = "The count"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/notifications/count — Count of unread notifications
#[tracing::instrument(skip_all)]
pub async fn notification_count(
Extension(agent): AgentExt,
@@ -120,19 +101,7 @@ pub async fn notification_count(
Ok(Json(serde_json::json!({ "count": count })))
}
/// Mark a notification as read.
#[utoipa::path(
patch,
path = "/api/v1/notifications/{id}/read",
tag = "Notifications",
params(("id" = String, Path, description = "The notification's id")),
responses(
(status = 200, description = "Marked as read"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such notification"),
(status = 401, description = "No valid bearer token"),
)
)]
/// PATCH /api/v1/notifications/:id/read — Mark a notification as read
#[tracing::instrument(skip_all, fields(id = %id))]
pub async fn mark_read(
Extension(agent): AgentExt,
@@ -160,19 +129,7 @@ pub async fn mark_read(
Ok(Json(serde_json::json!({ "status": "read" })))
}
/// Dismiss a notification.
#[utoipa::path(
patch,
path = "/api/v1/notifications/{id}/dismiss",
tag = "Notifications",
params(("id" = String, Path, description = "The notification's id")),
responses(
(status = 200, description = "Dismissed"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such notification"),
(status = 401, description = "No valid bearer token"),
)
)]
/// PATCH /api/v1/notifications/:id/dismiss — Dismiss a notification
#[tracing::instrument(skip_all, fields(id = %id))]
pub async fn dismiss_notification(
Extension(agent): AgentExt,
@@ -197,16 +154,7 @@ pub async fn dismiss_notification(
Ok(Json(serde_json::json!({ "status": "dismissed" })))
}
/// Mark every new notification as read.
#[utoipa::path(
post,
path = "/api/v1/notifications/read-all",
tag = "Notifications",
responses(
(status = 200, description = "Marked as read"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/notifications/read-all — Mark all new notifications as read
#[tracing::instrument(skip_all)]
pub async fn mark_all_read(
Extension(agent): AgentExt,
@@ -230,20 +178,11 @@ pub async fn mark_all_read(
))
}
/// Which notifications a list shows.
#[derive(Debug, Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Debug, Deserialize)]
pub struct NotificationFilter {
/// `new`, `read`, `dismissed` or `all`; new and read without it.
pub status: Option<String>,
/// Only one severity.
pub severity: Option<String>,
/// Only one target's notifications (its id).
pub repo_id: Option<String>,
/// The page, from 1 (default 1, at most 100 000).
#[param(minimum = 1, maximum = 100_000)]
pub page: Option<u64>,
/// Entries per page (default 50, at most 200).
#[param(minimum = 1, maximum = 200)]
pub limit: Option<i64>,
}
-702
View File
@@ -1,702 +0,0 @@
//! 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>,
/// The content hash of the version last delivered, so the same version
/// is never delivered twice.
#[serde(default)]
pub delivered_hash: Option<String>,
/// The label of the version last delivered.
#[serde(default)]
pub delivered_label: Option<String>,
#[serde(default)]
pub delivered_at: Option<BsonDateTime>,
/// While the offer is open: the supplier's latest published version,
/// what accepting delivers at once, and how many components it lists.
#[serde(default)]
pub offered_label: Option<String>,
#[serde(default)]
pub offered_components: Option<i64>,
}
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, the product's, and the version it offers.
#[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>>,
/// The version last delivered into the component, and when.
pub delivered_label: Option<String>,
pub delivered_at: Option<DateTime<Utc>>,
/// While it is open: the version accepting delivers at once, and how
/// many components it lists; `None` before the supplier published one.
pub offered_label: Option<String>,
pub offered_components: Option<i64>,
}
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),
delivered_label: o.delivered_label,
delivered_at: o.delivered_at.map(BsonDateTime::to_chrono),
offered_label: o.offered_label,
offered_components: o.offered_components,
}
}
}
/// 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(())
}
/// Tell `customer`'s open offer of release `release` that `label` (with
/// `components` components) is now what accepting delivers. Best-effort:
/// the next publication tells it again.
pub(super) async fn announce(
agent: &ComplianceAgent,
customer: &str,
release: &str,
label: &str,
components: i64,
) {
let db = agent.db_pool.for_existing_tenant_id(customer);
let told = offers(&db)
.update_one(
doc! { "release_id": release, "state": "offered" },
doc! { "$set": { "offered_label": label, "offered_components": components } },
)
.await;
if let Err(e) = told {
tracing::warn!(release, "new version not announced to the customer: {e}");
}
}
/// 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;
// What the supplier already published arrives at once.
let accepted = find(&db, &id).await?;
super::delivery::deliver_latest(&agent, &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())
}
+41 -534
View File
@@ -43,77 +43,6 @@ pub struct CreateTargetRequest {
/// The target's artifacts by reference; files are uploaded afterwards.
#[serde(default)]
pub artifacts: Vec<ArtifactInput>,
/// Who supplies the component, for one bought in (#1025).
#[serde(default)]
pub supplier: Option<SupplierInput>,
}
/// A supplier as a client sends it (#1025). An empty `name` removes it.
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct SupplierInput {
/// The supplier's name; empty removes the supplier.
pub name: String,
/// The supplier's name for the product, as its advisories name it.
#[serde(default)]
pub product: Option<String>,
/// The product's version in use.
#[serde(default)]
pub version: Option<String>,
/// The supplier's CSAF `provider-metadata.json`, an https URL. Its public
/// advisories are fetched for this workspace only.
#[serde(default)]
#[schema(example = "https://supplier.example/.well-known/csaf/provider-metadata.json")]
pub csaf_provider: Option<String>,
}
impl SupplierInput {
/// The supplier to store; `None` removes it.
///
/// # Errors
///
/// 422 for a CSAF provider that is not an https URL.
pub fn build(self) -> Result<Option<compliance_core::models::SupplierComponent>, StatusCode> {
let text = |v: Option<String>| v.map(|t| t.trim().to_string()).filter(|t| !t.is_empty());
let name = self.name.trim().to_string();
if name.is_empty() {
return Ok(None);
}
let csaf_provider = text(self.csaf_provider);
if csaf_provider
.as_deref()
.is_some_and(|url| !is_https_url(url))
{
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
Ok(Some(compliance_core::models::SupplierComponent {
name,
product: text(self.product),
version: text(self.version),
csaf_provider,
}))
}
}
/// Whether `url` is an https URL with a host: what a CSAF provider must be.
pub(super) fn is_https_url(url: &str) -> bool {
reqwest::Url::parse(url).is_ok_and(|u| u.scheme() == "https" && u.host_str().is_some())
}
/// Fetch the advisories of tenant `tenant_id`'s supplier providers now, in
/// the background, when `supplier` names one: a provider just set is then
/// matched by the next scan, not only after the nightly refresh.
pub(super) fn refresh_supplier_csaf(
agent: &Arc<ComplianceAgent>,
tenant_id: &str,
supplier: Option<&compliance_core::models::SupplierComponent>,
) {
if supplier.and_then(|s| s.csaf_provider.as_ref()).is_none() {
return;
}
let (agent, tenant_id) = (Arc::clone(agent), tenant_id.to_string());
tokio::spawn(async move {
crate::pipeline::csaf_feed::refresh_supplier_advisories(&agent, &tenant_id).await;
});
}
/// The body of [`update_target`]. A field left out keeps its stored value.
@@ -138,9 +67,6 @@ pub struct UpdateTargetRequest {
/// keeps the token and uploaded file of the stored artifact it matches.
#[serde(default)]
pub artifacts: Option<Vec<ArtifactInput>>,
/// Who supplies the component (#1025); an empty `name` removes it.
#[serde(default)]
pub supplier: Option<SupplierInput>,
}
/// One applicable-scan option, serialized for the wizard.
@@ -378,51 +304,30 @@ pub async fn create_target(
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
let mut target = OnboardedTarget::new(req.name, req.target_type);
target.description = req.description;
if let Some(supplier) = req.supplier {
target.supplier = supplier.build()?;
}
target.artifacts = merge_artifacts(&agent.secrets, &req.artifacts, &[]).map_err(|e| {
tracing::error!("storing a credential: {e}");
StatusCode::SERVICE_UNAVAILABLE
})?;
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_id, target.supplier.as_ref());
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
agent.emit_usage(
tenant_id,
&tenant.0.tenant_id,
"target.added",
format!("target:{tenant_id}:{target_id}"),
format!("target:{}:{target_id}", tenant.0.tenant_id),
serde_json::json!({ "target_id": target_id, "target_type": format!("{:?}", target.target_type) }),
);
Ok(target)
Ok(Json(ApiResponse {
data: target.redacted(),
total: None,
page: None,
}))
}
/// One target, credentials redacted.
@@ -611,29 +516,10 @@ pub async fn update_target(
);
}
let mut update = doc! {};
let mut supplier = None;
if let Some(input) = req.supplier {
supplier = input.build()?;
match &supplier {
Some(s) => {
set.insert(
"supplier",
to_bson(s).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
);
}
None => {
update.insert("$unset", doc! { "supplier": "" });
}
}
}
update.insert("$set", set);
db.onboarded_targets()
.update_one(doc! { "_id": oid }, update)
.update_one(doc! { "_id": oid }, doc! { "$set": set })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
refresh_supplier_csaf(&agent, &tenant.0.tenant_id, supplier.as_ref());
// Background and best-effort: the registry being down never fails the
// change itself.
if let (Some(entry), Some(registry)) = (projects_audit, agent.registry.clone()) {
@@ -695,9 +581,6 @@ 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;
@@ -723,19 +606,6 @@ pub async fn delete_target(
.embedding_builds()
.delete_many(doc! { "repo_id": &id })
.await;
// Its supplier invites and their uploads: the links allow nothing once
// it is gone.
for collection in [
super::supplier_invites::SupplierInvite::COLLECTION,
super::supplier_invites::SupplierUpload::COLLECTION,
super::releases::SbomRelease::COLLECTION,
super::releases::SbomVersion::COLLECTION,
] {
let _ = db
.raw_collection(collection)
.delete_many(doc! { "target_id": &id })
.await;
}
// DAST targets linked to this target, and all their downstream data.
for dast_target_id in ids_of(db.dast_targets(), doc! { "repo_id": &id }).await {
@@ -863,8 +733,7 @@ pub struct UploadArtifactForm {
#[schema(value_type = String, format = Binary)]
file: Vec<u8>,
/// What the file is, such as `plc_project`, `firmware_image`,
/// `source_archive`, `mobile_package`, `build_output` or `supplier_sbom`
/// (a supplier's CycloneDX or SPDX 2 SBOM of a bought-in component).
/// `source_archive` or `mobile_package`.
#[schema(example = "source_archive")]
kind: String,
/// The PLC project's format, for a PLC project.
@@ -873,8 +742,7 @@ pub struct UploadArtifactForm {
/// Attach an artifact to a target by uploading its file.
///
/// A PLC project, firmware image, source archive, mobile package, build
/// output or a supplier's SBOM of a bought-in component.
/// A PLC project, firmware image, source archive or mobile package.
///
/// The file is **streamed to disk** chunk by chunk as it arrives, never held in
/// memory whole (it used to be read into one buffer of up to 512 MiB, per
@@ -894,9 +762,8 @@ pub struct UploadArtifactForm {
(status = 200, description = "The target with the artifact"),
(status = 404, description = "No such target"),
(status = 400, description = "Not an id, or a missing or unknown field"),
(status = 413, description = "The file is too large (a supplier SBOM: over 20 MiB)"),
(status = 413, description = "The file is too large"),
(status = 415, description = "An archive format that cannot be unpacked"),
(status = 422, description = "A supplier SBOM that cannot be read; `error` says why"),
(status = 401, description = "No valid bearer token"),
)
)]
@@ -906,17 +773,18 @@ pub async fn upload_artifact(
tenant: TenantCtx,
Path(id): Path<String>,
mut multipart: Multipart,
) -> Result<Json<ApiResponse<OnboardedTarget>>, UploadRefusal> {
) -> Result<Json<ApiResponse<OnboardedTarget>>, StatusCode> {
let oid = parse_oid(&id)?;
let db = tenant_db(&agent, &tenant).await?;
let Some(stored_target) = db
if db
.onboarded_targets()
.find_one(doc! { "_id": oid })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
else {
return Err(StatusCode::NOT_FOUND.into());
};
.is_none()
{
return Err(StatusCode::NOT_FOUND);
}
let mut kind: Option<ArtifactKind> = None;
let mut plc_format: Option<PlcFormat> = None;
@@ -937,14 +805,14 @@ pub async fn upload_artifact(
}
"file" => {
if stored.is_some() {
return Err(StatusCode::BAD_REQUEST.into());
return Err(StatusCode::BAD_REQUEST);
}
if let Some(fname) = field.file_name() {
filename = fname.to_string();
}
let dest = upload_dest(&agent, &id, &filename)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut upload = StoredUpload::new(dest, filename.clone());
let mut upload = StoredUpload::new(dest);
upload.size = stream_to_disk(&mut field, &upload.path, MAX_UPLOAD_BYTES).await?;
stored = Some(upload);
}
@@ -953,48 +821,11 @@ pub async fn upload_artifact(
}
let (Some(kind), Some(upload)) = (kind, stored) else {
return Err(StatusCode::BAD_REQUEST.into());
return Err(StatusCode::BAD_REQUEST);
};
attach_upload(&db, &stored_target, kind, plc_format, upload).await?;
Ok(get_target(Extension(agent), tenant, Path(id)).await?)
}
/// What [`attach_upload`] kept.
#[derive(Debug)]
pub(super) struct AttachedUpload {
/// The new artifact's id.
pub artifact_id: String,
/// What a supplier SBOM holds; `None` for any other kind.
pub summary: Option<SupplierSbomSummary>,
}
/// Keep `upload`, a file already on disk, as an artifact of kind `kind` of
/// `target`: what every upload does once its file has arrived, the customer's
/// and a supplier's through an invite (#1027) alike.
///
/// The file's hash is kept for change detection. A supplier SBOM is read and
/// refused when it cannot be, its summary is kept with it, and it replaces the
/// target's previous one. Any other archive is checked for a format that can
/// be unpacked and for encryption. The file is deleted unless the artifact
/// references it.
///
/// # Errors
///
/// 400 for a kind that is not uploaded as a file, 415 for an archive that
/// cannot be unpacked, the supplier SBOM's refusal ([`SupplierSbomSummary::of`]),
/// 500 when the file or the database fails.
pub(super) async fn attach_upload(
db: &crate::database::Database,
target: &OnboardedTarget,
kind: ArtifactKind,
plc_format: Option<PlcFormat>,
upload: StoredUpload,
) -> Result<AttachedUpload, UploadRefusal> {
let oid = target.id.ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;
// Non-file kinds (git repo, live URL, container ref, text) use the JSON
// add-artifact endpoint, not upload.
let mut artifact = uploaded_artifact(kind, plc_format, &upload.name, &upload.path, upload.size)
let mut artifact = uploaded_artifact(kind, plc_format, &filename, &upload.path, upload.size)
.ok_or(StatusCode::BAD_REQUEST)?;
// What a scheduled scan compares to tell this upload from the files its
// last scan read (#465): without it, no upload was ever known unchanged.
@@ -1004,22 +835,10 @@ pub(super) async fn attach_upload(
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
artifact.content_hash = Some(sha);
artifact.ingested_at = Some(chrono::Utc::now());
let mut summary = None;
if kind == ArtifactKind::SupplierSbom {
let path = upload.path.clone();
let read = tokio::task::spawn_blocking(move || {
crate::pipeline::sbom::supplied::read_with_statements(&path, "", "")
})
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let read = SupplierSbomSummary::of(read)?;
artifact.detected.extend(read.facts());
summary = Some(read);
} else if kind != ArtifactKind::FirmwareImage {
if kind != ArtifactKind::FirmwareImage {
match archive_check(upload.path.clone()).await? {
// 7z and rar are never unpacked: say so now, not after a scan.
ArchiveCheck::Unsupported => return Err(StatusCode::UNSUPPORTED_MEDIA_TYPE.into()),
ArchiveCheck::Unsupported => return Err(StatusCode::UNSUPPORTED_MEDIA_TYPE),
// Kept, and marked: the dashboard asks for the password.
ArchiveCheck::Encrypted => {
artifact
@@ -1030,7 +849,6 @@ pub(super) async fn attach_upload(
}
}
let artifact_id = artifact.id.clone();
let artifact_bson = to_bson(&artifact).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
db.onboarded_targets()
.update_one(
@@ -1040,219 +858,8 @@ pub(super) async fn attach_upload(
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
upload.keep();
if kind == ArtifactKind::SupplierSbom {
replace_supplier_sboms(db, oid, &artifact_id, &target.artifacts).await;
}
Ok(AttachedUpload {
artifact_id,
summary,
})
}
/// Remove the target's supplier SBOMs other than the one just uploaded
/// (`kept`): a new version replaces the one before it (#1025), so a scan never
/// reads two versions as one. Their files go too, once nothing references
/// them. Best-effort, after the new one is stored: if this fails, the next
/// scan reads both versions, and nothing is lost.
async fn replace_supplier_sboms(
db: &crate::database::Database,
target: ObjectId,
kept: &str,
before: &[compliance_core::models::Artifact],
) {
let pulled = db
.onboarded_targets()
.update_one(
doc! { "_id": target },
doc! { "$pull": { "artifacts": { "kind": "supplier_sbom", "id": { "$ne": kept } } } },
)
.await;
if let Err(e) = pulled {
tracing::warn!(target_id = %target, error = %e, "replaced supplier SBOM not removed");
return;
}
for old in before
.iter()
.filter(|a| a.kind == ArtifactKind::SupplierSbom && a.id != kept)
.filter_map(|a| a.stored_path.as_deref())
{
if let Err(e) = std::fs::remove_file(old) {
tracing::warn!(target_id = %target, error = %e, "replaced supplier SBOM file left");
}
}
}
/// Why an upload is refused: its status and, for a supplier SBOM that cannot
/// be read, why (as `{"error": …, "code": …}`, for the dashboard to show).
#[derive(Debug)]
pub struct UploadRefusal {
status: StatusCode,
reason: Option<(String, &'static str)>,
}
impl UploadRefusal {
/// A refusal with its reason and code.
pub(super) fn because(
status: StatusCode,
error: impl Into<String>,
code: &'static str,
) -> Self {
Self {
status,
reason: Some((error.into(), code)),
}
}
/// Its code, when it gives one.
pub(super) fn code(&self) -> Option<&'static str> {
self.reason.as_ref().map(|(_, code)| *code)
}
}
impl From<StatusCode> for UploadRefusal {
fn from(status: StatusCode) -> Self {
Self {
status,
reason: None,
}
}
}
impl axum::response::IntoResponse for UploadRefusal {
fn into_response(self) -> axum::response::Response {
match self.reason {
Some((error, code)) => (
self.status,
Json(serde_json::json!({ "error": error, "code": code })),
)
.into_response(),
None => self.status.into_response(),
}
}
}
/// The fact keys an upload keeps a supplier SBOM's [`SupplierSbomSummary`]
/// under, for the target editor to show.
pub const SBOM_FORMAT_FACT: &str = "sbom_format";
/// See [`SBOM_FORMAT_FACT`].
pub const SBOM_COMPONENTS_FACT: &str = "sbom_components";
/// See [`SBOM_FORMAT_FACT`].
pub const SBOM_STATEMENTS_FACT: &str = "sbom_statements";
/// What a readable supplier SBOM holds (#1025): what the wizard shows when the
/// file is added, and what its upload keeps with the artifact.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SupplierSbomSummary {
/// The format and its version, such as `CycloneDX 1.5` or `SPDX 2.3`.
pub format: String,
/// The components it lists, nested ones included.
pub components: usize,
/// What the supplier states about its components' vulnerabilities
/// (CycloneDX VEX), one per vulnerability and component.
pub statements: usize,
}
impl SupplierSbomSummary {
/// The summary of a supplier SBOM as read, or why it is refused: the same
/// verdict for the check and for the upload.
///
/// # Errors
///
/// 413 past [`crate::pipeline::sbom::supplied::MAX_BYTES`], 500 when the
/// file cannot be read, 422 with the reason and its code for one that
/// cannot be read as an SBOM.
fn of(
read: Result<
crate::pipeline::sbom::supplied::SuppliedSbom,
crate::pipeline::sbom::supplied::SuppliedSbomError,
>,
) -> Result<Self, UploadRefusal> {
use crate::pipeline::sbom::supplied::SuppliedSbomError;
match read {
Ok(sbom) => Ok(Self {
format: sbom.format,
components: sbom.entries.len(),
statements: sbom.statements.len(),
}),
Err(SuppliedSbomError::Io(_)) => Err(StatusCode::INTERNAL_SERVER_ERROR.into()),
Err(e) => Err(UploadRefusal {
status: if e == SuppliedSbomError::TooLarge {
StatusCode::PAYLOAD_TOO_LARGE
} else {
StatusCode::UNPROCESSABLE_ENTITY
},
reason: Some((e.to_string(), e.code())),
}),
}
}
/// The summary as the artifact's facts.
fn facts(&self) -> [DetectedFact; 3] {
[
DetectedFact::new(SBOM_FORMAT_FACT, self.format.as_str(), "upload"),
DetectedFact::new(SBOM_COMPONENTS_FACT, self.components.to_string(), "upload"),
DetectedFact::new(SBOM_STATEMENTS_FACT, self.statements.to_string(), "upload"),
]
}
}
/// The multipart form of a supplier SBOM check.
// Only the API description reads it, as for [`UploadArtifactForm`].
#[derive(utoipa::ToSchema)]
#[allow(dead_code)]
pub struct CheckSupplierSbomForm {
/// The SBOM file, exactly one.
#[schema(value_type = String, format = Binary)]
file: Vec<u8>,
}
/// Check a supplier SBOM before any target holds it.
///
/// Reads the file as an upload of kind `supplier_sbom` would, and says what
/// it holds (`data`: `format`, `components`, `statements`) or why it is
/// refused, so the onboarding wizard can refuse a file
/// when it is added, before the target exists (#1025). Nothing is stored.
///
/// A refusal is `{"error": …, "code": …}`, the code one of `too_large`,
/// `too_many_components`, `empty`, `unknown_format` or `malformed`.
#[utoipa::path(
post,
path = "/api/v1/supplier-sboms/check",
tag = "Targets",
request_body(content = CheckSupplierSbomForm, content_type = "multipart/form-data"),
responses(
(status = 200, description = "What the SBOM holds"),
(status = 400, description = "No file, or more than one"),
(status = 413, description = "The file is over 20 MiB"),
(status = 422, description = "Not a supplier SBOM that can be read; `error` and `code` say why"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn check_supplier_sbom(
mut multipart: Multipart,
) -> Result<Json<ApiResponse<SupplierSbomSummary>>, UploadRefusal> {
let mut bytes = None;
while let Some(field) = multipart.next_field().await.map_err(|e| e.status())? {
if field.name() == Some("file") {
if bytes.is_some() {
return Err(StatusCode::BAD_REQUEST.into());
}
bytes = Some(field.bytes().await.map_err(|e| e.status())?);
}
}
let bytes = bytes.ok_or(StatusCode::BAD_REQUEST)?;
let read = tokio::task::spawn_blocking(move || {
crate::pipeline::sbom::supplied::parse_with_statements(&bytes, "", "")
})
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(ApiResponse {
data: SupplierSbomSummary::of(read)?,
total: None,
page: None,
}))
get_target(Extension(agent), tenant, Path(id)).await
}
/// The fact an upload records on a password-protected archive.
@@ -1401,7 +1008,7 @@ pub async fn set_archive_password(
///
/// 413 past `max`, the multipart error's own status for a malformed or
/// over-limit body, 500 if the file cannot be written.
pub(super) async fn stream_to_disk(
async fn stream_to_disk(
field: &mut axum::extract::multipart::Field<'_>,
dest: &std::path::Path,
max: u64,
@@ -1430,21 +1037,16 @@ pub(super) async fn stream_to_disk(
/// An uploaded file on disk that is deleted when dropped, unless [`Self::keep`]
/// is called once the artifact record references it. This is what stops a
/// rejected, oversized or half-received upload from being left on disk.
pub(super) struct StoredUpload {
pub path: std::path::PathBuf,
/// The file's name, as it was sent.
pub name: String,
pub size: u64,
struct StoredUpload {
path: std::path::PathBuf,
size: u64,
keep: bool,
}
impl StoredUpload {
/// The file `name`, about to be written at `path`, deleted unless it is
/// kept.
pub(super) fn new(path: std::path::PathBuf, name: String) -> Self {
fn new(path: std::path::PathBuf) -> Self {
Self {
path,
name,
size: 0,
keep: false,
}
@@ -1469,30 +1071,7 @@ fn parse_enum<T: for<'de> Deserialize<'de>>(s: &str) -> Option<T> {
serde_json::from_value(serde_json::Value::String(s.to_string())).ok()
}
/// `scans`, each scan the target runs listed once (#1043): one scan may
/// have several rules, one per artifact it can read (code, a firmware image,
/// a supplier SBOM). Once one of them runs, the others are no reason it
/// cannot, and read as if it did not. A scan none of them runs keeps every
/// reason why not.
fn listed_once(scans: Vec<ScanOptionDto>) -> Vec<ScanOptionDto> {
let runs: std::collections::HashSet<String> = scans
.iter()
.filter(|s| s.blocked_reason.is_none())
.map(|s| s.scan.clone())
.collect();
let mut listed = std::collections::HashSet::new();
scans
.into_iter()
.filter(|s| {
!runs.contains(&s.scan) || (s.blocked_reason.is_none() && listed.insert(s.scan.clone()))
})
.collect()
}
/// The scans that apply to a target, with why and what each one needs.
///
/// A scan the target runs is listed once; a scan it cannot run is listed
/// with each reason why not.
#[utoipa::path(
get,
path = "/api/v1/targets/{id}/applicable-scans",
@@ -1520,20 +1099,18 @@ pub async fn applicable_scans_for_target(
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
let scans = listed_once(
applicable_scans(&target)
.into_iter()
.map(|o| ScanOptionDto {
scan: o.scan.to_string(),
default_on: o.default_on,
// A scan nothing runs yet reads as blocked to every client, so the
// wizard neither pre-selects nor offers it.
blocked_reason: o.unrunnable_reason(),
rationale: o.rationale,
required_artifact: o.required_artifact.map(|k| k.to_string()),
})
.collect(),
);
let scans = applicable_scans(&target)
.into_iter()
.map(|o| ScanOptionDto {
scan: o.scan.to_string(),
default_on: o.default_on,
// A scan nothing runs yet reads as blocked to every client, so the
// wizard neither pre-selects nor offers it.
blocked_reason: o.unrunnable_reason(),
rationale: o.rationale,
required_artifact: o.required_artifact.map(|k| k.to_string()),
})
.collect();
Ok(Json(ApiResponse {
data: ApplicableScansResponse {
@@ -1768,76 +1345,6 @@ pub async fn trigger_target_scan(
mod filter_tests {
use super::*;
fn option(scan: &str, blocked: Option<&str>) -> ScanOptionDto {
ScanOptionDto {
scan: scan.into(),
default_on: blocked.is_none(),
rationale: String::new(),
required_artifact: None,
blocked_reason: blocked.map(String::from),
}
}
#[test]
fn a_scan_the_target_runs_is_listed_once() {
let listed = listed_once(vec![
option("sast", Some("no git_repo artifact provided")),
option("sbom", Some("no git_repo artifact provided")),
option("sbom", Some("firmware images are not unpacked yet")),
option("sbom", None),
option("cve", Some("no git_repo artifact provided")),
option("cve", None),
option("cve", None),
]);
let rows: Vec<(&str, bool)> = listed
.iter()
.map(|o| (o.scan.as_str(), o.blocked_reason.is_none()))
.collect();
// A scan nothing runs keeps its reason; one that runs is there once.
assert_eq!(rows, [("sast", false), ("sbom", true), ("cve", true)]);
}
#[test]
fn a_scan_nothing_runs_keeps_every_reason() {
let listed = listed_once(vec![
option("sbom", Some("no git_repo artifact provided")),
option("sbom", Some("firmware images are not unpacked yet")),
]);
assert_eq!(listed.len(), 2);
}
#[test]
fn a_supplier_needs_a_name_and_an_https_csaf_provider() {
let input = |name: &str, provider: Option<&str>| SupplierInput {
name: name.into(),
product: Some(" Pump Remote ".into()),
version: Some("".into()),
csaf_provider: provider.map(String::from),
};
let url = "https://supplier.example/.well-known/csaf/provider-metadata.json";
let built = input(" Example GmbH ", Some(url)).build().unwrap().unwrap();
assert_eq!(built.name, "Example GmbH");
assert_eq!(built.product.as_deref(), Some("Pump Remote"));
assert_eq!(built.version, None, "blank is none");
assert_eq!(built.csaf_provider.as_deref(), Some(url));
assert_eq!(
input(" ", Some(url)).build(),
Ok(None),
"an empty name removes it"
);
for bad in [
"http://supplier.example/provider-metadata.json",
"file:///etc/passwd",
"not a url",
] {
assert_eq!(
input("Example GmbH", Some(bad)).build(),
Err(StatusCode::UNPROCESSABLE_ENTITY),
"{bad}"
);
}
}
#[test]
fn a_scan_asked_for_new_content_is_change_driven() {
use compliance_core::models::ScanTrigger;
+2 -13
View File
@@ -18,24 +18,13 @@ use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{collect_cursor_async, tenant_db, AgentExt};
/// The body of [`assess_target`].
#[derive(Debug, Deserialize, utoipa::ToSchema)]
#[derive(Debug, Deserialize)]
pub struct AssessRequest {
/// The target / repo id whose findings are assessed.
pub target_id: String,
}
/// A target's findings as OSCAL assessment results.
#[utoipa::path(
post,
path = "/api/v1/oscal/assess",
tag = "Compliance",
request_body = AssessRequest,
responses(
(status = 200, description = "The OSCAL assessment results"),
(status = 401, description = "No valid bearer token"),
)
)]
/// `POST /api/v1/oscal/assess` — OSCAL assessment-results for a target's findings.
pub async fn assess_target(
Extension(agent): AgentExt,
tenant: TenantCtx,
@@ -21,10 +21,8 @@ use super::super::dto::{collect_cursor_async, tenant_db};
type AgentExt = Extension<Arc<ComplianceAgent>>;
/// The body of [`export_session_report`].
#[derive(Deserialize, utoipa::ToSchema)]
#[derive(Deserialize)]
pub struct ExportBody {
/// The password the archive is encrypted with.
pub password: String,
/// Requester display name (from auth)
#[serde(default)]
@@ -34,20 +32,7 @@ pub struct ExportBody {
pub requester_email: String,
}
/// A session's report as an encrypted archive to download.
#[utoipa::path(
post,
path = "/api/v1/pentest/sessions/{id}/export",
tag = "Pentest",
params(("id" = String, Path, description = "The session's id")),
request_body = ExportBody,
responses(
(status = 200, description = "The archive"),
(status = 400, description = "Not an id, or no password"),
(status = 404, description = "No such session"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/pentest/sessions/:id/export — Export an encrypted pentest report archive
#[tracing::instrument(skip_all, fields(session_id = %id))]
pub async fn export_session_report(
Extension(agent): AgentExt,
@@ -17,18 +17,13 @@ use super::super::dto::{collect_cursor_async, tenant_db, ApiResponse, Pagination
type AgentExt = Extension<Arc<ComplianceAgent>>;
/// The body of [`create_session`].
#[derive(Deserialize, utoipa::ToSchema)]
#[derive(Deserialize)]
pub struct CreateSessionRequest {
/// The target to test, for a session without `config`.
pub target_id: Option<String>,
/// `quick`, `comprehensive` (default), `targeted` or `aggressive`.
#[serde(default = "default_strategy")]
pub strategy: String,
/// The first instruction.
pub message: Option<String>,
/// Wizard configuration — if present, takes precedence over legacy fields
#[schema(value_type = Option<Object>)]
pub config: Option<PentestConfig>,
}
@@ -36,37 +31,17 @@ fn default_strategy() -> String {
"comprehensive".to_string()
}
/// The body of [`send_message`].
#[derive(Deserialize, utoipa::ToSchema)]
#[derive(Deserialize)]
pub struct SendMessageRequest {
/// The message.
pub message: String,
}
/// The query of [`lookup_repo`].
#[derive(Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Deserialize)]
pub struct LookupRepoQuery {
/// The repository's git URL.
pub url: String,
}
/// Create a pentest session and start it.
#[utoipa::path(
post,
path = "/api/v1/pentest/sessions",
tag = "Pentest",
request_body = CreateSessionRequest,
responses(
(status = 200, description = "The session"),
(status = 400, description = "A missing disclaimer, target or id, or a URL the agent may not reach"),
(status = 404, description = "No such target"),
(status = 409, description = "Pentests are not available on this deployment (static analysis only)"),
(status = 429, description = "Too many sessions are running"),
(status = 503, description = "A credential cannot be sealed"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/pentest/sessions — Create a new pentest session and start the orchestrator
#[tracing::instrument(skip_all)]
pub async fn create_session(
Extension(agent): AgentExt,
@@ -374,17 +349,7 @@ fn parse_strategy(s: &str) -> PentestStrategy {
}
}
/// Look up a tracked repository by its git URL.
#[utoipa::path(
get,
path = "/api/v1/pentest/lookup-repo",
tag = "Pentest",
params(LookupRepoQuery),
responses(
(status = 200, description = "The repository, or null"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/pentest/lookup-repo — Look up a tracked repository by git URL
#[tracing::instrument(skip_all)]
pub async fn lookup_repo(
Extension(agent): AgentExt,
@@ -417,17 +382,7 @@ pub async fn lookup_repo(
}))
}
/// The tenant's pentest sessions, a page at a time.
#[utoipa::path(
get,
path = "/api/v1/pentest/sessions",
tag = "Pentest",
params(PaginationParams),
responses(
(status = 200, description = "A page of sessions"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/pentest/sessions — List pentest sessions
#[tracing::instrument(skip_all)]
pub async fn list_sessions(
Extension(agent): AgentExt,
@@ -465,19 +420,7 @@ pub async fn list_sessions(
}))
}
/// One pentest session.
#[utoipa::path(
get,
path = "/api/v1/pentest/sessions/{id}",
tag = "Pentest",
params(("id" = String, Path, description = "The session's id")),
responses(
(status = 200, description = "The session"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such session"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/pentest/sessions/:id — Get a single pentest session
#[tracing::instrument(skip_all, fields(session_id = %id))]
pub async fn get_session(
Extension(agent): AgentExt,
@@ -511,20 +454,7 @@ pub async fn get_session(
}))
}
/// Send a message to a session, which starts its next iteration.
#[utoipa::path(
post,
path = "/api/v1/pentest/sessions/{id}/chat",
tag = "Pentest",
params(("id" = String, Path, description = "The session's id")),
request_body = SendMessageRequest,
responses(
(status = 200, description = "The stored message"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such session"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/pentest/sessions/:id/chat — Send a user message and trigger next orchestrator iteration
#[tracing::instrument(skip_all, fields(session_id = %id))]
pub async fn send_message(
Extension(agent): AgentExt,
@@ -624,19 +554,7 @@ pub async fn send_message(
}))
}
/// Stop a running session.
#[utoipa::path(
post,
path = "/api/v1/pentest/sessions/{id}/stop",
tag = "Pentest",
params(("id" = String, Path, description = "The session's id")),
responses(
(status = 200, description = "The stopped session"),
(status = 400, description = "Not an id, or the session is not running"),
(status = 404, description = "No such session"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/pentest/sessions/:id/stop — Stop a running pentest session
#[tracing::instrument(skip_all, fields(session_id = %id))]
pub async fn stop_session(
Extension(agent): AgentExt,
@@ -712,19 +630,7 @@ pub async fn stop_session(
}))
}
/// Pause a running session.
#[utoipa::path(
post,
path = "/api/v1/pentest/sessions/{id}/pause",
tag = "Pentest",
params(("id" = String, Path, description = "The session's id")),
responses(
(status = 200, description = "Paused"),
(status = 400, description = "Not an id, or the session is not running"),
(status = 404, description = "No such session"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/pentest/sessions/:id/pause — Pause a running pentest session
#[tracing::instrument(skip_all, fields(session_id = %id))]
pub async fn pause_session(
Extension(agent): AgentExt,
@@ -770,19 +676,7 @@ pub async fn pause_session(
}))
}
/// Resume a paused session.
#[utoipa::path(
post,
path = "/api/v1/pentest/sessions/{id}/resume",
tag = "Pentest",
params(("id" = String, Path, description = "The session's id")),
responses(
(status = 200, description = "Resumed"),
(status = 400, description = "Not an id, or the session is not paused"),
(status = 404, description = "No such session"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/pentest/sessions/:id/resume — Resume a paused pentest session
#[tracing::instrument(skip_all, fields(session_id = %id))]
pub async fn resume_session(
Extension(agent): AgentExt,
@@ -833,18 +727,7 @@ pub async fn resume_session(
/// being loaded whole into agent memory.
const MAX_ATTACK_CHAIN_NODES: i64 = 2_000;
/// A session's attack chain.
#[utoipa::path(
get,
path = "/api/v1/pentest/sessions/{id}/attack-chain",
tag = "Pentest",
params(("id" = String, Path, description = "The session's id")),
responses(
(status = 200, description = "The nodes"),
(status = 400, description = "Not an id"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/pentest/sessions/:id/attack-chain — Get attack chain nodes for a session
#[tracing::instrument(skip_all, fields(session_id = %id))]
pub async fn get_attack_chain(
Extension(agent): AgentExt,
@@ -884,18 +767,7 @@ pub async fn get_attack_chain(
}))
}
/// A session's messages, a page at a time.
#[utoipa::path(
get,
path = "/api/v1/pentest/sessions/{id}/messages",
tag = "Pentest",
params(("id" = String, Path, description = "The session's id"), PaginationParams),
responses(
(status = 200, description = "A page of messages"),
(status = 400, description = "Not an id"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/pentest/sessions/:id/messages — Get messages for a session
#[tracing::instrument(skip_all, fields(session_id = %id))]
pub async fn get_messages(
Extension(agent): AgentExt,
@@ -935,18 +807,7 @@ pub async fn get_messages(
}))
}
/// A session's findings, a page at a time.
#[utoipa::path(
get,
path = "/api/v1/pentest/sessions/{id}/findings",
tag = "Pentest",
params(("id" = String, Path, description = "The session's id"), PaginationParams),
responses(
(status = 200, description = "A page of findings"),
(status = 400, description = "Not an id"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/pentest/sessions/:id/findings — Get DAST findings for a pentest session
#[tracing::instrument(skip_all, fields(session_id = %id))]
pub async fn get_session_findings(
Extension(agent): AgentExt,
@@ -14,16 +14,7 @@ use super::super::dto::{collect_cursor_async, tenant_db, ApiResponse};
type AgentExt = Extension<Arc<ComplianceAgent>>;
/// The tenant's pentest statistics.
#[utoipa::path(
get,
path = "/api/v1/pentest/stats",
tag = "Pentest",
responses(
(status = 200, description = "The statistics"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/pentest/stats — Aggregated pentest statistics
#[tracing::instrument(skip_all)]
pub async fn pentest_stats(
Extension(agent): AgentExt,
@@ -19,22 +19,10 @@ use super::super::dto::{collect_cursor_async, tenant_db};
type AgentExt = Extension<Arc<ComplianceAgent>>;
/// A session's events as they happen (server-sent events).
/// GET /api/v1/pentest/sessions/:id/stream — SSE endpoint for real-time events
///
/// Replays stored messages/nodes as initial burst, then subscribes to the
/// broadcast channel for live updates. Sends keepalive comments every 15s.
#[utoipa::path(
get,
path = "/api/v1/pentest/sessions/{id}/stream",
tag = "Pentest",
params(("id" = String, Path, description = "The session's id")),
responses(
(status = 200, description = "The event stream (text/event-stream)"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such session"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(session_id = %id))]
pub async fn session_stream(
Extension(agent): AgentExt,
@@ -462,10 +462,6 @@ pub struct PlatformTarget {
pub open_vulnerabilities: u64,
/// Its projects that the registry still lists.
pub project_ids: Vec<String>,
/// Who supplies it, for a component bought in (#1025): the targets a
/// supplier can be invited for (#1027). Left out for the tenant's own.
#[serde(skip_serializing_if = "Option::is_none")]
pub supplier: Option<compliance_core::models::SupplierComponent>,
}
/// Open findings of each target in `target_ids`, in one query.
@@ -586,7 +582,6 @@ pub async fn list_targets(
},
name: t.name,
target_type: t.target_type,
supplier: t.supplier,
id,
}
})
+2 -13
View File
@@ -106,17 +106,8 @@ pub fn projects_changed_entry(
)
}
/// The tenant's projects, for choosing and showing them in the dashboard.
#[utoipa::path(
get,
path = "/api/v1/projects",
tag = "Workspace",
responses(
(status = 200, description = "The projects"),
(status = 503, description = "The registry cannot be asked"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/projects — the tenant's projects, for choosing and showing
/// them in the dashboard.
#[tracing::instrument(skip_all)]
pub async fn list_projects(
Extension(agent): AgentExt,
@@ -137,8 +128,6 @@ mod tests {
name: format!("Projekt {id}"),
kind: ProjectKind::Product,
description: String::new(),
level: None,
parent_id: None,
}
}
File diff suppressed because it is too large. Load diff
@@ -64,30 +64,11 @@ pub async fn target_scan_changes(
.map_err(db_error("reading the target"))?
.ok_or(StatusCode::NOT_FOUND)?;
let data = target_changes(&db, &id, query.limit).await?;
Ok(Json(ApiResponse {
total: Some(data.len() as u64),
data,
page: None,
}))
}
/// The last `limit` scans of target `id`, oldest first, each with what it
/// changed (see [`target_scan_changes`]).
///
/// # Errors
///
/// 500 when the database cannot be read.
pub(crate) async fn target_changes(
db: &crate::database::Database,
id: &str,
limit: usize,
) -> Result<Vec<ScanChange>, StatusCode> {
let runs: Vec<ScanRun> = collect_cursor_async(
db.scan_runs()
.find(doc! { "repo_id": id })
.find(doc! { "repo_id": &id })
.sort(doc! { "started_at": -1 })
.limit(i64::try_from(limit).unwrap_or(i64::MAX))
.limit(i64::try_from(query.limit).unwrap_or(i64::MAX))
.await
.map_err(db_error("listing the runs"))?,
)
@@ -98,7 +79,7 @@ pub(crate) async fn target_changes(
Some(oldest) => db
.scan_runs()
.find_one(doc! {
"repo_id": id,
"repo_id": &id,
"status": "completed",
"started_at": { "$lt": BsonDateTime::from_chrono(oldest) },
})
@@ -109,7 +90,7 @@ pub(crate) async fn target_changes(
None => None,
};
let mut filter = doc! { "repo_id": id };
let mut filter = doc! { "repo_id": &id };
if let Some(since) = since {
let since = BsonDateTime::from_chrono(since);
filter.insert(
@@ -131,7 +112,12 @@ pub(crate) async fn target_changes(
)
.await;
Ok(changes(&runs, since, &alerts))
let data = changes(&runs, since, &alerts);
Ok(Json(ApiResponse {
total: Some(data.len() as u64),
data,
page: None,
}))
}
#[cfg(test)]
+2 -13
View File
@@ -8,8 +8,7 @@ use compliance_core::models::ScanRun;
use compliance_core::tenant_ctx::TenantCtx;
/// Which scan runs to list.
#[derive(Debug, Default, Deserialize, utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
#[derive(Debug, Default, Deserialize)]
pub struct ScanRunFilter {
/// Only the runs of this target (its id), for the target's scan history.
#[serde(default)]
@@ -26,17 +25,7 @@ impl ScanRunFilter {
}
}
/// The tenant's scan runs, newest first, a page at a time.
#[utoipa::path(
get,
path = "/api/v1/scan-runs",
tag = "Scans",
params(PaginationParams, ScanRunFilter),
responses(
(status = 200, description = "A page of scan runs"),
(status = 401, description = "No valid bearer token"),
)
)]
/// GET /api/v1/scan-runs?target_id=&page=&limit= — newest first.
#[tracing::instrument(skip_all)]
pub async fn list_scan_runs(
Extension(agent): AgentExt,
@@ -1,90 +0,0 @@
//! What Prüfwerk knows of a bought-in component's supplier (#1025): how many
//! of its CSAF advisories are kept for the workspace, and when its provider
//! was last read.
use axum::extract::{Extension, Path};
use axum::http::StatusCode;
use axum::Json;
use mongodb::bson::{doc, oid::ObjectId};
use serde::Serialize;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{tenant_db, AgentExt};
use super::ApiResponse;
use crate::pipeline::csaf_feed::{supplier_key, MongoAdvisoryStore, SupplierProviderStatus};
/// The advisories of a target's supplier, as the target editor shows them.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SupplierAdvisories {
/// The supplier's advisories kept for the workspace.
pub advisories: u64,
/// When its provider was last read; none before the first refresh.
pub checked_at: Option<chrono::DateTime<chrono::Utc>>,
/// Whether its metadata and feeds could be read then; none before the
/// first refresh.
pub reachable: Option<bool>,
}
/// Count the target's supplier advisories, with their provider's last read.
///
/// `data` holds `advisories`, `checked_at` and `reachable` (both null before
/// the first refresh), or is null when the target names no supplier CSAF
/// provider. The
/// advisories are the workspace's own: a provider is read for the workspaces
/// that name it, daily and right after it is set.
#[utoipa::path(
get,
path = "/api/v1/targets/{id}/supplier-advisories",
tag = "Targets",
params(("id" = String, Path, description = "The target's id")),
responses(
(status = 200, description = "The supplier's advisories, or null without a provider"),
(status = 400, description = "Not an id"),
(status = 404, description = "No such target"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(target_id = %id))]
pub async fn get_supplier_advisories(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
) -> Result<Json<ApiResponse<Option<SupplierAdvisories>>>, StatusCode> {
let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
let db = tenant_db(&agent, &tenant).await?;
let target = db
.onboarded_targets()
.find_one(doc! { "_id": oid })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
let Some(url) = target.supplier.and_then(|s| s.csaf_provider) else {
return Ok(Json(ApiResponse {
data: None,
total: None,
page: None,
}));
};
let key = supplier_key(&url);
let advisories = MongoAdvisoryStore::supplier(db.inner())
.collection()
.count_documents(doc! { "provider": &key })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let status = db
.inner()
.collection::<SupplierProviderStatus>(SupplierProviderStatus::COLLECTION)
.find_one(doc! { "_id": &key })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(ApiResponse {
data: Some(SupplierAdvisories {
advisories,
checked_at: status.as_ref().map(|s| s.checked_at.to_chrono()),
reachable: status.map(|s| s.reachable),
}),
total: None,
page: None,
}))
}
@@ -1,904 +0,0 @@
//! Supplier invites (#1027): the customer invites a supplier, through the
//! portal, to upload the SBOM of one bought-in component.
//!
//! The portal owns the secret link and the mail; Prüfwerk keeps the invite in
//! the tenant's own database (so the tenant export and erasure cover it, the
//! supplier's address included) and refuses what an expired or withdrawn
//! invite would allow. The portal calls these endpoints with its platform
//! service token ([`super::platform::require_platform_token`]).
//!
//! An invite is valid for [`INVITE_LIFETIME_DAYS`] from when it is made, and
//! serves the component's later SBOM versions until it expires or is
//! withdrawn (decided 2026-11-18).
//!
//! An upload through an invite takes the customer's own upload path
//! ([`super::onboarding::attach_upload`]): it becomes the component's SBOM and
//! starts a scan. Every upload, refused ones included, is recorded with the
//! invite it came through ([`SupplierUpload`]), for the customer and the
//! supplier to see.
use std::collections::HashMap;
use axum::extract::{Multipart, Path, Query, State};
use axum::http::StatusCode;
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::{ArtifactKind, OnboardedTarget, ScanTrigger};
use super::onboarding::{
attach_upload, is_https_url, refresh_supplier_csaf, stream_to_disk, StoredUpload,
SupplierSbomSummary, UploadRefusal,
};
use super::platform::PlatformState;
use crate::agent::ComplianceAgent;
use crate::database::Database;
use crate::pipeline::sbom::supplied::MAX_BYTES as MAX_SBOM_BYTES;
/// How long an invite is valid, in days from when it is made.
pub const INVITE_LIFETIME_DAYS: i64 = 90;
/// The longest e-mail address accepted (RFC 5321's path limit).
const MAX_EMAIL_LEN: usize = 254;
/// The longest `invited_by` / `withdrawn_by` accepted: a portal user's id.
const MAX_ACTOR_LEN: usize = 200;
/// The most uploads one invite takes in a day, refused ones included: each
/// accepted one starts a scan the customer pays for.
pub const MAX_UPLOADS_PER_DAY: u64 = 20;
/// The longest file name kept with an upload, in characters.
const MAX_FILENAME_CHARS: usize = 200;
/// An invite as stored, in the tenant's [`SupplierInvite::COLLECTION`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SupplierInvite {
/// Its id, which the portal keys its secret link by.
#[serde(rename = "_id")]
pub id: ObjectId,
/// The target (a supplier component) the invite is for.
pub target_id: String,
/// Who was invited: the supplier's e-mail address, lower case.
pub email: String,
/// The portal user who sent it.
pub invited_by: String,
/// When it was made.
pub created_at: BsonDateTime,
/// When it stops being valid.
pub expires_at: BsonDateTime,
/// When it was withdrawn; `None` while it is not.
#[serde(default)]
pub withdrawn_at: Option<BsonDateTime>,
/// The portal user who withdrew it.
#[serde(default)]
pub withdrawn_by: Option<String>,
}
/// Whether an invite still allows an upload.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum InviteState {
/// Uploads are accepted.
Active,
/// Past `expires_at`.
Expired,
/// Withdrawn by the customer (this wins over expiry).
Withdrawn,
}
impl SupplierInvite {
/// The collection, in the tenant's own database.
pub const COLLECTION: &'static str = "supplier_invites";
/// A new invite for `target_id`, made at `now`.
pub fn new(target_id: String, email: String, invited_by: String, now: DateTime<Utc>) -> Self {
Self {
id: ObjectId::new(),
target_id,
email,
invited_by,
created_at: now.into(),
expires_at: (now + chrono::Duration::days(INVITE_LIFETIME_DAYS)).into(),
withdrawn_at: None,
withdrawn_by: None,
}
}
/// Its state at `now`.
pub fn state(&self, now: DateTime<Utc>) -> InviteState {
if self.withdrawn_at.is_some() {
InviteState::Withdrawn
} else if now >= self.expires_at.to_chrono() {
InviteState::Expired
} else {
InviteState::Active
}
}
}
/// An invite as the portal reads it.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct InviteView {
/// The invite's id.
pub id: String,
/// The target it is for.
pub target_id: String,
/// The supplier's e-mail address.
pub email: String,
/// The portal user who sent it.
pub invited_by: String,
/// When it was made.
pub created_at: DateTime<Utc>,
/// When it stops being valid.
pub expires_at: DateTime<Utc>,
/// When it was withdrawn, if it was.
pub withdrawn_at: Option<DateTime<Utc>>,
/// Who withdrew it, if anyone did.
pub withdrawn_by: Option<String>,
/// Whether it still allows an upload.
pub state: InviteState,
/// What came through it, newest first.
pub uploads: Vec<UploadView>,
}
impl InviteView {
/// The view of `invite` at `now`, with its `uploads`.
fn of(invite: SupplierInvite, now: DateTime<Utc>, uploads: Vec<UploadView>) -> Self {
Self {
uploads,
state: invite.state(now),
id: invite.id.to_hex(),
target_id: invite.target_id,
email: invite.email,
invited_by: invite.invited_by,
created_at: invite.created_at.to_chrono(),
expires_at: invite.expires_at.to_chrono(),
withdrawn_at: invite.withdrawn_at.map(BsonDateTime::to_chrono),
withdrawn_by: invite.withdrawn_by,
}
}
}
/// An upload through an invite, as stored in [`SupplierUpload::COLLECTION`]:
/// accepted or refused, with what the file held.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SupplierUpload {
/// Its id.
#[serde(rename = "_id")]
pub id: ObjectId,
/// The invite it came through.
pub invite_id: String,
/// The target it was for.
pub target_id: String,
/// When it arrived.
pub uploaded_at: BsonDateTime,
/// The file's name, as the supplier sent it.
pub filename: String,
/// Whether it became the component's SBOM.
pub accepted: bool,
/// Why it was refused: the code of the refusal.
#[serde(default)]
pub code: Option<String>,
/// What an accepted SBOM holds.
#[serde(default)]
pub summary: Option<SupplierSbomSummary>,
/// The artifact an accepted SBOM became.
#[serde(default)]
pub artifact_id: Option<String>,
/// The CSAF provider the supplier gave with it.
#[serde(default)]
pub csaf_provider: Option<String>,
}
impl SupplierUpload {
/// The collection, in the tenant's own database.
pub const COLLECTION: &'static str = "supplier_uploads";
/// A refused upload of `filename` through `invite`, with the refusal's code.
fn refused(invite: &SupplierInvite, filename: &str, code: &str) -> Self {
Self {
id: ObjectId::new(),
invite_id: invite.id.to_hex(),
target_id: invite.target_id.clone(),
uploaded_at: BsonDateTime::now(),
filename: filename.to_string(),
accepted: false,
code: Some(code.to_string()),
summary: None,
artifact_id: None,
csaf_provider: None,
}
}
}
/// An upload as the portal shows it, to the customer and to the supplier.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct UploadView {
/// Its id.
pub id: String,
/// When it arrived.
pub uploaded_at: DateTime<Utc>,
/// The file's name.
pub filename: String,
/// Whether it became the component's SBOM.
pub accepted: bool,
/// Why it was refused: `too_large`, `too_many_components`, `empty`,
/// `unknown_format`, `malformed` or `csaf_provider`.
pub code: Option<String>,
/// What an accepted SBOM holds.
pub summary: Option<SupplierSbomSummary>,
/// The CSAF provider given with it.
pub csaf_provider: Option<String>,
/// Whether it is the component's SBOM now (a later one replaces it).
pub current: bool,
}
impl UploadView {
/// The view of `upload`; `current` is the target's SBOM artifact now.
fn of(upload: SupplierUpload, current: Option<&str>) -> Self {
Self {
current: upload.artifact_id.is_some() && upload.artifact_id.as_deref() == current,
id: upload.id.to_hex(),
uploaded_at: upload.uploaded_at.to_chrono(),
filename: upload.filename,
accepted: upload.accepted,
code: upload.code,
summary: upload.summary,
csaf_provider: upload.csaf_provider,
}
}
}
/// What the supplier sees of its invite: the component, until when the link
/// is valid, and its uploads. Nothing else of the customer's.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SupplierPage {
/// The component, by the customer's name for it.
pub component: String,
/// The supplier's name for the product, if the customer gave it.
pub product: Option<String>,
/// The version in use, if the customer gave it.
pub version: Option<String>,
/// Until when the link is valid.
pub expires_at: DateTime<Utc>,
/// The CSAF provider kept for the component.
pub csaf_provider: Option<String>,
/// Its uploads through this invite, newest first.
pub uploads: Vec<UploadView>,
}
/// The body of an invite: which component, whom, and who invites.
#[derive(Debug, Deserialize)]
pub struct CreateInvite {
/// The supplier component's target id.
pub target_id: String,
/// The supplier's e-mail address.
pub email: String,
/// The portal user who invites.
pub invited_by: String,
}
/// The body of a withdrawal.
#[derive(Debug, Deserialize)]
pub struct WithdrawInvite {
/// The portal user who withdraws it.
pub withdrawn_by: String,
}
/// The query of the invite list: one target's, or all of them.
#[derive(Debug, Default, Deserialize)]
pub struct InviteFilter {
/// Only this target's invites.
#[serde(default)]
pub target: Option<String>,
}
/// `email` trimmed and in lower case, or `None` when it is not an address
/// with one `@` between a non-empty local part and a domain holding a dot.
fn normalized_email(email: &str) -> Option<String> {
let email = email.trim().to_lowercase();
let (local, domain) = email.split_once('@')?;
let plausible = !local.is_empty()
&& domain.contains('.')
&& !domain.starts_with('.')
&& !domain.ends_with('.')
&& !domain.contains('@')
&& email.len() <= MAX_EMAIL_LEN
&& !email.chars().any(|c| c.is_whitespace() || c.is_control());
plausible.then_some(email)
}
/// `actor` trimmed, or `None` when it is empty or too long.
fn normalized_actor(actor: &str) -> Option<String> {
let actor = actor.trim();
(!actor.is_empty() && actor.len() <= MAX_ACTOR_LEN).then(|| actor.to_string())
}
fn invites(db: &Database) -> mongodb::Collection<SupplierInvite> {
db.inner().collection(SupplierInvite::COLLECTION)
}
fn uploads(db: &Database) -> mongodb::Collection<SupplierUpload> {
db.inner().collection(SupplierUpload::COLLECTION)
}
/// The id of `target`'s supplier SBOM now, if it has one.
fn current_sbom(target: &OnboardedTarget) -> Option<&str> {
target
.artifacts
.iter()
.find(|a| a.kind == ArtifactKind::SupplierSbom)
.map(|a| a.id.as_str())
}
/// `listed` as the portal reads them at `now`, each with its uploads.
async fn views(
db: &Database,
listed: Vec<SupplierInvite>,
now: DateTime<Utc>,
) -> Result<Vec<InviteView>, StatusCode> {
let ids: Vec<String> = listed.iter().map(|i| i.id.to_hex()).collect();
let mut by_invite: HashMap<String, Vec<SupplierUpload>> = HashMap::new();
let mut cursor = uploads(db)
.find(doc! { "invite_id": { "$in": &ids } })
.sort(doc! { "uploaded_at": -1, "_id": -1 })
.await
.map_err(internal)?;
while let Some(upload) = cursor.try_next().await.map_err(internal)? {
by_invite
.entry(upload.invite_id.clone())
.or_default()
.push(upload);
}
let target_ids: Vec<ObjectId> = listed
.iter()
.filter_map(|i| ObjectId::parse_str(&i.target_id).ok())
.collect();
let targets: Vec<OnboardedTarget> = db
.onboarded_targets()
.find(doc! { "_id": { "$in": target_ids } })
.await
.map_err(internal)?
.try_collect()
.await
.map_err(internal)?;
let current: HashMap<String, String> = targets
.iter()
.filter_map(|t| Some((t.id?.to_hex(), current_sbom(t)?.to_string())))
.collect();
Ok(listed
.into_iter()
.map(|invite| {
let sbom = current.get(&invite.target_id).map(String::as_str);
let uploads = by_invite
.remove(&invite.id.to_hex())
.unwrap_or_default()
.into_iter()
.map(|u| UploadView::of(u, sbom))
.collect();
InviteView::of(invite, now, uploads)
})
.collect())
}
/// The invite `invite_id` of the tenant behind `db` while it allows uploads.
///
/// # Errors
///
/// 404 when there is no such invite; 410 with the code `expired` or
/// `withdrawn` when it no longer allows anything.
async fn open_invite(db: &Database, invite_id: &str) -> Result<SupplierInvite, UploadRefusal> {
let id = ObjectId::parse_str(invite_id.trim()).map_err(|_| StatusCode::NOT_FOUND)?;
let invite = invites(db)
.find_one(doc! { "_id": id })
.await
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
match invite.state(Utc::now()) {
InviteState::Active => Ok(invite),
InviteState::Expired => Err(closed("expired")),
InviteState::Withdrawn => Err(closed("withdrawn")),
}
}
/// 410: the invite allows nothing more.
fn closed(code: &'static str) -> UploadRefusal {
UploadRefusal::because(StatusCode::GONE, "the invite is no longer valid", code)
}
/// Whether the tenant may change its data now: not when the registry has it
/// read-only, halted or archived. Without a registry (dev) it may.
///
/// # Errors
///
/// 403 with the code `read_only` when it may not; 503 when the registry
/// cannot answer (access is never widened on doubt).
async fn accepts_writes(agent: &ComplianceAgent, tenant_id: &str) -> Result<(), UploadRefusal> {
let Some(registry) = agent.registry.as_ref() else {
return Ok(());
};
let check = registry
.check_entitlement(tenant_id, None, None)
.await
.map_err(|e| {
tracing::error!(tenant_id, "entitlement check unavailable: {e}");
StatusCode::SERVICE_UNAVAILABLE
})?;
// A status it does not name or Prüfwerk does not know limits nothing, as
// for a person's request (`require_entitlement`).
let status = check
.status
.as_deref()
.and_then(compliance_core::TenantStatus::parse);
let writable = check.allowed
&& !check.read_only
&& status.is_none_or(|s| !s.blocks_writes() && !s.is_halted() && !s.is_archived());
if writable {
Ok(())
} else {
Err(UploadRefusal::because(
StatusCode::FORBIDDEN,
"the workspace takes no uploads now",
"read_only",
))
}
}
/// The name an upload is shown by: the last part of `name`, at most
/// [`MAX_FILENAME_CHARS`] long.
fn shown_filename(name: &str) -> String {
let base = name.rsplit(['/', '\\']).next().unwrap_or(name).trim();
let base = if base.is_empty() { "sbom" } else { base };
base.chars().take(MAX_FILENAME_CHARS).collect()
}
fn internal<E: std::fmt::Display>(e: E) -> StatusCode {
tracing::error!("supplier invite endpoint failed: {e}");
StatusCode::INTERNAL_SERVER_ERROR
}
/// `POST /api/v1/platform/tenants/{id}/supplier-invites`: invite a supplier
/// to upload the SBOM of one supplier component. Answers 201 with the
/// invite, whose `id` the portal keys its secret link by.
///
/// # Errors
///
/// 404 when the tenant has no such target; 422 when the target is not a
/// supplier component, or the address or the inviting user is not usable.
pub async fn create_invite(
State(st): State<PlatformState>,
Path(tenant_id): Path<String>,
Json(body): Json<CreateInvite>,
) -> Result<(StatusCode, Json<InviteView>), StatusCode> {
let target = ObjectId::parse_str(body.target_id.trim()).map_err(|_| StatusCode::NOT_FOUND)?;
// Looked up without creating anything: an unknown tenant just has no target.
let lookup = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
let stored = lookup
.onboarded_targets()
.find_one(doc! { "_id": target })
.await
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
if stored.supplier.is_none() {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
let (Some(email), Some(invited_by)) = (
normalized_email(&body.email),
normalized_actor(&body.invited_by),
) else {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
};
let now = Utc::now();
let invite = SupplierInvite::new(target.to_hex(), email, invited_by, now);
let db = st
.agent
.db_pool
.for_tenant_id(&tenant_id)
.await
.map_err(internal)?;
invites(&db).insert_one(&invite).await.map_err(internal)?;
Ok((
StatusCode::CREATED,
Json(InviteView::of(invite, now, Vec::new())),
))
}
/// `GET /api/v1/platform/tenants/{id}/supplier-invites[?target=<id>]`: the
/// tenant's invites, newest first, each with its state.
///
/// # Errors
///
/// 500 when the database cannot be read.
pub async fn list_invites(
State(st): State<PlatformState>,
Path(tenant_id): Path<String>,
Query(filter): Query<InviteFilter>,
) -> Result<Json<Vec<InviteView>>, StatusCode> {
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
let query = match filter.target.as_deref().map(str::trim) {
Some(target) if !target.is_empty() => doc! { "target_id": target },
_ => doc! {},
};
let now = Utc::now();
let listed: Vec<SupplierInvite> = invites(&db)
.find(query)
.sort(doc! { "created_at": -1, "_id": -1 })
.await
.map_err(internal)?
.try_collect()
.await
.map_err(internal)?;
Ok(Json(views(&db, listed, now).await?))
}
/// `POST /api/v1/platform/tenants/{id}/supplier-invites/{invite}/withdraw`:
/// withdraw an invite, so its link allows nothing more. Withdrawing one
/// already withdrawn keeps the first withdrawal.
///
/// # Errors
///
/// 404 when the tenant has no such invite; 422 without a usable
/// `withdrawn_by`.
pub async fn withdraw_invite(
State(st): State<PlatformState>,
Path((tenant_id, invite_id)): Path<(String, String)>,
Json(body): Json<WithdrawInvite>,
) -> Result<Json<InviteView>, StatusCode> {
let id = ObjectId::parse_str(invite_id.trim()).map_err(|_| StatusCode::NOT_FOUND)?;
let by = normalized_actor(&body.withdrawn_by).ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
let now = Utc::now();
// Only an invite not yet withdrawn is changed; either way it is read back.
invites(&db)
.update_one(
doc! { "_id": id, "withdrawn_at": null },
doc! { "$set": {
"withdrawn_at": BsonDateTime::from(now),
"withdrawn_by": by,
} },
)
.await
.map_err(internal)?;
let invite = invites(&db)
.find_one(doc! { "_id": id })
.await
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
let mut viewed = views(&db, vec![invite], now).await?;
viewed
.pop()
.map(Json)
.ok_or(StatusCode::INTERNAL_SERVER_ERROR)
}
/// `GET /api/v1/platform/tenants/{id}/supplier-invites/{invite}/supplier-view`:
/// what the supplier's upload page shows, while the invite is valid.
///
/// # Errors
///
/// 404 when there is no such invite, or its component is gone or no longer a
/// supplier component; 410 with the code `expired` or `withdrawn`.
pub async fn supplier_view(
State(st): State<PlatformState>,
Path((tenant_id, invite_id)): Path<(String, String)>,
) -> Result<Json<SupplierPage>, UploadRefusal> {
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
let invite = open_invite(&db, &invite_id).await?;
let target = invite_target(&db, &invite).await?;
let sbom = current_sbom(&target).map(str::to_string);
let listed: Vec<UploadView> = uploads(&db)
.find(doc! { "invite_id": invite.id.to_hex() })
.sort(doc! { "uploaded_at": -1, "_id": -1 })
.await
.map_err(internal)?
.try_collect::<Vec<SupplierUpload>>()
.await
.map_err(internal)?
.into_iter()
.map(|u| UploadView::of(u, sbom.as_deref()))
.collect();
let (product, version, csaf_provider) = target
.supplier
.map(|s| (s.product, s.version, s.csaf_provider))
.unwrap_or_default();
Ok(Json(SupplierPage {
component: target.name,
product,
version,
expires_at: invite.expires_at.to_chrono(),
csaf_provider,
uploads: listed,
}))
}
/// The component `invite` is for, while it is a supplier component.
///
/// # Errors
///
/// 404 when it is gone, or names no supplier any more (the customer removed
/// it in the target editor).
async fn invite_target(
db: &Database,
invite: &SupplierInvite,
) -> Result<OnboardedTarget, UploadRefusal> {
let id = ObjectId::parse_str(&invite.target_id).map_err(|_| StatusCode::NOT_FOUND)?;
Ok(db
.onboarded_targets()
.find_one(doc! { "_id": id, "supplier": { "$ne": null } })
.await
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?)
}
/// `POST /api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms`: the
/// supplier uploads an SBOM through its invite.
///
/// Multipart fields: `file` (exactly one) and, optionally, `csaf_provider`
/// (the supplier's `provider-metadata.json`, an https URL). An accepted SBOM
/// becomes the component's SBOM, replacing the one before, exactly as a
/// customer's upload does, and a scan starts. A CSAF provider given with it
/// becomes the component's when it has none yet. Every upload is recorded,
/// refused ones with their code; the answer is the record (201).
///
/// # Errors
///
/// - 404: no such invite, or its component is gone or no longer a supplier
/// component.
/// - 410 (`expired`, `withdrawn`): the invite allows nothing more.
/// - 403 (`read_only`): the workspace takes no uploads now; 503 when the
/// registry cannot say.
/// - 429 (`too_many_uploads`): [`MAX_UPLOADS_PER_DAY`] reached.
/// - 400: no file, or more than one.
/// - 413 (`too_large`) and 422 (`too_many_components`, `empty`,
/// `unknown_format`, `malformed`, `csaf_provider`): refused, and recorded.
pub async fn upload_through_invite(
State(st): State<PlatformState>,
Path((tenant_id, invite_id)): Path<(String, String)>,
mut multipart: Multipart,
) -> Result<(StatusCode, Json<UploadView>), UploadRefusal> {
// Nothing is created before the invite is known to be valid.
let lookup = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
let invite = open_invite(&lookup, &invite_id).await?;
accepts_writes(&st.agent, &tenant_id).await?;
let day_ago = BsonDateTime::from(Utc::now() - chrono::Duration::days(1));
let recent = uploads(&lookup)
.count_documents(
doc! { "invite_id": invite.id.to_hex(), "uploaded_at": { "$gte": day_ago } },
)
.await
.map_err(internal)?;
if recent >= MAX_UPLOADS_PER_DAY {
return Err(UploadRefusal::because(
StatusCode::TOO_MANY_REQUESTS,
"too many uploads through this invite today",
"too_many_uploads",
));
}
let target = invite_target(&lookup, &invite).await?;
let db = st
.agent
.db_pool
.for_tenant_id(&tenant_id)
.await
.map_err(internal)?;
let mut csaf_provider = None;
let mut filename = String::from("sbom");
let mut stored: Option<StoredUpload> = None;
while let Some(mut field) = multipart.next_field().await.map_err(|e| e.status())? {
match field.name().unwrap_or("") {
"csaf_provider" => {
let url = field.text().await.map_err(|e| e.status())?;
csaf_provider = Some(url.trim().to_string()).filter(|u| !u.is_empty());
}
"file" => {
if stored.is_some() {
return Err(StatusCode::BAD_REQUEST.into());
}
filename = shown_filename(field.file_name().unwrap_or_default());
let dest = crate::targets::upload_dest(&st.agent, &invite.target_id, &filename)
.map_err(internal)?;
let mut upload = StoredUpload::new(dest, filename.clone());
match stream_to_disk(&mut field, &upload.path, MAX_SBOM_BYTES).await {
Ok(size) => upload.size = size,
Err(StatusCode::PAYLOAD_TOO_LARGE) => {
let refusal = UploadRefusal::because(
StatusCode::PAYLOAD_TOO_LARGE,
"the SBOM is larger than 20 MiB",
"too_large",
);
return Err(refused(&db, &invite, &filename, refusal).await);
}
Err(status) => return Err(status.into()),
}
stored = Some(upload);
}
_ => {}
}
}
let upload = stored.ok_or(StatusCode::BAD_REQUEST)?;
if csaf_provider
.as_deref()
.is_some_and(|url| !is_https_url(url))
{
let refusal = UploadRefusal::because(
StatusCode::UNPROCESSABLE_ENTITY,
"the CSAF provider must be an https URL",
"csaf_provider",
);
return Err(refused(&db, &invite, &filename, refusal).await);
}
let attached = match attach_upload(&db, &target, ArtifactKind::SupplierSbom, None, upload).await
{
Ok(attached) => attached,
Err(refusal) => return Err(refused(&db, &invite, &filename, refusal).await),
};
// Only a component without one takes the supplier's provider: one the
// customer set stays. The upload keeps what the supplier gave either way.
let unset = target
.supplier
.clone()
.filter(|supplier| supplier.csaf_provider.is_none());
if let (Some(url), Some(mut supplier)) = (&csaf_provider, unset) {
supplier.csaf_provider = Some(url.clone());
let set = mongodb::bson::to_bson(&supplier).map_err(internal)?;
db.onboarded_targets()
.update_one(
doc! { "_id": target.id },
doc! { "$set": { "supplier": set } },
)
.await
.map_err(internal)?;
refresh_supplier_csaf(&st.agent, &tenant_id, Some(&supplier));
}
let record = SupplierUpload {
id: ObjectId::new(),
invite_id: invite.id.to_hex(),
target_id: invite.target_id.clone(),
uploaded_at: BsonDateTime::now(),
filename,
accepted: true,
code: None,
summary: attached.summary,
artifact_id: Some(attached.artifact_id.clone()),
csaf_provider,
};
uploads(&db).insert_one(&record).await.map_err(internal)?;
let (agent, target_id) = (st.agent.clone(), invite.target_id.clone());
tokio::spawn(async move {
if let Err(e) = agent
.run_target_scan(&tenant_id, &target_id, ScanTrigger::NewContent)
.await
{
tracing::error!(target_id, "scan after a supplier upload failed: {e}");
}
});
let current = Some(attached.artifact_id.as_str());
Ok((StatusCode::CREATED, Json(UploadView::of(record, current))))
}
/// `POST /api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms/check`:
/// what the supplier's page shows of a file before it is uploaded, through a
/// valid invite: the same check as `POST /api/v1/supplier-sboms/check`.
/// Nothing is stored or recorded.
///
/// # Errors
///
/// 404 and 410 as for [`upload_through_invite`]; the check's own refusals.
pub async fn check_through_invite(
State(st): State<PlatformState>,
Path((tenant_id, invite_id)): Path<(String, String)>,
multipart: Multipart,
) -> Result<Json<super::ApiResponse<SupplierSbomSummary>>, UploadRefusal> {
let db = st.agent.db_pool.for_existing_tenant_id(&tenant_id);
let invite = open_invite(&db, &invite_id).await?;
invite_target(&db, &invite).await?;
super::onboarding::check_supplier_sbom(multipart).await
}
/// Record `refusal` of an upload of `filename` through `invite`, when it has a
/// code the supplier can act on, and hand it back. A failed record is logged:
/// the refusal stands either way.
async fn refused(
db: &Database,
invite: &SupplierInvite,
filename: &str,
refusal: UploadRefusal,
) -> UploadRefusal {
if let Some(code) = refusal.code() {
let record = SupplierUpload::refused(invite, filename, code);
if let Err(e) = uploads(db).insert_one(&record).await {
tracing::warn!(invite_id = %invite.id, "refused supplier upload not recorded: {e}");
}
}
refusal
}
#[cfg(test)]
mod tests {
use super::*;
fn invite_at(now: DateTime<Utc>) -> SupplierInvite {
SupplierInvite::new("t1".into(), "a@b.example".into(), "u1".into(), now)
}
#[test]
fn an_invite_is_active_for_ninety_days() {
let now = Utc::now();
let invite = invite_at(now);
assert_eq!(
invite.expires_at.to_chrono() - invite.created_at.to_chrono(),
chrono::Duration::days(90)
);
assert_eq!(invite.state(now), InviteState::Active);
let last = now + chrono::Duration::days(90) - chrono::Duration::seconds(1);
assert_eq!(invite.state(last), InviteState::Active);
assert_eq!(
invite.state(now + chrono::Duration::days(90)),
InviteState::Expired
);
}
#[test]
fn a_withdrawn_invite_stays_withdrawn_after_it_expires() {
let now = Utc::now();
let mut invite = invite_at(now);
invite.withdrawn_at = Some(now.into());
assert_eq!(invite.state(now), InviteState::Withdrawn);
assert_eq!(
invite.state(now + chrono::Duration::days(200)),
InviteState::Withdrawn
);
}
#[test]
fn an_address_is_kept_in_lower_case_and_nonsense_is_refused() {
assert_eq!(
normalized_email(" SBOM@Antrieb.Example "),
Some("sbom@antrieb.example".into())
);
for bad in [
"",
"no-at.example",
"@antrieb.example",
"a@localhost",
"a@.example",
"a@example.",
"a@b@c.example",
"a b@c.example",
] {
assert_eq!(normalized_email(bad), None, "{bad}");
}
let long = format!("{}@b.example", "a".repeat(250));
assert_eq!(normalized_email(&long), None);
}
#[test]
fn an_upload_is_shown_by_its_file_name_only() {
assert_eq!(shown_filename("../../dr4.cdx.json"), "dr4.cdx.json");
assert_eq!(shown_filename("C:\\sbom\\dr4.json"), "dr4.json");
assert_eq!(shown_filename(" "), "sbom");
assert_eq!(shown_filename("dir/"), "sbom");
assert_eq!(shown_filename(&"ä".repeat(300)).chars().count(), 200);
}
#[test]
fn an_actor_is_required_and_bounded() {
assert_eq!(normalized_actor(" u-1 "), Some("u-1".into()));
assert_eq!(normalized_actor(" "), None);
assert_eq!(normalized_actor(&"u".repeat(201)), None);
}
#[test]
fn an_invite_round_trips_through_bson() {
let invite = invite_at(Utc::now());
let stored = mongodb::bson::to_document(&invite).expect("bson");
assert!(stored.get_datetime("expires_at").is_ok(), "a BSON date");
let back: SupplierInvite = mongodb::bson::from_document(stored).expect("back");
assert_eq!(back, invite);
}
}
@@ -1,823 +0,0 @@
//! The supply chain (#1050, #1051): what a workspace's products are made of,
//! as a graph for the dashboard to draw.
//!
//! Suppliers deliver components (targets); components are part of assemblies
//! and products (the registry's product projects); assemblies are part of
//! products. A component can be part of several products, so the graph is a
//! DAG, not a tree. Every component and project carries its open CVEs.
use std::collections::{BTreeSet, HashMap, HashSet};
use axum::extract::Extension;
use axum::http::StatusCode;
use axum::Json;
use chrono::{DateTime, Utc};
use mongodb::bson::{doc, oid::ObjectId};
use serde::Serialize;
use compliance_core::cve_groups::SeverityCounts;
use compliance_core::models::{
ArtifactKind, CveAlert, OnboardedTarget, Project, ProjectKind, ProjectLevel, TargetType,
};
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{collect_cursor_async, tenant_db, AgentExt};
use super::machine::{open_alerts, open_counts};
use super::offers::SbomOffer;
use super::projects::tenant_projects;
use super::supplier_invites::SupplierInvite;
use super::ApiResponse;
use crate::database::Database;
/// The supply chain: its nodes and the edges between them.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SupplyChain {
/// Suppliers, then components, then projects.
pub nodes: Vec<ChainNode>,
/// From supplier to component, component to project, project to the
/// project above it.
pub edges: Vec<ChainEdge>,
}
/// What a node stands for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum NodeKind {
/// A supplier, by the name a target gives it.
Supplier,
/// A component: one of the workspace's targets.
Target,
/// A product project: a family, product or assembly.
Project,
}
/// One node of the supply chain.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ChainNode {
/// Stable across calls, for the arrangement to be kept by:
/// `supplier:<name>`, `target:<id>` or `project:<id>`.
pub key: String,
pub kind: NodeKind,
pub name: String,
/// A component's type.
#[serde(skip_serializing_if = "Option::is_none")]
pub target_type: Option<TargetType>,
/// A component bought in from a supplier, rather than the workspace's own.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub bought: bool,
/// A project's place in the hierarchy.
#[serde(skip_serializing_if = "Option::is_none")]
pub level: Option<ProjectLevel>,
/// Open CVEs: a component's own; a project's, the sum over the distinct
/// components beneath it. None for a supplier.
#[serde(skip_serializing_if = "Option::is_none")]
pub open: Option<SeverityCounts>,
}
/// What an edge means.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum EdgeKind {
/// A supplier delivers the component.
Supplies,
/// The component or project is part of the project.
PartOf,
}
/// How a supplier's SBOM reaches its component.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DeliveryKind {
/// A connected supplier's release, accepted into the component (#1028):
/// each version it publishes arrives by itself.
Release,
/// The supplier uploads it through an active invite link (#1027).
Invite,
/// The release it came by has ended (the supplier ended it, or the
/// connection ended); the version last delivered stays.
ReleaseEnded,
/// Someone in the workspace uploaded it.
Upload,
/// No SBOM yet.
Missing,
}
/// A supplier's delivery to its component.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Delivery {
pub how: DeliveryKind,
/// The version in use, as the workspace names it.
pub version: Option<String>,
/// When the current SBOM arrived.
pub at: Option<DateTime<Utc>>,
}
/// One edge of the supply chain, `from` and `to` by node key.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ChainEdge {
pub from: String,
pub to: String,
pub kind: EdgeKind,
/// How the SBOM arrives, on a supplier's edge.
#[serde(skip_serializing_if = "Option::is_none")]
pub delivery: Option<Delivery>,
}
fn target_key(id: &str) -> String {
format!("target:{id}")
}
fn project_key(id: &str) -> String {
format!("project:{id}")
}
/// The supplier `target` names, trimmed; `None` for one of its own.
fn supplier_name(target: &OnboardedTarget) -> Option<&str> {
target
.supplier
.as_ref()
.map(|s| s.name.trim())
.filter(|name| !name.is_empty())
}
/// What brings a component's new versions by themselves, if anything does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Feed {
/// An accepted release of a connected supplier.
Release,
/// An active invite link.
Invite,
/// A release that delivered, then ended.
ReleaseEnded,
}
/// How `target`'s SBOM arrives from its supplier: by its `feed`, else as an
/// upload once there is one. An ended release names the SBOM it left.
fn delivery(target: &OnboardedTarget, feed: Option<Feed>) -> Delivery {
let sbom = target
.artifacts
.iter()
.filter(|a| a.kind == ArtifactKind::SupplierSbom)
.max_by_key(|a| a.ingested_at);
let how = match (feed, sbom) {
(Some(Feed::Release), _) => DeliveryKind::Release,
(Some(Feed::Invite), _) => DeliveryKind::Invite,
(Some(Feed::ReleaseEnded), Some(_)) => DeliveryKind::ReleaseEnded,
(_, Some(_)) => DeliveryKind::Upload,
(_, None) => DeliveryKind::Missing,
};
Delivery {
how,
version: target.supplier.as_ref().and_then(|s| s.version.clone()),
at: sbom.and_then(|a| a.ingested_at),
}
}
/// The supply chain of `targets` in `projects`.
///
/// # Arguments
///
/// * `targets` - the workspace's targets, not archived, in display order
/// * `projects` - its projects; topics are left out
/// * `open` - each target's open CVEs, by id
/// * `feeds` - what brings each target's new versions, by id, if anything
pub fn supply_chain(
targets: &[OnboardedTarget],
projects: &[Project],
open: &HashMap<String, SeverityCounts>,
feeds: &HashMap<String, Feed>,
) -> SupplyChain {
let products: Vec<&Project> = projects
.iter()
.filter(|p| p.kind == ProjectKind::Product)
.collect();
let known: HashSet<&str> = products.iter().map(|p| p.id.as_str()).collect();
let mut nodes = Vec::new();
let mut edges = Vec::new();
let mut suppliers = BTreeSet::new();
for t in targets {
if let Some(name) = supplier_name(t) {
suppliers.insert(name);
}
}
nodes.extend(suppliers.into_iter().map(|name| ChainNode {
key: format!("supplier:{name}"),
kind: NodeKind::Supplier,
name: name.to_string(),
target_type: None,
bought: false,
level: None,
open: None,
}));
// The targets directly in each project, by id.
let mut direct: HashMap<&str, Vec<String>> = HashMap::new();
for t in targets {
let Some(id) = t.id.map(|o: ObjectId| o.to_hex()) else {
continue;
};
let key = target_key(&id);
if let Some(name) = supplier_name(t) {
edges.push(ChainEdge {
from: format!("supplier:{name}"),
to: key.clone(),
kind: EdgeKind::Supplies,
delivery: Some(delivery(t, feeds.get(&id).copied())),
});
}
for project in t.project_ids.iter().filter(|p| known.contains(p.as_str())) {
edges.push(ChainEdge {
from: key.clone(),
to: project_key(project),
kind: EdgeKind::PartOf,
delivery: None,
});
direct.entry(project.as_str()).or_default().push(id.clone());
}
nodes.push(ChainNode {
key,
kind: NodeKind::Target,
name: t.name.clone(),
target_type: Some(t.target_type),
bought: t.supplier.is_some(),
level: None,
open: Some(open.get(&id).copied().unwrap_or_default()),
});
}
// Each project's children: the projects whose parent it is.
let mut children: HashMap<&str, Vec<&str>> = HashMap::new();
for p in &products {
if let Some(parent) = p
.parent_id
.as_deref()
.filter(|id| known.contains(id) && *id != p.id)
{
children.entry(parent).or_default().push(&p.id);
edges.push(ChainEdge {
from: project_key(&p.id),
to: project_key(parent),
kind: EdgeKind::PartOf,
delivery: None,
});
}
}
for p in &products {
// Every target beneath the project, once, however it is reached.
let mut seen: HashSet<&str> = HashSet::new();
let mut beneath: HashSet<&String> = HashSet::new();
let mut queue = vec![p.id.as_str()];
while let Some(cur) = queue.pop() {
if !seen.insert(cur) {
continue;
}
beneath.extend(direct.get(cur).into_iter().flatten());
queue.extend(children.get(cur).into_iter().flatten().copied());
}
let sum = beneath
.into_iter()
.filter_map(|id| open.get(id))
.fold(SeverityCounts::default(), |sum, c| sum.plus(*c));
nodes.push(ChainNode {
key: project_key(&p.id),
kind: NodeKind::Project,
name: p.name.clone(),
target_type: None,
bought: false,
level: Some(p.level.unwrap_or(ProjectLevel::Product)),
open: Some(sum),
});
}
SupplyChain { nodes, edges }
}
/// A document of a product's box: one of the store's documents of the
/// product, opened in the portal.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BoxDocument {
/// The store's id of the document.
pub id: String,
pub title: String,
pub filename: String,
pub content_type: Option<String>,
pub size_bytes: Option<u64>,
/// Internal to the workspace rather than published with the product.
pub internal: bool,
pub created_at: Option<DateTime<Utc>>,
/// Where the portal shows it, below the portal's address.
pub path: String,
}
/// What a product's box shows besides its graph (#1054): the project's
/// description and its documents in the portal's Dokumentenablage.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ProjectDocuments {
/// The project's description, as the portal keeps it.
pub description: String,
/// Its documents, newest first.
pub documents: Vec<BoxDocument>,
/// Where the portal's store is, below the portal's address, for adding
/// one; empty without a registry.
pub store_path: String,
}
/// The documents of `store` that belong to product project `project`, newest
/// first, with where the portal of workspace `slug` shows each. Legal web
/// documents and BreakPilot's deliveries belong to no product.
fn box_documents(
store: Vec<crate::registry::StoreDocument>,
project: &str,
slug: &str,
) -> Vec<BoxDocument> {
let slug = urlencoding::encode(slug);
let mut documents: Vec<BoxDocument> = store
.into_iter()
.filter(|d| d.project_ids.iter().any(|p| p == project))
.filter_map(|d| {
let internal = match d.area.as_deref() {
Some("product_public") => false,
Some("internal") => true,
_ => return None,
};
Some(BoxDocument {
path: format!("/{slug}/dokumente/{}/original", urlencoding::encode(&d.id)),
id: d.id,
title: d.title,
filename: d.filename,
content_type: d.content_type,
size_bytes: d.size_bytes,
internal,
created_at: d.created_at,
})
})
.collect();
documents.sort_by_key(|d| std::cmp::Reverse(d.created_at));
documents
}
/// A product's description and documents, for its box on the Lieferkette.
///
/// The description is the project's, and the documents are those of the
/// portal's Dokumentenablage that belong to the project (published with the
/// product or internal), newest first. Each names where the portal shows it.
/// Prüfwerk keeps no copy. Without a registry (development) there is
/// nothing to show.
#[utoipa::path(
get,
path = "/api/v1/supply-chain/projects/{id}/documents",
tag = "Targets",
params(("id" = String, Path, description = "The product project's id")),
responses(
(status = 200, description = "Its description and documents (`data`)"),
(status = 404, description = "No product project of the workspace"),
(status = 503, description = "The registry cannot be asked"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all, fields(project_id = %id))]
pub async fn project_documents(
Extension(agent): AgentExt,
tenant: TenantCtx,
axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Json<ApiResponse<ProjectDocuments>>, StatusCode> {
let Some(registry) = agent.registry.as_ref() else {
return Ok(Json(ApiResponse {
data: ProjectDocuments {
description: String::new(),
documents: Vec::new(),
store_path: String::new(),
},
total: None,
page: None,
}));
};
let ctx = &tenant.0;
let project = tenant_projects(&agent, &ctx.tenant_id)
.await?
.into_iter()
.find(|p| p.id == id && p.kind == ProjectKind::Product)
.ok_or(StatusCode::NOT_FOUND)?;
let store = registry.list_store(&ctx.tenant_id).await.map_err(|e| {
tracing::error!(tenant_id = %ctx.tenant_id, "store list unavailable: {e}");
StatusCode::SERVICE_UNAVAILABLE
})?;
Ok(Json(ApiResponse {
data: ProjectDocuments {
description: project.description,
documents: box_documents(store, &id, &ctx.tenant_slug),
store_path: format!("/{}/dokumente", urlencoding::encode(&ctx.tenant_slug)),
},
total: None,
page: None,
}))
}
/// Without a registry (development), every project a target names, as a
/// product named by its id, as the machine page names it.
fn unregistered_projects(targets: &[OnboardedTarget]) -> Vec<Project> {
targets
.iter()
.flat_map(|t| t.project_ids.iter())
.collect::<BTreeSet<_>>()
.into_iter()
.map(|id| Project {
id: id.clone(),
name: id.clone(),
kind: ProjectKind::Product,
description: String::new(),
level: None,
parent_id: None,
})
.collect()
}
/// The targets among `ids` with a supplier invite that is neither withdrawn
/// nor expired.
async fn invited_targets(db: &Database, ids: &[String]) -> Result<HashSet<String>, StatusCode> {
let found = db
.inner()
.collection::<SupplierInvite>(SupplierInvite::COLLECTION)
.distinct(
"target_id",
doc! {
"target_id": { "$in": ids },
"withdrawn_at": null,
"expires_at": { "$gt": mongodb::bson::DateTime::now() },
},
)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(found
.into_iter()
.filter_map(|id| id.as_str().map(str::to_string))
.collect())
}
/// The targets among `ids` that offers of connected suppliers deliver into,
/// in state `state`; for an ended one, only if it delivered a version.
async fn offered_targets(
db: &Database,
ids: &[String],
state: &str,
) -> Result<HashSet<String>, StatusCode> {
let mut filter = doc! { "target_id": { "$in": ids }, "state": state };
if state == "ended" {
filter.insert("delivered_label", doc! { "$ne": null });
}
let found = db
.inner()
.collection::<SbomOffer>(SbomOffer::COLLECTION)
.distinct("target_id", filter)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(found
.into_iter()
.filter_map(|id| id.as_str().map(str::to_string))
.collect())
}
/// What brings each of the targets `ids` its new versions: an accepted
/// release before an invite link, and either before a release that ended.
async fn feeds(db: &Database, ids: &[String]) -> Result<HashMap<String, Feed>, StatusCode> {
let mut feeds = HashMap::new();
for (found, feed) in [
(offered_targets(db, ids, "ended").await?, Feed::ReleaseEnded),
(invited_targets(db, ids).await?, Feed::Invite),
(offered_targets(db, ids, "accepted").await?, Feed::Release),
] {
feeds.extend(found.into_iter().map(|id| (id, feed)));
}
Ok(feeds)
}
/// The workspace's supply chain.
///
/// Its suppliers, components (targets) and product projects (families,
/// products and assemblies) as nodes, and as edges: supplier to component,
/// with how its SBOM arrives; component to the projects it is part of;
/// project to the project above it. A component can be part of several
/// projects. Each component carries its open CVEs, each project the sum over
/// the distinct components beneath it. Archived targets and topic projects
/// are left out.
#[utoipa::path(
get,
path = "/api/v1/supply-chain",
tag = "Targets",
responses(
(status = 200, description = "The supply chain (`data`: `nodes` and `edges`)"),
(status = 503, description = "The registry cannot be asked"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn get_supply_chain(
Extension(agent): AgentExt,
tenant: TenantCtx,
) -> Result<Json<ApiResponse<SupplyChain>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let targets: Vec<OnboardedTarget> = collect_cursor_async(
db.onboarded_targets()
.find(doc! { "archived_at": null })
.sort(doc! { "name": 1 })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
)
.await;
let projects = match agent.registry {
Some(_) => tenant_projects(&agent, &tenant.0.tenant_id).await?,
None => unregistered_projects(&targets),
};
let ids: Vec<String> = targets
.iter()
.filter_map(|t| t.id.map(|o: ObjectId| o.to_hex()))
.collect();
let alerts = open_alerts(&db, &ids).await?;
let mut by_target: HashMap<&str, Vec<&CveAlert>> = HashMap::new();
for alert in &alerts {
by_target
.entry(alert.repo_id.as_str())
.or_default()
.push(alert);
}
let open: HashMap<String, SeverityCounts> = by_target
.into_iter()
.map(|(id, alerts)| (id.to_string(), open_counts(alerts)))
.collect();
let feeds = feeds(&db, &ids).await?;
Ok(Json(ApiResponse {
data: supply_chain(&targets, &projects, &open, &feeds),
total: None,
page: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::models::{Artifact, SupplierComponent};
fn target(name: &str, supplier: Option<&str>, projects: &[&str]) -> OnboardedTarget {
let mut t = OnboardedTarget::new(name.into(), TargetType::FirmwareRtos);
t.id = Some(ObjectId::new());
t.supplier = supplier.map(|s| SupplierComponent {
name: format!(" {s} "),
product: None,
version: Some("1.4.0".into()),
csaf_provider: None,
});
t.project_ids = projects.iter().map(|p| p.to_string()).collect();
t
}
fn project(id: &str, level: ProjectLevel, parent: Option<&str>) -> Project {
Project {
id: id.into(),
name: format!("Projekt {id}"),
kind: ProjectKind::Product,
description: String::new(),
level: Some(level),
parent_id: parent.map(String::from),
}
}
fn id(t: &OnboardedTarget) -> String {
t.id.unwrap().to_hex()
}
fn counts(critical: usize, high: usize, medium: usize) -> SeverityCounts {
SeverityCounts {
critical,
high,
medium,
..SeverityCounts::default()
}
}
/// A drive and a sensor in an assembly of product p1; a panel and the
/// workspace's own PLC program shared by products p1 and p2.
fn machine() -> (Vec<OnboardedTarget>, Vec<Project>) {
let mut drive = target("Antrieb", Some("Antriebe GmbH"), &["c1"]);
let mut sbom = Artifact::supplier_sbom("drive.cdx.json");
sbom.ingested_at = Some(Utc::now());
drive.artifacts.push(sbom);
let sensor = target("Sensor", Some("Sensorik AG"), &["c1"]);
let panel = target("Panel", Some("Display KG"), &["p1", "p2", "t1", "gone"]);
let plc = target("Steuerung", None, &["p1", "p2"]);
let mut topic = project("t1", ProjectLevel::Product, None);
topic.kind = ProjectKind::Topic;
topic.level = None;
let projects = vec![
project("p1", ProjectLevel::Product, None),
project("p2", ProjectLevel::Product, None),
project("c1", ProjectLevel::Component, Some("p1")),
topic,
];
(vec![drive, sensor, panel, plc], projects)
}
#[test]
fn suppliers_deliver_their_components_and_say_how() {
let (targets, projects) = machine();
let feeds = HashMap::from([(id(&targets[1]), Feed::Invite)]);
let chain = supply_chain(&targets, &projects, &HashMap::new(), &feeds);
let suppliers: Vec<&str> = chain
.nodes
.iter()
.filter(|n| n.kind == NodeKind::Supplier)
.map(|n| n.key.as_str())
.collect();
assert_eq!(
suppliers,
[
"supplier:Antriebe GmbH",
"supplier:Display KG",
"supplier:Sensorik AG"
],
"named once each, trimmed"
);
let how = |target: &OnboardedTarget| {
chain
.edges
.iter()
.find(|e| e.kind == EdgeKind::Supplies && e.to == target_key(&id(target)))
.and_then(|e| e.delivery.clone())
.unwrap()
};
let drive = how(&targets[0]);
assert_eq!(drive.how, DeliveryKind::Upload);
assert_eq!(drive.version.as_deref(), Some("1.4.0"));
assert!(drive.at.is_some());
assert_eq!(how(&targets[1]).how, DeliveryKind::Invite);
assert_eq!(how(&targets[2]).how, DeliveryKind::Missing);
let plc = chain.nodes.iter().find(|n| n.name == "Steuerung").unwrap();
assert!(!plc.bought, "the workspace's own");
assert!(!chain
.edges
.iter()
.any(|e| e.to == plc.key && e.kind == EdgeKind::Supplies));
}
#[test]
fn a_release_delivers_by_itself_and_leaves_its_version_when_it_ends() {
let (targets, _) = machine();
let (drive, sensor) = (&targets[0], &targets[1]);
let live = delivery(drive, Some(Feed::Release));
assert_eq!(live.how, DeliveryKind::Release);
assert_eq!(live.version.as_deref(), Some("1.4.0"));
assert!(live.at.is_some(), "when the version arrived");
assert_eq!(
delivery(sensor, Some(Feed::Release)).how,
DeliveryKind::Release
);
let ended = delivery(drive, Some(Feed::ReleaseEnded));
assert_eq!(ended.how, DeliveryKind::ReleaseEnded);
assert_eq!(
ended.version.as_deref(),
Some("1.4.0"),
"the version that stays"
);
assert_eq!(
delivery(sensor, Some(Feed::ReleaseEnded)).how,
DeliveryKind::Missing,
"an ended release that left no SBOM"
);
assert_eq!(
serde_json::to_value(DeliveryKind::ReleaseEnded).unwrap(),
"release_ended"
);
}
#[test]
fn components_are_part_of_products_and_assemblies_of_their_product() {
let (targets, projects) = machine();
let chain = supply_chain(&targets, &projects, &HashMap::new(), &HashMap::new());
let part_of: BTreeSet<(String, &str)> = chain
.edges
.iter()
.filter(|e| e.kind == EdgeKind::PartOf)
.map(|e| {
let from = chain
.nodes
.iter()
.find(|n| n.key == e.from)
.map(|n| n.name.clone())
.unwrap();
(from, e.to.as_str())
})
.collect();
let expected: BTreeSet<(String, &str)> = [
("Antrieb", "project:c1"),
("Sensor", "project:c1"),
("Projekt c1", "project:p1"),
("Panel", "project:p1"),
("Panel", "project:p2"),
("Steuerung", "project:p1"),
("Steuerung", "project:p2"),
]
.into_iter()
.map(|(a, b)| (a.to_string(), b))
.collect();
assert_eq!(part_of, expected, "no topic, no unknown project");
assert!(!chain.nodes.iter().any(|n| n.key == "project:t1"));
let c1 = chain.nodes.iter().find(|n| n.key == "project:c1").unwrap();
assert_eq!(c1.level, Some(ProjectLevel::Component));
}
#[test]
fn a_project_counts_each_component_beneath_it_once() {
let (targets, projects) = machine();
let open = HashMap::from([
(id(&targets[0]), counts(1, 0, 0)),
(id(&targets[1]), counts(0, 2, 0)),
(id(&targets[2]), counts(0, 0, 1)),
]);
let chain = supply_chain(&targets, &projects, &open, &HashMap::new());
let open_of = |key: &str| {
chain
.nodes
.iter()
.find(|n| n.key == key)
.and_then(|n| n.open)
.unwrap()
};
assert_eq!(open_of("project:c1"), counts(1, 2, 0));
// The assembly's parts and the shared panel; the PLC has none.
assert_eq!(open_of("project:p1"), counts(1, 2, 1));
assert_eq!(open_of("project:p2"), counts(0, 0, 1));
assert_eq!(
open_of(&target_key(&id(&targets[3]))),
SeverityCounts::default()
);
}
#[test]
fn a_cycle_of_parents_ends() {
let targets = vec![target("Teil", None, &["a"])];
let projects = vec![
project("a", ProjectLevel::Component, Some("b")),
project("b", ProjectLevel::Component, Some("a")),
];
let open = HashMap::from([(id(&targets[0]), counts(0, 1, 0))]);
let chain = supply_chain(&targets, &projects, &open, &HashMap::new());
let b = chain.nodes.iter().find(|n| n.key == "project:b").unwrap();
assert_eq!(b.open, Some(counts(0, 1, 0)));
}
#[test]
fn a_box_shows_the_documents_of_its_product_newest_first() {
use crate::registry::StoreDocument;
let doc = |id: &str, area: Option<&str>, projects: &[&str], day: u32| StoreDocument {
id: id.into(),
title: format!("Doc {id}"),
filename: format!("{id}.pdf"),
content_type: Some("application/pdf".into()),
size_bytes: Some(1024),
area: area.map(String::from),
project_ids: projects.iter().map(|p| p.to_string()).collect(),
created_at: chrono::NaiveDate::from_ymd_opt(2026, 11, day)
.and_then(|d| d.and_hms_opt(9, 0, 0))
.map(|d| d.and_utc()),
};
let store = vec![
doc("manual", Some("product_public"), &["p1"], 10),
doc("notes", Some("internal"), &["p1", "p2"], 12),
doc("other", Some("product_public"), &["p2"], 11),
doc("imprint", Some("legal_web"), &["p1"], 13),
doc("delivery", None, &["p1"], 14),
];
let shown = box_documents(store, "p1", "beispiel maschinenbau");
let ids: Vec<(&str, bool)> = shown.iter().map(|d| (d.id.as_str(), d.internal)).collect();
assert_eq!(
ids,
[("notes", true), ("manual", false)],
"newest first, its own only"
);
assert_eq!(
shown[1].path,
"/beispiel%20maschinenbau/dokumente/manual/original"
);
}
#[test]
fn without_a_registry_projects_are_named_by_their_id() {
let targets = vec![
target("Teil", None, &["m1", "m2"]),
target("Ander", None, &["m1"]),
];
let projects = unregistered_projects(&targets);
let ids: Vec<&str> = projects.iter().map(|p| p.name.as_str()).collect();
assert_eq!(ids, ["m1", "m2"]);
}
}
@@ -1,272 +0,0 @@
//! The customer's arrangement of the supply chain (#1050, #1052): where each
//! box of the Lieferkette sits, kept per workspace.
//!
//! One document in the tenant's own database, so the workspace export and
//! erasure cover it. The positions are a list, not a map keyed by node: a
//! supplier's name may hold a dot, which a document key may not. Saving
//! replaces the whole arrangement (the last save wins); a node the graph no
//! longer has is ignored by the page, and a new one takes its computed place.
use axum::extract::Extension;
use axum::http::StatusCode;
use axum::Json;
use chrono::{DateTime, Utc};
use mongodb::bson::{doc, DateTime as BsonDateTime};
use serde::{Deserialize, Serialize};
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{tenant_db, AgentExt};
use super::ApiResponse;
use crate::database::Database;
/// The collection, in the tenant's own database.
pub const COLLECTION: &str = "supply_chain_layout";
/// The one document's id.
const LAYOUT_ID: &str = "layout";
/// The most boxes an arrangement holds.
const MAX_POSITIONS: usize = 5_000;
/// The longest node key accepted.
const MAX_KEY_LEN: usize = 400;
/// How far a box may sit from the origin, in pixels, either way.
const MAX_COORDINATE: i32 = 100_000;
/// Where one box sits.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
pub struct NodePosition {
/// The node's key, as `GET /api/v1/supply-chain` gives it.
pub key: String,
/// Its left edge, in pixels.
pub x: i32,
/// Its top edge, in pixels.
pub y: i32,
}
/// The arrangement as the page reads it.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Layout {
/// The boxes the customer placed; any other takes its computed place.
pub positions: Vec<NodePosition>,
/// When it was last saved; `None` before the first save.
pub updated_at: Option<DateTime<Utc>>,
}
/// The body of a save.
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct SaveLayout {
/// Every placed box. One that is left out takes its computed place.
pub positions: Vec<NodePosition>,
}
/// The arrangement as stored.
#[derive(Debug, Serialize, Deserialize)]
struct StoredLayout {
#[serde(rename = "_id")]
id: String,
positions: Vec<NodePosition>,
updated_at: BsonDateTime,
updated_by: String,
}
fn layouts(db: &Database) -> mongodb::Collection<StoredLayout> {
db.inner().collection(COLLECTION)
}
/// `positions` as kept: each key trimmed and once (the last position given
/// wins), in the order first given.
///
/// # Errors
///
/// 422 for too many boxes, an empty or overlong key, or a box too far out.
fn checked(positions: Vec<NodePosition>) -> Result<Vec<NodePosition>, StatusCode> {
if positions.len() > MAX_POSITIONS {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
let mut kept: Vec<NodePosition> = Vec::with_capacity(positions.len());
// Where each key sits in `kept`: one lookup per box, not a scan.
let mut index: std::collections::HashMap<String, usize> =
std::collections::HashMap::with_capacity(positions.len());
for p in positions {
let key = p.key.trim();
let usable = !key.is_empty()
&& key.len() <= MAX_KEY_LEN
&& p.x.abs() <= MAX_COORDINATE
&& p.y.abs() <= MAX_COORDINATE;
if !usable {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
match index.get(key) {
Some(&i) => (kept[i].x, kept[i].y) = (p.x, p.y),
None => {
index.insert(key.to_string(), kept.len());
kept.push(NodePosition {
key: key.to_string(),
x: p.x,
y: p.y,
});
}
}
}
Ok(kept)
}
/// The workspace's arrangement of its supply chain.
///
/// The boxes the customer placed, by node key; an empty list before the
/// first save, when every box takes its computed place.
#[utoipa::path(
get,
path = "/api/v1/supply-chain/layout",
tag = "Targets",
responses(
(status = 200, description = "The arrangement (`data`: `positions`, `updated_at`)"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn get_layout(
Extension(agent): AgentExt,
tenant: TenantCtx,
) -> Result<Json<ApiResponse<Layout>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let stored = layouts(&db)
.find_one(doc! { "_id": LAYOUT_ID })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let data = stored.map_or(
Layout {
positions: Vec::new(),
updated_at: None,
},
|s| Layout {
positions: s.positions,
updated_at: Some(s.updated_at.to_chrono()),
},
);
Ok(Json(ApiResponse {
data,
total: None,
page: None,
}))
}
/// Save the workspace's arrangement of its supply chain.
///
/// Replaces the whole arrangement: the last save wins. Each key is kept once,
/// with the last position given for it.
#[utoipa::path(
put,
path = "/api/v1/supply-chain/layout",
tag = "Targets",
request_body = SaveLayout,
responses(
(status = 200, description = "The arrangement as kept (`data`)"),
(status = 422, description = "Too many boxes, an empty or overlong key, or a box too far out"),
(status = 401, description = "No valid bearer token"),
(status = 403, description = "A read-only role"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn save_layout(
Extension(agent): AgentExt,
tenant: TenantCtx,
Json(body): Json<SaveLayout>,
) -> Result<Json<ApiResponse<Layout>>, StatusCode> {
let positions = checked(body.positions)?;
let db = tenant_db(&agent, &tenant).await?;
let now = Utc::now();
let stored = StoredLayout {
id: LAYOUT_ID.to_string(),
positions,
updated_at: now.into(),
updated_by: tenant.0.user_id.clone(),
};
layouts(&db)
.replace_one(doc! { "_id": LAYOUT_ID }, &stored)
.upsert(true)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(ApiResponse {
data: Layout {
positions: stored.positions,
updated_at: Some(stored.updated_at.to_chrono()),
},
total: None,
page: None,
}))
}
/// Reset the workspace's arrangement: every box takes its computed place.
#[utoipa::path(
delete,
path = "/api/v1/supply-chain/layout",
tag = "Targets",
responses(
(status = 200, description = "The arrangement was reset"),
(status = 401, description = "No valid bearer token"),
(status = 403, description = "A read-only role"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn reset_layout(
Extension(agent): AgentExt,
tenant: TenantCtx,
) -> Result<Json<serde_json::Value>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
layouts(&db)
.delete_one(doc! { "_id": LAYOUT_ID })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(serde_json::json!({ "status": "reset" })))
}
#[cfg(test)]
mod tests {
use super::*;
fn at(key: &str, x: i32, y: i32) -> NodePosition {
NodePosition {
key: key.into(),
x,
y,
}
}
#[test]
fn a_key_is_kept_once_with_its_last_position() {
let kept = checked(vec![
at(" target:a ", 10, 20),
at("supplier:Beispiel GmbH & Co. KG", 0, 0),
at("target:a", 30, 40),
])
.expect("usable");
assert_eq!(
kept,
[
at("target:a", 30, 40),
at("supplier:Beispiel GmbH & Co. KG", 0, 0)
]
);
}
#[test]
fn nonsense_is_refused() {
for bad in [
vec![at(" ", 0, 0)],
vec![at(&"k".repeat(401), 0, 0)],
vec![at("target:a", 100_001, 0)],
vec![at("target:a", 0, -100_001)],
] {
assert_eq!(checked(bad), Err(StatusCode::UNPROCESSABLE_ENTITY));
}
let many = (0..=MAX_POSITIONS)
.map(|i| at(&format!("target:{i}"), 0, 0))
.collect();
assert_eq!(checked(many), Err(StatusCode::UNPROCESSABLE_ENTITY));
assert_eq!(checked(Vec::new()), Ok(Vec::new()));
}
}
+4 -27
View File
@@ -41,20 +41,8 @@ fn picker_order(mut tenants: Vec<SupportTenant>) -> Vec<SupportTenant> {
tenants
}
/// Every tenant, for Breakpilot support to choose from.
///
/// GET /api/v1/support/tenants — every tenant, for support to choose from.
/// 403 for anyone but support; 503 without a registry.
#[utoipa::path(
get,
path = "/api/v1/support/tenants",
tag = "Support",
responses(
(status = 200, description = "The tenants"),
(status = 403, description = "Not support"),
(status = 503, description = "No registry"),
(status = 401, description = "No valid bearer token"),
)
)]
#[tracing::instrument(skip_all)]
pub async fn list_tenants(
Extension(agent): AgentExt,
@@ -72,20 +60,9 @@ pub async fn list_tenants(
Ok(Json(serde_json::json!({ "data": tenants })))
}
/// Open the tenant named in the `X-Pruefwerk-Tenant` header for support.
///
/// The middleware has confirmed it with the registry and records the opening
/// in the audit log; this answers what was opened. 403 for anyone but support.
#[utoipa::path(
post,
path = "/api/v1/support/session",
tag = "Support",
responses(
(status = 200, description = "The opened tenant"),
(status = 403, description = "Not support"),
(status = 401, description = "No valid bearer token"),
)
)]
/// POST /api/v1/support/session — open the tenant named in the header. The
/// middleware has confirmed it with the registry and records the opening in
/// the audit log; this answers what was opened. 403 for anyone but support.
#[tracing::instrument(skip_all)]
pub async fn open_session(tenant: TenantCtx) -> Result<Json<serde_json::Value>, StatusCode> {
if tenant.0.staff.is_none() {
+2 -5
View File
@@ -253,7 +253,7 @@ async fn load_source(db: &crate::database::Database, id: &str) -> Result<VexSour
}
/// The workspace's name, the author of its VEX statements.
pub(super) fn author(tenant: &TenantCtx) -> String {
fn author(tenant: &TenantCtx) -> String {
if tenant.0.tenant_slug.is_empty() {
tenant.0.tenant_id.clone()
} else {
@@ -262,10 +262,7 @@ pub(super) fn author(tenant: &TenantCtx) -> String {
}
/// `body` as a JSON file named `filename` to download.
pub(super) fn download(
body: &serde_json::Value,
filename: &str,
) -> Result<impl IntoResponse, StatusCode> {
fn download(body: &serde_json::Value, filename: &str) -> Result<impl IntoResponse, StatusCode> {
let json = serde_json::to_string_pretty(body).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let disposition = HeaderValue::from_str(&format!("attachment; filename=\"{filename}\""))
.unwrap_or_else(|_| HeaderValue::from_static("attachment"));
+150 -93
View File
@@ -1,6 +1,6 @@
use axum::extract::DefaultBodyLimit;
use axum::http::header::CONTENT_TYPE;
use axum::routing::{get, patch};
use axum::routing::{delete, get, patch, post};
use axum::Router;
use utoipa::OpenApi;
use utoipa_axum::router::{OpenApiRouter, UtoipaMethodRouterExt};
@@ -10,7 +10,7 @@ use crate::api::{handlers, openapi};
/// Allowance on top of the file itself for the multipart framing: boundaries,
/// part headers and the small `kind` / `plc_format` text fields.
pub(crate) const MULTIPART_OVERHEAD: usize = 1024 * 1024;
const MULTIPART_OVERHEAD: usize = 1024 * 1024;
/// The customer API, with its OpenAPI description at [`openapi::SPEC_PATH`]
/// (#1006).
@@ -40,48 +40,30 @@ pub fn build_router() -> Router {
fn described_routes() -> OpenApiRouter {
OpenApiRouter::with_openapi(openapi::ApiDoc::openapi())
.routes(routes!(handlers::health))
.routes(routes!(handlers::oscal::assess_target))
.routes(routes!(handlers::stats_overview))
.route("/api/v1/health", get(handlers::health))
.route("/api/v1/oscal/assess", post(handlers::oscal::assess_target))
.route("/api/v1/stats/overview", get(handlers::stats_overview))
// The tenant's projects (owned by the registry), for assigning targets.
.routes(routes!(handlers::projects::list_projects))
// A machine: a product project and the targets it is made of (#1026).
.routes(routes!(handlers::machine::export_machine_sbom))
.routes(routes!(handlers::machine::machine_overview))
.routes(routes!(handlers::machine::machine_cves))
.routes(routes!(handlers::machine::machine_scan_changes))
.routes(routes!(handlers::supply_chain::get_supply_chain))
.routes(routes!(handlers::connections::list_connections))
// SBOM releases to connected workspaces, the supplier's side (#1028).
.routes(routes!(
handlers::releases::list_releases,
handlers::releases::create_release
))
.routes(routes!(handlers::releases::end_release))
.routes(routes!(handlers::releases::publish_version))
.routes(routes!(handlers::releases::preview_version))
.routes(routes!(handlers::releases::version_draft))
// 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!(
handlers::supply_chain_layout::get_layout,
handlers::supply_chain_layout::save_layout,
handlers::supply_chain_layout::reset_layout
))
.routes(routes!(handlers::metering::get_usage))
.route("/api/v1/projects", get(handlers::projects::list_projects))
.route("/api/v1/metering/usage", get(handlers::metering::get_usage))
// Whether the caller may use Prüfwerk at all: answered by the
// authentication and entitlement layers in front of it (a blocked
// member gets 403 MEMBER_BLOCKED), for the dashboard's sign-in check.
.routes(routes!(handlers::health::access))
.route("/api/v1/access", get(handlers::health::access))
// The managed git source, read-only (IT admin and support).
.routes(routes!(handlers::git_source::get_git_source))
.route(
"/api/v1/git-source",
get(handlers::git_source::get_git_source),
)
// BreakPilot support access: choose and open a customer's tenant.
.routes(routes!(handlers::support::list_tenants))
.routes(routes!(handlers::support::open_session))
.route(
"/api/v1/support/tenants",
get(handlers::support::list_tenants),
)
.route(
"/api/v1/support/session",
post(handlers::support::open_session),
)
// Unified onboarding targets (#131).
.routes(routes!(
handlers::onboarding::list_targets,
@@ -107,14 +89,6 @@ fn described_routes() -> OpenApiRouter {
crate::targets::MAX_UPLOAD_BYTES as usize + MULTIPART_OVERHEAD,
)),
)
// A supplier SBOM is checked when the wizard adds it, before any
// target holds it: up to its own size limit, never kept.
.routes(
routes!(handlers::onboarding::check_supplier_sbom).layer(DefaultBodyLimit::max(
crate::pipeline::sbom::supplied::MAX_BYTES as usize + MULTIPART_OVERHEAD,
)),
)
.routes(routes!(handlers::supplier::get_supplier_advisories))
.routes(routes!(handlers::onboarding::set_archive_password))
.routes(routes!(handlers::onboarding::applicable_scans_for_target))
.routes(routes!(handlers::onboarding::detect_target))
@@ -130,11 +104,14 @@ fn described_routes() -> OpenApiRouter {
.routes(routes!(handlers::finding_groups::list_finding_groups))
.routes(routes!(handlers::finding_groups::decide_finding_group))
// The "Heute" inbox (#950): open decisions in urgency buckets.
.routes(routes!(handlers::inbox::get_inbox))
.routes(routes!(handlers::inbox::decide))
.routes(routes!(handlers::inbox::undo))
.routes(routes!(handlers::inbox::snooze))
.routes(routes!(handlers::inbox::unsnooze))
.route("/api/v1/inbox", get(handlers::inbox::get_inbox))
.route("/api/v1/inbox/decide", post(handlers::inbox::decide))
.route("/api/v1/inbox/undo", post(handlers::inbox::undo))
.route("/api/v1/inbox/snooze", post(handlers::inbox::snooze))
.route(
"/api/v1/inbox/snooze/{key}",
delete(handlers::inbox::unsnooze),
)
// VEX on a target's CVE alerts (#498).
.route(
"/api/v1/targets/{id}/cves",
@@ -177,15 +154,34 @@ fn described_routes() -> OpenApiRouter {
"/api/v1/targets/{id}/sbom-ecosystems",
get(handlers::sbom_ecosystems::list_sbom_ecosystems),
)
.routes(routes!(handlers::evidence::evidence_pack))
.routes(routes!(handlers::evidence::compliance_view))
.routes(routes!(handlers::finding_breakdown::finding_breakdown))
.routes(routes!(handlers::evidence::compliance_summary))
.routes(routes!(handlers::evidence::describe_controls))
.route(
"/api/v1/targets/{id}/evidence-pack",
get(handlers::evidence::evidence_pack),
)
.route(
"/api/v1/targets/{id}/compliance",
get(handlers::evidence::compliance_view),
)
.route(
"/api/v1/targets/{id}/finding-breakdown",
get(handlers::finding_breakdown::finding_breakdown),
)
.route(
"/api/v1/compliance/summary",
get(handlers::evidence::compliance_summary),
)
.route(
"/api/v1/controls",
get(handlers::evidence::describe_controls),
)
// Findings from a manual DAST run or penetration test.
.routes(routes!(handlers::manual_findings::create_finding))
.routes(
routes!(handlers::manual_findings::import_findings).layer(DefaultBodyLimit::max(
.route(
"/api/v1/targets/{id}/findings",
post(handlers::manual_findings::create_finding),
)
.route(
"/api/v1/targets/{id}/findings/import",
post(handlers::manual_findings::import_findings).layer(DefaultBodyLimit::max(
handlers::manual_findings::MAX_IMPORT_BYTES,
)),
)
@@ -213,20 +209,30 @@ fn described_routes() -> OpenApiRouter {
handlers::licenses::withdraw_review
))
.routes(routes!(handlers::licenses::notices))
.routes(routes!(handlers::list_issues))
.routes(routes!(handlers::list_scan_runs))
.route("/api/v1/issues", get(handlers::list_issues))
.route("/api/v1/scan-runs", get(handlers::list_scan_runs))
// MCP token management (per-tenant API tokens for the MCP server)
.routes(routes!(
handlers::mcp_servers::list_mcp_servers,
handlers::mcp_servers::create_mcp_server
))
.routes(routes!(handlers::mcp_servers::delete_mcp_server))
.routes(routes!(handlers::mcp_servers::regenerate_mcp_server_token))
.routes(routes!(
handlers::mcp_tokens::list_mcp_tokens,
handlers::mcp_tokens::create_mcp_token
))
.routes(routes!(handlers::mcp_tokens::revoke_mcp_token))
.route(
"/api/v1/mcp-servers",
get(handlers::mcp_servers::list_mcp_servers)
.post(handlers::mcp_servers::create_mcp_server),
)
.route(
"/api/v1/mcp-servers/{id}",
delete(handlers::mcp_servers::delete_mcp_server),
)
.route(
"/api/v1/mcp-servers/{id}/token",
post(handlers::mcp_servers::regenerate_mcp_server_token),
)
.route(
"/api/v1/mcp-tokens",
get(handlers::mcp_tokens::list_mcp_tokens).post(handlers::mcp_tokens::create_mcp_token),
)
.route(
"/api/v1/mcp-tokens/{id}",
delete(handlers::mcp_tokens::revoke_mcp_token),
)
// Graph API endpoints
.routes(routes!(handlers::graph::get_graph))
.routes(routes!(handlers::graph::get_nodes))
@@ -252,28 +258,79 @@ fn described_routes() -> OpenApiRouter {
// Help chat (documentation-grounded Q&A)
.routes(routes!(handlers::help_chat::help_chat))
// CVE notification endpoints
.routes(routes!(handlers::notifications::list_notifications))
.routes(routes!(handlers::notifications::notification_count))
.routes(routes!(handlers::notifications::mark_all_read))
.routes(routes!(handlers::notifications::mark_read))
.routes(routes!(handlers::notifications::dismiss_notification))
.route(
"/api/v1/notifications",
get(handlers::notifications::list_notifications),
)
.route(
"/api/v1/notifications/count",
get(handlers::notifications::notification_count),
)
.route(
"/api/v1/notifications/read-all",
post(handlers::notifications::mark_all_read),
)
.route(
"/api/v1/notifications/{id}/read",
patch(handlers::notifications::mark_read),
)
.route(
"/api/v1/notifications/{id}/dismiss",
patch(handlers::notifications::dismiss_notification),
)
// Pentest API endpoints
.routes(routes!(handlers::pentest::lookup_repo))
.routes(routes!(
handlers::pentest::list_sessions,
handlers::pentest::create_session
))
.routes(routes!(handlers::pentest::get_session))
.routes(routes!(handlers::pentest::send_message))
.routes(routes!(handlers::pentest::stop_session))
.routes(routes!(handlers::pentest::pause_session))
.routes(routes!(handlers::pentest::resume_session))
.routes(routes!(handlers::pentest::session_stream))
.routes(routes!(handlers::pentest::get_attack_chain))
.routes(routes!(handlers::pentest::get_messages))
.routes(routes!(handlers::pentest::get_session_findings))
.routes(routes!(handlers::pentest::export_session_report))
.routes(routes!(handlers::pentest::pentest_stats))
.route(
"/api/v1/pentest/lookup-repo",
get(handlers::pentest::lookup_repo),
)
.route(
"/api/v1/pentest/sessions",
get(handlers::pentest::list_sessions).post(handlers::pentest::create_session),
)
.route(
"/api/v1/pentest/sessions/{id}",
get(handlers::pentest::get_session),
)
.route(
"/api/v1/pentest/sessions/{id}/chat",
post(handlers::pentest::send_message),
)
.route(
"/api/v1/pentest/sessions/{id}/stop",
post(handlers::pentest::stop_session),
)
.route(
"/api/v1/pentest/sessions/{id}/pause",
post(handlers::pentest::pause_session),
)
.route(
"/api/v1/pentest/sessions/{id}/resume",
post(handlers::pentest::resume_session),
)
.route(
"/api/v1/pentest/sessions/{id}/stream",
get(handlers::pentest::session_stream),
)
.route(
"/api/v1/pentest/sessions/{id}/attack-chain",
get(handlers::pentest::get_attack_chain),
)
.route(
"/api/v1/pentest/sessions/{id}/messages",
get(handlers::pentest::get_messages),
)
.route(
"/api/v1/pentest/sessions/{id}/findings",
get(handlers::pentest::get_session_findings),
)
.route(
"/api/v1/pentest/sessions/{id}/export",
post(handlers::pentest::export_session_report),
)
.route(
"/api/v1/pentest/stats",
get(handlers::pentest::pentest_stats),
)
// Webhook routes live on the separate webhook server (port 3002,
// see crate::webhooks::server). The M7.2-C tenant-in-URL form is
// `/webhook/{tenant_id}/{platform}/{repo_id}` and the handlers
-27
View File
@@ -18,7 +18,6 @@ use compliance_core::{OrgRole, TenantContext, TenantStatus};
use crate::agent::ComplianceAgent;
use crate::api::handlers;
use crate::api::handlers::platform::{self, PlatformState};
use crate::api::handlers::supplier_invites;
use crate::api::{role_gate, routes};
use crate::error::AgentError;
@@ -366,32 +365,6 @@ pub async fn start_api_server(
.put(platform::put_git_source)
.delete(platform::delete_git_source),
)
// Supplier invites (#1027): the portal invites a supplier to upload
// one component's SBOM.
.route(
"/api/v1/platform/tenants/{id}/supplier-invites",
get(supplier_invites::list_invites).post(supplier_invites::create_invite),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/withdraw",
post(supplier_invites::withdraw_invite),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/supplier-view",
get(supplier_invites::supplier_view),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms",
post(supplier_invites::upload_through_invite).layer(DefaultBodyLimit::max(
crate::pipeline::sbom::supplied::MAX_BYTES as usize + routes::MULTIPART_OVERHEAD,
)),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms/check",
post(supplier_invites::check_through_invite).layer(DefaultBodyLimit::max(
crate::pipeline::sbom::supplied::MAX_BYTES as usize + routes::MULTIPART_OVERHEAD,
)),
)
.layer(middleware::from_fn_with_state(
platform_state.clone(),
platform::require_platform_token,
@@ -3,6 +3,20 @@
# `.route("...")` in routes.rs is missing here, or when a line here names no
# such route, so the list only ever shrinks. Describe a route with
# `#[utoipa::path]` and `.routes(routes!(...))`, then delete its line.
/api/v1/health
/api/v1/oscal/assess
/api/v1/stats/overview
/api/v1/projects
/api/v1/metering/usage
/api/v1/access
/api/v1/git-source
/api/v1/support/tenants
/api/v1/support/session
/api/v1/inbox
/api/v1/inbox/decide
/api/v1/inbox/undo
/api/v1/inbox/snooze
/api/v1/inbox/snooze/{key}
/api/v1/targets/{id}/cves
/api/v1/targets/{id}/cve-matrix
/api/v1/cve-history
@@ -16,3 +30,35 @@
/api/v1/targets/{id}/cve-groups
/api/v1/targets/{id}/cve-groups/vex
/api/v1/targets/{id}/sbom-ecosystems
/api/v1/targets/{id}/evidence-pack
/api/v1/targets/{id}/compliance
/api/v1/targets/{id}/finding-breakdown
/api/v1/compliance/summary
/api/v1/controls
/api/v1/targets/{id}/findings
/api/v1/targets/{id}/findings/import
/api/v1/issues
/api/v1/scan-runs
/api/v1/mcp-servers
/api/v1/mcp-servers/{id}
/api/v1/mcp-servers/{id}/token
/api/v1/mcp-tokens
/api/v1/mcp-tokens/{id}
/api/v1/notifications
/api/v1/notifications/count
/api/v1/notifications/read-all
/api/v1/notifications/{id}/read
/api/v1/notifications/{id}/dismiss
/api/v1/pentest/lookup-repo
/api/v1/pentest/sessions
/api/v1/pentest/sessions/{id}
/api/v1/pentest/sessions/{id}/chat
/api/v1/pentest/sessions/{id}/stop
/api/v1/pentest/sessions/{id}/pause
/api/v1/pentest/sessions/{id}/resume
/api/v1/pentest/sessions/{id}/stream
/api/v1/pentest/sessions/{id}/attack-chain
/api/v1/pentest/sessions/{id}/messages
/api/v1/pentest/sessions/{id}/findings
/api/v1/pentest/sessions/{id}/export
/api/v1/pentest/stats
+1 -8
View File
@@ -18,20 +18,15 @@ const MAX_EVIDENCE_CHARS: usize = 4_000;
/// What a finding from a manual test says, whether typed into the form or
/// read from a report.
#[derive(Debug, Clone, Deserialize, PartialEq, utoipa::ToSchema)]
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct ManualFinding {
/// What was found.
pub title: String,
/// The finding in detail.
#[serde(default)]
pub description: String,
/// `info`, `low`, `medium`, `high` or `critical`.
#[schema(value_type = String, example = "high")]
pub severity: Severity,
/// `CWE-79`, or just `79`.
#[serde(default)]
pub cwe: Option<String>,
/// The CVSS base score.
#[serde(default)]
pub cvss_score: Option<f64>,
/// Where it was found: a URL, an endpoint, a file.
@@ -40,10 +35,8 @@ pub struct ManualFinding {
/// A request or response excerpt that shows it.
#[serde(default)]
pub evidence: Option<String>,
/// How to reproduce it.
#[serde(default)]
pub reproduction: Option<String>,
/// How to fix it.
#[serde(default)]
pub remediation: Option<String>,
/// The tool's rule or plugin id, for an imported finding.
+2 -3
View File
@@ -189,9 +189,8 @@ pub fn ingest_artifact(
ArtifactKind::SourceArchive | ArtifactKind::MobilePackage | ArtifactKind::PlcProject => {
ingest_blob(artifact, ctx, true)
}
// Stored as uploaded: the SPDX reader opens the archive itself, and a
// supplier's SBOM is read as the document it is.
ArtifactKind::FirmwareImage | ArtifactKind::BuildOutput | ArtifactKind::SupplierSbom => {
// Stored as uploaded: the SPDX reader opens the archive itself.
ArtifactKind::FirmwareImage | ArtifactKind::BuildOutput => {
ingest_blob(artifact, ctx, false)
}
ArtifactKind::ContainerImage => Ok(metadata_only(
-176
View File
@@ -93,46 +93,6 @@ impl Provider {
max_age: Some(CISA_MAX_AGE),
}
}
/// A supplier's provider a tenant named for a bought-in component (#1025),
/// keyed by its metadata URL ([`supplier_key`]).
pub(crate) fn supplier(metadata_url: &str) -> Self {
Self {
name: supplier_key(metadata_url),
metadata_url: metadata_url.to_string(),
feed_filter: None,
max_age: None,
}
}
}
/// When a supplier's provider was last read, and whether it could be
/// (#1025): kept per tenant in [`SupplierProviderStatus::COLLECTION`], so the
/// target editor can tell a provider without advisories from one never or no
/// longer read.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub(crate) struct SupplierProviderStatus {
/// The provider's key ([`supplier_key`]).
#[serde(rename = "_id")]
pub provider: String,
/// When the last refresh read it.
pub checked_at: mongodb::bson::DateTime,
/// Whether its metadata and feeds could be read then.
pub reachable: bool,
}
impl SupplierProviderStatus {
/// The collection, in the tenant's own database.
pub(crate) const COLLECTION: &'static str = "supplier_csaf_providers";
}
/// The prefix of a supplier provider's key, which tells its advisories from
/// the shared providers' ([`Provider::supplier`]).
pub(crate) const SUPPLIER_PREFIX: &str = "supplier:";
/// The key a supplier's advisories are stored and matched under.
pub(crate) fn supplier_key(metadata_url: &str) -> String {
format!("{SUPPLIER_PREFIX}{}", metadata_url.trim())
}
/// The providers `PW_CSAF_PROVIDERS` names: `off` (none), unset or `default`
@@ -264,19 +224,6 @@ impl MongoAdvisoryStore {
pub(crate) fn collection(&self) -> &mongodb::Collection<StoredAdvisory> {
&self.collection
}
/// The collection of a tenant's supplier advisories (#1025), in the
/// tenant's own database.
pub(crate) const SUPPLIER_COLLECTION: &'static str = "supplier_csaf_advisories";
/// The advisories of the suppliers a tenant named (#1025), in its own
/// database: a provider one tenant chooses is never matched against
/// another tenant's components.
pub(crate) fn supplier(tenant_db: &mongodb::Database) -> Self {
Self {
collection: tenant_db.collection(Self::SUPPLIER_COLLECTION),
}
}
}
impl AdvisoryStore for MongoAdvisoryStore {
@@ -369,8 +316,6 @@ pub(crate) struct Counts {
pub failed: usize,
/// Left for a later run (over the limits).
pub deferred: usize,
/// The provider's metadata or feeds could not be read at all.
pub unreachable: bool,
}
/// One advisory a feed lists.
@@ -511,7 +456,6 @@ pub(crate) async fn refresh(
Err(e) => {
tracing::warn!(provider = %provider.name, "CSAF provider not read: {e}");
counts.failed = 1;
counts.unreachable = true;
out.insert(provider.name.clone(), counts);
continue;
}
@@ -622,99 +566,6 @@ pub(crate) async fn refresh_index(admin_db: &mongodb::Database, guard: NetGuard)
refresh(&fetch, &store, &providers, Limits::default()).await;
}
/// The supplier providers a tenant's active targets name (#1025), once each.
pub(crate) fn supplier_providers(
targets: &[compliance_core::models::OnboardedTarget],
) -> Vec<Provider> {
let mut urls: Vec<&str> = targets
.iter()
.filter(|t| t.archived_at.is_none())
.filter_map(|t| t.supplier.as_ref()?.csaf_provider.as_deref())
.map(str::trim)
.filter(|u| !u.is_empty())
.collect();
urls.sort_unstable();
urls.dedup();
urls.into_iter().map(Provider::supplier).collect()
}
/// Bounds of one refresh of a tenant's supplier advisories: fewer than the
/// shared index, as one tenant's suppliers publish fewer.
fn supplier_limits() -> Limits {
Limits {
max_advisories: 200,
concurrency: 2,
budget: Duration::from_secs(5 * 60),
}
}
/// Refresh the advisories of the supplier providers tenant `tenant_id`'s
/// targets name (#1025), into its own database, through the guarded client.
/// Logs and returns on any failure.
pub(crate) async fn refresh_supplier_advisories(
agent: &crate::agent::ComplianceAgent,
tenant_id: &str,
) {
let db = match agent.db_pool.for_tenant_id(tenant_id).await {
Ok(db) => db,
Err(e) => {
tracing::warn!(tenant_id, "supplier CSAF advisories not refreshed: {e}");
return;
}
};
let targets: Vec<compliance_core::models::OnboardedTarget> = match db
.onboarded_targets()
.find(doc! { "supplier.csaf_provider": { "$exists": true }, "archived_at": null })
.await
{
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
Err(e) => {
tracing::warn!(tenant_id, "supplier CSAF providers not read: {e}");
return;
}
};
let providers = supplier_providers(&targets);
if providers.is_empty() {
return;
}
let fetch = match HttpFetch::new(agent.net_guard) {
Ok(fetch) => fetch,
Err(e) => {
tracing::warn!(tenant_id, "supplier CSAF advisories not refreshed: {e}");
return;
}
};
let store = MongoAdvisoryStore::supplier(db.inner());
let counts = refresh(&fetch, &store, &providers, supplier_limits()).await;
let statuses = db
.inner()
.collection::<SupplierProviderStatus>(SupplierProviderStatus::COLLECTION);
let checked_at = mongodb::bson::DateTime::now();
for (provider, c) in &counts {
let status = SupplierProviderStatus {
provider: provider.clone(),
checked_at,
reachable: !c.unreachable,
};
if let Err(e) = statuses
.replace_one(doc! { "_id": provider }, &status)
.upsert(true)
.await
{
tracing::warn!(tenant_id, provider, "supplier CSAF status not kept: {e}");
}
}
let stored: usize = counts.values().map(|c| c.stored).sum();
let failed: usize = counts.values().map(|c| c.failed).sum();
tracing::info!(
tenant_id,
providers = providers.len(),
stored,
failed,
"supplier CSAF advisories refreshed"
);
}
/// A store for tests: advisories in memory.
#[cfg(test)]
#[derive(Default)]
@@ -781,33 +632,6 @@ impl AdvisoryStore for MemoryStore {
mod tests {
use super::*;
#[test]
fn a_tenants_supplier_providers_are_its_active_targets_once_each() {
use compliance_core::models::{OnboardedTarget, SupplierComponent, TargetType};
let url = "https://supplier.example/.well-known/csaf/provider-metadata.json";
let target = |provider: Option<&str>, archived: bool| {
let mut t = OnboardedTarget::new("c".into(), TargetType::FirmwareBareMetal);
t.supplier = Some(SupplierComponent {
name: "Example GmbH".into(),
product: None,
version: None,
csaf_provider: provider.map(String::from),
});
t.archived_at = archived.then(chrono::Utc::now);
t
};
let providers = supplier_providers(&[
target(Some(url), false),
target(Some(&format!(" {url} ")), false),
target(Some("https://gone.example/provider-metadata.json"), true),
target(None, false),
]);
assert_eq!(providers.len(), 1);
assert_eq!(providers[0].metadata_url, url);
assert_eq!(providers[0].name, format!("{SUPPLIER_PREFIX}{url}"));
assert!(providers[0].feed_filter.is_none() && providers[0].max_age.is_none());
}
/// A provider answering from a table; counts requests.
#[derive(Default)]
struct Fake(HashMap<String, Vec<u8>>, std::sync::Mutex<Vec<String>>);
@@ -88,14 +88,6 @@ fn names(p: &AdvisoryProduct, provider: &str, entry: &SbomEntry) -> bool {
{
return true;
}
// A bought-in product (#1025), by its supplier's name for it, only in
// that supplier's own advisories.
if entry.package_manager == crate::pipeline::sbom::supplied::SUPPLIER_PRODUCT_MANAGER
&& provider.starts_with(crate::pipeline::csaf_feed::SUPPLIER_PREFIX)
&& p.covers(&entry.name, &entry.version)
{
return true;
}
let (Some(theirs), Some(ours)) = (p.purl.as_deref(), entry.purl.as_deref()) else {
return false;
};
@@ -300,52 +292,6 @@ mod tests {
e
}
#[test]
fn a_bought_in_product_is_matched_only_by_its_own_suppliers_advisory() {
// #1025: the product itself, named as its supplier names it, against
// that supplier's advisories; the same advisory under a shared
// provider's key does not name it.
let advisory = codesys_advisory();
let product = |version: &str| {
let mut e = SbomEntry::new(
"t".into(),
"CODESYS Control for Linux SL".into(),
version.into(),
crate::pipeline::sbom::supplied::SUPPLIER_PRODUCT_MANAGER.into(),
);
e.evidence = vec!["supplied by Example GmbH".into()];
e
};
let supplier = crate::pipeline::csaf_feed::supplier_key(
"https://supplier.example/.well-known/csaf/provider-metadata.json",
);
let mut entries = vec![product("3.5.16.0"), product("3.5.22.40")];
let mut alerts = Vec::new();
let n = apply(
"t",
&mut entries,
&[(supplier, advisory.clone())],
&mut alerts,
);
assert_eq!(n, 1, "only the version below the fix");
assert_eq!(alerts[0].cve_id, "CVE-2026-90001");
assert_eq!(alerts[0].affected_version, "3.5.16.0");
let mut entries = vec![product("3.5.16.0")];
let mut alerts = Vec::new();
let n = apply(
"t",
&mut entries,
&[("siemens".to_string(), advisory)],
&mut alerts,
);
assert_eq!(
n, 0,
"a shared provider's advisory does not name a supplier product"
);
}
#[test]
fn a_codesys_runtime_below_the_fix_gets_the_advisory() {
let advisories = vec![("codesys".to_string(), codesys_advisory())];
-38
View File
@@ -565,10 +565,6 @@ const PURL_TYPES_WITHOUT_OSV: &[&str] = &["pkg:cocoapods/"];
/// Whether `entry` belongs to a package manager OSV has no advisories for.
fn without_osv_advisories(entry: &SbomEntry) -> bool {
entry.package_manager == crate::pipeline::sbom::unity::UNITY_MANAGER
// A supplier SBOM's component without a purl (#1025): nothing else
// looks it up, so it is not checked rather than free of CVEs.
|| (entry.package_manager == crate::pipeline::sbom::supplied::SUPPLIER_MANAGER
&& entry.purl.is_none())
|| entry
.purl
.as_deref()
@@ -691,40 +687,6 @@ mod tests {
);
}
#[tokio::test]
async fn a_supplier_sboms_components_are_matched_like_any_others() {
// #1025: the parts of a bought-in component, read from its
// supplier's CycloneDX SBOM, go through the same OSV lookup; one
// without a purl is reported as not checked, not as free of CVEs.
let (url, hits) = fake_osv().await;
let scanner = CveScanner::new(NetGuard::allow_private(), None)
.unwrap()
.with_osv_api(url);
let sbom = r#"{"bomFormat": "CycloneDX", "specVersion": "1.5", "components": [
{"type": "library", "name": "lodash", "version": "4.17.20",
"purl": "pkg:npm/lodash@4.17.20"},
{"type": "library", "name": "vendor-blob", "version": "2.0"}
]}"#;
let mut entries = crate::pipeline::sbom::supplied::parse_with_statements(
sbom.as_bytes(),
"t",
"pump.cdx.json",
)
.unwrap()
.entries;
let lookup = scanner.scan_dependencies("t", &mut entries).await.unwrap();
assert_eq!(hits.load(Ordering::SeqCst), 1);
assert_eq!(lookup.alerts.len(), 1);
assert_eq!(lookup.alerts[0].affected_package, "lodash");
assert_eq!(
lookup.alerts[0].purl.as_deref(),
Some("pkg:npm/lodash@4.17.20")
);
assert_eq!(lookup.unchecked, ["vendor-blob 2.0"]);
}
#[tokio::test]
async fn yocto_recipes_are_left_to_nvd_not_asked_of_osv() {
let (url, hits) = fake_osv().await;
+20 -151
View File
@@ -88,16 +88,6 @@ pub struct PipelineOrchestrator {
pub(super) charged_as: Option<ScanTrigger>,
}
/// Why a target with only a build output skips its code stages: what the
/// dashboard words from it (`coverage::reason`).
const NO_CODE_BUILD_OUTPUT: &str = "the target has no source code (a git repository or a \
source archive): only its build output is read; code analysis, the recipe inventory and \
the recipe lint need the code";
/// Why a target with only a supplier SBOM (#1025) skips its code stages.
const NO_CODE_SUPPLIER_SBOM: &str = "the target has no source code (a git repository or a \
source archive): only its supplier SBOM is read; code analysis needs the code";
impl PipelineOrchestrator {
pub fn new(config: AgentConfig, tenant_id: &str, db: Database, llm: Arc<LlmClient>) -> Self {
let secrets = SecretBox::from_config(&config);
@@ -154,43 +144,6 @@ impl PipelineOrchestrator {
/// Add what the vendor advisories say about `entries` to `alerts`
/// (#515). Best-effort: an index that cannot be read leaves them as
/// they are.
/// Match `entries` against the advisories of the supplier this target is
/// bought from (#1025), stored for this tenant only: the product itself
/// by name and version, and its components by purl.
async fn match_supplier_advisories(
&self,
repo: &RepoView,
target_id: &str,
entries: &mut [SbomEntry],
alerts: &mut Vec<CveAlert>,
) {
use crate::pipeline::csaf_match::AdvisoryIndex;
let Some(url) = repo
.supplier
.as_ref()
.and_then(|s| s.csaf_provider.as_deref())
else {
return;
};
let providers = [crate::pipeline::csaf_feed::supplier_key(url)];
let (_, purls) = crate::pipeline::csaf_match::wanted(entries);
let store = crate::pipeline::csaf_feed::MongoAdvisoryStore::supplier(self.db.inner());
match store.relevant(&providers, &purls).await {
Ok(advisories) if advisories.is_empty() => {}
Ok(advisories) => {
let matched =
crate::pipeline::csaf_match::apply(target_id, entries, &advisories, alerts);
tracing::info!(
target_id,
advisories = advisories.len(),
matched,
"supplier CSAF advisories matched"
);
}
Err(e) => tracing::warn!(target_id, "supplier CSAF advisories not read: {e}"),
}
}
async fn match_advisories(
&self,
target_id: &str,
@@ -681,18 +634,7 @@ impl PipelineOrchestrator {
&repo_id,
));
let yocto_recipes = yocto.recipes;
let (mut supplied, supplier_statements) = self.read_supplier_sboms(repo, &repo_id).await?;
supplied.extend(
repo.supplier
.as_ref()
.and_then(|s| crate::pipeline::sbom::supplied::product_entry(s, &repo_id)),
);
for entry in embedded
.into_iter()
.chain(codesys)
.chain(yocto_entries)
.chain(supplied)
{
for entry in embedded.into_iter().chain(codesys).chain(yocto_entries) {
let known = sbom_entries
.iter()
.any(|e| e.name.eq_ignore_ascii_case(&entry.name) && e.version == entry.version);
@@ -908,10 +850,6 @@ impl PipelineOrchestrator {
self.match_advisories(&repo_id, &mut sbom_entries, &mut cve_alerts)
.await;
self.match_supplier_advisories(repo, &repo_id, &mut sbom_entries, &mut cve_alerts)
.await;
// What the supplier states about each, beside the alert (#1025).
crate::pipeline::sbom::supplied::attach(&supplier_statements, &mut cve_alerts);
self.enrich_cves(&repo_id, &mut cve_alerts, &mut sbom_entries)
.await;
@@ -1860,7 +1798,6 @@ impl PipelineOrchestrator {
let mut repo = RepoView::from_target(target, code, &self.secrets);
repo.yocto_layers = yocto_layers;
repo.build_outputs = build_output_paths(target, &working_paths);
repo.supplier_sboms = supplier_sbom_paths(target, &working_paths);
let n = self.run_pipeline(&repo, scan_run_id, trigger).await?;
self.finalize_target(target, &repo, n).await?;
new_count += n;
@@ -1878,7 +1815,6 @@ impl PipelineOrchestrator {
let mut repo = RepoView::from_target(target, code, &self.secrets);
repo.yocto_layers = yocto_layers;
repo.build_outputs = build_output_paths(target, &working_paths);
repo.supplier_sboms = supplier_sbom_paths(target, &working_paths);
let upload = crate::pipeline::plc::sbom::uploaded_archive(code);
let n = self.scan_tree(tree, upload, &repo, scan_run_id).await?;
self.finalize_target(target, &repo, n).await?;
@@ -1901,11 +1837,7 @@ impl PipelineOrchestrator {
// Only what a build wrote about its image (an image SPDX archive,
// a cve-check report): the same stages run over an empty tree, so
// the SBOM, CVEs and VEX come from the build output alone.
// Or only a supplier's SBOM of a bought-in component (#1025): the
// same, with the components read from it.
None if target.has(ArtifactKind::BuildOutput)
|| target.has(ArtifactKind::SupplierSbom) =>
{
None if target.has(ArtifactKind::BuildOutput) => {
new_count += self
.scan_build_output_only(target, &target_id, &working_paths, scan_run_id)
.await?;
@@ -3194,11 +3126,10 @@ impl PipelineOrchestrator {
/// The recipes, images and package groups of a Yocto layer tree. A parser
/// that failed, a tree with no layer, or recipes the parser could not read
/// are recorded on the run.
/// Scan a target whose only code-like input is its build output or a
/// supplier's SBOM: the stages run over an empty working directory
/// (nothing to find there), with the build outputs read as for a layer
/// tree and the supplier SBOMs as SBOMs. The run says that there was no
/// source code.
/// Scan a target whose only code-like input is its build output: the
/// stages run over an empty working directory (nothing to find there),
/// with the build outputs read as for a layer tree. The run says that
/// there was no source code.
///
/// # Returns
///
@@ -3215,24 +3146,22 @@ impl PipelineOrchestrator {
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
scan_run_id: &str,
) -> Result<u32, AgentError> {
let Some(first) = target.artifacts.iter().find(|a| {
matches!(
a.kind,
ArtifactKind::BuildOutput | ArtifactKind::SupplierSbom
)
}) else {
let Some(first) = target
.artifacts
.iter()
.find(|a| a.kind == ArtifactKind::BuildOutput)
else {
return Ok(0);
};
// What is read instead of code: a build output brings the recipe
// stages a supplier SBOM does not (#1042).
let reason = if target.has(ArtifactKind::BuildOutput) {
NO_CODE_BUILD_OUTPUT
} else {
NO_CODE_SUPPLIER_SBOM
};
self.skip_stage(
scan_run_id,
SkippedStage::new("source_code", SkipCode::NotAnalysedYet, reason),
SkippedStage::new(
"source_code",
SkipCode::NotAnalysedYet,
"the target has no source code (a git repository or a source archive): only \
its build output is read; code analysis, the recipe inventory and the recipe \
lint need the layer tree",
),
)
.await;
// Under the agent's own work directory, so it is never a tree the
@@ -3247,7 +3176,6 @@ impl PipelineOrchestrator {
.map_err(|e| AgentError::Other(format!("build-output work directory: {e}")))?;
let mut repo = RepoView::from_target(target, first, &self.secrets);
repo.build_outputs = build_output_paths(target, working_paths);
repo.supplier_sboms = supplier_sbom_paths(target, working_paths);
let scanned = self.scan_tree(&tree, None, &repo, scan_run_id).await;
let _ = std::fs::remove_dir_all(&tree);
let n = scanned?;
@@ -3255,42 +3183,6 @@ impl PipelineOrchestrator {
Ok(n)
}
/// The components of the target's supplier SBOMs (#1025), read on a
/// blocking thread.
///
/// # Errors
///
/// One that cannot be read fails the scan, with the reason: read as
/// empty, it would let a complete CVE check take every known CVE of the
/// component for gone.
async fn read_supplier_sboms(
&self,
repo: &RepoView,
repo_id: &str,
) -> Result<
(
Vec<compliance_core::models::SbomEntry>,
Vec<crate::pipeline::sbom::supplied::SuppliedStatement>,
),
AgentError,
> {
let (mut entries, mut statements) = (Vec::new(), Vec::new());
for (path, label) in &repo.supplier_sboms {
let (file, id, name) = (path.clone(), repo_id.to_string(), label.clone());
let read = tokio::task::spawn_blocking(move || {
crate::pipeline::sbom::supplied::read_with_statements(&file, &id, &name)
})
.await
.map_err(|e| AgentError::Other(format!("reading the supplier SBOM {label}: {e}")))?
.map_err(|e| {
AgentError::Other(format!("the supplier SBOM {label} cannot be read: {e}"))
})?;
entries.extend(read.entries);
statements.extend(read.statements);
}
Ok((entries, statements))
}
/// What the target's build outputs say: the images their SPDX archives
/// describe ([`crate::pipeline::yocto_spdx`]) and their cve-check reports
/// ([`crate::pipeline::yocto_cve_check`]), told apart by content. One
@@ -3681,40 +3573,17 @@ fn build_output_paths(
target: &OnboardedTarget,
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
) -> Vec<std::path::PathBuf> {
artifacts_of(target, ArtifactKind::BuildOutput, working_paths)
.map(|(_, path)| path)
.collect()
}
/// The target's supplier SBOMs (#1025) as ingested, each with the name it
/// was uploaded under.
fn supplier_sbom_paths(
target: &OnboardedTarget,
working_paths: &std::collections::HashMap<String, std::path::PathBuf>,
) -> Vec<(std::path::PathBuf, String)> {
artifacts_of(target, ArtifactKind::SupplierSbom, working_paths)
.map(|(artifact, path)| (path, artifact.source_ref.clone()))
.collect()
}
/// The target's artifacts of `kind` with the path each was ingested to (or
/// stored at, when this run did not ingest it).
fn artifacts_of<'a>(
target: &'a OnboardedTarget,
kind: ArtifactKind,
working_paths: &'a std::collections::HashMap<String, std::path::PathBuf>,
) -> impl Iterator<Item = (&'a compliance_core::models::Artifact, std::path::PathBuf)> + 'a {
target
.artifacts
.iter()
.filter(move |a| a.kind == kind)
.filter(|a| a.kind == ArtifactKind::BuildOutput)
.filter_map(|a| {
working_paths
.get(&a.id)
.cloned()
.or_else(|| a.stored_path.as_deref().map(std::path::PathBuf::from))
.map(|path| (a, path))
})
.collect()
}
#[cfg(test)]
@@ -60,11 +60,6 @@ pub struct RepoView {
/// The target's uploaded build outputs (Yocto image SPDX archives), as
/// ingested. Set by the caller; empty from [`Self::from_target`].
pub build_outputs: Vec<std::path::PathBuf>,
/// The target's supplier SBOMs (#1025) as ingested, each with the name it
/// was uploaded under. Set by the caller; empty from [`Self::from_target`].
pub supplier_sboms: Vec<(std::path::PathBuf, String)>,
/// Who supplies the component, for one bought in (#1025).
pub supplier: Option<compliance_core::models::SupplierComponent>,
}
impl RepoView {
@@ -100,8 +95,6 @@ impl RepoView {
yocto_layers: false,
exclude_paths: target.scan_config.exclude_paths.clone(),
build_outputs: Vec::new(),
supplier_sboms: Vec::new(),
supplier: target.supplier.clone(),
};
if let Some(git) = &code.git {
view.default_branch = git.default_branch.clone();
@@ -16,7 +16,6 @@ pub(crate) use nuget::nuget_components;
pub(crate) use nuget_license::{LicenseCache, MongoLicenseCache, NugetRegistry};
pub(crate) use nuget_resolve::enabled as nuget_resolution_enabled;
pub(crate) use registry_license::RegistryLicenses;
pub(crate) mod supplied;
mod syft;
pub(crate) mod unity;
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -263,7 +263,7 @@ pub(super) fn canonical_purl(purl: String) -> String {
/// Extract the ecosystem/package-manager from a PURL string.
/// e.g. "pkg:npm/lodash@4.17.21" -> "npm", "pkg:cargo/serde@1.0" -> "cargo"
pub(super) fn extract_ecosystem_from_purl(purl: &str) -> Option<String> {
fn extract_ecosystem_from_purl(purl: &str) -> Option<String> {
let rest = purl.strip_prefix("pkg:")?;
let ecosystem = rest.split('/').next()?;
if ecosystem.is_empty() {
+5 -16
View File
@@ -110,12 +110,8 @@ pub async fn upsert_reported(db: &Database, alert: &CveAlert) -> Result<(), Agen
let filter = doc! { "cve_id": &alert.cve_id, "repo_id": &alert.repo_id };
// The alert as found now; a VEX statement on it is left as it is (the
// alert carries none), and it is reported again.
let mut found = mongodb::bson::to_document(alert)
let found = mongodb::bson::to_document(alert)
.map_err(|e| AgentError::Other(format!("encode CVE alert: {e}")))?;
// When it was first found is written once (#1041): every scan builds its
// alerts anew, and a rescan must neither list it as new again nor move
// it later in the CVE history.
let first_found = found.remove("created_at");
// A purl is written when the scan knows one and otherwise kept (an alert
// stored before purls were recorded gets one on its next scan); kept only
// while it is the purl of the same package and version.
@@ -132,18 +128,11 @@ pub async fn upsert_reported(db: &Database, alert: &CveAlert) -> Result<(), Agen
.update_one(other_component, doc! { "$unset": { "purl": "" } })
.await?;
}
// A supplier's statement (#1025) is restated by every scan; one the
// supplier no longer makes goes.
let mut unset = doc! { "resolved_at": "" };
if alert.supplier_vex.is_none() {
unset.insert("supplier_vex", "");
}
let mut update = doc! { "$set": found, "$unset": unset };
if let Some(first_found) = first_found {
update.insert("$setOnInsert", doc! { "created_at": first_found });
}
db.cve_alerts()
.update_one(filter.clone(), update)
.update_one(
filter.clone(),
doc! { "$set": found, "$unset": { "resolved_at": "" } },
)
.upsert(true)
.await?;
// The first scan that finds it actively exploited starts the CRA's
-200
View File
@@ -39,69 +39,6 @@ const TOKEN_MARGIN: Duration = Duration::from_secs(30);
/// client's 30 s.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
/// One of the tenant's active connections to another workspace (#1028,
/// tenant-registry#138), as a product reads it. The peer's tenant id is for
/// delivering to it inside the product; it is never shown to anyone.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct Connection {
/// The connection's id.
pub id: String,
/// The other workspace's tenant id.
pub peer_tenant_id: String,
/// The other workspace's display name: all either side sees of the other.
pub peer_name: String,
}
/// One connection as the registry checks it
/// (`GET /v1/internal/connections/{id}`).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct ConnectionState {
/// Whether it is active: accepted and not ended.
pub active: bool,
/// The two tenants it joins.
pub tenant_ids: Vec<String>,
}
impl ConnectionState {
/// The tenant on the other side from `tenant`, while the connection is
/// active and `tenant` is one of its two sides; `None` otherwise. What a
/// delivery asks right before it writes to another tenant's database.
pub fn peer_of(&self, tenant: &str) -> Option<&str> {
let [a, b] = self.tenant_ids.as_slice() else {
return None;
};
match (self.active, a == b) {
(false, _) | (_, true) => None,
_ if a == tenant => Some(b),
_ if b == tenant => Some(a),
_ => None,
}
}
}
/// A document of the tenant's store (Dokumentenablage), as the registry
/// lists it (`GET /v1/tenants/{id}/store`).
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct StoreDocument {
pub id: String,
pub title: String,
#[serde(default)]
pub filename: String,
#[serde(default)]
pub content_type: Option<String>,
#[serde(default)]
pub size_bytes: Option<u64>,
/// `legal_web`, `product_public` or `internal`; none for BreakPilot's
/// deliveries.
#[serde(default)]
pub area: Option<String>,
/// The product projects it belongs to.
#[serde(default)]
pub project_ids: Vec<String>,
#[serde(default)]
pub created_at: Option<chrono::DateTime<chrono::Utc>>,
}
/// The registry's `reason` for a member blocked in the tenant.
pub const MEMBER_BLOCKED: &str = "member_blocked";
@@ -594,107 +531,6 @@ impl RegistryClient {
Ok(page.items)
}
/// The tenant's document store (Dokumentenablage): its published
/// documents, by area. Not cached: it is read when a product's box is
/// opened on the Lieferkette (#1054).
///
/// # Errors
///
/// The registry could not be asked, or answered with an error.
pub async fn list_store(&self, tenant_id: &str) -> Result<Vec<StoreDocument>, String> {
#[derive(Deserialize)]
struct Page {
#[serde(default)]
items: Vec<StoreDocument>,
}
let resp = self
.request(
reqwest::Method::GET,
&format!("/v1/tenants/{}/store", urlencoding::encode(tenant_id)),
)
.await?
.send()
.await
.map_err(|e| format!("store list failed: {e}"))?;
if !resp.status().is_success() {
return Err(format!("store list returned {}", resp.status()));
}
let page: Page = resp
.json()
.await
.map_err(|e| format!("store list invalid: {e}"))?;
Ok(page.items)
}
/// The tenant's active connections to other workspaces (#1028). Not
/// cached: a connection ended a second ago must not be offered.
///
/// # Errors
///
/// The registry could not be asked, or answered with an error other than
/// 404.
pub async fn active_connections(&self, tenant_id: &str) -> Result<Vec<Connection>, String> {
#[derive(Deserialize)]
struct Page {
#[serde(default)]
items: Vec<Connection>,
}
let resp = self
.request(
reqwest::Method::GET,
&format!(
"/v1/internal/tenants/{}/connections?state=active",
urlencoding::encode(tenant_id)
),
)
.await?
.send()
.await
.map_err(|e| format!("connection list failed: {e}"))?;
// A registry without connections for the tenant (or, before
// tenant-registry#138, without the route) has none to list.
if resp.status() == reqwest::StatusCode::NOT_FOUND {
return Ok(Vec::new());
}
if !resp.status().is_success() {
return Err(format!("connection list returned {}", resp.status()));
}
let page: Page = resp
.json()
.await
.map_err(|e| format!("connection list invalid: {e}"))?;
Ok(page.items)
}
/// Connection `id` as the registry knows it now; `None` when it knows no
/// such connection. Asked right before every delivery over it.
///
/// # Errors
///
/// The registry could not be asked, or answered with an error other than
/// 404.
pub async fn connection(&self, id: &str) -> Result<Option<ConnectionState>, String> {
let resp = self
.request(
reqwest::Method::GET,
&format!("/v1/internal/connections/{}", urlencoding::encode(id)),
)
.await?
.send()
.await
.map_err(|e| format!("connection check failed: {e}"))?;
if resp.status() == reqwest::StatusCode::NOT_FOUND {
return Ok(None);
}
if !resp.status().is_success() {
return Err(format!("connection check returned {}", resp.status()));
}
resp.json()
.await
.map(Some)
.map_err(|e| format!("connection check invalid: {e}"))
}
/// Verify a portal-issued API key (`bp_…`), valid or not, reusing a
/// verdict younger than [`API_KEY_TTL`].
///
@@ -822,42 +658,6 @@ pub fn scheduler_runs_for(status: &str) -> bool {
mod tests {
use super::*;
#[test]
fn a_connection_names_the_other_side_only_while_active_and_ours() {
let joined = |active: bool, ids: &[&str]| ConnectionState {
active,
tenant_ids: ids.iter().map(|t| t.to_string()).collect(),
};
let c = joined(true, &["supplier", "customer"]);
assert_eq!(c.peer_of("supplier"), Some("customer"));
assert_eq!(c.peer_of("customer"), Some("supplier"));
assert_eq!(
c.peer_of("someone else"),
None,
"a third tenant gets nothing"
);
assert_eq!(
joined(false, &["supplier", "customer"]).peer_of("supplier"),
None,
"ended"
);
assert_eq!(
joined(true, &["supplier", "supplier"]).peer_of("supplier"),
None,
"itself"
);
assert_eq!(
joined(true, &["supplier"]).peer_of("supplier"),
None,
"one side"
);
assert_eq!(
joined(true, &["a", "b", "c"]).peer_of("a"),
None,
"three sides"
);
}
#[test]
fn the_plan_sets_how_many_targets_are_included() {
let check = |limits: serde_json::Value| -> EntitlementCheck {
-10
View File
@@ -86,7 +86,6 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
Box::pin(async move {
crate::pipeline::csaf_feed::refresh_index(&agent.db_pool.admin_db(), agent.net_guard)
.await;
refresh_supplier_advisories(&agent).await;
})
})
.map_err(|e| AgentError::Scheduler(format!("Failed to create CSAF job: {e}")))?;
@@ -102,7 +101,6 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
startup_agent.net_guard,
)
.await;
refresh_supplier_advisories(&startup_agent).await;
});
// Managed git sync (#439): the organisation's repositories against the
@@ -193,14 +191,6 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
///
/// We never panic out of this function — the scheduler must keep
/// firing even if the registry is offline.
/// Each tenant's supplier CSAF advisories (#1025), one tenant after the
/// other, after the shared index.
async fn refresh_supplier_advisories(agent: &ComplianceAgent) {
for tenant_id in scheduler_tenants(agent).await {
crate::pipeline::csaf_feed::refresh_supplier_advisories(agent, &tenant_id).await;
}
}
pub(crate) async fn scheduler_tenants(agent: &ComplianceAgent) -> Vec<String> {
if let Some(registry) = agent.registry.as_ref() {
match registry.list_tenants().await {
-2
View File
@@ -111,7 +111,6 @@ pub fn uploaded_artifact(
ArtifactKind::SourceArchive => Artifact::source_archive(filename),
ArtifactKind::MobilePackage => Artifact::mobile_package(filename),
ArtifactKind::BuildOutput => Artifact::build_output(filename),
ArtifactKind::SupplierSbom => Artifact::supplier_sbom(filename),
_ => return None,
};
artifact.stored_path = Some(stored_path.to_string_lossy().to_string());
@@ -143,7 +142,6 @@ pub fn reference_artifact(
}
ArtifactKind::PlaintextDescription => Artifact::plaintext(source_ref),
ArtifactKind::BuildOutput => Artifact::build_output(source_ref),
ArtifactKind::SupplierSbom => Artifact::supplier_sbom(source_ref),
}
}
-10
View File
@@ -147,16 +147,6 @@ impl TestServer {
.expect("PATCH request failed")
}
/// PUT helper with JSON body
pub async fn put(&self, path: &str, body: &serde_json::Value) -> reqwest::Response {
self.client
.put(format!("{}{path}", self.base_url))
.json(body)
.send()
.await
.expect("PUT request failed")
}
/// DELETE helper
pub async fn delete(&self, path: &str) -> reqwest::Response {
self.client
-990
View File
@@ -1,990 +0,0 @@
//! 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();
}
@@ -205,31 +205,6 @@ async fn delete_repo_cascades_sast_findings_and_sbom() {
.await
.unwrap();
// Supplier invites and their uploads (#1027): the target's go, another
// target's stay.
for target in [repo_id.as_str(), "another-target"] {
db.collection::<mongodb::bson::Document>("supplier_invites")
.insert_one(mongodb::bson::doc! {
"target_id": target,
"email": "sbom@supplier.example",
"invited_by": "user-1",
"created_at": now,
"expires_at": now,
})
.await
.unwrap();
db.collection::<mongodb::bson::Document>("supplier_uploads")
.insert_one(mongodb::bson::doc! {
"invite_id": "invite-1",
"target_id": target,
"uploaded_at": now,
"filename": "sbom.cdx.json",
"accepted": true,
})
.await
.unwrap();
}
assert_eq!(count_docs(&server, "findings").await, 1);
assert_eq!(count_docs(&server, "sbom_entries").await, 1);
@@ -239,8 +214,6 @@ async fn delete_repo_cascades_sast_findings_and_sbom() {
// Both should be gone
assert_eq!(count_docs(&server, "findings").await, 0);
assert_eq!(count_docs(&server, "sbom_entries").await, 0);
assert_eq!(count_docs(&server, "supplier_invites").await, 1);
assert_eq!(count_docs(&server, "supplier_uploads").await, 1);
server.cleanup().await;
}
@@ -1,281 +0,0 @@
use crate::common::TestServer;
use compliance_core::models::SbomEntry;
use serde_json::json;
/// Create a target named `name`, with `supplier` when it is bought in, and
/// return its id.
async fn target(server: &TestServer, name: &str, supplier: Option<serde_json::Value>) -> String {
let resp = server
.post(
"/api/v1/targets",
&json!({ "name": name, "target_type": "firmware_rtos", "supplier": supplier }),
)
.await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
body["data"]["_id"]["$oid"].as_str().unwrap().to_string()
}
/// An SBOM entry of target `target`.
fn entry(target: &str, name: &str, manager: &str, purl: Option<&str>) -> SbomEntry {
let mut e = SbomEntry::new(target.into(), name.into(), "1.0".into(), manager.into());
e.purl = purl.map(String::from);
e
}
#[tokio::test]
async fn a_machines_sbom_lists_its_parts_with_their_suppliers_and_components() {
let server = TestServer::start().await;
let controller = target(&server, "Steuerung", None).await;
let drive = target(
&server,
"Antrieb",
Some(json!({ "name": "Example Drives GmbH", "product": "Drive Control", "version": "4.2.1" })),
)
.await;
let retired = target(&server, "Alte Steuerung", None).await;
let elsewhere = target(&server, "Andere Maschine", None).await;
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(&server.tenant_db_name());
// Projects are registry-owned, so assign the targets directly.
let targets = db.collection::<mongodb::bson::Document>("onboarded_targets");
for id in [&controller, &drive, &retired] {
let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap();
let mut set = mongodb::bson::doc! { "project_ids": ["m1"] };
if id == &retired {
set.insert("archived_at", mongodb::bson::DateTime::now());
}
targets
.update_one(
mongodb::bson::doc! { "_id": oid },
mongodb::bson::doc! { "$set": set },
)
.await
.unwrap();
}
db.collection::<SbomEntry>("sbom_entries")
.insert_many([
entry(&controller, "lodash", "npm", Some("pkg:npm/lodash@1.0")),
entry(&drive, "lodash", "npm", Some("pkg:npm/lodash@1.0")),
entry(&drive, "vendor-blob", "supplier", None),
// The bought-in product itself, as a scan stores it.
entry(&drive, "Drive Control", "supplier-product", None),
entry(
&retired,
"openssl",
"generic",
Some("pkg:generic/openssl@1.0"),
),
entry(&elsewhere, "zlib", "generic", Some("pkg:generic/zlib@1.0")),
])
.await
.unwrap();
let resp = server.get("/api/v1/projects/m1/sbom").await;
assert_eq!(resp.status(), 200);
let doc: serde_json::Value = resp.json().await.unwrap();
assert_eq!(doc["metadata"]["component"]["type"], "device");
let components = doc["components"].as_array().unwrap();
let names: Vec<&str> = components
.iter()
.map(|c| c["name"].as_str().unwrap())
.collect();
// The parts by name, then their components once each; nothing of the
// archived target or another machine, and the product is the part.
assert_eq!(names, ["Antrieb", "Steuerung", "lodash", "vendor-blob"]);
assert_eq!(components[0]["supplier"]["name"], "Example Drives GmbH");
assert_eq!(components[0]["version"], "4.2.1");
// The dev tenant's workspace makes the controller.
assert_eq!(components[1]["supplier"]["name"], "dev");
server.cleanup().await;
}
#[tokio::test]
async fn a_machine_without_parts_has_no_sbom() {
let server = TestServer::start().await;
let resp = server.get("/api/v1/projects/empty/sbom").await;
assert_eq!(resp.status(), 422);
server.cleanup().await;
}
/// A CVE alert of target `target` on `package`, as a scan stores it.
fn alert(target: &str, cve: &str, package: &str, severity: &str) -> serde_json::Value {
json!({
"cve_id": cve, "repo_id": target, "affected_package": package,
"affected_version": "1.0", "source": "osv", "severity": severity,
"cvss_score": null, "summary": null, "llm_impact_summary": null,
"references": [], "created_at": "2026-11-16T08:00:00Z",
})
}
#[tokio::test]
async fn a_machine_shows_its_parts_and_their_open_cves_together() {
let server = TestServer::start().await;
let provider = "https://drives.invalid/.well-known/csaf/provider-metadata.json";
let controller = target(&server, "Steuerung", None).await;
let drive = target(
&server,
"Antrieb",
Some(
json!({ "name": "Example Drives GmbH", "product": "Drive Control",
"version": "4.2.1", "csaf_provider": provider }),
),
)
.await;
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(&server.tenant_db_name());
let targets = db.collection::<mongodb::bson::Document>("onboarded_targets");
for id in [&controller, &drive] {
let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap();
targets
.update_one(
mongodb::bson::doc! { "_id": oid },
mongodb::bson::doc! { "$set": { "project_ids": ["m1"] } },
)
.await
.unwrap();
}
db.collection::<SbomEntry>("sbom_entries")
.insert_many([
entry(&controller, "lodash", "npm", Some("pkg:npm/lodash@1.0")),
entry(&drive, "lodash", "npm", Some("pkg:npm/lodash@1.0")),
entry(&drive, "vendor-blob", "supplier", None),
entry(&drive, "Drive Control", "supplier-product", None),
])
.await
.unwrap();
let mut on_product = alert(&drive, "CVE-2026-90001", "Drive Control", "critical");
on_product["supplier_vex"] =
json!({ "status": "affected", "state": "exploitable", "source": "drive.cdx.json" });
let mut decided = alert(&drive, "CVE-2021-23337", "lodash", "high");
decided["vex"] = json!({ "status": "not_affected", "impact_statement": "Never called.",
"by": "ada", "at": "2026-11-16T09:00:00Z" });
let mut gone = alert(&controller, "CVE-2020-0001", "zlib", "medium");
gone["resolved_at"] = json!("2026-11-16T10:00:00Z");
let alerts: Vec<compliance_core::models::CveAlert> = [
alert(&controller, "CVE-2021-23337", "lodash", "high"),
decided,
on_product,
gone,
]
.into_iter()
.map(|a| serde_json::from_value(a).unwrap())
.collect();
db.collection::<compliance_core::models::CveAlert>("cve_alerts")
.insert_many(alerts)
.await
.unwrap();
let key = format!("supplier:{provider}");
db.collection::<mongodb::bson::Document>("supplier_csaf_advisories")
.insert_many([
mongodb::bson::doc! { "_id": format!("{key}:A-1"), "provider": &key },
mongodb::bson::doc! { "_id": format!("{key}:A-2"), "provider": &key },
])
.await
.unwrap();
let resp = server.get("/api/v1/projects/m1/overview").await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
let data = &body["data"];
assert_eq!(data["name"], "m1");
let parts = data["parts"].as_array().unwrap();
assert_eq!(parts[0]["name"], "Antrieb");
assert_eq!(parts[0]["supplier"]["name"], "Example Drives GmbH");
assert_eq!(parts[0]["open"]["critical"], 1);
assert_eq!(parts[0]["open"]["high"], 0, "the stated one is settled");
assert_eq!(parts[1]["name"], "Steuerung");
assert!(parts[1].get("supplier").is_none());
assert_eq!(parts[1]["open"]["high"], 1);
assert_eq!(data["open"]["critical"], 1);
assert_eq!(data["open"]["high"], 1);
assert_eq!(data["open"]["medium"], 0, "a gone one is not open");
assert_eq!(data["undecided"], 2);
assert_eq!(data["undecided_with_supplier"], 1);
assert_eq!(data["components"], 2);
assert_eq!(data["shared_components"], 1);
assert_eq!(data["advisories"]["advisories"], 2);
assert_eq!(data["advisories"]["providers"], 1);
let resp = server.get("/api/v1/projects/m1/cves").await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
let groups = body["data"]["groups"].as_array().unwrap();
assert_eq!(groups.len(), 2);
assert_eq!(
groups[0]["package"], "Drive Control",
"the most severe first"
);
let alerts = body["data"]["alerts"].as_array().unwrap();
let parts_of = |cve: &str| -> Vec<&str> {
alerts
.iter()
.filter(|a| a["cve_id"] == cve)
.map(|a| a["repo_id"].as_str().unwrap())
.collect()
};
assert_eq!(parts_of("CVE-2021-23337"), [controller.as_str()]);
assert_eq!(parts_of("CVE-2026-90001"), [drive.as_str()]);
server.cleanup().await;
}
#[tokio::test]
async fn a_machines_history_is_its_parts_scans_newest_first() {
use compliance_core::models::{ScanRun, ScanRunStatus, ScanTrigger};
let server = TestServer::start().await;
let controller = target(&server, "Steuerung", None).await;
let drive = target(&server, "Antrieb", None).await;
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(&server.tenant_db_name());
let targets = db.collection::<mongodb::bson::Document>("onboarded_targets");
for id in [&controller, &drive] {
let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap();
targets
.update_one(
mongodb::bson::doc! { "_id": oid },
mongodb::bson::doc! { "$set": { "project_ids": ["m1"] } },
)
.await
.unwrap();
}
let run = |target: &str, hours_ago: i64| {
let mut run = ScanRun::new(target.into(), ScanTrigger::Manual);
run.started_at = chrono::Utc::now() - chrono::Duration::hours(hours_ago);
run.completed_at = Some(run.started_at + chrono::Duration::minutes(5));
run.status = ScanRunStatus::Completed;
run
};
db.collection::<ScanRun>("scan_runs")
.insert_many([run(&controller, 30), run(&drive, 20), run(&controller, 10)])
.await
.unwrap();
let resp = server.get("/api/v1/projects/m1/scan-changes?limit=2").await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
let parts: Vec<&str> = body["data"]
.as_array()
.unwrap()
.iter()
.map(|c| c["part"].as_str().unwrap())
.collect();
// The newest two over both parts.
assert_eq!(parts, [controller.as_str(), drive.as_str()]);
assert_eq!(body["data"][1]["baseline"], true, "the drive's first scan");
server.cleanup().await;
}
@@ -2,10 +2,7 @@ mod cascade_delete;
mod dast;
mod findings;
mod health;
mod machine;
mod onboarding;
mod openapi;
mod releases;
mod sbom;
mod stats;
mod supply_chain;
@@ -287,322 +287,3 @@ async fn the_list_pages_with_a_total_after_the_project_filter() {
server.cleanup().await;
}
/// Upload `bytes` as a supplier SBOM (#1025) named `name` to target `id`.
async fn upload_supplier_sbom(
server: &TestServer,
id: &str,
name: &str,
bytes: &[u8],
) -> reqwest::Response {
let form = reqwest::multipart::Form::new()
.text("kind", "supplier_sbom")
.part(
"file",
reqwest::multipart::Part::bytes(bytes.to_vec()).file_name(name.to_string()),
);
server
.client
.post(format!(
"{}/api/v1/targets/{id}/artifacts/upload",
server.base_url
))
.multipart(form)
.send()
.await
.unwrap()
}
#[tokio::test]
async fn a_supplier_sbom_is_kept_and_brings_its_scans() {
let server = TestServer::start().await;
let id = firmware_target(&server, "bought-in-pump").await;
let sbom = br#"{"bomFormat": "CycloneDX", "specVersion": "1.5", "components": [
{"type": "library", "name": "lodash", "version": "4.17.20", "purl": "pkg:npm/lodash@4.17.20"}
]}"#;
let resp = upload_supplier_sbom(&server, &id, "pump.cdx.json", sbom).await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
let artifacts = body["data"]["artifacts"].as_array().unwrap();
assert_eq!(artifacts.len(), 1);
assert_eq!(artifacts[0]["kind"], "supplier_sbom");
assert!(!artifacts[0]["ingested_at"].is_null(), "{body}");
// What the editor shows of it is kept with it.
let fact = |key: &str| {
artifacts[0]["detected"]
.as_array()
.unwrap()
.iter()
.find(|f| f["key"] == key)
.map(|f| f["value"].clone())
};
assert_eq!(fact("sbom_format"), Some(json!("CycloneDX 1.5")));
assert_eq!(fact("sbom_components"), Some(json!("1")));
assert_eq!(fact("sbom_statements"), Some(json!("0")));
assert_eq!(stored_uploads(&id).len(), 1);
// Its SBOM and CVE scans run, though the target has no code.
let resp = server
.get(&format!("/api/v1/targets/{id}/applicable-scans"))
.await;
let body: serde_json::Value = resp.json().await.unwrap();
let runs =
|scan: &str| {
body["data"]["scans"].as_array().unwrap().iter().any(|s| {
s["scan"] == scan && s["default_on"] == true && s["blocked_reason"].is_null()
})
};
assert!(runs("sbom") && runs("cve"), "{body}");
// Each once: not also as blocked by the rules that need code (#1043).
let listed = |scan: &str| {
body["data"]["scans"]
.as_array()
.unwrap()
.iter()
.filter(|s| s["scan"] == scan)
.count()
};
assert_eq!((listed("sbom"), listed("cve")), (1, 1), "{body}");
server.cleanup().await;
}
/// Files that are no supplier SBOM a scan can read: (name, bytes, part of
/// the reason, its code).
fn unreadable_sboms() -> [(&'static str, &'static [u8], &'static str, &'static str); 2] {
[
(
"valve.csv",
b"name,version\nzlib,1.2.11",
"not a CycloneDX",
"unknown_format",
),
(
"valve.cdx.json",
br#"{"bomFormat": "CycloneDX", "specVersion": "1.5"}"#,
"lists no components",
"empty",
),
]
}
/// Check `bytes` as a supplier SBOM, before any target holds it.
async fn check_supplier_sbom(server: &TestServer, bytes: &[u8]) -> reqwest::Response {
let form = reqwest::multipart::Form::new().part(
"file",
reqwest::multipart::Part::bytes(bytes.to_vec()).file_name("x.json"),
);
server
.client
.post(format!("{}/api/v1/supplier-sboms/check", server.base_url))
.multipart(form)
.send()
.await
.unwrap()
}
#[tokio::test]
async fn a_supplier_sbom_is_checked_before_a_target_holds_it() {
let server = TestServer::start().await;
let sbom = br#"{"bomFormat": "CycloneDX", "specVersion": "1.6",
"components": [
{"type": "library", "name": "lodash", "version": "4.17.20", "bom-ref": "l",
"purl": "pkg:npm/lodash@4.17.20"},
{"type": "library", "name": "zlib", "version": "1.2.11"}
],
"vulnerabilities": [{"id": "CVE-2021-23337", "affects": [{"ref": "l"}],
"analysis": {"state": "not_affected", "justification": "code_not_reachable"}}]
}"#;
let resp = check_supplier_sbom(&server, sbom).await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
assert_eq!(
body["data"],
json!({ "format": "CycloneDX 1.6", "components": 2, "statements": 1 })
);
for (name, bytes, _, code) in unreadable_sboms() {
let resp = check_supplier_sbom(&server, bytes).await;
assert_eq!(resp.status(), 422, "{name}");
let body: serde_json::Value = resp.json().await.unwrap();
assert_eq!(body["code"], code, "{name}");
}
// Larger than the 2 MiB of a JSON route, within the SBOM's 20 MiB.
let padded = [
&br#"{"bomFormat": "CycloneDX", "specVersion": "1.5", "x": ""#[..],
&vec![b'a'; 3 * 1024 * 1024],
br#"", "components": [{"type": "library", "name": "zlib", "version": "1.2.11"}]}"#,
]
.concat();
let resp = check_supplier_sbom(&server, &padded).await;
assert_eq!(resp.status(), 200);
server.cleanup().await;
}
#[tokio::test]
async fn a_supplier_sbom_that_cannot_be_read_is_refused_with_the_reason() {
let server = TestServer::start().await;
let id = firmware_target(&server, "bought-in-valve").await;
for (name, bytes, reason, code) in unreadable_sboms() {
let resp = upload_supplier_sbom(&server, &id, name, bytes).await;
assert_eq!(resp.status(), 422, "{name}");
let body: serde_json::Value = resp.json().await.unwrap();
assert!(
body["error"].as_str().is_some_and(|e| e.contains(reason)),
"{name}: {body}"
);
assert_eq!(body["code"], code, "{name}");
}
assert!(
stored_uploads(&id).is_empty(),
"a refused SBOM must be deleted"
);
let resp = server.get(&format!("/api/v1/targets/{id}")).await;
let body: serde_json::Value = resp.json().await.unwrap();
assert!(body["data"]["artifacts"].as_array().unwrap().is_empty());
server.cleanup().await;
}
#[tokio::test]
async fn a_new_supplier_sbom_replaces_the_one_before_it() {
let server = TestServer::start().await;
let id = firmware_target(&server, "bought-in-drive").await;
let version = |v: &str| {
format!(
r#"{{"bomFormat": "CycloneDX", "specVersion": "1.5", "components": [
{{"type": "library", "name": "zlib", "version": "{v}", "purl": "pkg:generic/zlib@{v}"}}
]}}"#
)
};
for (name, v) in [
("drive-1.cdx.json", "1.2.11"),
("drive-2.cdx.json", "1.3.1"),
] {
let resp = upload_supplier_sbom(&server, &id, name, version(v).as_bytes()).await;
assert_eq!(resp.status(), 200, "{name}");
}
let resp = server.get(&format!("/api/v1/targets/{id}")).await;
let body: serde_json::Value = resp.json().await.unwrap();
let artifacts = body["data"]["artifacts"].as_array().unwrap();
assert_eq!(artifacts.len(), 1, "{body}");
assert_eq!(artifacts[0]["source_ref"], "drive-2.cdx.json");
let files = stored_uploads(&id);
assert_eq!(files.len(), 1, "the replaced file must be gone: {files:?}");
assert!(std::fs::read_to_string(&files[0])
.unwrap()
.contains("1.3.1"));
server.cleanup().await;
}
#[tokio::test]
async fn a_targets_supplier_advisories_are_counted_with_their_last_read() {
let server = TestServer::start().await;
let id = firmware_target(&server, "bought-in-motor").await;
let path = format!("/api/v1/targets/{id}/supplier-advisories");
let advisories = || async {
let resp = server.get(&path).await;
assert_eq!(resp.status(), 200);
resp.json::<serde_json::Value>().await.unwrap()["data"].clone()
};
// Without a provider there is nothing to count.
assert!(advisories().await.is_null());
// `.invalid` never resolves: the background refresh reaches no network.
let url = "https://motor.invalid/.well-known/csaf/provider-metadata.json";
let resp = server
.patch(
&format!("/api/v1/targets/{id}"),
&json!({ "supplier": { "name": "Example GmbH", "csaf_provider": url } }),
)
.await;
assert_eq!(resp.status(), 200);
assert_eq!(advisories().await["advisories"], 0);
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db = mongodb::Client::with_uri_str(&uri)
.await
.unwrap()
.database(&server.tenant_db_name());
let key = format!("supplier:{url}");
db.collection::<mongodb::bson::Document>("supplier_csaf_advisories")
.insert_one(mongodb::bson::doc! { "_id": format!("{key}:SA-1"), "provider": &key })
.await
.unwrap();
// As the refresh keeps it: a provider that could not be read.
db.collection::<mongodb::bson::Document>("supplier_csaf_providers")
.replace_one(
mongodb::bson::doc! { "_id": &key },
mongodb::bson::doc! {
"_id": &key,
"checked_at": mongodb::bson::DateTime::now(),
"reachable": false,
},
)
.upsert(true)
.await
.unwrap();
let data = advisories().await;
assert_eq!(data["advisories"], 1, "{data}");
assert_eq!(data["reachable"], false, "{data}");
assert!(data["checked_at"].is_string(), "{data}");
server.cleanup().await;
}
#[tokio::test]
async fn a_targets_supplier_is_set_checked_and_removed() {
let server = TestServer::start().await;
let id = firmware_target(&server, "bought-in-gearbox").await;
let path = format!("/api/v1/targets/{id}");
// `.invalid` never resolves: the refresh started in the background
// reaches no network.
let url = "https://supplier.invalid/.well-known/csaf/provider-metadata.json";
let resp = server
.patch(
&path,
&json!({ "supplier": {
"name": " Example GmbH ", "product": "Gearbox Control", "version": "2.1",
"csaf_provider": url
} }),
)
.await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
assert_eq!(
body["data"]["supplier"],
json!({ "name": "Example GmbH", "product": "Gearbox Control", "version": "2.1",
"csaf_provider": url })
);
// A provider that is not an https URL is refused, and nothing changes.
let resp = server
.patch(
&path,
&json!({ "supplier": { "name": "Example GmbH",
"csaf_provider": "http://supplier.invalid/x.json" } }),
)
.await;
assert_eq!(resp.status(), 422);
let body: serde_json::Value = server.get(&path).await.json().await.unwrap();
assert_eq!(body["data"]["supplier"]["csaf_provider"], url);
// An empty name removes the supplier.
let resp = server
.patch(&path, &json!({ "supplier": { "name": "" } }))
.await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
assert!(body["data"].get("supplier").is_none(), "{body}");
server.cleanup().await;
}
@@ -1,143 +0,0 @@
use crate::common::TestServer;
use compliance_core::models::{SbomEntry, VulnRef};
use serde_json::json;
/// A target's id, created through the API.
async fn target(server: &TestServer, name: &str) -> String {
let resp = server
.post(
"/api/v1/targets",
&json!({ "name": name, "target_type": "firmware_rtos" }),
)
.await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
body["data"]["_id"]["$oid"].as_str().unwrap().to_string()
}
#[tokio::test]
async fn a_supplier_publishes_versions_of_a_stripped_sbom() {
let server = TestServer::start().await;
let id = target(&server, "DR-4 Firmware").await;
let publish = |label: &str| {
let (server, id, label) = (&server, id.clone(), label.to_string());
async move {
server
.post(
&format!("/api/v1/targets/{id}/versions"),
&json!({ "label": label }),
)
.await
}
};
// Nothing to publish before a scan found components.
let resp = publish("1.4.0").await;
assert_eq!(resp.status(), 422);
assert_eq!(
resp.json::<serde_json::Value>().await.unwrap()["error"],
"empty"
);
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(&server.tenant_db_name());
let mut lwip = SbomEntry::new(id.clone(), "lwip".into(), "2.1.2".into(), "generic".into());
lwip.purl = Some("pkg:generic/lwip@2.1.2".into());
lwip.known_vulnerabilities = vec![VulnRef {
id: "CVE-2026-0001".into(),
source: "osv".into(),
severity: Some("HIGH".into()),
url: None,
exploitation: None,
aliases: Vec::new(),
}];
let mbedtls = SbomEntry::new(
id.clone(),
"mbedtls".into(),
"3.6.2".into(),
"generic".into(),
);
db.collection::<SbomEntry>("sbom_entries")
.insert_many([lwip, mbedtls])
.await
.unwrap();
let resp = publish(" 1.4.0 ").await;
assert_eq!(resp.status(), 201);
let body: serde_json::Value = resp.json().await.unwrap();
assert_eq!(body["data"]["label"], "1.4.0");
assert_eq!(body["data"]["components"], 2);
let resp = publish("1.4.0").await;
assert_eq!(resp.status(), 409);
assert_eq!(
resp.json::<serde_json::Value>().await.unwrap()["error"],
"label_taken"
);
assert_eq!(publish(" ").await.status(), 422);
// The stored document is the stripped one.
let stored = db
.collection::<mongodb::bson::Document>("sbom_versions")
.find_one(mongodb::bson::doc! { "label": "1.4.0" })
.await
.unwrap()
.unwrap();
let text = std::fs::read_to_string(stored.get_str("stored_path").unwrap()).unwrap();
let doc: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(doc["metadata"]["component"]["name"], "DR-4 Firmware");
assert_eq!(doc["metadata"]["component"]["version"], "1.4.0");
assert!(doc["metadata"]["component"]["supplier"]["name"].is_string());
assert!(doc.get("vulnerabilities").is_none());
assert!(!text.contains("CVE-2026-0001"), "no vulnerability crosses");
// A preview stores nothing.
let resp = server
.get(&format!(
"/api/v1/targets/{id}/versions/preview?label=1.5.0"
))
.await;
assert_eq!(resp.status(), 200);
let preview: serde_json::Value = resp.json().await.unwrap();
assert_eq!(preview["metadata"]["component"]["version"], "1.5.0");
assert_eq!(preview["components"].as_array().unwrap().len(), 2);
let body: serde_json::Value = server
.get(&format!("/api/v1/targets/{id}/releases"))
.await
.json()
.await
.unwrap();
let labels: Vec<&str> = body["data"]["versions"]
.as_array()
.unwrap()
.iter()
.map(|v| v["label"].as_str().unwrap())
.collect();
assert_eq!(labels, ["1.4.0"], "the preview was not published");
assert_eq!(body["data"]["releases"], json!([]));
// Without a registry there is no connection to release over.
let resp = server
.post(
&format!("/api/v1/targets/{id}/releases"),
&json!({ "connection_id": "c-1" }),
)
.await;
assert_eq!(resp.status(), 422);
assert_eq!(
resp.json::<serde_json::Value>().await.unwrap()["error"],
"unknown_connection"
);
assert_eq!(
server
.get("/api/v1/targets/nonsense/releases")
.await
.status(),
404
);
server.cleanup().await;
}
@@ -1,167 +0,0 @@
use crate::common::TestServer;
use serde_json::json;
/// Create a target named `name`, with `supplier` when it is bought in, and
/// return its id.
async fn target(server: &TestServer, name: &str, supplier: Option<serde_json::Value>) -> String {
let resp = server
.post(
"/api/v1/targets",
&json!({ "name": name, "target_type": "firmware_rtos", "supplier": supplier }),
)
.await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
body["data"]["_id"]["$oid"].as_str().unwrap().to_string()
}
fn alert(target: &str, cve: &str, severity: &str) -> compliance_core::models::CveAlert {
serde_json::from_value(json!({
"cve_id": cve, "repo_id": target, "affected_package": "lodash",
"affected_version": "1.0", "source": "osv", "severity": severity,
"cvss_score": null, "summary": null, "llm_impact_summary": null,
"references": [], "created_at": "2026-11-16T08:00:00Z",
}))
.unwrap()
}
#[tokio::test]
async fn the_supply_chain_links_suppliers_components_and_products() {
let server = TestServer::start().await;
let drive = target(
&server,
"Antrieb",
Some(json!({ "name": "Example Drives GmbH", "version": "4.2.1" })),
)
.await;
let plc = target(&server, "Steuerung", None).await;
let retired = target(&server, "Alte Steuerung", None).await;
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let db = client.database(&server.tenant_db_name());
// Projects are registry-owned; without a registry they are named by id.
let targets = db.collection::<mongodb::bson::Document>("onboarded_targets");
for (id, projects) in [
(&drive, vec!["m1"]),
(&plc, vec!["m1", "m2"]),
(&retired, vec!["m2"]),
] {
let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap();
let mut set = mongodb::bson::doc! { "project_ids": projects };
if id == &retired {
set.insert("archived_at", mongodb::bson::DateTime::now());
}
targets
.update_one(
mongodb::bson::doc! { "_id": oid },
mongodb::bson::doc! { "$set": set },
)
.await
.unwrap();
}
db.collection::<compliance_core::models::CveAlert>("cve_alerts")
.insert_many([
alert(&drive, "CVE-2026-90001", "critical"),
alert(&plc, "CVE-2021-23337", "high"),
])
.await
.unwrap();
let resp = server.get("/api/v1/supply-chain").await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
let nodes = body["data"]["nodes"].as_array().unwrap();
let edges = body["data"]["edges"].as_array().unwrap();
let keys: Vec<&str> = nodes.iter().map(|n| n["key"].as_str().unwrap()).collect();
assert_eq!(
keys,
[
"supplier:Example Drives GmbH".to_string(),
format!("target:{drive}"),
format!("target:{plc}"),
"project:m1".to_string(),
"project:m2".to_string(),
],
"the archived target is left out"
);
let node = |key: &str| nodes.iter().find(|n| n["key"] == key).unwrap();
assert_eq!(node(&format!("target:{drive}"))["bought"], true);
assert_eq!(node(&format!("target:{drive}"))["open"]["critical"], 1);
assert!(node(&format!("target:{plc}")).get("bought").is_none());
assert_eq!(node("project:m1")["open"]["critical"], 1);
assert_eq!(node("project:m1")["open"]["high"], 1);
assert_eq!(node("project:m2")["open"]["high"], 1, "the shared PLC");
assert_eq!(node("project:m2")["level"], "product");
let supplies = edges.iter().find(|e| e["kind"] == "supplies").unwrap();
assert_eq!(supplies["to"], format!("target:{drive}"));
assert_eq!(supplies["delivery"]["how"], "missing");
assert_eq!(supplies["delivery"]["version"], "4.2.1");
let part_of = edges.iter().filter(|e| e["kind"] == "part_of").count();
assert_eq!(part_of, 3, "drive to m1, PLC to m1 and m2");
// Without a registry a product's box has no documents to show.
let body: serde_json::Value = server
.get("/api/v1/supply-chain/projects/m1/documents")
.await
.json()
.await
.unwrap();
assert_eq!(body["data"]["documents"], json!([]));
assert_eq!(body["data"]["store_path"], "");
server.cleanup().await;
}
#[tokio::test]
async fn the_arrangement_is_kept_until_it_is_reset() {
let server = TestServer::start().await;
let layout = "/api/v1/supply-chain/layout";
let resp = server.get(layout).await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
assert_eq!(body["data"]["positions"], json!([]));
assert!(body["data"]["updated_at"].is_null());
let saved = json!({ "positions": [
{ "key": "supplier:Beispiel GmbH & Co. KG", "x": 40, "y": 60 },
{ "key": "target:a", "x": 400, "y": 60 },
{ "key": "target:a", "x": 420, "y": 80 },
] });
let resp = server.put(layout, &saved).await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = server.get(layout).await.json().await.unwrap();
assert_eq!(
body["data"]["positions"],
json!([
{ "key": "supplier:Beispiel GmbH & Co. KG", "x": 40, "y": 60 },
{ "key": "target:a", "x": 420, "y": 80 },
]),
"a name with a dot is kept, a key once with its last position"
);
assert!(body["data"]["updated_at"].is_string());
let resp = server
.put(
layout,
&json!({ "positions": [{ "key": " ", "x": 0, "y": 0 }] }),
)
.await;
assert_eq!(resp.status(), 422);
let body: serde_json::Value = server.get(layout).await.json().await.unwrap();
assert_eq!(
body["data"]["positions"].as_array().unwrap().len(),
2,
"a refused save changes nothing"
);
let resp = server.delete(layout).await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = server.get(layout).await.json().await.unwrap();
assert_eq!(body["data"]["positions"], json!([]));
server.cleanup().await;
}
-747
View File
@@ -1,747 +0,0 @@
//! Supplier invites (#1027) against a live Mongo: the portal invites a
//! supplier for a supplier component only, lists the tenant's invites with
//! their state, and withdraws one once. The supplier uploads through a valid
//! invite only, and every upload is recorded. Skips cleanly when no Mongo is
//! reachable.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use std::sync::Arc;
use axum::routing::{get, post};
use axum::Router;
use mongodb::bson::doc;
use serde_json::{json, Value};
use compliance_agent::agent::ComplianceAgent;
use compliance_agent::api::handlers::platform::{self, PlatformState};
use compliance_agent::api::handlers::supplier_invites::{self, SupplierInvite, SupplierUpload};
use compliance_agent::database::{Database, DatabasePool};
use compliance_core::models::{ArtifactKind, OnboardedTarget, SupplierComponent, TargetType};
use common::dev_config;
const TENANT: &str = "invites";
const OTHER: &str = "invites-other";
struct Harness {
base_url: String,
client: reqwest::Client,
pool: DatabasePool,
db: Database,
}
async fn start() -> Option<Harness> {
start_with(None).await
}
/// The harness with `registry` as the agent's tenant registry.
async fn start_with(registry: Option<String>) -> Option<Harness> {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("si_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP supplier_invites: no MongoDB reachable at {uri}");
return None;
};
let db = pool.for_tenant_id(TENANT).await.expect("tenant db");
let mut config = dev_config(uri, db_name);
config.tenant_registry_url = registry;
let agent = Arc::new(ComplianceAgent::new(config, pool.clone()));
let state = PlatformState { agent, jwks: None };
let app = Router::new()
.route(
"/api/v1/platform/tenants/{id}/targets",
get(platform::list_targets),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites",
get(supplier_invites::list_invites).post(supplier_invites::create_invite),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/withdraw",
post(supplier_invites::withdraw_invite),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/supplier-view",
get(supplier_invites::supplier_view),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms",
post(supplier_invites::upload_through_invite),
)
.route(
"/api/v1/platform/tenants/{id}/supplier-invites/{invite}/sboms/check",
post(supplier_invites::check_through_invite),
)
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
Some(Harness {
base_url: format!("http://127.0.0.1:{port}"),
client: reqwest::Client::new(),
pool,
db,
})
}
/// A CycloneDX SBOM listing `components` npm packages.
fn sbom(components: usize) -> Vec<u8> {
let listed: Vec<Value> = (0..components)
.map(|i| {
json!({ "type": "library", "name": format!("pkg{i}"), "version": "1.0.0",
"purl": format!("pkg:npm/pkg{i}@1.0.0") })
})
.collect();
serde_json::to_vec(
&json!({ "bomFormat": "CycloneDX", "specVersion": "1.5", "components": listed }),
)
.unwrap()
}
impl Harness {
async fn target(&self, name: &str, supplier: bool) -> String {
let mut target = OnboardedTarget::new(name.into(), TargetType::FirmwareRtos);
target.supplier = supplier.then(|| SupplierComponent {
name: "Test Antriebstechnik".into(),
product: Some("DR-4".into()),
version: Some("1.1".into()),
csaf_provider: None,
});
let id = self
.db
.onboarded_targets()
.insert_one(&target)
.await
.unwrap()
.inserted_id;
id.as_object_id().unwrap().to_hex()
}
async fn call(&self, method: reqwest::Method, path: &str, body: Option<Value>) -> (u16, Value) {
let mut req = self.client.request(
method,
format!("{}/api/v1/platform/tenants/{path}", self.base_url),
);
if let Some(body) = body {
req = req.json(&body);
}
let resp = req.send().await.unwrap();
let status = resp.status().as_u16();
(status, resp.json().await.unwrap_or_default())
}
async fn upload(
&self,
tenant: &str,
invite: &str,
file: Option<(&str, Vec<u8>)>,
csaf_provider: Option<&str>,
) -> (u16, Value) {
self.send_sbom("sboms", tenant, invite, file, csaf_provider)
.await
}
async fn check(&self, tenant: &str, invite: &str, bytes: Vec<u8>) -> (u16, Value) {
self.send_sbom("sboms/check", tenant, invite, Some(("x.json", bytes)), None)
.await
}
async fn send_sbom(
&self,
route: &str,
tenant: &str,
invite: &str,
file: Option<(&str, Vec<u8>)>,
csaf_provider: Option<&str>,
) -> (u16, Value) {
let mut form = reqwest::multipart::Form::new();
if let Some(url) = csaf_provider {
form = form.text("csaf_provider", url.to_string());
}
if let Some((name, bytes)) = file {
form = form.part(
"file",
reqwest::multipart::Part::bytes(bytes).file_name(name.to_string()),
);
}
let resp = self
.client
.post(format!(
"{}/api/v1/platform/tenants/{tenant}/supplier-invites/{invite}/{route}",
self.base_url
))
.multipart(form)
.send()
.await
.unwrap();
let status = resp.status().as_u16();
(status, resp.json().await.unwrap_or_default())
}
async fn supplier_view(&self, tenant: &str, invite: &str) -> (u16, Value) {
self.call(
reqwest::Method::GET,
&format!("{tenant}/supplier-invites/{invite}/supplier-view"),
None,
)
.await
}
async fn stored_target(&self, id: &str) -> OnboardedTarget {
let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap();
self.db
.onboarded_targets()
.find_one(doc! { "_id": oid })
.await
.unwrap()
.unwrap()
}
async fn invite(&self, tenant: &str, target: &str, email: &str) -> (u16, Value) {
let body = json!({ "target_id": target, "email": email, "invited_by": "user-1" });
self.call(
reqwest::Method::POST,
&format!("{tenant}/supplier-invites"),
Some(body),
)
.await
}
}
#[tokio::test]
async fn a_supplier_is_invited_for_a_supplier_component_only() {
let Some(h) = start().await else { return };
let bought = h.target("Antriebsregler DR-4", true).await;
let own = h.target("Eigene Steuerung", false).await;
let (status, invite) = h.invite(TENANT, &bought, " SBOM@Antrieb.Example ").await;
assert_eq!(status, 201, "{invite}");
assert_eq!(invite["email"], "sbom@antrieb.example");
assert_eq!(invite["target_id"], bought.as_str());
assert_eq!(invite["invited_by"], "user-1");
assert_eq!(invite["state"], "active");
let created: chrono::DateTime<chrono::Utc> =
invite["created_at"].as_str().unwrap().parse().unwrap();
let expires: chrono::DateTime<chrono::Utc> =
invite["expires_at"].as_str().unwrap().parse().unwrap();
assert_eq!(expires - created, chrono::Duration::days(90));
// The tenant's own component, nonsense, and another tenant's target.
assert_eq!(h.invite(TENANT, &own, "a@b.example").await.0, 422);
assert_eq!(h.invite(TENANT, &bought, "no address").await.0, 422);
assert_eq!(h.invite(TENANT, "not-an-id", "a@b.example").await.0, 404);
assert_eq!(h.invite(OTHER, &bought, "a@b.example").await.0, 404);
let no_actor = json!({ "target_id": bought, "email": "a@b.example", "invited_by": " " });
let (status, _) = h
.call(
reqwest::Method::POST,
&format!("{TENANT}/supplier-invites"),
Some(no_actor),
)
.await;
assert_eq!(status, 422);
let stored =
h.db.inner()
.collection::<SupplierInvite>(SupplierInvite::COLLECTION)
.count_documents(doc! {})
.await
.unwrap();
assert_eq!(stored, 1, "a refused invite stores nothing");
let other = h.pool.list_tenant_ids().await.unwrap();
assert!(
!other.iter().any(|t| t == OTHER),
"an invite to an unknown tenant creates no database"
);
// The portal's target list says which targets a supplier can be invited for.
let (status, targets) = h
.call(reqwest::Method::GET, &format!("{TENANT}/targets"), None)
.await;
assert_eq!(status, 200);
let listed = targets["items"].as_array().unwrap();
let supplier_of = |id: &str| {
listed
.iter()
.find(|t| t["id"] == id)
.map(|t| t["supplier"]["name"].clone())
.unwrap()
};
assert_eq!(supplier_of(&bought), "Test Antriebstechnik");
assert_eq!(supplier_of(&own), Value::Null);
h.pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn invites_are_listed_with_their_state_and_withdrawn_once() {
let Some(h) = start().await else { return };
let first = h.target("Antriebsregler DR-4", true).await;
let second = h.target("HMI-Panel HP-7", true).await;
let (_, active) = h.invite(TENANT, &first, "sbom@antrieb.example").await;
let (_, other) = h.invite(TENANT, &second, "psirt@display.example").await;
// One made long ago: past its 90 days.
let old = SupplierInvite::new(
second.clone(),
"old@display.example".into(),
"user-2".into(),
chrono::Utc::now() - chrono::Duration::days(91),
);
h.db.inner()
.collection::<SupplierInvite>(SupplierInvite::COLLECTION)
.insert_one(&old)
.await
.unwrap();
let (status, all) = h
.call(
reqwest::Method::GET,
&format!("{TENANT}/supplier-invites"),
None,
)
.await;
assert_eq!(status, 200);
let states: Vec<(&str, &str)> = all
.as_array()
.unwrap()
.iter()
.map(|i| (i["email"].as_str().unwrap(), i["state"].as_str().unwrap()))
.collect();
assert_eq!(
states,
[
("psirt@display.example", "active"),
("sbom@antrieb.example", "active"),
("old@display.example", "expired"),
],
"newest first"
);
let (_, of_second) = h
.call(
reqwest::Method::GET,
&format!("{TENANT}/supplier-invites?target={second}"),
None,
)
.await;
assert_eq!(of_second.as_array().unwrap().len(), 2);
let withdraw = |id: &str, by: &str| {
let path = format!("{TENANT}/supplier-invites/{id}/withdraw");
let body = json!({ "withdrawn_by": by });
let h = &h;
async move { h.call(reqwest::Method::POST, &path, Some(body)).await }
};
let id = active["id"].as_str().unwrap();
let (status, withdrawn) = withdraw(id, "user-1").await;
assert_eq!(status, 200, "{withdrawn}");
assert_eq!(withdrawn["state"], "withdrawn");
assert_eq!(withdrawn["withdrawn_by"], "user-1");
let (status, again) = withdraw(id, "user-3").await;
assert_eq!(status, 200);
assert_eq!(
again["withdrawn_by"], "user-1",
"the first withdrawal is kept"
);
assert_eq!(again["withdrawn_at"], withdrawn["withdrawn_at"]);
assert_eq!(withdraw(other["id"].as_str().unwrap(), " ").await.0, 422);
assert_eq!(
withdraw(&mongodb::bson::oid::ObjectId::new().to_hex(), "user-1")
.await
.0,
404
);
assert_eq!(withdraw("nonsense", "user-1").await.0, 404);
let (status, _) = h
.call(
reqwest::Method::POST,
&format!("{OTHER}/supplier-invites/{id}/withdraw"),
Some(json!({ "withdrawn_by": "user-1" })),
)
.await;
assert_eq!(status, 404, "another tenant's invite is not found");
h.pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn a_supplier_uploads_versions_through_its_invite() {
let Some(h) = start().await else { return };
let target = h.target("Antriebsregler DR-4", true).await;
let (_, invite) = h.invite(TENANT, &target, "sbom@antrieb.example").await;
let id = invite["id"].as_str().unwrap();
let (status, page) = h.supplier_view(TENANT, id).await;
assert_eq!(status, 200, "{page}");
assert_eq!(page["component"], "Antriebsregler DR-4");
assert_eq!(page["product"], "DR-4");
assert_eq!(page["expires_at"], invite["expires_at"]);
assert_eq!(page["uploads"], json!([]));
assert!(page.get("email").is_none() && page.get("target_id").is_none());
let provider = "https://antrieb.example/.well-known/csaf/provider-metadata.json";
let (status, first) = h
.upload(
TENANT,
id,
Some(("dr4-1.0.cdx.json", sbom(2))),
Some(provider),
)
.await;
assert_eq!(status, 201, "{first}");
assert_eq!(first["accepted"], true);
assert_eq!(first["current"], true);
assert_eq!(first["filename"], "dr4-1.0.cdx.json");
assert_eq!(first["summary"]["components"], 2);
let stored = h.stored_target(&target).await;
let sboms: Vec<_> = stored
.artifacts
.iter()
.filter(|a| a.kind == ArtifactKind::SupplierSbom)
.collect();
assert_eq!(sboms.len(), 1, "the upload is the component's SBOM");
assert!(sboms[0].ingested_at.is_some());
assert_eq!(
stored.supplier.unwrap().csaf_provider.as_deref(),
Some(provider),
"the supplier's CSAF provider becomes the component's"
);
// A path in the name is not kept; the next version replaces the first.
let (status, second) = h
.upload(TENANT, id, Some(("../../dr4-1.1.cdx.json", sbom(3))), None)
.await;
assert_eq!(status, 201, "{second}");
assert_eq!(second["filename"], "dr4-1.1.cdx.json");
let stored = h.stored_target(&target).await;
let sboms: Vec<_> = stored
.artifacts
.iter()
.filter(|a| a.kind == ArtifactKind::SupplierSbom)
.collect();
assert_eq!(sboms.len(), 1, "a new version replaces the one before");
// The same name again, and another provider: the file the new SBOM
// points to stays, and the provider the component has stays too.
let (status, third) = h
.upload(
TENANT,
id,
Some(("dr4-1.1.cdx.json", sbom(3))),
Some("https://other.example/provider-metadata.json"),
)
.await;
assert_eq!(status, 201, "{third}");
assert_eq!(
third["csaf_provider"], "https://other.example/provider-metadata.json",
"the upload keeps what the supplier gave"
);
let stored = h.stored_target(&target).await;
let kept = stored
.artifacts
.iter()
.find(|a| a.kind == ArtifactKind::SupplierSbom)
.and_then(|a| a.stored_path.clone())
.unwrap();
assert!(std::path::Path::new(&kept).exists(), "{kept}");
assert_eq!(
stored.supplier.unwrap().csaf_provider.as_deref(),
Some(provider),
"a provider the component has is not replaced"
);
// Each accepted upload starts a scan of the component.
let mut scans = 0;
for _ in 0..50 {
scans =
h.db.scan_runs()
.count_documents(doc! { "repo_id": &target })
.await
.unwrap();
if scans > 0 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
assert!(scans > 0, "a scan started");
let (_, page) = h.supplier_view(TENANT, id).await;
let shown: Vec<(&str, bool)> = page["uploads"]
.as_array()
.unwrap()
.iter()
.map(|u| {
(
u["filename"].as_str().unwrap(),
u["current"].as_bool().unwrap(),
)
})
.collect();
assert_eq!(
shown,
[
("dr4-1.1.cdx.json", true),
("dr4-1.1.cdx.json", false),
("dr4-1.0.cdx.json", false)
]
);
assert_eq!(page["csaf_provider"], provider);
// The customer sees the same uploads with the invite.
let (_, all) = h
.call(
reqwest::Method::GET,
&format!("{TENANT}/supplier-invites"),
None,
)
.await;
assert_eq!(all[0]["uploads"].as_array().unwrap().len(), 3);
assert_eq!(all[0]["uploads"][0]["summary"]["components"], 3);
h.pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn a_refused_upload_is_recorded_with_its_code() {
let Some(h) = start().await else { return };
let target = h.target("Antriebsregler DR-4", true).await;
let (_, invite) = h.invite(TENANT, &target, "sbom@antrieb.example").await;
let id = invite["id"].as_str().unwrap();
let (status, body) = h
.upload(
TENANT,
id,
Some(("dr4.csv", b"name,version".to_vec())),
None,
)
.await;
assert_eq!(
(status, body["code"].as_str()),
(422, Some("unknown_format"))
);
let (status, body) = h
.upload(
TENANT,
id,
Some(("dr4.cdx.json", sbom(1))),
Some("http://antrieb.example/provider-metadata.json"),
)
.await;
assert_eq!(
(status, body["code"].as_str()),
(422, Some("csaf_provider"))
);
// No file is the portal's mistake, not the supplier's: not recorded.
assert_eq!(h.upload(TENANT, id, None, None).await.0, 400);
let (_, page) = h.supplier_view(TENANT, id).await;
let codes: Vec<(&str, &str)> = page["uploads"]
.as_array()
.unwrap()
.iter()
.map(|u| {
assert_eq!(u["accepted"], false);
(u["filename"].as_str().unwrap(), u["code"].as_str().unwrap())
})
.collect();
assert_eq!(
codes,
[
("dr4.cdx.json", "csaf_provider"),
("dr4.csv", "unknown_format")
]
);
let stored = h.stored_target(&target).await;
assert!(stored.artifacts.is_empty(), "nothing refused is kept");
assert_eq!(stored.supplier.unwrap().csaf_provider, None);
h.pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn only_a_valid_invite_takes_an_upload() {
let Some(h) = start().await else { return };
let target = h.target("Antriebsregler DR-4", true).await;
let (_, invite) = h.invite(TENANT, &target, "sbom@antrieb.example").await;
let id = invite["id"].as_str().unwrap().to_string();
let file = || Some(("dr4.cdx.json", sbom(1)));
// Another tenant, an unknown invite.
assert_eq!(h.upload(OTHER, &id, file(), None).await.0, 404);
assert_eq!(h.supplier_view(OTHER, &id).await.0, 404);
let unknown = mongodb::bson::oid::ObjectId::new().to_hex();
assert_eq!(h.upload(TENANT, &unknown, file(), None).await.0, 404);
// The day's uploads are capped.
let invites =
h.db.inner()
.collection::<SupplierInvite>(SupplierInvite::COLLECTION);
let stored = invites.find_one(doc! {}).await.unwrap().unwrap();
let records: Vec<SupplierUpload> = (0..supplier_invites::MAX_UPLOADS_PER_DAY)
.map(|_| SupplierUpload {
id: mongodb::bson::oid::ObjectId::new(),
invite_id: id.clone(),
target_id: target.clone(),
uploaded_at: mongodb::bson::DateTime::now(),
filename: "x".into(),
accepted: false,
code: Some("empty".into()),
summary: None,
artifact_id: None,
csaf_provider: None,
})
.collect();
let uploads =
h.db.inner()
.collection::<SupplierUpload>(SupplierUpload::COLLECTION);
uploads.insert_many(&records).await.unwrap();
let (status, body) = h.upload(TENANT, &id, file(), None).await;
assert_eq!(
(status, body["code"].as_str()),
(429, Some("too_many_uploads"))
);
uploads.delete_many(doc! {}).await.unwrap();
// Withdrawn, then one past its 90 days.
h.call(
reqwest::Method::POST,
&format!("{TENANT}/supplier-invites/{id}/withdraw"),
Some(json!({ "withdrawn_by": "user-1" })),
)
.await;
let (status, body) = h.upload(TENANT, &id, file(), None).await;
assert_eq!((status, body["code"].as_str()), (410, Some("withdrawn")));
let (status, body) = h.supplier_view(TENANT, &id).await;
assert_eq!((status, body["code"].as_str()), (410, Some("withdrawn")));
assert!(
body.get("component").is_none(),
"a closed invite shows nothing"
);
let old = SupplierInvite::new(
stored.target_id.clone(),
"old@antrieb.example".into(),
"user-2".into(),
chrono::Utc::now() - chrono::Duration::days(91),
);
invites.insert_one(&old).await.unwrap();
let (status, body) = h.upload(TENANT, &old.id.to_hex(), file(), None).await;
assert_eq!((status, body["code"].as_str()), (410, Some("expired")));
assert!(h.stored_target(&target).await.artifacts.is_empty());
assert_eq!(
uploads.count_documents(doc! {}).await.unwrap(),
0,
"closed: nothing recorded"
);
h.pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn the_supplier_page_checks_a_file_before_it_is_uploaded() {
let Some(h) = start().await else { return };
let target = h.target("Antriebsregler DR-4", true).await;
let (_, invite) = h.invite(TENANT, &target, "sbom@antrieb.example").await;
let id = invite["id"].as_str().unwrap();
let (status, body) = h.check(TENANT, id, sbom(4)).await;
assert_eq!(status, 200, "{body}");
assert_eq!(body["data"]["components"], 4);
let (status, body) = h.check(TENANT, id, b"name,version".to_vec()).await;
assert_eq!(
(status, body["code"].as_str()),
(422, Some("unknown_format"))
);
let count =
h.db.inner()
.collection::<SupplierUpload>(SupplierUpload::COLLECTION)
.count_documents(doc! {})
.await
.unwrap();
assert_eq!(count, 0, "a check records nothing");
// A component whose supplier was removed takes nothing more.
let oid = mongodb::bson::oid::ObjectId::parse_str(&target).unwrap();
h.db.onboarded_targets()
.update_one(doc! { "_id": oid }, doc! { "$unset": { "supplier": "" } })
.await
.unwrap();
assert_eq!(h.check(TENANT, id, sbom(1)).await.0, 404);
assert_eq!(h.supplier_view(TENANT, id).await.0, 404);
let (status, _) = h
.upload(TENANT, id, Some(("x.cdx.json", sbom(1))), None)
.await;
assert_eq!(status, 404);
assert!(h.stored_target(&target).await.artifacts.is_empty());
h.pool.drop_tenant(TENANT).await.ok();
}
/// A registry that answers each tenant's entitlement check as `answers` says.
async fn fake_registry(answers: Value) -> String {
let app = Router::new().route(
"/v1/internal/entitlements/check",
post(move |axum::Json(body): axum::Json<Value>| {
let answer = answers[body["tenant_id"].as_str().unwrap_or_default()].clone();
async move { axum::Json(answer) }
}),
);
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}")
}
#[tokio::test]
async fn a_workspace_that_takes_no_changes_takes_no_upload() {
let registry = fake_registry(json!({
"invites": { "allowed": true, "status": "active" },
"no-status": { "allowed": true },
"frozen": { "allowed": true, "status": "frozen" },
"read-only": { "allowed": true, "read_only": true, "status": "active" },
"halted": { "allowed": true, "status": "halted" },
"not-entitled": { "allowed": false, "status": "active" },
}))
.await;
let Some(h) = start_with(Some(registry)).await else {
return;
};
for (tenant, expected) in [
("invites", 201),
("no-status", 201),
("frozen", 403),
("read-only", 403),
("halted", 403),
("not-entitled", 403),
] {
let db = h.pool.for_tenant_id(tenant).await.unwrap();
let mut target = OnboardedTarget::new("DR-4".into(), TargetType::FirmwareRtos);
target.supplier = Some(SupplierComponent {
name: "Test Antriebstechnik".into(),
product: None,
version: None,
csaf_provider: None,
});
let id = db.onboarded_targets().insert_one(&target).await.unwrap();
let target = id.inserted_id.as_object_id().unwrap().to_hex();
let (_, invite) = h.invite(tenant, &target, "sbom@antrieb.example").await;
let (status, body) = h
.upload(
tenant,
invite["id"].as_str().unwrap(),
Some(("x.cdx.json", sbom(1))),
None,
)
.await;
assert_eq!(status, expected, "{tenant}: {body}");
if expected == 403 {
assert_eq!(body["code"], "read_only");
}
h.pool.drop_tenant(tenant).await.ok();
}
}
-56
View File
@@ -149,14 +149,6 @@ async fn vex_status_follows_the_scans_but_never_overrides_a_person() {
upsert_reported(&db, &exploited).await.unwrap();
assert_eq!(stored(&db, "CVE-5").await.exploited_seen_at, Some(first));
// When it was first found stays (#1041): a scan reporting it again
// builds it with a later `created_at`, which is not kept.
let first_found = stored(&db, "CVE-5").await.created_at;
let mut again = alert("CVE-5");
again.created_at = first_found + chrono::Duration::hours(5);
upsert_reported(&db, &again).await.unwrap();
assert_eq!(stored(&db, "CVE-5").await.created_at, first_found);
// An alert stored without a purl gets its component's on the next scan;
// a scan that knows none keeps it, unless the alert is now about another
// component.
@@ -476,51 +468,3 @@ async fn not_affected_and_fixed_raise_no_notification_until_withdrawn() {
pool.drop_tenant(tenant).await.ok();
}
/// #1025: a supplier's statement is stored with the alert as the scan read
/// it, beside (never in) the alert's own VEX, and goes once a scan's SBOM no
/// longer states it.
#[tokio::test]
async fn a_suppliers_statement_is_restated_by_each_scan() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"vexsup_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP vex_lifecycle: no MongoDB reachable at {uri}");
return;
};
let tenant = "vex-supplier";
let Ok(db) = pool.for_tenant_id(tenant).await else {
eprintln!("SKIP vex_lifecycle: MongoDB at {uri} not usable");
return;
};
let mut stated = alert("CVE-7");
stated.supplier_vex = Some(compliance_core::models::SupplierVex {
status: VexStatus::NotAffected,
state: "not_affected".into(),
justification: Some("code_not_reachable".into()),
detail: None,
response: Vec::new(),
source: "pump.cdx.json".into(),
});
upsert_reported(&db, &stated).await.unwrap();
let first = stored(&db, "CVE-7").await;
assert_eq!(
first.supplier_vex.as_ref().map(|v| v.status),
Some(VexStatus::NotAffected)
);
assert!(
first.vex.is_none(),
"it is not the manufacturer's statement"
);
assert!(!first.is_resolved_by_vex(), "and settles nothing");
upsert_reported(&db, &alert("CVE-7")).await.unwrap();
assert!(stored(&db, "CVE-7").await.supplier_vex.is_none());
pool.drop_tenant(tenant).await.ok();
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-core"
version = "0.4.17"
version = "0.4.16"
edition = "2021"
[lints]
-11
View File
@@ -91,17 +91,6 @@ impl SeverityCounts {
]
}
/// The counts of `self` and `other` together.
pub fn plus(self, other: Self) -> Self {
Self {
critical: self.critical + other.critical,
high: self.high + other.high,
medium: self.medium + other.medium,
low: self.low + other.low,
info: self.info + other.info,
}
}
/// The most severe severity counted, `Info` when none is.
pub fn max(&self) -> CveSeverity {
self.by_severity()
-1
View File
@@ -318,7 +318,6 @@ mod tests {
at: chrono::Utc::now(),
by_scan: false,
}),
supplier_vex: None,
resolved_at: None,
exploited_seen_at: None,
created_at: chrono::Utc::now(),
-7
View File
@@ -118,12 +118,6 @@ pub struct CveAlert {
/// The VEX statement on it (#498); none until someone states one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vex: Option<super::vex::VexAssessment>,
/// What the supplier of a bought-in component states about it in its SBOM
/// (#1025). Restated by every scan from the current SBOM, dropped when the
/// supplier no longer states it. Never the manufacturer's own statement:
/// it settles nothing and is not exported as one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub supplier_vex: Option<super::vex::SupplierVex>,
/// When a complete scan last found it gone (the component removed or
/// past a fixed version); `None` while it is reported.
#[serde(
@@ -243,7 +237,6 @@ impl CveAlert {
exploitation: None,
advisories: Vec::new(),
vex: None,
supplier_vex: None,
resolved_at: None,
exploited_seen_at: None,
created_at: Utc::now(),
+3 -3
View File
@@ -71,7 +71,7 @@ pub use onboarding::{
default_compliance_profile, Artifact, ArtifactAuth, ArtifactKind, Classification,
ComplianceFramework, ComplianceProfile, DetectedFact, ExternalRef, ExternalSystem,
GitArtifactConfig, IssueTrackerConfig, LastScan, OnboardedTarget, PlcArtifactConfig, PlcFormat,
SupplierComponent, TargetScanConfig, TargetType, TargetTypeCandidate, WebArtifactConfig,
TargetScanConfig, TargetType, TargetTypeCandidate, WebArtifactConfig,
};
pub use oscal::OscalDocument;
pub use oscal_assessment::{assess, AssessmentResultsDoc, ControlLinker};
@@ -81,7 +81,7 @@ pub use pentest::{
PentestStatus, PentestStrategy, SeverityDistribution, TestUserRecord, TesterInfo,
ToolCallRecord,
};
pub use project::{Project, ProjectKind, ProjectLevel};
pub use project::{Project, ProjectKind};
pub use repository::ScanTrigger;
pub use sbom::{
ComponentHash, InImage, InImageBasis, SbomEntry, SbomQuality, SbomQualityCheck,
@@ -91,7 +91,7 @@ pub use scan::{
RunErrorCode, RunNote, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode,
SkippedStage,
};
pub use vex::{SupplierVex, VexAssessment, VexError, VexJustification, VexStatus};
pub use vex::{VexAssessment, VexError, VexJustification, VexStatus};
pub use webhook_delivery::{DeliveryResult, WebhookDelivery, DELIVERIES_SHOWN};
pub use werkbank::{
CompleteRequest, CompleteResponse, DastCollect, Executor, HeartbeatAck, HeartbeatRequest,
-33
View File
@@ -87,9 +87,6 @@ pub enum ArtifactKind {
/// What a build wrote about its image: a Yocto image's SPDX archive
/// (`<image>.spdx.tar.zst`).
BuildOutput,
/// A component's SBOM as its supplier delivered it (CycloneDX or SPDX),
/// for a component bought in without its source code (#1025).
SupplierSbom,
}
impl std::fmt::Display for ArtifactKind {
@@ -104,7 +101,6 @@ impl std::fmt::Display for ArtifactKind {
Self::PlcProject => write!(f, "plc_project"),
Self::PlaintextDescription => write!(f, "plaintext_description"),
Self::BuildOutput => write!(f, "build_output"),
Self::SupplierSbom => write!(f, "supplier_sbom"),
}
}
}
@@ -341,11 +337,6 @@ impl Artifact {
Self::bare(ArtifactKind::BuildOutput, source_ref)
}
/// A supplier's SBOM of a component, uploaded as delivered (#1025).
pub fn supplier_sbom(source_ref: impl Into<String>) -> Self {
Self::bare(ArtifactKind::SupplierSbom, source_ref)
}
/// A container-image artifact referenced by OCI ref.
pub fn container_image(source_ref: impl Into<String>) -> Self {
Self::bare(ArtifactKind::ContainerImage, source_ref)
@@ -699,11 +690,6 @@ pub struct OnboardedTarget {
with = "super::serde_helpers::opt_bson_datetime"
)]
pub included_until: Option<DateTime<Utc>>,
/// Who supplies the component, for a component bought in (#1025): the
/// supplier, its product and version, and where it publishes its CSAF
/// advisories. `None` for what the tenant makes itself.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub supplier: Option<SupplierComponent>,
/// Creation timestamp.
#[serde(
default = "chrono::Utc::now",
@@ -718,24 +704,6 @@ pub struct OnboardedTarget {
pub updated_at: DateTime<Utc>,
}
/// A component bought in from a supplier (#1025).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SupplierComponent {
/// The supplier's name.
pub name: String,
/// The supplier's name for the product, as its advisories name it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub product: Option<String>,
/// The product's version in use.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// The supplier's CSAF provider metadata (`provider-metadata.json`, an
/// https URL). Its public (TLP:WHITE) advisories are fetched for this
/// tenant only and matched against the product and its components.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub csaf_provider: Option<String>,
}
impl OnboardedTarget {
/// A new target of the given type. It has no webhook secret: storing one
/// needs the agent's encryption key, and webhooks are off until a secret
@@ -765,7 +733,6 @@ impl OnboardedTarget {
billing: super::metering::TargetBilling::default(),
included_choice: None,
included_until: None,
supplier: None,
created_at: now,
updated_at: now,
}
-47
View File
@@ -16,19 +16,6 @@ pub enum ProjectKind {
Topic,
}
/// Where a product project sits in the registry's hierarchy
/// (family, then product, then component; tenant-registry 0020).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProjectLevel {
/// A product family: no project above it.
Family,
/// A product or machine, below a family or at the top.
Product,
/// An assembly of a product, below a product or another component.
Component,
}
/// One of a tenant's projects, as the registry lists it
/// (`GET /v1/tenants/{id}/projects`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -39,23 +26,6 @@ pub struct Project {
pub kind: ProjectKind,
#[serde(default)]
pub description: String,
/// A product project's place in the hierarchy; `None` for a topic, and
/// for a product from before the hierarchy (read as a product).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub level: Option<ProjectLevel>,
/// The project above it; `None` at the top.
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "non_empty"
)]
pub parent_id: Option<String>,
}
/// An optional string, with an empty one read as none (the registry writes
/// `""` for a detached project).
fn non_empty<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
Ok(Option::<String>::deserialize(d)?.filter(|s| !s.trim().is_empty()))
}
#[cfg(test)]
@@ -72,22 +42,5 @@ mod tests {
.expect("deserialize");
assert_eq!(p.kind, ProjectKind::Product);
assert_eq!(p.description, "");
assert_eq!((p.level, p.parent_id), (None, None));
}
#[test]
fn a_registry_project_reads_its_place_in_the_hierarchy() {
let read = |parent: serde_json::Value| -> Project {
serde_json::from_value(serde_json::json!({
"id": "c1", "name": "Antriebseinheit", "kind": "product",
"level": "component", "parent_id": parent
}))
.expect("deserialize")
};
let p = read(serde_json::json!("p1"));
assert_eq!(p.level, Some(ProjectLevel::Component));
assert_eq!(p.parent_id.as_deref(), Some("p1"));
assert_eq!(read(serde_json::json!("")).parent_id, None, "detached");
assert_eq!(read(serde_json::Value::Null).parent_id, None);
}
}
-38
View File
@@ -94,44 +94,6 @@ pub struct VexAssessment {
pub by_scan: bool,
}
/// A supplier's VEX statement on a vulnerability of its component, as its
/// SBOM gives it (CycloneDX `vulnerabilities[].analysis`; #1025). Shown to
/// the person who decides, beside the manufacturer's own statement; it
/// settles nothing by itself.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SupplierVex {
/// The status as OpenVEX names it, read from `state`.
pub status: VexStatus,
/// CycloneDX's `state` as the supplier wrote it (`not_affected`,
/// `resolved`, `exploitable`, `in_triage`, `false_positive`, …).
pub state: String,
/// CycloneDX's `justification` as the supplier wrote it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub justification: Option<String>,
/// The supplier's explanation (`detail`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
/// What the supplier says to do (`response`: `update`, `workaround_available`, …).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub response: Vec<String>,
/// The SBOM it was read from (its file name).
pub source: String,
}
impl SupplierVex {
/// The OpenVEX status of a CycloneDX analysis `state`; `None` for one
/// CycloneDX does not define.
pub fn status_of_state(state: &str) -> Option<VexStatus> {
Some(match state {
"resolved" | "resolved_with_pedigree" => VexStatus::Fixed,
"exploitable" => VexStatus::Affected,
"in_triage" => VexStatus::UnderInvestigation,
"not_affected" | "false_positive" => VexStatus::NotAffected,
_ => return None,
})
}
}
/// Why a VEX statement cannot be stored.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum VexError {
+3 -363
View File
@@ -411,148 +411,8 @@ pub fn cyclonedx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
let components = cdx_components(entries);
cdx_dependencies(&mut doc, &components);
doc["components"] = serde_json::Value::Array(components);
cdx_known_vulnerabilities(&mut doc, entries);
doc
}
/// The product a released SBOM describes (#1028): the target a supplier
/// workspace releases, the version it publishes, and the workspace's name as
/// its supplier.
#[derive(Debug, Clone, Copy)]
pub struct ReleasedProduct<'a> {
/// The target's name.
pub name: &'a str,
/// The version the supplier publishes, such as `1.4.0`.
pub version: &'a str,
/// The supplier: the releasing workspace's display name.
pub supplier: &'a str,
}
/// The keys of a component that a released SBOM keeps: what identifies the
/// component, its licences and its hashes. Everything else stays with the
/// supplier: properties (where it was found, the images it is in, the
/// licence review), copyright, references and the manufacturer. A list of
/// what is kept, so nothing added to the export later crosses unnoticed.
const RELEASED_COMPONENT_KEYS: [&str; 9] = [
"type", "bom-ref", "name", "group", "version", "purl", "cpe", "licenses", "hashes",
];
/// The SBOM a supplier workspace releases to a connected customer workspace
/// (#1028): a CycloneDX 1.6 document of `entries` about `product`, holding
/// only what identifies each component, its licences and its hashes.
///
/// No vulnerabilities, findings or provenance cross: the customer's own scan
/// finds the vulnerabilities. A confirmed custom licence keeps its name but
/// not its text, which may come from the supplier's own contract.
///
/// # Arguments
///
/// * `entries` - the SBOM entries of the target's latest scan
/// * `product` - the target, the version published and the supplier
pub fn released_cyclonedx(
entries: &[SbomEntry],
product: &ReleasedProduct<'_>,
) -> serde_json::Value {
let mut doc = cdx_frame(product.name, entries);
doc["metadata"]["component"]["version"] = serde_json::json!(product.version);
doc["metadata"]["component"]["supplier"] = serde_json::json!({ "name": product.supplier });
let mut components: Vec<serde_json::Value> = cdx_components(entries)
.into_iter()
.map(released_component)
.collect();
unique_refs(&mut components);
cdx_dependencies(&mut doc, &components);
doc["components"] = serde_json::Value::Array(components);
doc
}
/// Purl qualifiers that say where a component was fetched from. A released
/// SBOM leaves them out: they can name the supplier's own servers (a Yocto
/// recipe's `vcs_url`, an internal feed).
const ADDRESS_QUALIFIERS: [&str; 3] = ["download_url", "vcs_url", "repository_url"];
/// `purl` without its [`ADDRESS_QUALIFIERS`]; anything that is not a purl
/// as it is.
fn without_addresses(purl: &str) -> String {
if !purl.starts_with("pkg:") {
return purl.to_string();
}
let (body, subpath) = match purl.split_once('#') {
Some((body, subpath)) => (body, Some(subpath)),
None => (purl, None),
};
let Some((base, qualifiers)) = body.split_once('?') else {
return purl.to_string();
};
let kept: Vec<&str> = qualifiers
.split('&')
.filter(|q| {
let key = q.split_once('=').map_or(*q, |(key, _)| key);
!ADDRESS_QUALIFIERS.contains(&key)
})
.collect();
let mut out = base.to_string();
if !kept.is_empty() {
out.push('?');
out.push_str(&kept.join("&"));
}
if let Some(subpath) = subpath {
out.push('#');
out.push_str(subpath);
}
out
}
/// Make each component's `bom-ref` unique again: two components can differ
/// only in a qualifier [`without_addresses`] removed. A repeated one gets
/// ` (2)`, ` (3)`, ... appended.
fn unique_refs(components: &mut [serde_json::Value]) {
let mut seen: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
for component in components {
let Some(reference) = component["bom-ref"].as_str().map(str::to_string) else {
continue;
};
let count = seen.entry(reference.clone()).or_insert(0);
*count += 1;
if *count > 1 {
component["bom-ref"] = serde_json::json!(format!("{reference} ({count})"));
}
}
}
/// `component` with only [`RELEASED_COMPONENT_KEYS`], no licence text and
/// no addresses in its purl.
fn released_component(mut component: serde_json::Value) -> serde_json::Value {
if let Some(fields) = component.as_object_mut() {
fields.retain(|key, _| RELEASED_COMPONENT_KEYS.contains(&key.as_str()));
for key in ["purl", "bom-ref"] {
if let Some(stripped) = fields
.get(key)
.and_then(|v| v.as_str())
.map(without_addresses)
{
fields.insert(key.to_string(), serde_json::Value::String(stripped));
}
}
let licenses = fields
.get_mut("licenses")
.and_then(serde_json::Value::as_array_mut);
for choice in licenses.into_iter().flatten() {
if let Some(license) = choice
.get_mut("license")
.and_then(serde_json::Value::as_object_mut)
{
license.remove("text");
}
}
}
component
}
/// The known vulnerabilities of `entries` as the document's
/// `vulnerabilities`: one per CVE (or advisory without one), affecting every
/// component it was found in, by whichever scanner and id. None, none set.
fn cdx_known_vulnerabilities(doc: &mut serde_json::Value, entries: &[SbomEntry]) {
// One vulnerability per CVE (or advisory without one), affecting every
// component it was found in, by whichever scanner and id.
let mut vulns: Vec<SbomVulnerability<'_>> = Vec::new();
for e in entries {
for v in &e.known_vulnerabilities {
@@ -600,103 +460,6 @@ fn cdx_known_vulnerabilities(doc: &mut serde_json::Value, entries: &[SbomEntry])
})
.collect();
}
}
/// One part of a machine (#1026): one of its targets, in-house or bought in.
#[derive(Debug, Clone, Copy)]
pub struct MachinePart<'a> {
/// The target's id. Its SBOM entries are the ones with this `repo_id`.
pub id: &'a str,
/// The target's name.
pub name: &'a str,
/// Its CycloneDX component type, such as `firmware` or `application`.
pub kind: &'static str,
/// Who supplies it: the supplier of a bought-in component, the
/// manufacturer (the workspace) for one made in-house.
pub supplier: &'a str,
/// Its version, where the supplier names one; else when its SBOM data
/// was last compiled, as for a target's own SBOM.
pub version: Option<&'a str>,
}
impl MachinePart<'_> {
/// The part's `bom-ref`: by its target's id, unique in the machine
/// whatever the targets are called.
pub fn bom_ref(&self) -> String {
format!("urn:pruefwerk:target:{}", self.id)
}
}
/// The SBOM of a machine (#1026): the machine `machine` (a product project,
/// `project_id`) made of `parts`, each listing the components of `entries`
/// with its `repo_id` beneath it.
///
/// Every part is a component of the machine with its supplier, so the
/// document names who supplies each. A component two parts contain is listed
/// once, with both parts depending on it. The machine depends on its parts
/// and each part on its components: the top-level dependencies the CRA asks
/// for (Annex I, Part II (1)). Which of a part's components depend on which
/// is not known, so the graph is stated `incomplete`, as for a target.
///
/// # Arguments
///
/// * `machine` - the machine's name
/// * `project_id` - its project's id, its `bom-ref`
/// * `parts` - its parts, in the order they are listed
/// * `entries` - the SBOM entries of all parts
pub fn machine_cyclonedx(
machine: &str,
project_id: &str,
parts: &[MachinePart<'_>],
entries: &[SbomEntry],
) -> serde_json::Value {
let machine_ref = format!("urn:pruefwerk:project:{project_id}");
let mut doc = cdx_frame(machine, entries);
doc["metadata"]["component"]["type"] = serde_json::json!("device");
doc["metadata"]["component"]["bom-ref"] = serde_json::json!(machine_ref);
let mut components: Vec<serde_json::Value> = Vec::with_capacity(parts.len());
let mut dependencies = Vec::with_capacity(parts.len() + 1);
dependencies.push(serde_json::json!({
"ref": machine_ref,
"dependsOn": parts.iter().map(MachinePart::bom_ref).collect::<Vec<_>>(),
}));
for part in parts {
let own: Vec<&SbomEntry> = entries.iter().filter(|e| e.repo_id == part.id).collect();
let version = part.version.map(str::to_string).or_else(|| {
own.iter()
.map(|e| e.updated_at)
.max()
.map(|at| at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
});
let mut component = serde_json::json!({
"type": part.kind,
"bom-ref": part.bom_ref(),
"name": part.name,
"supplier": { "name": part.supplier },
});
if let Some(version) = version {
component["version"] = serde_json::Value::String(version);
}
components.push(component);
let mut refs: Vec<String> = own.iter().map(|e| component_ref(e)).collect();
refs.sort_unstable();
refs.dedup();
dependencies.push(serde_json::json!({ "ref": part.bom_ref(), "dependsOn": refs }));
}
let parts_of_machine = components.len();
components.extend(cdx_components(entries));
dependencies.extend(
components[parts_of_machine..]
.iter()
.map(|c| serde_json::json!({ "ref": c["bom-ref"] })),
);
doc["components"] = serde_json::Value::Array(components);
doc["dependencies"] = serde_json::Value::Array(dependencies);
doc["compositions"] = serde_json::json!([{
"aggregate": "incomplete",
"dependencies": [machine_ref],
}]);
cdx_known_vulnerabilities(&mut doc, entries);
doc
}
@@ -811,130 +574,7 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
#[cfg(test)]
mod tests {
use super::*;
use crate::models::{InImage, InImageBasis, VulnRef};
#[test]
fn a_released_sbom_keeps_what_identifies_each_component_and_nothing_else() {
let mut e = SbomEntry::new("t".into(), "pump-sdk".into(), "4.2".into(), "nuget".into());
e.purl = Some("pkg:nuget/pump-sdk@4.2".into());
e.cpe = Some("cpe:2.3:a:example:pump-sdk:4.2:*:*:*:*:*:*:*".into());
e.hashes = vec![ComponentHash {
alg: "SHA-256".into(),
content: "ab".repeat(32),
}];
e.download_url = Some("https://internal.example/feed/pump-sdk.4.2.nupkg".into());
e.manufacturer_url = Some("https://example.com".into());
e.concluded = Some(concluded("LicenseRef-Pump-EULA", Some("Pump EULA")));
e.in_image = Some(InImage {
basis: InImageBasis::Declared,
images: vec!["pump-image".into()],
});
e.known_vulnerabilities = vec![VulnRef {
id: "CVE-2026-0001".into(),
source: "osv".into(),
severity: Some("HIGH".into()),
url: None,
exploitation: None,
aliases: Vec::new(),
}];
let product = ReleasedProduct {
name: "DR-4 Firmware",
version: "1.4.0",
supplier: "Test Antriebstechnik",
};
let doc = released_cyclonedx(std::slice::from_ref(&e), &product);
let meta = &doc["metadata"]["component"];
assert_eq!(meta["name"], "DR-4 Firmware");
assert_eq!(meta["version"], "1.4.0");
assert_eq!(meta["supplier"]["name"], "Test Antriebstechnik");
assert!(doc.get("vulnerabilities").is_none(), "{doc}");
let component = doc["components"][0].as_object().unwrap();
let mut keys: Vec<&str> = component.keys().map(String::as_str).collect();
keys.sort_unstable();
assert_eq!(
keys,
["bom-ref", "cpe", "hashes", "licenses", "name", "purl", "type", "version"],
"nothing beyond identity, licences and hashes"
);
assert_eq!(component["licenses"][0]["license"]["name"], "Pump EULA");
assert!(component["licenses"][0]["license"].get("text").is_none());
let text = doc.to_string();
for leaked in [
"internal.example",
"pump-image",
"contract 4711",
"CVE-2026-0001",
] {
assert!(!text.contains(leaked), "{leaked} crossed: {text}");
}
// The product still depends on its component.
assert_eq!(doc["dependencies"][0]["dependsOn"][0], component["bom-ref"]);
}
#[test]
fn a_released_purl_names_no_address() {
let entry = |purl: &str| {
let mut e = SbomEntry::new("t".into(), "pump-fw".into(), "1.0".into(), "yocto".into());
e.purl = Some(purl.into());
e
};
let entries = [
entry("pkg:generic/pump-fw@1.0?vcs_url=git%2Bhttps%3A%2F%2Fgit.internal.example%2Fpump-fw.git"),
entry("pkg:generic/pump-fw@1.0?download_url=http%3A%2F%2Fdl.internal.example%2Fpump.tgz&arch=arm"),
];
let product = ReleasedProduct {
name: "DR-4 Firmware",
version: "1.4.0",
supplier: "Test Antriebstechnik",
};
let doc = released_cyclonedx(&entries, &product);
assert!(!doc.to_string().contains("internal.example"), "{doc}");
let purls: Vec<&str> = doc["components"]
.as_array()
.unwrap()
.iter()
.map(|c| c["purl"].as_str().unwrap())
.collect();
assert_eq!(
purls,
[
"pkg:generic/pump-fw@1.0",
"pkg:generic/pump-fw@1.0?arch=arm"
]
);
assert_eq!(
without_addresses("pkg:npm/lodash@4.17.21"),
"pkg:npm/lodash@4.17.21"
);
assert_eq!(
without_addresses("pkg:generic/a@1?vcs_url=x#src/lib"),
"pkg:generic/a@1#src/lib"
);
}
#[test]
fn released_bom_refs_stay_unique() {
let mut components = vec![
serde_json::json!({ "bom-ref": "pkg:generic/a@1" }),
serde_json::json!({ "bom-ref": "pkg:generic/a@1" }),
serde_json::json!({ "bom-ref": "pkg:generic/b@1" }),
];
unique_refs(&mut components);
let refs: Vec<&str> = components
.iter()
.map(|c| c["bom-ref"].as_str().unwrap())
.collect();
assert_eq!(
refs,
["pkg:generic/a@1", "pkg:generic/a@1 (2)", "pkg:generic/b@1"]
);
}
use crate::models::{InImage, InImageBasis};
#[test]
fn both_formats_list_every_component() {
-55
View File
@@ -62,8 +62,6 @@ pub enum ArtifactRequirement {
/// What a build wrote about its image: a Yocto image SPDX archive or its
/// cve-check report.
BuildOutput,
/// A supplier's SBOM of a bought-in component (#1025).
SupplierSbom,
/// No specific artifact required.
Any,
}
@@ -219,20 +217,6 @@ fn sast_umbrella() -> Vec<ScanRule> {
/// simply absent (e.g. DAST is not listed for a PLC target).
pub fn rules_for(target_type: TargetType) -> Vec<ScanRule> {
let mut rules = target_rules(target_type);
// Any target may carry a supplier's SBOM of a component bought in
// without its source (#1025): its components and their known CVEs.
rules.push(ScanRule::new(
ScanType::Sbom,
true,
"SBOM of the component as its supplier delivered it",
ArtifactRequirement::SupplierSbom,
));
rules.push(ScanRule::new(
ScanType::Cve,
true,
"The supplier SBOM's components against known CVEs and vendor advisories",
ArtifactRequirement::SupplierSbom,
));
// Any target may carry a container image, and nothing scans one; say so
// rather than accepting the artifact in silence.
rules.push(ScanRule::unavailable(
@@ -427,7 +411,6 @@ fn representative_kind(req: ArtifactRequirement) -> Option<ArtifactKind> {
ArtifactRequirement::Mobile => Some(ArtifactKind::MobilePackage),
ArtifactRequirement::Container => Some(ArtifactKind::ContainerImage),
ArtifactRequirement::BuildOutput => Some(ArtifactKind::BuildOutput),
ArtifactRequirement::SupplierSbom => Some(ArtifactKind::SupplierSbom),
ArtifactRequirement::Any => None,
}
}
@@ -458,7 +441,6 @@ fn requirement_satisfied(req: ArtifactRequirement, target: &OnboardedTarget) ->
ArtifactRequirement::Mobile => target.has(ArtifactKind::MobilePackage),
ArtifactRequirement::Container => target.has(ArtifactKind::ContainerImage),
ArtifactRequirement::BuildOutput => target.has(ArtifactKind::BuildOutput),
ArtifactRequirement::SupplierSbom => target.has(ArtifactKind::SupplierSbom),
ArtifactRequirement::Any => true,
}
}
@@ -498,43 +480,6 @@ pub fn applicable_scans(target: &OnboardedTarget) -> Vec<ScanOption> {
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
#[test]
fn a_supplier_sbom_brings_its_sbom_and_cve_scans_to_every_target_type() {
use crate::models::Artifact;
for target_type in [
TargetType::WebApp,
TargetType::BackendService,
TargetType::DesktopApp,
TargetType::AndroidApp,
TargetType::IosApp,
TargetType::FirmwareBareMetal,
TargetType::FirmwareRtos,
TargetType::EmbeddedLinuxYocto,
TargetType::PlcSps,
] {
let mut target = OnboardedTarget::new("component".into(), target_type);
target
.artifacts
.push(Artifact::supplier_sbom("pump.cdx.json"));
let runs = |scan: ScanType| {
applicable_scans(&target).iter().any(|o| {
o.scan == scan
&& o.default_on
&& o.required_artifact == Some(ArtifactKind::SupplierSbom)
})
};
assert!(
runs(ScanType::Sbom),
"{target_type:?}: no SBOM from the supplier SBOM"
);
assert!(
runs(ScanType::Cve),
"{target_type:?}: no CVE check of the supplier SBOM"
);
}
}
use super::*;
use crate::models::{Artifact, PlcFormat};
-32
View File
@@ -1,32 +0,0 @@
//! What the schema tests share: the vendored schemas and the CycloneDX
//! validation.
#![allow(clippy::expect_used, clippy::unwrap_used, dead_code)]
/// The vendored schema `name` (in `schemas/`).
pub fn schema(name: &str) -> serde_json::Value {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("schemas")
.join(name);
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}
/// The errors of `doc` against CycloneDX 1.6 (with the SPDX and JSF schemas
/// it refers to).
pub fn cyclonedx_errors(doc: &serde_json::Value) -> Vec<String> {
let validator = jsonschema::options()
.with_resource(
"http://cyclonedx.org/schema/spdx.schema.json",
jsonschema::Resource::from_contents(schema("spdx.schema.json")).unwrap(),
)
.with_resource(
"http://cyclonedx.org/schema/jsf-0.82.schema.json",
jsonschema::Resource::from_contents(schema("jsf-0.82.schema.json")).unwrap(),
)
.build(&schema("bom-1.6.schema.json"))
.unwrap();
validator
.iter_errors(doc)
.map(|e| format!("{} at {}", e, e.instance_path))
.collect()
}
-125
View File
@@ -1,125 +0,0 @@
//! The SBOM of a machine (#1026): its parts, in-house and bought in, with
//! their suppliers and components, valid against CycloneDX 1.6.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use std::collections::HashSet;
use compliance_core::models::{SbomEntry, VulnRef};
use compliance_core::sbom_docs::{self, MachinePart};
/// An SBOM entry of target `target`.
fn entry(target: &str, name: &str, version: &str, purl: Option<&str>) -> SbomEntry {
let mut e = SbomEntry::new(target.into(), name.into(), version.into(), "npm".into());
e.purl = purl.map(String::from);
e
}
/// A controller made in-house (`t1`) and a drive bought in (`t2`), sharing
/// lodash; the drive's vendor blob has no purl.
fn machine() -> (Vec<MachinePart<'static>>, Vec<SbomEntry>) {
let parts = vec![
MachinePart {
id: "t1",
name: "Steuerung",
kind: "firmware",
supplier: "Example Maschinenbau",
version: None,
},
// Named like the machine: the refs must still be unique.
MachinePart {
id: "t2",
name: "Packing Line",
kind: "firmware",
supplier: "Example Drives GmbH",
version: Some("4.2.1"),
},
];
let mut lodash = entry("t1", "lodash", "4.17.20", Some("pkg:npm/lodash@4.17.20"));
lodash.known_vulnerabilities = vec![VulnRef {
id: "CVE-2021-23337".into(),
source: "osv".into(),
severity: Some("high".into()),
url: None,
exploitation: None,
aliases: Vec::new(),
}];
let entries = vec![
lodash,
entry("t1", "zlib", "1.2.11", Some("pkg:generic/zlib@1.2.11")),
entry("t2", "lodash", "4.17.20", Some("pkg:npm/lodash@4.17.20")),
entry("t2", "vendor-blob", "2.0", None),
];
(parts, entries)
}
#[test]
fn a_machines_sbom_names_its_parts_with_their_suppliers_and_is_valid() {
let (parts, entries) = machine();
let doc = sbom_docs::machine_cyclonedx("Packing Line", "p1", &parts, &entries);
let errors = common::cyclonedx_errors(&doc);
assert!(errors.is_empty(), "{errors:#?}");
assert_eq!(doc["metadata"]["component"]["type"], "device");
assert_eq!(doc["metadata"]["component"]["name"], "Packing Line");
let components = doc["components"].as_array().unwrap();
// The parts first, each with its supplier; the drive with its version.
assert_eq!(components[0]["name"], "Steuerung");
assert_eq!(components[0]["supplier"]["name"], "Example Maschinenbau");
assert!(components[0]["version"].is_string());
assert_eq!(components[1]["supplier"]["name"], "Example Drives GmbH");
assert_eq!(components[1]["version"], "4.2.1");
// lodash, in both parts, is listed once.
let lodash = components
.iter()
.filter(|c| c["purl"] == "pkg:npm/lodash@4.17.20")
.count();
assert_eq!(lodash, 1);
assert_eq!(components.len(), 2 + 3);
}
#[test]
fn every_ref_of_a_machines_sbom_is_unique_and_every_dependency_resolves() {
let (parts, entries) = machine();
let doc = sbom_docs::machine_cyclonedx("Packing Line", "p1", &parts, &entries);
let machine_ref = doc["metadata"]["component"]["bom-ref"].as_str().unwrap();
let mut refs = HashSet::from([machine_ref]);
for c in doc["components"].as_array().unwrap() {
assert!(refs.insert(c["bom-ref"].as_str().unwrap()), "{c}");
}
let depends = |r: &str| -> Vec<&str> {
doc["dependencies"]
.as_array()
.unwrap()
.iter()
.find(|d| d["ref"] == r)
.and_then(|d| d["dependsOn"].as_array())
.map(|list| list.iter().map(|v| v.as_str().unwrap()).collect())
.unwrap_or_default()
};
for d in doc["dependencies"].as_array().unwrap() {
assert!(refs.contains(d["ref"].as_str().unwrap()), "{d}");
for on in d["dependsOn"].as_array().into_iter().flatten() {
assert!(refs.contains(on.as_str().unwrap()), "{on}");
}
}
// The machine depends on its parts, each part on its own components.
assert_eq!(
depends(machine_ref),
["urn:pruefwerk:target:t1", "urn:pruefwerk:target:t2"]
);
assert_eq!(
depends("urn:pruefwerk:target:t2"),
["npm:vendor-blob@2.0", "pkg:npm/lodash@4.17.20"]
);
// A vulnerability points at the shared component.
assert_eq!(
doc["vulnerabilities"][0]["affects"][0]["ref"],
"pkg:npm/lodash@4.17.20"
);
}
-37
View File
@@ -1,37 +0,0 @@
//! The SBOM a supplier workspace releases to a customer workspace (#1028):
//! valid against CycloneDX 1.6.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use compliance_core::models::{ComponentHash, SbomEntry};
use compliance_core::sbom_docs::{self, ReleasedProduct};
#[test]
fn a_released_sbom_is_valid_cyclonedx() {
let mut sdk = SbomEntry::new("t".into(), "pump-sdk".into(), "4.2".into(), "nuget".into());
sdk.purl = Some("pkg:nuget/pump-sdk@4.2".into());
sdk.license = Some("MIT".into());
sdk.hashes = vec![ComponentHash {
alg: "SHA-256".into(),
content: "ab".repeat(32),
}];
// No purl: listed by its name and version.
let blob = SbomEntry::new(
"t".into(),
"vendor-blob".into(),
"7".into(),
"supplier".into(),
);
let product = ReleasedProduct {
name: "DR-4 Firmware",
version: "1.4.0",
supplier: "Test Antriebstechnik",
};
let doc = sbom_docs::released_cyclonedx(&[sdk, blob], &product);
assert_eq!(common::cyclonedx_errors(&doc), Vec::<String>::new());
assert_eq!(doc["components"].as_array().unwrap().len(), 2);
}
+26 -2
View File
@@ -12,8 +12,32 @@ use compliance_core::models::{
use compliance_core::sbom_docs;
use compliance_core::vex_docs::{self, VexInput};
mod common;
use common::{cyclonedx_errors, schema};
fn schema(name: &str) -> serde_json::Value {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("schemas")
.join(name);
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}
/// The errors of `doc` against CycloneDX 1.6 (with the SPDX and JSF schemas
/// it refers to).
fn cyclonedx_errors(doc: &serde_json::Value) -> Vec<String> {
let validator = jsonschema::options()
.with_resource(
"http://cyclonedx.org/schema/spdx.schema.json",
jsonschema::Resource::from_contents(schema("spdx.schema.json")).unwrap(),
)
.with_resource(
"http://cyclonedx.org/schema/jsf-0.82.schema.json",
jsonschema::Resource::from_contents(schema("jsf-0.82.schema.json")).unwrap(),
)
.build(&schema("bom-1.6.schema.json"))
.unwrap();
validator
.iter_errors(doc)
.map(|e| format!("{} at {}", e, e.instance_path))
.collect()
}
/// The errors of `doc` against CSAF 2.0 (with the CVSS schemas it refers to).
fn csaf_errors(doc: &serde_json::Value) -> Vec<String> {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "compliance-dashboard"
version = "0.4.17"
version = "0.4.16"
edition = "2021"
default-run = "compliance-dashboard"
File diff suppressed because it is too large. Load diff
+2 -35
View File
@@ -17,14 +17,8 @@ pub enum Route {
HeutePage { target: String, bucket: String },
#[route("/overview")]
OverviewPage {},
// The supply chain as a graph the customer arranges (#1050).
#[route("/supply-chain")]
SupplyChainPage {},
#[route("/targets")]
TargetsPage {},
// What connected suppliers offer the workspace (#1028).
#[route("/supplier-offers")]
SupplierOffersPage {},
#[route("/targets/:id")]
TargetPage { id: String },
// The target's views (#957), one tab each (`findings`, `cves`,
@@ -44,18 +38,8 @@ pub enum Route {
},
#[route("/targets/:id/compliance")]
CompliancePage { id: String },
// Where the target's SBOM goes: its releases to connected customers
// and its published versions (#1028).
#[route("/targets/:id/releases")]
TargetReleasesPage { id: String },
// A machine (#1026): a product project and its targets; `?tab=`
// `parts` (the default), `cves` or `history`.
#[route("/projects/:id?:tab")]
MachinePage { id: String, tab: String },
// `?origin=bought` opens the wizard for a component bought in from a
// supplier, `own` (or nothing) for the workspace's own.
#[route("/onboard?:origin")]
OnboardingPage { origin: String },
#[route("/onboard")]
OnboardingPage {},
// `?target=<id>` opens the list filtered to one target; a chart of
// the findings view (#957) adds its type, severity or folder. The
// target comes last: the router writes a `&` after each argument
@@ -134,14 +118,6 @@ impl Route {
}
}
/// The onboarding wizard; `origin` `bought` preselects a component
/// bought in from a supplier.
pub fn onboarding(origin: &str) -> Self {
Self::OnboardingPage {
origin: origin.to_string(),
}
}
/// The findings list of target `target` (of all targets when empty),
/// without a chart's filters.
pub fn findings(target: String) -> Self {
@@ -197,15 +173,6 @@ mod tests {
Ok(Route::OverviewPage {})
));
assert_eq!(Route::OverviewPage {}.to_string(), "/overview");
// The wizard opens for a bought-in component with `?origin=bought`.
assert_eq!(
Route::from_str("/onboard?origin=bought").ok(),
Some(Route::onboarding("bought"))
);
assert_eq!(
Route::from_str("/onboard").ok(),
Some(Route::onboarding(""))
);
}
#[test]
@@ -1,28 +1,21 @@
//! Add a file (an archive, a PLC project, a firmware image, a supplier SBOM)
//! to an existing target: upload it at once, with its archive password if it
//! has one.
//! Add a file (an archive, a PLC project, a firmware image) to an existing
//! target: upload it at once, with its archive password if it has one.
use dioxus::prelude::*;
use crate::i18n::texts::{common, kinds, onboarding as otx, targets as tx};
use crate::i18n::use_lang;
use crate::infrastructure::onboarding::{
is_file_kind, may_need_password, plc_format_for, set_archive_password,
trigger_new_content_scan, upload_problem, upload_target_artifact, ArchivePassword,
PasswordOutcome,
is_file_kind, plc_format_for, set_archive_password, trigger_new_content_scan,
upload_target_artifact, ArchivePassword, PasswordOutcome, UNSUPPORTED_ARCHIVE,
};
/// The upload row for target `target_id`, starting with file kind `kind`;
/// `on_uploaded` runs once the file (and its password, if it needs one) is
/// stored.
/// The upload row for target `target_id`; `on_uploaded` runs once the file
/// (and its password, if it needs one) is stored.
#[component]
pub fn ArtifactUpload(
target_id: String,
#[props(default = "source_archive")] kind: &'static str,
on_uploaded: EventHandler<()>,
) -> Element {
pub fn ArtifactUpload(target_id: String, on_uploaded: EventHandler<()>) -> Element {
let lang = use_lang()();
let mut kind = use_signal(|| kind.to_string());
let mut kind = use_signal(|| "source_archive".to_string());
let mut plc_format = use_signal(|| "plcopen_xml".to_string());
let mut file = use_signal(|| Option::<dioxus::html::FileData>::None);
let mut password = use_signal(String::new);
@@ -71,8 +64,8 @@ pub fn ArtifactUpload(
}
}
}
// Firmware images, build outputs and SBOMs are never unpacked.
if may_need_password(&kind()) {
// Firmware images and build outputs are never unpacked.
if kind() != "firmware_image" && kind() != "build_output" {
div { class: "form-group artifact-upload-password",
label { {common::ARCHIVE_PASSWORD.get(lang)} }
input {
@@ -96,12 +89,10 @@ pub fn ArtifactUpload(
let result = match upload_target_artifact(id.clone(), kind, format, picked.into()).await {
Err(e) => {
let e = e.to_string();
let problem = upload_problem(e.clone(), lang);
// The agent's own words follow "upload failed".
Err(if problem == e {
format!("{}: {e}", otx::UPLOAD_FAILED.get(lang))
Err(if e.contains(UNSUPPORTED_ARCHIVE) {
common::UNSUPPORTED_ARCHIVE.get(lang).to_string()
} else {
problem
format!("{}: {e}", otx::UPLOAD_FAILED.get(lang))
})
}
Ok(resp) => {
+1 -15
View File
@@ -41,8 +41,6 @@ pub fn Sidebar() -> Element {
let lang = use_lang()();
let can_write = use_can_write();
// Open supplier offers, counted on "Prüfobjekte" (#1028).
let open_offers = crate::pages::offers::use_open_offers();
let nav_items = [
NavItem {
label: nav::OVERVIEW,
@@ -51,13 +49,6 @@ pub fn Sidebar() -> Element {
runtime_only: false,
write_only: false,
},
NavItem {
label: nav::SUPPLY_CHAIN,
route: Route::SupplyChainPage {},
icon: rsx! { Icon { icon: BsDiagram3, width: 18, height: 18 } },
runtime_only: false,
write_only: false,
},
NavItem {
label: nav::TARGETS,
route: Route::TargetsPage {},
@@ -67,7 +58,7 @@ pub fn Sidebar() -> Element {
},
NavItem {
label: nav::ONBOARD,
route: Route::onboarding(""),
route: Route::OnboardingPage {},
icon: rsx! { Icon { icon: BsPlusCircle, width: 18, height: 18 } },
runtime_only: false,
write_only: true,
@@ -187,8 +178,6 @@ pub fn Sidebar() -> Element {
(Route::SbomPage { .. }, Route::SbomPage { .. }) => true,
(Route::SbomEcosystemPage { .. }, Route::SbomPage { .. }) => true,
(Route::CompliancePage { .. }, Route::TargetsPage {}) => true,
(Route::TargetReleasesPage { .. }, Route::TargetsPage {}) => true,
(Route::SupplierOffersPage {}, Route::TargetsPage {}) => true,
(Route::DastTargetsPage {}, Route::DastOverviewPage {}) => true,
(Route::DastFindingsPage {}, Route::DastOverviewPage {}) => true,
(Route::DastFindingDetailPage { .. }, Route::DastOverviewPage {}) => true,
@@ -233,9 +222,6 @@ pub fn Sidebar() -> Element {
if !collapsed() {
span { "{label}" }
}
if let Some(n) = (item.route == Route::TargetsPage {}).then_some(open_offers).flatten().filter(|n| *n > 0) {
span { class: "nav-count", title: crate::i18n::texts::offers::waiting(n, lang), "{n}" }
}
}
}
}
+17 -267
View File
@@ -12,7 +12,7 @@ use dioxus_free_icons::Icon;
use compliance_core::cve_groups::{CveGroup, CveSeverity, PackageKey};
use compliance_core::cve_matrix::CveFilter;
use compliance_core::models::{CveAlert, SupplierVex, VexAssessment, VexJustification, VexStatus};
use compliance_core::models::{CveAlert, VexAssessment, VexJustification, VexStatus};
use compliance_core::vex_docs::status_of;
use crate::components::no_access::use_can_write;
@@ -43,7 +43,7 @@ const JUSTIFICATIONS: [VexJustification; 5] = [
VexJustification::InlineMitigationsAlreadyExist,
];
pub(crate) fn status_text(status: VexStatus) -> Text {
fn status_text(status: VexStatus) -> Text {
match status {
VexStatus::UnderInvestigation => tx::UNDER_INVESTIGATION,
VexStatus::Affected => tx::AFFECTED,
@@ -53,7 +53,7 @@ pub(crate) fn status_text(status: VexStatus) -> Text {
}
/// The badge class of a status: red for affected, green for settled.
pub(crate) fn status_class(status: VexStatus) -> &'static str {
fn status_class(status: VexStatus) -> &'static str {
match status {
VexStatus::UnderInvestigation => "badge badge-neutral",
VexStatus::Affected => "badge badge-danger",
@@ -99,89 +99,6 @@ fn missing(statement: &VexStatementDto) -> Option<Text> {
}
}
/// The justification a supplier's CycloneDX `justification` stands for, where
/// the two mean the same; `None` leaves the choice to the person.
fn justification_of_supplier(cyclonedx: &str) -> Option<VexJustification> {
match cyclonedx {
"code_not_present" => Some(VexJustification::VulnerableCodeNotPresent),
"code_not_reachable" => Some(VexJustification::VulnerableCodeNotInExecutePath),
_ => None,
}
}
/// A supplier's CycloneDX justification in words, else as written.
fn supplier_justification_words(value: &str, lang: Lang) -> String {
tx::supplier_justification(value).map_or_else(|| value.to_string(), |t| t.get(lang).to_string())
}
/// A supplier's CycloneDX responses in words, else as written.
fn supplier_response_words(responses: &[String], lang: Lang) -> String {
responses
.iter()
.map(|r| tx::supplier_response(r).map_or_else(|| r.clone(), |t| t.get(lang).to_string()))
.collect::<Vec<_>>()
.join(", ")
}
/// The short reason a supplier gives, for the table: its justification,
/// else its own words when they are short, else what it says to do.
pub(crate) fn supplier_gist(vex: &SupplierVex, lang: Lang) -> String {
/// Longer words are left for the statement's panel.
const SHORT: usize = 60;
match (&vex.justification, vex.detail.as_deref().map(str::trim)) {
(Some(j), _) => supplier_justification_words(j, lang),
(None, Some(detail)) if !detail.is_empty() && detail.chars().count() <= SHORT => {
detail.to_string()
}
(None, _) => supplier_response_words(&vex.response, lang),
}
}
/// The form a supplier's statement fills in, as (status, justification,
/// impact statement, action statement): the supplier's words, marked as
/// theirs, in the field its status asks for. Nothing is stored by this.
fn copied_from_supplier(
vex: &SupplierVex,
lang: Lang,
) -> (VexStatus, Option<VexJustification>, String, String) {
let words = vex
.detail
.clone()
.filter(|d| !d.trim().is_empty())
.unwrap_or_else(|| supplier_gist(vex, lang));
let text = if words.trim().is_empty() {
String::new()
} else {
format!("{}: {words}", tx::PER_SUPPLIER.get(lang))
};
let (impact, action) = match vex.status {
VexStatus::NotAffected => (text, String::new()),
VexStatus::Affected => (String::new(), text),
VexStatus::UnderInvestigation | VexStatus::Fixed => (String::new(), String::new()),
};
let justification = vex
.justification
.as_deref()
.and_then(justification_of_supplier)
.filter(|_| vex.status == VexStatus::NotAffected);
(vex.status, justification, impact, action)
}
/// Whether an alert is about the bought-in product itself: a supplier's own
/// advisory matches the product by its name and version, which has no purl,
/// and its components by purl (#1025).
pub(crate) fn is_supplier_product(alert: &CveAlert) -> bool {
alert.purl.is_none()
&& alert
.advisories
.iter()
.any(|a| a.provider.starts_with(SUPPLIER_PROVIDER_PREFIX))
}
/// The prefix of a supplier provider's key in an advisory reference, as the
/// agent stores it (`csaf_feed::SUPPLIER_PREFIX`).
pub(crate) const SUPPLIER_PROVIDER_PREFIX: &str = "supplier:";
/// Who made an alert's statement: the person's name, "Prüfung" for a scan.
fn stated_by(alert: &CveAlert, lang: Lang) -> String {
match &alert.vex {
@@ -221,21 +138,10 @@ pub fn VexPanel(target_id: String, #[props(default)] filter: Option<CveFilter>)
groups.restart();
};
let candidates = enisa.read().clone().unwrap_or_default();
let supplier_states = alerts
.read()
.as_ref()
.and_then(|a| a.as_ref())
.is_some_and(|list| list.iter().any(|a| a.supplier_vex.is_some()));
rsx! {
div { class: "vex-head",
p { class: "target-muted",
{tx::HINT.get(lang)}
if supplier_states {
" "
{tx::SUPPLIER_HINT.get(lang)}
}
}
p { class: "target-muted", {tx::HINT.get(lang)} }
div { class: "vex-exports",
for format in [VexFormat::OpenVex, VexFormat::CycloneDx] {
VexExportButton { target_id: target_id.clone(), format }
@@ -410,9 +316,6 @@ fn CveTable(
let lang = use_lang()();
let can_write = use_can_write();
let mut editing = use_signal(|| Option::<String>::None);
// The supplier's column only where a supplier states something (#1025).
let supplier = alerts.iter().any(|a| a.supplier_vex.is_some());
let columns = if supplier { "7" } else { "6" };
rsx! {
div { class: "table-wrapper",
table { class: "vex-table",
@@ -423,10 +326,7 @@ fn CveTable(
th { {tx::SEVERITY.get(lang)} }
th { {tx::STATUS.get(lang)} }
th { {tx::STATED_BY.get(lang)} }
if supplier {
th { {tx::SUPPLIER_SAYS.get(lang)} }
}
th { span { class: "sr-only", {tx::ACTIONS.get(lang)} } }
th {}
}
}
tbody {
@@ -438,54 +338,29 @@ fn CveTable(
let edit_id = alert_id.clone();
let current = alert.vex.clone().filter(|v| !v.by_scan);
let initial = current.as_ref().map_or(status, |v| v.status);
let supplier_product = is_supplier_product(alert);
rsx! {
tr { key: "{alert_id}", class: if open { "is-open" } else { "" },
tr { key: "{alert_id}",
td {
code { "{alert.cve_id}" }
// The vendor advisories that name it (#515), linked as
// their terms ask; the remediation on hover.
for adv in alert.advisories.iter() {
div { class: "vex-advisory-line",
a {
class: "vex-advisory",
href: adv.url.clone().unwrap_or_default(),
target: "_blank",
rel: "noopener noreferrer",
title: adv.remediation.clone().unwrap_or_else(|| adv.title.clone()),
"{adv.id}"
}
if adv.provider.starts_with(SUPPLIER_PROVIDER_PREFIX) {
" "
span { class: "vex-advisory-note", {tx::SUPPLIER_ADVISORY.get(lang)} }
}
a {
class: "vex-advisory",
href: adv.url.clone().unwrap_or_default(),
target: "_blank",
rel: "noopener noreferrer",
title: adv.remediation.clone().unwrap_or_else(|| adv.title.clone()),
"{adv.id}"
}
}
}
td {
"{alert.affected_package} {alert.affected_version}"
if supplier_product {
div { class: "vex-advisory-note", {tx::SUPPLIER_PRODUCT.get(lang)} }
}
}
td { "{alert.affected_package} {alert.affected_version}" }
// The severity the groups count it with (#949): the
// advisory's rating, else its CVSS score, else info.
td { SeverityBadge { severity: CveSeverity::of(alert).as_str().to_string() } }
td { span { class: status_class(status), {status_text(status).get(lang)} } }
td { class: "target-muted", "{stated_by(alert, lang)}" }
if supplier {
td {
match &alert.supplier_vex {
Some(vex) => rsx! {
span { class: "vex-supplier-pill",
span { class: status_class(vex.status), {status_text(vex.status).get(lang)} }
"{supplier_gist(vex, lang)}"
}
},
None => rsx! { span { class: "target-muted", "—" } },
}
}
}
td {
if can_write && !open {
button {
@@ -501,11 +376,10 @@ fn CveTable(
}
if open {
tr { class: "vex-editor-row",
td { colspan: columns,
td { colspan: "6",
VexEditor {
current,
initial,
supplier: alert.supplier_vex.clone(),
save: SaveTo::Alert(alert_id.clone()),
on_close: move |saved: bool| {
editing.set(None);
@@ -523,9 +397,6 @@ fn CveTable(
}
}
}
if supplier {
p { class: "target-muted vex-footnote", {tx::SUPPLIER_FOOTNOTE.get(lang)} }
}
}
}
@@ -735,14 +606,12 @@ impl SaveTo {
}
/// The statement editor, starting from `current` (a person's statement, if
/// any) with status `initial`, for one alert or a whole group. With the
/// `supplier`'s statement, that is shown beside it and can be copied into the
/// form (#1025). `on_close` gets whether a statement was saved.
/// any) with status `initial`, for one alert or a whole group. `on_close`
/// gets whether a statement was saved.
#[component]
fn VexEditor(
current: Option<VexAssessment>,
initial: VexStatus,
#[props(default)] supplier: Option<SupplierVex>,
save: SaveTo,
on_close: EventHandler<bool>,
) -> Element {
@@ -776,46 +645,6 @@ fn VexEditor(
let blocked = missing(&statement);
rsx! {
div { class: if supplier.is_some() { "vex-editor-with-supplier" } else { "" },
if let Some(vex) = supplier.clone() {
div { class: "vex-supplier-card",
span { class: "vex-supplier-label", {tx::SUPPLIER_STATEMENT.get(lang)} }
div { class: "vex-supplier-status",
span { class: status_class(vex.status), {status_text(vex.status).get(lang)} }
span { class: "target-muted",
if let Some(j) = &vex.justification {
"{tx::SUPPLIER_JUSTIFICATION.get(lang)}: {supplier_justification_words(j, lang)}"
}
if vex.justification.is_some() && !vex.response.is_empty() { " · " }
if !vex.response.is_empty() {
"{tx::SUPPLIER_RESPONSE.get(lang)}: {supplier_response_words(&vex.response, lang)}"
}
}
}
if let Some(detail) = vex.detail.as_deref().filter(|d| !d.trim().is_empty()) {
div { "„{detail}“" }
}
div { class: "target-muted",
"{tx::SUPPLIER_FROM.get(lang)} "
code { "{vex.source}" }
" · {tx::SUPPLIER_REREAD.get(lang)}"
}
div {
button {
class: "btn btn-secondary btn-sm",
onclick: move |_| {
let (s, j, i, a) = copied_from_supplier(&vex, lang);
status.set(s);
justification.set(j);
impact.set(i);
action.set(a);
},
{tx::COPY_SUPPLIER.get(lang)}
}
}
p { class: "target-muted", {tx::COPY_SUPPLIER_HINT.get(lang)} }
}
}
div { class: "vex-editor",
label {
{tx::STATUS.get(lang)}
@@ -884,7 +713,6 @@ fn VexEditor(
}
}
}
}
}
}
@@ -988,84 +816,6 @@ mod tests {
assert_eq!(reportable_candidate(&candidates, "a3"), None);
}
fn supplier(
state: VexStatus,
justification: Option<&str>,
detail: Option<&str>,
) -> SupplierVex {
SupplierVex {
status: state,
state: String::new(),
justification: justification.map(String::from),
detail: detail.map(String::from),
response: vec!["will_not_fix".into()],
source: "drive-control.cdx.json".into(),
}
}
#[test]
fn a_suppliers_statement_fills_the_form_as_theirs() {
let not_affected = supplier(
VexStatus::NotAffected,
Some("code_not_reachable"),
Some("template() is never called."),
);
assert_eq!(
copied_from_supplier(&not_affected, Lang::De),
(
VexStatus::NotAffected,
Some(VexJustification::VulnerableCodeNotInExecutePath),
"Laut Lieferant: template() is never called.".to_string(),
String::new(),
)
);
// A justification without an equal is left for the person; the
// supplier's words still give the reason.
let configured = supplier(VexStatus::NotAffected, Some("requires_configuration"), None);
let (_, justification, impact, _) = copied_from_supplier(&configured, Lang::En);
assert_eq!(justification, None);
assert_eq!(impact, "Per the supplier: Requires a configuration");
assert_eq!(
missing(&VexStatementDto {
status: VexStatus::NotAffected,
justification,
impact_statement: Some(impact),
action_statement: None,
}),
None
);
let short = supplier(VexStatus::Affected, None, Some("Update auf 4.3.0"));
assert_eq!(supplier_gist(&short, Lang::De), "Update auf 4.3.0");
// Affected: what to do goes where the agent asks for it.
let affected = supplier(VexStatus::Affected, None, None);
let (status, _, impact, action) = copied_from_supplier(&affected, Lang::De);
assert_eq!(status, VexStatus::Affected);
assert!(impact.is_empty());
assert_eq!(action, "Laut Lieferant: Wird nicht behoben");
}
#[test]
fn a_supplier_advisory_on_a_component_without_purl_is_about_the_product() {
let mut alert: CveAlert = serde_json::from_value(serde_json::json!({
"cve_id": "CVE-2026-90001", "repo_id": "t", "affected_package": "Drive Control",
"affected_version": "4.2.1", "source": "osv", "created_at": "2026-11-16T00:00:00Z",
"references": [], "severity": null, "cvss_score": null, "summary": null,
"llm_impact_summary": null,
}))
.unwrap();
assert!(!is_supplier_product(&alert));
alert.advisories.push(compliance_core::models::AdvisoryRef {
provider: "supplier:https://psirt.example/provider-metadata.json".into(),
id: "BAT-2026-0007".into(),
title: String::new(),
url: None,
remediation: None,
});
assert!(is_supplier_product(&alert));
alert.purl = Some("pkg:npm/lodash@4.17.20".into());
assert!(!is_supplier_product(&alert));
}
#[test]
fn options_round_trip_through_their_wire_names() {
for s in STATUSES {
-9
View File
@@ -70,15 +70,6 @@ impl Text {
}
}
/// The agent's refusal code in a server function's error message: the
/// first word of `error` that is one of `codes`, as in
/// `error running server function: label_taken (409) (details: None)`.
pub fn agent_code<'a>(error: &str, codes: &[&'a str]) -> Option<&'a str> {
error
.split(|c: char| !(c.is_ascii_lowercase() || c == '_'))
.find_map(|word| codes.iter().copied().find(|code| *code == word))
}
/// A byte count for people: `12,3 MB` in German, `12.3 MB` in English.
pub fn format_bytes(bytes: u64, lang: Lang) -> String {
const UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"];
File diff suppressed because it is too large. Load diff
@@ -66,26 +66,6 @@ pub async fn json_or_error<T: serde::de::DeserializeOwned>(
.map_err(|e| ServerFnError::new(e.to_string()))
}
/// The `data` of the agent's answer to `req`, its usual envelope.
///
/// # Errors
///
/// An unreachable agent, or its refusal (as for [`json_or_error`]).
pub async fn data<T: serde::de::DeserializeOwned>(
req: reqwest::RequestBuilder,
) -> Result<T, ServerFnError> {
#[derive(serde::Deserialize)]
struct Body<T> {
data: T,
}
let resp = req
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let body: Body<T> = json_or_error(resp).await?;
Ok(body.data)
}
/// The response itself when the agent accepted the request, else the refusal
/// (as for [`json_or_error`]); for a body the caller streams on.
///
@@ -1,120 +0,0 @@
//! A machine (#1026): a product project and the targets it is made of,
//! read from the agent's `/api/v1/projects/{id}/…` endpoints.
use chrono::{DateTime, Utc};
use compliance_core::cve_groups::{CveGroup, SeverityCounts};
use compliance_core::models::CveAlert;
use compliance_core::scan_changes::ScanChange;
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
use super::onboarding::SupplierDto;
/// One part of a machine, as its overview lists it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PartDto {
/// The target's id.
pub id: String,
pub name: String,
/// The target type's wire name (`firmware_rtos`).
pub target_type: String,
/// Its supplier, for a component bought in.
#[serde(default)]
pub supplier: Option<SupplierDto>,
/// Its open CVEs per severity.
pub open: SeverityCounts,
/// When it was last scanned.
#[serde(default)]
pub last_scan_at: Option<DateTime<Utc>>,
}
/// The advisories of a machine's suppliers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MachineAdvisoriesDto {
pub advisories: u64,
pub providers: usize,
#[serde(default)]
pub checked_at: Option<DateTime<Utc>>,
}
/// A machine at a glance (`GET /api/v1/projects/{id}/overview`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MachineOverviewDto {
pub name: String,
pub parts: Vec<PartDto>,
pub open: SeverityCounts,
pub undecided: usize,
pub undecided_with_supplier: usize,
pub components: u64,
pub shared_components: u64,
#[serde(default)]
pub advisories: Option<MachineAdvisoriesDto>,
}
impl MachineOverviewDto {
/// The part with target id `id`.
pub fn part(&self, id: &str) -> Option<&PartDto> {
self.parts.iter().find(|p| p.id == id)
}
}
/// A machine's open CVEs (`GET /api/v1/projects/{id}/cves`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MachineCvesDto {
pub groups: Vec<CveGroup>,
pub alerts: Vec<CveAlert>,
}
/// One scan of one of a machine's parts.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MachineChangeDto {
/// The part (its target's id).
pub part: String,
#[serde(flatten)]
pub change: ScanChange,
}
/// The `data` of an agent answer at `path`.
#[cfg(feature = "server")]
async fn data<T: serde::de::DeserializeOwned>(path: &str) -> Result<T, ServerFnError> {
#[derive(Deserialize)]
struct Body<T> {
data: T,
}
let resp = super::agent_client::agent_get(path)
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let body: Body<T> = super::agent_client::json_or_error(resp).await?;
Ok(body.data)
}
/// Machine `id` at a glance.
#[server]
pub async fn fetch_machine_overview(id: String) -> Result<MachineOverviewDto, ServerFnError> {
data(&format!("/api/v1/projects/{id}/overview")).await
}
/// Machine `id`'s open CVEs, grouped by component across its parts.
#[server]
pub async fn fetch_machine_cves(id: String) -> Result<MachineCvesDto, ServerFnError> {
data(&format!("/api/v1/projects/{id}/cves")).await
}
/// Machine `id`'s history: its parts' last scans, newest first.
#[server]
pub async fn fetch_machine_changes(id: String) -> Result<Vec<MachineChangeDto>, ServerFnError> {
data(&format!("/api/v1/projects/{id}/scan-changes")).await
}
/// Machine `id`'s SBOM, a CycloneDX document to save.
#[server]
pub async fn fetch_machine_sbom(id: String) -> Result<serde_json::Value, ServerFnError> {
let resp = super::agent_client::agent_get(&format!("/api/v1/projects/{id}/sbom"))
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
super::agent_client::json_or_error(resp).await
}
@@ -14,25 +14,21 @@ pub mod graph;
pub mod help_chat;
pub mod inbox;
pub mod issues;
pub mod machine;
pub mod manual_findings;
pub mod mcp;
pub mod mcp_tokens;
pub mod metering;
pub mod notifications;
pub mod offers;
pub mod onboarding;
pub mod pentest;
pub mod platform;
pub mod projects;
pub mod releases;
#[allow(clippy::too_many_arguments)]
pub mod sbom;
pub mod sbom_ecosystems;
pub mod scan_changes;
pub mod scans;
pub mod stats;
pub mod supply_chain;
pub mod support;
pub mod vex;
@@ -1,122 +0,0 @@
//! SBOM releases connected suppliers offer the workspace (#1028), the
//! customer's side: the agent's `/api/v1/sbom-offers`.
use chrono::{DateTime, Utc};
use compliance_core::models::TargetType;
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
/// Where an offer stands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OfferState {
/// Waiting for the workspace's answer.
Offered,
/// Accepted: each version arrives in its component.
Accepted,
Declined,
/// The supplier ended the release, the connection ended, or the
/// component was deleted.
Ended,
}
/// One supplier's offer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OfferDto {
pub id: String,
/// The supplier workspace's display name.
pub supplier_name: String,
pub product_name: String,
pub product_type: TargetType,
pub state: OfferState,
/// The component it was accepted into.
#[serde(default)]
pub target_id: Option<String>,
pub offered_at: DateTime<Utc>,
#[serde(default)]
pub ended_at: Option<DateTime<Utc>>,
/// The version last delivered, and when.
#[serde(default)]
pub delivered_label: Option<String>,
#[serde(default)]
pub delivered_at: Option<DateTime<Utc>>,
/// While open: the version accepting delivers at once.
#[serde(default)]
pub offered_label: Option<String>,
#[serde(default)]
pub offered_components: Option<i64>,
}
/// Where an accepted offer goes: an existing supplier component, or a new
/// one with its name and projects. Unset fields are left out (and read back
/// as unset: it also crosses to the server function this way).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Destination {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub project_ids: Vec<String>,
}
/// The workspace's offers, open ones first.
#[server]
pub async fn fetch_offers() -> Result<Vec<OfferDto>, ServerFnError> {
super::agent_client::data(super::agent_client::agent_get("/api/v1/sbom-offers").await?).await
}
/// Accept offer `id` into `to`.
#[server]
pub async fn accept_offer(id: String, to: Destination) -> Result<OfferDto, ServerFnError> {
let req = super::agent_client::agent_request(
reqwest::Method::POST,
&format!("/api/v1/sbom-offers/{id}/accept"),
)
.await?
.json(&to);
super::agent_client::data(req).await
}
/// Decline offer `id`.
#[server]
pub async fn decline_offer(id: String) -> Result<OfferDto, ServerFnError> {
let req = super::agent_client::agent_request(
reqwest::Method::POST,
&format!("/api/v1/sbom-offers/{id}/decline"),
)
.await?
.json(&serde_json::json!({}));
super::agent_client::data(req).await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_agents_offers_read() {
let offers: Vec<OfferDto> = serde_json::from_value(serde_json::json!([{
"id": "o1", "supplier_name": "Test Antriebstechnik", "product_name": "DR-4 Firmware",
"product_type": "firmware_rtos", "state": "offered", "target_id": null,
"offered_at": "2026-11-19T09:00:00Z", "decided_at": null, "ended_at": null,
"delivered_label": null, "delivered_at": null,
"offered_label": "1.4.0", "offered_components": 214
}]))
.expect("readable");
assert_eq!(offers[0].state, OfferState::Offered);
assert_eq!(offers[0].offered_components, Some(214));
}
#[test]
fn a_destination_names_only_what_is_set() {
let existing = Destination {
target_id: Some("t1".into()),
..Default::default()
};
let sent = serde_json::to_value(&existing).expect("serialisable");
assert_eq!(sent, serde_json::json!({ "target_id": "t1" }));
let read: Destination = serde_json::from_value(sent).expect("reads back");
assert_eq!(read, existing);
}
}
@@ -35,215 +35,6 @@ pub struct ArtifactInputDto {
/// set. Display only, never sent.
#[serde(skip)]
pub archive_password: ArchivePassword,
/// What the upload kept of a supplier SBOM. Display only, never sent.
#[serde(skip)]
pub sbom: Option<SbomSummary>,
/// When the file was uploaded. Display only, never sent.
#[serde(skip)]
pub uploaded_at: Option<chrono::DateTime<chrono::Utc>>,
}
/// A moment as the agent returns it: BSON extended JSON
/// (`{"$date": {"$numberLong": "…"}}`) or an RFC 3339 string.
pub fn agent_time(value: &serde_json::Value) -> Option<chrono::DateTime<chrono::Utc>> {
if let Some(text) = value.as_str().or_else(|| value["$date"].as_str()) {
return chrono::DateTime::parse_from_rfc3339(text)
.ok()
.map(|t| t.with_timezone(&chrono::Utc));
}
let millis = value["$date"]["$numberLong"].as_str()?.parse().ok()?;
chrono::DateTime::from_timestamp_millis(millis)
}
/// An upload error in words: a refused supplier SBOM by its code, a 7z or
/// rar archive as such, anything else as the agent said it.
pub fn upload_problem(error: String, lang: Lang) -> String {
use crate::i18n::texts::{common, onboarding};
if let Some(code) = sbom_refusal_code(&error) {
format!(
"{}: {}",
onboarding::REFUSED.get(lang),
onboarding::sbom_refusal(code, lang)
)
} else if error.contains(UNSUPPORTED_ARCHIVE) {
common::UNSUPPORTED_ARCHIVE.get(lang).to_string()
} else {
error
}
}
/// Who supplies a bought-in component (#1025), as the wizard and the target
/// editor send it. An empty `name` removes the supplier.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct SupplierDto {
/// The supplier's name.
pub name: String,
/// Its name for the product.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub product: Option<String>,
/// The product's version in use.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// Its CSAF provider's `provider-metadata.json`, an https URL.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub csaf_provider: Option<String>,
}
impl SupplierDto {
/// The supplier of a stored target (as the agent returns it), if any.
pub fn of(target: &serde_json::Value) -> Option<Self> {
serde_json::from_value(target.get("supplier")?.clone()).ok()
}
/// The supplier from the form's fields: blank fields left out, so an
/// empty name stands for no supplier.
pub fn from_fields(name: &str, product: &str, version: &str, csaf_provider: &str) -> Self {
let filled = |v: &str| (!v.trim().is_empty()).then(|| v.trim().to_string());
Self {
name: name.trim().to_string(),
product: filled(product),
version: filled(version),
csaf_provider: filled(csaf_provider),
}
}
/// Whether the CSAF provider is unusable, as the agent would refuse it:
/// set, but not an https URL.
pub fn provider_is_invalid(csaf_provider: &str) -> bool {
let url = csaf_provider.trim();
!url.is_empty() && (!url.starts_with("https://") || url.contains(char::is_whitespace))
}
}
/// What a supplier SBOM holds (#1025), as the agent's check and an upload's
/// facts report it.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SbomSummary {
/// The format and version, such as `CycloneDX 1.5`.
pub format: String,
/// The components it lists.
pub components: usize,
/// The supplier's statements about their vulnerabilities.
pub statements: usize,
}
impl SbomSummary {
/// The summary an upload kept with a stored supplier SBOM; `None` for
/// one uploaded before it was kept.
pub fn of(artifact: &serde_json::Value) -> Option<Self> {
let facts = artifact["detected"].as_array()?;
let fact = |key: &str| {
facts
.iter()
.find(|f| f["key"] == key)
.and_then(|f| f["value"].as_str())
};
Some(Self {
format: fact("sbom_format")?.to_string(),
components: fact("sbom_components")?.parse().ok()?,
statements: fact("sbom_statements")?.parse().ok()?,
})
}
}
/// The agent's verdict on a supplier SBOM before any target holds it.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum SbomCheck {
/// A scan can read it.
Readable(SbomSummary),
/// Refused: the agent's code (`empty`, `unknown_format`, …), worded by
/// [`crate::i18n::texts::onboarding::sbom_refusal`].
Refused(String),
}
/// The marker an upload error carries for a refused supplier SBOM, followed
/// by the agent's code.
pub const SBOM_REFUSED: &str = "supplier_sbom_refused:";
/// The agent's code of a refused supplier SBOM upload, from its error: the
/// lowercase word after [`SBOM_REFUSED`], whatever the error wraps it in.
pub fn sbom_refusal_code(error: &str) -> Option<&str> {
let rest = &error[error.find(SBOM_REFUSED)? + SBOM_REFUSED.len()..];
let end = rest
.find(|c: char| !(c.is_ascii_lowercase() || c == '_'))
.unwrap_or(rest.len());
(end > 0).then(|| &rest[..end])
}
/// Check a supplier SBOM before any target holds it, **streamed** to the
/// agent as for [`upload_target_artifact`]; nothing is stored.
#[post("/api/supplier-sbom-check")]
pub async fn check_supplier_sbom(
file: dioxus::fullstack::FileStream,
) -> Result<SbomCheck, ServerFnError> {
let filename = file.file_name().to_string();
let part =
reqwest::multipart::Part::stream(reqwest::Body::wrap_stream(file)).file_name(filename);
let resp =
super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/supplier-sboms/check")
.await?
.multipart(reqwest::multipart::Form::new().part("file", part))
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
match resp.status().as_u16() {
200 => {
#[derive(Deserialize)]
struct Body {
data: SbomSummary,
}
let body: Body = resp
.json()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
Ok(SbomCheck::Readable(body.data))
}
413 => Ok(SbomCheck::Refused("too_large".to_string())),
422 => Ok(SbomCheck::Refused(refusal_code(resp).await)),
code => Err(ServerFnError::new(format!(
"the agent could not check the SBOM ({code})"
))),
}
}
/// The `code` of an agent's supplier SBOM refusal.
#[cfg(feature = "server")]
async fn refusal_code(resp: reqwest::Response) -> String {
resp.json::<serde_json::Value>()
.await
.ok()
.and_then(|b| b["code"].as_str().map(String::from))
.unwrap_or_else(|| "malformed".to_string())
}
/// How many of a target's supplier advisories are kept, and when its CSAF
/// provider was last read (#1025).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SupplierAdvisoriesDto {
/// The advisories kept for the workspace.
pub advisories: u64,
/// When the provider was last read; none before the first refresh.
pub checked_at: Option<chrono::DateTime<chrono::Utc>>,
/// Whether it could be read then; none before the first refresh.
pub reachable: Option<bool>,
}
/// The supplier advisories of target `id`; `None` without a CSAF provider.
#[server]
pub async fn fetch_supplier_advisories(
id: String,
) -> Result<Option<SupplierAdvisoriesDto>, ServerFnError> {
#[derive(Deserialize)]
struct Body {
data: Option<SupplierAdvisoriesDto>,
}
let resp = super::agent_client::agent_get(&format!("/api/v1/targets/{id}/supplier-advisories"))
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let body: Body = super::agent_client::json_or_error(resp).await?;
Ok(body.data)
}
/// A stored archive's password state, as the target editor shows it.
@@ -442,21 +233,10 @@ pub fn demo_seed_default_selection(targets: &[DemoSeedTarget], source_only: bool
pub fn is_file_kind(kind: &str) -> bool {
matches!(
kind,
"plc_project"
| "firmware_image"
| "source_archive"
| "mobile_package"
| "build_output"
| "supplier_sbom"
"plc_project" | "firmware_image" | "source_archive" | "mobile_package" | "build_output"
)
}
/// Whether a file of `kind` may be a password-protected archive: firmware
/// images, build outputs and supplier SBOMs are never unpacked.
pub fn may_need_password(kind: &str) -> bool {
!matches!(kind, "firmware_image" | "build_output" | "supplier_sbom")
}
/// The PLC project format a file's name suggests, if any.
pub fn plc_format_for(file_name: &str) -> Option<&'static str> {
let name = file_name.to_ascii_lowercase();
@@ -523,8 +303,9 @@ pub fn validate_artifact_ref(kind: &str, source_ref: &str) -> Option<String> {
"container_image" => {
(!no_space).then(|| "Enter an image ref, e.g. registry/name:tag".to_string())
}
"source_archive" | "firmware_image" | "mobile_package" | "plc_project" | "build_output"
| "supplier_sbom" => (!no_space).then(|| "Enter a path or URL (no spaces)".to_string()),
"source_archive" | "firmware_image" | "mobile_package" | "plc_project" | "build_output" => {
(!no_space).then(|| "Enter a path or URL (no spaces)".to_string())
}
// plaintext_description (and anything unknown): accept free-form text.
_ => None,
}
@@ -634,14 +415,12 @@ pub async fn create_target(
target_type: String,
description: Option<String>,
artifacts: Vec<ArtifactInputDto>,
supplier: Option<SupplierDto>,
) -> Result<TargetResponse, ServerFnError> {
let body = serde_json::json!({
"name": name,
"target_type": target_type,
"description": description,
"artifacts": artifacts,
"supplier": supplier,
});
let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/targets")
.await?
@@ -670,7 +449,6 @@ pub async fn upload_target_artifact(
file: dioxus::fullstack::FileStream,
) -> Result<TargetResponse, ServerFnError> {
let filename = file.file_name().to_string();
let sbom = kind == "supplier_sbom";
let part =
reqwest::multipart::Part::stream(reqwest::Body::wrap_stream(file)).file_name(filename);
let mut form = reqwest::multipart::Form::new()
@@ -690,21 +468,17 @@ pub async fn upload_target_artifact(
.map_err(|e| ServerFnError::new(e.to_string()))?;
if !resp.status().is_success() {
return Err(ServerFnError::new(match resp.status().as_u16() {
// A supplier SBOM has its own, smaller limit.
413 if sbom => format!("{SBOM_REFUSED}too_large"),
413 => "file is larger than the 512 MiB upload limit".to_string(),
415 => UNSUPPORTED_ARCHIVE.to_string(),
422 => format!("{SBOM_REFUSED}{}", refusal_code(resp).await),
code => format!("upload rejected by the agent ({code})"),
}));
}
super::agent_client::json_or_error(resp).await
}
/// Update a target's name / type / artifacts / excluded paths / supplier
/// (dashboard editor). `exclude_paths` replaces the stored list; the agent
/// normalises and checks it (`normalise_exclude_paths`). A supplier with an
/// empty name removes it.
/// Update a target's name / type / artifacts / excluded paths (dashboard
/// editor). `exclude_paths` replaces the stored list; the agent normalises
/// and checks it (`normalise_exclude_paths`).
#[server]
pub async fn update_target(
id: String,
@@ -712,15 +486,8 @@ pub async fn update_target(
target_type: Option<String>,
artifacts: Option<Vec<ArtifactInputDto>>,
exclude_paths: Option<Vec<String>>,
supplier: Option<SupplierDto>,
) -> Result<TargetResponse, ServerFnError> {
let mut body = serde_json::Map::new();
if let Some(s) = supplier {
body.insert(
"supplier".to_string(),
serde_json::to_value(s).map_err(|e| ServerFnError::new(e.to_string()))?,
);
}
if let Some(n) = name {
body.insert("name".to_string(), serde_json::json!(n));
}
@@ -893,80 +660,6 @@ pub async fn trigger_target_scan(id: String) -> Result<serde_json::Value, Server
#[cfg(test)]
mod tests {
#[test]
fn a_supplier_is_sent_without_blank_fields_and_checked_as_the_agent_does() {
use super::SupplierDto;
let s = SupplierDto::from_fields(" Example GmbH ", "Drive Control", " ", "");
assert_eq!(s.name, "Example GmbH");
assert_eq!(s.product.as_deref(), Some("Drive Control"));
assert_eq!(s.version, None);
assert_eq!(
serde_json::to_value(&s).unwrap()["csaf_provider"],
serde_json::Value::Null
);
assert!(!SupplierDto::provider_is_invalid(""));
assert!(!SupplierDto::provider_is_invalid(
"https://psirt.example/provider-metadata.json"
));
assert!(SupplierDto::provider_is_invalid(
"http://psirt.example/x.json"
));
assert!(SupplierDto::provider_is_invalid(
"https://psirt.example/a b.json"
));
}
#[test]
fn an_uploaded_supplier_sbom_shows_what_its_upload_kept() {
use super::{agent_time, SbomSummary};
let artifact = serde_json::json!({
"detected": [
{ "key": "sbom_format", "value": "CycloneDX 1.5", "source": "upload" },
{ "key": "sbom_components", "value": "212", "source": "upload" },
{ "key": "sbom_statements", "value": "9", "source": "upload" },
],
"ingested_at": { "$date": { "$numberLong": "1794902428827" } },
});
assert_eq!(
SbomSummary::of(&artifact),
Some(SbomSummary {
format: "CycloneDX 1.5".into(),
components: 212,
statements: 9
})
);
// One uploaded before the summary was kept shows without it.
assert_eq!(
SbomSummary::of(&serde_json::json!({ "detected": [] })),
None
);
assert_eq!(
agent_time(&artifact["ingested_at"]).map(|t| t.timestamp_millis()),
Some(1_794_902_428_827)
);
assert!(agent_time(&serde_json::json!("2026-11-17T08:00:00Z")).is_some());
assert_eq!(agent_time(&serde_json::Value::Null), None);
}
#[test]
fn a_refused_supplier_sbom_keeps_its_code_through_the_server_function() {
use super::sbom_refusal_code;
assert_eq!(
sbom_refusal_code("error running server function: supplier_sbom_refused:empty"),
Some("empty")
);
// However the error is wrapped, only the code is taken.
assert_eq!(
sbom_refusal_code(r#"ServerError("supplier_sbom_refused:unknown_format")"#),
Some("unknown_format")
);
assert_eq!(sbom_refusal_code("supplier_sbom_refused:"), None);
assert_eq!(
sbom_refusal_code("upload rejected by the agent (500)"),
None
);
}
#[test]
fn a_plc_file_name_suggests_its_format() {
assert_eq!(
@@ -69,8 +69,6 @@ mod tests {
name: name.to_string(),
kind: ProjectKind::Product,
description: String::new(),
level: None,
parent_id: None,
}
}
@@ -1,228 +0,0 @@
//! A target's SBOM releases to connected workspaces (#1028), the supplier's
//! side: the agent's `/api/v1/targets/{id}/releases` and `…/versions`, and
//! the workspace's connections (`/api/v1/connections`).
use chrono::{DateTime, Utc};
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
/// The other workspace's answer to a release.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Answer {
/// Not answered yet.
Offered,
/// Accepted: it receives every version.
Accepted,
/// Declined.
Declined,
/// It removed the component the release went into.
Ended,
}
/// A release of the target to one connected workspace.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ReleaseDto {
pub id: String,
pub connection_id: String,
/// The other workspace's display name.
pub peer_name: String,
pub created_at: DateTime<Utc>,
#[serde(default)]
pub ended_at: Option<DateTime<Utc>>,
/// Not ended.
pub active: bool,
/// `None` while it is open.
#[serde(default)]
pub answer: Option<Answer>,
/// The version last delivered, and when.
#[serde(default)]
pub delivered_label: Option<String>,
#[serde(default)]
pub delivered_at: Option<DateTime<Utc>>,
}
/// A published version of the target's SBOM.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VersionDto {
pub id: String,
pub label: String,
pub components: i64,
pub created_at: DateTime<Utc>,
/// How many customers received it.
#[serde(default)]
pub customers: usize,
}
/// The target's releases (active ones first) and versions (newest first).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ReleasesDto {
pub releases: Vec<ReleaseDto>,
pub versions: Vec<VersionDto>,
}
/// One of the workspace's active connections.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConnectionDto {
pub id: String,
/// The other workspace's display name.
pub peer_name: String,
}
/// Why the next version cannot be published.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Unpublishable {
/// No components.
Empty,
/// More than a release holds.
TooManyComponents,
}
/// What the next version changes against the latest published one.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DraftChangesDto {
/// The latest published version's label.
pub against: String,
pub added: usize,
pub updated: usize,
pub removed: usize,
pub unchanged: usize,
#[serde(default)]
pub added_names: Vec<String>,
#[serde(default)]
pub updated_names: Vec<String>,
}
/// The next version as publishing it now would make it.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct VersionDraftDto {
pub components: usize,
/// When the scan it comes from finished.
#[serde(default)]
pub scanned_at: Option<DateTime<Utc>>,
#[serde(default)]
pub blocked: Option<Unpublishable>,
/// `None` before the first version.
#[serde(default)]
pub changes: Option<DraftChangesDto>,
}
/// Target `target_id`'s releases and versions.
#[server]
pub async fn fetch_releases(target_id: String) -> Result<ReleasesDto, ServerFnError> {
super::agent_client::data(
super::agent_client::agent_get(&format!("/api/v1/targets/{target_id}/releases")).await?,
)
.await
}
/// The workspace's active connections. An error when the registry cannot
/// be asked, so the page tells that apart from having none.
#[server]
pub async fn fetch_connections() -> Result<Vec<ConnectionDto>, ServerFnError> {
super::agent_client::data(super::agent_client::agent_get("/api/v1/connections").await?).await
}
/// What publishing target `target_id` now would make.
#[server]
pub async fn fetch_version_draft(target_id: String) -> Result<VersionDraftDto, ServerFnError> {
super::agent_client::data(
super::agent_client::agent_get(&format!("/api/v1/targets/{target_id}/versions/draft"))
.await?,
)
.await
}
/// Release target `target_id` over connection `connection_id`.
#[server]
pub async fn create_release(
target_id: String,
connection_id: String,
) -> Result<ReleaseDto, ServerFnError> {
let req = super::agent_client::agent_request(
reqwest::Method::POST,
&format!("/api/v1/targets/{target_id}/releases"),
)
.await?
.json(&serde_json::json!({ "connection_id": connection_id }));
super::agent_client::data(req).await
}
/// End release `release_id` of target `target_id`.
#[server]
pub async fn end_release(target_id: String, release_id: String) -> Result<(), ServerFnError> {
let req = super::agent_client::agent_request(
reqwest::Method::POST,
&format!("/api/v1/targets/{target_id}/releases/{release_id}/end"),
)
.await?
.json(&serde_json::json!({}));
super::agent_client::data::<ReleaseDto>(req)
.await
.map(|_| ())
}
/// Publish the next version of target `target_id`, labelled `label`.
#[server]
pub async fn publish_version(
target_id: String,
label: String,
) -> Result<VersionDto, ServerFnError> {
let req = super::agent_client::agent_request(
reqwest::Method::POST,
&format!("/api/v1/targets/{target_id}/versions"),
)
.await?
.json(&serde_json::json!({ "label": label }));
super::agent_client::data(req).await
}
/// The document a version of target `target_id` labelled `label` would
/// hold, as JSON text to save.
#[server]
pub async fn fetch_version_preview(
target_id: String,
label: String,
) -> Result<String, ServerFnError> {
let resp =
super::agent_client::agent_get(&format!("/api/v1/targets/{target_id}/versions/preview"))
.await?
.query(&[("label", label.as_str())])
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let document: serde_json::Value = super::agent_client::json_or_error(resp).await?;
serde_json::to_string_pretty(&document).map_err(|e| ServerFnError::new(e.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_agents_answers_read() {
let listed: ReleasesDto = serde_json::from_value(serde_json::json!({
"releases": [{
"id": "r1", "connection_id": "c-1", "peer_name": "Beispiel Maschinenbau",
"created_at": "2026-11-10T09:00:00Z", "ended_at": null, "active": true,
"answer": "accepted", "delivered_label": "1.4.0",
"delivered_at": "2026-11-14T10:00:00Z"
}],
"versions": [{
"id": "v1", "label": "1.4.0", "components": 214,
"created_at": "2026-11-14T10:00:00Z", "created_by": "u1", "customers": 1
}]
}))
.expect("readable");
assert_eq!(listed.releases[0].answer, Some(Answer::Accepted));
assert_eq!(listed.versions[0].customers, 1);
let draft: VersionDraftDto = serde_json::from_value(serde_json::json!({
"components": 0, "scanned_at": null, "blocked": "too_many_components",
"changes": null
}))
.expect("readable");
assert_eq!(draft.blocked, Some(Unpublishable::TooManyComponents));
}
}
@@ -1,235 +0,0 @@
//! The supply chain (#1050): what the workspace's products are made of, read
//! from the agent's `/api/v1/supply-chain`, and the customer's arrangement of
//! it (`/api/v1/supply-chain/layout`).
use chrono::{DateTime, Utc};
use compliance_core::cve_groups::SeverityCounts;
use compliance_core::models::{ProjectLevel, TargetType};
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
/// What a node stands for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NodeKind {
/// A supplier, by the name a target gives it.
Supplier,
/// A component: one of the workspace's targets.
Target,
/// A product project: a family, product or assembly.
Project,
}
/// One node of the supply chain.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NodeDto {
/// Stable across calls: `supplier:<name>`, `target:<id>`, `project:<id>`.
pub key: String,
pub kind: NodeKind,
pub name: String,
/// A component's type.
#[serde(default)]
pub target_type: Option<TargetType>,
/// A component bought in from a supplier.
#[serde(default)]
pub bought: bool,
/// A project's place in the hierarchy.
#[serde(default)]
pub level: Option<ProjectLevel>,
/// Open CVEs; none for a supplier.
#[serde(default)]
pub open: Option<SeverityCounts>,
}
impl NodeDto {
/// The target's id, for a component.
pub fn target_id(&self) -> Option<&str> {
self.key.strip_prefix("target:")
}
/// The project's id, for a project.
pub fn project_id(&self) -> Option<&str> {
self.key.strip_prefix("project:")
}
}
/// What an edge means.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EdgeKind {
/// A supplier delivers the component.
Supplies,
/// The component or project is part of the project.
PartOf,
}
/// How a supplier's SBOM reaches its component.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DeliveryKind {
/// An accepted release of a connected supplier: each version it
/// publishes arrives by itself.
Release,
/// Through an active invite link.
Invite,
/// The release it came by has ended; the version last delivered stays.
ReleaseEnded,
/// Uploaded in the workspace.
Upload,
/// No SBOM yet.
Missing,
}
/// A supplier's delivery to its component.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeliveryDto {
pub how: DeliveryKind,
#[serde(default)]
pub version: Option<String>,
#[serde(default)]
pub at: Option<DateTime<Utc>>,
}
/// One edge, by node key.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EdgeDto {
pub from: String,
pub to: String,
pub kind: EdgeKind,
#[serde(default)]
pub delivery: Option<DeliveryDto>,
}
/// The supply chain (`GET /api/v1/supply-chain`).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct SupplyChainDto {
pub nodes: Vec<NodeDto>,
pub edges: Vec<EdgeDto>,
}
/// Where one box sits.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PositionDto {
pub key: String,
pub x: i32,
pub y: i32,
}
/// The customer's arrangement (`GET /api/v1/supply-chain/layout`).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct LayoutDto {
pub positions: Vec<PositionDto>,
#[serde(default)]
pub updated_at: Option<DateTime<Utc>>,
}
/// A document of a product's box, shown in the portal.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BoxDocumentDto {
pub id: String,
pub title: String,
#[serde(default)]
pub filename: String,
#[serde(default)]
pub size_bytes: Option<u64>,
/// Internal to the workspace rather than published with the product.
#[serde(default)]
pub internal: bool,
/// Where the portal shows it, below the portal's address.
pub path: String,
}
/// A product's description and documents
/// (`GET /api/v1/supply-chain/projects/{id}/documents`).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ProjectDocumentsDto {
#[serde(default)]
pub description: String,
#[serde(default)]
pub documents: Vec<BoxDocumentDto>,
/// The portal's store, below its address; empty without a registry.
#[serde(default)]
pub store_path: String,
}
/// The workspace's supply chain.
#[server]
pub async fn fetch_supply_chain() -> Result<SupplyChainDto, ServerFnError> {
super::agent_client::data(super::agent_client::agent_get("/api/v1/supply-chain").await?).await
}
/// The customer's arrangement of the supply chain.
#[server]
pub async fn fetch_supply_chain_layout() -> Result<LayoutDto, ServerFnError> {
super::agent_client::data(super::agent_client::agent_get("/api/v1/supply-chain/layout").await?)
.await
}
/// Product project `id`'s description and documents.
#[server]
pub async fn fetch_project_documents(id: String) -> Result<ProjectDocumentsDto, ServerFnError> {
super::agent_client::data(
super::agent_client::agent_get(&format!("/api/v1/supply-chain/projects/{id}/documents"))
.await?,
)
.await
}
/// Save the arrangement: every placed box.
#[server]
pub async fn save_supply_chain_layout(positions: Vec<PositionDto>) -> Result<(), ServerFnError> {
let req =
super::agent_client::agent_request(reqwest::Method::PUT, "/api/v1/supply-chain/layout")
.await?
.json(&serde_json::json!({ "positions": positions }));
super::agent_client::data::<LayoutDto>(req)
.await
.map(|_| ())
}
/// Reset the arrangement to the computed columns.
#[server]
pub async fn reset_supply_chain_layout() -> Result<(), ServerFnError> {
let resp =
super::agent_client::agent_request(reqwest::Method::DELETE, "/api/v1/supply-chain/layout")
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
super::agent_client::json_or_error::<serde_json::Value>(resp)
.await
.map(|_| ())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_agents_answer_reads() {
let chain: SupplyChainDto = serde_json::from_value(serde_json::json!({
"nodes": [
{ "key": "supplier:Antriebe GmbH", "kind": "supplier", "name": "Antriebe GmbH" },
{ "key": "target:t1", "kind": "target", "name": "Antrieb",
"target_type": "firmware_rtos", "bought": true,
"open": { "critical": 1, "high": 0, "medium": 0, "low": 0, "info": 0 } },
{ "key": "project:p1", "kind": "project", "name": "Pumpe", "level": "product",
"open": { "critical": 1, "high": 0, "medium": 0, "low": 0, "info": 0 } }
],
"edges": [
{ "from": "supplier:Antriebe GmbH", "to": "target:t1", "kind": "supplies",
"delivery": { "how": "upload", "version": "1.4.0", "at": "2026-11-14T10:30:00Z" } },
{ "from": "target:t1", "to": "project:p1", "kind": "part_of" }
]
}))
.expect("readable");
assert_eq!(chain.nodes[1].target_id(), Some("t1"));
assert_eq!(chain.nodes[2].project_id(), Some("p1"));
assert_eq!(chain.nodes[2].level, Some(ProjectLevel::Product));
assert!(!chain.nodes[0].bought);
assert_eq!(
chain.edges[0].delivery.as_ref().map(|d| d.how),
Some(DeliveryKind::Upload)
);
}
}
-767
View File
@@ -1,767 +0,0 @@
//! A machine (#1026): a product project made of in-house targets and
//! components bought in from suppliers. Three tabs: its parts with its
//! documents, its open CVEs by component across the parts, and its history.
use std::collections::{BTreeSet, HashMap};
use dioxus::prelude::*;
use compliance_core::cve_groups::{CveGroup, CveSeverity, SeverityCounts};
use compliance_core::models::CveAlert;
use compliance_core::scan_changes::ComponentRowKind;
use compliance_core::vex_docs::status_of;
use crate::app::Route;
use crate::components::severity_badge::SeverityBadge;
use crate::components::toast::{ToastType, Toasts};
use crate::components::vex_panel::{
is_supplier_product, status_class, status_text, supplier_gist, SUPPLIER_PROVIDER_PREFIX,
};
use crate::i18n::texts::{common, cve_matrix, kinds, machine as tx, repo_views as rv};
use crate::i18n::{format_ago, format_count, format_time, use_lang, Lang};
use crate::infrastructure::machine::{
fetch_machine_changes, fetch_machine_cves, fetch_machine_overview, fetch_machine_sbom,
MachineChangeDto, MachineOverviewDto, PartDto,
};
use crate::pages::target_views::RepoView;
/// A tab of the machine page.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Tab {
Parts,
Cves,
History,
}
impl Tab {
const ALL: [Self; 3] = [Self::Parts, Self::Cves, Self::History];
/// Its name in the URL (`?tab=`).
const fn slug(self) -> &'static str {
match self {
Self::Parts => "parts",
Self::Cves => "cves",
Self::History => "history",
}
}
/// The tab named `slug`; anything else opens the parts.
fn from_slug(slug: &str) -> Self {
Self::ALL
.into_iter()
.find(|t| t.slug() == slug)
.unwrap_or(Self::Parts)
}
}
/// Which parts the CVE tab shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Origin {
All,
InHouse,
Bought,
}
/// The count badges of `counts`, most severe first, the empty ones left out.
fn count_badges(counts: &SeverityCounts, lang: Lang) -> Vec<(&'static str, String)> {
counts
.by_severity()
.into_iter()
.filter(|(_, n)| *n > 0)
.map(|(severity, n)| {
(
severity_class(severity),
format!(
"{n} {}",
cve_matrix::severity(matrix_row(severity)).get(lang)
),
)
})
.collect()
}
/// The CVE grid's row of `severity`, for its lower-case label ("kritisch").
const fn matrix_row(severity: CveSeverity) -> compliance_core::cve_matrix::CveSeverity {
use compliance_core::cve_matrix::CveSeverity as Row;
match severity {
CveSeverity::Critical => Row::Critical,
CveSeverity::High => Row::High,
CveSeverity::Medium => Row::Medium,
CveSeverity::Low => Row::Low,
CveSeverity::Info => Row::Unknown,
}
}
/// The badge class of `severity`.
const fn severity_class(severity: CveSeverity) -> &'static str {
match severity {
CveSeverity::Critical => "badge badge-critical",
CveSeverity::High => "badge badge-high",
CveSeverity::Medium => "badge badge-medium",
CveSeverity::Low => "badge badge-low",
CveSeverity::Info => "badge badge-info",
}
}
/// The total of `counts`.
fn total(counts: &SeverityCounts) -> usize {
counts.by_severity().iter().map(|(_, n)| n).sum()
}
/// A part's origin as a badge and the supplier's name beside it.
#[component]
fn OriginBadge(part: PartDto, #[props(default)] with_name: bool) -> Element {
let lang = use_lang()();
rsx! {
match part.supplier {
Some(s) => rsx! {
span { class: "badge badge-accent", {tx::SUPPLIER.get(lang)} }
if with_name {
" "
span { class: "target-muted", "{s.name}" }
}
},
None => rsx! { span { class: "badge badge-neutral", {tx::IN_HOUSE.get(lang)} } },
}
}
}
/// The machine `id`'s page, on tab `tab` (`parts`, `cves`, `history`).
#[component]
pub fn MachinePage(id: String, tab: String) -> Element {
let lang = use_lang()();
let tab = Tab::from_slug(&tab);
let machine_id = use_signal(|| id.clone());
let overview = use_resource(move || async move { fetch_machine_overview(machine_id()).await });
let read = overview.read();
let data = match &*read {
None => return rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
Some(Err(_)) => {
return rsx! { div { class: "card", p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } } }
}
Some(Ok(data)) => data.clone(),
};
let bought = data.parts.iter().filter(|p| p.supplier.is_some()).count();
let open = total(&data.open);
rsx! {
nav { class: "repo-crumbs", "aria-label": rv::BREADCRUMB.get(lang),
Link { to: Route::OverviewPage {}, {rv::OVERVIEW.get(lang)} }
span { class: "repo-crumb-sep", "aria-hidden": "true", "›" }
span { class: "repo-crumb-name", "aria-current": "page", "{data.name}" }
}
header { class: "machine-head",
div {
h2 { "{data.name}" }
p { class: "target-muted", {tx::subtitle(data.parts.len(), bought, lang)} }
}
span { class: "badge badge-accent", {tx::KIND.get(lang)} }
}
nav { class: "sbom-tab-bar machine-tabs", "aria-label": "{tx::TAB_PARTS.get(lang)}",
for t in Tab::ALL {
Link {
to: Route::MachinePage { id: id.clone(), tab: t.slug().to_string() },
class: if t == tab { "sbom-tab active" } else { "sbom-tab" },
"aria-current": if t == tab { "page" } else { "false" },
match t {
Tab::Parts => rsx! { {tx::TAB_PARTS.get(lang)} },
Tab::Cves => rsx! {
{tx::TAB_CVES.get(lang)}
" "
span { class: "target-muted", {tx::open_count(open, lang)} }
},
Tab::History => rsx! { {tx::TAB_HISTORY.get(lang)} },
}
}
}
}
if data.parts.is_empty() {
div { class: "card", p { class: "target-muted", {tx::NO_PARTS.get(lang)} } }
} else {
match tab {
Tab::Parts => rsx! { PartsTab { id: id.clone(), data: data.clone() } },
Tab::Cves => rsx! { CvesTab { id: id.clone(), data: data.clone() } },
Tab::History => rsx! { HistoryTab { id: id.clone(), data: data.clone() } },
}
}
}
}
/// The machine's figures, its parts and its documents.
#[component]
fn PartsTab(id: String, data: MachineOverviewDto) -> Element {
let lang = use_lang()();
let now = chrono::Utc::now();
rsx! {
div { class: "machine-tiles",
section { class: "card machine-tile",
span { class: "machine-label", {tx::OPEN_CVES.get(lang)} }
span { class: "machine-figure", "{total(&data.open)}" }
span { class: "machine-badges",
for (class, text) in count_badges(&data.open, lang) {
span { class, "{text}" }
}
}
}
section { class: "card machine-tile",
span { class: "machine-label", {tx::UNDECIDED.get(lang)} }
span { class: "machine-figure", "{data.undecided}" }
span { class: "target-muted", {tx::undecided_with_supplier(data.undecided_with_supplier, lang)} }
}
section { class: "card machine-tile",
span { class: "machine-label", {tx::COMPONENTS.get(lang)} }
span { class: "machine-figure", {format_count(data.components, lang)} }
span { class: "target-muted", {tx::components_hint(data.parts.len(), data.shared_components, lang)} }
}
if let Some(adv) = data.advisories.clone() {
section { class: "card machine-tile",
span { class: "machine-label", {tx::ADVISORIES.get(lang)} }
span { class: "machine-figure", {format_count(adv.advisories, lang)} }
span { class: "target-muted",
{tx::advisories_hint(adv.providers, adv.checked_at.map(|t| format_ago(&t, &now, lang)).as_deref(), lang)}
}
}
}
}
section { class: "card machine-parts",
div { class: "machine-card-head",
strong { {tx::PARTS.get(lang)} }
span { class: "target-muted", {tx::PARTS_HINT.get(lang)} }
}
div { class: "table-wrapper",
table { class: "machine-table",
thead {
tr {
th { {tx::COL_PART.get(lang)} }
th { {tx::COL_ORIGIN.get(lang)} }
th { {tx::COL_VERSION.get(lang)} }
th { {tx::COL_OPEN.get(lang)} }
th { {tx::COL_LAST_SCAN.get(lang)} }
th { span { class: "sr-only", {tx::OPEN.get(lang)} } }
}
}
tbody {
for part in data.parts.iter() {
tr { key: "{part.id}",
td {
strong { "{part.name}" }
div { class: "target-muted", {kinds::target_type(&part.target_type, lang)} }
}
td { OriginBadge { part: part.clone(), with_name: true } }
td {
match part.supplier.as_ref().map(|s| (s.product.clone(), s.version.clone())) {
Some((Some(product), Some(version))) => rsx! { "{product} {version}" },
Some((None, Some(version))) => rsx! { "{version}" },
_ => rsx! { span { class: "target-muted", "—" } },
}
}
td {
span { class: "machine-badges",
for (class, text) in count_badges(&part.open, lang) {
span { class, "{text}" }
}
if total(&part.open) == 0 {
span { class: "target-muted", {tx::NONE_OPEN.get(lang)} }
}
}
}
td { class: "target-muted",
match part.last_scan_at {
Some(at) => format_ago(&at, &now, lang),
None => tx::NOT_SCANNED.get(lang).to_string(),
}
}
td {
Link { to: Route::TargetPage { id: part.id.clone() }, {tx::OPEN.get(lang)} }
}
}
}
}
}
}
}
MachineDocuments { id }
}
}
/// The machine's documents: its SBOM now; VEX, CSAF and the evidence pack
/// follow (#1015).
#[component]
fn MachineDocuments(id: String) -> Element {
let lang = use_lang()();
let mut toasts = use_context::<Toasts>();
let mut busy = use_signal(|| false);
rsx! {
section { class: "card machine-docs",
div {
strong { {tx::DOCUMENTS.get(lang)} }
div { class: "target-muted", {tx::DOCUMENTS_HINT.get(lang)} }
}
div { class: "machine-doc",
span { class: "machine-label", {tx::SBOM.get(lang)} }
span { {tx::SBOM_HINT.get(lang)} }
div {
button {
class: "btn btn-secondary",
disabled: busy(),
onclick: move |_| {
let id = id.clone();
busy.set(true);
spawn(async move {
match fetch_machine_sbom(id.clone()).await {
Ok(doc) => crate::infrastructure::download::save_json(
&serde_json::to_string_pretty(&doc).unwrap_or_default(),
&format!("sbom-machine-{id}-cyclonedx.json"),
),
Err(e) => toasts.push(ToastType::Error, format!("{}: {e}", tx::DOWNLOAD_FAILED.get(lang))),
}
busy.set(false);
});
},
{tx::SBOM_DOWNLOAD.get(lang)}
}
}
}
p { class: "target-muted", {tx::MORE_DOCUMENTS.get(lang)} }
}
}
}
/// How many groups open with their rows shown; the rest open on demand.
const GROUPS_OPEN: usize = 2;
/// The machine's open CVEs by component, each with the parts it is in.
#[component]
fn CvesTab(id: String, data: MachineOverviewDto) -> Element {
let lang = use_lang()();
let machine_id = use_signal(|| id.clone());
let cves = use_resource(move || async move { fetch_machine_cves(machine_id()).await });
let mut origin = use_signal(|| Origin::All);
let parts: HashMap<String, PartDto> = data
.parts
.iter()
.map(|p| (p.id.clone(), p.clone()))
.collect();
let read = cves.read();
let Some(result) = &*read else {
return rsx! { div { class: "loading", {common::LOADING.get(lang)} } };
};
let Ok(found) = result else {
return rsx! { p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } };
};
let shows = |alert: &CveAlert| {
let bought = parts
.get(&alert.repo_id)
.is_some_and(|p| p.supplier.is_some());
match origin() {
Origin::All => true,
Origin::InHouse => !bought,
Origin::Bought => bought,
}
};
let by_id: HashMap<String, &CveAlert> = found
.alerts
.iter()
.filter_map(|a| a.id.map(|o| (o.to_hex(), a)))
.collect();
let groups: Vec<(CveGroup, Vec<CveAlert>)> = found
.groups
.iter()
.map(|g| {
let rows: Vec<CveAlert> = g
.alert_ids
.iter()
.filter_map(|id| by_id.get(id).copied())
.filter(|a| shows(a))
.cloned()
.collect();
(g.clone(), rows)
})
.filter(|(_, rows)| !rows.is_empty())
.collect();
rsx! {
p { class: "target-muted", {tx::CVES_HINT.get(lang)} }
div { class: "machine-filter",
span { class: "machine-label", {tx::PARTS.get(lang)} }
for (value, label) in [
(Origin::All, tx::FILTER_ALL),
(Origin::InHouse, tx::IN_HOUSE),
(Origin::Bought, tx::SUPPLIER),
] {
button {
r#type: "button",
class: if origin() == value { "btn btn-sm machine-filter-on" } else { "btn btn-sm" },
"aria-pressed": if origin() == value { "true" } else { "false" },
onclick: move |_| origin.set(value),
{label.get(lang)}
}
}
}
if groups.is_empty() {
p { class: "target-muted", {tx::NO_CVES.get(lang)} }
}
for (i, (group, rows)) in groups.into_iter().enumerate() {
MachineCveGroup {
key: "{group.key.package}@{group.key.version}@{group.key.purl.clone().unwrap_or_default()}",
group,
rows,
parts: parts.clone(),
open: i < GROUPS_OPEN,
}
}
p { class: "target-muted vex-footnote", {tx::CVES_FOOTNOTE.get(lang)} }
}
}
/// One component's open CVEs across the machine's parts.
#[component]
fn MachineCveGroup(
group: CveGroup,
rows: Vec<CveAlert>,
parts: HashMap<String, PartDto>,
open: bool,
) -> Element {
let lang = use_lang()();
let mut expanded = use_signal(|| open);
let in_parts = rows
.iter()
.map(|a| a.repo_id.as_str())
.collect::<BTreeSet<_>>()
.len();
let product = rows.iter().any(is_supplier_product);
rsx! {
section { class: "card machine-group",
div { class: "machine-group-head",
SeverityBadge { severity: group.counts.max().as_str().to_string() }
strong { "{group.key.package} {group.key.version}" }
span { class: "target-muted",
{tx::group_meta(group.cve_ids.len(), in_parts, lang)}
if let Some(fix) = &group.fix_version {
" · {tx::fixed_by(fix, lang)}"
}
}
if product {
span { class: "badge badge-accent", {crate::i18n::texts::vex::SUPPLIER_PRODUCT.get(lang)} }
}
if !open || !expanded() {
button {
r#type: "button",
class: "btn btn-ghost btn-sm machine-group-toggle",
"aria-expanded": if expanded() { "true" } else { "false" },
onclick: move |_| expanded.toggle(),
if expanded() { {tx::HIDE_ROWS.get(lang)} } else { {tx::show_rows(rows.len(), lang)} }
}
}
}
if expanded() {
div { class: "table-wrapper",
table { class: "vex-table",
thead {
tr {
th { {crate::i18n::texts::vex::CVE.get(lang)} }
th { {tx::COL_PART.get(lang)} }
th { {crate::i18n::texts::vex::STATUS.get(lang)} }
th { {crate::i18n::texts::vex::SUPPLIER_SAYS.get(lang)} }
th { span { class: "sr-only", {crate::i18n::texts::vex::ACTIONS.get(lang)} } }
}
}
tbody {
for alert in rows.iter() {
{
let status = status_of(alert);
let part = parts.get(&alert.repo_id).cloned();
let stated_by = alert.vex.as_ref().filter(|v| !v.by_scan).map(|v| v.by_name.clone().unwrap_or_else(|| v.by.clone()));
rsx! {
tr { key: "{alert.repo_id}-{alert.cve_id}",
td {
code { "{alert.cve_id}" }
for adv in alert.advisories.iter() {
div { class: "vex-advisory-line",
a {
class: "vex-advisory",
href: adv.url.clone().unwrap_or_default(),
target: "_blank",
rel: "noopener noreferrer",
"{adv.id}"
}
if adv.provider.starts_with(SUPPLIER_PROVIDER_PREFIX) {
" "
span { class: "vex-advisory-note", {crate::i18n::texts::vex::SUPPLIER_ADVISORY.get(lang)} }
}
}
}
}
td {
if let Some(part) = part.clone() {
"{part.name} "
OriginBadge { part }
}
}
td {
span { class: status_class(status), {status_text(status).get(lang)} }
if let Some(by) = stated_by {
" "
span { class: "target-muted", "{by}" }
}
}
td {
match &alert.supplier_vex {
Some(vex) => rsx! {
span { class: "vex-supplier-pill",
span { class: status_class(vex.status), {status_text(vex.status).get(lang)} }
"{supplier_gist(vex, lang)}"
}
},
None => rsx! { span { class: "target-muted", "—" } },
}
}
td {
Link {
class: "btn btn-secondary btn-sm",
to: Route::target_view(alert.repo_id.clone(), RepoView::Cves),
{tx::ASSESS_IN_PART.get(lang)}
}
}
}
}
}
}
}
}
}
}
}
}
}
/// What one scan of a part changed, in words: a supplier's new version, or
/// a scan (the first one marked as such).
fn change_title(change: &MachineChangeDto, part: Option<&PartDto>, lang: Lang) -> (String, String) {
let rows = change.change.components.as_deref().unwrap_or_default();
let product = part
.and_then(|p| p.supplier.as_ref())
.and_then(|s| s.product.as_deref());
let new_version = rows
.iter()
.find(|r| r.kind == ComponentRowKind::Updated && product.is_some_and(|p| p == r.name));
let added = rows
.iter()
.filter(|r| r.kind == ComponentRowKind::Added)
.count();
let removed = rows
.iter()
.filter(|r| r.kind == ComponentRowKind::Removed)
.count();
let moves = if added + removed > 0 {
tx::component_moves(added, removed, lang)
} else {
String::new()
};
match new_version {
Some(row) => (
format!(
"{}: {} {} → {}",
tx::NEW_VERSION.get(lang),
row.name,
row.from.as_deref().unwrap_or("?"),
row.to.as_deref().unwrap_or("?")
),
moves,
),
None if change.change.baseline => (
tx::SCAN.get(lang).to_string(),
tx::BASELINE.get(lang).to_string(),
),
None => (tx::SCAN.get(lang).to_string(), moves),
}
}
/// The machine's history: its parts' scans, newest first.
#[component]
fn HistoryTab(id: String, data: MachineOverviewDto) -> Element {
let lang = use_lang()();
let machine_id = use_signal(|| id.clone());
let changes = use_resource(move || async move { fetch_machine_changes(machine_id()).await });
let now = chrono::Utc::now();
let read = changes.read();
let Some(result) = &*read else {
return rsx! { div { class: "loading", {common::LOADING.get(lang)} } };
};
let Ok(list) = result else {
return rsx! { p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } };
};
rsx! {
p { class: "target-muted", {tx::HISTORY_HINT.get(lang)} }
if list.is_empty() {
p { class: "target-muted", {tx::NO_HISTORY.get(lang)} }
} else {
section { class: "card",
div { class: "table-wrapper",
table { class: "machine-table",
thead {
tr {
th { {tx::COL_WHEN.get(lang)} }
th { {tx::COL_PART.get(lang)} }
th { {tx::COL_WHAT.get(lang)} }
th { {tx::COL_NEW.get(lang)} }
th { {tx::COL_GONE.get(lang)} }
th { span { class: "sr-only", {tx::IN_PART.get(lang)} } }
}
}
tbody {
for change in list.iter() {
{
let part = data.part(&change.part).cloned();
let (title, detail) = change_title(change, part.as_ref(), lang);
let when = change.change.completed_at.unwrap_or(change.change.started_at);
let new = change.change.new_cves.len();
let gone = change.change.gone_cves.len();
rsx! {
tr { key: "{change.change.run_id}",
td { class: "target-muted machine-nowrap",
title: format_time(&when, lang),
{format_ago(&when, &now, lang)}
}
td {
if let Some(part) = part.clone() {
"{part.name} "
OriginBadge { part }
}
}
td {
strong { "{title}" }
if !detail.is_empty() {
div { class: "target-muted", "{detail}" }
}
}
td {
if new > 0 {
span { class: "badge badge-danger", "+{new}" }
} else {
span { class: "target-muted", "—" }
}
}
td {
if gone > 0 {
span { class: "badge badge-success", "−{gone}" }
} else {
span { class: "target-muted", "—" }
}
}
td {
Link {
class: "machine-nowrap",
to: Route::target_view(change.part.clone(), RepoView::History),
{tx::IN_PART.get(lang)}
}
}
}
}
}
}
}
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::scan_changes::{ComponentRow, ScanChange};
fn change(rows: Vec<ComponentRow>, baseline: bool) -> MachineChangeDto {
MachineChangeDto {
part: "t2".into(),
change: serde_json::from_value(serde_json::json!({
"run_id": "r1", "status": "completed",
"started_at": "2026-11-17T03:00:00Z", "baseline": baseline,
"new_cves": [], "gone_cves": [],
}))
.map(|mut c: ScanChange| {
c.components = Some(rows);
c
})
.unwrap(),
}
}
fn row(
kind: ComponentRowKind,
name: &str,
from: Option<&str>,
to: Option<&str>,
) -> ComponentRow {
ComponentRow {
kind,
name: name.into(),
from: from.map(String::from),
to: to.map(String::from),
cves_new: 0,
cves_gone: 0,
}
}
#[test]
fn a_suppliers_new_version_reads_as_such_with_the_components_it_moved() {
let part: PartDto = serde_json::from_value(serde_json::json!({
"id": "t2", "name": "Antrieb", "target_type": "firmware_rtos",
"supplier": { "name": "Example Drives", "product": "Drive Control", "version": "4.3.0" },
"open": { "critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0 },
}))
.unwrap();
let updated = change(
vec![
row(
ComponentRowKind::Updated,
"Drive Control",
Some("4.2.1"),
Some("4.3.0"),
),
row(ComponentRowKind::Added, "zstd", None, Some("1.5")),
row(ComponentRowKind::Removed, "zlib", Some("1.2"), None),
],
false,
);
assert_eq!(
change_title(&updated, Some(&part), Lang::De),
(
"Neue Version des Zulieferers: Drive Control 4.2.1 → 4.3.0".to_string(),
"Komponenten +1, −1".to_string()
)
);
// The same update in a part made in-house is a scan.
assert_eq!(change_title(&updated, None, Lang::En).0, "Scan");
assert_eq!(
change_title(&change(Vec::new(), true), None, Lang::De),
(
"Prüfung".to_string(),
"die erste: legt den Stand fest".to_string()
)
);
}
#[test]
fn only_the_severities_with_cves_get_a_badge() {
let counts = SeverityCounts {
critical: 1,
high: 0,
medium: 6,
low: 0,
info: 0,
};
assert_eq!(
count_badges(&counts, Lang::De),
[
("badge badge-critical", "1 kritisch".to_string()),
("badge badge-medium", "6 mittel".to_string())
]
);
assert_eq!(total(&counts), 7);
}
}
-8
View File
@@ -12,17 +12,13 @@ pub(crate) mod graph_view;
pub mod impact_analysis;
pub mod inbox;
pub mod issues;
pub mod machine;
pub mod mcp_servers;
pub mod mcp_tokens;
pub mod offers;
pub mod onboarding;
pub mod overview;
pub mod pentest_dashboard;
pub mod pentest_session;
pub mod releases;
pub mod sbom;
pub mod supply_chain;
pub mod target;
pub mod target_views;
pub mod targets;
@@ -40,17 +36,13 @@ pub use graph_explorer::GraphExplorerPage;
pub use impact_analysis::ImpactAnalysisPage;
pub use inbox::HeutePage;
pub use issues::IssuesPage;
pub use machine::MachinePage;
pub use mcp_servers::McpServersPage;
pub use mcp_tokens::McpTokensPage;
pub use offers::SupplierOffersPage;
pub use onboarding::OnboardingPage;
pub use overview::OverviewPage;
pub use pentest_dashboard::PentestDashboardPage;
pub use pentest_session::PentestSessionPage;
pub use releases::TargetReleasesPage;
pub use sbom::SbomPage;
pub use supply_chain::SupplyChainPage;
pub use target::TargetPage;
pub use target_views::TargetViewsPage;
pub use targets::TargetsPage;
-917
View File
@@ -1,917 +0,0 @@
//! What connected suppliers offer (#1028), the customer's side of releases:
//! for each open offer, where its SBOM would arrive (a new component in a
//! machine, or a bought-in component that has none from a supplier yet),
//! what accepting means, and the supply lines already running.
use dioxus::prelude::*;
use compliance_core::models::Project;
use crate::app::Route;
use crate::components::no_access::use_can_write;
use crate::components::toast::{ToastType, Toasts};
use crate::i18n::texts::{offers as tx, repo_views as rv};
use crate::i18n::{format_ago, use_lang};
use crate::infrastructure::metering::fetch_usage;
use crate::infrastructure::offers::{
accept_offer, decline_offer, fetch_offers, Destination, OfferDto, OfferState,
};
use crate::infrastructure::onboarding::{fetch_targets, SupplierDto};
use crate::infrastructure::projects::{fetch_projects, project_ids_of};
use crate::pages::targets::target_id;
/// Open offers, for the sidebar and the targets page; `None` until read.
pub static OPEN_OFFERS: GlobalSignal<Option<usize>> = Signal::global(|| None);
/// The schematic's width; it scrolls in its box on a narrow screen.
const WIDTH: i32 = 920;
/// The supplier's box.
const SUPPLIER_X: i32 = 40;
const SUPPLIER_W: i32 = 220;
const SUPPLIER_H: i32 = 88;
/// Where the line splits towards the choices.
const JUNCTION_X: i32 = 440;
/// The machine's frame, and the choices in it.
const FRAME_X: i32 = 560;
const FRAME_W: i32 = 340;
const OPTION_X: i32 = 580;
const OPTION_W: i32 = 300;
const OPTION_H: i32 = 76;
/// Space between choices, and the row of the machine's other parts.
const OPTION_GAP: i32 = 14;
const PARTS_H: i32 = 34;
/// The frame's title row.
const FRAME_TOP: i32 = 24;
const FIRST_OPTION: i32 = 64;
/// Bought-in components offered as choices; the rest in a list.
const SHOWN_COMPONENTS: usize = 2;
/// The machine's parts named in its frame.
const SHOWN_PARTS: usize = 2;
/// A line of the supply chain.
const CHAIN_PITCH: i32 = 96;
const CHAIN_TOP: i32 = 70;
/// A bought-in component that can receive the offer.
#[derive(Debug, Clone, PartialEq)]
struct Candidate {
id: String,
name: String,
}
/// The bought-in components no accepted offer delivers into, those named
/// after `supplier` first, then by name.
fn candidates(
targets: &[serde_json::Value],
offers: &[OfferDto],
supplier: &str,
) -> Vec<Candidate> {
let taken: Vec<&str> = offers
.iter()
.filter(|o| o.state == OfferState::Accepted)
.filter_map(|o| o.target_id.as_deref())
.collect();
let mut found: Vec<(bool, Candidate)> = targets
.iter()
.filter_map(|t| {
let bought = SupplierDto::of(t)?;
let id = target_id(t);
if id.is_empty() || taken.contains(&id.as_str()) {
return None;
}
let name = t["name"].as_str().unwrap_or_default().to_string();
Some((
!bought.name.eq_ignore_ascii_case(supplier),
Candidate { id, name },
))
})
.collect();
found.sort_by(|a, b| (a.0, &a.1.name).cmp(&(b.0, &b.1.name)));
found.into_iter().map(|(_, c)| c).collect()
}
/// Where the offer goes.
#[derive(Debug, Clone, PartialEq)]
enum Choice {
/// A new component, named after the product, in `project` if any.
New,
/// An existing bought-in component.
Existing(Candidate),
}
/// Where the choices sit in the schematic.
#[derive(Debug, Clone, PartialEq, Eq)]
struct DecisionGeometry {
height: i32,
frame_h: i32,
/// The top of the row naming the machine's parts, if it has any.
parts_y: Option<i32>,
/// The top of each choice: the new component first.
option_y: Vec<i32>,
trunk_y: i32,
}
impl DecisionGeometry {
fn new(choices: usize, parts: bool) -> Self {
let mut y = FIRST_OPTION;
let mut option_y = vec![y];
y += OPTION_H + OPTION_GAP;
let parts_y = parts.then_some(y);
if parts {
y += PARTS_H + OPTION_GAP;
}
for _ in 1..choices.max(1) {
option_y.push(y);
y += OPTION_H + OPTION_GAP;
}
let frame_h = y - OPTION_GAP + 20 - FRAME_TOP;
let height = (FRAME_TOP + frame_h + FRAME_TOP).max(SUPPLIER_H + 2 * FRAME_TOP);
let first = option_y[0] + OPTION_H / 2;
let last = option_y[option_y.len() - 1] + OPTION_H / 2;
Self {
height,
frame_h,
parts_y,
option_y,
trunk_y: (first + last) / 2,
}
}
}
/// Whether one more target goes beyond the plan's included ones.
fn beyond_plan(included: Option<u32>, active: usize) -> bool {
included.is_some_and(|n| active >= usize::try_from(n).unwrap_or(usize::MAX))
}
/// One running or ended supply line.
#[derive(Debug, Clone, PartialEq)]
struct ChainRow {
supplier: String,
/// The component's id and name; `None` when it was removed.
component: Option<(String, String)>,
products: Vec<String>,
state: OfferState,
delivered_label: Option<String>,
delivered_at: Option<chrono::DateTime<chrono::Utc>>,
}
/// The accepted offers, then those that ended after delivering, each group
/// newest first, each with its component and the products it is in.
fn chain_rows(
offers: &[OfferDto],
targets: &[serde_json::Value],
projects: &[Project],
) -> Vec<ChainRow> {
let mut rows: Vec<ChainRow> = offers
.iter()
.filter(|o| {
o.state == OfferState::Accepted
|| (o.state == OfferState::Ended && o.delivered_label.is_some())
})
.map(|o| {
let target = o
.target_id
.as_deref()
.and_then(|id| targets.iter().find(|t| target_id(t) == id));
let products = target
.map(|t| {
project_ids_of(t)
.iter()
.filter_map(|id| projects.iter().find(|p| &p.id == id))
.map(|p| p.name.clone())
.collect()
})
.unwrap_or_default();
ChainRow {
supplier: o.supplier_name.clone(),
component: target.map(|t| {
(
target_id(t),
t["name"].as_str().unwrap_or_default().to_string(),
)
}),
products,
state: o.state,
delivered_label: o.delivered_label.clone(),
delivered_at: o.delivered_at,
}
})
.collect();
// Running lines first; the stable sort keeps each group's order.
rows.sort_by_key(|r| r.state != OfferState::Accepted);
rows
}
/// The offers suppliers make the workspace.
#[component]
pub fn SupplierOffersPage() -> Element {
let lang = use_lang()();
let can_write = use_can_write();
let mut offers = use_resource(fetch_offers);
let mut targets = use_resource(fetch_targets);
let projects = use_resource(fetch_projects);
let usage = use_resource(fetch_usage);
let mut selected = use_signal(|| 0usize);
let listed = match &*offers.read() {
Some(Ok(listed)) => listed.clone(),
Some(Err(_)) => {
return rsx! {
OfferCrumbs {}
div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } }
}
}
None => return rsx! { div { class: "loading", {tx::LOADING.get(lang)} } },
};
let open: Vec<OfferDto> = listed
.iter()
.filter(|o| o.state == OfferState::Offered)
.cloned()
.collect();
if OPEN_OFFERS.peek().as_ref() != Some(&open.len()) {
*OPEN_OFFERS.write() = Some(open.len());
}
// Targets and projects are read for the choices; until then the offer
// waits rather than showing choices that may be wrong.
let all_targets = match &*targets.read() {
Some(Ok(found)) => Some(found.data.clone()),
Some(Err(_)) => Some(Vec::new()),
None => None,
};
let all_projects = match &*projects.read() {
Some(Ok(found)) => found.clone(),
_ => Vec::new(),
};
let included = usage
.read()
.as_ref()
.and_then(|u| u.as_ref().ok())
.and_then(|u| u.data.included_targets);
let current = open
.get(selected().min(open.len().saturating_sub(1)))
.cloned();
let on_answered = move |_| {
selected.set(0);
offers.restart();
targets.restart();
};
let chain = chain_rows(
&listed,
all_targets.as_deref().unwrap_or_default(),
&all_projects,
);
rsx! {
div { class: "rel-page",
OfferCrumbs {}
match &current {
Some(offer) => rsx! {
header { class: "chain-head",
h1 { {tx::title(&offer.supplier_name, &offer.product_name, lang)} }
p { {tx::INTRO.get(lang)} }
}
},
None => rsx! {
header { class: "chain-head",
h1 { {tx::CRUMB.get(lang)} }
p { {tx::NONE_OPEN.get(lang)} }
}
},
}
if open.len() > 1 {
nav { class: "offer-others", "aria-label": tx::OTHERS.get(lang),
span { class: "offer-others-title", {tx::OTHERS.get(lang)} }
for (i, o) in open.iter().enumerate() {
button {
key: "{o.id}",
class: if i == selected().min(open.len() - 1) { "offer-pick active" } else { "offer-pick" },
r#type: "button",
"aria-pressed": "{i == selected()}",
onclick: move |_| selected.set(i),
{tx::from(&o.product_name, &o.supplier_name, lang)}
}
}
}
}
if let (Some(offer), Some(found)) = (current.clone(), all_targets.clone()) {
OfferDecision {
key: "{offer.id}",
candidates: candidates(&found, &listed, &offer.supplier_name),
targets: found.clone(),
beyond_plan: beyond_plan(included, found.len()),
projects: all_projects.clone(),
offer,
can_write,
on_answered,
}
} else if current.is_some() {
div { class: "loading", {tx::LOADING.get(lang)} }
}
if !chain.is_empty() {
SupplyLines { rows: chain }
}
}
}
}
/// Prüfobjekte › Freigaben von Zulieferern.
#[component]
fn OfferCrumbs() -> Element {
let lang = use_lang()();
rsx! {
nav { class: "repo-crumbs", "aria-label": rv::BREADCRUMB.get(lang),
Link { to: Route::TargetsPage {}, {crate::i18n::texts::nav::TARGETS.get(lang)} }
span { class: "repo-crumb-sep", "aria-hidden": "true", "›" }
span { "aria-current": "page", {tx::CRUMB.get(lang)} }
}
}
}
/// One open offer: the supplier, the version on the way, where it can
/// arrive, what accepting means, and the answer.
#[component]
fn OfferDecision(
offer: OfferDto,
candidates: Vec<Candidate>,
targets: Vec<serde_json::Value>,
projects: Vec<Project>,
beyond_plan: bool,
can_write: bool,
on_answered: EventHandler<()>,
) -> Element {
let lang = use_lang()();
let mut toasts = use_context::<Toasts>();
let mut choice = use_signal(|| Choice::New);
let mut project = use_signal(String::new);
let mut asking = use_signal(|| false);
let mut declining = use_signal(|| false);
let mut busy = use_signal(|| false);
// Products and assemblies, the places a component can go.
let machines: Vec<&Project> = projects
.iter()
.filter(|p| p.kind == compliance_core::models::ProjectKind::Product)
.collect();
let parts: Vec<String> = if project().is_empty() {
Vec::new()
} else {
targets
.iter()
.filter(|t| project_ids_of(t).contains(&project()))
.map(|t| t["name"].as_str().unwrap_or_default().to_string())
.collect()
};
let shown: Vec<Candidate> = candidates.iter().take(SHOWN_COMPONENTS).cloned().collect();
let rest: Vec<Candidate> = candidates.iter().skip(SHOWN_COMPONENTS).cloned().collect();
// A component picked from the list takes the list's row.
let picked_rest = match choice() {
Choice::Existing(c) if rest.contains(&c) => Some(c),
_ => None,
};
let choices = 1 + shown.len() + usize::from(!rest.is_empty());
let geometry = DecisionGeometry::new(choices, !parts.is_empty());
let (height, trunk_y) = (geometry.height, geometry.trunk_y);
let supplier_top = trunk_y - SUPPLIER_H / 2;
let selected_row = match choice() {
Choice::New => 0,
Choice::Existing(c) => shown
.iter()
.position(|s| s == &c)
.map_or(choices - 1, |i| i + 1),
};
let has_version = offer.offered_label.is_some();
let parcel = offer
.offered_label
.as_deref()
.map(|l| tx::parcel(l, offer.offered_components, lang));
let accept_label = match choice() {
Choice::New => tx::ACCEPT_NEW.get(lang).to_string(),
Choice::Existing(c) if asking() => tx::confirm_replace(&c.name, lang),
Choice::Existing(c) => tx::accept_into(&c.name, lang),
};
let offer_id = offer.id.clone();
let product = offer.product_name.clone();
let decline_id = offer.id.clone();
let declined_product = offer.product_name.clone();
rsx! {
section { class: "rel-route", "aria-label": tx::ROUTE.get(lang),
div { class: "rel-canvas", style: "width: {WIDTH}px; height: {height}px;",
div {
class: "offer-frame",
"aria-hidden": "true",
style: "left: {FRAME_X}px; top: {FRAME_TOP}px; width: {FRAME_W}px; height: {geometry.frame_h}px;",
}
label { class: "offer-machine", r#for: "offer-machine", style: "left: {FRAME_X + 20}px; top: {FRAME_TOP + 10}px;",
span { "{tx::MACHINE.get(lang)}: " }
select {
id: "offer-machine",
disabled: choice() != Choice::New || !can_write,
onchange: move |e| project.set(e.value()),
option { value: "", selected: project().is_empty(), {tx::NO_MACHINE.get(lang)} }
for m in machines.iter() {
option { key: "{m.id}", value: "{m.id}", selected: project() == m.id, "{m.name}" }
}
}
}
svg { class: "rel-lines", width: "{WIDTH}", height: "{height}", "aria-hidden": "true",
defs {
marker { id: "offer-arrow", "markerWidth": "8", "markerHeight": "8", "refX": "6", "refY": "4", orient: "auto",
path { d: "M0 0 L8 4 L0 8 Z", class: "rel-arrow-head" }
}
}
path {
class: if has_version { "rel-line live" } else { "rel-line wait" },
d: "M {SUPPLIER_X + SUPPLIER_W} {trunk_y} H {JUNCTION_X}",
}
for (i, top) in geometry.option_y.iter().enumerate() {
{
let y = top + OPTION_H / 2;
let chosen = i == selected_row;
let end = if chosen { OPTION_X - 8 } else { OPTION_X };
rsx! {
path {
class: if chosen { "rel-line live" } else { "rel-line off" },
d: "M {JUNCTION_X} {trunk_y} V {y} H {end}",
"marker-end": if chosen { "url(#offer-arrow)" },
}
}
}
}
circle { class: "rel-dot live", cx: "{JUNCTION_X}", cy: "{trunk_y}", r: "5" }
}
div {
class: "rel-target",
style: "left: {SUPPLIER_X}px; top: {supplier_top}px; width: {SUPPLIER_W}px; height: {SUPPLIER_H}px;",
span { class: "rel-target-kind", {tx::SUPPLIER.get(lang)} }
span { class: "rel-target-name", title: "{offer.supplier_name}", "{offer.supplier_name}" }
}
span {
class: if has_version { "rel-chip parcel" } else { "rel-chip off" },
style: "left: {(SUPPLIER_X + SUPPLIER_W + JUNCTION_X) / 2}px; top: {trunk_y}px;",
{parcel.clone().unwrap_or_else(|| tx::NO_VERSION.get(lang).to_string())}
}
OptionButton {
top: geometry.option_y[0],
chosen: choice() == Choice::New,
enabled: can_write,
title: tx::AS_NEW.get(lang).to_string(),
sub: tx::created(&offer.product_name, lang),
on_pick: move |_| { choice.set(Choice::New); asking.set(false); },
}
if let Some(y) = geometry.parts_y {
div { class: "offer-parts", style: "left: {OPTION_X}px; top: {y}px; width: {OPTION_W}px; height: {PARTS_H}px;",
for part in parts.iter().take(SHOWN_PARTS) {
span { class: "offer-part", title: "{part}", "{part}" }
}
if parts.len() > SHOWN_PARTS {
span { class: "offer-part more", {tx::more_parts(parts.len() - SHOWN_PARTS, lang)} }
}
}
}
for (i, c) in shown.iter().enumerate() {
{
let picked = c.clone();
rsx! {
OptionButton {
key: "{c.id}",
top: geometry.option_y[i + 1],
chosen: choice() == Choice::Existing(c.clone()),
enabled: can_write,
title: tx::into(&c.name, lang),
sub: if has_version { tx::REPLACES.get(lang).to_string() } else { tx::REPLACES_LATER.get(lang).to_string() },
on_pick: move |_| { choice.set(Choice::Existing(picked.clone())); asking.set(false); },
}
}
}
}
if !rest.is_empty() {
{
let top = geometry.option_y[choices - 1];
let chosen = picked_rest.is_some();
let list = rest.clone();
rsx! {
div {
class: if chosen { "offer-option chosen" } else { "offer-option" },
style: "left: {OPTION_X}px; top: {top}px; width: {OPTION_W}px; height: {OPTION_H}px;",
select {
class: "offer-rest",
"aria-label": tx::OTHER_COMPONENT.get(lang),
disabled: !can_write,
onchange: move |e| {
let id = e.value();
asking.set(false);
match list.iter().find(|c| c.id == id) {
Some(c) => choice.set(Choice::Existing(c.clone())),
None => choice.set(Choice::New),
}
},
option { value: "", selected: !chosen, {tx::OTHER_COMPONENT.get(lang)} }
for c in rest.iter() {
option { key: "{c.id}", value: "{c.id}", selected: picked_rest.as_ref() == Some(c), "{c.name}" }
}
}
span { class: "offer-option-sub", if has_version { {tx::REPLACES.get(lang)} } else { {tx::REPLACES_LATER.get(lang)} } }
}
}
}
}
}
}
section { class: "offer-meaning", "aria-label": tx::MEANING.get(lang),
div { class: "offer-tile",
svg { width: "28", height: "28", view_box: "0 0 24 24", "aria-hidden": "true",
rect { x: "4", y: "4", width: "16", height: "16", rx: "4", fill: "none", stroke: "currentColor", stroke_width: "1.8" }
path { d: "M12 8.5v7M8.5 12h7", fill: "none", stroke: "currentColor", stroke_width: "1.8", stroke_linecap: "round" }
}
span {
match choice() {
Choice::New => rsx! {
b { {tx::ONE_MORE.get(lang)} }
br {}
span { class: if beyond_plan { "offer-tile-warn" } else { "offer-tile-sub" },
if beyond_plan { {tx::BILLED_EXTRA.get(lang)} } else { {tx::COUNTS_LIKE_ANY.get(lang)} }
}
},
Choice::Existing(_) => rsx! {
b { {tx::NO_NEW_TARGET.get(lang)} }
br {}
span { class: "offer-tile-sub",
if has_version { {tx::REPLACES.get(lang)} } else { {tx::REPLACES_LATER.get(lang)} }
}
},
}
}
}
div { class: "offer-tile",
svg { width: "28", height: "28", view_box: "0 0 24 24", "aria-hidden": "true",
path { d: "M4 12a8 8 0 0 1 13.7-5.6L20 8.5M20 4v4.5h-4.5M20 12a8 8 0 0 1-13.7 5.6L4 15.5M4 20v-4.5h4.5", fill: "none", stroke: "currentColor", stroke_width: "1.8", stroke_linecap: "round", stroke_linejoin: "round" }
}
span {
b { {tx::EVERY_VERSION.get(lang)} }
br {}
span { class: "offer-tile-sub", {tx::AND_IS_SCANNED.get(lang)} }
}
}
div { class: "offer-tile",
svg { width: "28", height: "28", view_box: "0 0 24 24", "aria-hidden": "true",
path { d: "M2.5 12s3.5-6.5 9.5-6.5S21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z", fill: "none", stroke: "currentColor", stroke_width: "1.8", stroke_linejoin: "round" }
circle { cx: "12", cy: "12", r: "3", fill: "none", stroke: "currentColor", stroke_width: "1.8" }
}
span {
b { {tx::ONLY_BOM.get(lang)} }
br {}
span { class: "offer-tile-sub", {tx::NO_FINDINGS.get(lang)} }
}
}
if can_write {
div { class: "offer-answer",
if declining() {
p { class: "offer-answer-note", {tx::DECLINE_HINT.get(lang)} }
button {
class: "btn offer-decline-confirm",
r#type: "button",
disabled: busy(),
onclick: move |_| {
let (id, product) = (decline_id.clone(), declined_product.clone());
busy.set(true);
spawn(async move {
match decline_offer(id).await {
Ok(_) => toasts.push(ToastType::Success, tx::declined(&product, lang)),
Err(e) => toasts.push(ToastType::Error, tx::refusal(&e.to_string(), lang)),
}
busy.set(false);
on_answered.call(());
});
},
{tx::DECLINE_CONFIRM.get(lang)}
}
button { class: "btn btn-ghost", r#type: "button", onclick: move |_| declining.set(false), {tx::CANCEL.get(lang)} }
} else {
button {
class: "btn btn-primary offer-accept",
r#type: "button",
disabled: busy(),
onclick: move |_| {
let to = match choice() {
Choice::Existing(_) if !asking() => {
// Replacing an uploaded SBOM is asked once more.
asking.set(true);
return;
}
Choice::Existing(c) => Destination { target_id: Some(c.id), ..Default::default() },
Choice::New => Destination {
name: Some(product.clone()),
project_ids: if project().is_empty() { Vec::new() } else { vec![project()] },
..Default::default()
},
};
let (id, product) = (offer_id.clone(), product.clone());
busy.set(true);
spawn(async move {
match accept_offer(id, to).await {
Ok(_) => toasts.push(ToastType::Success, tx::accepted(&product, lang)),
Err(e) => toasts.push(ToastType::Error, tx::refusal(&e.to_string(), lang)),
}
busy.set(false);
asking.set(false);
on_answered.call(());
});
},
"{accept_label}"
}
if asking() {
button { class: "btn btn-ghost", r#type: "button", onclick: move |_| asking.set(false), {tx::CANCEL.get(lang)} }
} else {
button { class: "btn btn-secondary", r#type: "button", disabled: busy(), onclick: move |_| declining.set(true), {tx::DECLINE.get(lang)} }
}
}
}
}
}
}
}
/// One choice in the machine's frame.
#[component]
fn OptionButton(
top: i32,
chosen: bool,
enabled: bool,
title: String,
sub: String,
on_pick: EventHandler<()>,
) -> Element {
rsx! {
button {
class: if chosen { "offer-option chosen" } else { "offer-option" },
style: "left: {OPTION_X}px; top: {top}px; width: {OPTION_W}px; height: {OPTION_H}px;",
r#type: "button",
"aria-pressed": "{chosen}",
disabled: !enabled,
onclick: move |_| on_pick.call(()),
span { class: "offer-radio", "aria-hidden": "true" }
span { class: "offer-option-text",
b { title: "{title}", "{title}" }
span { class: "offer-option-sub", "{sub}" }
}
}
}
}
/// The supply lines already running: supplier, the version that arrived,
/// the component it arrived in.
#[component]
fn SupplyLines(rows: Vec<ChainRow>) -> Element {
let lang = use_lang()();
let now = chrono::Utc::now();
let rows_i = i32::try_from(rows.len()).unwrap_or(i32::MAX / CHAIN_PITCH);
let height = CHAIN_TOP + rows_i * CHAIN_PITCH;
const LEFT_W: i32 = 200;
const RIGHT_X: i32 = 620;
const RIGHT_W: i32 = 260;
const BOX_H: i32 = 64;
rsx! {
section { class: "rel-train", "aria-labelledby": "offer-chain-h",
div { class: "rel-canvas plain", style: "width: {WIDTH}px; height: {height}px;",
h2 { id: "offer-chain-h", class: "offer-chain-title", {tx::CHAIN.get(lang)} }
Link { class: "offer-chain-link", to: Route::SupplyChainPage {}, {tx::CHAIN_LINK.get(lang)} }
for (i, row) in rows.iter().enumerate() {
{
let y = CHAIN_TOP + i32::try_from(i).unwrap_or(0) * CHAIN_PITCH;
let mid = y + BOX_H / 2;
let live = row.state == OfferState::Accepted && row.component.is_some();
let end = if live { RIGHT_X - 8 } else { RIGHT_X };
let chip = match (row.state, &row.delivered_label, &row.delivered_at) {
(OfferState::Accepted, Some(label), Some(at)) => format!("{label} {}", format_ago(at, &now, lang)),
(OfferState::Accepted, _, _) => tx::ACCEPTED_CHIP.get(lang).to_string(),
(_, label, _) => tx::ended(label.as_deref(), lang),
};
let component_name = row.component.as_ref().map_or_else(
|| tx::COMPONENT_GONE.get(lang).to_string(),
|(_, name)| name.clone(),
);
let aria = tx::line(&row.supplier, &component_name, &chip, lang);
let products = if row.products.is_empty() {
tx::IN_NO_PRODUCT.get(lang).to_string()
} else {
tx::in_products(&row.products.join(", "), lang)
};
rsx! {
svg { class: "rel-lines", width: "{WIDTH}", height: "{height}", role: "img", "aria-label": "{aria}",
path {
class: if live { "rel-line live" } else { "rel-line off" },
d: "M {40 + LEFT_W} {mid} H {end}",
"marker-end": if live { "url(#offer-chain-arrow)" },
}
if i == 0 {
defs {
marker { id: "offer-chain-arrow", "markerWidth": "8", "markerHeight": "8", "refX": "6", "refY": "4", orient: "auto",
path { d: "M0 0 L8 4 L0 8 Z", class: "rel-arrow-head" }
}
}
}
}
div {
class: if live { "offer-chain-supplier" } else { "offer-chain-supplier ended" },
style: "left: 40px; top: {y}px; width: {LEFT_W}px; height: {BOX_H}px;",
span { class: "rel-peer-name", title: "{row.supplier}", "{row.supplier}" }
}
span {
class: if live { "rel-chip live" } else { "rel-chip off" },
style: "left: {(40 + LEFT_W + RIGHT_X) / 2}px; top: {mid}px;",
"{chip}"
}
match &row.component {
Some((id, name)) => rsx! {
Link {
class: "rel-peer offer-chain-component",
style: "left: {RIGHT_X}px; top: {y}px; width: {RIGHT_W}px; height: {BOX_H}px;",
to: Route::target(id.clone()),
span { class: "rel-peer-name", title: "{name}", "{name}" }
span { class: "rel-peer-status", "{products}" }
}
},
None => rsx! {
div {
class: "rel-peer off",
style: "left: {RIGHT_X}px; top: {y}px; width: {RIGHT_W}px; height: {BOX_H}px;",
span { class: "rel-peer-status", {tx::COMPONENT_GONE.get(lang)} }
}
},
}
}
}
}
}
}
}
}
/// The open-offer count in the sidebar, read once, then kept by the page.
pub fn use_open_offers() -> Option<usize> {
let _read = use_resource(|| async {
if OPEN_OFFERS.peek().is_none() {
if let Ok(listed) = fetch_offers().await {
*OPEN_OFFERS.write() = Some(
listed
.iter()
.filter(|o| o.state == OfferState::Offered)
.count(),
);
}
}
});
OPEN_OFFERS()
}
/// The targets page's note about waiting offers.
#[component]
pub fn OffersWaiting() -> Element {
let lang = use_lang()();
let waiting = use_open_offers().filter(|n| *n > 0);
rsx! {
if let Some(n) = waiting {
Link { class: "offer-waiting", to: Route::SupplierOffersPage {},
span { class: "offer-waiting-dot", "aria-hidden": "true" }
span { {tx::waiting(n, lang)} }
span { class: "offer-waiting-go", {tx::OPEN_THEM.get(lang)} }
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::i18n::Lang;
use chrono::{TimeZone, Utc};
use compliance_core::models::{ProjectKind, ProjectLevel, TargetType};
fn offer(id: &str, state: OfferState, target: Option<&str>) -> OfferDto {
OfferDto {
id: id.into(),
supplier_name: "Beispiel Display".into(),
product_name: "HMI".into(),
product_type: TargetType::FirmwareRtos,
state,
target_id: target.map(String::from),
offered_at: Utc.with_ymd_and_hms(2026, 11, 10, 9, 0, 0).unwrap(),
ended_at: None,
delivered_label: None,
delivered_at: None,
offered_label: None,
offered_components: None,
}
}
fn target(
id: &str,
name: &str,
supplier: Option<&str>,
projects: &[&str],
) -> serde_json::Value {
serde_json::json!({
"_id": { "$oid": id },
"name": name,
"supplier": supplier.map(|s| serde_json::json!({ "name": s })),
"project_ids": projects,
})
}
#[test]
fn only_free_bought_in_components_are_choices_the_suppliers_own_first() {
let targets = [
target("t1", "Steuerung", None, &[]),
target("t2", "Antrieb", Some("Muster Antriebe"), &[]),
target("t3", "Display", Some("Beispiel Display"), &[]),
target("t4", "Funkmodul", Some("Muster Funk"), &[]),
];
let offers = [offer("o1", OfferState::Accepted, Some("t4"))];
let found = candidates(&targets, &offers, "beispiel display");
let names: Vec<&str> = found.iter().map(|c| c.name.as_str()).collect();
assert_eq!(
names,
["Display", "Antrieb"],
"own targets and taken ones are not choices"
);
}
#[test]
fn the_frame_holds_every_choice() {
for (choices, parts) in [(1, false), (1, true), (3, true), (4, false)] {
let g = DecisionGeometry::new(choices, parts);
assert_eq!(g.option_y.len(), choices);
let last = g.option_y[choices - 1] + OPTION_H;
assert!(
last <= FRAME_TOP + g.frame_h,
"{choices}/{parts}: inside the frame"
);
assert!(FRAME_TOP + g.frame_h <= g.height);
if let Some(y) = g.parts_y {
assert!(
y >= g.option_y[0] + OPTION_H,
"parts under the new component"
);
}
assert!(g.trunk_y - SUPPLIER_H / 2 >= 0);
}
}
#[test]
fn one_more_target_is_beyond_a_full_plan() {
assert!(!beyond_plan(Some(5), 4));
assert!(beyond_plan(Some(5), 5));
assert!(!beyond_plan(None, 500), "unlimited");
}
#[test]
fn the_supply_lines_are_the_running_and_the_ended_deliveries() {
let mut ended = offer("o2", OfferState::Ended, Some("gone"));
ended.delivered_label = Some("2.0.4".into());
let offers = [
offer("o1", OfferState::Accepted, Some("t3")),
ended,
offer("o3", OfferState::Declined, None),
offer("o4", OfferState::Ended, None),
];
let targets = [target("t3", "Display", Some("Beispiel Display"), &["p1"])];
let projects = [Project {
id: "p1".into(),
name: "Pumpstation PS-200".into(),
kind: ProjectKind::Product,
description: String::new(),
level: Some(ProjectLevel::Product),
parent_id: None,
}];
let rows = chain_rows(&offers, &targets, &projects);
assert_eq!(
rows.len(),
2,
"declined and never-delivered ended offers are not lines"
);
assert_eq!(rows[0].component, Some(("t3".into(), "Display".into())));
assert_eq!(rows[0].products, ["Pumpstation PS-200"]);
assert_eq!(rows[1].component, None, "its component was removed");
assert_eq!(
tx::ended(rows[1].delivered_label.as_deref(), Lang::De),
"beendet, 2.0.4 bleibt"
);
}
#[test]
fn an_offer_refusal_reads_in_words() {
assert_eq!(
tx::refusal(
"error running server function: target_taken (409) (details: None)",
Lang::De
),
"Diese Komponente erhält schon die SBOM eines anderen Zulieferers."
);
assert_eq!(tx::refusal("x (500)", Lang::De), "x (500)");
}
}
+30 -262
View File
@@ -14,13 +14,12 @@ use crate::components::page_header::PageHeader;
use crate::components::scan_coverage::ScanCoverage;
use crate::components::scan_runs::ScanRunList;
use crate::i18n::texts::{common, kinds, onboarding as tx};
use crate::i18n::{format_bytes, use_lang, Lang};
use crate::i18n::{format_bytes, use_lang};
use crate::infrastructure::onboarding::{
check_supplier_sbom, create_target, detect_target, enable_target_scans, fetch_applicable_scans,
is_file_kind, may_need_password, plc_format_for, set_archive_password,
trigger_new_content_scan, upload_problem, upload_target_artifact, validate_artifact_ref,
validate_target_name, ArchivePassword, ArtifactInputDto, PasswordOutcome, SbomCheck,
SbomSummary, SupplierDto,
create_target, detect_target, enable_target_scans, fetch_applicable_scans, is_file_kind,
plc_format_for, set_archive_password, trigger_new_content_scan, upload_target_artifact,
validate_artifact_ref, validate_target_name, ArchivePassword, ArtifactInputDto,
PasswordOutcome, UNSUPPORTED_ARCHIVE,
};
use crate::infrastructure::platform::{use_source_only, SourceOnlyNote};
@@ -30,29 +29,11 @@ fn is_runtime_kind(kind: &str) -> bool {
matches!(kind, "live_url")
}
/// What the agent said of a staged supplier SBOM (#1025), checked when it is
/// added so a file a scan cannot read is refused before the target exists.
#[derive(Debug, Clone, PartialEq)]
enum StagedCheck {
/// Not a supplier SBOM: nothing to check.
None,
/// The agent is reading it.
Checking,
/// A scan can read it.
Readable(SbomSummary),
/// Refused; the text says why.
Refused(String),
}
/// A file staged in the wizard. It holds the browser's file handle, not its
/// contents: the file is streamed straight from disk when it is uploaded, so a
/// 500 MB firmware image is never copied into WASM memory.
#[derive(Clone)]
struct PendingFile {
/// Which staged file this is, for the check's answer to find it.
id: usize,
/// The supplier SBOM check.
check: StagedCheck,
kind: String,
plc_format: Option<String>,
filename: String,
@@ -97,7 +78,7 @@ enum FirstScan {
}
#[component]
pub fn OnboardingPage(origin: String) -> Element {
pub fn OnboardingPage() -> Element {
let lang = use_lang()();
let can_write = use_can_write();
let mut step = use_signal(|| 0usize);
@@ -106,16 +87,7 @@ pub fn OnboardingPage(origin: String) -> Element {
let mut artifacts = use_signal(Vec::<ArtifactInputDto>::new);
// "Add artifact" mini-form.
// A component bought in brings its supplier's SBOM (`?origin=bought`).
let from_supplier = origin == "bought";
let mut new_kind = use_signal(move || {
if from_supplier {
"supplier_sbom"
} else {
"git_repo"
}
.to_string()
});
let mut new_kind = use_signal(|| "git_repo".to_string());
let mut new_source = use_signal(String::new);
let mut new_branch = use_signal(|| "main".to_string());
let mut new_token = use_signal(String::new);
@@ -124,13 +96,6 @@ pub fn OnboardingPage(origin: String) -> Element {
let mut new_plc_format = use_signal(|| "plcopen_xml".to_string());
let mut new_file = use_signal(|| Option::<(String, dioxus::html::FileData)>::None);
let mut pending_files = use_signal(Vec::<PendingFile>::new);
let mut staged_count = use_signal(|| 0usize);
// A bought-in component and its supplier (#1025).
let mut bought = use_signal(move || from_supplier);
let mut sup_name = use_signal(String::new);
let mut sup_product = use_signal(String::new);
let mut sup_version = use_signal(String::new);
let mut sup_csaf = use_signal(String::new);
// Create + result state.
let mut creating = use_signal(|| false);
@@ -148,38 +113,8 @@ pub fn OnboardingPage(origin: String) -> Element {
let source_only = use_source_only();
let step_now = step();
let name_error = validate_target_name(&name());
let csaf_invalid = SupplierDto::provider_is_invalid(&sup_csaf());
let supplier_ok = !bought() || (!sup_name().trim().is_empty() && !csaf_invalid);
let can_advance_type = name_error.is_none() && !target_type().trim().is_empty() && supplier_ok;
let supplier = bought().then(|| {
SupplierDto::from_fields(&sup_name(), &sup_product(), &sup_version(), &sup_csaf())
});
// A refused file is not uploaded; one still being read holds "Next".
let usable_files = pending_files()
.iter()
.filter(|f| !matches!(f.check, StagedCheck::Refused(_)))
.count();
let checking = pending_files()
.iter()
.any(|f| f.check == StagedCheck::Checking);
let has_artifacts = !artifacts().is_empty() || usable_files > 0;
// After the first step, the header says what is being onboarded.
let context = {
let mut parts = vec![name(), type_label_of(&target_type(), lang)];
if let Some(s) = supplier.as_ref().filter(|s| !s.name.is_empty()) {
parts.push(format!("{} {}", tx::FROM.get(lang), s.name));
}
parts.retain(|p| !p.is_empty());
parts.join(" · ")
};
// A bought-in component's SBOM first.
let artifact_kinds: Vec<(&'static str, crate::i18n::Text)> = {
let mut list = kinds::ARTIFACT_KINDS.to_vec();
if bought() {
list.sort_by_key(|(v, _)| *v != "supplier_sbom");
}
list
};
let can_advance_type = name_error.is_none() && !target_type().trim().is_empty();
let has_artifacts = !artifacts().is_empty() || !pending_files().is_empty();
let optin = if source_only {
Vec::new()
} else {
@@ -191,7 +126,7 @@ pub fn OnboardingPage(origin: String) -> Element {
} else {
validate_artifact_ref(&new_kind(), &new_source())
};
let type_label = move |value: &str| type_label_of(value, lang);
let type_label = move |value: &str| kinds::target_type(value, lang);
let kind_label = move |value: &str| kinds::artifact_kind(value, lang);
// Adding a target is a change: a read-only role only reads why not.
@@ -208,21 +143,14 @@ pub fn OnboardingPage(origin: String) -> Element {
rsx! {
PageHeader {
title: tx::TITLE.get(lang),
description: if step_now == 0 { tx::SUBTITLE.get(lang).to_string() } else { context.clone() },
description: tx::SUBTITLE.get(lang),
}
// Stepper.
div { class: "wizard-steps",
for (i, label) in tx::STEPS.iter().enumerate() {
div {
class: if i == step_now {
"wizard-step active"
} else if i < step_now {
"wizard-step completed"
} else {
"wizard-step"
},
"aria-current": if i == step_now { "step" } else { "false" },
class: if i == step_now { "wizard-step wizard-step-active" } else { "wizard-step" },
span { class: "wizard-step-dot", "{i + 1}" }
span { class: "wizard-step-label", {label.get(lang)} }
}
@@ -260,85 +188,6 @@ pub fn OnboardingPage(origin: String) -> Element {
span { {tx::DEMO_PROMPT.get(lang)} }
DemoTargetsButton { secondary: true }
}
h4 { class: "type-group-label",
{tx::ORIGIN.get(lang)}
" "
span { class: "badge badge-new", {tx::NEW.get(lang)} }
}
div { class: "origin-grid",
for (is_bought, title, hint) in [
(false, tx::ORIGIN_OWN, tx::ORIGIN_OWN_HINT),
(true, tx::ORIGIN_BOUGHT, tx::ORIGIN_BOUGHT_HINT),
] {
button {
r#type: "button",
class: "type-card",
"aria-pressed": if bought() == is_bought { "true" } else { "false" },
onclick: move |_| {
bought.set(is_bought);
// The SBOM is what a bought-in component brings.
if is_bought {
new_kind.set("supplier_sbom".to_string());
} else if new_kind() == "supplier_sbom" {
new_kind.set("git_repo".to_string());
}
},
span { class: "type-card-name", {title.get(lang)} }
span { class: "type-card-hint", {hint.get(lang)} }
}
}
}
if bought() {
div { class: "supplier-box",
h4 { class: "type-group-label supplier-box-title", {tx::SUPPLIER.get(lang)} }
div { class: "supplier-grid",
div { class: "form-group",
label { r#for: "sup-name", {tx::SUPPLIER.get(lang)} }
input {
id: "sup-name",
r#type: "text",
value: "{sup_name}",
oninput: move |e| sup_name.set(e.value()),
}
}
div { class: "supplier-grid",
div { class: "form-group",
label { r#for: "sup-product", {tx::PRODUCT.get(lang)} }
input {
id: "sup-product",
r#type: "text",
value: "{sup_product}",
oninput: move |e| sup_product.set(e.value()),
}
}
div { class: "form-group",
label { r#for: "sup-version", {tx::VERSION.get(lang)} }
input {
id: "sup-version",
r#type: "text",
value: "{sup_version}",
oninput: move |e| sup_version.set(e.value()),
}
}
}
}
div { class: "form-group",
label { r#for: "sup-csaf", {tx::CSAF_OPTIONAL.get(lang)} }
input {
id: "sup-csaf",
r#type: "url",
placeholder: "https://…/.well-known/csaf/provider-metadata.json",
value: "{sup_csaf}",
oninput: move |e| sup_csaf.set(e.value()),
}
if csaf_invalid {
div { class: "form-error", {tx::CSAF_HTTPS.get(lang)} }
}
div { class: "form-hint", {tx::CSAF_HINT.get(lang)} }
}
div { class: "form-hint", {tx::PRODUCT_HINT.get(lang)} }
}
}
for (group, range) in [
(tx::GROUP_MACHINE, 0..kinds::MACHINE_TYPES),
(tx::GROUP_SOFTWARE, kinds::MACHINE_TYPES..kinds::TARGET_TYPES.len()),
@@ -376,12 +225,6 @@ pub fn OnboardingPage(origin: String) -> Element {
// ---- Step 1: artifacts ----
if step_now == 1 {
div { class: "card-header", {tx::ATTACH.get(lang)} }
if bought() {
div { class: "callout-accent",
div { style: "font-weight: 600; margin-bottom: 2px;", {tx::BOUGHT_TITLE.get(lang)} }
{tx::BOUGHT_HINT.get(lang)}
}
}
if target_type() == "plc_sps" {
div {
style: "margin: 12px 16px 0; padding: 12px 14px; border-left: 3px solid var(--accent, #3b82f6); background: var(--surface-2, rgba(59,130,246,0.08)); font-size: 0.88em; line-height: 1.55;",
@@ -396,7 +239,7 @@ pub fn OnboardingPage(origin: String) -> Element {
select {
value: "{new_kind}",
oninput: move |e| new_kind.set(e.value()),
for (value, klabel) in artifact_kinds.iter().copied() {
for (value, klabel) in kinds::ARTIFACT_KINDS {
if source_only && is_runtime_kind(value) {
option { value: "{value}", disabled: true, title: common::NOT_AVAILABLE_HERE.get(lang),
"{klabel.get(lang)} — {common::NOT_AVAILABLE_HERE.get(lang)}"
@@ -460,30 +303,7 @@ pub fn OnboardingPage(origin: String) -> Element {
} else {
None
};
let id = staged_count();
staged_count.set(id + 1);
let sbom = kind == "supplier_sbom";
if sbom {
let file = data.clone();
spawn(async move {
let check = match check_supplier_sbom(file.into()).await {
Ok(SbomCheck::Readable(summary)) => StagedCheck::Readable(summary),
Ok(SbomCheck::Refused(code)) => StagedCheck::Refused(format!(
"{}: {}",
tx::REFUSED.get(lang),
tx::sbom_refusal(&code, lang)
)),
// Not checked: the upload checks it again.
Err(_) => StagedCheck::None,
};
if let Some(f) = pending_files.write().iter_mut().find(|f| f.id == id) {
f.check = check;
}
});
}
pending_files.write().push(PendingFile {
id,
check: if sbom { StagedCheck::Checking } else { StagedCheck::None },
kind,
plc_format,
filename: fname,
@@ -580,31 +400,14 @@ pub fn OnboardingPage(origin: String) -> Element {
// Staged file artifacts (uploaded after the target is created).
for (i, pf) in pending_files().iter().enumerate() {
div {
class: if matches!(pf.check, StagedCheck::Refused(_)) { "staged-file is-refused" } else { "staged-file" },
div { class: "staged-file-name",
span {
span { style: "opacity: 0.7;", "{kind_label(&pf.kind)} ({tx::FILE_SUFFIX.get(lang)}): " }
span { style: "font-family: var(--font-mono);", "{pf.filename}" }
" ({format_bytes(pf.file.size(), lang)})"
}
match &pf.check {
StagedCheck::None => rsx! {},
StagedCheck::Checking => rsx! {
span { class: "target-muted", {tx::SBOM_CHECKING.get(lang)} }
},
StagedCheck::Readable(summary) => rsx! {
span { class: "badge badge-accent",
{tx::sbom_summary(&summary.format, summary.components, summary.statements, lang)}
}
},
StagedCheck::Refused(why) => rsx! {
span { class: "staged-file-refusal", "{why}" }
},
}
style: "display: flex; justify-content: space-between; align-items: center; padding: 8px 12px; border: 1px solid var(--border, #333); border-radius: 6px; margin-top: 6px;",
span {
span { style: "opacity: 0.7;", "{kind_label(&pf.kind)} ({tx::FILE_SUFFIX.get(lang)}): " }
"{pf.filename} ({format_bytes(pf.file.size(), lang)})"
}
// Firmware images, build outputs and SBOMs are never
// unpacked; archives may be locked.
if may_need_password(&pf.kind) {
// Firmware images and build outputs are never unpacked;
// archives may be locked.
if pf.kind != "firmware_image" && pf.kind != "build_output" {
input {
r#type: "password",
autocomplete: "off",
@@ -622,9 +425,6 @@ pub fn OnboardingPage(origin: String) -> Element {
}
}
if new_kind() == "supplier_sbom" {
div { class: "form-hint", style: "margin-top: 8px;", {tx::SBOM_READ_ON_ADD.get(lang)} }
}
div { style: "margin-top: 16px;",
if has_artifacts {
for (i, a) in artifacts().iter().enumerate() {
@@ -658,14 +458,6 @@ pub fn OnboardingPage(origin: String) -> Element {
div { class: "wizard-summary",
div { strong { "{tx::NAME.get(lang)}: " } "{name()}" }
div { strong { "{tx::TYPE.get(lang)}: " } "{type_label(&target_type())}" }
if let Some(s) = supplier.clone() {
div {
strong { "{tx::SUPPLIER.get(lang)}: " }
"{s.name}"
if let Some(p) = s.product.as_ref() { " · {p}" }
if let Some(v) = s.version.as_ref() { " {v}" }
}
}
div { strong { "{tx::ARTIFACTS.get(lang)}:" } }
ul {
for a in artifacts() {
@@ -674,7 +466,7 @@ pub fn OnboardingPage(origin: String) -> Element {
if a.has_token { " ({tx::TOKEN_SET.get(lang)})" }
}
}
for pf in pending_files().into_iter().filter(|f| !matches!(f.check, StagedCheck::Refused(_))) {
for pf in pending_files() {
li { "{kind_label(&pf.kind)}: {pf.filename} ({format_bytes(pf.file.size(), lang)})" }
}
}
@@ -828,11 +620,6 @@ pub fn OnboardingPage(origin: String) -> Element {
artifacts.write().clear();
pending_files.write().clear();
new_file.set(None);
bought.set(false);
sup_name.set(String::new());
sup_product.set(String::new());
sup_version.set(String::new());
sup_csaf.set(String::new());
scans.write().clear();
suggested.set(None);
created_id.set(None);
@@ -860,7 +647,7 @@ pub fn OnboardingPage(origin: String) -> Element {
if step_now < 2 {
button {
class: "btn btn-primary",
disabled: (step_now == 0 && !can_advance_type) || (step_now == 1 && (!has_artifacts || checking)),
disabled: (step_now == 0 && !can_advance_type) || (step_now == 1 && !has_artifacts),
onclick: move |_| step.set(step() + 1),
{tx::NEXT.get(lang)}
}
@@ -872,17 +659,12 @@ pub fn OnboardingPage(origin: String) -> Element {
let n = name();
let tt = target_type();
let arts = artifacts();
// A refused SBOM is not uploaded.
let files: Vec<PendingFile> = pending_files()
.into_iter()
.filter(|f| !matches!(f.check, StagedCheck::Refused(_)))
.collect();
let sup = supplier.clone();
let files = pending_files();
creating.set(true);
error.set(None);
upload_errors.write().clear();
spawn(async move {
let id = match create_target(n, tt, None, arts, sup).await {
let id = match create_target(n, tt, None, arts).await {
Ok(resp) => resp
.data
.get("_id")
@@ -914,7 +696,12 @@ pub fn OnboardingPage(origin: String) -> Element {
.await
{
Err(e) => {
let msg = upload_problem(e.to_string(), lang);
let e = e.to_string();
let msg = if e.contains(UNSUPPORTED_ARCHIVE) {
common::UNSUPPORTED_ARCHIVE.get(lang).to_string()
} else {
e
};
upload_errors.write().push(format!("{fname}: {msg}"));
}
// A locked archive: store its password, or ask
@@ -980,29 +767,10 @@ pub fn OnboardingPage(origin: String) -> Element {
}
}
/// A target type's label; none chosen yet is empty.
fn type_label_of(value: &str, lang: Lang) -> String {
if value.is_empty() {
String::new()
} else {
kinds::target_type(value, lang)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_refused_supplier_sbom_upload_reads_in_the_readers_language() {
let error = "error running server function: supplier_sbom_refused:empty (details: None)";
assert_eq!(
upload_problem(error.to_string(), Lang::De),
format!("Abgelehnt: {}", tx::sbom_refusal("empty", Lang::De))
);
assert_eq!(upload_problem("boom".to_string(), Lang::En), "boom");
}
#[test]
fn only_unblocked_default_off_scans_are_opt_in() {
let scans = vec![
+3 -11
View File
@@ -22,7 +22,7 @@ use crate::pages::inbox::{bucket_texts, bucket_tone};
use crate::pages::target_views::RepoView;
use compliance_core::cve_history::{CveDay, CveHistory};
use compliance_core::models::inbox::{Bucket, InboxCounts, InboxTarget};
use compliance_core::models::{Project, ProjectKind, ScanRun, ScanRunStatus};
use compliance_core::models::{Project, ScanRun, ScanRunStatus};
/// Open findings the "Next up" list shows.
const NEXT_UP: usize = 6;
@@ -218,7 +218,7 @@ pub fn OverviewPage() -> Element {
h3 { {overview::EMPTY_TITLE.get(lang)} }
p { {overview::EMPTY_BODY.get(lang)} }
if can_write {
Link { to: Route::onboarding(""), class: "btn btn-primary",
Link { to: Route::OnboardingPage {}, class: "btn btn-primary",
{overview::EMPTY_ACTION.get(lang)}
}
}
@@ -355,13 +355,7 @@ fn ProjectSection(group: ProjectGroup, only: bool, lang: Lang) -> Element {
div { class: "ov-project",
div { class: "ov-project-head",
div { class: "ov-project-title",
// A product is a machine (#1026), with a page of its own.
match group.project.as_ref().filter(|p| p.kind == ProjectKind::Product) {
Some(p) => rsx! {
h4 { Link { to: Route::MachinePage { id: p.id.clone(), tab: String::new() }, "{name}" } }
},
None => rsx! { h4 { "{name}" } },
}
h4 { "{name}" }
span { "{summary}" }
}
if !trend.is_empty() {
@@ -602,8 +596,6 @@ mod tests {
name: name.to_string(),
kind: ProjectKind::Product,
description: String::new(),
level: None,
parent_id: None,
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more