feat(supply-chain): the supply chain as a graph (#1051) #1055
No files matched your search
@@ -66,7 +66,10 @@ async fn machine(
|
||||
}
|
||||
|
||||
/// The open CVE alerts of the targets `ids`.
|
||||
async fn open_alerts(db: &Database, ids: &[String]) -> Result<Vec<CveAlert>, StatusCode> {
|
||||
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 })
|
||||
@@ -324,7 +327,7 @@ async fn machine_advisories(
|
||||
}
|
||||
|
||||
/// The open CVEs per severity of `alerts`, a CVE counted once per component.
|
||||
fn open_counts<'a>(alerts: impl IntoIterator<Item = &'a CveAlert>) -> SeverityCounts {
|
||||
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()
|
||||
|
||||
@@ -34,6 +34,7 @@ pub mod scan_changes;
|
||||
pub mod scans;
|
||||
pub mod supplier;
|
||||
pub mod supplier_invites;
|
||||
pub mod supply_chain;
|
||||
pub mod support;
|
||||
pub mod target_input;
|
||||
pub mod vex;
|
||||
|
||||
@@ -137,6 +137,8 @@ mod tests {
|
||||
name: format!("Projekt {id}"),
|
||||
kind: ProjectKind::Product,
|
||||
description: String::new(),
|
||||
level: None,
|
||||
parent_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,576 @@
|
||||
//! 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::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 {
|
||||
/// The supplier uploads it through an active invite link (#1027).
|
||||
Invite,
|
||||
/// 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())
|
||||
}
|
||||
|
||||
/// How `target`'s SBOM arrives from its supplier: through an active invite
|
||||
/// (`invited`), else as an upload once there is one.
|
||||
fn delivery(target: &OnboardedTarget, invited: bool) -> Delivery {
|
||||
let sbom = target
|
||||
.artifacts
|
||||
.iter()
|
||||
.filter(|a| a.kind == ArtifactKind::SupplierSbom)
|
||||
.max_by_key(|a| a.ingested_at);
|
||||
let how = match (invited, sbom) {
|
||||
(true, _) => DeliveryKind::Invite,
|
||||
(false, Some(_)) => DeliveryKind::Upload,
|
||||
(false, 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
|
||||
/// * `invited` - the targets with an active supplier invite
|
||||
pub fn supply_chain(
|
||||
targets: &[OnboardedTarget],
|
||||
projects: &[Project],
|
||||
open: &HashMap<String, SeverityCounts>,
|
||||
invited: &HashSet<String>,
|
||||
) -> 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, invited.contains(&id))),
|
||||
});
|
||||
}
|
||||
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 }
|
||||
}
|
||||
|
||||
/// 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 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 invited = invited_targets(&db, &ids).await?;
|
||||
Ok(Json(ApiResponse {
|
||||
data: supply_chain(&targets, &projects, &open, &invited),
|
||||
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 invited = HashSet::from([id(&targets[1])]);
|
||||
|
||||
let chain = supply_chain(&targets, &projects, &HashMap::new(), &invited);
|
||||
|
||||
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 components_are_part_of_products_and_assemblies_of_their_product() {
|
||||
let (targets, projects) = machine();
|
||||
let chain = supply_chain(&targets, &projects, &HashMap::new(), &HashSet::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, &HashSet::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, &HashSet::new());
|
||||
let b = chain.nodes.iter().find(|n| n.key == "project:b").unwrap();
|
||||
assert_eq!(b.open, Some(counts(0, 1, 0)));
|
||||
}
|
||||
|
||||
#[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"]);
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,7 @@ fn described_routes() -> OpenApiRouter {
|
||||
.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::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
|
||||
|
||||
@@ -7,3 +7,4 @@ mod onboarding;
|
||||
mod openapi;
|
||||
mod sbom;
|
||||
mod stats;
|
||||
mod supply_chain;
|
||||
@@ -0,0 +1,105 @@
|
||||
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");
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
@@ -81,7 +81,7 @@ pub use pentest::{
|
||||
PentestStatus, PentestStrategy, SeverityDistribution, TestUserRecord, TesterInfo,
|
||||
ToolCallRecord,
|
||||
};
|
||||
pub use project::{Project, ProjectKind};
|
||||
pub use project::{Project, ProjectKind, ProjectLevel};
|
||||
pub use repository::ScanTrigger;
|
||||
pub use sbom::{
|
||||
ComponentHash, InImage, InImageBasis, SbomEntry, SbomQuality, SbomQualityCheck,
|
||||
|
||||
@@ -16,6 +16,19 @@ 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)]
|
||||
@@ -26,6 +39,23 @@ 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)]
|
||||
@@ -42,5 +72,22 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,8 @@ mod tests {
|
||||
name: name.to_string(),
|
||||
kind: ProjectKind::Product,
|
||||
description: String::new(),
|
||||
level: None,
|
||||
parent_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -602,6 +602,8 @@ mod tests {
|
||||
name: name.to_string(),
|
||||
kind: ProjectKind::Product,
|
||||
description: String::new(),
|
||||
level: None,
|
||||
parent_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user