diff --git a/.github/workflows/release-tools.yml b/.github/workflows/release-tools.yml new file mode 100644 index 000000000..926493eb2 --- /dev/null +++ b/.github/workflows/release-tools.yml @@ -0,0 +1,32 @@ +name: Release tools + +on: + pull_request: + paths: + - '.github/workflows/release*.yml' + - 'script/release.py' + - 'script/sign-release.py' + - 'tests/release/**' + push: + branches: [master] + paths: + - '.github/workflows/release*.yml' + - 'script/release.py' + - 'script/sign-release.py' + - 'tests/release/**' + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install signing and verification tools + run: | + sudo apt-get update + sudo apt-get install -y gnupg rpm + command -v gpg rpm rpmkeys rpmbuild rpmsign + - name: Test inventory, release guards and real signing + run: python3 -m unittest discover -s tests/release -v diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 24f43102b..4aae35805 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -10,12 +10,15 @@ permissions: packages: write jobs: - build-and-release: + build-packages: + permissions: + contents: read strategy: fail-fast: false matrix: include: - - runner: ubuntu-latest + # Same Ubuntu release on both architectures, so both get the same fpm/rpmbuild toolchain. + - runner: ubuntu-24.04 goarch: amd64 - runner: ubuntu-24.04-arm goarch: arm64 @@ -46,22 +49,74 @@ jobs: export GOPATH="$(go env GOPATH)" ./build.sh -a "$GOARCH" - - name: Collect artifacts + - name: Collect and validate packages + env: + TAG_NAME: ${{ github.ref_name }} + GOARCH: ${{ matrix.goarch }} run: | - mkdir -p dist - shopt -s nullglob - cp /tmp/orchestrator-release/*.tar.gz dist/ 2>/dev/null || true - cp /tmp/orchestrator-release/*.deb dist/ 2>/dev/null || true - cp /tmp/orchestrator-release/*.rpm dist/ 2>/dev/null || true - ls -la dist/ - - - name: Upload release assets - uses: softprops/action-gh-release@v2 + mkdir dist + shopt -s failglob + cp /tmp/orchestrator-release/*.tar.gz /tmp/orchestrator-release/*.deb /tmp/orchestrator-release/*.rpm dist/ + python3 script/release.py check-packages "$TAG_NAME" dist --arch "$GOARCH" + + - name: Upload intermediate packages + uses: actions/upload-artifact@v4 with: - files: dist/* - generate_release_notes: true - draft: false - prerelease: ${{ contains(github.ref_name, 'rc') }} + name: packages-${{ matrix.goarch }} + path: dist/* + if-no-files-found: error + compression-level: 0 + retention-days: 7 + + draft-release: + concurrency: + group: package-draft-${{ github.ref }} + cancel-in-progress: false + needs: build-packages + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + + - name: Download amd64 packages + uses: actions/download-artifact@v4 + with: + name: packages-amd64 + path: dist + + - name: Download arm64 packages + uses: actions/download-artifact@v4 + with: + name: packages-arm64 + path: dist + + - name: Validate complete inventory and record build provenance + env: + TAG_NAME: ${{ github.ref_name }} + run: python3 script/release.py build-info "$TAG_NAME" dist + + - name: Create draft for manual signing + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAG_NAME: ${{ github.ref_name }} + PRERELEASE: ${{ contains(github.ref_name, 'rc') }} + run: | + # List drafts as well as published releases. An API failure stops this step. + existing_tags="$(gh api --paginate "repos/$GITHUB_REPOSITORY/releases?per_page=100" --jq '.[].tag_name')" + while IFS= read -r existing_tag; do + if [[ "$existing_tag" == "$TAG_NAME" ]]; then + echo "Release $TAG_NAME already exists; refusing to overwrite or duplicate it." >&2 + exit 1 + fi + done <<< "$existing_tags" + extra=() + if [[ "$PRERELEASE" == "true" ]]; then + extra+=(--prerelease) + fi + gh release create "$TAG_NAME" dist/* \ + --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" \ + --verify-tag --draft --generate-notes "${extra[@]}" docker-build: strategy: diff --git a/docs/release.md b/docs/release.md index b1e58db71..a1404269e 100644 --- a/docs/release.md +++ b/docs/release.md @@ -1,121 +1,210 @@ -# Releasing and publishing packages +# Releasing and signing packages -`orchestrator` release artifacts are built and published automatically by the [`Release` workflow](../.github/workflows/release.yml). The workflow fires on any pushed tag matching `v*` and produces: +A pushed `v*` tag starts the [Release workflow](../.github/workflows/release.yml). +Native amd64 and arm64 jobs each build seven Linux packages. A final job waits +for **both** builds, validates all fourteen packages, and creates a **draft** +GitHub Release with `BUILD-INFO.json`. An operator signs and verifies the packages +before explicitly publishing the draft. -- `tar.gz`, `.deb`, and `.rpm` packages attached to a GitHub Release -- A multi-arch Docker image pushed to `ghcr.io/proxysql/orchestrator` +Container images still publish automatically to `ghcr.io/proxysql/orchestrator`. +Holding the package release as a draft does not hold back GHCR images. Container +signing and coordinated container publication are outside this procedure. -Both artifact sets cover `linux/amd64` and `linux/arm64`. +## Approved signing key -## Triggering a release +- Identity: `ProxySQL Package Builder ` +- Full fingerprint: `653F85BB38256DF8A96206C3E8CA2E8D8217C97E` +- [Public key](https://repo.proxysql.com/ProxySQL/proxysql-3.0.x/repo_pub_key) -``` - git tag v4.30.1 - git push origin v4.30.1 -``` - -That's the whole trigger. The workflow picks up the tag name as the release version, strips the leading `v`, and uses `4.30.1` for package versions and Docker tags. +RPMs receive embedded RSA/SHA256 signatures. DEBs and tarballs remain unchanged +and are authenticated by the detached signature on `SHA256SUMS`; they do not +receive embedded package signatures. The manifest also covers `BUILD-INFO.json`. +The private key remains in the signing server's existing keyring. GitHub Actions +has no signing key, passphrase, or SSH access to that server. -### Prerelease (release candidate) tags +## Trigger a release -Tags that contain `rc` (e.g. `v4.30.1-rc1`) are handled specially: - -- The GitHub Release is marked as a prerelease. -- The Docker `latest` tag is **not** updated — only the specific version tags are pushed. +```bash +git tag v4.32.1 +git push origin v4.32.1 +``` -Use this for testing the release pipeline end-to-end on a fork before cutting a real release. +Wait for the entire Release workflow to succeed, then locate its draft release. +The workflow fails rather than creating a partial draft if a build or inventory +check fails. Each architecture produces: -## What runs +- Full `orchestrator` tarball. +- Full, CLI-only and client-only variants in both `.deb` and `.rpm` formats. -The workflow has three jobs: +The final job records the repository, tag, exact commit, workflow run and attempt, +and original package SHA-256 hashes in `BUILD-INFO.json`. There are fifteen assets +at this stage: fourteen packages and build provenance. -### 1. `build-and-release` (matrix: amd64, arm64) +### Release candidates -Runs on `ubuntu-latest` (amd64) and `ubuntu-24.04-arm` (arm64) — GitHub's native ARM runners, free for public repos. No QEMU, no cross-compilation: each job builds on its own native architecture, so CGO (`go-sqlite3`) works without any special toolchain. +Tags containing `rc`, such as `v4.32.1-rc1`, retain the existing behavior: -Each matrix job: +- The draft and published GitHub Release are marked as a prerelease. +- GHCR does not update `latest`; version tags still publish automatically. +- RPM filenames use `4.32.1_rc1`; DEB and tarball filenames use `4.32.1-rc1`. -1. Installs Go, `fpm`, and `rpmbuild`. -2. Runs `./build.sh -a ` with `RELEASE_VERSION` set from the tag. -3. Collects everything `build.sh` writes to `/tmp/orchestrator-release/` and uploads it to the GitHub Release. +## Prepare, sign, verify and upload -Per arch, `build.sh` produces three variants (see `package_linux` in [`build.sh`](../build.sh)): +These commands can all run on `repo.proxysql.com`. Alternatively, run preparation, +verification, upload and publication on a laptop and transfer the bundle manually +for signing as described below. Use a checkout containing these scripts; Python +3.9+, authenticated `gh`, GnuPG and RPM tools (`rpm`, `rpmkeys`, `rpmsign`) are +required. On macOS the verification tools are available through `brew install gnupg rpm`; on Ubuntu install `gnupg rpm`. -- `orchestrator` — full package (binary + web resources + sample configs + systemd unit) -- `orchestrator-cli` — binary only -- `orchestrator-client` — the `orchestrator-client` shell script only +Use one operator per tag. Keep the original preparation directory until the +release has been published and verified. It contains the trusted local release +identity, unsigned checksums, provenance and original package backups. -Each variant is emitted as `.tar.gz`, `.deb`, and `.rpm`. Package names differ by arch (`_amd64.deb` / `_arm64.deb`, `.x86_64.rpm` / `.aarch64.rpm`), so the two matrix jobs don't collide when uploading to the same Release. +### 1. Download one specific draft into a fresh directory -Both matrix jobs call `softprops/action-gh-release@v2` — the action is idempotent and will attach to the existing Release created by whichever job finishes first. +```bash +cd /path/to/orchestrator +python3 script/release.py prepare v4.32.1 /path/to/releases/v4.32.1 +``` -### 2. `docker-build` (matrix: linux/amd64, linux/arm64) +`--repo OWNER/REPO` selects a fork when testing. The command requires a draft, +exact artifact coverage, matching GitHub and CI digests, a tag pointing at the +recorded commit, and a successful matching workflow run/attempt. It refuses an +existing preparation directory. The result is: -Each arch builds [`docker/Dockerfile`](../docker/Dockerfile) natively on its own runner and pushes **by digest** to `ghcr.io/proxysql/orchestrator` (no tag yet). The digest is uploaded as a workflow artifact for the merge job to consume. +```text +v4.32.1/ + release.json # trusted local snapshot of the draft and build identity + UNSIGNED-SHA256SUMS # original checksums, including BUILD-INFO.json + unsigned/ # original fourteen packages and BUILD-INFO.json +``` -### 3. `docker-merge` +### 2. Sign manually using the existing server keyring -Downloads both digests, runs `docker/metadata-action` to compute tags from the git tag: +On the signing server, from the same script checkout: -- `type=semver,pattern={{version}}` — e.g. `4.30.1` -- `type=semver,pattern={{major}}.{{minor}}` — e.g. `4.30` -- `type=raw,value=latest` — only when the tag does **not** contain `rc` +```bash +python3 script/sign-release.py /path/to/releases/v4.32.1 +``` -Then uses `docker buildx imagetools create` to assemble a multi-arch manifest under all those tags, and inspects the result. +Use an interactive terminal if the existing key requires a passphrase. An +established server-side GPG wrapper can be selected with `--gpg +/root/path/to/signing-gpg`; credentials must stay in the existing root-only +configuration or GPG agent. The script does not provision credentials or change +GPG/RPM configuration. Its RPM command-line macros select the approved full +fingerprint and SHA256, including compatibility with the server's RPM 4.17. + +The script validates the original inventory/checksums first and creates a fresh +`signed/` directory. It signs **all six RPM files**, computes checksums **after** +RPM signing, and creates `SHA256SUMS.asc`. It then verifies the result using an +isolated public keyring. All fifteen original files are returned, with the RPMs +replaced by their signed versions, plus the two checksum files: seventeen files. +An existing signing output is never overwritten; `--output /fresh/path` selects +a different output directory after an interrupted attempt. + +### 3. Verify against the original preparation directory + +```bash +python3 script/release.py verify /path/to/releases/v4.32.1 +``` -## Verifying a release +The public key is downloaded from the approved URL, and its **full fingerprint** +is checked before import into temporary GPG and RPM keyrings containing only that +key. `--public-key /path/to/repo_pub_key` uses a previously downloaded certificate +with the same mandatory fingerprint check. Verification requires: -### GitHub Release page +- A valid SHA256 signature on the complete checksum manifest. +- A valid RSA/SHA256 signature on every RPM; an unsigned RPM is rejected even if + `rpmkeys --checksig` returns success for its digests alone. +- Unchanged RPM header/payload digests relative to the original downloads. +- Unchanged DEB, tarball and provenance bytes. +- Exact artifact coverage, with no missing, extra, empty or symlinked files. -After the workflow completes, the Release page should list (for version `X.Y.Z`): +### 4. Upload verified files and check their uploaded bytes +```bash +python3 script/release.py upload /path/to/releases/v4.32.1 ``` -orchestrator-X.Y.Z-linux-amd64.tar.gz -orchestrator-X.Y.Z-linux-arm64.tar.gz -orchestrator_X.Y.Z-1_amd64.deb -orchestrator_X.Y.Z-1_arm64.deb -orchestrator-X.Y.Z-1.x86_64.rpm -orchestrator-X.Y.Z-1.aarch64.rpm -``` - -Plus the `-cli` and `-client` variants in `.deb` and `.rpm` form for each arch. -### Docker manifest - -``` - docker buildx imagetools inspect ghcr.io/proxysql/orchestrator:X.Y.Z +The command verifies again, confirms the draft identity and tag/build context, +then replaces the **RPM files themselves** using `gh release upload --clobber`. +It uploads the checksum manifest/signature after the RPMs. Existing DEBs, tarballs +and provenance are left in place. It downloads all seventeen release assets into +a fresh temporary directory, repeats signature/inventory checks, and requires +byte-for-byte digest agreement with the locally verified result. Only then does +it write a local `uploaded.json` receipt. The release remains a draft. + +`--clobber` deletes an old asset before uploading its replacement. Original +packages remain in `unsigned/`. If an upload fails, rerun the same upload command; +it accepts already uploaded verified files and restores missing RPMs from the +verified signed output. Empty `starter` assets left by interrupted RPM/checksum +uploads are also replaced; malformed completed assets still stop the operation. Unexpected asset changes or changed release identity +stop the operation. Never use returned server metadata to replace the original +trusted local `release.json` or `unsigned/` directory. + +## Manual transfer when using a laptop + +The repository scripts do not connect to any server. Transfer the prepared bundle +and make the same `script/release.py` and `script/sign-release.py` available on the +signing server. For example, run these transfers yourself: + +```bash +scp -P 1022 -r /laptop/releases/v4.32.1 root@repo.proxysql.com:/root/orchestrator-signing/ +ssh -t -p 1022 root@repo.proxysql.com +# On the server, from the script checkout: +python3 script/sign-release.py /root/orchestrator-signing/v4.32.1 +# Back on the laptop, download ONLY the signed output into a fresh directory: +scp -P 1022 -r root@repo.proxysql.com:/root/orchestrator-signing/v4.32.1/signed /laptop/returned-v4.32.1 +python3 script/release.py verify /laptop/releases/v4.32.1 --signed /laptop/returned-v4.32.1 +python3 script/release.py upload /laptop/releases/v4.32.1 --signed /laptop/returned-v4.32.1 ``` -The output should list both `linux/amd64` and `linux/arm64` entries. - -Pull and smoke-test each arch: - -``` - docker run --rm --platform linux/amd64 ghcr.io/proxysql/orchestrator:X.Y.Z orchestrator --version - docker run --rm --platform linux/arm64 ghcr.io/proxysql/orchestrator:X.Y.Z orchestrator --version -``` +Return the signed RPMs, unchanged DEBs/tarballs and provenance, and **both** +checksum files. Returning only the manifest would leave unsigned RPMs on GitHub. +Private keys and passphrases are never part of the transferred bundle. -## Local reproduction +## Publish explicitly -The release workflow does the same thing you can do locally with `build.sh` — see [Building and testing](build.md) and [`build.sh`](../build.sh). To produce ARM64 packages on a non-ARM host (outside of CI), run inside an arm64 container: +After upload succeeds and release notes are ready, run a separate command: +```bash +python3 script/release.py publish /path/to/releases/v4.32.1 ``` - docker run --rm -it --platform linux/arm64 \ - -v $PWD:/src -w /src \ - ubuntu:24.04 bash -c ' - apt-get update && - apt-get install -y golang git ruby ruby-dev build-essential rpm && - gem install --no-document fpm && - ./build.sh -a arm64 - ' -``` - -## Permissions and secrets -The workflow relies on `GITHUB_TOKEN` with `contents: write` (for the Release) and `packages: write` (for GHCR) — both declared in [`release.yml`](../.github/workflows/release.yml). No additional secrets are required. - -## Troubleshooting +This requires the local upload receipt and re-downloads/re-verifies the current +remote assets against it. It then invokes `gh release edit --draft=false`, +preserving the release's prerelease flag. Published or replaced drafts are +rejected by preparation and upload commands. + +## Workflow reruns and troubleshooting + +- Architecture jobs retain intermediate packages for seven days. Only the final + job creates the draft, so the two architecture jobs cannot race on release assets. +- A failed architecture job prevents draft creation. Re-run the failed build and + the dependent final job. +- The final job refuses any existing release, including a draft, rather than + overwriting packages after signing has started. Continue using an existing + complete draft. To rebuild an unused draft, explicitly remove it first after + confirming no signing/publication operation is in progress, then rerun the build. +- Preparation failures leave any downloaded bytes for inspection. Fix the source + issue and choose another fresh preparation directory. +- The recorded workflow attempt must have succeeded and the tag must still point + at its commit. A later workflow rerun does not invalidate an earlier successful + attempt. Do not edit trusted inventory files to bypass a failed check. +- Container builds and manifest merging keep their existing independent jobs. + Inspect images with `docker buildx imagetools inspect + ghcr.io/proxysql/orchestrator:4.32.1`. + +For local build reproduction see [Building and testing](build.md) and +[`build.sh`](../build.sh). + +## Tests + +```bash +python3 -m unittest discover -s tests/release -v +``` -- **Workflow didn't run after tagging.** The tag must start with `v` (see the `on.push.tags` filter). Tags pushed without `git push --tags` or without pushing the specific ref won't trigger it. -- **A matrix job failed mid-way and part of the release is missing.** The workflow uses `fail-fast: false`, so the other arch still completes. Re-running only the failed job from the Actions UI is safe — the GitHub Release and GHCR both accept re-uploads (fpm uses `-f` to overwrite, `action-gh-release` replaces files of the same name). -- **Docker manifest is missing one arch.** If `docker-build` succeeded for only one arch, `docker-merge` will still run but `imagetools create` will produce a single-arch manifest. Re-run the failed `docker-build` job, then re-run `docker-merge`. +Crypto integration tests generate a temporary test key and build temporary RPM +fixtures; they do not sign with the production key or access live releases. They +require `gpg`, `rpm`, `rpmkeys`, `rpmbuild` and `rpmsign`; the release-tools CI job +installs these dependencies. Network-facing tests stub the GitHub boundary. diff --git a/docs/superpowers/plans/2026-10-27-manual-release-signing.md b/docs/superpowers/plans/2026-10-27-manual-release-signing.md new file mode 100644 index 000000000..c5b199ddc --- /dev/null +++ b/docs/superpowers/plans/2026-10-27-manual-release-signing.md @@ -0,0 +1,72 @@ +# Manual Release Signing Implementation Plan + +> **For agentic workers:** Use superpowers:executing-plans to implement this plan task-by-task. + +**Goal:** Hold new package releases as drafts until manual signing and verification. + +**Architecture:** Native architecture jobs upload intermediate artifacts. One final +job validates all packages and creates the draft with build provenance. Python +stdlib commands manage preparation, manual signing, verification/upload and publication. + +**Tech Stack:** GitHub Actions, GitHub CLI, Python 3.9+, GnuPG, RPM 4.17+. + +**Spec:** `docs/superpowers/specs/2026-10-27-manual-release-signing-design.md` + +## Global Constraints + +- Approved key: `653F85BB38256DF8A96206C3E8CA2E8D8217C97E`. +- No private key exports, CI signing credentials or automated server access. +- Preserve rc prerelease handling and independent GHCR publication. +- Draft assets: fourteen packages and BUILD-INFO.json; signed assets add two checksum files. +- All mutating GitHub operations must be restricted to the prepared draft. + +## Review Focus + +- Re-running a build must not overwrite a published or already signed release. +- Prerelease RPM filenames differ from DEB and tarball filenames. +- An unsigned RPM can return a successful checksig exit status on RPM 4.17. +- Returned signing output must not be able to replace the trusted local inventory. +- Partial uploads must be recoverable without accidentally publishing the release. + +### Task 1: Inventory and provenance + +**Files:** `script/release.py`, `tests/release/test_release.py`, `.github/workflows/release.yml`. +**Interfaces:** `expected_names(tag, arch=None)`, `check_packages(directory, tag, arch=None)`, +`prepare(tag, directory, repo)`, BUILD-INFO.json schema version 1. + +- [ ] Write tests for fourteen package inventory, seven per architecture, rc names, + missing/extra files, symlinks and invalid tag names. Run and observe failure. +- [ ] Implement inventory and build provenance checks; add draft preparation with + recorded release identity, workflow run/attempt, original checksums and backup files. +- [ ] Split architecture builds and final draft creation. Fail missing files and + refuse existing releases. Preserve container jobs and prerelease expression. +- [ ] Run inventory/provenance tests and actionlint. + +### Task 2: Signing and verification + +**Files:** `script/sign-release.py`, `script/release.py`, `tests/release/test_release.py`. +**Interfaces:** `sign(directory, output=None, gpg="gpg")`, +`verify(directory, signed=None, public_key=None) -> dict[str, str]`. + +- [ ] Write tests for changed unsigned inventory, wrong signing key, unsigned RPMs, + incomplete/changed manifests, modified DEBs/tarballs and unchanged RPM payloads. +- [ ] Implement fresh output signing using installed RPM macros and existing GPG + credentials; create final checksums and detached signature after RPM signing. +- [ ] Implement isolated full-fingerprint GPG/RPM verification; run real crypto tests + with a temporary key and a public unsigned RPM fixture, never the production key. + +### Task 3: Verified upload, publication and documentation + +**Files:** `script/release.py`, `tests/release/test_release.py`, `docs/release.md`. +**Interfaces:** `upload(directory, signed=None, public_key=None)`, +`publish(directory, public_key=None)`. + +- [ ] Write state-guard tests for published/replaced drafts, changed tag/run, altered + assets and partial uploads. Assert upload cannot invoke publication. +- [ ] Implement verified upload and full re-download checks. Implement publication + separately, requiring re-verification and preserving prerelease state. +- [ ] Document server-only and manual-transfer operation, approved key, seventeen + assets, backup/resume behavior, rc handling, and independent GHCR publication. +- [ ] Run the full release-tool suite, syntax/lint and diff checks. Obtain independent + branch review, fix important findings with regression tests, commit, push the + feature branch and open a PR against master. diff --git a/docs/superpowers/specs/2026-10-27-manual-release-signing-design.md b/docs/superpowers/specs/2026-10-27-manual-release-signing-design.md new file mode 100644 index 000000000..69267dfa4 --- /dev/null +++ b/docs/superpowers/specs/2026-10-27-manual-release-signing-design.md @@ -0,0 +1,59 @@ +# Manual package release signing + +## Intent and scope + +Implement the manual signing proposal approved in the support-ticket discussion. +A pushed version tag builds packages for amd64 and arm64. Only a complete build +may create a draft release; publication follows operator signing and verification. +The approved key is `653F85BB38256DF8A96206C3E8CA2E8D8217C97E` (ProxySQL Package Builder). +Keep the private key on the signing server. No SSH automation or signing secrets +are added to GitHub Actions. GHCR publication and rc handling retain their behavior. + +## Approaches + +The conversation selected a draft release followed by manual signing, verification, +upload, and separate publication. Automatic server signing would require new CI +access to the signing key. Keeping immediate package publication would expose +unsigned packages before the operator could sign them. Neither alternative fits +the approved proposal. + +## Interfaces and invariants + +- `script/release.py`: check inventory, record build provenance, prepare one draft, + verify signed output, upload verified assets, and separately publish. +- `script/sign-release.py`: manually sign a prepared bundle using existing server + credentials; support the existing GPG wrapper through an explicit executable path. +- `docs/release.md`: commands usable entirely on repo.proxysql.com, with manual + transfer instructions when preparation/verification happen on a laptop. +- Every tag has fourteen packages: three variants in RPM/DEB for two architectures, + plus the full tarball for each architecture. RPM prerelease versions replace + hyphens with underscores; DEBs and tarballs preserve the tag version. +- CI also attaches `BUILD-INFO.json`, binding repository, tag, commit, workflow + run/attempt, and unsigned package digests. The signed checksum manifest covers + these fifteen files. A fully signed draft therefore has seventeen assets. +- Preparation requires a fresh directory, a complete draft, successful matching + workflow run/attempt, and GitHub/CI checksum agreement. Preserve original bytes + and provenance separately from returned signing output. +- Signing validates all original inventory/checksums first, writes to a fresh + output directory, signs all six RPMs with SHA256, then hashes final files and + creates the detached SHA256 manifest signature. DEBs/tarballs/provenance stay + byte-for-byte unchanged. The original unsigned bundle is retained. +- Verification trusts only the approved full fingerprint in isolated GPG and RPM + keyrings; it requires actual RPM signatures, complete manifest coverage, and + unchanged RPM header/payload digests and unchanged non-RPM bytes. +- Upload checks draft identity, tag/commit/run and original/current asset state, + supports resuming a partial upload (including empty GitHub starter assets), + validates the recorded workflow attempt even after later reruns, replaces RPMs, then + uploads checksum files. Re-download and verify all seventeen uploaded assets. +- Publication is a separate command that re-verifies the uploaded draft and changes + only its draft flag. Preserve prerelease state. +- CI refuses to overwrite any existing release on rerun. Operators can continue + with the existing complete draft or explicitly remove an unused draft themselves. + +## Validation + +Use stdlib unittest for inventory, provenance, tampering, and release-state guards. +Exercise real GPG/RPM signing with an isolated temporary test key, including wrong +key, unsigned RPM, altered package, incomplete manifest, and symlink rejection. +Lint the workflow with actionlint. Do not publish a tag or modify existing releases +while testing this PR. diff --git a/script/release.py b/script/release.py new file mode 100755 index 000000000..0071642a9 --- /dev/null +++ b/script/release.py @@ -0,0 +1,441 @@ +#!/usr/bin/env python3 +"""Prepare and verify manually signed package releases. Requires Python 3.9+.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile +from urllib.parse import quote +from urllib.request import urlopen + +KEY = "653F85BB38256DF8A96206C3E8CA2E8D8217C97E" +KEY_URL = "https://repo.proxysql.com/ProxySQL/proxysql-3.0.x/repo_pub_key" +BUILD_INFO = "BUILD-INFO.json" +REPOSITORY = "ProxySQL/orchestrator" +VARIANTS = ("orchestrator", "orchestrator-cli", "orchestrator-client") +ARCHES = {"amd64": "x86_64", "arm64": "aarch64"} + + +class ReleaseError(Exception): + """A release failed a required integrity or state check.""" + + +def require(condition, message): + if not condition: + raise ReleaseError(message) + + +def run(args, **kwargs): + result = subprocess.run([str(a) for a in args], capture_output=True, text=True, **kwargs) + if result.returncode: + raise ReleaseError(f"Command failed: {args[0]}\n{result.stdout}{result.stderr}") + return result.stdout + + +def api(repo, path): + return json.loads(run(["gh", "api", f"repos/{repo}/{path}"])) + + +def release_metadata(repo, tag): + # The REST by-tag endpoint only finds published releases. gh resolves drafts + # by their pending tag as well; fetch the full REST record by numeric ID. + reference = json.loads(run(["gh", "release", "view", tag, "--repo", repo, "--json", "databaseId"])) + release_id = reference.get("databaseId") + require(type(release_id) is int and release_id > 0, "Could not resolve release identity") + return api(repo, f"releases/{release_id}") + + +def validate_repo(repo): + require(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*", repo), + "Expected repository in OWNER/REPO form") + + +def expected_names(tag, arch=None): + require(re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9][A-Za-z0-9_.+-]*)?", tag), + "Expected a version tag such as v4.32.0 or v4.32.1-rc1") + require(arch is None or arch in ARCHES, "Unsupported architecture") + version = tag[1:] + names = set() + for goarch in ([arch] if arch else ARCHES): + names.add(f"orchestrator-{version}-linux-{goarch}.tar.gz") + for variant in VARIANTS: + names.add(f"{variant}_{version}_{goarch}.deb") + names.add(f"{variant}-{version.replace('-', '_')}-1.{ARCHES[goarch]}.rpm") + return names + + +def strict_files(directory, names): + directory = Path(directory) + require(directory.is_dir() and not directory.is_symlink(), f"Not a plain directory: {directory}") + actual = {p.name for p in directory.iterdir()} + require(actual == set(names), f"Inventory mismatch in {directory}: missing={sorted(set(names)-actual)}, extra={sorted(actual-set(names))}") + for name in names: + p = directory / name + require(p.is_file() and not p.is_symlink() and p.stat().st_size > 0, f"Not a nonempty regular file: {p}") + + +def check_packages(directory, tag, arch=None): + names = expected_names(tag, arch) + strict_files(directory, names) + return names + + +def sha256(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def file_hashes(directory, names): + return {name: sha256(Path(directory) / name) for name in sorted(names)} + + +def checksum_text(hashes): + return "".join(f"{hashes[name]} {name}\n" for name in sorted(hashes)) + + +def write_json(path, value): + Path(path).write_text(json.dumps(value, indent=2, sort_keys=True) + "\n") + + +def build_info(directory, tag): + names = check_packages(directory, tag) + repo = os.environ["GITHUB_REPOSITORY"] + validate_repo(repo) + commit = os.environ["GITHUB_SHA"] + require(re.fullmatch(r"[0-9a-f]{40}", commit), "Invalid workflow commit") + info = {"schema": 1, "repository": repo, "tag": tag, "commit": commit, + "workflow_run": int(os.environ["GITHUB_RUN_ID"]), + "workflow_attempt": int(os.environ["GITHUB_RUN_ATTEMPT"]), + "unsigned_sha256": file_hashes(directory, names)} + write_json(Path(directory) / BUILD_INFO, info) + + + +def validate_info(info, repo, tag): + require(info.get("schema") == 1 and info.get("repository") == repo and info.get("tag") == tag, + "Build provenance does not match the repository and tag") + require(re.fullmatch(r"[0-9a-f]{40}", info.get("commit", "")), "Invalid build commit") + for field in ("workflow_run", "workflow_attempt"): + require(type(info.get(field)) is int and info[field] > 0, f"Invalid {field}") + hashes = info.get("unsigned_sha256", {}) + require(set(hashes) == expected_names(tag), "Build provenance has an incomplete package inventory") + require(all(re.fullmatch(r"[0-9a-f]{64}", value) for value in hashes.values()), "Invalid build checksums") + + +def assets_by_name(meta, names): + assets = meta.get("assets", []) + require(len(assets) == len(names) and {a["name"] for a in assets} == set(names), + "GitHub release asset inventory is incomplete, duplicated or unexpected") + for asset in assets: + require(re.fullmatch(r"sha256:[0-9a-f]{64}", asset.get("digest") or ""), + f"GitHub has not recorded a SHA256 digest for {asset['name']}") + require(type(asset.get("size")) is int and asset["size"] > 0, "Invalid GitHub asset size") + return {a["name"]: a for a in assets} + + +def download(repo, tag, directory): + require(not Path(directory).exists(), f"Download directory already exists: {directory}") + run(["gh", "release", "download", tag, "--repo", repo, "--dir", directory]) + + +def require_draft(record, meta): + before = record["release"] + require(meta.get("draft") is True, "Release must still be a draft") + require(not meta.get("immutable", False), "Release is immutable") + for field in ("id", "tag_name", "prerelease", "target_commitish"): + require(meta.get(field) == before.get(field), f"Draft {field} changed since preparation") + + +def check_source(record): + repo, info = record["repository"], record["build"] + tag = info["tag"] + commit = api(repo, f"commits/{quote(tag, safe='')}")["sha"] + require(commit == info["commit"], "Release tag no longer points at the prepared commit") + workflow = api(repo, f"actions/runs/{info['workflow_run']}/attempts/{info['workflow_attempt']}") + expected = {"id": info["workflow_run"], "run_attempt": info["workflow_attempt"], + "event": "push", "head_branch": tag, "head_sha": commit, + "path": ".github/workflows/release.yml", "status": "completed", "conclusion": "success"} + require(all(workflow.get(k) == v for k, v in expected.items()) + and workflow.get("repository", {}).get("full_name") == repo, + "Build workflow run/attempt does not match a successful release build") + + +def prepare(tag, directory, repo=REPOSITORY): + directory = Path(directory) + validate_repo(repo) + names = expected_names(tag) | {BUILD_INFO} + require(not directory.exists() and not directory.is_symlink(), "Preparation requires a fresh directory") + meta = release_metadata(repo, tag) + require(meta.get("draft") is True and meta.get("tag_name") == tag, "Expected the requested draft release") + assets = assets_by_name(meta, names) + directory.mkdir(parents=True) + download(repo, tag, directory / "unsigned") + strict_files(directory / "unsigned", names) + hashes = file_hashes(directory / "unsigned", names) + for name, asset in assets.items(): + require(asset["digest"] == "sha256:" + hashes[name] + and asset["size"] == (directory / "unsigned" / name).stat().st_size, + f"Downloaded asset differs from GitHub's checksum: {name}") + info = json.loads((directory / "unsigned" / BUILD_INFO).read_text()) + validate_info(info, repo, tag) + require(info["unsigned_sha256"] == {name: hashes[name] for name in expected_names(tag)}, + "Downloaded packages differ from CI build provenance") + require(meta.get("target_commitish") == info["commit"], "Draft target differs from the build commit") + record = {"schema": 1, "repository": repo, "release": meta, "build": info, "unsigned_sha256": hashes} + require_draft(record, meta) + check_source(record) + write_json(directory / "release.json", record) + (directory / "UNSIGNED-SHA256SUMS").write_text(checksum_text(hashes)) + load_bundle(directory) + return directory + + +def load_bundle(directory): + directory = Path(directory) + require(directory.is_dir() and not directory.is_symlink(), "Expected a plain prepared directory") + for name in ("release.json", "UNSIGNED-SHA256SUMS"): + path = directory / name + require(path.is_file() and not path.is_symlink(), f"Missing trusted local record: {name}") + record = json.loads((directory / "release.json").read_text()) + require(record.get("schema") == 1, "Unknown preparation record schema") + repo, info = record["repository"], record["build"] + validate_repo(repo) + tag = info["tag"] + validate_info(info, repo, tag) + names = expected_names(tag) | {BUILD_INFO} + strict_files(directory / "unsigned", names) + hashes = file_hashes(directory / "unsigned", names) + require(hashes == record["unsigned_sha256"], "Unsigned package/provenance checksums changed") + require((directory / "UNSIGNED-SHA256SUMS").read_text() == checksum_text(hashes), + "Unsigned checksum manifest is incomplete or changed") + require(json.loads((directory / "unsigned" / BUILD_INFO).read_text()) == info, + "Build provenance changed") + require(info["unsigned_sha256"] == {name: hashes[name] for name in expected_names(tag)}, + "Build provenance package checksums differ") + assets = assets_by_name(record["release"], names) + require(record["release"]["tag_name"] == tag and record["release"]["target_commitish"] == info["commit"], + "Prepared release identity differs from build provenance") + for name, asset in assets.items(): + require(asset["digest"] == "sha256:" + hashes[name] + and asset["size"] == (directory / "unsigned" / name).stat().st_size, + f"Original asset record changed: {name}") + return record + + +def verification_keys(temp, public_key): + home = temp / "gnupg" + home.mkdir(mode=0o700) + keyfile = temp / "key.asc" + if public_key is None: + with urlopen(KEY_URL, timeout=30) as response: + keyfile.write_bytes(response.read()) + else: + keyfile.write_bytes(Path(public_key).read_bytes()) + gpg = ["gpg", "--no-options", "--homedir", home, "--batch", "--no-auto-key-retrieve", "--auto-key-locate", "clear"] + listing = run(gpg + ["--with-colons", "--import-options", "show-only", "--import", keyfile]) + rows = [line.split(":") for line in listing.splitlines()] + primary = [i for i, row in enumerate(rows) if row[0] == "pub"] + require(len(primary) == 1 and primary[0] + 1 < len(rows) + and rows[primary[0] + 1][0] == "fpr" and rows[primary[0] + 1][9] == KEY + and not any(row[0] in ("sec", "ssb") for row in rows), + "Public key full fingerprint does not match the single approved key") + run(gpg + ["--import", keyfile]) + rpm = ["rpm", "--define", "_keyring rpmdb", "--dbpath", temp / "rpmdb"] + run(rpm + ["--initdb"]) + run(rpm + ["--import", keyfile]) + version = re.search(r"\b([0-9]+)\.", run(["rpm", "--version"])) + if version and int(version[1]) >= 6: + keys = run(["rpmkeys", "--define", "_keyring rpmdb", "--dbpath", temp / "rpmdb", "--list"]).splitlines() + require(len(keys) == 1 and keys[0].lower().startswith(KEY.lower() + " "), "Unexpected RPM keyring contents") + else: + keys = run(rpm + ["-qa", "--qf", "%{NAME}-%{VERSION}\n"]).splitlines() + require(keys == ["gpg-pubkey-" + KEY[-8:].lower()], "Unexpected RPM keyring contents") + return gpg, rpm + + +def rpm_signature_info(rpm, path): + """Describe the RPM header signature(s), e.g. 'RSA/SHA256, , Key ID '.""" + info = run(rpm + ["-qp", "--qf", "%{RSAHEADER:pgpsig}", path]).strip() + if info in ("", "(none)"): + # RPM 6 stores OpenPGP signatures in the OPENPGP tag instead of RSAHEADER. + # Older RPM versions do not know the tag; then the package has no signature. + try: + info = run(rpm + ["-qp", "--qf", "[%{OPENPGP:pgpsig}\n]", path]).strip() + except ReleaseError: + info = "" + if "error:" in info or info == "(none)": + info = "" + return info + + +def rpm_content_digests(rpm, path): + """Return the SHA256 header digest and the payload digest, one per line.""" + # RPM 6 renamed PAYLOADDIGEST to PAYLOADSHA256. An unknown tag may still exit 0 + # with empty output, so validate the result rather than relying on the exit code. + for payload_tag in ("PAYLOADDIGEST", "PAYLOADSHA256"): + try: + output = run(rpm + ["-qp", "--qf", "%{SHA256HEADER}\n%{" + payload_tag + "}\n", path]) + except ReleaseError: + continue + if re.fullmatch(r"[0-9a-f]{64}\n[0-9a-f]{64}\n", output): + return output + raise ReleaseError(f"Could not read the RPM header and payload digests: {path}") + + +def verify(directory, signed=None, public_key=None): + directory = Path(directory) + record = load_bundle(directory) + signed = Path(signed) if signed is not None else directory / "signed" + names = expected_names(record["build"]["tag"]) | {BUILD_INFO} + strict_files(signed, names | {"SHA256SUMS", "SHA256SUMS.asc"}) + hashes = file_hashes(signed, names) + require((signed / "SHA256SUMS").read_text() == checksum_text(hashes), + "Signed checksum manifest must cover every package and BUILD-INFO.json exactly once") + with tempfile.TemporaryDirectory(prefix="orchestrator-verify-") as scratch: + gpg, rpm = verification_keys(Path(scratch), public_key) + status = run(gpg + ["--status-fd", "1", "--verify", signed / "SHA256SUMS.asc", signed / "SHA256SUMS"]) + valid = [line.split() for line in status.splitlines() if line.startswith("[GNUPG:] VALIDSIG ")] + require(len(valid) == 1 and valid[0][2] == KEY and valid[0][9] == "8" + and not re.search(r"BADSIG|ERRSIG|REVKEYSIG|EXPKEYSIG|KEYEXPIRED|SIGEXPIRED", status), + "Manifest signature is not a valid SHA256 signature from the approved key") + for name in sorted(names): + path = signed / name + if not name.endswith(".rpm"): + require(hashes[name] == record["unsigned_sha256"][name], f"Non-RPM file changed during signing: {name}") + continue + result = run(["rpmkeys", "--define", "_keyring rpmdb", "--dbpath", Path(scratch) / "rpmdb", "--checksig", "--verbose", path]) + require(re.search(r"(?im)^.*signature.*:\s+OK\s*$", result), f"RPM has no verified signature: {name}") + signature = rpm_signature_info(rpm, path) + require("RSA/SHA256" in signature and KEY[-16:].lower() in signature.lower(), f"RPM signature uses an unexpected key or digest: {name}") + original = rpm_content_digests(rpm, directory / "unsigned" / name) + current = rpm_content_digests(rpm, path) + require(original == current and len(original.splitlines()) == 2 + and all(re.fullmatch(r"[0-9a-f]{64}", value) for value in current.splitlines()), + f"RPM header or payload changed during signing: {name}") + require(hashes[name] != record["unsigned_sha256"][name], f"RPM was not changed by signing: {name}") + return file_hashes(signed, names | {"SHA256SUMS", "SHA256SUMS.asc"}) + + +def verify_remote(directory, public_key=None): + record = load_bundle(directory) + repo, tag = record["repository"], record["build"]["tag"] + meta = release_metadata(repo, tag) + require_draft(record, meta) + check_source(record) + names = expected_names(tag) | {BUILD_INFO, "SHA256SUMS", "SHA256SUMS.asc"} + assets = assets_by_name(meta, names) + with tempfile.TemporaryDirectory(prefix="orchestrator-upload-check-") as scratch: + downloaded = Path(scratch) / "download" + download(repo, tag, downloaded) + hashes = verify(directory, downloaded, public_key) + for name, asset in assets.items(): + require(asset["digest"] == "sha256:" + hashes[name] + and asset["size"] == (downloaded / name).stat().st_size, + f"Uploaded bytes do not match GitHub metadata: {name}") + after = release_metadata(repo, tag) + require_draft(record, after) + after_assets = assets_by_name(after, names) + require(all(after_assets[name][field] == asset[field] + for name, asset in assets.items() for field in ("id", "size", "digest")), + "Release assets changed during download verification") + return hashes + + +def upload(directory, signed=None, public_key=None): + directory = Path(directory) + record = load_bundle(directory) + signed = Path(signed) if signed is not None else directory / "signed" + hashes = verify(directory, signed, public_key) + repo, tag = record["repository"], record["build"]["tag"] + meta = release_metadata(repo, tag) + require_draft(record, meta) + check_source(record) + original = assets_by_name(record["release"], record["unsigned_sha256"]) + current_names = {a["name"] for a in meta["assets"]} + require({name for name in original if not name.endswith(".rpm")} <= current_names <= set(hashes), + "Draft asset coverage changed since preparation") + # A failed GitHub upload may leave an empty `starter` asset. Only our + # replaceable RPM/checksum names may be treated as pending replacements. + require(len(current_names) == len(meta["assets"]), "Duplicate draft asset names") + replaceable = {name for name in hashes if name.endswith(".rpm") or name in ("SHA256SUMS", "SHA256SUMS.asc")} + starters = {a["name"] for a in meta["assets"] if a["name"] in replaceable + and a.get("state") == "starter" and a.get("size") == 0 and a.get("digest") is None} + completed = dict(meta, assets=[a for a in meta["assets"] if a["name"] not in starters]) + current = assets_by_name(completed, current_names - starters) + for name, asset in current.items(): + allowed = {"sha256:" + hashes[name]} + if name in original: + allowed.add(original[name]["digest"]) + require(asset["digest"] in allowed, f"Draft asset changed unexpectedly: {name}") + if name in original and not name.endswith(".rpm"): + require(asset["id"] == original[name]["id"], f"Unchanged draft asset was replaced: {name}") + # Replace the RPM files themselves first. The signed manifest is uploaded last. + pending = [name for name in sorted(hashes) if name not in current or current[name]["digest"] != "sha256:" + hashes[name]] + for group in ([name for name in pending if name.endswith(".rpm")], + [name for name in pending if name in ("SHA256SUMS", "SHA256SUMS.asc")]): + if group: + run(["gh", "release", "upload", tag, "--repo", repo, "--clobber", *[signed / name for name in group]]) + require(verify_remote(directory, public_key) == hashes, "Re-downloaded assets differ from verified signing output") + write_json(directory / "uploaded.json", {"release_id": meta["id"], "sha256": hashes}) + return hashes + + +def publish(directory, public_key=None): + directory = Path(directory) + record = load_bundle(directory) + receipt = json.loads((directory / "uploaded.json").read_text()) + require(receipt.get("release_id") == record["release"]["id"], "Upload receipt is for another draft") + require(verify_remote(directory, public_key) == receipt["sha256"], "Uploaded assets changed after verification") + repo, tag = record["repository"], record["build"]["tag"] + run(["gh", "release", "edit", tag, "--repo", repo, "--draft=false"]) + meta = release_metadata(repo, tag) + require(meta.get("draft") is False and meta["id"] == record["release"]["id"] + and meta["prerelease"] == record["release"]["prerelease"], "Unexpected release state after publication") + return meta.get("html_url", tag) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + check = commands.add_parser("check-packages", help="require the exact package inventory") + check.add_argument("tag") + check.add_argument("directory", type=Path) + check.add_argument("--arch", choices=ARCHES) + info = commands.add_parser("build-info", help="record CI provenance from GITHUB_* variables") + info.add_argument("tag") + info.add_argument("directory", type=Path) + prep = commands.add_parser("prepare", help="download one complete draft into a fresh directory") + prep.add_argument("tag") + prep.add_argument("directory", type=Path) + prep.add_argument("--repo", default=REPOSITORY) + for command in ("verify", "upload", "publish"): + sub = commands.add_parser(command) + sub.add_argument("directory", type=Path, help="original trusted preparation directory") + sub.add_argument("--public-key", type=Path, help="public key file; full fingerprint is always checked") + if command != "publish": + sub.add_argument("--signed", type=Path, help="returned signed directory (default: DIRECTORY/signed)") + args = parser.parse_args() + try: + if args.command == "check-packages": + print(f"Validated {len(check_packages(args.directory, args.tag, args.arch))} packages") + elif args.command == "build-info": + build_info(args.directory, args.tag) + elif args.command == "prepare": + print(f"Prepared {prepare(args.tag, args.directory, args.repo)}") + elif args.command in ("verify", "upload"): + hashes = globals()[args.command](args.directory, args.signed, args.public_key) + print(f"{args.command}: verified {len(hashes)} files with key {KEY}; release remains a draft") + else: + print(f"Published {publish(args.directory, args.public_key)}") + except (ReleaseError, OSError, ValueError, KeyError, TypeError) as exc: + parser.exit(1, f"error: {exc}\n") + + +if __name__ == "__main__": + main() diff --git a/script/sign-release.py b/script/sign-release.py new file mode 100755 index 000000000..2a3ec488d --- /dev/null +++ b/script/sign-release.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Run manually on the signing server; never copy the private key into the bundle.""" +import argparse +import os +from pathlib import Path +import shutil +import tempfile + +import release + + +def sign(directory, output=None, gpg="gpg"): + directory = Path(directory).resolve() + record = release.load_bundle(directory) + output = Path(output) if output is not None else directory / "signed" + release.require(not output.exists() and not output.is_symlink(), "Signing output must be a fresh directory") + release.require(not output.resolve().is_relative_to(directory / "unsigned"), + "Signing output cannot be inside the original unsigned inventory") + executable = shutil.which(str(gpg)) + release.require(executable and not any(c.isspace() for c in executable), + "GPG executable must exist and have no whitespace in its path") + executable = str(Path(executable).resolve()) + names = release.expected_names(record["build"]["tag"]) | {release.BUILD_INFO} + output.mkdir(parents=True) + for name in names: + shutil.copyfile(directory / "unsigned" / name, output / name) + # Command-line macros work with the server's RPM 4.17 and newer RPM versions; + # the modern signing-key macro and the legacy GnuPG macro select the same key. + release.run(["rpmsign", "--define", f"__gpg {executable}", + "--define", f"_gpg_name {release.KEY}", + "--define", f"_openpgp_sign_id {release.KEY}", + "--define", "_gpg_digest_algo sha256", "--addsign", + *[output / name for name in sorted(names) if name.endswith(".rpm")]]) + (output / "SHA256SUMS").write_text(release.checksum_text(release.file_hashes(output, names))) + release.run([executable, "--local-user", release.KEY, "--digest-algo", "SHA256", + "--armor", "--detach-sign", "--output", output / "SHA256SUMS.asc", output / "SHA256SUMS"]) + # Export only the public certificate to verify without changing any keyring. + with tempfile.TemporaryDirectory(prefix="orchestrator-sign-check-") as scratch: + public_key = Path(scratch) / "public.asc" + public_key.write_text(release.run([executable, "--armor", "--export", release.KEY])) + release.verify(directory, output, public_key) + return output + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("directory", type=Path) + parser.add_argument("--output", type=Path, help="fresh output directory (default: DIRECTORY/signed)") + parser.add_argument("--gpg", default="gpg", help="existing GPG executable or server signing wrapper") + args = parser.parse_args() + try: + if os.isatty(0): + os.environ["GPG_TTY"] = os.ttyname(0) + print(f"Signed and verified: {sign(args.directory, args.output, args.gpg)}") + except (release.ReleaseError, OSError, ValueError, KeyError, TypeError) as exc: + parser.exit(1, f"error: {exc}\n") + + +if __name__ == "__main__": + main() diff --git a/tests/release/test_release.py b/tests/release/test_release.py new file mode 100644 index 000000000..343e071df --- /dev/null +++ b/tests/release/test_release.py @@ -0,0 +1,419 @@ +import importlib.util +import pathlib +import json +import os +import shutil +import subprocess +from unittest.mock import patch +import sys +import tempfile +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[2] + + +class ReleaseTestCase(unittest.TestCase): + def setUp(self): + path = ROOT / "script/release.py" + self.assertTrue(path.exists(), "release inventory command is missing") + spec = importlib.util.spec_from_file_location("release", path) + self.release = importlib.util.module_from_spec(spec) + sys.modules["release"] = self.release + spec.loader.exec_module(self.release) + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.directory = pathlib.Path(self.temp.name) + + def populate(self, tag="v4.32.0", arch=None): + for name in self.release.expected_names(tag, arch): + (self.directory / name).write_bytes(b"package") + + + def bundle(self, rpm=None, tag="v4.32.0"): + directory = self.directory / "bundle" + unsigned = directory / "unsigned" + unsigned.mkdir(parents=True) + names = self.release.expected_names(tag) + for name in names: + (unsigned / name).write_bytes(pathlib.Path(rpm).read_bytes() if rpm and name.endswith(".rpm") else b"original package") + info = {"schema": 1, "repository": "ProxySQL/orchestrator", "tag": tag, + "commit": "a" * 40, "workflow_run": 123, "workflow_attempt": 1, + "unsigned_sha256": self.release.file_hashes(unsigned, names)} + self.release.write_json(unsigned / self.release.BUILD_INFO, info) + hashes = self.release.file_hashes(unsigned, names | {self.release.BUILD_INFO}) + assets = [{"id": i, "name": name, "size": (unsigned / name).stat().st_size, + "digest": "sha256:" + hashes[name]} for i, name in enumerate(sorted(hashes), 1)] + meta = {"id": 100, "tag_name": tag, "draft": True, "prerelease": "rc" in tag, + "target_commitish": info["commit"], "assets": assets} + record = {"schema": 1, "repository": info["repository"], "release": meta, + "build": info, "unsigned_sha256": hashes} + self.release.write_json(directory / "release.json", record) + (directory / "UNSIGNED-SHA256SUMS").write_text(self.release.checksum_text(hashes)) + return directory, record + + +class InventoryTests(ReleaseTestCase): + def test_complete_release_has_fourteen_packages(self): + names = self.release.expected_names("v4.32.0") + self.assertEqual(len(names), 14) + self.assertIn("orchestrator-client_4.32.0_arm64.deb", names) + self.assertNotIn("orchestrator-cli-4.32.0-linux-amd64.tar.gz", names) + self.populate() + self.assertEqual(self.release.check_packages(self.directory, "v4.32.0"), names) + + def test_architecture_inventory_has_seven_packages(self): + for arch in ("amd64", "arm64"): + self.assertEqual(len(self.release.expected_names("v4.32.0", arch)), 7) + + def test_prerelease_names_match_fpm(self): + names = self.release.expected_names("v4.30.1-rc2") + self.assertIn("orchestrator-4.30.1_rc2-1.x86_64.rpm", names) + self.assertIn("orchestrator_4.30.1-rc2_amd64.deb", names) + self.assertIn("orchestrator-4.30.1-rc2-linux-amd64.tar.gz", names) + + def test_missing_architecture_is_rejected(self): + self.populate(arch="amd64") + with self.assertRaises(self.release.ReleaseError): + self.release.check_packages(self.directory, "v4.32.0") + + def test_unexpected_file_is_rejected(self): + self.populate() + (self.directory / "other.rpm").write_bytes(b"unrelated release") + with self.assertRaises(self.release.ReleaseError): + self.release.check_packages(self.directory, "v4.32.0") + + def test_symlink_package_is_rejected(self): + self.populate() + target = self.directory / "orchestrator-4.32.0-1.x86_64.rpm" + target.unlink() + target.symlink_to("orchestrator-4.32.0-1.aarch64.rpm") + with self.assertRaises(self.release.ReleaseError): + self.release.check_packages(self.directory, "v4.32.0") + + def test_empty_package_is_rejected(self): + self.populate() + (self.directory / "orchestrator-4.32.0-1.x86_64.rpm").write_bytes(b"") + with self.assertRaises(self.release.ReleaseError): + self.release.check_packages(self.directory, "v4.32.0") + + def test_unsafe_tag_is_rejected(self): + for tag in ("../v4.32.0", "--help", "v4.32.0/evil", "v4.32.0\n"): + with self.assertRaises(self.release.ReleaseError): + self.release.expected_names(tag) + + + +class BundleTests(ReleaseTestCase): + def test_recorded_successful_attempt_remains_usable_after_later_rerun(self): + directory, record = self.bundle() + original = {"id": 123, "run_attempt": 1, "event": "push", "head_branch": "v4.32.0", + "head_sha": "a" * 40, "path": ".github/workflows/release.yml", + "status": "completed", "conclusion": "success", "repository": {"full_name": "ProxySQL/orchestrator"}} + responses = {"commits/v4.32.0": {"sha": "a" * 40}, + "actions/runs/123": dict(original, run_attempt=2, conclusion="failure"), + "actions/runs/123/attempts/1": original} + with patch.object(self.release, "api", side_effect=lambda repo, path: responses[path]): + self.release.check_source(record) + + def test_original_checksums_are_required(self): + directory, record = self.bundle() + self.assertEqual(self.release.load_bundle(directory), record) + (directory / "unsigned" / "orchestrator_4.32.0_amd64.deb").write_bytes(b"changed") + with self.assertRaises(self.release.ReleaseError): + self.release.load_bundle(directory) + + def test_unsigned_manifest_must_cover_exact_inventory(self): + directory, _ = self.bundle() + (directory / "UNSIGNED-SHA256SUMS").write_text("partial inventory") + with self.assertRaises(self.release.ReleaseError): + self.release.load_bundle(directory) + + def test_draft_lookup_resolves_cli_id_before_rest_request(self): + directory, record = self.bundle() + with patch.object(self.release, "run", return_value='{"databaseId": 100}') as command, patch.object(self.release, "api", return_value=record["release"]) as api: + meta = self.release.release_metadata("ProxySQL/orchestrator", "v4.32.0") + self.assertTrue(meta["draft"]) + self.assertEqual(command.call_args.args[0][:4], ["gh", "release", "view", "v4.32.0"]) + api.assert_called_once_with("ProxySQL/orchestrator", "releases/100") + + def test_prepare_downloads_one_complete_draft_with_matching_successful_run(self): + directory, record = self.bundle() + target = self.directory / "prepared" + run = {"id": 123, "run_attempt": 1, "event": "push", "head_branch": "v4.32.0", + "head_sha": "a" * 40, "path": ".github/workflows/release.yml", + "status": "completed", "conclusion": "success", "repository": {"full_name": "ProxySQL/orchestrator"}} + responses = {"releases/tags/v4.32.0": record["release"], "commits/v4.32.0": {"sha": "a" * 40}, + "actions/runs/123/attempts/1": run} + def download(repo, tag, dest): + shutil.copytree(directory / "unsigned", dest) + with patch.object(self.release, "api", side_effect=lambda repo, path: responses[path]), patch.object(self.release, "release_metadata", return_value=record["release"]), patch.object(self.release, "download", side_effect=download): + self.release.prepare("v4.32.0", target, "ProxySQL/orchestrator") + self.assertEqual(self.release.load_bundle(target)["build"], record["build"]) + + def test_prepare_rejects_published_release(self): + directory, record = self.bundle() + record["release"]["draft"] = False + with patch.object(self.release, "release_metadata", return_value=record["release"]), patch.object(self.release, "download") as download: + with self.assertRaises(self.release.ReleaseError): + self.release.prepare("v4.32.0", self.directory / "prepared", "ProxySQL/orchestrator") + download.assert_not_called() + + def test_prepare_rejects_reused_directory(self): + with self.assertRaises(self.release.ReleaseError): + self.release.prepare("v4.32.0", self.directory, "ProxySQL/orchestrator") + + def test_changed_draft_identity_is_rejected(self): + directory, record = self.bundle() + for field, value in (("id", 101), ("draft", False), ("prerelease", True), ("target_commitish", "b" * 40)): + meta = dict(record["release"], **{field: value}) + with self.subTest(field=field), self.assertRaises(self.release.ReleaseError): + self.release.require_draft(record, meta) + + def test_upload_cannot_publish_and_refuses_changed_release(self): + directory, record = self.bundle() + changed = dict(record["release"], id=101) + with patch.object(self.release, "verify", return_value={}), patch.object(self.release, "release_metadata", return_value=changed), patch.object(self.release, "run") as run: + with self.assertRaises(self.release.ReleaseError): + self.release.upload(directory) + run.assert_not_called() + + def test_publication_requires_verified_remote_assets(self): + directory, _ = self.bundle() + self.release.write_json(directory / "uploaded.json", {"release_id": 100, "sha256": {}}) + with patch.object(self.release, "verify_remote", side_effect=self.release.ReleaseError("invalid signature")) as remote, patch.object(self.release, "run") as run: + with self.assertRaises(self.release.ReleaseError): + self.release.publish(directory) + remote.assert_called_once() + run.assert_not_called() + + +CRYPTO_TOOLS = ("gpg", "rpm", "rpmkeys", "rpmbuild", "rpmsign") + + +@unittest.skipUnless(all(shutil.which(tool) for tool in CRYPTO_TOOLS), "requires GnuPG and RPM build/sign tools") +class CryptoTests(ReleaseTestCase): + @classmethod + def setUpClass(cls): + cls.crypto = tempfile.TemporaryDirectory() + root = pathlib.Path(cls.crypto.name) + cls.home = root / "gnupg" + cls.home.mkdir(mode=0o700) + gpg = ["gpg", "--homedir", str(cls.home), "--batch", "--pinentry-mode", "loopback", "--passphrase", ""] + subprocess.run(gpg + ["--quick-gen-key", "Release test ", "rsa2048", "sign", "0"], check=True, capture_output=True) + listing = subprocess.check_output(gpg + ["--with-colons", "--list-keys"], text=True) + cls.fingerprint = next(line.split(":")[9] for line in listing.splitlines() if line.startswith("fpr:")) + cls.public_key = root / "key.asc" + cls.public_key.write_bytes(subprocess.check_output(gpg + ["--armor", "--export", cls.fingerprint])) + cls.rpms = [] + top = root / "rpm" + for marker in ("original", "different"): + spec = root / (marker + ".spec") + spec.write_text("Name: release-test\nVersion: 1\nRelease: 1\nSummary: Signing integration fixture\nLicense: Apache-2.0\nBuildArch: noarch\n%description\nTemporary test fixture.\n%install\nmkdir -p %{buildroot}/usr/share/release-test\nprintf " + marker + " > %{buildroot}/usr/share/release-test/marker\n%files\n/usr/share/release-test/marker\n") + subprocess.run(["rpmbuild", "--define", "_topdir " + str(top), "-bb", str(spec)], check=True, capture_output=True) + rpm = root / (marker + ".rpm") + shutil.copyfile(next((top / "RPMS").rglob("*.rpm")), rpm) + cls.rpms.append(rpm) + + @classmethod + def tearDownClass(cls): + subprocess.run(["gpgconf", "--homedir", str(cls.home), "--kill", "gpg-agent"], capture_output=True) + cls.crypto.cleanup() + + def setUp(self): + super().setUp() + self.release.KEY = self.fingerprint + self.env = patch.dict(os.environ, {"GNUPGHOME": str(self.home)}) + self.env.start() + self.addCleanup(self.env.stop) + path = ROOT / "script/sign-release.py" + self.assertTrue(path.exists(), "server-side signing command is missing") + spec = importlib.util.spec_from_file_location("sign_release", path) + self.signer = importlib.util.module_from_spec(spec) + spec.loader.exec_module(self.signer) + + def signed_bundle(self, tag="v4.32.0"): + directory, _ = self.bundle(self.rpms[0], tag) + output = self.signer.sign(directory) + return directory, pathlib.Path(output) + + def resign_manifest(self, signed): + names = self.release.expected_names("v4.32.0") | {self.release.BUILD_INFO} + (signed / "SHA256SUMS").write_text(self.release.checksum_text(self.release.file_hashes(signed, names))) + self.gpg_manifest(signed) + + def gpg_manifest(self, signed): + subprocess.run(["gpg", "--batch", "--yes", "--local-user", self.fingerprint, "--digest-algo", "SHA256", "--armor", "--detach-sign", "--output", str(signed / "SHA256SUMS.asc"), str(signed / "SHA256SUMS")], check=True, capture_output=True) + + def test_real_signing_and_isolated_verification(self): + directory, signed = self.signed_bundle() + hashes = self.release.verify(directory, signed, self.public_key) + self.assertEqual(len(hashes), 17) + self.assertNotEqual(self.release.sha256(signed / "orchestrator-4.32.0-1.x86_64.rpm"), self.release.sha256(directory / "unsigned/orchestrator-4.32.0-1.x86_64.rpm")) + + def test_changed_deb_with_valid_manifest_signature_is_rejected(self): + directory, signed = self.signed_bundle() + (signed / "orchestrator_4.32.0_amd64.deb").write_bytes(b"changed by signer") + self.resign_manifest(signed) + with self.assertRaises(self.release.ReleaseError): + self.release.verify(directory, signed, self.public_key) + + def test_unsigned_rpm_with_valid_manifest_is_rejected(self): + directory, signed = self.signed_bundle() + name = "orchestrator-4.32.0-1.x86_64.rpm" + shutil.copyfile(directory / "unsigned" / name, signed / name) + self.resign_manifest(signed) + with self.assertRaisesRegex(self.release.ReleaseError, "signature"): + self.release.verify(directory, signed, self.public_key) + + def test_changed_rpm_payload_with_valid_signatures_is_rejected(self): + directory, signed = self.signed_bundle() + target = signed / "orchestrator-4.32.0-1.x86_64.rpm" + shutil.copyfile(self.rpms[1], target) + # Pass __gpg explicitly like sign-release.py: some distributions default it to a missing gpg2. + subprocess.run(["rpmsign", "--define", "__gpg " + shutil.which("gpg"), "--define", "_gpg_name " + self.fingerprint, + "--define", "_openpgp_sign_id " + self.fingerprint, "--define", "_gpg_digest_algo sha256", + "--addsign", str(target)], check=True, capture_output=True) + self.resign_manifest(signed) + with self.assertRaisesRegex(self.release.ReleaseError, "header|payload"): + self.release.verify(directory, signed, self.public_key) + + def test_incomplete_signed_manifest_is_rejected(self): + directory, signed = self.signed_bundle() + sums = signed / "SHA256SUMS" + sums.write_text("".join(sums.read_text().splitlines(keepends=True)[1:])) + self.gpg_manifest(signed) + with self.assertRaises(self.release.ReleaseError): + self.release.verify(directory, signed, self.public_key) + + def test_unapproved_full_fingerprint_is_rejected(self): + directory, signed = self.signed_bundle() + self.release.KEY = "0" * 40 + with self.assertRaisesRegex(self.release.ReleaseError, "fingerprint"): + self.release.verify(directory, signed, self.public_key) + + + def remote_api(self, record, state): + def api(repo, path): + self.assertEqual(repo, record["repository"]) + if path.startswith("releases/tags/"): + return json.loads(json.dumps(state)) + if path.startswith("commits/"): + return {"sha": record["build"]["commit"]} + self.assertEqual(path, "actions/runs/123/attempts/1") + return {"id": 123, "run_attempt": 1, "event": "push", "head_branch": record["build"]["tag"], + "head_sha": record["build"]["commit"], "path": ".github/workflows/release.yml", + "status": "completed", "conclusion": "success", "repository": {"full_name": repo}} + return api + + def remote_assets(self, record, signed): + old = {a["name"]: a for a in record["release"]["assets"]} + return [{"id": old[p.name]["id"] if p.name in old else 1000 + i, + "name": p.name, "size": p.stat().st_size, + "digest": "sha256:" + self.release.sha256(p), "download_count": 0} + for i, p in enumerate(sorted(signed.iterdir()))] + + def test_remote_verification_allows_download_counter_updates(self): + directory, signed = self.signed_bundle() + record = self.release.load_bundle(directory) + state = dict(record["release"], assets=self.remote_assets(record, signed)) + def download(repo, tag, dest): + shutil.copytree(signed, dest) + for asset in state["assets"]: + asset["download_count"] += 1 + with patch.object(self.release, "api", side_effect=self.remote_api(record, state)), patch.object(self.release, "release_metadata", side_effect=lambda repo, tag: json.loads(json.dumps(state))), patch.object(self.release, "download", side_effect=download): + hashes = self.release.verify_remote(directory, self.public_key) + self.assertEqual(len(hashes), 17) + + def test_partial_upload_resumes_without_publishing_then_explicit_publish_preserves_rc(self): + directory, signed = self.signed_bundle("v4.32.0-rc1") + record = self.release.load_bundle(directory) + complete = self.remote_assets(record, signed) + state = json.loads(json.dumps(record["release"])) + missing = "orchestrator-4.32.0_rc1-1.x86_64.rpm" + state["assets"] = [a for a in state["assets"] if a["name"] != missing] + commands = [] + original_run = self.release.run + def run(args, **kwargs): + if args[0] != "gh": + return original_run(args, **kwargs) + commands.append([str(a) for a in args]) + if args[2] == "upload": + names = {pathlib.Path(p).name for p in args[7:]} + by_name = {a["name"]: a for a in state["assets"]} + by_name.update({a["name"]: a for a in complete if a["name"] in names}) + state["assets"] = list(by_name.values()) + else: + self.assertEqual(args[2], "edit") + self.assertIn("--draft=false", args) + state["draft"] = False + return "" + def download(repo, tag, dest): + shutil.copytree(signed, dest) + with patch.object(self.release, "api", side_effect=self.remote_api(record, state)), patch.object(self.release, "release_metadata", side_effect=lambda repo, tag: json.loads(json.dumps(state))), patch.object(self.release, "download", side_effect=download), patch.object(self.release, "run", side_effect=run): + hashes = self.release.upload(directory, signed, self.public_key) + self.assertTrue(state["draft"]) + self.assertEqual(len(hashes), 17) + self.assertTrue(all(command[2] == "upload" for command in commands)) + self.release.publish(directory, self.public_key) + self.assertFalse(state["draft"]) + self.assertTrue(state["prerelease"]) + self.assertEqual(sum(command[2] == "edit" for command in commands), 1) + self.assertTrue((directory / "uploaded.json").is_file()) + + def test_manifest_signed_by_another_key_is_rejected(self): + directory, signed = self.signed_bundle() + subprocess.run(["gpg", "--batch", "--pinentry-mode", "loopback", "--passphrase", "", "--quick-gen-key", "Wrong signing key ", "rsa2048", "sign", "0"], check=True, capture_output=True) + listing = subprocess.check_output(["gpg", "--batch", "--with-colons", "--list-keys", "wrong@example.invalid"], text=True) + wrong = next(line.split(":")[9] for line in listing.splitlines() if line.startswith("fpr:")) + subprocess.run(["gpg", "--batch", "--yes", "--local-user", wrong, "--digest-algo", "SHA256", "--armor", "--detach-sign", "--output", str(signed / "SHA256SUMS.asc"), str(signed / "SHA256SUMS")], check=True, capture_output=True) + with self.assertRaises(self.release.ReleaseError): + self.release.verify(directory, signed, self.public_key) + + def test_signing_refuses_changed_original_inventory(self): + directory, _ = self.bundle(self.rpms[0]) + (directory / "unsigned/orchestrator_4.32.0_amd64.deb").write_bytes(b"changed original") + with self.assertRaises(self.release.ReleaseError): + self.signer.sign(directory) + self.assertFalse((directory / "signed").exists()) + + + def test_signing_output_cannot_be_inside_original_inventory(self): + directory, record = self.bundle(self.rpms[0]) + output = directory / "unsigned" / "nested-output" + with self.assertRaises(self.release.ReleaseError): + self.signer.sign(directory, output=output) + self.assertFalse(output.exists()) + self.assertEqual(self.release.load_bundle(directory), record) + + + def test_upload_recovers_starter_rpm_and_checksum_assets(self): + directory, signed = self.signed_bundle() + record = self.release.load_bundle(directory) + complete = self.remote_assets(record, signed) + state = json.loads(json.dumps(record["release"])) + name = "orchestrator-4.32.0-1.x86_64.rpm" + for asset in state["assets"]: + if asset["name"] == name: + asset.update(state="starter", size=0, digest=None) + state["assets"].append({"id": 3000, "name": "SHA256SUMS", "state": "starter", "size": 0, "digest": None}) + original_run = self.release.run + commands = [] + def run(args, **kwargs): + if args[0] != "gh": + return original_run(args, **kwargs) + commands.append([str(a) for a in args]) + self.assertEqual(args[2], "upload") + names = {pathlib.Path(p).name for p in args[7:]} + by_name = {a["name"]: a for a in state["assets"]} + by_name.update({a["name"]: a for a in complete if a["name"] in names}) + state["assets"] = list(by_name.values()) + return "" + with patch.object(self.release, "api", side_effect=self.remote_api(record, state)), patch.object(self.release, "release_metadata", side_effect=lambda repo, tag: json.loads(json.dumps(state))), patch.object(self.release, "download", side_effect=lambda repo, tag, dest: shutil.copytree(signed, dest)), patch.object(self.release, "run", side_effect=run): + self.assertEqual(len(self.release.upload(directory, signed, self.public_key)), 17) + self.assertTrue(state["draft"]) + self.assertTrue(any(any(pathlib.Path(arg).name == name for arg in command[7:]) for command in commands)) + self.assertTrue((directory / "uploaded.json").exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/release/test_workflow.py b/tests/release/test_workflow.py new file mode 100644 index 000000000..40993597f --- /dev/null +++ b/tests/release/test_workflow.py @@ -0,0 +1,65 @@ +"""Execute the actual draft-creation shell step against a fake GitHub CLI.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +class DraftCreationTests(unittest.TestCase): + def execute(self, tags="", fail_api=False, prerelease=False): + text = (ROOT / ".github/workflows/release.yml").read_text() + lines = text[text.index(" - name: Create draft for manual signing\n"):].splitlines() + start = lines.index(" run: |") + 1 + body = [] + for line in lines[start:]: + if line and not line.startswith(" "): + break + body.append(line[8:] if line else "") + with tempfile.TemporaryDirectory() as scratch: + root = Path(scratch) + command = root / "gh" + command.write_text('''#!/usr/bin/env python3 +import json, os, sys +with open(os.environ["TEST_GH_LOG"], "a") as out: + out.write(json.dumps(sys.argv[1:]) + "\\n") +if sys.argv[1] == "api": + if os.environ["TEST_GH_FAIL"] == "true": + sys.exit(7) + print(os.environ["TEST_GH_TAGS"]) +''') + command.chmod(0o755) + log = root / "commands.jsonl" + env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], + TAG_NAME="v4.32.0", GITHUB_REPOSITORY="ProxySQL/orchestrator", GITHUB_SHA="a" * 40, + PRERELEASE=str(prerelease).lower(), TEST_GH_LOG=str(log), TEST_GH_TAGS=tags, + TEST_GH_FAIL=str(fail_api).lower()) + result = subprocess.run(["bash", "-e", "-o", "pipefail", "-c", "\n".join(body)], + cwd=root, env=env, capture_output=True, text=True) + commands = [json.loads(line) for line in log.read_text().splitlines()] + return result, commands + + def test_existing_release_prevents_draft_creation(self): + result, commands = self.execute(tags="v4.31.1\nv4.32.0") + self.assertNotEqual(result.returncode, 0) + self.assertFalse(any(command[:2] == ["release", "create"] for command in commands)) + + def test_api_failure_cannot_bypass_existing_release_check(self): + result, commands = self.execute(fail_api=True) + self.assertNotEqual(result.returncode, 0) + self.assertFalse(any(command[:2] == ["release", "create"] for command in commands)) + + def test_new_tag_creates_one_draft_and_preserves_prerelease(self): + result, commands = self.execute(tags="v4.31.1", prerelease=True) + self.assertEqual(result.returncode, 0, result.stderr) + create = [command for command in commands if command[:2] == ["release", "create"]] + self.assertEqual(len(create), 1) + self.assertIn("--draft", create[0]) + self.assertIn("--prerelease", create[0]) + + +if __name__ == "__main__": + unittest.main()