feat(api): a machine's history, its parts' scans newest first (#1026)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m29s
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 / Check (pull_request) Canceled after 10m45s
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m29s
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 / Check (pull_request) Canceled after 10m45s
GET /api/v1/projects/{id}/scan-changes merges the last scans of the
machine's parts, newest first, each with its part and what it changed
(new and gone CVEs, components added, updated and removed), as a
target's own history; a target's history moves into a helper both use.
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
294fd06274
commit
6522e32c51
5 files changed
+148
-12
No files matched your search
@@ -4,7 +4,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use axum::extract::{Extension, Path};
|
||||
use axum::extract::{Extension, Path, Query};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::Json;
|
||||
@@ -18,6 +18,7 @@ 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};
|
||||
@@ -452,3 +453,69 @@ pub async fn machine_cves(
|
||||
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)]
|
||||
|
||||
@@ -49,6 +49,7 @@ fn described_routes() -> OpenApiRouter {
|
||||
.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
|
||||
|
||||
@@ -229,3 +229,53 @@ async fn a_machine_shows_its_parts_and_their_open_cves_together() {
|
||||
|
||||
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;
|
||||
}
|
||||
+5
-1
@@ -514,7 +514,11 @@ 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.
|
||||
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
|
||||
|
||||
|
||||
Reference in new issue
Block a user