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/graph.py ADDED
@@ -0,0 +1,257 @@
1
+ """Dependency graph: source files, remote models/datasets, local artifacts and packages.
2
+
3
+ Nodes are connected by ``loads`` / ``downloads`` / ``references`` / ``declares`` / ``imports``
4
+ edges. The graph is the substrate for the attack-path engine and can be exported as Mermaid,
5
+ Graphviz DOT or JSON.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import posixpath
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+
15
+ from .artifacts import ARTIFACT_EXTS
16
+ from .deps import normalize
17
+ from .models import AttackPath, ScanResult, Severity
18
+
19
+ _IMPORT_TO_DIST = {
20
+ "sklearn": "scikit-learn",
21
+ "yaml": "pyyaml",
22
+ "cv2": "opencv-python",
23
+ "PIL": "pillow",
24
+ "huggingface_hub": "huggingface-hub",
25
+ "sentence_transformers": "sentence-transformers",
26
+ "llama_index": "llama-index",
27
+ "llama_cpp": "llama-cpp-python",
28
+ "tf_keras": "tf-keras",
29
+ }
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Link:
34
+ source: str # code file path
35
+ target: str # artifact path
36
+ label: str # "loads" | "references"
37
+ line: int | None
38
+
39
+
40
+ @dataclass
41
+ class Graph:
42
+ nodes: dict[str, dict[str, Any]] = field(default_factory=dict)
43
+ edges: list[tuple[str, str, str]] = field(default_factory=list)
44
+
45
+ def add_node(self, node_id: str, node_type: str, label: str) -> None:
46
+ self.nodes.setdefault(node_id, {"id": node_id, "type": node_type, "label": label, "risk": None})
47
+
48
+ def add_edge(self, source: str, target: str, label: str) -> None:
49
+ edge = (source, target, label)
50
+ if edge not in self.edges:
51
+ self.edges.append(edge)
52
+
53
+ def mark(self, node_id: str, severity: Severity) -> None:
54
+ node = self.nodes.get(node_id)
55
+ if node is None:
56
+ return
57
+ current = node["risk"]
58
+ if current is None or Severity.parse(current) < severity:
59
+ node["risk"] = severity.label
60
+
61
+
62
+ def _norm_literal(value: str) -> str | None:
63
+ value = value.strip().replace("\\", "/")
64
+ if not value or "://" in value or "\n" in value:
65
+ return None
66
+ if not any(value.lower().endswith(ext) for ext in ARTIFACT_EXTS) and "/" not in value:
67
+ return None
68
+ return posixpath.normpath(value)
69
+
70
+
71
+ def build_links(result: ScanResult) -> list[Link]:
72
+ """Link string literals in code to artifacts found on disk."""
73
+ by_path = {a.path: a for a in result.artifacts}
74
+ by_base: dict[str, list[str]] = {}
75
+ for a in result.artifacts:
76
+ by_base.setdefault(posixpath.basename(a.path), []).append(a.path)
77
+ links: list[Link] = []
78
+ seen: set[tuple[str, str]] = set()
79
+ for cf in result.code_files:
80
+ load_literals = {lit for site in cf.load_sites for lit in site.literals}
81
+ code_dir = posixpath.dirname(cf.path)
82
+ for value, line in cf.literals:
83
+ norm = _norm_literal(value)
84
+ if norm is None:
85
+ continue
86
+ target = None
87
+ if norm in by_path:
88
+ target = norm
89
+ else:
90
+ joined = posixpath.normpath(posixpath.join(code_dir, norm)) if code_dir else norm
91
+ if joined in by_path:
92
+ target = joined
93
+ else:
94
+ candidates = by_base.get(posixpath.basename(norm), [])
95
+ if len(candidates) == 1 and any(norm.lower().endswith(e) for e in ARTIFACT_EXTS):
96
+ target = candidates[0]
97
+ if target is None or (cf.path, target) in seen:
98
+ continue
99
+ seen.add((cf.path, target))
100
+ label = "loads" if value in load_literals else "references"
101
+ links.append(Link(cf.path, target, label, line))
102
+ return links
103
+
104
+
105
+ def _dist_for_import(module: str, declared: set[str]) -> str | None:
106
+ for candidate in (_IMPORT_TO_DIST.get(module, ""), normalize(module)):
107
+ if candidate and candidate in declared:
108
+ return candidate
109
+ if module == "faiss":
110
+ return next((d for d in sorted(declared) if d.startswith("faiss")), None)
111
+ return None
112
+
113
+
114
+ def build_graph(result: ScanResult, links: list[Link] | None = None) -> Graph:
115
+ links = build_links(result) if links is None else links
116
+ g = Graph()
117
+ for a in result.artifacts:
118
+ g.add_node(a.ref, "artifact" if a.kind != "data" else "data", a.path)
119
+ for ref in result.model_refs:
120
+ node_type = "dataset" if ref.kind == "dataset" else "model"
121
+ label = f"{ref.name} @ {ref.revision or 'unpinned'}"
122
+ g.add_node(ref.ref, node_type, label)
123
+ file_id = f"file:{ref.path}"
124
+ g.add_node(file_id, "file", ref.path)
125
+ verb = "downloads" if ref.call.endswith(("hf_hub_download", "snapshot_download")) else "loads"
126
+ g.add_edge(file_id, ref.ref, verb)
127
+ for link in links:
128
+ file_id = f"file:{link.source}"
129
+ g.add_node(file_id, "file", link.source)
130
+ g.add_edge(file_id, f"artifact:{link.target}", link.label)
131
+ declared = {d.name for d in result.dependencies}
132
+ for d in result.dependencies:
133
+ pkg_id = f"pkg:{d.name}"
134
+ label = d.name + (f" {d.version}" if d.version else (f" {d.specifier}" if d.specifier else ""))
135
+ if pkg_id in g.nodes and d.version:
136
+ g.nodes[pkg_id]["label"] = label
137
+ g.add_node(pkg_id, "package", label)
138
+ manifest = f"file:{d.source}"
139
+ g.add_node(manifest, "manifest", d.source)
140
+ g.add_edge(manifest, pkg_id, "declares")
141
+ for cf in result.code_files:
142
+ for module in sorted(cf.imports):
143
+ dist = _dist_for_import(module, declared)
144
+ if dist is None:
145
+ continue
146
+ file_id = f"file:{cf.path}"
147
+ g.add_node(file_id, "file", cf.path)
148
+ g.add_edge(file_id, f"pkg:{dist}", "imports")
149
+ for f in result.reportable():
150
+ if f.severity == Severity.INFO:
151
+ continue
152
+ g.mark(f"file:{f.path}", f.severity)
153
+ g.mark(f"artifact:{f.details.get('artifact', f.path)}", f.severity)
154
+ if f.details.get("ref"):
155
+ g.mark(str(f.details["ref"]), f.severity)
156
+ if f.details.get("package"):
157
+ g.mark(f"pkg:{f.details['package']}", f.severity)
158
+ return g
159
+
160
+
161
+ # --- exporters -------------------------------------------------------------------------------
162
+
163
+ _MERMAID_SHAPES = {
164
+ "file": ('["', '"]'),
165
+ "manifest": ('["', '"]'),
166
+ "artifact": ('[/"', '"/]'),
167
+ "data": ('[("', '")]'),
168
+ "model": ('(["', '"])'),
169
+ "dataset": ('[("', '")]'),
170
+ "package": ('{{"', '"}}'),
171
+ }
172
+
173
+
174
+ def _mermaid_text(text: str) -> str:
175
+ return text.replace('"', "#quot;").replace("<", "#lt;").replace(">", "#gt;")
176
+
177
+
178
+ def to_mermaid(graph: Graph, paths: list[AttackPath]) -> str:
179
+ ids = {node_id: f"n{i}" for i, node_id in enumerate(graph.nodes, start=1)}
180
+ out = ["flowchart LR"]
181
+ for node_id, node in graph.nodes.items():
182
+ left, right = _MERMAID_SHAPES.get(node["type"], ('["', '"]'))
183
+ prefix = {"model": "model: ", "dataset": "dataset: ", "package": ""}.get(node["type"], "")
184
+ out.append(f" {ids[node_id]}{left}{_mermaid_text(prefix + node['label'])}{right}")
185
+ for src, dst, label in graph.edges:
186
+ if src in ids and dst in ids:
187
+ out.append(f" {ids[src]} -->|{label}| {ids[dst]}")
188
+ for path in paths:
189
+ nodes = [n for n in path.nodes if n in ids]
190
+ for a, b in zip(nodes, nodes[1:], strict=False):
191
+ out.append(f" {ids[a]} -.->|{path.id}| {ids[b]}")
192
+ out.append(" classDef critical fill:#fde2e2,stroke:#c0392b,stroke-width:3px")
193
+ out.append(" classDef high fill:#fdebd0,stroke:#d35400,stroke-width:2px")
194
+ out.append(" classDef medium fill:#fcf3cf,stroke:#b7950b")
195
+ out.append(" classDef low fill:#eaf2f8,stroke:#5d6d7e")
196
+ for level in ("critical", "high", "medium", "low"):
197
+ members = [ids[n] for n, node in graph.nodes.items() if node["risk"] == level]
198
+ if members:
199
+ out.append(f" class {','.join(members)} {level}")
200
+ for path in paths:
201
+ out.append(f" %% {path.id} [{path.severity.label}] {path.title}")
202
+ return "\n".join(out) + "\n"
203
+
204
+
205
+ _DOT_SHAPES = {
206
+ "file": "note",
207
+ "manifest": "note",
208
+ "artifact": "box3d",
209
+ "data": "cylinder",
210
+ "model": "component",
211
+ "dataset": "cylinder",
212
+ "package": "hexagon",
213
+ }
214
+ _DOT_COLORS = {"critical": "#c0392b", "high": "#d35400", "medium": "#b7950b", "low": "#5d6d7e"}
215
+
216
+
217
+ def _dot_text(text: str) -> str:
218
+ return text.replace("\\", "\\\\").replace('"', '\\"')
219
+
220
+
221
+ def to_dot(graph: Graph, paths: list[AttackPath]) -> str:
222
+ out = ["digraph modelbom {", " rankdir=LR;", ' node [fontname="Helvetica", fontsize=10];']
223
+ for node_id, node in graph.nodes.items():
224
+ attrs = [f'label="{_dot_text(node["label"])}"', f'shape={_DOT_SHAPES.get(node["type"], "box")}']
225
+ if node["risk"] in _DOT_COLORS:
226
+ attrs.append(f'color="{_DOT_COLORS[node["risk"]]}"')
227
+ attrs.append("penwidth=2")
228
+ out.append(f' "{_dot_text(node_id)}" [{", ".join(attrs)}];')
229
+ for src, dst, label in graph.edges:
230
+ out.append(f' "{_dot_text(src)}" -> "{_dot_text(dst)}" [label="{label}"];')
231
+ for path in paths:
232
+ nodes = [n for n in path.nodes if n in graph.nodes]
233
+ for a, b in zip(nodes, nodes[1:], strict=False):
234
+ out.append(
235
+ f' "{_dot_text(a)}" -> "{_dot_text(b)}" '
236
+ f'[label="{path.id}", color="#c0392b", style=dashed, fontcolor="#c0392b"];'
237
+ )
238
+ out.append("}")
239
+ return "\n".join(out) + "\n"
240
+
241
+
242
+ def to_json(graph: Graph, paths: list[AttackPath]) -> str:
243
+ payload = {
244
+ "nodes": list(graph.nodes.values()),
245
+ "edges": [{"source": s, "target": t, "label": label} for s, t, label in graph.edges],
246
+ "attack_paths": [
247
+ {
248
+ "id": p.id,
249
+ "kind": p.kind,
250
+ "title": p.title,
251
+ "severity": p.severity.label,
252
+ "nodes": p.nodes,
253
+ }
254
+ for p in paths
255
+ ],
256
+ }
257
+ return json.dumps(payload, indent=2) + "\n"
modelbom/models.py ADDED
@@ -0,0 +1,201 @@
1
+ """Core data model shared by scanners, the attack-path engine and the reporters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from dataclasses import dataclass, field
7
+ from enum import IntEnum
8
+ from typing import Any
9
+
10
+
11
+ class Severity(IntEnum):
12
+ """Ordered severity scale used for findings, attack paths and ``--fail-on``."""
13
+
14
+ INFO = 0
15
+ LOW = 1
16
+ MEDIUM = 2
17
+ HIGH = 3
18
+ CRITICAL = 4
19
+
20
+ @property
21
+ def label(self) -> str:
22
+ return self.name.lower()
23
+
24
+ @classmethod
25
+ def parse(cls, value: str) -> Severity:
26
+ try:
27
+ return cls[value.strip().upper()]
28
+ except KeyError as exc:
29
+ raise ValueError(f"unknown severity: {value!r}") from exc
30
+
31
+
32
+ @dataclass
33
+ class Finding:
34
+ """A single issue reported against a file location."""
35
+
36
+ rule_id: str
37
+ severity: Severity
38
+ path: str
39
+ message: str
40
+ line: int | None = None
41
+ snippet: str | None = None
42
+ details: dict[str, Any] = field(default_factory=dict)
43
+ suppressed: bool = False
44
+
45
+ @property
46
+ def location(self) -> str:
47
+ if self.line is not None:
48
+ return f"{self.path}:{self.line}"
49
+ cell = self.details.get("cell")
50
+ if cell is not None:
51
+ return f"{self.path} (cell {cell}, line {self.details.get('cell_line')})"
52
+ return self.path
53
+
54
+ @property
55
+ def fingerprint(self) -> str:
56
+ """Stable identifier that survives unrelated line shifts."""
57
+ basis = "|".join(
58
+ [
59
+ self.rule_id,
60
+ self.path,
61
+ self.snippet or self.message,
62
+ str(self.details.get("cell", "")),
63
+ str(self.details.get("member", "")),
64
+ ]
65
+ )
66
+ return hashlib.sha256(basis.encode()).hexdigest()[:16]
67
+
68
+
69
+ @dataclass
70
+ class Artifact:
71
+ """A model, dataset or model-configuration file found on disk."""
72
+
73
+ path: str
74
+ format: str
75
+ kind: str # "model" | "data" | "config"
76
+ size: int
77
+ sha256: str | None
78
+ serialization: str # "pickle" | "safe" | "code" | "unknown"
79
+ details: dict[str, Any] = field(default_factory=dict)
80
+
81
+ @property
82
+ def ref(self) -> str:
83
+ return f"artifact:{self.path}"
84
+
85
+
86
+ @dataclass
87
+ class ModelRef:
88
+ """A remote model or dataset referenced from source code."""
89
+
90
+ source: str # "huggingface" | "torch-hub"
91
+ name: str
92
+ kind: str # "model" | "dataset"
93
+ revision: str | None
94
+ path: str
95
+ line: int | None
96
+ call: str
97
+ trust_remote_code: bool = False
98
+
99
+ @property
100
+ def pinned(self) -> bool:
101
+ return self.revision is not None and self.revision not in ("main", "master")
102
+
103
+ @property
104
+ def ref(self) -> str:
105
+ prefix = "hf" if self.source == "huggingface" else "hub"
106
+ kind = "dataset:" if self.kind == "dataset" else ""
107
+ return f"{prefix}:{kind}{self.name}@{self.revision or 'unpinned'}"
108
+
109
+
110
+ @dataclass
111
+ class Dependency:
112
+ """A Python package declared in a manifest or lock file."""
113
+
114
+ name: str # PEP 503 normalized
115
+ specifier: str
116
+ version: str | None # exact version when pinned
117
+ pinned: bool
118
+ source: str
119
+ line: int | None
120
+ ml_relevant: bool
121
+ kind: str = "declared" # "declared" | "locked"
122
+
123
+ @property
124
+ def purl(self) -> str:
125
+ if self.version:
126
+ return f"pkg:pypi/{self.name}@{self.version}"
127
+ return f"pkg:pypi/{self.name}"
128
+
129
+
130
+ @dataclass
131
+ class LoadSite:
132
+ """A call in source code that loads or downloads a model or data file."""
133
+
134
+ path: str
135
+ line: int | None
136
+ call: str
137
+ rule_id: str | None
138
+ literals: list[str] = field(default_factory=list)
139
+
140
+
141
+ @dataclass
142
+ class CodeFile:
143
+ """Facts extracted from one Python file or notebook, used to build the graph."""
144
+
145
+ path: str
146
+ imports: set[str] = field(default_factory=set)
147
+ literals: list[tuple[str, int | None]] = field(default_factory=list)
148
+ load_sites: list[LoadSite] = field(default_factory=list)
149
+
150
+
151
+ @dataclass
152
+ class AttackStep:
153
+ rule_id: str
154
+ location: str
155
+ description: str
156
+ fingerprint: str
157
+
158
+
159
+ @dataclass
160
+ class AttackPath:
161
+ """A chain of findings whose preconditions combine into a concrete compromise."""
162
+
163
+ id: str
164
+ kind: str
165
+ title: str
166
+ severity: Severity
167
+ precondition: str
168
+ steps: list[AttackStep]
169
+ impact: str
170
+ nodes: list[str] = field(default_factory=list)
171
+
172
+
173
+ @dataclass
174
+ class ScanResult:
175
+ root: str
176
+ findings: list[Finding] = field(default_factory=list)
177
+ artifacts: list[Artifact] = field(default_factory=list)
178
+ model_refs: list[ModelRef] = field(default_factory=list)
179
+ dependencies: list[Dependency] = field(default_factory=list)
180
+ code_files: list[CodeFile] = field(default_factory=list)
181
+ attack_paths: list[AttackPath] = field(default_factory=list)
182
+ files_scanned: int = 0
183
+ online: bool = False
184
+
185
+ def active(self) -> list[Finding]:
186
+ """Findings that are not suppressed."""
187
+ return [f for f in self.findings if not f.suppressed]
188
+
189
+ def reportable(self) -> list[Finding]:
190
+ """Active findings excluding pure inventory records (MB206)."""
191
+ return [f for f in self.active() if f.rule_id != "MB206"]
192
+
193
+ def counts(self) -> dict[str, int]:
194
+ out = {s.label: 0 for s in sorted(Severity, reverse=True)}
195
+ for f in self.reportable():
196
+ out[f.severity.label] += 1
197
+ return out
198
+
199
+ def max_severity(self) -> Severity | None:
200
+ sevs = [f.severity for f in self.reportable()]
201
+ return max(sevs) if sevs else None