okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
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 9python -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.""" 40buf = io .BytesIO () 41with zipfile .ZipFile (buf ,"w" )as zf : 42zf .writestr ("strata.exe" ,b"not a real engine" ) 43zf .writestr ("BUILD.json" ,b'{"version": "0.1.40"}' ) 44return buf .getvalue () 45 46 47def sha_of (b :bytes )-> str : 48return 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 54def test_a_tag_url_names_its_tag (self ): 55self .assertEqual (setup .release_of (TAG_BASE ), 56 ("https://api.github.com/repos/Niko1221/Strata/releases" ,"0.1.40" )) 57 58def test_the_latest_url_names_no_tag (self ): 59self .assertEqual (setup .release_of (LATEST_BASE ), 60 ("https://api.github.com/repos/Niko1221/Strata/releases" ,None )) 61 62def 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. 65self .assertEqual (setup .release_of (FORK_BASE ), 66 ("https://api.github.com/repos/someone/Strata/releases" ,"1.0" )) 67 68def 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. 71for base in (LOCAL_BASE ,"https://mirror.invalid/dl/" ,"/mnt/mirror" ,"\\\\share\\engine" ): 72self .assertIsNone (setup .release_of (base ),base ) 73 74def 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. 77for base in (LOCAL_BASE ,r"C:\\mirror" ,"/mnt/mirror" ,"file:///srv/engine" , 78r"\\\\share\\engine" ): 79self .assertTrue (setup .is_local (base ),base ) 80for base in (setup .PREBUILT_URL ,TAG_BASE ,FORK_BASE ,"https://mirror.invalid/dl/" , 81"http://example.invalid/engine/" ): 82self .assertFalse (setup .is_local (base ),base ) 83 84def test_a_local_folder_asks_the_api_nothing_at_all (self ): 85# Air-gapped and shared-IP installs must not depend on GitHub answering. 86with mock .patch .object (setup .netpolicy ,"urlopen" , 87side_effect = AssertionError ("the API was called" )): 88self .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 94def release_json (self ,tag ,assets ): 95return json .dumps ({"tag_name" :tag ,"assets" :assets }).encode ("utf-8" ) 96 97def asked (self ,payload ): 98"""Patch urlopen with a fake that serves `payload`; returns the list the URL goes into. 99 100A list rather than a mock, because patching urlopen with a plain function hands back the function, 101and the URL asked for is part of what is under test. 102""" 103seen = [] 104 105class R : 106def __init__ (self ,data ): 107self ._b = io .BytesIO (data ) 108 109def read (self ,* a ): 110return self ._b .read (* a ) 111 112def __enter__ (self ): 113return self 114 115def __exit__ (self ,* a ): 116return False 117 118def open_it (req ,timeout = None ): 119seen .append (req .full_url ) 120return R (payload ) 121 122patcher = mock .patch .object (setup .netpolicy ,"urlopen" ,open_it ) 123patcher .start () 124self .addCleanup (patcher .stop ) 125return seen 126 127def 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. 130seen = self .asked (self .release_json ( 131"v0.1.40" , [{"name" :ASSET ,"size" :42 ,"digest" :"sha256:" + "a" * 64 }])) 132self .assertEqual (setup .engine_digest (ASSET ,TAG_BASE ), (42 ,"a" * 64 )) 133self .assertEqual (seen , ["https://api.github.com/repos/Niko1221/Strata/releases/tags/v0.1.40" ]) 134 135def test_latest_when_the_url_says_latest (self ): 136seen = self .asked (self .release_json ( 137"v0.1.40.1" , [{"name" :ASSET ,"size" :7 ,"digest" :"sha256:" + "b" * 64 }])) 138setup .engine_digest (ASSET ,LATEST_BASE ) 139self .assertEqual (seen , ["https://api.github.com/repos/Niko1221/Strata/releases/latest" ]) 140 141def test_asks_the_fork_for_a_fork_url (self ): 142seen = self .asked (self .release_json ( 143"v1.0" , [{"name" :ASSET ,"size" :9 ,"digest" :"sha256:" + "c" * 64 }])) 144self .assertEqual (setup .engine_digest (ASSET ,FORK_BASE ), (9 ,"c" * 64 )) 145self .assertIn ("/repos/someone/Strata/releases/tags/v1.0" ,seen [0 ]) 146 147def test_none_when_no_digest_is_published (self ): 148# No digest is not a pass. The caller refuses. 149self .asked (self .release_json ("v0.1.40" , [{"name" :ASSET ,"size" :42 }])) 150self .assertIsNone (setup .engine_digest (ASSET ,TAG_BASE )) 151 152def test_none_when_the_digest_is_not_a_sha256 (self ): 153for other in ("md5:" + "d" * 32 ,"sha512:" + "e" * 128 ,"" ,None ): 154self .asked (self .release_json ("v0.1.40" , 155 [{"name" :ASSET ,"size" :42 ,"digest" :other }])) 156self .assertIsNone (setup .engine_digest (ASSET ,TAG_BASE ),other ) 157 158def 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. 161self .asked (self .release_json ("v0.1.40" , 162 [{"name" :"other.zip" ,"size" :1 ,"digest" :"sha256:" + "f" * 64 }])) 163self .assertIsNone (setup .engine_digest (ASSET ,TAG_BASE )) 164 165def test_none_when_github_cannot_be_reached (self ): 166for exc in (OSError ("no network" ),TimeoutError ("slow" )): 167with mock .patch .object (setup .netpolicy ,"urlopen" ,side_effect = exc ): 168self .assertIsNone (setup .engine_digest (ASSET ,TAG_BASE ),exc ) 169 170def 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. 173self .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 ])) 178self .assertEqual (setup .engine_digest ("strata-windows-x64-cuda12.zip" ,LATEST_BASE ), (2 ,"2" * 64 )) 179self .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 185def setUp (self ): 186self .tmp = tempfile .TemporaryDirectory () 187self .addCleanup (self .tmp .cleanup ) 188self .z = Path (self .tmp .name )/ ASSET 189self .data = zip_bytes () 190self .z .write_bytes (self .data ) 191patch = mock .patch .dict (os .environ , {},clear = False ) 192env = patch .start () 193self .addCleanup (patch .stop ) 194env .pop ("STRATA_SKIP_SHA256" ,None ) 195 196def digest (self ,value ): 197return mock .patch .object (setup ,"engine_digest" ,return_value = value ) 198 199def test_passes_when_the_hash_matches (self ): 200with self .digest ((len (self .data ),sha_of (self .data ))): 201setup .verify_engine_archive (self .z ,ASSET ,TAG_BASE )# must not raise 202self .assertTrue (self .z .exists ()) 203 204def 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. 206with self .digest ((len (self .data ),"0" * 64 )): 207with self .assertRaises (setup .UnverifiedEngine )as caught : 208setup .verify_engine_archive (self .z ,ASSET ,TAG_BASE ) 209self .assertIn ("wrong SHA-256" ,str (caught .exception )) 210self .assertFalse (self .z .exists ()) 211self .assertFalse (self .z .with_name (self .z .name + ".done" ).exists ()) 212 213def test_refuses_a_wrong_size_before_hashing (self ): 214with self .digest ((len (self .data )+ 1 ,sha_of (self .data ))): 215with self .assertRaises (setup .UnverifiedEngine )as caught : 216setup .verify_engine_archive (self .z ,ASSET ,TAG_BASE ) 217self .assertIn ("not the published" ,str (caught .exception )) 218self .assertFalse (self .z .exists ()) 219 220def 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. 222impostor = b"x" * len (self .data ) 223self .z .write_bytes (impostor ) 224with self .digest ((len (impostor ),sha_of (self .data ))): 225with self .assertRaises (setup .UnverifiedEngine ): 226setup .verify_engine_archive (self .z ,ASSET ,TAG_BASE ) 227self .assertFalse (self .z .exists ()) 228 229def 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. 231for base in (TAG_BASE ,LOCAL_BASE ,"https://mirror.invalid/dl/" ): 232said = io .StringIO () 233with self .digest (None ),mock .patch .object (setup ,"warn" ,said .write ): 234setup .verify_engine_archive (self .z ,ASSET ,base )# must not raise 235self .assertIn ("NOT verified" ,said .getvalue (),base ) 236self .assertTrue (self .z .exists ()) 237 238def test_skip_env_skips_the_check_loudly (self ): 239os .environ ["STRATA_SKIP_SHA256" ]= "1" 240said = io .StringIO () 241with mock .patch .object (setup ,"engine_digest" ,return_value = (1 ,"0" * 64 ))as m ,mock .patch .object (setup ,"warn" ,said .write ): 242setup .verify_engine_archive (self .z ,ASSET ,TAG_BASE )# a wrong digest, but skipped 243self .assertEqual (m .call_count ,0 ) 244self .assertIn ("STRATA_SKIP_SHA256" ,said .getvalue ()) 245self .assertIn ("NOT checking" ,said .getvalue ()) 246self .assertTrue (self .z .exists ()) 247 248def test_skip_env_needs_exactly_1 (self ): 249os .environ ["STRATA_SKIP_SHA256" ]= "0" 250with self .digest ((1 ,"0" * 64 )): 251with self .assertRaises (setup .UnverifiedEngine ): 252setup .verify_engine_archive (self .z ,ASSET ,TAG_BASE ) 253 254def 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. 258with self .digest ((len (self .data ),sha_of (self .data ))): 259setup .verify_engine_archive (self .z ,ASSET ,TAG_BASE ) 260with open (self .z ,"r+b" )as f : 261f .truncate (len (self .data )// 2 ) 262with self .assertRaises (setup .UnverifiedEngine )as caught : 263setup .verify_engine_archive (self .z ,ASSET ,TAG_BASE ) 264self .assertIn ("not the published" ,str (caught .exception )) 265 266def 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. 269with self .digest ((len (self .data ),sha_of (self .data ))): 270setup .verify_engine_archive (self .z ,ASSET ,TAG_BASE ) 271with open (self .z ,"r+b" )as f : 272f .seek (0 ) 273f .write (b"X" ) 274with self .assertRaises (setup .UnverifiedEngine )as caught : 275setup .verify_engine_archive (self .z ,ASSET ,TAG_BASE ) 276self .assertIn ("wrong SHA-256" ,str (caught .exception )) 277 278def 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. 280with mock .patch .object (setup ,"engine_digest" , 281return_value = (len (self .data ),sha_of (self .data )))as m : 282setup .verify_engine_archive (self .z ,ASSET ,TAG_BASE ) 283self .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 289This 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 291it and setup died instead of starting with the engine it already had. 292""" 293 294def setUp (self ): 295self .tmp = tempfile .TemporaryDirectory () 296self .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. 300for patcher in (mock .patch .object (setup ,"engine_dir" ,lambda toolkit = 13 :Path (self .tmp .name )/ "engine" ), 301mock .patch .object (setup ,"_urlopen" ,lambda req ,timeout = None :mock .MagicMock ())): 302patcher .start () 303self .addCleanup (patcher .stop ) 304 305def fake_download (self ,url ,dst ,what = None ): 306with zipfile .ZipFile (dst ,"w" )as z : 307z .writestr ("BUILD.json" ,json .dumps ({"version" :"0.1.40" ,"archs" : [89 ]})) 308z .writestr (setup .EXE ,b"engine" ) 309 310def get_prebuilt (self ,updating ,digest ): 311out = io .StringIO () 312with contextlib_redirect (out ),mock .patch .object (setup ,"download" ,self .fake_download ),mock .patch .object (setup ,"engine_digest" ,return_value = digest ): 313return setup .get_prebuilt (setup .PREBUILT_URL , {"arch" :89 },"gpu" ,updating = updating ),out 314 315def 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". 317for digest in ((999 ,"f" * 64 ), (1 ,"0" * 64 )): 318eng ,out = self .get_prebuilt (updating = True ,digest = digest ) 319self .assertIsNone (eng ,f"digest= { digest !r } did not return None" ) 320self .assertNotIn ("Setup stopped" ,out .getvalue (), 321"a refusal while updating must not claim setup stopped" ) 322self .assertIn ("keeping the engine that is installed" ,out .getvalue ()) 323 324def 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. 326self .assertTrue (issubclass (setup .UnverifiedEngine ,Exception )) 327self .assertFalse (issubclass (SystemExit ,Exception )) 328eng ,_ = self .get_prebuilt (updating = True ,digest = (999 ,"f" * 64 )) 329self .assertIsNone (eng ,"a refusal must not escape get_prebuilt as SystemExit" ) 330 331def test_a_first_install_stops_because_there_is_nothing_to_fall_back_to (self ): 332with mock .patch .object (setup ,"download" ,self .fake_download ),mock .patch .object (setup ,"engine_digest" ,return_value = (999 ,"f" * 64 )): 333with self .assertRaises (SystemExit ): 334setup .get_prebuilt (setup .PREBUILT_URL , {"arch" :89 },"gpu" ) 335 336def 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. 339src = (ROOT / "setup.py" ).read_text (encoding = "utf-8" ) 340for call in ('download(base + asset, z, "Strata engine")' , 341'download(base + WIN_HIP_ASSET, z, "Strata AMD engine")' ): 342i = src .index (call ) 343self .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 349def test_get_prebuilt_verifies_before_it_unpacks (self ): 350src = (ROOT / "setup.py" ).read_text (encoding = "utf-8" ) 351body = src [src .index ("def get_prebuilt(" ):] 352body = body [:body .index ("\ndef " )] 353i_verify = body .index ("verify_engine_archive(" ) 354for opener in ("ZipFile(" ,"_unpack" ,"install_unpacked" ): 355self .assertGreater (body .index (opener ),i_verify , 356f" { opener } happens before the SHA-256 is checked" ) 357 358def test_the_digest_is_read_from_the_api_not_the_download_host (self ): 359src = (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. 363body = src [src .index ("def release_of(" ):] 364body = body [:body .index ("\ndef " )] 365self .assertIn ("api.github.com/repos/" ,body ) 366self .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 368body = src [src .index ("def engine_digest(" ):] 369body = body [:body .index ("\ndef " )] 370self .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 376def __init__ (self ,buf ): 377self .buf = buf 378 379def __enter__ (self ): 380self .old = sys .stdout 381sys .stdout = self .buf 382return self 383 384def __exit__ (self ,* a ): 385sys .stdout = self .old 386return False 387 388 389if __name__ == "__main__" : 390unittest .main ()