diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b443544..a6336f8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,7 +3,17 @@ name: Release and PyPI Publish # A reviewed pull request prepares the version and changelog. A dispatch from # protected main can then create one annotated tag through the release App. The # tag event rebuilds and publishes the exact source through the protected PyPI -# environment. +# environment, then creates the GitHub Release through the release App with +# ``gh release create "$tag" dist/* --verify-tag``. The Release body is that +# version's CHANGELOG.md section. Its assets are exactly the PyPI artifacts, +# proven by SHA-256 digest before and after the Release exists. +# +# A dispatch from protected main with ``publish_existing_tag`` set publishes +# only the GitHub Release for a tag that already exists and is already on PyPI. +# It runs the same tag, version, evidence, and digest checks as the tag path, +# never publishes to PyPI, and never creates or moves a tag. Use it when a tag +# run published to PyPI but not to GitHub. Re-running that tag run cannot help, +# because a tag run uses release.yml from the tagged commit. on: workflow_dispatch: @@ -12,6 +22,11 @@ on: description: "Reviewed version already present on protected main (for example 1.3.0)" type: string required: true + publish_existing_tag: + description: "Only publish the GitHub Release for the existing vVERSION tag, whose PyPI artifacts already exist" + type: boolean + required: false + default: false push: tags: ["v*"] @@ -48,7 +63,7 @@ jobs: create-release-tag: needs: validate-dispatch - if: ${{ github.event_name == 'workflow_dispatch' && needs.validate-dispatch.result == 'success' }} + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.publish_existing_tag && needs.validate-dispatch.result == 'success' }} runs-on: ubuntu-latest environment: release-identity permissions: @@ -107,7 +122,7 @@ jobs: release_tag="v${RELEASE_VERSION}" if git ls-remote --exit-code --tags origin "refs/tags/${release_tag}" >/dev/null 2>&1; then - echo "${release_tag} already exists. Rerun its tag workflow instead of creating another ref." + echo "${release_tag} already exists. To publish only its missing GitHub Release, dispatch release.yml with publish_existing_tag." exit 1 fi RELEASE_VERSION="${RELEASE_VERSION}" python - <<'PY' @@ -314,12 +329,39 @@ jobs: if: ${{ steps.publication.outputs.publish_pypi == 'true' }} uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + - name: Keep exactly the PyPI artifacts as release assets + if: ${{ steps.publication.outputs.create_github_release == 'true' }} + env: + RELEASE_VERSION: ${{ needs.validate-tag.outputs.version }} + shell: bash + run: | + set -euo pipefail + # The PyPI action writes *.publish.attestation files into dist/. + # PyPI serves those itself; the Release carries only the artifacts. + mkdir -p "${RUNNER_TEMP}/pypi-attestations" + find dist -maxdepth 1 -name '*.publish.attestation' \ + -exec mv -t "${RUNNER_TEMP}/pypi-attestations" {} + + python scripts/release_assets.py check-pypi \ + --dist dist \ + --package openadapt-capture \ + --version "${RELEASE_VERSION}" + python scripts/release_assets.py notes \ + --changelog CHANGELOG.md \ + --version "${RELEASE_VERSION}" \ + --output "${RUNNER_TEMP}/release-notes.md" + - name: Publish the GitHub Release through the release App if: ${{ steps.publication.outputs.create_github_release == 'true' }} - uses: python-semantic-release/publish-action@99d4062dd393b5a7a62c5fe9ed78fb364b5674f2 # v10.7.0 - with: - github_token: ${{ steps.release-app.outputs.token }} - tag: ${{ needs.validate-tag.outputs.tag }} + env: + GH_TOKEN: ${{ steps.release-app.outputs.token }} + GH_REPO: ${{ github.repository }} + RELEASE_TAG: ${{ needs.validate-tag.outputs.tag }} + shell: bash + run: | + set -euo pipefail + gh release create "${RELEASE_TAG}" dist/* --verify-tag \ + --title "${RELEASE_TAG}" \ + --notes-file "${RUNNER_TEMP}/release-notes.md" - name: Verify both publication surfaces and artifact digests env: @@ -333,3 +375,187 @@ jobs: --repository "${GITHUB_REPOSITORY}" \ --wait-seconds 180 \ --poll-seconds 10 + + publish-existing-tag-release: + needs: validate-dispatch + if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish_existing_tag && needs.validate-dispatch.result == 'success' }} + runs-on: ubuntu-latest + environment: release-identity + permissions: + actions: read + contents: read + steps: + - name: Create the exact release App token + id: release-app + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 + with: + app-id: ${{ vars.OPENADAPT_RELEASE_APP_ID }} + private-key: ${{ secrets.OPENADAPT_RELEASE_APP_PRIVATE_KEY }} + owner: ${{ github.repository_owner }} + repositories: ${{ github.event.repository.name }} + permission-contents: write + + - name: Checkout the dispatched main commit + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.12" + + - name: Install exact uv + uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2 + with: + version: "0.11.29" + + - name: Verify the existing release App tag and its reviewed version + id: tag + env: + RELEASE_VERSION: ${{ inputs.version }} + shell: bash + run: | + set -euo pipefail + release_tag="v${RELEASE_VERSION}" + git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main + current_main="$(git rev-parse refs/remotes/origin/main)" + if [ "${current_main}" != "${GITHUB_SHA}" ] || [ "$(git rev-parse HEAD)" != "${GITHUB_SHA}" ]; then + echo "Refusing a stale dispatch. Current main is ${current_main}; the dispatch is ${GITHUB_SHA}." + exit 1 + fi + if ! git ls-remote --exit-code --tags origin "refs/tags/${release_tag}" >/dev/null 2>&1; then + echo "${release_tag} does not exist. Dispatch release.yml without publish_existing_tag to create it." + exit 1 + fi + git fetch --no-tags --force origin "+refs/tags/${release_tag}:refs/tags/${release_tag}" + if [ "$(git cat-file -t "refs/tags/${release_tag}")" != "tag" ]; then + echo "${release_tag} is not an annotated tag." + exit 1 + fi + tagger="$(git for-each-ref --format='%(taggername)' "refs/tags/${release_tag}")" + if [ "${tagger}" != "openadapt-release[bot]" ]; then + echo "${release_tag} was not created by the release App (tagger: ${tagger})." + exit 1 + fi + tagged_sha="$(git rev-parse "refs/tags/${release_tag}^{commit}")" + if ! git merge-base --is-ancestor "${tagged_sha}" refs/remotes/origin/main; then + echo "The tagged commit is not contained in protected main." + exit 1 + fi + + # Check out the tagged source beside main. main's checkout supplies + # this workflow's tooling; the tagged tree supplies everything that + # is released. + source_dir="${RUNNER_TEMP}/tagged-source" + git worktree add --detach "${source_dir}" "${tagged_sha}" + cd "${source_dir}" + project_version="$(python -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')" + if [ "${release_tag}" != "v${project_version}" ]; then + echo "The tag and the tagged pyproject version (${project_version}) differ." + exit 1 + fi + python scripts/check_changelog.py + if ! grep -Eq "^## ${release_tag} \(" CHANGELOG.md; then + echo "CHANGELOG.md has no entry for ${release_tag}." + exit 1 + fi + { + echo "tag=${release_tag}" + echo "sha=${tagged_sha}" + echo "source=${source_dir}" + } >> "${GITHUB_OUTPUT}" + + - name: Require exact-tag test and hosted qualification evidence + env: + GH_TOKEN: ${{ github.token }} + TAGGED_SHA: ${{ steps.tag.outputs.sha }} + run: | + python scripts/check_release_ci.py \ + --repository "${GITHUB_REPOSITORY}" \ + --sha "${TAGGED_SHA}" + + - name: Rebuild and verify the tagged source + working-directory: ${{ steps.tag.outputs.source }} + shell: bash + run: | + set -euo pipefail + rm -rf dist + uv build --wheel --sdist + python scripts/verify_distribution.py dist/* + python scripts/check_source_boundary.py --require-dist + + - name: Download the exact PyPI artifacts and match them to the rebuild + env: + RELEASE_VERSION: ${{ inputs.version }} + SOURCE_DIR: ${{ steps.tag.outputs.source }} + shell: bash + run: | + set -euo pipefail + rm -rf dist + python scripts/release_assets.py fetch-pypi \ + --dist dist \ + --rebuilt "${SOURCE_DIR}/dist" \ + --package openadapt-capture \ + --version "${RELEASE_VERSION}" + + - name: Check for an exact existing GitHub Release + id: publication + env: + GH_TOKEN: ${{ steps.release-app.outputs.token }} + run: | + python scripts/verify_release_publication.py \ + --dist dist \ + --package openadapt-capture \ + --version "${{ inputs.version }}" \ + --tag "${{ steps.tag.outputs.tag }}" \ + --repository "${GITHUB_REPOSITORY}" \ + --allow-missing \ + --github-output "${GITHUB_OUTPUT}" + + # fetch-pypi already failed if PyPI lacks the version. The verifier writes + # no outputs when both surfaces already match, so a rerun after success + # skips both this guard and the creation step. + - name: Refuse a version that is not on PyPI + if: ${{ steps.publication.outputs.publish_pypi == 'true' }} + run: | + echo "This path never publishes to PyPI, and the version is not there." + exit 1 + + - name: Write the release notes from the tagged CHANGELOG + if: ${{ steps.publication.outputs.create_github_release == 'true' }} + env: + RELEASE_VERSION: ${{ inputs.version }} + SOURCE_DIR: ${{ steps.tag.outputs.source }} + run: | + python scripts/release_assets.py notes \ + --changelog "${SOURCE_DIR}/CHANGELOG.md" \ + --version "${RELEASE_VERSION}" \ + --output "${RUNNER_TEMP}/release-notes.md" + + - name: Publish the GitHub Release through the release App + if: ${{ steps.publication.outputs.create_github_release == 'true' }} + env: + GH_TOKEN: ${{ steps.release-app.outputs.token }} + GH_REPO: ${{ github.repository }} + RELEASE_TAG: ${{ steps.tag.outputs.tag }} + shell: bash + run: | + set -euo pipefail + gh release create "${RELEASE_TAG}" dist/* --verify-tag \ + --title "${RELEASE_TAG}" \ + --notes-file "${RUNNER_TEMP}/release-notes.md" + + - name: Verify both publication surfaces and artifact digests + env: + GH_TOKEN: ${{ steps.release-app.outputs.token }} + run: | + python scripts/verify_release_publication.py \ + --dist dist \ + --package openadapt-capture \ + --version "${{ inputs.version }}" \ + --tag "${{ steps.tag.outputs.tag }}" \ + --repository "${GITHUB_REPOSITORY}" \ + --wait-seconds 180 \ + --poll-seconds 10 diff --git a/scripts/release_assets.py b/scripts/release_assets.py new file mode 100644 index 0000000..a0d8023 --- /dev/null +++ b/scripts/release_assets.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python3 +"""Prepare the GitHub Release body and prove its assets are the PyPI artifacts. + +Both release paths in ``release.yml`` attach assets with +``gh release create "$tag" dist/* --verify-tag``. Before they do, this script +proves ``dist`` holds exactly one wheel and one sdist, and that PyPI serves +those exact files for that version (SHA-256 digests). The tag path built +``dist`` and uploaded it to PyPI. The existing-tag path downloads the files +from PyPI, checks them against PyPI's own digests, and requires them to equal +a rebuild of the tagged source, so no asset can differ from PyPI. + +Subcommands: + +``notes`` write the ``## vX.Y.Z (date)`` section of CHANGELOG.md. +``check-pypi`` require ``dist`` to be exactly the PyPI artifacts. +``fetch-pypi`` download the PyPI artifacts into ``dist`` and require them to + equal a rebuilt ``--rebuilt`` directory. +""" + +from __future__ import annotations + +import argparse +import hashlib +import re +import sys +import urllib.parse +from pathlib import Path +from typing import Any + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from verify_release_publication import ( # noqa: E402 + PublicationError, + _json_document, + _request, + artifact_digests, +) + +RELEASE_HEADING = re.compile(r"^## v(?P\d+\.\d+\.\d+) \(\d{4}-\d{2}-\d{2}\)$") +STABLE_VERSION = re.compile(r"^\d+\.\d+\.\d+$") +PYPI_FILES_HOST = "files.pythonhosted.org" + + +def release_notes(changelog: str, version: str) -> str: + """Return the exact CHANGELOG section for one version, heading included.""" + if not STABLE_VERSION.fullmatch(version): + raise PublicationError(f"not an exact stable version: {version!r}") + lines = changelog.splitlines() + starts = [index for index, line in enumerate(lines) if RELEASE_HEADING.match(line)] + matching = [ + index for index in starts if RELEASE_HEADING.match(lines[index])["version"] == version + ] + if len(matching) != 1: + raise PublicationError( + f"CHANGELOG.md must contain exactly one v{version} section, found {len(matching)}" + ) + start = matching[0] + later = [index for index in starts if index > start] + end = later[0] if later else len(lines) + section = "\n".join(lines[start:end]).strip() + if section == lines[start].strip(): + raise PublicationError(f"the v{version} CHANGELOG section is empty") + return section + "\n" + + +def exact_dist(dist: Path) -> dict[str, str]: + """Require ``dist/*`` to expand to one wheel, one sdist, and nothing else. + + A shell glob skips hidden names, so ``uv build``'s own ``dist/.gitignore`` + is not an asset; every other entry, such as a ``*.publish.attestation`` + file the PyPI action writes, must not be there. + """ + if not dist.is_dir(): + raise PublicationError(f"{dist} is not a directory") + entries = sorted(path.name for path in dist.iterdir() if not path.name.startswith(".")) + digests = artifact_digests(dist) + if entries != sorted(digests): + extra = sorted(set(entries) - set(digests)) + raise PublicationError(f"dist holds files that are not release artifacts: {extra}") + return digests + + +def pypi_files(package: str, version: str) -> list[dict[str, Any]]: + """Return PyPI's file entries for one version; fail if the version is absent.""" + url = ( + "https://pypi.org/pypi/" + f"{urllib.parse.quote(package, safe='')}/{urllib.parse.quote(version, safe='')}/json" + ) + document = _json_document(_request(url), surface="PyPI") + if document is None: + raise PublicationError(f"{package} {version} is not on PyPI") + urls = document.get("urls") + if not isinstance(urls, list) or not urls: + raise PublicationError("PyPI response has no artifact list") + files = [] + for entry in urls: + if not isinstance(entry, dict): + raise PublicationError("PyPI response has an invalid artifact entry") + filename = entry.get("filename") + file_url = entry.get("url") + digests = entry.get("digests") + digest = digests.get("sha256") if isinstance(digests, dict) else None + if not all(isinstance(value, str) for value in (filename, file_url, digest)): + raise PublicationError("PyPI response has an incomplete artifact entry") + if Path(filename).name != filename or filename.startswith("."): + raise PublicationError(f"PyPI returned an unsafe file name: {filename!r}") + parsed = urllib.parse.urlsplit(file_url) + if parsed.scheme != "https" or parsed.hostname != PYPI_FILES_HOST: + raise PublicationError(f"PyPI artifact is not served from {PYPI_FILES_HOST}") + files.append({"filename": filename, "url": file_url, "sha256": digest}) + return files + + +def pypi_digests(package: str, version: str) -> dict[str, str]: + return {entry["filename"]: entry["sha256"] for entry in pypi_files(package, version)} + + +def check_pypi(dist: Path, package: str, version: str) -> dict[str, str]: + """Require ``dist`` to be exactly the artifacts PyPI serves for ``version``.""" + local = exact_dist(dist) + remote = pypi_digests(package, version) + if local != remote: + raise PublicationError(f"dist differs from PyPI: dist={local}, PyPI={remote}") + return local + + +def fetch_pypi(dist: Path, rebuilt: Path, package: str, version: str) -> dict[str, str]: + """Download the PyPI artifacts into an empty ``dist``; they must equal the rebuild.""" + expected = exact_dist(rebuilt) + files = pypi_files(package, version) + remote = {entry["filename"]: entry["sha256"] for entry in files} + if remote != expected: + raise PublicationError( + f"PyPI artifacts differ from the tagged rebuild: PyPI={remote}, rebuild={expected}" + ) + dist.mkdir(parents=True, exist_ok=True) + if any(not path.name.startswith(".") for path in dist.iterdir()): + raise PublicationError(f"{dist} must be empty before PyPI artifacts are fetched") + for entry in files: + content = _request(entry["url"], accept="application/octet-stream") + if content is None: + raise PublicationError(f"PyPI artifact disappeared: {entry['filename']}") + if hashlib.sha256(content).hexdigest() != entry["sha256"]: + raise PublicationError(f"downloaded {entry['filename']} does not match PyPI's digest") + (dist / entry["filename"]).write_bytes(content) + return check_pypi(dist, package, version) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + commands = parser.add_subparsers(dest="command", required=True) + notes = commands.add_parser("notes") + notes.add_argument("--changelog", type=Path, default=Path("CHANGELOG.md")) + notes.add_argument("--version", required=True) + notes.add_argument("--output", type=Path, required=True) + for name in ("check-pypi", "fetch-pypi"): + command = commands.add_parser(name) + command.add_argument("--dist", type=Path, required=True) + command.add_argument("--package", required=True) + command.add_argument("--version", required=True) + if name == "fetch-pypi": + command.add_argument("--rebuilt", type=Path, required=True) + args = parser.parse_args(argv) + + if args.command == "notes": + text = release_notes(args.changelog.read_text(encoding="utf-8"), args.version) + args.output.write_text(text, encoding="utf-8") + print(f"Wrote the v{args.version} CHANGELOG section to {args.output}.") + return 0 + if args.command == "check-pypi": + digests = check_pypi(args.dist, args.package, args.version) + else: + digests = fetch_pypi(args.dist, args.rebuilt, args.package, args.version) + for name, digest in sorted(digests.items()): + print(f"{digest} {name}") + print(f"dist is exactly the PyPI artifacts of {args.package} {args.version}.") + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except PublicationError as exc: + raise SystemExit(f"error: {exc}") from None diff --git a/tests/test_release_assets.py b/tests/test_release_assets.py new file mode 100644 index 0000000..052138a --- /dev/null +++ b/tests/test_release_assets.py @@ -0,0 +1,195 @@ +"""The GitHub Release body and assets come from CHANGELOG.md and PyPI exactly.""" + +from __future__ import annotations + +import hashlib +import json +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) + +import release_assets # noqa: E402 +from verify_release_publication import PublicationError # noqa: E402 + +WHEEL = "openadapt_capture-1.3.0-py3-none-any.whl" +SDIST = "openadapt_capture-1.3.0.tar.gz" +CONTENT = {WHEEL: b"wheel bytes", SDIST: b"sdist bytes"} +CHANGELOG = """# CHANGELOG + + + +## v1.3.0 (2026-10-17) + +### Features + +- Shadow mode. + +## v1.2.2 (2026-07-28) + +### Bug Fixes + +- Older fix. +""" + + +def _sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _dist(path: Path, files: dict[str, bytes] = CONTENT) -> Path: + path.mkdir() + for name, data in files.items(): + (path / name).write_bytes(data) + (path / ".gitignore").write_text("*\n", encoding="utf-8") + return path + + +def _pypi( + monkeypatch: pytest.MonkeyPatch, + files: dict[str, bytes], + *, + host: str = "files.pythonhosted.org", +) -> None: + document = { + "urls": [ + { + "filename": name, + "url": f"https://{host}/packages/{name}", + "digests": {"sha256": _sha(data)}, + } + for name, data in files.items() + ] + } + + def request(url: str, *, token: str | None = None, accept: str = "") -> bytes | None: + if url.startswith("https://pypi.org/pypi/openadapt-capture/1.3.0/json"): + return json.dumps(document).encode() + name = url.rsplit("/", 1)[-1] + return files.get(name) + + monkeypatch.setattr(release_assets, "_request", request) + + +def test_notes_are_exactly_one_versions_changelog_section() -> None: + notes = release_assets.release_notes(CHANGELOG, "1.3.0") + + assert notes == "## v1.3.0 (2026-10-17)\n\n### Features\n\n- Shadow mode.\n" + assert "Older fix" not in notes + assert release_assets.release_notes(CHANGELOG, "1.2.2").endswith("- Older fix.\n") + + +@pytest.mark.parametrize("version", ["9.9.9", "1.3", "v1.3.0"]) +def test_notes_refuse_a_missing_or_inexact_version(version: str) -> None: + with pytest.raises(PublicationError): + release_assets.release_notes(CHANGELOG, version) + + +def test_notes_refuse_an_empty_section() -> None: + with pytest.raises(PublicationError, match="empty"): + release_assets.release_notes( + "## v1.3.0 (2026-10-17)\n\n## v1.2.2 (2026-07-28)\n- x\n", "1.3.0" + ) + + +def test_the_real_changelog_has_notes_for_its_latest_release() -> None: + changelog = (ROOT / "CHANGELOG.md").read_text(encoding="utf-8") + version = changelog.split("\n## v", 1)[1].split(" ", 1)[0] + + assert release_assets.release_notes(changelog, version).startswith(f"## v{version} (") + + +def test_check_pypi_accepts_dist_that_is_exactly_pypi( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _pypi(monkeypatch, CONTENT) + + digests = release_assets.check_pypi(_dist(tmp_path / "dist"), "openadapt-capture", "1.3.0") + + assert digests == {name: _sha(data) for name, data in CONTENT.items()} + + +def test_check_pypi_rejects_an_attestation_left_in_dist( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _pypi(monkeypatch, CONTENT) + dist = _dist(tmp_path / "dist") + (dist / f"{WHEEL}.publish.attestation").write_text("{}", encoding="utf-8") + + with pytest.raises(PublicationError, match="not release artifacts"): + release_assets.check_pypi(dist, "openadapt-capture", "1.3.0") + + +def test_check_pypi_rejects_different_bytes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _pypi(monkeypatch, {WHEEL: b"other wheel", SDIST: CONTENT[SDIST]}) + + with pytest.raises(PublicationError, match="differs from PyPI"): + release_assets.check_pypi(_dist(tmp_path / "dist"), "openadapt-capture", "1.3.0") + + +def test_fetch_pypi_downloads_bytes_equal_to_the_rebuild( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _pypi(monkeypatch, CONTENT) + rebuilt = _dist(tmp_path / "rebuilt") + dist = tmp_path / "dist" + + release_assets.fetch_pypi(dist, rebuilt, "openadapt-capture", "1.3.0") + + assert sorted(path.name for path in dist.iterdir()) == sorted(CONTENT) + assert all((dist / name).read_bytes() == data for name, data in CONTENT.items()) + + +def test_fetch_pypi_refuses_a_rebuild_that_differs_from_pypi( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _pypi(monkeypatch, CONTENT) + rebuilt = _dist(tmp_path / "rebuilt", {WHEEL: b"rebuilt differently", SDIST: CONTENT[SDIST]}) + + with pytest.raises(PublicationError, match="differ from the tagged rebuild"): + release_assets.fetch_pypi(tmp_path / "dist", rebuilt, "openadapt-capture", "1.3.0") + assert not (tmp_path / "dist").exists() + + +def test_fetch_pypi_refuses_a_download_that_does_not_match_pypis_digest( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _pypi(monkeypatch, CONTENT) + rebuilt = _dist(tmp_path / "rebuilt") + original = release_assets._request + + def tampered(url: str, **kwargs: object) -> bytes | None: + data = original(url, **kwargs) + return b"tampered" if url.endswith(WHEEL) else data + + monkeypatch.setattr(release_assets, "_request", tampered) + + with pytest.raises(PublicationError, match="does not match PyPI's digest"): + release_assets.fetch_pypi(tmp_path / "dist", rebuilt, "openadapt-capture", "1.3.0") + + +def test_fetch_pypi_refuses_files_served_from_another_host( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _pypi(monkeypatch, CONTENT, host="example.com") + + with pytest.raises(PublicationError, match="files.pythonhosted.org"): + release_assets.fetch_pypi( + tmp_path / "dist", _dist(tmp_path / "rebuilt"), "openadapt-capture", "1.3.0" + ) + + +def test_fetch_pypi_refuses_a_version_missing_from_pypi( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(release_assets, "_request", lambda url, **kwargs: None) + + with pytest.raises(PublicationError, match="not on PyPI"): + release_assets.fetch_pypi( + tmp_path / "dist", _dist(tmp_path / "rebuilt"), "openadapt-capture", "1.3.0" + ) diff --git a/tests/test_repository_contracts.py b/tests/test_repository_contracts.py index a4c8d00..0baf7b4 100644 --- a/tests/test_repository_contracts.py +++ b/tests/test_repository_contracts.py @@ -87,7 +87,9 @@ def test_exact_test_workflow_can_be_started_by_the_release_orchestrator() -> Non def test_tag_publication_requires_exact_tag_oidc_and_digest_verification() -> None: workflow = (ROOT / ".github/workflows/release.yml").read_text(encoding="utf-8") validate = workflow[workflow.index("\n validate-tag:") : workflow.index("\n publish-tag:")] - publish = workflow[workflow.index("\n publish-tag:") :] + publish = workflow[ + workflow.index("\n publish-tag:") : workflow.index("\n publish-existing-tag-release:") + ] assert "GITHUB_EVENT_NAME" in validate assert "GITHUB_REF_TYPE" in validate @@ -103,10 +105,81 @@ def test_tag_publication_requires_exact_tag_oidc_and_digest_verification() -> No assert "python scripts/verify_distribution.py dist/*" in publish assert "python scripts/check_source_boundary.py --require-dist" in publish assert "pypa/gh-action-pypi-publish@" in publish - assert "python-semantic-release/publish-action@" in publish assert "scripts/verify_release_publication.py" in publish assert "--allow-missing" in publish assert "--wait-seconds 180" in publish + _assert_release_app_publishes_exact_pypi_assets(publish) + + +def _assert_release_app_publishes_exact_pypi_assets(job: str) -> None: + """One GitHub Release creation, by the release App, from exact PyPI bytes.""" + create = job.index('gh release create "${RELEASE_TAG}" dist/* --verify-tag') + exact = job.rindex("python scripts/release_assets.py", 0, create) + final = job.index("--wait-seconds 180") + + # The semantic-release action refuses a detached tag checkout. + assert "python-semantic-release" not in job + assert job.count("gh release create") == 1 + assert "GH_TOKEN: ${{ steps.release-app.outputs.token }}" in job[:create][-400:] + assert '--notes-file "${RUNNER_TEMP}/release-notes.md"' in job + assert "python scripts/release_assets.py notes" in job + assert ("check-pypi" in job) or ("fetch-pypi" in job) + assert exact < create < final + + +def test_existing_tag_release_path_reuses_every_check_and_never_publishes_pypi() -> None: + """The recovery path proves the tag, version, evidence, and PyPI digests.""" + workflow = (ROOT / ".github/workflows/release.yml").read_text(encoding="utf-8") + triggers = workflow[workflow.index("\non:\n") : workflow.index("\njobs:\n")] + create_tag = workflow[ + workflow.index("\n create-release-tag:") : workflow.index("\n validate-tag:") + ] + job = workflow[workflow.index("\n publish-existing-tag-release:") :] + steps = [ + "- name: Verify the existing release App tag and its reviewed version", + "- name: Require exact-tag test and hosted qualification evidence", + "- name: Rebuild and verify the tagged source", + "- name: Download the exact PyPI artifacts and match them to the rebuild", + "- name: Check for an exact existing GitHub Release", + "- name: Refuse a version that is not on PyPI", + "- name: Write the release notes from the tagged CHANGELOG", + "- name: Publish the GitHub Release through the release App", + "- name: Verify both publication surfaces and artifact digests", + ] + + assert " publish_existing_tag:" in triggers + assert "type: boolean" in triggers + assert "default: false" in triggers + assert "!inputs.publish_existing_tag" in create_tag + assert "needs: validate-dispatch" in job + assert "inputs.publish_existing_tag &&" in job + assert "environment: release-identity" in job + assert "persist-credentials: false" in job + # Only the release App token may write; the job's own token stays read-only. + assert "\n permissions:\n actions: read\n contents: read\n steps:" in job + assert "permission-contents: write" in job + assert "id-token: write" not in job + assert "environment: pypi" not in job + assert "pypa/gh-action-pypi-publish" not in job + assert "git tag" not in job + assert "git push" not in job + assert [job.index(step) for step in steps] == sorted(job.index(step) for step in steps) + # Same tag checks as the tag event: current main, annotated, made by the + # release App, contained in main, and matching the reviewed version. + assert 'if [ "${current_main}" != "${GITHUB_SHA}" ]' in job + assert 'git cat-file -t "refs/tags/${release_tag}"' in job + assert '"${tagger}" != "openadapt-release[bot]"' in job + assert "git merge-base --is-ancestor" in job + assert "python scripts/check_changelog.py" in job + assert "--dispatch-missing" not in job + assert '--sha "${TAGGED_SHA}"' in job + assert "python scripts/verify_distribution.py dist/*" in job + assert "python scripts/check_source_boundary.py --require-dist" in job + assert '--rebuilt "${SOURCE_DIR}/dist"' in job + assert "publish_pypi == 'true'" in job + # A rerun after success: the verifier writes no outputs, so nothing runs. + assert "create_github_release == 'true'" in job + _assert_release_app_publishes_exact_pypi_assets(job) def test_native_observers_are_part_of_each_interactive_qualification() -> None: