Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

engine component manifest schema 2: archs, min_driver, build_id, signature hook; start hashes every file; packager takes nested files

Niko1221480cfc5f3b47
diff --git a/packaging/ENGINE-COMPONENT.md b/packaging/ENGINE-COMPONENT.md
new file mode 100644
index 000000000..84399aba7
--- /dev/null
+++ b/packaging/ENGINE-COMPONENT.md
@@ -0,0 +1,88 @@
+# Engine component manifest (schema 2)
+
+One format for every engine package: Windows CUDA 13 and 12, Windows HIP, Linux CUDA, Linux HIP, Linux SYCL and macOS
+Metal. Control (`strata_control/engine_component.py`) reads it, checks it, and only then starts the engine.
+`packaging/package_engine.py` writes it. Packages are local and unsigned for now; publishing and signing are S6.
+
+## Folder
+
+ <components>/engine/<version>-<platform>-<backend>/
+ engine-component.json
+ strata | strata.exe the entrypoint
+ lib*.so* | *.dll | *.dylib the GPU runtime libraries it loads from beside itself
+ BUILD.json LICENSE* optional records
+ rocm/** strata-vision.exe ... anything else the build needs, listed in the manifest like the rest
+
+`<components>` is `%LOCALAPPDATA%\Strata\components`, `$XDG_DATA_HOME/strata/components` or `STRATA_COMPONENTS_DIR`.
+A package folder is immutable: a new build is a new folder.
+
+## `engine-component.json`
+
+| field | type | meaning |
+|---|---|---|
+| `schema_version` | 2 | schema 1 packages (no `archs`, `min_driver`, `build_id`, `signature`; `cuda_archs` instead of `archs`) still load |
+| `id`, `name` | `"strata-engine"` | the component name; anything else is refused |
+| `version` | string | the engine release, e.g. `0.1.45`; the newest compatible version wins |
+| `platform` | string | `windows-x86_64`, `linux-x86_64`, `macos-arm64` (must match this PC) |
+| `backend` | string | `cuda`, `hip`, `sycl`, `metal`, `cpu`; must be a combination `BACKEND_MATRIX` commits to, and the one this PC's GPU needs |
+| `archs` | list of strings | what the build contains. CUDA: `sm_86` (machine code for that card), `compute_89` (PTX, runs on that generation or newer). HIP: `gfx1201`. SYCL and Metal: a descriptive tag (`intel-arc`, `apple-gpu`). Required for every non-`cpu` backend. Enforced for CUDA against `nvidia-smi` compute capability; recorded for the others |
+| `min_driver` | `{vendor: version}` | the oldest driver the build runs on, e.g. `{"nvidia": "580.65"}`. Enforced for NVIDIA where `nvidia-smi` answers; an unreadable driver is not a refusal |
+| `build_id` | string | which engine build this is: source commit and toolkit, e.g. `be885026f96a-cuda13.0`. Required |
+| `min_runtime` | string, optional | the oldest Control that may start it |
+| `entrypoint` | string | relative path of the binary; must be in `files` |
+| `files` | list | `{path, sha256, bytes}` for **every** file of the package except the manifest; paths are plain relative POSIX paths that stay inside the folder; no duplicates |
+| `notes` | string, optional | free text |
+| `signature` | `null` or `{alg, key_id, value}` | see below |
+
+Example (shortened):
+
+```json
+{"schema_version": 2, "id": "strata-engine", "name": "strata-engine", "version": "0.1.45",
+ "platform": "linux-x86_64", "backend": "cuda", "archs": ["sm_86"], "min_driver": {"nvidia": "580.65"},
+ "build_id": "be885026f96a-cuda13.0", "entrypoint": "strata",
+ "files": [{"path": "strata", "sha256": "<64 hex>", "bytes": 191000000}], "signature": null}
+```
+
+## What Control checks before a start
+
+In this order, each refusal names the cause; none of them starts anything and none of them downloads anything:
+
+1. the manifest parses strictly (types, schema, paths, archs, driver, signature shape);
+2. the platform and backend are this PC's;
+3. `min_runtime`, CUDA archs vs. the card, `min_driver` vs. the driver;
+4. the **signature policy** (below);
+5. **every file** exists, is a regular file inside the folder (no symlinks), has the listed size, **and matches its SHA-256**
+ (a start hashes the whole package; the listing commands `strata components engine` hash only the entrypoint unless given `--full`);
+6. on POSIX the entrypoint is executable.
+
+If a package fails (5) or (4) and no other package fits this PC, the start ends with `EngineIntegrityError`
+(exit code 5): "The engine package failed its integrity check, so it was not started: 0.1.45 linux-x86_64-cuda:
+libcudart.so.13 does not match its recorded SHA-256. Repair or reinstall the engine component from the Terminal". A package
+for another GPU or an older driver is `EngineMissing` with its reason. A tampered newer package never falls back silently
+to nothing: a good older package is used and the tampered one is listed under `problems` in `strata components engine`.
+
+## Signature (S6)
+
+`signature` is `null` today. S6 fills it and registers the verifier:
+
+ engine_component.register_signature_verifier(fn) # fn(payload: bytes, signature: dict, component) -> None, raises if bad
+ engine_component.signing_payload(manifest_dict) # canonical bytes the signature covers
+
+The payload is the manifest without its `signature` member, as canonical JSON (sorted keys, `,` and `:` separators,
+UTF-8). It contains every file hash, so one signature covers the whole package. Policy:
+
+* unsigned package: loads, reported `unsigned`;
+* signed, no verifier registered: loads, reported `unverified` (never "verified");
+* signed, verifier registered: must verify, otherwise refused;
+* `STRATA_REQUIRE_SIGNED_COMPONENTS=1`: unsigned and unverifiable packages are refused (the setting S6 turns on for released builds).
+
+## Building a package
+
+ python packaging/package_engine.py --src <build folder> --backend cuda --version 0.1.45 \
+ --out <components>/engine --arch sm_86 --arch compute_89 --min-driver nvidia=580.65 \
+ [--build-id <id>] [--platform linux-x86_64] [--include 'rocm/**' --include strata-vision.exe | --tree]
+ python packaging/package_engine.py --verify <package folder> # full hash check
+
+Without `--include`/`--tree` it takes the entrypoint, the libraries beside it, `BUILD.json` and `LICENSE*`. The build id
+defaults to the checkout's commit (`-dirty` when the tree has changes). It prints the size, file count and the SHA-256 of
+the manifest file (which holds every file's hash), used as the package's digest in notes.
diff --git a/packaging/README.md b/packaging/README.md
index af86ac8b4..3385eafba 100644
--- a/packaging/README.md
+++ b/packaging/README.md
@@ -90,14 +90,16 @@ Terminal) attaches to the same instance.
(`%LOCALAPPDATA%\Strata\components`, `$XDG_DATA_HOME/strata/components`, or `STRATA_COMPONENTS_DIR`):
components/engine/<version>-<platform>-<backend>/
- engine-component.json schema_version, id "strata-engine", version, platform, backend, entrypoint,
- cuda_archs (optional), min_runtime (optional), files [{path, sha256, bytes}]
+ engine-component.json schema 2: id/name "strata-engine", version, platform, backend, archs, min_driver,
+ build_id, min_runtime (optional), entrypoint, files [{path, sha256, bytes}],
+ signature (null until S6); full table and the checks in ENGINE-COMPONENT.md
strata[.exe] *.dll | *.so the binary and the GPU runtime libraries beside it
A run config names it as `"exe": "component:strata-engine"`; at start `strata_control/engine_component.py` picks the package
for this PC (platform, then the backend its GPU needs: nvidia-smi / rocminfo / sycl-ls, or `STRATA_ENGINE_BACKEND`; CUDA
-architectures and `min_runtime` are checked; the newest version wins), checks every file's size and the entrypoint's
-SHA-256 (`strata components engine --full` hashes everything) and puts the package folder first on the library path.
+architectures, `min_driver` and `min_runtime` are checked; the newest version wins), checks every file's size and
+SHA-256 (a start hashes the whole package; a mismatch is `EngineIntegrityError` and nothing starts) and puts the package
+folder first on the library path.
Nothing matching is `EngineMissing`: exit 5, "No engine for this PC was found in ... The app never downloads an engine
while it starts or serves", and no fetch. `packaging/package_engine.py` makes a local package from a build folder.
diff --git a/packaging/package_engine.py b/packaging/package_engine.py
index d29704289..3152472b7 100644
--- a/packaging/package_engine.py
+++ b/packaging/package_engine.py
@@ -2,24 +2,32 @@
"""Make a local, unpublished engine package for the component folder (strata_control/engine_component.py).
python packaging/package_engine.py --src <folder with strata[.exe] and its libraries> --backend cuda \
- --version 0.1.45 [--platform linux-x86_64] --out <components>/engine [--cuda-arch sm_86 ...]
+ --version 0.1.45 --out <components>/engine --arch sm_86 --arch compute_89 \
+ --min-driver nvidia=580.65 [--build-id <id>] [--platform linux-x86_64] [--tree] [--include GLOB ...]
-The result is one folder `<out>/<version>-<platform>-<backend>/` holding the engine binary, the shared libraries
-next to it, BUILD.json when the source has one, and `engine-component.json` (every file's SHA-256 and size). It
-is the thing the app resolves; it is not signed, not published, and nothing here uploads it. Publishing and
-signing are stream S6.
+ python packaging/package_engine.py --verify <components>/engine/<package folder> # full hash check, exit 0 / 1
-Files taken from --src: the entrypoint, every `*.dll` / `*.so` / `*.so.*` / `*.dylib` in the same folder (the GPU
-runtime libraries the engine loads from beside itself), `BUILD.json`, and `LICENSE*` when present. Nothing else.
+The result is one folder `<out>/<version>-<platform>-<backend>/` holding the engine binary, the libraries it loads,
+BUILD.json when the source has one, and `engine-component.json` (schema 2: every file's SHA-256 and size, the arch
+list, the oldest driver, the engine build id, and an empty `signature` for S6). It is the thing Control resolves,
+checks and starts; it is not signed, not published, and nothing here uploads it. Signing is stream S6
+(`engine_component.register_signature_verifier`); `--sign-with` is deliberately absent until then.
+
+Files taken from --src, by default: the entrypoint, every `*.dll` / `*.so` / `*.so.*` / `*.dylib` / `*.metallib`
+beside it, `BUILD.json`, and `LICENSE*`. `--include GLOB` (repeatable, relative to --src, `**` allowed) adds more, for
+example `strata-vision.exe`, `strata-device.exe` or `rocm/**`. `--tree` takes every regular file under --src (the HIP
+package ships a `rocm/` tree of kernels). Symlinks are never followed or copied.
"""
from __future__ import annotations
import argparse
+import fnmatch
import hashlib
import json
-import platform
+import os
import shutil
+import subprocess
import sys
from pathlib import Path
@@ -40,14 +48,45 @@ def sha256(path: Path) -> str:
def wanted(path: Path) -> bool:
name = path.name.lower()
- return (name.endswith((".dll", ".so", ".dylib")) or ".so." in name or name == "build.json"
+ return (name.endswith((".dll", ".so", ".dylib", ".metallib")) or ".so." in name or name == "build.json"
or name.startswith("license"))
+def git_build_id(repo: Path = ROOT) -> str:
+ """The source commit of the engine build, `-dirty` when the tree had changes. `unknown` outside a checkout."""
+ try:
+ head = subprocess.run(["git", "-C", str(repo), "rev-parse", "--short=12", "HEAD"], capture_output=True,
+ text=True, timeout=20).stdout.strip()
+ dirty = subprocess.run(["git", "-C", str(repo), "status", "--porcelain", "--untracked-files=no"],
+ capture_output=True, text=True, timeout=60).stdout.strip()
+ except (OSError, subprocess.SubprocessError):
+ return "unknown"
+ return (head + ("-dirty" if dirty else "")) if head else "unknown"
+
+
+def select(src: Path, entrypoint: str, *, tree: bool, include: list[str]) -> list[str]:
+ """Relative POSIX paths to package, entrypoint first, the rest sorted."""
+ chosen: set[str] = set()
+ for path in sorted(src.rglob("*") if (tree or include) else src.iterdir()):
+ if path.is_symlink() or not path.is_file():
+ continue
+ rel = path.relative_to(src).as_posix()
+ if rel == ec.MANIFEST:
+ continue
+ top_level = "/" not in rel
+ if tree or (top_level and wanted(path)) or any(fnmatch.fnmatch(rel, pattern) for pattern in include):
+ chosen.add(rel)
+ chosen.discard(entrypoint)
+ return [entrypoint] + sorted(chosen)
+
+
def build(src: Path, backend: str, version: str, target: str, out: Path, *, entry: str | None = None,
- cuda_archs: tuple[str, ...] = (), min_runtime: str | None = None, notes: str = "") -> Path:
+ archs: tuple[str, ...] = (), min_driver: dict | None = None, build_id: str | None = None,
+ min_runtime: str | None = None, notes: str = "", tree: bool = False, include: list[str] | None = None) -> Path:
if backend not in BACKEND_MATRIX:
raise SystemExit(f"unknown backend {backend!r}")
+ if backend != "cpu" and not archs:
+ raise SystemExit(f"a {backend} package needs at least one --arch (sm_86, gfx1201, ...)")
entrypoint = entry or ("strata.exe" if target.startswith("windows") else "strata")
if not (src / entrypoint).is_file():
raise SystemExit(f"{src / entrypoint} does not exist")
@@ -59,20 +98,23 @@ def build(src: Path, backend: str, version: str, target: str, out: Path, *, entr
shutil.rmtree(staging)
staging.mkdir(parents=True)
try:
- names = [entrypoint] + sorted(p.name for p in src.iterdir() if p.is_file() and p.name != entrypoint and wanted(p))
files = []
- for name in names:
- shutil.copy2(src / name, staging / name)
- files.append({"path": name, "sha256": sha256(staging / name), "bytes": (staging / name).stat().st_size})
- manifest = {"schema_version": ec.SCHEMA_VERSION, "id": ec.COMPONENT_ID, "version": version,
- "platform": target, "backend": backend, "entrypoint": entrypoint, "files": files}
+ for rel in select(src, entrypoint, tree=tree, include=include or []):
+ destination = staging / rel
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(src / rel, destination)
+ files.append({"path": rel, "sha256": sha256(destination), "bytes": destination.stat().st_size})
+ manifest = {"schema_version": ec.SCHEMA_VERSION, "id": ec.COMPONENT_ID, "name": ec.COMPONENT_ID,
+ "version": version, "platform": target, "backend": backend, "archs": list(archs),
+ "min_driver": dict(min_driver or {}), "build_id": build_id or git_build_id(),
+ "entrypoint": entrypoint, "files": files, "signature": None}
if min_runtime:
manifest["min_runtime"] = min_runtime
- if cuda_archs:
- manifest["cuda_archs"] = list(cuda_archs)
if notes:
manifest["notes"] = notes
(staging / ec.MANIFEST).write_text(json.dumps(manifest, indent=1) + "\n", encoding="utf-8")
+ if os.name != "nt":
+ (staging / entrypoint).chmod(0o755)
ec.verify(ec.read_manifest(staging), full=True)
staging.rename(folder)
except BaseException:
@@ -81,23 +123,55 @@ def build(src: Path, backend: str, version: str, target: str, out: Path, *, entr
return folder
+def package_sha256(folder: Path) -> str:
+ """One digest for the whole package: SHA-256 of the manifest file (it holds every file's hash)."""
+ return sha256(folder / ec.MANIFEST)
+
+
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- ap.add_argument("--src", required=True, type=Path)
- ap.add_argument("--backend", required=True, choices=sorted(BACKEND_MATRIX))
- ap.add_argument("--version", required=True)
+ ap.add_argument("--verify", type=Path, metavar="FOLDER", help="hash-check an existing package and exit")
+ ap.add_argument("--src", type=Path)
+ ap.add_argument("--backend", choices=sorted(BACKEND_MATRIX))
+ ap.add_argument("--version")
ap.add_argument("--platform", default=None, help="default: this machine")
- ap.add_argument("--out", required=True, type=Path, help="the component folder's engine/ directory")
+ ap.add_argument("--out", type=Path, help="the component folder's engine/ directory")
ap.add_argument("--entrypoint", default=None)
- ap.add_argument("--cuda-arch", action="append", default=[], help="e.g. sm_86; repeat for several")
+ ap.add_argument("--arch", "--cuda-arch", dest="arch", action="append", default=[],
+ help="sm_86 (code for that card), compute_89 (PTX), gfx1201, ...; repeat for several")
+ ap.add_argument("--min-driver", action="append", default=[], metavar="VENDOR=VERSION",
+ help="the oldest driver, e.g. nvidia=580.65; repeat for several vendors")
+ ap.add_argument("--build-id", default=None, help="default: the source commit of this checkout")
ap.add_argument("--min-runtime", default=None)
ap.add_argument("--notes", default="")
+ ap.add_argument("--tree", action="store_true", help="every regular file under --src, recursively")
+ ap.add_argument("--include", action="append", default=[], metavar="GLOB", help="more files, relative to --src")
a = ap.parse_args(argv)
+ if a.verify:
+ try:
+ component = ec.read_manifest(a.verify)
+ ec.verify(component, full=True)
+ except ec.ComponentProblem as exc:
+ print(f"{a.verify}: REFUSED: {exc}")
+ return 1
+ print(f"{a.verify}: ok ({len(component.files)} files, manifest sha256 {package_sha256(a.verify)})")
+ return 0
+ for needed in ("src", "backend", "version", "out"):
+ if getattr(a, needed) is None:
+ ap.error(f"--{needed} is required")
+ drivers = {}
+ for item in a.min_driver:
+ vendor, _, version = item.partition("=")
+ if not vendor or not version:
+ ap.error(f"--min-driver {item!r} is not VENDOR=VERSION")
+ drivers[vendor] = version
a.out.mkdir(parents=True, exist_ok=True)
folder = build(a.src, a.backend, a.version, a.platform or host_platform(), a.out, entry=a.entrypoint,
- cuda_archs=tuple(a.cuda_arch), min_runtime=a.min_runtime, notes=a.notes)
- total = sum(p.stat().st_size for p in folder.iterdir())
- print(f"{folder} ({total / (1 << 20):.1f} MiB, {len(list(folder.iterdir()))} files)")
+ archs=tuple(a.arch), min_driver=drivers, build_id=a.build_id, min_runtime=a.min_runtime,
+ notes=a.notes, tree=a.tree, include=a.include)
+ entries = [p for p in folder.rglob("*") if p.is_file()]
+ total = sum(p.stat().st_size for p in entries)
+ print(f"{folder} ({total / (1 << 20):.1f} MiB, {len(entries)} files, manifest sha256 {package_sha256(folder)})")
return 0
diff --git a/strata_control/doctor.py b/strata_control/doctor.py
index 1030be84a..1538796c3 100644
--- a/strata_control/doctor.py
+++ b/strata_control/doctor.py
@@ -30,7 +30,7 @@ def _location(raw: str, cfg: dict, config_path: Path) -> Path:
from strata_control import engine_component
if engine_component.is_reference(raw):
try:
- return Path(engine_component.expand(raw, cfg))
+ return Path(engine_component.expand(raw, cfg, full=False))
except engine_component.EngineMissing:
return engine_component.engine_dir() / "(no engine for this PC)" # reported as missing
value = Path(raw).expanduser()
diff --git a/strata_control/engine_component.py b/strata_control/engine_component.py
index d5eeabfff..aaf28f4f5 100644
--- a/strata_control/engine_component.py
+++ b/strata_control/engine_component.py
@@ -13,21 +13,25 @@ Layout (``components_dir()``)::
*.dll | *.so the GPU runtime libraries, hashed in the manifest too
BUILD.json optional, the engine's own build record
-Manifest (``engine-component.json``)::
+Manifest (``engine-component.json``, schema 2; schema 1 packages still load). packaging/README.md has the full table::
- {"schema_version": 1, "id": "strata-engine", "version": "0.1.45", "platform": "windows-x86_64",
- "backend": "cuda", "entrypoint": "strata.exe", "min_runtime": "0.1.45",
- "cuda_archs": ["sm_86"], # optional: GPU architectures the build contains
- "files": [{"path": "strata.exe", "sha256": "...", "bytes": 1}, ...]}
+ {"schema_version": 2, "id": "strata-engine", "name": "strata-engine", "version": "0.1.45",
+ "platform": "linux-x86_64", "backend": "cuda", "archs": ["sm_86", "compute_89"],
+ "min_driver": {"nvidia": "580.65"}, "build_id": "be885026f9-cuda13.0", "min_runtime": "0.1.45",
+ "entrypoint": "strata", "files": [{"path": "strata", "sha256": "...", "bytes": 1}, ...],
+ "signature": null} # S6 fills it; verify_signature() is the hook
Checks, in order, and each one names what failed:
* the manifest parses strictly; file paths are relative, plain, and stay inside the component folder;
* the platform and backend are combinations the project commits to (`components.BACKEND_MATRIX`);
* the backend is the one this machine's GPU needs (detected, or asked for);
-* every listed file exists with the listed size (always, it is cheap), and the entrypoint's SHA-256 matches;
- `verify(full=True)` hashes every file (a few hundred MB of libraries: used by Repair and by tests);
-* the runtime that is asking is new enough for `min_runtime`.
+* the signature (none yet; a verifier registered by S6 is called, and `STRATA_REQUIRE_SIGNED_COMPONENTS=1` refuses
+ an unsigned or unverifiable package);
+* every listed file exists with the listed size, and every file's SHA-256 matches (`verify(full=True)`, which is what
+ a start does; the quick listing/status path hashes only the entrypoint);
+* the runtime that is asking is new enough for `min_runtime`, and the GPU driver (when it can be read) for
+ `min_driver`. A package that fails an integrity check is `EngineIntegrityError`: nothing is started.
Nothing here imports anything outside the standard library and `strata_control`.
"""
@@ -40,17 +44,20 @@ import os
import re
import shutil
import subprocess
+from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath, PureWindowsPath
from strata_control import acquisition
from strata_control.targets import BACKEND_MATRIX, backend_supported, host_platform
-SCHEMA_VERSION = 1
+SCHEMA_VERSION = 2
+READABLE_SCHEMAS = (1, 2) # schema 1 (S3's first packages: no archs/min_driver/build_id/signature) still loads
MANIFEST = "engine-component.json"
COMPONENT_ID = "strata-engine"
ENV_DIR = "STRATA_COMPONENTS_DIR"
ENV_BACKEND = "STRATA_ENGINE_BACKEND"
+ENV_REQUIRE_SIGNED = "STRATA_REQUIRE_SIGNED_COMPONENTS"
#: the version of the control/runtime that is asking; the app reads it from VERSION when it has one.
RUNTIME_VERSION_FILE = Path(__file__).resolve().parents[1] / "VERSION"
@@ -76,10 +83,32 @@ class EngineMissing(acquisition.AcquisitionRefused):
self.command = "strata install"
+class EngineIntegrityError(EngineMissing):
+ """A package is installed but is not what its manifest says (a changed or missing file, a bad signature). Nothing
+ was started. The message names the file; the fix is to repair or reinstall the component, never to run it anyway."""
+
+ code = "engine_component_integrity"
+
+ def __init__(self, reason: str, root: Path | None = None, *, problems: list[dict] | None = None):
+ self.reason = reason
+ self.root = root
+ self.problems = problems or []
+ RuntimeError.__init__(
+ self,
+ f"The engine package failed its integrity check, so it was not started: {reason}. Repair or reinstall "
+ f"the engine component from the Terminal (`strata install`); the app never downloads one while it runs.")
+ self.what = "the engine component"
+ self.command = "strata install"
+
+
class ComponentProblem(ValueError):
"""One engine package is unusable. The message says why; the caller decides what to do next."""
+class IntegrityProblem(ComponentProblem):
+ """The package's files or signature do not match its manifest (as opposed to a package for another PC)."""
+
+
@dataclass
class EngineComponent:
id: str
@@ -90,18 +119,26 @@ class EngineComponent:
files: tuple[tuple[str, str, int], ...] # (relative path, sha256, bytes)
root: Path
min_runtime: str | None = None
- cuda_archs: tuple[str, ...] = ()
+ archs: tuple[str, ...] = ()
notes: str = ""
+ min_driver: dict = field(default_factory=dict) # {"nvidia": "580.65"}: the oldest driver the build runs on
+ build_id: str = "" # which engine build this is (source commit + toolkit)
+ signature: dict | None = None # S6: {"alg", "key_id", "value"} over signing_payload()
+ raw: dict = field(default_factory=dict, repr=False) # the manifest as read, for the signature check
@property
def exe(self) -> Path:
return self.root / self.entrypoint
+ @property
+ def cuda_archs(self) -> tuple[str, ...]:
+ return tuple(item for item in self.archs if item.startswith(("sm_", "compute_")))
+
def to_dict(self) -> dict:
return {"id": self.id, "version": self.version, "platform": self.platform, "backend": self.backend,
"entrypoint": self.entrypoint, "exe": str(self.exe), "root": str(self.root),
- "min_runtime": self.min_runtime, "cuda_archs": list(self.cuda_archs),
- "file_count": len(self.files), "bytes": sum(item[2] for item in self.files)}
+ "min_runtime": self.min_runtime, "archs": list(self.archs), "min_driver": dict(self.min_driver),
+ "build_id": self.build_id, "signed": bool(self.signature), "file_count": len(self.files), "bytes": sum(item[2] for item in self.files)}
# ----------------------------------------------------------------------------------------------- where
@@ -148,13 +185,16 @@ def read_manifest(folder: Path) -> EngineComponent:
raise ComponentProblem(f"{MANIFEST} is missing") from None
except (OSError, ValueError) as exc:
raise ComponentProblem(f"{MANIFEST} is not valid JSON ({type(exc).__name__})") from None
- if not isinstance(data, dict) or data.get("schema_version") != SCHEMA_VERSION:
+ if not isinstance(data, dict) or data.get("schema_version") not in READABLE_SCHEMAS:
raise ComponentProblem(f"{MANIFEST} has an unsupported schema_version")
- if data.get("id") != COMPONENT_ID:
+ schema = data["schema_version"]
+ if data.get("id") != COMPONENT_ID or data.get("name", COMPONENT_ID) != COMPONENT_ID:
raise ComponentProblem(f"{MANIFEST} is not an engine component (id {data.get('id')!r})")
for key in ("version", "platform", "backend", "entrypoint"):
if not isinstance(data.get(key), str) or not data[key]:
raise ComponentProblem(f"{MANIFEST} has no {key}")
+ if schema >= 2 and (not isinstance(data.get("build_id"), str) or not data["build_id"].strip()):
+ raise ComponentProblem(f"{MANIFEST} has no build_id")
if data["backend"] not in BACKEND_MATRIX:
raise ComponentProblem(f"unknown backend {data['backend']!r}")
files = data.get("files")
@@ -175,13 +215,68 @@ def read_manifest(folder: Path) -> EngineComponent:
entry = _plain_relative(data["entrypoint"])
if entry not in {item[0] for item in parsed}:
raise ComponentProblem(f"the entrypoint {entry} is not in the file list")
- archs = data.get("cuda_archs") or []
- if not isinstance(archs, list) or not all(isinstance(a, str) for a in archs):
- raise ComponentProblem("cuda_archs must be a list of strings")
+ if len({item[0] for item in parsed}) != len(parsed):
+ raise ComponentProblem(f"{MANIFEST} lists a file twice")
+ archs = data.get("archs", data.get("cuda_archs")) or [] # schema 1 called the list cuda_archs
+ if not isinstance(archs, list) or not all(isinstance(a, str) and a for a in archs):
+ raise ComponentProblem("archs must be a list of strings")
+ if schema >= 2 and data["backend"] != "cpu" and not archs:
+ raise ComponentProblem(f"{MANIFEST} lists no archs for a {data['backend']} engine")
+ driver = data.get("min_driver") or {}
+ if not isinstance(driver, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in driver.items()):
+ raise ComponentProblem("min_driver must map a vendor to a version string")
+ signature = data.get("signature")
+ if signature is not None and not (isinstance(signature, dict) and isinstance(signature.get("alg"), str)
+ and isinstance(signature.get("value"), str)):
+ raise ComponentProblem("signature must be null or {alg, key_id, value}")
return EngineComponent(
id=data["id"], version=data["version"], platform=data["platform"], backend=data["backend"],
entrypoint=entry, files=tuple(parsed), root=folder, min_runtime=data.get("min_runtime"),
- cuda_archs=tuple(archs), notes=str(data.get("notes") or ""))
+ archs=tuple(archs), notes=str(data.get("notes") or ""), min_driver=dict(driver),
+ build_id=str(data.get("build_id") or ""), signature=signature, raw=data)
+
+
+# ----------------------------------------------------------------------------------------------- signature (S6)
+
+#: A signature verifier is ``fn(payload: bytes, signature: dict, component) -> None``; it raises
+#: ``IntegrityProblem`` (or any exception) when the signature does not hold. S6 registers one that checks the project's
+#: key; until then there is none, unsigned packages load (unless ``STRATA_REQUIRE_SIGNED_COMPONENTS=1``), and a package
+#: that carries a signature nobody can check is reported as "signature not verified", never as verified.
+_verifier: Callable[[bytes, dict, "EngineComponent"], None] | None = None
+
+
+def register_signature_verifier(fn: Callable[[bytes, dict, "EngineComponent"], None] | None) -> None:
+ global _verifier
+ _verifier = fn
+
+
+def signing_payload(manifest: dict) -> bytes:
+ """The bytes a signature covers: the manifest without its ``signature`` member, as canonical JSON (sorted keys,
+ no spaces, UTF-8). The file hashes are inside it, so one signature covers every file."""
+ body = {key: value for key, value in manifest.items() if key != "signature"}
+ return json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
+
+
+def verify_signature(component: "EngineComponent", environ=None) -> str:
+ """"verified", "unsigned" or "unverified" (signed, no verifier yet). Raises IntegrityProblem for a bad signature,
+ and for an unsigned or unverifiable package when ``STRATA_REQUIRE_SIGNED_COMPONENTS`` is set."""
+ environ = os.environ if environ is None else environ
+ required = environ.get(ENV_REQUIRE_SIGNED, "").strip().lower() in ("1", "true", "yes", "on")
+ if not component.signature:
+ if required:
+ raise IntegrityProblem("the package is not signed and this PC requires signed components")
+ return "unsigned"
+ if _verifier is None:
+ if required:
+ raise IntegrityProblem("the package is signed but this build cannot check signatures yet")
+ return "unverified"
+ try:
+ _verifier(signing_payload(component.raw), component.signature, component)
+ except IntegrityProblem:
+ raise
+ except Exception as exc:
+ raise IntegrityProblem(f"the signature does not verify ({type(exc).__name__}: {exc})") from None
+ return "verified"
def _sha256(path: Path) -> str:
@@ -193,26 +288,27 @@ def _sha256(path: Path) -> str:
def verify(component: EngineComponent, *, full: bool = False) -> None:
- """Raise ComponentProblem unless the files are what the manifest says. `full` hashes every file."""
+ """Raise IntegrityProblem unless the files are what the manifest says. `full` hashes every file; without it only
+ the entrypoint is hashed (sizes are always checked)."""
root = component.root.resolve()
for rel, digest, size in component.files:
target = component.root / rel
try:
info = target.lstat()
except OSError:
- raise ComponentProblem(f"{rel} is missing") from None
+ raise IntegrityProblem(f"{rel} is missing") from None
if target.is_symlink() or not target.is_file():
- raise ComponentProblem(f"{rel} is not a regular file")
+ raise IntegrityProblem(f"{rel} is not a regular file")
try:
target.resolve().relative_to(root)
except ValueError:
- raise ComponentProblem(f"{rel} resolves outside the component folder") from None
+ raise IntegrityProblem(f"{rel} resolves outside the component folder") from None
if info.st_size != size:
- raise ComponentProblem(f"{rel} is {info.st_size} bytes, the manifest says {size}")
+ raise IntegrityProblem(f"{rel} is {info.st_size} bytes, the manifest says {size}")
if (full or rel == component.entrypoint) and _sha256(target) != digest:
- raise ComponentProblem(f"{rel} does not match its recorded SHA-256")
+ raise IntegrityProblem(f"{rel} does not match its recorded SHA-256")
if os.name != "nt" and not os.access(component.exe, os.X_OK):
- raise ComponentProblem(f"{component.entrypoint} is not executable")
+ raise IntegrityProblem(f"{component.entrypoint} is not executable")
def runtime_version() -> str | None:
@@ -253,25 +349,78 @@ def detect_backend(environ=None) -> tuple[str | None, str]:
if backend == "sycl" and "level_zero" not in done.stdout.lower() and "gpu" not in done.stdout.lower():
continue
return backend, command[0]
+ found = _drm_vendor_backend()
+ if found:
+ return found, "sysfs pci vendor"
return None, "no GPU tool answered"
+def _drm_vendor_backend() -> str | None:
+ """Linux without the vendor tools on PATH (a HIP box that runs ROCm from Python wheels has no rocminfo): the PCI
+ vendor of the display adapters decides. NVIDIA 0x10de -> cuda, AMD 0x1002 -> hip, Intel 0x8086 -> sycl, in that
+ order. Read-only sysfs, nothing is run."""
+ if not os.path.isdir("/sys/class/drm"):
+ return None
+ vendors = set()
+ try:
+ for card in sorted(Path("/sys/class/drm").glob("card[0-9]*")):
+ if "-" in card.name:
+ continue
+ try:
+ vendors.add((card / "device" / "vendor").read_text().strip().lower())
+ except OSError:
+ continue
+ except OSError:
+ return None
+ for vendor, backend in (("0x10de", "cuda"), ("0x1002", "hip"), ("0x8086", "sycl")):
+ if vendor in vendors:
+ return backend
+ return None
+
+
def cuda_archs_present(environ=None) -> list[str]:
"""``sm_XX`` for each NVIDIA card nvidia-smi reports; empty when it cannot say."""
+ found = []
+ for line in _smi_query("compute_cap"):
+ match = re.fullmatch(r"(\d+)\.(\d+)", line.strip())
+ if match:
+ found.append(f"sm_{match.group(1)}{match.group(2)}")
+ return found
+
+
+def _smi_query(field_name: str) -> list[str]:
tool = shutil.which("nvidia-smi")
if not tool:
return []
try:
- done = subprocess.run([tool, "--query-gpu=compute_cap", "--format=csv,noheader"], capture_output=True,
+ done = subprocess.run([tool, f"--query-gpu={field_name}", "--format=csv,noheader"], capture_output=True,
timeout=8, text=True, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
except (OSError, subprocess.SubprocessError):
return []
- found = []
- for line in done.stdout.split():
- match = re.fullmatch(r"(\d+)\.(\d+)", line.strip())
- if match:
- found.append(f"sm_{match.group(1)}{match.group(2)}")
- return found
+ return [line.strip() for line in done.stdout.splitlines() if line.strip()] if done.returncode == 0 else []
+
+
+def nvidia_driver_version() -> str | None:
+ """The NVIDIA driver version nvidia-smi reports (the oldest one when several cards disagree); None when unreadable."""
+ versions = _smi_query("driver_version")
+ return min(versions, key=_version_key) if versions else None
+
+
+def arch_covers(archs, present: list[str]) -> bool:
+ """Whether a build with `archs` (``sm_86`` = machine code for that card, ``compute_89`` = PTX that any card of
+ that generation or newer can JIT) can run on at least one of the `present` cards (``sm_XX``)."""
+ cards = {int(item[3:]) for item in present if item.startswith("sm_") and item[3:].isdigit()}
+ if not cards:
+ return True # cannot tell: not a refusal
+ for arch in archs:
+ kind, _, number = arch.partition("_")
+ if not number.isdigit():
+ continue
+ if kind == "sm" and int(number) in cards:
+ return True
+ if kind == "compute" and any(card >= int(number) for card in cards):
+ return True
+ return False
# ----------------------------------------------------------------------------------------------- resolve
@@ -294,7 +443,8 @@ def scan(root: Path | None = None) -> tuple[list[EngineComponent], list[dict]]:
def resolve(root: Path | None = None, *, backend: str | None = None, target: str | None = None,
full: bool = False, runtime: str | None = None) -> EngineComponent:
- """The engine to start on this machine, or `EngineMissing`. Never downloads, never creates the folder."""
+ """The engine to start on this machine, or `EngineMissing` / `EngineIntegrityError`. Never downloads, never creates
+ the folder. `full=True` hashes every file (a start does); the default is the quick check the listings use."""
base = root or components_dir()
target = target or host_platform()
found, problems = scan(base)
@@ -307,8 +457,9 @@ def resolve(root: Path | None = None, *, backend: str | None = None, target: str
if wanted is None:
# no GPU tool answered: only a CPU engine can be started
wanted = "cpu"
- usable, reasons = [], []
+ usable, reasons, broken = [], [], []
archs_here = cuda_archs_present() if wanted == "cuda" else []
+ driver_here = nvidia_driver_version() if wanted == "cuda" else None
have_runtime = runtime if runtime is not None else runtime_version()
for item in found:
label = f"{item.version} {item.platform}-{item.backend}"
@@ -325,19 +476,27 @@ def resolve(root: Path | None = None, *, backend: str | None = None, target: str
if item.min_runtime and have_runtime and _version_key(have_runtime) < _version_key(item.min_runtime):
reasons.append(f"{label} needs control {item.min_runtime} or newer, this is {have_runtime}")
continue
- if item.cuda_archs and archs_here and not set(archs_here) & set(item.cuda_archs):
+ if item.cuda_archs and archs_here and not arch_covers(item.cuda_archs, archs_here):
reasons.append(f"{label} has code for {', '.join(item.cuda_archs)}, this PC's GPU is "
f"{', '.join(archs_here)}")
continue
+ need = item.min_driver.get("nvidia")
+ if need and driver_here and _version_key(driver_here) < _version_key(need):
+ reasons.append(f"{label} needs NVIDIA driver {need} or newer, this PC has {driver_here}")
+ continue
try:
+ verify_signature(item)
verify(item, full=full)
except ComponentProblem as exc:
reasons.append(f"{label}: {exc}")
+ broken.append(f"{label}: {exc}")
continue
usable.append(item)
if not usable:
- raise EngineMissing("; ".join(reasons + [p["folder"] + ": " + p["problem"] for p in problems])
- or "nothing matched", base, problems=problems)
+ everything = reasons + [p["folder"] + ": " + p["problem"] for p in problems]
+ if broken and len(broken) == len(reasons): # every package that fits this PC failed its integrity check
+ raise EngineIntegrityError("; ".join(broken), base, problems=problems)
+ raise EngineMissing("; ".join(everything) or "nothing matched", base, problems=problems)
return max(usable, key=lambda item: _version_key(item.version))
@@ -351,15 +510,16 @@ def is_reference(value: object) -> bool:
return isinstance(value, str) and value.startswith(REFERENCE_PREFIX)
-def expand(value: str, cfg: dict | None = None, *, root: Path | None = None) -> str:
- """The engine path for `value`: unchanged when it is a path, resolved when it is a component reference."""
+def expand(value: str, cfg: dict | None = None, *, root: Path | None = None, full: bool = True) -> str:
+ """The engine path for `value`: unchanged when it is a path, resolved when it is a component reference. This is the
+ start path, so every file's SHA-256 is checked (`full`): a changed file refuses the start instead of running."""
if not is_reference(value):
return value
name = value[len(REFERENCE_PREFIX):]
if name not in ("", COMPONENT_ID):
raise EngineMissing(f"the run config names an unknown component {name!r}", root or components_dir())
backend = (cfg or {}).get("backend")
- return str(resolve(root, backend=backend if backend in BACKEND_MATRIX else None).exe)
+ return str(resolve(root, backend=backend if backend in BACKEND_MATRIX else None, full=full).exe)
def status(root: Path | None = None, *, backend: str | None = None, full: bool = False) -> dict:
diff --git a/tests/terminal/test_engine_manifest.py b/tests/terminal/test_engine_manifest.py
new file mode 100644
index 000000000..f79ece107
--- /dev/null
+++ b/tests/terminal/test_engine_manifest.py
@@ -0,0 +1,259 @@
+"""The engine component manifest (schema 2): its fields, the checks a start makes, the signature hook S6 fills, and
+packaging/package_engine.py round trips. Every folder is a throwaway; no GPU tool is run."""
+
+import contextlib
+import hashlib
+import io
+import json
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from strata_control import components, engine_component as ec
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "packaging"))
+import package_engine # noqa: E402
+
+WINDOWS = os.name == "nt"
+HERE = components.host_platform()
+EXE = "strata.exe" if WINDOWS else "strata"
+LIB = "cudart64_13.dll" if WINDOWS else "libcudart.so.13"
+
+
+def make_source(folder: Path) -> Path:
+ folder.mkdir(parents=True, exist_ok=True)
+ (folder / EXE).write_bytes(b"engine-binary-" * 40)
+ (folder / LIB).write_bytes(b"runtime-library-" * 60)
+ (folder / "BUILD.json").write_text(json.dumps({"version": "0.1.45"}))
+ (folder / "LICENSE.txt").write_text("MIT")
+ (folder / "notes.txt").write_text("not packaged by default")
+ (folder / "rocm" / "bin").mkdir(parents=True, exist_ok=True)
+ (folder / "rocm" / "bin" / "kernel.co").write_bytes(b"kernel" * 100)
+ return folder
+
+
+class Manifest(unittest.TestCase):
+ def setUp(self):
+ self.dir = tempfile.TemporaryDirectory()
+ self.addCleanup(self.dir.cleanup)
+ self.root = Path(self.dir.name)
+ self.src = make_source(self.root / "src")
+ self.out = self.root / "components" / "engine"
+ self.out.mkdir(parents=True)
+
+ def package(self, **kw):
+ args = dict(archs=("sm_86", "compute_89"), min_driver={"nvidia": "580.65"}, build_id="abc123-cuda13.0")
+ args.update(kw)
+ return package_engine.build(self.src, "cuda", "0.1.45", HERE, self.out, **args)
+
+ def test_the_packager_writes_every_field_the_plan_asks_for(self):
+ folder = self.package()
+ data = json.loads((folder / ec.MANIFEST).read_text())
+ self.assertEqual(data["schema_version"], 2)
+ self.assertEqual((data["id"], data["name"], data["version"]), ("strata-engine", "strata-engine", "0.1.45"))
+ self.assertEqual((data["platform"], data["backend"]), (HERE, "cuda"))
+ self.assertEqual(data["archs"], ["sm_86", "compute_89"])
+ self.assertEqual(data["min_driver"], {"nvidia": "580.65"})
+ self.assertEqual(data["build_id"], "abc123-cuda13.0")
+ self.assertIn("signature", data)
+ self.assertIsNone(data["signature"])
+ names = {item["path"] for item in data["files"]}
+ self.assertEqual(names, {EXE, LIB, "BUILD.json", "LICENSE.txt"}) # notes.txt and rocm/ need --include / --tree
+ for item in data["files"]:
+ body = (folder / item["path"]).read_bytes()
+ self.assertEqual((item["sha256"], item["bytes"]), (hashlib.sha256(body).hexdigest(), len(body)))
+ self.assertEqual(data["entrypoint"], EXE)
+ component = ec.read_manifest(folder)
+ self.assertEqual((component.build_id, component.archs, component.min_driver),
+ ("abc123-cuda13.0", ("sm_86", "compute_89"), {"nvidia": "580.65"}))
+ ec.verify(component, full=True)
+
+ def test_include_and_tree_take_nested_files(self):
+ with_include = self.package(include=["rocm/**"])
+ self.assertIn("rocm/bin/kernel.co", {f[0] for f in ec.read_manifest(with_include).files})
+ self.assertNotIn("notes.txt", {f[0] for f in ec.read_manifest(with_include).files})
+ every = self.out / "tree"
+ every.mkdir()
+ folder = package_engine.build(self.src, "cuda", "9.9", HERE, every, archs=("sm_86",), tree=True, build_id="x")
+ self.assertIn("notes.txt", {f[0] for f in ec.read_manifest(folder).files})
+ self.assertEqual(ec.read_manifest(folder).files[0][0], EXE)
+
+ def test_symlinks_are_never_packaged(self):
+ if WINDOWS:
+ self.skipTest("POSIX symlinks")
+ os.symlink("/etc/passwd", self.src / "link.so")
+ folder = self.package()
+ self.assertNotIn("link.so", {f[0] for f in ec.read_manifest(folder).files})
+
+ def test_a_gpu_package_without_archs_is_refused_by_the_packager(self):
+ with self.assertRaises(SystemExit):
+ self.package(archs=())
+
+ def test_schema_2_needs_build_id_and_archs(self):
+ folder = self.package()
+ path = folder / ec.MANIFEST
+ original = json.loads(path.read_text())
+ for key, why in (("build_id", "no build_id"), ("archs", "no archs")):
+ data = dict(original)
+ data.pop(key)
+ path.write_text(json.dumps(data))
+ with self.assertRaises(ec.ComponentProblem) as caught:
+ ec.read_manifest(folder)
+ self.assertIn(why, str(caught.exception))
+ data = dict(original, min_driver={"nvidia": 580})
+ path.write_text(json.dumps(data))
+ with self.assertRaises(ec.ComponentProblem):
+ ec.read_manifest(folder)
+ data = dict(original, signature="trust me")
+ path.write_text(json.dumps(data))
+ with self.assertRaises(ec.ComponentProblem):
+ ec.read_manifest(folder)
+
+ def test_a_schema_1_package_from_s3_still_loads(self):
+ folder = self.package()
+ path = folder / ec.MANIFEST
+ data = json.loads(path.read_text())
+ for key in ("name", "build_id", "min_driver", "signature", "archs"):
+ data.pop(key)
+ data["schema_version"] = 1
+ data["cuda_archs"] = ["sm_86"]
+ path.write_text(json.dumps(data))
+ component = ec.read_manifest(folder)
+ self.assertEqual((component.archs, component.build_id), (("sm_86",), ""))
+
+ def test_duplicate_file_entries_are_refused(self):
+ folder = self.package()
+ path = folder / ec.MANIFEST
+ data = json.loads(path.read_text())
+ data["files"].append(dict(data["files"][1]))
+ path.write_text(json.dumps(data))
+ with self.assertRaises(ec.ComponentProblem):
+ ec.read_manifest(folder)
+
+ def test_verify_cli_and_package_digest(self):
+ folder = self.package()
+ out = io.StringIO()
+ with contextlib.redirect_stdout(out):
+ self.assertEqual(package_engine.main(["--verify", str(folder)]), 0)
+ self.assertIn(package_engine.package_sha256(folder), out.getvalue())
+ (folder / LIB).write_bytes(b"x" * (folder / LIB).stat().st_size)
+ with contextlib.redirect_stdout(out):
+ self.assertEqual(package_engine.main(["--verify", str(folder)]), 1)
+
+
+class Arch(unittest.TestCase):
+ def test_machine_code_and_ptx(self):
+ self.assertTrue(ec.arch_covers(["sm_86"], ["sm_86"]))
+ self.assertFalse(ec.arch_covers(["sm_86"], ["sm_120"]))
+ self.assertTrue(ec.arch_covers(["sm_75", "compute_89"], ["sm_120"]), "PTX of an older generation runs on a newer card")
+ self.assertFalse(ec.arch_covers(["sm_75", "compute_89"], ["sm_86"]), "PTX never runs on an older card")
+ self.assertTrue(ec.arch_covers(["sm_86"], []), "cannot tell: not a refusal")
+
+
+class Start(unittest.TestCase):
+ """What a start checks: every file's hash (not only the entrypoint), the driver, the signature policy."""
+
+ def setUp(self):
+ self.dir = tempfile.TemporaryDirectory()
+ self.addCleanup(self.dir.cleanup)
+ self.root = Path(self.dir.name)
+ self.out = self.root / "engine"
+ self.out.mkdir()
+ self.folder = package_engine.build(make_source(self.root / "src"), "cuda", "0.1.45", HERE, self.out,
+ archs=("sm_86",), min_driver={"nvidia": "580.65"}, build_id="b1")
+ self.addCleanup(ec.register_signature_verifier, None)
+
+ def start(self, **kw):
+ with mock.patch.object(ec, "cuda_archs_present", return_value=kw.pop("cards", ["sm_86"])), \
+ mock.patch.object(ec, "nvidia_driver_version", return_value=kw.pop("driver", "590.00")):
+ return ec.expand("component:strata-engine", {"backend": "cuda"}, root=self.root, **kw)
+
+ def test_a_good_package_starts(self):
+ self.assertEqual(Path(self.start()).resolve(), (self.folder / EXE).resolve())
+
+ def test_a_same_size_change_in_a_library_refuses_the_start_with_the_file_named(self):
+ lib = self.folder / LIB
+ body = bytearray(lib.read_bytes())
+ body[7] ^= 0xFF # same size, same entrypoint: only the full hash sees it
+ lib.write_bytes(bytes(body))
+ with mock.patch.object(ec, "cuda_archs_present", return_value=["sm_86"]), mock.patch.object(ec, "nvidia_driver_version", return_value=None):
+ self.assertEqual(ec.resolve(self.root, backend="cuda", runtime="1").version, "0.1.45", "the quick check passes")
+ with self.assertRaises(ec.EngineIntegrityError) as caught:
+ self.start()
+ self.assertIn(LIB, str(caught.exception))
+ self.assertIn("SHA-256", str(caught.exception))
+ self.assertIn("not started", str(caught.exception))
+ self.assertEqual(caught.exception.exit_code, 5)
+ self.assertIsInstance(caught.exception, ec.EngineMissing)
+
+ def test_a_changed_manifest_hash_is_refused(self):
+ path = self.folder / ec.MANIFEST
+ data = json.loads(path.read_text())
+ data["files"][0]["sha256"] = "0" * 64
+ path.write_text(json.dumps(data))
+ with self.assertRaises(ec.EngineIntegrityError):
+ self.start()
+
+ def test_a_good_package_does_not_hide_a_tampered_one(self):
+ newer = package_engine.build(make_source(self.root / "src2"), "cuda", "0.1.46", HERE, self.out,
+ archs=("sm_86",), build_id="b2")
+ (newer / LIB).write_bytes(b"y" * (newer / LIB).stat().st_size)
+ self.assertEqual(ec.read_manifest(Path(self.start()).parent).version, "0.1.45")
+
+ def test_other_pc_reasons_are_not_integrity_errors(self):
+ with self.assertRaises(ec.EngineMissing) as caught:
+ self.start(cards=["sm_120"])
+ self.assertNotIsInstance(caught.exception, ec.EngineIntegrityError)
+ self.assertIn("sm_86", str(caught.exception))
+
+ def test_an_old_driver_is_refused_with_both_versions(self):
+ with self.assertRaises(ec.EngineMissing) as caught:
+ self.start(driver="535.10")
+ self.assertIn("580.65", str(caught.exception))
+ self.assertIn("535.10", str(caught.exception))
+ self.assertTrue(self.start(driver=None), "an unreadable driver is not a refusal")
+
+ def test_signature_policy_and_hook(self):
+ self.assertEqual(ec.verify_signature(ec.read_manifest(self.folder), {}), "unsigned")
+ with self.assertRaises(ec.IntegrityProblem):
+ ec.verify_signature(ec.read_manifest(self.folder), {ec.ENV_REQUIRE_SIGNED: "1"})
+ with mock.patch.dict(os.environ, {ec.ENV_REQUIRE_SIGNED: "1"}):
+ with self.assertRaises(ec.EngineIntegrityError):
+ self.start()
+ # sign it: a stand-in "signature" over the canonical payload
+ path = self.folder / ec.MANIFEST
+ data = json.loads(path.read_text())
+ key = b"test-key"
+ data["signature"] = {"alg": "test-hmac", "key_id": "k1",
+ "value": hashlib.sha256(key + ec.signing_payload(data)).hexdigest()}
+ path.write_text(json.dumps(data))
+ component = ec.read_manifest(self.folder)
+ self.assertEqual(ec.verify_signature(component, {}), "unverified", "signed but nobody can check it")
+ with self.assertRaises(ec.IntegrityProblem):
+ ec.verify_signature(component, {ec.ENV_REQUIRE_SIGNED: "1"})
+
+ def verifier(payload, signature, comp):
+ if signature["value"] != hashlib.sha256(key + payload).hexdigest():
+ raise ValueError("wrong")
+ ec.register_signature_verifier(verifier)
+ self.assertEqual(ec.verify_signature(component, {ec.ENV_REQUIRE_SIGNED: "1"}), "verified")
+ self.assertTrue(self.start())
+ data["version"] = "0.1.46-evil" # any manifest change breaks the signature
+ path.write_text(json.dumps(data))
+ with self.assertRaises(ec.EngineIntegrityError) as caught:
+ self.start()
+ self.assertIn("signature", str(caught.exception))
+
+ def test_the_payload_is_canonical_and_excludes_the_signature(self):
+ a = ec.signing_payload({"b": 1, "a": [1, 2], "signature": {"alg": "x", "value": "y"}})
+ b = ec.signing_payload({"a": [1, 2], "b": 1, "signature": None})
+ self.assertEqual(a, b)
+ self.assertEqual(a, b'{"a":[1,2],"b":1}')
+
+
+if __name__ == "__main__":
+ unittest.main()