From 0dc8679edcc6061fbcdf3de13c7e16000e9d1b65 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:42:42 +0800 Subject: [PATCH] ci: publish accepted releases to PyPI in one click --- .github/workflows/publish-pypi.yml | 61 ++++----- .github/workflows/trigger-pypi.yml | 4 +- docs/releasing.md | 30 ++--- scripts/prepare_pypi_release.py | 26 ++-- tests/scripts/test_pypi_release_trigger.py | 148 +++++++++------------ tests/test_prepare_pypi_release.py | 33 +++-- 6 files changed, 142 insertions(+), 160 deletions(-) diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index 1fb5eb0a2..fc0bc0c69 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -1,4 +1,4 @@ -name: Publish approved release to PyPI +name: Publish accepted release to PyPI on: workflow_run: @@ -7,7 +7,7 @@ on: workflow_dispatch: inputs: version: - description: Published, signed stable release version (without v) + description: Published stable release version (without v) required: true type: string destination: @@ -32,16 +32,17 @@ jobs: (github.event_name == 'workflow_dispatch' || (github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'release' && + github.event.workflow_run.head_repository.full_name == github.repository && (github.event.workflow_run.path == '.github/workflows/trigger-pypi.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/trigger-pypi.yml@')))) runs-on: ubuntu-latest timeout-minutes: 30 permissions: contents: read + actions: read outputs: artifact_id: ${{ steps.staged.outputs.artifact-id }} upload_required: ${{ steps.reconcile.outputs.upload_required }} - release_actor: ${{ steps.release.outputs.release_actor }} release_version: ${{ steps.release.outputs.release_version }} destination: ${{ steps.release.outputs.destination }} steps: @@ -54,7 +55,7 @@ jobs: - name: Install locked verification dependencies run: | python -m pip install --require-hashes --only-binary=:all: -r .github/release-signing-requirements.txt - - name: Download and verify the approved public release + - name: Match the public release to the accepted candidate id: release env: GH_TOKEN: ${{ github.token }} @@ -62,7 +63,6 @@ jobs: DESTINATION_INPUT: ${{ inputs.destination }} UPSTREAM_TAG: ${{ github.event.workflow_run.head_branch }} UPSTREAM_SHA: ${{ github.event.workflow_run.head_sha }} - UPSTREAM_ACTOR: ${{ github.event.workflow_run.actor.login }} shell: bash run: | set -euo pipefail @@ -70,15 +70,12 @@ jobs: [[ "$UPSTREAM_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo 'Invalid release tag.' >&2; exit 1; } VERSION="${UPSTREAM_TAG#v}" destination=pypi - release_actor="$UPSTREAM_ACTOR" else VERSION="$VERSION_INPUT" destination="$DESTINATION_INPUT" - release_actor="$GITHUB_ACTOR" fi [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo 'Expected a final X.Y.Z version.' >&2; exit 1; } [[ "$destination" == pypi || "$destination" == testpypi ]] || { echo 'Invalid destination.' >&2; exit 1; } - [[ "$release_actor" =~ ^[A-Za-z0-9-]+$ ]] || { echo 'A human release actor is required.' >&2; exit 1; } tag="v$VERSION" gh release view "$tag" --repo HKUDS/nanobot --json tagName,isDraft,isPrerelease \ | jq -e --arg tag "$tag" '.tagName == $tag and .isDraft == false and .isPrerelease == false' >/dev/null @@ -87,15 +84,33 @@ jobs: if [[ "$GITHUB_EVENT_NAME" == workflow_run ]]; then [[ "$UPSTREAM_SHA" == "$commit" ]] || { echo 'Release tag no longer matches the trigger.' >&2; exit 1; } fi - echo "release_actor=$release_actor" >> "$GITHUB_OUTPUT" - echo "release_version=$VERSION" >> "$GITHUB_OUTPUT" - echo "destination=$destination" >> "$GITHUB_OUTPUT" gh release download "$tag" --repo HKUDS/nanobot --dir "$RUNNER_TEMP/release" \ - --pattern 'release-manifest.json' --pattern 'release-manifest.json.sigstore.json' \ + --pattern 'release-manifest.json' \ --pattern 'nanobot_ai-*.whl' --pattern 'nanobot_ai-*.tar.gz' \ --pattern 'nanobot-tui-*.zip' --pattern 'nanobot-tui-*.zip.sha256' - python -m scripts.prepare_pypi_release --release-dir "$RUNNER_TEMP/release" \ - --output "$RUNNER_TEMP/pypi" --version "$VERSION" --tag-commit "$commit" + # The build report alone isn't acceptance: require the final gate from the same attempt. + gh api --paginate --method GET 'repos/HKUDS/nanobot/actions/workflows/release-candidate.yml/runs' \ + -f head_sha="$commit" -f branch=main -f event=workflow_dispatch -f status=success -F per_page=100 \ + --jq '.workflow_runs[] | select(.head_repository.full_name == "HKUDS/nanobot") | [.id, .run_number, .run_attempt] | @tsv' \ + > "$RUNNER_TEMP/candidate-runs" + while IFS=$'\t' read -r run number attempt; do + accepted="$(gh api "repos/HKUDS/nanobot/actions/runs/$run/attempts/$attempt/jobs?per_page=100" \ + --jq 'any(.jobs[]; .name == "Candidate required" and .conclusion == "success")')" + [[ "$accepted" == true ]] || continue + report="candidate-report-$number-$attempt" + if ! gh run download "$run" --repo HKUDS/nanobot --name "$report" --dir "$RUNNER_TEMP/$report"; then + continue + fi + manifest="$RUNNER_TEMP/$report/release-artifacts/release-manifest.json" + cmp -s "$manifest" "$RUNNER_TEMP/release/release-manifest.json" || continue + python -m scripts.prepare_pypi_release --release-dir "$RUNNER_TEMP/release" \ + --accepted-manifest "$manifest" --output "$RUNNER_TEMP/pypi" --version "$VERSION" --tag-commit "$commit" + echo "release_version=$VERSION" >> "$GITHUB_OUTPUT" + echo "destination=$destination" >> "$GITHUB_OUTPUT" + exit 0 + done < "$RUNNER_TEMP/candidate-runs" + echo 'No matching accepted main candidate report. Check the original run, tag and manifest before retrying.' >&2 + exit 1 - name: Check for an interrupted upload id: reconcile env: @@ -130,26 +145,12 @@ jobs: timeout-minutes: 20 permissions: id-token: write - actions: read steps: - - name: Require a fresh run and verify PyPI approval - env: - GH_TOKEN: ${{ github.token }} - DESTINATION: ${{ needs.verify.outputs.destination }} - RELEASE_ACTOR: ${{ needs.verify.outputs.release_actor }} + - name: Require a fresh run shell: bash run: | - set -euo pipefail - # GitHub can reuse job outputs and the approval API is scoped to the run, not the attempt. + # Reruns can reuse previous staging outputs instead of reconciling the current index. [[ "$GITHUB_RUN_ATTEMPT" == 1 ]] || { echo 'To retry, start a new workflow run for the same version and destination.' >&2; exit 1; } - if [[ "$DESTINATION" == testpypi ]]; then - exit 0 - fi - [[ "$DESTINATION" == pypi ]] - gh api "repos/HKUDS/nanobot/actions/runs/$GITHUB_RUN_ID/approvals" | jq -e \ - --arg actor "$RELEASE_ACTOR" \ - 'any(.[]; .state == "approved" and ([.environments[]?.name] | index("pypi")) != null and (.user.login | ascii_downcase) != ($actor | ascii_downcase))' >/dev/null \ - || { echo 'A different maintainer must approve this release in the pypi environment.' >&2; exit 1; } - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: artifact-ids: ${{ needs.verify.outputs.artifact_id }} diff --git a/.github/workflows/trigger-pypi.yml b/.github/workflows/trigger-pypi.yml index 35b484aee..24500b761 100644 --- a/.github/workflows/trigger-pypi.yml +++ b/.github/workflows/trigger-pypi.yml @@ -2,7 +2,7 @@ name: Validate published release for PyPI on: release: - types: [released] + types: [published] permissions: {} @@ -19,4 +19,4 @@ jobs: run: | set -euo pipefail [[ "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo 'Expected a final vX.Y.Z tag.' >&2; exit 1; } - echo 'The protected main-branch publisher will check this release and request approval.' >> "$GITHUB_STEP_SUMMARY" + echo 'The main-branch publisher will match the release to its accepted candidate before uploading.' >> "$GITHUB_STEP_SUMMARY" diff --git a/docs/releasing.md b/docs/releasing.md index 6bde7d83b..d1ca78dd3 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -127,7 +127,20 @@ Final releases also require `release-manifest.json` for `stable`. Run `scripts.r For same-build candidate acceptance on all five native targets, run **Verify Release Candidate** at the exact final-version ref with `channel=stable`, `next_stable` equal to that declared version and `retain_installable=true`. Stable preparation copies the exact commit without changing version declarations or creating a Preview commit; it rejects mismatched versions and existing stable tags. The default `channel=preview` retains the version-only Preview preparation. Both modes are read-only preparation, require **Candidate required** and retain accepted files for one day; neither publishes a tag, release, PyPI package or feed. Download and independently preserve the accepted handoff before expiry, then complete remaining interactive and real historical-owner acceptance against that same manifest. -## Publish, with maintainer approval +## Publish a stable package + +One maintainer publishes the GitHub Release. GitHub Actions verifies and uploads the accepted distributions to PyPI via Trusted Publishing. Publishing installable packages does not enable application-managed updates. + +1. Complete candidate acceptance on `main`. Preserve the original files and their manifest, and use the accepted commit for `vX.Y.Z`. Never move or reuse a published tag. +2. Create a draft with the five platform wheels, sdist, five TUI archives, their checksums and the original `release-manifest.json`. Use the artifact set that passed acceptance, without rebuilding any files under that release identity. If using **Publish Terminal UI** to rebuild, assemble new matching wheels and manifests and repeat candidate acceptance before publishing. +3. Click **Publish release**. A stable publication starts **Validate published release for PyPI**, which starts **Publish accepted release to PyPI** on `main`. The publisher requires a matching CI manifest from a successful **Verify Release Candidate** run and a successful **Candidate required** job for that same attempt. It checks the tag, all public artifacts and the package index, then uploads only the five wheels and sdist. Prereleases and tag pushes alone do not publish Python packages. +4. Verify clean installation from public PyPI, bundled WebUI and download-free TUI startup. Add the dated [Release Archive](./release-archive.md) entry and record the publication result. Only after GitHub and PyPI assets are public and verified should the wiki PR be merged; check affected localized routes. An update catalogue change is separate and requires the signature described below. + +### Configure Trusted Publishing + +Protect `main` and the publication workflows. In the `nanobot-ai` PyPI project's **Publishing** settings, bind `HKUDS/nanobot`, `publish-pypi.yml` and the `pypi` environment. Keep that GitHub environment restricted to `main`; the single-click path does not require an environment reviewer. During rollout, verify the publishing path with a separately configured TestPyPI trusted publisher (the same repository and workflow, environment `testpypi`) before removing a production reviewer requirement. Production does not use a long-lived token. The separate `release-approval` environment retains independent review. + +To rehearse or resume, use **Run workflow** on `main` with the already-published version and destination `testpypi` or `pypi`. If the human GitHub publication did not dispatch the upload, use the same manual workflow entry point. Use a new run, not **Re-run jobs**: a new run checks the index and uploads only missing files. If the original CI report has expired, automatic publication stops. Preserve the accepted bytes and their verification record; use the existing manual upload route for those same verified files when necessary. Never replace a published file or move its tag. ### Release approval proof @@ -149,20 +162,7 @@ Review resolved dependencies; hashes are not malware review. Before the first re The proof authenticates release approval, not reproducible builds or harmless code. Compromised authorized workflows/reviewers, malicious source that passes review and compromised runtime dependencies remain risks. The signing lock does not lock runtime resolution, which retains the installation owner's policy. A reviewed runtime dependency inventory, public signed upgrade continuity and verified repository protection settings remain security-release gates; do not claim comprehensive supply-chain protection without them. The first installer and checksum source also need a trusted distribution channel. -1. Complete pre-tag gates, then create and push exactly `vX.Y.Z`; never move or reuse a published tag. -2. Create the matching GitHub Release as a draft. A tag push alone runs neither **Publish Terminal UI** nor PyPI publication. -3. Attach five platform wheels, sdist, five TUI archives, their `.sha256` files, `release-manifest.json` and its approval proof. Confirm tag sources match the manifest and uploaded hashes match preflight; never upload a naked executable. -4. If rebuilding via **Publish Terminal UI**, use `tag=vX.Y.Z` with compliance review confirmed. Wait for all five targets, recheck outputs, and assemble/recheck wheels and manifest from those exact archives. Never mix rebuilt archives with old wheel bytes/hashes; replacing public assets requires a new version. -5. Click **Publish release** only after the complete signed artifact set is attached. A final `vX.Y.Z` release starts **Validate published release for PyPI**; its successful completion triggers the protected **Publish approved release to PyPI** workflow on `main`. A prerelease or tag push does not start publication. -6. A different maintainer must approve the `pypi` environment; check both Actions runs for success. The publisher verifies the signed manifest, tag identity and all public release files, then uploads only the matching sdist and five wheels. It does not build packages. If the trigger did not run, including when a release was created using `GITHUB_TOKEN`, or the release actor was a bot, a human maintainer must manually run **Publish approved release to PyPI** from `main` with the version and `pypi` destination. Until signing is enabled, an authorized maintainer can use the existing manual upload route for the same checked files; unsigned releases cannot be offered through the automatic updater. Platform-wheel TUI startup must not need downloads. -7. Verify clean PyPI installation, bundled WebUI and download-free TUI startup. After all public GitHub/PyPI files pass, advance `stable`, preserving Preview and withdrawals; check discovery for both subscriptions. Only then merge the wiki PR: its `main` deploys automatically. Confirm all localized `/docs/latest/` routes select the new version and old-version links still work. -8. Add the dated [Release Archive](./release-archive.md) entry and record publication links/status. Feature releases can include a separate announcement; ordinary patches can use the generated notes with necessary additions. Complete any coordinated advisory and reporter notifications separately. - -### Configure trusted publishing - -An administrator must protect the `pypi` GitHub environment so only `main` can deploy. Require a second maintainer, prevent self-review, and disable administrator bypass. Protect changes to `main` and both publication workflows. Keep independent review on the separate release-approval workflow. The publisher checks the original Release actor from GitHub's workflow event; an approval by that actor is rejected. In the `nanobot-ai` PyPI project's **Publishing** settings, add a GitHub trusted publisher for owner `HKUDS`, repository `nanobot`, workflow `publish-pypi.yml` and environment `pypi`. These names must match exactly. No long-lived PyPI token is needed by the workflow. Before using the production workflow, test the default `testpypi` destination with a separately registered `nanobot-ai` TestPyPI project and its own trusted publisher using environment `testpypi`; protect that environment in GitHub too. TestPyPI registration does not grant production access. The test still requires a complete signed public release of an unused TestPyPI version. - -If an upload only partially succeeds, preserve the original approved bytes. Choose **Run workflow** from `main` with the same version and destination to start a new run. Do not use **Re-run jobs**: GitHub can reuse outputs from an earlier attempt, and review history is scoped to the whole run. The new run compares existing index files with the signed release and uploads only missing files. A production run that uploads files needs a new independent approval. A mismatch, yanked file, unexpected file or unavailable index stops the run for investigation. Published versions cannot be replaced; do not rebuild or upload a different file under the same version. The approval proof and verification cannot establish historical upgrade or interactive acceptance, which remain separate release gates. +Only after the signature, matching public release files and applicable public update checks are verified may the maintainer advance `stable` or `preview`. Preserve the other channel and withdrawals, and check discovery for both subscriptions. A package published without this proof remains available for manual installation, not application-managed updates. ## If a gate fails diff --git a/scripts/prepare_pypi_release.py b/scripts/prepare_pypi_release.py index 841561296..b6ab1c1aa 100644 --- a/scripts/prepare_pypi_release.py +++ b/scripts/prepare_pypi_release.py @@ -1,4 +1,4 @@ -"""Stage only the publicly available files covered by an approved release manifest.""" +"""Stage published PyPI packages only when they match the accepted CI manifest.""" from __future__ import annotations @@ -8,23 +8,21 @@ import re import shutil from pathlib import Path -from nanobot.release_trust import verify_release_approval from nanobot.releases import ReleaseManifest -def stage_release(release_dir: Path, output: Path, *, version: str, tag_commit: str) -> None: +def stage_release(release_dir: Path, output: Path, *, accepted_manifest: Path, version: str, tag_commit: str) -> None: if not re.fullmatch(r"\d+\.\d+\.\d+", version): raise ValueError("Only final stable versions may be published to PyPI") manifest_path = release_dir / "release-manifest.json" - proof_path = release_dir / "release-manifest.json.sigstore.json" - for path, limit in ((manifest_path, 64 * 1024), (proof_path, 256 * 1024)): - if path.is_symlink() or not path.is_file() or path.stat().st_size > limit: - raise ValueError(f"Missing or invalid approval file: {path.name}") - payload, proof = manifest_path.read_bytes(), proof_path.read_bytes() - verify_release_approval(payload, proof) + if manifest_path.is_symlink() or not manifest_path.is_file() or manifest_path.stat().st_size > 64 * 1024: + raise ValueError("Missing or invalid release manifest") + payload = manifest_path.read_bytes() + if payload != accepted_manifest.read_bytes(): + raise ValueError("Public release manifest differs from the accepted CI manifest") manifest = ReleaseManifest.model_validate_json(payload) - if manifest.version != version or manifest.candidate_commit != tag_commit: - raise ValueError("Signed release identity does not match the version and tag") + if manifest.version != version or manifest.source_commit != tag_commit or manifest.candidate_commit != tag_commit: + raise ValueError("Accepted stable release identity does not match the version and tag") for item in manifest.artifacts: path = release_dir / item.filename @@ -39,17 +37,19 @@ def stage_release(release_dir: Path, output: Path, *, version: str, tag_commit: for item in manifest.artifacts: if item.filename.endswith((".whl", ".tar.gz")): shutil.copyfile(release_dir / item.filename, output / item.filename) - print(f"Staged signed release {version}: five wheels and one source distribution") + print(f"Staged accepted release {version}: five wheels and one source distribution") def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--release-dir", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--accepted-manifest", type=Path, required=True) parser.add_argument("--version", required=True) parser.add_argument("--tag-commit", required=True) args = parser.parse_args() - stage_release(args.release_dir, args.output, version=args.version, tag_commit=args.tag_commit) + stage_release(args.release_dir, args.output, accepted_manifest=args.accepted_manifest, + version=args.version, tag_commit=args.tag_commit) if __name__ == "__main__": diff --git a/tests/scripts/test_pypi_release_trigger.py b/tests/scripts/test_pypi_release_trigger.py index 30d37b27b..e3a6be5a3 100644 --- a/tests/scripts/test_pypi_release_trigger.py +++ b/tests/scripts/test_pypi_release_trigger.py @@ -1,4 +1,3 @@ -import json import os import subprocess from pathlib import Path @@ -22,33 +21,49 @@ def shell_env(tmp_path): bin_dir.mkdir() gh = bin_dir / "gh" gh.write_text( - "#!/usr/bin/env python3\n" - "import json, os, sys\n" - "args = sys.argv[1:]\n" - "if args[:2] == ['release', 'view']:\n" - " print(json.dumps({'tagName': 'v1.2.3', 'isDraft': False, 'isPrerelease': False}))\n" - "elif args[:2] == ['release', 'download']:\n" - " pass\n" - "elif args[0] == 'api':\n" - " print(open(os.environ['MOCK_APPROVALS']).read())\n" - "else:\n" - " sys.exit(2)\n" + """#!/usr/bin/env python3 +import os +import sys +from pathlib import Path + +args = sys.argv[1:] +if args[:2] == ["release", "view"]: + print(os.environ["PUBLIC_RELEASE"]) +elif args[:2] == ["release", "download"]: + path = Path(args[args.index("--dir") + 1]) + path.mkdir() + (path / "release-manifest.json").write_text("public manifest") +elif args[0] == "api" and "repos/HKUDS/nanobot/actions/workflows/release-candidate.yml/runs" in args: + print(os.environ["CANDIDATE_RUNS"]) +elif args[0] == "api" and args[1].startswith("repos/HKUDS/nanobot/actions/runs/"): + parts = args[1].split("/") + print("true" if f"{parts[5]}/{parts[7]}" in os.environ["ACCEPTED_ATTEMPTS"].split() else "false") +elif args[:2] == ["run", "download"]: + run = args[2] + if run == os.environ.get("EXPIRED_RUN"): + sys.exit(1) + manifest = Path(args[args.index("--dir") + 1]) / "release-artifacts/release-manifest.json" + manifest.parent.mkdir(parents=True) + manifest.write_text("public manifest" if run == os.environ["MATCHING_RUN"] else "other manifest") +else: + sys.exit(2) +""" ) gh.chmod(0o755) git = bin_dir / "git" git.write_text(f"#!/bin/bash\n[[ $1 != rev-parse ]] || echo {COMMIT}\n") git.chmod(0o755) python = bin_dir / "python" - python.write_text("#!/bin/bash\nexit 0\n") + python.write_text('#!/bin/bash\nprintf "%s\\n" "$@" > "$RUNNER_TEMP/staged"\n') python.chmod(0o755) return { - "PATH": f"{bin_dir}:{os.environ.get('PATH', '/usr/bin:/bin')}", "HOME": str(tmp_path), "GH_TOKEN": "test", - "GITHUB_RUN_ID": "987", "GITHUB_RUN_ATTEMPT": "1", "RUNNER_TEMP": str(tmp_path), + "PATH": f"{bin_dir}:{os.environ.get('PATH', '/usr/bin:/bin')}", + "GITHUB_RUN_ATTEMPT": "1", "RUNNER_TEMP": str(tmp_path), "GITHUB_OUTPUT": str(tmp_path / "outputs"), "GITHUB_STEP_SUMMARY": str(tmp_path / "summary"), - "MOCK_APPROVALS": str(tmp_path / "approvals.json"), "GITHUB_EVENT_NAME": "workflow_run", "UPSTREAM_TAG": "v1.2.3", "UPSTREAM_SHA": COMMIT, - "UPSTREAM_ACTOR": "publisher", "VERSION_INPUT": "", "DESTINATION_INPUT": "", - "GITHUB_ACTOR": "github-actions[bot]", + "VERSION_INPUT": "", "DESTINATION_INPUT": "", + "PUBLIC_RELEASE": '{"tagName":"v1.2.3","isDraft":false,"isPrerelease":false}', + "CANDIDATE_RUNS": "101\t7\t1\n102\t8\t2", "ACCEPTED_ATTEMPTS": "102/2", "MATCHING_RUN": "102", } @@ -65,87 +80,54 @@ def publish_gate(): return workflow("publish-pypi.yml")["jobs"]["publish"]["steps"][0] -def test_only_stable_release_completion_can_start_the_main_publisher(shell_env): +def test_publishing_a_stable_release_stages_the_accepted_files(shell_env): trigger = workflow("trigger-pypi.yml") - assert trigger["on"]["release"]["types"] == ["released"] + assert trigger["on"]["release"]["types"] == ["published"] job = trigger["jobs"]["release"] assert "!github.event.release.prerelease" in job["if"] assert trigger["permissions"] == {} - result = run(job["steps"][0], {**shell_env, "RELEASE_TAG": "v1.2.3"}) - assert result.returncode == 0, result.stderr + assert run(job["steps"][0], {**shell_env, "RELEASE_TAG": "v1.2.3"}).returncode == 0 publisher = workflow("publish-pypi.yml") assert publisher["on"]["workflow_run"]["workflows"] == ["Validate published release for PyPI"] - assert publisher["on"]["workflow_run"]["types"] == ["completed"] - assert "github.event.workflow_run.head_branch" in publisher["concurrency"]["group"] - assert "format('v{0}', inputs.version)" in publisher["concurrency"]["group"] guard = publisher["jobs"]["verify"]["if"] assert all(value in guard for value in ("refs/heads/main", "conclusion == 'success'", "event == 'release'", - ".github/workflows/trigger-pypi.yml")) + "head_repository.full_name", ".github/workflows/trigger-pypi.yml")) + result = run(release_step(), shell_env) + assert result.returncode == 0, result.stderr + assert set(Path(shell_env["GITHUB_OUTPUT"]).read_text().splitlines()) == { + "release_version=1.2.3", "destination=pypi" + } + staged = (Path(shell_env["RUNNER_TEMP"]) / "staged").read_text() + assert "candidate-report-8-2/release-artifacts/release-manifest.json" in staged + assert run(publish_gate(), shell_env).returncode == 0 -@pytest.mark.parametrize("tag", ["v1.2.3-rc1", "v1.2.3;echo BAD", "1.2.3"]) +@pytest.mark.parametrize("tag", ["v1.2.3-rc1", "1.2.3"]) def test_invalid_release_tag_fails_before_publisher(shell_env, tag): step = workflow("trigger-pypi.yml")["jobs"]["release"]["steps"][0] assert run(step, {**shell_env, "RELEASE_TAG": tag}).returncode != 0 -def test_release_origin_preserves_tag_and_original_actor(shell_env): - result = run(release_step(), shell_env) - assert result.returncode == 0, result.stderr - assert set(Path(shell_env["GITHUB_OUTPUT"]).read_text().splitlines()) == { - "release_actor=publisher", "release_version=1.2.3", "destination=pypi" - } - - -def test_simulated_release_reaches_independently_approved_publisher(shell_env): - trigger = workflow("trigger-pypi.yml")["jobs"]["release"]["steps"][0] - assert run(trigger, {**shell_env, "RELEASE_TAG": "v1.2.3"}).returncode == 0 - assert run(release_step(), shell_env).returncode == 0 - outputs = dict(line.split("=", 1) for line in Path(shell_env["GITHUB_OUTPUT"]).read_text().splitlines()) - assert outputs["release_version"] == "1.2.3" and outputs["destination"] == "pypi" - Path(shell_env["MOCK_APPROVALS"]).write_text(json.dumps([ - {"state": "approved", "user": {"login": "reviewer"}, "environments": [{"name": "pypi"}]} - ])) - assert run(publish_gate(), {**shell_env, "DESTINATION": "pypi", - "RELEASE_ACTOR": outputs["release_actor"]}).returncode == 0 - - -@pytest.mark.parametrize("change", [{"UPSTREAM_SHA": "b" * 40}, {"UPSTREAM_TAG": "v1.2.3-rc1"}, - {"UPSTREAM_ACTOR": "bad\nactor"}, {"UPSTREAM_ACTOR": "publisher[bot]"}]) -def test_release_origin_rejects_changed_tag_or_invalid_actor(shell_env, change): - assert run(release_step(), {**shell_env, **change}).returncode != 0 - - -def test_manual_testpypi_run_uses_its_real_actor_not_upstream_input(shell_env): - result = run(release_step(), {**shell_env, "GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_ACTOR": "maintainer", - "VERSION_INPUT": "1.2.3", "DESTINATION_INPUT": "testpypi"}) - assert result.returncode == 0, result.stderr - assert set(Path(shell_env["GITHUB_OUTPUT"]).read_text().splitlines()) == { - "release_actor=maintainer", "release_version=1.2.3", "destination=testpypi" - } - - -@pytest.mark.parametrize(("reviewer", "environment", "state", "allowed"), [ - ("reviewer", "pypi", "approved", True), - ("publisher", "pypi", "approved", False), - ("PUBLISHER", "pypi", "approved", False), - ("reviewer", "testpypi", "approved", False), - ("reviewer", "pypi", "rejected", False), +@pytest.mark.parametrize("change", [ + {"UPSTREAM_SHA": "b" * 40}, + {"PUBLIC_RELEASE": '{"tagName":"v1.2.3","isDraft":true,"isPrerelease":false}'}, + {"ACCEPTED_ATTEMPTS": "101/1 102/1"}, + {"EXPIRED_RUN": "102"}, ]) -def test_production_approval_must_be_independent(shell_env, reviewer, environment, state, allowed): - payload = [{"state": state, "user": {"login": reviewer}, "environments": [{"name": environment}]}] - Path(shell_env["MOCK_APPROVALS"]).write_text(json.dumps(payload)) - result = run(publish_gate(), {**shell_env, "DESTINATION": "pypi", "RELEASE_ACTOR": "publisher"}) - assert (result.returncode == 0) == allowed +def test_changed_release_or_unaccepted_manifest_never_stages(shell_env, change): + assert run(release_step(), {**shell_env, **change}).returncode != 0 + assert not (Path(shell_env["RUNNER_TEMP"]) / "staged").exists() -@pytest.mark.parametrize("destination", ["pypi", "testpypi"]) -def test_rerun_cannot_use_prior_approval_or_staged_files(shell_env, destination): - if destination == "pypi": - Path(shell_env["MOCK_APPROVALS"]).write_text(json.dumps([ - {"state": "approved", "user": {"login": "reviewer"}, "environments": [{"name": "pypi"}]} - ])) - env = {**shell_env, "DESTINATION": destination, "RELEASE_ACTOR": "publisher"} - assert run(publish_gate(), env).returncode == 0 - result = run(publish_gate(), {**env, "GITHUB_RUN_ATTEMPT": "2"}) +def test_manual_testpypi_checks_the_same_public_release(shell_env): + env = {**shell_env, "GITHUB_EVENT_NAME": "workflow_dispatch", "VERSION_INPUT": "1.2.3", + "DESTINATION_INPUT": "testpypi", "ACCEPTED_ATTEMPTS": "101/1 102/2"} + result = run(release_step(), env) + assert result.returncode == 0, result.stderr + assert "destination=testpypi" in Path(shell_env["GITHUB_OUTPUT"]).read_text() + assert "candidate-report-8-2" in (Path(shell_env["RUNNER_TEMP"]) / "staged").read_text() + + +def test_rerun_cannot_reuse_staged_files(shell_env): + result = run(publish_gate(), {**shell_env, "GITHUB_RUN_ATTEMPT": "2"}) assert result.returncode != 0 and "start a new workflow run" in result.stderr diff --git a/tests/test_prepare_pypi_release.py b/tests/test_prepare_pypi_release.py index 69f7804a6..4508d7d88 100644 --- a/tests/test_prepare_pypi_release.py +++ b/tests/test_prepare_pypi_release.py @@ -7,7 +7,7 @@ from scripts import prepare_pypi_release @pytest.fixture -def approved_release(tmp_path, monkeypatch): +def accepted_release(tmp_path): source = tmp_path / "release" source.mkdir() artifacts = [] @@ -15,26 +15,27 @@ def approved_release(tmp_path, monkeypatch): data = filename.encode() (source / filename).write_bytes(data) artifacts.append(ReleaseArtifact(filename=filename, size=len(data), sha256=hashlib.sha256(data).hexdigest())) - manifest = ReleaseManifest(version="1.2.3", source_commit="a" * 40, candidate_commit="b" * 40, + manifest = ReleaseManifest(version="1.2.3", source_commit="b" * 40, candidate_commit="b" * 40, requires_python=">=3.11", artifacts=artifacts) - (source / "release-manifest.json").write_text(manifest.model_dump_json()) - (source / "release-manifest.json.sigstore.json").write_bytes(b"proof") - monkeypatch.setattr(prepare_pypi_release, "verify_release_approval", lambda payload, proof: None) - return source, tmp_path / "output" + payload = manifest.model_dump_json() + (source / "release-manifest.json").write_text(payload) + accepted = tmp_path / "accepted-manifest.json" + accepted.write_text(payload) + return source, tmp_path / "output", accepted -def test_stages_only_matching_pypi_distributions(approved_release): - source, output = approved_release - prepare_pypi_release.stage_release(source, output, version="1.2.3", tag_commit="b" * 40) +def test_stages_only_matching_pypi_distributions(accepted_release): + source, output, accepted = accepted_release + prepare_pypi_release.stage_release(source, output, accepted_manifest=accepted, version="1.2.3", tag_commit="b" * 40) assert {path.name for path in output.iterdir()} == { name for name in release_filenames("1.2.3") if name.endswith((".whl", ".tar.gz")) } assert all(path.read_bytes() == (source / path.name).read_bytes() for path in output.iterdir()) -@pytest.mark.parametrize("failure", ["changed", "missing_archive", "wrong_tag", "invalid_signature", "preview"]) -def test_refuses_unapproved_or_incomplete_release(approved_release, monkeypatch, failure): - source, output = approved_release +@pytest.mark.parametrize("failure", ["changed", "missing_archive", "wrong_tag", "different_manifest", "preview"]) +def test_refuses_unaccepted_or_incomplete_release(accepted_release, failure): + source, output, accepted = accepted_release version, commit = "1.2.3", "b" * 40 archive = next(source.glob("nanobot-tui-*.zip")) if failure == "changed": @@ -44,12 +45,10 @@ def test_refuses_unapproved_or_incomplete_release(approved_release, monkeypatch, archive.unlink() elif failure == "wrong_tag": commit = "c" * 40 - elif failure == "invalid_signature": - def reject(payload, proof): - raise ValueError("invalid signature") - monkeypatch.setattr(prepare_pypi_release, "verify_release_approval", reject) + elif failure == "different_manifest": + (source / "release-manifest.json").write_bytes(accepted.read_bytes() + b"\n") else: version = "1.2.3.dev1" with pytest.raises(ValueError): - prepare_pypi_release.stage_release(source, output, version=version, tag_commit=commit) + prepare_pypi_release.stage_release(source, output, accepted_manifest=accepted, version=version, tag_commit=commit) assert not output.exists()