diff --git a/.github/PAGES.md b/.github/PAGES.md index 3fb7f8e..3d4bde5 100644 --- a/.github/PAGES.md +++ b/.github/PAGES.md @@ -18,8 +18,10 @@ the build installs it at `zig-out/docs-site`. `scripts/check_docs.py` runs befor ## Publishing contract -`.github/workflows/docs.yml` builds and uploads an ordinary artifact on `main` pushes, pull requests, -and manual runs. That job needs no Pages configuration or secrets, so it remains usable in forks. +`.github/workflows/ci.yml` builds and uploads an ordinary artifact in its Linux ReleaseSafe quality +job on `main` pushes, pull requests, and manual runs. That job needs no Pages configuration or +secrets, so it remains usable in forks. The same artifact must pass the Debug compatibility matrix +on Linux, Windows, and macOS before deployment. Deployment runs only for a push to `main` in `LukasNiessen/ArchUnitZig`. The deploy job downloads the already-validated ordinary artifact, configures Pages, packages the Pages artifact, and deploys it diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ce8861f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,140 @@ +name: CI + +on: + push: + branches: + - main + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + ZIG_VERSION: "0.16.0" + PYTHON_VERSION: "3.13" + +jobs: + compatibility: + name: Debug · ${{ matrix.name }} + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - name: Linux + os: ubuntu-latest + - name: Windows + os: windows-latest + - name: macOS + os: macos-latest + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: ${{ env.PYTHON_VERSION }} + + - name: Test pinned toolchain installer + run: python -B -m unittest scripts.test_install_zig + + - name: Install checksum-pinned Zig + run: >- + python -B scripts/install_zig.py + --version "${{ env.ZIG_VERSION }}" + --destination "${{ runner.temp }}/zig-${{ env.ZIG_VERSION }}" + + - name: Verify Zig version + run: zig version + + - name: Run unit, acceptance, dogfood, and consumer tests + run: zig build test -Doptimize=Debug + + quality: + name: ReleaseSafe, formatting, and docs · Linux + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: ${{ env.PYTHON_VERSION }} + + - name: Test pinned toolchain installer + run: python -B -m unittest scripts.test_install_zig + + - name: Validate pinned CI contract + run: python -B scripts/check_ci.py + + - name: Install checksum-pinned Zig + run: >- + python -B scripts/install_zig.py + --version "${{ env.ZIG_VERSION }}" + --destination "${{ runner.temp }}/zig-${{ env.ZIG_VERSION }}" + + - name: Verify Zig version + run: zig version + + - name: Check Zig formatting + run: >- + zig fmt --check + build.zig build.zig.zon src + test/acceptance.zig test/dogfood.zig test/readme.zig test/readme + + - name: Run ReleaseSafe unit, acceptance, dogfood, and consumer tests + run: zig build test -Doptimize=ReleaseSafe + + - name: Build and validate ReleaseSafe guide and API docs + run: zig build docs -Doptimize=ReleaseSafe + + - name: Upload validated documentation site + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: documentation-site + path: zig-out/docs-site + if-no-files-found: error + include-hidden-files: true + retention-days: 7 + + deploy: + name: Deploy GitHub Pages + if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository == 'LukasNiessen/ArchUnitZig' + needs: + - compatibility + - quality + runs-on: ubuntu-latest + permissions: + contents: read + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Download validated site + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: documentation-site + path: _site + + - name: Configure Pages + uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0 + + - name: Package Pages artifact + uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 + with: + path: _site + + - name: Deploy Pages + id: deployment + uses: actions/deploy-pages@cd2ce8fcbc39b97be8ca5fce6e763baed58fa128 # v5.0.0 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml deleted file mode 100644 index 4259803..0000000 --- a/.github/workflows/docs.yml +++ /dev/null @@ -1,76 +0,0 @@ -name: Documentation - -on: - push: - branches: - - main - pull_request: - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: pages-${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - build: - name: Build and validate - runs-on: ubuntu-latest - steps: - - name: Check out repository - uses: actions/checkout@v7 - - - name: Set up Zig - uses: mlugg/setup-zig@v2 - with: - version: 0.16.0 - - - name: Set up Python - uses: actions/setup-python@v7 - with: - python-version: "3.13" - - - name: Build guide and API docs - run: zig build docs - - - name: Upload validated site - uses: actions/upload-artifact@v7 - with: - name: documentation-site - path: zig-out/docs-site - if-no-files-found: error - include-hidden-files: true - retention-days: 7 - - deploy: - name: Deploy GitHub Pages - if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository == 'LukasNiessen/ArchUnitZig' - needs: build - runs-on: ubuntu-latest - permissions: - contents: read - pages: write - id-token: write - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - steps: - - name: Download validated site - uses: actions/download-artifact@v8 - with: - name: documentation-site - path: _site - - - name: Configure Pages - uses: actions/configure-pages@v6 - - - name: Package Pages artifact - uses: actions/upload-pages-artifact@v5 - with: - path: _site - - - name: Deploy Pages - id: deployment - uses: actions/deploy-pages@v5 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4aa2c1c..0b3e7dd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,6 +20,15 @@ the repository documentation records decisions that outlive an individual ticket zig build test ``` + Documentation, public API, CI installer, and release-oriented changes also run: + + ```console + python -B -m unittest scripts.test_install_zig + python -B scripts/check_ci.py + zig build test -Doptimize=ReleaseSafe + zig build docs -Doptimize=ReleaseSafe + ``` + 5. Open a pull request that links the issue, explains Zig-specific trade-offs, and records the exact checks run. 6. Review the complete diff and checks, merge the pull request, delete the branch, and return to a @@ -51,3 +60,16 @@ README/license root commit is the one unavoidable exception to the pull-request - [ ] `zig fmt --check` passes. - [ ] `zig build test` passes. - [ ] Documentation and decisions match the implementation. + +## Continuous integration + +CI runs Debug tests on current GitHub-hosted Linux, Windows, and macOS runners. A Linux quality job +checks formatting, reruns the complete suite in `ReleaseSafe`, builds the documentation site and Zig +API docs, and uploads the validated artifact. The complete test command includes unit tests, +acceptance fixtures, executable dogfood rules, and the standalone README consumer. + +Zig 0.16.0 is installed by `scripts/install_zig.py` from exact official archive URLs. The script +checks both the published byte size and SHA-256 before extraction. External workflow actions are +pinned to immutable commits with their reviewed release tag in a comment. CI deliberately uses no +dependency or build cache; adding one requires a key containing the Zig version and all relevant ZON +hash/lock inputs. diff --git a/README.md b/README.md index 7efa067..5f4eb36 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # ArchUnitZig +[![CI](https://github.com/LukasNiessen/ArchUnitZig/actions/workflows/ci.yml/badge.svg)](https://github.com/LukasNiessen/ArchUnitZig/actions/workflows/ci.yml) + ArchUnitZig turns a Zig project into a dependency graph and lets you enforce architecture as ordinary `zig test` tests. Rules are lazy values: constructing a fluent chain performs no I/O; checking it returns structured violations or integrates with Zig's test runner. diff --git a/docs/decisions.md b/docs/decisions.md index f7dfe70..dc7d782 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -1183,3 +1183,32 @@ duplicate branch-push and pull-request pair. Consequence: guide prose, public Zig examples, generated API documentation, site navigation, and deployment packaging fail one local/CI contract when they drift; the site stays maintainable and offline-readable; and a fork can prove documentation quality without being able to publish it. + +### D049 — CI verifies pinned binaries across three operating systems + +The supported CI toolchain is exactly Zig 0.16.0, downloaded from the versioned official Zig release +URLs rather than a moving master build or an opaque setup action. A repository-owned standard-library +Python installer maps the hosted runner's operating system and architecture to a closed manifest of +Linux, macOS, and Windows archives. Every entry records the official byte size and SHA-256. Both are +verified before a path-traversal-checked ZIP or TAR extraction, the installed binary must report the +requested exact version, and unsupported versions or platforms fail closed. Unit tests exercise the +manifest, verification, and extraction boundary without network access. + +All external GitHub Actions references use immutable commit SHAs with the reviewed stable release tag +beside them. The workflow grants only `contents: read` globally. Pages write and OIDC permissions +exist only on the canonical main-push deploy job, which depends on every compatibility and quality +gate. Fork pull requests can build and upload the ordinary documentation artifact but cannot deploy. +No dependency or build cache is configured; a future cache must include the Zig version plus relevant +ZON hash or lock inputs in its key. + +Debug compatibility runs on current GitHub-hosted Linux, Windows, and macOS with `fail-fast` disabled, +so one platform cannot conceal another platform's result. The Linux quality job explicitly checks +formatting, runs the complete unit/acceptance/dogfood/README-consumer chain in `ReleaseSafe`, builds +and validates the guide plus compiler API docs, and uploads their deployable artifact. CI runs for +every pull request, manual dispatch, and `main` push. Feature-branch pushes are represented by their +pull-request run, avoiding a canceled duplicate status set on the same commit. Superseded runs for +the same Git reference cancel through the workflow concurrency key. + +Consequence: toolchain downloads are reproducible and tamper-evident, allocator and path behavior are +exercised on the three supported runner families, documentation cannot deploy ahead of code quality, +and no optional matrix leg or `continue-on-error` can turn a red supported platform into a green PR. diff --git a/scripts/check_ci.py b/scripts/check_ci.py new file mode 100644 index 0000000..dd155f9 --- /dev/null +++ b/scripts/check_ci.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Fail when the reviewed CI security and coverage contract drifts.""" + +from __future__ import annotations + +from pathlib import Path +import re + +try: + from scripts import install_zig +except ModuleNotFoundError: + import install_zig + + +ROOT = Path(__file__).resolve().parent.parent +WORKFLOW = ROOT / ".github" / "workflows" / "ci.yml" + + +def require(source: str, value: str, errors: list[str]) -> None: + if value not in source: + errors.append(f"missing CI contract: {value}") + + +def main() -> None: + source = WORKFLOW.read_text(encoding="utf-8") + errors: list[str] = [] + + for value in ( + "push:", + "branches:", + "- main", + "pull_request:", + "workflow_dispatch:", + "contents: read", + "cancel-in-progress: true", + "fail-fast: false", + "ubuntu-latest", + "windows-latest", + "macos-latest", + "zig fmt --check", + "zig build test -Doptimize=Debug", + "zig build test -Doptimize=ReleaseSafe", + "zig build docs -Doptimize=ReleaseSafe", + "pages: write", + "id-token: write", + "needs:", + "- compatibility", + "- quality", + ): + require(source, value, errors) + + if "continue-on-error" in source: + errors.append("supported CI gates must not use continue-on-error") + if "actions/cache" in source: + errors.append("CI caches require a separately reviewed Zig/ZON-complete key") + + action_pattern = re.compile(r"^\s*uses:\s*([^\s#]+)(?:\s+#\s*(\S+))?", re.MULTILINE) + actions = action_pattern.findall(source) + if not actions: + errors.append("CI workflow has no external action references") + for reference, comment in actions: + if reference.startswith("./"): + continue + if not re.search(r"@[0-9a-f]{40}$", reference): + errors.append(f"action is not pinned to an immutable commit: {reference}") + if not re.fullmatch(r"v\d+(?:\.\d+){0,2}", comment): + errors.append(f"action pin is missing its reviewed release tag comment: {reference}") + + version_match = re.search(r'^\s*ZIG_VERSION:\s*"([^"]+)"', source, re.MULTILINE) + workflow_version = version_match.group(1) if version_match else None + zon_source = (ROOT / "build.zig.zon").read_text(encoding="utf-8") + zon_match = re.search(r'\.minimum_zig_version\s*=\s*"([^"]+)"', zon_source) + zon_version = zon_match.group(1) if zon_match else None + if workflow_version != install_zig.SUPPORTED_VERSION or zon_version != install_zig.SUPPORTED_VERSION: + errors.append( + "workflow, installer, and build.zig.zon must pin the same exact supported Zig version" + ) + + if len(install_zig.ARTIFACTS) != 6: + errors.append("installer must pin x86_64 and aarch64 artifacts for all three runner families") + for key, artifact in install_zig.ARTIFACTS.items(): + if not artifact.url.startswith(f"https://ziglang.org/download/{install_zig.SUPPORTED_VERSION}/"): + errors.append(f"toolchain URL is not an exact official release URL: {key}") + if not re.fullmatch(r"[0-9a-f]{64}", artifact.sha256): + errors.append(f"toolchain SHA-256 is malformed: {key}") + if artifact.size <= 0: + errors.append(f"toolchain byte size is missing: {key}") + + if errors: + raise SystemExit("CI contract validation failed:\n- " + "\n- ".join(errors)) + print(f"CI contract validation passed: {len(actions)} immutable actions, 6 Zig archives") + + +if __name__ == "__main__": + main() diff --git a/scripts/install_zig.py b/scripts/install_zig.py new file mode 100644 index 0000000..7a3b7fb --- /dev/null +++ b/scripts/install_zig.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Install a checksum-pinned Zig toolchain on supported CI runners.""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass +import hashlib +import os +from pathlib import Path +import platform +import shutil +import stat +import subprocess +import tarfile +import tempfile +import urllib.request +import zipfile + + +SUPPORTED_VERSION = "0.16.0" + + +@dataclass(frozen=True) +class Artifact: + url: str + sha256: str + size: int + + +ARTIFACTS = { + "x86_64-linux": Artifact( + "https://ziglang.org/download/0.16.0/zig-x86_64-linux-0.16.0.tar.xz", + "70e49664a74374b48b51e6f3fdfbf437f6395d42509050588bd49abe52ba3d00", + 55_478_392, + ), + "aarch64-linux": Artifact( + "https://ziglang.org/download/0.16.0/zig-aarch64-linux-0.16.0.tar.xz", + "ea4b09bfb22ec6f6c6ceac57ab63efb6b46e17ab08d21f69f3a48b38e1534f17", + 51_211_944, + ), + "x86_64-macos": Artifact( + "https://ziglang.org/download/0.16.0/zig-x86_64-macos-0.16.0.tar.xz", + "0387557ed1877bc6a2e1802c8391953baddba76081876301c522f52977b52ba7", + 57_396_836, + ), + "aarch64-macos": Artifact( + "https://ziglang.org/download/0.16.0/zig-aarch64-macos-0.16.0.tar.xz", + "b23d70deaa879b5c2d486ed3316f7eaa53e84acf6fc9cc747de152450d401489", + 52_238_004, + ), + "x86_64-windows": Artifact( + "https://ziglang.org/download/0.16.0/zig-x86_64-windows-0.16.0.zip", + "68659eb5f1e4eb1437a722f1dd889c5a322c9954607f5edcf337bc3684a75a7e", + 97_217_739, + ), + "aarch64-windows": Artifact( + "https://ziglang.org/download/0.16.0/zig-aarch64-windows-0.16.0.zip", + "aee38316ee4111717900f45dd3130145c39289e105541d737eb8c5ed653c78ef", + 93_109_828, + ), +} + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--version", required=True) + parser.add_argument("--destination", type=Path, required=True) + return parser.parse_args() + + +def platform_key(system: str, machine: str) -> str: + operating_systems = {"linux": "linux", "darwin": "macos", "windows": "windows"} + architectures = { + "amd64": "x86_64", + "x86_64": "x86_64", + "x64": "x86_64", + "arm64": "aarch64", + "aarch64": "aarch64", + } + normalized_system = operating_systems.get(system.lower()) + normalized_machine = architectures.get(machine.lower()) + if normalized_system is None or normalized_machine is None: + raise ValueError(f"unsupported Zig CI platform: {system}/{machine}") + return f"{normalized_machine}-{normalized_system}" + + +def select_artifact(version: str, system: str, machine: str) -> Artifact: + if version != SUPPORTED_VERSION: + raise ValueError(f"unsupported Zig version {version}; expected {SUPPORTED_VERSION}") + key = platform_key(system, machine) + try: + return ARTIFACTS[key] + except KeyError as error: + raise ValueError(f"no pinned Zig artifact for {key}") from error + + +def download(artifact: Artifact, destination: Path) -> None: + request = urllib.request.Request(artifact.url, headers={"User-Agent": "ArchUnitZig-CI/1"}) + with urllib.request.urlopen(request, timeout=60) as response, destination.open("wb") as output: + shutil.copyfileobj(response, output, length=1024 * 1024) + + +def verify_download(archive: Path, artifact: Artifact) -> None: + actual_size = archive.stat().st_size + if actual_size != artifact.size: + raise ValueError(f"Zig archive size mismatch: expected {artifact.size}, got {actual_size}") + digest = hashlib.sha256() + with archive.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + actual_hash = digest.hexdigest() + if actual_hash != artifact.sha256: + raise ValueError(f"Zig archive SHA-256 mismatch: expected {artifact.sha256}, got {actual_hash}") + + +def safe_member_path(root: Path, name: str) -> Path: + candidate = (root / name).resolve() + try: + candidate.relative_to(root.resolve()) + except ValueError as error: + raise ValueError(f"archive member leaves extraction root: {name}") from error + return candidate + + +def extract_archive(archive: Path, destination: Path) -> None: + destination.mkdir(parents=True) + if archive.suffix == ".zip": + with zipfile.ZipFile(archive) as bundle: + for member in bundle.infolist(): + safe_member_path(destination, member.filename) + file_type = (member.external_attr >> 16) & 0o170000 + if file_type == stat.S_IFLNK: + raise ValueError(f"symbolic links are not allowed in Zig archive: {member.filename}") + bundle.extractall(destination) + return + + with tarfile.open(archive, mode="r:xz") as bundle: + for member in bundle.getmembers(): + safe_member_path(destination, member.name) + if member.issym() or member.islnk() or member.isdev(): + raise ValueError(f"links and devices are not allowed in Zig archive: {member.name}") + bundle.extractall(destination) + + +def zig_executable(directory: Path) -> Path: + return directory / ("zig.exe" if platform.system().lower() == "windows" else "zig") + + +def verify_installed(directory: Path, version: str) -> None: + executable = zig_executable(directory) + if not executable.is_file(): + raise FileNotFoundError(f"installed Zig executable is missing: {executable}") + actual = subprocess.check_output([str(executable), "version"], text=True).strip() + if actual != version: + raise ValueError(f"installed Zig version mismatch: expected {version}, got {actual}") + + +def add_to_github_path(directory: Path) -> None: + github_path = os.environ.get("GITHUB_PATH") + if github_path: + with Path(github_path).open("a", encoding="utf-8", newline="\n") as handle: + handle.write(f"{directory}\n") + else: + print(f"Add this directory to PATH: {directory}") + + +def install(version: str, destination: Path) -> None: + destination = destination.resolve() + if destination.exists(): + verify_installed(destination, version) + add_to_github_path(destination) + print(f"Reusing checksum-pinned Zig {version} at {destination}") + return + + artifact = select_artifact(version, platform.system(), platform.machine()) + destination.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="archunitzig-zig-", dir=destination.parent) as temporary: + temporary_root = Path(temporary) + archive = temporary_root / Path(artifact.url).name + extracted = temporary_root / "extracted" + print(f"Downloading {artifact.url}") + download(artifact, archive) + verify_download(archive, artifact) + extract_archive(archive, extracted) + roots = list(extracted.iterdir()) + if len(roots) != 1 or not roots[0].is_dir(): + raise ValueError("Zig archive must contain exactly one root directory") + shutil.move(str(roots[0]), str(destination)) + + verify_installed(destination, version) + add_to_github_path(destination) + print(f"Installed checksum-pinned Zig {version} at {destination}") + + +def main() -> None: + args = parse_args() + install(args.version, args.destination) + + +if __name__ == "__main__": + main() diff --git a/scripts/test_install_zig.py b/scripts/test_install_zig.py new file mode 100644 index 0000000..47b5e76 --- /dev/null +++ b/scripts/test_install_zig.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 + +from __future__ import annotations + +from contextlib import contextmanager +from io import BytesIO +from pathlib import Path +import shutil +import tarfile +import unittest +import uuid +import zipfile + +from scripts import install_zig + + +@contextmanager +def scratch_directory(): + root = Path(".zig-cache") / "python-tests" / uuid.uuid4().hex + root.mkdir(parents=True) + try: + yield root + finally: + shutil.rmtree(root, ignore_errors=True) + + +class InstallZigTests(unittest.TestCase): + def test_supported_runner_platforms_have_pinned_artifacts(self) -> None: + cases = { + ("Linux", "AMD64"): "x86_64-linux", + ("Linux", "aarch64"): "aarch64-linux", + ("Darwin", "x86_64"): "x86_64-macos", + ("Darwin", "arm64"): "aarch64-macos", + ("Windows", "x64"): "x86_64-windows", + ("Windows", "ARM64"): "aarch64-windows", + } + for inputs, expected in cases.items(): + with self.subTest(inputs=inputs): + self.assertEqual(expected, install_zig.platform_key(*inputs)) + artifact = install_zig.select_artifact(install_zig.SUPPORTED_VERSION, *inputs) + self.assertRegex(artifact.sha256, r"^[0-9a-f]{64}$") + self.assertIn("/0.16.0/", artifact.url) + self.assertGreater(artifact.size, 50_000_000) + + def test_unknown_version_and_platform_fail_closed(self) -> None: + with self.assertRaisesRegex(ValueError, "unsupported Zig version"): + install_zig.select_artifact("master", "Linux", "x86_64") + with self.assertRaisesRegex(ValueError, "unsupported Zig CI platform"): + install_zig.platform_key("Plan9", "mips") + + def test_size_and_checksum_are_both_verified(self) -> None: + with scratch_directory() as temporary: + archive = temporary / "zig.zip" + archive.write_bytes(b"known bytes") + valid = install_zig.Artifact( + "https://example.invalid/zig.zip", + "25cb6d61356e5cada4238d160f3a77522e550e27a69758da40cd281c7ef2c8dc", + 11, + ) + install_zig.verify_download(archive, valid) + with self.assertRaisesRegex(ValueError, "size mismatch"): + install_zig.verify_download(archive, install_zig.Artifact(valid.url, valid.sha256, 12)) + with self.assertRaisesRegex(ValueError, "SHA-256 mismatch"): + install_zig.verify_download(archive, install_zig.Artifact(valid.url, "0" * 64, 11)) + + def test_zip_and_tar_extraction_reject_parent_traversal(self) -> None: + with scratch_directory() as root: + zip_path = root / "bad.zip" + with zipfile.ZipFile(zip_path, mode="w") as bundle: + bundle.writestr("../escape", "bad") + with self.assertRaisesRegex(ValueError, "leaves extraction root"): + install_zig.extract_archive(zip_path, root / "zip-output") + + tar_path = root / "bad.tar.xz" + with tarfile.open(tar_path, mode="w:xz") as bundle: + payload = b"bad" + member = tarfile.TarInfo("../escape") + member.size = len(payload) + bundle.addfile(member, BytesIO(payload)) + with self.assertRaisesRegex(ValueError, "leaves extraction root"): + install_zig.extract_archive(tar_path, root / "tar-output") + + def test_safe_archives_extract_under_the_requested_root(self) -> None: + with scratch_directory() as root: + zip_path = root / "safe.zip" + with zipfile.ZipFile(zip_path, mode="w") as bundle: + bundle.writestr("zig-root/zig.exe", "binary") + output = root / "output" + install_zig.extract_archive(zip_path, output) + self.assertEqual("binary", (output / "zig-root" / "zig.exe").read_text()) + + +if __name__ == "__main__": + unittest.main()