diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 0f17152..660150d 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -12,7 +12,8 @@ use mongodb::bson::{doc, oid::ObjectId, to_bson}; use serde::{Deserialize, Serialize}; use compliance_core::models::{ - ArtifactKind, ComplianceProfile, Credentials, OnboardedTarget, PlcFormat, ScanRun, TargetType, + ArtifactKind, ComplianceProfile, Credentials, Finding, OnboardedTarget, PlcFormat, ScanRun, + TargetType, }; use compliance_core::scan_matrix::{applicable_scans, supports_pentest}; use compliance_core::tenant_ctx::TenantCtx; @@ -100,16 +101,27 @@ pub async fn list_targets( Vec::new() } }; - let ids = targets + let ids: Vec = targets .iter() .filter_map(|t| t.id.map(|id| id.to_hex())) .collect(); - let mut last_scans = latest_scan_runs(&db.scan_runs(), ids).await; + // `join!` borrows its futures' arguments, so the collections need names. + let (runs, findings) = (db.scan_runs(), db.findings()); + let (mut last_scans, counts) = tokio::join!( + latest_scan_runs(&runs, ids.clone()), + findings_counts(&findings, ids), + ); let data = targets .redacted() .into_iter() - .map(|target| { - let last_scan = target.id.and_then(|id| last_scans.remove(&id.to_hex())); + .map(|mut target| { + let hex = target.id.map(|id| id.to_hex()).unwrap_or_default(); + // The stored count only moves when a scan runs; manual findings, + // imports and deletions change the real number, so count now. + if let Some(count) = counts.as_ref() { + target.findings_count = count.get(&hex).copied().unwrap_or(0); + } + let last_scan = last_scans.remove(&hex); TargetListItem { target, last_scan } }) .collect(); @@ -165,6 +177,44 @@ async fn latest_scan_runs( } } +/// The number of findings of each target in `target_ids`, in one query. +/// +/// Targets without findings are absent from the map. `None` when the query +/// fails, so the caller keeps the stored counts instead of showing zeros. +async fn findings_counts( + findings: &mongodb::Collection, + target_ids: Vec, +) -> Option> { + use futures_util::StreamExt; + + if target_ids.is_empty() { + return Some(HashMap::new()); + } + // Findings store their target's id as `repo_id`. + let pipeline = vec![ + doc! { "$match": { "repo_id": { "$in": target_ids } } }, + doc! { "$group": { "_id": "$repo_id", "count": { "$sum": 1 } } }, + ]; + match findings.aggregate(pipeline).await { + Ok(cursor) => Some( + cursor + .filter_map(|row| async move { + let row = row.ok()?; + let id = row.get_str("_id").ok()?.to_string(); + // `$sum` over ones yields an int32 for any count a target can hold. + let count = u32::try_from(row.get_i32("count").ok()?).ok()?; + Some((id, count)) + }) + .collect() + .await, + ), + Err(e) => { + tracing::warn!("Failed to count the targets' findings: {e}"); + None + } + } +} + /// POST /api/v1/targets — create an onboarded target. #[tracing::instrument(skip_all)] pub async fn create_target( diff --git a/compliance-agent/tests/manual_findings.rs b/compliance-agent/tests/manual_findings.rs index ca9af9b..680108e 100644 --- a/compliance-agent/tests/manual_findings.rs +++ b/compliance-agent/tests/manual_findings.rs @@ -174,6 +174,24 @@ async fn pentest_findings_are_added_and_imported_once() { .expect("imported finding"); assert_eq!(nuclei["file_path"], "https://192.0.2.10/login"); + // The targets list counts them, although no scan has run. + let list: serde_json::Value = h + .client + .get(format!("{}/api/v1/targets", h.base_url)) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let listed = list["data"] + .as_array() + .unwrap() + .iter() + .find(|t| t["_id"]["$oid"] == id.as_str()) + .expect("target in the list"); + assert_eq!(listed["findings_count"], 3); + h.pool.drop_tenant(TENANT).await.ok(); }