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/cli.py ADDED
@@ -0,0 +1,431 @@
1
+ """devsecpac / devsec-cli main entrypoint."""
2
+
3
+ import argparse
4
+ import os
5
+ import sys
6
+ import time
7
+ from pathlib import Path
8
+ from typing import List, Optional
9
+ from rich.console import Console
10
+
11
+ from .contracts import ToolResult, StatusEnum
12
+ from .discovery import TargetDiscovery
13
+ from .reporter import Reporter
14
+ from .installer import ToolInstaller
15
+ from .ingestion import RepoIngestion
16
+ from .scanners.secrets import GitleaksScanner, TruffleHogScanner
17
+ from .scanners.docker import HadolintScanner
18
+ from .scanners.iac import CheckovScanner, KubeconformScanner
19
+ from .scanners.kyverno import KyvernoScanner
20
+ from .scanners.codeql import CodeQLScanner
21
+ from .scanners.sonar import SonarQubeScanner
22
+ from .scanners.sca import TrivyFSScanner, DependencyCheckScanner
23
+ from .scanners.sbom import SyftScanner
24
+ from .scanners.dast import OWASPZAPScanner
25
+ from .scanners.k8s_audit import K8sStructuralAuditScanner
26
+ from .scanners.mobsf import MobSFScanner
27
+ from .scanners.nmap import NmapScanner
28
+ from .scanners.semgrep import SemgrepScanner
29
+ from .scanners.schemathesis import SchemathesisScanner
30
+ from .scanners.cosign import CosignAttestationEngine
31
+
32
+
33
+ console = Console()
34
+
35
+
36
+ def build_scanners():
37
+ return [
38
+ GitleaksScanner(),
39
+ TruffleHogScanner(),
40
+ SemgrepScanner(),
41
+ HadolintScanner(),
42
+ CodeQLScanner(),
43
+ SonarQubeScanner(),
44
+ CheckovScanner(),
45
+ KubeconformScanner(),
46
+ KyvernoScanner(),
47
+ TrivyFSScanner(),
48
+ DependencyCheckScanner(),
49
+ SyftScanner(),
50
+ CosignAttestationEngine(),
51
+ OWASPZAPScanner(),
52
+ SchemathesisScanner(),
53
+ NmapScanner(),
54
+ MobSFScanner(),
55
+ K8sStructuralAuditScanner(),
56
+ ]
57
+
58
+
59
+ def filter_scanners(scanners, include_str: Optional[str] = None, exclude_str: Optional[str] = None):
60
+ """Filters scanner instances by user-provided comma-separated include/exclude lists."""
61
+ filtered = scanners
62
+
63
+ def normalize(val: str) -> str:
64
+ return val.lower().replace("-", "").replace("_", "").replace(" ", "")
65
+
66
+ if include_str:
67
+ targets = [normalize(t.strip()) for t in include_str.split(",") if t.strip()]
68
+ selected = []
69
+ for s in filtered:
70
+ name_norm = normalize(s.name)
71
+ bin_norm = normalize(s.binary_name) if s.binary_name else ""
72
+ cat_norm = normalize(s.category.value if hasattr(s.category, "value") else str(s.category))
73
+ if any(t in name_norm or (bin_norm and t in bin_norm) or t in cat_norm for t in targets):
74
+ selected.append(s)
75
+ filtered = selected
76
+
77
+ if exclude_str:
78
+ skips = [normalize(x.strip()) for x in exclude_str.split(",") if x.strip()]
79
+ selected = []
80
+ for s in filtered:
81
+ name_norm = normalize(s.name)
82
+ bin_norm = normalize(s.binary_name) if s.binary_name else ""
83
+ cat_norm = normalize(s.category.value if hasattr(s.category, "value") else str(s.category))
84
+ if not any(x in name_norm or (bin_norm and x in bin_norm) or x in cat_norm for x in skips):
85
+ selected.append(s)
86
+ filtered = selected
87
+
88
+ return filtered
89
+
90
+
91
+ def run_info():
92
+ """Prints diagnostic information about available security tools on the current host."""
93
+ scanners = build_scanners()
94
+ console.print("\n[bold cyan]DevSecOps Host Binary Detection Status (16 Engines)[/bold cyan]\n")
95
+ for s in scanners:
96
+ if s.binary_name is None:
97
+ console.print(f" * [green][OK][/green] {s.name:<32} (Native Python Engine)")
98
+ elif s.binary_path or s.is_tool_available():
99
+ found_path = s.binary_path or "Available (Container/CLI)"
100
+ console.print(f" * [green][OK][/green] {s.name:<32} Found: [dim]{found_path}[/dim]")
101
+ else:
102
+ console.print(f" * [yellow][--][/yellow] {s.name:<32} [dim]Missing '{s.binary_name}' in PATH (will gracefully SKIP)[/dim]")
103
+ console.print()
104
+ console.print("[dim]Tip: Run 'devsec setup' to automatically install missing security scanners.[/dim]\n")
105
+
106
+
107
+ def run_setup():
108
+ installer = ToolInstaller()
109
+ installer.install_all()
110
+
111
+
112
+ def run_scan(
113
+ target_path: Path,
114
+ output_json: Path,
115
+ output_md: Path,
116
+ strict: bool = False,
117
+ install_missing: bool = False,
118
+ repo_url: Optional[str] = None,
119
+ branch: Optional[str] = None,
120
+ token: Optional[str] = None,
121
+ keep_repo: bool = False,
122
+ tools: Optional[str] = None,
123
+ exclude: Optional[str] = None
124
+ ) -> int:
125
+ ingestion: Optional[RepoIngestion] = None
126
+
127
+ # Handle remote repository ingestion
128
+ if repo_url:
129
+ ingestion = RepoIngestion(repo_url=repo_url, token=token, branch=branch, keep_repo=keep_repo)
130
+ success, cloned_path, err = ingestion.clone_repository()
131
+ if not success or not cloned_path:
132
+ console.print(f"[bold red][FAIL] Remote Ingestion Failed:[/bold red] {err}\n")
133
+ return 1
134
+ target_path = cloned_path
135
+
136
+ if install_missing:
137
+ console.print("[bold blue]Checking and installing missing tools first...[/bold blue]")
138
+ installer = ToolInstaller()
139
+ installer.install_all()
140
+
141
+ console.print(f"\n[bold green]Initiating DevSecOps Scan on:[/bold green] [bold white]{target_path.resolve()}[/bold white]\n")
142
+
143
+ try:
144
+ # Stack and File discovery
145
+ discovery = TargetDiscovery(target_path)
146
+ languages = discovery.detect_languages()
147
+ dockerfiles = discovery.discover_dockerfiles()
148
+ k8s = discovery.discover_k8s_manifests()
149
+ iac = discovery.discover_iac_files()
150
+ compose = discovery.discover_compose_files()
151
+ all_scannable_files = discovery.discover_scannable_files()
152
+ total_files_count = len(all_scannable_files)
153
+
154
+ console.print(f" Target is Git repo: [bold]{'Yes' if discovery.is_git_repo() else 'No'}[/bold]")
155
+ console.print(f" Total Scannable Files: [bold]{total_files_count}[/bold]")
156
+ console.print(f" Detected Runtimes: [bold]{', '.join(languages.keys()) if languages else 'None'}[/bold]")
157
+ console.print(f" Dockerfiles found: [bold]{len(dockerfiles)}[/bold]")
158
+ console.print(f" Kubernetes manifests: [bold]{len(k8s)}[/bold]")
159
+ console.print(f" IaC files found: [bold]{len(iac)}[/bold]")
160
+ console.print(f" Compose files found: [bold]{len(compose)}[/bold]")
161
+ console.print()
162
+
163
+ scanners = build_scanners()
164
+ scanners = filter_scanners(scanners, include_str=tools, exclude_str=exclude)
165
+ if not scanners:
166
+ console.print("[bold yellow][WARN][/bold yellow] No security scanners matched the provided filters.\n")
167
+ return 0
168
+ results: List[ToolResult] = []
169
+
170
+ total_scanners = len(scanners)
171
+ start_overall_time = time.time()
172
+ processed_files_set = set()
173
+
174
+ from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn, TimeRemainingColumn
175
+
176
+ with Progress(
177
+ SpinnerColumn(),
178
+ TextColumn("[bold cyan]{task.description}"),
179
+ BarColumn(bar_width=None),
180
+ TextColumn("[bold yellow]{task.completed}/{task.total} engines"),
181
+ TextColumn("•"),
182
+ TextColumn("[green]{task.fields[file_progress]}"),
183
+ TextColumn("•"),
184
+ TimeElapsedColumn(),
185
+ TextColumn("•"),
186
+ TimeRemainingColumn(),
187
+ console=console,
188
+ transient=True
189
+ ) as progress:
190
+ scan_task = progress.add_task(
191
+ "Running security scan pipeline...",
192
+ total=total_scanners,
193
+ file_progress=f"0/{total_files_count} files"
194
+ )
195
+
196
+ for idx, scanner in enumerate(scanners, start=1):
197
+ progress.update(
198
+ scan_task,
199
+ description=f"Scanning with [{idx}/{total_scanners}] {scanner.name}..."
200
+ )
201
+ progress.refresh()
202
+ try:
203
+ res = scanner.scan(target_path)
204
+ results.append(res)
205
+ except Exception as e:
206
+ res = ToolResult(
207
+ tool_name=scanner.name,
208
+ category=scanner.category,
209
+ status=StatusEnum.ERROR,
210
+ exit_code=1,
211
+ summary=f"Internal error: {str(e)}"
212
+ )
213
+ results.append(res)
214
+
215
+ # Collect per-file count progress
216
+ if res.file_timings:
217
+ for fpath in res.file_timings:
218
+ processed_files_set.add(fpath)
219
+ elif res.status in (StatusEnum.PASS, StatusEnum.FAIL) and scanner.category in ("Fast SAST", "SAST", "Secret Detection", "SCA & Vulnerability", "SBOM Generation", "Code Quality & SAST"):
220
+ for f in all_scannable_files:
221
+ rel = str(f.relative_to(target_path)) if str(f).startswith(str(target_path)) else f.name
222
+ processed_files_set.add(rel)
223
+
224
+ current_files_count = len(processed_files_set)
225
+ if total_files_count > 0:
226
+ current_files_count = min(current_files_count, total_files_count)
227
+ progress.update(
228
+ scan_task,
229
+ advance=1,
230
+ file_progress=f"{current_files_count}/{total_files_count} files"
231
+ )
232
+
233
+ total_elapsed_overall = round(time.time() - start_overall_time, 2)
234
+
235
+ # Apply specific finding bypasses from .devsecignore if present
236
+ from .bypass import FindingBypassManager
237
+ bypass_mgr = FindingBypassManager(target_path)
238
+ results, bypassed_total = bypass_mgr.filter_tool_results(results)
239
+ if bypassed_total > 0:
240
+ console.print(f"[dim cyan][INFO] Suppressed {bypassed_total} finding(s) matching .devsecignore rules.[/dim cyan]")
241
+
242
+ # Reporting & Terminal Output
243
+ reporter = Reporter(console)
244
+ reporter.print_terminal_table(results)
245
+ reporter.print_findings_drilldown(results)
246
+ reporter.generate_markdown_summary(results, output_md)
247
+
248
+ telemetry_payload = {
249
+ "total_files": total_files_count,
250
+ "total_elapsed_seconds": total_elapsed_overall,
251
+ "total_engines": total_scanners
252
+ }
253
+ reporter.export_json_report(results, output_json, telemetry=telemetry_payload)
254
+
255
+ console.print(f"[dim]Exported Markdown summary to: {output_md.name}[/dim]")
256
+ console.print(f"[dim]Exported JSON report to: {output_json.name}[/dim]")
257
+ console.print(f"[bold cyan]Total Scan Time:[/bold cyan] [bold white]{total_elapsed_overall}s[/bold white] across [bold white]{total_files_count}[/bold white] files\n")
258
+
259
+ # Quality Gate evaluation
260
+ total_crit = sum(r.findings.critical for r in results)
261
+ total_high = sum(r.findings.high for r in results)
262
+ total_med = sum(r.findings.medium for r in results)
263
+ total_low = sum(r.findings.low for r in results)
264
+
265
+ # Notify user with actionable guidance if SonarQube was skipped
266
+ sonar_result = next((r for r in results if r.tool_name == "SonarQube"), None)
267
+ if sonar_result and sonar_result.status == StatusEnum.SKIPPED and "unreachable" in sonar_result.summary.lower():
268
+ console.print("[bold yellow]Tip: How to Enable SonarQube[/bold yellow]")
269
+ console.print(" SonarQube was skipped because no running SonarQube server was detected.")
270
+ console.print(" To enable SonarQube analysis:")
271
+ console.print(" 1. Start SonarQube: [cyan]docker run -d --name sonarqube -p 9000:9000 sonarqube:lts-community[/cyan]")
272
+ console.print(" 2. Open [link=http://localhost:9000]http://localhost:9000[/link] (Default login: [bold]admin[/bold] / [bold]admin[/bold])")
273
+ console.print(" 3. Generate Token: Go to [bold]User Icon (top-right) -> My Account -> Security -> Generate Token[/bold]")
274
+ console.print(" 4. Export variables in your terminal:")
275
+ console.print(" [cyan]export SONAR_HOST_URL=\"http://localhost:9000\"[/cyan]")
276
+ console.print(" [cyan]export SONAR_TOKEN=\"squ_your_token_here\"[/cyan]")
277
+ console.print(" [dim]Note: GitHub CodeQL is already active and performing deep-AST SAST analysis.[/dim]\n")
278
+
279
+ total_all_issues = total_crit + total_high + total_med + total_low
280
+
281
+ if total_all_issues > 0:
282
+ console.print("[bold cyan]Automated Remediation & Fix Suggestions:[/bold cyan]")
283
+ console.print(" Generate a recommended remediation patch to test locally before committing:")
284
+ console.print(" [bold white]devsec fix . --patch-output devsec-fix.patch[/bold white]")
285
+ console.print(" Inspect and test the patch locally (e.g. [dim]git apply --check devsec-fix.patch[/dim]).")
286
+ console.print(" Once verified in your local environment, commit and push the updates.")
287
+ console.print()
288
+ console.print("[bold yellow]False Positive or Accepted Risk Bypass:[/bold yellow]")
289
+ console.print(" To permanently suppress a specific finding without altering your global quality gate,")
290
+ console.print(" add the exact file and rule/CVE to [bold white].devsecignore[/bold white]:")
291
+ console.print(" [dim]echo \"Dockerfile:DL3008\" >> .devsecignore[/dim] # Suppress rule on specific file")
292
+ console.print(" [dim]echo \"CVE-2024-XXXX\" >> .devsecignore[/dim] # Suppress specific vulnerability")
293
+ console.print()
294
+
295
+ if (total_crit + total_high) > 0 or (strict and total_med > 0):
296
+ console.print(
297
+ f"[bold red][FAIL] Quality Gate FAILED[/bold red] "
298
+ f"([bold red]{total_crit} Critical[/bold red], [red]{total_high} High[/red], "
299
+ f"[yellow]{total_med} Med[/yellow], [blue]{total_low} Low[/blue] issues detected)!\n"
300
+ )
301
+ return 1
302
+ else:
303
+ console.print(
304
+ f"[bold green][PASS] Quality Gate PASSED[/bold green] "
305
+ f"(0 Critical, 0 High issues detected; [yellow]{total_med} Med[/yellow], [blue]{total_low} Low[/blue])!\n"
306
+ )
307
+ return 0
308
+
309
+ finally:
310
+ # Scrub temp cloned repository if applicable
311
+ if ingestion:
312
+ ingestion.cleanup()
313
+
314
+
315
+ def main():
316
+ parser = argparse.ArgumentParser(
317
+ prog="devsecpac",
318
+ description="devsecpac: Universal Autonomous DevSecOps Scanner Orchestrator"
319
+ )
320
+ subparsers = parser.add_subparsers(dest="command", help="Command to execute")
321
+
322
+ # scan command
323
+ scan_parser = subparsers.add_parser("scan", help="Run full security scan against target path or remote Git repo")
324
+ scan_parser.add_argument("target", nargs="?", default=None, help="Local target path to scan (use '.' for current folder)")
325
+ scan_parser.add_argument("-r", "--repo", help="Remote Git repository URL (HTTPS or SSH, e.g. https://github.com/org/repo.git)")
326
+ scan_parser.add_argument("-b", "--branch", help="Specific branch/tag to checkout for remote repository scan")
327
+ scan_parser.add_argument("--token", help="PAT / Token for private HTTPS repository ingestion")
328
+ scan_parser.add_argument("--keep-repo", action="store_true", help="Preserve cloned repository files after scan finishes")
329
+ scan_parser.add_argument("-t", "--tools", help="Comma-separated list of scanners to run (e.g. gitleaks,trivy,codeql)")
330
+ scan_parser.add_argument("-x", "--exclude", help="Comma-separated list of scanners to exclude/skip")
331
+ scan_parser.add_argument("--json", default="devsec-report.json", help="Path for JSON status report")
332
+ scan_parser.add_argument("--md", default="devsec-summary.md", help="Path for Markdown executive summary")
333
+ scan_parser.add_argument("--strict", action="store_true", help="Fail pipeline even on Medium severity issues")
334
+ scan_parser.add_argument("--install-missing", action="store_true", help="Automatically download and install missing tools before scanning")
335
+ scan_parser.add_argument("--defectdojo-push", action="store_true", help="Push consolidated findings to active DefectDojo instance")
336
+ scan_parser.add_argument("--defectdojo-url", default=os.environ.get("DEFECTDOJO_URL", "http://localhost:8080"), help="DefectDojo base URL")
337
+ scan_parser.add_argument("--defectdojo-key", default=os.environ.get("DEFECTDOJO_KEY", ""), help="DefectDojo API v2 Key")
338
+ scan_parser.add_argument("--defectdojo-engagement", type=int, default=int(os.environ.get("DEFECTDOJO_ENGAGEMENT_ID", "1")), help="Target DefectDojo Engagement ID")
339
+
340
+ # info command
341
+ subparsers.add_parser("info", help="Show environment tool discovery status")
342
+
343
+ # setup command
344
+ subparsers.add_parser("setup", help="Auto-download and configure missing DevSecOps tools into user bin")
345
+
346
+ # fix command
347
+ fix_parser = subparsers.add_parser("fix", help="Generate recommended remediation patch for detected issues")
348
+ fix_parser.add_argument("target", nargs="?", default=".", help="Local target path to fix (default: .)")
349
+ fix_parser.add_argument("--patch-output", default="devsec-fix.patch", help="Path for output unified git patch file")
350
+
351
+ # pr-comment command
352
+ pr_parser = subparsers.add_parser("pr-comment", help="Generate or post interactive GitHub PR comment from scan results")
353
+ pr_parser.add_argument("--json", default="devsec-report.json", help="Path of existing scan JSON report")
354
+ pr_parser.add_argument("--output", default="devsec-pr-comment.md", help="Path to write PR markdown comment")
355
+
356
+ args = parser.parse_args()
357
+
358
+ if args.command == "info":
359
+ run_info()
360
+ sys.exit(0)
361
+ elif args.command == "setup":
362
+ run_setup()
363
+ sys.exit(0)
364
+ elif args.command == "pr-comment":
365
+ from .ci import CICDIntegrator
366
+ report_file = Path(args.json)
367
+ if not report_file.exists():
368
+ console.print(f"[bold red][ERROR] Report file not found: {report_file}[/bold red]")
369
+ sys.exit(1)
370
+ results = CICDIntegrator.load_results_from_json(report_file)
371
+ comment_md = CICDIntegrator.generate_pr_comment(results)
372
+ out_path = Path(args.output)
373
+ out_path.write_text(comment_md, encoding="utf-8")
374
+ console.print(f"[bold green][OK][/bold green] Generated PR Markdown comment at: [bold cyan]{out_path}[/bold cyan]")
375
+ sys.exit(0)
376
+ elif args.command == "fix":
377
+ from .remediation import RemediationEngine
378
+ target = Path(args.target).resolve()
379
+ engine = RemediationEngine(target)
380
+ patch_file = Path(args.patch_output)
381
+ engine.generate_remediation_patch([], patch_file)
382
+ sys.exit(0)
383
+ elif args.command == "scan":
384
+ # Target must be explicitly '.' or a specific local directory, OR -r/--repo must be provided
385
+ if not args.repo and args.target is None:
386
+ console.print("[bold red][ERROR] Target not specified.[/bold red]")
387
+ console.print("Please provide a target directory (use [bold cyan].[/bold cyan] for current folder) or [bold cyan]-r / --repo <url>[/bold cyan] for a remote Git repository.\n")
388
+ scan_parser.print_help()
389
+ sys.exit(1)
390
+
391
+ target = Path(args.target).resolve() if args.target else Path(".").resolve()
392
+ code = run_scan(
393
+ target_path=target,
394
+ output_json=Path(args.json),
395
+ output_md=Path(args.md),
396
+ strict=args.strict,
397
+ install_missing=args.install_missing,
398
+ repo_url=args.repo,
399
+ branch=args.branch,
400
+ token=args.token,
401
+ keep_repo=args.keep_repo,
402
+ tools=args.tools,
403
+ exclude=args.exclude
404
+ )
405
+
406
+ if args.defectdojo_push or os.environ.get("DEFECTDOJO_PUSH"):
407
+ from .ci import CICDIntegrator
408
+ dojo_key = args.defectdojo_key or os.environ.get("DEFECTDOJO_KEY", "")
409
+ if not dojo_key:
410
+ console.print("[yellow][WARN] DefectDojo push skipped: API key not provided (pass --defectdojo-key or export DEFECTDOJO_KEY)[/yellow]")
411
+ else:
412
+ console.print(f"Pushed to DefectDojo engagement #{args.defectdojo_engagement} at {args.defectdojo_url}...", end=" ")
413
+ pushed = CICDIntegrator.push_to_defectdojo(
414
+ json_report_path=Path(args.json),
415
+ dojo_url=args.defectdojo_url,
416
+ api_key=dojo_key,
417
+ engagement_id=args.defectdojo_engagement
418
+ )
419
+ if pushed:
420
+ console.print("[bold green][OK][/bold green]")
421
+ else:
422
+ console.print("[bold red][FAILED][/bold red]")
423
+
424
+ sys.exit(code)
425
+ else:
426
+ parser.print_help()
427
+ sys.exit(0)
428
+
429
+
430
+ if __name__ == "__main__":
431
+ main()
@@ -0,0 +1,67 @@
1
+ """Standardized Execution Contract and Status Schema."""
2
+
3
+ from dataclasses import dataclass, field, asdict
4
+ from enum import Enum
5
+ from typing import Dict, Any, List, Optional
6
+ import json
7
+
8
+
9
+ class StatusEnum(str, Enum):
10
+ PASS = "PASS"
11
+ FAIL = "FAIL"
12
+ NOT_APPLICABLE = "NOT_APPLICABLE"
13
+ SKIPPED = "SKIPPED"
14
+ ERROR = "ERROR"
15
+
16
+
17
+ @dataclass
18
+ class FindingCounts:
19
+ critical: int = 0
20
+ high: int = 0
21
+ medium: int = 0
22
+ low: int = 0
23
+ info: int = 0
24
+
25
+ @property
26
+ def total(self) -> int:
27
+ return self.critical + self.high + self.medium + self.low + self.info
28
+
29
+ @property
30
+ def has_blocking(self) -> bool:
31
+ """Determines if there are blocking issues (Critical or High)."""
32
+ return (self.critical + self.high) > 0
33
+
34
+
35
+ @dataclass
36
+ class FindingDetail:
37
+ severity: str # CRITICAL, HIGH, MEDIUM, LOW, INFO
38
+ tool: str # Scanner name
39
+ file: str # File where issue was found
40
+ line: Optional[str] = "" # Line number or range
41
+ rule: str = "" # Rule ID / CVE ID
42
+ description: str = "" # Brief issue description
43
+
44
+
45
+ @dataclass
46
+ class ToolResult:
47
+ tool_name: str
48
+ category: str
49
+ status: StatusEnum
50
+ exit_code: int = 0
51
+ summary: str = ""
52
+ findings: FindingCounts = field(default_factory=FindingCounts)
53
+ duration_seconds: float = 0.0
54
+ files_scanned: int = 0
55
+ file_timings: Dict[str, float] = field(default_factory=dict)
56
+ items: List[FindingDetail] = field(default_factory=list)
57
+ details: Dict[str, Any] = field(default_factory=dict)
58
+
59
+ def to_dict(self) -> Dict[str, Any]:
60
+ data = asdict(self)
61
+ data["status"] = self.status.value
62
+ data["findings"] = asdict(self.findings)
63
+ data["items"] = [asdict(item) for item in self.items]
64
+ return data
65
+
66
+ def to_json(self, indent: int = 2) -> str:
67
+ return json.dumps(self.to_dict(), indent=indent)
@@ -0,0 +1,110 @@
1
+ """Unified Finding Deduplication and Cross-Engine Correlation Engine for DevSecPac v2.0."""
2
+
3
+ import re
4
+ from typing import List, Dict, Tuple, Set
5
+ from .contracts import ToolResult, FindingDetail, FindingCounts, StatusEnum
6
+
7
+
8
+ class FindingCorrelator:
9
+ """Normalizes and deduplicates findings across different security scanners.
10
+
11
+ Examples:
12
+ - Correlates CVE-2024-XXXX and GHSA-YYYY between Trivy and Dependency-Check
13
+ - Correlates leaked secret matches between Gitleaks and TruffleHog on the same file/line
14
+ - Consolidates AST issues between CodeQL and SonarQube
15
+ """
16
+
17
+ @staticmethod
18
+ def extract_cve(rule_str: str, desc_str: str) -> List[str]:
19
+ """Extracts standard CVE identifiers (e.g. CVE-2024-12345) from strings."""
20
+ combined = f"{rule_str} {desc_str}".upper()
21
+ matches = re.findall(r"CVE-\d{4}-\d{4,7}", combined)
22
+ return list(set(matches))
23
+
24
+ @staticmethod
25
+ def extract_ghsa(rule_str: str, desc_str: str) -> List[str]:
26
+ """Extracts standard GitHub Advisory IDs (e.g. GHSA-xxxx-xxxx-xxxx)."""
27
+ combined = f"{rule_str} {desc_str}"
28
+ matches = re.findall(r"GHSA-[2-9a-z]{4}-[2-9a-z]{4}-[2-9a-z]{4}", combined, re.IGNORECASE)
29
+ return list(set(m.upper() for m in matches))
30
+
31
+ @classmethod
32
+ def deduplicate_findings(cls, results: List[ToolResult]) -> Tuple[List[FindingDetail], Dict[str, any]]:
33
+ """Deduplicates and correlates findings across all tool results.
34
+
35
+ Returns:
36
+ Tuple of (deduplicated_findings: List[FindingDetail], stats: Dict)
37
+ """
38
+ raw_items: List[FindingDetail] = []
39
+ for r in results:
40
+ raw_items.extend(r.items)
41
+
42
+ if not raw_items:
43
+ return [], {"total_raw": 0, "total_unique": 0, "duplicates_removed": 0}
44
+
45
+ seen_keys: Dict[str, FindingDetail] = {}
46
+ cve_index: Dict[Tuple[str, str], FindingDetail] = {} # (file, CVE) -> canonical item
47
+ secret_index: Dict[Tuple[str, str], FindingDetail] = {} # (file, line) -> secret item
48
+
49
+ for item in raw_items:
50
+ norm_file = item.file.strip().replace("\\", "/").lower()
51
+ norm_line = str(item.line or "").strip()
52
+ norm_rule = item.rule.strip().upper()
53
+
54
+ # 1. Check for CVE / GHSA correlation in SCA findings
55
+ cves = cls.extract_cve(item.rule, item.description)
56
+ ghsas = cls.extract_ghsa(item.rule, item.description)
57
+
58
+ correlated = False
59
+
60
+ if cves or ghsas:
61
+ for cve in (cves or ghsas):
62
+ cve_key = (norm_file, cve)
63
+ if cve_key in cve_index:
64
+ # Existing finding found - append reporting tool if not already present
65
+ canonical = cve_index[cve_key]
66
+ if item.tool not in canonical.tool:
67
+ canonical.tool = f"{canonical.tool}, {item.tool}"
68
+ correlated = True
69
+ break
70
+ else:
71
+ cve_index[cve_key] = item
72
+
73
+ # 2. Check for Secret correlation (same file and line)
74
+ if not correlated and item.tool.lower() in ("gitleaks", "trufflehog"):
75
+ sec_key = (norm_file, norm_line)
76
+ if norm_line and sec_key in secret_index:
77
+ canonical = secret_index[sec_key]
78
+ if item.tool not in canonical.tool:
79
+ canonical.tool = f"{canonical.tool}, {item.tool}"
80
+ correlated = True
81
+ elif norm_line:
82
+ secret_index[sec_key] = item
83
+
84
+ if correlated:
85
+ continue
86
+
87
+ # 3. Standard deduplication by (file, line, rule, severity)
88
+ exact_key = f"{norm_file}::{norm_line}::{norm_rule}::{item.severity.upper()}"
89
+ if exact_key in seen_keys:
90
+ canonical = seen_keys[exact_key]
91
+ if item.tool not in canonical.tool:
92
+ canonical.tool = f"{canonical.tool}, {item.tool}"
93
+ else:
94
+ seen_keys[exact_key] = item
95
+
96
+ # Combine all unique items
97
+ all_unique: Set[int] = set()
98
+ deduped: List[FindingDetail] = []
99
+
100
+ for item in list(cve_index.values()) + list(secret_index.values()) + list(seen_keys.values()):
101
+ if id(item) not in all_unique:
102
+ all_unique.add(id(item))
103
+ deduped.append(item)
104
+
105
+ stats = {
106
+ "total_raw": len(raw_items),
107
+ "total_unique": len(deduped),
108
+ "duplicates_removed": len(raw_items) - len(deduped)
109
+ }
110
+ return deduped, stats