okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1"""Component store tests (checklist P06, P07, P11, P12, P13). 2 3The security tests here use the actual attack shapes rather than a generic "bad path", because the 4failure this guards against is arbitrary file writes from a hostile archive, and each shape defeats a 5different naive check: 6 7* ``../`` escapes a destination that only joins paths; 8* a leading ``/`` defeats a check that only looks for ``..``; 9* a Windows drive letter defeats a POSIX-only check on a Windows host; 10* a backslash separator defeats a check that only splits on ``/``; 11* a symlink pointing outside defeats every name-based check, because the *name* is innocent. 12 13Every refusal is asserted to leave the destination directory **empty**: checking after extraction 14would be too late. 15""" 16 17from __future__import annotations 18 19import io 20import json 21import os 22import stat 23import sys 24import tarfile 25import tempfile 26import unittest 27import zipfile 28from pathlib import Path 29 30sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [1 ])) 31 32from strata_control import components as C # noqa: E402 33 34 35def manifest (** over )-> dict : 36base = { 37"schema_version" :1 , 38"id" :"strata-engine" , 39"version" :"0.1.44.1" , 40"kind" :"engine" , 41"backend" :"metal" , 42"platforms" : ["macos-arm64" ], 43"artifacts" : [{"name" :"engine.tar.gz" ,"url" :"https://example.invalid/e.tar.gz" , 44"sha256" :"a" * 64 ,"bytes" :1024 ,"format" :"tar.gz" }], 45"license" :"proprietary" , 46 } 47base .update (over ) 48return base 49 50 51def tar_bytes (entries :list [tuple [str ,bytes ]],* ,links :list [tuple [str ,str ]]| None = None , 52devices :bool = False )-> bytes : 53buffer = io .BytesIO () 54with tarfile .open (fileobj = buffer ,mode = "w:gz" )as tar : 55for name ,payload in entries : 56info = tarfile .TarInfo (name ) 57info .size = len (payload ) 58info .mode = 0o644 59tar .addfile (info ,io .BytesIO (payload )) 60for name ,target in (links or []): 61info = tarfile .TarInfo (name ) 62info .type = tarfile .SYMTYPE 63info .linkname = target 64tar .addfile (info ) 65if devices : 66info = tarfile .TarInfo ("dev/null" ) 67info .type = tarfile .CHRTYPE 68info .devmajor ,info .devminor = 1 ,3 69tar .addfile (info ) 70return buffer .getvalue () 71 72 73class StoreCase (unittest .TestCase ): 74def setUp (self ): 75self .tmp = Path (tempfile .mkdtemp (prefix = "strata-components-" )) 76self .store = C .ComponentStore (self .tmp / "store" ) 77 78def tearDown (self ): 79import shutil 80shutil .rmtree (self .tmp ,ignore_errors = True ) 81 82def payload (self ,data :bytes ,name :str = "engine.tar.gz" )-> tuple [C .Component ,dict ]: 83import hashlib 84man = manifest (artifacts = [{"name" :name ,"url" :None , 85"sha256" :hashlib .sha256 (data ).hexdigest (), 86"bytes" :len (data ),"format" :"tar.gz" }]) 87return C .parse_manifest (man ), {name :data } 88 89 90class TestManifestParsing (StoreCase ): 91def test_a_valid_manifest_parses (self ): 92c = C .parse_manifest (manifest ()) 93self .assertEqual (c .id ,"strata-engine" ) 94self .assertEqual (c .backend ,"metal" ) 95self .assertEqual (len (c .artifacts ),1 ) 96 97def test_a_manifest_without_a_digest_is_refused (self ): 98bad = manifest (artifacts = [{"name" :"e.tar.gz" ,"sha256" :"" ,"bytes" :10 }]) 99with self .assertRaises (C .ComponentError )as ctx : 100C .parse_manifest (bad ) 101self .assertIn ("sha256" ,str (ctx .exception )) 102 103def test_a_short_or_non_hex_digest_is_refused (self ): 104for digest in ("abc" ,"z" * 64 ,"A" * 63 ): 105with self .assertRaises (C .ComponentError ): 106C .parse_manifest (manifest (artifacts = [{"name" :"e" ,"sha256" :digest ,"bytes" :1 }])) 107 108def test_an_unknown_kind_is_refused (self ): 109with self .assertRaises (C .ComponentError )as ctx : 110C .parse_manifest (manifest (kind = "kernel" )) 111self .assertIn ("unknown component kind" ,str (ctx .exception )) 112 113def test_a_manifest_that_does_not_state_its_platforms_is_refused (self ): 114"""An unstated platform would be read as every platform, which is the unsafe default.""" 115bad = manifest () 116bad .pop ("platforms" ) 117with self .assertRaises (C .ComponentError )as ctx : 118C .parse_manifest (bad ) 119self .assertIn ("which platforms" ,str (ctx .exception )) 120 121def test_an_artifact_name_that_is_a_path_is_refused (self ): 122for name in ("../../etc/passwd" ,"sub/dir" ,".." ,"a\\b" ): 123with self .assertRaises (C .ComponentError ): 124C .parse_manifest (manifest (artifacts = [ 125 {"name" :name ,"sha256" :"a" * 64 ,"bytes" :1 }])) 126 127def test_an_unknown_schema_version_is_refused (self ): 128with self .assertRaises (C .ComponentError )as ctx : 129C .parse_manifest (manifest (schema_version = 99 )) 130self .assertIn ("schema_version" ,str (ctx .exception )) 131 132def test_malformed_json_is_refused_with_the_parse_error (self ): 133with self .assertRaises (C .ComponentError )as ctx : 134C .parse_manifest ("{not json" ) 135self .assertIn ("not valid JSON" ,str (ctx .exception )) 136 137def test_the_cache_key_is_the_bytes_not_the_version_label (self ): 138"""A rebuilt artifact with the same version must be a different key.""" 139a = C .parse_manifest (manifest ()) 140b = C .parse_manifest (manifest (artifacts = [{"name" :"engine.tar.gz" ,"url" :None , 141"sha256" :"b" * 64 ,"bytes" :1024 }])) 142self .assertEqual (a .version ,b .version ,"the label is the same" ) 143self .assertNotEqual (a .cache_key ,b .cache_key ,"the bytes differ, so the key must differ" ) 144 145 146class TestCompatibility (StoreCase ): 147def test_a_component_for_this_platform_is_compatible (self ): 148self .assertEqual (C .check_compatible (C .parse_manifest (manifest ()),target = "macos-arm64" ), []) 149 150def test_another_platform_is_refused_with_both_named (self ): 151reasons = C .check_compatible (C .parse_manifest (manifest ()),target = "linux-x86_64" ) 152self .assertTrue (reasons ) 153self .assertIn ("macos-arm64" ,reasons [0 ]) 154self .assertIn ("linux-x86_64" ,reasons [0 ]) 155 156def test_a_backend_that_is_not_committed_to_on_a_platform_is_refused (self ): 157"""Windows SYCL and Intel Macs are explicitly not supported, not merely untested.""" 158ok ,why = C .backend_supported ("sycl" ,"windows-x86_64" ) 159self .assertFalse (ok ) 160self .assertIn ("not a supported combination" ,why ) 161ok ,why = C .backend_supported ("metal" ,"macos-x86_64" ) 162self .assertFalse (ok ,"Intel Macs are excluded from local Metal support" ) 163self .assertTrue (C .backend_supported ("metal" ,"macos-arm64" )[0 ]) 164self .assertTrue (C .backend_supported ("cuda" ,"linux-x86_64" )[0 ]) 165self .assertTrue (C .backend_supported ("sycl" ,"linux-x86_64" )[0 ]) 166 167def test_an_unknown_backend_is_refused (self ): 168ok ,why = C .backend_supported ("vulkan" ,"linux-x86_64" ) 169self .assertFalse (ok ) 170self .assertIn ("unknown backend family" ,why ) 171 172def test_a_component_for_another_backend_is_refused (self ): 173c = C .parse_manifest (manifest (backend = "metal" ,platforms = ["macos-arm64" ])) 174reasons = C .check_compatible (c ,target = "macos-arm64" ,backend = "cuda" ) 175self .assertTrue (any ("built for the metal backend" in r for r in reasons ),reasons ) 176 177 178class TestSafeExtraction (StoreCase ): 179"""The attack shapes, each asserted to write nothing.""" 180 181def extract (self ,data :bytes ,name :str = "a.tar.gz" )-> Path : 182archive = self .tmp / name 183archive .write_bytes (data ) 184destination = self .tmp / "out" 185C .safe_extract (archive ,destination ) 186return destination 187 188def assert_refused_and_empty (self ,data :bytes ,expect :str ): 189destination = self .tmp / "out" 190with self .assertRaises (C .UnsafeArchive )as ctx : 191archive = self .tmp / "bad.tar.gz" 192archive .write_bytes (data ) 193C .safe_extract (archive ,destination ) 194self .assertIn (expect ,str (ctx .exception )) 195present = sorted (p .name for p in destination .rglob ("*" ))if destination .exists ()else [] 196self .assertEqual (present , [],f"a refusal must leave nothing behind, found { present } " ) 197 198def test_a_normal_archive_extracts (self ): 199out = self .extract (tar_bytes ([("bin/strata" ,b"#!/bin/sh\n" ), ("README" ,b"hi" )])) 200self .assertEqual ((out / "bin/strata" ).read_bytes (),b"#!/bin/sh\n" ) 201self .assertEqual ((out / "README" ).read_bytes (),b"hi" ) 202 203def test_a_parent_segment_is_refused (self ): 204self .assert_refused_and_empty (tar_bytes ([("../escaped" ,b"x" )]),"'..' segment" ) 205 206def test_a_nested_parent_segment_is_refused (self ): 207self .assert_refused_and_empty (tar_bytes ([("a/b/../../../escaped" ,b"x" )]),"'..' segment" ) 208 209def test_an_absolute_path_is_refused (self ): 210self .assert_refused_and_empty (tar_bytes ([("/etc/passwd" ,b"x" )]),"absolute path" ) 211 212def test_a_windows_drive_path_is_refused (self ): 213self .assert_refused_and_empty (tar_bytes ([("C:\\Windows\\evil" ,b"x" )]),"drive-letter" ) 214 215def test_a_backslash_parent_segment_is_refused (self ): 216self .assert_refused_and_empty (tar_bytes ([("..\\escaped" ,b"x" )]),"'..' segment" ) 217 218def test_a_unc_path_is_refused (self ): 219self .assert_refused_and_empty (tar_bytes ([("//server/share/evil" ,b"x" )]),"absolute path" ) 220 221def test_a_symlink_is_refused (self ): 222"""A symlink's *name* is innocent, so only refusing links catches it.""" 223self .assert_refused_and_empty ( 224tar_bytes ([("link" ,b"" )],links = [("escape" ,"/etc/passwd" )]),"symlink" ) 225 226def test_a_device_member_is_refused (self ): 227self .assert_refused_and_empty (tar_bytes ([("ok" ,b"x" )],devices = True ),"device" ) 228 229def test_a_good_member_before_a_bad_one_does_not_leave_the_good_one (self ): 230"""Validation happens over the whole archive first, so nothing is written before a refusal.""" 231self .assert_refused_and_empty ( 232tar_bytes ([("fine.txt" ,b"hello" ), ("../escaped" ,b"x" )]),"'..' segment" ) 233 234def test_a_zip_with_a_parent_segment_is_refused (self ): 235buffer = io .BytesIO () 236with zipfile .ZipFile (buffer ,"w" )as zf : 237zf .writestr ("../escaped" ,"x" ) 238archive = self .tmp / "bad.zip" 239archive .write_bytes (buffer .getvalue ()) 240destination = self .tmp / "out" 241with self .assertRaises (C .UnsafeArchive ): 242C .safe_extract (archive ,destination ,fmt = "zip" ) 243self .assertFalse (destination .exists ()and any (destination .rglob ("*" ))) 244 245def test_the_executable_bit_survives_and_nothing_else_does (self ): 246buffer = io .BytesIO () 247with tarfile .open (fileobj = buffer ,mode = "w:gz" )as tar : 248info = tarfile .TarInfo ("bin/run" ) 249info .size = 2 250info .mode = 0o4755 # setuid, which must not survive 251tar .addfile (info ,io .BytesIO (b"#\n" )) 252out = self .extract (buffer .getvalue ()) 253mode = (out / "bin/run" ).stat ().st_mode 254if os .name != "nt" : 255# NTFS has no execute bit: Windows decides by file extension (.exe), so there is nothing to keep. 256self .assertTrue (mode & stat .S_IXUSR ,"a bundled runtime needs its executable bit" ) 257self .assertFalse (mode & stat .S_ISUID ,"setuid from an archive is never trusted" ) 258 259 260class TestInstall (StoreCase ): 261def test_a_verified_component_installs_into_the_cache (self ): 262component ,payloads = self .payload (tar_bytes ([("bin/strata" ,b"engine" )])) 263path = self .store .install (component ,payloads = payloads ,target = "macos-arm64" ) 264self .assertTrue ((path / ".complete" ).exists ()) 265self .assertEqual ((path / "bin/strata" ).read_bytes (),b"engine" ) 266self .assertEqual (path .name ,component .cache_key ) 267 268def test_a_digest_mismatch_installs_nothing (self ): 269data = tar_bytes ([("bin/strata" ,b"engine" )]) 270component ,_ = self .payload (data ) 271wrong = b"different bytes entirely" 272with self .assertRaises (C .ComponentError )as ctx : 273self .store .install (component ,payloads = {"engine.tar.gz" :wrong },target = "macos-arm64" ) 274self .assertIn ("does not match its manifest" ,str (ctx .exception )) 275cache = self .store .root / "cache" 276present = [p .name for p in cache .iterdir ()]if cache .exists ()else [] 277self .assertEqual (present , [],"a mismatch must leave no cache entry and no staging directory" ) 278 279def test_a_declared_size_mismatch_is_refused (self ): 280data = tar_bytes ([("a" ,b"x" )]) 281component ,_ = self .payload (data ) 282object .__setattr__ (component .artifacts [0 ],"bytes" ,len (data )+ 5 ) 283with self .assertRaises (C .ComponentError )as ctx : 284self .store .install (component ,payloads = {"engine.tar.gz" :data },target = "macos-arm64" ) 285self .assertIn ("bytes" ,str (ctx .exception )) 286 287def test_an_incompatible_component_is_refused_before_anything_is_written (self ): 288component ,payloads = self .payload (tar_bytes ([("a" ,b"x" )])) 289with self .assertRaises (C .ComponentError )as ctx : 290self .store .install (component ,payloads = payloads ,target = "linux-x86_64" ) 291self .assertEqual (ctx .exception .code ,2 ) 292self .assertFalse (any ((self .store .root / "cache" ).iterdir ())) 293 294def test_a_second_install_of_the_same_bytes_reuses_the_cache (self ): 295component ,payloads = self .payload (tar_bytes ([("a" ,b"x" )])) 296first = self .store .install (component ,payloads = payloads ,target = "macos-arm64" ) 297stamp = (first / ".complete" ).stat ().st_mtime_ns 298second = self .store .install (component ,target = "macos-arm64" ) 299self .assertEqual (first ,second ) 300self .assertEqual ((second / ".complete" ).stat ().st_mtime_ns ,stamp , 301"the cached payload was reused rather than rebuilt" ) 302 303def test_a_hostile_archive_installs_nothing (self ): 304data = tar_bytes ([("fine.txt" ,b"ok" ), ("../escape" ,b"x" )]) 305component ,payloads = self .payload (data ) 306with self .assertRaises (C .UnsafeArchive ): 307self .store .install (component ,payloads = payloads ,target = "macos-arm64" ) 308self .assertFalse (any ((self .store .root / "cache" ).iterdir ())) 309self .assertFalse ((self .tmp / "escape" ).exists (),"nothing escaped the destination" ) 310 311 312class TestActivation (StoreCase ): 313def build (self ,version :str ,marker :bytes )-> tuple [C .Component ,dict ]: 314import hashlib 315data = tar_bytes ([("marker" ,marker )]) 316man = manifest (version = version ,artifacts = [ 317 {"name" :"engine.tar.gz" ,"url" :None ,"sha256" :hashlib .sha256 (data ).hexdigest (), 318"bytes" :len (data ),"format" :"tar.gz" }]) 319return C .parse_manifest (man ), {"engine.tar.gz" :data } 320 321def test_activation_puts_the_payload_at_the_active_path (self ): 322component ,payloads = self .build ("1.0" ,b"one" ) 323self .store .install (component ,payloads = payloads ,target = "macos-arm64" ) 324result = self .store .activate (component ,target = "macos-arm64" ) 325self .assertEqual ((Path (result ["active" ])/ "marker" ).read_bytes (),b"one" ) 326 327def test_the_cache_survives_activation (self ): 328"""A compatible application update must not have to download the engine again.""" 329component ,payloads = self .build ("1.0" ,b"one" ) 330cached = self .store .install (component ,payloads = payloads ,target = "macos-arm64" ) 331self .store .activate (component ,target = "macos-arm64" ) 332self .assertTrue ((cached / "marker" ).exists (),"the cached payload was consumed" ) 333 334def test_activating_a_newer_version_retains_the_previous_one (self ): 335first ,p1 = self .build ("1.0" ,b"one" ) 336self .store .install (first ,payloads = p1 ,target = "macos-arm64" ) 337self .store .activate (first ,target = "macos-arm64" ) 338second ,p2 = self .build ("2.0" ,b"two" ) 339self .store .install (second ,payloads = p2 ,target = "macos-arm64" ) 340result = self .store .activate (second ,target = "macos-arm64" ) 341self .assertTrue (result ["moved_aside" ],"the displaced version is kept, not deleted" ) 342self .assertEqual ((Path (result ["active" ])/ "marker" ).read_bytes (),b"two" ) 343 344def test_rollback_restores_the_previous_version_exactly (self ): 345first ,p1 = self .build ("1.0" ,b"one" ) 346self .store .install (first ,payloads = p1 ,target = "macos-arm64" ) 347self .store .activate (first ,target = "macos-arm64" ) 348second ,p2 = self .build ("2.0" ,b"two" ) 349self .store .install (second ,payloads = p2 ,target = "macos-arm64" ) 350self .store .activate (second ,target = "macos-arm64" ) 351 352result = self .store .rollback ("strata-engine" ) 353self .assertEqual (result ["restored" ],"1.0" ) 354active = self .store .active_path ("strata-engine" ) 355self .assertEqual ((active / "marker" ).read_bytes (),b"one" ) 356 357def test_rollback_without_a_previous_version_is_refused (self ): 358"""'Rollback succeeded' and 'the component is gone' must not be the same outcome.""" 359component ,payloads = self .build ("1.0" ,b"one" ) 360self .store .install (component ,payloads = payloads ,target = "macos-arm64" ) 361self .store .activate (component ,target = "macos-arm64" ) 362with self .assertRaises (C .ComponentError )as ctx : 363self .store .rollback ("strata-engine" ) 364self .assertEqual (ctx .exception .code ,2 ) 365self .assertTrue (self .store .active_path ("strata-engine" ).exists (), 366"the active version must survive a refused rollback" ) 367 368def test_activating_something_not_installed_is_refused (self ): 369component ,_ = self .build ("1.0" ,b"one" ) 370with self .assertRaises (C .ComponentError )as ctx : 371self .store .activate (component ,target = "macos-arm64" ) 372self .assertIn ("not installed" ,str (ctx .exception )) 373 374def test_activating_an_incompatible_component_is_refused (self ): 375component ,payloads = self .build ("1.0" ,b"one" ) 376self .store .install (component ,payloads = payloads ,target = "macos-arm64" ) 377with self .assertRaises (C .ComponentError )as ctx : 378self .store .activate (component ,target = "linux-x86_64" ) 379self .assertEqual (ctx .exception .code ,2 ) 380 381 382class TestStoreState (StoreCase ): 383def build (self ,version :str )-> tuple [C .Component ,dict ]: 384import hashlib 385data = tar_bytes ([("marker" ,version .encode ())]) 386man = manifest (version = version ,artifacts = [ 387 {"name" :"engine.tar.gz" ,"url" :None ,"sha256" :hashlib .sha256 (data ).hexdigest (), 388"bytes" :len (data ),"format" :"tar.gz" }]) 389return C .parse_manifest (man ), {"engine.tar.gz" :data } 390 391def test_installed_versions_are_listed_and_the_active_one_marked (self ): 392one ,p1 = self .build ("1.0" ) 393self .store .install (one ,payloads = p1 ,target = "macos-arm64" ) 394two ,p2 = self .build ("2.0" ) 395self .store .install (two ,payloads = p2 ,target = "macos-arm64" ) 396self .store .activate (one ,target = "macos-arm64" ) 397listed = self .store .installed ("strata-engine" ) 398self .assertEqual ([c .version for c in listed ], ["1.0" ,"2.0" ]) 399self .assertEqual ([c .version for c in listed if c .active ], ["1.0" ]) 400 401def test_a_damaged_state_file_does_not_make_the_store_unusable (self ): 402 (self .store .root / "state.json" ).write_text ("{ broken" ,encoding = "utf-8" ) 403self .assertEqual (self .store .state ()["components" ], {}) 404 405def test_pruning_keeps_what_is_active_and_what_rollback_needs (self ): 406one ,p1 = self .build ("1.0" ) 407self .store .install (one ,payloads = p1 ,target = "macos-arm64" ) 408self .store .activate (one ,target = "macos-arm64" ) 409two ,p2 = self .build ("2.0" ) 410kept = self .store .install (two ,payloads = p2 ,target = "macos-arm64" ) 411self .store .activate (two ,target = "macos-arm64" ) 412 413removed = self .store .prune_cache () 414self .assertNotIn (one .cache_key ,removed ,"the rollback target must survive a prune" ) 415self .assertNotIn (two .cache_key ,removed ,"the active version must survive a prune" ) 416self .assertTrue ((kept / "marker" ).exists ()) 417 418def test_pruning_removes_a_cache_entry_nothing_refers_to (self ): 419orphan = self .store .root / "cache" / ("f" * 64 ) 420orphan .mkdir (parents = True ) 421 (orphan / "junk" ).write_text ("x" ,encoding = "utf-8" ) 422self .assertIn ("f" * 64 ,self .store .prune_cache ()) 423self .assertFalse (orphan .exists ()) 424 425 426class TestInterruptedTransfer (StoreCase ): 427"""P12: an interrupted download keeps its bytes and resumes.""" 428 429def test_a_partial_file_larger_than_the_declared_size_is_discarded (self ): 430"""A stale partial from a different artifact must not be appended to.""" 431partial = self .store .root / "partial" / "engine.tar.gz" 432partial .write_bytes (b"x" * 5000 ) 433component ,_ = self .payload (tar_bytes ([("a" ,b"x" )])) 434artifact = component .artifacts [0 ] 435# A URL is needed to reach the transfer logic at all; it is never fetched, because the stale 436# partial is discarded and the ranged request then fails on the unreachable host. 437object .__setattr__ (artifact ,"url" ,"https://example.invalid/e.tar.gz" ) 438object .__setattr__ (artifact ,"bytes" ,100 ) 439from tests .terminal import net_dead 440with net_dead .no_name_resolution (),self .assertRaises (C .ComponentError ):# (no real name service: the host is unreachable) 441self .store ._fetch (artifact ) 442self .assertFalse (partial .exists (),"a stale partial is removed, not appended to" ) 443 444def test_a_short_download_is_an_error_and_the_partial_is_kept (self ): 445"""The bytes are kept so a later attempt resumes rather than restarting.""" 446import urllib .request 447body = b"only part of it" 448 449class FakeResponse (io .BytesIO ): 450status = 200 451 452def __enter__ (self_inner ): 453return self_inner 454 455def __exit__ (self_inner ,* a ): 456return False 457 458from strata_control import netpolicy # the download's own seam (strata_control/netpolicy.py) 459original = netpolicy .urlopen 460netpolicy .urlopen = lambda * a ,** k :FakeResponse (body ) 461try : 462component ,_ = self .payload (tar_bytes ([("a" ,b"x" )])) 463artifact = component .artifacts [0 ] 464object .__setattr__ (artifact ,"url" ,"https://example.invalid/e.tar.gz" ) 465with self .assertRaises (C .ComponentError )as ctx : 466self .store ._fetch (artifact ) 467self .assertIn ("resume" ,str (ctx .exception )) 468finally : 469netpolicy .urlopen = original 470self .assertTrue ((self .store .root / "partial" / "engine.tar.gz" ).exists (), 471"the partial bytes must be kept for a resume" ) 472 473def test_an_unreachable_url_is_reported_as_an_interruption_not_a_crash (self ): 474from strata_control import netpolicy # the download's own seam (strata_control/netpolicy.py) 475original = netpolicy .urlopen 476 477def boom (* a ,** k ): 478raise OSError ("network unreachable" ) 479 480netpolicy .urlopen = boom 481try : 482component ,_ = self .payload (tar_bytes ([("a" ,b"x" )])) 483artifact = component .artifacts [0 ] 484object .__setattr__ (artifact ,"url" ,"https://example.invalid/e.tar.gz" ) 485with self .assertRaises (C .ComponentError )as ctx : 486self .store ._fetch (artifact ) 487self .assertIn ("interrupted" ,str (ctx .exception )) 488finally : 489netpolicy .urlopen = original 490 491def test_a_crash_during_install_leaves_no_complete_entry (self ): 492"""The `.complete` marker is written last, so a partial directory is never trusted.""" 493data = tar_bytes ([("a" ,b"x" )]) 494component ,_ = self .payload (data ) 495with self .assertRaises (C .ComponentError ): 496self .store .install (component ,payloads = {"engine.tar.gz" :b"wrong" },target = "macos-arm64" ) 497self .assertIsNone (self .store .cached (component )) 498 499 500if __name__ == "__main__" : 501unittest .main ()