diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index f9e9a4c..e8038dd 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -374,12 +374,132 @@ jobs: name: pure-wheel-${{ matrix.os }}-py${{ matrix.python }} path: dist-pure + # ------------------------------------------------------------------ + # PR regression for the release PyPI checks — NO publishing, NO + # environment/OIDC, read-only permissions, and NO PyPI registry + # uploads and NO PyPI JSON API requests from these checks themselves + # (the tooling install steps and the consumer probe may still contact + # the package index for packages, and GitHub artifacts are uploaded + # for the round-trip job — only PyPI uploads/requests are absent): + # + # 1. Unit tests exercise the EXACT preflight / post-upload functions + # the release workflow calls (scripts/pypi_preflight.py) against + # mocked HTTP responses (404 / partial / full same-hash repeat / + # conflicting digest / duplicate filenames / malformed payload / + # post-upload match & mismatch) with fake local files. + # 2. The sdist is built with the same provenance gate as the release + # sdist job, then installed from the EXACT built archive into a + # fresh venv OUTSIDE the checkout via the shared consumer probe. + # ------------------------------------------------------------------ + pypi-publish-regression: + name: PyPI preflight regression (no PyPI registry requests, no PyPI uploads) + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-python@v6 + with: + python-version: "3.12" + - uses: dtolnay/rust-toolchain@stable + - name: Install pytest (package-index access for tooling only) + run: python -m pip install --upgrade pip pytest + + # Unit tests over the shared implementation — mocked openers only. + # PYTHONPATH exposes the pure package so tests/conftest.py can import + # ktav without building the native extension. + - name: Pytest — preflight/post-upload regression (mocked HTTP) + env: + PYTHONPATH: python + run: python -m pytest tests/ci/test_pypi_preflight.py -v + + # Same provenance gate + sdist build as the release sdist job. + - name: Generate Cargo.lock (no --locked) + run: cargo generate-lockfile + - name: Check Rust provenance + run: python scripts/check_rust_provenance.py + - name: Build sdist + uses: PyO3/maturin-action@v1 + with: + command: sdist + args: --out dist + - name: Assert the artifact is exactly one sdist and record its sha256 + shell: bash + run: | + set -euo pipefail + count="$(ls dist | wc -l)" + test "$count" -eq 1 || { echo "expected exactly one file in dist:"; ls dist; exit 1; } + test -f dist/ktav-0.9.0.tar.gz || { echo "missing dist/ktav-0.9.0.tar.gz:"; ls dist; exit 1; } + sha256sum dist/ktav-0.9.0.tar.gz + sha256sum dist/ktav-0.9.0.tar.gz | cut -d' ' -f1 > dist/sdist-sha256.txt + + # Hand the built sdist + its recorded sha256 sidecar to the + # round-trip job, which downloads them as an Actions artifact and + # re-verifies checksum equality against the DOWNLOADED copy (until + # now equality was only checked in the release job, skipped here by + # dry-run). No release, no publish, read-only permissions. + - name: Upload sdist + sha256 sidecar for the round-trip job + uses: actions/upload-artifact@v7 + with: + name: pr-sdist + path: dist + retention-days: 1 + + # Safe artifact round-trip: download the sdist + sidecar uploaded by + # pypi-publish-regression into a DIFFERENT directory, compare the + # downloaded archive's sha256 against the sidecar (checksum coverage + # previously existed only in the release job), then run the shared + # consumer probe against exactly that DOWNLOADED file. No release, no + # publish, no extra privileges. + sdist-checksum-roundtrip: + name: Sdist artifact round-trip checksum (no release, no publish) + runs-on: ubuntu-latest + needs: [pypi-publish-regression] + permissions: + contents: read + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-python@v6 + with: + python-version: "3.12" + - uses: actions/download-artifact@v8 + with: + name: pr-sdist + path: downloaded-dist + - name: Compare downloaded sdist sha256 against the sidecar + shell: bash + run: | + set -euo pipefail + recorded="$(tr -d '[:space:]' < downloaded-dist/sdist-sha256.txt)" + if [[ ! "$recorded" =~ ^[0-9a-f]{64}$ ]]; then + echo "sidecar is not a 64-hex sha256: $recorded"; exit 1 + fi + test -f downloaded-dist/ktav-0.9.0.tar.gz \ + || { echo "downloaded archive ktav-0.9.0.tar.gz is missing"; exit 1; } + actual="$(sha256sum downloaded-dist/ktav-0.9.0.tar.gz | cut -d' ' -f1)" + echo "recorded=$recorded" + echo "actual=$actual" + test "$actual" = "$recorded" \ + || { echo "downloaded sdist sha256 differs from sidecar"; exit 1; } + - uses: dtolnay/rust-toolchain@stable + - name: Consumer probe — install the DOWNLOADED sdist outside the checkout + shell: bash + run: | + set -euo pipefail + sdist="$PWD/downloaded-dist/ktav-0.9.0.tar.gz" + test -f "$sdist" + scratch="$(mktemp -d)" + cd "$scratch" + python "$GITHUB_WORKSPACE/scripts/pypi_preflight.py" consumer-probe \ + --sdist "$sdist" \ + --version "0.9.0" + # Guarantees the three OS × Python matrix all pass before merging; useful # as a required check in branch protection without listing every cell. test-summary: name: Test summary runs-on: ubuntu-latest - needs: [test, pure-mode] + needs: [test, pure-mode, pypi-publish-regression, sdist-checksum-roundtrip] if: always() steps: - name: Fail if any matrix job failed diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 251cd53..dafaebd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -55,6 +55,43 @@ jobs: command: sdist args: --out dist + - name: Assert the artifact is exactly one sdist and record its sha256 + shell: bash + run: | + set -euo pipefail + # Exactly one distribution file must come out of the sdist build: + # the ktav 0.9.0 tar.gz. Anything else means the build swept in + # unexpected output and the artifact cannot be bound to a single + # checksum. + count="$(ls dist | wc -l)" + test "$count" -eq 1 || { echo "expected exactly one file in dist:"; ls dist; exit 1; } + test -f dist/ktav-0.9.0.tar.gz || { echo "missing dist/ktav-0.9.0.tar.gz:"; ls dist; exit 1; } + sha256sum dist/ktav-0.9.0.tar.gz + # SHA256 sidecar rides INSIDE dist, so the wheels-sdist artifact + # (uploaded with path: dist) carries archive + checksum together + # and the release job can prove it publishes the EXACT tested file. + sha256sum dist/ktav-0.9.0.tar.gz | cut -d' ' -f1 > dist/sdist-sha256.txt + + - name: Install the EXACT built sdist in a clean venv outside the checkout + shell: bash + run: | + set -euo pipefail + sdist="$PWD/dist/ktav-0.9.0.tar.gz" + test -f "$sdist" + # The whole check runs from a scratch directory OUTSIDE the + # checkout tree; the venv gets ktav ONLY from the sdist file path — + # never from the checkout as a package source. (--no-index is not + # used on purpose: building the sdist needs maturin from the index, + # but the ktav package itself can only come from the sdist file.) + scratch="$(mktemp -d)" + cd "$scratch" + # The probe (venv creation, install of the EXACT sdist file path, + # installed-package assertions) lives in scripts/pypi_preflight.py + # and is shared verbatim with the PR CI job. + python "$GITHUB_WORKSPACE/scripts/pypi_preflight.py" consumer-probe \ + --sdist "$sdist" \ + --version "0.9.0" + - uses: actions/upload-artifact@v7 with: name: wheels-sdist @@ -317,11 +354,67 @@ jobs: # Not a distribution file — keep it out of the PyPI upload. rm dist/pure-wheel-sha256.txt + - name: Re-verify the downloaded sdist against the tested sha256 + shell: bash + run: | + set -euo pipefail + sdist="dist/ktav-0.9.0.tar.gz" + test -f "$sdist" || { ls dist; exit 1; } + # Cross-job checksum equality rides on artifact integrity + # (upload/download of the `wheels-sdist` artifact); assert the + # published sdist is the EXACT file that was built, size-checked + # and install-tested in the sdist job. + echo "sdist sha256 (downloaded): $(sha256sum "$sdist")" + cat dist/sdist-sha256.txt + recorded="$(cut -d' ' -f1 dist/sdist-sha256.txt)" + actual="$(sha256sum "$sdist" | cut -d' ' -f1)" + test "$recorded" = "$actual" || { + echo "downloaded sdist does not match the tested sha256"; exit 1; + } + # Not a distribution file — keep it out of the PyPI upload. + rm dist/sdist-sha256.txt + + # Single-source implementation: scripts/pypi_preflight.py is shared + # verbatim with the PR CI regression tests + # (tests/ci/test_pypi_preflight.py) — keep no logic inline here. + - name: PyPI pre-flight — hash-checked idempotency (fail closed) + id: pypi-preflight + shell: bash + run: | + set -euo pipefail + python scripts/pypi_preflight.py preflight \ + --dist dist \ + --project ktav \ + --version "${GITHUB_REF_NAME#v}" \ + --output "$GITHUB_OUTPUT" + - name: Publish to PyPI + if: steps.pypi-preflight.outputs.skip != 'true' uses: pypa/gh-action-pypi-publish@release/v1 with: - packages-dir: dist - skip-existing: true + # Upload ONLY the files the pre-flight proved absent from PyPI; + # an empty upload-dir here is impossible (skip=true would have + # short-circuited this step). + packages-dir: ${{ steps.pypi-preflight.outputs.upload-dir }} + # Deliberately NOT skip-existing: idempotent re-runs are decided + # by the sha256 pre-flight above, so an existing file with a + # different digest can never be silently accepted — and a race + # (file appearing after pre-flight) fails the upload, which is + # the safe outcome. + skip-existing: false + verify-metadata: true + + - name: PyPI post-upload verification of every published digest + if: steps.pypi-preflight.outputs.skip != 'true' + shell: bash + run: | + set -euo pipefail + # Same single-source implementation as the pre-flight above; + # unit-tested in tests/ci/test_pypi_preflight.py. + python scripts/pypi_preflight.py post-upload \ + --dist dist \ + --project ktav \ + --version "${GITHUB_REF_NAME#v}" # ------------------------------------------------------------------ # GitHub Release — pulls notes from the matching `## [vX.Y.Z]` @@ -361,6 +454,18 @@ jobs: echo "__END_NOTES__" } >> "$GITHUB_OUTPUT" + # Drop ONLY the sdist checksum sidecar from the release assets; + # pure-wheel-sha256.txt is an intentionally published checksum + # asset and must survive (a bare `rm -f dist/*.txt` deleted it). + - name: Drop the sdist checksum sidecar from the release assets + shell: bash + run: | + set -euo pipefail + rm -f dist/sdist-sha256.txt + test -f dist/pure-wheel-sha256.txt || { + echo "pure-wheel-sha256.txt missing; refusing to publish without it"; ls dist; exit 1; + } + - uses: softprops/action-gh-release@v3 with: tag_name: ${{ github.ref_name }} diff --git a/scripts/pypi_preflight.py b/scripts/pypi_preflight.py new file mode 100644 index 0000000..2c27175 --- /dev/null +++ b/scripts/pypi_preflight.py @@ -0,0 +1,420 @@ +#!/usr/bin/env python3 +"""Single implementation of the production PyPI release checks. + +This module implements the PyPI preflight / post-upload checks and the +out-of-checkout sdist consumer probe, and is the ONLY source of that logic: + +* the release workflow (``release.yml``) calls the CLI entry points + (``preflight``, ``post-upload``, ``consumer-probe``) — no inline copies; +* PR CI (``CI.yml``) unit-tests the same functions with mocked HTTP + openers and fake local files — no real PyPI requests, no uploads. + +Every remote condition that is not "version absent from PyPI" fails +closed: the caller must abort instead of guessing that an upload is safe. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import subprocess +import sys +import urllib.error +import urllib.request +from pathlib import Path +from typing import Callable + +DEFAULT_PROJECT = "ktav" +PYPI_TIMEOUT = 30 +_SHA256_RE = re.compile(r"[0-9a-f]{64}") + + +class PypiCheckError(Exception): + """Fail-closed condition: refuse to continue the release.""" + + +class VersionAbsentError(Exception): + """PyPI answered 404 — the version is not published yet (safe).""" + + +# ---------------------------------------------------------------------- +# HTTP plumbing (injected so unit tests never touch the network) +# ---------------------------------------------------------------------- + +Opener = Callable[[str], object] + + +def default_opener(url: str): + """Open ``url`` with a fixed User-Agent and the shared PyPI timeout.""" + req = urllib.request.Request(url, headers={"User-Agent": "ktav-release-check"}) + return urllib.request.urlopen(req, timeout=PYPI_TIMEOUT) + + +def _read_json(opener: Opener, url: str, not_found_is_absent: bool) -> dict: + """Fetch ``url`` and return the parsed JSON payload. + + With ``not_found_is_absent`` a 404 maps to :class:`VersionAbsentError` + ("new release"); any other HTTP error or payload problem fails closed. + """ + try: + with opener(url) as resp: + status = getattr(resp, "status", 200) + if status != 200: + raise PypiCheckError( + f"PyPI API returned HTTP {status}; refusing to continue (fail closed)" + ) + raw = resp.read() + except urllib.error.HTTPError as exc: + if not_found_is_absent and exc.code == 404: + raise VersionAbsentError(f"{url}: HTTP 404 (version absent)") from exc + raise PypiCheckError( + f"PyPI API request failed with HTTP {exc.code}; refusing to continue (fail closed)" + ) from exc + except VersionAbsentError: + raise + except PypiCheckError: + raise + except Exception as exc: # network/socket/protocol problems + raise PypiCheckError( + f"PyPI API request failed ({exc!r}); refusing to continue (fail closed)" + ) from exc + + def _no_duplicate_keys(pairs): + seen = set() + out = {} + for key, value in pairs: + if key in seen: + raise ValueError(f"duplicate JSON key: {key!r}") + seen.add(key) + out[key] = value + return out + + try: + data = json.loads(raw.decode("utf-8"), object_pairs_hook=_no_duplicate_keys) + except Exception as exc: + raise PypiCheckError(f"PyPI API response is not valid JSON ({exc!r}); fail closed") from exc + if not isinstance(data, dict): + raise PypiCheckError("PyPI API response is not a JSON object; fail closed") + return data + + +def validate_payload(version: str, data: dict, *, context: str = "") -> dict[str, str]: + """Fail-closed validation of a PyPI JSON payload; returns name -> sha256. + + A 200 response that does not carry the expected version and a + well-formed ``urls`` list with unique, non-empty filenames and + 64-hex sha256 + digests must NEVER be read as "files are absent / verification ok". + """ + prefix = f"{context}: " if context else "" + info = data.get("info") if isinstance(data, dict) else None + if not isinstance(info, dict) or info.get("version") != version: + raise PypiCheckError( + f"{prefix}PyPI API response has unexpected/missing version info; fail closed" + ) + urls = data.get("urls") + if not isinstance(urls, list): + raise PypiCheckError(f"{prefix}PyPI API response has malformed 'urls'; fail closed") + remote: dict[str, str] = {} + for entry in urls: + if not isinstance(entry, dict): + raise PypiCheckError(f"{prefix}PyPI API 'urls' contains a malformed entry; fail closed") + name = entry.get("filename") + digests = entry.get("digests") + sha = digests.get("sha256") if isinstance(digests, dict) else None + if not isinstance(name, str) or not isinstance(sha, str) or not sha or not name.strip(): + raise PypiCheckError( + f"{prefix}PyPI API 'urls' entry lacks filename/sha256 ({entry!r}); fail closed" + ) + if not _SHA256_RE.fullmatch(sha): + raise PypiCheckError( + f"{prefix}PyPI API sha256 for {name!r} is not a 64-char hex digest " + f"({sha!r}); fail closed" + ) + # A repeated filename means PyPI reports the same distribution + # twice — ambiguous state; fail closed even when both entries + # carry the same digest. + if name in remote: + raise PypiCheckError(f"{prefix}PyPI API 'urls' repeats filename {name!r}; fail closed") + remote[name] = sha + return remote + + +def fetch_remote_files(project: str, version: str, opener: Opener) -> dict[str, str]: + """Return filename -> sha256 for ``version`` on PyPI. + + Raises :class:`VersionAbsentError` when PyPI answers 404 (new release). + """ + url = f"https://pypi.org/pypi/{project}/{version}/json" + data = _read_json(opener, url, not_found_is_absent=True) + return validate_payload(version, data, context="preflight") + + +# ---------------------------------------------------------------------- +# Local dist helpers +# ---------------------------------------------------------------------- + + +def hash_dist_dir(dist: str) -> dict[str, str]: + """Return filename -> sha256 for every file in ``dist``.""" + dist_path = Path(dist) + files = sorted(p.name for p in dist_path.iterdir() if p.is_file()) + if not files: + raise PypiCheckError("dist is empty; nothing to publish") + local: dict[str, str] = {} + for name in files: + with (dist_path / name).open("rb") as fh: + local[name] = hashlib.sha256(fh.read()).hexdigest() + for name, digest in sorted(local.items()): + print(f"local {name} sha256={digest}") + return local + + +# ---------------------------------------------------------------------- +# Preflight (hash-checked idempotency, fail closed) +# ---------------------------------------------------------------------- + + +def pypi_preflight( + dist: str, + project: str, + version: str, + opener: Opener | None = None, +) -> dict[str, object]: + """Compare local ``dist`` files against PyPI and decide what to upload. + + Returns ``{"skip": bool, "upload_dir": str, "missing": [...], + "identical": [...]}``. Stages only missing files into a fresh + ``dist-upload`` directory, re-hashing each staged copy. + """ + if opener is None: + opener = default_opener + local = hash_dist_dir(dist) + try: + remote = fetch_remote_files(project, version, opener) + except VersionAbsentError: + print(f"{project} {version} is absent from PyPI (new release)") + remote = {} + + mismatched = [n for n in sorted(local) if n in remote and remote[n] != local[n]] + if mismatched: + for n in mismatched: + print(f"CONFLICT {n}: local sha256={local[n]} remote sha256={remote[n]}") + raise PypiCheckError( + "PyPI already has file(s) with a DIFFERENT sha256 for the same " + "distribution names; refusing to overwrite or skip (fail closed). " + "The release must be stopped and investigated." + ) + + # Sibling of the dist directory ("dist-upload" next to "dist" in the + # release workflow); keeps parallel/unit-test runs isolated. + upload_dir = Path(dist).resolve().parent / "dist-upload" + missing = [n for n in sorted(local) if n not in remote] + upload_dir.mkdir(exist_ok=False) + for n in missing: + src = Path(dist) / n + dst = upload_dir / n + with Path(src).open("rb") as fin, Path(dst).open("wb") as fout: + fout.write(fin.read()) + with Path(dst).open("rb") as fh: + copied = hashlib.sha256(fh.read()).hexdigest() + if copied != local[n]: + raise PypiCheckError(f"staged copy of {n} changed sha256; fail closed") + + identical = sorted(n for n in local if n in remote) + skip = not missing + print(f"identical files already on PyPI: {identical or 'none'}") + print(f"files to upload: {missing or 'none (full set already on PyPI)'}") + print(f"skip-upload={str(skip).lower()} upload-dir={upload_dir if missing else '-'}") + return { + "skip": skip, + "upload_dir": str(upload_dir) if missing else "", + "missing": missing, + "identical": identical, + } + + +def run_preflight_cli(dist: str, project: str, version: str, output_path: str | None) -> int: + """CLI wrapper used by the release workflow.""" + try: + result = pypi_preflight(dist, project, version) + except VersionAbsentError as exc: # defensive; preflight treats it as new release + print(f"unexpected VersionAbsentError: {exc}", file=sys.stderr) + return 1 + except PypiCheckError as exc: + print(f"PyPI pre-flight FAILED (fail closed): {exc}", file=sys.stderr) + return 1 + if output_path: + with Path(output_path).open("a", encoding="utf-8") as out: + out.write(f"skip={str(result['skip']).lower()}\n") + out.write(f"upload-dir={result['upload_dir']}\n") + return 0 + + +# ---------------------------------------------------------------------- +# Post-upload verification of every published digest +# ---------------------------------------------------------------------- + + +def pypi_post_upload_verify( + dist: str, + project: str, + version: str, + opener: Opener | None = None, +) -> None: + """Verify every local dist file matches PyPI's recorded sha256.""" + if opener is None: + opener = default_opener + url = f"https://pypi.org/pypi/{project}/{version}/json" + data = _read_json(opener, url, not_found_is_absent=False) + remote = validate_payload(version, data, context="post-upload") + failed = [] + for entry in sorted(Path(dist).iterdir()): + with entry.open("rb") as fh: + digest = hashlib.sha256(fh.read()).hexdigest() + name = entry.name + if remote.get(name) != digest: + failed.append((name, digest, remote.get(name))) + if failed: + for name, local_sha, remote_sha in failed: + print(f"MISMATCH {name}: local={local_sha} remote={remote_sha}") + raise PypiCheckError("uploaded files do not all match PyPI's recorded sha256; fail closed") + print("all uploaded files verified byte-identical on PyPI by sha256") + + +def run_post_upload_cli(dist: str, project: str, version: str) -> int: + """CLI wrapper: verify every uploaded file; exit nonzero on failure.""" + try: + pypi_post_upload_verify(dist, project, version) + except PypiCheckError as exc: + print(f"PyPI post-upload verification FAILED (fail closed): {exc}", file=sys.stderr) + return 1 + return 0 + + +# ---------------------------------------------------------------------- +# Consumer probe: install the EXACT built sdist in a clean venv OUTSIDE +# the checkout, then prove the installed package resolves from the venv. +# Used identically by the release sdist job and the PR CI job. +# ---------------------------------------------------------------------- + +_PROBE_SNIPPET = r""" +import importlib.machinery +import json +import sys + +import ktav +import ktav._core + +version = sys.argv[1] +venv_marker = sys.argv[2] + +assert ktav.__version__ == version, ktav.__version__ +# Package and compiled core must BOTH resolve inside the scratch venv, +# proving no checkout path leaked into sys.path. +assert venv_marker in ktav.__file__, ktav.__file__ +assert venv_marker in ktav._core.__file__, ktav._core.__file__ +# The native backend must actually be present: a source-edit must not be +# passable through the pure-Python fallback. +has_core = getattr(ktav, "_HAS_CORE", None) +assert has_core is True, f"_HAS_CORE={has_core!r} (pure fallback active?)" +core_file = ktav._core.__file__ +suffixes = importlib.machinery.EXTENSION_SUFFIXES +assert any(core_file.endswith(s) for s in suffixes), ( + f"ktav._core is not a compiled extension: {core_file!r}" +) +print(f"native core extension verified: {core_file}") +# Real source-edit round trip through the installed package, matching +# tests/edit/test_native_pin.py:38 exactly (byte-identical result). +out = ktav.edit_value("a: 1\n", "a", 2) +assert out == "a: 2\n", out +print(json.dumps({ + "version": ktav.__version__, + "ktav": ktav.__file__, + "core": ktav._core.__file__, + "edit_value": out, +})) +""" + + +def consumer_probe( + sdist: str, + version: str, + scratch: str | None = None, + runner: Callable[..., object] = subprocess.run, +) -> dict[str, str]: + """Verify the native package installed from ``sdist`` outside the checkout. + + The venv directory name (``venv-sdist``) is asserted against + ``ktav.__file__`` so a checkout path leak fails the probe. + """ + sdist = Path(sdist).resolve() + if not sdist.is_file(): + raise PypiCheckError(f"consumer probe: missing sdist {sdist}") + if scratch is None: + import tempfile + + scratch = Path(tempfile.mkdtemp(prefix="ktav-consumer-")) + scratch = Path(scratch).resolve() + python = sys.executable + venv_dir = scratch / "venv-sdist" + marker = "venv-sdist" + + def run(cmd, **kw): + print(f"probe: {' '.join(str(part) for part in cmd)}") + result = runner(cmd, **kw) + if getattr(result, "returncode", 0) != 0: + raise PypiCheckError( + f"consumer probe step failed ({cmd[0]}): " + f"{getattr(result, 'stderr', '') or getattr(result, 'stdout', '')}" + ) + return result + + run([python, "-m", "venv", str(venv_dir)]) + venv_python = venv_dir / ("Scripts" if os.name == "nt" else "bin") / "python" + run([venv_python, "-m", "pip", "install", "--upgrade", "pip"]) + # ktav can ONLY come from the sdist file path — never from the + # checkout as a package source. + run([venv_python, "-m", "pip", "install", sdist]) + probe = run( + [venv_python, "-c", _PROBE_SNIPPET, version, marker], + capture_output=True, + text=True, + ) + print(probe.stdout) + return {"stdout": probe.stdout, "venv": str(venv_dir)} + + +def main(argv: list[str] | None = None) -> int: + """Parse CLI arguments and dispatch to the selected subcommand.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("command", choices=["preflight", "post-upload", "consumer-probe"]) + parser.add_argument("--dist", default="dist") + parser.add_argument("--project", default=DEFAULT_PROJECT) + parser.add_argument("--version", required=True) + parser.add_argument("--sdist", help="consumer-probe only: path to the sdist tarball") + parser.add_argument( + "--scratch", help="consumer-probe only: scratch directory (default: mkdtemp)" + ) + parser.add_argument("--output", help="preflight only: GitHub outputs file to append to") + args = parser.parse_args(argv) + + if args.command == "preflight": + return run_preflight_cli(args.dist, args.project, args.version, args.output) + if args.command == "post-upload": + return run_post_upload_cli(args.dist, args.project, args.version) + if not args.sdist: + parser.error("consumer-probe requires --sdist") + try: + consumer_probe(args.sdist, args.version, scratch=args.scratch) + except PypiCheckError as exc: + print(f"consumer probe FAILED: {exc}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/ci/test_pypi_preflight.py b/tests/ci/test_pypi_preflight.py new file mode 100644 index 0000000..5e67868 --- /dev/null +++ b/tests/ci/test_pypi_preflight.py @@ -0,0 +1,403 @@ +"""PR-CI regression tests for scripts/pypi_preflight.py. + +These tests exercise the EXACT functions the release workflow calls for +PyPI preflight / post-upload verification, with a mocked HTTP opener and +fake local files. They never touch the network and never upload anything. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +from pathlib import Path + +import pytest + +_SCRIPTS = Path(__file__).resolve().parents[2] / "scripts" +_SPEC = importlib.util.spec_from_file_location("pypi_preflight", _SCRIPTS / "pypi_preflight.py") +pypi_preflight_mod = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(pypi_preflight_mod) + +fail_closed = pypi_preflight_mod.PypiCheckError +VersionAbsentError = pypi_preflight_mod.VersionAbsentError + +VERSION = "0.9.0" +DIGEST_A = "a" * 64 +DIGEST_B = "b" * 64 + + +def sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def make_dist(tmp_path: Path, files: dict[str, bytes]) -> str: + dist = tmp_path / "dist" + dist.mkdir() + for name, blob in files.items(): + (dist / name).write_bytes(blob) + return str(dist) + + +def fake_opener(payload) -> object: + """Build an opener() returning a canned PyPI JSON response (or HTTPError).""" + + class Resp: + status = 200 + + def read(self): + if isinstance(payload, Exception): + raise payload + if isinstance(payload, (str, bytes)): + # Raw JSON payload — lets tests exercise duplicate keys, + # exotic formatting, etc., exactly as PyPI would send it. + return payload.encode() if isinstance(payload, str) else payload + return json.dumps(payload).encode() + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def opener(url: str): + assert url.startswith("https://pypi.org/pypi/"), url + return Resp() + + return opener + + +def not_found_opener() -> object: + import urllib.error + + def opener(url: str): + raise urllib.error.HTTPError(url, 404, "Not Found", hdrs=None, fp=None) + + return opener + + +def pypi_payload(files: dict[str, str], version: str = VERSION) -> dict: + return { + "info": {"version": version}, + "urls": [ + {"filename": name, "digests": {"sha256": digest}} for name, digest in files.items() + ], + } + + +# ---------------------------------------------------------------------- +# preflight +# ---------------------------------------------------------------------- + + +def test_new_release_404_uploads_everything(tmp_path, capsys): + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"sdist"}) + result = pypi_preflight_mod.pypi_preflight(dist, "ktav", VERSION, opener=not_found_opener()) + assert result["skip"] is False + assert result["missing"] == ["ktav-0.9.0.tar.gz"] + staged = Path(result["upload_dir"]) / "ktav-0.9.0.tar.gz" + assert staged.read_bytes() == b"sdist" + + +def test_preflight_generic_error_fail_closed(monkeypatch): + # 404 is the ONLY HTTP error treated as "version absent". + with pytest.raises(fail_closed): + pypi_preflight_mod.fetch_remote_files("ktav", VERSION, fake_opener(Exception("boom"))) + + +def test_partial_same_hash_repeat_uploads_only_missing(tmp_path): + blob_a, blob_b = b"a", b"b" + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": blob_a, "ktav-0.9.0-pure.whl": blob_b}) + remote = pypi_payload({"ktav-0.9.0.tar.gz": sha(blob_a)}) + result = pypi_preflight_mod.pypi_preflight(dist, "ktav", VERSION, opener=fake_opener(remote)) + assert result["skip"] is False + assert result["identical"] == ["ktav-0.9.0.tar.gz"] + assert result["missing"] == ["ktav-0.9.0-pure.whl"] + + +def test_full_same_hash_repeat_skips(tmp_path): + blobs = {"ktav-0.9.0.tar.gz": b"sdist", "ktav-0.9.0-cp312.whl": b"wheel"} + dist = make_dist(tmp_path, blobs) + remote = pypi_payload({name: sha(blob) for name, blob in blobs.items()}) + result = pypi_preflight_mod.pypi_preflight(dist, "ktav", VERSION, opener=fake_opener(remote)) + assert result["skip"] is True + assert result["upload_dir"] == "" + assert result["missing"] == [] + + +def test_same_filename_different_hash_fails_closed(tmp_path): + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"local bytes"}) + remote = pypi_payload({"ktav-0.9.0.tar.gz": DIGEST_A}) + with pytest.raises(fail_closed, match="DIFFERENT sha256"): + pypi_preflight_mod.pypi_preflight(dist, "ktav", VERSION, opener=fake_opener(remote)) + + +def test_pypi_preflight_empty_filename_fails_closed_no_upload(tmp_path): + """Regression: a 200 response whose urls entry carries an EMPTY + filename with a valid sha256 must fail closed through the production + preflight path, staging no upload directory.""" + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"sdist"}) + payload = { + "info": {"version": VERSION}, + "urls": [{"filename": "", "digests": {"sha256": DIGEST_A}}], + } + with pytest.raises(fail_closed, match="lacks filename/sha256"): + pypi_preflight_mod.pypi_preflight(dist, "ktav", VERSION, opener=fake_opener(payload)) + assert not (tmp_path / "dist-upload").exists() + + +def test_validate_payload_whitespace_only_filename_fails_closed(): + payload = { + "info": {"version": VERSION}, + "urls": [{"filename": " ", "digests": {"sha256": DIGEST_A}}], + } + with pytest.raises(fail_closed, match="lacks filename/sha256"): + pypi_preflight_mod.validate_payload(VERSION, payload, context="preflight") + + +def test_duplicate_filenames_same_digest_fail_closed(): + payload = { + "info": {"version": VERSION}, + "urls": [ + {"filename": "ktav-0.9.0.tar.gz", "digests": {"sha256": DIGEST_A}}, + {"filename": "ktav-0.9.0.tar.gz", "digests": {"sha256": DIGEST_A}}, + ], + } + with pytest.raises(fail_closed, match="repeats filename"): + pypi_preflight_mod.fetch_remote_files("ktav", VERSION, fake_opener(payload)) + + +def test_duplicate_filenames_different_digest_fail_closed(tmp_path): + payload = { + "info": {"version": VERSION}, + "urls": [ + {"filename": "ktav-0.9.0.tar.gz", "digests": {"sha256": DIGEST_A}}, + {"filename": "ktav-0.9.0.tar.gz", "digests": {"sha256": DIGEST_B}}, + ], + } + with pytest.raises(fail_closed, match="repeats filename"): + pypi_preflight_mod.fetch_remote_files("ktav", VERSION, fake_opener(payload)) + + +def test_malformed_response_payload_fail_closed(tmp_path): + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"x"}) + for bad in [ + {"urls": []}, # missing/unexpected info.version + {"info": {"version": "0.8.0"}, "urls": []}, + {"info": {"version": VERSION}}, # urls missing + {"info": {"version": VERSION}, "urls": "nope"}, + {"info": {"version": VERSION}, "urls": [42]}, + {"info": {"version": VERSION}, "urls": [{"filename": "x"}]}, # no digests + ]: + with pytest.raises(fail_closed): + pypi_preflight_mod.pypi_preflight(dist, "ktav", VERSION, opener=fake_opener(bad)) + + +def test_malformed_sha256_fail_closed(tmp_path): + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"x"}) + for bad_sha in ["zz" * 32, "abc", DIGEST_A.upper(), "a" * 63]: + payload = pypi_payload({"ktav-0.9.0.tar.gz": bad_sha}) + with pytest.raises(fail_closed, match="64-char hex"): + pypi_preflight_mod.pypi_preflight(dist, "ktav", VERSION, opener=fake_opener(payload)) + + +def test_preflight_non_200_and_500_fail_closed(tmp_path): + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"x"}) + + class Resp: + status = 503 + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def read(self): + return b"{}" + + with pytest.raises(fail_closed, match="HTTP 503"): + pypi_preflight_mod.pypi_preflight(dist, "ktav", VERSION, opener=lambda url: Resp()) + import urllib.error + + def opener_500(url): + raise urllib.error.HTTPError(url, 500, "boom", hdrs=None, fp=None) + + with pytest.raises(fail_closed, match="HTTP 500"): + pypi_preflight_mod.fetch_remote_files("ktav", VERSION, opener_500) + + +def test_preflight_empty_dist_fail_closed(tmp_path): + dist = tmp_path / "dist" + dist.mkdir() + with pytest.raises(fail_closed, match="dist is empty"): + pypi_preflight_mod.pypi_preflight(dist, "ktav", VERSION, opener=not_found_opener()) + + +def test_preflight_staged_copy_rehashed(tmp_path): + # The staged upload copy is re-read and re-hashed; assert the staged + # file's digest matches the source file byte-for-byte. + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"sdist"}) + result = pypi_preflight_mod.pypi_preflight(dist, "ktav", VERSION, opener=not_found_opener()) + staged = Path(result["upload_dir"]) / "ktav-0.9.0.tar.gz" + assert sha(staged.read_bytes()) == sha(b"sdist") + + +def test_preflight_cli_writes_github_output(tmp_path, monkeypatch, capsys): + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"sdist"}) + monkeypatch.setattr(pypi_preflight_mod, "default_opener", not_found_opener()) + out_file = tmp_path / "github-output.txt" + rc = pypi_preflight_mod.run_preflight_cli(dist, "ktav", VERSION, str(out_file)) + assert rc == 0 + text = out_file.read_text(encoding="utf-8") + assert "skip=false\n" in text + upload_line = next(line for line in text.splitlines() if line.startswith("upload-dir=")) + assert upload_line.endswith("dist-upload") + + +def test_preflight_cli_conflict_nonzero(tmp_path, monkeypatch, capsys): + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"local"}) + remote = pypi_payload({"ktav-0.9.0.tar.gz": DIGEST_A}) + monkeypatch.setattr(pypi_preflight_mod, "default_opener", fake_opener(remote)) + rc = pypi_preflight_mod.run_preflight_cli(dist, "ktav", VERSION, None) + assert rc != 0 + + +# ---------------------------------------------------------------------- +# post-upload verification +# ---------------------------------------------------------------------- + + +def test_post_upload_matching_passes(tmp_path): + blobs = {"ktav-0.9.0.tar.gz": b"sdist", "ktav-0.9.0.whl": b"wheel"} + dist = make_dist(tmp_path, blobs) + remote = pypi_payload({name: sha(blob) for name, blob in blobs.items()}) + pypi_preflight_mod.pypi_post_upload_verify(dist, "ktav", VERSION, opener=fake_opener(remote)) + + +def test_post_upload_mismatch_fails_closed(tmp_path): + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"sdist"}) + remote = pypi_payload({"ktav-0.9.0.tar.gz": DIGEST_A}) + with pytest.raises(fail_closed, match="do not all match"): + pypi_preflight_mod.pypi_post_upload_verify( + dist, "ktav", VERSION, opener=fake_opener(remote) + ) + + +def test_post_upload_duplicate_filename_same_digest_fail_closed(tmp_path): + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"sdist"}) + payload = { + "info": {"version": VERSION}, + "urls": [ + {"filename": "ktav-0.9.0.tar.gz", "digests": {"sha256": sha(b"sdist")}}, + {"filename": "ktav-0.9.0.tar.gz", "digests": {"sha256": sha(b"sdist")}}, + ], + } + with pytest.raises(fail_closed, match="repeats filename"): + pypi_preflight_mod.pypi_post_upload_verify( + dist, "ktav", VERSION, opener=fake_opener(payload) + ) + + +def test_post_upload_duplicate_filename_different_digest_fail_closed(tmp_path): + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"sdist"}) + payload = { + "info": {"version": VERSION}, + "urls": [ + {"filename": "ktav-0.9.0.tar.gz", "digests": {"sha256": sha(b"sdist")}}, + {"filename": "ktav-0.9.0.tar.gz", "digests": {"sha256": DIGEST_B}}, + ], + } + with pytest.raises(fail_closed, match="repeats filename"): + pypi_preflight_mod.pypi_post_upload_verify( + dist, "ktav", VERSION, opener=fake_opener(payload) + ) + + +def test_post_upload_malformed_sha256_fail_closed(tmp_path): + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"sdist"}) + for bad_sha in ["zz" * 32, "abc", DIGEST_A.upper(), "a" * 63]: + payload = pypi_payload({"ktav-0.9.0.tar.gz": bad_sha}) + with pytest.raises(fail_closed, match="64-char hex"): + pypi_preflight_mod.pypi_post_upload_verify( + dist, "ktav", VERSION, opener=fake_opener(payload) + ) + + +def test_post_upload_missing_remote_file_fails_closed(tmp_path, capsys): + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"sdist", "ktav-0.9.0.whl": b"w"}) + remote = pypi_payload({"ktav-0.9.0.tar.gz": sha(b"sdist")}) + with pytest.raises(fail_closed): + pypi_preflight_mod.pypi_post_upload_verify( + dist, "ktav", VERSION, opener=fake_opener(remote) + ) + # The missing file's name is reported on stdout, not in the exception. + assert "ktav-0.9.0.whl" in capsys.readouterr().out + + +def test_raw_payload_duplicate_sha256_last_wins_fail_closed(tmp_path, capsys): + """A duplicated JSON key must fail closed even when the LAST occurrence + carries the true digest — plain last-wins parsing is no longer possible. + Exercise the production preflight path with a raw JSON response body.""" + blob = b"real sdist bytes" + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": blob}) + real_sha = sha(blob) + raw = ( + ( + '{"info": {"version": "VERSION"}, "urls": [{"filename": "ktav-0.9.0.tar.gz", ' + '"digests": {"sha256": "FIRST", "sha256": "LAST"}}]}' + ) + .replace("VERSION", VERSION) + .replace("FIRST", DIGEST_A) + .replace("LAST", real_sha) + ) + assert json.loads(raw)["urls"][0]["digests"]["sha256"] == real_sha + with pytest.raises(fail_closed, match="duplicate JSON key: 'sha256'"): + pypi_preflight_mod.pypi_preflight(dist, "ktav", VERSION, opener=fake_opener(raw)) + # No upload was staged for the poisoned file. + assert "files to upload: none" not in capsys.readouterr().out + + +def test_post_upload_malformed_payload_fail_closed(tmp_path): + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"sdist"}) + with pytest.raises(fail_closed): + pypi_preflight_mod.pypi_post_upload_verify( + dist, "ktav", VERSION, opener=fake_opener({"urls": []}) + ) + + +def test_post_upload_non_200_fail_closed(tmp_path): + dist = make_dist(tmp_path, {"ktav-0.9.0.tar.gz": b"sdist"}) + + class Resp: + status = 500 + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def read(self): + return b"{}" + + with pytest.raises(fail_closed, match="HTTP 500"): + pypi_preflight_mod.pypi_post_upload_verify(dist, "ktav", VERSION, opener=lambda url: Resp()) + + +# ---------------------------------------------------------------------- +# no-network guarantee +# ---------------------------------------------------------------------- + + +def test_module_never_opens_real_urls(monkeypatch): + """Any real urllib call inside the module raises in these tests' env.""" + + def boom(*args, **kw): + raise AssertionError("real network access attempted") + + monkeypatch.setattr(pypi_preflight_mod.urllib.request, "urlopen", boom) + # default_opener must route through urlopen — mocked here proves the + # tests above (which inject their own openers) never hit the network. + with pytest.raises(AssertionError): + pypi_preflight_mod.default_opener("https://pypi.org/pypi/ktav/0.9.0/json")