diff --git a/Cargo.lock b/Cargo.lock index 12abab2..37b39ac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4772,9 +4772,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "log", "once_cell", diff --git a/compliance-agent/src/api/handlers/platform.rs b/compliance-agent/src/api/handlers/platform.rs index c4a8662..0a011d8 100644 --- a/compliance-agent/src/api/handlers/platform.rs +++ b/compliance-agent/src/api/handlers/platform.rs @@ -472,6 +472,9 @@ pub struct PlatformTarget { pub last_scan_at: Option>, /// Findings that still need attention. pub open_findings: u64, + /// Known vulnerabilities in its components that are still open: CVE + /// alerts neither resolved nor assessed `not_affected` / `fixed`. + pub open_vulnerabilities: u64, /// Its projects that the registry still lists. pub project_ids: Vec, } @@ -481,23 +484,56 @@ async fn open_findings_counts( db: &crate::database::Database, target_ids: Vec, ) -> Result, StatusCode> { - let pipeline = vec![ - doc! { "$match": { - "repo_id": { "$in": target_ids }, - "status": { "$in": super::health::OPEN_STATUSES.to_vec() }, - } }, - doc! { "$group": { "_id": "$repo_id", "n": { "$sum": 1 } } }, - ]; let rows: Vec = db .findings() - .aggregate(pipeline) + .aggregate(count_by_target(doc! { + "repo_id": { "$in": target_ids }, + "status": { "$in": super::health::OPEN_STATUSES.to_vec() }, + })) .await .map_err(internal)? .try_collect() .await .map_err(internal)?; - Ok(rows - .iter() + Ok(counts_by_target(&rows)) +} + +/// The CVE alerts that still need a decision: not resolved by a later scan +/// and not assessed as `not_affected` or `fixed` in VEX. +fn open_vulnerabilities_filter(target_ids: Vec) -> Document { + doc! { + "repo_id": { "$in": target_ids }, + "resolved_at": null, + "vex.status": { "$nin": ["not_affected", "fixed"] }, + } +} + +/// Open vulnerabilities (CVE alerts) of each target in `target_ids`, in one +/// query. +async fn open_vulnerabilities_counts( + db: &crate::database::Database, + target_ids: Vec, +) -> Result, StatusCode> { + let rows: Vec = db + .cve_alerts() + .aggregate(count_by_target(open_vulnerabilities_filter(target_ids))) + .await + .map_err(internal)? + .try_collect() + .await + .map_err(internal)?; + Ok(counts_by_target(&rows)) +} + +fn count_by_target(filter: Document) -> Vec { + vec![ + doc! { "$match": filter }, + doc! { "$group": { "_id": "$repo_id", "n": { "$sum": 1 } } }, + ] +} + +fn counts_by_target(rows: &[Document]) -> std::collections::HashMap { + rows.iter() .filter_map(|row| { let id = row.get_str("_id").ok()?.to_string(); let n = row @@ -507,7 +543,7 @@ async fn open_findings_counts( .ok()?; Some((id, u64::try_from(n).ok()?)) }) - .collect()) + .collect() } /// `GET /api/v1/platform/tenants/{id}/targets?project=` — the tenant's @@ -538,11 +574,12 @@ pub async fn list_targets( .filter_map(|t| t.id.map(|id| id.to_hex())) .collect(); let runs = db.scan_runs(); - let (mut last_scans, open) = tokio::join!( + let (mut last_scans, open, vulns) = tokio::join!( super::onboarding::latest_scan_runs(&runs, ids.clone()), - open_findings_counts(&db, ids), + open_findings_counts(&db, ids.clone()), + open_vulnerabilities_counts(&db, ids), ); - let open = open?; + let (open, vulns) = (open?, vulns?); let known = super::projects::tenant_projects(&st.agent, &tenant_id) .await .ok(); @@ -553,6 +590,7 @@ pub async fn list_targets( PlatformTarget { last_scan_at: last_scans.remove(&id).map(|run| run.started_at), open_findings: open.get(&id).copied().unwrap_or(0), + open_vulnerabilities: vulns.get(&id).copied().unwrap_or(0), project_ids: match known.as_deref() { Some(known) => super::projects::known_project_ids(&t.project_ids, known), None => t.project_ids, @@ -782,3 +820,51 @@ mod build_info_tests { assert!(!BUILD_COMMIT.is_empty()); } } + +#[cfg(test)] +mod target_count_tests { + use super::*; + + #[test] + fn open_vulnerabilities_leave_out_resolved_and_assessed_alerts() { + let f = open_vulnerabilities_filter(vec!["a".into(), "b".into()]); + assert_eq!( + f.get_document("repo_id") + .unwrap() + .get_array("$in") + .unwrap() + .len(), + 2 + ); + assert_eq!(f.get("resolved_at"), Some(&mongodb::bson::Bson::Null)); + let nin = f + .get_document("vex.status") + .unwrap() + .get_array("$nin") + .unwrap(); + assert_eq!( + nin, + &vec![ + mongodb::bson::Bson::from("not_affected"), + mongodb::bson::Bson::from("fixed") + ] + ); + } + + #[test] + fn counts_are_read_per_target_whatever_the_integer_width() { + let rows = vec![ + doc! { "_id": "a", "n": 3_i32 }, + doc! { "_id": "b", "n": 5_i64 }, + doc! { "_id": "c", "n": -1_i64 }, + doc! { "n": 2_i32 }, + ]; + let counts = counts_by_target(&rows); + assert_eq!(counts.get("a"), Some(&3)); + assert_eq!(counts.get("b"), Some(&5)); + assert_eq!(counts.len(), 2); + let stages = count_by_target(doc! { "x": 1 }); + assert_eq!(stages.len(), 2); + assert!(stages[0].contains_key("$match") && stages[1].contains_key("$group")); + } +}