okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
19.1 KiB390 linesraw
1"""Tests for setup.py's verification of the ready-made engine archive against its published SHA-256.
2
3`get_prebuilt()` used to install the engine on nothing more than the byte count matching the server's
4Content-Length, so a substituted file of the same length passed. These cover the check that closes that, the
5refusal and what a refusal does to the caller, the cases where there is nothing published to check against,
6and the order it happens in - it must run before the archive is opened, or a wrong engine still reaches the
7disk. Mocked network - nothing is downloaded.
8
9    python -m unittest tools.test_setup_engine_hash
10"""
11
12from __future__ import annotations
13
14import hashlib
15import io
16import json
17import os
18import sys
19import tempfile
20import unittest
21import zipfile
22from pathlib import Path
23from unittest import mock
24
25ROOT = Path(__file__).resolve().parents[1]
26sys.path.insert(0, str(ROOT))
27
28import setup  # noqa: E402
29
30ASSET = "strata-windows-x64.zip"
31HIP_ASSET = "strata-windows-x64-hip.zip"
32TAG_BASE = "https://github.com/Niko1221/Strata/releases/download/v0.1.40/"
33LATEST_BASE = "https://github.com/Niko1221/Strata/releases/latest/download/"
34FORK_BASE = "https://github.com/someone/Strata/releases/download/v1.0/"
35LOCAL_BASE = r"C:\my\mirror"
36
37
38def zip_bytes() -> bytes:
39    """A stand-in engine archive. Small; its hash is what matters, not its size."""
40    buf = io.BytesIO()
41    with zipfile.ZipFile(buf, "w") as zf:
42        zf.writestr("strata.exe", b"not a real engine")
43        zf.writestr("BUILD.json", b'{"version": "0.1.40"}')
44    return buf.getvalue()
45
46
47def sha_of(b: bytes) -> str:
48    return hashlib.sha256(b).hexdigest()
49
50
51class WhereTheHashComesFrom(unittest.TestCase):
52    """`release_of` and `is_local`: which base names a published release, and which is the user's own disk."""
53
54    def test_a_tag_url_names_its_tag(self):
55        self.assertEqual(setup.release_of(TAG_BASE),
56                         ("https://api.github.com/repos/Niko1221/Strata/releases", "0.1.40"))
57
58    def test_the_latest_url_names_no_tag(self):
59        self.assertEqual(setup.release_of(LATEST_BASE),
60                         ("https://api.github.com/repos/Niko1221/Strata/releases", None))
61
62    def test_a_fork_names_the_fork_not_this_repository(self):
63        # The repository used to be hardcoded, so a fork's own tag was looked up under Niko1221/Strata,
64        # where it does not exist - every fork install would be refused.
65        self.assertEqual(setup.release_of(FORK_BASE),
66                         ("https://api.github.com/repos/someone/Strata/releases", "1.0"))
67
68    def test_something_that_is_not_a_github_release_url_names_nothing(self):
69        # This is the case that mattered: a local folder or a plain mirror used to match no tag, fall
70        # through to releases/latest, and be checked against a release the user did not ask for.
71        for base in (LOCAL_BASE, "https://mirror.invalid/dl/", "/mnt/mirror", "\\\\share\\engine"):
72            self.assertIsNone(setup.release_of(base), base)
73
74    def test_a_local_folder_is_local_and_a_remote_mirror_is_not(self):
75        # The distinction the policy turns on: nothing is between a local file and setup; a remote mirror
76        # has a network in the middle and still no release to check against.
77        for base in (LOCAL_BASE, r"C:\\mirror", "/mnt/mirror", "file:///srv/engine",
78                     r"\\\\share\\engine"):
79            self.assertTrue(setup.is_local(base), base)
80        for base in (setup.PREBUILT_URL, TAG_BASE, FORK_BASE, "https://mirror.invalid/dl/",
81                     "http://example.invalid/engine/"):
82            self.assertFalse(setup.is_local(base), base)
83
84    def test_a_local_folder_asks_the_api_nothing_at_all(self):
85        # Air-gapped and shared-IP installs must not depend on GitHub answering.
86        with mock.patch.object(setup.netpolicy, "urlopen",
87                               side_effect=AssertionError("the API was called")):
88            self.assertIsNone(setup.engine_digest(ASSET, LOCAL_BASE))
89
90
91class DigestLookup(unittest.TestCase):
92    """`engine_digest`: the size and hash for one asset, from the releases API."""
93
94    def release_json(self, tag, assets):
95        return json.dumps({"tag_name": tag, "assets": assets}).encode("utf-8")
96
97    def asked(self, payload):
98        """Patch urlopen with a fake that serves `payload`; returns the list the URL goes into.
99
100        A list rather than a mock, because patching urlopen with a plain function hands back the function,
101        and the URL asked for is part of what is under test.
102        """
103        seen = []
104
105        class R:
106            def __init__(self, data):
107                self._b = io.BytesIO(data)
108
109            def read(self, *a):
110                return self._b.read(*a)
111
112            def __enter__(self):
113                return self
114
115            def __exit__(self, *a):
116                return False
117
118        def open_it(req, timeout=None):
119            seen.append(req.full_url)
120            return R(payload)
121
122        patcher = mock.patch.object(setup.netpolicy, "urlopen", open_it)
123        patcher.start()
124        self.addCleanup(patcher.stop)
125        return seen
126
127    def test_reads_the_tag_out_of_the_download_url(self):
128        # The URL already names the release, so the API call must ask for THAT release and not "latest":
129        # the tag URL is tried first (#214) so a checkout normally gets its own version's engine.
130        seen = self.asked(self.release_json(
131            "v0.1.40", [{"name": ASSET, "size": 42, "digest": "sha256:" + "a" * 64}]))
132        self.assertEqual(setup.engine_digest(ASSET, TAG_BASE), (42, "a" * 64))
133        self.assertEqual(seen, ["https://api.github.com/repos/Niko1221/Strata/releases/tags/v0.1.40"])
134
135    def test_latest_when_the_url_says_latest(self):
136        seen = self.asked(self.release_json(
137            "v0.1.40.1", [{"name": ASSET, "size": 7, "digest": "sha256:" + "b" * 64}]))
138        setup.engine_digest(ASSET, LATEST_BASE)
139        self.assertEqual(seen, ["https://api.github.com/repos/Niko1221/Strata/releases/latest"])
140
141    def test_asks_the_fork_for_a_fork_url(self):
142        seen = self.asked(self.release_json(
143            "v1.0", [{"name": ASSET, "size": 9, "digest": "sha256:" + "c" * 64}]))
144        self.assertEqual(setup.engine_digest(ASSET, FORK_BASE), (9, "c" * 64))
145        self.assertIn("/repos/someone/Strata/releases/tags/v1.0", seen[0])
146
147    def test_none_when_no_digest_is_published(self):
148        # No digest is not a pass. The caller refuses.
149        self.asked(self.release_json("v0.1.40", [{"name": ASSET, "size": 42}]))
150        self.assertIsNone(setup.engine_digest(ASSET, TAG_BASE))
151
152    def test_none_when_the_digest_is_not_a_sha256(self):
153        for other in ("md5:" + "d" * 32, "sha512:" + "e" * 128, "", None):
154            self.asked(self.release_json("v0.1.40",
155                                         [{"name": ASSET, "size": 42, "digest": other}]))
156            self.assertIsNone(setup.engine_digest(ASSET, TAG_BASE), other)
157
158    def test_none_when_the_asset_is_not_in_that_release(self):
159        # A CUDA 12 asset asked for on a release that has none, or a renamed asset. Refuse, do not verify
160        # against some other file's hash.
161        self.asked(self.release_json("v0.1.40",
162                                     [{"name": "other.zip", "size": 1, "digest": "sha256:" + "f" * 64}]))
163        self.assertIsNone(setup.engine_digest(ASSET, TAG_BASE))
164
165    def test_none_when_github_cannot_be_reached(self):
166        for exc in (OSError("no network"), TimeoutError("slow")):
167            with mock.patch.object(setup.netpolicy, "urlopen", side_effect=exc):
168                self.assertIsNone(setup.engine_digest(ASSET, TAG_BASE), exc)
169
170    def test_picks_the_asset_the_url_actually_wants(self):
171        # v0.1.40.1 ships several engine builds with different hashes; the one asked for must be the one
172        # used, not whichever the API lists first.
173        self.asked(self.release_json("v0.1.40.1", [
174            {"name": "strata-windows-x64.zip", "size": 1, "digest": "sha256:" + "1" * 64},
175            {"name": "strata-windows-x64-cuda12.zip", "size": 2, "digest": "sha256:" + "2" * 64},
176            {"name": HIP_ASSET, "size": 3, "digest": "sha256:" + "3" * 64},
177        ]))
178        self.assertEqual(setup.engine_digest("strata-windows-x64-cuda12.zip", LATEST_BASE), (2, "2" * 64))
179        self.assertEqual(setup.engine_digest(HIP_ASSET, LATEST_BASE), (3, "3" * 64))
180
181
182class ArchiveVerification(unittest.TestCase):
183    """`verify_engine_archive`: the downloaded file against the published size and hash."""
184
185    def setUp(self):
186        self.tmp = tempfile.TemporaryDirectory()
187        self.addCleanup(self.tmp.cleanup)
188        self.z = Path(self.tmp.name) / ASSET
189        self.data = zip_bytes()
190        self.z.write_bytes(self.data)
191        patch = mock.patch.dict(os.environ, {}, clear=False)
192        env = patch.start()
193        self.addCleanup(patch.stop)
194        env.pop("STRATA_SKIP_SHA256", None)
195
196    def digest(self, value):
197        return mock.patch.object(setup, "engine_digest", return_value=value)
198
199    def test_passes_when_the_hash_matches(self):
200        with self.digest((len(self.data), sha_of(self.data))):
201            setup.verify_engine_archive(self.z, ASSET, TAG_BASE)      # must not raise
202        self.assertTrue(self.z.exists())
203
204    def test_refuses_a_wrong_hash_and_deletes_the_file(self):
205        # A wrong engine left on disk is the thing this exists to prevent, so it goes.
206        with self.digest((len(self.data), "0" * 64)):
207            with self.assertRaises(setup.UnverifiedEngine) as caught:
208                setup.verify_engine_archive(self.z, ASSET, TAG_BASE)
209        self.assertIn("wrong SHA-256", str(caught.exception))
210        self.assertFalse(self.z.exists())
211        self.assertFalse(self.z.with_name(self.z.name + ".done").exists())
212
213    def test_refuses_a_wrong_size_before_hashing(self):
214        with self.digest((len(self.data) + 1, sha_of(self.data))):
215            with self.assertRaises(setup.UnverifiedEngine) as caught:
216                setup.verify_engine_archive(self.z, ASSET, TAG_BASE)
217        self.assertIn("not the published", str(caught.exception))
218        self.assertFalse(self.z.exists())
219
220    def test_a_same_size_impostor_is_caught_by_the_hash_alone(self):
221        # The case Content-Length cannot see, and the reason the hash is there at all.
222        impostor = b"x" * len(self.data)
223        self.z.write_bytes(impostor)
224        with self.digest((len(impostor), sha_of(self.data))):
225            with self.assertRaises(setup.UnverifiedEngine):
226                setup.verify_engine_archive(self.z, ASSET, TAG_BASE)
227        self.assertFalse(self.z.exists())
228
229    def test_no_digest_warns_and_installs_anyway(self):
230        # "recommend, never force": no digest (offline, rate limit, mirror, folder) is a warning, not a refusal.
231        for base in (TAG_BASE, LOCAL_BASE, "https://mirror.invalid/dl/"):
232            said = io.StringIO()
233            with self.digest(None), mock.patch.object(setup, "warn", said.write):
234                setup.verify_engine_archive(self.z, ASSET, base)     # must not raise
235            self.assertIn("NOT verified", said.getvalue(), base)
236            self.assertTrue(self.z.exists())
237
238    def test_skip_env_skips_the_check_loudly(self):
239        os.environ["STRATA_SKIP_SHA256"] = "1"
240        said = io.StringIO()
241        with mock.patch.object(setup, "engine_digest", return_value=(1, "0" * 64)) as m,                 mock.patch.object(setup, "warn", said.write):
242            setup.verify_engine_archive(self.z, ASSET, TAG_BASE)     # a wrong digest, but skipped
243        self.assertEqual(m.call_count, 0)
244        self.assertIn("STRATA_SKIP_SHA256", said.getvalue())
245        self.assertIn("NOT checking", said.getvalue())
246        self.assertTrue(self.z.exists())
247
248    def test_skip_env_needs_exactly_1(self):
249        os.environ["STRATA_SKIP_SHA256"] = "0"
250        with self.digest((1, "0" * 64)):
251            with self.assertRaises(setup.UnverifiedEngine):
252                setup.verify_engine_archive(self.z, ASSET, TAG_BASE)
253
254    def test_a_truncated_archive_is_refused(self):
255        # There is no finish mark any more, so nothing can vouch for a file that changed after it was
256        # checked. Measured cost of that decision: 190 MB hashes in 0.79 s at 242 MB/s on this machine,
257        # against 3.0 s to download the same file, so re-checking is not worth saving.
258        with self.digest((len(self.data), sha_of(self.data))):
259            setup.verify_engine_archive(self.z, ASSET, TAG_BASE)
260            with open(self.z, "r+b") as f:
261                f.truncate(len(self.data) // 2)
262            with self.assertRaises(setup.UnverifiedEngine) as caught:
263                setup.verify_engine_archive(self.z, ASSET, TAG_BASE)
264        self.assertIn("not the published", str(caught.exception))
265
266    def test_a_same_length_change_after_verification_is_refused(self):
267        # The hole the mark left: same length, so the size check passes, and the mark would have vouched
268        # for it. With no mark, the hash is recomputed and it is caught.
269        with self.digest((len(self.data), sha_of(self.data))):
270            setup.verify_engine_archive(self.z, ASSET, TAG_BASE)
271            with open(self.z, "r+b") as f:
272                f.seek(0)
273                f.write(b"X")
274            with self.assertRaises(setup.UnverifiedEngine) as caught:
275                setup.verify_engine_archive(self.z, ASSET, TAG_BASE)
276        self.assertIn("wrong SHA-256", str(caught.exception))
277
278    def test_the_api_is_asked_once_not_twice(self):
279        # It is a rate-limited API and an install is not the place to spend two calls on one lookup.
280        with mock.patch.object(setup, "engine_digest",
281                               return_value=(len(self.data), sha_of(self.data))) as m:
282            setup.verify_engine_archive(self.z, ASSET, TAG_BASE)
283        self.assertEqual(m.call_count, 1, f"engine_digest was called {m.call_count} times")
284
285
286class WhatARefusalDoesToTheCaller(unittest.TestCase):
287    """`engine_refused`, and the paths that call it.
288
289    This is where the adversarial pass found the worst bug: a refusal used to end in `fail()`, i.e.
290    `sys.exit(1)`, which is a BaseException, so the engine-UPDATE paths' `except Exception` could not catch
291    it and setup died instead of starting with the engine it already had.
292    """
293
294    def setUp(self):
295        self.tmp = tempfile.TemporaryDirectory()
296        self.addCleanup(self.tmp.cleanup)
297        (Path(self.tmp.name) / "engine").mkdir(parents=True, exist_ok=True)
298        # get_prebuilt looks for the release with a HEAD request before it downloads (0.2.0), and keeps the engine in
299        # an engine folder of its own: no network, and never this checkout's engine folder.  A published release answers the probe.
300        for patcher in (mock.patch.object(setup, "engine_dir", lambda toolkit=13: Path(self.tmp.name) / "engine"),
301                        mock.patch.object(setup, "_urlopen", lambda req, timeout=None: mock.MagicMock())):
302            patcher.start()
303            self.addCleanup(patcher.stop)
304
305    def fake_download(self, url, dst, what=None):
306        with zipfile.ZipFile(dst, "w") as z:
307            z.writestr("BUILD.json", json.dumps({"version": "0.1.40", "archs": [89]}))
308            z.writestr(setup.EXE, b"engine")
309
310    def get_prebuilt(self, updating, digest):
311        out = io.StringIO()
312        with contextlib_redirect(out),                 mock.patch.object(setup, "download", self.fake_download),                 mock.patch.object(setup, "engine_digest", return_value=digest):
313            return setup.get_prebuilt(setup.PREBUILT_URL, {"arch": 89}, "gpu", updating=updating), out
314
315    def test_updating_keeps_the_installed_engine_instead_of_stopping(self):
316        # The call site's own words: "a failed download must not stop the model from starting".
317        for digest in ((999, "f" * 64), (1, "0" * 64)):
318            eng, out = self.get_prebuilt(updating=True, digest=digest)
319            self.assertIsNone(eng, f"digest={digest!r} did not return None")
320        self.assertNotIn("Setup stopped", out.getvalue(),
321                         "a refusal while updating must not claim setup stopped")
322        self.assertIn("keeping the engine that is installed", out.getvalue())
323
324    def test_a_refusal_is_an_exception_the_update_path_can_catch(self):
325        # The regression guard for the actual bug: SystemExit escaped this guard before.
326        self.assertTrue(issubclass(setup.UnverifiedEngine, Exception))
327        self.assertFalse(issubclass(SystemExit, Exception))
328        eng, _ = self.get_prebuilt(updating=True, digest=(999, "f" * 64))
329        self.assertIsNone(eng, "a refusal must not escape get_prebuilt as SystemExit")
330
331    def test_a_first_install_stops_because_there_is_nothing_to_fall_back_to(self):
332        with mock.patch.object(setup, "download", self.fake_download),                 mock.patch.object(setup, "engine_digest", return_value=(999, "f" * 64)):
333            with self.assertRaises(SystemExit):
334                setup.get_prebuilt(setup.PREBUILT_URL, {"arch": 89}, "gpu")
335
336    def test_the_cuda_and_amd_paths_both_verify(self):
337        # get_prebuilt_hip downloads the AMD engine from a SECOND `download(base + ...)` call site, which
338        # the first version of this change missed entirely - so AMD users got nothing from it.
339        src = (ROOT / "setup.py").read_text(encoding="utf-8")
340        for call in ('download(base + asset, z, "Strata engine")',
341                     'download(base + WIN_HIP_ASSET, z, "Strata AMD engine")'):
342            i = src.index(call)
343            self.assertIn("verify_engine_archive", src[i:i + 400], f"{call} is not verified")
344
345
346class Wiring(unittest.TestCase):
347    """The check is reached, and reached before the archive is opened."""
348
349    def test_get_prebuilt_verifies_before_it_unpacks(self):
350        src = (ROOT / "setup.py").read_text(encoding="utf-8")
351        body = src[src.index("def get_prebuilt("):]
352        body = body[:body.index("\ndef ")]
353        i_verify = body.index("verify_engine_archive(")
354        for opener in ("ZipFile(", "_unpack", "install_unpacked"):
355            self.assertGreater(body.index(opener), i_verify,
356                               f"{opener} happens before the SHA-256 is checked")
357
358    def test_the_digest_is_read_from_the_api_not_the_download_host(self):
359        src = (ROOT / "setup.py").read_text(encoding="utf-8")
360        # release_of() builds the API URL, from the OWNER/REPO in the download URL - so a mirror of this
361        # repository is checked against this repository's published hash, not against whatever the mirror
362        # happens to be serving.
363        body = src[src.index("def release_of("):]
364        body = body[:body.index("\ndef ")]
365        self.assertIn("api.github.com/repos/", body)
366        self.assertIn("m.group(1)", body, "the repository comes out of the URL, not a constant")
367        # and engine_digest asks release_of rather than the download URL
368        body = src[src.index("def engine_digest("):]
369        body = body[:body.index("\ndef ")]
370        self.assertIn("release_of(base)", body)
371
372
373class contextlib_redirect:
374    """stdout into a StringIO, without importing contextlib under a name setup.py also uses."""
375
376    def __init__(self, buf):
377        self.buf = buf
378
379    def __enter__(self):
380        self.old = sys.stdout
381        sys.stdout = self.buf
382        return self
383
384    def __exit__(self, *a):
385        sys.stdout = self.old
386        return False
387
388
389if __name__ == "__main__":
390    unittest.main()