modelbom 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.
- modelbom/__init__.py +9 -0
- modelbom/__main__.py +5 -0
- modelbom/artifacts.py +696 -0
- modelbom/attack_paths.py +202 -0
- modelbom/cli.py +202 -0
- modelbom/code_rules.py +642 -0
- modelbom/deps.py +461 -0
- modelbom/discovery.py +126 -0
- modelbom/graph.py +257 -0
- modelbom/models.py +201 -0
- modelbom/pickle_scan.py +417 -0
- modelbom/py.typed +0 -0
- modelbom/report/__init__.py +16 -0
- modelbom/report/cyclonedx.py +219 -0
- modelbom/report/jsonfmt.py +78 -0
- modelbom/report/sarif.py +110 -0
- modelbom/report/text.py +60 -0
- modelbom/rules.py +350 -0
- modelbom/scanner.py +77 -0
- modelbom-0.1.0.dist-info/METADATA +265 -0
- modelbom-0.1.0.dist-info/RECORD +25 -0
- modelbom-0.1.0.dist-info/WHEEL +4 -0
- modelbom-0.1.0.dist-info/entry_points.txt +2 -0
- modelbom-0.1.0.dist-info/licenses/LICENSE +202 -0
- modelbom-0.1.0.dist-info/licenses/NOTICE +14 -0
modelbom/deps.py
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
"""Dependency manifests and lock files: parsing, pinning analysis (MB301) and OSV lookups (MB302).
|
|
2
|
+
|
|
3
|
+
Supported inputs: ``requirements*.txt`` / ``*.in`` (with ``-r``/``-c`` includes), ``constraints.txt``,
|
|
4
|
+
``pyproject.toml`` (PEP 621, PEP 735 dependency groups, Poetry), ``Pipfile``, and the lock files
|
|
5
|
+
``uv.lock``, ``poetry.lock``, ``pdm.lock`` and ``Pipfile.lock``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
import tomllib
|
|
13
|
+
import urllib.request
|
|
14
|
+
from collections.abc import Callable, Iterable
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from . import __version__
|
|
19
|
+
from .models import Dependency, Finding, Severity
|
|
20
|
+
|
|
21
|
+
OSV_BATCH_URL = "https://api.osv.dev/v1/querybatch"
|
|
22
|
+
OSV_VULN_URL = "https://api.osv.dev/v1/vulns/{id}"
|
|
23
|
+
|
|
24
|
+
ML_PACKAGES = frozenset(
|
|
25
|
+
{
|
|
26
|
+
"torch",
|
|
27
|
+
"torchvision",
|
|
28
|
+
"torchaudio",
|
|
29
|
+
"transformers",
|
|
30
|
+
"tensorflow",
|
|
31
|
+
"keras",
|
|
32
|
+
"tf-keras",
|
|
33
|
+
"jax",
|
|
34
|
+
"flax",
|
|
35
|
+
"safetensors",
|
|
36
|
+
"huggingface-hub",
|
|
37
|
+
"datasets",
|
|
38
|
+
"diffusers",
|
|
39
|
+
"accelerate",
|
|
40
|
+
"onnx",
|
|
41
|
+
"onnxruntime",
|
|
42
|
+
"onnxruntime-gpu",
|
|
43
|
+
"scikit-learn",
|
|
44
|
+
"joblib",
|
|
45
|
+
"numpy",
|
|
46
|
+
"pandas",
|
|
47
|
+
"sentence-transformers",
|
|
48
|
+
"vllm",
|
|
49
|
+
"openai",
|
|
50
|
+
"anthropic",
|
|
51
|
+
"tiktoken",
|
|
52
|
+
"tokenizers",
|
|
53
|
+
"sentencepiece",
|
|
54
|
+
"peft",
|
|
55
|
+
"trl",
|
|
56
|
+
"bitsandbytes",
|
|
57
|
+
"xgboost",
|
|
58
|
+
"lightgbm",
|
|
59
|
+
"catboost",
|
|
60
|
+
"mlflow",
|
|
61
|
+
"timm",
|
|
62
|
+
"llama-cpp-python",
|
|
63
|
+
"litellm",
|
|
64
|
+
"chromadb",
|
|
65
|
+
"faiss-cpu",
|
|
66
|
+
"faiss-gpu",
|
|
67
|
+
"optimum",
|
|
68
|
+
"deepspeed",
|
|
69
|
+
"ray",
|
|
70
|
+
"gguf",
|
|
71
|
+
}
|
|
72
|
+
)
|
|
73
|
+
_ML_PREFIXES = ("langchain", "llama-index", "tensorflow-", "keras-", "torch-", "onnxruntime-")
|
|
74
|
+
LOCK_FILES = frozenset({"uv.lock", "poetry.lock", "pdm.lock", "Pipfile.lock"})
|
|
75
|
+
|
|
76
|
+
_REQ = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)\s*(\[[^\]]*\])?\s*(.*)$")
|
|
77
|
+
_EXACT = re.compile(r"^===?\s*([A-Za-z0-9][A-Za-z0-9.+!_-]*)$")
|
|
78
|
+
_HEX_REF = re.compile(r"@[0-9a-f]{7,40}\b")
|
|
79
|
+
_EGG = re.compile(r"[#&]egg=([A-Za-z0-9][A-Za-z0-9._-]*)")
|
|
80
|
+
|
|
81
|
+
HttpJson = Callable[[str, Any], Any]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def normalize(name: str) -> str:
|
|
85
|
+
return re.sub(r"[-_.]+", "-", name).lower()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def is_ml_package(name: str) -> bool:
|
|
89
|
+
n = normalize(name)
|
|
90
|
+
return n in ML_PACKAGES or n.startswith(_ML_PREFIXES)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def is_manifest(rel: str) -> bool:
|
|
94
|
+
parts = rel.split("/")
|
|
95
|
+
name = parts[-1]
|
|
96
|
+
lower = name.lower()
|
|
97
|
+
if name in LOCK_FILES or name in ("pyproject.toml", "Pipfile"):
|
|
98
|
+
return True
|
|
99
|
+
if lower in ("constraints.txt",) or re.match(r"^(.*[-_.])?requirements([-_.].*)?\.(txt|in)$", lower):
|
|
100
|
+
return True
|
|
101
|
+
return len(parts) > 1 and parts[-2].lower() == "requirements" and lower.endswith((".txt", ".in"))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _spec_info(spec: str) -> tuple[str | None, bool]:
|
|
105
|
+
"""Return (exact_version, pinned) for a PEP 508 version specifier or direct reference."""
|
|
106
|
+
spec = spec.strip()
|
|
107
|
+
if spec.startswith("@"):
|
|
108
|
+
url = spec[1:].strip()
|
|
109
|
+
return None, bool(_HEX_REF.search(url) or "#sha256=" in url or url.endswith(".whl"))
|
|
110
|
+
if spec.startswith("(") and spec.endswith(")"):
|
|
111
|
+
spec = spec[1:-1].strip()
|
|
112
|
+
m = _EXACT.match(spec)
|
|
113
|
+
if m and "*" not in m.group(1):
|
|
114
|
+
return m.group(1), True
|
|
115
|
+
return None, False
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def parse_requirement(text: str) -> tuple[str, str, str | None, bool] | None:
|
|
119
|
+
"""Parse a single PEP 508 requirement string into (name, specifier, version, pinned)."""
|
|
120
|
+
text = text.split(";", 1)[0].strip()
|
|
121
|
+
if not text:
|
|
122
|
+
return None
|
|
123
|
+
m = _REQ.match(text)
|
|
124
|
+
if not m:
|
|
125
|
+
return None
|
|
126
|
+
name, _extras, rest = m.groups()
|
|
127
|
+
rest = rest.strip()
|
|
128
|
+
version, pinned = _spec_info(rest)
|
|
129
|
+
return normalize(name), rest, version, pinned
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _dep(name: str, spec: str, version: str | None, pinned: bool, rel: str, line: int | None, kind: str) -> Dependency:
|
|
133
|
+
return Dependency(
|
|
134
|
+
name=name,
|
|
135
|
+
specifier=spec,
|
|
136
|
+
version=version,
|
|
137
|
+
pinned=pinned,
|
|
138
|
+
source=rel,
|
|
139
|
+
line=line,
|
|
140
|
+
ml_relevant=is_ml_package(name),
|
|
141
|
+
kind=kind,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _logical_lines(text: str) -> Iterable[tuple[int, str, str]]:
|
|
146
|
+
"""Yield (line_number, content, comment) joining backslash continuations."""
|
|
147
|
+
buf = ""
|
|
148
|
+
start = 0
|
|
149
|
+
for number, raw in enumerate(text.splitlines(), start=1):
|
|
150
|
+
if not buf:
|
|
151
|
+
start = number
|
|
152
|
+
content, _, comment = raw.partition(" #")
|
|
153
|
+
if raw.lstrip().startswith("#"):
|
|
154
|
+
content, comment = "", raw.lstrip()[1:]
|
|
155
|
+
if content.rstrip().endswith("\\"):
|
|
156
|
+
buf += content.rstrip()[:-1] + " "
|
|
157
|
+
continue
|
|
158
|
+
yield start, (buf + content).strip(), comment
|
|
159
|
+
buf = ""
|
|
160
|
+
if buf:
|
|
161
|
+
yield start, buf.strip(), ""
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def parse_requirements_text(text: str, rel: str) -> tuple[list[Dependency], list[str], dict[int, str]]:
|
|
165
|
+
"""Return (dependencies, include_paths, comments_by_line)."""
|
|
166
|
+
deps: list[Dependency] = []
|
|
167
|
+
includes: list[str] = []
|
|
168
|
+
comments: dict[int, str] = {}
|
|
169
|
+
for number, content, comment in _logical_lines(text):
|
|
170
|
+
if comment:
|
|
171
|
+
comments[number] = comment
|
|
172
|
+
if not content:
|
|
173
|
+
continue
|
|
174
|
+
if content.startswith(("-r", "--requirement", "-c", "--constraint")):
|
|
175
|
+
parts = content.replace("=", " ").split(None, 1)
|
|
176
|
+
if len(parts) == 2:
|
|
177
|
+
includes.append(parts[1].strip())
|
|
178
|
+
continue
|
|
179
|
+
if content.startswith(("-e", "--editable")):
|
|
180
|
+
egg = _EGG.search(content)
|
|
181
|
+
if egg:
|
|
182
|
+
pinned = bool(_HEX_REF.search(content))
|
|
183
|
+
deps.append(_dep(normalize(egg.group(1)), content, None, pinned, rel, number, "declared"))
|
|
184
|
+
continue
|
|
185
|
+
if content.startswith("-"):
|
|
186
|
+
continue
|
|
187
|
+
content = content.split(" --", 1)[0].strip()
|
|
188
|
+
if re.match(r"^[a-z+]+://", content):
|
|
189
|
+
egg = _EGG.search(content)
|
|
190
|
+
if egg:
|
|
191
|
+
pinned = bool(_HEX_REF.search(content))
|
|
192
|
+
deps.append(_dep(normalize(egg.group(1)), content, None, pinned, rel, number, "declared"))
|
|
193
|
+
continue
|
|
194
|
+
parsed = parse_requirement(content)
|
|
195
|
+
if parsed:
|
|
196
|
+
name, spec, version, pinned = parsed
|
|
197
|
+
deps.append(_dep(name, spec, version, pinned, rel, number, "declared"))
|
|
198
|
+
return deps, includes, comments
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _find_line(lines: list[str], *needles: str) -> int | None:
|
|
202
|
+
for i, text in enumerate(lines, start=1):
|
|
203
|
+
if all(n in text for n in needles):
|
|
204
|
+
return i
|
|
205
|
+
return None
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _from_pep508_list(items: Iterable[Any], rel: str, lines: list[str]) -> list[Dependency]:
|
|
209
|
+
out = []
|
|
210
|
+
for item in items:
|
|
211
|
+
if not isinstance(item, str):
|
|
212
|
+
continue
|
|
213
|
+
parsed = parse_requirement(item)
|
|
214
|
+
if parsed:
|
|
215
|
+
name, spec, version, pinned = parsed
|
|
216
|
+
out.append(_dep(name, spec, version, pinned, rel, _find_line(lines, item), "declared"))
|
|
217
|
+
return out
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _poetry_entry(name: str, value: Any) -> tuple[str, str | None, bool]:
|
|
221
|
+
spec = value.get("version", "") if isinstance(value, dict) else str(value)
|
|
222
|
+
if isinstance(value, dict) and "git" in value:
|
|
223
|
+
rev = str(value.get("rev", ""))
|
|
224
|
+
return f"git {value['git']}", None, bool(re.fullmatch(r"[0-9a-f]{7,40}", rev))
|
|
225
|
+
spec = str(spec).strip()
|
|
226
|
+
if re.fullmatch(r"[0-9][A-Za-z0-9.+!_-]*", spec):
|
|
227
|
+
return spec, spec, True
|
|
228
|
+
version, pinned = _spec_info(spec)
|
|
229
|
+
return spec, version, pinned
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def parse_pyproject(text: str, rel: str) -> list[Dependency]:
|
|
233
|
+
data = tomllib.loads(text)
|
|
234
|
+
lines = text.splitlines()
|
|
235
|
+
deps: list[Dependency] = []
|
|
236
|
+
project = data.get("project", {})
|
|
237
|
+
deps += _from_pep508_list(project.get("dependencies", []), rel, lines)
|
|
238
|
+
for group in project.get("optional-dependencies", {}).values():
|
|
239
|
+
deps += _from_pep508_list(group, rel, lines)
|
|
240
|
+
for group in data.get("dependency-groups", {}).values():
|
|
241
|
+
deps += _from_pep508_list(group, rel, lines)
|
|
242
|
+
poetry = data.get("tool", {}).get("poetry", {})
|
|
243
|
+
sections = [poetry.get("dependencies", {}), poetry.get("dev-dependencies", {})]
|
|
244
|
+
sections += [g.get("dependencies", {}) for g in poetry.get("group", {}).values() if isinstance(g, dict)]
|
|
245
|
+
for section in sections:
|
|
246
|
+
for name, value in section.items():
|
|
247
|
+
if name.lower() == "python":
|
|
248
|
+
continue
|
|
249
|
+
spec, version, pinned = _poetry_entry(name, value)
|
|
250
|
+
deps.append(_dep(normalize(name), spec, version, pinned, rel, _find_line(lines, name), "declared"))
|
|
251
|
+
return deps
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def parse_pipfile(text: str, rel: str) -> list[Dependency]:
|
|
255
|
+
data = tomllib.loads(text)
|
|
256
|
+
lines = text.splitlines()
|
|
257
|
+
deps: list[Dependency] = []
|
|
258
|
+
for section in ("packages", "dev-packages"):
|
|
259
|
+
for name, value in data.get(section, {}).items():
|
|
260
|
+
spec = value.get("version", "*") if isinstance(value, dict) else str(value)
|
|
261
|
+
version, pinned = _spec_info(spec)
|
|
262
|
+
deps.append(_dep(normalize(name), spec, version, pinned, rel, _find_line(lines, name), "declared"))
|
|
263
|
+
return deps
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def parse_lockfile(text: str, rel: str) -> list[Dependency]:
|
|
267
|
+
name = rel.rsplit("/", 1)[-1]
|
|
268
|
+
deps: list[Dependency] = []
|
|
269
|
+
if name == "Pipfile.lock":
|
|
270
|
+
data = json.loads(text)
|
|
271
|
+
for section in ("default", "develop"):
|
|
272
|
+
for pkg, info in data.get(section, {}).items():
|
|
273
|
+
version, pinned = _spec_info(str(info.get("version", ""))) if isinstance(info, dict) else (None, False)
|
|
274
|
+
deps.append(_dep(normalize(pkg), str(info.get("version", "")), version, pinned, rel, None, "locked"))
|
|
275
|
+
return deps
|
|
276
|
+
data = tomllib.loads(text)
|
|
277
|
+
for pkg in data.get("package", []):
|
|
278
|
+
if not isinstance(pkg, dict) or "name" not in pkg or "version" not in pkg:
|
|
279
|
+
continue
|
|
280
|
+
source = pkg.get("source", {})
|
|
281
|
+
if isinstance(source, dict) and ("editable" in source or "virtual" in source):
|
|
282
|
+
continue
|
|
283
|
+
version = str(pkg["version"])
|
|
284
|
+
deps.append(_dep(normalize(str(pkg["name"])), f"=={version}", version, True, rel, None, "locked"))
|
|
285
|
+
return deps
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
_SUPPRESS = re.compile(r"modelbom:\s*ignore(?:\[([A-Za-z0-9_,\s]+)\])?", re.IGNORECASE)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _suppressed(comment: str | None, rule_id: str) -> bool:
|
|
292
|
+
if not comment:
|
|
293
|
+
return False
|
|
294
|
+
m = _SUPPRESS.search(comment)
|
|
295
|
+
if not m:
|
|
296
|
+
return False
|
|
297
|
+
return m.group(1) is None or rule_id in {x.strip().upper() for x in m.group(1).split(",")}
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def collect_dependencies(root: Path, manifests: Iterable[str]) -> tuple[list[Dependency], list[Finding]]:
|
|
301
|
+
"""Parse all manifests (following requirement includes) and compute MB301 findings."""
|
|
302
|
+
queue = list(manifests)
|
|
303
|
+
seen: set[str] = set()
|
|
304
|
+
deps: list[Dependency] = []
|
|
305
|
+
comments: dict[tuple[str, int], str] = {}
|
|
306
|
+
errors: list[Finding] = []
|
|
307
|
+
while queue:
|
|
308
|
+
rel = queue.pop(0)
|
|
309
|
+
if rel in seen:
|
|
310
|
+
continue
|
|
311
|
+
seen.add(rel)
|
|
312
|
+
path = root / rel
|
|
313
|
+
if not path.is_file():
|
|
314
|
+
continue
|
|
315
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
316
|
+
name = rel.rsplit("/", 1)[-1]
|
|
317
|
+
try:
|
|
318
|
+
if name in LOCK_FILES:
|
|
319
|
+
deps += parse_lockfile(text, rel)
|
|
320
|
+
elif name == "pyproject.toml":
|
|
321
|
+
deps += parse_pyproject(text, rel)
|
|
322
|
+
for i, line in enumerate(text.splitlines(), start=1):
|
|
323
|
+
if "#" in line:
|
|
324
|
+
comments[(rel, i)] = line.split("#", 1)[1]
|
|
325
|
+
elif name == "Pipfile":
|
|
326
|
+
deps += parse_pipfile(text, rel)
|
|
327
|
+
else:
|
|
328
|
+
found, includes, cmts = parse_requirements_text(text, rel)
|
|
329
|
+
deps += found
|
|
330
|
+
comments.update({(rel, n): c for n, c in cmts.items()})
|
|
331
|
+
base = Path(rel).parent
|
|
332
|
+
for inc in includes:
|
|
333
|
+
inc_rel = (base / inc).as_posix()
|
|
334
|
+
if (root / inc_rel).resolve().is_relative_to(root.resolve()):
|
|
335
|
+
queue.append(inc_rel)
|
|
336
|
+
except (tomllib.TOMLDecodeError, json.JSONDecodeError, AttributeError, TypeError) as exc:
|
|
337
|
+
errors.append(Finding("MB100", Severity.INFO, rel, f"could not parse manifest: {exc}"))
|
|
338
|
+
pinned_names = {d.name for d in deps if d.pinned}
|
|
339
|
+
findings: list[Finding] = list(errors)
|
|
340
|
+
reported: set[tuple[str, str]] = set()
|
|
341
|
+
for d in deps:
|
|
342
|
+
if d.kind != "declared" or not d.ml_relevant or d.pinned or d.name in pinned_names:
|
|
343
|
+
continue
|
|
344
|
+
key = (d.source, d.name)
|
|
345
|
+
if key in reported:
|
|
346
|
+
continue
|
|
347
|
+
reported.add(key)
|
|
348
|
+
spec = d.specifier or "any version"
|
|
349
|
+
# Version ranges in pyproject.toml are normal for libraries; only applications need
|
|
350
|
+
# exact pins, which belong in a lock file. Report those as informational.
|
|
351
|
+
is_pyproject = d.source.rsplit("/", 1)[-1] == "pyproject.toml"
|
|
352
|
+
message = f"{d.name} declared as '{spec}' with no exact pin or lock file entry"
|
|
353
|
+
if is_pyproject:
|
|
354
|
+
message += " (fine for a library; applications should commit a lock file)"
|
|
355
|
+
finding = Finding(
|
|
356
|
+
"MB301",
|
|
357
|
+
Severity.INFO if is_pyproject else Severity.LOW,
|
|
358
|
+
d.source,
|
|
359
|
+
message,
|
|
360
|
+
line=d.line,
|
|
361
|
+
snippet=f"{d.name} {d.specifier}".strip(),
|
|
362
|
+
details={"package": d.name, "purl": d.purl},
|
|
363
|
+
)
|
|
364
|
+
finding.suppressed = _suppressed(comments.get((d.source, d.line or -1)), "MB301")
|
|
365
|
+
findings.append(finding)
|
|
366
|
+
return deps, findings
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
# --- OSV -------------------------------------------------------------------------------------
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _http_json(url: str, payload: Any = None, timeout: float = 20.0) -> Any:
|
|
373
|
+
data = json.dumps(payload).encode() if payload is not None else None
|
|
374
|
+
req = urllib.request.Request(
|
|
375
|
+
url,
|
|
376
|
+
data=data,
|
|
377
|
+
method="POST" if data is not None else "GET",
|
|
378
|
+
headers={"Content-Type": "application/json", "User-Agent": f"modelbom/{__version__}"},
|
|
379
|
+
)
|
|
380
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
381
|
+
return json.loads(resp.read().decode("utf-8"))
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
_OSV_SEVERITY = {
|
|
385
|
+
"CRITICAL": Severity.CRITICAL,
|
|
386
|
+
"HIGH": Severity.HIGH,
|
|
387
|
+
"MODERATE": Severity.MEDIUM,
|
|
388
|
+
"MEDIUM": Severity.MEDIUM,
|
|
389
|
+
"LOW": Severity.LOW,
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _fixed_versions(vuln: dict[str, Any], package: str) -> list[str]:
|
|
394
|
+
out: list[str] = []
|
|
395
|
+
for affected in vuln.get("affected", []):
|
|
396
|
+
pkg = affected.get("package", {})
|
|
397
|
+
if normalize(str(pkg.get("name", ""))) != package:
|
|
398
|
+
continue
|
|
399
|
+
for rng in affected.get("ranges", []):
|
|
400
|
+
for event in rng.get("events", []):
|
|
401
|
+
if "fixed" in event:
|
|
402
|
+
out.append(str(event["fixed"]))
|
|
403
|
+
return sorted(set(out))
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def osv_findings(deps: list[Dependency], http_json: HttpJson | None = None, max_details: int = 100) -> list[Finding]:
|
|
407
|
+
"""Query OSV.dev for every exactly pinned dependency and return MB302/MB303 findings."""
|
|
408
|
+
call = http_json or (lambda url, payload: _http_json(url, payload))
|
|
409
|
+
pinned: dict[tuple[str, str], Dependency] = {}
|
|
410
|
+
for d in deps:
|
|
411
|
+
if d.version and (d.name, d.version) not in pinned:
|
|
412
|
+
pinned[(d.name, d.version)] = d
|
|
413
|
+
if not pinned:
|
|
414
|
+
return []
|
|
415
|
+
keys = list(pinned)[:1000]
|
|
416
|
+
queries = [{"package": {"name": n, "ecosystem": "PyPI"}, "version": v} for n, v in keys]
|
|
417
|
+
try:
|
|
418
|
+
batch = call(OSV_BATCH_URL, {"queries": queries})
|
|
419
|
+
results = batch.get("results", [])
|
|
420
|
+
findings: list[Finding] = []
|
|
421
|
+
details_cache: dict[str, dict[str, Any]] = {}
|
|
422
|
+
for (name, version), result in zip(keys, results, strict=False):
|
|
423
|
+
for vuln_ref in (result or {}).get("vulns", []) or []:
|
|
424
|
+
vid = str(vuln_ref.get("id"))
|
|
425
|
+
if vid not in details_cache and len(details_cache) < max_details:
|
|
426
|
+
details_cache[vid] = call(OSV_VULN_URL.format(id=vid), None) or {}
|
|
427
|
+
vuln = details_cache.get(vid, {})
|
|
428
|
+
sev_text = str(vuln.get("database_specific", {}).get("severity", "")).upper()
|
|
429
|
+
sev = _OSV_SEVERITY.get(sev_text, Severity.HIGH)
|
|
430
|
+
aliases = [a for a in vuln.get("aliases", []) if str(a).startswith("CVE-")]
|
|
431
|
+
summary = str(vuln.get("summary", "")).strip()
|
|
432
|
+
fixed = _fixed_versions(vuln, name)
|
|
433
|
+
dep = pinned[(name, version)]
|
|
434
|
+
label = vid + (f" ({', '.join(aliases)})" if aliases else "")
|
|
435
|
+
msg = f"{name} {version} is affected by {label}"
|
|
436
|
+
if summary:
|
|
437
|
+
msg += f": {summary}"
|
|
438
|
+
if fixed:
|
|
439
|
+
msg += f" (fixed in {', '.join(fixed[:3])})"
|
|
440
|
+
findings.append(
|
|
441
|
+
Finding(
|
|
442
|
+
"MB302",
|
|
443
|
+
sev,
|
|
444
|
+
dep.source,
|
|
445
|
+
msg,
|
|
446
|
+
line=dep.line,
|
|
447
|
+
snippet=f"{name}=={version} {vid}",
|
|
448
|
+
details={
|
|
449
|
+
"package": name,
|
|
450
|
+
"version": version,
|
|
451
|
+
"purl": dep.purl,
|
|
452
|
+
"vuln_id": vid,
|
|
453
|
+
"aliases": aliases,
|
|
454
|
+
"summary": summary,
|
|
455
|
+
"fixed": fixed,
|
|
456
|
+
},
|
|
457
|
+
)
|
|
458
|
+
)
|
|
459
|
+
return findings
|
|
460
|
+
except (OSError, ValueError, AttributeError) as exc: # URLError and timeouts are OSErrors
|
|
461
|
+
return [Finding("MB303", Severity.INFO, ".", f"OSV.dev lookup failed: {exc}")]
|
modelbom/discovery.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""File discovery with default excludes, ``--exclude`` globs and ``.modelbomignore``.
|
|
2
|
+
|
|
3
|
+
``.modelbomignore`` format (one entry per line, ``#`` starts a comment)::
|
|
4
|
+
|
|
5
|
+
data/raw/ # exclude a directory everywhere it appears
|
|
6
|
+
*.ckpt # exclude by basename
|
|
7
|
+
models/legacy/*.pkl # exclude by path glob (relative to the scan root)
|
|
8
|
+
MB202:models/*.pkl # keep scanning these files but suppress rule MB202 for them
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import fnmatch
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
from collections.abc import Iterable, Iterator
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
DEFAULT_EXCLUDED_DIRS = frozenset(
|
|
21
|
+
{
|
|
22
|
+
".git",
|
|
23
|
+
".hg",
|
|
24
|
+
".svn",
|
|
25
|
+
".venv",
|
|
26
|
+
"venv",
|
|
27
|
+
"env",
|
|
28
|
+
"node_modules",
|
|
29
|
+
"__pycache__",
|
|
30
|
+
"site-packages",
|
|
31
|
+
"dist",
|
|
32
|
+
"build",
|
|
33
|
+
".tox",
|
|
34
|
+
".nox",
|
|
35
|
+
".mypy_cache",
|
|
36
|
+
".pytest_cache",
|
|
37
|
+
".ruff_cache",
|
|
38
|
+
".ipynb_checkpoints",
|
|
39
|
+
}
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
IGNORE_FILE = ".modelbomignore"
|
|
43
|
+
_RULE_SCOPED = re.compile(r"^(MB\d{3}):(.+)$")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def match_glob(pattern: str, rel: str) -> bool:
|
|
47
|
+
"""Match a gitignore-style pattern against a relative POSIX path."""
|
|
48
|
+
pattern = pattern.strip()
|
|
49
|
+
if not pattern:
|
|
50
|
+
return False
|
|
51
|
+
parts = rel.split("/")
|
|
52
|
+
if pattern.endswith("/"):
|
|
53
|
+
pat = pattern.rstrip("/").lstrip("/")
|
|
54
|
+
for i in range(1, len(parts) + 1):
|
|
55
|
+
prefix = "/".join(parts[:i])
|
|
56
|
+
if fnmatch.fnmatchcase(prefix, pat):
|
|
57
|
+
return True
|
|
58
|
+
if "/" not in pat and fnmatch.fnmatchcase(parts[i - 1], pat):
|
|
59
|
+
return True
|
|
60
|
+
return False
|
|
61
|
+
if "/" not in pattern:
|
|
62
|
+
return any(fnmatch.fnmatchcase(part, pattern) for part in parts)
|
|
63
|
+
pat = pattern.lstrip("/")
|
|
64
|
+
if fnmatch.fnmatchcase(rel, pat):
|
|
65
|
+
return True
|
|
66
|
+
return rel.startswith(pat.rstrip("/") + "/")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass
|
|
70
|
+
class IgnoreSpec:
|
|
71
|
+
path_globs: list[str] = field(default_factory=list)
|
|
72
|
+
rule_globs: list[tuple[str, str]] = field(default_factory=list)
|
|
73
|
+
|
|
74
|
+
def excludes(self, rel: str) -> bool:
|
|
75
|
+
return any(match_glob(p, rel) for p in self.path_globs)
|
|
76
|
+
|
|
77
|
+
def suppresses(self, rule_id: str, rel: str) -> bool:
|
|
78
|
+
return any(rid == rule_id and match_glob(p, rel) for rid, p in self.rule_globs)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def parse_ignore_lines(lines: Iterable[str]) -> IgnoreSpec:
|
|
82
|
+
spec = IgnoreSpec()
|
|
83
|
+
for raw in lines:
|
|
84
|
+
line = raw.split("#", 1)[0].strip()
|
|
85
|
+
if not line:
|
|
86
|
+
continue
|
|
87
|
+
m = _RULE_SCOPED.match(line)
|
|
88
|
+
if m:
|
|
89
|
+
spec.rule_globs.append((m.group(1), m.group(2).strip()))
|
|
90
|
+
else:
|
|
91
|
+
spec.path_globs.append(line)
|
|
92
|
+
return spec
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def load_ignore(root: Path, extra_excludes: Iterable[str] = ()) -> IgnoreSpec:
|
|
96
|
+
lines: list[str] = []
|
|
97
|
+
ignore_path = root / IGNORE_FILE
|
|
98
|
+
if ignore_path.is_file():
|
|
99
|
+
lines.extend(ignore_path.read_text(encoding="utf-8", errors="replace").splitlines())
|
|
100
|
+
spec = parse_ignore_lines(lines)
|
|
101
|
+
spec.path_globs.extend(p for p in extra_excludes if p.strip())
|
|
102
|
+
return spec
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def iter_files(root: Path, ignore: IgnoreSpec) -> Iterator[str]:
|
|
106
|
+
"""Yield relative POSIX paths of regular files under ``root`` (symlinks are skipped)."""
|
|
107
|
+
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
|
|
108
|
+
rel_dir = Path(dirpath).relative_to(root).as_posix()
|
|
109
|
+
rel_dir = "" if rel_dir == "." else rel_dir
|
|
110
|
+
kept = []
|
|
111
|
+
for d in sorted(dirnames):
|
|
112
|
+
rel = f"{rel_dir}/{d}" if rel_dir else d
|
|
113
|
+
if d in DEFAULT_EXCLUDED_DIRS or ignore.excludes(rel + "/") or ignore.excludes(rel):
|
|
114
|
+
continue
|
|
115
|
+
if os.path.islink(os.path.join(dirpath, d)):
|
|
116
|
+
continue
|
|
117
|
+
kept.append(d)
|
|
118
|
+
dirnames[:] = kept
|
|
119
|
+
for name in sorted(filenames):
|
|
120
|
+
full = os.path.join(dirpath, name)
|
|
121
|
+
if os.path.islink(full) or not os.path.isfile(full):
|
|
122
|
+
continue
|
|
123
|
+
rel = f"{rel_dir}/{name}" if rel_dir else name
|
|
124
|
+
if ignore.excludes(rel):
|
|
125
|
+
continue
|
|
126
|
+
yield rel
|