lockly 0.1.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.
lockly/diff.py ADDED
@@ -0,0 +1,329 @@
1
+ """Compare two versions of a lockfile: what moved, and what deserves a look."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ from dataclasses import dataclass, field
7
+
8
+ from . import licenses, versions
9
+ from .model import Lockfile, Package
10
+
11
+ CHANGE_KINDS = ("added", "removed", "upgraded", "downgraded", "changed")
12
+
13
+ # Finding kinds, most serious first. Each says why a change deserves a
14
+ # reviewer's attention; the network ones need registry or OSV data.
15
+ FINDING_KINDS = (
16
+ "hash", # same version, different contents
17
+ "install-script", # now runs code when installed
18
+ "publisher", # published by a different account than before
19
+ "provenance", # the previous version had a provenance attestation; this one doesn't
20
+ "source", # comes from somewhere other than the registry, or from somewhere new
21
+ "new-package", # the package itself is only days old
22
+ "young", # this version is only days old
23
+ "vulnerable", # the new version has known vulnerabilities
24
+ "deprecated", # deprecated or yanked
25
+ "copyleft", # brings in copyleft terms
26
+ "license", # the licence changed
27
+ )
28
+ FAIL_ON_CHOICES = FINDING_KINDS + ("any",)
29
+
30
+
31
+ @dataclass
32
+ class Meta:
33
+ """What the registry and OSV say about one version. Every field may be
34
+ missing: not every registry exposes everything, and lookups can fail."""
35
+ published: str = ""
36
+ created: str = "" # when the package itself was first published
37
+ publisher: str = ""
38
+ trusted_publisher: bool = False # published from CI through OIDC, not a person's token
39
+ # The release just before this one in the registry, whoever installed it.
40
+ # An account takeover shows up as a release by a different, unfamiliar
41
+ # account from the one before it.
42
+ prev_version: str = ""
43
+ prev_publisher: str = ""
44
+ prev_trusted: bool = False
45
+ prev_provenance: bool | None = None
46
+ # Had this publisher published or maintained the package before? None
47
+ # when the registry can't say.
48
+ known_publisher: bool | None = None
49
+ license: str = ""
50
+ deprecated: str = "" # the deprecation or yank message
51
+ install_script: bool | None = None
52
+ provenance: bool | None = None
53
+ vulns: list[str] = field(default_factory=list)
54
+ vuln_details: dict[str, dict] = field(default_factory=dict) # id → {severity, summary}
55
+
56
+
57
+ @dataclass
58
+ class Change:
59
+ lockfile: str
60
+ kind: str
61
+ ecosystem: str
62
+ name: str
63
+ old: Package | None = None
64
+ new: Package | None = None
65
+ old_meta: Meta | None = None
66
+ new_meta: Meta | None = None
67
+
68
+ @property
69
+ def old_version(self) -> str:
70
+ return self.old.version if self.old else ""
71
+
72
+ @property
73
+ def new_version(self) -> str:
74
+ return self.new.version if self.new else ""
75
+
76
+ @property
77
+ def current(self) -> Package:
78
+ assert self.new or self.old
79
+ return self.new or self.old # type: ignore[return-value]
80
+
81
+ @property
82
+ def direct(self) -> bool | None:
83
+ return self.current.direct
84
+
85
+ @property
86
+ def dev(self) -> bool:
87
+ return self.current.dev
88
+
89
+
90
+ @dataclass
91
+ class Finding:
92
+ kind: str
93
+ lockfile: str
94
+ ecosystem: str
95
+ name: str
96
+ version: str
97
+ message: str
98
+ # False for findings worth showing but not stopping for (a known exploit
99
+ # gets fixed, a licence moves between two permissive ones).
100
+ gating: bool = True
101
+
102
+
103
+ @dataclass
104
+ class FileDiff:
105
+ path: str
106
+ kind: str
107
+ ecosystem: str
108
+ changes: list[Change] = field(default_factory=list)
109
+ unchanged: int = 0
110
+ findings: list[Finding] = field(default_factory=list)
111
+ fixed: dict[str, list[str]] = field(default_factory=dict) # "name version" → advisory IDs an upgrade fixed
112
+
113
+ def count(self, kind: str) -> int:
114
+ return sum(1 for c in self.changes if c.kind == kind)
115
+
116
+
117
+ @dataclass
118
+ class Diff:
119
+ files: list[FileDiff]
120
+ notes: list[str] = field(default_factory=list) # what couldn't be checked, and why
121
+
122
+ @property
123
+ def changes(self) -> list[Change]:
124
+ return [c for f in self.files for c in f.changes]
125
+
126
+ @property
127
+ def findings(self) -> list[Finding]:
128
+ return [x for f in self.files for x in f.findings]
129
+
130
+ def count(self, kind: str) -> int:
131
+ return sum(f.count(kind) for f in self.files)
132
+
133
+ def triggered(self, kinds: set[str]) -> dict[str, int]:
134
+ gating = [f for f in self.findings if f.gating]
135
+ if "any" in kinds:
136
+ kinds = set(FINDING_KINDS)
137
+ hits: dict[str, int] = {}
138
+ for f in gating:
139
+ if f.kind in kinds:
140
+ hits[f.kind] = hits.get(f.kind, 0) + 1
141
+ return hits
142
+
143
+
144
+ # ── Pairing ──────────────────────────────────────────────────────────
145
+
146
+ def _index(lock: Lockfile) -> dict[tuple[str, str], dict[str, Package]]:
147
+ out: dict[tuple[str, str], dict[str, Package]] = {}
148
+ for p in lock.packages:
149
+ out.setdefault(p.key, {})[p.version] = p
150
+ return out
151
+
152
+
153
+ def compare_lockfiles(old: Lockfile, new: Lockfile) -> FileDiff:
154
+ a, b = _index(old), _index(new)
155
+ result = FileDiff(new.path or old.path, new.kind or old.kind, new.ecosystem or old.ecosystem)
156
+ path = result.path
157
+ for key in sorted(set(a) | set(b), key=lambda k: k[1].lower()):
158
+ before, after = a.get(key, {}), b.get(key, {})
159
+ common = set(before) & set(after)
160
+ result.unchanged += len(common)
161
+ for version in sorted(common, key=versions.sort_key):
162
+ o, n = before[version], after[version]
163
+ # Same version, nothing to classify, but its contents or origin
164
+ # may still have changed; keep it for the findings.
165
+ if contents_differ(o.integrity, n.integrity) or o.source != n.source \
166
+ or (o.install_script is False and n.install_script):
167
+ result.changes.append(Change(path, "changed", key[0], n.name, o, n))
168
+ result.unchanged -= 1
169
+ gone = sorted((v for v in before if v not in common), key=versions.sort_key)
170
+ came = sorted((v for v in after if v not in common), key=versions.sort_key)
171
+ # Pair leftovers in version order: 1.0, 2.0 → 1.1, 2.1 is two upgrades.
172
+ while gone and came:
173
+ o, n = before[gone.pop(0)], after[came.pop(0)]
174
+ order = versions.compare(o.version, n.version)
175
+ kind = "upgraded" if order == -1 else "downgraded" if order == 1 else "changed"
176
+ result.changes.append(Change(path, kind, key[0], n.name, o, n))
177
+ for v in gone:
178
+ result.changes.append(Change(path, "removed", key[0], before[v].name, old=before[v]))
179
+ for v in came:
180
+ result.changes.append(Change(path, "added", key[0], after[v].name, new=after[v]))
181
+ return result
182
+
183
+
184
+ # ── Findings ─────────────────────────────────────────────────────────
185
+
186
+ def _digests(integrity: str) -> dict[str, str]:
187
+ """'sha512-abc sha1-def' → {sha512: abc, sha1: def}. Formats without an
188
+ algorithm prefix (Cargo's hex) count as one unnamed algorithm."""
189
+ out = {}
190
+ for part in integrity.split():
191
+ if part.startswith(("sha1-", "sha256-", "sha384-", "sha512-")): # npm SRI
192
+ alg, _, value = part.partition("-")
193
+ elif ":" in part[:8]: # sha256:… (uv, Poetry), h1:… (Go)
194
+ alg, _, value = part.partition(":")
195
+ elif "/" in part[:4]: # Yarn Berry's cacheKey/hash: a new cacheKey re-hashes
196
+ alg, _, value = part.partition("/")
197
+ else: # Cargo's bare hex
198
+ alg, value = "", part
199
+ out[alg] = value
200
+ return out
201
+
202
+
203
+ def contents_differ(a: str, b: str) -> bool:
204
+ """Same version, different hashes, by an algorithm both sides use. A
205
+ lockfile tool moving from sha1 to sha512 isn't a change of contents."""
206
+ if not a or not b:
207
+ return False
208
+ da, db = _digests(a), _digests(b)
209
+ common = set(da) & set(db)
210
+ return any(da[alg] != db[alg] for alg in common)
211
+
212
+
213
+ def _age_days(timestamp: str, now: datetime.datetime) -> float | None:
214
+ if not timestamp:
215
+ return None
216
+ try:
217
+ when = datetime.datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
218
+ except ValueError:
219
+ return None
220
+ if when.tzinfo is None:
221
+ when = when.replace(tzinfo=datetime.timezone.utc)
222
+ return (now - when).total_seconds() / 86400
223
+
224
+
225
+ def _ago(days: float) -> str:
226
+ if days < 1:
227
+ hours = max(1, round(days * 24))
228
+ return f"{hours} hour{'s' if hours != 1 else ''} ago"
229
+ whole = round(days)
230
+ return f"{whole} day{'s' if whole != 1 else ''} ago"
231
+
232
+
233
+ def find(fd: FileDiff, min_age_days: float = 3, new_package_days: float = 30,
234
+ now: datetime.datetime | None = None) -> None:
235
+ """Fill fd.findings from its changes and whatever enrichment added."""
236
+ now = now or datetime.datetime.now(datetime.timezone.utc)
237
+ out: list[Finding] = []
238
+ fixed: dict[str, list[str]] = {}
239
+
240
+ for c in fd.changes:
241
+ if c.kind == "removed" or c.new is None:
242
+ continue
243
+ new, old = c.new, c.old
244
+ nm, om = c.new_meta or Meta(), c.old_meta or Meta()
245
+
246
+ def add(kind: str, message: str, gating: bool = True) -> None:
247
+ out.append(Finding(kind, c.lockfile, c.ecosystem, c.name, new.version, message, gating))
248
+
249
+ if old and old.version == new.version and contents_differ(old.integrity, new.integrity):
250
+ add("hash", "same version, different contents: rebuilt, republished or tampered with")
251
+
252
+ scripts = new.install_script if new.install_script is not None else nm.install_script
253
+ had = (old.install_script if old and old.install_script is not None else om.install_script) if old else None
254
+ if scripts and (old is None or had is False):
255
+ add("install-script", "runs a script when installed" + (" (new in this version)" if old else ""))
256
+
257
+ new_version = old is None or old.version != new.version
258
+ if new_version and nm.publisher and nm.prev_publisher and nm.publisher != nm.prev_publisher:
259
+ prev = f"{nm.prev_version} was published by {nm.prev_publisher}"
260
+ if nm.trusted_publisher and not nm.prev_trusted:
261
+ # Moving to trusted publishing is an improvement, not a takeover.
262
+ add("publisher", f"now published through trusted publishing; {prev}", gating=False)
263
+ elif nm.prev_trusted and not nm.trusted_publisher:
264
+ add("publisher", f"published by {nm.publisher}, no longer through trusted publishing; {prev}")
265
+ elif nm.known_publisher is False:
266
+ add("publisher", f"published by {nm.publisher}, new to this package; {prev}")
267
+ # A maintainer of the previous release taking a turn is routine.
268
+ if new_version and nm.prev_provenance and nm.provenance is False:
269
+ add("provenance", f"{nm.prev_version}, the release before it, was published with a provenance "
270
+ "attestation; this version wasn't")
271
+
272
+ def origin(src: str) -> str:
273
+ if not src:
274
+ return "the registry"
275
+ if src.startswith("replaced by "):
276
+ return f"{src[12:]} (a replace directive)"
277
+ return {"git": "a git repository", "path": "a local path", "patch": "a local patch"}.get(src, src)
278
+
279
+ if old and new.source != old.source:
280
+ add("source", f"now comes from {origin(new.source)} instead of {origin(old.source)}")
281
+ elif old is None and new.source and new.source not in ("path", "patch"):
282
+ add("source", f"comes from {origin(new.source)}, not the registry")
283
+
284
+ created_age = _age_days(nm.created, now)
285
+ if old is None and created_age is not None and created_age < new_package_days:
286
+ add("new-package", f"the package was first published {_ago(created_age)}")
287
+ published = new.published or nm.published
288
+ age = _age_days(published, now)
289
+ if c.kind != "removed" and age is not None and age < min_age_days and (old is None or old.version != new.version):
290
+ add("young", f"this version was published {_ago(age)}")
291
+
292
+ introduced = [v for v in nm.vulns if v not in set(om.vulns)]
293
+ if nm.vulns and (old is None or introduced or old.version == new.version):
294
+ shown = nm.vulns if old is None else introduced or nm.vulns
295
+ add("vulnerable", f"{len(shown)} known vulnerabilit{'y' if len(shown) == 1 else 'ies'}: "
296
+ + ", ".join(_vuln_label(v, nm) for v in shown[:4]) + (f" and {len(shown) - 4} more" if len(shown) > 4 else ""))
297
+ resolved = [v for v in om.vulns if v not in set(nm.vulns)]
298
+ if old and resolved:
299
+ fixed[f"{c.name} {new.version}"] = resolved
300
+
301
+ if nm.deprecated and not (om.deprecated and old and old.version == new.version):
302
+ add("deprecated", nm.deprecated[:200])
303
+
304
+ new_lic = new.license or nm.license
305
+ old_lic = (old.license or om.license) if old else ""
306
+ level = licenses.copyleft_level(new_lic) if new_lic else licenses.NONE
307
+ old_level = licenses.copyleft_level(old_lic) if old_lic else licenses.NONE
308
+ if level > old_level:
309
+ add("copyleft", f"{licenses.LABELS[level]}: {new_lic}" + (f" (was {old_lic})" if old_lic else ""))
310
+ elif old and old_lic and new_lic and licenses.normalise(old_lic) != licenses.normalise(new_lic):
311
+ add("license", f"licence changed from {old_lic} to {new_lic}",
312
+ gating=level > licenses.NONE or old_level > licenses.NONE)
313
+ elif old and old_lic and not new_lic and (old.license or c.new_meta is not None):
314
+ # Only when the new version's licence was actually looked for: a
315
+ # lockfile field that vanished, or registry data that has none.
316
+ add("license", f"no longer declares a licence (was {old_lic})", gating=False)
317
+
318
+ order = {k: n for n, k in enumerate(FINDING_KINDS)}
319
+ fd.findings = sorted(out, key=lambda f: (not f.gating, order[f.kind], f.name.lower()))
320
+ fd.fixed = fixed
321
+
322
+
323
+ def _vuln_label(vid: str, meta: Meta) -> str:
324
+ sev = meta.vuln_details.get(vid, {}).get("severity", "")
325
+ return f"{vid} ({sev})" if sev and sev != "unknown" else vid
326
+
327
+
328
+ def diff(pairs: list[tuple[Lockfile, Lockfile]]) -> Diff:
329
+ return Diff([compare_lockfiles(old, new) for old, new in pairs])
lockly/enrich.py ADDED
@@ -0,0 +1,346 @@
1
+ """What the registries and OSV say about the versions that changed.
2
+
3
+ Only changed packages are looked up, so a lockfile with thousands of entries
4
+ and a handful of changes costs a handful of requests. Responses are cached for
5
+ a day. A lookup that fails leaves that field empty and a note on the diff; it
6
+ never stops the report.
7
+
8
+ npm registry.npmjs.org: publish time, publisher and whether it was
9
+ trusted publishing, provenance, licence, install scripts,
10
+ deprecation, when the package was created
11
+ PyPI pypi.org: upload time, licence, yanked, when the project was created
12
+ crates.io crates.io API: publish time, publisher, licence, yanked, created
13
+ (crates.io asks crawlers for one request a second, so these run
14
+ one at a time)
15
+ Go proxy.golang.org: publish time, when the module first appeared
16
+ all OSV: known vulnerabilities in the old and new versions
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import threading
24
+ import time
25
+ import urllib.error
26
+ import urllib.parse
27
+ import urllib.request
28
+ from concurrent.futures import ThreadPoolExecutor
29
+ from pathlib import Path
30
+
31
+ from . import __version__, cvss, versions
32
+ from .diff import Change, Diff, Meta
33
+ from .model import CARGO, GO, NPM, PYPI
34
+
35
+ _TIMEOUT = 5 # per connect and read, so a dead network costs seconds, not minutes
36
+ _DAY = 24 * 60 * 60
37
+ _MAX_BODY = 64_000_000 # the largest npm packuments run to tens of megabytes
38
+ _USER_AGENT = f"lockly/{__version__} (+https://github.com/fullstackspectrum/lockly)"
39
+
40
+
41
+ class LookupError_(Exception):
42
+ pass
43
+
44
+
45
+ # ── HTTP and cache ───────────────────────────────────────────────────
46
+
47
+ def cache_dir() -> Path:
48
+ if os.environ.get("LOCKLY_CACHE_DIR"):
49
+ return Path(os.environ["LOCKLY_CACHE_DIR"])
50
+ base = os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache"
51
+ return Path(base) / "lockly"
52
+
53
+
54
+ def _cache_path(url: str) -> Path:
55
+ import hashlib
56
+
57
+ return cache_dir() / "http" / (hashlib.sha256(url.encode()).hexdigest()[:40] + ".json")
58
+
59
+
60
+ def fetch(url: str, body: dict | None = None):
61
+ """GET (or POST JSON) and parse JSON. Tests replace this, so no test
62
+ reaches the network. 404 returns None."""
63
+ data = json.dumps(body).encode() if body is not None else None
64
+ req = urllib.request.Request(url, data, {"Accept": "application/json", "User-Agent": _USER_AGENT,
65
+ **({"Content-Type": "application/json"} if data else {})})
66
+ try:
67
+ with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp:
68
+ raw = resp.read(_MAX_BODY + 1)
69
+ except urllib.error.HTTPError as exc:
70
+ if exc.code == 404:
71
+ return None
72
+ raise LookupError_(f"HTTP {exc.code} from {urllib.parse.urlsplit(url).netloc}") from None
73
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
74
+ raise LookupError_(f"can't reach {urllib.parse.urlsplit(url).netloc} ({getattr(exc, 'reason', exc)})") from None
75
+ if len(raw) > _MAX_BODY:
76
+ raise LookupError_(f"response from {urllib.parse.urlsplit(url).netloc} is too large")
77
+ return json.loads(raw)
78
+
79
+
80
+ def _get(url: str, use_cache: bool = True):
81
+ path = _cache_path(url)
82
+ if use_cache:
83
+ try:
84
+ if time.time() - path.stat().st_mtime < _DAY:
85
+ return json.loads(path.read_text("utf-8"))
86
+ except (OSError, ValueError):
87
+ pass
88
+ value = fetch(url)
89
+ if use_cache:
90
+ try:
91
+ path.parent.mkdir(parents=True, exist_ok=True)
92
+ tmp = path.with_suffix(f".{os.getpid()}.{threading.get_ident()}.tmp")
93
+ tmp.write_text(json.dumps(value), "utf-8")
94
+ tmp.replace(path)
95
+ except OSError:
96
+ pass
97
+ return value
98
+
99
+
100
+ # ── Registries ───────────────────────────────────────────────────────
101
+
102
+ def _previous(all_versions, version: str) -> str:
103
+ """The release just before this one: the highest lower version, skipping
104
+ pre-releases unless this is one."""
105
+ stable = "-" not in version
106
+ lower = [v for v in all_versions if versions.compare(v, version) == -1 and (not stable or "-" not in v)]
107
+ return max(lower, key=versions.sort_key) if lower else ""
108
+
109
+
110
+ def _npm(name: str, version: str, want_created: bool, cache: bool) -> Meta:
111
+ doc = _get("https://registry.npmjs.org/" + urllib.parse.quote(name, safe="@"), cache) or {}
112
+ all_versions = doc.get("versions") or {}
113
+ v = all_versions.get(version) or {}
114
+ user = v.get("_npmUser") or {}
115
+ prev = _previous(all_versions, version)
116
+ pv = all_versions.get(prev) or {}
117
+ prev_user = pv.get("_npmUser") or {}
118
+ known = None
119
+ if user.get("name") and prev:
120
+ maintainers = {m.get("name") for m in pv.get("maintainers") or []}
121
+ earlier = {(all_versions[x].get("_npmUser") or {}).get("name") for x in all_versions
122
+ if versions.compare(x, version) == -1}
123
+ known = user["name"] in maintainers | earlier
124
+ scripts = v.get("scripts") or {}
125
+ times = doc.get("time") or {}
126
+ lic = v.get("license")
127
+ if isinstance(lic, dict): # old packages: {"type": "MIT", "url": ...}
128
+ lic = lic.get("type", "")
129
+ return Meta(
130
+ published=str(times.get(version) or ""),
131
+ created=str(times.get("created") or "") if want_created else "",
132
+ publisher=str(user.get("name") or ""),
133
+ trusted_publisher=bool(user.get("trustedPublisher")),
134
+ prev_version=prev,
135
+ prev_publisher=str(prev_user.get("name") or ""),
136
+ prev_trusted=bool(prev_user.get("trustedPublisher")),
137
+ prev_provenance=bool(((pv.get("dist") or {}).get("attestations") or {}).get("provenance")) if pv else None,
138
+ known_publisher=known,
139
+ license=lic if isinstance(lic, str) else "",
140
+ deprecated=str(v.get("deprecated") or ""),
141
+ install_script=any(k in scripts for k in ("preinstall", "install", "postinstall")) if v else None,
142
+ provenance=bool(((v.get("dist") or {}).get("attestations") or {}).get("provenance")) if v else None,
143
+ )
144
+
145
+
146
+ def _pypi(name: str, version: str, want_created: bool, cache: bool) -> Meta:
147
+ doc = _get(f"https://pypi.org/pypi/{urllib.parse.quote(name)}/{urllib.parse.quote(version)}/json", cache) or {}
148
+ info = doc.get("info") or {}
149
+ uploads = [u.get("upload_time_iso_8601") for u in doc.get("urls") or [] if u.get("upload_time_iso_8601")]
150
+ lic = info.get("license_expression") or info.get("license") or ""
151
+ if not lic or len(lic) > 80: # some projects paste the whole licence text
152
+ classifiers = [c.split("::")[-1].strip() for c in info.get("classifiers") or [] if c.startswith("License ::")]
153
+ lic = " OR ".join(classifiers) if classifiers else ("" if len(lic) > 80 else lic)
154
+ meta = Meta(published=min(uploads) if uploads else "", license=lic,
155
+ deprecated=f"yanked: {info.get('yanked_reason') or 'no reason given'}" if info.get("yanked") else "")
156
+ if want_created:
157
+ project = _get(f"https://pypi.org/pypi/{urllib.parse.quote(name)}/json", cache) or {}
158
+ first = [f.get("upload_time_iso_8601") for files in (project.get("releases") or {}).values()
159
+ for f in files if f.get("upload_time_iso_8601")]
160
+ meta.created = min(first) if first else ""
161
+ return meta
162
+
163
+
164
+ _crates_lock = threading.Lock()
165
+ _crates_last = [0.0]
166
+
167
+
168
+ def _crates_get(url: str, cache: bool):
169
+ path = _cache_path(url)
170
+ if cache and path.exists() and time.time() - path.stat().st_mtime < _DAY:
171
+ return _get(url, cache)
172
+ with _crates_lock: # crates.io's crawler policy: one request a second
173
+ wait = _crates_last[0] + 1.0 - time.monotonic()
174
+ if wait > 0:
175
+ time.sleep(wait)
176
+ try:
177
+ return _get(url, cache)
178
+ finally:
179
+ _crates_last[0] = time.monotonic()
180
+
181
+
182
+ def _crates(name: str, version: str, want_created: bool, cache: bool) -> Meta:
183
+ # One request lists every version with its publisher, so it covers this
184
+ # version, the one before it, and when the crate first appeared.
185
+ doc = _crates_get(f"https://crates.io/api/v1/crates/{urllib.parse.quote(name)}/versions", cache) or {}
186
+ by_num = {str(v.get("num")): v for v in doc.get("versions") or []}
187
+ v = by_num.get(version) or {}
188
+ prev = _previous(by_num, version)
189
+ pv = by_num.get(prev) or {}
190
+ login = lambda x: str((x.get("published_by") or {}).get("login") or "") # noqa: E731
191
+ publisher = login(v)
192
+ earlier = {login(x) for num, x in by_num.items() if versions.compare(num, version) == -1}
193
+ created = [str(x.get("created_at")) for x in by_num.values() if x.get("created_at")]
194
+ return Meta(published=str(v.get("created_at") or ""), license=str(v.get("license") or ""),
195
+ publisher=publisher, trusted_publisher=bool(v.get("trustpub_data")),
196
+ prev_version=prev, prev_publisher=login(pv), prev_trusted=bool(pv.get("trustpub_data")),
197
+ known_publisher=(publisher in earlier) if publisher and prev else None,
198
+ deprecated="yanked" if v.get("yanked") else "",
199
+ created=min(created) if want_created and created else "")
200
+
201
+
202
+ def _go_escape(path: str) -> str:
203
+ """The module proxy's case encoding: Azure → !azure."""
204
+ return "".join("!" + ch.lower() if ch.isupper() else ch for ch in path)
205
+
206
+
207
+ def _go(name: str, version: str, want_created: bool, cache: bool) -> Meta:
208
+ base = f"https://proxy.golang.org/{_go_escape(name)}/@v/"
209
+ info = _get(base + _go_escape(version) + ".info", cache) or {}
210
+ meta = Meta(published=str(info.get("Time") or ""))
211
+ if want_created:
212
+ # The proxy has no creation date; the oldest tagged version's will do.
213
+ listing = _get_text(base + "list", cache)
214
+ tagged = sorted((v for v in listing.split() if v), key=versions.sort_key)
215
+ if tagged:
216
+ first = _get(base + _go_escape(tagged[0]) + ".info", cache) or {}
217
+ meta.created = str(first.get("Time") or "")
218
+ return meta
219
+
220
+
221
+ def _get_text(url: str, cache: bool) -> str:
222
+ """/@v/list is plain text; cached as a JSON string."""
223
+ path = _cache_path(url)
224
+ if cache:
225
+ try:
226
+ if time.time() - path.stat().st_mtime < _DAY:
227
+ return json.loads(path.read_text("utf-8"))
228
+ except (OSError, ValueError):
229
+ pass
230
+ req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT})
231
+ try:
232
+ with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp:
233
+ text = resp.read(1_000_000).decode("utf-8", "replace")
234
+ except urllib.error.HTTPError as exc:
235
+ if exc.code in (404, 410):
236
+ return ""
237
+ raise LookupError_(f"HTTP {exc.code} from proxy.golang.org") from None
238
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
239
+ raise LookupError_(f"can't reach proxy.golang.org ({getattr(exc, 'reason', exc)})") from None
240
+ if cache:
241
+ try:
242
+ path.parent.mkdir(parents=True, exist_ok=True)
243
+ path.write_text(json.dumps(text), "utf-8")
244
+ except OSError:
245
+ pass
246
+ return text
247
+
248
+
249
+ _REGISTRIES = {NPM: _npm, PYPI: _pypi, CARGO: _crates, GO: _go}
250
+
251
+
252
+ # ── OSV ──────────────────────────────────────────────────────────────
253
+
254
+ def _osv(queries: list[tuple[str, str, str]]) -> dict[tuple[str, str, str], list[str]]:
255
+ """(ecosystem, name, version) → vulnerability IDs. querybatch isn't
256
+ cached: it's one request, and new advisories matter most."""
257
+ out: dict[tuple[str, str, str], list[str]] = {}
258
+ for start in range(0, len(queries), 1000):
259
+ chunk = queries[start:start + 1000]
260
+ body = {"queries": [{"package": {"ecosystem": e, "name": n}, "version": v} for e, n, v in chunk]}
261
+ doc = fetch("https://api.osv.dev/v1/querybatch", body) or {}
262
+ for q, r in zip(chunk, doc.get("results") or []):
263
+ out[q] = sorted({x["id"] for x in r.get("vulns") or []})
264
+ return out
265
+
266
+
267
+ def _osv_detail(vid: str, cache: bool) -> dict:
268
+ record = _get(f"https://api.osv.dev/v1/vulns/{urllib.parse.quote(vid)}", cache) or {}
269
+ score = None
270
+ for s in record.get("severity") or []:
271
+ if s.get("type") in ("CVSS_V3", "CVSS_V4"):
272
+ score = cvss.score(s.get("score", ""))
273
+ if score is not None:
274
+ break
275
+ label = cvss.severity(score)
276
+ if label == "unknown":
277
+ ghsa = str((record.get("database_specific") or {}).get("severity", "")).lower()
278
+ label = {"moderate": "medium"}.get(ghsa, ghsa) if ghsa in ("critical", "high", "moderate", "medium", "low") else "unknown"
279
+ cve = next((a for a in record.get("aliases") or [] if a.startswith("CVE-")), "")
280
+ return {"severity": label, "score": score, "summary": (record.get("summary") or "")[:160], "cve": cve}
281
+
282
+
283
+ # ── Putting it together ──────────────────────────────────────────────
284
+
285
+ def enrich(d: Diff, cache: bool = True, workers: int = 8) -> None:
286
+ """Fill old_meta and new_meta on every change, and note what failed."""
287
+ wanted: dict[tuple[str, str, str], bool] = {} # (eco, name, version) → also want created
288
+ for c in d.changes:
289
+ if c.kind == "removed":
290
+ continue # nothing is flagged on a removal, so nothing to look up
291
+ for pkg, is_new in ((c.old, False), (c.new, True)):
292
+ if pkg and pkg.ecosystem in _REGISTRIES and pkg.source in ("",) and pkg.version:
293
+ key = (pkg.ecosystem, pkg.name, pkg.version)
294
+ wanted[key] = wanted.get(key, False) or (is_new and c.kind == "added")
295
+
296
+ failures: dict[str, str] = {}
297
+ lock = threading.Lock()
298
+ metas: dict[tuple[str, str, str], Meta] = {}
299
+
300
+ def look(item):
301
+ (eco, name, version), want_created = item
302
+ try:
303
+ metas[(eco, name, version)] = _REGISTRIES[eco](name, version, want_created, cache)
304
+ except (LookupError_, ValueError) as exc:
305
+ with lock:
306
+ failures.setdefault(eco, str(exc))
307
+
308
+ items = list(wanted.items())
309
+ crates = [i for i in items if i[0][0] == CARGO]
310
+ others = [i for i in items if i[0][0] != CARGO]
311
+ with ThreadPoolExecutor(workers) as pool:
312
+ future = pool.submit(lambda: [look(i) for i in crates]) # one at a time, in one thread
313
+ list(pool.map(look, others))
314
+ future.result()
315
+
316
+ try:
317
+ vulns = _osv(list(wanted)) if wanted else {}
318
+ except (LookupError_, ValueError) as exc:
319
+ vulns = {}
320
+ failures["OSV"] = str(exc)
321
+ for key, ids in vulns.items():
322
+ metas.setdefault(key, Meta()).vulns = ids
323
+
324
+ # Severity for the vulnerabilities the change brings in.
325
+ introduced = {vid for c in d.changes if c.new for vid in vulns.get((c.new.ecosystem, c.new.name, c.new.version), [])
326
+ if not c.old or vid not in vulns.get((c.old.ecosystem, c.old.name, c.old.version), [])}
327
+ details: dict[str, dict] = {}
328
+
329
+ def detail(vid):
330
+ try:
331
+ details[vid] = _osv_detail(vid, cache)
332
+ except (LookupError_, ValueError):
333
+ pass
334
+
335
+ with ThreadPoolExecutor(workers) as pool:
336
+ list(pool.map(detail, sorted(introduced)))
337
+ for meta in metas.values():
338
+ meta.vuln_details = {v: details[v] for v in meta.vulns if v in details}
339
+
340
+ for c in d.changes:
341
+ if c.old:
342
+ c.old_meta = metas.get((c.old.ecosystem, c.old.name, c.old.version))
343
+ if c.new:
344
+ c.new_meta = metas.get((c.new.ecosystem, c.new.name, c.new.version))
345
+ for where, why in sorted(failures.items()):
346
+ d.notes.append(f"{where} lookups incomplete: {why}")