diff --git a/scripts/packs/finalize.py b/scripts/packs/finalize.py index 8e1a1353d..4b4a9fac7 100644 --- a/scripts/packs/finalize.py +++ b/scripts/packs/finalize.py @@ -17,7 +17,7 @@ from core.options import reject_unknown from model.registry import list_registered_platforms from model.targets import load_target_config from packs.archive import write_generated_member -from packs.integrity import generate_sha256sums, verify_pack, verify_pack_against_platform +from packs.integrity import verify_pack, verify_pack_against_platform from packs.naming import expected_pack_names, narrows_contents, pack_archives from packs.scope import annotate_pack_systems @@ -35,7 +35,7 @@ def baseline_shortfall(excluded: int, absent: int) -> list[str]: return parts -# Post-generation pack verification + manifest + SHA256SUMS +# Post-generation pack verification + manifest def inject_manifest(zip_path: str, manifest: dict) -> None: @@ -156,7 +156,7 @@ def verify_and_finalize_packs( db: dict, **options: Unpack[FinalizeOptions], ) -> bool: - """Verify all packs, inject manifests, generate SHA256SUMS. + """Verify all packs and inject their manifests. pack_systems_by_name gives, per pack file name, the systems its manifest.json records (pack_systems). @@ -225,7 +225,6 @@ def verify_and_finalize_packs( all_ok = False failing.append(f"{name} ({pname})") - generate_sha256sums(output_dir) if failing: # Named at the end, where a 4,000-line log is read, and on stderr. print(f"ERROR: packs failed verification: {', '.join(failing)}", file=sys.stderr) diff --git a/scripts/packs/integrity.py b/scripts/packs/integrity.py index a390e8950..ae5d0733e 100644 --- a/scripts/packs/integrity.py +++ b/scripts/packs/integrity.py @@ -22,7 +22,7 @@ from resolve.nativemode import hash_mismatch_excludes_file import sys from resolve.cores import filter_systems_by_target from core.hashing import ( - compute_hashes, file_digest, md5_composite, md5_composite_of, md5sum, parse_hash_list, + compute_hashes, md5_composite, md5_composite_of, md5sum, parse_hash_list, stream_hashes, ) from core.options import reject_unknown @@ -43,7 +43,6 @@ from resolve.cores import resolve_platform_cores from core.paths import BIOS_DIR, EMULATORS_DIR, declared_destination import zipfile from collections.abc import Callable -from pathlib import Path # Imported at run time where typing has it: a test reads the signature of # verify_pack_against_platform with its annotations evaluated. @@ -316,22 +315,6 @@ def verify_pack( all_ok = len(errors) == 0 return all_ok, manifest -def generate_sha256sums(output_dir: str) -> str | None: - """Generate SHA256SUMS.txt for all ZIP files in output_dir.""" - sums_path = os.path.join(output_dir, "SHA256SUMS.txt") - entries = [] - for name in sorted(os.listdir(output_dir)): - if not name.endswith(".zip"): - continue - path = os.path.join(output_dir, name) - entries.append(f"{file_digest(Path(path), 'sha256')} {name}") - if not entries: - return None - with open(sums_path, "w") as f: - f.write("\n".join(entries) + "\n") - print(f"\n{sums_path}: {len(entries)} pack checksums") - return sums_path - def _check_member_hash( zf: zipfile.ZipFile, member: str, file_entry: dict, mode: str, rule: str = "" ) -> str | None: diff --git a/scripts/release/check.py b/scripts/release/check.py index 9a55592b2..374c6ff01 100644 --- a/scripts/release/check.py +++ b/scripts/release/check.py @@ -7,9 +7,9 @@ import subprocess from dataclasses import dataclass from model.largefiles import LARGE_FILES_REPO, digests_of +from release.sums import SUMS -SUMS = "SHA256SUMS.txt" SIGNATURE = SUMS + ".sig" @dataclass(frozen=True) class Asset: diff --git a/scripts/release/sums.py b/scripts/release/sums.py new file mode 100644 index 000000000..48af61ad8 --- /dev/null +++ b/scripts/release/sums.py @@ -0,0 +1,33 @@ +"""The checksum list of the pack files a release publishes.""" + +from __future__ import annotations + +from pathlib import Path + +from core.hashing import file_digest +from model.releaserecord import PACK_SUFFIX + +SUMS = "SHA256SUMS.txt" + + +def published_packs(directory: Path) -> list[Path]: + """The pack files a release uploads from a directory: whole packs and parts.""" + stem = PACK_SUFFIX.removesuffix(".zip") + return sorted( + path for path in Path(directory).glob(f"*{stem}*.zip") if path.is_file() + ) + + +def write_sums(directory: Path) -> Path | None: + """Write SHA256SUMS.txt over the published packs, in `sha256sum` form. + + Returns its path, or None when the directory holds no pack. + """ + lines = [ + f"{file_digest(path, 'sha256')} {path.name}" for path in published_packs(directory) + ] + if not lines: + return None + sums = Path(directory) / SUMS + sums.write_text("\n".join(lines) + "\n", encoding="utf-8") + return sums diff --git a/scripts/split_pack.py b/scripts/split_pack.py index 3b622e6d2..a125b39ea 100644 --- a/scripts/split_pack.py +++ b/scripts/split_pack.py @@ -11,6 +11,9 @@ the pack it belongs to, its number, and the name and size of every part. Extracted with the files, the markers let `install.py --check` name a part that is missing from the folder. +The directory's SHA256SUMS.txt is then written over the pack files a +release publishes, the list the release signs and uploads. + Usage: python scripts/split_pack.py dist/ python scripts/split_pack.py dist/RetroArch_v1.22.2_BIOS_Pack.zip @@ -26,6 +29,7 @@ from pathlib import Path from core.artifacts import ArtifactLockBusy, artifact_lock from packs.parts import ASSET_LIMIT, parse_size, split_directory, split_pack +from release.sums import write_sums def main() -> int: @@ -53,11 +57,14 @@ def main() -> int: published = split_directory(args.target, args.max_size) else: published = split_pack(args.target, args.max_size) + sums = write_sums(directory) except (ArtifactLockBusy, OSError, ValueError, zipfile.BadZipFile) as exc: print(f"Error: {exc}", file=sys.stderr) return 1 for path in published: print(f"{path.stat().st_size:>13,} {path.name}") + if sums is not None: + print(f"{sums}: checksums of the files to publish") return 0 diff --git a/tests/sources.py b/tests/sources.py index 5c4ad20a2..f7304c46c 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -39,7 +39,7 @@ COMMANDS = { "core/gitclone.py", ), "refresh_data_dirs.py": ("packs/datadirs.py",), - "split_pack.py": ("packs/parts.py",), + "split_pack.py": ("packs/parts.py", "release/sums.py"), "retired_files.py": ("model/retired.py", "collection/retiredhistory.py"), "region_audit.py": ("resolve/regionaudit.py",), "dedup.py": ( diff --git a/tests/test_site_wiki.py b/tests/test_site_wiki.py index 2feb6f9fd..450099379 100644 --- a/tests/test_site_wiki.py +++ b/tests/test_site_wiki.py @@ -40,6 +40,7 @@ import fnmatch import functools import json import re +import tempfile import unittest from pathlib import Path import yaml @@ -50,6 +51,7 @@ from tests import sitepages from installer_build import port from installer_build.module import installer_module from release.check import SUMS, Asset, compare_release +from release.sums import published_packs REPO_ROOT = Path(__file__).resolve().parents[1] @@ -886,18 +888,23 @@ class PinnedInstaller(unittest.TestCase): def test_the_release_steps_ship_none(self): text = _wiki("release-process.md") self.assertNotIn("cp install.py", text) - sums = re.search(r"sha256sum [^>]+> SHA256SUMS.txt", text, re.S).group(0) + # One producer: split_pack.py writes the list, never a shell line. + self.assertNotIn("> SHA256SUMS.txt", text) upload = re.search(r"for f in dist/SHA256SUMS.txt.*?; do", text, re.S).group(0) for name in ("install.py", "install.sh", "install.ps1", ".json", "RetroBIOS", ".muxapp", "build_port", " *.zip", "/*.zip"): with self.subTest(name=name): - self.assertNotIn(name, sums) self.assertNotIn(name, upload) + with tempfile.TemporaryDirectory() as tmp: + for name in ("P_BIOS_Pack.zip", "Q_BIOS_Pack.part1of2.zip", "install.py", + "install.sh", "install.ps1", "retroarch.json", *port.ARCHIVES): + (Path(tmp) / name).write_bytes(b"x") + self.assertEqual([p.name for p in published_packs(Path(tmp))], + ["P_BIOS_Pack.zip", "Q_BIOS_Pack.part1of2.zip"]) # A launcher built into dist/ is never caught by the glob either. for archive in port.ARCHIVES: with self.subTest(archive=archive): self.assertFalse(fnmatch.fnmatch(archive, "*_BIOS_Pack*.zip")) - self.assertIn("*_BIOS_Pack*.zip", sums) self.assertIn("*_BIOS_Pack*.zip", upload) self.assertNotIn("scripts/build_port.py", text) diff --git a/tests/test_split_pack.py b/tests/test_split_pack.py index 498217bbe..82886ce9d 100644 --- a/tests/test_split_pack.py +++ b/tests/test_split_pack.py @@ -28,6 +28,7 @@ import unittest import zipfile from pathlib import Path +from core.hashing import file_digest, parse_sha256sums from packs import finalize from packs import naming from core.artifacts import artifact_lock @@ -221,6 +222,29 @@ class SplitHoldsTheDirectory(SplitFixture): ) +class SplitWritesThePublishedChecksums(SplitFixture): + """The pack build wrote SHA256SUMS.txt over every ZIP before the split, + naming a pack the split then removed and none of its parts, and the + release overwrote it by hand. The split now writes the one list.""" + + def test_the_list_names_the_parts_and_not_the_split_pack(self): + self._build(self.dist / "Small_BIOS_Pack.zip", {"one.bin": b"1"}) + self._build(self.dist / "RetroBIOS.zip", {"install.py": b"launcher"}) + proc = subprocess.run( + [sys.executable, "scripts/split_pack.py", str(self.dist), "--max-size", str(LIMIT)], + cwd=str(REPO_ROOT), capture_output=True, text=True, timeout=60, check=False, + ) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + sums = parse_sha256sums((self.dist / "SHA256SUMS.txt").read_text(encoding="utf-8")) + published = sorted( + p.name for p in self.dist.glob("*.zip") if p.name != "RetroBIOS.zip" + ) + self.assertEqual(sorted(sums), published) + self.assertNotIn(self.pack.name, sums) + for name, digest in sums.items(): + self.assertEqual(digest, file_digest(self.dist / name, "sha256")) + + class PartsAreNotTakenForPacks(SplitFixture): def test_a_part_is_recognised_by_its_name(self): self.assertTrue(packs_parts.is_part("RetroArch_BIOS_Pack.part1of2.zip")) @@ -278,8 +302,8 @@ class ReleaseProcessPublishesArchives(unittest.TestCase): def test_the_checksums_are_those_of_the_published_files(self): self.assertLess( - self.text.index("scripts/split_pack.py"), - self.text.index("sha256sum *_BIOS_Pack*.zip"), + self.text.index("python scripts/split_pack.py"), + self.text.index("ssh-keygen -Y sign"), ) diff --git a/wiki/release-process.md b/wiki/release-process.md index 774c935de..1a1fc0958 100644 --- a/wiki/release-process.md +++ b/wiki/release-process.md @@ -246,6 +246,8 @@ python scripts/pipeline.py # and the set compared with the pack before the pack is removed. Each part # also holds a marker (Pack.part1of2.txt) naming every part and its size, # which install.py --check reads to name a part missing from a folder. +# It then writes dist/SHA256SUMS.txt, the checksums of the pack files as +# published, whole packs and parts. python scripts/split_pack.py dist/ # 2b. The release carries the packs and the signed checksum list, and @@ -255,11 +257,9 @@ python scripts/split_pack.py dist/ # builds and serves them from its own commit. check_release.py refuses an # installer, a file list or a launcher attached to the release. -# 3. Checksums of the files as published, then sign the list. The checksums -# answer corruption, and the signature answers a rewritten release, which is -# the one thing a checksum published beside its own artifacts cannot -# answer. -(cd dist && sha256sum *_BIOS_Pack*.zip > SHA256SUMS.txt) +# 3. Sign the checksum list split_pack.py wrote. The checksums answer +# corruption, and the signature answers a rewritten release, which is the +# one thing a checksum published beside its own artifacts cannot answer. ssh-keygen -Y sign -f ~/.ssh/retrobios_signing -n file dist/SHA256SUMS.txt # 4. Record what each pack holds, read from the archives just checked: diff --git a/wiki/tools.md b/wiki/tools.md index 306aa8cfe..243c07b30 100644 --- a/wiki/tools.md +++ b/wiki/tools.md @@ -1386,7 +1386,7 @@ before a release (wiki/release-process.md). Its lines stay in | `list_platforms.py` | List the registered platforms as JSON | | `download.py` | Download a pack from GitHub releases, every part checked (Python, stdlib only) | | `download.sh` | Same, as a shell one-liner (`curl` + `unzip`) | -| `split_pack.py` | Cut a pack over the release asset limit into parts that are each a ZIP of whole files, each with a marker naming every part, read back before the pack is removed | +| `split_pack.py` | Cut a pack over the release asset limit into parts that are each a ZIP of whole files, each with a marker naming every part, read back before the pack is removed, then write `SHA256SUMS.txt` over the files to publish | | `provenance_report.py` | Dump-catalog coverage and acquisition targets (see above) | | `find_pinned_revision.py` | Walk the upstream commits that touched a file and return the revision whose bytes match a platform's pinned md5 (`--write` saves them) | | `generate_readme.py` | Generate README.md and CONTRIBUTING.md from database |