intentumdiff-python 0.0.1__py3-none-win_amd64.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.
Files changed (165) hide show
  1. intentumdiff/__init__.py +134 -0
  2. intentumdiff/_differ_gate.py +210 -0
  3. intentumdiff/_differ_presentation.py +786 -0
  4. intentumdiff/_differ_runtime.py +320 -0
  5. intentumdiff/analysis/__init__.py +1 -0
  6. intentumdiff/analysis/compile_commands.py +151 -0
  7. intentumdiff/analysis/cross_file.py +71 -0
  8. intentumdiff/analysis/diagnostics.py +309 -0
  9. intentumdiff/analysis/guardrail_reports.py +254 -0
  10. intentumdiff/analysis/guardrails.py +318 -0
  11. intentumdiff/analysis/invariances.py +1207 -0
  12. intentumdiff/analysis/keyed_profiles.py +25 -0
  13. intentumdiff/analysis/resource_profiles.py +14 -0
  14. intentumdiff/analysis/schema_resolver.py +816 -0
  15. intentumdiff/analysis/text_review.py +46 -0
  16. intentumdiff/analysis/user_schemas.py +430 -0
  17. intentumdiff/assets.py +45 -0
  18. intentumdiff/cache/__init__.py +37 -0
  19. intentumdiff/cache/duckdb_store.py +98 -0
  20. intentumdiff/cache/sqlite_store.py +149 -0
  21. intentumdiff/cache/store.py +190 -0
  22. intentumdiff/cli/__init__.py +199 -0
  23. intentumdiff/cli/_commands.py +2141 -0
  24. intentumdiff/cli/_parser.py +1061 -0
  25. intentumdiff/cli/_shared.py +644 -0
  26. intentumdiff/content_type.py +59 -0
  27. intentumdiff/core/__init__.py +1 -0
  28. intentumdiff/core/commit_differ.py +599 -0
  29. intentumdiff/core/config.py +51 -0
  30. intentumdiff/core/cst_serializer.py +101 -0
  31. intentumdiff/core/diffignore.py +87 -0
  32. intentumdiff/core/index.py +189 -0
  33. intentumdiff/core/indexer.py +792 -0
  34. intentumdiff/core/models.py +837 -0
  35. intentumdiff/differ.py +2195 -0
  36. intentumdiff/github_app.py +287 -0
  37. intentumdiff/intentumdiff_rust_core/__init__.py +7 -0
  38. intentumdiff/intentumdiff_rust_core/ffi.py +8 -0
  39. intentumdiff/intentumdiff_rust_core/intentumdiff_rust_core.dll +0 -0
  40. intentumdiff/invariances/__init__.py +2 -0
  41. intentumdiff/invariances/rules.schema.json +283 -0
  42. intentumdiff/invariances/rules.yaml +349 -0
  43. intentumdiff/live_server.py +1314 -0
  44. intentumdiff/lsp/__init__.py +67 -0
  45. intentumdiff/lsp/client.py +544 -0
  46. intentumdiff/lsp/config.py +96 -0
  47. intentumdiff/lsp/enricher.py +227 -0
  48. intentumdiff/lsp/exceptions.py +27 -0
  49. intentumdiff/lsp/launcher.py +273 -0
  50. intentumdiff/lsp/servers.py +356 -0
  51. intentumdiff/lsp_server/__init__.py +14 -0
  52. intentumdiff/lsp_server/_codelens.py +67 -0
  53. intentumdiff/lsp_server/_diagnostics.py +62 -0
  54. intentumdiff/lsp_server/_handlers.py +175 -0
  55. intentumdiff/lsp_server/server.py +205 -0
  56. intentumdiff/plugins/__init__.py +1 -0
  57. intentumdiff/plugins/adapter.py +397 -0
  58. intentumdiff/plugins/builtins.py +323 -0
  59. intentumdiff/plugins/exceptions.py +93 -0
  60. intentumdiff/plugins/hub.py +1155 -0
  61. intentumdiff/plugins/language_metadata.py +250 -0
  62. intentumdiff/plugins/loader.py +1252 -0
  63. intentumdiff/plugins/registry.py +1079 -0
  64. intentumdiff/plugins/registry.schema.json +99 -0
  65. intentumdiff/plugins/registry_schema.py +280 -0
  66. intentumdiff/plugins/wit/plugin.wit +351 -0
  67. intentumdiff/rust_core.py +2370 -0
  68. intentumdiff/serve/__init__.py +19 -0
  69. intentumdiff/serve/_app.py +485 -0
  70. intentumdiff/serve/_static/index.html +326 -0
  71. intentumdiff/serve/_static/playground.js +567 -0
  72. intentumdiff/sources/__init__.py +1 -0
  73. intentumdiff/sources/base.py +28 -0
  74. intentumdiff/sources/file_source.py +48 -0
  75. intentumdiff/sources/git_source.py +375 -0
  76. intentumdiff/sources/live_buffer_source.py +113 -0
  77. intentumdiff/sources/patch_source.py +126 -0
  78. intentumdiff/sources/string_source.py +44 -0
  79. intentumdiff/testing.py +165 -0
  80. intentumdiff/vcs/__init__.py +37 -0
  81. intentumdiff/vcs/_safe_path.py +50 -0
  82. intentumdiff/vcs/base.py +136 -0
  83. intentumdiff/vcs/git_backend.py +97 -0
  84. intentumdiff/vcs/git_cli.py +100 -0
  85. intentumdiff/vcs/hg_backend.py +94 -0
  86. intentumdiff/vcs/perforce_backend.py +109 -0
  87. intentumdiff/vcs/svn_backend.py +105 -0
  88. intentumdiff/wasm/.gitkeep +2 -0
  89. intentumdiff/wasm/abap_parser.wasm +0 -0
  90. intentumdiff/wasm/adf_parser.wasm +0 -0
  91. intentumdiff/wasm/asciidoc_parser.wasm +0 -0
  92. intentumdiff/wasm/asm_parser.wasm +0 -0
  93. intentumdiff/wasm/assemblyscript_parser.wasm +0 -0
  94. intentumdiff/wasm/astro_parser.wasm +0 -0
  95. intentumdiff/wasm/bash_parser.wasm +0 -0
  96. intentumdiff/wasm/clojure_parser.wasm +0 -0
  97. intentumdiff/wasm/cmake_parser.wasm +0 -0
  98. intentumdiff/wasm/cpp_parser.wasm +0 -0
  99. intentumdiff/wasm/csharp_parser.wasm +0 -0
  100. intentumdiff/wasm/css_parser.wasm +0 -0
  101. intentumdiff/wasm/dart_parser.wasm +0 -0
  102. intentumdiff/wasm/databricks_parser.wasm +0 -0
  103. intentumdiff/wasm/dax_parser.wasm +0 -0
  104. intentumdiff/wasm/delphi_parser.wasm +0 -0
  105. intentumdiff/wasm/dockerfile_parser.wasm +0 -0
  106. intentumdiff/wasm/elixir_parser.wasm +0 -0
  107. intentumdiff/wasm/freebasic_parser.wasm +0 -0
  108. intentumdiff/wasm/generic_parser.wasm +0 -0
  109. intentumdiff/wasm/gitignore_parser.wasm +0 -0
  110. intentumdiff/wasm/go_parser.wasm +0 -0
  111. intentumdiff/wasm/gomod_parser.wasm +0 -0
  112. intentumdiff/wasm/graphql_parser.wasm +0 -0
  113. intentumdiff/wasm/groovy_parser.wasm +0 -0
  114. intentumdiff/wasm/haskell_parser.wasm +0 -0
  115. intentumdiff/wasm/html_parser.wasm +0 -0
  116. intentumdiff/wasm/ini_parser.wasm +0 -0
  117. intentumdiff/wasm/java_parser.wasm +0 -0
  118. intentumdiff/wasm/js_ts_parser.wasm +0 -0
  119. intentumdiff/wasm/json_parser.wasm +0 -0
  120. intentumdiff/wasm/kotlin_parser.wasm +0 -0
  121. intentumdiff/wasm/latex_parser.wasm +0 -0
  122. intentumdiff/wasm/lua_parser.wasm +0 -0
  123. intentumdiff/wasm/make_parser.wasm +0 -0
  124. intentumdiff/wasm/markdown_parser.wasm +0 -0
  125. intentumdiff/wasm/mdx_parser.wasm +0 -0
  126. intentumdiff/wasm/ocaml_parser.wasm +0 -0
  127. intentumdiff/wasm/odin_parser.wasm +0 -0
  128. intentumdiff/wasm/parser_manifest.json +590 -0
  129. intentumdiff/wasm/perl_parser.wasm +0 -0
  130. intentumdiff/wasm/php_parser.wasm +0 -0
  131. intentumdiff/wasm/plsql_parser.wasm +0 -0
  132. intentumdiff/wasm/po_parser.wasm +0 -0
  133. intentumdiff/wasm/postscript_parser.wasm +0 -0
  134. intentumdiff/wasm/powershell_parser.wasm +0 -0
  135. intentumdiff/wasm/proto_parser.wasm +0 -0
  136. intentumdiff/wasm/puppet_parser.wasm +0 -0
  137. intentumdiff/wasm/python_parser.wasm +0 -0
  138. intentumdiff/wasm/qsharp_parser.wasm +0 -0
  139. intentumdiff/wasm/r_parser.wasm +0 -0
  140. intentumdiff/wasm/reasonml_parser.wasm +0 -0
  141. intentumdiff/wasm/ruby_parser.wasm +0 -0
  142. intentumdiff/wasm/rust_parser.wasm +0 -0
  143. intentumdiff/wasm/sas_parser.wasm +0 -0
  144. intentumdiff/wasm/scala_parser.wasm +0 -0
  145. intentumdiff/wasm/scss_parser.wasm +0 -0
  146. intentumdiff/wasm/sql_parser.wasm +0 -0
  147. intentumdiff/wasm/squirrel_parser.wasm +0 -0
  148. intentumdiff/wasm/svelte_parser.wasm +0 -0
  149. intentumdiff/wasm/swift_parser.wasm +0 -0
  150. intentumdiff/wasm/terraform_parser.wasm +0 -0
  151. intentumdiff/wasm/toml_parser.wasm +0 -0
  152. intentumdiff/wasm/tsql_parser.wasm +0 -0
  153. intentumdiff/wasm/vbnet_parser.wasm +0 -0
  154. intentumdiff/wasm/vue_parser.wasm +0 -0
  155. intentumdiff/wasm/wat_parser.wasm +0 -0
  156. intentumdiff/wasm/xml_parser.wasm +0 -0
  157. intentumdiff/wasm/yaml_parser.wasm +0 -0
  158. intentumdiff/wasm/zig_parser.wasm +0 -0
  159. intentumdiff/watcher.py +259 -0
  160. intentumdiff_python-0.0.1.dist-info/METADATA +112 -0
  161. intentumdiff_python-0.0.1.dist-info/RECORD +165 -0
  162. intentumdiff_python-0.0.1.dist-info/WHEEL +4 -0
  163. intentumdiff_python-0.0.1.dist-info/entry_points.txt +80 -0
  164. intentumdiff_python-0.0.1.dist-info/licenses/LICENSE +21 -0
  165. intentumdiff_python-0.0.1.dist-info/sboms/intentumdiff-rust-core.cyclonedx.json +10968 -0
@@ -0,0 +1,1155 @@
1
+ """
2
+ intentumdiff.plugins.hub
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Plugin hub: resolve, install, verify, and remove IntentumDiff plugins.
6
+
7
+ Sources
8
+ -------
9
+ Plugins can be installed from two sources:
10
+
11
+ ``source: git`` (default)
12
+ ``pip install git+<url>@<ref>``
13
+ ``ref`` is a git tag, branch, or commit SHA.
14
+ ``repo`` overrides the default official-org URL.
15
+
16
+ ``source: pypi``
17
+ ``pip install <package>[==<ref>]``
18
+ ``ref`` is a PEP 440 version string (e.g. ``"1.2.3"``).
19
+ ``repo`` is unused.
20
+
21
+ For official plugins (no ``repo``), the short name is expanded to the
22
+ full package in the ``buchochelliq-labs`` GitHub org:
23
+ ``dbt`` -> ``intentumdiff-dbt``
24
+ -> ``https://github.com/buchochelliq-labs/intentumdiff-dbt``
25
+
26
+ Security model
27
+ --------------
28
+ After installation, two checks are run (unless ``--skip-verify`` is passed):
29
+
30
+ 1. **Wasm checksum verification** — SHA-256 of every ``.wasm`` file in the
31
+ installed package is compared against the expected hashes stored in
32
+ ``intentumdiff_plugins.yaml`` (populated from the official registry or supplied
33
+ manually). A mismatch means the installed binary is different from the
34
+ one the author published.
35
+
36
+ 2. **Wasm capability scan** — the binary's import section is scanned for
37
+ unexpected WASI imports (filesystem, sockets, network, HTTP, …). The only
38
+ permitted host import is the IntentumDiff WIT package
39
+ ``intentdiff:plugin/host-utils@1.0.0``.
40
+ Any other import is flagged as a warning.
41
+
42
+ When installing from the **official registry**, the registry manifest already
43
+ contains the expected checksums for each release, so verification is
44
+ automatic. When installing from a custom source, checksums are computed and
45
+ stored in ``intentumdiff_plugins.yaml`` on first install (trust-on-first-use), and
46
+ subsequent ``intentumdiff plugins install`` will verify them.
47
+
48
+ Plugin file format (intentumdiff_plugins.yaml)
49
+ ----------------------------------------
50
+ ::
51
+
52
+ # intentumdiff_plugins.yaml
53
+ version: 1
54
+ plugins:
55
+ - name: dbt
56
+ source: pypi # "pypi" or "git" (default: git)
57
+ ref: "0.3.1" # git: tag/branch/commit; pypi: version (e.g. "1.2.3")
58
+ wasm_checksums: # populated automatically; verify on every install
59
+ dbt_sql_parser.wasm: <sha256_hex>
60
+ dbt_schema_parser.wasm: <sha256_hex>
61
+ dbt_enricher.wasm: <sha256_hex>
62
+
63
+ - name: terraform
64
+ source: git
65
+ ref: v0.2.0
66
+ wasm_checksums:
67
+ terraform_parser.wasm: <sha256_hex>
68
+
69
+ - name: custom-plugin
70
+ source: git
71
+ ref: abc1234
72
+ repo: https://github.com/myorg/intentumdiff-custom
73
+ # wasm_checksums intentionally omitted — will warn about unverified install
74
+ """
75
+
76
+ from __future__ import annotations
77
+
78
+ import hashlib
79
+ import importlib.metadata as _meta
80
+ import logging
81
+ import re
82
+ import ssl
83
+ import subprocess
84
+ import sys
85
+ import urllib.error
86
+ import urllib.request
87
+ from dataclasses import dataclass, field
88
+ from pathlib import Path, PurePosixPath, PureWindowsPath
89
+ from typing import Any
90
+
91
+ logger = logging.getLogger(__name__)
92
+
93
+ # ---------------------------------------------------------------------------
94
+ # Official plugin organisation
95
+ # ---------------------------------------------------------------------------
96
+
97
+ #: GitHub organisation that hosts official IntentumDiff plugins.
98
+ OFFICIAL_ORG = "buchochelliq-labs"
99
+ OFFICIAL_BASE_URL = f"https://github.com/{OFFICIAL_ORG}"
100
+
101
+ #: Raw-content URL for the official registry manifest (the intentumdiff-registry repo — the
102
+ #: #95 root of trust, populated at the #82 split; formerly the unpopulated intentumdiff-plugins).
103
+ OFFICIAL_REGISTRY_RAW_URL = (
104
+ f"https://raw.githubusercontent.com/{OFFICIAL_ORG}/intentumdiff-registry"
105
+ )
106
+
107
+ # The safe-Git-ref pattern (registry URL path segments), the strict commit-SHA
108
+ # pattern, and the dep_hashes key/value patterns now live in the shared Rust
109
+ # core (registry.rs) — see _validate_registry_ref / _validate_dep_hashes, which
110
+ # delegate so every binding enforces the identical #88 controls.
111
+ _PLUGIN_NAME_RE = re.compile(r"^(?:intentumdiff-)?[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
112
+ _PLUGIN_SOURCE_VALUES = frozenset({"git", "pypi"})
113
+
114
+
115
+ def _normalise_package_name(name: str) -> str:
116
+ """Return a comparison key for Python package names."""
117
+ return re.sub(r"[-_.]+", "_", name).lower()
118
+
119
+
120
+ def _package_from_dep_spec(dep_spec: str) -> str:
121
+ """Return the normalised package name from a ``package==version`` key."""
122
+ return _normalise_package_name(dep_spec.split("==", 1)[0])
123
+
124
+
125
+ def _package_from_wheel(wheel_path: "Path") -> str:
126
+ """Return the normalised distribution name encoded in a wheel filename."""
127
+ return _normalise_package_name(wheel_path.name.split("-", 1)[0])
128
+
129
+
130
+ def _main_package_names(spec: "PluginSpec", install_target: str | None) -> set[str]:
131
+ names = {_normalise_package_name(spec.package_name)}
132
+ if install_target:
133
+ names.add(_package_from_dep_spec(install_target))
134
+ return names
135
+
136
+
137
+ def _validate_registry_ref(ref: str, *, strict: bool = False) -> None:
138
+ """Raise ValueError if *ref* is not a safe Git ref for URL interpolation.
139
+
140
+ When *strict* is ``True``, the ref must be a full 40-character lowercase
141
+ hex commit SHA. This is the production/CI mode: it rejects mutable refs
142
+ like branch names and tags, making registry fetches reproducible and
143
+ tamper-evident.
144
+
145
+ The validation lives in the shared Rust core (``registry.rs``) so every
146
+ binding enforces the identical #88 guard; this is a thin delegator.
147
+ """
148
+ from intentumdiff.rust_core import validate_registry_ref as _rust_validate_ref
149
+
150
+ _rust_validate_ref(ref, strict)
151
+
152
+ def _validate_dep_hashes(spec: "PluginSpec", install_target: str | None = None) -> list[str]:
153
+ """Validate *spec.dep_hashes* keys and coverage.
154
+
155
+ Returns a list of human-readable error strings. An empty list means the
156
+ dep_hashes dict is well-formed and the main package is listed.
157
+
158
+ Rules:
159
+ - Every key must match ``package==version`` (exact PEP 440 pin).
160
+ - Every hash must be a SHA-256 hash in pip's ``sha256:<hex>`` form.
161
+ - The main plugin package must appear as one of the keys.
162
+ - Extra packages must be explicitly listed in ``allowed_dependencies``.
163
+
164
+ The key/value/coverage checks live in the shared Rust core
165
+ (``registry.rs``) so every binding enforces the identical #88 controls;
166
+ this is a thin delegator. ``dep_hashes`` is passed as ordered
167
+ ``(key, value)`` pairs so error ordering matches the dict iteration.
168
+ """
169
+ from intentumdiff.rust_core import validate_dep_hashes as _rust_validate_dep_hashes
170
+
171
+ return _rust_validate_dep_hashes(
172
+ list(spec.dep_hashes.items()),
173
+ list(spec.allowed_dependencies),
174
+ spec.package_name,
175
+ install_target,
176
+ )
177
+
178
+
179
+ #: Default filename for the project-level plugins manifest.
180
+
181
+ # Wasm imports that are legitimately expected in every plugin binary.
182
+ # Any module name NOT in this set (and not an IntentumDiff namespace)
183
+ # will be flagged by the capability scanner.
184
+ _ALLOWED_WASM_HOST_MODULES: frozenset[str] = frozenset(
185
+ {
186
+ "intentdiff:plugin/host-utils@1.0.0",
187
+ }
188
+ )
189
+
190
+ # WASI capability prefixes that are always suspicious for a sandboxed plugin.
191
+ _SUSPICIOUS_WASI_PREFIXES: tuple[bytes, ...] = (
192
+ b"wasi:filesystem",
193
+ b"wasi:sockets",
194
+ b"wasi:network",
195
+ b"wasi:http",
196
+ b"wasi:keyvalue",
197
+ b"wasi:blobstore",
198
+ b"wasi:messaging",
199
+ # wasi:io/streams is used internally by the Component Model runtime for
200
+ # async; we allow it via wasmtime's empty WasiConfig. Flag anything else.
201
+ )
202
+
203
+
204
+ # ---------------------------------------------------------------------------
205
+ # PluginSpec dataclass
206
+ # ---------------------------------------------------------------------------
207
+
208
+
209
+ @dataclass
210
+ class PluginSpec:
211
+ """A single plugin dependency declaration."""
212
+
213
+ #: Short name (e.g. ``"dbt"``) or full package name.
214
+ name: str
215
+
216
+ #: Source type: ``"git"`` (default) or ``"pypi"``.
217
+ source: str = "git"
218
+
219
+ #: For git: tag, branch, or commit SHA (default ``"main"``).
220
+ #: For pypi: version string (e.g. ``"1.2.3"``); empty = latest.
221
+ ref: str = "main"
222
+
223
+ #: Optional custom git repo URL (git source only).
224
+ #: When empty the official org URL is derived from ``package_name``.
225
+ repo: str = ""
226
+
227
+ #: Expected SHA-256 hex digests of the installed ``.wasm`` files.
228
+ #: Key: filename (e.g. ``"dbt_sql_parser.wasm"``); value: lowercase hex.
229
+ #: Populated automatically by ``intentumdiff plugins add``.
230
+ #: An empty dict means checksums have not been recorded (install will warn).
231
+ wasm_checksums: dict[str, str] = field(default_factory=dict)
232
+
233
+ #: Approved dependency hashes for plugins that cannot be fully self-contained.
234
+ #: Key: ``"package==version"``; value: ``"sha256:hexdigest"``.
235
+ #: An empty dict (default) means the plugin wheel must be self-contained and
236
+ #: will be installed with ``--no-deps``. When non-empty every entry is passed
237
+ #: to pip as ``--require-hashes``, acting as a minimal inline lock-file.
238
+ #: The main package wheel **must** be included in this dict as well.
239
+ dep_hashes: dict[str, str] = field(default_factory=dict)
240
+
241
+ #: Reviewed package names, without versions, that may appear in ``dep_hashes``
242
+ #: in addition to the main plugin package.
243
+ allowed_dependencies: list[str] = field(default_factory=list)
244
+
245
+ # ── derived ──────────────────────────────────────────────────────────────
246
+
247
+ def __post_init__(self) -> None:
248
+ if not _PLUGIN_NAME_RE.fullmatch(self.name):
249
+ raise ValueError(
250
+ f"Invalid plugin name {self.name!r}: expected a package-safe "
251
+ "IntentumDiff plugin name, not a URL, path, or requirement expression."
252
+ )
253
+ if self.source not in _PLUGIN_SOURCE_VALUES:
254
+ raise ValueError(
255
+ f"Invalid plugin source {self.source!r}: expected one of "
256
+ f"{sorted(_PLUGIN_SOURCE_VALUES)!r}."
257
+ )
258
+
259
+ @property
260
+ def package_name(self) -> str:
261
+ """Canonical Python package name with the primary ``intentumdiff-`` prefix."""
262
+ if self.name.startswith("intentumdiff-"):
263
+ return self.name
264
+ return f"intentumdiff-{self.name}"
265
+
266
+ @property
267
+ def short_name(self) -> str:
268
+ """Short name without the primary package prefix."""
269
+ if self.name.startswith("intentumdiff-"):
270
+ return self.name[len("intentumdiff-"):]
271
+ return self.name
272
+
273
+ @property
274
+ def resolved_git_url(self) -> str:
275
+ """Git repository URL (git source only)."""
276
+ return self.repo or f"{OFFICIAL_BASE_URL}/{self.package_name}"
277
+
278
+ @property
279
+ def install_target(self) -> str:
280
+ """The pip install argument for this spec."""
281
+ if self.source == "pypi":
282
+ if self.ref:
283
+ return f"{self.package_name}=={self.ref}"
284
+ return self.package_name
285
+ # git (default)
286
+ url = self.resolved_git_url
287
+ if self.ref:
288
+ return f"git+{url}@{self.ref}"
289
+ return f"git+{url}"
290
+
291
+ @property
292
+ def pip_install_url(self) -> str:
293
+ """Deprecated alias for :attr:`install_target`."""
294
+ return self.install_target
295
+
296
+ @property
297
+ def is_official(self) -> bool:
298
+ """True when the plugin comes from the official org (no custom repo)."""
299
+ return not self.repo
300
+
301
+
302
+ # ---------------------------------------------------------------------------
303
+ # Official registry manifest
304
+ # ---------------------------------------------------------------------------
305
+
306
+
307
+ @dataclass
308
+ class RegistryEntry:
309
+ """Metadata for a single plugin as recorded in the official registry."""
310
+
311
+ name: str
312
+ source: str = "git"
313
+ ref: str = "main"
314
+ repo: str = ""
315
+ description: str = ""
316
+ #: SHA-256 hex digests keyed by ``.wasm`` filename.
317
+ wasm_checksums: dict[str, str] = field(default_factory=dict)
318
+ dep_hashes: dict[str, str] = field(default_factory=dict)
319
+ allowed_dependencies: list[str] = field(default_factory=list)
320
+ #: Plugin-contract ABI version the plugin implements (#94). Empty = unspecified
321
+ #: (older registry entries) — treated as compatible so it is not a breaking change.
322
+ abi_target: str = ""
323
+ #: Declared trust tier (#95): ``"official"`` (org-built/scanned) or ``"community"``
324
+ #: (listed but unverified). Empty defaults to ``"official"``. The EFFECTIVE tier
325
+ #: (:meth:`effective_trust_tier`) additionally demotes to community when the entry lacks
326
+ #: the verification an official plugin must carry.
327
+ trust_tier: str = "official"
328
+
329
+ def effective_trust_tier(self) -> str:
330
+ """The trust tier actually earned, mapping onto the existing verification signals (#95).
331
+
332
+ An entry is ``"official"`` only when it declares so (or leaves it default), comes from
333
+ the official org (no custom ``repo``), AND carries ``wasm_checksums`` for verification.
334
+ An explicit ``"community"`` tier, a custom repo, or missing checksums all resolve to
335
+ ``"community"`` — i.e. the same "listed but unverified → warn" condition hub.py already
336
+ surfaces, now named.
337
+ """
338
+ declared = self.trust_tier or "official"
339
+ if declared == "community" or self.repo or not self.wasm_checksums:
340
+ return "community"
341
+ return "official"
342
+
343
+ def trust_warning(self) -> str | None:
344
+ """A non-blocking warning string when this entry is (effectively) community-tier, else
345
+ ``None``. Community plugins install, but the user is told they are unverified (#95)."""
346
+ if self.effective_trust_tier() == "community":
347
+ return (
348
+ f"plugin {self.name!r} is community-tier (listed but unverified — no official "
349
+ "checksums / custom source). Install only if you trust the source."
350
+ )
351
+ return None
352
+
353
+ def abi_incompatibility(self, host_version: str | None = None) -> str | None:
354
+ """A human-readable reason string when this entry's ``abi_target`` is incompatible
355
+ with the host contract, else ``None``. Consumed at RESOLVE time (before install) so an
356
+ incompatible plugin is refused early, not at instantiation (#94). An empty
357
+ ``abi_target`` is treated as compatible (unspecified, not incompatible)."""
358
+ if not self.abi_target:
359
+ return None
360
+ from intentumdiff.plugins.registry_schema import HOST_CONTRACT_VERSION, abi_compatible
361
+
362
+ host = host_version or HOST_CONTRACT_VERSION
363
+ if not abi_compatible(self.abi_target, host):
364
+ return (
365
+ f"plugin {self.name!r} targets plugin-contract ABI {self.abi_target}, "
366
+ f"which is incompatible with this IntentumDiff host's contract {host}. "
367
+ "Upgrade IntentumDiff or install a plugin build that targets the host's ABI."
368
+ )
369
+ return None
370
+
371
+ def to_spec(self) -> PluginSpec:
372
+ """Convert to a :class:`PluginSpec` ready for installation."""
373
+ return PluginSpec(
374
+ name=self.name,
375
+ source=self.source,
376
+ ref=self.ref,
377
+ repo=self.repo,
378
+ wasm_checksums=dict(self.wasm_checksums),
379
+ dep_hashes=dict(self.dep_hashes),
380
+ allowed_dependencies=list(self.allowed_dependencies),
381
+ )
382
+
383
+
384
+ def fetch_official_registry(
385
+ ref: str = "main",
386
+ *,
387
+ strict: bool = False,
388
+ timeout: int = 15,
389
+ ) -> dict[str, RegistryEntry]:
390
+ """
391
+ Fetch and parse the official plugin registry manifest.
392
+
393
+ Parameters
394
+ ----------
395
+ ref:
396
+ Git ref (branch, tag, or commit SHA) of the registry repo to fetch
397
+ from. Default ``"main"``. **Pin to a commit SHA in production for
398
+ reproducible, tamper-evident installs.**
399
+ strict:
400
+ When ``True``, *ref* must be a full 40-character commit SHA. This
401
+ enforces the production/CI policy: mutable refs (branch names, tags)
402
+ are rejected. Pass ``strict=True`` via the ``--strict-registry`` CLI
403
+ flag.
404
+ timeout:
405
+ HTTP timeout in seconds.
406
+
407
+ Returns
408
+ -------
409
+ dict[str, RegistryEntry]
410
+ Mapping of short plugin name → registry entry.
411
+
412
+ Raises
413
+ ------
414
+ RuntimeError
415
+ If the registry cannot be fetched or parsed.
416
+ """
417
+ _validate_registry_ref(ref, strict=strict)
418
+ url = f"{OFFICIAL_REGISTRY_RAW_URL}/{ref}/registry.yaml"
419
+ logger.info("Fetching official registry at ref=%s (strict=%s)", ref, strict)
420
+ ctx = ssl.create_default_context() # always verify TLS certificates
421
+ if not url.startswith("https://"): # defense-in-depth: urllib also accepts file:// (#76 semgrep)
422
+ raise RuntimeError(f"registry URL must be https, got: {url.split(':', 1)[0]}")
423
+ try:
424
+ with urllib.request.urlopen(url, timeout=timeout, context=ctx) as resp: # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected -- scheme asserted https above; base is a fixed constant + validated ref. noqa: S310 # nosec B310 - https scheme asserted above
425
+ content = resp.read().decode("utf-8")
426
+ except urllib.error.URLError as exc:
427
+ raise RuntimeError(
428
+ f"Could not fetch the official plugin registry from {url}.\n"
429
+ f"Check your internet connection. Detail: {exc}"
430
+ ) from exc
431
+
432
+ return parse_registry_manifest(content)
433
+
434
+
435
+ def parse_registry_manifest(content: str) -> dict[str, RegistryEntry]:
436
+ """Parse a registry manifest (YAML text) into ``{short name -> RegistryEntry}``.
437
+
438
+ Split out from :func:`fetch_official_registry` so the parse (including the #94
439
+ ``abi_target``) is testable without the network fetch.
440
+ """
441
+ yaml = _require_yaml()
442
+ data: dict[str, Any] = yaml.safe_load(content) or {}
443
+
444
+ entries: dict[str, RegistryEntry] = {}
445
+ for plugin_name, entry_data in data.get("plugins", {}).items():
446
+ if not isinstance(entry_data, dict):
447
+ continue
448
+ entries[plugin_name] = RegistryEntry(
449
+ name=plugin_name,
450
+ source=entry_data.get("source", "git"),
451
+ ref=entry_data.get("ref", "main"),
452
+ repo=entry_data.get("repo", ""),
453
+ description=entry_data.get("description", ""),
454
+ wasm_checksums=dict(entry_data.get("wasm_checksums", {})),
455
+ dep_hashes=dict(entry_data.get("dep_hashes", {})),
456
+ allowed_dependencies=list(entry_data.get("allowed_dependencies") or []),
457
+ abi_target=str(entry_data.get("abi_target", "")),
458
+ trust_tier=str(entry_data.get("trust_tier", "") or "official"),
459
+ )
460
+ return entries
461
+
462
+
463
+ # ---------------------------------------------------------------------------
464
+ # YAML file I/O
465
+ # ---------------------------------------------------------------------------
466
+
467
+
468
+ def _require_yaml() -> Any:
469
+ """Import pyyaml, raising a friendly error if it is not installed."""
470
+ try:
471
+ import yaml # type: ignore[import-untyped]
472
+ return yaml
473
+ except ImportError as exc:
474
+ raise ImportError(
475
+ "pyyaml is required to read/write intentumdiff_plugins.yaml. "
476
+ "Install it with: pip install pyyaml"
477
+ ) from exc
478
+
479
+
480
+ def load_plugins_file(path: Path) -> list[PluginSpec]:
481
+ """Parse *path* (``intentumdiff_plugins.yaml``) and return a list of :class:`PluginSpec`."""
482
+ yaml = _require_yaml()
483
+ data: dict[str, Any] = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
484
+ specs: list[PluginSpec] = []
485
+ for entry in data.get("plugins", []):
486
+ if isinstance(entry, str):
487
+ specs.append(PluginSpec(name=entry))
488
+ elif isinstance(entry, dict):
489
+ specs.append(
490
+ PluginSpec(
491
+ name=entry.get("name", ""),
492
+ source=entry.get("source", "git"),
493
+ ref=entry.get("ref", "main"),
494
+ repo=entry.get("repo", ""),
495
+ wasm_checksums=dict(entry.get("wasm_checksums") or {}),
496
+ dep_hashes=dict(entry.get("dep_hashes") or {}),
497
+ allowed_dependencies=list(entry.get("allowed_dependencies") or []),
498
+ )
499
+ )
500
+ return specs
501
+
502
+
503
+ def save_plugins_file(path: Path, specs: list[PluginSpec]) -> None:
504
+ """Write *specs* to *path* as a ``intentumdiff_plugins.yaml`` file."""
505
+ yaml = _require_yaml()
506
+ entries: list[dict[str, Any]] = []
507
+ for s in specs:
508
+ entry: dict[str, Any] = {
509
+ "name": s.name,
510
+ "source": s.source,
511
+ "ref": s.ref,
512
+ }
513
+ if s.repo:
514
+ entry["repo"] = s.repo
515
+ if s.wasm_checksums:
516
+ entry["wasm_checksums"] = dict(s.wasm_checksums)
517
+ if s.dep_hashes:
518
+ entry["dep_hashes"] = dict(s.dep_hashes)
519
+ if s.allowed_dependencies:
520
+ entry["allowed_dependencies"] = list(s.allowed_dependencies)
521
+ entries.append(entry)
522
+
523
+ header = (
524
+ "# intentumdiff_plugins.yaml - plugin dependencies for IntentumDiff\n"
525
+ "# Install all plugins: intentumdiff plugins install\n"
526
+ "# Add/update a plugin: intentumdiff plugins add <name>\n"
527
+ "# Remove a plugin: intentumdiff plugins remove <name>\n"
528
+ "# Checksums are verified on every install. Do not edit them manually.\n\n"
529
+ )
530
+ body = yaml.dump(
531
+ {"version": 1, "plugins": entries},
532
+ default_flow_style=False,
533
+ sort_keys=False,
534
+ allow_unicode=True,
535
+ )
536
+ path.write_text(header + body, encoding="utf-8")
537
+
538
+
539
+ # ---------------------------------------------------------------------------
540
+ # Wasm security checks
541
+ # ---------------------------------------------------------------------------
542
+
543
+
544
+ def compute_wasm_checksums(package_name: str) -> dict[str, str]:
545
+ """
546
+ Find all ``.wasm`` files installed by *package_name* and return their
547
+ SHA-256 hex digests keyed by filename.
548
+
549
+ Returns an empty dict if the package is not installed or has no ``.wasm``
550
+ files.
551
+ """
552
+ try:
553
+ dist = _meta.distribution(package_name)
554
+ except _meta.PackageNotFoundError:
555
+ return {}
556
+
557
+ checksums: dict[str, str] = {}
558
+ for record in dist.files or []:
559
+ if not str(record).endswith(".wasm"):
560
+ continue
561
+ full_path = Path(str(dist.locate_file(record)))
562
+ if full_path.exists():
563
+ digest = hashlib.sha256(full_path.read_bytes()).hexdigest()
564
+ checksums[full_path.name] = digest
565
+ return checksums
566
+
567
+
568
+ def verify_wasm_checksums(spec: PluginSpec) -> list[str]:
569
+ """
570
+ Verify the SHA-256 of every installed ``.wasm`` file against the expected
571
+ values stored in *spec.wasm_checksums*.
572
+
573
+ Returns a list of human-readable error strings. An empty list means all
574
+ checks passed. A non-empty list must be treated as a security failure —
575
+ **do not load the plugin**.
576
+
577
+ This function is **post-install defence-in-depth**. It detects tampering or
578
+ corruption after the package is already on disk. The primary security
579
+ controls are the pre-install wheel linter and ``--no-deps`` / ``--require-hashes``
580
+ install enforcement in :func:`pip_install`.
581
+ """
582
+ if not spec.wasm_checksums:
583
+ # No stored checksums — caller should warn but not block.
584
+ return []
585
+
586
+ actual = compute_wasm_checksums(spec.package_name)
587
+ if not actual:
588
+ return [
589
+ f"Package '{spec.package_name}' is not installed or contains no .wasm files."
590
+ ]
591
+
592
+ errors: list[str] = []
593
+ for filename, expected_hex in spec.wasm_checksums.items():
594
+ if filename not in actual:
595
+ errors.append(
596
+ f"Expected .wasm file '{filename}' not found in the installed package."
597
+ )
598
+ continue
599
+ got_hex = actual[filename]
600
+ if got_hex != expected_hex.lower():
601
+ errors.append(
602
+ f"Checksum mismatch for '{filename}':\n"
603
+ f" expected: {expected_hex}\n"
604
+ f" actual: {got_hex}\n"
605
+ "The installed binary does not match the recorded checksum — "
606
+ "possible tampering or corrupted download."
607
+ )
608
+
609
+ # Also flag any wasm files that exist but are NOT in the recorded set.
610
+ for filename in actual:
611
+ if filename not in spec.wasm_checksums:
612
+ errors.append(
613
+ f"Unexpected .wasm file '{filename}' found in '{spec.package_name}' "
614
+ "that is not in the recorded checksum set."
615
+ )
616
+
617
+ return errors
618
+
619
+
620
+ def check_wasm_capabilities(wasm_path: Path) -> list[str]:
621
+ """
622
+ Scan a ``.wasm`` binary for unexpected host capability imports.
623
+
624
+ This is a fast byte-scan heuristic (not a full binary parse) that detects
625
+ WASI import strings embedded in the module's import section. Any WASI
626
+ capability other than the expected WIT host-utils interface is flagged.
627
+
628
+ Returns a list of human-readable warning strings (empty = clean).
629
+
630
+ Note: this check catches accidental or malicious inclusion of WASI imports
631
+ at build time. Runtime enforcement is still provided by the wasmtime
632
+ ``WasiConfig()`` empty sandbox — but pre-flight scanning lets us reject
633
+ suspicious binaries before they are ever loaded.
634
+ """
635
+ try:
636
+ raw = wasm_path.read_bytes()
637
+ except OSError as exc:
638
+ return [f"Could not read '{wasm_path.name}': {exc}"]
639
+
640
+ warnings: list[str] = []
641
+ for prefix in _SUSPICIOUS_WASI_PREFIXES:
642
+ if prefix in raw:
643
+ warnings.append(
644
+ f"'{wasm_path.name}' contains a suspicious WASI import: {prefix.decode()!r}. "
645
+ "This plugin may attempt to access host filesystem, network, or I/O resources. "
646
+ "Only install plugins from trusted sources."
647
+ )
648
+ return warnings
649
+
650
+
651
+ def security_check_plugin(
652
+ spec: PluginSpec,
653
+ *,
654
+ check_checksums: bool = True,
655
+ check_capabilities: bool = True,
656
+ ) -> tuple[list[str], list[str]]:
657
+ """
658
+ Run all post-install security checks for *spec*.
659
+
660
+ Returns
661
+ -------
662
+ tuple[list[str], list[str]]
663
+ ``(errors, warnings)`` where errors are checksum failures that must
664
+ block loading, and warnings are capability concerns that should be
665
+ surfaced to the user.
666
+ """
667
+ errors: list[str] = []
668
+ warnings: list[str] = []
669
+
670
+ if check_checksums:
671
+ if not spec.wasm_checksums:
672
+ warnings.append(
673
+ f"No wasm_checksums recorded for '{spec.package_name}'. "
674
+ "Integrity cannot be verified. "
675
+ "Use 'intentumdiff plugins add' to populate checksums from the official registry."
676
+ )
677
+ else:
678
+ errors.extend(verify_wasm_checksums(spec))
679
+
680
+ if check_capabilities:
681
+ try:
682
+ dist = _meta.distribution(spec.package_name)
683
+ except _meta.PackageNotFoundError:
684
+ errors.append(f"Package '{spec.package_name}' not found after installation.")
685
+ return errors, warnings
686
+
687
+ for record in dist.files or []:
688
+ if not str(record).endswith(".wasm"):
689
+ continue
690
+ full_path = Path(str(dist.locate_file(record)))
691
+ if full_path.exists():
692
+ warnings.extend(check_wasm_capabilities(full_path))
693
+
694
+ return errors, warnings
695
+
696
+
697
+ # ---------------------------------------------------------------------------
698
+ # pip wrappers
699
+ # ---------------------------------------------------------------------------
700
+
701
+
702
+ def classify_install_target(install_target: str) -> str:
703
+ """
704
+ Classify *install_target* into one of the following categories.
705
+
706
+ Categories
707
+ ----------
708
+ ``"vcs"``
709
+ A VCS URL such as ``git+https://…`` or ``hg+ssh://…``.
710
+ ``"local"``
711
+ A local path (relative ``./…`` / ``../…`` or absolute ``/…`` / ``C:\\…``).
712
+ ``"direct_url"``
713
+ A direct HTTP/HTTPS/FTP URL.
714
+ ``"pypi"``
715
+ A plain package name or PEP 440 version specifier.
716
+ ``"unknown"``
717
+ Anything that does not match the above patterns.
718
+ """
719
+ import re
720
+
721
+ t = install_target.strip()
722
+ if re.search(r"\s@\s*(?:https?|ftp|file|git\+)://", t, flags=re.IGNORECASE):
723
+ return "direct_url"
724
+ if t.startswith(("git+", "hg+", "svn+", "bzr+")):
725
+ return "vcs"
726
+ if t.startswith(("./", "../", "/")) or (
727
+ len(t) > 2 and t[1] == ":" and t[2] in ("/", "\\")
728
+ ):
729
+ return "local"
730
+ if t.lower().startswith(("http://", "https://", "ftp://")):
731
+ return "direct_url"
732
+ if re.match(r"^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?([<>=!;\[@ ]|$)", t):
733
+ return "pypi"
734
+ return "unknown"
735
+
736
+
737
+ # Wheel entries that are never permitted in plugin packages.
738
+ _BLOCKED_WHEEL_EXTENSIONS: tuple[str, ...] = (
739
+ ".so", # native extension (Linux / macOS)
740
+ ".pyd", # native extension (Windows)
741
+ ".dll", # native extension (Windows)
742
+ )
743
+
744
+
745
+ def _lint_wheel_contents(wheel_path: "Path", *, allow_wasm: bool = True) -> list[str]:
746
+ """
747
+ Scan *wheel_path* for entries that are never permitted in plugin packages.
748
+
749
+ Returns a list of error strings. An empty list means the wheel is clean.
750
+
751
+ Blocked entries
752
+ ---------------
753
+ - ``.pth`` files — inject into ``sys.path`` at interpreter startup.
754
+ - ``sitecustomize.py`` / ``usercustomize.py`` — startup hook injection.
755
+ - Native extensions (``.so``, ``.pyd``, ``.dll``) — arbitrary native code
756
+ outside the Wasm sandbox.
757
+ """
758
+ import zipfile
759
+
760
+ errors: list[str] = []
761
+ try:
762
+ with zipfile.ZipFile(wheel_path, "r") as zf:
763
+ for name in zf.namelist():
764
+ lower = name.lower()
765
+ basename = Path(name).name.lower()
766
+ posix_path = PurePosixPath(name)
767
+ windows_path = PureWindowsPath(name)
768
+ if (
769
+ posix_path.is_absolute()
770
+ or windows_path.is_absolute()
771
+ or windows_path.drive
772
+ or ".." in posix_path.parts
773
+ or ".." in windows_path.parts
774
+ ):
775
+ errors.append(
776
+ f"Wheel '{wheel_path.name}' contains an unsafe archive "
777
+ f"path ({name!r}) — rejected."
778
+ )
779
+ elif lower.endswith(".pth"):
780
+ errors.append(
781
+ f"Wheel '{wheel_path.name}' contains a .pth file "
782
+ f"({name!r}) — rejected. Plugin wheels must be "
783
+ "self-contained and must not inject sys.path entries."
784
+ )
785
+ elif basename in ("sitecustomize.py", "usercustomize.py"):
786
+ errors.append(
787
+ f"Wheel '{wheel_path.name}' contains a startup hook "
788
+ f"({name!r}) — rejected. Plugin wheels must not include "
789
+ "interpreter startup hooks."
790
+ )
791
+ elif lower.endswith(".wasm") and not allow_wasm:
792
+ errors.append(
793
+ f"Wheel '{wheel_path.name}' contains undeclared Wasm "
794
+ f"({name!r}) — rejected. Dependency wheels must not "
795
+ "ship Wasm binaries."
796
+ )
797
+ elif any(lower.endswith(ext) for ext in _BLOCKED_WHEEL_EXTENSIONS):
798
+ errors.append(
799
+ f"Wheel '{wheel_path.name}' contains a native extension "
800
+ f"({name!r}) — rejected. Plugin wheels must not include "
801
+ "native compiled extensions outside of .wasm binaries."
802
+ )
803
+ except (zipfile.BadZipFile, OSError) as exc:
804
+ errors.append(f"Could not inspect wheel '{wheel_path.name}': {exc}")
805
+ return errors
806
+
807
+
808
+ def _dep_hash_requirement_lines(spec: "PluginSpec") -> list[str]:
809
+ return [
810
+ f"{pkg_spec} \\\n --hash={pkg_hash}"
811
+ for pkg_spec, pkg_hash in spec.dep_hashes.items()
812
+ ]
813
+
814
+
815
+ def _write_dep_hash_requirements(spec: "PluginSpec", req_path: "Path") -> None:
816
+ req_path.write_text(
817
+ "\n".join(_dep_hash_requirement_lines(spec)) + "\n",
818
+ encoding="utf-8",
819
+ )
820
+
821
+
822
+ def pip_download_requirements(requirements_file: "Path", dest_dir: "Path") -> int:
823
+ """Download exactly the hash-pinned requirements into *dest_dir*."""
824
+ cmd = [
825
+ sys.executable,
826
+ "-m",
827
+ "pip",
828
+ "download",
829
+ "--no-deps",
830
+ "--require-hashes",
831
+ "--only-binary=:all:",
832
+ "-r",
833
+ str(requirements_file),
834
+ "-d",
835
+ str(dest_dir),
836
+ ]
837
+ return subprocess.run(cmd).returncode # noqa: S603 - fixed pip command, no shell
838
+
839
+
840
+ def _lint_wheelhouse(
841
+ wheel_files: list["Path"],
842
+ spec: "PluginSpec",
843
+ install_target: str | None,
844
+ ) -> list[str]:
845
+ errors: list[str] = []
846
+ main_names = _main_package_names(spec, install_target)
847
+ for wheel in wheel_files:
848
+ errors.extend(
849
+ _lint_wheel_contents(
850
+ wheel,
851
+ allow_wasm=_package_from_wheel(wheel) in main_names,
852
+ )
853
+ )
854
+ return errors
855
+
856
+
857
+ def _find_main_wheel(
858
+ wheel_files: list["Path"],
859
+ spec: "PluginSpec",
860
+ install_target: str | None,
861
+ ) -> "Path | None":
862
+ main_names = _main_package_names(spec, install_target)
863
+ for wheel in wheel_files:
864
+ if _package_from_wheel(wheel) in main_names:
865
+ return wheel
866
+ return None
867
+
868
+
869
+ def pip_install(
870
+ install_target: str,
871
+ spec: "PluginSpec | None" = None,
872
+ *,
873
+ upgrade: bool = False,
874
+ ) -> int:
875
+ """
876
+ Install *install_target* in the current environment.
877
+
878
+ Security policy
879
+ ---------------
880
+ - When *spec.dep_hashes* is **empty** (default): adds ``--no-deps`` so pip
881
+ cannot resolve or install undeclared transitive dependencies. The plugin
882
+ wheel must be fully self-contained.
883
+ - When *spec.dep_hashes* is **non-empty**: downloads the complete
884
+ hash-pinned wheelhouse, lints every wheel, then installs from that local
885
+ wheelhouse with ``--no-index`` and ``--require-hashes``. The main
886
+ package **must** be listed as one of the entries.
887
+
888
+ Returns the pip exit code (0 = success).
889
+ """
890
+ import tempfile
891
+
892
+ cmd = [sys.executable, "-m", "pip", "install"]
893
+ if upgrade:
894
+ cmd.append("--upgrade")
895
+
896
+ if spec is not None and spec.dep_hashes:
897
+ # Validate key format before doing anything with the network.
898
+ hash_errors = _validate_dep_hashes(spec, install_target)
899
+ if hash_errors:
900
+ for msg in hash_errors:
901
+ logger.error("dep_hashes validation error: %s", msg)
902
+ raise ValueError(
903
+ f"dep_hashes for {spec.package_name!r} failed validation:\n"
904
+ + "\n".join(f" - {e}" for e in hash_errors)
905
+ )
906
+
907
+ with tempfile.TemporaryDirectory() as tmp_dir:
908
+ tmp_path = Path(tmp_dir)
909
+ wheelhouse = tmp_path / "wheelhouse"
910
+ wheelhouse.mkdir()
911
+ tmp_req = tmp_path / "requirements.txt"
912
+ _write_dep_hash_requirements(spec, tmp_req)
913
+
914
+ rc = pip_download_requirements(tmp_req, wheelhouse)
915
+ if rc != 0:
916
+ return rc
917
+
918
+ wheel_files = sorted(wheelhouse.glob("*.whl"))
919
+ lint_errors = _lint_wheelhouse(wheel_files, spec, install_target)
920
+ if lint_errors:
921
+ raise ValueError(
922
+ f"dep_hashes for {spec.package_name!r} failed wheel lint:\n"
923
+ + "\n".join(f" - {e}" for e in lint_errors)
924
+ )
925
+ if _find_main_wheel(wheel_files, spec, install_target) is None:
926
+ raise ValueError(
927
+ f"dep_hashes for {spec.package_name!r} did not download "
928
+ "the main plugin wheel."
929
+ )
930
+
931
+ cmd.extend([
932
+ "--no-deps",
933
+ "--require-hashes",
934
+ "--only-binary=:all:",
935
+ "--no-index",
936
+ "--find-links", str(wheelhouse),
937
+ "-r", str(tmp_req),
938
+ ])
939
+ return subprocess.run(cmd).returncode # noqa: S603 - fixed pip command, no shell
940
+ else:
941
+ # Default: self-contained wheel — no undeclared dependencies.
942
+ cmd.extend(["--no-deps", install_target])
943
+ return subprocess.run(cmd).returncode # noqa: S603 - fixed pip command, no shell; install target is operator-selected.
944
+
945
+
946
+ def pip_uninstall(package_name: str) -> int:
947
+ """
948
+ Run ``python -m pip uninstall -y <package_name>`` in the current env.
949
+
950
+ Returns the pip exit code (0 = success).
951
+ """
952
+ cmd = [sys.executable, "-m", "pip", "uninstall", "-y", package_name]
953
+ return subprocess.run(cmd).returncode # noqa: S603 - fixed pip command, no shell; package name comes from selected plugin spec.
954
+
955
+
956
+ def pip_download(install_target: str, dest_dir: str, *, only_binary: bool = True) -> int:
957
+ """
958
+ Run ``python -m pip download --no-deps [--only-binary=:all:] <install_target> -d <dest_dir>``.
959
+
960
+ Downloads the wheel (or sdist) to *dest_dir* without installing anything.
961
+ When *only_binary* is ``True`` (default), ``--only-binary=:all:`` is added
962
+ so pip refuses to build from source.
963
+ Returns the pip exit code (0 = success).
964
+ """
965
+ cmd = [
966
+ sys.executable, "-m", "pip", "download",
967
+ "--no-deps",
968
+ ]
969
+ if only_binary:
970
+ cmd.append("--only-binary=:all:")
971
+ cmd.extend([install_target, "-d", dest_dir])
972
+ return subprocess.run(cmd).returncode # noqa: S603 - fixed pip command, no shell; destination is caller-controlled temp dir.
973
+
974
+
975
+ def inspect_wasm_in_wheel(
976
+ wheel_path: "Path",
977
+ ) -> tuple[dict[str, str], list[str]]:
978
+ """
979
+ Open *wheel_path* as a ZIP archive and inspect every ``.wasm`` entry.
980
+
981
+ Returns
982
+ -------
983
+ tuple[dict[str, str], list[str]]
984
+ ``(checksums, capability_warnings)`` where *checksums* maps wasm
985
+ filename → SHA-256 hex digest and *capability_warnings* is a list of
986
+ human-readable warnings from :func:`check_wasm_capabilities`.
987
+
988
+ The wheel is not installed — no Python code from the plugin is executed.
989
+ """
990
+ import io
991
+ import zipfile
992
+
993
+ checksums: dict[str, str] = {}
994
+ cap_warnings: list[str] = []
995
+
996
+ try:
997
+ with zipfile.ZipFile(wheel_path, "r") as zf:
998
+ for name in zf.namelist():
999
+ if not name.endswith(".wasm"):
1000
+ continue
1001
+ raw = zf.read(name)
1002
+ fname = Path(name).name
1003
+ checksums[fname] = hashlib.sha256(raw).hexdigest()
1004
+ # Run capability scan on the in-memory bytes via a temp Path.
1005
+ import tempfile
1006
+ with tempfile.NamedTemporaryFile(
1007
+ suffix=".wasm", delete=False
1008
+ ) as tmp:
1009
+ tmp.write(raw)
1010
+ tmp_path = Path(tmp.name)
1011
+ try:
1012
+ cap_warnings.extend(check_wasm_capabilities(tmp_path))
1013
+ finally:
1014
+ try:
1015
+ tmp_path.unlink()
1016
+ except OSError:
1017
+ pass
1018
+ except (zipfile.BadZipFile, OSError) as exc:
1019
+ logger.warning("Could not inspect wheel %s: %s", wheel_path.name, exc)
1020
+
1021
+ return checksums, cap_warnings
1022
+
1023
+
1024
+ def pre_install_security_check(
1025
+ install_target: str,
1026
+ spec: "PluginSpec",
1027
+ *,
1028
+ allow_source: bool = False,
1029
+ ) -> tuple[list[str], list[str]]:
1030
+ """
1031
+ Download the plugin wheel and verify its ``.wasm`` contents **before**
1032
+ running ``pip install``.
1033
+
1034
+ Steps
1035
+ -----
1036
+ 1. Classify *install_target*; reject VCS / local / direct-URL sources
1037
+ unless *allow_source* is ``True``.
1038
+ 2. ``pip download --only-binary=:all:`` the wheel to a temporary directory.
1039
+ 3. Open the wheel as a ZIP; extract and hash every ``.wasm`` file.
1040
+ 4. Run the capability scan on each ``.wasm``.
1041
+ 5. If *spec.wasm_checksums* is non-empty, verify the pre-install digests
1042
+ against the expected values.
1043
+
1044
+ Returns ``(errors, warnings)``. A non-empty *errors* list means the
1045
+ download should be refused and ``pip install`` must not be called.
1046
+
1047
+ The temporary download directory is cleaned up before returning.
1048
+ """
1049
+ import tempfile
1050
+
1051
+ errors: list[str] = []
1052
+ warnings: list[str] = []
1053
+ hash_errors = _validate_dep_hashes(spec, install_target)
1054
+ if hash_errors:
1055
+ return hash_errors, warnings
1056
+
1057
+ # ── 0. Classify the install target ────────────────────────────────────────
1058
+ kind = classify_install_target(install_target)
1059
+ if kind in ("vcs", "local", "direct_url"):
1060
+ if not allow_source:
1061
+ errors.append(
1062
+ f"Install target '{install_target}' is a {kind} source, which "
1063
+ "cannot be verified before installation. Pass "
1064
+ "--allow-source-plugin to override (not recommended for "
1065
+ "production)."
1066
+ )
1067
+ return errors, warnings
1068
+ warnings.append(
1069
+ f"Installing from {kind} source '{install_target}' — "
1070
+ "pre-install wasm scan is limited for source distributions."
1071
+ )
1072
+
1073
+ with tempfile.TemporaryDirectory() as tmp_dir:
1074
+ # ── 1. Download ────────────────────────────────────────────────────
1075
+ # Use --only-binary=:all: for PyPI so pip refuses to build from source.
1076
+ tmp_path = Path(tmp_dir)
1077
+ if spec.dep_hashes:
1078
+ req_path = tmp_path / "requirements.txt"
1079
+ _write_dep_hash_requirements(spec, req_path)
1080
+ rc = pip_download_requirements(req_path, tmp_path)
1081
+ else:
1082
+ use_binary_only = kind == "pypi"
1083
+ rc = pip_download(install_target, tmp_dir, only_binary=use_binary_only)
1084
+ if rc != 0:
1085
+ errors.append(
1086
+ f"pip download failed (exit {rc}) — refusing to install "
1087
+ "without pre-install verification."
1088
+ )
1089
+ return errors, warnings
1090
+
1091
+ wheel_files = sorted(Path(tmp_dir).glob("*.whl"))
1092
+ if not wheel_files:
1093
+ errors.append(
1094
+ "No wheel found in download output — refusing to install "
1095
+ "a source distribution without pre-install verification. "
1096
+ "Use --allow-source-plugin to override."
1097
+ )
1098
+ return errors, warnings
1099
+
1100
+ wheel = wheel_files[0]
1101
+ if spec.dep_hashes:
1102
+ lint_errors = _lint_wheelhouse(wheel_files, spec, install_target)
1103
+ main_wheel = _find_main_wheel(wheel_files, spec, install_target)
1104
+ if main_wheel is None:
1105
+ errors.append(
1106
+ "No wheel for the main plugin package was found in the "
1107
+ "hash-pinned wheelhouse."
1108
+ )
1109
+ return errors, warnings
1110
+ wheel = main_wheel
1111
+ else:
1112
+ lint_errors = _lint_wheel_contents(wheel)
1113
+
1114
+ # ── 1b. Wheel content linter ───────────────────────────────────────
1115
+ errors.extend(lint_errors)
1116
+ if lint_errors:
1117
+ return errors, warnings
1118
+
1119
+ pre_checksums, cap_warnings = inspect_wasm_in_wheel(wheel)
1120
+ warnings.extend(cap_warnings)
1121
+
1122
+ if not pre_checksums:
1123
+ if spec.wasm_checksums:
1124
+ # Registry declared expected .wasm files that are absent — fail closed.
1125
+ errors.append(
1126
+ f"No .wasm files found in {wheel.name} but "
1127
+ f"{len(spec.wasm_checksums)} checksum(s) are expected "
1128
+ f"({', '.join(spec.wasm_checksums.keys())}). "
1129
+ "The wheel does not match the registry record — "
1130
+ "possible substitution or wrong version."
1131
+ )
1132
+ else:
1133
+ warnings.append(
1134
+ f"No .wasm files found in {wheel.name} — "
1135
+ "pre-install checksum verification skipped."
1136
+ )
1137
+ elif spec.wasm_checksums:
1138
+ # Verify pre-download digests against expected values.
1139
+ for fname, expected_hex in spec.wasm_checksums.items():
1140
+ if fname not in pre_checksums:
1141
+ errors.append(
1142
+ f"Expected .wasm file '{fname}' not found in the "
1143
+ f"downloaded wheel '{wheel.name}'."
1144
+ )
1145
+ continue
1146
+ if pre_checksums[fname] != expected_hex.lower():
1147
+ errors.append(
1148
+ f"Pre-install checksum mismatch for '{fname}':\n"
1149
+ f" expected: {expected_hex}\n"
1150
+ f" in wheel: {pre_checksums[fname]}\n"
1151
+ "The downloaded binary does not match the recorded "
1152
+ "checksum — possible tampering or wrong version."
1153
+ )
1154
+
1155
+ return errors, warnings