patchloop 0.2.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.
- patchloop/__init__.py +23 -0
- patchloop/api.py +110 -0
- patchloop/build.py +118 -0
- patchloop/classify.py +137 -0
- patchloop/cli.py +370 -0
- patchloop/config.py +148 -0
- patchloop/detect.py +133 -0
- patchloop/doctor.py +207 -0
- patchloop/enrich/__init__.py +66 -0
- patchloop/enrich/epss.py +65 -0
- patchloop/enrich/kev.py +39 -0
- patchloop/fixers/__init__.py +1 -0
- patchloop/fixers/base.py +20 -0
- patchloop/fixers/js_fix.py +288 -0
- patchloop/fixers/poetry_fix.py +144 -0
- patchloop/fixers/uv_fix.py +118 -0
- patchloop/git_ops.py +171 -0
- patchloop/github.py +161 -0
- patchloop/hints.py +180 -0
- patchloop/images.py +208 -0
- patchloop/isolate.py +57 -0
- patchloop/js/__init__.py +1 -0
- patchloop/js/lockfiles.py +237 -0
- patchloop/js/manifest.py +121 -0
- patchloop/js/ranges.py +130 -0
- patchloop/js/registry.py +67 -0
- patchloop/js/yarn.py +189 -0
- patchloop/lockgraph.py +181 -0
- patchloop/models.py +248 -0
- patchloop/plan.py +194 -0
- patchloop/pr_body.py +253 -0
- patchloop/prioritize.py +38 -0
- patchloop/proc.py +71 -0
- patchloop/py.typed +0 -0
- patchloop/pypi.py +60 -0
- patchloop/report/__init__.py +1 -0
- patchloop/report/console.py +243 -0
- patchloop/report/json_out.py +26 -0
- patchloop/report/sarif.py +143 -0
- patchloop/runner.py +494 -0
- patchloop/scanner.py +214 -0
- patchloop/sources/__init__.py +1 -0
- patchloop/sources/base.py +5 -0
- patchloop/sources/imports.py +292 -0
- patchloop/sources/merge.py +113 -0
- patchloop/sources/osv.py +255 -0
- patchloop/specifiers.py +259 -0
- patchloop/validate.py +198 -0
- patchloop/versions.py +81 -0
- patchloop/workspaces.py +142 -0
- patchloop/worktree.py +153 -0
- patchloop-0.2.0.dist-info/METADATA +388 -0
- patchloop-0.2.0.dist-info/RECORD +56 -0
- patchloop-0.2.0.dist-info/WHEEL +4 -0
- patchloop-0.2.0.dist-info/entry_points.txt +3 -0
- patchloop-0.2.0.dist-info/licenses/LICENSE +21 -0
patchloop/prioritize.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Order findings most urgent first: known exploited, then likely exploited, then severity.
|
|
2
|
+
|
|
3
|
+
1. In CISA KEV (exploited in the wild).
|
|
4
|
+
2. EPSS at or above 0.1 (likely to be exploited soon).
|
|
5
|
+
3. Severity, CRITICAL first; unrated counts as HIGH.
|
|
6
|
+
4. Then the EPSS score, then CVSS, so equal severities still break by real-world risk.
|
|
7
|
+
|
|
8
|
+
Within the same severity, the more likely exploited finding comes first.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from patchloop.models import Finding, Severity
|
|
14
|
+
|
|
15
|
+
EPSS_LIKELY = 0.1
|
|
16
|
+
"""EPSS probability at or above which a finding counts as likely to be exploited."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def gate_severity(f: Finding) -> Severity:
|
|
20
|
+
"""Severity used for the threshold and ordering: unrated counts as HIGH until rated."""
|
|
21
|
+
return Severity.HIGH if f.severity is Severity.UNKNOWN else f.severity
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def always_fix(f: Finding) -> bool:
|
|
25
|
+
"""Known or likely exploitation outranks the severity threshold."""
|
|
26
|
+
return f.in_kev or (f.epss or 0.0) >= EPSS_LIKELY
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def sort_key(f: Finding) -> tuple[bool, bool, int, float, float, str, str]:
|
|
30
|
+
return (
|
|
31
|
+
not f.in_kev,
|
|
32
|
+
(f.epss or 0.0) < EPSS_LIKELY,
|
|
33
|
+
-gate_severity(f).rank,
|
|
34
|
+
-(f.epss or 0.0),
|
|
35
|
+
-(f.cvss or 0.0),
|
|
36
|
+
f.package,
|
|
37
|
+
f.advisory_id,
|
|
38
|
+
)
|
patchloop/proc.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""The one place PatchLoop runs external tools.
|
|
2
|
+
|
|
3
|
+
Commands are always argv lists (never ``shell=True``), so nothing from a repo or a
|
|
4
|
+
scanner file is ever interpreted by a shell.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import subprocess
|
|
10
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ToolNotFoundError(Exception):
|
|
16
|
+
"""The executable is not on PATH."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, tool: str) -> None:
|
|
19
|
+
super().__init__(f"'{tool}' was not found on PATH")
|
|
20
|
+
self.tool = tool
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ToolTimeoutError(Exception):
|
|
24
|
+
"""The command ran longer than its timeout."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, cmd: Sequence[str], timeout: float) -> None:
|
|
27
|
+
super().__init__(f"'{' '.join(cmd)}' timed out after {timeout:g}s")
|
|
28
|
+
self.cmd = list(cmd)
|
|
29
|
+
self.timeout = timeout
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class ProcResult:
|
|
34
|
+
returncode: int
|
|
35
|
+
stdout: str
|
|
36
|
+
stderr: str
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def ok(self) -> bool:
|
|
40
|
+
return self.returncode == 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
Runner = Callable[[Sequence[str]], ProcResult]
|
|
44
|
+
"""Signature used wherever a command runner can be swapped out in tests."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def run(
|
|
48
|
+
cmd: Sequence[str],
|
|
49
|
+
*,
|
|
50
|
+
cwd: Path | None = None,
|
|
51
|
+
timeout: float | None = None,
|
|
52
|
+
env: Mapping[str, str] | None = None,
|
|
53
|
+
) -> ProcResult:
|
|
54
|
+
"""Run ``cmd`` and capture its output. Never raises on a non-zero exit code."""
|
|
55
|
+
try:
|
|
56
|
+
completed = subprocess.run(
|
|
57
|
+
list(cmd),
|
|
58
|
+
cwd=cwd,
|
|
59
|
+
capture_output=True,
|
|
60
|
+
text=True,
|
|
61
|
+
encoding="utf-8",
|
|
62
|
+
errors="replace", # a tool printing other bytes must not crash the run
|
|
63
|
+
timeout=timeout,
|
|
64
|
+
env=dict(env) if env is not None else None,
|
|
65
|
+
check=False,
|
|
66
|
+
)
|
|
67
|
+
except FileNotFoundError as exc:
|
|
68
|
+
raise ToolNotFoundError(cmd[0]) from exc
|
|
69
|
+
except subprocess.TimeoutExpired as exc:
|
|
70
|
+
raise ToolTimeoutError(cmd, timeout or 0) from exc
|
|
71
|
+
return ProcResult(completed.returncode, completed.stdout, completed.stderr)
|
patchloop/py.typed
ADDED
|
File without changes
|
patchloop/pypi.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Which releases of a package exist and are not yanked (PyPI JSON API)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Protocol
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from patchloop import __version__
|
|
10
|
+
from patchloop.versions import parse, sort_versions
|
|
11
|
+
|
|
12
|
+
PYPI_JSON = "https://pypi.org/pypi/{name}/json"
|
|
13
|
+
TIMEOUT_S = 15.0
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ReleaseIndex(Protocol):
|
|
17
|
+
def releases(self, package: str) -> list[str] | None:
|
|
18
|
+
"""Final, non-yanked versions, lowest first; None when the index can't be reached."""
|
|
19
|
+
...
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def usable_releases(data: dict[str, Any]) -> list[str]:
|
|
23
|
+
out: list[str] = []
|
|
24
|
+
for version, files in (data.get("releases") or {}).items():
|
|
25
|
+
v = parse(version)
|
|
26
|
+
if v is None or v.is_prerelease or v.is_devrelease or not files:
|
|
27
|
+
continue
|
|
28
|
+
if all(f.get("yanked") for f in files):
|
|
29
|
+
continue
|
|
30
|
+
out.append(version)
|
|
31
|
+
return sort_versions(out)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class PyPIIndex:
|
|
35
|
+
def __init__(self, client: httpx.Client | None = None) -> None:
|
|
36
|
+
self._client = client or httpx.Client(
|
|
37
|
+
timeout=TIMEOUT_S, headers={"User-Agent": f"patchloop/{__version__}"}
|
|
38
|
+
)
|
|
39
|
+
self._cache: dict[str, list[str] | None] = {}
|
|
40
|
+
|
|
41
|
+
def releases(self, package: str) -> list[str] | None:
|
|
42
|
+
if package not in self._cache:
|
|
43
|
+
try:
|
|
44
|
+
resp = self._client.get(PYPI_JSON.format(name=package))
|
|
45
|
+
resp.raise_for_status()
|
|
46
|
+
self._cache[package] = usable_releases(resp.json())
|
|
47
|
+
except (httpx.HTTPError, ValueError):
|
|
48
|
+
self._cache[package] = None
|
|
49
|
+
return self._cache[package]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class StaticIndex:
|
|
53
|
+
"""For tests and offline runs."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, releases: dict[str, list[str]] | None = None) -> None:
|
|
56
|
+
self._releases = releases or {}
|
|
57
|
+
|
|
58
|
+
def releases(self, package: str) -> list[str] | None:
|
|
59
|
+
found = self._releases.get(package)
|
|
60
|
+
return sort_versions(found) if found is not None else None
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Output writers: console, JSON (and SARIF / PR body in later stages)."""
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Human-readable scan output."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import Counter
|
|
6
|
+
|
|
7
|
+
from rich.console import Console
|
|
8
|
+
from rich.table import Table
|
|
9
|
+
|
|
10
|
+
from patchloop.models import Finding, FixStatus, Severity
|
|
11
|
+
from patchloop.runner import FixOutcome
|
|
12
|
+
from patchloop.scanner import ScanResult
|
|
13
|
+
from patchloop.versions import is_major_upgrade
|
|
14
|
+
|
|
15
|
+
_STYLE = {
|
|
16
|
+
Severity.CRITICAL: "bold red",
|
|
17
|
+
Severity.HIGH: "red",
|
|
18
|
+
Severity.MEDIUM: "yellow",
|
|
19
|
+
Severity.LOW: "cyan",
|
|
20
|
+
Severity.UNKNOWN: "dim",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def fix_label(f: Finding) -> str:
|
|
25
|
+
if not f.fixed_versions:
|
|
26
|
+
return "none"
|
|
27
|
+
target = f.fixed_versions[0]
|
|
28
|
+
if is_major_upgrade(f.installed_version, target):
|
|
29
|
+
return f"{target} (major)"
|
|
30
|
+
return target
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def kind_label(f: Finding) -> str:
|
|
34
|
+
if not f.in_lockfile:
|
|
35
|
+
return {"os": "os package", "PyPI": "not in lockfile"}.get(f.ecosystem, "image only")
|
|
36
|
+
if f.fixed_in_source:
|
|
37
|
+
return "fixed in lockfile"
|
|
38
|
+
kind = "direct" if f.is_direct else "transitive"
|
|
39
|
+
return f"{kind}, dev" if f.dev_only else kind
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def exploit_label(f: Finding) -> str:
|
|
43
|
+
parts = ["[bold red]KEV[/]"] if f.in_kev else []
|
|
44
|
+
if f.epss is not None and f.epss >= 0.001:
|
|
45
|
+
parts.append(f"EPSS {f.epss:.1%}")
|
|
46
|
+
return " · ".join(parts)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def found_by(f: Finding) -> str:
|
|
50
|
+
return ", ".join(dict.fromkeys(h.tool.removesuffix("-scanner") for h in f.sources))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def via_label(f: Finding) -> str:
|
|
54
|
+
"""For transitive packages: the shortest chain of parents, without the project itself."""
|
|
55
|
+
if f.is_direct or not f.dependency_paths:
|
|
56
|
+
return ""
|
|
57
|
+
return " → ".join(f.dependency_paths[0][1:-1])
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def render_scan(result: ScanResult, console: Console) -> None:
|
|
61
|
+
rel = result.project.lockfile.name
|
|
62
|
+
console.print(
|
|
63
|
+
f"[bold]{result.project.root.name}[/bold] · {result.project.manager} · {rel}"
|
|
64
|
+
+ (f" · {result.project.commit_sha[:8]}" if result.project.commit_sha else "")
|
|
65
|
+
)
|
|
66
|
+
if result.shown:
|
|
67
|
+
table = Table(show_lines=False, header_style="bold")
|
|
68
|
+
for col in ("Severity", "Package", "Installed", "Advisory", "Fixed in", "Type"):
|
|
69
|
+
table.add_column(col, no_wrap=True)
|
|
70
|
+
show_via = any(via_label(f) for f in result.shown)
|
|
71
|
+
if show_via:
|
|
72
|
+
table.add_column("Via", overflow="fold", min_width=8)
|
|
73
|
+
show_exploit = any(exploit_label(f) for f in result.shown)
|
|
74
|
+
if show_exploit:
|
|
75
|
+
table.add_column("Exploit", no_wrap=True)
|
|
76
|
+
if result.imports:
|
|
77
|
+
table.add_column("Found by", overflow="fold")
|
|
78
|
+
for f in result.shown:
|
|
79
|
+
row = [
|
|
80
|
+
f"[{_STYLE[f.severity]}]{f.severity.value}[/]",
|
|
81
|
+
f.package,
|
|
82
|
+
f.installed_version,
|
|
83
|
+
f.advisory_id,
|
|
84
|
+
fix_label(f),
|
|
85
|
+
kind_label(f),
|
|
86
|
+
]
|
|
87
|
+
extra = [via_label(f)] if show_via else []
|
|
88
|
+
if show_exploit:
|
|
89
|
+
extra.append(exploit_label(f))
|
|
90
|
+
if result.imports:
|
|
91
|
+
extra.append(found_by(f))
|
|
92
|
+
table.add_row(*row, *extra)
|
|
93
|
+
console.print(table)
|
|
94
|
+
|
|
95
|
+
counts = Counter(f.severity for f in result.shown)
|
|
96
|
+
parts = [f"{counts[s]} {s.value.lower()}" for s in reversed(Severity) if counts[s]]
|
|
97
|
+
packages = len({f.package for f in result.shown})
|
|
98
|
+
|
|
99
|
+
def plural(n: int, word: str) -> str:
|
|
100
|
+
return f"{n} {word}" + ("" if n == 1 else "s")
|
|
101
|
+
|
|
102
|
+
summary = (
|
|
103
|
+
f"{plural(len(result.shown), 'finding')} in {plural(packages, 'package')}"
|
|
104
|
+
+ (f" ({', '.join(parts)})" if parts else "")
|
|
105
|
+
if result.shown
|
|
106
|
+
else "No findings at or above the threshold."
|
|
107
|
+
)
|
|
108
|
+
extras = []
|
|
109
|
+
if result.ignored:
|
|
110
|
+
extras.append(f"{len(result.ignored)} ignored by config")
|
|
111
|
+
if result.below_threshold:
|
|
112
|
+
extras.append(f"{len(result.below_threshold)} below threshold")
|
|
113
|
+
console.print(summary + (f" · {' · '.join(extras)}" if extras else ""))
|
|
114
|
+
for rule in result.expired_rules:
|
|
115
|
+
console.print(
|
|
116
|
+
f"[yellow]Ignore rule for {rule.id} expired on {rule.expires}; "
|
|
117
|
+
"it no longer hides that finding.[/yellow]"
|
|
118
|
+
)
|
|
119
|
+
for warning in result.warnings:
|
|
120
|
+
console.print(f"[yellow]Warning: {warning}[/yellow]")
|
|
121
|
+
console.print(f"[dim]Raw scanner output: {result.raw_dir}[/dim]")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
_STATUS_STYLE = {
|
|
125
|
+
FixStatus.FIXED_AND_VALIDATED: "green",
|
|
126
|
+
FixStatus.FIXED_NOT_TESTED: "green",
|
|
127
|
+
FixStatus.FIXED_BUT_TESTS_FAILED: "red",
|
|
128
|
+
FixStatus.STILL_PRESENT: "red",
|
|
129
|
+
FixStatus.NO_SAFE_FIX: "yellow",
|
|
130
|
+
FixStatus.FIXED_IN_SOURCE: "cyan",
|
|
131
|
+
FixStatus.OUT_OF_SCOPE: "cyan",
|
|
132
|
+
FixStatus.INTRODUCED: "bold red",
|
|
133
|
+
FixStatus.SKIPPED: "dim",
|
|
134
|
+
FixStatus.ERROR: "bold red",
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def render_plan(outcome: FixOutcome, console: Console) -> None:
|
|
139
|
+
plan = outcome.plan
|
|
140
|
+
if plan is None:
|
|
141
|
+
return
|
|
142
|
+
for warning in plan.warnings:
|
|
143
|
+
console.print(f"[yellow]{warning}[/yellow]")
|
|
144
|
+
resolvable = {u.package: u for u in outcome.resolvable}
|
|
145
|
+
if plan.upgrades:
|
|
146
|
+
table = Table(title="Planned upgrades", header_style="bold", title_justify="left")
|
|
147
|
+
for col in ("Package", "From", "To", "How", "Fixes", "Left", "Resolves"):
|
|
148
|
+
table.add_column(col, no_wrap=col != "Resolves", overflow="fold")
|
|
149
|
+
for u in plan.upgrades:
|
|
150
|
+
r = resolvable.get(u.package)
|
|
151
|
+
how: str = r.method if r else u.method
|
|
152
|
+
if r and r.parents:
|
|
153
|
+
how += f" ({', '.join(r.parents)})"
|
|
154
|
+
table.add_row(
|
|
155
|
+
u.package,
|
|
156
|
+
u.from_version,
|
|
157
|
+
u.to_version,
|
|
158
|
+
how,
|
|
159
|
+
str(len(u.finding_keys)),
|
|
160
|
+
str(len(u.unfixed_keys)) if u.unfixed_keys else "",
|
|
161
|
+
"[green]yes[/green]"
|
|
162
|
+
if r
|
|
163
|
+
else f"[red]no[/red]: {outcome.blocked.get(u.package, '')}",
|
|
164
|
+
)
|
|
165
|
+
console.print(table)
|
|
166
|
+
else:
|
|
167
|
+
console.print("No upgrades to make.")
|
|
168
|
+
if plan.no_fix:
|
|
169
|
+
console.print(f"{len(plan.no_fix)} findings have no safe fix (details in the full run).")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def render_fix(outcome: FixOutcome, console: Console) -> None:
|
|
173
|
+
scan = outcome.scan
|
|
174
|
+
if scan is not None:
|
|
175
|
+
console.print(
|
|
176
|
+
f"[bold]{outcome.display_name or scan.project.root.name}[/bold] · "
|
|
177
|
+
f"{scan.project.manager} · "
|
|
178
|
+
f"worktree of {outcome.ref} @ {(scan.project.commit_sha or '')[:8]}"
|
|
179
|
+
)
|
|
180
|
+
if outcome.dry_run or outcome.report is None:
|
|
181
|
+
render_plan(outcome, console)
|
|
182
|
+
console.print("[dim]Dry run: nothing was tested or changed.[/dim]")
|
|
183
|
+
return
|
|
184
|
+
report = outcome.report
|
|
185
|
+
by_key = {f.key: f for f in [*report.findings_before, *report.findings_after]}
|
|
186
|
+
table = Table(header_style="bold")
|
|
187
|
+
for col in ("Status", "Package", "Advisory", "Change", "Note"):
|
|
188
|
+
table.add_column(col, no_wrap=col in ("Status", "Package", "Advisory"), overflow="fold")
|
|
189
|
+
order = list(FixStatus)
|
|
190
|
+
shown = [r for r in report.results if r.status is not FixStatus.SKIPPED]
|
|
191
|
+
shown.sort(key=lambda r: (order.index(r.status), by_key[r.finding_key].package))
|
|
192
|
+
for r in shown:
|
|
193
|
+
f = by_key[r.finding_key]
|
|
194
|
+
change = f"{r.upgrade.from_version} → {r.upgrade.to_version}" if r.upgrade else ""
|
|
195
|
+
table.add_row(
|
|
196
|
+
f"[{_STATUS_STYLE[r.status]}]{r.status.value}[/]",
|
|
197
|
+
f.package,
|
|
198
|
+
f.advisory_id,
|
|
199
|
+
change,
|
|
200
|
+
r.note,
|
|
201
|
+
)
|
|
202
|
+
console.print(table)
|
|
203
|
+
counts = Counter(r.status for r in report.results)
|
|
204
|
+
console.print(" · ".join(f"{n} {s.value}" for s, n in counts.items()))
|
|
205
|
+
for pkg, changes in outcome.manifest_changes.items():
|
|
206
|
+
for file, old, new in changes:
|
|
207
|
+
console.print(f"{file} ({pkg}): {old} → {new}")
|
|
208
|
+
if outcome.changed:
|
|
209
|
+
console.print(f"Changed files: {', '.join(outcome.changed)}")
|
|
210
|
+
check = outcome.image_check
|
|
211
|
+
if check is not None:
|
|
212
|
+
console.print(
|
|
213
|
+
f"Image check ({', '.join(check.scanners)}): {check.total_before} → "
|
|
214
|
+
f"{check.total_after} findings in the rebuilt image; {len(check.gone)} gone"
|
|
215
|
+
)
|
|
216
|
+
console.print(f"Test runs after the baseline: {outcome.test_runs}")
|
|
217
|
+
if outcome.worktree_path:
|
|
218
|
+
console.print(f"Worktree kept at {outcome.worktree_path}")
|
|
219
|
+
render_publish(outcome, console)
|
|
220
|
+
console.print(f"[dim]Run folder: {outcome.run_dir}[/dim]")
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def render_publish(outcome: FixOutcome, console: Console) -> None:
|
|
224
|
+
sha = (outcome.commit_sha or "")[:8]
|
|
225
|
+
pr = outcome.pr
|
|
226
|
+
if outcome.pr_action == "created" and pr:
|
|
227
|
+
console.print(f"[green]Opened PR #{pr.number}[/green]: {pr.url}")
|
|
228
|
+
elif outcome.pr_action == "updated" and pr:
|
|
229
|
+
console.print(f"[green]Updated PR #{pr.number}[/green] ({sha} pushed): {pr.url}")
|
|
230
|
+
elif outcome.pr_action == "unchanged" and pr:
|
|
231
|
+
console.print(
|
|
232
|
+
f"PR #{pr.number} already has these exact changes; description refreshed: {pr.url}"
|
|
233
|
+
)
|
|
234
|
+
elif outcome.pr_action == "local":
|
|
235
|
+
console.print(
|
|
236
|
+
f"--no-push: committed {sha} on local branch '{outcome.branch}'; nothing pushed."
|
|
237
|
+
)
|
|
238
|
+
console.print(f"PR title: {outcome.pr_title}")
|
|
239
|
+
console.print(f"PR body: {outcome.body_path}")
|
|
240
|
+
if outcome.pr_note:
|
|
241
|
+
console.print(f"[yellow]{outcome.pr_note}[/yellow]")
|
|
242
|
+
for warning in outcome.warnings:
|
|
243
|
+
console.print(f"[yellow]Warning: {warning}[/yellow]")
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Machine-readable `scan` output (`fix` writes its RunReport to the run folder)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from patchloop.scanner import ScanResult
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def write_scan_json(result: ScanResult, path: Path) -> None:
|
|
12
|
+
payload = {
|
|
13
|
+
"run_id": result.run_id,
|
|
14
|
+
"project": result.project.root.name,
|
|
15
|
+
"manager": result.project.manager,
|
|
16
|
+
"commit_sha": result.project.commit_sha,
|
|
17
|
+
"tool_versions": result.tool_versions,
|
|
18
|
+
"findings": [f.model_dump(mode="json") for f in result.shown],
|
|
19
|
+
"ignored": [
|
|
20
|
+
{"finding_key": f.key, "rule": r.id, "reason": r.reason} for f, r in result.ignored
|
|
21
|
+
],
|
|
22
|
+
"below_threshold": [f.key for f in result.below_threshold],
|
|
23
|
+
"expired_ignore_rules": [r.id for r in result.expired_rules],
|
|
24
|
+
"warnings": result.warnings,
|
|
25
|
+
}
|
|
26
|
+
path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""SARIF 2.1.0 output, for GitHub code scanning and other SARIF viewers.
|
|
2
|
+
|
|
3
|
+
One rule per advisory, one result per finding. Each result points at the package's entry
|
|
4
|
+
in the lockfile; findings that exist only in an image point at the lockfile without a line.
|
|
5
|
+
``partialFingerprints`` carries the finding key, so a finding keeps its identity across runs.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from patchloop import __version__
|
|
16
|
+
from patchloop.models import Finding, FixResult, FixStatus, Severity
|
|
17
|
+
from patchloop.prioritize import gate_severity
|
|
18
|
+
|
|
19
|
+
SCHEMA = (
|
|
20
|
+
"https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json"
|
|
21
|
+
)
|
|
22
|
+
_OSV = "https://osv.dev/vulnerability/"
|
|
23
|
+
# GitHub reads security-severity (a CVSS-like 0-10 string) to bucket alerts.
|
|
24
|
+
_SECURITY_SEVERITY = {
|
|
25
|
+
Severity.CRITICAL: "9.5",
|
|
26
|
+
Severity.HIGH: "8.0",
|
|
27
|
+
Severity.MEDIUM: "5.5",
|
|
28
|
+
Severity.LOW: "2.0",
|
|
29
|
+
}
|
|
30
|
+
_LEVEL = {
|
|
31
|
+
Severity.CRITICAL: "error",
|
|
32
|
+
Severity.HIGH: "error",
|
|
33
|
+
Severity.MEDIUM: "warning",
|
|
34
|
+
Severity.LOW: "note",
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _package_lines(lockfile: Path) -> dict[str, int]:
|
|
39
|
+
"""1-based line of each ``name = "pkg"`` entry in a uv.lock / poetry.lock."""
|
|
40
|
+
lines: dict[str, int] = {}
|
|
41
|
+
try:
|
|
42
|
+
text = lockfile.read_text("utf-8")
|
|
43
|
+
except OSError:
|
|
44
|
+
return lines
|
|
45
|
+
for i, line in enumerate(text.splitlines(), start=1):
|
|
46
|
+
m = re.match(r'^name = "([^"]+)"', line)
|
|
47
|
+
if m:
|
|
48
|
+
lines.setdefault(m.group(1).lower().replace("_", "-").replace(".", "-"), i)
|
|
49
|
+
return lines
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _rule(f: Finding) -> dict[str, Any]:
|
|
53
|
+
sev = gate_severity(f)
|
|
54
|
+
score = f"{f.cvss:.1f}" if f.cvss is not None else _SECURITY_SEVERITY[sev]
|
|
55
|
+
return {
|
|
56
|
+
"id": f.advisory_id,
|
|
57
|
+
"name": f.advisory_id.replace("-", ""),
|
|
58
|
+
"shortDescription": {"text": f"{f.advisory_id} in {f.package}"},
|
|
59
|
+
"helpUri": f"{_OSV}{f.advisory_id}",
|
|
60
|
+
"help": {"text": f"See {_OSV}{f.advisory_id}. Aliases: {', '.join(f.aliases)}."},
|
|
61
|
+
"properties": {
|
|
62
|
+
"security-severity": score,
|
|
63
|
+
"tags": ["security", "vulnerability", "dependency"],
|
|
64
|
+
},
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _message(f: Finding, status: FixResult | None) -> str:
|
|
69
|
+
fixed = f"; fixed in {f.fixed_versions[0]}" if f.fixed_versions else "; no fixed version"
|
|
70
|
+
text = f"{f.package} {f.installed_version} is affected by {f.advisory_id}{fixed}."
|
|
71
|
+
image = next((h.target for h in f.sources if h.target.startswith("image:")), None)
|
|
72
|
+
if image and not f.in_lockfile:
|
|
73
|
+
text += f" Found in {image.removeprefix('image:')}, not in the lockfile."
|
|
74
|
+
if status is not None:
|
|
75
|
+
text += f" PatchLoop: {status.status.value}" + (f" ({status.note})" if status.note else "")
|
|
76
|
+
return text
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def build_sarif(
|
|
80
|
+
findings: list[Finding],
|
|
81
|
+
lockfile: Path,
|
|
82
|
+
lockfile_uri: str,
|
|
83
|
+
statuses: dict[str, FixResult] | None = None,
|
|
84
|
+
) -> dict[str, Any]:
|
|
85
|
+
lines = _package_lines(lockfile)
|
|
86
|
+
rules: dict[str, dict[str, Any]] = {}
|
|
87
|
+
results = []
|
|
88
|
+
for f in findings:
|
|
89
|
+
rules.setdefault(f.advisory_id, _rule(f))
|
|
90
|
+
region = {"startLine": lines[f.package]} if f.in_lockfile and f.package in lines else None
|
|
91
|
+
physical: dict[str, Any] = {"artifactLocation": {"uri": lockfile_uri}}
|
|
92
|
+
if region:
|
|
93
|
+
physical["region"] = region
|
|
94
|
+
status = (statuses or {}).get(f.key)
|
|
95
|
+
results.append(
|
|
96
|
+
{
|
|
97
|
+
"ruleId": f.advisory_id,
|
|
98
|
+
"level": _LEVEL[gate_severity(f)],
|
|
99
|
+
"message": {"text": _message(f, status)},
|
|
100
|
+
"locations": [{"physicalLocation": physical}],
|
|
101
|
+
"partialFingerprints": {"patchloopFindingKey/v1": f.key},
|
|
102
|
+
"properties": {
|
|
103
|
+
"package": f.package,
|
|
104
|
+
"installedVersion": f.installed_version,
|
|
105
|
+
"fixedVersions": f.fixed_versions,
|
|
106
|
+
"severity": f.severity.value,
|
|
107
|
+
"kev": f.in_kev,
|
|
108
|
+
"epss": f.epss,
|
|
109
|
+
"sources": sorted({h.tool for h in f.sources}),
|
|
110
|
+
**({"status": status.status.value} if status else {}),
|
|
111
|
+
},
|
|
112
|
+
}
|
|
113
|
+
)
|
|
114
|
+
return {
|
|
115
|
+
"$schema": SCHEMA,
|
|
116
|
+
"version": "2.1.0",
|
|
117
|
+
"runs": [
|
|
118
|
+
{
|
|
119
|
+
"tool": {
|
|
120
|
+
"driver": {
|
|
121
|
+
"name": "PatchLoop",
|
|
122
|
+
"semanticVersion": __version__.split(".dev")[0],
|
|
123
|
+
"rules": list(rules.values()),
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
"results": results,
|
|
127
|
+
}
|
|
128
|
+
],
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def remaining(findings: list[Finding], results: list[FixResult]) -> list[Finding]:
|
|
133
|
+
"""After a fix run: the findings still open (not fixed, not skipped)."""
|
|
134
|
+
open_keys = {
|
|
135
|
+
r.finding_key
|
|
136
|
+
for r in results
|
|
137
|
+
if not r.status.counts_as_fixed and r.status is not FixStatus.SKIPPED
|
|
138
|
+
}
|
|
139
|
+
return [f for f in findings if f.key in open_keys]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def write_sarif(payload: dict[str, Any], path: Path) -> None:
|
|
143
|
+
path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
|