diff --git a/setup.py b/setup.py index f0e7c0eb..2e482f3e 100644 --- a/setup.py +++ b/setup.py @@ -171,6 +171,10 @@ LLAMA_CPP_ZIP = f"https://github.com/ggml-org/llama.cpp/archive/{LLAMA_CPP_COMMI # With the default, the release of this checkout's own version (PREBUILT_TAG_URL, CMakeLists.txt's version) is # tried first and the latest release is the fallback (#214): an older checkout keeps the engine it shipped with. PREBUILT_URL = "https://github.com/Niko1221/Strata/releases/latest/download/" +# The repository the release assets and their SHA-256 come from; `engine_digest` reads the API here even +# when --prebuilt points the download somewhere else, because the hash is only worth having if it comes +# from somewhere the download does not. +REPO = "Niko1221/Strata" PREBUILT_TAG_URL = "https://github.com/Niko1221/Strata/releases/download/v{version}/" PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip" # the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packages @@ -2220,6 +2224,11 @@ def get_prebuilt_hip(url_base, gpu, updating=False) -> Path | None: return None say(" Downloading the ready-made Strata engine for AMD GPUs (with the ROCm libraries it uses) ...") download(base + WIN_HIP_ASSET, z, "Strata AMD engine") + try: + verify_engine_archive(z, WIN_HIP_ASSET, base) + except UnverifiedEngine as e: + engine_refused(WIN_HIP_ASSET, e, updating) + return None tmp = eng / "_unpack" shutil.rmtree(tmp, ignore_errors=True) with zipfile.ZipFile(z) as f: @@ -2451,6 +2460,171 @@ def driver_major(gpu): return 0 +class UnverifiedEngine(Exception): + """The engine archive could not be verified, with the reason. + + Raised rather than `fail()`-ed on purpose. The engine-UPDATE paths wrap their download in + `except Exception` and fall back to the engine already installed, so a refusal has to be an Exception: + `fail()` ends in `sys.exit(1)`, and SystemExit is a BaseException, so it flies past that guard and + kills the start instead. Measured on this change before the fix - a wrong hash, a wrong size and a + missing digest each escaped get_prebuilt(updating=True) as SystemExit(1). + """ + + +def release_of(base: str) -> tuple[str, str | None] | None: + """("github", tag) for a GitHub release URL, or None when the URL is not one. + + `base` is one of the bases from `prebuilt_bases`: a `releases/download/v0.1.40/` URL (which names its + tag), the `releases/latest/download/` URL, or something else entirely - a local folder, a plain mirror. + That last case matters: it has no published digest, so treating it as "latest" would check the file + against a release the user did not ask for, over the network, which is wrong twice over. + + The repository comes out of the URL when it names one, so a fork's own releases are checked against + the fork rather than against Niko1221/Strata (which never has the fork's tags, so the check would + always fail). + """ + m = re.search(r"https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/releases/(?:download/v([^/]+)|latest)/", + base) + if not m: + return None + return f"https://api.github.com/repos/{m.group(1)}/{m.group(2)}/releases", m.group(3) + + +def is_local(base: str) -> bool: + """True for a path on this machine - `C:\mirror`, `/mnt/mirror`, `\\share\engine`, `file://...`. + + A local folder is the user's own file on their own disk, the same trust decision as `--gguf-dir`, and + there is no published digest for it to be checked against. It is treated differently from a remote + mirror on purpose: nothing is between the file and setup, whereas a remote mirror has a network in the + middle and still no release to check it against. + """ + b = base.strip() + if b.lower().startswith("file://"): + return True + return not re.match(r"^[a-z][a-z0-9+.\-]*://", b, re.I) + + +def engine_digest(asset: str, base: str) -> tuple[int, str] | None: + """(size, "sha256:") for `asset` in the release `base` points at, or None if GitHub will not say. + + The size and hash come from the releases API - a different origin from the download, which is the + whole point: a mirrored, substituted or TLS-intercepted download does not come with a matching digest, + while a compromised release does (see `verify_engine_archive` for what that leaves uncovered). + + GitHub populates `digest` for every asset, including ones uploaded before the field existed + (measured on v0.1.34 through v0.1.40.1). None means no answer - no network, a rate limit, or a + release that does not publish one - and the caller refuses rather than treating it as a pass. + """ + where = release_of(base) + if where is None: # a local folder or a plain mirror: nothing published to check against + return None + releases, tag = where + url = f"{releases}/tags/v{tag}" if tag else f"{releases}/latest" + try: + req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", + "Accept": "application/vnd.github+json"}) + with urllib.request.urlopen(req, timeout=60) as r: + rel = json.loads(r.read().decode("utf-8")) + except Exception: + return None # offline, rate-limited, or the release is not there + for a in rel.get("assets") or []: + if a.get("name") == asset and a.get("digest") and str(a.get("digest")).startswith("sha256:"): + return int(a.get("size") or 0), str(a["digest"]).split(":", 1)[1] + return None + + +def drop_download(z: Path) -> None: + """The archive and its finish mark. A refused engine is not left where a later run would reuse it.""" + z.unlink(missing_ok=True) + z.with_name(z.name + ".done").unlink(missing_ok=True) + + +def verify_engine_archive(z: Path, asset: str, base: str) -> None: + """The downloaded engine archive against the published size and SHA-256, before it is unpacked. + + Without this, a ready-made engine is installed on nothing more than the byte count matching the + server's Content-Length - and a substituted file of the same length passes that. It runs before the + archive is opened, so a wrong engine never reaches `_unpack`, let alone the engine directory. + + Raises UnverifiedEngine on a refusal; the caller decides whether that stops setup (a first install, + with nothing to fall back to) or keeps the engine that is already there (an update). + + Where the hash comes from, and where it cannot: + + - a GitHub release URL: the tag is read out of the URL, so the exact release the bytes claim to come + from is the one checked rather than "latest" (setup tries the checkout's own release first, #214), + and the repository comes out of the URL too, so a fork's releases are checked against the fork; + - a local folder (`--prebuilt D:\mirror`): nothing published to check against. This warns and goes + ahead - it is the user's own file, the same trust decision as `--gguf-dir`, and there is nothing an + API could say about it; + - any other remote mirror: nothing published to check against either, but a network is in the middle, + so it refuses unless `STRATA_ALLOW_UNVERIFIED_ENGINE=1`. + + What a digest from the API does NOT cover, stated plainly: it proves the bytes are the ones GitHub + published for that asset, so it catches a corrupted transfer, a mirror or proxy that substituted the + file, and a hostile network. It does not make a malicious RELEASE safe - if whoever can publish a + release publishes a hostile engine, the digest matches it. Only a hash pinned in this file closes + that, at the cost of a commit per release; a dict of tag -> sha next to `engine_digest` is where one + would go. + + The size and the hashing below are spelled out rather than delegated to `verify_sha256`, for two + reasons, both measured here. That function ends in `fail()`, and a refusal has to be an Exception so + the update paths can fall back. And it keeps a `.done` mark so 111 GB of Unsloth shards is hashed + once; the engine archive is 190 MB, which hashes in 0.79 s at 242 MB/s on this machine, against 3.0 s + to download the same file. A mark that saves 0.8 s is not worth a class of hole - anything that + changes the file after it was verified, at any length - so there is no mark here. + """ + want = engine_digest(asset, base) # one API call: this is a rate-limited API + if not want: + if is_local(base): + warn(f"{base} is a folder on this PC, not a published release, so {asset} cannot be checked " + f"against a SHA-256. Installing it as it is.") + return + if os.environ.get("STRATA_ALLOW_UNVERIFIED_ENGINE"): + warn(f"no published SHA-256 for {asset}; installing it UNVERIFIED " + f"(STRATA_ALLOW_UNVERIFIED_ENGINE)") + return + if release_of(base) is None: + raise UnverifiedEngine(f"{base} is not a GitHub release URL, so there is no published " + f"SHA-256 for {asset}, and it is not a folder on this PC either") + raise UnverifiedEngine(f"GitHub's API did not give a SHA-256 for {asset}") + size, sha = want + have = z.stat().st_size if z.exists() else -1 + if have != size: + drop_download(z) + raise UnverifiedEngine(f"{z.name} is {have:,} bytes, not the published {size:,}") + h = hashlib.sha256() + with open(z, "rb") as f: + while True: + b = f.read(16 << 20) + if not b: + break + h.update(b) + if h.hexdigest() != sha: + got = h.hexdigest() + drop_download(z) + raise UnverifiedEngine(f"{z.name} has the wrong SHA-256 ({got}, expected {sha})") + + +def engine_refused(asset: str, e: Exception, updating: bool) -> None: + """Report a refusal and either stop setup or keep the engine that is installed. + + A first install has nothing to fall back to, so it stops. An update does: the engine already in + place is untouched by a refusal (nothing has been unpacked), it works, and stopping the model from + starting over a hash is worse than keeping what is there - which is the whole reason that call site + catches what the download can throw. + """ + if not updating: + fail(f"cannot verify the Strata engine: {e}", + "the downloaded archive has been deleted so the next run fetches the published one. " + "Re-run when GitHub answers - it publishes a size and SHA-256 for every asset - or set " + "STRATA_ALLOW_UNVERIFIED_ENGINE=1 to install an engine that cannot be checked") + return + warn(f"keeping the engine that is installed: {e}") + say(f" Nothing was replaced. Run setup again when GitHub answers, or set " + f"STRATA_ALLOW_UNVERIFIED_ENGINE=1 to install an engine that cannot be checked.") + + def prebuilt_bases(url_base) -> list[str]: """Where to look for the ready-made engine, in order (each ending in a slash). The default: the release of this checkout's version first, then the latest (#214); an explicit --prebuilt / STRATA_PREBUILT_URL: only that.""" @@ -2568,6 +2742,11 @@ def get_prebuilt(url_base, gpu, vision, updating=False, toolkit=13) -> Path | No return None say(" Downloading the ready-made Strata engine" + (" (CUDA 12, experimental)" if int(toolkit) == 12 else "") + " ...") download(base + asset, z, "Strata engine") + try: + verify_engine_archive(z, asset, base) + except UnverifiedEngine as e: + engine_refused(asset, e, updating) + return None tmp = eng / "_unpack" shutil.rmtree(tmp, ignore_errors=True) try: diff --git a/tools/test_setup_engine_hash.py b/tools/test_setup_engine_hash.py new file mode 100644 index 00000000..f315e187 --- /dev/null +++ b/tools/test_setup_engine_hash.py @@ -0,0 +1,403 @@ +"""Tests for setup.py's verification of the ready-made engine archive against its published SHA-256. + +`get_prebuilt()` used to install the engine on nothing more than the byte count matching the server's +Content-Length, so a substituted file of the same length passed. These cover the check that closes that, the +refusal and what a refusal does to the caller, the cases where there is nothing published to check against, +and the order it happens in - it must run before the archive is opened, or a wrong engine still reaches the +disk. Mocked network - nothing is downloaded. + + python -m unittest tools.test_setup_engine_hash +""" + +from __future__ import annotations + +import hashlib +import io +import json +import os +import sys +import tempfile +import unittest +import zipfile +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +import setup # noqa: E402 + +ASSET = "strata-windows-x64.zip" +HIP_ASSET = "strata-windows-x64-hip.zip" +TAG_BASE = "https://github.com/Niko1221/Strata/releases/download/v0.1.40/" +LATEST_BASE = "https://github.com/Niko1221/Strata/releases/latest/download/" +FORK_BASE = "https://github.com/someone/Strata/releases/download/v1.0/" +LOCAL_BASE = r"C:\my\mirror" + + +def zip_bytes() -> bytes: + """A stand-in engine archive. Small; its hash is what matters, not its size.""" + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as zf: + zf.writestr("strata.exe", b"not a real engine") + zf.writestr("BUILD.json", b'{"version": "0.1.40"}') + return buf.getvalue() + + +def sha_of(b: bytes) -> str: + return hashlib.sha256(b).hexdigest() + + +class WhereTheHashComesFrom(unittest.TestCase): + """`release_of` and `is_local`: which base names a published release, and which is the user's own disk.""" + + def test_a_tag_url_names_its_tag(self): + self.assertEqual(setup.release_of(TAG_BASE), + ("https://api.github.com/repos/Niko1221/Strata/releases", "0.1.40")) + + def test_the_latest_url_names_no_tag(self): + self.assertEqual(setup.release_of(LATEST_BASE), + ("https://api.github.com/repos/Niko1221/Strata/releases", None)) + + def test_a_fork_names_the_fork_not_this_repository(self): + # The repository used to be hardcoded, so a fork's own tag was looked up under Niko1221/Strata, + # where it does not exist - every fork install would be refused. + self.assertEqual(setup.release_of(FORK_BASE), + ("https://api.github.com/repos/someone/Strata/releases", "1.0")) + + def test_something_that_is_not_a_github_release_url_names_nothing(self): + # This is the case that mattered: a local folder or a plain mirror used to match no tag, fall + # through to releases/latest, and be checked against a release the user did not ask for. + for base in (LOCAL_BASE, "https://mirror.invalid/dl/", "/mnt/mirror", "\\\\share\\engine"): + self.assertIsNone(setup.release_of(base), base) + + def test_a_local_folder_is_local_and_a_remote_mirror_is_not(self): + # The distinction the policy turns on: nothing is between a local file and setup; a remote mirror + # has a network in the middle and still no release to check against. + for base in (LOCAL_BASE, r"C:\\mirror", "/mnt/mirror", "file:///srv/engine", + r"\\\\share\\engine"): + self.assertTrue(setup.is_local(base), base) + for base in (setup.PREBUILT_URL, TAG_BASE, FORK_BASE, "https://mirror.invalid/dl/", + "http://example.invalid/engine/"): + self.assertFalse(setup.is_local(base), base) + + def test_a_local_folder_asks_the_api_nothing_at_all(self): + # Air-gapped and shared-IP installs must not depend on GitHub answering. + with mock.patch.object(setup.urllib.request, "urlopen", + side_effect=AssertionError("the API was called")): + self.assertIsNone(setup.engine_digest(ASSET, LOCAL_BASE)) + + +class DigestLookup(unittest.TestCase): + """`engine_digest`: the size and hash for one asset, from the releases API.""" + + def release_json(self, tag, assets): + return json.dumps({"tag_name": tag, "assets": assets}).encode("utf-8") + + def asked(self, payload): + """Patch urlopen with a fake that serves `payload`; returns the list the URL goes into. + + A list rather than a mock, because patching urlopen with a plain function hands back the function, + and the URL asked for is part of what is under test. + """ + seen = [] + + class R: + def __init__(self, data): + self._b = io.BytesIO(data) + + def read(self, *a): + return self._b.read(*a) + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def open_it(req, timeout=None): + seen.append(req.full_url) + return R(payload) + + patcher = mock.patch.object(setup.urllib.request, "urlopen", open_it) + patcher.start() + self.addCleanup(patcher.stop) + return seen + + def test_reads_the_tag_out_of_the_download_url(self): + # The URL already names the release, so the API call must ask for THAT release and not "latest": + # the tag URL is tried first (#214) so a checkout normally gets its own version's engine. + seen = self.asked(self.release_json( + "v0.1.40", [{"name": ASSET, "size": 42, "digest": "sha256:" + "a" * 64}])) + self.assertEqual(setup.engine_digest(ASSET, TAG_BASE), (42, "a" * 64)) + self.assertEqual(seen, ["https://api.github.com/repos/Niko1221/Strata/releases/tags/v0.1.40"]) + + def test_latest_when_the_url_says_latest(self): + seen = self.asked(self.release_json( + "v0.1.40.1", [{"name": ASSET, "size": 7, "digest": "sha256:" + "b" * 64}])) + setup.engine_digest(ASSET, LATEST_BASE) + self.assertEqual(seen, ["https://api.github.com/repos/Niko1221/Strata/releases/latest"]) + + def test_asks_the_fork_for_a_fork_url(self): + seen = self.asked(self.release_json( + "v1.0", [{"name": ASSET, "size": 9, "digest": "sha256:" + "c" * 64}])) + self.assertEqual(setup.engine_digest(ASSET, FORK_BASE), (9, "c" * 64)) + self.assertIn("/repos/someone/Strata/releases/tags/v1.0", seen[0]) + + def test_none_when_no_digest_is_published(self): + # No digest is not a pass. The caller refuses. + self.asked(self.release_json("v0.1.40", [{"name": ASSET, "size": 42}])) + self.assertIsNone(setup.engine_digest(ASSET, TAG_BASE)) + + def test_none_when_the_digest_is_not_a_sha256(self): + for other in ("md5:" + "d" * 32, "sha512:" + "e" * 128, "", None): + self.asked(self.release_json("v0.1.40", + [{"name": ASSET, "size": 42, "digest": other}])) + self.assertIsNone(setup.engine_digest(ASSET, TAG_BASE), other) + + def test_none_when_the_asset_is_not_in_that_release(self): + # A CUDA 12 asset asked for on a release that has none, or a renamed asset. Refuse, do not verify + # against some other file's hash. + self.asked(self.release_json("v0.1.40", + [{"name": "other.zip", "size": 1, "digest": "sha256:" + "f" * 64}])) + self.assertIsNone(setup.engine_digest(ASSET, TAG_BASE)) + + def test_none_when_github_cannot_be_reached(self): + for exc in (OSError("no network"), TimeoutError("slow")): + with mock.patch.object(setup.urllib.request, "urlopen", side_effect=exc): + self.assertIsNone(setup.engine_digest(ASSET, TAG_BASE), exc) + + def test_picks_the_asset_the_url_actually_wants(self): + # v0.1.40.1 ships several engine builds with different hashes; the one asked for must be the one + # used, not whichever the API lists first. + self.asked(self.release_json("v0.1.40.1", [ + {"name": "strata-windows-x64.zip", "size": 1, "digest": "sha256:" + "1" * 64}, + {"name": "strata-windows-x64-cuda12.zip", "size": 2, "digest": "sha256:" + "2" * 64}, + {"name": HIP_ASSET, "size": 3, "digest": "sha256:" + "3" * 64}, + ])) + self.assertEqual(setup.engine_digest("strata-windows-x64-cuda12.zip", LATEST_BASE), (2, "2" * 64)) + self.assertEqual(setup.engine_digest(HIP_ASSET, LATEST_BASE), (3, "3" * 64)) + + +class ArchiveVerification(unittest.TestCase): + """`verify_engine_archive`: the downloaded file against the published size and hash.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.z = Path(self.tmp.name) / ASSET + self.data = zip_bytes() + self.z.write_bytes(self.data) + patch = mock.patch.dict(os.environ, {}, clear=False) + env = patch.start() + self.addCleanup(patch.stop) + env.pop("STRATA_ALLOW_UNVERIFIED_ENGINE", None) + + def digest(self, value): + return mock.patch.object(setup, "engine_digest", return_value=value) + + def test_passes_when_the_hash_matches(self): + with self.digest((len(self.data), sha_of(self.data))): + setup.verify_engine_archive(self.z, ASSET, TAG_BASE) # must not raise + self.assertTrue(self.z.exists()) + + def test_refuses_a_wrong_hash_and_deletes_the_file(self): + # A wrong engine left on disk is the thing this exists to prevent, so it goes. + with self.digest((len(self.data), "0" * 64)): + with self.assertRaises(setup.UnverifiedEngine) as caught: + setup.verify_engine_archive(self.z, ASSET, TAG_BASE) + self.assertIn("wrong SHA-256", str(caught.exception)) + self.assertFalse(self.z.exists()) + self.assertFalse(self.z.with_name(self.z.name + ".done").exists()) + + def test_refuses_a_wrong_size_before_hashing(self): + with self.digest((len(self.data) + 1, sha_of(self.data))): + with self.assertRaises(setup.UnverifiedEngine) as caught: + setup.verify_engine_archive(self.z, ASSET, TAG_BASE) + self.assertIn("not the published", str(caught.exception)) + self.assertFalse(self.z.exists()) + + def test_a_same_size_impostor_is_caught_by_the_hash_alone(self): + # The case Content-Length cannot see, and the reason the hash is there at all. + impostor = b"x" * len(self.data) + self.z.write_bytes(impostor) + with self.digest((len(impostor), sha_of(self.data))): + with self.assertRaises(setup.UnverifiedEngine): + setup.verify_engine_archive(self.z, ASSET, TAG_BASE) + self.assertFalse(self.z.exists()) + + def test_refuses_when_github_gives_no_hash(self): + with self.digest(None): + with self.assertRaises(setup.UnverifiedEngine) as caught: + setup.verify_engine_archive(self.z, ASSET, TAG_BASE) + self.assertIn("did not give a SHA-256", str(caught.exception)) + self.assertTrue(self.z.exists(), "the file is left alone; only the install is refused") + + def test_a_local_folder_warns_and_proceeds(self): + # `--prebuilt D:\mirror` used to be refused unless the override was set, which was a regression on + # a supported workflow: it is the user's own file on their own disk, the same trust decision as + # --gguf-dir, and no API could say anything about it. It now warns by name and goes ahead. + said = io.StringIO() + with self.digest(None), mock.patch.object(setup, "warn", said.write): + setup.verify_engine_archive(self.z, ASSET, LOCAL_BASE) # must not raise + out = said.getvalue() + self.assertIn(LOCAL_BASE, out) + self.assertIn("cannot be checked", out) + + def test_a_remote_mirror_still_needs_the_override(self): + # There IS a network in the middle of a mirror, and still no release to check it against. + with self.digest(None): + with self.assertRaises(setup.UnverifiedEngine) as caught: + setup.verify_engine_archive(self.z, ASSET, "https://mirror.invalid/dl/") + msg = str(caught.exception) + self.assertIn("not a GitHub release URL", msg) + # and it says why a local folder would have been different, which is the distinction + self.assertIn("is not a folder on this PC either", msg) + + def test_a_truncated_archive_is_refused(self): + # There is no finish mark any more, so nothing can vouch for a file that changed after it was + # checked. Measured cost of that decision: 190 MB hashes in 0.79 s at 242 MB/s on this machine, + # against 3.0 s to download the same file, so re-checking is not worth saving. + with self.digest((len(self.data), sha_of(self.data))): + setup.verify_engine_archive(self.z, ASSET, TAG_BASE) + with open(self.z, "r+b") as f: + f.truncate(len(self.data) // 2) + with self.assertRaises(setup.UnverifiedEngine) as caught: + setup.verify_engine_archive(self.z, ASSET, TAG_BASE) + self.assertIn("not the published", str(caught.exception)) + + def test_a_same_length_change_after_verification_is_refused(self): + # The hole the mark left: same length, so the size check passes, and the mark would have vouched + # for it. With no mark, the hash is recomputed and it is caught. + with self.digest((len(self.data), sha_of(self.data))): + setup.verify_engine_archive(self.z, ASSET, TAG_BASE) + with open(self.z, "r+b") as f: + f.seek(0) + f.write(b"X") + with self.assertRaises(setup.UnverifiedEngine) as caught: + setup.verify_engine_archive(self.z, ASSET, TAG_BASE) + self.assertIn("wrong SHA-256", str(caught.exception)) + + def test_the_api_is_asked_once_not_twice(self): + # It is a rate-limited API and an install is not the place to spend two calls on one lookup. + with mock.patch.object(setup, "engine_digest", + return_value=(len(self.data), sha_of(self.data))) as m: + setup.verify_engine_archive(self.z, ASSET, TAG_BASE) + self.assertEqual(m.call_count, 1, f"engine_digest was called {m.call_count} times") + + def test_the_api_is_asked_once_when_the_escape_hatch_is_set_too(self): + os.environ["STRATA_ALLOW_UNVERIFIED_ENGINE"] = "1" + with mock.patch.object(setup, "engine_digest", return_value=None) as m: + said = io.StringIO() + with mock.patch.object(setup, "say", said.write), mock.patch.object(setup, "warn", said.write): + setup.verify_engine_archive(self.z, ASSET, TAG_BASE) # must not raise + self.assertEqual(m.call_count, 1, f"engine_digest was called {m.call_count} times") + self.assertIn("UNVERIFIED", said.getvalue()) + self.assertIn(ASSET, said.getvalue()) + + def test_the_escape_hatch_is_opt_in(self): + self.assertNotIn("STRATA_ALLOW_UNVERIFIED_ENGINE", os.environ) + with self.digest(None): + with self.assertRaises(setup.UnverifiedEngine): + setup.verify_engine_archive(self.z, ASSET, TAG_BASE) + + +class WhatARefusalDoesToTheCaller(unittest.TestCase): + """`engine_refused`, and the paths that call it. + + This is where the adversarial pass found the worst bug: a refusal used to end in `fail()`, i.e. + `sys.exit(1)`, which is a BaseException, so the engine-UPDATE paths' `except Exception` could not catch + it and setup died instead of starting with the engine it already had. + """ + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + (Path(self.tmp.name) / "engine").mkdir(parents=True, exist_ok=True) + + def fake_download(self, url, dst, what=None): + with zipfile.ZipFile(dst, "w") as z: + z.writestr("BUILD.json", json.dumps({"version": "0.1.40", "archs": [89]})) + z.writestr(setup.EXE, b"engine") + + def get_prebuilt(self, updating, digest): + out = io.StringIO() + with contextlib_redirect(out), mock.patch.object(setup, "download", self.fake_download), mock.patch.object(setup, "engine_digest", return_value=digest): + return setup.get_prebuilt(setup.PREBUILT_URL, {"arch": 89}, "gpu", updating=updating), out + + def test_updating_keeps_the_installed_engine_instead_of_stopping(self): + # The call site's own words: "a failed download must not stop the model from starting". + for digest in ((999, "f" * 64), (1, "0" * 64), None): + eng, out = self.get_prebuilt(updating=True, digest=digest) + self.assertIsNone(eng, f"digest={digest!r} did not return None") + self.assertNotIn("Setup stopped", out.getvalue(), + "a refusal while updating must not claim setup stopped") + self.assertIn("keeping the engine that is installed", out.getvalue()) + + def test_a_refusal_is_an_exception_the_update_path_can_catch(self): + # The regression guard for the actual bug: SystemExit escaped this guard before. + self.assertTrue(issubclass(setup.UnverifiedEngine, Exception)) + self.assertFalse(issubclass(SystemExit, Exception)) + eng, _ = self.get_prebuilt(updating=True, digest=(999, "f" * 64)) + self.assertIsNone(eng, "a refusal must not escape get_prebuilt as SystemExit") + + def test_a_first_install_stops_because_there_is_nothing_to_fall_back_to(self): + with mock.patch.object(setup, "download", self.fake_download), mock.patch.object(setup, "engine_digest", return_value=(999, "f" * 64)): + with self.assertRaises(SystemExit): + setup.get_prebuilt(setup.PREBUILT_URL, {"arch": 89}, "gpu") + + def test_the_cuda_and_amd_paths_both_verify(self): + # get_prebuilt_hip downloads the AMD engine from a SECOND `download(base + ...)` call site, which + # the first version of this change missed entirely - so AMD users got nothing from it. + src = (ROOT / "setup.py").read_text(encoding="utf-8") + for call in ('download(base + asset, z, "Strata engine")', + 'download(base + WIN_HIP_ASSET, z, "Strata AMD engine")'): + i = src.index(call) + self.assertIn("verify_engine_archive", src[i:i + 400], f"{call} is not verified") + + +class Wiring(unittest.TestCase): + """The check is reached, and reached before the archive is opened.""" + + def test_get_prebuilt_verifies_before_it_unpacks(self): + src = (ROOT / "setup.py").read_text(encoding="utf-8") + body = src[src.index("def get_prebuilt("):] + body = body[:body.index("\ndef ")] + i_verify = body.index("verify_engine_archive(") + for opener in ("ZipFile(", "_unpack", "install_unpacked"): + self.assertGreater(body.index(opener), i_verify, + f"{opener} happens before the SHA-256 is checked") + + def test_the_digest_is_read_from_the_api_not_the_download_host(self): + src = (ROOT / "setup.py").read_text(encoding="utf-8") + # release_of() builds the API URL, from the OWNER/REPO in the download URL - so a mirror of this + # repository is checked against this repository's published hash, not against whatever the mirror + # happens to be serving. + body = src[src.index("def release_of("):] + body = body[:body.index("\ndef ")] + self.assertIn("api.github.com/repos/", body) + self.assertIn("m.group(1)", body, "the repository comes out of the URL, not a constant") + # and engine_digest asks release_of rather than the download URL + body = src[src.index("def engine_digest("):] + body = body[:body.index("\ndef ")] + self.assertIn("release_of(base)", body) + + +class contextlib_redirect: + """stdout into a StringIO, without importing contextlib under a name setup.py also uses.""" + + def __init__(self, buf): + self.buf = buf + + def __enter__(self): + self.old = sys.stdout + sys.stdout = self.buf + return self + + def __exit__(self, *a): + sys.stdout = self.old + return False + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_pins.py b/tools/test_setup_pins.py index bdcafb73..9e09d27e 100644 --- a/tools/test_setup_pins.py +++ b/tools/test_setup_pins.py @@ -7,6 +7,7 @@ requirements file, and an existing install left as it is. Mocked network - noth from __future__ import annotations import contextlib +import hashlib import io import json import re @@ -178,16 +179,31 @@ class Engine(unittest.TestCase): p.stop() self.tmp.cleanup() - def fake_download(self, got): + def fake_download(self, got, wrote=None): def download(url, dst, what=None): got.append(url) + if wrote is not None: + wrote.append(Path(dst)) with zipfile.ZipFile(dst, "w") as z: z.writestr("BUILD.json", json.dumps({"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [89]})) z.writestr(setup.EXE, b"engine") return download + def fake_digest(self, wrote): + """The SHA-256 of whatever the fake download just wrote, computed for real. + + `get_prebuilt()` now checks the archive against GitHub's size and SHA-256 before it unpacks + anything, so a test that mocks the download has to supply a hash or it stops at the check. These + tests are about WHICH release and WHICH asset are chosen, not about the bytes; what happens when + the hash is wrong has its own file (tools/test_setup_engine_hash.py). + """ + def digest(asset, base): + data = Path(wrote[-1]).read_bytes() + return len(data), hashlib.sha256(data).hexdigest() + return digest + def run_get(self, published): - heads, got = [], [] + heads, got, wrote = [], [], [] def urlopen(req, timeout=None): heads.append(req.full_url) @@ -196,7 +212,8 @@ class Engine(unittest.TestCase): return Response() with mock.patch.object(setup.urllib.request, "urlopen", urlopen), \ - mock.patch.object(setup, "download", self.fake_download(got)): + mock.patch.object(setup, "download", self.fake_download(got, wrote)), \ + mock.patch.object(setup, "engine_digest", self.fake_digest(wrote)): eng, out = quiet(setup.get_prebuilt, setup.PREBUILT_URL, {"arch": 89}, "gpu") return eng, out, heads, got @@ -224,14 +241,18 @@ class Engine(unittest.TestCase): for meta in ({"version": "0.1.0", "archs": [89]}, {"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [120]}): with self.subTest(meta=meta): + wrote = [] + def download(url, dst, what=None): + wrote.append(Path(dst)) with zipfile.ZipFile(dst, "w") as z: z.writestr("BUILD.json", json.dumps(meta)) z.writestr(setup.EXE, b"engine") setup.mark(dst) with mock.patch.object(setup.urllib.request, "urlopen", lambda req, timeout=None: Response()), \ - mock.patch.object(setup, "download", download): + mock.patch.object(setup, "download", download), \ + mock.patch.object(setup, "engine_digest", self.fake_digest(wrote)): eng, _ = quiet(setup.get_prebuilt, setup.PREBUILT_URL, {"arch": 89}, "gpu") self.assertIsNone(eng) z = self.root / "engine" / setup.PREBUILT_ASSET diff --git a/tools/test_setup_strix_halo.py b/tools/test_setup_strix_halo.py index 2b271dbd..65fa56c5 100644 --- a/tools/test_setup_strix_halo.py +++ b/tools/test_setup_strix_halo.py @@ -14,6 +14,7 @@ The other chips are synthetic (their KFD gfx_target_version and pci.ids ids). N """ from __future__ import annotations +import hashlib import io import json import re @@ -360,6 +361,7 @@ class WindowsZip(unittest.TestCase): for p in (mock.patch.object(setup, "ROOT", self.root), mock.patch.object(setup, "warn", self.warnings.append), mock.patch.object(setup, "say", lambda *a, **k: None), mock.patch.object(setup, "ok", lambda *a, **k: None), mock.patch.object(setup, "download", self.fake_download), + mock.patch.object(setup, "engine_digest", self.fake_digest), mock.patch.object(setup.urllib.request, "urlopen", lambda *a, **k: io.BytesIO(b"")), mock.patch.object(setup, "hip_runtime_beside_exe", lambda eng: None)): p.start() @@ -372,6 +374,18 @@ class WindowsZip(unittest.TestCase): "version": "0.1.40", "archs": self.archs, "lib_dirs": []})) z.writestr(setup.EXE, "x") + + def fake_digest(self, asset, base): + """The size and SHA-256 of whatever the mocked download just wrote. + + The engine archive is checked against a published digest before it is unpacked, so a test that + mocks the download has to say what the hash is or it never reaches the part it is about. This + hashes the real bytes the fake download produced, so the check still runs. + """ + p = self.root / "engine" / asset + data = p.read_bytes() if p.exists() else b"" + return len(data), hashlib.sha256(data).hexdigest() + def halo(self): return {"index": 0, "name": setup.AMD_NAMES["gfx1151"], "vram_gb": 52.0, "arch": "gfx1151", "uma": True, "dedicated_gb": 4.0, "shared_gb": 48.0, "vendor": "amd", "driver": "amd"}