Building an Automated Vulnerability Scanner with OWASP ZAP API: Project Guide

Manual security assessments run once a quarter cannot keep pace with teams deploying microservices multiple times a day. Integrating Dynamic Application Security Testing (DAST) directly into your CI/CD pipeline catches missing security headers, insecure cookie flags, Cross-Site Scripting (XSS), SQL injection flaws, and misconfigured CORS policies before code reaches production.

In this hands-on DevSecOps project, you will build a headless, containerized Automated Vulnerability Scanner powered by the OWASP ZAP (Zed Attack Proxy) REST/Python API. Your orchestrator will launch ZAP in daemon mode, import an OpenAPI/Swagger specification to map authenticated endpoints, run baseline passive and active security scans against a staging environment, export structured JSON/SARIF findings, and enforce a CI/CD severity quality gate.

Manual DAST vs. Automated ZAP API Pipeline

Understanding how an API-driven ZAP orchestrator transforms DAST from an ad-hoc desktop exercise into a deterministic CI/CD control:

Engineering DimensionManual Desktop ZAP GUIAutomated ZAP API Pipeline (This Project)
Execution TriggerManual click-through by an AppSec engineerTriggered automatically on every staging deployment or nightly CI build
Endpoint DiscoveryManual browser proxying or basic HTML spideringProgrammatic OpenAPI / GraphQL schema import + AJAX/Traditional Spider
Authentication HandlingManual browser login session captureAutomated Replacer rules injecting short-lived staging Bearer tokens
Runtime & DeterminismUnbounded manual exploration (hours)Strict scan policy profiles & time-boxed active scan budgets (5–15 mins)
Output & TriageAd-hoc HTML export emailed to developersStructured JSON / SARIF reports mapped to CWE IDs and PR annotations
Release EnforcementAdvisory PDF findingsAutomated exit code 1 build breaker when High or Critical alerts exceed threshold
TEXT
+-----------------------------------------------------------------------------------+
|               CI/CD AUTOMATED DAST PIPELINE WITH OWASP ZAP API                    |
+-----------------------------------------------------------------------------------+
|                                                                                   |
|  [CI/CD Runner (GitHub Actions / GitLab CI)]                                      |
|         |                                                                         |
|         | 1. Spins up Staging App + ZAP Daemon Container on Isolated Network      |
|         v                                                                         |
|  +-----------------------------------------------------------------------------+  |
|  |                     PYTHON ZAP ORCHESTRATOR (zap_scanner.py)                |  |
|  |                                                                             |  |
|  |  Step 1: Health-check ZAP Daemon API (http://zap:8090)                      |  |
|  |  Step 2: Configure Auth Replacer Rule (Authorization: Bearer <STAGING_JWT>) |  |
|  |  Step 3: Import OpenAPI Spec (/openapi.json) + Run Traditional Spider       |  |
|  |  Step 4: Wait for Passive Scan Queue (pscan.records_to_scan == 0)           |  |
|  |  Step 5: Execute Scoped Active Scan Policy (SQLi, XSS, Path Traversal)      |  |
|  |  Step 6: Export Deduplicated JSON/SARIF Report & Evaluate Quality Gate      |  |
|  +-----------------------------------------------------------------------------+  |
|         |                                   |                                     |
|         | HTTP/HTTPS Probe Traffic          | Structured Alerts (CWE / Risk)      |
|         v                                   v                                     |
|  +-----------------------------+     +-----------------------------------------+  |
|  |   Staging Web Application   |     |  Quality Gate Decision:                 |  |
|  |   (http://staging-app:8000) |     |  - High Risk > 0 -> Exit 1 (Fail Build) |  |
|  +-----------------------------+     |  - High Risk == 0 -> Exit 0 (Pass)      |  |
|                                      +-----------------------------------------+  |
+-----------------------------------------------------------------------------------+

Project Structure

Create a clean repository directory for the Docker Compose environment, Python ZAP API orchestrator, and generated security reports:

TEXT
zap-dast-scanner/
├── docker-compose.yml       # Isolated network running OWASP ZAP daemon + staging target
├── requirements.txt         # zaproxy Python SDK & requests dependencies
├── zap_scanner.py           # End-to-end ZAP API scan orchestrator & quality gate
└── reports/                 # Output directory for JSON & HTML vulnerability reports

Step 1: Containerized ZAP Daemon & Staging Environment (docker-compose.yml)

Run OWASP ZAP in headless daemon mode (zap.sh -daemon) inside an isolated Docker bridge network so scan traffic never leaves your local test or staging environment. Configure an explicit api.key and restrict api.addrs.addr.name to internal container hostnames:

YAML
services:
  owasp-zap:
    image: ghcr.io/zaproxy/zaproxy:stable
    container_name: codecrown-zap-daemon
    command: >
      zap.sh -daemon
      -host 0.0.0.0
      -port 8090
      -config api.key=${ZAP_API_KEY:-change-me-local-dev-key}
      -config api.addrs.addr.name=.*
      -config api.addrs.addr.regex=true
      -config connection.timeoutInSecs=30
    ports:
      - "8090:8090"
    networks:
      - dast-isolated-net
    healthcheck:
      test: ["CMD", "curl", "-fsS", "http://localhost:8090/JSON/core/view/version/?apikey=${ZAP_API_KEY:-change-me-local-dev-key}"]
      interval: 5s
      timeout: 5s
      retries: 12

  # Example isolated staging application target (replace with your staging container)
  staging-target:
    image: bkimminich/juice-shop:latest
    container_name: codecrown-staging-target
    networks:
      - dast-isolated-net
    ports:
      - "3000:3000"

networks:
  dast-isolated-net:
    driver: bridge
    internal: false

Define the Python dependency in requirements.txt:

TEXT
zaproxy==0.4.0
requests==2.32.3

Step 2: Building the ZAP API Scan Orchestrator (zap_scanner.py)

Modern REST APIs and Single-Page Applications rarely expose all routes via traditional <a href> HTML links. To achieve high endpoint coverage, zap_scanner.py combines OpenAPI/Swagger schema ingestion with Authenticated Header Injection (using ZAP's replacer API) and tracks both passive and active scan queues to completion before evaluating a release quality gate:

Python
import json
import os
from pathlib import Path
import sys
import time
from typing import Any
from zapv2 import ZAPv2


ZAP_PROXY_URL = os.getenv("ZAP_PROXY_URL", "http://127.0.0.1:8090")
ZAP_API_KEY = os.getenv("ZAP_API_KEY", "change-me-local-dev-key")
TARGET_BASE_URL = os.getenv("TARGET_BASE_URL", "http://staging-target:3000")
OPENAPI_SPEC_URL = os.getenv("OPENAPI_SPEC_URL", "")  # Optional: e.g., http://staging-target:3000/openapi.json
STAGING_BEARER_TOKEN = os.getenv("STAGING_BEARER_TOKEN", "")
REPORT_DIR = Path(os.getenv("REPORT_DIR", "reports"))
MAX_HIGH_ALERTS = int(os.getenv("MAX_HIGH_ALERTS", "0"))


def wait_for_zap_ready(zap: ZAPv2, timeout_seconds: int = 60) -> None:
    deadline = time.monotonic() + timeout_seconds
    while time.monotonic() < deadline:
        try:
            version = zap.core.version
            if version:
                print(f"[INFO] Connected to OWASP ZAP Daemon v{version}")
                return
        except Exception:
            time.sleep(2)
    raise TimeoutError(f"OWASP ZAP daemon did not become ready within {timeout_seconds}s.")


def configure_auth_header(zap: ZAPv2, bearer_token: str) -> None:
    if not bearer_token:
        print("[INFO] No STAGING_BEARER_TOKEN provided; running unauthenticated scan.")
        return

    rule_desc = "CI-Staging-Bearer-Auth"
    # Remove any stale rule from prior runs
    try:
        zap.replacer.remove_rule(description=rule_desc)
    except Exception:
        pass

    zap.replacer.add_rule(
        description=rule_desc,
        enabled="true",
        matchtype="REQ_HEADER",
        matchregex="false",
        matchstring="Authorization",
        replacement=f"Bearer {bearer_token}",
    )
    print("[INFO] Configured ZAP Replacer rule for authenticated API scanning.")


def discover_attack_surface(zap: ZAPv2, target_url: str, openapi_url: str) -> None:
    # 1. Import OpenAPI / Swagger schema if available for deterministic REST route discovery
    if openapi_url:
        print(f"[INFO] Importing OpenAPI specification from {openapi_url}...")
        zap.openapi.import_url(url=openapi_url, hostoverride=target_url)

    # 2. Run Traditional Spider to discover linked web routes and static assets
    print(f"[INFO] Starting Traditional Spider against {target_url}...")
    spider_id = zap.spider.scan(url=target_url, maxchildren=200, recurse=True)
    while int(zap.spider.status(spider_id)) < 100:
        print(f"  -> Spider progress: {zap.spider.status(spider_id)}%")
        time.sleep(2)
    print(f"[INFO] Spider completed. Total URLs discovered: {len(zap.core.urls(baseurl=target_url))}")


def wait_for_passive_scan(zap: ZAPv2, timeout_seconds: int = 120) -> None:
    print("[INFO] Waiting for ZAP passive scan queue to drain...")
    deadline = time.monotonic() + timeout_seconds
    while time.monotonic() < deadline:
        remaining = int(zap.pscan.records_to_scan)
        if remaining == 0:
            print("[INFO] Passive scan analysis complete.")
            return
        print(f"  -> Passive records remaining: {remaining}")
        time.sleep(2)
    print("[WARN] Passive scan queue timeout reached; proceeding with active scan.")


def run_active_scan(zap: ZAPv2, target_url: str, max_duration_minutes: int = 10) -> None:
    # Tune scanner thread count and max rule duration for deterministic CI execution
    zap.ascan.set_option_thread_per_host(5)
    zap.ascan.set_option_max_scan_duration_in_mins(max_duration_minutes)

    print(f"[INFO] Launching Active Security Scan on {target_url} (budget: {max_duration_minutes}m)...")
    scan_id = zap.ascan.scan(url=target_url, recurse=True, inscopeonly=False)
    while int(zap.ascan.status(scan_id)) < 100:
        print(f"  -> Active Scan progress: {zap.ascan.status(scan_id)}%")
        time.sleep(5)
    print("[INFO] Active Security Scan completed.")


def export_reports_and_evaluate_gate(zap: ZAPv2, target_url: str) -> int:
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    raw_alerts: list[dict[str, Any]] = zap.core.alerts(baseurl=target_url)

    # Deduplicate findings by (pluginId, alert name, risk) for concise developer triage
    grouped: dict[tuple[str, str, str], dict[str, Any]] = {}
    risk_counts = {"High": 0, "Medium": 0, "Low": 0, "Informational": 0}

    for alert in raw_alerts:
        risk = alert.get("risk", "Informational")
        plugin_id = str(alert.get("pluginId", "0"))
        name = alert.get("alert", "Unknown Finding")
        key = (plugin_id, name, risk)

        if key not in grouped:
            risk_counts[risk] = risk_counts.get(risk, 0) + 1
            grouped[key] = {
                "plugin_id": plugin_id,
                "name": name,
                "risk": risk,
                "cwe_id": alert.get("cweid", ""),
                "wasc_id": alert.get("wascid", ""),
                "description": alert.get("description", ""),
                "solution": alert.get("solution", ""),
                "affected_urls": [],
            }
        url_entry = f"{alert.get('method', 'GET')} {alert.get('url', '')}"
        if url_entry not in grouped[key]["affected_urls"] and len(grouped[key]["affected_urls"]) < 10:
            grouped[key]["affected_urls"].append(url_entry)

    summary_report = {
        "target": target_url,
        "summary_counts": risk_counts,
        "unique_findings": list(grouped.values()),
    }

    json_report_path = REPORT_DIR / "zap-dast-report.json"
    json_report_path.write_text(json.dumps(summary_report, indent=2), encoding="utf-8")

    html_report_path = REPORT_DIR / "zap-dast-report.html"
    html_report_path.write_text(zap.core.htmlreport(), encoding="utf-8")

    print("\n================ DAST SCAN SUMMARY ================")
    for level in ("High", "Medium", "Low", "Informational"):
        print(f"  {level:<14}: {risk_counts.get(level, 0)} unique findings")
    print(f"  JSON Report   : {json_report_path}")
    print(f"  HTML Report   : {html_report_path}")
    print("===================================================\n")

    if risk_counts.get("High", 0) > MAX_HIGH_ALERTS:
        print(f"[FAILED] Quality Gate Blocked Release: {risk_counts['High']} High-risk findings exceed threshold ({MAX_HIGH_ALERTS}).")
        return 1

    print("[PASSED] Quality Gate Passed: High-risk findings within acceptable threshold.")
    return 0


if __name__ == "__main__":
    zap_client = ZAPv2(
        apikey=ZAP_API_KEY,
        proxies={"http": ZAP_PROXY_URL, "https": ZAP_PROXY_URL},
    )

    wait_for_zap_ready(zap_client)
    configure_auth_header(zap_client, STAGING_BEARER_TOKEN)
    discover_attack_surface(zap_client, TARGET_BASE_URL, OPENAPI_SPEC_URL)
    wait_for_passive_scan(zap_client)
    run_active_scan(zap_client, TARGET_BASE_URL, max_duration_minutes=10)
    exit_code = export_reports_and_evaluate_gate(zap_client, TARGET_BASE_URL)
    sys.exit(exit_code)

Step 3: Integrating into GitHub Actions CI/CD (.github/workflows/dast-scan.yml)

Wire your Python ZAP orchestrator into GitHub Actions so every pull request or merge to main automatically spins up the staging application, executes the scan, uploads the JSON/HTML reports as build artifacts, and enforces the quality gate:

YAML
name: Automated DAST Vulnerability Scan (OWASP ZAP)

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  zap-dast-gate:
    runs-on: ubuntu-latest
    timeout-minutes: 25

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4

      - name: Set up Python 3.12
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install ZAP Python SDK
        run: pip install -r requirements.txt

      - name: Start Staging Application & OWASP ZAP Daemon
        env:
          ZAP_API_KEY: ${{ secrets.ZAP_API_KEY || 'ci-ephemeral-zap-key' }}
        run: docker compose up -d --wait

      - name: Run Automated ZAP Vulnerability Scan & Quality Gate
        env:
          ZAP_PROXY_URL: "http://127.0.0.1:8090"
          ZAP_API_KEY: ${{ secrets.ZAP_API_KEY || 'ci-ephemeral-zap-key' }}
          TARGET_BASE_URL: "http://staging-target:3000"
          MAX_HIGH_ALERTS: "0"
        run: python3 zap_scanner.py

      - name: Upload ZAP Security Reports
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: zap-dast-security-reports
          path: reports/

      - name: Tear Down Containers
        if: always()
        run: docker compose down -v

Step 4: Running the Scanner Locally & Inspecting Findings

Execute the full pipeline locally against the isolated staging container:

Bash
# 1. Start the OWASP ZAP daemon and isolated staging target
docker compose up -d --wait

# 2. Install Python dependencies and run the ZAP API orchestrator
pip install -r requirements.txt
python3 zap_scanner.py

# 3. Inspect deduplicated High/Medium findings in JSON
cat reports/zap-dast-report.json | python3 -m json.tool | head -n 45

# 4. Clean up containers when finished
docker compose down -v

Common Mistakes

  • Running Active DAST scans against production or shared third-party SaaS endpoints: Active scans inject test payloads, submit forms, and trigger database writes. Always point automated active scans exclusively at an isolated, ephemeral staging environment with synthetic test data—and only run against targets you explicitly own and have authorization to test.
  • Relying solely on the Traditional HTML Spider for REST APIs: Modern JSON APIs return 404 on root paths without an OpenAPI/Swagger specification or Postman collection. Always feed zap.openapi.import_url() (or import_file()) into ZAP so parameterized POST, PUT, and DELETE endpoints are tested.
  • Failing builds immediately on Low or Informational alerts: Blocking developer pull requests over minor informational headers (like X-Powered-By or timestamp disclosure) causes alert fatigue and prompts teams to disable the scanner. Gate builds strictly on verified High findings while routing Medium findings to your security backlog.

Summary

Automating OWASP ZAP via its Python REST API transforms dynamic vulnerability scanning into a repeatable, self-service CI/CD security gate. By combining containerized daemon isolation, OpenAPI endpoint discovery, authenticated header injection, and deduplicated JSON/HTML reporting, engineering teams catch high-severity web and API flaws before deployment without slowing release velocity.