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/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """devsec-cli: Universal Autonomous DevSecOps Scanner Orchestrator."""
2
+
3
+ __version__ = "0.1.0"
4
+ __author__ = "Fahad Shaikh"
devsec_cli/bypass.py ADDED
@@ -0,0 +1,98 @@
1
+ """Finding bypass and suppression mechanism (.devsecignore)."""
2
+
3
+ from pathlib import Path
4
+ from typing import List, Set, Tuple
5
+ from .contracts import FindingDetail, ToolResult, FindingCounts, StatusEnum
6
+
7
+
8
+ class FindingBypassManager:
9
+ """Loads and checks rule or file-level bypass definitions from .devsecignore or .devsec-suppress."""
10
+
11
+ def __init__(self, target_dir: Path):
12
+ self.target_dir = target_dir
13
+ self.ignore_rules: Set[str] = set()
14
+ self.ignore_file_rules: Set[Tuple[str, str]] = set() # (normalized_path, rule_id)
15
+ self.ignore_cves: Set[str] = set()
16
+ self._load_ignore_file()
17
+
18
+ def _load_ignore_file(self):
19
+ """Looks for .devsecignore or .devsec-suppress in repository root."""
20
+ possible_files = [
21
+ self.target_dir / ".devsecignore",
22
+ self.target_dir / ".devsec-suppress"
23
+ ]
24
+
25
+ for pf in possible_files:
26
+ if pf.is_file():
27
+ try:
28
+ for line in pf.read_text(encoding="utf-8").splitlines():
29
+ line = line.strip()
30
+ if not line or line.startswith("#"):
31
+ continue
32
+
33
+ # Format 1: file:rule (e.g. Dockerfile:DL3008 or requirements.txt:CVE-2024-1234)
34
+ if ":" in line:
35
+ parts = line.split(":", 1)
36
+ fpath_norm = parts[0].strip().replace("\\", "/").lower()
37
+ rule_norm = parts[1].strip().upper()
38
+ self.ignore_file_rules.add((fpath_norm, rule_norm))
39
+ # Format 2: standalone rule/CVE (e.g. DL3008, CK_DOCKER_3, CVE-2024-21626)
40
+ elif line.upper().startswith("CVE-") or line.upper().startswith("GHSA-"):
41
+ self.ignore_cves.add(line.upper())
42
+ else:
43
+ self.ignore_rules.add(line.upper())
44
+ except Exception:
45
+ pass
46
+
47
+ def is_bypassed(self, finding: FindingDetail) -> bool:
48
+ """Determines if a finding is suppressed by a specific bypass rule."""
49
+ if not self.ignore_rules and not self.ignore_file_rules and not self.ignore_cves:
50
+ return False
51
+
52
+ norm_file = finding.file.strip().replace("\\", "/").lower()
53
+ rule_upper = (finding.rule or "").strip().upper()
54
+
55
+ # Check global rule match
56
+ if rule_upper in self.ignore_rules:
57
+ return True
58
+
59
+ # Check file + rule match
60
+ for fpath, r in self.ignore_file_rules:
61
+ if (fpath in norm_file or norm_file.endswith(fpath)) and r == rule_upper:
62
+ return True
63
+
64
+ # Check CVE match
65
+ if rule_upper in self.ignore_cves:
66
+ return True
67
+
68
+ return False
69
+
70
+ def filter_tool_results(self, results: List[ToolResult]) -> Tuple[List[ToolResult], int]:
71
+ """Filters out bypassed findings from each ToolResult and recalculates finding counts."""
72
+ bypassed_count = 0
73
+
74
+ for r in results:
75
+ if not r.items:
76
+ continue
77
+
78
+ active_items = []
79
+ for item in r.items:
80
+ if self.is_bypassed(item):
81
+ bypassed_count += 1
82
+ else:
83
+ active_items.append(item)
84
+
85
+ r.items = active_items
86
+
87
+ # Recount findings for this tool
88
+ r.findings.critical = sum(1 for i in active_items if i.severity.upper() == "CRITICAL")
89
+ r.findings.high = sum(1 for i in active_items if i.severity.upper() == "HIGH")
90
+ r.findings.medium = sum(1 for i in active_items if i.severity.upper() == "MEDIUM")
91
+ r.findings.low = sum(1 for i in active_items if i.severity.upper() == "LOW")
92
+ r.findings.info = sum(1 for i in active_items if i.severity.upper() == "INFO")
93
+
94
+ # Adjust status if quality gate failed purely due to suppressed items
95
+ if r.status == StatusEnum.FAIL and not r.findings.has_blocking:
96
+ r.status = StatusEnum.PASS
97
+
98
+ return results, bypassed_count
devsec_cli/ci.py ADDED
@@ -0,0 +1,163 @@
1
+ """CI/CD Pull Request Commenter and DefectDojo ASPM Exporter for DevSecPac v2.0."""
2
+
3
+ from pathlib import Path
4
+ from typing import List, Dict
5
+ import json
6
+ import os
7
+ import requests
8
+ from rich.console import Console
9
+ from .contracts import ToolResult, FindingDetail, FindingCounts, StatusEnum
10
+ from .correlator import FindingCorrelator
11
+
12
+ console = Console()
13
+
14
+
15
+ class CICDIntegrator:
16
+ """Provides GitHub Actions / GitLab CI PR commenting and DefectDojo push integrations."""
17
+
18
+ @classmethod
19
+ def load_results_from_json(cls, json_path: Path) -> List[ToolResult]:
20
+ """Loads and reconstructs ToolResult objects from devsec-report.json."""
21
+ with open(json_path, "r", encoding="utf-8") as f:
22
+ data = json.load(f)
23
+
24
+ results: List[ToolResult] = []
25
+ raw_results = data.get("results", [])
26
+ for item in raw_results:
27
+ findings_data = item.get("findings", {})
28
+ fc = FindingCounts(
29
+ critical=findings_data.get("critical", 0),
30
+ high=findings_data.get("high", 0),
31
+ medium=findings_data.get("medium", 0),
32
+ low=findings_data.get("low", 0),
33
+ info=findings_data.get("info", 0)
34
+ )
35
+ raw_items = item.get("items", [])
36
+ detail_items = [
37
+ FindingDetail(
38
+ severity=d.get("severity", "MEDIUM"),
39
+ tool=d.get("tool", item.get("tool_name", "")),
40
+ file=d.get("file", ""),
41
+ line=str(d.get("line", "")),
42
+ rule=d.get("rule", ""),
43
+ description=d.get("description", "")
44
+ )
45
+ for d in raw_items
46
+ ]
47
+ res = ToolResult(
48
+ tool_name=item.get("tool_name", ""),
49
+ category=item.get("category", ""),
50
+ status=StatusEnum(item.get("status", "PASS")),
51
+ exit_code=item.get("exit_code", 0),
52
+ summary=item.get("summary", ""),
53
+ findings=fc,
54
+ duration_seconds=float(item.get("duration_seconds", 0.0)),
55
+ items=detail_items,
56
+ details=item.get("details", {})
57
+ )
58
+ results.append(res)
59
+ return results
60
+
61
+ @staticmethod
62
+ def generate_pr_comment(results: List[ToolResult]) -> str:
63
+ """Generates GitHub-flavored interactive collapsible PR comment Markdown."""
64
+ deduped, stats = FindingCorrelator.deduplicate_findings(results)
65
+
66
+ total_crit = sum(r.findings.critical for r in results)
67
+ total_high = sum(r.findings.high for r in results)
68
+ total_med = sum(r.findings.medium for r in results)
69
+ total_low = sum(r.findings.low for r in results)
70
+
71
+ gate_status = "PASSED" if (total_crit + total_high) == 0 else "FAILED"
72
+ badge_color = "brightgreen" if gate_status == "PASSED" else "red"
73
+
74
+ lines = [
75
+ f"## ![DevSecOps Gate](https://img.shields.io/badge/Security_Gate-{gate_status}-{badge_color}) Autonomous Pipeline Report",
76
+ "",
77
+ f"**Findings Summary**: {total_crit} Critical | {total_high} High | {total_med} Medium | {total_low} Low",
78
+ f"*(Auto-Deduplication: {stats['duplicates_removed']} duplicate alerts consolidated)*" if stats['duplicates_removed'] > 0 else "",
79
+ "",
80
+ "<details><summary><b>View Scanner Tool Execution Matrix</b></summary>",
81
+ "",
82
+ "| Scanner | Category | Status | Time | Summary |",
83
+ "|:---|:---|:---:|:---:|:---|"
84
+ ]
85
+
86
+ for r in results:
87
+ lines.append(f"| **{r.tool_name}** | {r.category} | `{r.status.value}` | {r.duration_seconds}s | {r.summary} |")
88
+
89
+ lines.extend([
90
+ "",
91
+ "</details>",
92
+ "",
93
+ "### Critical & High Priority Action Items",
94
+ ""
95
+ ])
96
+
97
+ blocking = [i for i in deduped if i.severity.upper() in ("CRITICAL", "HIGH")]
98
+ if not blocking:
99
+ lines.append("> [!NOTE]\n> No Critical or High vulnerabilities detected. Pipeline approved to merge.")
100
+ else:
101
+ lines.append("| Severity | Tool | Location | Rule / CVE | Description |")
102
+ lines.append("|:---:|:---|:---|:---|:---|")
103
+ for item in blocking[:25]:
104
+ loc = f"`{item.file}:{item.line}`" if item.line else f"`{item.file}`"
105
+ lines.append(f"| **{item.severity}** | {item.tool} | {loc} | `{item.rule}` | {item.description} |")
106
+
107
+ lines.append("\n---\n*Report generated autonomously by [devsecpac v2](https://github.com/iamfahadshaikh)*")
108
+ return "\n".join(lines)
109
+
110
+ @classmethod
111
+ def push_to_defectdojo(cls, json_report_path: Path, dojo_url: str, api_key: str, engagement_id: int) -> bool:
112
+ """Transforms unified devsec-report.json into DefectDojo Generic Findings format and pushes it."""
113
+ if not json_report_path.exists():
114
+ return False
115
+
116
+ try:
117
+ results = cls.load_results_from_json(json_report_path)
118
+ deduped, _ = FindingCorrelator.deduplicate_findings(results)
119
+
120
+ dojo_findings = []
121
+ for item in deduped:
122
+ sev = item.severity.capitalize() # Critical, High, Medium, Low, Info
123
+ if sev not in ("Critical", "High", "Medium", "Low", "Info"):
124
+ sev = "Medium"
125
+
126
+ finding_obj = {
127
+ "title": f"[{item.tool}] {item.rule or item.description[:50]}",
128
+ "severity": sev,
129
+ "description": f"Tool: {item.tool}\nRule/CVE: {item.rule}\nFile: {item.file}:{item.line}\n\n{item.description}",
130
+ "file_path": item.file,
131
+ "active": True,
132
+ "verified": True
133
+ }
134
+ if item.line and item.line.isdigit():
135
+ finding_obj["line"] = int(item.line)
136
+ if item.rule and (item.rule.startswith("CVE-") or item.rule.startswith("GHSA-")):
137
+ finding_obj["vulnerability_ids"] = [item.rule]
138
+
139
+ dojo_findings.append(finding_obj)
140
+
141
+ payload = {
142
+ "name": "DevSecPac Unified Scan",
143
+ "findings": dojo_findings
144
+ }
145
+
146
+ url = f"{dojo_url.rstrip('/')}/api/v2/import-scan/"
147
+ headers = {
148
+ "Authorization": f"Token {api_key}"
149
+ }
150
+ files = {
151
+ "file": ("devsec-dojo.json", json.dumps(payload), "application/json")
152
+ }
153
+ data = {
154
+ "scan_type": "Generic Findings Import",
155
+ "engagement": str(engagement_id),
156
+ "active": "true",
157
+ "verified": "true"
158
+ }
159
+ resp = requests.post(url, headers=headers, files=files, data=data, timeout=45)
160
+ return resp.status_code in (200, 201)
161
+ except Exception as e:
162
+ console.print(f"[bold red][FAIL][/bold red] DefectDojo push error: {str(e)}")
163
+ return False