feat(api): the machine page's overview, CVEs and history (#1026) #1037
No files matched your search
@@ -2,20 +2,83 @@
|
||||
//! the targets assigned to it, in-house ones and components bought in from
|
||||
//! suppliers (#1025). Its documents cover all of them.
|
||||
|
||||
use axum::extract::{Extension, Path};
|
||||
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::models::{OnboardedTarget, ProjectKind, SbomEntry, TargetType};
|
||||
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};
|
||||
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`.
|
||||
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
|
||||
@@ -82,24 +145,11 @@ pub async fn export_machine_sbom(
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<impl IntoResponse, 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 (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);
|
||||
}
|
||||
let ids: Vec<String> = targets
|
||||
.iter()
|
||||
.filter_map(|t| t.id.map(|o: ObjectId| o.to_hex()))
|
||||
.collect();
|
||||
// The supplier's product is the part itself, not one of its components.
|
||||
let of_parts = doc! {
|
||||
"repo_id": { "$in": &ids },
|
||||
@@ -144,3 +194,331 @@ pub async fn export_machine_sbom(
|
||||
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.
|
||||
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,
|
||||
}))
|
||||
}
|
||||
@@ -64,11 +64,30 @@ 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(query.limit).unwrap_or(i64::MAX))
|
||||
.limit(i64::try_from(limit).unwrap_or(i64::MAX))
|
||||
.await
|
||||
.map_err(db_error("listing the runs"))?,
|
||||
)
|
||||
@@ -79,7 +98,7 @@ pub async fn target_scan_changes(
|
||||
Some(oldest) => db
|
||||
.scan_runs()
|
||||
.find_one(doc! {
|
||||
"repo_id": &id,
|
||||
"repo_id": id,
|
||||
"status": "completed",
|
||||
"started_at": { "$lt": BsonDateTime::from_chrono(oldest) },
|
||||
})
|
||||
@@ -90,7 +109,7 @@ pub async fn target_scan_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(
|
||||
@@ -112,12 +131,7 @@ pub async fn target_scan_changes(
|
||||
)
|
||||
.await;
|
||||
|
||||
let data = changes(&runs, since, &alerts);
|
||||
Ok(Json(ApiResponse {
|
||||
total: Some(data.len() as u64),
|
||||
data,
|
||||
page: None,
|
||||
}))
|
||||
Ok(changes(&runs, since, &alerts))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -47,6 +47,9 @@ fn described_routes() -> OpenApiRouter {
|
||||
.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::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
|
||||
|
||||
@@ -103,3 +103,179 @@ async fn a_machine_without_parts_has_no_sbom() {
|
||||
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;
|
||||
}
|
||||
@@ -91,6 +91,17 @@ 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()
|
||||
|
||||
@@ -514,6 +514,21 @@ and the components bought in from suppliers. `GET
|
||||
targets, has no SBOM (422). More than 100,000 components are refused (413),
|
||||
as for one target.
|
||||
|
||||
`GET /api/v1/projects/{id}/overview` shows the machine at a glance. It has
|
||||
each part with its supplier, open CVEs and last scan. Across the parts it
|
||||
gives the open CVEs by severity, the ones nobody has stated anything on yet
|
||||
(and how many of those the supplier states something on), the components
|
||||
(each once, and how many sit in more than one part) and the suppliers'
|
||||
advisories. `GET /api/v1/projects/{id}/cves` lists the machine's open CVEs
|
||||
grouped by component across its parts, with each alert naming its part
|
||||
(`repo_id`). A component in two parts is one group. Whether it affects the
|
||||
machine is still stated per part, because the vulnerable code may be reached
|
||||
in one part and not in the other. `GET /api/v1/projects/{id}/scan-changes`
|
||||
is the machine's history: the last scans of its parts, newest first, each
|
||||
naming its part (`part`) and what it changed, as in a target's history. A
|
||||
supplier's new version shows as its product updated (`from` → `to`) in a
|
||||
part bought in.
|
||||
|
||||
## VEX: the status of each vulnerability
|
||||
|
||||
For each known vulnerability (CVE alert) of a target you state whether the
|
||||
|
||||
Reference in new issue
Block a user