Files
pruefwerk/compliance-agent/tests/scan_changes.rs
T
Sharang ParnerkarandClaude Opus 5.5 b136dd041e
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m25s
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Check (pull_request) Successful in 19m56s
feat(dashboard): CRA Annex I tiles and the scan history chart (#957)
The two views the repo tabs still showed as placeholders, as in the mockup:

- CRA Annex I: the 40 requirements as tiles, ten to a row, coloured by state
  and marked with a sign (! ? ~ OK –) so the state is never told by colour
  alone, with a legend and counts. A tile opens the requirement (in the
  URL, ?control=cra-ai-3) with its state, findings and reason, reusing the
  CRA page's row.
- Verlauf: per scan the CVE alerts found new above the line and those found
  gone below it, with the run's status, and a table view. A scan opens what
  it changed (?scan=<run id>): each CVE with component, version and
  severity. New: GET /api/v1/targets/{id}/scan-changes and
  compliance_core::scan_changes. A completed scan's window runs from the end
  of the completed scan before it; the first is the baseline; scans that did
  not complete change nothing. Which components a scan added, updated or
  removed is not stored, and the view says so.

Docs: the target's page and its views in the targets guide; the overview's
repo cards with their Heute buckets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 22:03:08 +01:00

149 lines
4.9 KiB
Rust

//! A target's "Verlauf" (#957) through the real API: per scan the CVE
//! alerts found new and gone since the completed scan before it.
//!
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
//! one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use chrono::{DateTime, Duration, Utc};
use compliance_core::models::{CveAlert, CveSource, ScanRun, ScanRunStatus, ScanTrigger};
use mongodb::bson::{doc, oid::ObjectId, Document};
use serde_json::Value;
use common::TestServer;
const TARGET: &str = "665f1c2ab0c4d1e2f3a4b5c7";
async fn mongo_reachable() -> bool {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let Ok(client) = mongodb::Client::with_uri_str(&uri).await else {
return false;
};
client
.database("admin")
.run_command(doc! { "ping": 1 })
.await
.is_ok()
}
/// Store a run of the target that started `start` and ended `end`.
async fn run(
db: &mongodb::Database,
status: ScanRunStatus,
start: DateTime<Utc>,
end: Option<DateTime<Utc>>,
) {
let mut run = ScanRun::new(TARGET.into(), ScanTrigger::Scheduled);
run.status = status;
run.started_at = start;
run.completed_at = end;
db.collection::<ScanRun>("scan_runs")
.insert_one(&run)
.await
.unwrap();
}
/// Store an alert of the target found at `created`, gone at `resolved`.
async fn alert(
db: &mongodb::Database,
cve: &str,
created: DateTime<Utc>,
resolved: Option<DateTime<Utc>>,
) {
let mut a = CveAlert::new(
cve.into(),
TARGET.into(),
"openssl".into(),
"3.0.9".into(),
CveSource::Osv,
);
a.severity = Some("HIGH".into());
a.created_at = created;
a.resolved_at = resolved;
db.collection::<CveAlert>("cve_alerts")
.insert_one(&a)
.await
.unwrap();
}
/// The CVE ids of a change's `side` (`new_cves` or `gone_cves`).
fn cves(change: &Value, side: &str) -> Vec<String> {
change[side]
.as_array()
.unwrap()
.iter()
.map(|c| c["cve"].as_str().unwrap().to_string())
.collect()
}
#[tokio::test]
async fn each_scan_shows_the_cves_it_found_new_and_gone() {
if !mongo_reachable().await {
eprintln!("SKIP scan_changes: no MongoDB reachable");
return;
}
let server = TestServer::start().await;
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());
db.collection::<Document>("onboarded_targets")
.insert_one(doc! { "_id": ObjectId::parse_str(TARGET).unwrap(), "name": "Pumpe", "target_type": "software" })
.await
.unwrap();
// Arrange: three scans, the middle one failed; one CVE from the first
// scan goes in the last, one comes with it.
let t0 = Utc::now() - Duration::days(3);
let hour = |h: i64| t0 + Duration::hours(h);
run(&db, ScanRunStatus::Completed, hour(0), Some(hour(1))).await;
run(&db, ScanRunStatus::Failed, hour(24), Some(hour(25))).await;
run(&db, ScanRunStatus::Completed, hour(48), Some(hour(49))).await;
alert(&db, "CVE-2026-1001", hour(1), Some(hour(49))).await;
alert(&db, "CVE-2026-1002", hour(1), None).await;
alert(&db, "CVE-2026-1003", hour(49), None).await;
// Act
let resp = server
.get(&format!("/api/v1/targets/{TARGET}/scan-changes"))
.await;
assert_eq!(resp.status(), 200);
let body: Value = resp.json().await.unwrap();
let changes = body["data"].as_array().unwrap();
// Assert: oldest first; the first is the baseline, the failed one
// changes nothing, the last has one new and one gone.
assert_eq!(changes.len(), 3);
assert_eq!(changes[0]["baseline"], true);
assert!(cves(&changes[0], "new_cves").is_empty());
assert_eq!(changes[1]["status"], "failed");
assert!(cves(&changes[1], "new_cves").is_empty());
assert_eq!(cves(&changes[2], "new_cves"), ["CVE-2026-1003"]);
assert_eq!(cves(&changes[2], "gone_cves"), ["CVE-2026-1001"]);
// With a limit the oldest scans drop out, and the window of the first
// shown one starts at the end of the completed scan before it.
let resp = server
.get(&format!("/api/v1/targets/{TARGET}/scan-changes?limit=1"))
.await;
let body: Value = resp.json().await.unwrap();
let changes = body["data"].as_array().unwrap();
assert_eq!(changes.len(), 1);
assert_eq!(changes[0]["baseline"], false);
assert_eq!(cves(&changes[0], "new_cves"), ["CVE-2026-1003"]);
// An unknown target is a 404.
let resp = server
.get("/api/v1/targets/665f1c2ab0c4d1e2f3a4b5ff/scan-changes")
.await;
assert_eq!(resp.status(), 404);
server.cleanup().await;
}