feat(api): a machine at a glance, and its open CVEs by component across its parts (#1026)
GET /api/v1/projects/{id}/overview: the machine's parts with their
supplier, open CVEs and last scan; across them the open and undecided
CVEs (and the undecided ones the supplier states something on), the
components each once and how many parts share, and the suppliers'
advisories. GET /api/v1/projects/{id}/cves: the open alerts of all parts,
grouped by component; a component in two parts is one group, its alerts
still decided per part. Both resolve the machine as the SBOM export does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
This commit is contained in:
1 parent
90d5c8f8d1
commit
0ed4e510b9
5 files changed
+474
-16
No files matched your search
@@ -2,20 +2,82 @@
|
||||
//! 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};
|
||||
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::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 +144,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 +193,262 @@ 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, a CVE counted once per component.
|
||||
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 = 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 {
|
||||
name: machine.name,
|
||||
parts,
|
||||
open: open_counts(&alerts),
|
||||
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,
|
||||
}))
|
||||
}
|
||||
@@ -47,6 +47,8 @@ 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::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
|
||||
|
||||
Reference in new issue
Block a user