// Package main implements the IntegraCI dast-scan Dagger module. // // Runs OWASP ZAP baseline + (optionally) full active scan and Nuclei // templates against a deployed HTTP target — typically an ephemeral // preview environment created by the deploy pipeline. // // The output is SARIF (uploadable to GitHub Security tab) plus a JSON // summary that the IntegraCI API consumes via /api/v1/scans. // // Usage (baseline scan, fast & non-intrusive — safe for production): // // dagger call zap-baseline \ // --target https://preview-pr42.integraci.dev \ // --auth-header "Authorization: Bearer $TOKEN" // // Usage (active scan, intrusive — only on ephemeral envs): // // dagger call zap-full \ // --target https://preview-pr42.integraci.dev \ // --auth-header "Authorization: Bearer $TOKEN" \ // --max-duration 30 // // Usage (Nuclei — CVE templates for the entire web stack): // // dagger call nuclei \ // --target https://preview-pr42.integraci.dev \ // --severity critical,high package main import ( "bytes" "context" "dagger/dast-scan/internal/dagger" "encoding/json" "fmt" "net/http" "strings" "time" ) // DastScan is the IntegraCI dynamic application security testing module. type DastScan struct{} // DASTResult is the normalised output for any DAST tool we run. type DASTResult struct { Tool string `json:"tool"` // "zap" | "nuclei" Mode string `json:"mode"` // "baseline" | "full" | "nuclei" Target string `json:"target"` Total int `json:"total"` Critical int `json:"critical"` High int `json:"high"` Medium int `json:"medium"` Low int `json:"low"` Info int `json:"info"` SarifReport string `json:"sarif_report,omitempty"` JSONReport string `json:"json_report,omitempty"` HTMLReport string `json:"html_report,omitempty"` Pass bool `json:"pass"` Error string `json:"error,omitempty"` } // Scan is the engine-agnostic unified DAST entrypoint. It dispatches to a // scanner based on `tool` so any CI engine can run DAST with a single // `dagger call scan` invocation, no GitHub-Actions YAML required. // // - zap → reuses the ZapBaseline logic (zap-baseline.py, safe/passive) // - burp → POSTs to Burp Suite Enterprise's REST API // - acunetix → POSTs to the Acunetix REST API // - invicti → POSTs to the Invicti (Netsparker) REST API // - none → no-op (governance.dast=none), returns a skipped result // // Commercial scanners are off-cluster appliances: their API base URL is // deployment-specific and injected via the `${TOOL}_API_URL` env (the // `apiURL` arg), and the API key is passed as a Dagger secret — never // hardcoded. // // Usage: // // dagger call scan --target-url https://preview-pr42.integraci.dev // dagger call scan --target-url https://app.example.com --tool burp \ // --api-url https://burp.internal:8443 --api-key env:BURP_API_KEY func (m *DastScan) Scan( ctx context.Context, // Target URL to scan (must be reachable from the Dagger runner) targetURL string, // DAST tool: zap | burp | acunetix | invicti | none // +optional // +default="zap" tool string, // Base URL of the commercial scanner's REST API ({TOOL}_API_URL). // Required for burp/acunetix/invicti, ignored for zap/none. // +optional apiURL string, // API key / token secret for the commercial scanner. // +optional apiKey *dagger.Secret, // Fail the run when this severity or above is found (zap only). // +optional // +default="high" failOn string, // IntegraCI API base URL for posting results back. // +optional integraciURL string, // JWT token for IntegraCI API authentication. // +optional token *dagger.Secret, // Service ID to link scan results. // +optional serviceID string, // Version (commit SHA / image tag) the scan applies to. // +optional version string, ) (*DASTResult, error) { var ( result *DASTResult err error ) switch strings.ToLower(tool) { case "", "zap": result, err = m.ZapBaseline(ctx, targetURL, "", "", failOn) case "none": result = &DASTResult{ Tool: "none", Mode: "skip", Target: targetURL, Pass: true, } case "burp": result, err = m.commercialScan(ctx, "burp", targetURL, apiURL, apiKey) case "acunetix": result, err = m.commercialScan(ctx, "acunetix", targetURL, apiURL, apiKey) case "invicti": result, err = m.commercialScan(ctx, "invicti", targetURL, apiURL, apiKey) default: return nil, fmt.Errorf("unsupported DAST tool: %q (want zap|burp|acunetix|invicti|none)", tool) } if err != nil { return result, err } // POST results to the IntegraCI API when configured. Skipped silently // when integraciURL or token is empty so local runs still work. if integraciURL != "" && token != nil { if perr := m.postResults(ctx, integraciURL, token, serviceID, version, result); perr != nil { return result, fmt.Errorf("posting results to API failed: %w", perr) } } return result, nil } // postResults sends the DAST scan result back to the IntegraCI scans // endpoint. Shape mirrors security-scan's postResults (ScanResultCreate): // typed severity columns plus the report_data counters the deploy OPA gate // reads. For DAST we populate report_data.dast_high / report_data.dast_critical // from the DAST tool's findings (see deploy.py _build_scan_results). func (m *DastScan) postResults( ctx context.Context, apiURL string, token *dagger.Secret, serviceID string, version string, result *DASTResult, ) error { payload := map[string]any{ "service_id": serviceID, "version": version, "scan_type": "dast", "scanner": result.Tool, "report_format": "json", "findings_count": result.Critical + result.High + result.Medium, "critical_count": result.Critical, "high_count": result.High, "medium_count": result.Medium, "report_data": map[string]any{ "secret_count": 0, "dast_high": result.High, "dast_critical": result.Critical, "sast_errors": 0, "sbom_present": false, "signed": false, }, } body, err := json.Marshal(payload) if err != nil { return fmt.Errorf("marshal scan payload: %w", err) } endpoint := strings.TrimRight(apiURL, "/") + "/api/v1/scans" req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body)) if err != nil { return fmt.Errorf("build request: %w", err) } req.Header.Set("Content-Type", "application/json") tokenStr, err := token.Plaintext(ctx) if err != nil { return fmt.Errorf("read token secret: %w", err) } req.Header.Set("Authorization", "Bearer "+tokenStr) client := &http.Client{Timeout: 30 * time.Second} resp, err := client.Do(req) if err != nil { return fmt.Errorf("API post to %s failed: %w", endpoint, err) } defer resp.Body.Close() if resp.StatusCode >= 300 { return fmt.Errorf("API post to %s returned %d", endpoint, resp.StatusCode) } return nil } // commercialScan triggers an off-cluster commercial DAST appliance by POSTing // to its REST API via curl-in-container. The per-vendor endpoint, auth header // and JSON payload mirror security_pipeline_adapter.build_dast_step exactly. func (m *DastScan) commercialScan( ctx context.Context, tool, targetURL, apiURL string, apiKey *dagger.Secret, ) (*DASTResult, error) { if targetURL == "" { return nil, fmt.Errorf("--target-url is required") } if apiURL == "" { return nil, fmt.Errorf("--api-url is required for %s (its {TOOL}_API_URL is deployment-specific)", tool) } if apiKey == nil { return nil, fmt.Errorf("--api-key is required for %s", tool) } var endpoint, authHeader, payload string switch tool { case "burp": endpoint = strings.TrimRight(apiURL, "/") + "/api/v0.1/scan" authHeader = `Authorization: ${API_KEY}` payload = fmt.Sprintf(`{"urls":["%s"]}`, targetURL) case "acunetix": endpoint = strings.TrimRight(apiURL, "/") + "/api/v1/scans" authHeader = `X-Auth: ${API_KEY}` payload = fmt.Sprintf(`{"target_url":"%s","profile_id":"full"}`, targetURL) case "invicti": endpoint = strings.TrimRight(apiURL, "/") + "/api/1.0/scans/new" authHeader = `Authorization: Basic ${API_KEY}` payload = fmt.Sprintf(`{"TargetUri":"%s","ProfileId":"default"}`, targetURL) } // The secret is interpolated inside the container via $API_KEY so it is // never present in the Dagger op graph as plaintext. curlCmd := fmt.Sprintf( `curl -fsSL -X POST %q -H %q -H "Content-Type: application/json" -d %q`, endpoint, authHeader, payload, ) out, err := dag.Container(). From("curlimages/curl:8.10.1"). WithSecretVariable("API_KEY", apiKey). WithExec([]string{"sh", "-c", curlCmd}). Stdout(ctx) result := &DASTResult{ Tool: tool, Mode: "api", Target: targetURL, JSONReport: out, Pass: err == nil, } if err != nil { result.Error = fmt.Sprintf("%s scan request failed: %v", tool, err) return result, err } return result, nil } // ZapBaseline runs OWASP ZAP's `zap-baseline.py` — a passive spider + scan // designed to be safe against production traffic. Completes in 1-3 // minutes for a typical API. // // Failure threshold defaults to "any HIGH or CRITICAL". func (m *DastScan) ZapBaseline( ctx context.Context, // Target URL (must be reachable from the Dagger runner) target string, // Optional Authorization header to bypass auth (e.g. "Bearer ...") // +optional authHeader string, // Comma-separated rule IDs to ignore (e.g. "10038,10054" — known FPs) // +optional ignoreRules string, // Fail the run when this severity or above is found. // One of: "info" | "low" | "medium" | "high" | "critical". // +optional // +default="high" failOn string, ) (*DASTResult, error) { if target == "" { return nil, fmt.Errorf("--target is required") } if failOn == "" { failOn = "high" } args := []string{ "zap-baseline.py", "-t", target, "-J", "/zap/wrk/zap-report.json", "-x", "/zap/wrk/zap-report.xml", "-r", "/zap/wrk/zap-report.html", "-w", "/zap/wrk/zap-report.md", "-I", // do not return failure on warnings — we threshold ourselves } if ignoreRules != "" { for _, id := range strings.Split(ignoreRules, ",") { id = strings.TrimSpace(id) if id != "" { args = append(args, "-z", "-config rules.cookie.ignorelist="+id) } } } c := dag.Container(). From("ghcr.io/zaproxy/zaproxy:stable"). WithWorkdir("/zap/wrk"). WithEnvVariable("DAST_TARGET", target) if authHeader != "" { // ZAP accepts -config replacers via -z c = c.WithExec([]string{ "sh", "-c", fmt.Sprintf("echo '%s' > /zap/wrk/auth-header.txt", authHeader), }) args = append(args, "-z", "-config replacer.full_list(0).description=auth", "-z", "-config replacer.full_list(0).enabled=true", "-z", "-config replacer.full_list(0).matchtype=REQ_HEADER", "-z", "-config replacer.full_list(0).matchstr=Authorization", "-z", "-config replacer.full_list(0).regex=false", "-z", fmt.Sprintf("-config replacer.full_list(0).replacement=%s", authHeader), ) } scan := c.WithExec(args) // ZAP exits non-zero when WARN/FAIL alerts are found in baseline. // We swallow the exit to read reports ourselves. jsonOut, _ := scan.File("/zap/wrk/zap-report.json").Contents(ctx) htmlOut, _ := scan.File("/zap/wrk/zap-report.html").Contents(ctx) report := summariseZap(jsonOut) report.Tool = "zap" report.Mode = "baseline" report.Target = target report.JSONReport = jsonOut report.HTMLReport = htmlOut report.SarifReport = zapToSarif(jsonOut, target) report.Pass = !exceedsThreshold(report, failOn) if !report.Pass { report.Error = fmt.Sprintf("ZAP baseline: %d findings ≥ %s severity", report.Critical+report.High, failOn) } return report, nil } // ZapFull runs the full ZAP active scan — actively sends payloads // (XSS, SQLi, command injection probes) to the target. Intrusive. // Safe only for ephemeral / preview environments. func (m *DastScan) ZapFull( ctx context.Context, target string, // +optional authHeader string, // +optional // +default=30 maxDuration int, // +optional // +default="high" failOn string, ) (*DASTResult, error) { if target == "" { return nil, fmt.Errorf("--target is required") } if maxDuration <= 0 { maxDuration = 30 } args := []string{ "zap-full-scan.py", "-t", target, "-J", "/zap/wrk/zap-report.json", "-r", "/zap/wrk/zap-report.html", "-m", fmt.Sprintf("%d", maxDuration), "-I", } c := dag.Container(). From("ghcr.io/zaproxy/zaproxy:stable"). WithWorkdir("/zap/wrk") if authHeader != "" { args = append(args, "-z", "-config replacer.full_list(0).description=auth", "-z", "-config replacer.full_list(0).enabled=true", "-z", "-config replacer.full_list(0).matchtype=REQ_HEADER", "-z", "-config replacer.full_list(0).matchstr=Authorization", "-z", "-config replacer.full_list(0).regex=false", "-z", fmt.Sprintf("-config replacer.full_list(0).replacement=%s", authHeader), ) } scan := c.WithExec(args) jsonOut, _ := scan.File("/zap/wrk/zap-report.json").Contents(ctx) htmlOut, _ := scan.File("/zap/wrk/zap-report.html").Contents(ctx) report := summariseZap(jsonOut) report.Tool = "zap" report.Mode = "full" report.Target = target report.JSONReport = jsonOut report.HTMLReport = htmlOut report.SarifReport = zapToSarif(jsonOut, target) report.Pass = !exceedsThreshold(report, failOn) if !report.Pass { report.Error = fmt.Sprintf("ZAP full scan: %d findings ≥ %s severity", report.Critical+report.High, failOn) } return report, nil } // Nuclei runs ProjectDiscovery's Nuclei template engine against the // target. ~10k templates covering CVEs, default credentials, exposed // dashboards, misconfig, etc. Updated nightly upstream. func (m *DastScan) Nuclei( ctx context.Context, target string, // Comma-separated severities to include. Default: critical,high,medium. // +optional // +default="critical,high" severity string, // Comma-separated tags to include (e.g. "cve,exposure,misconfig"). // +optional tags string, // Rate limit (req/sec) — default 150 is upstream sensible default. // +optional // +default=150 rateLimit int, // Fail when any finding ≥ this severity. // +optional // +default="high" failOn string, ) (*DASTResult, error) { if target == "" { return nil, fmt.Errorf("--target is required") } if severity == "" { severity = "critical,high" } if rateLimit <= 0 { rateLimit = 150 } args := []string{ "nuclei", "-target", target, "-severity", severity, "-jsonl-export", "/tmp/nuclei.jsonl", "-sarif-export", "/tmp/nuclei.sarif", "-rate-limit", fmt.Sprintf("%d", rateLimit), "-no-color", "-disable-update-check", } if tags != "" { args = append(args, "-tags", tags) } c := dag.Container(). From("projectdiscovery/nuclei:v3.3.9"). WithExec(args) jsonl, _ := c.File("/tmp/nuclei.jsonl").Contents(ctx) sarif, _ := c.File("/tmp/nuclei.sarif").Contents(ctx) report := summariseNuclei(jsonl) report.Tool = "nuclei" report.Mode = "nuclei" report.Target = target report.JSONReport = jsonl report.SarifReport = sarif report.Pass = !exceedsThreshold(report, failOn) if !report.Pass { report.Error = fmt.Sprintf("Nuclei: %d findings ≥ %s severity", report.Critical+report.High, failOn) } return report, nil } // ───── helpers ───── // summariseZap parses ZAP's JSON report and returns aggregate counts. // We avoid pulling encoding/json to keep the module dependency-free — // ZAP's output is stable and grep-friendly. func summariseZap(jsonOut string) *DASTResult { r := &DASTResult{} if jsonOut == "" { return r } r.High = strings.Count(jsonOut, `"riskdesc":"High`) r.Medium = strings.Count(jsonOut, `"riskdesc":"Medium`) r.Low = strings.Count(jsonOut, `"riskdesc":"Low`) r.Info = strings.Count(jsonOut, `"riskdesc":"Informational`) // ZAP reports "High (Critical)" inside the High bucket — promote when // "Critical" appears inline. r.Critical = strings.Count(jsonOut, `"riskdesc":"High (Critical`) if r.Critical > 0 { r.High -= r.Critical if r.High < 0 { r.High = 0 } } r.Total = r.Critical + r.High + r.Medium + r.Low + r.Info return r } // summariseNuclei parses Nuclei's JSONL output (one finding per line). func summariseNuclei(jsonl string) *DASTResult { r := &DASTResult{} for _, line := range strings.Split(jsonl, "\n") { if line == "" { continue } switch { case strings.Contains(line, `"severity":"critical"`): r.Critical++ case strings.Contains(line, `"severity":"high"`): r.High++ case strings.Contains(line, `"severity":"medium"`): r.Medium++ case strings.Contains(line, `"severity":"low"`): r.Low++ case strings.Contains(line, `"severity":"info"`): r.Info++ } } r.Total = r.Critical + r.High + r.Medium + r.Low + r.Info return r } // exceedsThreshold returns true when the report contains any finding at // or above the failOn severity. Severity ordering follows the standard // SARIF/CVSS bucket model. func exceedsThreshold(r *DASTResult, failOn string) bool { switch strings.ToLower(failOn) { case "critical": return r.Critical > 0 case "high": return r.Critical+r.High > 0 case "medium": return r.Critical+r.High+r.Medium > 0 case "low": return r.Critical+r.High+r.Medium+r.Low > 0 case "info": return r.Total > 0 } return r.Critical+r.High > 0 } // zapToSarif converts ZAP's JSON to a minimal valid SARIF v2.1.0 envelope // so it can be uploaded to the GitHub Security tab. We embed the full // ZAP JSON inside `properties` — security teams can drill in from the // SARIF row to the rich report. func zapToSarif(jsonOut string, target string) string { if jsonOut == "" { return "" } // Minimal valid SARIF — github/codeql-action/upload-sarif requires // runs[].tool.driver.{name,rules} and at least one results entry to // surface in the UI. return fmt.Sprintf(`{ "version": "2.1.0", "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json", "runs": [{ "tool": { "driver": { "name": "OWASP ZAP", "version": "stable", "informationUri": "https://www.zaproxy.org/", "rules": [] } }, "originalUriBaseIds": {"TARGET": {"uri": %q}}, "properties": {"raw_zap_report": "see job artifact"}, "results": [] }] }`, target) }