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.
Files changed (56) hide show
  1. patchloop/__init__.py +23 -0
  2. patchloop/api.py +110 -0
  3. patchloop/build.py +118 -0
  4. patchloop/classify.py +137 -0
  5. patchloop/cli.py +370 -0
  6. patchloop/config.py +148 -0
  7. patchloop/detect.py +133 -0
  8. patchloop/doctor.py +207 -0
  9. patchloop/enrich/__init__.py +66 -0
  10. patchloop/enrich/epss.py +65 -0
  11. patchloop/enrich/kev.py +39 -0
  12. patchloop/fixers/__init__.py +1 -0
  13. patchloop/fixers/base.py +20 -0
  14. patchloop/fixers/js_fix.py +288 -0
  15. patchloop/fixers/poetry_fix.py +144 -0
  16. patchloop/fixers/uv_fix.py +118 -0
  17. patchloop/git_ops.py +171 -0
  18. patchloop/github.py +161 -0
  19. patchloop/hints.py +180 -0
  20. patchloop/images.py +208 -0
  21. patchloop/isolate.py +57 -0
  22. patchloop/js/__init__.py +1 -0
  23. patchloop/js/lockfiles.py +237 -0
  24. patchloop/js/manifest.py +121 -0
  25. patchloop/js/ranges.py +130 -0
  26. patchloop/js/registry.py +67 -0
  27. patchloop/js/yarn.py +189 -0
  28. patchloop/lockgraph.py +181 -0
  29. patchloop/models.py +248 -0
  30. patchloop/plan.py +194 -0
  31. patchloop/pr_body.py +253 -0
  32. patchloop/prioritize.py +38 -0
  33. patchloop/proc.py +71 -0
  34. patchloop/py.typed +0 -0
  35. patchloop/pypi.py +60 -0
  36. patchloop/report/__init__.py +1 -0
  37. patchloop/report/console.py +243 -0
  38. patchloop/report/json_out.py +26 -0
  39. patchloop/report/sarif.py +143 -0
  40. patchloop/runner.py +494 -0
  41. patchloop/scanner.py +214 -0
  42. patchloop/sources/__init__.py +1 -0
  43. patchloop/sources/base.py +5 -0
  44. patchloop/sources/imports.py +292 -0
  45. patchloop/sources/merge.py +113 -0
  46. patchloop/sources/osv.py +255 -0
  47. patchloop/specifiers.py +259 -0
  48. patchloop/validate.py +198 -0
  49. patchloop/versions.py +81 -0
  50. patchloop/workspaces.py +142 -0
  51. patchloop/worktree.py +153 -0
  52. patchloop-0.2.0.dist-info/METADATA +388 -0
  53. patchloop-0.2.0.dist-info/RECORD +56 -0
  54. patchloop-0.2.0.dist-info/WHEEL +4 -0
  55. patchloop-0.2.0.dist-info/entry_points.txt +3 -0
  56. patchloop-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1 @@
1
+ """Finding sources: scanners PatchLoop runs, and files it imports."""
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class SourceError(Exception):
5
+ """A scanner failed or produced output PatchLoop cannot read."""
@@ -0,0 +1,292 @@
1
+ """Trivy and Wiz JSON files, scanned elsewhere (a repo or a container image), merged in.
2
+
3
+ Each vulnerability becomes a Finding for the package *as the lockfile has it*:
4
+
5
+ - a Python package the lockfile holds -> installed_version is the lockfile's version; if
6
+ that version is no longer affected, the finding is ``fixed_in_source`` (the image was
7
+ built before the fix: FIXED_IN_SOURCE);
8
+ - an OS package, another language, or a Python package the lockfile does not hold ->
9
+ ``in_lockfile=False`` (OUT_OF_SCOPE).
10
+
11
+ Secret findings in either format are skipped: never parsed, printed or stored, and the
12
+ import file itself is never copied into the run folder.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+ from typing import Any, Literal
21
+
22
+ from packaging.version import InvalidVersion, Version
23
+
24
+ from patchloop.models import (
25
+ Finding,
26
+ Severity,
27
+ SourceHit,
28
+ VersionRange,
29
+ finding_key,
30
+ normalize_package,
31
+ )
32
+ from patchloop.sources.base import SourceError
33
+ from patchloop.sources.osv import preferred_id
34
+ from patchloop.versions import is_affected, parse, sort_versions
35
+
36
+ Tool = Literal["trivy", "wiz"]
37
+ Kind = Literal["repo", "image"]
38
+
39
+ # Trivy 0.69.4 to 0.69.6 were malicious releases (supply-chain compromise, March 2026).
40
+ _BAD_TRIVY = (Version("0.69.4"), Version("0.69.6"))
41
+ _TRIVY_PYTHON = {"python-pkg", "pip", "pipenv", "poetry", "uv", "conda-pkg"}
42
+ _PY_MARKERS = (".dist-info", ".egg-info", "site-packages", "dist-packages")
43
+ _PY_FILES = ("uv.lock", "poetry.lock", "requirements.txt", "pipfile.lock", "pyproject.toml")
44
+ _TRIVY_NODE = {"node-pkg", "npm", "yarn", "pnpm", "bun"}
45
+ _JS_FILES = ("package-lock.json", "yarn.lock", "pnpm-lock.yaml", "package.json")
46
+
47
+
48
+ class ImportFileError(SourceError):
49
+ """An import file is missing, unreadable, or not a format PatchLoop knows."""
50
+
51
+
52
+ @dataclass
53
+ class ImportedFile:
54
+ path: Path
55
+ tool: Tool
56
+ kind: Kind
57
+ target: str
58
+ """"source" for a repo scan, "image:<name>" for an image."""
59
+ tool_version: str | None
60
+ findings: list[Finding] = field(default_factory=list)
61
+ warnings: list[str] = field(default_factory=list)
62
+
63
+
64
+ def detect_format(data: Any) -> tuple[Tool, Kind]:
65
+ if isinstance(data, dict) and "SchemaVersion" in data and "Results" in data:
66
+ return "trivy", "image" if data.get("ArtifactType") == "container_image" else "repo"
67
+ if isinstance(data, dict) and isinstance(data.get("result"), dict) and "status" in data:
68
+ origin = str((data.get("scanOriginResource") or {}).get("__typename", ""))
69
+ result = data["result"]
70
+ is_image = "ContainerImage" in origin or (not origin and bool(result.get("osPackages")))
71
+ return "wiz", "image" if is_image else "repo"
72
+ raise ImportFileError("not a Trivy or Wiz JSON report")
73
+
74
+
75
+ _LOWEST = {"INFORMATIONAL", "INFO", "NONE", "NEGLIGIBLE"}
76
+
77
+
78
+ def _severity(text: object) -> Severity:
79
+ label = str(text).upper()
80
+ if label in _LOWEST:
81
+ return Severity.LOW # not "unrated": those count as HIGH
82
+ try:
83
+ return Severity(label)
84
+ except ValueError:
85
+ return Severity.UNKNOWN
86
+
87
+
88
+ def _fixed_list(text: object) -> list[str]:
89
+ parts = [p.strip() for p in str(text or "").replace(";", ",").split(",")]
90
+ return [p for p in parts if p]
91
+
92
+
93
+ def _ranges_from_fixed(fixed: list[str]) -> list[VersionRange]:
94
+ """Approximate affected ranges from fixed versions on several release lines.
95
+
96
+ "1.26.19, 2.2.2" -> [0, 1.26.19) and [2, 2.2.2): each later line starts at its major.
97
+ """
98
+ parsed: list[tuple[Version, str]] = []
99
+ for f in fixed:
100
+ try:
101
+ parsed.append((Version(f), f))
102
+ except InvalidVersion:
103
+ continue
104
+ parsed.sort()
105
+ ranges = []
106
+ for i, (v, text) in enumerate(parsed):
107
+ start = "0" if i == 0 else str(v.major)
108
+ ranges.append(VersionRange(introduced=start, fixed=text))
109
+ return ranges
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class _Vuln:
114
+ ecosystem: str
115
+ package: str
116
+ version: str
117
+ advisory: str
118
+ severity: Severity
119
+ fixed: list[str]
120
+ score: float | None = None
121
+ epss: float | None = None
122
+ kev: bool = False
123
+ references: tuple[str, ...] = ()
124
+
125
+
126
+ def _trivy_vulns(data: dict[str, Any]) -> list[_Vuln]:
127
+ out: list[_Vuln] = []
128
+ for result in data.get("Results") or []:
129
+ kind = str(result.get("Type", ""))
130
+ if result.get("Class") == "os-pkgs":
131
+ ecosystem = "os" # same label as Wiz, so the two merge
132
+ else:
133
+ if kind in _TRIVY_PYTHON:
134
+ ecosystem = "PyPI"
135
+ elif kind in _TRIVY_NODE:
136
+ ecosystem = "npm"
137
+ else:
138
+ ecosystem = kind or "unknown"
139
+ for v in result.get("Vulnerabilities") or []: # result["Secrets"] is never read
140
+ scores = [
141
+ float(s["V3Score"])
142
+ for s in (v.get("CVSS") or {}).values()
143
+ if isinstance(s, dict) and s.get("V3Score") is not None
144
+ ]
145
+ out.append(
146
+ _Vuln(
147
+ ecosystem=ecosystem,
148
+ package=str(v.get("PkgName", "")),
149
+ version=str(v.get("InstalledVersion", "")),
150
+ advisory=str(v.get("VulnerabilityID", "")),
151
+ severity=_severity(v.get("Severity")),
152
+ fixed=_fixed_list(v.get("FixedVersion")),
153
+ score=max(scores) if scores else None,
154
+ references=tuple(str(r) for r in (v.get("References") or [])[:5]),
155
+ )
156
+ )
157
+ return out
158
+
159
+
160
+ def _wiz_ecosystem(path: str) -> str:
161
+ low = path.lower()
162
+ if any(m in low for m in _PY_MARKERS) or low.endswith(_PY_FILES):
163
+ return "PyPI"
164
+ if "node_modules" in low or low.endswith(_JS_FILES):
165
+ return "npm"
166
+ return "unknown"
167
+
168
+
169
+ def _wiz_vulns(data: dict[str, Any]) -> list[_Vuln]:
170
+ result = data.get("result") or {}
171
+ groups = [
172
+ *[(p, "os") for p in result.get("osPackages") or []],
173
+ *[(p, _wiz_ecosystem(str(p.get("path", "")))) for p in result.get("libraries") or []],
174
+ *[(p, "cpe") for p in result.get("cpes") or []],
175
+ ] # result["secrets"] is never read
176
+ out: list[_Vuln] = []
177
+ for pkg, ecosystem in groups:
178
+ for v in pkg.get("vulnerabilities") or []:
179
+ epss = v.get("epssProbability")
180
+ out.append(
181
+ _Vuln(
182
+ ecosystem=ecosystem,
183
+ package=str(pkg.get("name", "")),
184
+ version=str(pkg.get("version", "")),
185
+ advisory=str(v.get("name", "")),
186
+ severity=_severity(v.get("severity")),
187
+ fixed=_fixed_list(v.get("fixedVersion")),
188
+ score=v.get("score"),
189
+ # Wiz gives EPSS in percent (0.5 = 0.5 %); PatchLoop uses 0-1 like FIRST.
190
+ epss=float(epss) / 100 if epss is not None else None,
191
+ kev=bool(v.get("hasCisaKevExploit")),
192
+ references=(str(v["source"]),) if v.get("source") else (),
193
+ )
194
+ )
195
+ return out
196
+
197
+
198
+ def _trivy_version(data: dict[str, Any]) -> str | None:
199
+ version = (data.get("Trivy") or {}).get("Version")
200
+ return str(version) if version else None
201
+
202
+
203
+ def _to_finding(
204
+ v: _Vuln,
205
+ tool: Tool,
206
+ tool_version: str | None,
207
+ source: str,
208
+ target: str,
209
+ lock: dict[str, str],
210
+ lock_ecosystem: str,
211
+ ) -> Finding:
212
+ if v.ecosystem in ("PyPI", "npm"):
213
+ name = normalize_package(v.package, v.ecosystem)
214
+ else:
215
+ name = v.package
216
+ hit = SourceHit(
217
+ source=source,
218
+ tool=tool,
219
+ tool_version=tool_version,
220
+ target=target,
221
+ raw_id=v.advisory,
222
+ severity=v.severity,
223
+ installed_version=v.version,
224
+ fixed_version=v.fixed[0] if v.fixed else None,
225
+ )
226
+ locked = lock.get(name) if v.ecosystem == lock_ecosystem else None
227
+ installed = locked or v.version
228
+ # Scanners list fixes on every release line; only those above the installed one count.
229
+ current = parse(installed)
230
+ fixed = sort_versions(
231
+ [x for x in v.fixed if current is None or ((p := parse(x)) is not None and p > current)]
232
+ )
233
+ severity = v.severity if v.severity is not Severity.UNKNOWN else Severity.from_cvss(v.score)
234
+ finding = Finding(
235
+ key=finding_key(v.ecosystem, name, [v.advisory]),
236
+ advisory_id=preferred_id([v.advisory]),
237
+ aliases=[v.advisory],
238
+ ecosystem=v.ecosystem,
239
+ package=name,
240
+ installed_version=installed,
241
+ fixed_versions=fixed,
242
+ affected_ranges=_ranges_from_fixed(v.fixed),
243
+ in_lockfile=locked is not None,
244
+ severity=severity,
245
+ cvss=v.score,
246
+ epss=v.epss,
247
+ in_kev=v.kev,
248
+ references=list(v.references),
249
+ sources=[hit],
250
+ )
251
+ if locked is not None and locked != v.version and not is_affected(locked, finding):
252
+ finding.fixed_in_source = True
253
+ return finding
254
+
255
+
256
+ def load_import(path: Path, lock: dict[str, str], lock_ecosystem: str = "PyPI") -> ImportedFile:
257
+ """Parse one Trivy / Wiz JSON file and map it onto the lockfile ``lock``."""
258
+ try:
259
+ data = json.loads(path.read_text(encoding="utf-8"))
260
+ except OSError as exc:
261
+ raise ImportFileError(f"cannot read import file {path}: {exc.strerror}") from exc
262
+ except json.JSONDecodeError as exc:
263
+ raise ImportFileError(f"import file {path} is not valid JSON") from exc
264
+ try:
265
+ tool, kind = detect_format(data)
266
+ except ImportFileError as exc:
267
+ raise ImportFileError(f"{path}: {exc}") from exc
268
+
269
+ warnings: list[str] = []
270
+ if tool == "trivy":
271
+ tool_version = _trivy_version(data)
272
+ vulns = _trivy_vulns(data)
273
+ name = str(data.get("ArtifactName", "")) or path.name
274
+ v = parse(tool_version) if tool_version else None # e.g. "dev" from a source build
275
+ if v is not None and _BAD_TRIVY[0] <= v <= _BAD_TRIVY[1]:
276
+ warnings.append(
277
+ f"{path.name} was made by Trivy {tool_version}, a compromised release; "
278
+ "rescan with a safe Trivy version before trusting it"
279
+ )
280
+ else:
281
+ tool_version = (data.get("extraInfo") or {}).get("clientVersion")
282
+ vulns = _wiz_vulns(data)
283
+ name = str((data.get("scanOriginResource") or {}).get("name", "")) or path.name
284
+
285
+ target = f"image:{name}" if kind == "image" else "source"
286
+ source = f"import:{path.name}"
287
+ findings = [
288
+ _to_finding(v, tool, tool_version, source, target, lock, lock_ecosystem)
289
+ for v in vulns
290
+ if v.package and v.advisory
291
+ ]
292
+ return ImportedFile(path, tool, kind, target, tool_version, findings, warnings)
@@ -0,0 +1,113 @@
1
+ """Merge findings from all sources and attach dependency information.
2
+
3
+ Two findings are the same issue when they are for the same package (and installed
4
+ version) and their advisory IDs overlap, followed transitively: if A shares an ID with
5
+ B and B with C, all three are one finding.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections import defaultdict
11
+
12
+ from packaging.version import InvalidVersion, Version
13
+
14
+ from patchloop.lockgraph import LockGraph
15
+ from patchloop.models import Finding, finding_key, normalize_package
16
+ from patchloop.sources.osv import preferred_id
17
+
18
+
19
+ def _sort_versions(versions: set[str]) -> list[str]:
20
+ def key(v: str) -> tuple[int, Version | str]:
21
+ try:
22
+ return (0, Version(v))
23
+ except InvalidVersion:
24
+ return (1, v)
25
+
26
+ return sorted(versions, key=key)
27
+
28
+
29
+ def _combine(items: list[Finding]) -> Finding:
30
+ first = items[0]
31
+ aliases = sorted({a for f in items for a in f.aliases})
32
+ severity = max((f.severity for f in items), key=lambda s: s.rank)
33
+ scores = [f.cvss for f in items if f.cvss is not None]
34
+ epss = [f.epss for f in items if f.epss is not None]
35
+ refs: dict[str, None] = {}
36
+ for f in items:
37
+ for r in f.references:
38
+ refs.setdefault(r, None)
39
+ return first.model_copy(
40
+ update={
41
+ "key": finding_key(first.ecosystem, first.package, aliases),
42
+ "advisory_id": preferred_id(aliases),
43
+ "aliases": aliases,
44
+ "fixed_versions": _sort_versions({v for f in items for v in f.fixed_versions}),
45
+ # A version counts as affected if any source says so (conservative).
46
+ "affected_ranges": list(
47
+ {
48
+ (r.introduced, r.fixed, r.last_affected): r
49
+ for f in items
50
+ for r in f.affected_ranges
51
+ }.values()
52
+ ),
53
+ "in_lockfile": any(f.in_lockfile for f in items),
54
+ # Fixed in source only if no source (e.g. OSV on the lockfile) still sees it there.
55
+ "fixed_in_source": all(f.fixed_in_source for f in items),
56
+ "in_kev": any(f.in_kev for f in items),
57
+ "epss": max(epss) if epss else None,
58
+ "severity": severity,
59
+ "cvss": max(scores) if scores else None,
60
+ "references": list(refs),
61
+ "sources": [s for f in items for s in f.sources],
62
+ }
63
+ )
64
+
65
+
66
+ def merge_findings(findings: list[Finding]) -> list[Finding]:
67
+ buckets: dict[tuple[str, str, str], list[Finding]] = defaultdict(list)
68
+ for f in findings:
69
+ buckets[
70
+ (f.ecosystem, normalize_package(f.package, f.ecosystem), f.installed_version)
71
+ ].append(f)
72
+
73
+ merged: list[Finding] = []
74
+ for items in buckets.values():
75
+ merged.extend(_combine(group) for group in _alias_groups(items))
76
+ return merged
77
+
78
+
79
+ def _find(parent: list[int], i: int) -> int:
80
+ while parent[i] != i:
81
+ parent[i] = parent[parent[i]]
82
+ i = parent[i]
83
+ return i
84
+
85
+
86
+ def _alias_groups(items: list[Finding]) -> list[list[Finding]]:
87
+ """Union-find over shared advisory IDs."""
88
+ parent = list(range(len(items)))
89
+ owner: dict[str, int] = {}
90
+ for i, f in enumerate(items):
91
+ for alias in f.aliases:
92
+ if alias in owner:
93
+ parent[_find(parent, i)] = _find(parent, owner[alias])
94
+ else:
95
+ owner[alias] = i
96
+ groups: dict[int, list[Finding]] = defaultdict(list)
97
+ for i, f in enumerate(items):
98
+ groups[_find(parent, i)].append(f)
99
+ return list(groups.values())
100
+
101
+
102
+ def annotate(findings: list[Finding], graph: LockGraph) -> list[Finding]:
103
+ """Mark direct / dev-only and record how each vulnerable package is pulled in."""
104
+ return [
105
+ f.model_copy(
106
+ update={
107
+ "is_direct": graph.is_direct(f.package),
108
+ "dev_only": graph.is_dev_only(f.package),
109
+ "dependency_paths": graph.paths_to(f.package),
110
+ }
111
+ )
112
+ for f in findings
113
+ ]
@@ -0,0 +1,255 @@
1
+ """OSV-Scanner adapter: run it on the lockfile and turn its JSON into findings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from collections.abc import Iterable
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from packaging.version import InvalidVersion, Version
12
+
13
+ from patchloop import proc
14
+ from patchloop.doctor import parse_version
15
+ from patchloop.models import (
16
+ Finding,
17
+ Project,
18
+ Severity,
19
+ SourceHit,
20
+ VersionRange,
21
+ finding_key,
22
+ normalize_package,
23
+ )
24
+ from patchloop.proc import Runner, ToolNotFoundError, ToolTimeoutError
25
+ from patchloop.sources.base import SourceError
26
+
27
+ TOOL = "osv-scanner"
28
+ EXIT_NO_VULNS = 0
29
+ EXIT_VULNS_FOUND = 1
30
+ SCAN_TIMEOUT_S = 300
31
+ OFFLINE_TIMEOUT_S = 1200
32
+ """With the offline database, a scan may first download or refresh it (npm's is ~213 MB),
33
+ which takes minutes on a slow connection."""
34
+ MAX_REFERENCES = 10
35
+
36
+ _GHSA_SEVERITY = {
37
+ "LOW": Severity.LOW,
38
+ "MODERATE": Severity.MEDIUM,
39
+ "MEDIUM": Severity.MEDIUM,
40
+ "HIGH": Severity.HIGH,
41
+ "CRITICAL": Severity.CRITICAL,
42
+ }
43
+ _ID_PREFERENCE = ("CVE-", "GHSA-", "PYSEC-")
44
+
45
+
46
+ def preferred_id(ids: Iterable[str]) -> str:
47
+ """CVE first, then GHSA, then PYSEC, then anything else; lowest within a kind."""
48
+ ordered = sorted(set(ids))
49
+ for prefix in _ID_PREFERENCE:
50
+ for advisory in ordered:
51
+ if advisory.startswith(prefix):
52
+ return advisory
53
+ return ordered[0]
54
+
55
+
56
+ def _version(text: str) -> Version | None:
57
+ try:
58
+ return Version(text)
59
+ except InvalidVersion:
60
+ return None
61
+
62
+
63
+ SUPPORTED_ECOSYSTEMS = frozenset({"PyPI", "npm"})
64
+
65
+
66
+ def _ranges(vuln: dict[str, Any], package: str, ecosystem: str = "PyPI") -> list[VersionRange]:
67
+ """OSV ECOSYSTEM events -> intervals. Events alternate introduced / fixed (or last_affected)."""
68
+ out: list[VersionRange] = []
69
+ for affected in vuln.get("affected", []):
70
+ pkg = affected.get("package", {})
71
+ if pkg.get("ecosystem") != ecosystem or (
72
+ normalize_package(pkg.get("name", ""), ecosystem) != package
73
+ ):
74
+ continue
75
+ for rng in affected.get("ranges", []):
76
+ if rng.get("type") not in ("ECOSYSTEM", "SEMVER"):
77
+ continue
78
+ current: VersionRange | None = None
79
+ for event in rng.get("events", []):
80
+ if "introduced" in event:
81
+ if current is not None:
82
+ out.append(current)
83
+ current = VersionRange(introduced=event["introduced"])
84
+ elif "fixed" in event:
85
+ out.append(
86
+ (current or VersionRange()).model_copy(update={"fixed": event["fixed"]})
87
+ )
88
+ current = None
89
+ elif "last_affected" in event:
90
+ out.append(
91
+ (current or VersionRange()).model_copy(
92
+ update={"last_affected": event["last_affected"]}
93
+ )
94
+ )
95
+ current = None
96
+ if current is not None:
97
+ out.append(current)
98
+ return out
99
+
100
+
101
+ def _dedupe(ranges: list[VersionRange]) -> list[VersionRange]:
102
+ seen: dict[tuple[str, str | None, str | None], VersionRange] = {}
103
+ for r in ranges:
104
+ seen.setdefault((r.introduced, r.fixed, r.last_affected), r)
105
+ return list(seen.values())
106
+
107
+
108
+ def _sorted_versions(versions: Iterable[str]) -> list[str]:
109
+ parsed = [(pv, v) for v in set(versions) if (pv := _version(v)) is not None]
110
+ return [v for _, v in sorted(parsed)]
111
+
112
+
113
+ def _severity(group: dict[str, Any], vulns: list[dict[str, Any]]) -> tuple[Severity, float | None]:
114
+ raw = str(group.get("max_severity") or "").strip()
115
+ try:
116
+ score = float(raw) if raw else None
117
+ except ValueError:
118
+ score = None
119
+ if score is not None:
120
+ return Severity.from_cvss(score), score
121
+ best = Severity.UNKNOWN
122
+ for vuln in vulns:
123
+ label = str((vuln.get("database_specific") or {}).get("severity", "")).upper()
124
+ sev = _GHSA_SEVERITY.get(label, Severity.UNKNOWN)
125
+ if sev.rank > best.rank:
126
+ best = sev
127
+ return best, None
128
+
129
+
130
+ def _references(vulns: list[dict[str, Any]]) -> list[str]:
131
+ refs = [r for v in vulns for r in v.get("references", []) if r.get("url")]
132
+ refs.sort(key=lambda r: r.get("type") != "ADVISORY")
133
+ seen: dict[str, None] = {}
134
+ for ref in refs:
135
+ seen.setdefault(ref["url"], None)
136
+ return list(seen)[:MAX_REFERENCES]
137
+
138
+
139
+ def parse_osv_json(data: dict[str, Any], tool_version: str | None = None) -> list[Finding]:
140
+ """Turn ``osv-scanner --format json`` output into one Finding per advisory group."""
141
+ findings: list[Finding] = []
142
+ for result in data.get("results") or []:
143
+ for entry in result.get("packages") or []:
144
+ pkg = entry["package"]
145
+ ecosystem = str(pkg.get("ecosystem"))
146
+ if ecosystem not in SUPPORTED_ECOSYSTEMS:
147
+ continue
148
+ name = normalize_package(pkg["name"], ecosystem)
149
+ installed = pkg["version"]
150
+ installed_v = _version(installed)
151
+ vulns_by_id = {v["id"]: v for v in entry.get("vulnerabilities") or []}
152
+ groups = entry.get("groups") or [{"ids": [i]} for i in vulns_by_id]
153
+ for group in groups:
154
+ vulns = [vulns_by_id[i] for i in group.get("ids", []) if i in vulns_by_id]
155
+ aliases = set(group.get("ids", [])) | set(group.get("aliases", []))
156
+ for vuln in vulns:
157
+ aliases.update(vuln.get("aliases", []))
158
+ if not aliases:
159
+ continue
160
+ ranges = [r for vuln in vulns for r in _ranges(vuln, name, ecosystem)]
161
+ fixed = {r.fixed for r in ranges if r.fixed is not None}
162
+ relevant = [
163
+ f
164
+ for f in _sorted_versions(fixed)
165
+ if installed_v is None or (_version(f) or installed_v) > installed_v
166
+ ]
167
+ severity, score = _severity(group, vulns)
168
+ alias_list = sorted(aliases)
169
+ hit = SourceHit(
170
+ source="osv",
171
+ tool=TOOL,
172
+ tool_version=tool_version,
173
+ target="source",
174
+ raw_id=group.get("ids", alias_list)[0],
175
+ severity=severity,
176
+ installed_version=installed,
177
+ fixed_version=relevant[0] if relevant else None,
178
+ )
179
+ findings.append(
180
+ Finding(
181
+ key=finding_key(ecosystem, name, alias_list),
182
+ advisory_id=preferred_id(alias_list),
183
+ aliases=alias_list,
184
+ ecosystem=ecosystem,
185
+ package=name,
186
+ installed_version=installed,
187
+ fixed_versions=relevant,
188
+ affected_ranges=_dedupe(ranges),
189
+ in_lockfile=True,
190
+ severity=severity,
191
+ cvss=score,
192
+ references=_references(vulns),
193
+ sources=[hit],
194
+ )
195
+ )
196
+ return findings
197
+
198
+
199
+ class OsvSource:
200
+ name = "osv"
201
+
202
+ def __init__(
203
+ self, raw_dir: Path, run: Runner | None = None, offline_db: Path | None = None
204
+ ) -> None:
205
+ """``offline_db``: match against a local copy of the OSV database kept there, so no
206
+ package names or versions are sent anywhere (only the database is downloaded)."""
207
+ self.raw_dir = raw_dir
208
+ self._run = run
209
+ self.offline_db = offline_db
210
+
211
+ def _exec(self, cmd: list[str], cwd: Path | None = None) -> proc.ProcResult:
212
+ if self._run is not None:
213
+ return self._run(cmd)
214
+ env = None
215
+ if self.offline_db is not None:
216
+ env = {**os.environ, "OSV_SCANNER_LOCAL_DB_CACHE_DIRECTORY": str(self.offline_db)}
217
+ return proc.run(cmd, cwd=cwd, timeout=self.timeout, env=env)
218
+
219
+ @property
220
+ def timeout(self) -> int:
221
+ return OFFLINE_TIMEOUT_S if self.offline_db is not None else SCAN_TIMEOUT_S
222
+
223
+ def tool_version(self) -> str | None:
224
+ try:
225
+ result = self._exec([TOOL, "--version"])
226
+ except (ToolNotFoundError, ToolTimeoutError):
227
+ return None
228
+ return parse_version(result.stdout) if result.ok else None
229
+
230
+ def collect(self, project: Project) -> list[Finding]:
231
+ cmd = [TOOL, "scan", "source", "-L", str(project.lockfile), "--format", "json"]
232
+ if self.offline_db is not None:
233
+ cmd[3:3] = ["--offline-vulnerabilities", "--download-offline-databases"]
234
+ try:
235
+ result = self._exec(cmd, cwd=project.root)
236
+ except ToolNotFoundError as exc:
237
+ raise SourceError(f"{TOOL} is not installed; run `patchloop doctor`") from exc
238
+ except ToolTimeoutError as exc:
239
+ detail = (
240
+ "; it first downloads the vulnerability database (npm's is ~213 MB), so try "
241
+ "again on a faster connection, or set osv_offline: false"
242
+ if self.offline_db is not None
243
+ else ""
244
+ )
245
+ raise SourceError(f"{TOOL} timed out after {self.timeout // 60} min{detail}") from exc
246
+ if result.returncode not in (EXIT_NO_VULNS, EXIT_VULNS_FOUND):
247
+ detail = (result.stderr.strip().splitlines() or ["no error output"])[-1]
248
+ raise SourceError(f"{TOOL} failed (exit {result.returncode}): {detail}")
249
+ try:
250
+ data = json.loads(result.stdout or "{}")
251
+ except json.JSONDecodeError as exc:
252
+ raise SourceError(f"{TOOL} did not return valid JSON") from exc
253
+ self.raw_dir.mkdir(parents=True, exist_ok=True)
254
+ (self.raw_dir / "osv-scanner.json").write_text(result.stdout, encoding="utf-8")
255
+ return parse_osv_json(data, self.tool_version())