use crate::common::TestServer; use compliance_core::models::SbomEntry; use serde_json::json; /// Create a target named `name`, with `supplier` when it is bought in, and /// return its id. async fn target(server: &TestServer, name: &str, supplier: Option) -> String { let resp = server .post( "/api/v1/targets", &json!({ "name": name, "target_type": "firmware_rtos", "supplier": supplier }), ) .await; assert_eq!(resp.status(), 200); let body: serde_json::Value = resp.json().await.unwrap(); body["data"]["_id"]["$oid"].as_str().unwrap().to_string() } /// An SBOM entry of target `target`. fn entry(target: &str, name: &str, manager: &str, purl: Option<&str>) -> SbomEntry { let mut e = SbomEntry::new(target.into(), name.into(), "1.0".into(), manager.into()); e.purl = purl.map(String::from); e } #[tokio::test] async fn a_machines_sbom_lists_its_parts_with_their_suppliers_and_components() { let server = TestServer::start().await; 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" })), ) .await; let retired = target(&server, "Alte Steuerung", None).await; let elsewhere = target(&server, "Andere Maschine", 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()); // Projects are registry-owned, so assign the targets directly. let targets = db.collection::("onboarded_targets"); for id in [&controller, &drive, &retired] { let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap(); let mut set = mongodb::bson::doc! { "project_ids": ["m1"] }; if id == &retired { set.insert("archived_at", mongodb::bson::DateTime::now()); } targets .update_one( mongodb::bson::doc! { "_id": oid }, mongodb::bson::doc! { "$set": set }, ) .await .unwrap(); } db.collection::("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), // The bought-in product itself, as a scan stores it. entry(&drive, "Drive Control", "supplier-product", None), entry( &retired, "openssl", "generic", Some("pkg:generic/openssl@1.0"), ), entry(&elsewhere, "zlib", "generic", Some("pkg:generic/zlib@1.0")), ]) .await .unwrap(); let resp = server.get("/api/v1/projects/m1/sbom").await; assert_eq!(resp.status(), 200); let doc: serde_json::Value = resp.json().await.unwrap(); assert_eq!(doc["metadata"]["component"]["type"], "device"); let components = doc["components"].as_array().unwrap(); let names: Vec<&str> = components .iter() .map(|c| c["name"].as_str().unwrap()) .collect(); // The parts by name, then their components once each; nothing of the // archived target or another machine, and the product is the part. assert_eq!(names, ["Antrieb", "Steuerung", "lodash", "vendor-blob"]); assert_eq!(components[0]["supplier"]["name"], "Example Drives GmbH"); assert_eq!(components[0]["version"], "4.2.1"); // The dev tenant's workspace makes the controller. assert_eq!(components[1]["supplier"]["name"], "dev"); server.cleanup().await; } #[tokio::test] async fn a_machine_without_parts_has_no_sbom() { let server = TestServer::start().await; let resp = server.get("/api/v1/projects/empty/sbom").await; 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::("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::("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 = [ alert(&controller, "CVE-2021-23337", "lodash", "high"), decided, on_product, gone, ] .into_iter() .map(|a| serde_json::from_value(a).unwrap()) .collect(); db.collection::("cve_alerts") .insert_many(alerts) .await .unwrap(); let key = format!("supplier:{provider}"); db.collection::("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::("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::("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; }