diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..9cd34e5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,26 @@ +name: Checks +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + workflow_call: +permissions: + contents: read +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +jobs: + check: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - run: rustup show active-toolchain + - run: python3 -m unittest discover -s scripts -p 'test_*.py' + - run: cargo fmt --check + - run: cargo clippy --locked --all-targets -- -D warnings + - run: cargo test --locked + - run: cargo install cargo-deny --locked --version 0.20.2 && cargo deny check diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..c1afe2b --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,120 @@ +name: Release +on: + push: + tags: ['v*'] + workflow_dispatch: + inputs: + publish: + description: Publish the checked CLI version + type: boolean + default: false +permissions: + contents: read +concurrency: + group: release + cancel-in-progress: false +jobs: + check: + uses: ./.github/workflows/ci.yml + version: + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + - id: version + run: python3 scripts/release-version.py + build: + needs: [check, version] + strategy: + fail-fast: false + matrix: + include: + - runner: ubuntu-24.04 + target: x86_64-unknown-linux-musl + - runner: ubuntu-24.04-arm + target: aarch64-unknown-linux-musl + - runner: macos-15-intel + target: x86_64-apple-darwin + - runner: macos-15 + target: aarch64-apple-darwin + runs-on: ${{ matrix.runner }} + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install --no-install-recommends --yes musl-tools + - env: + TARGET: ${{ matrix.target }} + CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_LINKER: musl-gcc + CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER: musl-gcc + CC_x86_64_unknown_linux_musl: musl-gcc + CC_aarch64_unknown_linux_musl: musl-gcc + run: | + rustup target add "$TARGET" + cargo build --release --locked --target "$TARGET" + - env: + TARGET: ${{ matrix.target }} + VERSION: ${{ needs.version.outputs.version }} + run: | + test "$(target/"$TARGET"/release/proofline --version)" = "proofline $VERSION" + python3 scripts/archive.py "$TARGET" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: cli-${{ matrix.target }} + path: artifacts/*.tar.gz + if-no-files-found: error + publish: + if: github.event_name == 'push' || inputs.publish + needs: [version, build] + runs-on: ubuntu-24.04 + timeout-minutes: 15 + environment: release + permissions: + contents: write + id-token: write + attestations: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: cli-* + merge-multiple: true + path: artifacts + - env: + VERSION: ${{ needs.version.outputs.version }} + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + test "$(find artifacts -name '*.tar.gz' | wc -l)" -eq 4 + (cd artifacts && LC_ALL=C sha256sum proofline-*.tar.gz > SHA256SUMS) + printf '%s\n' "$VERSION" > artifacts/latest + # Creating the draft reserves the GitHub version atomically. + gh release create "v$VERSION" --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --draft --title "Proofline $VERSION" --generate-notes + - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-path: artifacts/*.tar.gz + - env: + VERSION: ${{ needs.version.outputs.version }} + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} + CLI_RELEASE_R2_CREDENTIALS: ${{ secrets.CLI_RELEASE_R2_CREDENTIALS }} + run: scripts/publish-r2.sh "$VERSION" artifacts + - env: + VERSION: ${{ needs.version.outputs.version }} + GH_TOKEN: ${{ github.token }} + run: | + gh release upload "v$VERSION" artifacts/* --repo "$GITHUB_REPOSITORY" + gh release edit "v$VERSION" --repo "$GITHUB_REPOSITORY" --draft=false --latest + for archive in artifacts/*.tar.gz; do + name=$(basename "$archive") + curl --proto '=https' --tlsv1.2 --fail --silent --show-error --location "https://proofline.sh/cli/download/$VERSION/$name" -o "/tmp/$name" + cmp "$archive" "/tmp/$name" + done diff --git a/README.md b/README.md index 9c99bdd..0f9fc26 100644 --- a/README.md +++ b/README.md @@ -13,3 +13,18 @@ is installed by rustup. Run `cargo fmt --check`, `cargo clippy --locked --all-ta Server compatibility is checked in the Proofline control plane. Licensed under Apache-2.0. + +## Publishing + +GitHub Actions checks pull requests and main. Run `Release` on main with +`publish=false` to build all four Linux/macOS archives without publishing. +A `vX.Y.Z` tag equal to Cargo's version, or a main dispatch with `publish=true`, +publishes after the `release` environment approves the job. The commit must be on main. + +The build jobs have no write credential. The publisher creates a GitHub draft +to reserve the version, records artifact attestations, and uploads the binaries +and SHA256SUMS to the existing R2 download bucket and GitHub Releases. +The bucket-scoped credential is the `CLI_RELEASE_R2_CREDENTIALS` environment secret; +`CLOUDFLARE_ACCOUNT_ID` is an environment variable. R2 versions are reserved +with a conditional write. A failed publication retains its reservation; raise +the package version before another release. Install and update URLs stay on proofline.sh. diff --git a/scripts/archive.py b/scripts/archive.py new file mode 100644 index 0000000..780b16f --- /dev/null +++ b/scripts/archive.py @@ -0,0 +1,19 @@ +"""Package one checked CLI binary with deterministic archive metadata.""" +import gzip +import io +from pathlib import Path +import sys +import tarfile + +target = sys.argv[1] +source = Path("target") / target / "release/proofline" +data = source.read_bytes() +Path("artifacts").mkdir(exist_ok=True) +with Path(f"artifacts/proofline-{target}.tar.gz").open("wb") as output: + with gzip.GzipFile(filename="", fileobj=output, mode="wb", mtime=0) as compressed: + with tarfile.open(fileobj=compressed, mode="w") as archive: + entry = tarfile.TarInfo("proofline") + entry.size = len(data) + entry.mode = 0o755 + entry.mtime = 0 + archive.addfile(entry, io.BytesIO(data)) diff --git a/scripts/publish-r2.sh b/scripts/publish-r2.sh new file mode 100755 index 0000000..978c3d2 --- /dev/null +++ b/scripts/publish-r2.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +# Upload the reserved CLI version through R2's bucket-scoped S3 API. +# Credentials arrive only in the publish step and travel to curl on stdin. +set -euo pipefail + +version=${1:-} +dist=${2:-} +refuse() { printf 'cli publish: %s\n' "$*" >&2; exit 1; } +[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || refuse 'expected an x.y.z version' +[ -d "$dist" ] || refuse 'the release directory is missing' +: "${CLOUDFLARE_ACCOUNT_ID:?the Cloudflare account is required}" +: "${CLI_RELEASE_R2_CREDENTIALS:?the bucket-scoped S3 credentials are required}" +[[ "$CLOUDFLARE_ACCOUNT_ID" =~ ^[0-9a-f]{32}$ ]] || refuse 'invalid Cloudflare account ID' +access_key=$(printf '%s' "$CLI_RELEASE_R2_CREDENTIALS" | jq -er '.access_key_id') +secret_key=$(printf '%s' "$CLI_RELEASE_R2_CREDENTIALS" | jq -er '.secret_access_key') +[[ "$access_key" =~ ^[0-9a-f]{32}$ ]] || refuse 'invalid R2 access key ID' +[[ "$secret_key" =~ ^[0-9a-f]{64}$ ]] || refuse 'invalid R2 secret access key' +unset CLI_RELEASE_R2_CREDENTIALS + +temporary=$(mktemp -d) +trap 'rm -rf "$temporary"' EXIT +targets='aarch64-apple-darwin aarch64-unknown-linux-musl x86_64-apple-darwin x86_64-unknown-linux-musl' +# Verify every archive before the first upload. The manifest names exactly +# the four files the installer can download, with their actual digests. +for target in $targets; do + archive="proofline-$target.tar.gz" + [ -f "$dist/$archive" ] || refuse "missing $archive" + digest=$(sha256sum "$dist/$archive" | cut -d ' ' -f 1) + printf '%s %s\n' "$digest" "$archive" >> "$temporary/SHA256SUMS" +done +cmp -s "$temporary/SHA256SUMS" "$dist/SHA256SUMS" || refuse 'SHA256SUMS does not match the four release archives' + +put() { + local key=$1 source=$2 content_type=$3 cache_control=$4 condition=${5:-} digest + digest=$(sha256sum "$source" | cut -d ' ' -f 1) + # Object Read & Write tokens support the S3 API only. curl signs the exact + # payload and metadata; credentials stay out of command arguments and logs. + printf 'user = "%s:%s"\n' "$access_key" "$secret_key" | + curl --config - --aws-sigv4 'aws:amz:auto:s3' \ + --proto '=https' --tlsv1.2 --fail --silent --show-error \ + --connect-timeout 15 --max-time 120 --retry 2 \ + --request PUT --upload-file "$source" \ + --header "Content-Type: $content_type" \ + --header "Cache-Control: $cache_control" \ + --header "x-amz-content-sha256: $digest" \ + --header "If-None-Match: $condition" \ + "https://$CLOUDFLARE_ACCOUNT_ID.r2.cloudflarestorage.com/proofline-cli-releases/$key" +} + +# Old releases predate R2 reservations. Refuse those too, and never replace +# latest with an older version. An unavailable origin is not an empty registry. +status=$(curl --proto '=https' --tlsv1.2 --silent --show-error --location \ + --connect-timeout 15 --max-time 30 --output "$temporary/probe" --write-out '%{http_code}' \ + "https://proofline.sh/cli/download/$version/SHA256SUMS") +[ "$status" = 404 ] || refuse "version $version is already published or its status is unavailable ($status)" +status=$(curl --proto '=https' --tlsv1.2 --silent --show-error --location \ + --connect-timeout 15 --max-time 30 --output "$temporary/latest" --write-out '%{http_code}' \ + 'https://proofline.sh/cli/latest') +case "$status" in + 200) + latest=$(cat "$temporary/latest") + [[ "$latest" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || refuse 'latest is not a version' + [ "$latest" != "$version" ] && [ "$(printf '%s\n%s\n' "$latest" "$version" | sort -V | tail -1)" = "$version" ] \ + || refuse "$version is not newer than $latest" + ;; + 404) ;; + *) refuse "could not read latest ($status)" ;; +esac + +# Reserve the version before any release object is written. A failed upload +# retains the claim, so another run cannot overwrite a partial publication. +printf '{"version":"%s","commit":"%s"}\n' "$version" "${GITHUB_SHA:?missing release commit}" > "$temporary/reservation.json" +put "$version/RELEASE.json" "$temporary/reservation.json" application/json 'public, max-age=31536000, immutable' '*' +immutable='public, max-age=31536000, immutable' +for target in $targets; do + archive="proofline-$target.tar.gz" + put "$version/$archive" "$dist/$archive" application/gzip "$immutable" +done +put "$version/SHA256SUMS" "$dist/SHA256SUMS" 'text/plain; charset=utf-8' "$immutable" +# Installers see the version only after all five release objects exist. +printf '%s\n' "$version" > "$temporary/latest" +put latest "$temporary/latest" 'text/plain; charset=utf-8' 'public, max-age=60' +printf 'cli publish: uploaded CLI %s\n' "$version" diff --git a/scripts/release-version.py b/scripts/release-version.py new file mode 100644 index 0000000..552e7f2 --- /dev/null +++ b/scripts/release-version.py @@ -0,0 +1,18 @@ +"""Admit a release only at its package version and a commit on main.""" +import os +from pathlib import Path +import re +import subprocess +import tomllib + +version = tomllib.loads(Path("Cargo.toml").read_text())["package"]["version"] +if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version): + raise SystemExit("package version must be x.y.z") +ref = os.environ["GITHUB_REF"] +if ref not in ("refs/heads/main", f"refs/tags/v{version}"): + raise SystemExit("release requires main or a tag equal to the package version") +subprocess.run(["git", "fetch", "--quiet", "origin", "main"], check=True) +subprocess.run(["git", "merge-base", "--is-ancestor", "HEAD", "origin/main"], check=True) +with Path(os.environ["GITHUB_OUTPUT"]).open("a") as output: + output.write(f"version={version}\n") +print(f"Release version: {version}") diff --git a/scripts/test_publish_r2.py b/scripts/test_publish_r2.py new file mode 100644 index 0000000..4310880 --- /dev/null +++ b/scripts/test_publish_r2.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""Verify real curl S3 signatures and release ordering against local HTTPS.""" +import hashlib +import hmac +import http.server +import json +import os +from pathlib import Path +import re +import shlex +import shutil +import ssl +import subprocess +import tempfile +import threading +import unittest + +ROOT = Path(__file__).resolve().parent.parent +ACCOUNT = "a" * 32 +HOST = f"{ACCOUNT}.r2.cloudflarestorage.com" +ACCESS = "b" * 32 +SECRET = "c" * 64 +TARGETS = sorted([ + "x86_64-unknown-linux-musl", "aarch64-unknown-linux-musl", + "x86_64-apple-darwin", "aarch64-apple-darwin", +]) + + +class PublishTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.temp = tempfile.TemporaryDirectory() + cls.base = Path(cls.temp.name) + cert = cls.base / "cert.pem" + key = cls.base / "key.pem" + subprocess.run([ + "openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", + "-keyout", str(key), "-out", str(cert), "-days", "1", + "-subj", f"/CN={HOST}", "-addext", f"subjectAltName=DNS:{HOST},DNS:proofline.sh", + ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + code = cls.probe_status if self.path.endswith("SHA256SUMS") else 200 + body = cls.latest.encode() if self.path == "/cli/latest" else b"" + self.send_response(code) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_PUT(self): + body = self.rfile.read(int(self.headers["Content-Length"])) + cls.requests.append((self.path, dict(self.headers), body)) + status = 403 if self.path == cls.reject else 200 + if self.headers.get("If-None-Match") == "*" and self.path in cls.objects: + status = 412 + if status == 200: + cls.objects.add(self.path) + self.send_response(status) + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, *_args): + pass + + cls.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(cert, key) + cls.server.socket = context.wrap_socket(cls.server.socket, server_side=True) + cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True) + cls.thread.start() + cls.fakebin = cls.base / "bin" + cls.fakebin.mkdir() + curl = shutil.which("curl") + if not curl: + raise RuntimeError("curl is required") + wrapper = cls.fakebin / "curl" + destination = f"{HOST}:443:127.0.0.1:{cls.server.server_port}" + wrapper.write_text( + f"#!/bin/sh\nexec {shlex.quote(curl)} --noproxy '*' " + f"--connect-to {shlex.quote(destination)} --connect-to proofline.sh:443:127.0.0.1:{cls.server.server_port} --cacert {shlex.quote(str(cert))} \"$@\"\n" + ) + wrapper.chmod(0o755) + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.server.server_close() + cls.thread.join() + cls.temp.cleanup() + + def setUp(self): + type(self).requests = [] + type(self).reject = None + type(self).objects = set() + type(self).probe_status = 404 + type(self).latest = "0.0.9" + self.dist = self.base / self._testMethodName + self.dist.mkdir() + self.env = os.environ.copy() + self.env.update({ + "PATH": str(self.fakebin) + os.pathsep + self.env["PATH"], + "GITHUB_SHA": "d" * 40, + "CLOUDFLARE_ACCOUNT_ID": ACCOUNT, + "CLI_RELEASE_R2_CREDENTIALS": json.dumps({ + "access_key_id": ACCESS, "secret_access_key": SECRET, + }), + }) + manifest = [] + for target in TARGETS: + name = f"proofline-{target}.tar.gz" + body = f"archive for {target}\n".encode() + (self.dist / name).write_bytes(body) + manifest.append(f"{hashlib.sha256(body).hexdigest()} {name}\n") + (self.dist / "SHA256SUMS").write_text("".join(manifest)) + + def run_publish(self, version="0.1.0"): + result = subprocess.run([ + str(ROOT / "scripts/publish-r2.sh"), version, str(self.dist), + ], env=self.env, capture_output=True, text=True, timeout=30) + self.assertNotIn(ACCESS, result.stdout + result.stderr) + self.assertNotIn(SECRET, result.stdout + result.stderr) + return result + + def test_signed_uploads_and_latest_last(self): + result = self.run_publish() + self.assertEqual(result.returncode, 0, result.stderr) + prefix = "/proofline-cli-releases/" + expected = ["0.1.0/RELEASE.json"] + [f"0.1.0/proofline-{target}.tar.gz" for target in TARGETS] + expected += ["0.1.0/SHA256SUMS", "latest"] + self.assertEqual([path for path, _, _ in self.requests], [prefix + key for key in expected]) + for path, original_headers, body in self.requests: + headers = {name.lower(): value for name, value in original_headers.items()} + payload = hashlib.sha256(body).hexdigest() + self.assertEqual(headers["x-amz-content-sha256"], payload) + match = re.fullmatch( + r"AWS4-HMAC-SHA256 Credential=([^/]+)/([0-9]+)/auto/s3/aws4_request, " + r"SignedHeaders=([^,]+), Signature=([0-9a-f]{64})", headers["authorization"], + ) + self.assertIsNotNone(match, headers["authorization"]) + access, date, signed_headers, signature = match.groups() + self.assertEqual(access, ACCESS) + canonical_headers = "".join(f"{name}:{headers[name].strip()}\n" for name in signed_headers.split(";")) + canonical = f"PUT\n{path}\n\n{canonical_headers}\n{signed_headers}\n{payload}" + scope = f"{date}/auto/s3/aws4_request" + to_sign = f"AWS4-HMAC-SHA256\n{headers['x-amz-date']}\n{scope}\n{hashlib.sha256(canonical.encode()).hexdigest()}" + signing_key = ("AWS4" + SECRET).encode() + for part in [date, "auto", "s3", "aws4_request"]: + signing_key = hmac.new(signing_key, part.encode(), hashlib.sha256).digest() + self.assertEqual(signature, hmac.new(signing_key, to_sign.encode(), hashlib.sha256).hexdigest()) + self.assertEqual(headers["host"], HOST) + self.assertEqual(headers["cache-control"], "public, max-age=60" if path.endswith("/latest") else "public, max-age=31536000, immutable") + self.assertEqual(self.requests[-1][2], b"0.1.0\n") + + def test_upload_refusal_keeps_latest_absent(self): + type(self).reject = f"/proofline-cli-releases/0.1.0/proofline-{TARGETS[1]}.tar.gz" + self.assertNotEqual(self.run_publish().returncode, 0) + self.assertEqual(len(self.requests), 3) + self.assertFalse(any(path.endswith("/latest") for path, _, _ in self.requests)) + + def test_checksum_mismatch_writes_nothing(self): + (self.dist / f"proofline-{TARGETS[-1]}.tar.gz").write_bytes(b"damaged") + self.assertNotEqual(self.run_publish().returncode, 0) + self.assertEqual(self.requests, []) + + def test_missing_archive_writes_nothing(self): + (self.dist / f"proofline-{TARGETS[-1]}.tar.gz").unlink() + self.assertNotEqual(self.run_publish().returncode, 0) + self.assertEqual(self.requests, []) + + def test_existing_or_unavailable_release_and_version_regression_refuse(self): + for status, latest in [(200, "0.0.9"), (503, "0.0.9"), (404, "1.10.0"), (404, "0.1.0")]: + with self.subTest(status=status, latest=latest): + type(self).probe_status = status + type(self).latest = latest + self.assertNotEqual(self.run_publish().returncode, 0) + self.assertEqual(self.requests, []) + + def test_reserved_version_cannot_overwrite_partial_release(self): + type(self).objects.add("/proofline-cli-releases/0.1.0/RELEASE.json") + self.assertNotEqual(self.run_publish().returncode, 0) + self.assertEqual(len(self.requests), 1) + self.assertEqual(self.requests[0][1]["If-None-Match"], "*") + + def test_invalid_credentials_and_version_write_nothing(self): + self.env["CLI_RELEASE_R2_CREDENTIALS"] = json.dumps({"access_key_id": "invalid", "secret_access_key": SECRET}) + self.assertNotEqual(self.run_publish().returncode, 0) + self.assertNotEqual(self.run_publish("../latest").returncode, 0) + self.assertEqual(self.requests, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test_release_version.py b/scripts/test_release_version.py new file mode 100644 index 0000000..618f076 --- /dev/null +++ b/scripts/test_release_version.py @@ -0,0 +1,53 @@ +"""Release admission binds a version to the ref and main's ancestry.""" + +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts/release-version.py" + + +class ReleaseAdmission(unittest.TestCase): + def test_ref_version_and_main_ancestry(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + def git(*arguments: str) -> None: + subprocess.run(["git", *arguments], cwd=root, check=True, capture_output=True) + git("init", "--quiet", "-b", "main") + git("config", "user.name", "Fixture") + git("config", "user.email", "fixture@example.com") + git("remote", "add", "origin", str(root)) + (root / 'Cargo.toml').write_text('[package]\nversion = "1.2.3"\n') + (root / "openapi.public.json").write_text(json.dumps({"info": {"version": "1.2.3"}})) + git("add", ".") + git("commit", "--quiet", "-m", "fixture") + for ref, admitted in (("refs/heads/main", True), ("refs/tags/v1.2.3", True), + ("refs/tags/v9.9.9", False), ("refs/heads/feature", False)): + with self.subTest(ref=ref): + output = root / "output" + output.unlink(missing_ok=True) + result = subprocess.run([sys.executable, str(SCRIPT)], cwd=root, + env={**os.environ, "GITHUB_REF": ref, "GITHUB_OUTPUT": str(output)}, + capture_output=True, text=True) + self.assertEqual(result.returncode == 0, admitted, result.stderr) + if admitted: + self.assertEqual(output.read_text(), "version=1.2.3\n") + else: + self.assertFalse(output.exists()) + git("checkout", "--quiet", "-b", "feature") + (root / "change").write_text("unmerged") + git("add", ".") + git("commit", "--quiet", "-m", "unmerged") + result = subprocess.run([sys.executable, str(SCRIPT)], cwd=root, + env={**os.environ, "GITHUB_REF": "refs/tags/v1.2.3", "GITHUB_OUTPUT": str(root / "rejected")}, + capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertFalse((root / "rejected").exists()) + + +if __name__ == "__main__": + unittest.main()