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,453 @@
1
+ """Autonomous Resilient Toolchain Installer for devsec-cli.
2
+
3
+ Multi-strategy installer:
4
+ 1. Native OS package manager (apt/apt-get on Debian/Ubuntu/Kali)
5
+ 2. Safe user-level pip/pipx installation with PEP 668 break-system-packages support
6
+ 3. Official GitHub binary releases with isolated wrapper scripts
7
+ """
8
+
9
+ import os
10
+ import sys
11
+ import platform
12
+ import shutil
13
+ import tarfile
14
+ import zipfile
15
+ import subprocess
16
+ import requests
17
+ import json
18
+ from pathlib import Path
19
+ from typing import Optional, List
20
+ from rich.console import Console
21
+
22
+ console = Console()
23
+
24
+
25
+ class ToolInstaller:
26
+ def __init__(self, install_dir: Optional[Path] = None):
27
+ self.os_type = platform.system().lower() # linux, windows, darwin
28
+ self.arch = platform.machine().lower()
29
+ self.arch_norm = "arm64" if self.arch in ("aarch64", "arm64") else "amd64"
30
+ self.has_apt = shutil.which("apt-get") is not None or shutil.which("apt") is not None
31
+
32
+ if install_dir:
33
+ self.install_dir = install_dir.resolve()
34
+ self.opt_dir = self.install_dir.parent / "opt"
35
+ else:
36
+ if self.os_type == "windows":
37
+ base = Path(os.environ.get("USERPROFILE", ".")) / ".local"
38
+ self.install_dir = base / "bin"
39
+ self.opt_dir = base / "opt"
40
+ else:
41
+ base = Path.home() / ".local"
42
+ self.install_dir = base / "bin"
43
+ self.opt_dir = base / "opt"
44
+
45
+ self.install_dir.mkdir(parents=True, exist_ok=True)
46
+ self.opt_dir.mkdir(parents=True, exist_ok=True)
47
+
48
+ def is_in_path(self, tool_name: str) -> bool:
49
+ bin_path = shutil.which(tool_name)
50
+ if bin_path and Path(bin_path).is_file():
51
+ return True
52
+ # Also check directly in install_dir
53
+ local_bin = self.install_dir / (f"{tool_name}.exe" if self.os_type == "windows" else tool_name)
54
+ return local_bin.is_file() and os.access(local_bin, os.X_OK)
55
+
56
+ def install_all(self):
57
+ console.print(f"\n[bold green]DevSecOps Autonomous Toolchain Installer[/bold green]")
58
+ console.print(f" * Platform: [cyan]{self.os_type}[/cyan] ({self.arch_norm})")
59
+ console.print(f" * Target Directory: [yellow]{self.install_dir}[/yellow]")
60
+ console.print(f" * Apt Available: [bold]{'Yes' if self.has_apt else 'No'}[/bold]\n")
61
+
62
+ tools = [
63
+ ("gitleaks", self.install_gitleaks),
64
+ ("trufflehog", self.install_trufflehog),
65
+ ("hadolint", self.install_hadolint),
66
+ ("checkov", self.install_checkov),
67
+ ("kubeconform", self.install_kubeconform),
68
+ ("trivy", self.install_trivy),
69
+ ("syft", self.install_syft),
70
+ ("kyverno", self.install_kyverno),
71
+ ("codeql", self.install_codeql),
72
+ ("sonar-scanner", self.install_sonar),
73
+ ("dependency-check", self.install_dependency_check),
74
+ ("mobsfscan", self.install_mobsfscan),
75
+ ("nmap", self.install_nmap),
76
+ ("semgrep", self.install_semgrep),
77
+ ("cosign", self.install_cosign),
78
+ ("st", self.install_schemathesis),
79
+ ]
80
+
81
+ for name, installer_fn in tools:
82
+ if self.is_in_path(name):
83
+ console.print(f" * [green][OK][/green] {name:<18} Already installed in PATH.")
84
+ continue
85
+ console.print(f" * [bold blue][..][/bold blue] {name:<18} Installing...", end="\r")
86
+ try:
87
+ installer_fn()
88
+ if self.is_in_path(name):
89
+ console.print(f" * [green][OK][/green] {name:<18} [bold green]Installed successfully![/bold green] ")
90
+ else:
91
+ console.print(f" * [green][OK][/green] {name:<18} [bold green]Setup completed![/bold green] ")
92
+ except Exception as e:
93
+ console.print(f" * [red][ERR][/red] {name:<18} [red]Failed:[/red] {str(e)[:70]}")
94
+
95
+ console.print(f"\n[bold yellow]Tip:[/bold yellow] Ensure [cyan]{self.install_dir}[/cyan] is in your PATH:")
96
+ if self.os_type == "windows":
97
+ console.print(f' [dim]$env:PATH += ";{self.install_dir}"[/dim]')
98
+ else:
99
+ console.print(f' [dim]export PATH="{self.install_dir}:$PATH"[/dim]')
100
+ console.print()
101
+
102
+ def _try_apt_install(self, package_name: str) -> bool:
103
+ if not self.has_apt:
104
+ return False
105
+ apt_bin = shutil.which("apt-get") or shutil.which("apt")
106
+ cmd = [apt_bin, "install", "-y", package_name]
107
+ if os.geteuid() != 0 if hasattr(os, "geteuid") else False:
108
+ if shutil.which("sudo"):
109
+ cmd = ["sudo", "-n", apt_bin, "install", "-y", package_name]
110
+ else:
111
+ return False
112
+ try:
113
+ res = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
114
+ return res.returncode == 0
115
+ except Exception:
116
+ return False
117
+
118
+ def _download_file(self, url: str, dest: Path):
119
+ headers = {
120
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) devsec-cli/0.1.0"
121
+ }
122
+ with requests.get(url, headers=headers, stream=True, timeout=180) as r:
123
+ r.raise_for_status()
124
+ with open(dest, "wb") as out_file:
125
+ shutil.copyfileobj(r.raw, out_file)
126
+
127
+ def install_gitleaks(self):
128
+ ver = "8.18.4"
129
+ ext = "zip" if self.os_type == "windows" else "tar.gz"
130
+ os_str = "windows" if self.os_type == "windows" else ("linux" if self.os_type == "linux" else "darwin")
131
+ arch_str = "x64" if self.arch_norm == "amd64" else "arm64"
132
+ url = f"https://github.com/gitleaks/gitleaks/releases/download/v{ver}/gitleaks_{ver}_{os_str}_{arch_str}.{ext}"
133
+
134
+ tmp_archive = self.install_dir / f"gitleaks_tmp.{ext}"
135
+ self._download_file(url, tmp_archive)
136
+
137
+ if ext == "zip":
138
+ with zipfile.ZipFile(tmp_archive, "r") as z:
139
+ z.extract("gitleaks.exe", self.install_dir)
140
+ else:
141
+ with tarfile.open(tmp_archive, "r:gz") as t:
142
+ for member in t.getmembers():
143
+ if member.name == "gitleaks":
144
+ t.extract(member, self.install_dir)
145
+ (self.install_dir / "gitleaks").chmod(0o755)
146
+ tmp_archive.unlink(missing_ok=True)
147
+
148
+ def install_trufflehog(self):
149
+ if self._try_apt_install("trufflehog"):
150
+ return
151
+ ver = "3.88.5"
152
+ os_str = "windows" if self.os_type == "windows" else ("linux" if self.os_type == "linux" else "darwin")
153
+ url = f"https://github.com/trufflesecurity/trufflehog/releases/download/v{ver}/trufflehog_{ver}_{os_str}_{self.arch_norm}.tar.gz"
154
+
155
+ tmp_archive = self.install_dir / "trufflehog_tmp.tar.gz"
156
+ self._download_file(url, tmp_archive)
157
+
158
+ with tarfile.open(tmp_archive, "r:gz") as t:
159
+ for member in t.getmembers():
160
+ if member.name in ("trufflehog", "trufflehog.exe"):
161
+ t.extract(member, self.install_dir)
162
+ bin_path = self.install_dir / member.name
163
+ bin_path.chmod(0o755)
164
+ tmp_archive.unlink(missing_ok=True)
165
+
166
+ def install_hadolint(self):
167
+ bin_name = "hadolint.exe" if self.os_type == "windows" else "hadolint"
168
+ os_str = "Windows-x86_64.exe" if self.os_type == "windows" else ("Linux-x86_64" if self.os_type == "linux" else "Darwin-x86_64")
169
+ url = f"https://github.com/hadolint/hadolint/releases/latest/download/hadolint-{os_str}"
170
+
171
+ dest = self.install_dir / bin_name
172
+ self._download_file(url, dest)
173
+ dest.chmod(0o755)
174
+
175
+ def install_checkov(self):
176
+ pipx = shutil.which("pipx")
177
+ if pipx:
178
+ subprocess.run([pipx, "install", "checkov"], check=True, capture_output=True)
179
+ return
180
+
181
+ cmd = [sys.executable, "-m", "pip", "install", "checkov", "--break-system-packages"]
182
+ try:
183
+ subprocess.run(cmd, check=True, capture_output=True)
184
+ return
185
+ except subprocess.CalledProcessError:
186
+ pass
187
+
188
+ cmd_standard = [sys.executable, "-m", "pip", "install", "checkov"]
189
+ subprocess.run(cmd_standard, check=True, capture_output=True)
190
+
191
+ def install_kubeconform(self):
192
+ ver = "0.6.7"
193
+ os_str = "windows" if self.os_type == "windows" else ("linux" if self.os_type == "linux" else "darwin")
194
+ ext = "zip" if self.os_type == "windows" else "tar.gz"
195
+ url = f"https://github.com/yannh/kubeconform/releases/download/v{ver}/kubeconform-{os_str}-{self.arch_norm}.{ext}"
196
+
197
+ tmp_archive = self.install_dir / f"kubeconform_tmp.{ext}"
198
+ self._download_file(url, tmp_archive)
199
+
200
+ if ext == "zip":
201
+ with zipfile.ZipFile(tmp_archive, "r") as z:
202
+ z.extract("kubeconform.exe", self.install_dir)
203
+ else:
204
+ with tarfile.open(tmp_archive, "r:gz") as t:
205
+ for member in t.getmembers():
206
+ if member.name == "kubeconform":
207
+ t.extract(member, self.install_dir)
208
+ (self.install_dir / "kubeconform").chmod(0o755)
209
+ tmp_archive.unlink(missing_ok=True)
210
+
211
+ def install_trivy(self):
212
+ if self._try_apt_install("trivy"):
213
+ return
214
+ ver = "0.76.2"
215
+ os_str = "windows" if self.os_type == "windows" else ("Linux" if self.os_type == "linux" else "macOS")
216
+ arch_title = "64bit" if self.arch_norm == "amd64" else "ARM64"
217
+ ext = "zip" if self.os_type == "windows" else "tar.gz"
218
+ url = f"https://github.com/aquasecurity/trivy/releases/download/v{ver}/trivy_{ver}_{os_str}-{arch_title}.{ext}"
219
+
220
+ tmp_archive = self.install_dir / f"trivy_tmp.{ext}"
221
+ self._download_file(url, tmp_archive)
222
+
223
+ if ext == "zip":
224
+ with zipfile.ZipFile(tmp_archive, "r") as z:
225
+ z.extract("trivy.exe", self.install_dir)
226
+ else:
227
+ with tarfile.open(tmp_archive, "r:gz") as t:
228
+ for member in t.getmembers():
229
+ if member.name == "trivy":
230
+ t.extract(member, self.install_dir)
231
+ (self.install_dir / "trivy").chmod(0o755)
232
+ tmp_archive.unlink(missing_ok=True)
233
+
234
+ def install_syft(self):
235
+ ver = "1.18.0"
236
+ os_str = "windows" if self.os_type == "windows" else ("linux" if self.os_type == "linux" else "darwin")
237
+ ext = "zip" if self.os_type == "windows" else "tar.gz"
238
+ url = f"https://github.com/anchore/syft/releases/download/v{ver}/syft_{ver}_{os_str}_{self.arch_norm}.{ext}"
239
+
240
+ tmp_archive = self.install_dir / f"syft_tmp.{ext}"
241
+ self._download_file(url, tmp_archive)
242
+
243
+ if ext == "zip":
244
+ with zipfile.ZipFile(tmp_archive, "r") as z:
245
+ z.extract("syft.exe", self.install_dir)
246
+ else:
247
+ with tarfile.open(tmp_archive, "r:gz") as t:
248
+ for member in t.getmembers():
249
+ if member.name == "syft":
250
+ t.extract(member, self.install_dir)
251
+ (self.install_dir / "syft").chmod(0o755)
252
+ tmp_archive.unlink(missing_ok=True)
253
+
254
+ def install_kyverno(self):
255
+ ver = "1.12.5"
256
+ ext = "zip" if self.os_type == "windows" else "tar.gz"
257
+ os_str = "windows" if self.os_type == "windows" else ("linux" if self.os_type == "linux" else "darwin")
258
+ arch_str = "x86_64" if self.arch_norm == "amd64" else "arm64"
259
+ url = f"https://github.com/kyverno/kyverno/releases/download/v{ver}/kyverno-cli_v{ver}_{os_str}_{arch_str}.{ext}"
260
+
261
+ tmp_archive = self.install_dir / f"kyverno_tmp.{ext}"
262
+ self._download_file(url, tmp_archive)
263
+
264
+ if ext == "zip":
265
+ with zipfile.ZipFile(tmp_archive, "r") as z:
266
+ z.extract("kyverno.exe", self.install_dir)
267
+ else:
268
+ with tarfile.open(tmp_archive, "r:gz") as t:
269
+ for member in t.getmembers():
270
+ if member.name == "kyverno":
271
+ t.extract(member, self.install_dir)
272
+ (self.install_dir / "kyverno").chmod(0o755)
273
+ tmp_archive.unlink(missing_ok=True)
274
+
275
+ def install_codeql(self):
276
+ """Installs CodeQL into opt/codeql and creates a clean executable wrapper."""
277
+ os_str = "win64" if self.os_type == "windows" else ("linux64" if self.os_type == "linux" else "osx64")
278
+ url = f"https://github.com/github/codeql-cli-binaries/releases/latest/download/codeql-{os_str}.zip"
279
+
280
+ codeql_opt = self.opt_dir / "codeql"
281
+ if codeql_opt.exists():
282
+ shutil.rmtree(codeql_opt, ignore_errors=True)
283
+
284
+ tmp_zip = self.opt_dir / "codeql_tmp.zip"
285
+ self._download_file(url, tmp_zip)
286
+
287
+ with zipfile.ZipFile(tmp_zip, "r") as z:
288
+ z.extractall(self.opt_dir)
289
+ tmp_zip.unlink(missing_ok=True)
290
+
291
+ # Ensure all extracted binaries and JRE sub-executables are marked executable on POSIX
292
+ if self.os_type != "windows":
293
+ for p in (self.opt_dir / "codeql").rglob("*"):
294
+ if p.is_file() and not p.name.endswith((".txt", ".md", ".json", ".xml", ".properties")):
295
+ try:
296
+ p.chmod(p.stat().st_mode | 0o755)
297
+ except Exception:
298
+ pass
299
+
300
+ # Remove any lingering directory named codeql in ~/.local/bin
301
+ legacy_dir = self.install_dir / "codeql"
302
+ if legacy_dir.is_dir():
303
+ shutil.rmtree(legacy_dir, ignore_errors=True)
304
+ elif legacy_dir.is_file():
305
+ legacy_dir.unlink(missing_ok=True)
306
+
307
+ real_bin = self.opt_dir / "codeql" / ("codeql.exe" if self.os_type == "windows" else "codeql")
308
+ real_bin.chmod(0o755)
309
+
310
+ # Create wrapper in bin/
311
+ if self.os_type == "windows":
312
+ wrapper = self.install_dir / "codeql.cmd"
313
+ wrapper.write_text(f'@echo off\n"{real_bin}" %*\n', encoding="utf-8")
314
+ else:
315
+ wrapper = self.install_dir / "codeql"
316
+ wrapper.write_text(f'#!/bin/sh\nexec "{real_bin}" "$@"\n', encoding="utf-8")
317
+ wrapper.chmod(0o755)
318
+
319
+ def install_sonar(self):
320
+ ver = "6.2.1.4610"
321
+ os_str = "windows-x64" if self.os_type == "windows" else ("linux-x64" if self.os_type == "linux" else "macosx-x64")
322
+ url = f"https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-{ver}-{os_str}.zip"
323
+
324
+ sonar_dir = self.opt_dir / f"sonar-scanner-{ver}-{os_str}"
325
+ if not sonar_dir.exists():
326
+ tmp_zip = self.opt_dir / "sonar_tmp.zip"
327
+ self._download_file(url, tmp_zip)
328
+ with zipfile.ZipFile(tmp_zip, "r") as z:
329
+ z.extractall(self.opt_dir)
330
+ tmp_zip.unlink(missing_ok=True)
331
+
332
+ # Ensure extracted binaries are executable on POSIX
333
+ if self.os_type != "windows":
334
+ for p in sonar_dir.rglob("*"):
335
+ if p.is_file() and not p.name.endswith((".txt", ".md", ".json", ".xml", ".properties")):
336
+ try:
337
+ p.chmod(p.stat().st_mode | 0o755)
338
+ except Exception:
339
+ pass
340
+
341
+ real_bin = sonar_dir / "bin" / ("sonar-scanner.bat" if self.os_type == "windows" else "sonar-scanner")
342
+ real_bin.chmod(0o755)
343
+
344
+ if self.os_type == "windows":
345
+ wrapper = self.install_dir / "sonar-scanner.cmd"
346
+ wrapper.write_text(f'@echo off\n"{real_bin}" %*\n', encoding="utf-8")
347
+ else:
348
+ wrapper = self.install_dir / "sonar-scanner"
349
+ wrapper.write_text(f'#!/bin/sh\nexec "{real_bin}" "$@"\n', encoding="utf-8")
350
+ wrapper.chmod(0o755)
351
+
352
+ def install_dependency_check(self):
353
+ """Installs OWASP Dependency-Check into opt/ and creates a clean executable wrapper."""
354
+ ver = "12.1.0"
355
+ url = f"https://github.com/jeremylong/DependencyCheck/releases/download/v{ver}/dependency-check-{ver}-release.zip"
356
+
357
+ dc_opt = self.opt_dir / "dependency-check"
358
+ if not dc_opt.exists():
359
+ tmp_zip = self.opt_dir / "dc_tmp.zip"
360
+ self._download_file(url, tmp_zip)
361
+ with zipfile.ZipFile(tmp_zip, "r") as z:
362
+ z.extractall(self.opt_dir)
363
+ tmp_zip.unlink(missing_ok=True)
364
+
365
+ # Ensure extracted binaries are executable on POSIX
366
+ if self.os_type != "windows":
367
+ for p in dc_opt.rglob("*"):
368
+ if p.is_file() and not p.name.endswith((".txt", ".md", ".json", ".xml", ".properties")):
369
+ try:
370
+ p.chmod(p.stat().st_mode | 0o755)
371
+ except Exception:
372
+ pass
373
+
374
+ # Remove any lingering directory named dependency-check in ~/.local/bin
375
+ legacy = self.install_dir / "dependency-check"
376
+ if legacy.is_dir():
377
+ shutil.rmtree(legacy, ignore_errors=True)
378
+ elif legacy.is_file():
379
+ legacy.unlink(missing_ok=True)
380
+
381
+ real_bin = self.opt_dir / "dependency-check" / "bin" / ("dependency-check.bat" if self.os_type == "windows" else "dependency-check.sh")
382
+ real_bin.chmod(0o755)
383
+
384
+ if self.os_type == "windows":
385
+ wrapper = self.install_dir / "dependency-check.cmd"
386
+ wrapper.write_text(f'@echo off\n"{real_bin}" %*\n', encoding="utf-8")
387
+ else:
388
+ wrapper = self.install_dir / "dependency-check"
389
+ wrapper.write_text(f'#!/bin/sh\nexec "{real_bin}" "$@"\n', encoding="utf-8")
390
+ wrapper.chmod(0o755)
391
+
392
+ def install_mobsfscan(self):
393
+ """Installs mobsfscan using pip or pipx with PEP 668 support."""
394
+ pipx = shutil.which("pipx")
395
+ if pipx:
396
+ subprocess.run([pipx, "install", "mobsfscan"], check=True, capture_output=True)
397
+ return
398
+
399
+ cmd = [sys.executable, "-m", "pip", "install", "mobsfscan", "--break-system-packages"]
400
+ try:
401
+ subprocess.run(cmd, check=True, capture_output=True)
402
+ return
403
+ except subprocess.CalledProcessError:
404
+ pass
405
+
406
+ cmd_standard = [sys.executable, "-m", "pip", "install", "mobsfscan"]
407
+ subprocess.run(cmd_standard, check=True, capture_output=True)
408
+
409
+ def install_nmap(self):
410
+ """Installs nmap via apt if on Debian/Ubuntu/Kali."""
411
+ if self._try_apt_install("nmap"):
412
+ return
413
+ raise RuntimeError("nmap should be installed via your system package manager (e.g. sudo apt install nmap)")
414
+
415
+ def install_semgrep(self):
416
+ """Installs Semgrep fast SAST via pip with PEP 668 support."""
417
+ pipx = shutil.which("pipx")
418
+ if pipx:
419
+ subprocess.run([pipx, "install", "semgrep"], check=True, capture_output=True)
420
+ return
421
+
422
+ cmd = [sys.executable, "-m", "pip", "install", "semgrep", "--break-system-packages"]
423
+ try:
424
+ subprocess.run(cmd, check=True, capture_output=True)
425
+ return
426
+ except subprocess.CalledProcessError:
427
+ subprocess.run([sys.executable, "-m", "pip", "install", "semgrep"], check=True, capture_output=True)
428
+
429
+ def install_schemathesis(self):
430
+ """Installs Schemathesis API tester via pip with PEP 668 support."""
431
+ pipx = shutil.which("pipx")
432
+ if pipx:
433
+ subprocess.run([pipx, "install", "schemathesis"], check=True, capture_output=True)
434
+ return
435
+
436
+ cmd = [sys.executable, "-m", "pip", "install", "schemathesis", "--break-system-packages"]
437
+ try:
438
+ subprocess.run(cmd, check=True, capture_output=True)
439
+ return
440
+ except subprocess.CalledProcessError:
441
+ subprocess.run([sys.executable, "-m", "pip", "install", "schemathesis"], check=True, capture_output=True)
442
+
443
+ def install_cosign(self):
444
+ """Installs Cosign from official GitHub release."""
445
+ tag = "v2.4.1"
446
+ ext = "exe" if self.os_type == "windows" else ""
447
+ binary_name = f"cosign-windows-{self.arch_norm}.exe" if self.os_type == "windows" else f"cosign-linux-{self.arch_norm}"
448
+ url = f"https://github.com/sigstore/cosign/releases/download/{tag}/{binary_name}"
449
+
450
+ target_file = self.install_dir / ("cosign.exe" if self.os_type == "windows" else "cosign")
451
+ self._download_file(url, target_file)
452
+ target_file.chmod(0o755)
453
+
@@ -0,0 +1,63 @@
1
+ """Autonomous Remediation Engine for DevSecPac v2.0."""
2
+
3
+ from pathlib import Path
4
+ from typing import List, Dict
5
+ import re
6
+ from rich.console import Console
7
+ from .contracts import FindingDetail
8
+
9
+ console = Console()
10
+
11
+
12
+ class RemediationEngine:
13
+ """Analyzes findings and generates automatic patches or fixes for common vulnerabilities.
14
+
15
+ Supported Auto-Fixes:
16
+ - Pinning base Dockerfile images or package-install commands (DL3008, DL3042)
17
+ - Package lockfile remediation recommendations
18
+ - Patch file generation (devsec-fix.patch)
19
+ """
20
+
21
+ def __init__(self, target_dir: Path):
22
+ self.target_dir = target_dir
23
+
24
+ def generate_remediation_patch(self, findings: List[FindingDetail], patch_path: Path) -> int:
25
+ """Generates a standard unified git patch for fixable issues."""
26
+ diff_lines = []
27
+ fixes_applied = 0
28
+
29
+ # Scan for Dockerfile issues (e.g. Hadolint DL3008, DL3042)
30
+ dockerfiles = list(self.target_dir.glob("**/Dockerfile*"))
31
+ for df in dockerfiles:
32
+ if not df.is_file() or ".git" in df.parts:
33
+ continue
34
+
35
+ content = df.read_text(encoding="utf-8")
36
+ original_content = content
37
+
38
+ # Fix DL3042: Avoid cache directory with pip install by adding --no-cache-dir
39
+ if re.search(r"pip\s+install\s+(?!.*--no-cache-dir)", content):
40
+ content = re.sub(r"(pip\s+install\s+)", r"\1--no-cache-dir ", content)
41
+ fixes_applied += 1
42
+
43
+ # Fix DL3008: apt-get install without cleanup
44
+ if "apt-get install" in content and "rm -rf /var/lib/apt/lists/*" not in content:
45
+ content = content.replace("apt-get install", "apt-get install -y --no-install-recommends")
46
+ fixes_applied += 1
47
+
48
+ if content != original_content:
49
+ rel_path = df.relative_to(self.target_dir)
50
+ diff_lines.append(f"--- a/{rel_path}")
51
+ diff_lines.append(f"+++ b/{rel_path}")
52
+ diff_lines.append("@@ -1 +1 @@")
53
+ diff_lines.append(f"-{original_content.splitlines()[0] if original_content.splitlines() else ''}")
54
+ diff_lines.append(f"+{content.splitlines()[0] if content.splitlines() else ''}")
55
+
56
+ if diff_lines:
57
+ patch_path.write_text("\n".join(diff_lines) + "\n", encoding="utf-8")
58
+ console.print(f"[bold green][OK][/bold green] Generated unified remediation patch: [bold cyan]{patch_path.name}[/bold cyan] ({fixes_applied} auto-fixable issue(s))")
59
+ console.print(f"[dim]Tip: Review the suggested diff and apply with: git apply {patch_path.name}[/dim]")
60
+ else:
61
+ console.print("[dim yellow]No deterministic auto-fixes identified for current findings.[/dim yellow]")
62
+
63
+ return fixes_applied