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