okami.mom/strata

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

Niko1221Merge f-0213-secure (f374b5029) into f-0213-int97da46cc1

main
7.2 KiB135 linesraw
1"""The terminal archive's pins: the interpreter digests, the hash-pinned wheel locks, and the launchers that prefer the
2bundled runtime. Offline: nothing is downloaded (the build and the smoke test do that)."""
3
4import re
5import sys
6import tempfile
7import unittest
8from pathlib import Path
9
10ROOT = Path(__file__).resolve().parents[2]
11sys.path.insert(0, str(ROOT / "packaging"))
12
13import package_terminal as pt  # noqa: E402
14
15
16def norm(name):
17    return re.sub(r"[-_.]+", "-", name).lower()
18
19
20class InterpreterPins(unittest.TestCase):
21    def test_every_target_has_a_digest_and_a_matching_url(self):
22        self.assertEqual(sorted(pt.PYTHON_PINS), ["darwin-arm64", "linux-aarch64", "linux-x86_64", "windows-x86_64"])
23        for target, pin in pt.PYTHON_PINS.items():
24            with self.subTest(target):
25                self.assertRegex(pin["sha256"], r"^[0-9a-f]{64}$")
26                self.assertIn(pt.PYTHON_VERSION, pin["url"])
27                self.assertIn(pt.PBS_RELEASE, pin["url"])
28                self.assertTrue(pin["url"].startswith("https://github.com/astral-sh/python-build-standalone/"))
29                self.assertTrue(pin["url"].endswith("install_only.tar.gz"))
30        self.assertEqual(len({p["sha256"] for p in pt.PYTHON_PINS.values()}), 4)
31
32    def test_the_mac_pin_is_the_one_setup_sh_downloads(self):
33        text = (ROOT / "setup.sh").read_text(encoding="utf-8")
34        self.assertIn(pt.PYTHON_PINS["darwin-arm64"]["sha256"], text)
35        self.assertIn(pt.PYTHON_PINS["darwin-arm64"]["url"].split("/")[-1], text)
36
37    def test_fetch_refuses_a_download_that_does_not_match_its_pin(self):
38        with tempfile.TemporaryDirectory() as d:
39            cache = Path(d)
40            pin = pt.PYTHON_PINS["linux-x86_64"]
41            (cache / pin["file"].replace("+", "_")).write_bytes(b"not the interpreter")
42            with self.assertRaises(SystemExit) as cm:
43                pt.fetch_python("linux-x86_64", cache)
44            self.assertIn("does not match its pin", str(cm.exception))
45
46
47class WheelLocks(unittest.TestCase):
48    def locks(self):
49        found = sorted((ROOT / "packaging" / "locks").glob("runtime-*-cp312.txt"))
50        self.assertEqual([p.name for p in found], ["runtime-darwin-arm64-cp312.txt", "runtime-linux-aarch64-cp312.txt",
51                                                    "runtime-linux-x86_64-cp312.txt", "runtime-windows-x86_64-cp312.txt"])
52        return found
53
54    def test_every_entry_is_pinned_and_hashed_and_nothing_else_is_in_the_file(self):
55        for lock in self.locks():
56            with self.subTest(lock.name):
57                entries = {}
58                current = None
59                for line in lock.read_text(encoding="utf-8").splitlines():
60                    if not line.strip() or line.startswith("#"):
61                        continue
62                    m = re.match(r"^([A-Za-z0-9_.-]+)==([0-9][^\s\\]*) \\$", line)
63                    if m:
64                        current = norm(m.group(1))
65                        entries[current] = {"version": m.group(2), "hashes": []}
66                        continue
67                    h = re.match(r"^\s+--hash=sha256:([0-9a-f]{64})( \\)?$", line)
68                    self.assertTrue(h and current, f"unexpected line in {lock.name}: {line!r}")
69                    entries[current]["hashes"].append(h.group(1))
70                self.assertGreater(len(entries), 15)
71                for name, e in entries.items():
72                    self.assertTrue(e["hashes"], name)
73
74    def test_the_locks_agree_with_requirements_txt(self):
75        pins = {}
76        for name in ("requirements.txt", "requirements-monitor.txt"):
77            for line in (ROOT / name).read_text(encoding="utf-8").splitlines():
78                m = re.match(r"^([A-Za-z0-9_.-]+)==([^\s;]+)(?:\s*;\s*(.*))?$", line.split(" #")[0].strip())
79                if m:
80                    pins.setdefault(norm(m.group(1)), []).append((m.group(2), m.group(3) or ""))
81        for lock in self.locks():
82            names = pt.lock_names(lock)
83            with self.subTest(lock.name):
84                for pkg, versions in pins.items():
85                    if pkg == "colorama":
86                        self.assertEqual(pkg in names, "windows" in lock.name)
87                        continue
88                    if pkg == "numpy":                       # python_version markers: the 3.12 line applies
89                        self.assertEqual(names[pkg], "2.5.3")
90                        continue
91                    self.assertEqual(names.get(pkg), versions[0][0], pkg)
92                self.assertNotIn("cmake", names)             # build tools never ship in the bundle
93                self.assertNotIn("ninja", names)
94
95    def test_pillow_is_the_patched_release_everywhere_it_is_pinned(self):
96        """#4220: 12.3.0's bundled OpenJPEG has a heap overflow (GHSA-78g4-xqwv-q3g8, fixed in 13.0.0). Pillow 13 needs Python 3.11, so
97        requirements.txt keeps 12.3.0 for 3.10 only; every hash-locked bundle (Python 3.12) carries 13.0.0 or later."""
98        lines = [l.split(" #")[0].strip() for l in (ROOT / "requirements.txt").read_text(encoding="utf-8").splitlines()]
99        pillow = [l for l in lines if l.lower().startswith("pillow")]
100        self.assertEqual(sorted(pillow), ['pillow==12.3.0; python_version < "3.11"', 'pillow==13.0.0; python_version >= "3.11"'])
101        for lock in self.locks():
102            with self.subTest(lock.name):
103                version = pt.lock_names(lock)["pillow"]
104                self.assertGreaterEqual(tuple(int(x) for x in version.split(".")), (13, 0, 0), version)
105
106    def test_the_build_installs_with_hash_checking_and_no_resolution(self):
107        text = (ROOT / "packaging" / "package_terminal.py").read_text(encoding="utf-8")
108        for flag in ("--require-hashes", "--no-deps", "--only-binary=:all:"):
109            self.assertIn(flag, text)
110        self.assertNotIn('"--upgrade"', text)               # pip itself is the interpreter's, not a fresh download
111
112
113class Launchers(unittest.TestCase):
114    def test_wrappers_prefer_the_bundled_runtime(self):
115        cmd = (ROOT / "bin" / "strata.cmd").read_text(encoding="utf-8")
116        ps1 = (ROOT / "bin" / "strata.ps1").read_text(encoding="utf-8")
117        sh = (ROOT / "bin" / "strata").read_text(encoding="utf-8")
118        self.assertLess(cmd.index("python\\python.exe"), cmd.index("py -3"))
119        self.assertLess(ps1.index("python\\python.exe"), ps1.index("'py', '-3'"))
120        self.assertLess(sh.index("python/bin/python3"), sh.index("command -v python3"))
121        for text in (cmd, ps1, sh):
122            self.assertIn("PYTHONNOUSERSITE", text)
123
124    def test_start_here_setup_and_update_use_it(self):
125        bat = (ROOT / "START-HERE.bat").read_text(encoding="utf-8")
126        self.assertLess(bat.index('if exist "python\\python.exe" goto bundled'), bat.index("call :findpy"))
127        self.assertIn("START-HERE.bat", (ROOT / "SETUP.bat").read_text(encoding="utf-8"))
128        self.assertIn("START-HERE.bat", (ROOT / "UPDATE.bat").read_text(encoding="utf-8"))
129        sh = (ROOT / "setup.sh").read_text(encoding="utf-8")
130        self.assertLess(sh.index("exec python/bin/python3"), sh.index("if [ ! -x .venv/bin/python ]"))
131        self.assertIn("setup.sh", (ROOT / "update.sh").read_text(encoding="utf-8"))
132
133
134if __name__ == "__main__":
135    unittest.main()