devsecpac 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
devsec_cli/reporter.py ADDED
@@ -0,0 +1,207 @@
1
+ """Consolidated Reporting, Finding Drill-Down, and Quality Gate Enforcement."""
2
+
3
+ from pathlib import Path
4
+ from typing import List
5
+ import json
6
+ from rich.console import Console
7
+ from rich.table import Table
8
+ from rich.panel import Panel
9
+ from .contracts import ToolResult, StatusEnum, FindingDetail
10
+
11
+
12
+ class Reporter:
13
+ def __init__(self, console: Console = None):
14
+ self.console = console or Console()
15
+
16
+ def print_terminal_table(self, results: List[ToolResult]):
17
+ """Prints a refined, non-wrapping terminal table of active scanner results.
18
+ Filters out NOT_APPLICABLE tools with 0 findings to keep outputs clean."""
19
+ active_results = [
20
+ r for r in results
21
+ if not (r.status == StatusEnum.NOT_APPLICABLE and r.findings.total == 0)
22
+ ]
23
+
24
+ table = Table(
25
+ title="DevSecOps Autonomous Pipeline Scan Results",
26
+ show_lines=True,
27
+ header_style="bold cyan",
28
+ expand=False
29
+ )
30
+
31
+ table.add_column("Scanner / Tool", style="bold white", no_wrap=True)
32
+ table.add_column("Category", style="magenta", no_wrap=True)
33
+ table.add_column("Status", justify="center", no_wrap=True)
34
+ table.add_column("Crit", justify="right", style="bold red", no_wrap=True)
35
+ table.add_column("High", justify="right", style="red", no_wrap=True)
36
+ table.add_column("Med", justify="right", style="yellow", no_wrap=True)
37
+ table.add_column("Low", justify="right", style="blue", no_wrap=True)
38
+ table.add_column("Time", justify="right", style="dim", no_wrap=True)
39
+ table.add_column("Summary", style="dim white")
40
+
41
+ status_styles = {
42
+ StatusEnum.PASS: "[bold green]PASS[/bold green]",
43
+ StatusEnum.FAIL: "[bold red]FAIL[/bold red]",
44
+ StatusEnum.NOT_APPLICABLE: "[dim cyan]NOT_APPLICABLE[/dim cyan]",
45
+ StatusEnum.SKIPPED: "[dim yellow]SKIPPED[/dim yellow]",
46
+ StatusEnum.ERROR: "[bold white on red]ERROR[/bold white on red]",
47
+ }
48
+
49
+ for r in active_results:
50
+ styled_status = status_styles.get(r.status, r.status.value)
51
+ table.add_row(
52
+ r.tool_name,
53
+ r.category,
54
+ styled_status,
55
+ str(r.findings.critical),
56
+ str(r.findings.high),
57
+ str(r.findings.medium),
58
+ str(r.findings.low),
59
+ f"{r.duration_seconds}s",
60
+ r.summary
61
+ )
62
+
63
+ self.console.print()
64
+ self.console.print(table)
65
+ self.console.print()
66
+
67
+ def print_findings_drilldown(self, results: List[ToolResult]):
68
+ """Prints detailed findings grouped by file and severity, with automatic cross-scanner deduplication."""
69
+ from .correlator import FindingCorrelator
70
+ all_items, stats = FindingCorrelator.deduplicate_findings(results)
71
+
72
+ if not all_items:
73
+ return
74
+
75
+ # Separate items by severity
76
+ crit_items = [i for i in all_items if i.severity.upper() == "CRITICAL"]
77
+ high_items = [i for i in all_items if i.severity.upper() == "HIGH"]
78
+ med_items = [i for i in all_items if i.severity.upper() == "MEDIUM"]
79
+ low_items = [i for i in all_items if i.severity.upper() == "LOW"]
80
+
81
+ total_crit = len(crit_items)
82
+ total_high = len(high_items)
83
+ total_med = len(med_items)
84
+ total_low = len(low_items)
85
+
86
+ dedup_info = f" (Deduplicated: {stats['duplicates_removed']} duplicate alerts collapsed)" if stats['duplicates_removed'] > 0 else ""
87
+ summary_title = (
88
+ f"Security Findings Breakdown: "
89
+ f"[bold red]{total_crit} Critical[/bold red] | "
90
+ f"[red]{total_high} High[/red] | "
91
+ f"[yellow]{total_med} Medium[/yellow] | "
92
+ f"[blue]{total_low} Low[/blue]{dedup_info}"
93
+ )
94
+
95
+ table = Table(
96
+ title=summary_title,
97
+ show_lines=True,
98
+ header_style="bold yellow",
99
+ expand=False
100
+ )
101
+
102
+ table.add_column("Severity", justify="center", no_wrap=True)
103
+ table.add_column("Scanner", style="cyan", no_wrap=True)
104
+ table.add_column("Location (File:Line)", style="bold white")
105
+ table.add_column("Rule / CVE", style="bold magenta", no_wrap=True)
106
+ table.add_column("Description", style="dim white")
107
+
108
+ sev_styles = {
109
+ "CRITICAL": "[bold white on red] CRIT [/bold white on red]",
110
+ "HIGH": "[bold red] HIGH [/bold red]",
111
+ "MEDIUM": "[yellow] MED [/yellow]",
112
+ "LOW": "[blue] LOW [/blue]",
113
+ "INFO": "[dim] INFO [/dim]",
114
+ }
115
+
116
+ # Show in priority order: CRITICAL -> HIGH -> MEDIUM -> LOW
117
+ for item in (crit_items + high_items + med_items + low_items):
118
+ loc = f"{item.file}:{item.line}" if item.line else item.file
119
+ table.add_row(
120
+ sev_styles.get(item.severity.upper(), item.severity),
121
+ item.tool,
122
+ loc,
123
+ item.rule or "-",
124
+ item.description
125
+ )
126
+
127
+ self.console.print(table)
128
+ self.console.print()
129
+
130
+ def generate_markdown_summary(self, results: List[ToolResult], output_path: Path):
131
+ """Generates an executive Markdown table with full findings drill-down."""
132
+ md = []
133
+ md.append("# Autonomous DevSecOps Pipeline Security Report\n")
134
+ md.append("| Scanner / Tool | Category | Status | Crit | High | Med | Low | Time | Summary |")
135
+ md.append("|:---|:---|:---:|:---:|:---:|:---:|:---:|:---:|:---|")
136
+
137
+ status_labels = {
138
+ StatusEnum.PASS: "[PASS]",
139
+ StatusEnum.FAIL: "[FAIL]",
140
+ StatusEnum.NOT_APPLICABLE: "[N/A]",
141
+ StatusEnum.SKIPPED: "[SKIPPED]",
142
+ StatusEnum.ERROR: "[ERROR]",
143
+ }
144
+
145
+ total_crit = sum(r.findings.critical for r in results)
146
+ total_high = sum(r.findings.high for r in results)
147
+ total_med = sum(r.findings.medium for r in results)
148
+ total_low = sum(r.findings.low for r in results)
149
+
150
+ active_results = [
151
+ r for r in results
152
+ if not (r.status == StatusEnum.NOT_APPLICABLE and r.findings.total == 0)
153
+ ]
154
+
155
+ for r in active_results:
156
+ tag = status_labels.get(r.status, r.status.value)
157
+ md.append(
158
+ f"| **{r.tool_name}** | {r.category} | {tag} | "
159
+ f"{r.findings.critical} | {r.findings.high} | {r.findings.medium} | {r.findings.low} | "
160
+ f"{r.duration_seconds}s | {r.summary} |"
161
+ )
162
+
163
+ md.append(
164
+ f"| **TOTAL** | **ALL CATEGORIES** | - | **{total_crit}** | **{total_high}** | **{total_med}** | **{total_low}** | - | - |"
165
+ )
166
+ md.append("\n---\n")
167
+
168
+ if (total_crit + total_high) > 0:
169
+ md.append(f"> **GATE FAILED**: Found **{total_crit} Critical** and **{total_high} High** severity issue(s). Pipeline gate blocked.\n")
170
+ else:
171
+ md.append("> **GATE PASSED**: No Critical or High severity security issues detected.\n")
172
+
173
+ # Detailed Findings Table in Markdown
174
+ all_items: List[FindingDetail] = []
175
+ for r in results:
176
+ all_items.extend(r.items)
177
+
178
+ if all_items:
179
+ md.append("## Detailed Findings Drill-Down\n")
180
+ md.append("| Severity | Scanner | Location (File:Line) | Rule / CVE | Description |")
181
+ md.append("|:---:|:---|:---|:---|:---|")
182
+ for item in all_items:
183
+ loc = f"`{item.file}:{item.line}`" if item.line else f"`{item.file}`"
184
+ md.append(f"| **{item.severity}** | {item.tool} | {loc} | `{item.rule}` | {item.description} |")
185
+ md.append("\n")
186
+
187
+ if output_path.parent:
188
+ output_path.parent.mkdir(parents=True, exist_ok=True)
189
+ output_path.write_text("\n".join(md), encoding="utf-8")
190
+
191
+ def export_json_report(self, results: List[ToolResult], output_path: Path, telemetry: dict = None):
192
+ """Consolidates status.json outputs into one JSON report with scan telemetry."""
193
+ if output_path.parent:
194
+ output_path.parent.mkdir(parents=True, exist_ok=True)
195
+ report = {
196
+ "total_tools": len(results),
197
+ "telemetry": telemetry or {},
198
+ "summary": {
199
+ "critical": sum(r.findings.critical for r in results),
200
+ "high": sum(r.findings.high for r in results),
201
+ "medium": sum(r.findings.medium for r in results),
202
+ "low": sum(r.findings.low for r in results),
203
+ },
204
+ "gate_passed": (sum(r.findings.critical for r in results) + sum(r.findings.high for r in results)) == 0,
205
+ "results": [r.to_dict() for r in results]
206
+ }
207
+ output_path.write_text(json.dumps(report, indent=2), encoding="utf-8")
devsec_cli/runner.py ADDED
@@ -0,0 +1,68 @@
1
+ """Cross-platform process runner and binary locator."""
2
+
3
+ import os
4
+ import shutil
5
+ import subprocess
6
+ import time
7
+ from pathlib import Path
8
+ from typing import List, Optional, Tuple
9
+
10
+
11
+ class ProcessRunner:
12
+ @staticmethod
13
+ def find_binary(binary_name: Optional[str]) -> Optional[str]:
14
+ """Locates a binary executable across PATH and ~/.local/bin fallback."""
15
+ if not binary_name:
16
+ return None
17
+
18
+ # 1. Standard PATH lookup
19
+ found = shutil.which(binary_name)
20
+ if found and Path(found).is_file():
21
+ return found
22
+
23
+ # 2. Local bin fallback (~/.local/bin or %USERPROFILE%\.local\bin)
24
+ user_home = Path(os.environ.get("USERPROFILE") if os.name == "nt" else Path.home())
25
+ local_bin = user_home / ".local" / "bin" / binary_name
26
+ if local_bin.is_file() and (os.name == "nt" or os.access(local_bin, os.X_OK)):
27
+ return str(local_bin)
28
+
29
+ if os.name == "nt":
30
+ for ext in (".exe", ".cmd", ".bat"):
31
+ cand = user_home / ".local" / "bin" / f"{binary_name}{ext}"
32
+ if cand.is_file():
33
+ return str(cand)
34
+
35
+ return None
36
+
37
+ @staticmethod
38
+ def run_command(
39
+ args: List[str],
40
+ cwd: Optional[str] = None,
41
+ timeout: int = 300,
42
+ env: Optional[dict] = None
43
+ ) -> Tuple[int, str, str, float]:
44
+ """
45
+ Executes a command safely without shell=True.
46
+ Returns: (exit_code, stdout, stderr, elapsed_time_seconds)
47
+ """
48
+ start = time.time()
49
+ try:
50
+ process = subprocess.run(
51
+ args,
52
+ cwd=cwd,
53
+ capture_output=True,
54
+ text=True,
55
+ encoding="utf-8",
56
+ errors="replace",
57
+ timeout=timeout,
58
+ env=env,
59
+ shell=False
60
+ )
61
+ elapsed = round(time.time() - start, 2)
62
+ return process.returncode, process.stdout, process.stderr, elapsed
63
+ except subprocess.TimeoutExpired:
64
+ elapsed = round(time.time() - start, 2)
65
+ return -1, "", f"Command timed out after {timeout} seconds", elapsed
66
+ except Exception as e:
67
+ elapsed = round(time.time() - start, 2)
68
+ return -1, "", str(e), elapsed
@@ -0,0 +1 @@
1
+ """Scanner implementations."""
@@ -0,0 +1,45 @@
1
+ """Base scanner interface."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from pathlib import Path
5
+ from typing import Optional, List
6
+ from ..contracts import ToolResult, StatusEnum, FindingCounts
7
+ from ..runner import ProcessRunner
8
+
9
+
10
+ class BaseScanner(ABC):
11
+ def __init__(self, name: str, category: str, binary_name: Optional[str] = None):
12
+ self.name = name
13
+ self.category = category
14
+ self.binary_name = binary_name
15
+ self.binary_path = ProcessRunner.find_binary(binary_name) if binary_name else None
16
+
17
+ def is_tool_available(self) -> bool:
18
+ if self.binary_name is None:
19
+ return True
20
+ return self.binary_path is not None
21
+
22
+ @abstractmethod
23
+ def scan(self, target_dir: Path) -> ToolResult:
24
+ """Executes the scan and returns a normalized ToolResult."""
25
+ pass
26
+
27
+ def create_not_applicable_result(self, reason: str) -> ToolResult:
28
+ return ToolResult(
29
+ tool_name=self.name,
30
+ category=self.category,
31
+ status=StatusEnum.NOT_APPLICABLE,
32
+ exit_code=0,
33
+ summary=f"N/A: {reason}",
34
+ findings=FindingCounts()
35
+ )
36
+
37
+ def create_skipped_result(self, reason: str) -> ToolResult:
38
+ return ToolResult(
39
+ tool_name=self.name,
40
+ category=self.category,
41
+ status=StatusEnum.SKIPPED,
42
+ exit_code=0,
43
+ summary=f"Skipped: {reason}",
44
+ findings=FindingCounts()
45
+ )
@@ -0,0 +1,140 @@
1
+ """GitHub CodeQL Deep SAST scanner."""
2
+
3
+ from pathlib import Path
4
+ import json
5
+ import shutil
6
+ import tempfile
7
+ from .base import BaseScanner
8
+ from ..contracts import ToolResult, StatusEnum, FindingCounts, FindingDetail
9
+ from ..runner import ProcessRunner
10
+ from ..discovery import TargetDiscovery
11
+
12
+
13
+ class CodeQLScanner(BaseScanner):
14
+ def __init__(self):
15
+ super().__init__(name="GitHub CodeQL", category="SAST", binary_name="codeql")
16
+
17
+ def _map_language(self, detected: dict) -> str:
18
+ """Maps detected application runtimes to primary CodeQL language identifier."""
19
+ priority_map = {
20
+ "python": "python",
21
+ "nodejs": "javascript",
22
+ "golang": "go",
23
+ "java": "java",
24
+ "dotnet": "csharp",
25
+ "rust": None # CodeQL does not natively analyze Rust
26
+ }
27
+ for lang_key, codeql_lang in priority_map.items():
28
+ if lang_key in detected and codeql_lang:
29
+ return codeql_lang
30
+ return ""
31
+
32
+ def scan(self, target_dir: Path) -> ToolResult:
33
+ discovery = TargetDiscovery(target_dir)
34
+ languages = discovery.detect_languages()
35
+ codeql_lang = self._map_language(languages)
36
+
37
+ if not codeql_lang:
38
+ return self.create_not_applicable_result("No CodeQL-supported languages detected")
39
+
40
+ if not self.is_tool_available():
41
+ return self.create_skipped_result("codeql binary not found in PATH")
42
+
43
+ findings = FindingCounts()
44
+ items = []
45
+ status = StatusEnum.PASS
46
+ summary = f"CodeQL SAST analysis completed for {codeql_lang}"
47
+
48
+ sarif_out = target_dir / ".codeql_results.sarif"
49
+ db_dir = target_dir / ".codeql_db"
50
+
51
+ try:
52
+ # 1. Create database
53
+ create_cmd = [
54
+ str(self.binary_path),
55
+ "database", "create",
56
+ str(db_dir),
57
+ f"--language={codeql_lang}",
58
+ f"--source-root={target_dir}",
59
+ "--overwrite"
60
+ ]
61
+ c_code, _, stderr_c, _ = ProcessRunner.run_command(create_cmd, cwd=str(target_dir), timeout=600)
62
+ if c_code != 0:
63
+ return self.create_skipped_result(f"CodeQL database build skipped for {codeql_lang} (compilation or query pack required)")
64
+
65
+ # 2. Analyze database and emit SARIF
66
+ # Specify the query pack for the language (e.g. codeql/javascript-queries)
67
+ query_pack = f"codeql/{codeql_lang}-queries"
68
+ analyze_cmd = [
69
+ str(self.binary_path),
70
+ "database", "analyze",
71
+ str(db_dir),
72
+ query_pack,
73
+ "--format=sarif-latest",
74
+ f"--output={sarif_out}"
75
+ ]
76
+ a_code, _, _, elapsed = ProcessRunner.run_command(analyze_cmd, cwd=str(target_dir), timeout=600)
77
+
78
+ # 3. Parse SARIF findings
79
+ if sarif_out.exists():
80
+ sarif_data = json.loads(sarif_out.read_text(encoding="utf-8"))
81
+ for run in sarif_data.get("runs", []):
82
+ for res in run.get("results", []):
83
+ level = str(res.get("level", "warning")).lower()
84
+ sev = "MEDIUM"
85
+ if level == "error":
86
+ findings.high += 1
87
+ sev = "HIGH"
88
+ elif level == "warning":
89
+ findings.medium += 1
90
+ sev = "MEDIUM"
91
+ else:
92
+ findings.low += 1
93
+ sev = "LOW"
94
+
95
+ rule_id = res.get("ruleId", "CodeQLRule")
96
+ msg = res.get("message", {}).get("text", "")
97
+ locs = res.get("locations", [])
98
+ file_uri = ""
99
+ line_str = ""
100
+ if locs:
101
+ phys = locs[0].get("physicalLocation", {})
102
+ file_uri = phys.get("artifactLocation", {}).get("uri", "unknown")
103
+ start_line = phys.get("region", {}).get("startLine")
104
+ line_str = str(start_line) if start_line else ""
105
+
106
+ items.append(
107
+ FindingDetail(
108
+ severity=sev,
109
+ tool=self.name,
110
+ file=file_uri,
111
+ line=line_str,
112
+ rule=rule_id,
113
+ description=msg[:120]
114
+ )
115
+ )
116
+
117
+ if findings.has_blocking:
118
+ status = StatusEnum.FAIL
119
+ summary = f"Detected {findings.high} High SAST issue(s) ({codeql_lang})"
120
+ elif findings.total > 0:
121
+ summary = f"Detected {findings.total} non-blocking SAST issue(s) ({codeql_lang})"
122
+
123
+ except Exception as e:
124
+ return self.create_skipped_result(f"CodeQL analysis skipped: {str(e)[:50]}")
125
+ finally:
126
+ # Clean up db and temp sarif
127
+ sarif_out.unlink(missing_ok=True)
128
+ if db_dir.exists():
129
+ shutil.rmtree(db_dir, ignore_errors=True)
130
+
131
+ return ToolResult(
132
+ tool_name=self.name,
133
+ category=self.category,
134
+ status=status,
135
+ exit_code=0,
136
+ summary=summary,
137
+ findings=findings,
138
+ duration_seconds=elapsed,
139
+ items=items
140
+ )
@@ -0,0 +1,69 @@
1
+ """Cosign & Sigstore Cryptographic Attestation and SBOM Signing Engine."""
2
+
3
+ from pathlib import Path
4
+ import os
5
+ from .base import BaseScanner
6
+ from ..contracts import ToolResult, StatusEnum, FindingCounts, FindingDetail
7
+ from ..runner import ProcessRunner
8
+
9
+
10
+ class CosignAttestationEngine(BaseScanner):
11
+ """Cryptographically signs and verifies SBOMs and build artifacts using Sigstore/Cosign."""
12
+
13
+ def __init__(self):
14
+ super().__init__(name="Cosign (Sigstore)", category="Supply Chain Security", binary_name="cosign")
15
+
16
+ def scan(self, target_dir: Path) -> ToolResult:
17
+ sbom_path = target_dir / "sbom-cyclonedx.json"
18
+
19
+ if not sbom_path.exists():
20
+ # Check current working directory for generated SBOM
21
+ local_sbom = Path("sbom-cyclonedx.json")
22
+ if local_sbom.exists():
23
+ sbom_path = local_sbom
24
+ else:
25
+ return self.create_not_applicable_result("No CycloneDX SBOM file found to attest/sign")
26
+
27
+ if not self.is_tool_available():
28
+ return self.create_skipped_result("cosign binary not found in PATH")
29
+
30
+ # Verify or sign SBOM based on key presence
31
+ cosign_key = os.environ.get("COSIGN_KEY")
32
+ sig_path = target_dir / "sbom-cyclonedx.json.sig"
33
+
34
+ findings = FindingCounts()
35
+ items = []
36
+
37
+ if cosign_key:
38
+ # Sign blob
39
+ cmd = [
40
+ str(self.binary_path),
41
+ "sign-blob",
42
+ "--key", cosign_key,
43
+ "--output-signature", str(sig_path),
44
+ str(sbom_path)
45
+ ]
46
+ code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir), timeout=60)
47
+ if code == 0:
48
+ summary = f"Cosign signed SBOM with cryptographic signature at {sig_path.name}"
49
+ status = StatusEnum.PASS
50
+ else:
51
+ findings.medium += 1
52
+ summary = f"Cosign signing failed: {stderr.strip()}"
53
+ status = StatusEnum.FAIL
54
+ else:
55
+ # Keyless verification or attestation check
56
+ elapsed = 0.1
57
+ summary = "Cosign ready (export COSIGN_KEY to cryptographically sign generated CycloneDX SBOM)"
58
+ status = StatusEnum.PASS
59
+
60
+ return ToolResult(
61
+ tool_name=self.name,
62
+ category=self.category,
63
+ status=status,
64
+ exit_code=0,
65
+ summary=summary,
66
+ findings=findings,
67
+ duration_seconds=elapsed,
68
+ items=items
69
+ )
@@ -0,0 +1,127 @@
1
+ """OWASP ZAP Dynamic Application Security Testing (DAST) Scanner."""
2
+
3
+ from pathlib import Path
4
+ import os
5
+ import json
6
+ from .base import BaseScanner
7
+ from ..contracts import ToolResult, StatusEnum, FindingCounts, FindingDetail
8
+ from ..runner import ProcessRunner
9
+ from ..discovery import TargetDiscovery
10
+
11
+
12
+ class OWASPZAPScanner(BaseScanner):
13
+ def __init__(self):
14
+ # Can run either via native zap-baseline.py CLI or zap.sh
15
+ super().__init__(name="OWASP ZAP (Baseline)", category="DAST", binary_name="zap-baseline.py")
16
+
17
+ def is_tool_available(self) -> bool:
18
+ # Check either zap-baseline.py or zap.sh or docker
19
+ return (
20
+ super().is_tool_available()
21
+ or ProcessRunner.find_binary("zap.sh") is not None
22
+ or ProcessRunner.find_binary("docker") is not None
23
+ )
24
+
25
+ def scan(self, target_dir: Path) -> ToolResult:
26
+ discovery = TargetDiscovery(target_dir)
27
+ compose_files = discovery.discover_compose_files()
28
+ target_url = os.environ.get("DAST_TARGET_URL")
29
+
30
+ if not compose_files and not target_url:
31
+ return self.create_not_applicable_result("No docker-compose file or DAST_TARGET_URL configured")
32
+
33
+ if not self.is_tool_available():
34
+ return self.create_skipped_result("Neither zap-baseline.py, zap.sh, nor docker found in PATH")
35
+
36
+ # Default URL to scan if compose is present
37
+ scan_url = target_url or "http://localhost:8080"
38
+ report_json = target_dir / ".zap_report.json"
39
+
40
+ # Determine run command (native zap-baseline.py or docker ghcr.io/zaproxy/zaproxy:stable)
41
+ cmd = []
42
+ if self.binary_path:
43
+ cmd = [
44
+ str(self.binary_path),
45
+ "-t", scan_url,
46
+ "-J", report_json.name,
47
+ "-m", "2" # 2 minute baseline limit
48
+ ]
49
+ elif ProcessRunner.find_binary("docker"):
50
+ docker_bin = ProcessRunner.find_binary("docker")
51
+ cmd = [
52
+ str(docker_bin),
53
+ "run", "--rm",
54
+ "--network", "host",
55
+ "-v", f"{target_dir}:/zap/wrk/:rw",
56
+ "ghcr.io/zaproxy/zaproxy:stable",
57
+ "zap-baseline.py",
58
+ "-t", scan_url,
59
+ "-J", report_json.name,
60
+ "-m", "2"
61
+ ]
62
+
63
+ code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir), timeout=300)
64
+
65
+ findings = FindingCounts()
66
+ items = []
67
+ status = StatusEnum.PASS
68
+ summary = f"DAST baseline scan completed against {scan_url}"
69
+
70
+ if report_json.exists():
71
+ try:
72
+ data = json.loads(report_json.read_text(encoding="utf-8"))
73
+ site_alerts = data.get("site", [])
74
+ for site in site_alerts:
75
+ alerts = site.get("alerts", [])
76
+ for alert in alerts:
77
+ riskcode = str(alert.get("riskcode", "0"))
78
+ sev = "LOW"
79
+ if riskcode == "3":
80
+ findings.high += 1
81
+ sev = "HIGH"
82
+ elif riskcode == "2":
83
+ findings.medium += 1
84
+ sev = "MEDIUM"
85
+ elif riskcode == "1":
86
+ findings.low += 1
87
+ sev = "LOW"
88
+ else:
89
+ findings.info += 1
90
+ sev = "INFO"
91
+
92
+ name = alert.get("alert", "ZAPAlert")
93
+ desc = alert.get("desc", "")[:100]
94
+ plugin_id = alert.get("pluginid", "ZAP")
95
+ uri = alert.get("instances", [{}])[0].get("uri", scan_url) if alert.get("instances") else scan_url
96
+
97
+ items.append(
98
+ FindingDetail(
99
+ severity=sev,
100
+ tool=self.name,
101
+ file=uri,
102
+ line="",
103
+ rule=f"ZAP-{plugin_id}",
104
+ description=f"{name}: {desc}"
105
+ )
106
+ )
107
+ except Exception:
108
+ pass
109
+ finally:
110
+ report_json.unlink(missing_ok=True)
111
+
112
+ if findings.has_blocking:
113
+ status = StatusEnum.FAIL
114
+ summary = f"Detected {findings.high} High/Critical DAST vulnerability(ies) on {scan_url}"
115
+ elif findings.total > 0:
116
+ summary = f"Detected {findings.total} non-blocking alerts ({findings.medium} Med, {findings.low} Low)"
117
+
118
+ return ToolResult(
119
+ tool_name=self.name,
120
+ category=self.category,
121
+ status=status,
122
+ exit_code=0,
123
+ summary=summary,
124
+ findings=findings,
125
+ duration_seconds=elapsed,
126
+ items=items
127
+ )