feat(pipeline): DAST findings are findings of the target (#998) (#1008)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m7s
CI / Deploy Agent (push) Successful in 5m47s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m7s
CI / Deploy Agent (push) Successful in 5m47s
This commit was merged in pull request #1008.
This commit is contained in:
1 parent
4f5d713bbc
commit
cdb84f0967
7 files changed
+314
-21
No files matched your search
@@ -102,7 +102,7 @@ pub fn normalise_cwe(raw: &str) -> Option<String> {
|
||||
|
||||
/// The CRA controls a verified weakness is evidence for (see
|
||||
/// [`control_map::ControlMap::controls_for_cwe`]).
|
||||
fn control_refs(cwe: &str) -> Vec<String> {
|
||||
pub(crate) fn control_refs(cwe: &str) -> Vec<String> {
|
||||
control_map::ControlMap::cra()
|
||||
.map(|map| {
|
||||
map.controls_for_cwe(cwe)
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
//! DAST findings as findings of the target they were found on (#998), so they
|
||||
//! carry control refs and reach the findings list, the issue tracker and the
|
||||
//! evidence pack like every other finding. The request and response evidence
|
||||
//! stays with the DAST finding.
|
||||
|
||||
use compliance_core::models::dast::DastFinding;
|
||||
use compliance_core::models::{Finding, ScanType};
|
||||
|
||||
use super::dedup;
|
||||
use crate::import::{control_refs, normalise_cwe};
|
||||
|
||||
/// The scanner name DAST findings are stored under.
|
||||
pub const SCANNER: &str = "dast";
|
||||
|
||||
/// The finding of target `repo_id` that `dast` stands for.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `repo_id` - the target the DAST target belongs to
|
||||
/// * `dast` - the finding as the DAST scan reported it
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// A finding with a fingerprint that is the same for the same weakness at the
|
||||
/// same endpoint, method and parameter in every scan (so a later scan finds it
|
||||
/// again instead of adding it twice), the CWE normalised, and the control refs
|
||||
/// that CWE is evidence for. The endpoint goes into the description, since a
|
||||
/// DAST finding has no file.
|
||||
pub fn as_finding(repo_id: &str, dast: &DastFinding) -> Finding {
|
||||
let fingerprint =
|
||||
dedup::compute_fingerprint(&[repo_id, SCANNER, &dedup::compute_dast_fingerprint(dast)]);
|
||||
let parameter = dast
|
||||
.parameter
|
||||
.as_deref()
|
||||
.map(|p| format!(", parameter `{p}`"))
|
||||
.unwrap_or_default();
|
||||
let description = format!(
|
||||
"{}\n\nFound by DAST at {} {}{parameter}.",
|
||||
dast.description, dast.method, dast.endpoint
|
||||
);
|
||||
let mut finding = Finding::new(
|
||||
repo_id.to_string(),
|
||||
fingerprint,
|
||||
SCANNER.to_string(),
|
||||
ScanType::Dast,
|
||||
dast.title.clone(),
|
||||
description,
|
||||
dast.severity.clone(),
|
||||
);
|
||||
finding.rule_id = Some(format!("dast-{}", dast.vuln_type));
|
||||
finding.cwe = dast.cwe.as_deref().and_then(normalise_cwe);
|
||||
finding.control_refs = finding.cwe.as_deref().map(control_refs).unwrap_or_default();
|
||||
finding.remediation = dast.remediation.clone();
|
||||
finding
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use compliance_core::models::dast::DastVulnType;
|
||||
use compliance_core::models::Severity;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn dast(endpoint: &str, parameter: Option<&str>) -> DastFinding {
|
||||
let mut f = DastFinding::new(
|
||||
"run-1".into(),
|
||||
"dast-target-1".into(),
|
||||
DastVulnType::CorsMisconfiguration,
|
||||
"CORS misconfiguration allows arbitrary origins".into(),
|
||||
"The server allows any origin.".into(),
|
||||
Severity::Medium,
|
||||
endpoint.into(),
|
||||
"GET".into(),
|
||||
);
|
||||
f.cwe = Some("cwe-942".into());
|
||||
f.parameter = parameter.map(str::to_string);
|
||||
f.remediation = Some("Allow only trusted origins.".into());
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dast_finding_becomes_a_finding_of_the_target() {
|
||||
let finding = as_finding("target-1", &dast("https://app.example.com/", None));
|
||||
|
||||
assert_eq!(finding.repo_id, "target-1");
|
||||
assert_eq!(finding.scanner, "dast");
|
||||
assert_eq!(finding.scan_type, ScanType::Dast);
|
||||
assert_eq!(
|
||||
finding.rule_id.as_deref(),
|
||||
Some("dast-cors_misconfiguration")
|
||||
);
|
||||
assert_eq!(
|
||||
finding.title,
|
||||
"CORS misconfiguration allows arbitrary origins"
|
||||
);
|
||||
assert_eq!(finding.severity, Severity::Medium);
|
||||
assert_eq!(finding.cwe.as_deref(), Some("CWE-942"));
|
||||
assert_eq!(finding.control_refs, ["cra-ai-1"]);
|
||||
assert!(finding
|
||||
.description
|
||||
.ends_with("Found by DAST at GET https://app.example.com/."));
|
||||
assert_eq!(
|
||||
finding.remediation.as_deref(),
|
||||
Some("Allow only trusted origins.")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_weakness_keeps_its_fingerprint_and_others_get_their_own() {
|
||||
let first = as_finding("target-1", &dast("https://app.example.com/", None));
|
||||
let again = as_finding("target-1", &dast("https://app.example.com", None));
|
||||
let elsewhere = as_finding("target-1", &dast("https://app.example.com/login", None));
|
||||
let other_target = as_finding("target-2", &dast("https://app.example.com/", None));
|
||||
let with_parameter = as_finding("target-1", &dast("https://app.example.com/", Some("q")));
|
||||
|
||||
assert_eq!(first.fingerprint, again.fingerprint);
|
||||
for other in [&elsewhere, &other_target, &with_parameter] {
|
||||
assert_ne!(first.fingerprint, other.fingerprint);
|
||||
}
|
||||
assert!(with_parameter.description.contains("parameter `q`"));
|
||||
}
|
||||
}
|
||||
@@ -112,7 +112,11 @@ impl PipelineOrchestrator {
|
||||
/// 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) {
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many findings the DAST scans added to the target's findings.
|
||||
pub(super) async fn maybe_trigger_dast(&self, repo_id: &str, scan_run_id: &str) -> u32 {
|
||||
use futures_util::TryStreamExt;
|
||||
|
||||
if self.source_only() {
|
||||
@@ -121,48 +125,57 @@ impl PipelineOrchestrator {
|
||||
compliance_core::models::SkippedStage::feature_disabled("dast"),
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
return 0;
|
||||
}
|
||||
|
||||
let filter = mongodb::bson::doc! { "repo_id": repo_id };
|
||||
let targets: Vec<compliance_core::models::DastTarget> =
|
||||
match self.db.dast_targets().find(filter).await {
|
||||
Ok(cursor) => cursor.try_collect().await.unwrap_or_default(),
|
||||
Err(_) => return,
|
||||
Err(_) => return 0,
|
||||
};
|
||||
|
||||
if targets.is_empty() {
|
||||
tracing::info!("[{repo_id}] No DAST targets configured, skipping");
|
||||
return;
|
||||
return 0;
|
||||
}
|
||||
|
||||
let mut new_count = 0;
|
||||
for mut target in targets {
|
||||
self.secrets.open_in_place(&mut target);
|
||||
if let Some(failed) = self.run_dast_target(&target, scan_run_id).await {
|
||||
self.skip_stage(scan_run_id, failed).await;
|
||||
match self.run_dast_target(&target, repo_id, scan_run_id).await {
|
||||
Ok(added) => new_count += added,
|
||||
Err(failed) => self.skip_stage(scan_run_id, failed).await,
|
||||
}
|
||||
}
|
||||
new_count
|
||||
}
|
||||
|
||||
/// Scan one DAST target, waiting for the result (#998), and store the
|
||||
/// scan run and its findings.
|
||||
/// scan run and its findings: as DAST findings, with their evidence, and
|
||||
/// as findings of the target `repo_id`.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many findings the target did not have yet.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 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.
|
||||
/// failed, timed out, or its run could not be stored. The error itself
|
||||
/// goes to the log only.
|
||||
async fn run_dast_target(
|
||||
&self,
|
||||
target: &compliance_core::models::DastTarget,
|
||||
repo_id: &str,
|
||||
scan_run_id: &str,
|
||||
) -> Option<compliance_core::models::SkippedStage> {
|
||||
) -> Result<u32, compliance_core::models::SkippedStage> {
|
||||
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"))
|
||||
Err(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()));
|
||||
@@ -182,18 +195,53 @@ impl PipelineOrchestrator {
|
||||
tracing::error!("Failed to store DAST scan run: {e}");
|
||||
return failed("DAST results could not be stored");
|
||||
}
|
||||
let mut new_count = 0;
|
||||
for finding in &findings {
|
||||
if let Err(e) = self.db.dast_findings().insert_one(finding).await {
|
||||
tracing::error!("Failed to store DAST finding: {e}");
|
||||
}
|
||||
match self.add_dast_finding(repo_id, scan_run_id, finding).await {
|
||||
Ok(added) => new_count += u32::from(added),
|
||||
Err(e) => tracing::error!("Failed to store DAST finding as a finding: {e}"),
|
||||
}
|
||||
}
|
||||
tracing::info!(target = %target.name, findings = findings.len(), "DAST scan done");
|
||||
tracing::info!(target = %target.name, findings = findings.len(), new = new_count, "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
|
||||
Ok(new_count)
|
||||
}
|
||||
|
||||
/// Store `dast` as a finding of target `repo_id`, unless the target has
|
||||
/// it already (the same fingerprint).
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Whether it was new.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The database's error.
|
||||
async fn add_dast_finding(
|
||||
&self,
|
||||
repo_id: &str,
|
||||
scan_run_id: &str,
|
||||
dast: &compliance_core::models::DastFinding,
|
||||
) -> Result<bool, mongodb::error::Error> {
|
||||
let mut finding = super::dast_findings::as_finding(repo_id, dast);
|
||||
finding.scan_run_id = Some(scan_run_id.to_string());
|
||||
let known = self
|
||||
.db
|
||||
.findings()
|
||||
.find_one(mongodb::bson::doc! { "fingerprint": &finding.fingerprint })
|
||||
.await?
|
||||
.is_some();
|
||||
if !known {
|
||||
self.db.findings().insert_one(&finding).await?;
|
||||
}
|
||||
Ok(!known)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ pub mod cve;
|
||||
pub(crate) mod cve_enrichment;
|
||||
pub(crate) mod cve_issues;
|
||||
pub mod cve_notify;
|
||||
pub mod dast_findings;
|
||||
pub mod dedup;
|
||||
pub mod devskim;
|
||||
pub mod dotnet;
|
||||
|
||||
@@ -1763,7 +1763,7 @@ impl PipelineOrchestrator {
|
||||
if plan.has(ScanType::Dast) {
|
||||
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
||||
.await;
|
||||
self.maybe_trigger_dast(&target_id, scan_run_id).await;
|
||||
new_count += self.maybe_trigger_dast(&target_id, scan_run_id).await;
|
||||
}
|
||||
return Ok(new_count);
|
||||
}
|
||||
@@ -1801,7 +1801,8 @@ impl PipelineOrchestrator {
|
||||
let n = self.run_pipeline(&repo, scan_run_id, trigger).await?;
|
||||
self.finalize_target(target, &repo, n).await?;
|
||||
new_count += n;
|
||||
self.dast_after_code_scan(&target_id, &plan, scan_run_id)
|
||||
new_count += self
|
||||
.dast_after_code_scan(&target_id, &plan, scan_run_id)
|
||||
.await;
|
||||
}
|
||||
Some(code) => {
|
||||
@@ -1818,7 +1819,8 @@ impl PipelineOrchestrator {
|
||||
let n = self.scan_tree(tree, upload, &repo, scan_run_id).await?;
|
||||
self.finalize_target(target, &repo, n).await?;
|
||||
new_count += n;
|
||||
self.dast_after_code_scan(&target_id, &plan, scan_run_id)
|
||||
new_count += self
|
||||
.dast_after_code_scan(&target_id, &plan, scan_run_id)
|
||||
.await;
|
||||
}
|
||||
// The ingest stage recorded why. A run over nothing must not
|
||||
@@ -1854,7 +1856,7 @@ impl PipelineOrchestrator {
|
||||
);
|
||||
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
||||
.await;
|
||||
self.maybe_trigger_dast(&target_id, scan_run_id).await;
|
||||
new_count += self.maybe_trigger_dast(&target_id, scan_run_id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2608,13 +2610,13 @@ impl PipelineOrchestrator {
|
||||
target_id: &str,
|
||||
plan: &crate::pipeline::plan::ScanPlan,
|
||||
scan_run_id: &str,
|
||||
) {
|
||||
) -> u32 {
|
||||
if !plan.has(ScanType::Dast) {
|
||||
return;
|
||||
return 0;
|
||||
}
|
||||
self.update_phase(scan_run_id, ScanPhase::DastScanning)
|
||||
.await;
|
||||
self.maybe_trigger_dast(target_id, scan_run_id).await;
|
||||
self.maybe_trigger_dast(target_id, scan_run_id).await
|
||||
}
|
||||
|
||||
/// If the target has a `LiveUrl` artifact and DAST is planned, provision a
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
//! DAST findings join the findings of the target they were found on (#998),
|
||||
//! with their control refs, and a second scan does not add them again.
|
||||
//! Drives the real API and pipeline against a live Mongo (`TEST_MONGODB_URI`)
|
||||
//! and a local site, so this binary allows private targets for its process.
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
mod common;
|
||||
|
||||
use axum::http::header::ACCESS_CONTROL_ALLOW_ORIGIN;
|
||||
use axum::Router;
|
||||
use common::TestServer;
|
||||
use mongodb::bson::{doc, Document};
|
||||
use serde_json::json;
|
||||
|
||||
/// A site that lets any origin read its answers.
|
||||
async fn open_cors_site() -> String {
|
||||
let app = Router::new().fallback(|| async {
|
||||
(
|
||||
[(ACCESS_CONTROL_ALLOW_ORIGIN, "*")],
|
||||
"<html><body>shop</body></html>",
|
||||
)
|
||||
});
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
format!("http://{addr}")
|
||||
}
|
||||
|
||||
/// Scan target `id` and return the finished scan run.
|
||||
async fn scan(server: &TestServer, runs: &mongodb::Collection<Document>, id: &str) -> Document {
|
||||
let before = runs.count_documents(doc! { "repo_id": id }).await.unwrap();
|
||||
server
|
||||
.post(&format!("/api/v1/targets/{id}/scan"), &json!({}))
|
||||
.await;
|
||||
for _ in 0..240 {
|
||||
let done = runs
|
||||
.count_documents(doc! { "repo_id": id, "status": { "$in": ["completed", "failed"] } })
|
||||
.await
|
||||
.unwrap();
|
||||
if done > before {
|
||||
return runs
|
||||
.find_one(doc! { "repo_id": id })
|
||||
.sort(doc! { "started_at": -1 })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
}
|
||||
panic!("the scan of {id} did not finish");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dast_findings_are_findings_of_the_target_once() {
|
||||
// This binary holds only this test, so the setting reaches no other one.
|
||||
std::env::set_var("PW_ALLOW_PRIVATE_TARGETS", "1");
|
||||
let site = open_cors_site().await;
|
||||
let server = TestServer::start().await;
|
||||
let created: serde_json::Value = server
|
||||
.post(
|
||||
"/api/v1/targets",
|
||||
&json!({
|
||||
"name": "shop",
|
||||
"target_type": "web_app",
|
||||
"artifacts": [{ "kind": "live_url", "source_ref": site }]
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
let id = created["data"]["_id"]["$oid"].as_str().unwrap().to_string();
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let db = mongodb::Client::with_uri_str(&uri)
|
||||
.await
|
||||
.unwrap()
|
||||
.database(&server.tenant_db_name());
|
||||
let runs = db.collection::<Document>("scan_runs");
|
||||
let findings = db.collection::<Document>("findings");
|
||||
|
||||
let first = scan(&server, &runs, &id).await;
|
||||
|
||||
assert_eq!(first.get_str("status").unwrap(), "completed", "{first:?}");
|
||||
let cors = findings
|
||||
.find_one(doc! { "repo_id": &id, "scanner": "dast", "cwe": "CWE-942" })
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("the CORS finding is a finding of the target");
|
||||
assert_eq!(cors.get_str("scan_type").unwrap(), "dast");
|
||||
let refs: Vec<&str> = cors
|
||||
.get_array("control_refs")
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|r| r.as_str())
|
||||
.collect();
|
||||
assert_eq!(refs, ["cra-ai-1"]);
|
||||
let stored = findings
|
||||
.count_documents(doc! { "repo_id": &id, "scanner": "dast" })
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(first.get_i64("new_findings_count").unwrap() >= i64::try_from(stored).unwrap());
|
||||
|
||||
let second = scan(&server, &runs, &id).await;
|
||||
|
||||
assert_eq!(
|
||||
findings
|
||||
.count_documents(doc! { "repo_id": &id, "scanner": "dast" })
|
||||
.await
|
||||
.unwrap(),
|
||||
stored,
|
||||
"a second scan finds the same weaknesses, it does not add them again"
|
||||
);
|
||||
assert_eq!(second.get_i64("new_findings_count").unwrap(), 0);
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
@@ -71,6 +71,8 @@ Click the **Scan** button on any target row. The scan progresses through:
|
||||
|
||||
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.
|
||||
|
||||
Its findings are findings of the target too: they appear in the target's findings list with the other findings (scanner `dast`), count as new findings of the scan, and carry the CRA controls their CWE is evidence for. A later scan that finds the same weakness at the same endpoint, method and parameter does not add it again. The request and response evidence stays with the finding under **DAST > Findings**.
|
||||
|
||||
## Viewing DAST Findings
|
||||
|
||||
Navigate to **DAST > Findings** to see all discovered vulnerabilities. Each finding shows:
|
||||
|
||||
Reference in new issue
Block a user