//! 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::component_changes::{ComponentChange, ComponentChangeKind}; 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`, with the /// component changes it recorded. async fn run( db: &mongodb::Database, status: ScanRunStatus, start: DateTime, end: Option>, components: Option>, ) { let mut run = ScanRun::new(TARGET.into(), ScanTrigger::Scheduled); run.status = status; run.started_at = start; run.completed_at = end; run.component_changes = components; db.collection::("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, resolved: Option>, ) { 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::("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 { 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::("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)), None).await; run(&db, ScanRunStatus::Failed, hour(24), Some(hour(25)), None).await; // The last one recorded its components (#974): openssl was updated. let updated = ComponentChange { kind: ComponentChangeKind::Updated, package_manager: "npm".into(), name: "openssl".into(), from: Some("3.0.9".into()), to: Some("3.0.11".into()), }; run( &db, ScanRunStatus::Completed, hour(48), Some(hour(49)), Some(vec![updated]), ) .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"]); // The update took the gone CVE (at 3.0.9). The new one names 3.0.9 too, // which the update left, so no change explains it: an advisory row, // after the change of the same component. assert!(changes[0].get("components").is_none(), "not recorded"); let rows = changes[2]["components"].as_array().unwrap(); let read: Vec<(&str, &str, u64, u64)> = rows .iter() .map(|r| { ( r["kind"].as_str().unwrap(), r["name"].as_str().unwrap(), r["cves_new"].as_u64().unwrap(), r["cves_gone"].as_u64().unwrap(), ) }) .collect(); assert_eq!( read, [("updated", "openssl", 0, 1), ("advisory", "openssl", 1, 0)] ); // 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; }