codeveto 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.
- codeveto/__init__.py +3 -0
- codeveto/__main__.py +8 -0
- codeveto/ai/__init__.py +19 -0
- codeveto/ai/harness.py +303 -0
- codeveto/ai/packets.py +855 -0
- codeveto/ai/policy.py +222 -0
- codeveto/ai/prompt.py +101 -0
- codeveto/ai/providers/__init__.py +178 -0
- codeveto/ai/providers/claude.py +247 -0
- codeveto/ai/providers/openai_compat.py +246 -0
- codeveto/ai/runner.py +293 -0
- codeveto/ai/verify.py +324 -0
- codeveto/anchor.py +211 -0
- codeveto/cli.py +247 -0
- codeveto/cli_explain.py +49 -0
- codeveto/cli_hook.py +31 -0
- codeveto/cli_init.py +254 -0
- codeveto/cli_mcp.py +29 -0
- codeveto/cli_packets.py +35 -0
- codeveto/cli_publish.py +29 -0
- codeveto/cli_review.py +362 -0
- codeveto/cli_rules.py +78 -0
- codeveto/cli_verify.py +47 -0
- codeveto/config.py +1229 -0
- codeveto/data/README.md +16 -0
- codeveto/data/ai-wire.schema.json +53 -0
- codeveto/data/prompts/system.md +57 -0
- codeveto/data/report-v1.schema.json +268 -0
- codeveto/data/templates/forgejo-codeveto.yml +104 -0
- codeveto/data/templates/github-codeveto.yml +18 -0
- codeveto/embedded.py +311 -0
- codeveto/engine.py +1570 -0
- codeveto/git.py +1549 -0
- codeveto/globs.py +348 -0
- codeveto/integrations/__init__.py +1 -0
- codeveto/integrations/hooks.py +327 -0
- codeveto/integrations/mcp.py +770 -0
- codeveto/integrations/mcp_ai.py +77 -0
- codeveto/integrations/prepush.py +222 -0
- codeveto/jsonsafe.py +60 -0
- codeveto/languages.py +539 -0
- codeveto/lexers.py +2560 -0
- codeveto/model.py +372 -0
- codeveto/publish/__init__.py +28 -0
- codeveto/publish/action.py +330 -0
- codeveto/publish/common.py +84 -0
- codeveto/publish/diff.py +208 -0
- codeveto/publish/event.py +241 -0
- codeveto/publish/forgejo.py +184 -0
- codeveto/publish/github.py +380 -0
- codeveto/publish/http.py +263 -0
- codeveto/publish/pull.py +218 -0
- codeveto/publish/untrusted.py +110 -0
- codeveto/py.typed +0 -0
- codeveto/redact.py +113 -0
- codeveto/render/__init__.py +64 -0
- codeveto/render/agent.py +43 -0
- codeveto/render/github.py +101 -0
- codeveto/render/json.py +23 -0
- codeveto/render/markdown.py +208 -0
- codeveto/render/safe.py +249 -0
- codeveto/render/sarif.py +217 -0
- codeveto/render/text.py +210 -0
- codeveto/report.py +252 -0
- codeveto/rules/__init__.py +84 -0
- codeveto/rules/agent.py +2972 -0
- codeveto/rules/base.py +1026 -0
- codeveto/rules/ci.py +1708 -0
- codeveto/rules/config.py +493 -0
- codeveto/rules/deps.py +1693 -0
- codeveto/rules/docker.py +479 -0
- codeveto/rules/examples/__init__.py +148 -0
- codeveto/rules/examples/agent.py +839 -0
- codeveto/rules/examples/ci.py +1046 -0
- codeveto/rules/examples/config.py +191 -0
- codeveto/rules/examples/deps.py +369 -0
- codeveto/rules/examples/docker.py +157 -0
- codeveto/rules/examples/go.py +241 -0
- codeveto/rules/examples/hygiene.py +466 -0
- codeveto/rules/examples/js.py +462 -0
- codeveto/rules/examples/python.py +595 -0
- codeveto/rules/examples/rust.py +268 -0
- codeveto/rules/examples/secrets.py +561 -0
- codeveto/rules/examples/security.py +608 -0
- codeveto/rules/examples/shell.py +174 -0
- codeveto/rules/examples/sql.py +194 -0
- codeveto/rules/examples/tests.py +497 -0
- codeveto/rules/go.py +328 -0
- codeveto/rules/hygiene.py +1094 -0
- codeveto/rules/js.py +768 -0
- codeveto/rules/python.py +1642 -0
- codeveto/rules/rust.py +209 -0
- codeveto/rules/secrets.py +1335 -0
- codeveto/rules/security.py +3680 -0
- codeveto/rules/shell.py +867 -0
- codeveto/rules/sql.py +629 -0
- codeveto/rules/tests.py +1404 -0
- codeveto/schema.py +384 -0
- codeveto/statements.py +607 -0
- codeveto/worktree.py +1176 -0
- codeveto/yamlish.py +1179 -0
- codeveto-0.1.0.dist-info/METADATA +253 -0
- codeveto-0.1.0.dist-info/RECORD +106 -0
- codeveto-0.1.0.dist-info/WHEEL +4 -0
- codeveto-0.1.0.dist-info/entry_points.txt +2 -0
- codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
codeveto/rules/deps.py
ADDED
|
@@ -0,0 +1,1693 @@
|
|
|
1
|
+
"""Deps pack (SPEC 6.1): manifests, lockfiles, registry configuration and submodules.
|
|
2
|
+
|
|
3
|
+
Structured files are read with the context's parsers (``json``, ``toml``,
|
|
4
|
+
``yaml``; ``tomllib`` and ``yamlish`` for the other side of a change or a
|
|
5
|
+
lockfile in a text-named file), text formats (``requirements*.txt``,
|
|
6
|
+
``go.mod``, ``go.sum``, ``Gemfile``, ``Gemfile.lock``, ``yarn.lock`` v1,
|
|
7
|
+
``.npmrc``, ``pip.conf``, ``.gitmodules``) line by line. Parsed values only
|
|
8
|
+
locate their lines through bounded per-line patterns.
|
|
9
|
+
|
|
10
|
+
Most rules are ``line`` rules with ``evidence`` (the engine drops findings
|
|
11
|
+
that already existed on the old side); the rules that compare old and new
|
|
12
|
+
themselves are ``file`` or ``change`` rules.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import re
|
|
19
|
+
import tomllib
|
|
20
|
+
from collections.abc import Iterator
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
|
|
23
|
+
from codeveto import jsonsafe, yamlish
|
|
24
|
+
from codeveto.model import FileKind, FileStatus, git_lines
|
|
25
|
+
from codeveto.rules.base import ChangeContext, FileContext, Hit, PartialCoverage, rule
|
|
26
|
+
from codeveto.yamlish import YamlMap, YamlScalar, YamlSeq
|
|
27
|
+
|
|
28
|
+
# --- Paths --------------------------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _base(path: str) -> str:
|
|
32
|
+
return path.rsplit("/", 1)[-1]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _dir(path: str) -> str:
|
|
36
|
+
return path.rsplit("/", 1)[0] if "/" in path else ""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _is_requirements(path: str) -> bool:
|
|
40
|
+
name = _base(path)
|
|
41
|
+
if name.endswith(".txt") and name.startswith("requirements"):
|
|
42
|
+
return True
|
|
43
|
+
return name.endswith(".txt") and "/requirements/" in "/" + path
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
MANIFESTS = {
|
|
47
|
+
"package.json": "npm",
|
|
48
|
+
"composer.json": "composer",
|
|
49
|
+
"pyproject.toml": "python",
|
|
50
|
+
"Pipfile": "python",
|
|
51
|
+
"Cargo.toml": "cargo",
|
|
52
|
+
"go.mod": "go",
|
|
53
|
+
"Gemfile": "ruby",
|
|
54
|
+
}
|
|
55
|
+
LOCKFILES = {
|
|
56
|
+
"package-lock.json": "npm",
|
|
57
|
+
"npm-shrinkwrap.json": "npm",
|
|
58
|
+
"yarn.lock": "npm",
|
|
59
|
+
"pnpm-lock.yaml": "npm",
|
|
60
|
+
"uv.lock": "python",
|
|
61
|
+
"poetry.lock": "python",
|
|
62
|
+
"pdm.lock": "python",
|
|
63
|
+
"Pipfile.lock": "python",
|
|
64
|
+
"Cargo.lock": "cargo",
|
|
65
|
+
"go.sum": "go",
|
|
66
|
+
"Gemfile.lock": "ruby",
|
|
67
|
+
"composer.lock": "composer",
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def manifest_kind(path: str) -> str | None:
|
|
72
|
+
"""The manifest format of ``path`` (``requirements`` for requirements files)."""
|
|
73
|
+
name = _base(path)
|
|
74
|
+
if name in MANIFESTS:
|
|
75
|
+
return name
|
|
76
|
+
return "requirements" if _is_requirements(path) else None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# --- Small parsing helpers -------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _json(text: str | None) -> object:
|
|
83
|
+
if not text:
|
|
84
|
+
return None
|
|
85
|
+
try:
|
|
86
|
+
return jsonsafe.loads(text.removeprefix(""))
|
|
87
|
+
except (ValueError, RecursionError):
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _toml(text: str | None) -> dict[str, object] | None:
|
|
92
|
+
if not text:
|
|
93
|
+
return None
|
|
94
|
+
try:
|
|
95
|
+
return tomllib.loads(text.removeprefix(""))
|
|
96
|
+
except (ValueError, RecursionError):
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _dict(value: object) -> dict[str, object]:
|
|
101
|
+
return value if isinstance(value, dict) else {}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _str(value: object) -> str:
|
|
105
|
+
return value if isinstance(value, str) else ""
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _pyname(name: str) -> str:
|
|
109
|
+
return re.sub(r"[-_.]+", "-", name).lower()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
_TOML_HEADER = re.compile(r"\s{0,40}(\[\[?)\s{0,5}([^\]\n]{1,500}?)\s{0,5}\]\]?\s{0,40}(?:#.*)?\Z")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _split_key(text: str) -> tuple[str, ...]:
|
|
116
|
+
parts: list[str] = []
|
|
117
|
+
buf = ""
|
|
118
|
+
quote = ""
|
|
119
|
+
for c in text:
|
|
120
|
+
if quote:
|
|
121
|
+
if c == quote:
|
|
122
|
+
quote = ""
|
|
123
|
+
else:
|
|
124
|
+
buf += c
|
|
125
|
+
elif c in "\"'":
|
|
126
|
+
quote = c
|
|
127
|
+
elif c == ".":
|
|
128
|
+
parts.append(buf.strip())
|
|
129
|
+
buf = ""
|
|
130
|
+
else:
|
|
131
|
+
buf += c
|
|
132
|
+
parts.append(buf.strip())
|
|
133
|
+
return tuple(parts)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass(frozen=True, slots=True)
|
|
137
|
+
class TomlTable:
|
|
138
|
+
path: tuple[str, ...]
|
|
139
|
+
array: bool
|
|
140
|
+
header: int
|
|
141
|
+
end: int
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class TomlLines:
|
|
145
|
+
"""Where each TOML table starts and ends, to locate values ``tomllib`` returned.
|
|
146
|
+
|
|
147
|
+
Line 0 stands for the root table (before the first header).
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
def __init__(self, lines: tuple[str, ...]) -> None:
|
|
151
|
+
self.lines = lines
|
|
152
|
+
tables: list[TomlTable] = []
|
|
153
|
+
current: tuple[tuple[str, ...], bool, int] = ((), False, 0)
|
|
154
|
+
multiline = ""
|
|
155
|
+
for number, line in enumerate(lines, start=1):
|
|
156
|
+
if multiline:
|
|
157
|
+
if line.count(multiline) % 2 == 1:
|
|
158
|
+
multiline = ""
|
|
159
|
+
continue
|
|
160
|
+
for delim in ('"""', "'''"):
|
|
161
|
+
if line.count(delim) % 2 == 1:
|
|
162
|
+
multiline = delim
|
|
163
|
+
m = _TOML_HEADER.match(line) if line.lstrip().startswith("[") else None
|
|
164
|
+
if m is None or "=" in line.split("]", 1)[0]:
|
|
165
|
+
continue
|
|
166
|
+
tables.append(TomlTable(current[0], current[1], current[2], number - 1))
|
|
167
|
+
current = (_split_key(m.group(2)), m.group(1) == "[[", number)
|
|
168
|
+
tables.append(TomlTable(current[0], current[1], current[2], len(lines)))
|
|
169
|
+
self.tables = tuple(tables)
|
|
170
|
+
|
|
171
|
+
def find(self, path: tuple[str, ...], index: int | None = None) -> list[TomlTable]:
|
|
172
|
+
found = [t for t in self.tables if t.path == path]
|
|
173
|
+
if index is not None:
|
|
174
|
+
return found[index : index + 1]
|
|
175
|
+
return found
|
|
176
|
+
|
|
177
|
+
def key_line(self, table: TomlTable, key: str) -> int | None:
|
|
178
|
+
pattern = re.compile(
|
|
179
|
+
r"\s{0,40}(?:"
|
|
180
|
+
+ re.escape(json.dumps(key))
|
|
181
|
+
+ "|'"
|
|
182
|
+
+ re.escape(key)
|
|
183
|
+
+ "'|"
|
|
184
|
+
+ re.escape(key)
|
|
185
|
+
+ r")\s{0,10}="
|
|
186
|
+
)
|
|
187
|
+
for number in range(table.header + 1, table.end + 1):
|
|
188
|
+
if pattern.match(self.lines[number - 1]):
|
|
189
|
+
return number
|
|
190
|
+
return None
|
|
191
|
+
|
|
192
|
+
def locate(self, path: tuple[str, ...], key: str, value: str | None = None) -> int | None:
|
|
193
|
+
"""Line of ``key`` in table ``path`` (or of ``value`` in its array, or of a subtable)."""
|
|
194
|
+
for table in self.find(path):
|
|
195
|
+
line = self.key_line(table, key)
|
|
196
|
+
if line is not None and value is not None:
|
|
197
|
+
quoted = (json.dumps(value), "'" + value + "'")
|
|
198
|
+
for number in range(line, table.end + 1):
|
|
199
|
+
if any(q in self.lines[number - 1] for q in quoted):
|
|
200
|
+
return number
|
|
201
|
+
if line is not None:
|
|
202
|
+
return line
|
|
203
|
+
for table in self.find((*path, key)):
|
|
204
|
+
return table.header
|
|
205
|
+
if len(path) >= 1:
|
|
206
|
+
# a dotted key in the parent table: [project] ... dependencies = [...]
|
|
207
|
+
parent = path[:-1]
|
|
208
|
+
for table in self.find(parent):
|
|
209
|
+
line = self.key_line(table, f"{path[-1]}.{key}")
|
|
210
|
+
if line is not None:
|
|
211
|
+
return line
|
|
212
|
+
return None
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
_JSON_KEY = re.compile(r'\s{0,80}("(?:[^"\\\n]|\\.){1,400}")\s{0,10}:')
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def json_key_lines(lines: tuple[str, ...]) -> list[tuple[int, str, int]]:
|
|
219
|
+
"""``(line, key, indent)`` of each line that starts with a JSON object key."""
|
|
220
|
+
out: list[tuple[int, str, int]] = []
|
|
221
|
+
for number, line in enumerate(lines, start=1):
|
|
222
|
+
m = _JSON_KEY.match(line)
|
|
223
|
+
if m is not None:
|
|
224
|
+
try:
|
|
225
|
+
key = json.loads(m.group(1))
|
|
226
|
+
except ValueError:
|
|
227
|
+
continue
|
|
228
|
+
out.append((number, key, len(line) - len(line.lstrip())))
|
|
229
|
+
return out
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def json_locate(keys: list[tuple[int, str, int]], section: str, name: str) -> int | None:
|
|
233
|
+
"""Line of key ``name`` after the first key ``section`` (deeper than it)."""
|
|
234
|
+
start = None
|
|
235
|
+
indent = 0
|
|
236
|
+
for number, key, ind in keys:
|
|
237
|
+
if start is None:
|
|
238
|
+
if key == section:
|
|
239
|
+
start, indent = number, ind
|
|
240
|
+
continue
|
|
241
|
+
if ind <= indent:
|
|
242
|
+
break
|
|
243
|
+
if key == name:
|
|
244
|
+
return number
|
|
245
|
+
return None
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
# --- Dependencies ------------------------------------------------------------------------
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
@dataclass(frozen=True, slots=True)
|
|
252
|
+
class Dep:
|
|
253
|
+
"""One dependency declaration.
|
|
254
|
+
|
|
255
|
+
``kind`` is ``version`` (from a registry), ``url``, ``git``, ``path``
|
|
256
|
+
(local or workspace) or ``source`` (an override that does not declare
|
|
257
|
+
a dependency itself, like ``tool.uv.sources``).
|
|
258
|
+
"""
|
|
259
|
+
|
|
260
|
+
ecosystem: str
|
|
261
|
+
section: str
|
|
262
|
+
name: str
|
|
263
|
+
spec: str
|
|
264
|
+
kind: str
|
|
265
|
+
line: int | None
|
|
266
|
+
|
|
267
|
+
@property
|
|
268
|
+
def key(self) -> str:
|
|
269
|
+
return _pyname(self.name) if self.ecosystem == "python" else self.name
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
_NPM_SECTIONS = ("dependencies", "devDependencies", "optionalDependencies", "peerDependencies")
|
|
273
|
+
_NPM_LOCAL = ("file:", "link:", "workspace:", "portal:", "patch:")
|
|
274
|
+
_NPM_URL = re.compile(r"(?:git\+|git:|git@|github:|gitlab:|bitbucket:|gist:|https?:)")
|
|
275
|
+
_NPM_SHORTHAND = re.compile(r"[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}(?:#\S{0,200})?")
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _npm_kind(spec: str) -> str:
|
|
279
|
+
s = spec.strip()
|
|
280
|
+
if s.startswith(_NPM_LOCAL):
|
|
281
|
+
return "path"
|
|
282
|
+
if _NPM_URL.match(s):
|
|
283
|
+
return "git" if not s.startswith(("http:", "https:")) or ".git" in s else "url"
|
|
284
|
+
if not s.startswith(("npm:", "@")) and _NPM_SHORTHAND.fullmatch(s):
|
|
285
|
+
return "git"
|
|
286
|
+
return "version"
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _npm_deps(data: object, lines: tuple[str, ...]) -> list[Dep]:
|
|
290
|
+
keys = json_key_lines(lines)
|
|
291
|
+
out: list[Dep] = []
|
|
292
|
+
for section in _NPM_SECTIONS:
|
|
293
|
+
for name, spec in _dict(_dict(data).get(section)).items():
|
|
294
|
+
if isinstance(spec, str):
|
|
295
|
+
line = json_locate(keys, section, name)
|
|
296
|
+
out.append(Dep("npm", section, name, spec, _npm_kind(spec), line))
|
|
297
|
+
return out
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
_COMPOSER_PLATFORM = re.compile(r"(?:php|hhvm|composer(?:-[a-z-]{1,40})?|(?:ext|lib)-.{1,100})")
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _composer_deps(data: object, lines: tuple[str, ...]) -> list[Dep]:
|
|
304
|
+
keys = json_key_lines(lines)
|
|
305
|
+
out: list[Dep] = []
|
|
306
|
+
for section in ("require", "require-dev"):
|
|
307
|
+
for name, spec in _dict(_dict(data).get(section)).items():
|
|
308
|
+
if isinstance(spec, str) and not _COMPOSER_PLATFORM.fullmatch(name):
|
|
309
|
+
line = json_locate(keys, section, name)
|
|
310
|
+
out.append(Dep("composer", section, name, spec, "version", line))
|
|
311
|
+
return out
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
_PEP508 = re.compile(
|
|
315
|
+
r"\s{0,20}([A-Za-z0-9](?:[A-Za-z0-9._-]{0,200}[A-Za-z0-9])?)\s{0,20}(\[[^\]]{0,500}\])?(.*)"
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def pep508(text: str) -> tuple[str, str, str] | None:
|
|
320
|
+
"""``(name, spec, kind)`` of a PEP 508 requirement (``spec`` is the URL for URL ones)."""
|
|
321
|
+
m = _PEP508.match(text)
|
|
322
|
+
if m is None:
|
|
323
|
+
return None
|
|
324
|
+
rest = m.group(3).split(";", 1)[0].strip()
|
|
325
|
+
if rest.startswith("@"):
|
|
326
|
+
url = rest[1:].strip()
|
|
327
|
+
kind = "git" if url.startswith("git+") else "path" if url.startswith("file:") else "url"
|
|
328
|
+
return m.group(1), url, kind
|
|
329
|
+
return m.group(1), rest, "version"
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _py_list(
|
|
333
|
+
out: list[Dep], index: TomlLines, items: object, path: tuple[str, ...], key: str, section: str
|
|
334
|
+
) -> None:
|
|
335
|
+
if not isinstance(items, list):
|
|
336
|
+
return
|
|
337
|
+
for item in items:
|
|
338
|
+
if not isinstance(item, str):
|
|
339
|
+
continue
|
|
340
|
+
parsed = pep508(item)
|
|
341
|
+
if parsed is not None:
|
|
342
|
+
line = index.locate(path, key, item)
|
|
343
|
+
out.append(Dep("python", section, parsed[0], parsed[1], parsed[2], line))
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _table_kind(value: object) -> tuple[str, str]:
|
|
347
|
+
"""``(spec, kind)`` of a Poetry, Pipfile or Cargo dependency value."""
|
|
348
|
+
if isinstance(value, str):
|
|
349
|
+
return value, "version"
|
|
350
|
+
table = _dict(value)
|
|
351
|
+
if "git" in table:
|
|
352
|
+
return _str(table["git"]), "git"
|
|
353
|
+
if "url" in table or "file" in table:
|
|
354
|
+
return _str(table.get("url") or table.get("file")), "url"
|
|
355
|
+
if "path" in table or table.get("workspace") is True:
|
|
356
|
+
return _str(table.get("path")), "path"
|
|
357
|
+
return _str(table.get("version")), "version"
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _named_tables(
|
|
361
|
+
out: list[Dep], index: TomlLines, table: object, path: tuple[str, ...], eco: str, skip=()
|
|
362
|
+
) -> None:
|
|
363
|
+
for name, value in _dict(table).items():
|
|
364
|
+
if name in skip:
|
|
365
|
+
continue
|
|
366
|
+
spec, kind = _table_kind(value)
|
|
367
|
+
out.append(Dep(eco, ".".join(path), name, spec, kind, index.locate(path, name)))
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _pyproject_deps(data: object, lines: tuple[str, ...]) -> list[Dep]:
|
|
371
|
+
index = TomlLines(lines)
|
|
372
|
+
root = _dict(data)
|
|
373
|
+
out: list[Dep] = []
|
|
374
|
+
project = _dict(root.get("project"))
|
|
375
|
+
_py_list(out, index, project.get("dependencies"), ("project",), "dependencies", "project")
|
|
376
|
+
for group, items in _dict(project.get("optional-dependencies")).items():
|
|
377
|
+
_py_list(out, index, items, ("project", "optional-dependencies"), group, f"extra {group}")
|
|
378
|
+
for group, items in _dict(root.get("dependency-groups")).items():
|
|
379
|
+
_py_list(out, index, items, ("dependency-groups",), group, f"group {group}")
|
|
380
|
+
tool = _dict(root.get("tool"))
|
|
381
|
+
poetry = _dict(tool.get("poetry"))
|
|
382
|
+
for key in ("dependencies", "dev-dependencies"):
|
|
383
|
+
_named_tables(
|
|
384
|
+
out, index, poetry.get(key), ("tool", "poetry", key), "python", skip=("python",)
|
|
385
|
+
)
|
|
386
|
+
for group, body in _dict(poetry.get("group")).items():
|
|
387
|
+
path = ("tool", "poetry", "group", group, "dependencies")
|
|
388
|
+
_named_tables(out, index, _dict(body).get("dependencies"), path, "python")
|
|
389
|
+
uv = _dict(tool.get("uv"))
|
|
390
|
+
_py_list(out, index, uv.get("dev-dependencies"), ("tool", "uv"), "dev-dependencies", "uv dev")
|
|
391
|
+
local: set[str] = set()
|
|
392
|
+
for name, value in _dict(uv.get("sources")).items():
|
|
393
|
+
spec, kind = _table_kind(value)
|
|
394
|
+
if kind in ("git", "url"):
|
|
395
|
+
line = index.locate(("tool", "uv", "sources"), name)
|
|
396
|
+
out.append(Dep("python", "tool.uv.sources", name, spec, f"source-{kind}", line))
|
|
397
|
+
elif kind == "path":
|
|
398
|
+
local.add(_pyname(name))
|
|
399
|
+
# A dependency that uv takes from the workspace or a local path is local.
|
|
400
|
+
return [
|
|
401
|
+
Dep(d.ecosystem, d.section, d.name, d.spec, "path", d.line)
|
|
402
|
+
if d.kind == "version" and d.key in local
|
|
403
|
+
else d
|
|
404
|
+
for d in out
|
|
405
|
+
]
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _pipfile_deps(data: object, lines: tuple[str, ...]) -> list[Dep]:
|
|
409
|
+
index = TomlLines(lines)
|
|
410
|
+
out: list[Dep] = []
|
|
411
|
+
for section in ("packages", "dev-packages"):
|
|
412
|
+
_named_tables(out, index, _dict(data).get(section), (section,), "python")
|
|
413
|
+
return out
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
_CARGO_SECTIONS = ("dependencies", "dev-dependencies", "build-dependencies")
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _cargo_deps(data: object, lines: tuple[str, ...]) -> list[Dep]:
|
|
420
|
+
index = TomlLines(lines)
|
|
421
|
+
root = _dict(data)
|
|
422
|
+
out: list[Dep] = []
|
|
423
|
+
for section in _CARGO_SECTIONS:
|
|
424
|
+
_named_tables(out, index, root.get(section), (section,), "cargo")
|
|
425
|
+
_named_tables(
|
|
426
|
+
out,
|
|
427
|
+
index,
|
|
428
|
+
_dict(root.get("workspace")).get("dependencies"),
|
|
429
|
+
("workspace", "dependencies"),
|
|
430
|
+
"cargo",
|
|
431
|
+
)
|
|
432
|
+
for cfg, body in _dict(root.get("target")).items():
|
|
433
|
+
for section in _CARGO_SECTIONS:
|
|
434
|
+
_named_tables(out, index, _dict(body).get(section), ("target", cfg, section), "cargo")
|
|
435
|
+
return out
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _strip_hash_comment(line: str) -> str:
|
|
439
|
+
m = re.search(r"(?:^|\s)#", line)
|
|
440
|
+
return line[: m.start()] if m else line
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def requirement_lines(lines: tuple[str, ...]) -> Iterator[tuple[int, str]]:
|
|
444
|
+
"""``(first line, logical line)`` of a requirements file, comments and continuations removed."""
|
|
445
|
+
buf = ""
|
|
446
|
+
first = 0
|
|
447
|
+
for number, raw in enumerate(lines, start=1):
|
|
448
|
+
text = _strip_hash_comment(raw).rstrip()
|
|
449
|
+
if not buf:
|
|
450
|
+
first = number
|
|
451
|
+
if text.endswith("\\"):
|
|
452
|
+
buf += text[:-1] + " "
|
|
453
|
+
continue
|
|
454
|
+
buf += text
|
|
455
|
+
if buf.strip():
|
|
456
|
+
yield first, buf.strip()
|
|
457
|
+
buf = ""
|
|
458
|
+
if buf.strip():
|
|
459
|
+
yield first, buf.strip()
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
_REQ_OPTION = re.compile(r"(--?[A-Za-z][A-Za-z-]{0,40})(?:[ =]\s{0,5}(\S{1,4000}))?")
|
|
463
|
+
_EGG = re.compile(r"#egg=([A-Za-z0-9._-]{1,200})")
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _requirements_deps(lines: tuple[str, ...]) -> list[Dep]:
|
|
467
|
+
out: list[Dep] = []
|
|
468
|
+
for number, text in requirement_lines(lines):
|
|
469
|
+
editable = False
|
|
470
|
+
if text.startswith("-"):
|
|
471
|
+
m = _REQ_OPTION.match(text)
|
|
472
|
+
if m is None or m.group(1) not in ("-e", "--editable"):
|
|
473
|
+
continue
|
|
474
|
+
editable = True
|
|
475
|
+
text = (m.group(2) or "").strip()
|
|
476
|
+
text = re.split(r"\s--?[A-Za-z]", " " + text, maxsplit=1)[0].strip()
|
|
477
|
+
if not text:
|
|
478
|
+
continue
|
|
479
|
+
if "://" in text.split("@", 1)[0] or text.startswith(("git+", "file:")):
|
|
480
|
+
name = _EGG.search(text)
|
|
481
|
+
kind = (
|
|
482
|
+
"git" if text.startswith("git+") else "path" if text.startswith("file:") else "url"
|
|
483
|
+
)
|
|
484
|
+
out.append(
|
|
485
|
+
Dep("python", "requirements", name.group(1) if name else text, text, kind, number)
|
|
486
|
+
)
|
|
487
|
+
continue
|
|
488
|
+
if text.startswith((".", "/", "~")) or (editable and "/" in text):
|
|
489
|
+
out.append(Dep("python", "requirements", text, text, "path", number))
|
|
490
|
+
continue
|
|
491
|
+
parsed = pep508(text)
|
|
492
|
+
if parsed is not None:
|
|
493
|
+
out.append(Dep("python", "requirements", parsed[0], parsed[1], parsed[2], number))
|
|
494
|
+
return out
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
_GO_REQUIRE = re.compile(r"\s{0,40}(?:require\s{1,20})?([^\s()]{1,500})\s{1,20}(v[^\s]{1,200})")
|
|
498
|
+
_GO_REPLACE = re.compile(
|
|
499
|
+
r"\s{0,40}(?:replace\s{1,20})?([^\s()]{1,500})(?:\s{1,20}v\S{1,200})?\s{1,20}=>\s{1,20}"
|
|
500
|
+
r"([^\s]{1,500})(?:\s{1,20}(v\S{1,200}))?"
|
|
501
|
+
)
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def _gomod_deps(lines: tuple[str, ...]) -> list[Dep]:
|
|
505
|
+
out: list[Dep] = []
|
|
506
|
+
block = ""
|
|
507
|
+
for number, raw in enumerate(lines, start=1):
|
|
508
|
+
line = raw.split("//", 1)[0].rstrip()
|
|
509
|
+
stripped = line.strip()
|
|
510
|
+
if block:
|
|
511
|
+
if stripped == ")":
|
|
512
|
+
block = ""
|
|
513
|
+
continue
|
|
514
|
+
elif stripped.startswith(("require (", "replace (")) or stripped in (
|
|
515
|
+
"require(",
|
|
516
|
+
"replace(",
|
|
517
|
+
):
|
|
518
|
+
block = stripped.split("(", 1)[0].strip()
|
|
519
|
+
continue
|
|
520
|
+
directive = block or (stripped.split(None, 1)[0] if stripped else "")
|
|
521
|
+
if directive == "require":
|
|
522
|
+
m = _GO_REQUIRE.match(line)
|
|
523
|
+
if m is not None and m.group(1) != "require":
|
|
524
|
+
out.append(Dep("go", "require", m.group(1), m.group(2), "version", number))
|
|
525
|
+
elif directive == "replace":
|
|
526
|
+
m = _GO_REPLACE.match(line)
|
|
527
|
+
if m is not None:
|
|
528
|
+
target = m.group(2)
|
|
529
|
+
local = target.startswith((".", "/"))
|
|
530
|
+
spec = f"{target} {m.group(3) or ''}".strip()
|
|
531
|
+
out.append(
|
|
532
|
+
Dep(
|
|
533
|
+
"go", "replace", m.group(1), spec, "path" if local else "source-git", number
|
|
534
|
+
)
|
|
535
|
+
)
|
|
536
|
+
return out
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
_GEM = re.compile(r"\s{0,40}gem\s{1,10}[\"']([^\"']{1,200})[\"'](.{0,2000})")
|
|
540
|
+
_GEM_VERSION = re.compile(r"\s{0,10},\s{0,10}[\"']([^\"']{1,100})[\"']")
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def _gemfile_deps(lines: tuple[str, ...]) -> list[Dep]:
|
|
544
|
+
out: list[Dep] = []
|
|
545
|
+
for number, raw in enumerate(lines, start=1):
|
|
546
|
+
m = _GEM.match(_strip_hash_comment(raw))
|
|
547
|
+
if m is None:
|
|
548
|
+
continue
|
|
549
|
+
rest = m.group(2)
|
|
550
|
+
if re.search(r"\b(?:git|github|gist|bitbucket)\s{0,3}(?::|=>)", rest):
|
|
551
|
+
kind = "git"
|
|
552
|
+
elif re.search(r"\bpath\s{0,3}(?::|=>)", rest):
|
|
553
|
+
kind = "path"
|
|
554
|
+
else:
|
|
555
|
+
kind = "version"
|
|
556
|
+
versions = []
|
|
557
|
+
pos = 0
|
|
558
|
+
while True:
|
|
559
|
+
v = _GEM_VERSION.match(rest, pos)
|
|
560
|
+
if v is None:
|
|
561
|
+
break
|
|
562
|
+
versions.append(v.group(1))
|
|
563
|
+
pos = v.end()
|
|
564
|
+
out.append(Dep("ruby", "gems", m.group(1), ", ".join(versions), kind, number))
|
|
565
|
+
return out
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def manifest_deps(path: str, text: str | None, parsed: object = None) -> list[Dep] | None:
|
|
569
|
+
"""The dependencies ``text`` declares, or ``None`` when it is no manifest or unreadable.
|
|
570
|
+
|
|
571
|
+
``parsed`` is the context's parse of ``text`` (JSON or TOML) when there
|
|
572
|
+
is one; otherwise the text is parsed here.
|
|
573
|
+
"""
|
|
574
|
+
kind = manifest_kind(path)
|
|
575
|
+
if kind is None or text is None:
|
|
576
|
+
return None
|
|
577
|
+
lines = git_lines(text)
|
|
578
|
+
if kind in ("package.json", "composer.json"):
|
|
579
|
+
data = parsed if parsed is not None else _json(text)
|
|
580
|
+
if not isinstance(data, dict):
|
|
581
|
+
return None
|
|
582
|
+
return _npm_deps(data, lines) if kind == "package.json" else _composer_deps(data, lines)
|
|
583
|
+
if kind in ("pyproject.toml", "Pipfile", "Cargo.toml"):
|
|
584
|
+
data = parsed if parsed is not None else _toml(text)
|
|
585
|
+
if not isinstance(data, dict):
|
|
586
|
+
return None
|
|
587
|
+
if kind == "pyproject.toml":
|
|
588
|
+
return _pyproject_deps(data, lines)
|
|
589
|
+
return _pipfile_deps(data, lines) if kind == "Pipfile" else _cargo_deps(data, lines)
|
|
590
|
+
if kind == "go.mod":
|
|
591
|
+
return _gomod_deps(lines)
|
|
592
|
+
if kind == "Gemfile":
|
|
593
|
+
return _gemfile_deps(lines)
|
|
594
|
+
return _requirements_deps(lines)
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def _ctx_deps(ctx: FileContext) -> list[Dep]:
|
|
598
|
+
kind = manifest_kind(ctx.path)
|
|
599
|
+
if kind is None or ctx.new_text is None:
|
|
600
|
+
return []
|
|
601
|
+
parsed: object = None
|
|
602
|
+
if kind in ("package.json", "composer.json"):
|
|
603
|
+
parsed = ctx.json
|
|
604
|
+
elif kind in ("pyproject.toml", "Pipfile", "Cargo.toml"):
|
|
605
|
+
parsed = ctx.toml
|
|
606
|
+
return manifest_deps(ctx.path, ctx.new_text, parsed) or []
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def _dep_hit(ctx: FileContext, dep: Dep, evidence: str, message: str) -> Hit:
|
|
610
|
+
if dep.line is None:
|
|
611
|
+
return Hit(1, end_line=max(len(ctx.lines), 1), evidence=evidence, message=message)
|
|
612
|
+
return Hit(
|
|
613
|
+
dep.line, column=_column(ctx, dep.line, dep.name), evidence=evidence, message=message
|
|
614
|
+
)
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
def _column(ctx: FileContext, line: int, needle: str) -> int | None:
|
|
618
|
+
if not needle or line > len(ctx.lines):
|
|
619
|
+
return None
|
|
620
|
+
index = ctx.lines[line - 1].find(needle)
|
|
621
|
+
return index + 1 if index >= 0 else None
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
# --- new-dependency / unpinned-version / url-dependency -----------------------------
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
@rule(
|
|
628
|
+
id="deps/new-dependency",
|
|
629
|
+
severity="note",
|
|
630
|
+
title="New dependency",
|
|
631
|
+
rationale=(
|
|
632
|
+
"Every new dependency brings its maintainers, its own dependencies and its install-time "
|
|
633
|
+
"code into the project."
|
|
634
|
+
),
|
|
635
|
+
hint="Check that the package is the intended one (spelling, owner) and is maintained.",
|
|
636
|
+
tags={"deps", "supply-chain"},
|
|
637
|
+
)
|
|
638
|
+
def new_dependency(ctx: FileContext) -> Iterator[Hit]:
|
|
639
|
+
"""A dependency name added to a manifest (moving or re-versioning one is not new).
|
|
640
|
+
|
|
641
|
+
Local path and workspace dependencies are the project's own code and are
|
|
642
|
+
not reported.
|
|
643
|
+
"""
|
|
644
|
+
for dep in _ctx_deps(ctx):
|
|
645
|
+
if dep.kind.startswith("source") or dep.kind == "path":
|
|
646
|
+
continue
|
|
647
|
+
yield _dep_hit(ctx, dep, f"{dep.ecosystem}:{dep.key}", f"New dependency {dep.name}")
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
_UPPER_BOUND = re.compile(r"(?:==|~=|<|\^|~(?!>)|~>|===)")
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def _unpinned(dep: Dep, manifest: str) -> bool:
|
|
654
|
+
spec = dep.spec.strip()
|
|
655
|
+
if dep.kind != "version":
|
|
656
|
+
return False
|
|
657
|
+
if manifest == "package.json":
|
|
658
|
+
if spec in ("", "*", "x", "X", "latest", "next") or re.fullmatch(
|
|
659
|
+
r"[A-Za-z][\w.-]{0,40}", spec
|
|
660
|
+
):
|
|
661
|
+
return True
|
|
662
|
+
return spec.startswith((">", ">=")) and "<" not in spec
|
|
663
|
+
if manifest in ("Pipfile", "Cargo.toml", "composer.json"):
|
|
664
|
+
return spec in ("", "*") or spec.startswith("dev-")
|
|
665
|
+
if manifest == "pyproject.toml":
|
|
666
|
+
return spec == ""
|
|
667
|
+
if manifest == "requirements":
|
|
668
|
+
return spec == "" or not _UPPER_BOUND.search(spec)
|
|
669
|
+
return False
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
@rule(
|
|
673
|
+
id="deps/unpinned-version",
|
|
674
|
+
severity="note",
|
|
675
|
+
title="Dependency without a version bound",
|
|
676
|
+
rationale=(
|
|
677
|
+
"A dependency that accepts any version (or any newer one) installs whatever is "
|
|
678
|
+
"published next, including a compromised or breaking release, wherever no lockfile "
|
|
679
|
+
"applies."
|
|
680
|
+
),
|
|
681
|
+
hint="Give the dependency an upper bound or an exact version, or rely on a lockfile.",
|
|
682
|
+
tags={"deps", "supply-chain"},
|
|
683
|
+
)
|
|
684
|
+
def unpinned_version(ctx: FileContext) -> Iterator[Hit]:
|
|
685
|
+
"""``*``, ``latest``, a dist-tag or a lower bound only (npm); ``*`` (Pipfile, Cargo,
|
|
686
|
+
Composer); no specifier (pyproject); no specifier or no upper bound (requirements files).
|
|
687
|
+
"""
|
|
688
|
+
manifest = manifest_kind(ctx.path) or ""
|
|
689
|
+
for dep in _ctx_deps(ctx):
|
|
690
|
+
if _unpinned(dep, manifest):
|
|
691
|
+
spec = dep.spec.strip() or "any version"
|
|
692
|
+
yield _dep_hit(ctx, dep, f"{dep.key} {spec}", f"{dep.name} accepts {spec}")
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
@rule(
|
|
696
|
+
id="deps/url-dependency",
|
|
697
|
+
severity="warning",
|
|
698
|
+
title="Dependency installed from a URL or Git repository",
|
|
699
|
+
rationale=(
|
|
700
|
+
"A Git or URL dependency bypasses the registry: no immutable version, no registry "
|
|
701
|
+
"malware scanning, and the content can change at the source unless pinned to a commit "
|
|
702
|
+
"or checksum."
|
|
703
|
+
),
|
|
704
|
+
hint="Use a published registry version, or pin the Git dependency to a full commit hash.",
|
|
705
|
+
tags={"deps", "supply-chain"},
|
|
706
|
+
)
|
|
707
|
+
def url_dependency(ctx: FileContext) -> Iterator[Hit]:
|
|
708
|
+
"""Git, GitHub-shorthand and URL dependencies in every manifest format.
|
|
709
|
+
|
|
710
|
+
Includes ``tool.uv.sources`` Git and URL sources and ``go.mod``
|
|
711
|
+
``replace`` directives that point at another module; local path and
|
|
712
|
+
workspace dependencies are not reported.
|
|
713
|
+
"""
|
|
714
|
+
for dep in _ctx_deps(ctx):
|
|
715
|
+
if dep.kind in ("git", "url", "source-git", "source-url"):
|
|
716
|
+
what = "Git" if "git" in dep.kind else "URL"
|
|
717
|
+
yield _dep_hit(
|
|
718
|
+
ctx, dep, f"{dep.key} {dep.spec}", f"{dep.name} comes from a {what} source"
|
|
719
|
+
)
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
# --- install-script-added --------------------------------------------------------------
|
|
723
|
+
|
|
724
|
+
_NPM_HOOKS = frozenset(
|
|
725
|
+
{"preinstall", "install", "postinstall", "prepare", "preprepare", "postprepare", "prepublish"}
|
|
726
|
+
)
|
|
727
|
+
_COMPOSER_HOOKS = frozenset(
|
|
728
|
+
{
|
|
729
|
+
"pre-install-cmd",
|
|
730
|
+
"post-install-cmd",
|
|
731
|
+
"pre-update-cmd",
|
|
732
|
+
"post-update-cmd",
|
|
733
|
+
"pre-autoload-dump",
|
|
734
|
+
"post-autoload-dump",
|
|
735
|
+
"post-root-package-install",
|
|
736
|
+
"post-create-project-cmd",
|
|
737
|
+
}
|
|
738
|
+
)
|
|
739
|
+
_BUILD_FILES = frozenset({"build.rs", "binding.gyp"})
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
@rule(
|
|
743
|
+
id="deps/install-script-added",
|
|
744
|
+
severity="warning",
|
|
745
|
+
title="Install-time script added or changed",
|
|
746
|
+
scope="file",
|
|
747
|
+
rationale=(
|
|
748
|
+
"Install hooks run automatically on every machine and CI job that installs the "
|
|
749
|
+
"project, before any review of what they do."
|
|
750
|
+
),
|
|
751
|
+
hint="Review the script as code that runs on install; prefer an explicit build step.",
|
|
752
|
+
tags={"deps", "supply-chain"},
|
|
753
|
+
)
|
|
754
|
+
def install_script_added(ctx: FileContext) -> Iterator[Hit]:
|
|
755
|
+
"""A new or changed install hook.
|
|
756
|
+
|
|
757
|
+
npm lifecycle scripts (``preinstall``, ``install``, ``postinstall``,
|
|
758
|
+
``prepare`` and the like) and Composer install/update hooks, compared
|
|
759
|
+
with the old side; a Cargo ``package.build`` setting; an added
|
|
760
|
+
``build.rs`` or ``binding.gyp`` (npm runs ``node-gyp`` for it);
|
|
761
|
+
``build-system.backend-path`` (an in-tree build backend).
|
|
762
|
+
"""
|
|
763
|
+
name = _base(ctx.path)
|
|
764
|
+
if name in _BUILD_FILES and ctx.change.status is FileStatus.ADDED:
|
|
765
|
+
yield Hit(None, message=f"{name} added; it runs at build or install time")
|
|
766
|
+
return
|
|
767
|
+
if name in ("package.json", "composer.json"):
|
|
768
|
+
hooks = _NPM_HOOKS if name == "package.json" else _COMPOSER_HOOKS
|
|
769
|
+
new = _dict(_dict(ctx.json).get("scripts"))
|
|
770
|
+
old = _dict(_dict(ctx.old_json).get("scripts"))
|
|
771
|
+
keys = json_key_lines(ctx.lines)
|
|
772
|
+
for hook, command in new.items():
|
|
773
|
+
if hook in hooks and old.get(hook) != command:
|
|
774
|
+
line = json_locate(keys, "scripts", hook)
|
|
775
|
+
if line is not None:
|
|
776
|
+
yield Hit(
|
|
777
|
+
line,
|
|
778
|
+
column=_column(ctx, line, hook),
|
|
779
|
+
message=f"Install hook {hook} added or changed",
|
|
780
|
+
)
|
|
781
|
+
elif name in ("Cargo.toml", "pyproject.toml"):
|
|
782
|
+
section, key = (
|
|
783
|
+
("package", "build") if name == "Cargo.toml" else ("build-system", "backend-path")
|
|
784
|
+
)
|
|
785
|
+
new_value = _dict(_dict(ctx.toml).get(section)).get(key)
|
|
786
|
+
old_value = _dict(_dict(ctx.old_toml).get(section)).get(key)
|
|
787
|
+
if new_value is not None and new_value != old_value and new_value is not False:
|
|
788
|
+
line = TomlLines(ctx.lines).locate((section,), key)
|
|
789
|
+
if line is not None:
|
|
790
|
+
yield Hit(
|
|
791
|
+
line,
|
|
792
|
+
column=_column(ctx, line, key),
|
|
793
|
+
message=f"{section}.{key} added or changed",
|
|
794
|
+
)
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
# --- Registry configuration -----------------------------------------------------------------
|
|
798
|
+
|
|
799
|
+
_DEFAULT_HOSTS = frozenset(
|
|
800
|
+
{
|
|
801
|
+
"registry.npmjs.org",
|
|
802
|
+
"registry.yarnpkg.com",
|
|
803
|
+
"pypi.org",
|
|
804
|
+
"pypi.python.org",
|
|
805
|
+
"files.pythonhosted.org",
|
|
806
|
+
"index.crates.io",
|
|
807
|
+
"crates.io",
|
|
808
|
+
"rubygems.org",
|
|
809
|
+
"repo.packagist.org",
|
|
810
|
+
"packagist.org",
|
|
811
|
+
}
|
|
812
|
+
)
|
|
813
|
+
_LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1", "[::1]", "::1"})
|
|
814
|
+
_URL = re.compile(
|
|
815
|
+
r"(?:[a-z0-9+]{1,20}\+)?([a-z][a-z0-9+.-]{0,20})://(?:[^@/\s]{1,200}@)?([^/:\s?#]{1,253})(?::[0-9]{1,5})?([^\s?#]{0,2000})",
|
|
816
|
+
re.I,
|
|
817
|
+
)
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
def url_host(url: str) -> str | None:
|
|
821
|
+
m = _URL.match(url.strip())
|
|
822
|
+
return m.group(2).lower() if m is not None else None
|
|
823
|
+
|
|
824
|
+
|
|
825
|
+
def is_default_registry(url: str) -> bool:
|
|
826
|
+
m = _URL.match(url.strip())
|
|
827
|
+
if m is None:
|
|
828
|
+
return False
|
|
829
|
+
host = m.group(2).lower()
|
|
830
|
+
if host == "github.com":
|
|
831
|
+
return m.group(3).rstrip("/").lower() == "/rust-lang/crates.io-index"
|
|
832
|
+
return host in _DEFAULT_HOSTS
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
def is_plain_http(url: str) -> bool:
|
|
836
|
+
m = _URL.match(url.strip())
|
|
837
|
+
return m is not None and m.group(1).lower() == "http" and m.group(2).lower() not in _LOCAL_HOSTS
|
|
838
|
+
|
|
839
|
+
|
|
840
|
+
@dataclass(frozen=True, slots=True)
|
|
841
|
+
class Setting:
|
|
842
|
+
"""A registry setting: ``kind`` is ``url`` (a registry or index), ``name`` (a
|
|
843
|
+
replacement registry chosen by name) or ``insecure`` (TLS or host checks off).
|
|
844
|
+
|
|
845
|
+
``scoped`` marks a registry that only serves packages that name it (an npm
|
|
846
|
+
scope, an explicit uv index, a Cargo alternate registry) and so cannot
|
|
847
|
+
shadow a public package.
|
|
848
|
+
"""
|
|
849
|
+
|
|
850
|
+
line: int
|
|
851
|
+
key: str
|
|
852
|
+
value: str
|
|
853
|
+
kind: str
|
|
854
|
+
scoped: bool = False
|
|
855
|
+
|
|
856
|
+
|
|
857
|
+
def _placeholder(value: str) -> bool:
|
|
858
|
+
return "${" in value or value.startswith("$") or "%(" in value
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
def _ini_settings(lines: tuple[str, ...], url_keys, insecure) -> Iterator[Setting]:
|
|
862
|
+
"""``key = value`` (``key value`` for .yarnrc) lines; continuation lines extend a value."""
|
|
863
|
+
last: str | None = None
|
|
864
|
+
for number, raw in enumerate(lines, start=1):
|
|
865
|
+
stripped = raw.strip()
|
|
866
|
+
if not stripped or stripped[0] in "#;[":
|
|
867
|
+
last = None
|
|
868
|
+
continue
|
|
869
|
+
if raw[:1] in " \t" and last is not None:
|
|
870
|
+
key, value = last, stripped
|
|
871
|
+
else:
|
|
872
|
+
m = re.match(r"([^=\s]{1,200})\s{0,10}(?:=\s{0,10}|\s{1,10})(.{0,4000})", stripped)
|
|
873
|
+
if m is None:
|
|
874
|
+
continue
|
|
875
|
+
key, value = m.group(1).strip("\"'").lower(), m.group(2).strip().strip("\"'")
|
|
876
|
+
last = key
|
|
877
|
+
if any(key == k or key.endswith(":" + k) for k in url_keys):
|
|
878
|
+
for part in value.split():
|
|
879
|
+
if not _placeholder(part):
|
|
880
|
+
yield Setting(number, key, part, "url", scoped=key.startswith("@"))
|
|
881
|
+
elif key in insecure and value and (insecure[key] == "*" or value.lower() in insecure[key]):
|
|
882
|
+
yield Setting(number, key, value, "insecure")
|
|
883
|
+
|
|
884
|
+
|
|
885
|
+
def _requirements_settings(lines: tuple[str, ...]) -> Iterator[Setting]:
|
|
886
|
+
for number, text in requirement_lines(lines):
|
|
887
|
+
for m in re.finditer(
|
|
888
|
+
r"(?:^|\s)(-i|--index-url|--extra-index-url|-f|--find-links|"
|
|
889
|
+
r"--trusted-host)(?:\s{1,10}|=)(\S{1,4000})",
|
|
890
|
+
text,
|
|
891
|
+
):
|
|
892
|
+
key, value = m.group(1), m.group(2)
|
|
893
|
+
if key == "--trusted-host":
|
|
894
|
+
yield Setting(number, key, value, "insecure")
|
|
895
|
+
elif "://" in value and not _placeholder(value):
|
|
896
|
+
yield Setting(number, key, value, "url")
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
def _toml_settings(ctx: FileContext, name: str) -> Iterator[Setting]:
|
|
900
|
+
data = ctx.toml
|
|
901
|
+
if data is None:
|
|
902
|
+
return
|
|
903
|
+
index = TomlLines(ctx.lines)
|
|
904
|
+
|
|
905
|
+
def at(
|
|
906
|
+
path: tuple[str, ...],
|
|
907
|
+
key: str,
|
|
908
|
+
value: str,
|
|
909
|
+
kind: str,
|
|
910
|
+
i: int | None = None,
|
|
911
|
+
scoped: bool = False,
|
|
912
|
+
) -> None:
|
|
913
|
+
tables = index.find(path, i) if i is not None else index.find(path)
|
|
914
|
+
line = None
|
|
915
|
+
for table in tables:
|
|
916
|
+
line = index.key_line(table, key)
|
|
917
|
+
if line is not None:
|
|
918
|
+
break
|
|
919
|
+
if line is None:
|
|
920
|
+
line = index.locate(path, key)
|
|
921
|
+
if line is not None and not _placeholder(value):
|
|
922
|
+
found.append(Setting(line, key, value, kind, scoped))
|
|
923
|
+
|
|
924
|
+
found: list[Setting] = []
|
|
925
|
+
if name in ("pyproject.toml", "uv.toml"):
|
|
926
|
+
uv = _dict(_dict(data.get("tool")).get("uv")) if name == "pyproject.toml" else data
|
|
927
|
+
base = ("tool", "uv") if name == "pyproject.toml" else ()
|
|
928
|
+
for key in ("index-url", "extra-index-url", "find-links"):
|
|
929
|
+
values = uv.get(key)
|
|
930
|
+
for value in values if isinstance(values, list) else [values]:
|
|
931
|
+
if isinstance(value, str):
|
|
932
|
+
at(base, key, value, "url")
|
|
933
|
+
indexes = uv.get("index")
|
|
934
|
+
for i, entry in enumerate(indexes if isinstance(indexes, list) else []):
|
|
935
|
+
table = _dict(entry)
|
|
936
|
+
if isinstance(table.get("url"), str):
|
|
937
|
+
# explicit = true: used only by packages that name it in tool.uv.sources
|
|
938
|
+
scoped = table.get("explicit") is True and table.get("default") is not True
|
|
939
|
+
at((*base, "index"), "url", table["url"], "url", i, scoped) # type: ignore[arg-type]
|
|
940
|
+
hosts = uv.get("allow-insecure-host")
|
|
941
|
+
for value in hosts if isinstance(hosts, list) else []:
|
|
942
|
+
if isinstance(value, str):
|
|
943
|
+
at(base, "allow-insecure-host", value, "insecure")
|
|
944
|
+
tool = _dict(data.get("tool")) if name == "pyproject.toml" else {}
|
|
945
|
+
for tool_name in ("poetry", "pdm"):
|
|
946
|
+
sources = _dict(tool.get(tool_name)).get("source")
|
|
947
|
+
for i, entry in enumerate(sources if isinstance(sources, list) else []):
|
|
948
|
+
url = _dict(entry).get("url")
|
|
949
|
+
priority = _str(_dict(entry).get("priority")).lower()
|
|
950
|
+
# Poetry: explicit sources serve only packages that name them, and
|
|
951
|
+
# supplemental ones only packages no primary source has.
|
|
952
|
+
scoped = tool_name == "poetry" and priority in ("explicit", "supplemental")
|
|
953
|
+
if isinstance(url, str):
|
|
954
|
+
at(("tool", tool_name, "source"), "url", url, "url", i, scoped)
|
|
955
|
+
elif name == "Pipfile":
|
|
956
|
+
sources = data.get("source")
|
|
957
|
+
for i, entry in enumerate(sources if isinstance(sources, list) else []):
|
|
958
|
+
table = _dict(entry)
|
|
959
|
+
if isinstance(table.get("url"), str):
|
|
960
|
+
at(("source",), "url", table["url"], "url", i) # type: ignore[arg-type]
|
|
961
|
+
if table.get("verify_ssl") is False:
|
|
962
|
+
at(("source",), "verify_ssl", "false", "insecure", i)
|
|
963
|
+
else: # .cargo/config.toml
|
|
964
|
+
for source, table in _dict(data.get("source")).items():
|
|
965
|
+
table = _dict(table)
|
|
966
|
+
if source == "crates-io" and isinstance(table.get("replace-with"), str):
|
|
967
|
+
at(("source", source), "replace-with", table["replace-with"], "name") # type: ignore[arg-type]
|
|
968
|
+
for key in ("registry", "local-registry", "directory"):
|
|
969
|
+
if isinstance(table.get(key), str):
|
|
970
|
+
kind = "url" if key == "registry" else "name"
|
|
971
|
+
# a source is inert until crates-io's replace-with names it
|
|
972
|
+
scoped = source != "crates-io"
|
|
973
|
+
at(("source", source), key, table[key], kind, None, scoped) # type: ignore[arg-type]
|
|
974
|
+
for registry, table in _dict(data.get("registries")).items():
|
|
975
|
+
if isinstance(_dict(table).get("index"), str):
|
|
976
|
+
index_url = _dict(table)["index"]
|
|
977
|
+
at(("registries", registry), "index", index_url, "url", None, True) # type: ignore[arg-type]
|
|
978
|
+
yield from found
|
|
979
|
+
|
|
980
|
+
|
|
981
|
+
def _yarnrc_yml_settings(ctx: FileContext) -> Iterator[Setting]:
|
|
982
|
+
result = ctx.yaml
|
|
983
|
+
if result is None:
|
|
984
|
+
return
|
|
985
|
+
for document in result.documents:
|
|
986
|
+
root = document.root
|
|
987
|
+
if not isinstance(root, YamlMap):
|
|
988
|
+
continue
|
|
989
|
+
maps = [(root, False)]
|
|
990
|
+
scopes = root.get("npmScopes")
|
|
991
|
+
if isinstance(scopes, YamlMap):
|
|
992
|
+
maps.extend((e.value, True) for e in scopes.entries if isinstance(e.value, YamlMap))
|
|
993
|
+
for node, scoped in maps:
|
|
994
|
+
server = node.get("npmRegistryServer")
|
|
995
|
+
if isinstance(server, YamlScalar) and not _placeholder(server.value):
|
|
996
|
+
yield Setting(
|
|
997
|
+
server.start_line, "npmRegistryServer", server.value.strip(), "url", scoped
|
|
998
|
+
)
|
|
999
|
+
ssl = root.get("enableStrictSsl")
|
|
1000
|
+
if isinstance(ssl, YamlScalar) and ssl.value.strip().lower() == "false":
|
|
1001
|
+
yield Setting(ssl.start_line, "enableStrictSsl", "false", "insecure")
|
|
1002
|
+
allow = root.get("unsafeHttpWhitelist")
|
|
1003
|
+
if isinstance(allow, YamlSeq):
|
|
1004
|
+
for item in allow.items:
|
|
1005
|
+
if isinstance(item, YamlScalar):
|
|
1006
|
+
yield Setting(item.start_line, "unsafeHttpWhitelist", item.value, "insecure")
|
|
1007
|
+
|
|
1008
|
+
|
|
1009
|
+
_GEM_SOURCE = re.compile(r"\s{0,40}source\s{1,10}\(?\s{0,5}[\"']([^\"']{1,2000})[\"']")
|
|
1010
|
+
|
|
1011
|
+
|
|
1012
|
+
def registry_settings(ctx: FileContext) -> Iterator[Setting]:
|
|
1013
|
+
"""Every registry or index setting of a registry config file or manifest."""
|
|
1014
|
+
path, name = ctx.path, _base(ctx.path)
|
|
1015
|
+
lines = ctx.lines
|
|
1016
|
+
if name == ".npmrc" or name == ".yarnrc":
|
|
1017
|
+
yield from _ini_settings(lines, ("registry",), {"strict-ssl": ("false",)})
|
|
1018
|
+
elif name == ".yarnrc.yml":
|
|
1019
|
+
yield from _yarnrc_yml_settings(ctx)
|
|
1020
|
+
elif name in ("pip.conf", "pip.ini"):
|
|
1021
|
+
yield from _ini_settings(
|
|
1022
|
+
lines, ("index-url", "extra-index-url", "find-links"), {"trusted-host": "*"}
|
|
1023
|
+
)
|
|
1024
|
+
elif _is_requirements(path):
|
|
1025
|
+
yield from _requirements_settings(lines)
|
|
1026
|
+
elif name in ("pyproject.toml", "uv.toml", "Pipfile"):
|
|
1027
|
+
yield from _toml_settings(ctx, name)
|
|
1028
|
+
elif name in ("config.toml", "config") and _dir(path).rsplit("/", 1)[-1] == ".cargo":
|
|
1029
|
+
yield from _toml_settings(ctx, "cargo")
|
|
1030
|
+
elif name == "Gemfile":
|
|
1031
|
+
for number, raw in enumerate(lines, start=1):
|
|
1032
|
+
m = _GEM_SOURCE.match(raw)
|
|
1033
|
+
if m is not None:
|
|
1034
|
+
# source "..." do ... end serves only the gems inside the block
|
|
1035
|
+
scoped = bool(re.search(r"\bdo\s{0,10}(?:\|[^|]{0,100}\|)?\s{0,10}\Z", raw))
|
|
1036
|
+
yield Setting(number, "source", m.group(1), "url", scoped)
|
|
1037
|
+
|
|
1038
|
+
|
|
1039
|
+
@rule(
|
|
1040
|
+
id="deps/registry-override",
|
|
1041
|
+
severity="error",
|
|
1042
|
+
title="Package registry redirected",
|
|
1043
|
+
rationale=(
|
|
1044
|
+
"Pointing installs at another registry or index (or adding an extra index, which "
|
|
1045
|
+
"enables dependency confusion) decides where every dependency's code comes from; one "
|
|
1046
|
+
"line can swap the whole supply chain. A registry that only serves packages naming it "
|
|
1047
|
+
"(an npm scope, an explicit index) cannot shadow public packages and is a warning."
|
|
1048
|
+
),
|
|
1049
|
+
hint=(
|
|
1050
|
+
"Confirm the registry is the organization's own; prefer scoped or explicit per-package "
|
|
1051
|
+
"indexes over replacing or extending the default."
|
|
1052
|
+
),
|
|
1053
|
+
tags={"deps", "supply-chain"},
|
|
1054
|
+
)
|
|
1055
|
+
def registry_override(ctx: FileContext) -> Iterator[Hit]:
|
|
1056
|
+
"""A registry, index or source replacement other than the public default.
|
|
1057
|
+
|
|
1058
|
+
``error`` for settings that replace or extend the default for every
|
|
1059
|
+
package: npm/Yarn ``registry`` and root ``npmRegistryServer``, pip
|
|
1060
|
+
``index-url``, ``extra-index-url`` and ``find-links`` (dependency
|
|
1061
|
+
confusion), uv ``index-url``/``extra-index-url`` and indexes that are
|
|
1062
|
+
not ``explicit``, Poetry sources other than ``explicit``/``supplemental``,
|
|
1063
|
+
PDM and Pipfile sources (both merge with PyPI), Cargo crates.io
|
|
1064
|
+
``replace-with``, and a global Gemfile ``source``. ``warning`` for
|
|
1065
|
+
registries only packages that name them use: npm ``@scope:registry``
|
|
1066
|
+
and Yarn ``npmScopes``, uv ``explicit = true`` indexes, Poetry
|
|
1067
|
+
``explicit``/``supplemental`` sources (a supplemental source is asked
|
|
1068
|
+
only for packages no primary source has), Cargo ``[registries]`` and
|
|
1069
|
+
``[source.*]`` entries without ``replace-with``, and Gemfile
|
|
1070
|
+
``source ... do`` blocks. A scope that also exists publicly is still
|
|
1071
|
+
redirected; the warning asks a human to confirm it.
|
|
1072
|
+
|
|
1073
|
+
Read from ``.npmrc`` (``registry``, ``@scope:registry``), ``.yarnrc``,
|
|
1074
|
+
``.yarnrc.yml`` (``npmRegistryServer``, also under ``npmScopes``),
|
|
1075
|
+
``pip.conf``/``pip.ini`` and requirements files (``index-url``,
|
|
1076
|
+
``extra-index-url``, ``find-links``), ``pyproject.toml``/``uv.toml``
|
|
1077
|
+
(uv indexes, Poetry and PDM sources), ``Pipfile`` sources,
|
|
1078
|
+
``.cargo/config.toml`` (crates.io ``replace-with``, ``[registries]``)
|
|
1079
|
+
and Gemfile ``source``. Values from environment variables are not
|
|
1080
|
+
judged. Default registries (npmjs, PyPI, crates.io, RubyGems,
|
|
1081
|
+
Packagist) and local test registries (``localhost``, ``127.0.0.1``)
|
|
1082
|
+
are not reported.
|
|
1083
|
+
"""
|
|
1084
|
+
for setting in registry_settings(ctx):
|
|
1085
|
+
if setting.kind == "insecure":
|
|
1086
|
+
continue
|
|
1087
|
+
if setting.kind == "url" and (
|
|
1088
|
+
"://" not in setting.value
|
|
1089
|
+
or is_default_registry(setting.value)
|
|
1090
|
+
or url_host(setting.value) in _LOCAL_HOSTS
|
|
1091
|
+
):
|
|
1092
|
+
continue # a local directory (find-links), the default, or a test registry
|
|
1093
|
+
yield Hit(
|
|
1094
|
+
setting.line,
|
|
1095
|
+
column=_column(ctx, setting.line, setting.value),
|
|
1096
|
+
evidence=f"{setting.key} {setting.value}",
|
|
1097
|
+
message=f"{setting.key} set to {setting.value}"
|
|
1098
|
+
+ (" (only for packages that name it)" if setting.scoped else ""),
|
|
1099
|
+
severity="warning" if setting.scoped else None,
|
|
1100
|
+
)
|
|
1101
|
+
|
|
1102
|
+
|
|
1103
|
+
@rule(
|
|
1104
|
+
id="deps/insecure-registry",
|
|
1105
|
+
severity="warning",
|
|
1106
|
+
title="Packages fetched without TLS or host verification",
|
|
1107
|
+
rationale=(
|
|
1108
|
+
"Plain http registries, disabled certificate checks and trusted hosts let anyone on "
|
|
1109
|
+
"the network path replace packages during install."
|
|
1110
|
+
),
|
|
1111
|
+
hint="Use https registries and keep TLS verification on.",
|
|
1112
|
+
tags={"deps", "supply-chain", "tls"},
|
|
1113
|
+
)
|
|
1114
|
+
def insecure_registry(ctx: FileContext) -> Iterator[Hit]:
|
|
1115
|
+
"""``http://`` registries and indexes (not localhost), ``strict-ssl=false``,
|
|
1116
|
+
``enableStrictSsl: false``, ``unsafeHttpWhitelist``, ``trusted-host``,
|
|
1117
|
+
uv ``allow-insecure-host``, Pipfile ``verify_ssl = false``, and lockfile
|
|
1118
|
+
entries resolved over ``http://``.
|
|
1119
|
+
"""
|
|
1120
|
+
for setting in registry_settings(ctx):
|
|
1121
|
+
if setting.kind == "insecure" or (setting.kind == "url" and is_plain_http(setting.value)):
|
|
1122
|
+
yield Hit(
|
|
1123
|
+
setting.line,
|
|
1124
|
+
column=_column(ctx, setting.line, setting.value),
|
|
1125
|
+
evidence=f"{setting.key} {setting.value}",
|
|
1126
|
+
message=f"{setting.key} {setting.value} turns off transport security",
|
|
1127
|
+
)
|
|
1128
|
+
if _base(ctx.path) in LOCKFILES and ctx.new_text is not None:
|
|
1129
|
+
entries = lock_entries(ctx.path, ctx.new_text, ctx)
|
|
1130
|
+
for entry in entries or ():
|
|
1131
|
+
if entry.line is not None and is_plain_http(entry.raw.removeprefix("git+")):
|
|
1132
|
+
yield Hit(
|
|
1133
|
+
entry.line,
|
|
1134
|
+
evidence=f"{entry.key} {entry.raw}",
|
|
1135
|
+
message=f"{entry.key} is downloaded over plain http",
|
|
1136
|
+
)
|
|
1137
|
+
|
|
1138
|
+
|
|
1139
|
+
# --- Lockfiles --------------------------------------------------------------------------------
|
|
1140
|
+
|
|
1141
|
+
|
|
1142
|
+
@dataclass(frozen=True, slots=True)
|
|
1143
|
+
class LockEntry:
|
|
1144
|
+
"""One locked package: its key, raw source text and where that text is."""
|
|
1145
|
+
|
|
1146
|
+
key: str
|
|
1147
|
+
raw: str
|
|
1148
|
+
line: int | None
|
|
1149
|
+
|
|
1150
|
+
|
|
1151
|
+
_NPM_HOST_ALIASES = {"registry.yarnpkg.com": "registry.npmjs.org"}
|
|
1152
|
+
_CRATES = (
|
|
1153
|
+
"registry+https://github.com/rust-lang/crates.io-index",
|
|
1154
|
+
"sparse+https://index.crates.io/",
|
|
1155
|
+
)
|
|
1156
|
+
|
|
1157
|
+
|
|
1158
|
+
def normalize_source(raw: str) -> str:
|
|
1159
|
+
"""The part of a source that names where code comes from (host, or Git repository)."""
|
|
1160
|
+
s = raw.strip()
|
|
1161
|
+
if s.rstrip("/") in (c.rstrip("/") for c in _CRATES):
|
|
1162
|
+
return "crates.io"
|
|
1163
|
+
s = s.split("#", 1)[0]
|
|
1164
|
+
git = s.startswith(("git+", "git://", "git@", "ssh://")) or s.endswith(".git")
|
|
1165
|
+
if git:
|
|
1166
|
+
s = s.removeprefix("git+").split("?", 1)[0]
|
|
1167
|
+
m = re.match(
|
|
1168
|
+
r"(?:[a-z0-9+.-]{1,20}://)?(?:[^@/\s]{1,200}@)?([^/:\s]{1,253})(?::[0-9]{1,5}(?=/))?[:/]?(.{0,2000})",
|
|
1169
|
+
s,
|
|
1170
|
+
re.I,
|
|
1171
|
+
)
|
|
1172
|
+
if m is None:
|
|
1173
|
+
return "git:" + s
|
|
1174
|
+
return (
|
|
1175
|
+
"git:" + m.group(1).lower() + "/" + m.group(2).removesuffix(".git").strip("/").lower()
|
|
1176
|
+
)
|
|
1177
|
+
for prefix in ("registry+", "sparse+"):
|
|
1178
|
+
if s.startswith(prefix):
|
|
1179
|
+
return "registry:" + s[len(prefix) :].rstrip("/").lower()
|
|
1180
|
+
host = url_host(s)
|
|
1181
|
+
if host is not None:
|
|
1182
|
+
return _NPM_HOST_ALIASES.get(host, host)
|
|
1183
|
+
return s
|
|
1184
|
+
|
|
1185
|
+
|
|
1186
|
+
_RESOLVED = re.compile(r'\s{0,80}"resolved"\s{0,5}:\s{0,5}"([^"\n]{1,4000})"')
|
|
1187
|
+
_JSON_URL = re.compile(r'\s{0,80}"url"\s{0,5}:\s{0,5}"([^"\n]{1,4000})"')
|
|
1188
|
+
|
|
1189
|
+
|
|
1190
|
+
def _first_lines(lines: tuple[str, ...], pattern: re.Pattern[str]) -> dict[str, int]:
|
|
1191
|
+
found: dict[str, int] = {}
|
|
1192
|
+
for number, line in enumerate(lines, start=1):
|
|
1193
|
+
m = pattern.match(line)
|
|
1194
|
+
if m is not None:
|
|
1195
|
+
found.setdefault(m.group(1).replace("\\/", "/"), number)
|
|
1196
|
+
return found
|
|
1197
|
+
|
|
1198
|
+
|
|
1199
|
+
def _npm_lock(data: object, lines: tuple[str, ...]) -> list[LockEntry]:
|
|
1200
|
+
where = _first_lines(lines, _RESOLVED)
|
|
1201
|
+
out: list[LockEntry] = []
|
|
1202
|
+
packages = _dict(data).get("packages")
|
|
1203
|
+
if isinstance(packages, dict):
|
|
1204
|
+
for key, entry in packages.items():
|
|
1205
|
+
resolved = _dict(entry).get("resolved")
|
|
1206
|
+
if key and isinstance(resolved, str):
|
|
1207
|
+
out.append(LockEntry(key, resolved, where.get(resolved)))
|
|
1208
|
+
return out
|
|
1209
|
+
|
|
1210
|
+
def walk(deps: object, prefix: str, depth: int) -> None:
|
|
1211
|
+
if depth > 64:
|
|
1212
|
+
return
|
|
1213
|
+
for name, entry in _dict(deps).items():
|
|
1214
|
+
resolved = _dict(entry).get("resolved")
|
|
1215
|
+
key = f"{prefix}{name}"
|
|
1216
|
+
if isinstance(resolved, str):
|
|
1217
|
+
out.append(LockEntry(key, resolved, where.get(resolved)))
|
|
1218
|
+
walk(_dict(entry).get("dependencies"), key + ">", depth + 1)
|
|
1219
|
+
|
|
1220
|
+
walk(_dict(data).get("dependencies"), "", 0)
|
|
1221
|
+
return out
|
|
1222
|
+
|
|
1223
|
+
|
|
1224
|
+
_YARN_RESOLVED = re.compile(r"\s{2,8}resolved\s{1,5}\"?([^\"\s]{1,4000})\"?")
|
|
1225
|
+
|
|
1226
|
+
|
|
1227
|
+
def _yarn_lock(text: str, lines: tuple[str, ...]) -> list[LockEntry] | None:
|
|
1228
|
+
if any(line.startswith("__metadata:") for line in lines[:50]):
|
|
1229
|
+
result = yamlish.parse(text.removeprefix(""))
|
|
1230
|
+
if result.errors or result.unsupported:
|
|
1231
|
+
return None
|
|
1232
|
+
out: list[LockEntry] = []
|
|
1233
|
+
for document in result.documents:
|
|
1234
|
+
if not isinstance(document.root, YamlMap):
|
|
1235
|
+
continue
|
|
1236
|
+
for entry in document.root.entries:
|
|
1237
|
+
if entry.key_text == "__metadata" or not isinstance(entry.value, YamlMap):
|
|
1238
|
+
continue
|
|
1239
|
+
resolution = entry.value.get("resolution")
|
|
1240
|
+
if not isinstance(resolution, YamlScalar):
|
|
1241
|
+
continue
|
|
1242
|
+
value = resolution.value
|
|
1243
|
+
at = value.find("@", 1)
|
|
1244
|
+
source = value[at + 1 :] if at > 0 else value
|
|
1245
|
+
protocol = source.split(":", 1)[0]
|
|
1246
|
+
if protocol in ("workspace", "patch", "portal", "link", "file", "exec"):
|
|
1247
|
+
continue
|
|
1248
|
+
raw = "npm" if protocol == "npm" else source
|
|
1249
|
+
out.append(LockEntry(entry.key_text, raw, resolution.start_line))
|
|
1250
|
+
return out
|
|
1251
|
+
out = []
|
|
1252
|
+
key = ""
|
|
1253
|
+
for number, line in enumerate(lines, start=1):
|
|
1254
|
+
if (
|
|
1255
|
+
line
|
|
1256
|
+
and not line[0].isspace()
|
|
1257
|
+
and not line.startswith("#")
|
|
1258
|
+
and line.rstrip().endswith(":")
|
|
1259
|
+
):
|
|
1260
|
+
key = line.rstrip()[:-1].strip()
|
|
1261
|
+
continue
|
|
1262
|
+
m = _YARN_RESOLVED.match(line)
|
|
1263
|
+
if m is not None and key:
|
|
1264
|
+
out.append(LockEntry(key, m.group(1), number))
|
|
1265
|
+
return out
|
|
1266
|
+
|
|
1267
|
+
|
|
1268
|
+
def _pnpm_lock(result: yamlish.YamlResult | None) -> list[LockEntry] | None:
|
|
1269
|
+
if result is None or result.errors:
|
|
1270
|
+
return None
|
|
1271
|
+
out: list[LockEntry] = []
|
|
1272
|
+
for document in result.documents:
|
|
1273
|
+
if not isinstance(document.root, YamlMap):
|
|
1274
|
+
continue
|
|
1275
|
+
packages = document.root.get("packages")
|
|
1276
|
+
if not isinstance(packages, YamlMap):
|
|
1277
|
+
continue
|
|
1278
|
+
for entry in packages.entries:
|
|
1279
|
+
body = entry.value
|
|
1280
|
+
resolution = body.get("resolution") if isinstance(body, YamlMap) else None
|
|
1281
|
+
if not isinstance(resolution, YamlMap):
|
|
1282
|
+
continue
|
|
1283
|
+
for field in ("tarball", "repo"):
|
|
1284
|
+
node = resolution.get(field)
|
|
1285
|
+
if isinstance(node, YamlScalar):
|
|
1286
|
+
out.append(LockEntry(entry.key_text, node.value, node.start_line))
|
|
1287
|
+
break
|
|
1288
|
+
else:
|
|
1289
|
+
out.append(LockEntry(entry.key_text, "registry", entry.key_line))
|
|
1290
|
+
return out
|
|
1291
|
+
|
|
1292
|
+
|
|
1293
|
+
def _toml_packages(data: object, lines: tuple[str, ...], eco: str) -> list[LockEntry]:
|
|
1294
|
+
index = TomlLines(lines)
|
|
1295
|
+
blocks = index.find(("package",))
|
|
1296
|
+
out: list[LockEntry] = []
|
|
1297
|
+
packages = _dict(data).get("package")
|
|
1298
|
+
for i, package in enumerate(packages if isinstance(packages, list) else []):
|
|
1299
|
+
package = _dict(package)
|
|
1300
|
+
name = _str(package.get("name"))
|
|
1301
|
+
version = _str(package.get("version"))
|
|
1302
|
+
source = package.get("source")
|
|
1303
|
+
raw = ""
|
|
1304
|
+
if eco == "cargo":
|
|
1305
|
+
raw = _str(source)
|
|
1306
|
+
elif eco == "uv":
|
|
1307
|
+
table = _dict(source)
|
|
1308
|
+
for field in ("registry", "git", "url"):
|
|
1309
|
+
if isinstance(table.get(field), str):
|
|
1310
|
+
raw = table[field] if field != "git" else "git+" + table[field] # type: ignore[operator]
|
|
1311
|
+
break
|
|
1312
|
+
else: # poetry
|
|
1313
|
+
table = _dict(source)
|
|
1314
|
+
if isinstance(table.get("url"), str):
|
|
1315
|
+
raw = ("git+" if table.get("type") == "git" else "") + table["url"] # type: ignore[operator]
|
|
1316
|
+
elif not table:
|
|
1317
|
+
raw = "pypi"
|
|
1318
|
+
if not name or not raw:
|
|
1319
|
+
continue
|
|
1320
|
+
line = None
|
|
1321
|
+
if i < len(blocks):
|
|
1322
|
+
block = blocks[i]
|
|
1323
|
+
line = index.key_line(block, "source")
|
|
1324
|
+
if line is None:
|
|
1325
|
+
for sub in index.find(("package", "source")):
|
|
1326
|
+
if (
|
|
1327
|
+
block.header
|
|
1328
|
+
< sub.header
|
|
1329
|
+
<= (blocks[i + 1].header if i + 1 < len(blocks) else len(lines) + 1)
|
|
1330
|
+
):
|
|
1331
|
+
line = index.key_line(sub, "url") or sub.header
|
|
1332
|
+
break
|
|
1333
|
+
if line is None:
|
|
1334
|
+
line = block.header
|
|
1335
|
+
out.append(LockEntry(f"{name} {version}", raw, line))
|
|
1336
|
+
return out
|
|
1337
|
+
|
|
1338
|
+
|
|
1339
|
+
def _go_sum(lines: tuple[str, ...]) -> list[LockEntry]:
|
|
1340
|
+
out: list[LockEntry] = []
|
|
1341
|
+
for number, line in enumerate(lines, start=1):
|
|
1342
|
+
parts = line.split()
|
|
1343
|
+
if len(parts) == 3:
|
|
1344
|
+
out.append(LockEntry(f"{parts[0]} {parts[1]}", "checksum " + parts[2], number))
|
|
1345
|
+
return out
|
|
1346
|
+
|
|
1347
|
+
|
|
1348
|
+
def _gemfile_lock(lines: tuple[str, ...]) -> list[LockEntry]:
|
|
1349
|
+
out: list[LockEntry] = []
|
|
1350
|
+
section = ""
|
|
1351
|
+
remote = ""
|
|
1352
|
+
remote_line = 0
|
|
1353
|
+
in_specs = False
|
|
1354
|
+
for number, line in enumerate(lines, start=1):
|
|
1355
|
+
if line and not line[0].isspace():
|
|
1356
|
+
section, remote, in_specs = line.strip(), "", False
|
|
1357
|
+
continue
|
|
1358
|
+
stripped = line.strip()
|
|
1359
|
+
if stripped.startswith("remote:"):
|
|
1360
|
+
remote, remote_line = stripped[len("remote:") :].strip(), number
|
|
1361
|
+
elif stripped == "specs:":
|
|
1362
|
+
in_specs = True
|
|
1363
|
+
elif in_specs and line.startswith(" ") and not line.startswith(" "):
|
|
1364
|
+
name = stripped.split(" ", 1)[0]
|
|
1365
|
+
if section in ("GEM", "GIT", "PLUGIN SOURCE") and remote:
|
|
1366
|
+
raw = remote if section == "GEM" else "git+" + remote
|
|
1367
|
+
out.append(LockEntry(name, raw, remote_line))
|
|
1368
|
+
elif section == "PATH":
|
|
1369
|
+
out.append(LockEntry(name, "path:" + remote, remote_line or number))
|
|
1370
|
+
return out
|
|
1371
|
+
|
|
1372
|
+
|
|
1373
|
+
def _composer_lock(data: object, lines: tuple[str, ...]) -> list[LockEntry]:
|
|
1374
|
+
where = _first_lines(lines, _JSON_URL)
|
|
1375
|
+
out: list[LockEntry] = []
|
|
1376
|
+
for section in ("packages", "packages-dev"):
|
|
1377
|
+
items = _dict(data).get(section)
|
|
1378
|
+
for package in items if isinstance(items, list) else []:
|
|
1379
|
+
package = _dict(package)
|
|
1380
|
+
name = _str(package.get("name"))
|
|
1381
|
+
url = _str(_dict(package.get("source")).get("url")) or _str(
|
|
1382
|
+
_dict(package.get("dist")).get("url")
|
|
1383
|
+
)
|
|
1384
|
+
if name and url:
|
|
1385
|
+
out.append(LockEntry(name, url, where.get(url)))
|
|
1386
|
+
return out
|
|
1387
|
+
|
|
1388
|
+
|
|
1389
|
+
def lock_entries(path: str, text: str, ctx: FileContext | None = None) -> list[LockEntry] | None:
|
|
1390
|
+
"""The locked packages of ``text``, or ``None`` when it cannot be read.
|
|
1391
|
+
|
|
1392
|
+
``ctx`` (whose new side is ``text``) lends its cached JSON/TOML/YAML parse.
|
|
1393
|
+
"""
|
|
1394
|
+
name = _base(path)
|
|
1395
|
+
lines = git_lines(text)
|
|
1396
|
+
if name in ("package-lock.json", "npm-shrinkwrap.json", "composer.lock"):
|
|
1397
|
+
data = ctx.json if ctx is not None else _json(text)
|
|
1398
|
+
if not isinstance(data, dict):
|
|
1399
|
+
return None
|
|
1400
|
+
return _composer_lock(data, lines) if name == "composer.lock" else _npm_lock(data, lines)
|
|
1401
|
+
if name == "yarn.lock":
|
|
1402
|
+
return _yarn_lock(text, lines)
|
|
1403
|
+
if name == "pnpm-lock.yaml":
|
|
1404
|
+
return _pnpm_lock(ctx.yaml if ctx is not None else yamlish.parse(text.removeprefix("")))
|
|
1405
|
+
if name in ("uv.lock", "poetry.lock", "Cargo.lock"):
|
|
1406
|
+
data = ctx.toml if ctx is not None else _toml(text)
|
|
1407
|
+
if not isinstance(data, dict):
|
|
1408
|
+
return None
|
|
1409
|
+
eco = {"uv.lock": "uv", "poetry.lock": "poetry", "Cargo.lock": "cargo"}[name]
|
|
1410
|
+
return _toml_packages(data, lines, eco)
|
|
1411
|
+
if name == "go.sum":
|
|
1412
|
+
return _go_sum(lines)
|
|
1413
|
+
if name == "Gemfile.lock":
|
|
1414
|
+
return _gemfile_lock(lines)
|
|
1415
|
+
return []
|
|
1416
|
+
|
|
1417
|
+
|
|
1418
|
+
_SOURCE_CHECKED = frozenset(
|
|
1419
|
+
{
|
|
1420
|
+
"package-lock.json",
|
|
1421
|
+
"npm-shrinkwrap.json",
|
|
1422
|
+
"yarn.lock",
|
|
1423
|
+
"pnpm-lock.yaml",
|
|
1424
|
+
"uv.lock",
|
|
1425
|
+
"poetry.lock",
|
|
1426
|
+
"Cargo.lock",
|
|
1427
|
+
"go.sum",
|
|
1428
|
+
"Gemfile.lock",
|
|
1429
|
+
"composer.lock",
|
|
1430
|
+
}
|
|
1431
|
+
)
|
|
1432
|
+
|
|
1433
|
+
|
|
1434
|
+
@rule(
|
|
1435
|
+
id="deps/lockfile-source-changed",
|
|
1436
|
+
severity="error",
|
|
1437
|
+
title="Locked package now comes from another source",
|
|
1438
|
+
scope="file",
|
|
1439
|
+
rationale=(
|
|
1440
|
+
"Lockfile diffs are rarely read. Changing where an already-locked package is downloaded "
|
|
1441
|
+
"from (another registry host or Git repository), or its go.sum checksum, swaps its code "
|
|
1442
|
+
"without any visible version change."
|
|
1443
|
+
),
|
|
1444
|
+
hint="Regenerate the lockfile from the manifest with the official registry and compare.",
|
|
1445
|
+
tags={"deps", "supply-chain"},
|
|
1446
|
+
)
|
|
1447
|
+
def lockfile_source_changed(ctx: FileContext) -> Iterator[Hit]:
|
|
1448
|
+
"""An existing lockfile entry whose source changed.
|
|
1449
|
+
|
|
1450
|
+
Entries are keyed per format (install path in ``package-lock.json``,
|
|
1451
|
+
descriptor in ``yarn.lock`` v1 and Berry, package key in
|
|
1452
|
+
``pnpm-lock.yaml``, name and version in ``uv.lock``/``poetry.lock``/
|
|
1453
|
+
``Cargo.lock``, module and version in ``go.sum``, gem name in
|
|
1454
|
+
``Gemfile.lock``, package name in ``composer.lock``). The source is the
|
|
1455
|
+
registry host or Git repository (``registry.yarnpkg.com`` counts as
|
|
1456
|
+
npmjs, the crates.io Git and sparse indexes as one); for ``go.sum`` it
|
|
1457
|
+
is the checksum. Version bumps on the same source are not reported. A
|
|
1458
|
+
new side that cannot be read makes coverage partial.
|
|
1459
|
+
"""
|
|
1460
|
+
if _base(ctx.path) not in _SOURCE_CHECKED or ctx.old_text is None or ctx.new_text is None:
|
|
1461
|
+
return
|
|
1462
|
+
new = lock_entries(ctx.path, ctx.new_text, ctx)
|
|
1463
|
+
if new is None:
|
|
1464
|
+
raise PartialCoverage("lockfile could not be read")
|
|
1465
|
+
old = lock_entries(ctx.old_path or ctx.path, ctx.old_text)
|
|
1466
|
+
if not old:
|
|
1467
|
+
return
|
|
1468
|
+
before: dict[str, str] = {}
|
|
1469
|
+
for entry in old:
|
|
1470
|
+
before.setdefault(entry.key, normalize_source(entry.raw))
|
|
1471
|
+
for entry in new:
|
|
1472
|
+
if entry.key not in before:
|
|
1473
|
+
continue
|
|
1474
|
+
was, now = before[entry.key], normalize_source(entry.raw)
|
|
1475
|
+
if was != now:
|
|
1476
|
+
line = entry.line or 1
|
|
1477
|
+
end = None if entry.line else max(len(ctx.lines), 1)
|
|
1478
|
+
yield Hit(
|
|
1479
|
+
line,
|
|
1480
|
+
end_line=end,
|
|
1481
|
+
evidence=f"{entry.key}: {was} -> {now}",
|
|
1482
|
+
message=f"{entry.key} changed source from {was} to {now}",
|
|
1483
|
+
)
|
|
1484
|
+
|
|
1485
|
+
|
|
1486
|
+
# --- lockfile-mismatch ---------------------------------------------------------------------
|
|
1487
|
+
|
|
1488
|
+
|
|
1489
|
+
def _parsed(f: FileContext, side: str) -> object:
|
|
1490
|
+
kind = manifest_kind(f.path)
|
|
1491
|
+
if kind in ("package.json", "composer.json"):
|
|
1492
|
+
return f.json if side == "new" else f.old_json
|
|
1493
|
+
if kind in ("pyproject.toml", "Pipfile", "Cargo.toml"):
|
|
1494
|
+
return f.toml if side == "new" else f.old_toml
|
|
1495
|
+
return None
|
|
1496
|
+
|
|
1497
|
+
|
|
1498
|
+
def _dep_set(f: FileContext, side: str) -> frozenset[tuple[str, str, str, str]]:
|
|
1499
|
+
text = f.new_text if side == "new" else f.old_text
|
|
1500
|
+
path = f.path if side == "new" else (f.old_path or f.path)
|
|
1501
|
+
deps = manifest_deps(path, text, _parsed(f, side)) or []
|
|
1502
|
+
return frozenset((d.section, d.key, d.spec.strip(), d.kind) for d in deps)
|
|
1503
|
+
|
|
1504
|
+
|
|
1505
|
+
def _expects_lock(f: FileContext) -> bool:
|
|
1506
|
+
name = _base(f.path)
|
|
1507
|
+
if name != "pyproject.toml":
|
|
1508
|
+
return name in MANIFESTS
|
|
1509
|
+
for data in (f.toml, f.old_toml):
|
|
1510
|
+
tool = _dict(_dict(data).get("tool"))
|
|
1511
|
+
if any(k in tool for k in ("poetry", "uv", "pdm")):
|
|
1512
|
+
return True
|
|
1513
|
+
return False
|
|
1514
|
+
|
|
1515
|
+
|
|
1516
|
+
def _within(child_dir: str, parent_dir: str) -> bool:
|
|
1517
|
+
return not parent_dir or child_dir == parent_dir or child_dir.startswith(parent_dir + "/")
|
|
1518
|
+
|
|
1519
|
+
|
|
1520
|
+
def _first_change(f: FileContext) -> int | None:
|
|
1521
|
+
if f.change.status is not FileStatus.MODIFIED:
|
|
1522
|
+
return None
|
|
1523
|
+
changed = f.added_lines | f.deletion_points
|
|
1524
|
+
return min(changed) if changed else None
|
|
1525
|
+
|
|
1526
|
+
|
|
1527
|
+
@rule(
|
|
1528
|
+
id="deps/lockfile-mismatch",
|
|
1529
|
+
severity="warning",
|
|
1530
|
+
title="Manifest and lockfile changed apart",
|
|
1531
|
+
scope="change",
|
|
1532
|
+
rationale=(
|
|
1533
|
+
"A dependency change without the lockfile change installs something nobody reviewed "
|
|
1534
|
+
"(or fails a frozen install); a lockfile change without a manifest change alters "
|
|
1535
|
+
"installed code where reviewers seldom look."
|
|
1536
|
+
),
|
|
1537
|
+
hint=(
|
|
1538
|
+
"Change dependencies through the package manager and commit manifest and lockfile together."
|
|
1539
|
+
),
|
|
1540
|
+
tags={"deps", "supply-chain"},
|
|
1541
|
+
)
|
|
1542
|
+
def lockfile_mismatch(ctx: ChangeContext) -> Iterator[Hit]:
|
|
1543
|
+
"""Per ecosystem (npm, Python, Cargo, Go, Ruby, Composer).
|
|
1544
|
+
|
|
1545
|
+
A manifest whose declared dependencies changed needs a lockfile change
|
|
1546
|
+
of its ecosystem in its directory or an ancestor (workspaces); a
|
|
1547
|
+
``pyproject.toml`` only when it configures Poetry, uv or PDM, and
|
|
1548
|
+
requirements files never (they are their own lock). A changed lockfile
|
|
1549
|
+
needs some change to a manifest of its ecosystem (or a ``.gemspec``
|
|
1550
|
+
for ``Gemfile.lock``) in its directory or below. The change only shows
|
|
1551
|
+
changed files, so a project that keeps no lockfile at all is reported
|
|
1552
|
+
too: the message says so.
|
|
1553
|
+
"""
|
|
1554
|
+
files = [f for f in ctx.files if f.kind is FileKind.TEXT]
|
|
1555
|
+
locks = [(f, LOCKFILES[_base(f.path)]) for f in files if _base(f.path) in LOCKFILES]
|
|
1556
|
+
manifests = [(f, MANIFESTS[_base(f.path)]) for f in files if _base(f.path) in MANIFESTS]
|
|
1557
|
+
gemspecs = [f for f in files if f.path.endswith(".gemspec")]
|
|
1558
|
+
for f, eco in manifests:
|
|
1559
|
+
if not _expects_lock(f) or _dep_set(f, "new") == _dep_set(f, "old"):
|
|
1560
|
+
continue
|
|
1561
|
+
here = _dir(f.path)
|
|
1562
|
+
if any(e == eco and _within(here, _dir(lock.path)) for lock, e in locks):
|
|
1563
|
+
continue
|
|
1564
|
+
names = sorted({n for n, e in LOCKFILES.items() if e == eco and n != "Pipfile.lock"})
|
|
1565
|
+
if _base(f.path) == "Pipfile":
|
|
1566
|
+
names = ["Pipfile.lock"]
|
|
1567
|
+
yield Hit(
|
|
1568
|
+
_first_change(f),
|
|
1569
|
+
path=f.path,
|
|
1570
|
+
message=f"Dependencies changed without a lockfile change ({', '.join(names)}); "
|
|
1571
|
+
"fine only if the project keeps no lockfile",
|
|
1572
|
+
)
|
|
1573
|
+
for f, eco in locks:
|
|
1574
|
+
here = _dir(f.path)
|
|
1575
|
+
related = [m for m, e in manifests if e == eco and _within(_dir(m.path), here)]
|
|
1576
|
+
if eco == "ruby":
|
|
1577
|
+
related += [g for g in gemspecs if _within(_dir(g.path), here)]
|
|
1578
|
+
if related:
|
|
1579
|
+
continue
|
|
1580
|
+
yield Hit(
|
|
1581
|
+
_first_change(f),
|
|
1582
|
+
path=f.path,
|
|
1583
|
+
message=f"{_base(f.path)} changed without any manifest change",
|
|
1584
|
+
)
|
|
1585
|
+
|
|
1586
|
+
|
|
1587
|
+
# --- Submodules -----------------------------------------------------------------------------
|
|
1588
|
+
|
|
1589
|
+
_SUBMODULE_HEADER = re.compile(r"\s{0,40}\[\s{0,5}submodule\s{1,10}\"([^\"\n]{1,500})\"\s{0,5}\]")
|
|
1590
|
+
_SUBMODULE_KEY = re.compile(r"\s{0,40}(path|url)\s{0,10}=\s{0,10}(.{1,4000}?)\s{0,40}\Z")
|
|
1591
|
+
|
|
1592
|
+
|
|
1593
|
+
def gitmodules(lines: tuple[str, ...]) -> dict[str, dict[str, tuple[str, int]]]:
|
|
1594
|
+
"""``{name: {"path"|"url": (value, line)}}`` of a ``.gitmodules`` file."""
|
|
1595
|
+
out: dict[str, dict[str, tuple[str, int]]] = {}
|
|
1596
|
+
current: dict[str, tuple[str, int]] | None = None
|
|
1597
|
+
for number, line in enumerate(lines, start=1):
|
|
1598
|
+
stripped = line.strip()
|
|
1599
|
+
if not stripped or stripped[0] in "#;":
|
|
1600
|
+
continue
|
|
1601
|
+
m = _SUBMODULE_HEADER.match(line)
|
|
1602
|
+
if m is not None:
|
|
1603
|
+
current = out.setdefault(m.group(1), {})
|
|
1604
|
+
continue
|
|
1605
|
+
if stripped.startswith("["):
|
|
1606
|
+
current = None
|
|
1607
|
+
continue
|
|
1608
|
+
k = _SUBMODULE_KEY.match(line)
|
|
1609
|
+
if k is not None and current is not None:
|
|
1610
|
+
current[k.group(1)] = (k.group(2).strip().strip('"'), number)
|
|
1611
|
+
return out
|
|
1612
|
+
|
|
1613
|
+
|
|
1614
|
+
def normalize_repo(url: str) -> str:
|
|
1615
|
+
"""``host/path`` of a Git URL (scheme, user, ``.git`` and case of the host dropped)."""
|
|
1616
|
+
s = url.strip()
|
|
1617
|
+
m = re.match(
|
|
1618
|
+
r"(?:[a-z][a-z0-9+.-]{0,20}://)?(?:[^@/\s]{1,200}@)?([^/:\s]{1,253})(?::[0-9]{1,5}(?=/))?[:/](.{0,2000})",
|
|
1619
|
+
s,
|
|
1620
|
+
re.I,
|
|
1621
|
+
)
|
|
1622
|
+
if m is None or s.startswith((".", "/")):
|
|
1623
|
+
return s.rstrip("/")
|
|
1624
|
+
return m.group(1).lower() + "/" + m.group(2).rstrip("/").removesuffix(".git")
|
|
1625
|
+
|
|
1626
|
+
|
|
1627
|
+
@rule(
|
|
1628
|
+
id="deps/submodule-url-changed",
|
|
1629
|
+
severity="error",
|
|
1630
|
+
title="Submodule now points at another repository",
|
|
1631
|
+
scope="file",
|
|
1632
|
+
rationale=(
|
|
1633
|
+
"Changing a submodule's URL swaps the repository its code is fetched from; the commit "
|
|
1634
|
+
"pointer may look unchanged while the code behind it now comes from someone else."
|
|
1635
|
+
),
|
|
1636
|
+
hint="Confirm the new repository is the intended, trusted source.",
|
|
1637
|
+
tags={"deps", "supply-chain"},
|
|
1638
|
+
)
|
|
1639
|
+
def submodule_url_changed(ctx: FileContext) -> Iterator[Hit]:
|
|
1640
|
+
"""A ``.gitmodules`` URL changed for a submodule of the same name or path.
|
|
1641
|
+
|
|
1642
|
+
URLs are compared as host and path, so switching between HTTPS and SSH,
|
|
1643
|
+
adding ``.git`` or changing the host's case is not a change. New and
|
|
1644
|
+
removed submodules are ``deps/submodule-changed``.
|
|
1645
|
+
"""
|
|
1646
|
+
if _base(ctx.path) != ".gitmodules" or ctx.old_text is None or ctx.new_text is None:
|
|
1647
|
+
return
|
|
1648
|
+
old = gitmodules(ctx.old_lines)
|
|
1649
|
+
old_by_path = {v["path"][0]: v for v in old.values() if "path" in v}
|
|
1650
|
+
for name, entry in gitmodules(ctx.lines).items():
|
|
1651
|
+
if "url" not in entry:
|
|
1652
|
+
continue
|
|
1653
|
+
before = old.get(name)
|
|
1654
|
+
if before is None and "path" in entry:
|
|
1655
|
+
before = old_by_path.get(entry["path"][0])
|
|
1656
|
+
if before is None or "url" not in before:
|
|
1657
|
+
continue
|
|
1658
|
+
url, line = entry["url"]
|
|
1659
|
+
if normalize_repo(url) != normalize_repo(before["url"][0]):
|
|
1660
|
+
yield Hit(
|
|
1661
|
+
line,
|
|
1662
|
+
column=_column(ctx, line, url),
|
|
1663
|
+
evidence=f"{name}: {before['url'][0]} -> {url}",
|
|
1664
|
+
message=f"Submodule {name} URL changed from {before['url'][0]} to {url}",
|
|
1665
|
+
)
|
|
1666
|
+
|
|
1667
|
+
|
|
1668
|
+
@rule(
|
|
1669
|
+
id="deps/submodule-changed",
|
|
1670
|
+
severity="warning",
|
|
1671
|
+
title="Submodule added, removed or moved to another commit",
|
|
1672
|
+
scope="file",
|
|
1673
|
+
kinds={"submodule"},
|
|
1674
|
+
rationale=(
|
|
1675
|
+
"A submodule pointer change pulls in another commit of an external repository; the diff "
|
|
1676
|
+
"shows only two hashes, none of the code."
|
|
1677
|
+
),
|
|
1678
|
+
hint="Review the submodule's own history between the two commits.",
|
|
1679
|
+
tags={"deps", "supply-chain"},
|
|
1680
|
+
)
|
|
1681
|
+
def submodule_changed(ctx: FileContext) -> Iterator[Hit]:
|
|
1682
|
+
"""Any submodule (gitlink) change: added, removed, renamed or a new commit."""
|
|
1683
|
+
change = ctx.change
|
|
1684
|
+
old, new = change.submodule_old, change.submodule_new
|
|
1685
|
+
if change.status is FileStatus.ADDED:
|
|
1686
|
+
message = f"Submodule {ctx.path} added at {(new or '?')[:12]}"
|
|
1687
|
+
elif change.status is FileStatus.DELETED:
|
|
1688
|
+
message = f"Submodule {ctx.path} removed"
|
|
1689
|
+
elif old and new and old != new:
|
|
1690
|
+
message = f"Submodule {ctx.path} moved from {old[:12]} to {new[:12]}"
|
|
1691
|
+
else:
|
|
1692
|
+
message = f"Submodule {ctx.path} {change.status.value}"
|
|
1693
|
+
yield Hit(None, message=message)
|