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/hints.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""One "how to fix it" line for each error that stops a run (exit code 2).
|
|
2
|
+
|
|
3
|
+
Kept in one table so every message gets a hint, and the hints stay consistent.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from patchloop.build import BuildError
|
|
9
|
+
from patchloop.config import ConfigError
|
|
10
|
+
from patchloop.detect import DetectError
|
|
11
|
+
from patchloop.fixers.base import LockError
|
|
12
|
+
from patchloop.git_ops import GitError
|
|
13
|
+
from patchloop.github import GitHubError
|
|
14
|
+
from patchloop.images import ImageScanError
|
|
15
|
+
from patchloop.runner import FixError
|
|
16
|
+
from patchloop.sources.base import SourceError
|
|
17
|
+
from patchloop.sources.imports import ImportFileError
|
|
18
|
+
from patchloop.worktree import WorktreeError
|
|
19
|
+
|
|
20
|
+
_CREDENTIALS = (
|
|
21
|
+
"a private package index needs credentials: set them in your environment the way "
|
|
22
|
+
"`uv sync` / `poetry install` expects (e.g. UV_INDEX_<NAME>_USERNAME / _PASSWORD, "
|
|
23
|
+
"or POETRY_HTTP_BASIC_<NAME>_USERNAME / _PASSWORD)"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
# (error type, text in the message or "" for any, hint). First match wins.
|
|
27
|
+
_HINTS: list[tuple[type[Exception], str, str]] = [
|
|
28
|
+
(ConfigError, "", "fix patchloop.yml; the README lists every key and its default"),
|
|
29
|
+
(BuildError, "no value", "export the build arg's value first, or pass --build-arg NAME=VALUE"),
|
|
30
|
+
(BuildError, "no Dockerfile", "pass --dockerfile path/to/Dockerfile (relative to the project)"),
|
|
31
|
+
(BuildError, "not installed", "install Docker and start it, then run `patchloop doctor`"),
|
|
32
|
+
(
|
|
33
|
+
BuildError,
|
|
34
|
+
"",
|
|
35
|
+
"read the build log; private feeds or registries may need --build-arg or `docker login`",
|
|
36
|
+
),
|
|
37
|
+
(
|
|
38
|
+
ImageScanError,
|
|
39
|
+
"not installed",
|
|
40
|
+
"install the tool named above (`patchloop doctor` shows how), then run it again",
|
|
41
|
+
),
|
|
42
|
+
(
|
|
43
|
+
ImageScanError,
|
|
44
|
+
"wizcli auth",
|
|
45
|
+
"log in with `wizcli auth`, or export WIZ_CLIENT_ID and WIZ_CLIENT_SECRET",
|
|
46
|
+
),
|
|
47
|
+
(
|
|
48
|
+
ImageScanError,
|
|
49
|
+
"could not save",
|
|
50
|
+
"pull or build the image for this platform, or pass --platform",
|
|
51
|
+
),
|
|
52
|
+
(ImageScanError, "", "check the image name; it must be local (`docker image ls`) or pullable"),
|
|
53
|
+
(
|
|
54
|
+
DetectError,
|
|
55
|
+
"separate projects",
|
|
56
|
+
"run it once per folder, e.g. `patchloop fix backend`; each folder gets its own PR branch",
|
|
57
|
+
),
|
|
58
|
+
(
|
|
59
|
+
DetectError,
|
|
60
|
+
"member of the workspace",
|
|
61
|
+
"run it on the workspace root; one run fixes every member through the shared lockfile",
|
|
62
|
+
),
|
|
63
|
+
(
|
|
64
|
+
DetectError,
|
|
65
|
+
"no pyproject.toml",
|
|
66
|
+
"run it on the project folder: `patchloop scan path/to/project`",
|
|
67
|
+
),
|
|
68
|
+
(
|
|
69
|
+
DetectError,
|
|
70
|
+
"no uv.lock or poetry.lock",
|
|
71
|
+
"create and commit a lockfile first: `uv lock` or `poetry lock`",
|
|
72
|
+
),
|
|
73
|
+
(
|
|
74
|
+
DetectError,
|
|
75
|
+
"no package-lock.json",
|
|
76
|
+
"create and commit a lockfile first: `npm install`, `pnpm install` or `yarn install`",
|
|
77
|
+
),
|
|
78
|
+
(DetectError, "not valid JSON", "fix the JSON syntax in package.json"),
|
|
79
|
+
(DetectError, "not valid TOML", "fix the TOML syntax in pyproject.toml"),
|
|
80
|
+
(
|
|
81
|
+
ImportFileError,
|
|
82
|
+
"",
|
|
83
|
+
"pass a Trivy (`--format json`) or Wiz (`--json-output-file`) JSON report",
|
|
84
|
+
),
|
|
85
|
+
(
|
|
86
|
+
SourceError,
|
|
87
|
+
"not installed",
|
|
88
|
+
"install OSV-Scanner v2 (`brew install osv-scanner`), then run `patchloop doctor`",
|
|
89
|
+
),
|
|
90
|
+
(SourceError, "timed out", "check your network connection and run it again"),
|
|
91
|
+
(SourceError, "", "run `osv-scanner scan source -L <lockfile>` to see the full error"),
|
|
92
|
+
(
|
|
93
|
+
WorktreeError,
|
|
94
|
+
"not inside a git repository",
|
|
95
|
+
"`fix` needs a git repo with the project committed; `scan` works without git",
|
|
96
|
+
),
|
|
97
|
+
(
|
|
98
|
+
WorktreeError,
|
|
99
|
+
"could not fetch",
|
|
100
|
+
"check you can `git fetch origin`, or set pr.base_branch in patchloop.yml "
|
|
101
|
+
"to your default branch",
|
|
102
|
+
),
|
|
103
|
+
(
|
|
104
|
+
WorktreeError,
|
|
105
|
+
"no local branch",
|
|
106
|
+
"set pr.base_branch in patchloop.yml to your default branch (e.g. master)",
|
|
107
|
+
),
|
|
108
|
+
(
|
|
109
|
+
WorktreeError,
|
|
110
|
+
"has no pyproject.toml on",
|
|
111
|
+
"commit pyproject.toml and the lockfile to the base branch first",
|
|
112
|
+
),
|
|
113
|
+
(WorktreeError, "", "run `git worktree prune` and try again"),
|
|
114
|
+
(FixError, "installing the project failed", f"see the log; if it is a 401/403, {_CREDENTIALS}"),
|
|
115
|
+
(
|
|
116
|
+
FixError,
|
|
117
|
+
"tests already fail",
|
|
118
|
+
"fix the tests on the base branch, or set validate.test in patchloop.yml "
|
|
119
|
+
"(`none` skips tests)",
|
|
120
|
+
),
|
|
121
|
+
(
|
|
122
|
+
FixError,
|
|
123
|
+
"files other than",
|
|
124
|
+
"an install or test step wrote files into the repo; add them to .gitignore",
|
|
125
|
+
),
|
|
126
|
+
(LockError, "401", _CREDENTIALS),
|
|
127
|
+
(LockError, "403", _CREDENTIALS),
|
|
128
|
+
(
|
|
129
|
+
LockError,
|
|
130
|
+
"poetry is not installed",
|
|
131
|
+
"install Poetry (https://python-poetry.org/docs/#installation)",
|
|
132
|
+
),
|
|
133
|
+
(LockError, "", "the full resolver message is in logs/resolver.log in the run folder"),
|
|
134
|
+
(
|
|
135
|
+
GitError,
|
|
136
|
+
"user.name",
|
|
137
|
+
'`git config user.name "Your Name"` and `git config user.email you@example.com`',
|
|
138
|
+
),
|
|
139
|
+
(GitError, "owner/repo", "set pr.repo: owner/name in patchloop.yml"),
|
|
140
|
+
(
|
|
141
|
+
GitError,
|
|
142
|
+
"no 'origin' remote",
|
|
143
|
+
"add the GitHub remote (`git remote add origin …`), or use --no-push",
|
|
144
|
+
),
|
|
145
|
+
(GitError, "changed on origin", "someone pushed to the branch during the run; run it again"),
|
|
146
|
+
(
|
|
147
|
+
GitError,
|
|
148
|
+
"holds commits",
|
|
149
|
+
"move that work to another branch, or delete the branch so PatchLoop can rebuild it",
|
|
150
|
+
),
|
|
151
|
+
(
|
|
152
|
+
GitError,
|
|
153
|
+
"git push",
|
|
154
|
+
"check you can push (`git push --dry-run origin HEAD`) and which account pr.gh_user names",
|
|
155
|
+
),
|
|
156
|
+
(
|
|
157
|
+
GitHubError,
|
|
158
|
+
"was pushed, but",
|
|
159
|
+
"open the PR by hand: `gh pr create --head patchloop/security-fixes`, or run it again",
|
|
160
|
+
),
|
|
161
|
+
(GitHubError, "no login", "`gh auth login`, then `gh auth switch` back to your usual account"),
|
|
162
|
+
(
|
|
163
|
+
GitHubError,
|
|
164
|
+
"cannot push to",
|
|
165
|
+
"set pr.gh_user in patchloop.yml to an account with write access",
|
|
166
|
+
),
|
|
167
|
+
(
|
|
168
|
+
GitHubError,
|
|
169
|
+
"",
|
|
170
|
+
"check `gh auth status` and that this account can see the repo (`gh repo view owner/name`)",
|
|
171
|
+
),
|
|
172
|
+
]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def hint_for(exc: Exception) -> str | None:
|
|
176
|
+
text = str(exc)
|
|
177
|
+
for kind, needle, hint in _HINTS:
|
|
178
|
+
if isinstance(exc, kind) and needle in text:
|
|
179
|
+
return hint
|
|
180
|
+
return None
|
patchloop/images.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Scan a container image with Trivy or Wiz, then hand the report to the import path.
|
|
2
|
+
|
|
3
|
+
The image must already exist (pulled or built locally, or reachable by the scanner).
|
|
4
|
+
Each scan writes one JSON report into the run folder; ``sources.imports`` reads it like a
|
|
5
|
+
file passed with ``--import``. Secret findings are removed before the report is saved.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import platform
|
|
13
|
+
import re
|
|
14
|
+
from collections.abc import Iterator
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Literal
|
|
18
|
+
|
|
19
|
+
from patchloop import proc
|
|
20
|
+
from patchloop.proc import ProcResult, ToolNotFoundError, ToolTimeoutError
|
|
21
|
+
|
|
22
|
+
Scanner = Literal["trivy", "wiz"]
|
|
23
|
+
SCANNERS: tuple[Scanner, ...] = ("trivy", "wiz")
|
|
24
|
+
SCAN_TIMEOUT_S = 1800
|
|
25
|
+
WIZ_POLICY_FAILED = 4
|
|
26
|
+
"""wizcli exits 4 when a policy fails; the report is still complete."""
|
|
27
|
+
|
|
28
|
+
# Docker cannot export a multi-platform image whose other platforms were never pulled.
|
|
29
|
+
_EXPORT_FAILED = re.compile(
|
|
30
|
+
r"unable to export|content digest .* not found|unable to create manifests"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ImageScanError(Exception):
|
|
35
|
+
"""The scanner could not scan the image."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class ImageScan:
|
|
40
|
+
image: str
|
|
41
|
+
scanner: Scanner
|
|
42
|
+
report: Path
|
|
43
|
+
leaked: tuple[str, ...] = ()
|
|
44
|
+
"""Names of build args whose values were found inside the image (e.g. its history)."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
MIN_SECRET_LEN = 4
|
|
48
|
+
"""Shorter build-arg values are not masked (masking "1" or "on" would garble the report)."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _mask(node: Any, values: list[str]) -> Any:
|
|
52
|
+
"""Mask ``values`` inside every string of a parsed report (keys and numbers untouched)."""
|
|
53
|
+
if isinstance(node, str):
|
|
54
|
+
for value in values:
|
|
55
|
+
node = node.replace(value, "***")
|
|
56
|
+
return node
|
|
57
|
+
if isinstance(node, list):
|
|
58
|
+
return [_mask(item, values) for item in node]
|
|
59
|
+
if isinstance(node, dict):
|
|
60
|
+
return {key: _mask(item, values) for key, item in node.items()}
|
|
61
|
+
return node
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _strings(node: Any) -> Iterator[str]:
|
|
65
|
+
if isinstance(node, str):
|
|
66
|
+
yield node
|
|
67
|
+
elif isinstance(node, list):
|
|
68
|
+
for item in node:
|
|
69
|
+
yield from _strings(item)
|
|
70
|
+
elif isinstance(node, dict):
|
|
71
|
+
for item in node.values():
|
|
72
|
+
yield from _strings(item)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _scrub(out: Path, scanner: Scanner, secrets: dict[str, str]) -> tuple[str, ...]:
|
|
76
|
+
"""Drop the parts PatchLoop never uses that can hold secrets, and mask build-arg values.
|
|
77
|
+
|
|
78
|
+
Returns the names of build args whose values the scanner found in the image itself
|
|
79
|
+
(Trivy: the image config and history; Wiz: anywhere in its report).
|
|
80
|
+
"""
|
|
81
|
+
data = json.loads(out.read_text("utf-8"))
|
|
82
|
+
kept = {k: v for k, v in secrets.items() if len(v) >= MIN_SECRET_LEN}
|
|
83
|
+
if scanner == "trivy":
|
|
84
|
+
inside: Any = (data.get("Metadata") or {}).pop("ImageConfig", None)
|
|
85
|
+
else:
|
|
86
|
+
inside = data
|
|
87
|
+
found = list(_strings(inside))
|
|
88
|
+
leaked = tuple(name for name, value in kept.items() if any(value in s for s in found))
|
|
89
|
+
values = sorted(kept.values(), key=len, reverse=True)
|
|
90
|
+
out.write_text(json.dumps(_mask(data, values), ensure_ascii=False), "utf-8")
|
|
91
|
+
return leaked
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _slug(image: str) -> str:
|
|
95
|
+
return re.sub(r"[^A-Za-z0-9._-]+", "_", image)[-80:]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _last_line(result: ProcResult) -> str:
|
|
99
|
+
lines = [ln for ln in (result.stderr or result.stdout).splitlines() if ln.strip()]
|
|
100
|
+
return lines[-1].strip() if lines else f"exit code {result.returncode}"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def local_platform() -> str:
|
|
104
|
+
arch = {"x86_64": "amd64", "aarch64": "arm64", "arm64": "arm64"}.get(
|
|
105
|
+
platform.machine(), "amd64"
|
|
106
|
+
)
|
|
107
|
+
return f"linux/{arch}"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _run(cmd: list[str], what: str) -> ProcResult:
|
|
111
|
+
try:
|
|
112
|
+
return proc.run(cmd, timeout=SCAN_TIMEOUT_S, env=dict(os.environ))
|
|
113
|
+
except ToolNotFoundError as exc:
|
|
114
|
+
raise ImageScanError(f"{cmd[0]} is not installed; it is needed for {what}") from exc
|
|
115
|
+
except ToolTimeoutError as exc:
|
|
116
|
+
raise ImageScanError(f"{what} timed out after {SCAN_TIMEOUT_S // 60} min") from exc
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _trivy(image: str, out: Path, platform_: str | None) -> None:
|
|
120
|
+
base = ["trivy", "image", "--scanners", "vuln", "--format", "json", "--quiet"]
|
|
121
|
+
result = _run([*base, "--output", str(out), image], f"scanning {image} with Trivy")
|
|
122
|
+
if result.ok:
|
|
123
|
+
return
|
|
124
|
+
if not _EXPORT_FAILED.search(result.stderr):
|
|
125
|
+
raise ImageScanError(f"Trivy could not scan {image}: {_last_line(result)}")
|
|
126
|
+
# Save only the platform that is present locally, then scan the saved file.
|
|
127
|
+
tar = out.with_suffix(".tar")
|
|
128
|
+
plat = platform_ or local_platform()
|
|
129
|
+
saved = _run(["docker", "save", "--platform", plat, "-o", str(tar), image], f"saving {image}")
|
|
130
|
+
if not saved.ok:
|
|
131
|
+
raise ImageScanError(f"could not save {image} for {plat}: {_last_line(saved)}")
|
|
132
|
+
try:
|
|
133
|
+
result = _run([*base, "--output", str(out), "--input", str(tar)], f"scanning {image}")
|
|
134
|
+
if not result.ok:
|
|
135
|
+
raise ImageScanError(f"Trivy could not scan {image}: {_last_line(result)}")
|
|
136
|
+
data = json.loads(out.read_text("utf-8"))
|
|
137
|
+
data["ArtifactName"] = image # not the temporary tar path
|
|
138
|
+
for res in data.get("Results") or []:
|
|
139
|
+
res["Target"] = str(res.get("Target", "")).replace(str(tar), image)
|
|
140
|
+
out.write_text(json.dumps(data), "utf-8")
|
|
141
|
+
finally:
|
|
142
|
+
tar.unlink(missing_ok=True)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _wiz(image: str, out: Path) -> None:
|
|
146
|
+
cmd = [
|
|
147
|
+
"wizcli", "scan", "container-image", image,
|
|
148
|
+
"--by-policy-hits", "DISABLED", "--json-output-file", str(out),
|
|
149
|
+
] # fmt: skip
|
|
150
|
+
result = _run(cmd, f"scanning {image} with Wiz")
|
|
151
|
+
if result.returncode not in (0, WIZ_POLICY_FAILED) or not out.is_file():
|
|
152
|
+
detail = _last_line(result)
|
|
153
|
+
if re.search(r"401|invalid_client|not authenticated|unauthori", detail, re.I):
|
|
154
|
+
raise ImageScanError(
|
|
155
|
+
"Wiz rejected the credentials; run `wizcli auth` or set WIZ_CLIENT_ID / "
|
|
156
|
+
"WIZ_CLIENT_SECRET"
|
|
157
|
+
)
|
|
158
|
+
raise ImageScanError(f"Wiz could not scan {image}: {detail}")
|
|
159
|
+
data = json.loads(out.read_text("utf-8"))
|
|
160
|
+
result_part = data.get("result") or {}
|
|
161
|
+
if result_part.get("secrets") is not None:
|
|
162
|
+
result_part["secrets"] = [] # never keep secret findings, even redacted
|
|
163
|
+
out.write_text(json.dumps(data), "utf-8")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def scan_image(
|
|
167
|
+
image: str,
|
|
168
|
+
scanner: Scanner,
|
|
169
|
+
out_dir: Path,
|
|
170
|
+
platform_: str | None = None,
|
|
171
|
+
secrets: dict[str, str] | None = None,
|
|
172
|
+
) -> ImageScan:
|
|
173
|
+
"""``secrets``: build-arg name -> value, masked in the saved report."""
|
|
174
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
175
|
+
out = out_dir / f"{scanner}-{_slug(image)}.json"
|
|
176
|
+
if scanner == "trivy":
|
|
177
|
+
_trivy(image, out, platform_)
|
|
178
|
+
else:
|
|
179
|
+
_wiz(image, out)
|
|
180
|
+
leaked = _scrub(out, scanner, secrets or {})
|
|
181
|
+
return ImageScan(image, scanner, out, leaked)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def scan_images(
|
|
185
|
+
images: list[str],
|
|
186
|
+
scanners: list[Scanner],
|
|
187
|
+
out_dir: Path,
|
|
188
|
+
platform_: str | None = None,
|
|
189
|
+
secrets: dict[str, str] | None = None,
|
|
190
|
+
) -> list[ImageScan]:
|
|
191
|
+
return [scan_image(i, s, out_dir, platform_, secrets) for i in images for s in scanners]
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def leak_warning(names: set[str]) -> str:
|
|
195
|
+
return (
|
|
196
|
+
f"build arg(s) {', '.join(sorted(names))} are stored inside the built image (its "
|
|
197
|
+
"history), where anyone who can pull it can read them; pass them as BuildKit "
|
|
198
|
+
"secrets (RUN --mount=type=secret) instead of ARG"
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def parse_scanners(value: str) -> list[Scanner]:
|
|
203
|
+
"""``"trivy"``, ``"wiz"`` or ``"trivy,wiz"``."""
|
|
204
|
+
names = [v.strip().lower() for v in value.split(",") if v.strip()]
|
|
205
|
+
bad = [n for n in names if n not in SCANNERS]
|
|
206
|
+
if bad or not names:
|
|
207
|
+
raise ValueError(f"unknown scanner {', '.join(bad) or value!r}; use trivy, wiz or both")
|
|
208
|
+
return list(dict.fromkeys(names)) # type: ignore[arg-type]
|
patchloop/isolate.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Find upgrades that break the tests by bisection.
|
|
2
|
+
|
|
3
|
+
Invariant while searching: ``context`` passes and ``context + suspects`` fails. Each round
|
|
4
|
+
tests ``context + first half``: if it fails the breaker is in the first half, otherwise the
|
|
5
|
+
first half joins the context and the breaker is in the second half. That is about log2(N)
|
|
6
|
+
test runs per breaker, and it also finds breakers that only fail in combination.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
|
|
14
|
+
from patchloop.models import Upgrade, ValidationResult
|
|
15
|
+
|
|
16
|
+
TestFn = Callable[[list[Upgrade]], ValidationResult]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Isolation:
|
|
21
|
+
kept: list[Upgrade]
|
|
22
|
+
final: ValidationResult | None
|
|
23
|
+
"""The passing run of exactly ``kept`` (None when nothing was kept)."""
|
|
24
|
+
breakers: dict[str, ValidationResult] = field(default_factory=dict)
|
|
25
|
+
"""package -> the failing run that convicted it."""
|
|
26
|
+
test_runs: int = 0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def isolate_breakers(upgrades: list[Upgrade], test: TestFn) -> Isolation:
|
|
30
|
+
runs = 0
|
|
31
|
+
|
|
32
|
+
def check(items: list[Upgrade]) -> ValidationResult:
|
|
33
|
+
nonlocal runs
|
|
34
|
+
runs += 1
|
|
35
|
+
return test(items)
|
|
36
|
+
|
|
37
|
+
remaining = list(upgrades)
|
|
38
|
+
breakers: dict[str, ValidationResult] = {}
|
|
39
|
+
while remaining:
|
|
40
|
+
result = check(remaining)
|
|
41
|
+
if result.passed:
|
|
42
|
+
return Isolation(remaining, result, breakers, runs)
|
|
43
|
+
context: list[Upgrade] = []
|
|
44
|
+
suspects = remaining
|
|
45
|
+
evidence = result
|
|
46
|
+
while len(suspects) > 1:
|
|
47
|
+
half = len(suspects) // 2
|
|
48
|
+
first, second = suspects[:half], suspects[half:]
|
|
49
|
+
trial = check(context + first)
|
|
50
|
+
if not trial.passed:
|
|
51
|
+
suspects, evidence = first, trial
|
|
52
|
+
else:
|
|
53
|
+
context, suspects = context + first, second
|
|
54
|
+
breaker = suspects[0]
|
|
55
|
+
breakers[breaker.package] = evidence
|
|
56
|
+
remaining = [u for u in remaining if u != breaker] # other copies of it may pass
|
|
57
|
+
return Isolation([], None, breakers, runs)
|
patchloop/js/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""JavaScript projects: npm, pnpm and yarn."""
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""Read JavaScript lockfiles: npm (package-lock.json), pnpm (pnpm-lock.yaml) and yarn
|
|
2
|
+
(yarn.lock, classic v1 and Berry).
|
|
3
|
+
|
|
4
|
+
Each reader returns a :class:`JsLock`: every installed version of every package (npm can
|
|
5
|
+
install one package at several versions), dependency edges between package names, and
|
|
6
|
+
which packages come from a registry (not git, a local path or a URL).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
from collections import defaultdict
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import yaml
|
|
19
|
+
|
|
20
|
+
from patchloop.lockgraph import LockGraph
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class JsLock:
|
|
25
|
+
versions: dict[str, set[str]] = field(default_factory=lambda: defaultdict(set))
|
|
26
|
+
"""package name -> every version installed."""
|
|
27
|
+
edges: dict[str, set[str]] = field(default_factory=lambda: defaultdict(set))
|
|
28
|
+
registry: set[str] = field(default_factory=set)
|
|
29
|
+
"""Packages installed from a registry (npm or a private one)."""
|
|
30
|
+
names: dict[str, str] = field(default_factory=dict)
|
|
31
|
+
"""lower-cased name -> the name as written (the npm registry is case-sensitive)."""
|
|
32
|
+
|
|
33
|
+
def add(self, name: str, version: str, deps: list[str], from_registry: bool) -> None:
|
|
34
|
+
self.names.setdefault(name.lower(), name)
|
|
35
|
+
name = name.lower()
|
|
36
|
+
self.versions[name].add(version)
|
|
37
|
+
self.edges[name].update(d.lower() for d in deps)
|
|
38
|
+
if from_registry:
|
|
39
|
+
self.registry.add(name)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def read_manifest(project_dir: Path) -> dict[str, Any]:
|
|
43
|
+
data: dict[str, Any] = json.loads((project_dir / "package.json").read_text("utf-8"))
|
|
44
|
+
return data
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def manifest_deps(manifest: dict[str, Any]) -> tuple[set[str], set[str]]:
|
|
48
|
+
"""(runtime direct, dev-only direct) package names from package.json."""
|
|
49
|
+
runtime = {
|
|
50
|
+
n.lower() for s in ("dependencies", "optionalDependencies") for n in manifest.get(s) or {}
|
|
51
|
+
}
|
|
52
|
+
dev = {n.lower() for n in manifest.get("devDependencies") or {}} - runtime
|
|
53
|
+
return runtime, dev
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# --- npm -------------------------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _npm_name(path: str, entry: dict[str, Any]) -> str:
|
|
60
|
+
if entry.get("name"):
|
|
61
|
+
return str(entry["name"])
|
|
62
|
+
return path.rsplit("node_modules/", 1)[-1]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def read_npm(lockfile: Path) -> JsLock:
|
|
66
|
+
data = json.loads(lockfile.read_text("utf-8"))
|
|
67
|
+
lock = JsLock()
|
|
68
|
+
for path, entry in (data.get("packages") or {}).items():
|
|
69
|
+
if not path or entry.get("link") or "version" not in entry:
|
|
70
|
+
continue # the project itself, or a workspace link
|
|
71
|
+
resolved = str(entry.get("resolved", ""))
|
|
72
|
+
from_registry = resolved.startswith(("http://", "https://")) and resolved.endswith(".tgz")
|
|
73
|
+
deps = [*(entry.get("dependencies") or {}), *(entry.get("optionalDependencies") or {})]
|
|
74
|
+
lock.add(_npm_name(path, entry), str(entry["version"]), deps, from_registry)
|
|
75
|
+
return lock
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def npm_top_level(lockfile: Path) -> dict[str, str]:
|
|
79
|
+
"""name -> the version installed at the top of node_modules (what `require` finds)."""
|
|
80
|
+
data = json.loads(lockfile.read_text("utf-8"))
|
|
81
|
+
out = {}
|
|
82
|
+
for path, entry in (data.get("packages") or {}).items():
|
|
83
|
+
top = path.startswith("node_modules/") and path.count("node_modules/") == 1
|
|
84
|
+
if top and "version" in entry: # not packages/a/node_modules/x in a workspace
|
|
85
|
+
out[_npm_name(path, entry).lower()] = str(entry["version"])
|
|
86
|
+
return out
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# --- pnpm ------------------------------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
_PEERS = re.compile(r"\(.*\)$")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def split_name_version(key: str) -> tuple[str, str]:
|
|
95
|
+
"""'@scope/name@1.2.3(peer@1)' or '/name@1.2.3' -> (name, version)."""
|
|
96
|
+
key = _PEERS.sub("", key.lstrip("/"))
|
|
97
|
+
at = key.rfind("@")
|
|
98
|
+
if at <= 0:
|
|
99
|
+
raise ValueError(key)
|
|
100
|
+
return key[:at], key[at + 1 :]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def read_pnpm(lockfile: Path) -> JsLock:
|
|
104
|
+
data = yaml.safe_load(lockfile.read_text("utf-8")) or {}
|
|
105
|
+
lock = JsLock()
|
|
106
|
+
packages = data.get("packages") or {}
|
|
107
|
+
snapshots = data.get("snapshots") or {} # lockfile v9; v6 keeps deps in packages
|
|
108
|
+
for key, entry in packages.items():
|
|
109
|
+
try:
|
|
110
|
+
name, version = split_name_version(str(key))
|
|
111
|
+
except ValueError:
|
|
112
|
+
continue
|
|
113
|
+
resolution = (entry or {}).get("resolution") or {}
|
|
114
|
+
from_registry = "integrity" in resolution and "type" not in resolution
|
|
115
|
+
deps = list(((entry or {}).get("dependencies") or {}).keys())
|
|
116
|
+
lock.add(name, version, deps, from_registry)
|
|
117
|
+
for key, entry in snapshots.items():
|
|
118
|
+
try:
|
|
119
|
+
name, version = split_name_version(str(key))
|
|
120
|
+
except ValueError:
|
|
121
|
+
continue
|
|
122
|
+
lock.edges[name.lower()].update(
|
|
123
|
+
d.lower()
|
|
124
|
+
for section in ("dependencies", "optionalDependencies")
|
|
125
|
+
for d in ((entry or {}).get(section) or {})
|
|
126
|
+
)
|
|
127
|
+
lock.versions[name.lower()].add(version)
|
|
128
|
+
return lock
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# --- yarn ------------------------------------------------------------------------------
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _descriptor_name(descriptor: str) -> str:
|
|
135
|
+
descriptor = descriptor.strip().strip('"')
|
|
136
|
+
at = descriptor.find("@", 1) # skip the leading @ of a scope
|
|
137
|
+
return descriptor[:at] if at > 0 else descriptor
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def is_berry(lockfile: Path) -> bool:
|
|
141
|
+
return "__metadata:" in lockfile.read_text("utf-8")[:2000]
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def read_yarn(lockfile: Path) -> JsLock:
|
|
145
|
+
return _read_yarn_berry(lockfile) if is_berry(lockfile) else _read_yarn_classic(lockfile)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _read_yarn_berry(lockfile: Path) -> JsLock:
|
|
149
|
+
data = yaml.safe_load(lockfile.read_text("utf-8")) or {}
|
|
150
|
+
lock = JsLock()
|
|
151
|
+
for key, entry in data.items():
|
|
152
|
+
if key == "__metadata" or not isinstance(entry, dict):
|
|
153
|
+
continue
|
|
154
|
+
resolution = str(entry.get("resolution", ""))
|
|
155
|
+
if "@workspace:" in resolution:
|
|
156
|
+
continue # the project itself
|
|
157
|
+
name = _descriptor_name(str(key).split(",")[0])
|
|
158
|
+
deps = list((entry.get("dependencies") or {}).keys())
|
|
159
|
+
lock.add(name, str(entry.get("version", "")), deps, "@npm:" in resolution)
|
|
160
|
+
return lock
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _read_yarn_classic(lockfile: Path) -> JsLock:
|
|
164
|
+
lock = JsLock()
|
|
165
|
+
current: dict[str, Any] | None = None
|
|
166
|
+
names: list[str] = []
|
|
167
|
+
in_deps = False
|
|
168
|
+
|
|
169
|
+
def flush() -> None:
|
|
170
|
+
if current is not None and "version" in current:
|
|
171
|
+
resolved = str(current.get("resolved", ""))
|
|
172
|
+
from_registry = resolved.startswith(("http://", "https://")) and ".tgz" in resolved
|
|
173
|
+
for n in dict.fromkeys(names):
|
|
174
|
+
lock.add(n, current["version"], current["deps"], from_registry)
|
|
175
|
+
|
|
176
|
+
for raw in lockfile.read_text("utf-8").splitlines():
|
|
177
|
+
if not raw.strip() or raw.lstrip().startswith("#"):
|
|
178
|
+
continue
|
|
179
|
+
indent = len(raw) - len(raw.lstrip())
|
|
180
|
+
line = raw.strip()
|
|
181
|
+
if indent == 0 and line.endswith(":"):
|
|
182
|
+
flush()
|
|
183
|
+
names = [_descriptor_name(d) for d in line[:-1].split(",")]
|
|
184
|
+
current, in_deps = {"deps": []}, False
|
|
185
|
+
elif current is not None and indent == 2:
|
|
186
|
+
in_deps = line in ("dependencies:", "optionalDependencies:")
|
|
187
|
+
if not line.endswith(":"):
|
|
188
|
+
key, _, value = line.partition(" ")
|
|
189
|
+
current[key] = value.strip().strip('"')
|
|
190
|
+
elif current is not None and indent >= 4 and in_deps:
|
|
191
|
+
current["deps"].append(line.split(" ")[0].strip('"'))
|
|
192
|
+
flush()
|
|
193
|
+
return lock
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
# --- shared ----------------------------------------------------------------------------
|
|
197
|
+
|
|
198
|
+
READERS = {"npm": read_npm, "pnpm": read_pnpm, "yarn": read_yarn}
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def read_lock(manager: str, lockfile: Path) -> JsLock:
|
|
202
|
+
return READERS[manager](lockfile)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def load_js_graph(
|
|
206
|
+
project_dir: Path, manager: str, lockfile: Path, members: list[str] | None = None
|
|
207
|
+
) -> LockGraph:
|
|
208
|
+
"""Direct dependencies of the project, or of every workspace member together."""
|
|
209
|
+
manifest = read_manifest(project_dir)
|
|
210
|
+
lock = read_lock(manager, lockfile)
|
|
211
|
+
runtime, dev = manifest_deps(manifest)
|
|
212
|
+
own = {str(manifest.get("name") or "").lower()}
|
|
213
|
+
for member in members or []:
|
|
214
|
+
m = read_manifest(project_dir / member)
|
|
215
|
+
own.add(str(m.get("name") or "").lower())
|
|
216
|
+
r, d = manifest_deps(m)
|
|
217
|
+
runtime |= r
|
|
218
|
+
dev |= d
|
|
219
|
+
runtime -= own # members depend on each other through workspace links
|
|
220
|
+
dev = dev - runtime - own
|
|
221
|
+
root = str(manifest.get("name") or project_dir.name).lower()
|
|
222
|
+
graph = LockGraph(root=root, ecosystem="npm", direct=runtime, direct_dev=dev)
|
|
223
|
+
graph.edges = {k: set(v) for k, v in lock.edges.items()}
|
|
224
|
+
graph.edges[root] = runtime | dev
|
|
225
|
+
return graph
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def lock_versions_js(manager: str, lockfile: Path) -> dict[str, str]:
|
|
229
|
+
"""name -> one version per package (npm: the top-level one), for mapping image scans."""
|
|
230
|
+
if manager == "npm":
|
|
231
|
+
return npm_top_level(lockfile)
|
|
232
|
+
lock = read_lock(manager, lockfile)
|
|
233
|
+
return {name: max(vs, key=_version_key) for name, vs in lock.versions.items() if vs}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _version_key(v: str) -> tuple[int, ...]:
|
|
237
|
+
return tuple(int(p) if p.isdigit() else 0 for p in re.split(r"[.+-]", v)[:3])
|