diff --git a/.github/workflows/build-android.yml b/.github/workflows/build-android.yml index a61902b16..54c583304 100644 --- a/.github/workflows/build-android.yml +++ b/.github/workflows/build-android.yml @@ -1,13 +1,9 @@ name: Hash Bags Android build -# Triggers: -# - push to dev/main (validate every commit) -# - PRs targeting dev/main (gate merges) -# - manual via workflow_dispatch on: - # Manual-only for now. Trigger via Actions → "Hash Bags Android build" - # → Run workflow when you want a build. workflow_dispatch runs as the - # triggering user, so secrets are always available (unlike PR triggers). + push: + tags: + - 'hash-bags-*-build*' workflow_dispatch: concurrency: @@ -20,6 +16,8 @@ defaults: jobs: build: + # Manual builds stay available. Signed tag builds require separate activation. + if: github.event_name == 'workflow_dispatch' || vars.HASH_BAGS_ANDROID_RELEASE_TAGS == 'true' runs-on: ubuntu-latest container: # Same Cake-Labs prebuilt image used for Linux. Bundles Flutter 3.41.9, @@ -44,6 +42,24 @@ jobs: git config --global user.email "ci@suchsoftware.com" git config --global user.name "Hash Bags CI" + - name: Verify the canonical release tag + if: github.event_name == 'push' + run: | + set -euo pipefail + version=$(awk '/^version:/ {print $2; exit}' pubspec_description.yaml) + expected_ref="refs/tags/hash-bags-${version%%+*}-build${version#*+}" + if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+\+[1-9][0-9]*$ || + "$GITHUB_REF" != "$expected_ref" ]]; then + echo "The Android release tag must match the committed version and build number." >&2 + exit 1 + fi + tags=$(git ls-remote https://github.com/Such-Software/hash-wallet.git "$expected_ref" "${expected_ref}^{}") + canonical=$(awk -v ref="$expected_ref" '$2==ref { direct=$1 } $2==ref "^{}" { peeled=$1 } END { print peeled ? peeled : direct }' <<< "$tags") + if [[ "$canonical" != "$GITHUB_SHA" ]]; then + echo "The canonical GitHub tag does not point to the Android build commit." >&2 + exit 1 + fi + # ---- External prebuilt deps (same approach as Linux workflow) -------- - name: Fetch prebuilt torch_dart run: | diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml index e67547b35..ebefea16d 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -322,16 +322,16 @@ jobs: # that did not happen. Release assets are the path that actually returns # bytes, and GitHub is where users are told to look. # - # Both steps skip quietly without a token, so a fork or a local runner - # does not fail a build over a credential it was never given. - name: Resolve the release tag id: reltag + env: + REQUESTED_RELEASE_TAG: ${{ github.event.inputs.release_tag }} run: | set -euo pipefail if [ "${GITHUB_REF:-}" != "${GITHUB_REF#refs/tags/}" ]; then TAG="${GITHUB_REF#refs/tags/}" else - TAG="${{ github.event.inputs.release_tag }}" + TAG="$REQUESTED_RELEASE_TAG" fi echo "tag=$TAG" >> "$GITHUB_OUTPUT" if [ -n "$TAG" ]; then echo "publishing to $TAG"; else echo "no tag; build only"; fi @@ -341,37 +341,4 @@ jobs: env: GH_TOKEN: ${{ secrets.GH_RELEASE_TOKEN }} TAG: ${{ steps.reltag.outputs.tag }} - run: | - set -euo pipefail - if [ -z "${GH_TOKEN:-}" ]; then - echo "GH_RELEASE_TOKEN not set; skipping the GitHub upload" - exit 0 - fi - REPO="Such-Software/hash-wallet" - API="https://api.github.com/repos/$REPO" - AUTH="Authorization: Bearer $GH_TOKEN" - FILE="build/linux/x64/release/Hash_Bags-x86_64.AppImage" - [ -f "$FILE" ] || { echo "no AppImage to upload"; exit 1; } - NAME="$(basename "$FILE")" - code=$(curl -sS -o rel-gh.json -w '%{http_code}' -H "$AUTH" "$API/releases/tags/$TAG" || true) - if [ "$code" != "200" ]; then - echo "no GitHub release for $TAG (HTTP $code); skipping" - exit 0 - fi - # Fail rather than skip if there is no JSON parser. An upload that - # quietly did not happen leaves a release page that looks finished - # and a user with nothing to download. - PY="" - for c in python3 python; do command -v "$c" >/dev/null && { PY="$c"; break; }; done - [ -n "$PY" ] || { echo "no python available to parse the release JSON"; exit 1; } - ID=$($PY -c 'import json;print(json.load(open("rel-gh.json"))["id"])') - # Replace a same-named asset from an earlier attempt, so a re-run does - # not leave two that differ only by which build produced them. - for oid in $($PY -c 'import json,sys;d=json.load(open("rel-gh.json"));print(" ".join(str(a["id"]) for a in d.get("assets",[]) if a["name"]==sys.argv[1]))' "$NAME"); do - curl -sS -o /dev/null -X DELETE -H "$AUTH" "$API/releases/assets/$oid" || true - done - curl -sS --fail-with-body -o /dev/null -X POST -H "$AUTH" \ - -H "Content-Type: application/octet-stream" \ - --data-binary "@$FILE" \ - "https://uploads.github.com/repos/$REPO/releases/$ID/assets?name=$NAME" - echo "uploaded $NAME to the GitHub release $TAG" + run: python3 scripts/release/publish-desktop-asset.py "$TAG" "build/linux/x64/release/Hash_Bags-x86_64.AppImage" diff --git a/.github/workflows/build-macos.yml b/.github/workflows/build-macos.yml index 84176d276..0eb0d921e 100644 --- a/.github/workflows/build-macos.yml +++ b/.github/workflows/build-macos.yml @@ -65,11 +65,10 @@ jobs: timeout-minutes: 90 env: APP_MACOS_TYPE: cakewallet - # A tag push builds both lanes and uploads; a dispatch says what it wants. - LANES: ${{ github.event.inputs.lanes || 'both' }} - # Gitea hands a dispatch boolean over as a real false, which `|| 'true'` - # would turn back into true; format() keeps it as the string 'false'. - APP_STORE_UPLOAD: ${{ github.event_name == 'workflow_dispatch' && format('{0}', github.event.inputs.app_store_upload) || 'true' }} + # Release tags produce the direct download. The Mac App Store has its own dispatch. + LANES: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.lanes || 'developer-id' }} + # Gitea passes a checkbox as a boolean. format() preserves an explicit false. + APP_STORE_UPLOAD: ${{ github.event_name == 'workflow_dispatch' && format('{0}', github.event.inputs.app_store_upload) || 'false' }} KEYCHAIN: ${{ github.workspace }}/../hashbags-macos.keychain-db LANG: en_US.UTF-8 LC_ALL: en_US.UTF-8 @@ -496,12 +495,14 @@ jobs: - name: Resolve the release tag id: reltag + env: + REQUESTED_RELEASE_TAG: ${{ github.event.inputs.release_tag }} run: | set -euo pipefail if [ "${GITHUB_REF:-}" != "${GITHUB_REF#refs/tags/}" ]; then TAG="${GITHUB_REF#refs/tags/}" else - TAG="${{ github.event.inputs.release_tag }}" + TAG="$REQUESTED_RELEASE_TAG" fi echo "tag=$TAG" >> "$GITHUB_OUTPUT" if [ -n "$TAG" ]; then echo "publishing to $TAG"; else echo "no tag; build only"; fi @@ -513,30 +514,7 @@ jobs: GH_TOKEN: ${{ secrets.GH_RELEASE_TOKEN }} TAG: ${{ steps.reltag.outputs.tag }} FILE: ${{ steps.package.outputs.zip }} - run: | - set -euo pipefail - if [ -z "${GH_TOKEN:-}" ]; then - echo "GH_RELEASE_TOKEN not set; skipping the GitHub upload" - exit 0 - fi - REPO="Such-Software/hash-wallet" - API="https://api.github.com/repos/$REPO" - AUTH="Authorization: Bearer $GH_TOKEN" - NAME="$(basename "$FILE")" - code=$(curl -sS -o rel-gh.json -w '%{http_code}' -H "$AUTH" "$API/releases/tags/$TAG" || true) - if [ "$code" != "200" ]; then - echo "no GitHub release for $TAG (HTTP $code); skipping" - exit 0 - fi - ID=$(python3 -c 'import json;print(json.load(open("rel-gh.json"))["id"])') - for oid in $(python3 -c 'import json,sys;d=json.load(open("rel-gh.json"));print(" ".join(str(a["id"]) for a in d.get("assets",[]) if a["name"]==sys.argv[1]))' "$NAME"); do - curl -sS -o /dev/null -X DELETE -H "$AUTH" "$API/releases/assets/$oid" || true - done - curl -sS --fail-with-body -o /dev/null -X POST -H "$AUTH" \ - -H "Content-Type: application/octet-stream" \ - --data-binary "@$FILE" \ - "https://uploads.github.com/repos/$REPO/releases/$ID/assets?name=$NAME" - echo "uploaded $NAME to the GitHub release $TAG" + run: python3 scripts/release/publish-desktop-asset.py "$TAG" "$FILE" - name: Clean up the keychain, profiles and API key if: always() diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index 0fc6576b7..106d0633d 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -627,15 +627,17 @@ jobs: # ---- Publish to the GitHub release ------------------------------------ # PowerShell rather than the bash used elsewhere in this file: this step # parses JSON, and git-bash here has neither python nor node guaranteed, - # while ConvertFrom-Json is native. Skips quietly without a token. + # while ConvertFrom-Json is native. - name: Resolve the release tag id: reltag + env: + REQUESTED_RELEASE_TAG: ${{ github.event.inputs.release_tag }} run: | set -euo pipefail if [ "${GITHUB_REF:-}" != "${GITHUB_REF#refs/tags/}" ]; then TAG="${GITHUB_REF#refs/tags/}" else - TAG="${{ github.event.inputs.release_tag }}" + TAG="$REQUESTED_RELEASE_TAG" fi echo "tag=$TAG" >> "$GITHUB_OUTPUT" if [ -n "$TAG" ]; then echo "publishing to $TAG"; else echo "no tag; build only"; fi @@ -648,10 +650,7 @@ jobs: TAG: ${{ steps.reltag.outputs.tag }} run: | $ErrorActionPreference = 'Stop' - if (-not $env:GH_TOKEN) { - Write-Host 'GH_RELEASE_TOKEN not set; skipping the GitHub upload' - exit 0 - } + if (-not $env:GH_TOKEN) { throw 'GH_RELEASE_TOKEN is missing' } $repo = 'Such-Software/hash-wallet' $api = "https://api.github.com/repos/$repo" $hdr = @{ Authorization = "Bearer $env:GH_TOKEN"; 'User-Agent' = 'hash-bags-ci' } @@ -660,18 +659,43 @@ jobs: # Named for the tag, not the commit: a release asset called # HashBags-windows-<40 hex>.zip tells a downloader nothing. $name = "HashBags-windows-$env:TAG.zip" - try { - $rel = Invoke-RestMethod -Headers $hdr -Uri "$api/releases/tags/$env:TAG" - } catch { - Write-Host "no GitHub release for $env:TAG; skipping" + $page = 1 + do { + $releases = Invoke-RestMethod -Headers $hdr -Uri "$api/releases?per_page=100&page=$page" + $rel = $releases | Where-Object { $_.tag_name -ceq $env:TAG } | Select-Object -First 1 + $page++ + } while (-not $rel -and $releases.Count -eq 100) + if (-not $rel) { throw "GitHub release $env:TAG does not exist" } + + if ($env:GITHUB_EVENT_NAME -eq 'push') { + $ref = "refs/tags/$env:TAG" + $peeledRef = $ref + '^{}' + $tagRefs = @(git ls-remote "https://github.com/$repo.git" $ref $peeledRef) + if ($LASTEXITCODE -ne 0) { throw 'Could not read the GitHub release tag' } + $tagSha = $tagRefs | Where-Object { $_.EndsWith("`t$peeledRef") } | Select-Object -First 1 + if (-not $tagSha) { + $tagSha = $tagRefs | Where-Object { $_.EndsWith("`t$ref") } | Select-Object -First 1 + } + if (-not $tagSha -or ($tagSha -split "`t")[0] -cne $env:GITHUB_SHA) { + throw "GitHub tag $env:TAG does not point to the build commit" + } + if (-not $rel.draft) { throw 'Tag builds may only attach assets to a draft release' } + } + + $digest = 'sha256:' + (Get-FileHash -Algorithm SHA256 -LiteralPath $src.FullName).Hash.ToLowerInvariant() + $asset = $rel.assets | Where-Object { $_.name -ceq $name } | Select-Object -First 1 + if ($asset) { + if ($asset.state -ne 'uploaded' -or $asset.digest -cne $digest) { + throw "GitHub already has a different or incomplete asset named $name" + } + Write-Host "$name is already uploaded with the expected digest" exit 0 } - # Replace a same-named asset from an earlier attempt, so a re-run does - # not leave two that differ only by which build produced them. - foreach ($a in @($rel.assets | Where-Object { $_.name -eq $name })) { - Invoke-RestMethod -Headers $hdr -Method Delete -Uri "$api/releases/assets/$($a.id)" | Out-Null + $encodedName = [uri]::EscapeDataString($name) + $up = "https://uploads.github.com/repos/$repo/releases/$($rel.id)/assets?name=$encodedName" + $uploaded = Invoke-RestMethod -Headers $hdr -Method Post -ContentType 'application/octet-stream' ` + -InFile $src.FullName -Uri $up + if ($uploaded.state -ne 'uploaded' -or $uploaded.digest -cne $digest) { + throw "GitHub did not confirm the expected digest for $name" } - $up = "https://uploads.github.com/repos/$repo/releases/$($rel.id)/assets?name=$name" - Invoke-RestMethod -Headers $hdr -Method Post -ContentType 'application/octet-stream' ` - -InFile $src.FullName -Uri $up | Out-Null Write-Host "uploaded $name to the GitHub release $env:TAG" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 06216ea3e..827075df4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -30,6 +30,9 @@ jobs: run: echo "HOME=/root" >> $GITHUB_ENV - uses: actions/checkout@v4 + + - name: Test desktop release tooling + run: PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s scripts/release with: fetch-depth: 1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 32fe5020f..1bc255b86 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -69,6 +69,28 @@ Open an issue at https://github.com/Such-Software/hash-wallet/issues. Please inc - Terminal output if you built and ran from a terminal — many error popups don't print to stderr; check `/error.txt` (typically `~/.config/hash_wallet/error.txt` on Linux). - Whether the bug also reproduces in the latest Cake Wallet build (so we know whether it's a Cake-upstream bug or a Hash Bags regression). +## Desktop releases + +From a checkout with the canonical GitHub and Gitea Builds remotes, use the exact +reviewed commit on canonical `dev`. The command reads the version and build number +from that commit. + +```sh +python3 scripts/release/desktop-release.py FULL_COMMIT_SHA +python3 scripts/release/desktop-release.py FULL_COMMIT_SHA --start +python3 scripts/release/desktop-release.py FULL_COMMIT_SHA --verify +``` + +The default command checks the source and prints the release tag. `--start` creates +the canonical tag and GitHub draft before pushing the same tag to Builds. The +tag starts the Windows, Linux, and Developer ID macOS jobs. `--verify` checks that +the three expected assets have uploaded with SHA-256 digests. Review the download +files before publishing the GitHub draft. + +The Android workflow can also produce an APK and AAB from the same tag after +`HASH_BAGS_ANDROID_RELEASE_TAGS` is explicitly enabled in Builds. Play internal +upload uses a separately enrolled Fleet publisher. + ## Security disclosures See [`docs/SECURITY.md`](docs/SECURITY.md). Email `support@such.software` for anything sensitive; do not open a public issue for unpatched vulnerabilities. diff --git a/scripts/release/desktop-release.py b/scripts/release/desktop-release.py new file mode 100644 index 000000000..cfa04437c --- /dev/null +++ b/scripts/release/desktop-release.py @@ -0,0 +1,161 @@ +"""Stage and check a Hash Bags desktop release without publishing the draft.""" + +import argparse +import json +from pathlib import Path +import re +import subprocess +import sys + + +REPO = "Such-Software/hash-wallet" +BUILDS = "Builds/hash-wallet" +SOURCE_BRANCH = "refs/heads/dev" +SCRIPT = "scripts/release/desktop-release.py" +REMOTE_URLS = { + "origin": {f"git@github.com:{REPO}.git", f"https://github.com/{REPO}.git"}, + "gitea-builds": { + f"such-git@git.such.software:{BUILDS}.git", + f"ssh://such-git@git.such.software:2222/{BUILDS}.git", + }, +} + + +def command(*args): + return subprocess.check_output(args, text=True).strip() + + +def verify_remote(name): + allowed = {url.lower() for url in REMOTE_URLS[name]} + for direction in ([], ["--push"]): + urls = command("git", "remote", "get-url", *direction, "--all", name).splitlines() + if len(urls) != 1 or urls[0].lower() not in allowed: + raise ValueError(f"{name} does not have the expected fetch and push destinations") + + +def remote_refs(remote, *refs): + return { + ref: sha + for sha, ref in (line.split() for line in command("git", "ls-remote", remote, *refs).splitlines()) + } + + +def remote_tag(remote, ref): + peeled = f"{ref}^{{}}" + refs = remote_refs(remote, ref, peeled) + return refs.get(peeled, refs.get(ref)) + + +def release_for(tag): + raw = command("gh", "api", "--paginate", f"repos/{REPO}/releases?per_page=100") + decoder = json.JSONDecoder() + matches = [] + while raw: + page, end = decoder.raw_decode(raw) + matches.extend(release for release in page if release["tag_name"] == tag) + raw = raw[end:].lstrip() + if len(matches) > 1: + raise ValueError(f"GitHub returned more than one release for {tag}") + return matches[0] if matches else None + + +def verify_assets(release, names): + assets = {asset["name"]: asset for asset in release["assets"]} + missing = [] + for name in names: + asset = assets.get(name, {}) + if (asset.get("state") != "uploaded" or asset.get("size", 0) <= 0 + or not re.fullmatch(r"sha256:[0-9a-f]{64}", asset.get("digest") or "")): + missing.append(name) + else: + print(f"{name} {asset['digest']}") + if missing: + raise ValueError("Desktop assets are missing or unverified: " + ", ".join(missing)) + + +def has_release_driver(commit): + source = subprocess.run( + ["git", "show", f"{commit}:{SCRIPT}"], capture_output=True, text=True, + ) + return source.returncode == 0 and source.stdout.strip() == Path(__file__).read_text().strip() + + +def stage(commit, tag, version, ref, canonical, builds, release): + if not has_release_driver(commit): + raise ValueError("The exact release commit does not contain this desktop release automation") + if release is not None and not release["draft"]: + raise ValueError(f"GitHub release {tag} is already public") + if builds is not None and (canonical is None or release is None): + raise ValueError(f"Builds tag {tag} already exists without its expected GitHub tag and draft") + if canonical is None: + subprocess.run(["git", "push", "origin", f"{commit}:{ref}"], check=True) + if release is None: + subprocess.run( + ["gh", "release", "create", tag, "--repo", REPO, "--draft", "--verify-tag", + "--title", f"Hash Bags {version}", "--notes", ""], + check=True, + ) + release = release_for(tag) + if release is None or not release["draft"] or remote_tag("origin", ref) != commit: + raise ValueError("GitHub did not confirm the exact release tag and draft") + if builds is None: + subprocess.run(["git", "push", "gitea-builds", f"{commit}:{ref}"], check=True) + if remote_tag("gitea-builds", ref) != commit: + raise ValueError(f"Builds did not confirm tag {tag} at {commit}") + print(f"Desktop build tag confirmed: {tag}") + print(release["html_url"]) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("commit", help="Full reviewed canonical Git commit") + operation = parser.add_mutually_exclusive_group() + operation.add_argument("--start", action="store_true", help="Create the draft and start the desktop tag builds") + operation.add_argument("--verify", action="store_true", help="Check the three GitHub asset names and digests") + args = parser.parse_args() + if not re.fullmatch(r"[0-9a-f]{40}", args.commit): + parser.error("commit must be a full lowercase Git SHA") + + for remote in REMOTE_URLS: + verify_remote(remote) + head = remote_refs("origin", SOURCE_BRANCH).get(SOURCE_BRANCH) + if head is None: + raise ValueError("Canonical dev did not return a commit") + ancestry = subprocess.run(["git", "merge-base", "--is-ancestor", args.commit, head]) + if ancestry.returncode != 0: + raise ValueError("The commit is not on locally available canonical dev history. Fetch origin dev if it moved.") + + spec = command("git", "show", f"{args.commit}:pubspec_description.yaml") + match = re.search(r"^version:\s+([0-9]+\.[0-9]+\.[0-9]+)\+([1-9][0-9]*)$", spec, re.MULTILINE) + if not match: + raise ValueError("Expected a version and positive build number in pubspec_description.yaml") + version, build = match.groups() + tag = f"hash-bags-{version}-build{build}" + ref = f"refs/tags/{tag}" + canonical = remote_tag("origin", ref) + builds = remote_tag("gitea-builds", ref) + if any(sha is not None and sha != args.commit for sha in (canonical, builds)): + raise ValueError(f"Tag {tag} already points at a different commit") + release = release_for(tag) + names = [f"{tag}-macos.zip", f"HashBags-windows-{tag}.zip", "Hash_Bags-x86_64.AppImage"] + print(f"{tag} at {args.commit}") + if args.start: + stage(args.commit, tag, version, ref, canonical, builds, release) + elif args.verify: + if canonical is None or builds is None or release is None: + raise ValueError("The GitHub tag, Builds tag, and GitHub release must all exist") + verify_assets(release, names) + print(release["html_url"]) + else: + print("Desktop assets: " + ", ".join(names)) + if has_release_driver(args.commit): + print("Use --start to stage the draft and trigger the desktop tag builds.") + else: + print("This commit predates the desktop tag workflow or carries a different release command.") + + +if __name__ == "__main__": + try: + main() + except (ValueError, OSError, subprocess.SubprocessError) as error: + sys.exit(f"Desktop release failed: {error}") diff --git a/scripts/release/publish-desktop-asset.py b/scripts/release/publish-desktop-asset.py new file mode 100644 index 000000000..d958d4bd6 --- /dev/null +++ b/scripts/release/publish-desktop-asset.py @@ -0,0 +1,101 @@ +"""Attach an immutable desktop asset to an existing Hash Bags release.""" + +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +from urllib.error import HTTPError, URLError +from urllib.parse import urlencode +from urllib.request import Request, urlopen + + +REPO = "Such-Software/hash-wallet" +API = f"https://api.github.com/repos/{REPO}" + + +def request(url, *, asset=None): + token = os.environ.get("GH_TOKEN") + if not token: + raise ValueError("GH_RELEASE_TOKEN is missing") + headers = { + "Accept": "application/vnd.github+json", + "User-Agent": "hash-bags-ci", + } + if asset is None: + attempt = Request(url, headers=headers) + attempt.add_unredirected_header("Authorization", f"Bearer {token}") + with urlopen(attempt, timeout=30) as response: + return json.load(response) + headers["Content-Type"] = "application/octet-stream" + headers["Content-Length"] = str(asset.stat().st_size) + with asset.open("rb") as handle: + attempt = Request(url, data=handle, headers=headers) + attempt.add_unredirected_header("Authorization", f"Bearer {token}") + with urlopen(attempt, timeout=600) as response: + return json.load(response) + + +def find_release(tag): + page = 1 + while True: + releases = request(f"{API}/releases?per_page=100&page={page}") + for release in releases: + if release["tag_name"] == tag: + return release + if len(releases) < 100: + raise ValueError(f"GitHub release {tag} does not exist") + page += 1 + + +def verify_tag(tag): + ref = f"refs/tags/{tag}" + output = subprocess.check_output( + ["git", "ls-remote", f"https://github.com/{REPO}.git", ref, f"{ref}^{{}}"], + text=True, + timeout=30, + ) + refs = dict(reversed(line.split()) for line in output.splitlines()) + sha = refs.get(f"{ref}^{{}}", refs.get(ref)) + if sha is None or sha != os.environ.get("GITHUB_SHA"): + raise ValueError(f"GitHub tag {tag} does not point to the build commit") + + +def publish(tag, asset): + if not asset.is_file() or asset.stat().st_size == 0: + raise ValueError(f"Desktop asset is missing or empty: {asset}") + release = find_release(tag) + if os.environ.get("GITHUB_EVENT_NAME") == "push": + verify_tag(tag) + if not release["draft"]: + raise ValueError(f"Tag builds may only attach assets to a draft release: {tag}") + + digest = hashlib.sha256() + with asset.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + expected_digest = f"sha256:{digest.hexdigest()}" + + existing = next((item for item in release["assets"] if item["name"] == asset.name), None) + if existing is not None: + if existing.get("state") != "uploaded" or existing.get("digest") != expected_digest: + raise ValueError(f"GitHub already has a different or incomplete asset named {asset.name}") + print(f"{asset.name} is already uploaded with the expected digest") + return + + upload_url = f"https://uploads.github.com/repos/{REPO}/releases/{release['id']}/assets" + uploaded = request(f"{upload_url}?{urlencode({'name': asset.name})}", asset=asset) + if uploaded.get("state") != "uploaded" or uploaded.get("digest") != expected_digest: + raise ValueError(f"GitHub did not confirm the expected digest for {asset.name}") + print(f"Uploaded {asset.name} to GitHub release {tag}") + + +if __name__ == "__main__": + try: + tag, filename = sys.argv[1:] + publish(tag, Path(filename)) + except HTTPError as error: + sys.exit(f"Desktop asset upload refused by GitHub (HTTP {error.code})") + except (ValueError, URLError, OSError, subprocess.SubprocessError) as error: + sys.exit(f"Desktop asset upload failed: {error}") diff --git a/scripts/release/test_desktop_release.py b/scripts/release/test_desktop_release.py new file mode 100644 index 000000000..3944f479e --- /dev/null +++ b/scripts/release/test_desktop_release.py @@ -0,0 +1,89 @@ +import contextlib +import hashlib +import importlib.util +import io +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + + +def load_script(name): + spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(f"{name}.py")) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +release = load_script("desktop-release") +publisher = load_script("publish-desktop-asset") + + +class DesktopReleaseTests(unittest.TestCase): + def test_lookup_finds_draft_on_later_github_page(self): + draft = {"tag_name": "target", "draft": True} + paginated_output = json.dumps([{"tag_name": "previous"}]) + json.dumps([draft]) + with patch.object(release, "command", return_value=paginated_output): + self.assertEqual(release.release_for("target"), draft) + + def test_staging_creates_draft_before_pushing_the_builds_tag(self): + commit = "a" * 40 + tag = "hash-bags-1.2.3-build4" + draft = {"draft": True, "html_url": "https://example.invalid/draft"} + with ( + patch.object(release, "has_release_driver", return_value=True), + patch.object(release, "release_for", return_value=draft), + patch.object(release, "remote_tag", return_value=commit), + patch.object(release.subprocess, "run") as run, + contextlib.redirect_stdout(io.StringIO()), + ): + release.stage(commit, tag, "1.2.3", f"refs/tags/{tag}", None, None, None) + actions = [call.args[0] for call in run.call_args_list] + self.assertEqual([action[0] for action in actions], ["git", "gh", "git"]) + self.assertIn("--draft", actions[1]) + self.assertIn("origin", actions[0]) + self.assertIn("gitea-builds", actions[2]) + + def test_verification_refuses_a_missing_desktop_asset(self): + with self.assertRaisesRegex(ValueError, "AppImage"): + release.verify_assets({"assets": []}, ["Hash_Bags-x86_64.AppImage"]) + + +class DesktopPublisherTests(unittest.TestCase): + def test_tag_build_refuses_public_release(self): + with tempfile.TemporaryDirectory() as directory: + artifact = Path(directory) / "desktop.zip" + artifact.write_bytes(b"fixture") + with ( + patch.dict(publisher.os.environ, {"GITHUB_EVENT_NAME": "push"}), + patch.object(publisher, "find_release", return_value={"draft": False}), + patch.object(publisher, "verify_tag"), + patch.object(publisher, "request") as request, + self.assertRaisesRegex(ValueError, "draft release"), + ): + publisher.publish("target", artifact) + request.assert_not_called() + + def test_retry_accepts_identical_asset_and_refuses_replacement(self): + with tempfile.TemporaryDirectory() as directory: + artifact = Path(directory) / "desktop.zip" + artifact.write_bytes(b"fixture") + digest = "sha256:" + hashlib.sha256(artifact.read_bytes()).hexdigest() + asset = {"name": artifact.name, "state": "uploaded", "digest": digest} + draft = {"draft": True, "assets": [asset]} + with ( + patch.dict(publisher.os.environ, {"GITHUB_EVENT_NAME": "workflow_dispatch"}), + patch.object(publisher, "find_release", return_value=draft), + patch.object(publisher, "request") as request, + contextlib.redirect_stdout(io.StringIO()), + ): + publisher.publish("target", artifact) + artifact.write_bytes(b"different fixture") + with self.assertRaisesRegex(ValueError, "different or incomplete asset"): + publisher.publish("target", artifact) + request.assert_not_called() + + +if __name__ == "__main__": + unittest.main()