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/doctor.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""``patchloop doctor``: check the external tools PatchLoop drives.
|
|
2
|
+
|
|
3
|
+
Only exit codes and version strings are read. The output of ``gh auth status`` is never
|
|
4
|
+
printed or stored, so no account details or token fragments leak into logs.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
import sys
|
|
11
|
+
from collections.abc import Sequence
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
|
|
14
|
+
from patchloop import proc
|
|
15
|
+
from patchloop.proc import ProcResult, Runner, ToolNotFoundError, ToolTimeoutError
|
|
16
|
+
|
|
17
|
+
_VERSION_RE = re.compile(r"(\d+)\.(\d+)\.(\d+)")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class ToolSpec:
|
|
22
|
+
name: str
|
|
23
|
+
version_cmd: tuple[str, ...]
|
|
24
|
+
required: bool
|
|
25
|
+
purpose: str
|
|
26
|
+
required_major: int | None = None
|
|
27
|
+
install_hint: str = ""
|
|
28
|
+
"""How to install it on macOS (and on Linux unless ``linux_hint`` is set)."""
|
|
29
|
+
linux_hint: str = ""
|
|
30
|
+
|
|
31
|
+
def hint(self, platform: str | None = None) -> str:
|
|
32
|
+
on_linux = (platform or sys.platform).startswith("linux")
|
|
33
|
+
return self.linux_hint if on_linux and self.linux_hint else self.install_hint
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
TOOLS: tuple[ToolSpec, ...] = (
|
|
37
|
+
ToolSpec(
|
|
38
|
+
"osv-scanner",
|
|
39
|
+
("osv-scanner", "--version"),
|
|
40
|
+
required=True,
|
|
41
|
+
purpose="finds vulnerable packages in the lockfile",
|
|
42
|
+
required_major=2,
|
|
43
|
+
install_hint="brew install osv-scanner",
|
|
44
|
+
linux_hint="download the v2 release: https://github.com/google/osv-scanner/releases",
|
|
45
|
+
),
|
|
46
|
+
ToolSpec(
|
|
47
|
+
"uv",
|
|
48
|
+
("uv", "--version"),
|
|
49
|
+
required=True,
|
|
50
|
+
purpose="locks, upgrades and installs uv projects",
|
|
51
|
+
install_hint="brew install uv",
|
|
52
|
+
linux_hint="https://docs.astral.sh/uv/getting-started/installation/",
|
|
53
|
+
),
|
|
54
|
+
ToolSpec(
|
|
55
|
+
"poetry",
|
|
56
|
+
("poetry", "--version"),
|
|
57
|
+
required=False,
|
|
58
|
+
purpose="needed only for Poetry projects",
|
|
59
|
+
install_hint="pipx install poetry",
|
|
60
|
+
),
|
|
61
|
+
ToolSpec(
|
|
62
|
+
"node",
|
|
63
|
+
("node", "--version"),
|
|
64
|
+
required=False,
|
|
65
|
+
purpose="JavaScript projects (yarn comes through corepack)",
|
|
66
|
+
install_hint="brew install node",
|
|
67
|
+
linux_hint="https://nodejs.org/en/download",
|
|
68
|
+
),
|
|
69
|
+
ToolSpec(
|
|
70
|
+
"npm",
|
|
71
|
+
("npm", "--version"),
|
|
72
|
+
required=False,
|
|
73
|
+
purpose="npm projects",
|
|
74
|
+
install_hint="comes with Node: brew install node",
|
|
75
|
+
linux_hint="comes with Node: https://nodejs.org/en/download",
|
|
76
|
+
),
|
|
77
|
+
ToolSpec(
|
|
78
|
+
"pnpm",
|
|
79
|
+
("pnpm", "--version"),
|
|
80
|
+
required=False,
|
|
81
|
+
purpose="pnpm projects",
|
|
82
|
+
install_hint="corepack enable pnpm",
|
|
83
|
+
),
|
|
84
|
+
ToolSpec(
|
|
85
|
+
"trivy",
|
|
86
|
+
("trivy", "--version"),
|
|
87
|
+
required=False,
|
|
88
|
+
purpose="scans container images (--scanner trivy)",
|
|
89
|
+
install_hint="brew install trivy",
|
|
90
|
+
linux_hint="apt / rpm repositories: https://trivy.dev/latest/getting-started/installation/",
|
|
91
|
+
),
|
|
92
|
+
ToolSpec(
|
|
93
|
+
"wizcli",
|
|
94
|
+
("wizcli", "version"),
|
|
95
|
+
required=False,
|
|
96
|
+
purpose="scans container images (--scanner wiz); needs `wizcli auth`",
|
|
97
|
+
install_hint="ask your Wiz admin for wizcli and credentials, then run: wizcli auth",
|
|
98
|
+
),
|
|
99
|
+
ToolSpec(
|
|
100
|
+
"docker",
|
|
101
|
+
("docker", "--version"),
|
|
102
|
+
required=False,
|
|
103
|
+
purpose="saves multi-platform images for scanning; builds images (--build)",
|
|
104
|
+
install_hint="brew install --cask docker (or Docker Desktop: https://docs.docker.com/get-docker/)",
|
|
105
|
+
linux_hint="https://docs.docker.com/engine/install/",
|
|
106
|
+
),
|
|
107
|
+
ToolSpec(
|
|
108
|
+
"git",
|
|
109
|
+
("git", "--version"),
|
|
110
|
+
required=True,
|
|
111
|
+
purpose="worktree, branch and commit",
|
|
112
|
+
install_hint="xcode-select --install (or brew install git)",
|
|
113
|
+
linux_hint="your distribution's package, e.g. sudo apt install git",
|
|
114
|
+
),
|
|
115
|
+
ToolSpec(
|
|
116
|
+
"gh",
|
|
117
|
+
("gh", "--version"),
|
|
118
|
+
required=True,
|
|
119
|
+
purpose="opens and updates the PR",
|
|
120
|
+
install_hint="brew install gh, then: gh auth login",
|
|
121
|
+
linux_hint="https://github.com/cli/cli#installation, then: gh auth login",
|
|
122
|
+
),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@dataclass(frozen=True)
|
|
127
|
+
class CheckResult:
|
|
128
|
+
name: str
|
|
129
|
+
ok: bool
|
|
130
|
+
required: bool
|
|
131
|
+
version: str | None
|
|
132
|
+
detail: str
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _default_runner(cmd: Sequence[str]) -> ProcResult:
|
|
136
|
+
return proc.run(cmd, timeout=30)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def parse_version(text: str) -> str | None:
|
|
140
|
+
match = _VERSION_RE.search(text)
|
|
141
|
+
return ".".join(match.groups()) if match else None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def check_tool(spec: ToolSpec, run: Runner = _default_runner) -> CheckResult:
|
|
145
|
+
def missing(detail: str) -> CheckResult:
|
|
146
|
+
hint = f". Install: {spec.hint()}" if spec.hint() else ""
|
|
147
|
+
return CheckResult(spec.name, False, spec.required, None, f"{detail}{hint}")
|
|
148
|
+
|
|
149
|
+
try:
|
|
150
|
+
result = run(spec.version_cmd)
|
|
151
|
+
except ToolNotFoundError:
|
|
152
|
+
return missing("not found on PATH")
|
|
153
|
+
except ToolTimeoutError:
|
|
154
|
+
return missing("did not answer --version")
|
|
155
|
+
if not result.ok:
|
|
156
|
+
return missing(f"'{' '.join(spec.version_cmd)}' exited with {result.returncode}")
|
|
157
|
+
|
|
158
|
+
version = parse_version(result.stdout + result.stderr)
|
|
159
|
+
if version is None:
|
|
160
|
+
return CheckResult(spec.name, False, spec.required, None, "could not read its version")
|
|
161
|
+
if spec.required_major is not None and int(version.split(".")[0]) != spec.required_major:
|
|
162
|
+
return CheckResult(
|
|
163
|
+
spec.name,
|
|
164
|
+
False,
|
|
165
|
+
spec.required,
|
|
166
|
+
version,
|
|
167
|
+
f"version {spec.required_major}.x is required",
|
|
168
|
+
)
|
|
169
|
+
return CheckResult(spec.name, True, spec.required, version, spec.purpose)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def check_gh_login(run: Runner = _default_runner) -> CheckResult:
|
|
173
|
+
try:
|
|
174
|
+
result = run(("gh", "auth", "status"))
|
|
175
|
+
except (ToolNotFoundError, ToolTimeoutError):
|
|
176
|
+
return CheckResult("gh login", False, True, None, "gh is not available")
|
|
177
|
+
if result.ok:
|
|
178
|
+
return CheckResult("gh login", True, True, None, "logged in")
|
|
179
|
+
return CheckResult("gh login", False, True, None, "not logged in; run: gh auth login")
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def check_gh_user(user: str, run: Runner = _default_runner) -> CheckResult:
|
|
183
|
+
"""``pr.gh_user`` has a gh login. Only the exit code is read; the token is discarded."""
|
|
184
|
+
name = f"gh login ({user})"
|
|
185
|
+
try:
|
|
186
|
+
result = run(("gh", "auth", "token", "--user", user))
|
|
187
|
+
except (ToolNotFoundError, ToolTimeoutError):
|
|
188
|
+
return CheckResult(name, False, True, None, "gh is not available")
|
|
189
|
+
if result.ok:
|
|
190
|
+
return CheckResult(name, True, True, None, "pr.gh_user can be used")
|
|
191
|
+
return CheckResult(
|
|
192
|
+
name, False, True, None, f"no login for {user}; run: gh auth login, then gh auth switch"
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def run_checks(run: Runner = _default_runner, gh_user: str | None = None) -> list[CheckResult]:
|
|
197
|
+
results = [check_tool(spec, run) for spec in TOOLS]
|
|
198
|
+
gh = next(r for r in results if r.name == "gh")
|
|
199
|
+
if gh.ok:
|
|
200
|
+
results.append(check_gh_login(run))
|
|
201
|
+
if gh_user:
|
|
202
|
+
results.append(check_gh_user(gh_user, run))
|
|
203
|
+
return results
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def all_required_ok(results: list[CheckResult]) -> bool:
|
|
207
|
+
return all(r.ok for r in results if r.required)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Add exploitation signals to findings: CISA KEV (known exploited) and FIRST EPSS
|
|
2
|
+
(probability of exploitation in the next 30 days).
|
|
3
|
+
|
|
4
|
+
Only CVE IDs leave the machine. Results are cached for 24 hours under the PatchLoop cache
|
|
5
|
+
folder. Offline, a stale cache is used if there is one; otherwise the run goes on without
|
|
6
|
+
the signal and says so. ``enrich: false`` in patchloop.yml turns this off.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
from datetime import UTC, datetime
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from patchloop import __version__
|
|
18
|
+
from patchloop.enrich.epss import lookup_epss
|
|
19
|
+
from patchloop.enrich.kev import load_kev
|
|
20
|
+
from patchloop.models import Finding
|
|
21
|
+
|
|
22
|
+
OFFLINE_ENV = "PATCHLOOP_OFFLINE"
|
|
23
|
+
TIMEOUT_S = 20.0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def cves(findings: list[Finding]) -> list[str]:
|
|
27
|
+
return sorted({a for f in findings for a in f.aliases if a.startswith("CVE-")})
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def enrich(
|
|
31
|
+
findings: list[Finding],
|
|
32
|
+
cache: Path,
|
|
33
|
+
*,
|
|
34
|
+
client: httpx.Client | None = None,
|
|
35
|
+
now: datetime | None = None,
|
|
36
|
+
) -> list[str]:
|
|
37
|
+
"""Set ``in_kev`` and ``epss`` on ``findings`` in place; return warnings."""
|
|
38
|
+
if os.environ.get(OFFLINE_ENV) == "1":
|
|
39
|
+
return []
|
|
40
|
+
ids = cves(findings)
|
|
41
|
+
if not ids:
|
|
42
|
+
return []
|
|
43
|
+
now = now or datetime.now(UTC)
|
|
44
|
+
own = client is None
|
|
45
|
+
http = client or httpx.Client(
|
|
46
|
+
timeout=TIMEOUT_S, headers={"User-Agent": f"patchloop/{__version__}"}
|
|
47
|
+
)
|
|
48
|
+
warnings: list[str] = []
|
|
49
|
+
try:
|
|
50
|
+
kev, warning = load_kev(http, cache / "kev.json", now)
|
|
51
|
+
if warning:
|
|
52
|
+
warnings.append(warning)
|
|
53
|
+
scores, warning = lookup_epss(ids, http, cache / "epss.json", now)
|
|
54
|
+
if warning:
|
|
55
|
+
warnings.append(warning)
|
|
56
|
+
finally:
|
|
57
|
+
if own:
|
|
58
|
+
http.close()
|
|
59
|
+
for f in findings:
|
|
60
|
+
ids_here = set(f.aliases)
|
|
61
|
+
if ids_here & kev:
|
|
62
|
+
f.in_kev = True
|
|
63
|
+
found = [s for c in ids_here if (s := scores.get(c)) is not None]
|
|
64
|
+
if found:
|
|
65
|
+
f.epss = max([*found, f.epss or 0.0])
|
|
66
|
+
return warnings
|
patchloop/enrich/epss.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""FIRST EPSS scores, looked up 100 CVEs at a time and cached per CVE for a day."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from datetime import datetime, timedelta
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
EPSS_URL = "https://api.first.org/data/v1/epss"
|
|
12
|
+
BATCH = 100
|
|
13
|
+
MAX_AGE = timedelta(hours=24)
|
|
14
|
+
|
|
15
|
+
# cve -> [score or None (no EPSS entry), fetched_at]
|
|
16
|
+
_Cache = dict[str, list[object]]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _read_cache(path: Path) -> _Cache:
|
|
20
|
+
try:
|
|
21
|
+
data = json.loads(path.read_text("utf-8"))
|
|
22
|
+
return data if isinstance(data, dict) else {}
|
|
23
|
+
except (OSError, ValueError):
|
|
24
|
+
return {}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _fresh(entry: list[object], now: datetime) -> bool:
|
|
28
|
+
try:
|
|
29
|
+
return now - datetime.fromisoformat(str(entry[1])) < MAX_AGE
|
|
30
|
+
except (ValueError, IndexError):
|
|
31
|
+
return False
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def lookup_epss(
|
|
35
|
+
cves: list[str], client: httpx.Client, cache: Path, now: datetime
|
|
36
|
+
) -> tuple[dict[str, float | None], str | None]:
|
|
37
|
+
"""EPSS probability per CVE (None = no score published), and a warning if offline."""
|
|
38
|
+
stored = _read_cache(cache)
|
|
39
|
+
wanted = [c for c in cves if c not in stored or not _fresh(stored[c], now)]
|
|
40
|
+
failed = False
|
|
41
|
+
for i in range(0, len(wanted), BATCH):
|
|
42
|
+
batch = wanted[i : i + BATCH]
|
|
43
|
+
try:
|
|
44
|
+
response = client.get(EPSS_URL, params={"cve": ",".join(batch)})
|
|
45
|
+
response.raise_for_status()
|
|
46
|
+
rows = response.json().get("data", [])
|
|
47
|
+
except (httpx.HTTPError, ValueError):
|
|
48
|
+
failed = True
|
|
49
|
+
break
|
|
50
|
+
got = {str(r["cve"]): float(r["epss"]) for r in rows if "cve" in r and "epss" in r}
|
|
51
|
+
for c in batch:
|
|
52
|
+
stored[c] = [got.get(c), now.isoformat()]
|
|
53
|
+
if wanted and not failed:
|
|
54
|
+
cache.parent.mkdir(parents=True, exist_ok=True)
|
|
55
|
+
cache.write_text(json.dumps(stored), "utf-8")
|
|
56
|
+
scores: dict[str, float | None] = {}
|
|
57
|
+
for c in cves:
|
|
58
|
+
entry = stored.get(c)
|
|
59
|
+
scores[c] = float(entry[0]) if entry and isinstance(entry[0], (int, float)) else None
|
|
60
|
+
warning = (
|
|
61
|
+
"could not reach the FIRST EPSS API; EPSS scores are missing or out of date this run"
|
|
62
|
+
if failed
|
|
63
|
+
else None
|
|
64
|
+
)
|
|
65
|
+
return scores, warning
|
patchloop/enrich/kev.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""CISA Known Exploited Vulnerabilities catalog, downloaded at most once a day."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from datetime import datetime, timedelta
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
KEV_URL = "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"
|
|
12
|
+
MAX_AGE = timedelta(hours=24)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _read_cache(path: Path) -> tuple[set[str], datetime] | None:
|
|
16
|
+
try:
|
|
17
|
+
data = json.loads(path.read_text("utf-8"))
|
|
18
|
+
return set(data["cves"]), datetime.fromisoformat(data["fetched_at"])
|
|
19
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
20
|
+
return None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def load_kev(client: httpx.Client, cache: Path, now: datetime) -> tuple[set[str], str | None]:
|
|
24
|
+
"""CVE IDs in the KEV catalog, and a warning if they could not be refreshed."""
|
|
25
|
+
cached = _read_cache(cache)
|
|
26
|
+
if cached and now - cached[1] < MAX_AGE:
|
|
27
|
+
return cached[0], None
|
|
28
|
+
try:
|
|
29
|
+
response = client.get(KEV_URL)
|
|
30
|
+
response.raise_for_status()
|
|
31
|
+
ids = {str(v["cveID"]) for v in response.json().get("vulnerabilities", [])}
|
|
32
|
+
except (httpx.HTTPError, ValueError, KeyError, TypeError):
|
|
33
|
+
if cached:
|
|
34
|
+
day = cached[1].date().isoformat()
|
|
35
|
+
return cached[0], f"could not refresh the CISA KEV catalog; using the copy from {day}"
|
|
36
|
+
return set(), "could not download the CISA KEV catalog; KEV status is unknown this run"
|
|
37
|
+
cache.parent.mkdir(parents=True, exist_ok=True)
|
|
38
|
+
cache.write_text(json.dumps({"fetched_at": now.isoformat(), "cves": sorted(ids)}), "utf-8")
|
|
39
|
+
return ids, None
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Fixers apply planned upgrades to the project files (uv and Poetry)."""
|
patchloop/fixers/base.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""What the uv, Poetry and JavaScript fixers share."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from patchloop.lockgraph import LockGraph
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class LockError(Exception):
|
|
9
|
+
"""The resolver could not satisfy the requested upgrades."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def last_lines(text: str, n: int = 4) -> str:
|
|
13
|
+
"""The end of a tool's output, for a one-line error."""
|
|
14
|
+
lines = [ln.strip() for ln in text.strip().splitlines() if ln.strip()]
|
|
15
|
+
return " ".join(lines[-n:]) if lines else "no output"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def direct_parents(graph: LockGraph, package: str) -> list[str]:
|
|
19
|
+
"""The project's direct dependencies that pull ``package`` in."""
|
|
20
|
+
return sorted({path[1] for path in graph.paths_to(package) if len(path) > 2})
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""Apply upgrades to an npm, pnpm or yarn project, to the exact target version.
|
|
2
|
+
|
|
3
|
+
Same idea as the Poetry fixer: pin each target, lock, remove the pins, lock again. A direct
|
|
4
|
+
dependency is pinned in its own package.json entry; a transitive one through the manager's
|
|
5
|
+
override mechanism (npm ``overrides``, pnpm ``pnpm.overrides``, yarn ``resolutions``).
|
|
6
|
+
The managers keep locked versions that still satisfy every range, so the targets stay
|
|
7
|
+
and package.json ends up with only the range edits a direct dependency needed.
|
|
8
|
+
|
|
9
|
+
When a parent's range caps a transitive package, the pin is lost on the second lock.
|
|
10
|
+
PatchLoop then upgrades that parent (npm and pnpm) and tries again; if the parent still
|
|
11
|
+
caps it, the override is kept: the upgrade's method becomes ``override`` and the PR says
|
|
12
|
+
the version was forced.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import shutil
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from patchloop import proc
|
|
21
|
+
from patchloop.fixers.base import LockError, direct_parents, last_lines
|
|
22
|
+
from patchloop.js import manifest, yarn
|
|
23
|
+
from patchloop.js.lockfiles import is_berry, read_lock
|
|
24
|
+
from patchloop.lockgraph import LockGraph
|
|
25
|
+
from patchloop.models import Upgrade
|
|
26
|
+
from patchloop.proc import ToolNotFoundError, ToolTimeoutError
|
|
27
|
+
from patchloop.specifiers import SpecifierEditError
|
|
28
|
+
|
|
29
|
+
LOCK_TIMEOUT_S = 900
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def yarn_cmd() -> list[str]:
|
|
33
|
+
"""yarn itself if installed, else through corepack (which reads packageManager)."""
|
|
34
|
+
return ["yarn"] if shutil.which("yarn") else ["corepack", "yarn"]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def lock_command(manager: str, berry: bool = False) -> list[str]:
|
|
38
|
+
"""Re-resolve the lockfile from package.json without running install scripts."""
|
|
39
|
+
if manager == "npm":
|
|
40
|
+
return ["npm", "install", "--package-lock-only", "--ignore-scripts"]
|
|
41
|
+
if manager == "pnpm":
|
|
42
|
+
return ["pnpm", "install", "--lockfile-only", "--ignore-scripts", "--no-frozen-lockfile"]
|
|
43
|
+
if berry:
|
|
44
|
+
return [*yarn_cmd(), "install", "--mode=update-lockfile"]
|
|
45
|
+
return [*yarn_cmd(), "install", "--ignore-scripts", "--non-interactive", "--no-frozen-lockfile"]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class JsFixer:
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
project_dir: Path,
|
|
52
|
+
manager: str,
|
|
53
|
+
lockfile: Path,
|
|
54
|
+
graph: LockGraph,
|
|
55
|
+
env: dict[str, str],
|
|
56
|
+
members: list[str] | None = None,
|
|
57
|
+
) -> None:
|
|
58
|
+
self.project_dir = project_dir
|
|
59
|
+
self.manager = manager
|
|
60
|
+
self.manifest_path = project_dir / "package.json"
|
|
61
|
+
self.manifests = [
|
|
62
|
+
self.manifest_path,
|
|
63
|
+
*(project_dir / m / "package.json" for m in members or []),
|
|
64
|
+
]
|
|
65
|
+
self.workspace = bool(members)
|
|
66
|
+
self.lockfile = lockfile
|
|
67
|
+
self.graph = graph
|
|
68
|
+
self.env = {
|
|
69
|
+
**env,
|
|
70
|
+
"COREPACK_ENABLE_DOWNLOAD_PROMPT": "0",
|
|
71
|
+
"npm_config_audit": "false",
|
|
72
|
+
"npm_config_fund": "false",
|
|
73
|
+
"CI": "true",
|
|
74
|
+
}
|
|
75
|
+
self.berry = manager == "yarn" and is_berry(lockfile)
|
|
76
|
+
self._orig = {p: p.read_bytes() for p in self.manifests}
|
|
77
|
+
self._orig_lock = lockfile.read_bytes()
|
|
78
|
+
locked = read_lock(manager, lockfile)
|
|
79
|
+
self.names = locked.names
|
|
80
|
+
"""lower-cased name -> name as written (override keys must match it)."""
|
|
81
|
+
self._copies = {name: len(vs) for name, vs in locked.versions.items()}
|
|
82
|
+
self.manifest_changes: dict[str, list[tuple[str, str, str]]] = {}
|
|
83
|
+
"""package -> (file, old, new) package.json entries."""
|
|
84
|
+
self.resolver_errors: dict[str, str] = {}
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def overrides_work(self) -> bool:
|
|
88
|
+
"""npm ignores new overrides for packages under workspace members once locked."""
|
|
89
|
+
return not (self.manager == "npm" and self.workspace)
|
|
90
|
+
|
|
91
|
+
# --- commands --------------------------------------------------------------------
|
|
92
|
+
|
|
93
|
+
def _lock_cmd(self) -> list[str]:
|
|
94
|
+
return lock_command(self.manager, self.berry)
|
|
95
|
+
|
|
96
|
+
def _update_cmd(self, parents: list[str]) -> list[str] | None:
|
|
97
|
+
if self.manager == "npm":
|
|
98
|
+
every = ["--workspaces", "--include-workspace-root"] if self.workspace else []
|
|
99
|
+
return ["npm", "update", *parents, *every, "--package-lock-only", "--ignore-scripts"]
|
|
100
|
+
if self.manager == "pnpm":
|
|
101
|
+
every = ["--recursive"] if self.workspace else []
|
|
102
|
+
return ["pnpm", "update", *parents, *every, "--lockfile-only", "--ignore-scripts"]
|
|
103
|
+
return None # yarn: straight to resolutions
|
|
104
|
+
|
|
105
|
+
def _run(self, cmd: list[str]) -> None:
|
|
106
|
+
try:
|
|
107
|
+
result = proc.run(cmd, cwd=self.project_dir, timeout=LOCK_TIMEOUT_S, env=self.env)
|
|
108
|
+
except ToolNotFoundError as exc:
|
|
109
|
+
raise LockError(f"{cmd[0]} is not installed; it is needed for {self.manager}") from exc
|
|
110
|
+
except ToolTimeoutError as exc:
|
|
111
|
+
raise LockError(f"{' '.join(cmd[:2])} timed out after {LOCK_TIMEOUT_S}s") from exc
|
|
112
|
+
if not result.ok:
|
|
113
|
+
raise LockError(last_lines(result.stderr or result.stdout))
|
|
114
|
+
|
|
115
|
+
# --- applying ----------------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
def restore(self) -> None:
|
|
118
|
+
for path, data in self._orig.items():
|
|
119
|
+
path.write_bytes(data)
|
|
120
|
+
self.lockfile.write_bytes(self._orig_lock)
|
|
121
|
+
|
|
122
|
+
def _originals(self) -> dict[Path, str]:
|
|
123
|
+
return {p: data.decode("utf-8") for p, data in self._orig.items()}
|
|
124
|
+
|
|
125
|
+
def _raise(self, texts: dict[Path, str], upgrades: list[Upgrade]) -> None:
|
|
126
|
+
"""Widen every package.json range that excludes a raise-bound target."""
|
|
127
|
+
for u in upgrades:
|
|
128
|
+
if u.method != "raise-bound":
|
|
129
|
+
continue
|
|
130
|
+
edits: list[tuple[str, str, str]] = []
|
|
131
|
+
for path, text in texts.items():
|
|
132
|
+
texts[path], changes = manifest.raise_in_manifest(text, u.package, u.to_version)
|
|
133
|
+
label = path.relative_to(self.project_dir).as_posix()
|
|
134
|
+
edits += [(label, old, new) for old, new in changes]
|
|
135
|
+
self.manifest_changes[u.package] = edits
|
|
136
|
+
|
|
137
|
+
def _write(self, texts: dict[Path, str]) -> None:
|
|
138
|
+
for path, text in texts.items():
|
|
139
|
+
if text.encode("utf-8") != (path.read_bytes() if path.is_file() else b""):
|
|
140
|
+
path.write_text(text, "utf-8")
|
|
141
|
+
|
|
142
|
+
def _pinned(
|
|
143
|
+
self,
|
|
144
|
+
texts: dict[Path, str],
|
|
145
|
+
direct: dict[str, str],
|
|
146
|
+
overrides: list[tuple[str, str, str]],
|
|
147
|
+
) -> dict[Path, str]:
|
|
148
|
+
"""Direct pins in every manifest that lists the package; forced versions at the root."""
|
|
149
|
+
out = {}
|
|
150
|
+
for path, text in texts.items():
|
|
151
|
+
root = path == self.manifest_path
|
|
152
|
+
if root and overrides and not self.overrides_work:
|
|
153
|
+
text = manifest.with_root_deps(text, {n: new for n, _, new in overrides})
|
|
154
|
+
out[path] = manifest.with_pins(text, self.manager, direct, [], self.berry)
|
|
155
|
+
continue
|
|
156
|
+
out[path] = manifest.with_pins(
|
|
157
|
+
text, self.manager, direct, overrides if root else [], self.berry
|
|
158
|
+
)
|
|
159
|
+
return out
|
|
160
|
+
|
|
161
|
+
def _is_direct(self, u: Upgrade) -> bool:
|
|
162
|
+
"""The copy package.json asks for (npm can also hold older copies under parents)."""
|
|
163
|
+
return self.graph.is_direct(u.package) and all(
|
|
164
|
+
manifest.manifest_allows(text, u.package, u.from_version)
|
|
165
|
+
for text in self._originals().values()
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def _forced(self, u: Upgrade) -> tuple[str, str, str]:
|
|
169
|
+
return self.names.get(u.package, u.package), u.from_version, u.to_version
|
|
170
|
+
|
|
171
|
+
def _pins(self, upgrades: list[Upgrade]) -> tuple[dict[str, str], list[tuple[str, str, str]]]:
|
|
172
|
+
direct: dict[str, str] = {}
|
|
173
|
+
overrides: list[tuple[str, str, str]] = []
|
|
174
|
+
for u in upgrades:
|
|
175
|
+
if self._is_direct(u):
|
|
176
|
+
direct[u.package] = u.to_version
|
|
177
|
+
else:
|
|
178
|
+
overrides.append(self._forced(u))
|
|
179
|
+
return direct, overrides
|
|
180
|
+
|
|
181
|
+
def _landed(self, u: Upgrade) -> bool:
|
|
182
|
+
"""No copy of the package is left at the vulnerable version, and the target is in."""
|
|
183
|
+
versions = read_lock(self.manager, self.lockfile).versions.get(u.package.lower(), set())
|
|
184
|
+
return u.to_version in versions and u.from_version not in versions
|
|
185
|
+
|
|
186
|
+
def _apply_yarn(self, upgrades: list[Upgrade]) -> None:
|
|
187
|
+
"""yarn keys its lockfile by range: pin each target in yarn.lock itself."""
|
|
188
|
+
texts = self._originals()
|
|
189
|
+
self._raise(texts, upgrades)
|
|
190
|
+
forced = [self._forced(u) for u in upgrades if u.method == "override"]
|
|
191
|
+
texts[self.manifest_path] = manifest.with_pins(
|
|
192
|
+
texts[self.manifest_path], "yarn", {}, forced, self.berry
|
|
193
|
+
)
|
|
194
|
+
if texts != self._originals():
|
|
195
|
+
self._write(texts)
|
|
196
|
+
self._run(self._lock_cmd())
|
|
197
|
+
run = yarn.run_in(self.project_dir, self.env)
|
|
198
|
+
for u in upgrades:
|
|
199
|
+
if u.method == "override":
|
|
200
|
+
continue
|
|
201
|
+
only_from = None if u.method == "raise-bound" else u.from_version
|
|
202
|
+
try:
|
|
203
|
+
if self.berry:
|
|
204
|
+
pinned = yarn.berry_pin(
|
|
205
|
+
run, yarn_cmd(), self.lockfile, u.package, u.to_version, only_from
|
|
206
|
+
)
|
|
207
|
+
else:
|
|
208
|
+
pinned = yarn.classic_pin(self.lockfile, u.package, u.to_version, only_from)
|
|
209
|
+
except yarn.YarnPinError as exc:
|
|
210
|
+
raise LockError(str(exc)) from exc
|
|
211
|
+
if not pinned:
|
|
212
|
+
raise LockError(f"no range of {u.package} allows {u.to_version}")
|
|
213
|
+
self._run(self._lock_cmd())
|
|
214
|
+
for u in upgrades:
|
|
215
|
+
if not self._landed(u):
|
|
216
|
+
raise LockError(f"{u.package} did not stay at {u.to_version}")
|
|
217
|
+
|
|
218
|
+
def apply(self, upgrades: list[Upgrade]) -> None:
|
|
219
|
+
self.restore()
|
|
220
|
+
if not upgrades:
|
|
221
|
+
return
|
|
222
|
+
if self.manager == "yarn":
|
|
223
|
+
try:
|
|
224
|
+
self._apply_yarn(upgrades)
|
|
225
|
+
except (LockError, SpecifierEditError) as exc:
|
|
226
|
+
self.restore()
|
|
227
|
+
raise LockError(str(exc)) from exc
|
|
228
|
+
except BaseException:
|
|
229
|
+
self.restore() # never leave half-edited files behind
|
|
230
|
+
raise
|
|
231
|
+
return
|
|
232
|
+
try:
|
|
233
|
+
texts = self._originals()
|
|
234
|
+
self._raise(texts, upgrades)
|
|
235
|
+
direct, overrides = self._pins(upgrades)
|
|
236
|
+
self._write(self._pinned(texts, direct, overrides))
|
|
237
|
+
self._run(self._lock_cmd())
|
|
238
|
+
# Keep only the overrides that had to be forced; drop every other pin.
|
|
239
|
+
kept = [self._forced(u) for u in upgrades if u.method == "override"]
|
|
240
|
+
self._write(self._pinned(texts, {}, kept))
|
|
241
|
+
parents = sorted(
|
|
242
|
+
{p for u in upgrades if u.method == "parent-upgrade" for p in u.parents}
|
|
243
|
+
)
|
|
244
|
+
update = self._update_cmd(parents) if parents else None
|
|
245
|
+
if update:
|
|
246
|
+
self._run(update)
|
|
247
|
+
self._run(self._lock_cmd())
|
|
248
|
+
for u in upgrades:
|
|
249
|
+
if not self._landed(u):
|
|
250
|
+
raise LockError(f"{u.package} did not stay at {u.to_version}")
|
|
251
|
+
except (LockError, SpecifierEditError) as exc:
|
|
252
|
+
self.restore()
|
|
253
|
+
raise LockError(str(exc)) from exc
|
|
254
|
+
except BaseException:
|
|
255
|
+
self.restore() # never leave half-edited files behind
|
|
256
|
+
raise
|
|
257
|
+
|
|
258
|
+
def resolve_each(self, upgrades: list[Upgrade]) -> tuple[list[Upgrade], dict[str, str]]:
|
|
259
|
+
accepted: list[Upgrade] = []
|
|
260
|
+
blocked: dict[str, str] = {}
|
|
261
|
+
for u in upgrades:
|
|
262
|
+
tries = [u]
|
|
263
|
+
parents = direct_parents(self.graph, u.package)
|
|
264
|
+
transitive = not self._is_direct(u)
|
|
265
|
+
if transitive and parents and self._update_cmd(parents):
|
|
266
|
+
tries.append(u.model_copy(update={"method": "parent-upgrade", "parents": parents}))
|
|
267
|
+
# yarn resolutions force every copy of a package, so only when there is one.
|
|
268
|
+
one_copy = self.manager != "yarn" or self._copies.get(u.package, 0) <= 1
|
|
269
|
+
if transitive and self.overrides_work and one_copy:
|
|
270
|
+
tries.append(u.model_copy(update={"method": "override", "parents": parents}))
|
|
271
|
+
errors = []
|
|
272
|
+
for attempt in tries:
|
|
273
|
+
try:
|
|
274
|
+
self.apply([*accepted, attempt])
|
|
275
|
+
except LockError as exc:
|
|
276
|
+
errors.append(str(exc))
|
|
277
|
+
continue
|
|
278
|
+
accepted.append(attempt)
|
|
279
|
+
break
|
|
280
|
+
else:
|
|
281
|
+
self.resolver_errors[u.package] = " | ".join(errors)
|
|
282
|
+
blocked[u.package] = f"{self.manager} could not move {u.package} to {u.to_version}"
|
|
283
|
+
if transitive and not self.overrides_work:
|
|
284
|
+
blocked[u.package] += (
|
|
285
|
+
" (npm does not apply overrides inside an existing workspace lockfile)"
|
|
286
|
+
)
|
|
287
|
+
self.restore()
|
|
288
|
+
return accepted, blocked
|