#!/usr/bin/env python3 """Hardware release gate for a packaged macOS Kiri.app bundle. Runs on an Apple Silicon Mac before a release is notarised or published: python3 scripts/release-gate-mac.py target/Kiri.app [--receipt target/release-gate-receipt.json] Checks: 1. Contents/MacOS/kiri and Contents/Resources/guest/{Image,initramfs.cpio,data.img.tgz} exist, initramfs.cpio contains init, sbin/e2fsck, and sbin/resize2fs, and data.img.tgz unpacks to a 64 GiB sparse ext4 image without sparse_super2. 2. `codesign --verify --deep --strict` passes on Kiri.app and Contents/MacOS/kiri carries `com.apple.security.virtualization`. 3. `tests/disk-grow.py` passes against the packaged binary and unpacked guest assets inside an isolated `/tmp` sandbox without touching `~/.kiri`. 4. Writes an atomic JSON pass receipt (`git_head`, `app_sha256`, `timestamp`, `checks_passed`). """ import argparse from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import platform import plistlib import posixpath import shutil import stat import struct import subprocess import sys import tempfile EXT4_SUPERBLOCK_OFFSET = 1024 EXT4_SUPERBLOCK_SIZE = 1024 EXT4_SUPER_MAGIC = 0xEF53 EXT2_FEATURE_COMPAT_SPARSE_SUPER2 = 0x0200 EXPECTED_TEMPLATE_BYTES = 64 << 30 REQUIRED_GUEST_FILES = ("Image", "initramfs.cpio", "data.img.tgz") REQUIRED_INITRAMFS_TOOLS = ("init", "sbin/e2fsck", "sbin/resize2fs") class GateError(RuntimeError): """Raised when any release gate check fails.""" def _normalise_cpio_name(raw_name: str) -> str: name = raw_name.replace("\\", "/") while name.startswith("./"): name = name[2:] name = name.lstrip("/") return posixpath.normpath(name) if name else "" def parse_cpio_newc(data: bytes) -> dict[str, tuple[int, int, bytes]]: """Parse an uncompressed newc (070701/070702) initramfs archive. Returns a mapping of normalised archive path to (mode, filesize, payload). """ entries: dict[str, tuple[int, int, bytes]] = {} offset = 0 total = len(data) saw_trailer = False while offset < total: # Concatenated cpio archives may be padded with NUL bytes between segments. while offset < total and data[offset] == 0: offset += 1 if offset >= total: break if offset + 110 > total: raise GateError(f"truncated cpio header at byte {offset}") magic = data[offset : offset + 6] if magic not in (b"070701", b"070702"): raise GateError(f"unsupported initramfs header magic {magic!r} at byte {offset} (expected uncompressed newc)") try: mode = int(data[offset + 14 : offset + 22].decode("ascii"), 16) filesize = int(data[offset + 54 : offset + 62].decode("ascii"), 16) namesize = int(data[offset + 94 : offset + 102].decode("ascii"), 16) except (UnicodeDecodeError, ValueError) as exc: raise GateError(f"malformed cpio hex header at byte {offset}: {exc}") from exc if namesize < 1: raise GateError(f"invalid cpio namesize {namesize} at byte {offset}") name_start = offset + 110 name_end = name_start + namesize if name_end > total: raise GateError(f"truncated cpio entry name at byte {offset}") name_bytes = data[name_start:name_end] if not name_bytes.endswith(b"\x00"): raise GateError(f"cpio entry name at byte {offset} is missing NUL terminator") raw_name = name_bytes[:-1].decode("utf-8", errors="replace") data_start = (name_end + 3) & ~3 data_end = data_start + filesize if data_end > total: raise GateError(f"truncated cpio payload for {raw_name!r} at byte {offset}") payload = data[data_start:data_end] offset = (data_end + 3) & ~3 if raw_name == "TRAILER!!!": saw_trailer = True continue norm = _normalise_cpio_name(raw_name) if norm and norm != ".": entries[norm] = (mode, filesize, payload) if not saw_trailer: raise GateError("initramfs.cpio is missing TRAILER!!! sentinel") return entries def _resolve_cpio_entry( entries: dict[str, tuple[int, int, bytes]], path: str, depth: int = 0, ) -> tuple[int, int]: if depth > 16: raise GateError(f"initramfs symlink loop while resolving {path!r}") if path not in entries: raise GateError(f"initramfs.cpio is missing required entry {path!r}") mode, filesize, payload = entries[path] kind = stat.S_IFMT(mode) if kind == stat.S_IFLNK: target_raw = payload.decode("utf-8", errors="replace").rstrip("\x00") if not target_raw: raise GateError(f"initramfs symlink {path!r} has an empty target") if target_raw.startswith("/"): resolved = _normalise_cpio_name(target_raw) else: parent = posixpath.dirname(path) resolved = _normalise_cpio_name(posixpath.join(parent, target_raw)) return _resolve_cpio_entry(entries, resolved, depth + 1) if kind != stat.S_IFREG: raise GateError(f"initramfs entry {path!r} is not a regular file (mode 0o{mode:o})") if filesize <= 0: raise GateError(f"initramfs entry {path!r} is empty (0 bytes)") return mode, filesize def verify_initramfs( cpio_path: Path, required: tuple[str, ...] = REQUIRED_INITRAMFS_TOOLS, ) -> None: if not cpio_path.is_file(): raise GateError(f"missing initramfs archive: {cpio_path}") entries = parse_cpio_newc(cpio_path.read_bytes()) for item in required: _resolve_cpio_entry(entries, item) def verify_ext4_superblock( img_path: Path, expected_size: int | None = EXPECTED_TEMPLATE_BYTES, ) -> None: if not img_path.is_file(): raise GateError(f"missing unpacked disk image: {img_path}") info = img_path.stat() if expected_size is not None and info.st_size != expected_size: raise GateError( f"{img_path}: expected {expected_size} bytes ({expected_size >> 30} GiB), got {info.st_size}" ) if info.st_size < EXT4_SUPERBLOCK_OFFSET + EXT4_SUPERBLOCK_SIZE: raise GateError(f"{img_path}: file too small ({info.st_size} bytes) to hold an ext4 superblock") with img_path.open("rb") as fh: fh.seek(EXT4_SUPERBLOCK_OFFSET) sb = fh.read(EXT4_SUPERBLOCK_SIZE) if len(sb) != EXT4_SUPERBLOCK_SIZE: raise GateError(f"{img_path}: short read of ext4 superblock") magic = struct.unpack_from(" None: exe = app_path / "Contents/MacOS/kiri" if not exe.is_file() or not os.access(exe, os.X_OK): raise GateError(f"missing or non-executable host binary: {exe}") guest_dir = app_path / "Contents/Resources/guest" for name in REQUIRED_GUEST_FILES: asset = guest_dir / name if not asset.is_file(): raise GateError(f"missing packaged guest asset: {asset}") if asset.stat().st_size <= 0: raise GateError(f"packaged guest asset is empty: {asset}") verify_initramfs(guest_dir / "initramfs.cpio") guest_stage_dir.mkdir(parents=True, exist_ok=True) proc = subprocess.run( ["tar", "-xzf", str(guest_dir / "data.img.tgz"), "-C", str(guest_stage_dir)], capture_output=True, text=True, ) if proc.returncode != 0: detail = (proc.stderr or proc.stdout).strip() raise GateError(f"failed to unpack {guest_dir / 'data.img.tgz'}: {detail}") data_img = guest_stage_dir / "data.img" verify_ext4_superblock(data_img) img_stat = data_img.stat() if hasattr(img_stat, "st_blocks") and img_stat.st_blocks * 512 >= img_stat.st_size // 4: raise GateError(f"{data_img}: unpacked template is not sparse ({img_stat.st_blocks * 512} bytes allocated)") for name in ("Image", "initramfs.cpio"): shutil.copyfile(guest_dir / name, guest_stage_dir / name) def verify_codesign(app_path: Path) -> None: verify = subprocess.run( ["codesign", "--verify", "--deep", "--strict", str(app_path)], capture_output=True, text=True, ) if verify.returncode != 0: detail = (verify.stderr or verify.stdout).strip() raise GateError(f"codesign verification failed for {app_path}: {detail}") exe = app_path / "Contents/MacOS/kiri" ent = subprocess.run( ["codesign", "-d", "--entitlements", ":-", str(exe)], capture_output=True, ) if ent.returncode != 0: detail = ent.stderr.decode("utf-8", errors="replace").strip() raise GateError(f"could not read entitlements from {exe}: {detail}") try: plist = plistlib.loads(ent.stdout) if ent.stdout.strip() else {} except Exception as exc: raise GateError(f"malformed entitlements plist on {exe}: {exc}") from exc if plist.get("com.apple.security.virtualization") is not True: raise GateError(f"{exe} is missing com.apple.security.virtualization entitlement") def bundle_sha256(app_path: Path) -> str: """Compute a deterministic SHA-256 digest across all files in an .app bundle.""" if not app_path.is_dir(): raise GateError(f"app bundle directory does not exist: {app_path}") outer = hashlib.sha256() entries: list[tuple[str, Path]] = [] for root, dirs, files in os.walk(app_path, followlinks=False): dirs.sort() files.sort() root_path = Path(root) for name in dirs: candidate = root_path / name if candidate.is_symlink(): rel = candidate.relative_to(app_path).as_posix() entries.append((rel, candidate)) for name in files: candidate = root_path / name rel = candidate.relative_to(app_path).as_posix() entries.append((rel, candidate)) entries.sort(key=lambda item: item[0]) for rel, full in entries: st = full.lstat() kind = stat.S_IFMT(st.st_mode) if kind == stat.S_IFLNK: target = os.readlink(full) outer.update(f"L\0{rel}\0{target}\n".encode("utf-8")) elif kind == stat.S_IFREG: file_hash = hashlib.sha256() with full.open("rb") as fh: while chunk := fh.read(1 << 20): file_hash.update(chunk) exec_bit = 1 if (st.st_mode & stat.S_IXUSR) else 0 outer.update(f"F\0{rel}\0{exec_bit}\0{file_hash.hexdigest()}\n".encode("utf-8")) else: raise GateError(f"unexpected special file in bundle: {full}") return outer.hexdigest() def git_head(repo_root: Path) -> str: proc = subprocess.run( ["git", "-C", str(repo_root), "rev-parse", "HEAD"], capture_output=True, text=True, ) if proc.returncode != 0: detail = (proc.stderr or proc.stdout).strip() raise GateError(f"could not read git HEAD in {repo_root}: {detail}") head = proc.stdout.strip() if len(head) != 40 or any(ch not in "0123456789abcdef" for ch in head): raise GateError(f"unexpected git HEAD output: {head!r}") return head def run_disk_grow_gate( repo_root: Path, app_path: Path, guest_stage_dir: Path, sandbox_dir: Path, ) -> None: home_dir = sandbox_dir / "home" docker_cfg = sandbox_dir / "docker-config" home_dir.mkdir(parents=True, exist_ok=True) docker_cfg.mkdir(parents=True, exist_ok=True) env = os.environ.copy() env["HOME"] = str(home_dir) env["DOCKER_CONFIG"] = str(docker_cfg) bundled_bin = app_path / "Contents/Resources/bin" if bundled_bin.is_dir(): env["PATH"] = f"{bundled_bin}{os.pathsep}{env.get('PATH', '')}" script = repo_root / "tests/disk-grow.py" exe = app_path / "Contents/MacOS/kiri" proc = subprocess.run( [sys.executable, str(script), str(exe), "--guest-dir", str(guest_stage_dir)], cwd=str(repo_root), env=env, ) if proc.returncode != 0: raise GateError(f"tests/disk-grow.py failed with exit code {proc.returncode}") def write_receipt( receipt_path: Path, app_path: Path, checks_passed: list[str], *, head: str, app_digest: str, timestamp: str | None = None, ) -> dict[str, object]: if timestamp is None: timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") payload: dict[str, object] = { "git_head": head, "app_path": str(app_path), "app_sha256": app_digest, "timestamp": timestamp, "checks_passed": list(checks_passed), } receipt_path.parent.mkdir(parents=True, exist_ok=True) tmp_path = receipt_path.with_name(f".{receipt_path.name}.{os.getpid()}.tmp") tmp_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") os.replace(tmp_path, receipt_path) return payload def run_gate(repo_root: Path, app_path: Path, receipt_path: Path) -> dict[str, object]: if platform.system() != "Darwin" or platform.machine() != "arm64": raise GateError( f"release-gate-mac.py must run on Apple Silicon macOS (got {platform.system()} {platform.machine()})" ) app_resolved = app_path.resolve() if not app_resolved.is_dir() or app_resolved.suffix != ".app": raise GateError(f"expected a .app bundle directory, got: {app_path}") if app_resolved == Path("/Applications/Kiri.app"): raise GateError("refusing to run release gate against installed /Applications/Kiri.app; pass a built bundle") head = git_head(repo_root) checks_passed: list[str] = [] with tempfile.TemporaryDirectory(prefix="kiri-release-gate-", dir="/tmp") as tmp: sandbox = Path(tmp).resolve() guest_stage = sandbox / "guest" print(f"==> [1/4] Checking guest assets and ext4 template in {app_resolved}", flush=True) unpack_and_verify_guest(app_resolved, guest_stage) checks_passed.extend([ "guest_assets_present", "initramfs_tools_present", "ext4_superblock_valid_no_sparse_super2", ]) print(f"==> [2/4] Verifying code signature and entitlements on {app_resolved}", flush=True) verify_codesign(app_resolved) checks_passed.append("codesign_deep_strict_and_virtualization_entitlement") print("==> [3/4] Running packaged VM disk-growth test in isolated /tmp sandbox", flush=True) run_disk_grow_gate(repo_root, app_resolved, guest_stage, sandbox) checks_passed.append("packaged_vm_disk_grow") print("==> [4/4] Writing release gate receipt", flush=True) digest = bundle_sha256(app_resolved) receipt = write_receipt( receipt_path.resolve(), app_resolved, checks_passed, head=head, app_digest=digest, ) print(f"PASS release gate receipt written to {receipt_path.resolve()}", flush=True) return receipt def main(argv: list[str] | None = None) -> int: repo_root = Path(__file__).resolve().parent.parent parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("app", type=Path, help="Path to the built Kiri.app bundle (for example target/Kiri.app)") parser.add_argument( "--receipt", type=Path, default=None, help="Output path for the JSON pass receipt (default: /release-gate-receipt.json)", ) args = parser.parse_args(argv) receipt_path = args.receipt if args.receipt is not None else args.app.resolve().parent / "release-gate-receipt.json" try: run_gate(repo_root, args.app, receipt_path) except GateError as exc: print(f"FAIL release gate: {exc}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": sys.exit(main())