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.
@@ -0,0 +1,322 @@
1
+ """SonarQube SAST and Quality Gate Scanner."""
2
+
3
+ from pathlib import Path
4
+ import os
5
+ import json
6
+ import time
7
+ import requests
8
+ import base64
9
+ from rich.prompt import Confirm
10
+ from rich.console import Console
11
+ from .base import BaseScanner
12
+ from ..contracts import ToolResult, StatusEnum, FindingCounts, FindingDetail
13
+ from ..runner import ProcessRunner
14
+ from ..discovery import TargetDiscovery
15
+
16
+ console = Console()
17
+
18
+
19
+ class SonarQubeScanner(BaseScanner):
20
+ def __init__(self):
21
+ super().__init__(name="SonarQube", category="Code Quality & SAST", binary_name="sonar-scanner")
22
+
23
+ def _save_cached_token(self, token: str):
24
+ """Caches auto-generated token to ~/.devsec/sonar_token for future scans."""
25
+ try:
26
+ cache_file = Path.home() / ".devsec" / "sonar_token"
27
+ cache_file.parent.mkdir(parents=True, exist_ok=True)
28
+ cache_file.write_text(token.strip(), encoding="utf-8")
29
+ except Exception:
30
+ pass
31
+
32
+ def _resolve_token(self) -> str:
33
+ """Finds SonarQube token from environment, devsec cache, or global sonar-scanner.properties config."""
34
+ token = os.environ.get("SONAR_TOKEN", "")
35
+ if token:
36
+ return token
37
+
38
+ # Check ~/.devsec/sonar_token cache
39
+ cache_file = Path.home() / ".devsec" / "sonar_token"
40
+ if cache_file.exists():
41
+ try:
42
+ cached = cache_file.read_text(encoding="utf-8").strip()
43
+ if cached:
44
+ return cached
45
+ except Exception:
46
+ pass
47
+
48
+ # Check ~/.local/bin/sonar-scanner-*/conf/sonar-scanner.properties or /etc
49
+ search_paths = [
50
+ Path.home() / ".local" / "bin",
51
+ Path.home() / ".local" / "opt"
52
+ ]
53
+ for base in search_paths:
54
+ for conf in base.glob("**/conf/sonar-scanner.properties"):
55
+ try:
56
+ for line in conf.read_text(encoding="utf-8").splitlines():
57
+ line = line.strip()
58
+ if line.startswith("sonar.token=") or line.startswith("sonar.login="):
59
+ return line.split("=", 1)[1].strip()
60
+ except Exception:
61
+ pass
62
+ return ""
63
+
64
+ def _fetch_sonar_issues(self, sonar_host: str, sonar_token: str, project_key: str):
65
+ """Fetches active security vulnerabilities and hotspots directly from SonarQube REST API."""
66
+ findings = FindingCounts()
67
+ items = []
68
+
69
+ try:
70
+ url = f"{sonar_host.rstrip('/')}/api/issues/search"
71
+ params = {"componentKeys": project_key, "ps": "100"}
72
+ auth = (sonar_token, "") if sonar_token else None
73
+ resp = requests.get(url, params=params, auth=auth, timeout=10)
74
+ if resp.status_code == 200:
75
+ data = resp.json()
76
+ issues = data.get("issues", [])
77
+
78
+ for issue in issues:
79
+ # Ignore resolved or closed issues
80
+ if issue.get("status") == "CLOSED" or issue.get("resolution"):
81
+ continue
82
+
83
+ # Filter for Security vulnerabilities, hotspots, or bugs
84
+ issue_type = issue.get("type", "")
85
+ severity = str(issue.get("severity", "INFO")).upper()
86
+ impacts = issue.get("impacts", [])
87
+ # Check if impact is security
88
+ is_security = issue_type in ("VULNERABILITY", "SECURITY_HOTSPOT", "BUG") or any(
89
+ imp.get("softwareQuality") == "SECURITY" for imp in impacts
90
+ )
91
+
92
+ if not is_security:
93
+ continue
94
+
95
+ sev_level = "LOW"
96
+ if severity in ("BLOCKER", "CRITICAL"):
97
+ findings.critical += 1
98
+ sev_level = "CRITICAL"
99
+ elif severity == "MAJOR":
100
+ findings.high += 1
101
+ sev_level = "HIGH"
102
+ elif severity == "MINOR":
103
+ findings.medium += 1
104
+ sev_level = "MEDIUM"
105
+ else:
106
+ findings.low += 1
107
+ sev_level = "LOW"
108
+
109
+ raw_component = issue.get("component", "")
110
+ clean_file = raw_component.replace(f"{project_key}:", "")
111
+ line_num = str(issue.get("line", issue.get("textRange", {}).get("startLine", "")))
112
+
113
+ items.append(
114
+ FindingDetail(
115
+ severity=sev_level,
116
+ tool=self.name,
117
+ file=clean_file,
118
+ line=line_num,
119
+ rule=issue.get("rule", "SonarRule"),
120
+ description=issue.get("message", "SonarQube issue detected")
121
+ )
122
+ )
123
+ except Exception:
124
+ pass
125
+
126
+ return findings, items
127
+
128
+ def _check_server_reachable(self, sonar_host: str) -> bool:
129
+ """Checks if SonarQube server is reachable and active."""
130
+ try:
131
+ resp = requests.get(f"{sonar_host.rstrip('/')}/api/system/status", timeout=3)
132
+ if resp.status_code == 200:
133
+ data = resp.json()
134
+ return data.get("status") == "UP"
135
+ return False
136
+ except Exception:
137
+ return False
138
+
139
+ def _auto_generate_token(self, sonar_host: str) -> str:
140
+ """Attempts to auto-generate a devsec-cli token using default admin:admin."""
141
+ try:
142
+ url = f"{sonar_host.rstrip('/')}/api/user_tokens/generate"
143
+ data = {"name": f"devsec-cli-{int(time.time())}"}
144
+ resp = requests.post(url, data=data, auth=("admin", "admin"), timeout=5)
145
+ if resp.status_code == 200:
146
+ return resp.json().get("token", "")
147
+ return ""
148
+ except Exception:
149
+ return ""
150
+
151
+ def _prompt_start_sonarqube(self, sonar_host: str) -> str:
152
+ """Prompts user if they want to start a local SonarQube container automatically."""
153
+ import sys
154
+ if not sys.stdin.isatty():
155
+ return ""
156
+
157
+ docker_bin = ProcessRunner.find_binary("docker")
158
+ if not docker_bin:
159
+ return ""
160
+
161
+ console.print("\n[bold yellow]SonarQube server is not reachable.[/bold yellow]")
162
+ if not Confirm.ask("Would you like devsec to launch a SonarQube container via Docker?"):
163
+ return ""
164
+
165
+ # Check if container named 'sonarqube' already exists
166
+ code, stdout, _, _ = ProcessRunner.run_command([docker_bin, "ps", "-a", "--filter", "name=sonarqube", "--format", "{{.Names}}"])
167
+ if "sonarqube" in stdout:
168
+ console.print(" * Starting existing [bold cyan]sonarqube[/bold cyan] container...")
169
+ ProcessRunner.run_command([docker_bin, "start", "sonarqube"])
170
+ else:
171
+ console.print(" * Pulling and starting [bold cyan]sonarqube:lts-community[/bold cyan] on port 9000...")
172
+ ProcessRunner.run_command([
173
+ docker_bin, "run", "-d", "--name", "sonarqube",
174
+ "-p", "9000:9000", "sonarqube:lts-community"
175
+ ])
176
+
177
+ # Wait for SonarQube to be UP
178
+ with console.status("[bold blue]Waiting for SonarQube server to become ready (this may take up to 45s)...[/bold blue]"):
179
+ for _ in range(60):
180
+ if self._check_server_reachable(sonar_host):
181
+ break
182
+ time.sleep(2)
183
+
184
+ # Attempt auto-generating token
185
+ token = self._auto_generate_token(sonar_host)
186
+ if token:
187
+ self._save_cached_token(token)
188
+ console.print(f" * [bold green][OK][/bold green] Generated analysis token: [dim]{token[:12]}...[/dim]")
189
+ return token
190
+
191
+ def scan(self, target_dir: Path) -> ToolResult:
192
+ discovery = TargetDiscovery(target_dir)
193
+ languages = discovery.detect_languages()
194
+
195
+ if not languages:
196
+ return self.create_not_applicable_result("No application source files detected")
197
+
198
+ if not self.is_tool_available():
199
+ return self.create_skipped_result("sonar-scanner binary not found in PATH")
200
+
201
+ sonar_host = os.environ.get("SONAR_HOST_URL", "http://localhost:9000")
202
+ sonar_token = self._resolve_token()
203
+
204
+ # If not reachable and no token, prompt user to start it or auto-connect
205
+ if not self._check_server_reachable(sonar_host):
206
+ new_token = self._prompt_start_sonarqube(sonar_host)
207
+ if new_token:
208
+ sonar_token = new_token
209
+ elif not self._check_server_reachable(sonar_host):
210
+ return self.create_skipped_result("SonarQube server unreachable (export SONAR_HOST_URL & SONAR_TOKEN)")
211
+
212
+ # When new container was created, old conf properties has old token that fails
213
+ # Verify token by testing /api/authentication/validate
214
+ if sonar_token:
215
+ try:
216
+ val_resp = requests.get(
217
+ f"{sonar_host.rstrip('/')}/api/authentication/validate",
218
+ auth=(sonar_token, ""),
219
+ timeout=3
220
+ )
221
+ if val_resp.status_code == 200:
222
+ val_data = val_resp.json()
223
+ if not val_data.get("valid"):
224
+ sonar_token = ""
225
+ else:
226
+ sonar_token = ""
227
+ except Exception:
228
+ sonar_token = ""
229
+
230
+ # If server is reachable but token is missing or invalid, generate fresh token from live container
231
+ if not sonar_token and self._check_server_reachable(sonar_host):
232
+ sonar_token = self._auto_generate_token(sonar_host)
233
+ if sonar_token:
234
+ self._save_cached_token(sonar_token)
235
+
236
+ # Unique project key for remote/local repositories to avoid cross-repo project collisions
237
+ project_key = target_dir.name
238
+ if project_key in ("repo", "target") and target_dir.parent:
239
+ project_key = f"{target_dir.parent.name}_{target_dir.name}"
240
+
241
+ cmd = [
242
+ str(self.binary_path),
243
+ f"-Dsonar.projectKey={project_key}",
244
+ f"-Dsonar.sources={target_dir}",
245
+ f"-Dsonar.host.url={sonar_host}"
246
+ ]
247
+
248
+ # Auto-configure sonar.java.binaries for Java / Android projects
249
+ if "java" in languages:
250
+ # Look for existing build directories (target/classes, build/classes, app/build)
251
+ possible_bins = []
252
+ for candidate in ("target/classes", "build/classes", "app/build/intermediates/javac", "bin"):
253
+ cand_path = target_dir / candidate
254
+ if cand_path.is_dir():
255
+ possible_bins.append(str(cand_path))
256
+
257
+ if possible_bins:
258
+ cmd.append(f"-Dsonar.java.binaries={','.join(possible_bins)}")
259
+ else:
260
+ # If uncompiled, point to project root or empty placeholder so SonarQube still analyzes raw source AST
261
+ fallback_bin = target_dir / ".sonar_binaries"
262
+ fallback_bin.mkdir(exist_ok=True)
263
+ cmd.append(f"-Dsonar.java.binaries={fallback_bin}")
264
+
265
+ # SonarQube token supports both -Dsonar.token and -Dsonar.login
266
+ if sonar_token:
267
+ cmd.extend([f"-Dsonar.token={sonar_token}", f"-Dsonar.login={sonar_token}"])
268
+
269
+ code, stdout, stderr, elapsed = ProcessRunner.run_command(cmd, cwd=str(target_dir), timeout=600)
270
+
271
+ # Cleanup fallback binaries directory if created
272
+ fallback_bin = target_dir / ".sonar_binaries"
273
+ if fallback_bin.exists():
274
+ try:
275
+ fallback_bin.rmdir()
276
+ except Exception:
277
+ pass
278
+
279
+ if code != 0:
280
+ return self.create_skipped_result("SonarQube analysis failed")
281
+
282
+ # Wait briefly for SonarQube background Compute Engine processing to finalize issue indexing
283
+ ce_url = f"{sonar_host.rstrip('/')}/api/ce/activity"
284
+ auth = (sonar_token, "") if sonar_token else None
285
+ for _ in range(10):
286
+ try:
287
+ ce_resp = requests.get(ce_url, params={"component": project_key}, auth=auth, timeout=3)
288
+ if ce_resp.status_code == 200:
289
+ tasks = ce_resp.json().get("tasks", [])
290
+ if tasks and tasks[0].get("status") in ("SUCCESS", "FAILED"):
291
+ break
292
+ except Exception:
293
+ pass
294
+ time.sleep(1)
295
+
296
+ # Query REST API for detailed findings
297
+ findings, items = self._fetch_sonar_issues(sonar_host, sonar_token, project_key)
298
+
299
+ # Check for Quality Gate failure in CLI output
300
+ output_combined = stdout + stderr
301
+ qg_failed = "QUALITY GATE STATUS: FAILED" in output_combined
302
+
303
+ if qg_failed or (findings.critical + findings.high) > 0:
304
+ status = StatusEnum.FAIL
305
+ summary = f"SonarQube detected {findings.critical} Critical, {findings.high} High issue(s)"
306
+ elif (findings.medium + findings.low) > 0:
307
+ status = StatusEnum.PASS
308
+ summary = f"SonarQube detected {findings.medium + findings.low} non-blocking issue(s)"
309
+ else:
310
+ status = StatusEnum.PASS
311
+ summary = "SonarQube analysis passed"
312
+
313
+ return ToolResult(
314
+ tool_name=self.name,
315
+ category=self.category,
316
+ status=status,
317
+ exit_code=code,
318
+ summary=summary,
319
+ findings=findings,
320
+ duration_seconds=elapsed,
321
+ items=items
322
+ )
@@ -0,0 +1,249 @@
1
+ Metadata-Version: 2.4
2
+ Name: devsecpac
3
+ Version: 2.0.0
4
+ Summary: Universal Autonomous DevSecOps Scanner Orchestrator
5
+ Author-email: Fahad Shaikh <iamfahadshaikh@users.noreply.github.com>
6
+ License: MIT
7
+ Keywords: devsecops,security,sast,dast,sca,sbom,secrets-detection,compliance,kubernetes,container-security
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Intended Audience :: Information Technology
11
+ Classifier: Topic :: Security
12
+ Classifier: Topic :: Software Development :: Build Tools
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Operating System :: OS Independent
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+ Requires-Dist: rich>=13.0.0
22
+ Requires-Dist: pyyaml>=6.0
23
+ Requires-Dist: requests>=2.28.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
26
+ Requires-Dist: pytest-cov; extra == "dev"
27
+
28
+ # devsecpac (Universal Autonomous DevSecOps Orchestrator)
29
+
30
+ DevSecPac is an autonomous multi-engine security scanning orchestrator. It automatically discovers repository structures, executes relevant security tools across SAST, SCA, Secrets, IaC, Containers, Kubernetes, and Mobile stacks, unifies and deduplicates findings, generates local remediation patches, and exports results to CI/CD and ASPM platforms.
31
+
32
+ ---
33
+
34
+ ## Security Engines and Capabilities
35
+
36
+ Below is the complete matrix of integrated engines, their specific security role, the protection gained by running them, and the security risk exposure if skipped:
37
+
38
+ | Security Engine | Security Category | Purpose and Why It Is Included | What Happens If Used | What Happens If Skipped |
39
+ | :--- | :--- | :--- | :--- | :--- |
40
+ | **Gitleaks** | Secret Detection | Scans git commits, branches, and staged files for exposed API keys, private tokens, and passwords using pattern matching. | Catches leaked credentials prior to deployment, preventing account compromise. | High risk of leaking production credentials to public or shared git history. |
41
+ | **TruffleHog** | Deep Secret Scanning | Uses Shannon entropy and comprehensive secret verification algorithms across entire commit histories. | Finds rotated or legacy credentials buried deep in past commit trees. | Hidden, forgotten keys remaining in historical commits remain undetected. |
42
+ | **Semgrep** | Fast SAST & Guardrails | Multi-language static code analysis for Python, JS/TS, Go, Java, Docker, and configs without compilation. | Detects injection flaws (XSS, SQLi), insecure library calls, and logic flaws in seconds. | Application logic bugs and common CVE design patterns enter production code. |
43
+ | **Hadolint** | Dockerfile Linter | AST-based Dockerfile parser enforcing container best practices and non-root execution. | Flags root execution, untagged images, unpinned packages, and insecure curl/wget pipes. | Container images risk privilege escalation, bloated layers, and supply-chain tampering. |
44
+ | **GitHub CodeQL** | Semantic SAST | Compiles source code into relational database models to track deep taint-flow paths. | Flags complex, multi-hop remote code execution and cross-file injection paths. | Inter-procedural taint flow vulnerabilities slip past simple regex linters. |
45
+ | **SonarQube** | SAST & Quality Gate | Enterprise code quality, maintainability, test coverage, and security vulnerability analyzer. | Enforces strict release quality gates and identifies long-term maintainability debt. | Technical debt and security code smells accumulate unchecked across sprints. |
46
+ | **Checkov** | IaC Security | Scans Terraform, CloudFormation, Kubernetes, ARM, and Docker compose manifests against compliance benchmarks. | Catches open AWS S3 buckets, overly permissive IAM roles, and missing encryption. | Cloud infrastructure misconfigurations reach production, causing cloud leaks. |
47
+ | **Kubeconform** | Kubernetes Schema | Validates Kubernetes YAML against official OpenAPI and custom resource definition (CRD) schemas. | Blocks invalid API versions, missing spec fields, and syntax mistakes before deployment. | `kubectl apply` failures or silent cluster deployment rejections during rollouts. |
48
+ | **Kyverno CLI** | K8s Policy as Code | Evaluates Kubernetes manifests against security admission policies (e.g. Pod Security Standards). | Enforces mandatory read-only root filesystems, memory limits, and drops Linux capabilities. | Workloads run with host namespaces or excessive kernel privileges in cluster. |
49
+ | **Aqua Trivy** | Filesystem & Vuln SCA | Deep scanning of OS packages, application lockfiles, and container base layers. | Detects known CVEs in installed dependencies with severity and fixed version metadata. | Vulnerable third-party dependencies are deployed with unpatched vulnerabilities. |
50
+ | **OWASP Dependency-Check** | Software Composition (SCA) | Analyzes project dependencies for known published vulnerabilities against NVD CVE feeds. | Comprehensive enterprise visibility across Java, .NET, Node, and Python packages. | Dependency vulnerabilities in legacy libraries remain hidden without CVE alerts. |
51
+ | **Syft** | SBOM Generation | Inspects project dependencies and packages to build a machine-readable software inventory. | Produces CycloneDX-compliant SBOMs required by federal and compliance mandates. | Zero visibility into software supply chain; non-compliant with standard audits. |
52
+ | **Cosign (Sigstore)** | Supply Chain Attestation | Cryptographically signs generated SBOM artifacts and container images. | Guarantees pipeline tamper-proof provenance and satisfies SLSA level 2/3 requirements. | Inability to prove that build artifacts were not tampered with post-build. |
53
+ | **OWASP ZAP** | Baseline DAST | Dynamic application security testing of running HTTP web endpoints and APIs. | Identifies active runtime issues: missing CSP/HSTS headers, cookie flags, and active XSS. | Runtime misconfigurations and missing transport security go unnoticed in production. |
54
+ | **Schemathesis** | API Contract Security | Property-based fuzzing of OpenAPI, Swagger, and GraphQL interface schemas. | Discovers edge-case unhandled server 500 exceptions, type crashes, and input parsing errors. | API endpoints crash when receiving unexpected or malformed customer requests. |
55
+ | **Nmap** | Port & Service Discovery | Scans network targets and localhost to detect exposed ports and service banners. | Identifies open backend database ports or debug listeners inadvertently exposed. | Database, management, or debug ports remain exposed to external networks. |
56
+ | **MobSF** | Mobile Security (SAST) | Security analysis of Android and iOS application source directories and manifests. | Detects exported activities, insecure storage, and broken permission boundaries. | Mobile client secrets and insecure local storage vulnerabilities reach mobile stores. |
57
+
58
+ ---
59
+
60
+ ## Usage Variations
61
+
62
+ DevSecPac can be consumed in two primary workflows:
63
+ 1. **As a Standalone Python Package** (`pip install devsecpac`)
64
+ 2. **As an Air-Gapped Docker Container** (`docker run iamfahadshaikh/devsec-cli:latest`)
65
+
66
+ ---
67
+
68
+ ### Section 1: Running as a Python Package
69
+
70
+ Install the orchestrator into your Python environment:
71
+
72
+ ```bash
73
+ pip install devsecpac
74
+ ```
75
+
76
+ #### 1. Setup Required Tools Automatically
77
+ DevSecPac includes an autonomous installer that downloads and configures missing binary security engines into your local user path (`~/.local/bin`):
78
+ ```bash
79
+ devsec setup
80
+ ```
81
+
82
+ #### 2. Check Tool Discovery
83
+ Inspect which scanners are active and detected in your environment:
84
+ ```bash
85
+ devsec info
86
+ ```
87
+
88
+ #### 3. Run Autonomous Full Scan
89
+ Scan the current directory or target project path:
90
+ ```bash
91
+ devsec scan .
92
+ ```
93
+
94
+ #### 4. Run Targeted Scanners
95
+ Select specific security engines using comma-separated engine names:
96
+ ```bash
97
+ # Scan secrets and static code
98
+ devsec scan . -t gitleaks,semgrep
99
+
100
+ # Scan container Dockerfile and Kubernetes manifests
101
+ devsec scan . -t hadolint,checkov,kubeconform
102
+ ```
103
+
104
+ #### 5. Scan a Remote Git Repository
105
+ Ingest and scan a remote repository directly:
106
+ ```bash
107
+ devsec scan -r https://github.com/owner/repository.git -t semgrep,hadolint
108
+ ```
109
+
110
+ #### 6. Export to Enterprise ASPM (DefectDojo)
111
+ Push deduplicated vulnerability findings directly into DefectDojo:
112
+ ```bash
113
+ devsec scan . --defectdojo-push \
114
+ --defectdojo-url "http://localhost:8080" \
115
+ --defectdojo-key "your-api-token"
116
+ ```
117
+
118
+ #### 7. Generate Remediation Patch
119
+ Create a unified Git patch containing recommended fixes for local verification:
120
+ ```bash
121
+ devsec fix . --patch-output devsec-fix.patch
122
+
123
+ # Inspect the patch
124
+ git apply --check devsec-fix.patch
125
+
126
+ # Apply after manual review
127
+ git apply devsec-fix.patch
128
+ ```
129
+
130
+ #### 8. Suppress Known Findings (.devsecignore)
131
+ To bypass a specific rule or CVE permanently:
132
+ ```bash
133
+ # Suppress a specific rule on a file
134
+ echo "Dockerfile:DL3008" >> .devsecignore
135
+
136
+ # Suppress a specific CVE
137
+ echo "CVE-2024-XXXX" >> .devsecignore
138
+ ```
139
+
140
+ ---
141
+
142
+ ### Section 2: Running via Docker Image
143
+
144
+ The official Docker image (`iamfahadshaikh/devsec-cli:latest`) packages all 16 security engines, runtimes, and dependencies into a hardened container running as unprivileged user `devsecuser` (UID: 10001).
145
+
146
+ #### 1. Check Tool Status Inside Container
147
+ ```bash
148
+ docker run --rm iamfahadshaikh/devsec-cli:latest info
149
+ ```
150
+
151
+ #### 2. Scan Local Workspace
152
+ Mount your host source directory into `/workspace`:
153
+ ```bash
154
+ docker run --rm \
155
+ -v "$(pwd)":/workspace \
156
+ iamfahadshaikh/devsec-cli:latest scan .
157
+ ```
158
+
159
+ #### 3. Run Fast Scan (Secrets + SAST)
160
+ ```bash
161
+ docker run --rm \
162
+ -v "$(pwd)":/workspace \
163
+ iamfahadshaikh/devsec-cli:latest scan . -t gitleaks,semgrep,hadolint
164
+ ```
165
+
166
+ #### 4. Generate Remediation Patch from Container
167
+ ```bash
168
+ docker run --rm \
169
+ -v "$(pwd)":/workspace \
170
+ iamfahadshaikh/devsec-cli:latest fix . --patch-output devsec-fix.patch
171
+ ```
172
+
173
+ #### 5. Remote Repository Scanning
174
+ Scan any remote repository without cloning it locally:
175
+ ```bash
176
+ docker run --rm \
177
+ iamfahadshaikh/devsec-cli:latest scan -r https://github.com/owner/repository.git -t semgrep,trivy
178
+ ```
179
+
180
+ #### 6. Integration in CI/CD (GitHub Actions)
181
+ ```yaml
182
+ name: DevSecOps Autonomous Scan
183
+
184
+ on: [push, pull_request]
185
+
186
+ jobs:
187
+ security:
188
+ runs-on: ubuntu-latest
189
+ steps:
190
+ - uses: actions/checkout@v4
191
+ - name: Run DevSecPac Security Suite
192
+ run: |
193
+ docker run --rm -v ${{ github.workspace }}:/workspace \
194
+ iamfahadshaikh/devsec-cli:latest scan .
195
+ ```
196
+
197
+ ---
198
+
199
+ ## Publishing to PyPI as a Python Package
200
+
201
+ ### Required Files Checklist for Python Packaging
202
+
203
+ A production-ready Python package requires:
204
+ 1. `pyproject.toml` (Build system, package metadata, dependencies, and CLI entry points).
205
+ 2. `README.md` (Package description, documentation, and installation guide).
206
+ 3. `LICENSE` (Permissive license file, e.g. MIT).
207
+ 4. `src/<package_name>/` (Clean module package structure with `__init__.py`).
208
+ 5. `tests/` (Unit test suite verified with pytest).
209
+
210
+ ### Publishing Procedure
211
+
212
+ #### Step 1: Install Build and Distribution Utilities
213
+ ```bash
214
+ pip install --upgrade build twine
215
+ ```
216
+
217
+ #### Step 2: Build Source Distribution and Wheel
218
+ Run from repository root:
219
+ ```bash
220
+ python -m build
221
+ ```
222
+ This generates the distribution archives inside the `dist/` directory:
223
+ - `dist/devsecpac-2.0.0.tar.gz` (Source Archive)
224
+ - `dist/devsecpac-2.0.0-py3-none-any.whl` (Built Wheel)
225
+
226
+ #### Step 3: Validate Built Packages
227
+ Run `twine check` to ensure your README format, metadata, and syntax pass PyPI requirements:
228
+ ```bash
229
+ twine check dist/*
230
+ ```
231
+
232
+ #### Step 4: Test Upload to TestPyPI (Recommended First Step)
233
+ Verify metadata and package rendering on TestPyPI:
234
+ ```bash
235
+ twine upload --repository testpypi dist/*
236
+ ```
237
+
238
+ #### Step 5: Official Production Upload to PyPI
239
+ Upload the final package to the Python Package Index:
240
+ ```bash
241
+ twine upload dist/*
242
+ ```
243
+ Enter your PyPI API token (`__token__` as username and your token as password) when prompted. Once complete, users can install it globally via `pip install devsecpac`.
244
+
245
+ ---
246
+
247
+ ## License
248
+
249
+ This project is licensed under the MIT License.
@@ -0,0 +1,34 @@
1
+ devsec_cli/__init__.py,sha256=0w2ZOcxHZIOI0ey5_o4k5xL7jh0fEYyl2A447bmYW_8,122
2
+ devsec_cli/bypass.py,sha256=mQoKPpjpkoBScidFi4_k8uKjZz2PUyM91MFXlJ42Xew,4146
3
+ devsec_cli/ci.py,sha256=ExKkLZr6NdUDIIaKLVwwhtqF2wJOkzB5aJv8Lt3kOjM,7052
4
+ devsec_cli/cli.py,sha256=buB_G6YqNi4-7kr-v8VHnhfdn_E1J405FwPacZtZbB4,20879
5
+ devsec_cli/contracts.py,sha256=60OY0OcSD093O9mUU-p_XUh0zz_-99O4G8GqqbtBOBE,1905
6
+ devsec_cli/correlator.py,sha256=sezkOQrXZRcGSJAF-1YQ_V206NiepK0eKi4PU2_W8yU,4672
7
+ devsec_cli/discovery.py,sha256=_LX7fWbR2CSWm_4vUQ61sf25--xcBMqyQ_lLgU0Z60Y,4725
8
+ devsec_cli/ingestion.py,sha256=IKjwkqqBtpsw8K6uCq3XEFoOboE28Mwz7oidqxURCoY,6684
9
+ devsec_cli/installer.py,sha256=uZrlLrlKKPy5zYns9o8-KNsP5zNKWr7L7UsJmC3fKg0,20374
10
+ devsec_cli/remediation.py,sha256=WwvOVe8uaZZjxXCFhN5KBY1_MHQej0cVXQwcMuG0aZE,2819
11
+ devsec_cli/reporter.py,sha256=-9Ys9r7OC4m1oqNoh5IMEpO5FZdupwH_conzpyDtgiM,8854
12
+ devsec_cli/runner.py,sha256=cHu2uN-erqp_HeF_pGqVay7tLd8TxaAZHYpVjmp35iI,2298
13
+ devsec_cli/scanners/__init__.py,sha256=qFpXO7P-EkhZyvSRaTOpAn56JI0jrXCE4hydcFZvc0I,31
14
+ devsec_cli/scanners/base.py,sha256=aZS8CTDDyQo675uS9rN4g5jfl9nQPqMbWfkdnTO8B8Q,1462
15
+ devsec_cli/scanners/codeql.py,sha256=UlHVvK30O1EPvrG_Gm_gBd2HFuU12PdIR6W0rrQRR0E,5574
16
+ devsec_cli/scanners/cosign.py,sha256=ATJjDsQabq991QK5qsXaddIPtQnpVMRwofYWShtOtLs,2562
17
+ devsec_cli/scanners/dast.py,sha256=Vn5FN8jcafoHwWnr4kbTPeimMJRtQZ_gPm7ph3KZkqU,5002
18
+ devsec_cli/scanners/docker.py,sha256=JscBA69x2fNjGv-n7ZxB6-uEB0ErSa399DoZdyhEE9k,3527
19
+ devsec_cli/scanners/iac.py,sha256=-EioItp03t-iMVw41gjhxEPxGu3Zd-fCoz33JGKzde0,6619
20
+ devsec_cli/scanners/k8s_audit.py,sha256=DWZKLeW7YWGO76e9L9epXkt-1eCP-SKRJCZ7bLzhIII,6107
21
+ devsec_cli/scanners/kyverno.py,sha256=E7koPC22RGEzwy2YcmRp3oxpNcOfQEuG1hLS4j-8_ns,3077
22
+ devsec_cli/scanners/mobsf.py,sha256=1AuPwYg8_itZh4EMYRiJ1hXMDTtt-tZ1q841xZNzZr0,6103
23
+ devsec_cli/scanners/nmap.py,sha256=Y4cFuKwFgsEhm973bWBfWmmb7U6cd9X_y6UFASxyuUY,2558
24
+ devsec_cli/scanners/sbom.py,sha256=LJ2nb_tCRoUjsDqzcAzfYSQSrDLNfyJmgvjgfWgpVDc,1365
25
+ devsec_cli/scanners/sca.py,sha256=Te5OeqtA0mvThBsMw-DT0yd4vK4JpQK964nX9iGwtXM,7462
26
+ devsec_cli/scanners/schemathesis.py,sha256=34MxR975p2UETZSppqO4iPgNVuesIQbO7xBZiC5SU8o,2705
27
+ devsec_cli/scanners/secrets.py,sha256=ryNd3LoBt6wsN8sMlhAas8v_2fhVW7uh4Q0M8jzXm5A,6052
28
+ devsec_cli/scanners/semgrep.py,sha256=FGNVu-HTLZr7foI_SFdRti47pzu269A_8o3Dc6SAlsk,3244
29
+ devsec_cli/scanners/sonar.py,sha256=BTFFupVpoX1k2HszIh7Vu7CewOHdvcKtlXCW-yTWyU4,13667
30
+ devsecpac-2.0.0.dist-info/METADATA,sha256=1pQvzNnsMRaGCg5we4-nSz3OYKjgnrzk-IGH6Dyx4x8,12133
31
+ devsecpac-2.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
32
+ devsecpac-2.0.0.dist-info/entry_points.txt,sha256=sDbvsjeATRfx_XyYAANUwgibYWEXf_v9-TOZZsV4rWQ,79
33
+ devsecpac-2.0.0.dist-info/top_level.txt,sha256=9680CLlNBBHhAwrABMbxXiyBtqjbwiJ8GKusJTlhr2w,11
34
+ devsecpac-2.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ devsec = devsec_cli.cli:main
3
+ devsecpac = devsec_cli.cli:main
@@ -0,0 +1 @@
1
+ devsec_cli