diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 8a3cb7e..1758238 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -62,6 +62,14 @@ jobs: runs-on: docker container: image: rust:1.94-bookworm + # The agent's integration tests run against a real MongoDB (as the nightly + # does); without one they had rotted unnoticed since the M7.2 tenant split. + services: + mongo: + image: mongo:7 + env: + MONGO_INITDB_ROOT_USERNAME: root + MONGO_INITDB_ROOT_PASSWORD: example steps: - name: Checkout run: | @@ -142,6 +150,10 @@ jobs: # compliance-core's integration tests need no services. - name: Tests (core integration) run: cargo test -p compliance-core --tests + - name: Tests (agent integration) + run: cargo test -p compliance-agent --test '*' + env: + TEST_MONGODB_URI: mongodb://root:example@mongo:27017/?authSource=admin - name: Tests (dashboard server) run: cargo test -p compliance-dashboard --features server --no-default-features - name: Tests (dashboard web) diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 9cd82a4..f21425c 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -516,36 +516,13 @@ pub async fn delete_target( .await; // DAST targets linked to this target, and all their downstream data. - if let Ok(mut cursor) = db.dast_targets().find(doc! { "repo_id": &id }).await { - use futures_util::StreamExt; - while let Some(Ok(dt)) = cursor.next().await { - let dast_target_id = dt.id.map(|oid| oid.to_hex()).unwrap_or_default(); - if !dast_target_id.is_empty() { - cascade_delete_dast_target(db, &dast_target_id).await; - } - } + for dast_target_id in ids_of(db.dast_targets(), doc! { "repo_id": &id }).await { + cascade_delete_dast_target(db, &dast_target_id).await; } // Pentest sessions linked directly to this target (not via a DAST target). - if let Ok(mut cursor) = db.pentest_sessions().find(doc! { "repo_id": &id }).await { - use futures_util::StreamExt; - while let Some(Ok(session)) = cursor.next().await { - let session_id = session.id.map(|oid| oid.to_hex()).unwrap_or_default(); - if !session_id.is_empty() { - let _ = db - .attack_chain_nodes() - .delete_many(doc! { "session_id": &session_id }) - .await; - let _ = db - .pentest_messages() - .delete_many(doc! { "session_id": &session_id }) - .await; - let _ = db - .dast_findings() - .delete_many(doc! { "session_id": &session_id }) - .await; - } - } + for session_id in ids_of(db.pentest_sessions(), doc! { "repo_id": &id }).await { + delete_session_data(db, &session_id).await; } let _ = db .pentest_sessions() @@ -555,32 +532,32 @@ pub async fn delete_target( Ok(Json(serde_json::json!({ "status": "deleted" }))) } +/// The `_id`s (hex) of the documents in `coll` that match `filter`, read raw +/// with only `_id` projected: a document stored in another shape (an older +/// version, a manual insert) is still found, so a cascade never stops at it +/// and leaves its downstream data behind. +async fn ids_of( + coll: mongodb::Collection, + filter: mongodb::bson::Document, +) -> Vec { + use futures_util::StreamExt; + let raw = coll.clone_with_type::(); + let mut out = Vec::new(); + if let Ok(mut cursor) = raw.find(filter).projection(doc! { "_id": 1 }).await { + while let Some(next) = cursor.next().await { + if let Ok(Ok(oid)) = next.as_ref().map(|d| d.get_object_id("_id")) { + out.push(oid.to_hex()); + } + } + } + out +} + /// Delete a DAST target and everything downstream of it (pentest sessions + /// their attack chains / messages / findings, DAST scan runs + findings). async fn cascade_delete_dast_target(db: &crate::database::Database, target_id: &str) { - use futures_util::StreamExt; - if let Ok(mut cursor) = db - .pentest_sessions() - .find(doc! { "target_id": target_id }) - .await - { - while let Some(Ok(session)) = cursor.next().await { - let session_id = session.id.map(|oid| oid.to_hex()).unwrap_or_default(); - if !session_id.is_empty() { - let _ = db - .attack_chain_nodes() - .delete_many(doc! { "session_id": &session_id }) - .await; - let _ = db - .pentest_messages() - .delete_many(doc! { "session_id": &session_id }) - .await; - let _ = db - .dast_findings() - .delete_many(doc! { "session_id": &session_id }) - .await; - } - } + for session_id in ids_of(db.pentest_sessions(), doc! { "target_id": target_id }).await { + delete_session_data(db, &session_id).await; } let _ = db .pentest_sessions() @@ -599,6 +576,22 @@ async fn cascade_delete_dast_target(db: &crate::database::Database, target_id: & } } +/// The attack chain, messages and findings of one pentest session. +async fn delete_session_data(db: &crate::database::Database, session_id: &str) { + let _ = db + .attack_chain_nodes() + .delete_many(doc! { "session_id": session_id }) + .await; + let _ = db + .pentest_messages() + .delete_many(doc! { "session_id": session_id }) + .await; + let _ = db + .dast_findings() + .delete_many(doc! { "session_id": session_id }) + .await; +} + /// POST /api/v1/targets/{id}/artifacts — attach an artifact (by reference). #[tracing::instrument(skip_all, fields(target_id = %id))] pub async fn add_artifact( diff --git a/compliance-agent/tests/common/mod.rs b/compliance-agent/tests/common/mod.rs index ab60f2d..85b1c0e 100644 --- a/compliance-agent/tests/common/mod.rs +++ b/compliance-agent/tests/common/mod.rs @@ -161,6 +161,14 @@ impl TestServer { &self.db_name } + /// The database the API reads and writes for the unauthenticated dev + /// tenant (`_dev`, M7.2-D). Tests that seed data directly must + /// write here; `db_name()` alone is never opened by the agent. + #[allow(dead_code)] // not every test binary seeds data + pub fn tenant_db_name(&self) -> String { + format!("{}_dev", self.db_name) + } + /// Drop every per-tenant database belonging to this test run. /// Post-M7.2-D the agent never opens a `db_name` directly — /// data lives only in `_` per-tenant databases. diff --git a/compliance-agent/tests/integration/api/cascade_delete.rs b/compliance-agent/tests/integration/api/cascade_delete.rs index 3208b20..c45e754 100644 --- a/compliance-agent/tests/integration/api/cascade_delete.rs +++ b/compliance-agent/tests/integration/api/cascade_delete.rs @@ -6,7 +6,7 @@ async fn insert_dast_target(server: &TestServer, repo_id: &str, name: &str) -> S 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.db_name()); + let db = client.database(&server.tenant_db_name()); let result = db .collection::("dast_targets") @@ -30,7 +30,7 @@ async fn insert_pentest_session(server: &TestServer, target_id: &str, repo_id: & 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.db_name()); + let db = client.database(&server.tenant_db_name()); let result = db .collection::("pentest_sessions") @@ -54,7 +54,7 @@ async fn insert_attack_node(server: &TestServer, session_id: &str) { 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.db_name()); + let db = client.database(&server.tenant_db_name()); db.collection::("attack_chain_nodes") .insert_one(mongodb::bson::doc! { @@ -73,7 +73,7 @@ async fn insert_dast_finding(server: &TestServer, target_id: &str, session_id: & 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.db_name()); + let db = client.database(&server.tenant_db_name()); db.collection::("dast_findings") .insert_one(mongodb::bson::doc! { @@ -99,7 +99,7 @@ async fn count_docs(server: &TestServer, collection: &str) -> u64 { 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.db_name()); + let db = client.database(&server.tenant_db_name()); db.collection::(collection) .count_documents(mongodb::bson::doc! {}) .await @@ -175,7 +175,7 @@ async fn delete_repo_cascades_sast_findings_and_sbom() { 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.db_name()); + let db = client.database(&server.tenant_db_name()); let now = mongodb::bson::DateTime::now(); db.collection::("findings") diff --git a/compliance-agent/tests/integration/api/dast.rs b/compliance-agent/tests/integration/api/dast.rs index 67d13b7..2125d5a 100644 --- a/compliance-agent/tests/integration/api/dast.rs +++ b/compliance-agent/tests/integration/api/dast.rs @@ -18,7 +18,7 @@ async fn add_and_list_dast_targets() { &json!({ "name": "test-app", "base_url": "https://test-app.example.com", - "target_type": "webapp", + "target_type": "web_app", }), ) .await; diff --git a/compliance-agent/tests/integration/api/findings.rs b/compliance-agent/tests/integration/api/findings.rs index 9656a1d..7a68617 100644 --- a/compliance-agent/tests/integration/api/findings.rs +++ b/compliance-agent/tests/integration/api/findings.rs @@ -14,7 +14,7 @@ async fn insert_finding(server: &TestServer, repo_id: &str, title: &str, severit // Get the DB name from the test server by parsing the health response // For now, we use a direct insert approach - let db = client.database(server.db_name()); + let db = client.database(&server.tenant_db_name()); let now = mongodb::bson::DateTime::now(); db.collection::("findings") diff --git a/compliance-agent/tests/integration/api/health.rs b/compliance-agent/tests/integration/api/health.rs index 97bd07b..ededee1 100644 --- a/compliance-agent/tests/integration/api/health.rs +++ b/compliance-agent/tests/integration/api/health.rs @@ -22,7 +22,7 @@ async fn stats_overview_returns_zeroes_on_empty_db() { let body: serde_json::Value = resp.json().await.unwrap(); let data = &body["data"]; - assert_eq!(data["repositories"], 0); + assert_eq!(data["total_repositories"], 0); assert_eq!(data["total_findings"], 0); server.cleanup().await; diff --git a/compliance-agent/tests/integration/api/onboarding.rs b/compliance-agent/tests/integration/api/onboarding.rs index 30a832a..2925708 100644 --- a/compliance-agent/tests/integration/api/onboarding.rs +++ b/compliance-agent/tests/integration/api/onboarding.rs @@ -235,7 +235,7 @@ async fn the_list_pages_with_a_total_after_the_project_filter() { .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap(); let targets = client - .database(&format!("{}_dev", server.db_name())) + .database(&server.tenant_db_name()) .collection::("onboarded_targets"); for id in &ids[1..] { let oid = mongodb::bson::oid::ObjectId::parse_str(id).unwrap(); diff --git a/compliance-agent/tests/integration/api/sbom.rs b/compliance-agent/tests/integration/api/sbom.rs index 5f50623..c2a98e7 100644 --- a/compliance-agent/tests/integration/api/sbom.rs +++ b/compliance-agent/tests/integration/api/sbom.rs @@ -39,7 +39,7 @@ async fn the_sbom_lists_components_in_the_image_first_and_filters_by_it() { .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap(); // The dev tenant's database, which the API reads. - let db = client.database(&format!("{}_dev", server.db_name())); + let db = client.database(&server.tenant_db_name()); let entries = [ recipe("aaa-tools", false), recipe("busybox", true), diff --git a/compliance-agent/tests/integration/api/stats.rs b/compliance-agent/tests/integration/api/stats.rs index f66b5f1..bec1a2c 100644 --- a/compliance-agent/tests/integration/api/stats.rs +++ b/compliance-agent/tests/integration/api/stats.rs @@ -21,7 +21,7 @@ async fn stats_overview_reflects_inserted_data() { 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.db_name()); + let db = client.database(&server.tenant_db_name()); let now = mongodb::bson::DateTime::now(); for (title, severity) in [ @@ -52,10 +52,10 @@ async fn stats_overview_reflects_inserted_data() { let body: serde_json::Value = resp.json().await.unwrap(); let data = &body["data"]; - assert_eq!(data["repositories"], 1); + assert_eq!(data["total_repositories"], 1); assert_eq!(data["total_findings"], 4); - assert_eq!(data["critical"], 1); - assert_eq!(data["high"], 1); + assert_eq!(data["critical_findings"], 1); + assert_eq!(data["high_findings"], 1); server.cleanup().await; } @@ -68,7 +68,7 @@ async fn stats_update_after_finding_status_change() { 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.db_name()); + let db = client.database(&server.tenant_db_name()); let now = mongodb::bson::DateTime::now(); let result = db @@ -102,11 +102,11 @@ async fn stats_update_after_finding_status_change() { ) .await; - // The finding still exists (status changed, not deleted) + // The overview counts open findings only (open, triaged, needs_review): + // a resolved one drops out, though the finding itself is kept. let resp = server.get("/api/v1/stats/overview").await; let body: serde_json::Value = resp.json().await.unwrap(); - // total_findings counts all findings regardless of status - assert_eq!(body["data"]["total_findings"], 1); + assert_eq!(body["data"]["total_findings"], 0); server.cleanup().await; }