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/artifacts.py ADDED
@@ -0,0 +1,696 @@
1
+ """Model, dataset and model-configuration artifact inspection.
2
+
3
+ Every format is inspected statically: headers are parsed with ``struct``/``json``, archives are
4
+ read with ``zipfile`` and pickle payloads go through :mod:`modelbom.pickle_scan`. No artifact is
5
+ ever loaded with the library that would normally consume it.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import bz2
12
+ import hashlib
13
+ import json
14
+ import lzma
15
+ import re
16
+ import struct
17
+ import zipfile
18
+ import zlib
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+ from typing import Any, BinaryIO
22
+
23
+ from .models import Artifact, Finding, Severity
24
+ from .pickle_scan import PickleReport, analyze_pickle, looks_like_pickle
25
+
26
+ DEFAULT_MAX_BYTES = 64 * 1024 * 1024
27
+
28
+ PICKLE_EXTS = frozenset({".pkl", ".pickle", ".dill"})
29
+ TORCH_EXTS = frozenset({".pt", ".pth", ".bin", ".ckpt"})
30
+ OTHER_MODEL_EXTS = {".onnx": "onnx", ".pb": "tensorflow-pb", ".tflite": "tflite", ".mlmodel": "coreml"}
31
+ DATA_EXTS = {
32
+ ".parquet": "parquet",
33
+ ".arrow": "arrow",
34
+ ".feather": "feather",
35
+ ".csv": "csv",
36
+ ".tsv": "tsv",
37
+ ".jsonl": "jsonl",
38
+ ".ndjson": "jsonl",
39
+ ".tfrecord": "tfrecord",
40
+ }
41
+ MODEL_EXTS = frozenset(
42
+ PICKLE_EXTS
43
+ | TORCH_EXTS
44
+ | set(OTHER_MODEL_EXTS)
45
+ | {".joblib", ".npy", ".npz", ".keras", ".h5", ".hdf5", ".safetensors", ".gguf"}
46
+ )
47
+ ARTIFACT_EXTS = frozenset(MODEL_EXTS | set(DATA_EXTS))
48
+ CONFIG_NAMES = frozenset({"config.json", "tokenizer_config.json", "chat_template.jinja"})
49
+
50
+ _HDF5_SIG = b"\x89HDF\r\n\x1a\n"
51
+ _ZIP_SIG = b"PK\x03\x04"
52
+ _NPY_MAGIC = b"\x93NUMPY"
53
+ _LAMBDA_RE = re.compile(rb'"class_name"\s*:\s*"(?:Lambda|__lambda__)"')
54
+ _TEMPLATE_RISK = re.compile(
55
+ r"__[A-Za-z]+__|\|\s*attr\s*\(|\\x5f|\\u005f|\bpopen\b|\bsubprocess\b|\bos\.system\b"
56
+ )
57
+
58
+
59
+ @dataclass
60
+ class ArtifactOptions:
61
+ hash_files: bool = True
62
+ max_bytes: int = DEFAULT_MAX_BYTES
63
+
64
+
65
+ @dataclass
66
+ class _Inspection:
67
+ format: str
68
+ kind: str
69
+ serialization: str
70
+ details: dict[str, Any] = field(default_factory=dict)
71
+ findings: list[Finding] = field(default_factory=list)
72
+
73
+
74
+ def is_candidate(rel: str) -> bool:
75
+ name = rel.rsplit("/", 1)[-1]
76
+ return Path(name).suffix.lower() in ARTIFACT_EXTS or name in CONFIG_NAMES
77
+
78
+
79
+ # --- small helpers ---------------------------------------------------------------------------
80
+
81
+
82
+ def sha256_file(path: Path) -> str:
83
+ h = hashlib.sha256()
84
+ with path.open("rb") as fh:
85
+ for chunk in iter(lambda: fh.read(1024 * 1024), b""):
86
+ h.update(chunk)
87
+ return h.hexdigest()
88
+
89
+
90
+ def _read_capped(fh: BinaryIO, cap: int) -> tuple[bytes, bool]:
91
+ data = fh.read(cap + 1)
92
+ return data[:cap], len(data) > cap
93
+
94
+
95
+ def _compression(head: bytes) -> str | None:
96
+ if head[:2] == b"\x1f\x8b":
97
+ return "gzip"
98
+ if head[:3] == b"BZh":
99
+ return "bz2"
100
+ if head[:6] == b"\xfd7zXZ\x00" or head[:3] == b"]\x00\x00":
101
+ return "xz"
102
+ if head[:4] == b"\x04\x22\x4d\x18":
103
+ return "lz4"
104
+ if len(head) >= 2 and head[0] == 0x78 and (head[0] * 256 + head[1]) % 31 == 0:
105
+ return "zlib"
106
+ return None
107
+
108
+
109
+ def _decompress(data: bytes, kind: str, cap: int) -> tuple[bytes, bool]:
110
+ if kind in ("zlib", "gzip"):
111
+ wbits = zlib.MAX_WBITS if kind == "zlib" else 16 + zlib.MAX_WBITS
112
+ dz = zlib.decompressobj(wbits)
113
+ out = dz.decompress(data, cap)
114
+ return out, bool(dz.unconsumed_tail)
115
+ if kind == "bz2":
116
+ db = bz2.BZ2Decompressor()
117
+ out = db.decompress(data, max_length=cap)
118
+ return out, not db.eof and not db.needs_input
119
+ if kind == "xz":
120
+ dl = lzma.LZMADecompressor()
121
+ out = dl.decompress(data, max_length=cap)
122
+ return out, not dl.eof and not dl.needs_input
123
+ raise ValueError(f"unsupported compression: {kind}")
124
+
125
+
126
+ def _finding(rule: str, sev: Severity, rel: str, msg: str, **details: Any) -> Finding:
127
+ return Finding(rule, sev, rel, msg, details={k: v for k, v in details.items() if v is not None})
128
+
129
+
130
+ def pickle_findings(report: PickleReport, rel: str, member: str | None = None) -> list[Finding]:
131
+ """Translate a :class:`PickleReport` into findings for one artifact (or archive member)."""
132
+ where = f" in {member}" if member else ""
133
+ out: list[Finding] = []
134
+ if report.dangerous:
135
+ names = sorted({i.qualname for i in report.dangerous})
136
+ out.append(
137
+ _finding(
138
+ "MB201",
139
+ Severity.CRITICAL,
140
+ rel,
141
+ f"pickle{where} imports dangerous callables: {', '.join(names)}",
142
+ member=member,
143
+ imports=names,
144
+ )
145
+ )
146
+ if report.unknown:
147
+ names = sorted({i.qualname for i in report.unknown})
148
+ out.append(
149
+ _finding(
150
+ "MB202",
151
+ Severity.MEDIUM,
152
+ rel,
153
+ f"pickle{where} imports non-allowlisted callables: {', '.join(names)}",
154
+ member=member,
155
+ imports=names,
156
+ )
157
+ )
158
+ if report.pickles == 0 and report.error:
159
+ out.append(
160
+ _finding(
161
+ "MB205",
162
+ Severity.LOW,
163
+ rel,
164
+ f"could not parse pickle{where}: {report.error}",
165
+ member=member,
166
+ )
167
+ )
168
+ elif report.truncated:
169
+ out.append(
170
+ _finding(
171
+ "MB205",
172
+ Severity.LOW,
173
+ rel,
174
+ f"pickle{where} larger than the analysis limit; analyzed the first "
175
+ f"{report.bytes_analyzed} bytes",
176
+ member=member,
177
+ )
178
+ )
179
+ return out
180
+
181
+
182
+ def _with_pickle_format_note(insp: _Inspection, rel: str) -> _Inspection:
183
+ """Add MB203 when a pickle-based artifact has no stronger pickle finding."""
184
+ strong = {"MB201", "MB202"}
185
+ if not any(f.rule_id in strong for f in insp.findings) and insp.details.get("pickles", 0):
186
+ insp.findings.append(
187
+ _finding(
188
+ "MB203",
189
+ Severity.LOW,
190
+ rel,
191
+ f"{insp.format} artifact uses pickle serialization; prefer safetensors",
192
+ )
193
+ )
194
+ return insp
195
+
196
+
197
+ def _merge_pickle_details(target: dict[str, Any], report: PickleReport) -> None:
198
+ det = report.to_details()
199
+ target["pickles"] = int(target.get("pickles", 0)) + int(det["pickles"]) # type: ignore[arg-type]
200
+ for key in ("imports", "dangerous_imports", "unknown_imports"):
201
+ merged = set(target.get(key, [])) | set(det[key]) # type: ignore[arg-type]
202
+ target[key] = sorted(merged)
203
+ if det["protocol"] is not None and "protocol" not in target:
204
+ target["protocol"] = det["protocol"]
205
+
206
+
207
+ # --- format handlers -------------------------------------------------------------------------
208
+
209
+
210
+ def _inspect_pickle_bytes(
211
+ data: bytes, truncated: bool, rel: str, fmt: str, opts: ArtifactOptions
212
+ ) -> _Inspection:
213
+ insp = _Inspection(fmt, "model", "pickle")
214
+ comp = None if looks_like_pickle(data[:2]) else _compression(data[:8])
215
+ if comp == "lz4":
216
+ insp.details["compression"] = comp
217
+ insp.findings.append(
218
+ _finding("MB205", Severity.LOW, rel, "lz4-compressed payload; not inspected")
219
+ )
220
+ return insp
221
+ if comp is not None:
222
+ insp.details["compression"] = comp
223
+ try:
224
+ data, more = _decompress(data, comp, opts.max_bytes)
225
+ except (OSError, ValueError, EOFError, lzma.LZMAError, zlib.error) as exc:
226
+ insp.findings.append(
227
+ _finding("MB205", Severity.LOW, rel, f"could not decompress {comp} payload: {exc}")
228
+ )
229
+ return insp
230
+ truncated = truncated or more
231
+ report = analyze_pickle(data, truncated=truncated)
232
+ _merge_pickle_details(insp.details, report)
233
+ insp.findings.extend(pickle_findings(report, rel))
234
+ return _with_pickle_format_note(insp, rel)
235
+
236
+
237
+ def _inspect_zip_pickles(path: Path, rel: str, fmt_hint: str, opts: ArtifactOptions) -> _Inspection:
238
+ with zipfile.ZipFile(path) as zf:
239
+ names = zf.namelist()
240
+ pkl_members = [n for n in names if n.endswith(".pkl")]
241
+ torchscript = any("/code/" in f"/{n}" for n in names) or any(
242
+ n.endswith("constants.pkl") for n in names
243
+ )
244
+ fmt = "torchscript" if torchscript else fmt_hint
245
+ insp = _Inspection(fmt, "model", "pickle", {"members": len(names)})
246
+ budget = opts.max_bytes
247
+ for member in pkl_members:
248
+ if budget <= 0:
249
+ insp.findings.append(
250
+ _finding("MB205", Severity.LOW, rel, "analysis limit reached; some members skipped")
251
+ )
252
+ break
253
+ with zf.open(member) as fh:
254
+ data, truncated = _read_capped(fh, budget)
255
+ budget -= len(data)
256
+ report = analyze_pickle(data, truncated=truncated)
257
+ _merge_pickle_details(insp.details, report)
258
+ insp.findings.extend(pickle_findings(report, rel, member=member))
259
+ return _with_pickle_format_note(insp, rel)
260
+
261
+
262
+ def _npy_header(data: bytes) -> tuple[dict[str, Any], int] | None:
263
+ if not data.startswith(_NPY_MAGIC) or len(data) < 10:
264
+ return None
265
+ major = data[6]
266
+ if major == 1:
267
+ hlen = struct.unpack("<H", data[8:10])[0]
268
+ start = 10
269
+ else:
270
+ if len(data) < 12:
271
+ return None
272
+ hlen = struct.unpack("<I", data[8:12])[0]
273
+ start = 12
274
+ raw = data[start : start + hlen]
275
+ if len(raw) < hlen:
276
+ return None
277
+ try:
278
+ header = ast.literal_eval(raw.decode("utf-8" if major >= 3 else "latin-1"))
279
+ except (ValueError, SyntaxError, UnicodeDecodeError):
280
+ return None
281
+ if not isinstance(header, dict):
282
+ return None
283
+ return header, start + hlen
284
+
285
+
286
+ def _has_object_dtype(descr: object) -> bool:
287
+ if isinstance(descr, str):
288
+ return descr.lstrip("|<>=").startswith("O")
289
+ if isinstance(descr, list | tuple):
290
+ return any(_has_object_dtype(x) for x in descr)
291
+ return False
292
+
293
+
294
+ def _inspect_npy_bytes(data: bytes, truncated: bool, rel: str, member: str | None) -> _Inspection:
295
+ insp = _Inspection("numpy", "model", "safe")
296
+ parsed = _npy_header(data)
297
+ where = f" in {member}" if member else ""
298
+ if parsed is None:
299
+ insp.findings.append(_finding("MB205", Severity.LOW, rel, f"invalid .npy header{where}"))
300
+ return insp
301
+ header, offset = parsed
302
+ insp.details["dtype"] = str(header.get("descr"))
303
+ insp.details["shape"] = list(header.get("shape", ()))
304
+ if _has_object_dtype(header.get("descr")):
305
+ insp.serialization = "pickle"
306
+ report = analyze_pickle(data[offset:], truncated=truncated)
307
+ _merge_pickle_details(insp.details, report)
308
+ insp.findings.extend(pickle_findings(report, rel, member=member))
309
+ _with_pickle_format_note(insp, rel)
310
+ return insp
311
+
312
+
313
+ def _inspect_npz(path: Path, rel: str, opts: ArtifactOptions) -> _Inspection:
314
+ insp = _Inspection("numpy-npz", "model", "safe")
315
+ with zipfile.ZipFile(path) as zf:
316
+ members = [n for n in zf.namelist() if n.endswith(".npy")]
317
+ insp.details["arrays"] = len(members)
318
+ for member in members:
319
+ with zf.open(member) as fh:
320
+ data, truncated = _read_capped(fh, opts.max_bytes)
321
+ sub = _inspect_npy_bytes(data, truncated, rel, member)
322
+ if sub.serialization == "pickle":
323
+ insp.serialization = "pickle"
324
+ insp.details["pickles"] = int(insp.details.get("pickles", 0)) + int(
325
+ sub.details.get("pickles", 0)
326
+ )
327
+ for key in ("imports", "dangerous_imports", "unknown_imports"):
328
+ merged = set(insp.details.get(key, [])) | set(sub.details.get(key, []))
329
+ insp.details[key] = sorted(merged)
330
+ insp.findings.extend(f for f in sub.findings if f.rule_id != "MB203")
331
+ if insp.serialization == "pickle":
332
+ _with_pickle_format_note(insp, rel)
333
+ return insp
334
+
335
+
336
+ def _walk_layers(obj: object, out: list[str]) -> None:
337
+ if isinstance(obj, dict):
338
+ cls = obj.get("class_name")
339
+ if cls in ("Lambda", "__lambda__"):
340
+ name = obj.get("config", {}).get("name") if isinstance(obj.get("config"), dict) else None
341
+ out.append(str(name or cls))
342
+ for v in obj.values():
343
+ _walk_layers(v, out)
344
+ elif isinstance(obj, list):
345
+ for v in obj:
346
+ _walk_layers(v, out)
347
+
348
+
349
+ def _inspect_keras_zip(path: Path, rel: str, opts: ArtifactOptions) -> _Inspection:
350
+ insp = _Inspection("keras", "model", "safe")
351
+ with zipfile.ZipFile(path) as zf:
352
+ names = set(zf.namelist())
353
+ if "config.json" not in names:
354
+ insp.findings.append(_finding("MB205", Severity.LOW, rel, "keras archive has no config.json"))
355
+ return insp
356
+ with zf.open("config.json") as fh:
357
+ raw, truncated = _read_capped(fh, opts.max_bytes)
358
+ if "metadata.json" in names:
359
+ with zf.open("metadata.json") as fh:
360
+ try:
361
+ meta = json.loads(fh.read(1024 * 1024))
362
+ insp.details["keras_version"] = meta.get("keras_version")
363
+ except (json.JSONDecodeError, UnicodeDecodeError, AttributeError):
364
+ pass
365
+ try:
366
+ config = json.loads(raw)
367
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:
368
+ msg = "config.json truncated" if truncated else f"invalid config.json: {exc}"
369
+ insp.findings.append(_finding("MB205", Severity.LOW, rel, msg))
370
+ return insp
371
+ lambdas: list[str] = []
372
+ _walk_layers(config, lambdas)
373
+ if lambdas:
374
+ insp.serialization = "code"
375
+ insp.details["lambda_layers"] = lambdas
376
+ insp.findings.append(
377
+ _finding(
378
+ "MB204",
379
+ Severity.HIGH,
380
+ rel,
381
+ f"Keras model contains Lambda layer(s): {', '.join(lambdas)}",
382
+ layers=lambdas,
383
+ )
384
+ )
385
+ return insp
386
+
387
+
388
+ def _is_hdf5(head: bytes) -> bool:
389
+ return any(head[o : o + 8] == _HDF5_SIG for o in (0, 512, 1024, 2048))
390
+
391
+
392
+ def _inspect_h5(fh: BinaryIO, rel: str, opts: ArtifactOptions) -> _Inspection:
393
+ insp = _Inspection("keras-h5", "model", "safe")
394
+ fh.seek(0)
395
+ data, truncated = _read_capped(fh, opts.max_bytes)
396
+ hits = len(_LAMBDA_RE.findall(data))
397
+ if hits:
398
+ insp.serialization = "code"
399
+ insp.details["lambda_layers"] = hits
400
+ insp.findings.append(
401
+ _finding("MB204", Severity.HIGH, rel, f"HDF5 model config contains {hits} Lambda layer(s)")
402
+ )
403
+ elif truncated:
404
+ insp.findings.append(
405
+ _finding(
406
+ "MB205",
407
+ Severity.LOW,
408
+ rel,
409
+ f"HDF5 file larger than the analysis limit; searched the first {len(data)} bytes",
410
+ )
411
+ )
412
+ return insp
413
+
414
+
415
+ def _inspect_safetensors(fh: BinaryIO, size: int, rel: str) -> _Inspection:
416
+ insp = _Inspection("safetensors", "model", "safe")
417
+ fh.seek(0)
418
+ raw_len = fh.read(8)
419
+ if len(raw_len) < 8:
420
+ insp.findings.append(_finding("MB205", Severity.LOW, rel, "file too small for safetensors"))
421
+ return insp
422
+ n = struct.unpack("<Q", raw_len)[0]
423
+ if n > min(size - 8, 100 * 1024 * 1024):
424
+ insp.findings.append(_finding("MB205", Severity.LOW, rel, "invalid safetensors header length"))
425
+ return insp
426
+ try:
427
+ header = json.loads(fh.read(n))
428
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:
429
+ insp.findings.append(_finding("MB205", Severity.LOW, rel, f"invalid safetensors header: {exc}"))
430
+ return insp
431
+ if not isinstance(header, dict):
432
+ insp.findings.append(_finding("MB205", Severity.LOW, rel, "safetensors header is not an object"))
433
+ return insp
434
+ metadata = header.pop("__metadata__", None)
435
+ params = 0
436
+ dtypes: set[str] = set()
437
+ max_end = 0
438
+ for info in header.values():
439
+ if not isinstance(info, dict):
440
+ continue
441
+ dtypes.add(str(info.get("dtype")))
442
+ count = 1
443
+ for dim in info.get("shape", []):
444
+ count *= int(dim)
445
+ params += count
446
+ offsets = info.get("data_offsets") or [0, 0]
447
+ max_end = max(max_end, int(offsets[-1]))
448
+ insp.details.update({"tensors": len(header), "parameters": params, "dtypes": sorted(dtypes)})
449
+ if isinstance(metadata, dict):
450
+ insp.details["metadata"] = {str(k): str(v) for k, v in list(metadata.items())[:32]}
451
+ if 8 + n + max_end > size:
452
+ insp.findings.append(
453
+ _finding("MB205", Severity.LOW, rel, "safetensors data section is shorter than the header declares")
454
+ )
455
+ return insp
456
+
457
+
458
+ class _GGUFReader:
459
+ _SCALARS = {0: "<B", 1: "<b", 2: "<H", 3: "<h", 4: "<I", 5: "<i", 6: "<f", 7: "<?", 10: "<Q", 11: "<q", 12: "<d"}
460
+
461
+ def __init__(self, fh: BinaryIO, size: int, version: int) -> None:
462
+ self.fh = fh
463
+ self.size = size
464
+ self.len_fmt = "<I" if version == 1 else "<Q"
465
+
466
+ def _read(self, n: int) -> bytes:
467
+ data = self.fh.read(n)
468
+ if len(data) != n:
469
+ raise ValueError("unexpected end of GGUF header")
470
+ return data
471
+
472
+ def _unpack(self, fmt: str) -> Any:
473
+ return struct.unpack(fmt, self._read(struct.calcsize(fmt)))[0]
474
+
475
+ def string(self) -> str:
476
+ n = self._unpack(self.len_fmt)
477
+ if n > 64 * 1024 * 1024 or self.fh.tell() + n > self.size:
478
+ raise ValueError("GGUF string length out of bounds")
479
+ return self._read(n).decode("utf-8", errors="replace")
480
+
481
+ def value(self, vtype: int, keep: bool) -> Any:
482
+ if vtype in self._SCALARS:
483
+ return self._unpack(self._SCALARS[vtype])
484
+ if vtype == 8:
485
+ return self.string() if keep else self._skip_string()
486
+ if vtype == 9:
487
+ etype = self._unpack("<I")
488
+ count = self._unpack(self.len_fmt)
489
+ if etype in self._SCALARS:
490
+ nbytes = struct.calcsize(self._SCALARS[etype]) * count
491
+ if self.fh.tell() + nbytes > self.size:
492
+ raise ValueError("GGUF array out of bounds")
493
+ self.fh.seek(nbytes, 1)
494
+ else:
495
+ for _ in range(count):
496
+ self.value(etype, keep=False)
497
+ return f"<array:{count}>"
498
+ raise ValueError(f"unknown GGUF value type {vtype}")
499
+
500
+ def _skip_string(self) -> None:
501
+ n = self._unpack(self.len_fmt)
502
+ if self.fh.tell() + n > self.size:
503
+ raise ValueError("GGUF string length out of bounds")
504
+ self.fh.seek(n, 1)
505
+ return None
506
+
507
+
508
+ def _template_risks(text: str) -> list[str]:
509
+ return sorted({m.group(0) for m in _TEMPLATE_RISK.finditer(text)})[:10]
510
+
511
+
512
+ def _template_finding(rel: str, text: str, where: str) -> Finding | None:
513
+ risks = _template_risks(text)
514
+ if not risks:
515
+ return None
516
+ return _finding(
517
+ "MB207",
518
+ Severity.HIGH,
519
+ rel,
520
+ f"chat template{where} references {', '.join(risks)}",
521
+ markers=risks,
522
+ )
523
+
524
+
525
+ def _inspect_gguf(fh: BinaryIO, size: int, rel: str) -> _Inspection:
526
+ insp = _Inspection("gguf", "model", "safe")
527
+ fh.seek(4)
528
+ try:
529
+ version = struct.unpack("<I", fh.read(4))[0]
530
+ reader = _GGUFReader(fh, size, version)
531
+ tensors = reader._unpack(reader.len_fmt)
532
+ kv_count = reader._unpack(reader.len_fmt)
533
+ insp.details.update({"version": version, "tensors": tensors, "metadata_keys": kv_count})
534
+ general: dict[str, Any] = {}
535
+ for _ in range(min(kv_count, 100_000)):
536
+ key = reader.string()
537
+ vtype = reader._unpack("<I")
538
+ keep = key.startswith("general.") or key.startswith("tokenizer.chat_template")
539
+ val = reader.value(vtype, keep)
540
+ if key.startswith("general.") and isinstance(val, str | int | float | bool):
541
+ general[key] = val
542
+ if key.startswith("tokenizer.chat_template") and isinstance(val, str):
543
+ f = _template_finding(rel, val, f" ({key})")
544
+ if f:
545
+ insp.serialization = "code"
546
+ insp.findings.append(f)
547
+ if general:
548
+ insp.details["general"] = dict(list(general.items())[:32])
549
+ except (ValueError, struct.error) as exc:
550
+ insp.findings.append(_finding("MB205", Severity.LOW, rel, f"could not parse GGUF header: {exc}"))
551
+ return insp
552
+
553
+
554
+ def _inspect_config(path: Path, rel: str, name: str) -> _Inspection | None:
555
+ if path.stat().st_size > 16 * 1024 * 1024:
556
+ return None
557
+ text = path.read_text(encoding="utf-8", errors="replace")
558
+ if name == "chat_template.jinja":
559
+ insp = _Inspection("chat-template", "config", "code")
560
+ f = _template_finding(rel, text, "")
561
+ if f:
562
+ insp.findings.append(f)
563
+ return insp
564
+ try:
565
+ data = json.loads(text)
566
+ except json.JSONDecodeError:
567
+ return None
568
+ if not isinstance(data, dict):
569
+ return None
570
+ if name == "tokenizer_config.json" and "chat_template" in data:
571
+ insp = _Inspection("hf-tokenizer-config", "config", "code")
572
+ tpl = data["chat_template"]
573
+ templates: list[tuple[str, str]] = []
574
+ if isinstance(tpl, str):
575
+ templates.append(("", tpl))
576
+ elif isinstance(tpl, list):
577
+ for entry in tpl:
578
+ if isinstance(entry, dict) and isinstance(entry.get("template"), str):
579
+ templates.append((f" ({entry.get('name', 'unnamed')})", entry["template"]))
580
+ for where, text_t in templates:
581
+ f = _template_finding(rel, text_t, where)
582
+ if f:
583
+ insp.findings.append(f)
584
+ return insp
585
+ if name == "config.json" and ("auto_map" in data or "architectures" in data or "model_type" in data):
586
+ insp = _Inspection("hf-config", "config", "safe")
587
+ insp.details["model_type"] = data.get("model_type")
588
+ insp.details["architectures"] = data.get("architectures")
589
+ if "auto_map" in data:
590
+ insp.serialization = "code"
591
+ auto_map = data["auto_map"]
592
+ modules = sorted({str(v) for v in auto_map.values()}) if isinstance(auto_map, dict) else []
593
+ insp.details["auto_map"] = modules
594
+ insp.findings.append(
595
+ _finding(
596
+ "MB208",
597
+ Severity.MEDIUM,
598
+ rel,
599
+ "config.json declares auto_map; loading requires custom code"
600
+ + (f" ({', '.join(modules[:5])})" if modules else ""),
601
+ modules=modules,
602
+ )
603
+ )
604
+ return insp
605
+ return None
606
+
607
+
608
+ # --- dispatcher ------------------------------------------------------------------------------
609
+
610
+
611
+ def _dispatch(path: Path, rel: str, ext: str, name: str, size: int, opts: ArtifactOptions) -> _Inspection | None:
612
+ if name in CONFIG_NAMES:
613
+ return _inspect_config(path, rel, name)
614
+ if ext in DATA_EXTS:
615
+ return _Inspection(DATA_EXTS[ext], "data", "safe")
616
+ if ext in OTHER_MODEL_EXTS:
617
+ return _Inspection(OTHER_MODEL_EXTS[ext], "model", "safe")
618
+ with path.open("rb") as fh:
619
+ head = fh.read(4096)
620
+ if ext == ".safetensors":
621
+ return _inspect_safetensors(fh, size, rel)
622
+ if ext == ".gguf":
623
+ if head[:4] != b"GGUF":
624
+ return _Inspection("gguf", "model", "unknown", findings=[
625
+ _finding("MB205", Severity.LOW, rel, "missing GGUF magic")
626
+ ])
627
+ return _inspect_gguf(fh, size, rel)
628
+ if ext in (".h5", ".hdf5") or (ext == ".keras" and _is_hdf5(head)):
629
+ if not _is_hdf5(head):
630
+ return _Inspection("keras-h5", "model", "unknown", findings=[
631
+ _finding("MB205", Severity.LOW, rel, "missing HDF5 signature")
632
+ ])
633
+ return _inspect_h5(fh, rel, opts)
634
+ if ext == ".npy":
635
+ fh.seek(0)
636
+ data, truncated = _read_capped(fh, opts.max_bytes)
637
+ return _inspect_npy_bytes(data, truncated, rel, None)
638
+ if head.startswith(_ZIP_SIG):
639
+ try:
640
+ if ext == ".keras":
641
+ return _inspect_keras_zip(path, rel, opts)
642
+ if ext == ".npz":
643
+ return _inspect_npz(path, rel, opts)
644
+ return _inspect_zip_pickles(path, rel, "pytorch-zip", opts)
645
+ except zipfile.BadZipFile as exc:
646
+ return _Inspection("zip", "model", "unknown", findings=[
647
+ _finding("MB205", Severity.LOW, rel, f"corrupt zip archive: {exc}")
648
+ ])
649
+ if ext in (".keras", ".npz"):
650
+ return _Inspection(ext.lstrip("."), "model", "unknown", findings=[
651
+ _finding("MB205", Severity.LOW, rel, "expected a zip archive")
652
+ ])
653
+ if ext in TORCH_EXTS and not looks_like_pickle(head[:2]) and _compression(head[:8]) is None:
654
+ return None # an arbitrary binary that merely shares the extension
655
+ fmt = {".joblib": "joblib"}.get(ext, "pytorch-legacy" if ext in TORCH_EXTS else "pickle")
656
+ with path.open("rb") as fh:
657
+ data, truncated = _read_capped(fh, opts.max_bytes)
658
+ return _inspect_pickle_bytes(data, truncated, rel, fmt, opts)
659
+
660
+
661
+ def inspect_artifact(path: Path, rel: str, opts: ArtifactOptions) -> tuple[Artifact | None, list[Finding]]:
662
+ """Inspect one candidate file. Returns ``(None, [])`` when the file is not an artifact."""
663
+ name = rel.rsplit("/", 1)[-1]
664
+ ext = Path(name).suffix.lower()
665
+ size = path.stat().st_size
666
+ try:
667
+ insp = _dispatch(path, rel, ext, name, size, opts)
668
+ except OSError as exc:
669
+ return None, [_finding("MB205", Severity.LOW, rel, f"could not read file: {exc}")]
670
+ except Exception as exc: # hostile files must never crash the scan
671
+ insp = _Inspection(
672
+ ext.lstrip(".") or "unknown",
673
+ "model",
674
+ "unknown",
675
+ findings=[_finding("MB205", Severity.LOW, rel, f"{type(exc).__name__}: {exc}")],
676
+ )
677
+ if insp is None:
678
+ return None, []
679
+ digest = sha256_file(path) if opts.hash_files else None
680
+ artifact = Artifact(
681
+ path=rel,
682
+ format=insp.format,
683
+ kind=insp.kind,
684
+ size=size,
685
+ sha256=digest,
686
+ serialization=insp.serialization,
687
+ details=insp.details,
688
+ )
689
+ findings = insp.findings
690
+ if not findings:
691
+ findings = [
692
+ _finding("MB206", Severity.INFO, rel, f"{insp.format} {insp.kind} inventoried")
693
+ ]
694
+ for f in findings:
695
+ f.details.setdefault("artifact", rel)
696
+ return artifact, findings