//! The "Heute" inbox (#950) through the real API: cards in their buckets, //! decisions on a card through the findings' and VEX code, undo, and //! resubmission dates. //! //! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without //! one. #![allow(clippy::expect_used, clippy::unwrap_used)] mod common; use chrono::{Duration, Utc}; use compliance_core::models::inbox::{CardKey, InboxSnooze}; use compliance_core::models::{CveAlert, CveSource, Exploitation, KevEntry}; use mongodb::bson::{doc, oid::ObjectId, Document}; use serde_json::{json, Value}; use common::TestServer; /// A target id and its name. const TARGET: &str = "665f1c2ab0c4d1e2f3a4b5c6"; /// Whether a Mongo answers at the test URI. 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() } async fn tenant_db(server: &TestServer) -> mongodb::Database { let uri = std::env::var("TEST_MONGODB_URI") .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); mongodb::Client::with_uri_str(&uri) .await .unwrap() .database(&server.tenant_db_name()) } /// Store a finding; its id. async fn finding( db: &mongodb::Database, title: &str, scan_type: &str, severity: &str, status: &str, file: &str, ) -> String { let id = ObjectId::new(); let now = mongodb::bson::DateTime::now(); db.collection::("findings") .insert_one(doc! { "_id": id, "repo_id": TARGET, "fingerprint": format!("fp-{title}"), "scanner": "test", "scan_type": scan_type, "title": title, "description": title, "severity": severity, "status": status, "file_path": file, "line_number": 7, "triage_action": if status == "needs_review" { "dismiss" } else { "confirm" }, "status_history": [], "created_at": now, "updated_at": now, }) .await .unwrap(); id.to_hex() } /// Store a CVE alert of log4j-core 2.14.1; its id. async fn alert(db: &mongodb::Database, cve: &str, kev: bool) -> String { let mut a = CveAlert::new( cve.into(), TARGET.into(), "log4j-core".into(), "2.14.1".into(), CveSource::Osv, ); let id = ObjectId::new(); a.id = Some(id); a.severity = Some("CRITICAL".into()); a.fixed_versions = vec!["2.17.1".into()]; if kev { a.exploitation = Some(Exploitation { kev: Some(KevEntry { date_added: "2021-12-10".into(), known_ransomware: true, }), ..Exploitation::default() }); a.exploited_seen_at = Some(Utc::now() - Duration::hours(2)); } db.collection::("cve_alerts") .insert_one(&a) .await .unwrap(); id.to_hex() } async fn inbox(server: &TestServer, query: &str) -> Value { let resp = server.get(&format!("/api/v1/inbox{query}")).await; assert_eq!(resp.status(), 200); let body: Value = resp.json().await.unwrap(); body["data"].clone() } fn counts(view: &Value) -> [u64; 4] { let c = &view["counts"]; [ c["today"].as_u64().unwrap(), c["this_week"].as_u64().unwrap(), c["later"].as_u64().unwrap(), c["likely_false_positive"].as_u64().unwrap(), ] } #[tokio::test] async fn the_inbox_buckets_decides_undoes_and_resubmits() { if !mongo_reachable().await { eprintln!("SKIP inbox: no MongoDB reachable"); return; } let server = TestServer::start().await; let db = tenant_db(&server).await; db.collection::("onboarded_targets") .insert_one(doc! { "_id": ObjectId::parse_str(TARGET).unwrap(), "name": "Pumpe", "target_type": "software" }) .await .unwrap(); let secret = finding( &db, "AWS key", "secretdetection", "medium", "open", "src/config.rs", ) .await; let _test_secret = finding( &db, "Test key", "secretdetection", "low", "open", "tests/keys.env", ) .await; let high = finding(&db, "SQL injection", "sast", "high", "triaged", "src/db.rs").await; let ai = finding( &db, "Weak hash", "sast", "medium", "needs_review", "src/hash.rs", ) .await; finding( &db, "Old decision", "sast", "low", "false_positive", "src/a.rs", ) .await; let a1 = alert(&db, "CVE-2021-44228", true).await; let a2 = alert(&db, "CVE-2021-45046", false).await; // Today: the secret in code and log4j (KEV); this week: the high finding; // later: the test secret; the AI's: the dismissed one. let all = inbox(&server, "").await; assert_eq!(counts(&all), [2, 1, 1, 1]); assert_eq!(all["progress"], json!({ "decided": 1, "total": 7 })); assert_eq!( all["targets"], json!([{ "id": TARGET, "name": "Pumpe", "counts": { "today": 2, "this_week": 1, "later": 1, "likely_false_positive": 1 }, }]) ); let today = all["cards"].as_array().unwrap(); let log4j = today .iter() .find(|c| c["kind"] == "cve_package") .unwrap() .clone(); let log4j_key = CardKey::cve_package(TARGET, "log4j-core", "2.14.1"); assert_eq!(log4j["key"], log4j_key); assert_eq!(log4j["count"], 2); assert_eq!(log4j["fix_version"], "2.17.1"); assert_eq!(log4j["reasons"][0]["kind"], "kev"); assert!(today .iter() .any(|c| c["item_ids"] == json!([secret]) && c["reasons"][0]["kind"] == "secret_in_code")); let ai_card = inbox(&server, "?bucket=likely_false_positive").await["cards"][0].clone(); assert_eq!(ai_card["actions"], json!(["false_positive", "confirm"])); assert_eq!(inbox(&server, "?target=other").await["counts"]["today"], 0); // A CVE decision needs its justification; with it, every alert of the // card gets the statement, and undo puts them back to open. let refused = server .post( "/api/v1/inbox/decide", &json!({ "key": log4j_key, "action": "not_affected" }), ) .await; assert_eq!(refused.status(), 422); let decided = server .post( "/api/v1/inbox/decide", &json!({ "key": log4j_key, "action": "not_affected", "justification": "vulnerable_code_not_in_execute_path", }), ) .await; assert_eq!(decided.status(), 200); let decided: Value = decided.json().await.unwrap(); let mut previous = decided["previous"].as_array().unwrap().clone(); previous.sort_by_key(|p| p["id"].as_str().unwrap().to_string()); let mut expected = vec![ json!({ "kind": "cve", "id": a1, "vex": null }), json!({ "kind": "cve", "id": a2, "vex": null }), ]; expected.sort_by_key(|p| p["id"].as_str().unwrap().to_string()); assert_eq!(previous, expected); let stored = db .collection::("cve_alerts") .find_one(doc! { "_id": ObjectId::parse_str(&a1).unwrap() }) .await .unwrap() .unwrap(); assert_eq!( stored.vex.map(|v| v.status), Some(compliance_core::models::VexStatus::NotAffected) ); let after = inbox(&server, "").await; assert_eq!(counts(&after), [1, 1, 1, 1]); assert_eq!(after["progress"], json!({ "decided": 3, "total": 7 })); let again = server .post( "/api/v1/inbox/decide", &json!({ "key": log4j_key, "action": "affected", "statement": "Update" }), ) .await; assert_eq!(again.status(), 409, "nothing left to decide"); let undone = server .post( "/api/v1/inbox/undo", &json!({ "key": log4j_key, "previous": decided["previous"] }), ) .await; assert_eq!(undone.status(), 200); assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 1]); // A finding's risk needs a reason; the status change is recorded as the // findings endpoint records it, and undo restores the previous status. let high_key = CardKey::finding(&high); let no_reason = server .post( "/api/v1/inbox/decide", &json!({ "key": high_key, "action": "accepted_risk" }), ) .await; assert_eq!(no_reason.status(), 422); let not_offered = server .post( "/api/v1/inbox/decide", &json!({ "key": high_key, "action": "confirm" }), ) .await; assert_eq!(not_offered.status(), 422); let accepted: Value = server .post( "/api/v1/inbox/decide", &json!({ "key": high_key, "action": "accepted_risk", "reason": "isolated network" }), ) .await .json() .await .unwrap(); assert_eq!( accepted["previous"], json!([{ "kind": "finding", "id": high, "status": "triaged" }]) ); let stored = db .collection::("findings") .find_one(doc! { "_id": ObjectId::parse_str(&high).unwrap() }) .await .unwrap() .unwrap(); assert_eq!(stored.get_str("status").ok(), Some("accepted_risk")); let history = stored.get_array("status_history").unwrap(); assert_eq!( history[0].as_document().unwrap().get_str("reason").ok(), Some("isolated network") ); assert_eq!(counts(&inbox(&server, "").await), [2, 0, 1, 1]); let undone = server .post( "/api/v1/inbox/undo", &json!({ "key": high_key, "previous": accepted["previous"] }), ) .await; assert_eq!(undone.status(), 200); assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 1]); // Undo only touches the card's own items. let foreign = server .post( "/api/v1/inbox/undo", &json!({ "key": high_key, "previous": [{ "kind": "finding", "id": ai, "status": "open" }] }), ) .await; assert_eq!(foreign.status(), 422); // The AI was right: the dismissed finding is a false positive. let confirmed = server .post( "/api/v1/inbox/decide", &json!({ "key": CardKey::finding(&ai), "action": "false_positive" }), ) .await; assert_eq!(confirmed.status(), 200); assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 0]); // Put off: hidden until the date, then back in its own bucket (today). let secret_key = CardKey::finding(&secret); let past = server .post( "/api/v1/inbox/snooze", &json!({ "key": secret_key, "for": { "kind": "date", "date": "2020-01-01" } }), ) .await; assert_eq!(past.status(), 422); let snoozed = server .post( "/api/v1/inbox/snooze", &json!({ "key": secret_key, "for": { "kind": "week" } }), ) .await; assert_eq!(snoozed.status(), 200); assert_eq!(counts(&inbox(&server, "").await), [1, 1, 1, 0]); let record = db .collection::("inbox_snoozes") .find_one(doc! { "key": &secret_key }) .await .unwrap() .unwrap(); assert_eq!(record.by, "dev-user"); assert!(record.until > Utc::now() + Duration::days(6)); // The card's items are recorded, so a new one would end the snooze early. assert_eq!(record.items, std::slice::from_ref(&secret)); db.collection::("inbox_snoozes") .update_one( doc! { "key": &secret_key }, doc! { "$set": { "until": mongodb::bson::DateTime::from_chrono(Utc::now() - Duration::hours(1)) } }, ) .await .unwrap(); let due = inbox(&server, "?bucket=today").await; assert_eq!(counts(&due), [2, 1, 1, 0]); assert!(due["cards"] .as_array() .unwrap() .iter() .any(|c| c["key"] == secret_key && c["reasons"][0]["kind"] == "resubmission")); let unsnoozed = server .delete(&format!("/api/v1/inbox/snooze/{secret_key}")) .await; assert_eq!(unsnoozed.status(), 200); assert_eq!(counts(&inbox(&server, "").await), [2, 1, 1, 0]); server.cleanup().await; }