From 96c48c96bf02f606db4dc063786aea8e92a98543 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:54:23 +0800 Subject: [PATCH] Add trusted PyPI publishing for approved releases (#6642) Co-authored-by: chengyongru --- .github/workflows/publish-pypi.yml | 172 +++++++++++++++++++++ .github/workflows/trigger-pypi.yml | 22 +++ docs/releasing.md | 16 +- scripts/prepare_pypi_release.py | 56 +++++++ scripts/reconcile_pypi_release.py | 68 ++++++++ tests/scripts/test_pypi_release_trigger.py | 151 ++++++++++++++++++ tests/test_prepare_pypi_release.py | 55 +++++++ tests/test_reconcile_pypi_release.py | 87 +++++++++++ webui/browser/composer-action.spec.ts | 35 +++-- 9 files changed, 646 insertions(+), 16 deletions(-) create mode 100644 .github/workflows/publish-pypi.yml create mode 100644 .github/workflows/trigger-pypi.yml create mode 100644 scripts/prepare_pypi_release.py create mode 100644 scripts/reconcile_pypi_release.py create mode 100644 tests/scripts/test_pypi_release_trigger.py create mode 100644 tests/test_prepare_pypi_release.py create mode 100644 tests/test_reconcile_pypi_release.py diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml new file mode 100644 index 000000000..1fb5eb0a2 --- /dev/null +++ b/.github/workflows/publish-pypi.yml @@ -0,0 +1,172 @@ +name: Publish approved release to PyPI + +on: + workflow_run: + workflows: [Validate published release for PyPI] + types: [completed] + workflow_dispatch: + inputs: + version: + description: Published, signed stable release version (without v) + required: true + type: string + destination: + description: Package index + required: true + type: choice + default: testpypi + options: + - testpypi + - pypi + +permissions: {} + +concurrency: + group: publish-pypi-${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_branch || format('v{0}', inputs.version) }} + cancel-in-progress: false + +jobs: + verify: + if: >- + github.repository == 'HKUDS/nanobot' && github.ref == 'refs/heads/main' && + (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.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 + 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: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: '3.11' + - 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 + id: release + env: + GH_TOKEN: ${{ github.token }} + VERSION_INPUT: ${{ inputs.version }} + 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 + if [[ "$GITHUB_EVENT_NAME" == workflow_run ]]; then + [[ "$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 + git fetch --no-tags origin "refs/tags/$tag:refs/tags/$tag" + commit="$(git rev-parse "refs/tags/$tag^{commit}")" + 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 '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" + - name: Check for an interrupted upload + id: reconcile + env: + VERSION: ${{ steps.release.outputs.release_version }} + DESTINATION: ${{ steps.release.outputs.destination }} + shell: bash + run: | + set -euo pipefail + python -m scripts.reconcile_pypi_release --directory "$RUNNER_TEMP/pypi" \ + --version "$VERSION" --destination "$DESTINATION" + if [[ -n "$(find "$RUNNER_TEMP/pypi" -type f -print -quit)" ]]; then + echo 'upload_required=true' >> "$GITHUB_OUTPUT" + else + echo 'upload_required=false' >> "$GITHUB_OUTPUT" + echo 'The complete release is already present with matching hashes.' + fi + - name: Transfer verified PyPI files + if: steps.reconcile.outputs.upload_required == 'true' + id: staged + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: verified-pypi-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/pypi/* + if-no-files-found: error + retention-days: 1 + + publish: + needs: verify + if: needs.verify.outputs.upload_required == 'true' + runs-on: ubuntu-latest + environment: ${{ needs.verify.outputs.destination }} + 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 }} + shell: bash + run: | + set -euo pipefail + # GitHub can reuse job outputs and the approval API is scoped to the run, not the attempt. + [[ "$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 }} + path: dist + merge-multiple: true + - name: Publish with PyPI Trusted Publishing + if: needs.verify.outputs.destination == 'pypi' + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1 + - name: Publish to TestPyPI + if: needs.verify.outputs.destination == 'testpypi' + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1 + with: + repository-url: https://test.pypi.org/legacy/ + - name: Show safe retry instructions + if: failure() + shell: bash + run: | + message='To resume, use "Run workflow" on main with the same version and destination. Do not rerun the old run. Preserve the original approved release files.' + echo "::notice title=Retry the complete publication workflow::$message" + printf '### Resume publication\n\n%s\n' "$message" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/trigger-pypi.yml b/.github/workflows/trigger-pypi.yml new file mode 100644 index 000000000..35b484aee --- /dev/null +++ b/.github/workflows/trigger-pypi.yml @@ -0,0 +1,22 @@ +name: Validate published release for PyPI + +on: + release: + types: [released] + +permissions: {} + +jobs: + release: + if: github.repository == 'HKUDS/nanobot' && !github.event.release.prerelease + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Validate the stable release tag + env: + RELEASE_TAG: ${{ github.event.release.tag_name }} + shell: bash + 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" diff --git a/docs/releasing.md b/docs/releasing.md index e0ad67ca0..6bde7d83b 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -14,7 +14,7 @@ Stable is the default feed; Preview is opt-in. Both use one update flow and requ These are three publication lines, not three build systems. Feature and patch releases both use `channel=stable`; dev uses the existing `preview` channel. A patch does not require a Preview first or a complete wiki and promotional refresh. Preserve necessary tests and release checks, and reuse unaffected evidence under the [verification guidance](../.agent/workflow.md). -Implementation status: **Verify Release Candidate** supports manual preparation and opt-in daily Preview preparation. It generates draft notes and reuses the same five-platform build and acceptance jobs. It does not publish. Automatic prerelease upload, signing handoff and catalogue advancement are not connected yet; PyPI publication remains manual. Daily preparation is disabled by default. Do not describe this first step as an available daily public release channel. +Implementation status: **Verify Release Candidate** supports manual preparation and opt-in daily Preview preparation. It generates draft notes and reuses the same five-platform build and acceptance jobs. It does not publish. Automatic prerelease upload, signing handoff and catalogue advancement are not connected yet; PyPI publication requires a separate manual workflow after its trusted publisher is configured. Daily preparation is disabled by default. Do not describe this first step as an available daily public release channel. Record the requested channel, exact source and candidate identity. Unchanged source, failed checks, missing assets, incomplete acceptance or absent approval leaves the last verified release in place. Scheduled execution can be delayed; there is no promise of a new release every day. Acceptance must cover the supported stable baseline and an earlier Preview, including skipped previews, not just the previous build. @@ -150,14 +150,20 @@ 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. A tag push alone runs neither **Publish Terminal UI** nor PyPI publication. -3. Attach five platform wheels, sdist, five TUI archives, their `.sha256` files and `release-manifest.json`. Confirm tag sources match the manifest and uploaded hashes match preflight. Complete approval proof before offering automatic updates; never upload a naked executable. +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. Make the release and complete artifact set public. Verify every file against the accepted manifest, including native fallback/source-install archives. Platform-wheel TUI startup must not need downloads. -6. Upload only the checked `nanobot_ai-X.Y.Z.tar.gz` and five final wheels to PyPI, not the universal intermediate or stale shared `dist/` files. There is no automatic PyPI publication workflow. +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. + ## If a gate fails Do not publish to PyPI with missing TUI artifacts or verification. Keep public documentation's `latest` on the usable stable version. Correct published packages with a new version, never replacement code behind an existing tag. Before downgrading a migrated installation, stop all old processes and follow the documented session rollback procedure. diff --git a/scripts/prepare_pypi_release.py b/scripts/prepare_pypi_release.py new file mode 100644 index 000000000..841561296 --- /dev/null +++ b/scripts/prepare_pypi_release.py @@ -0,0 +1,56 @@ +"""Stage only the publicly available files covered by an approved release manifest.""" + +from __future__ import annotations + +import argparse +import hashlib +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: + 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) + 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") + + for item in manifest.artifacts: + path = release_dir / item.filename + if path.is_symlink() or not path.is_file() or path.stat().st_size != item.size: + raise ValueError(f"Missing or changed release file: {item.filename}") + with path.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + if digest != item.sha256: + raise ValueError(f"Release checksum mismatch: {item.filename}") + + output.mkdir(parents=True, exist_ok=False) + 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") + + +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("--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) + + +if __name__ == "__main__": + main() diff --git a/scripts/reconcile_pypi_release.py b/scripts/reconcile_pypi_release.py new file mode 100644 index 000000000..805035a47 --- /dev/null +++ b/scripts/reconcile_pypi_release.py @@ -0,0 +1,68 @@ +"""Resume a partial index upload only when existing files match staged bytes.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import re +from pathlib import Path +from urllib.error import HTTPError +from urllib.request import urlopen + +from nanobot.releases import PLATFORMS + +INDEXES = {"pypi": "https://pypi.org", "testpypi": "https://test.pypi.org"} + + +def remove_uploaded_files(directory: Path, *, version: str, destination: str) -> int: + """Check the complete remote release before removing any identical local files.""" + if not re.fullmatch(r"\d+\.\d+\.\d+", version) or destination not in INDEXES: + raise ValueError("Expected a final stable version and supported package index") + expected = {f"nanobot_ai-{version}-py3-none-{platform}.whl" for platform in PLATFORMS.values()} + expected.add(f"nanobot_ai-{version}.tar.gz") + if {item.name for item in directory.iterdir()} != expected: + raise ValueError("Staged files do not match the complete release") + url = f"{INDEXES[destination]}/pypi/nanobot-ai/{version}/json" + try: + with urlopen(url, timeout=30) as response: + payload = response.read(4 * 1024 * 1024 + 1) + except HTTPError as exc: + if exc.code == 404: + return len(expected) + raise + if len(payload) > 4 * 1024 * 1024: + raise ValueError("Package index response is too large") + data = json.loads(payload) + if data["info"]["name"] != "nanobot-ai" or data["info"]["version"] != version: + raise ValueError("Package index returned a different project or version") + uploaded: set[str] = set() + for entry in data["urls"]: + name = entry["filename"] + if name not in expected or name in uploaded or entry.get("yanked"): + raise ValueError("Package index contains an unexpected, duplicate or yanked file") + path = directory / name + if path.is_symlink() or not path.is_file() or entry["size"] != path.stat().st_size: + raise ValueError(f"Published file differs from the staged release: {name}") + with path.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + if entry["digests"]["sha256"] != digest: + raise ValueError(f"Published file differs from the staged release: {name}") + uploaded.add(name) + for name in uploaded: + (directory / name).unlink() + return len(expected) - len(uploaded) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--directory", type=Path, required=True) + parser.add_argument("--version", required=True) + parser.add_argument("--destination", choices=INDEXES, required=True) + args = parser.parse_args() + remaining = remove_uploaded_files(args.directory, version=args.version, destination=args.destination) + print(f"Files remaining to upload: {remaining}") + + +if __name__ == "__main__": + main() diff --git a/tests/scripts/test_pypi_release_trigger.py b/tests/scripts/test_pypi_release_trigger.py new file mode 100644 index 000000000..30d37b27b --- /dev/null +++ b/tests/scripts/test_pypi_release_trigger.py @@ -0,0 +1,151 @@ +import json +import os +import subprocess +from pathlib import Path + +import pytest +import yaml + +WORKFLOWS = Path(__file__).resolve().parents[2] / ".github/workflows" +COMMIT = "a" * 40 + + +def workflow(name): + return yaml.load((WORKFLOWS / name).read_text(encoding="utf-8"), Loader=yaml.BaseLoader) + + +@pytest.fixture +def shell_env(tmp_path): + if os.name == "nt": + pytest.skip("Release workflows run their Bash steps on Ubuntu") + bin_dir = tmp_path / "bin" + 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" + ) + 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.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), + "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]", + } + + +def run(step, env): + return subprocess.run(["bash", "-c", step["run"]], env=env, capture_output=True, text=True) + + +def release_step(): + return next(step for step in workflow("publish-pypi.yml")["jobs"]["verify"]["steps"] + if step.get("id") == "release") + + +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): + trigger = workflow("trigger-pypi.yml") + assert trigger["on"]["release"]["types"] == ["released"] + 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 + 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")) + + +@pytest.mark.parametrize("tag", ["v1.2.3-rc1", "v1.2.3;echo BAD", "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), +]) +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 + + +@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"}) + 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 new file mode 100644 index 000000000..69f7804a6 --- /dev/null +++ b/tests/test_prepare_pypi_release.py @@ -0,0 +1,55 @@ +import hashlib + +import pytest + +from nanobot.releases import ReleaseArtifact, ReleaseManifest, release_filenames +from scripts import prepare_pypi_release + + +@pytest.fixture +def approved_release(tmp_path, monkeypatch): + source = tmp_path / "release" + source.mkdir() + artifacts = [] + for filename in sorted(release_filenames("1.2.3")): + 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, + 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" + + +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) + 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 + version, commit = "1.2.3", "b" * 40 + archive = next(source.glob("nanobot-tui-*.zip")) + if failure == "changed": + data = archive.read_bytes() + archive.write_bytes(b"x" * len(data)) + elif failure == "missing_archive": + 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) + else: + version = "1.2.3.dev1" + with pytest.raises(ValueError): + prepare_pypi_release.stage_release(source, output, version=version, tag_commit=commit) + assert not output.exists() diff --git a/tests/test_reconcile_pypi_release.py b/tests/test_reconcile_pypi_release.py new file mode 100644 index 000000000..c94eb2d86 --- /dev/null +++ b/tests/test_reconcile_pypi_release.py @@ -0,0 +1,87 @@ +import hashlib +import json +from urllib.error import HTTPError + +import pytest + +from nanobot.releases import PLATFORMS +from scripts import reconcile_pypi_release as reconcile + + +@pytest.fixture +def staged(tmp_path): + names = {f"nanobot_ai-1.2.3-py3-none-{platform}.whl" for platform in PLATFORMS.values()} + names.add("nanobot_ai-1.2.3.tar.gz") + for name in names: + (tmp_path / name).write_bytes(name.encode()) + return tmp_path + + +def index_entry(path): + content = path.read_bytes() + return {"filename": path.name, "size": len(content), "yanked": False, + "digests": {"sha256": hashlib.sha256(content).hexdigest()}} + + +def serve(monkeypatch, entries): + payload = json.dumps({"info": {"name": "nanobot-ai", "version": "1.2.3"}, "urls": entries}).encode() + class Response: + def __enter__(self): + return self + + def __exit__(self, *args): + pass + + def read(self, size): + return payload[:size] + + monkeypatch.setattr(reconcile, "urlopen", lambda url, timeout: Response()) + + +def test_new_release_uploads_all_files(staged, monkeypatch): + def missing(url, timeout): + raise HTTPError(url, 404, "Not Found", {}, None) + monkeypatch.setattr(reconcile, "urlopen", missing) + assert reconcile.remove_uploaded_files(staged, version="1.2.3", destination="pypi") == 6 + assert len(list(staged.iterdir())) == 6 + + +def test_index_failure_never_becomes_a_new_release(staged, monkeypatch): + def unavailable(url, timeout): + raise HTTPError(url, 503, "Unavailable", {}, None) + monkeypatch.setattr(reconcile, "urlopen", unavailable) + with pytest.raises(HTTPError): + reconcile.remove_uploaded_files(staged, version="1.2.3", destination="pypi") + assert len(list(staged.iterdir())) == 6 + + +def test_retry_uploads_only_missing_files(staged, monkeypatch): + already_uploaded = sorted(staged.iterdir())[:2] + serve(monkeypatch, [index_entry(path) for path in already_uploaded]) + assert reconcile.remove_uploaded_files(staged, version="1.2.3", destination="testpypi") == 4 + assert all(not path.exists() for path in already_uploaded) + assert len(list(staged.iterdir())) == 4 + + +def test_complete_release_requires_no_upload(staged, monkeypatch): + serve(monkeypatch, [index_entry(path) for path in staged.iterdir()]) + assert reconcile.remove_uploaded_files(staged, version="1.2.3", destination="pypi") == 0 + assert not list(staged.iterdir()) + + +@pytest.mark.parametrize("change", ["digest", "unexpected", "yanked", "duplicate"]) +def test_refuses_inconsistent_index_without_removing_files(staged, monkeypatch, change): + paths = sorted(staged.iterdir()) + entries = [index_entry(path) for path in paths[:2]] + if change == "digest": + entries[1]["digests"]["sha256"] = "0" * 64 + elif change == "unexpected": + entries[1]["filename"] = "other.whl" + elif change == "yanked": + entries[1]["yanked"] = True + else: + entries[1] = entries[0] + serve(monkeypatch, entries) + with pytest.raises(ValueError): + reconcile.remove_uploaded_files(staged, version="1.2.3", destination="pypi") + assert len(list(staged.iterdir())) == 6 diff --git a/webui/browser/composer-action.spec.ts b/webui/browser/composer-action.spec.ts index 41a6d133f..bc67b6e1f 100644 --- a/webui/browser/composer-action.spec.ts +++ b/webui/browser/composer-action.spec.ts @@ -32,19 +32,32 @@ for (const width of [1280, 390]) { expect(bounds!.y + bounds!.height / 2).toBe(pillBounds!.y + pillBounds!.height / 2); const model = page.getByText("Preview", { exact: true }); const modelBounds = await model.boundingBox(); + const send = action.locator('[data-action-icon="send"]'); + await expect(send).toHaveCSS("opacity", "0"); + const capture = await send.evaluateHandle((icon) => { + // Sample the real transition at activation, before a test round trip can outlast it. + const sample = { opacity: 0 }; + const observer = new MutationObserver(() => { + if (!icon.hasAttribute("data-active")) return; + observer.disconnect(); + const fade = icon.getAnimations().find((animation) => animation instanceof CSSTransition + && animation.transitionProperty === "opacity"); + if (!fade || !fade.effect) return; + fade.pause(); + fade.currentTime = Number(fade.effect.getTiming().duration) / 2; + sample.opacity = Number(getComputedStyle(icon).opacity); + fade.play(); + }); + observer.observe(icon, { attributes: true, attributeFilter: ["data-active"] }); + return sample; + }); await input.fill("Please work"); await expect(action).toHaveAccessibleName("Send message"); - const samples = await action.evaluate((button) => new Promise((resolve) => { - const values: number[] = []; - const start = performance.now(); - const sample = () => { - values.push(Number(getComputedStyle(button.querySelector('[data-action-icon="send"]')!).opacity)); - if (performance.now() - start < 200) requestAnimationFrame(sample); - else resolve(values); - }; - requestAnimationFrame(sample); - })); - expect(samples.some((opacity) => opacity > 0 && opacity < 1)).toBe(true); + const { opacity } = await capture.jsonValue(); + await capture.dispose(); + expect(opacity).toBeGreaterThan(0); + expect(opacity).toBeLessThan(1); + await expect(send).toHaveCSS("opacity", "1"); expect(await action.boundingBox()).toEqual(bounds); expect(await model.boundingBox()).toEqual(modelBounds);