diff --git a/compliance-agent/src/pipeline/graph_build.rs b/compliance-agent/src/pipeline/graph_build.rs index df6070c..63b3ede 100644 --- a/compliance-agent/src/pipeline/graph_build.rs +++ b/compliance-agent/src/pipeline/graph_build.rs @@ -9,6 +9,9 @@ use super::orchestrator::{GraphContext, PipelineOrchestrator}; use super::plc::PlcFile; use crate::error::AgentError; +/// How long the DAST stage waits for one target's scan. +const DAST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20 * 60); + /// The most nodes a graph build parses. const GRAPH_MAX_NODES: u32 = 50_000; @@ -105,7 +108,10 @@ impl PipelineOrchestrator { }) } - /// Trigger DAST scan if a target is configured for this repo + /// The DAST stage: scan every DAST target of `repo_id` and wait for the + /// scans (#998). A scan that does not complete is recorded as the `dast` + /// stage with [`SkipCode::ToolFailed`](compliance_core::models::SkipCode); + /// it fails the stage, not the run. pub(super) async fn maybe_trigger_dast(&self, repo_id: &str, scan_run_id: &str) { use futures_util::TryStreamExt; @@ -132,29 +138,62 @@ impl PipelineOrchestrator { for mut target in targets { self.secrets.open_in_place(&mut target); - let db = self.db.clone(); - let scan_run_id = scan_run_id.to_string(); - let net_guard = self.net_guard; - tokio::spawn(async move { - let orchestrator = compliance_dast::DastOrchestrator::new(100, net_guard); - match orchestrator.run_scan(&target, Vec::new()).await { - Ok((mut scan_run, findings)) => { - scan_run.sast_scan_run_id = Some(scan_run_id); - if let Err(e) = db.dast_scan_runs().insert_one(&scan_run).await { - tracing::error!("Failed to store DAST scan run: {e}"); - } - for finding in &findings { - if let Err(e) = db.dast_findings().insert_one(finding).await { - tracing::error!("Failed to store DAST finding: {e}"); - } - } - tracing::info!("DAST scan complete: {} findings", findings.len()); - } - Err(e) => { - tracing::error!("DAST scan failed: {e}"); - } - } - }); + if let Some(failed) = self.run_dast_target(&target, scan_run_id).await { + self.skip_stage(scan_run_id, failed).await; + } } } + + /// Scan one DAST target, waiting for the result (#998), and store the + /// scan run and its findings. + /// + /// # Returns + /// + /// The `dast` stage entry to record when the scan did not complete: it + /// failed, timed out, or its run could not be stored. `None` when it + /// completed. The error itself goes to the log only. + async fn run_dast_target( + &self, + target: &compliance_core::models::DastTarget, + scan_run_id: &str, + ) -> Option { + use compliance_core::models::{DastScanStatus, SkipCode, SkippedStage}; + + // The subject names the tool, as for the other stages: the dashboard + // reads it as "DAST did not complete". The log names the target. + let failed = |reason: &str| { + Some(SkippedStage::new("dast", SkipCode::ToolFailed, reason).about("DAST")) + }; + let orchestrator = compliance_dast::DastOrchestrator::new(100, self.net_guard); + let scan = tokio::time::timeout(DAST_TIMEOUT, orchestrator.run_scan(target, Vec::new())); + let (mut run, findings) = match scan.await { + Ok(Ok(result)) => result, + Ok(Err(e)) => { + tracing::error!(target = %target.name, "DAST scan failed: {e}"); + return failed("DAST did not complete"); + } + Err(_) => { + tracing::error!(target = %target.name, "DAST scan timed out"); + return failed("DAST did not complete in time"); + } + }; + run.sast_scan_run_id = Some(scan_run_id.to_string()); + if let Err(e) = self.db.dast_scan_runs().insert_one(&run).await { + tracing::error!("Failed to store DAST scan run: {e}"); + return failed("DAST results could not be stored"); + } + for finding in &findings { + if let Err(e) = self.db.dast_findings().insert_one(finding).await { + tracing::error!("Failed to store DAST finding: {e}"); + } + } + tracing::info!(target = %target.name, findings = findings.len(), "DAST scan done"); + if run.status == DastScanStatus::Failed { + // `error_message` is the scanner's English reason ("Login: ...", + // "Reconnaissance failed: ..."); the run keeps it in full. + tracing::warn!(target = %target.name, error = ?run.error_message, "DAST scan failed"); + return failed("DAST did not complete"); + } + None + } } diff --git a/compliance-agent/tests/integration/api/dast.rs b/compliance-agent/tests/integration/api/dast.rs index f5723f3..7559dc2 100644 --- a/compliance-agent/tests/integration/api/dast.rs +++ b/compliance-agent/tests/integration/api/dast.rs @@ -1,4 +1,5 @@ use crate::common::TestServer; +use mongodb::bson::doc; use serde_json::json; #[tokio::test] @@ -121,3 +122,79 @@ async fn a_login_the_scan_cannot_send_is_refused() { server.cleanup().await; } + +/// A DAST scan that does not complete is a failed `dast` stage of the scan +/// run, recorded once the stage has waited for it; the run itself completes +/// (#998). The live URL does not resolve, so reconnaissance fails. +#[tokio::test] +async fn a_dast_scan_that_does_not_complete_is_a_failed_stage_of_the_run() { + let server = TestServer::start().await; + let created: serde_json::Value = server + .post( + "/api/v1/targets", + &json!({ + "name": "web", + "target_type": "web_app", + "artifacts": [ + { "kind": "live_url", "source_ref": "https://no-such-host.example.com" } + ] + }), + ) + .await + .json() + .await + .unwrap(); + let id = created["data"]["_id"]["$oid"].as_str().unwrap().to_string(); + + server + .post(&format!("/api/v1/targets/{id}/scan"), &json!({})) + .await; + + let client = mongodb::Client::with_uri_str(&server_mongodb_uri()) + .await + .unwrap(); + let runs = client + .database(&server.tenant_db_name()) + .collection::("scan_runs"); + let mut run = None; + for _ in 0..120 { + let found = runs + .find_one(doc! { "repo_id": &id, "status": { "$in": ["completed", "failed"] } }) + .await + .unwrap(); + if found.is_some() { + run = found; + break; + } + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + } + let run = run.expect("the scan run finished"); + + assert_eq!(run.get_str("status").unwrap(), "completed"); + let dast: Vec<_> = run + .get_array("skipped_stages") + .unwrap() + .iter() + .filter_map(|s| s.as_document()) + .filter(|s| s.get_str("stage") == Ok("dast")) + .collect(); + assert_eq!(dast.len(), 1, "{run:?}"); + assert_eq!(dast[0].get_str("code").unwrap(), "tool_failed"); + assert_eq!(dast[0].get_str("subject").unwrap(), "DAST"); + // The DAST run itself is stored, with the scanner's reason. + let dast_run = client + .database(&server.tenant_db_name()) + .collection::("dast_scan_runs") + .find_one(doc! {}) + .await + .unwrap() + .expect("the DAST run is stored"); + assert_eq!(dast_run.get_str("status").unwrap(), "failed"); + + server.cleanup().await; +} + +fn server_mongodb_uri() -> String { + std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()) +} diff --git a/compliance-core/src/models/dast.rs b/compliance-core/src/models/dast.rs index 4972aca..da1abf9 100644 --- a/compliance-core/src/models/dast.rs +++ b/compliance-core/src/models/dast.rs @@ -91,6 +91,7 @@ pub enum DastScanPhase { Reconnaissance, Crawling, VulnerabilityAnalysis, + /// Recorded without doing anything; only in runs from before #998. Exploitation, Reporting, Completed, diff --git a/compliance-dast/src/orchestrator/state_machine.rs b/compliance-dast/src/orchestrator/state_machine.rs index cb20e6f..44fab28 100644 --- a/compliance-dast/src/orchestrator/state_machine.rs +++ b/compliance-dast/src/orchestrator/state_machine.rs @@ -143,12 +143,7 @@ impl DastOrchestrator { .phases_completed .push(DastScanPhase::VulnerabilityAnalysis); - // Phase 4: Exploitation (verify findings) - scan_run.current_phase = DastScanPhase::Exploitation; - // Exploitation is handled within each agent's evidence collection - scan_run.phases_completed.push(DastScanPhase::Exploitation); - - // Phase 5: Reporting + // Phase 4: Reporting scan_run.current_phase = DastScanPhase::Reporting; scan_run.findings_count = all_findings.len() as u32; scan_run.exploitable_count = all_findings.iter().filter(|f| f.exploitable).count() as u32; diff --git a/docs/features/dast.md b/docs/features/dast.md index 30015c5..1ad8007 100644 --- a/docs/features/dast.md +++ b/docs/features/dast.md @@ -67,6 +67,10 @@ Click the **Scan** button on any target row. The scan progresses through: 2. **Test** -- sends attack payloads to discovered parameters 3. **Report** -- collects results and generates findings +### DAST in a target's scan + +A target with a live URL gets a DAST scan in each of its scans, where the deployment runs DAST. The scan waits for it like for its other stages. When the DAST scan does not complete (the site cannot be reached, the login cannot be sent, or it takes longer than 20 minutes), the scan shows the DAST stage as not completed. The rest of the scan is not affected, and the DAST run keeps the reason. + ## Viewing DAST Findings Navigate to **DAST > Findings** to see all discovered vulnerabilities. Each finding shows: