A full-featured download manager.
ci(snap): recover uploads from verified tag artifacts (#2483)
Dr_rOot8bb006124447
diff --git a/.claude/rules/git-workflow.md b/.claude/rules/git-workflow.mdindex 8373c32a..5e31607b 100644--- a/.claude/rules/git-workflow.md+++ b/.claude/rules/git-workflow.md@@ -61,6 +61,10 @@ them with local publishing steps.- Protected stable and beta tags publish one verified amd64/arm64 Snap buildset to `latest/edge`. Promote those exact revisions with `snap-promote.yml`from protected `main`; never rebuild during promotion. Stable rejects- prereleases.+ prereleases. Protected-main `snap-publish.yml` recovery may reuse only the+ original tag run's successful builds after validating the tag ancestry,+ artifact archive digests, package contents, and exact Store hashes. It must+ preserve per-architecture receipts and complete provenance for promotion;+ never accept manually selected revisions or rebuild during recovery.- If a release gate fails, fix the source or workflow and run the completegated path again. Do not publish a partial platform set.diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2431a36f..e4d810f8 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -633,6 +633,9 @@ jobs:uses: ./.github/workflows/flatpak.ymlsnap:+ permissions:+ contents: read+ actions: readneeds: planif: needs.plan.outputs.distributions == 'true'uses: ./.github/workflows/snap.ymldiff --git a/.github/workflows/snap-promote.yml b/.github/workflows/snap-promote.ymlindex 8d97bed2..b88771f1 100644--- a/.github/workflows/snap-promote.yml+++ b/.github/workflows/snap-promote.yml@@ -13,7 +13,7 @@ on:required: truetype: stringsource_run_id:- description: Successful protected-tag Snap workflow run ID+ description: Successful Snap tag publication or protected-main artifact recovery run IDrequired: truetype: stringsource_run_attempt:@@ -118,6 +118,12 @@ jobs:gh api \"repos/${GITHUB_REPOSITORY}/actions/runs/${SOURCE_RUN_ID}")"+ # Recovery is a separate trusted path with the original tag build,+ # archive digests, and exact Store receipts independently reverified.+ if [[ "$(jq -r '.event' <<< "$run_json")" == 'workflow_dispatch' ]]; then+ python3 scripts/snap_publication.py promotion+ exit 0+ fiworkflow_json="$(gh api \"repos/${GITHUB_REPOSITORY}/actions/workflows/snap.yml"diff --git a/.github/workflows/snap-publish.yml b/.github/workflows/snap-publish.ymlnew file mode 100644index 00000000..8e0ef62e--- /dev/null+++ b/.github/workflows/snap-publish.yml@@ -0,0 +1,276 @@+# Uploads are independently resumable; only the complete verified set is released.+name: Publish Snap artifacts+on:+ workflow_call:+ inputs:+ expected_version:+ required: true+ type: string+ source_run_id:+ required: true+ type: string+ secrets:+ SNAPCRAFT_STORE_CREDENTIALS:+ required: false+ workflow_dispatch:+ inputs:+ expected_version:+ description: Exact version of the original protected release tag+ required: true+ type: string+ source_run_id:+ description: Original tag-triggered Snap build run (never a recovery run)+ required: true+ type: string+permissions:+ actions: read+ contents: read+concurrency:+ group: snap-store-publication+ cancel-in-progress: false+jobs:+ preflight:+ name: Verify original Snap build provenance+ runs-on: ubuntu-24.04+ timeout-minutes: 10+ outputs:+ source: ${{ steps.source.outputs.source }}+ steps:+ - name: Checkout trusted publication tools+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ fetch-depth: 0+ - name: Verify original tag, successful builds, and immutable artifacts+ id: source+ env:+ GH_TOKEN: ${{ github.token }}+ EXPECTED_VERSION: ${{ inputs.expected_version }}+ SOURCE_RUN_ID: ${{ inputs.source_run_id }}+ RELEASE_REF_PROTECTED: ${{ github.ref_protected }}+ run: python3 scripts/snap_publication.py source++ upload:+ name: Upload Snap / ${{ matrix.arch }}+ needs: preflight+ runs-on: ubuntu-24.04+ timeout-minutes: 120+ environment: snap-store-edge+ strategy:+ fail-fast: false+ max-parallel: 1+ matrix:+ arch: [amd64, arm64]+ env:+ SNAP_ARCH: ${{ matrix.arch }}+ EXPECTED_VERSION: ${{ inputs.expected_version }}+ SNAP_SOURCE: ${{ needs.preflight.outputs.source }}+ steps:+ - name: Checkout verification tools+ timeout-minutes: 10+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ fetch-depth: 0++ - name: Setup pnpm for verification+ timeout-minutes: 5+ uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0+ with:+ version: 12.16.1+ run_install: false++ - name: Setup Node.js for verification+ timeout-minutes: 5+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0+ with:+ node-version: 24+ cache: pnpm++ - name: Install verifier dependencies+ timeout-minutes: 10+ run: pnpm install --frozen-lockfile --ignore-scripts+ env:+ MOTRIX_SKIP_ELECTRON_REBUILD: '1'+ MOTRIX_SKIP_ENGINE_FETCH: '1'++ - name: Download and authenticate original architecture artifact+ timeout-minutes: 10+ env:+ GH_TOKEN: ${{ github.token }}+ run: python3 scripts/snap_publication.py download++ - name: Verify architecture package before Store access+ timeout-minutes: 5+ run: |+ sudo apt-get update+ sudo apt-get install --yes squashfs-tools+ node scripts/verify-snap-artifact.mjs --snap "release/snap-verified/motrix_verified_${SNAP_ARCH}.snap" --arch "$SNAP_ARCH" --version "$EXPECTED_VERSION"++ - name: Install Snapcraft 9+ timeout-minutes: 10+ run: sudo snap install snapcraft --classic --channel=9.x/stable++ - name: Verify edge credential scope+ timeout-minutes: 5+ env:+ SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}+ run: python3 scripts/verify_snap_credential_scope.py --channel latest/edge --require-upload++ - name: Reconcile Store hash and upload at most once+ timeout-minutes: 15+ env:+ SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}+ # Reuse Snapcraft's own credential handling and bundled Python libraries.+ run: |+ # Expand SNAP inside snap run's shell, not the runner's shell.+ # shellcheck disable=SC2016+ snap run --shell snapcraft -c 'exec "$SNAP/bin/python" scripts/upload_snap_revision.py'++ - name: Preserve architecture receipt immediately+ if: ${{ always() && hashFiles('release/snap-upload-receipt.json') != '' }}+ timeout-minutes: 5+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2+ with:+ name: snap-upload-${{ github.run_id }}-${{ matrix.arch }}-${{ github.run_attempt }}+ path: release/snap-upload-receipt.json+ if-no-files-found: error+ retention-days: 90++ - name: Preserve sanitized upload diagnostics+ if: ${{ always() && hashFiles('release/snap-upload-state.json') != '' }}+ timeout-minutes: 5+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2+ with:+ name: snap-upload-state-${{ github.run_id }}-${{ matrix.arch }}-${{ github.run_attempt }}+ path: release/snap-upload-state.json+ retention-days: 90++ publish-edge:+ name: Release complete verified Snap build set+ needs: [preflight, upload]+ runs-on: ubuntu-24.04+ timeout-minutes: 120+ environment: snap-store-edge+ env:+ SNAP_SOURCE: ${{ needs.preflight.outputs.source }}+ SNAP_REVISION_FILE: ${{ github.workspace }}/release/motrix-snap-revisions.json+ steps:+ - name: Checkout verification tools+ timeout-minutes: 10+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ fetch-depth: 0++ - name: Setup pnpm for verification+ timeout-minutes: 5+ uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0+ with:+ version: 12.16.1+ run_install: false++ - name: Setup Node.js for verification+ timeout-minutes: 5+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0+ with:+ node-version: 24+ cache: pnpm++ - name: Install verifier dependencies+ timeout-minutes: 10+ run: pnpm install --frozen-lockfile --ignore-scripts+ env:+ MOTRIX_SKIP_ELECTRON_REBUILD: '1'+ MOTRIX_SKIP_ENGINE_FETCH: '1'++ - name: Aggregate verified architecture receipts+ timeout-minutes: 10+ env:+ GH_TOKEN: ${{ github.token }}+ run: python3 scripts/snap_publication.py aggregate++ - name: Install Snapcraft 9+ timeout-minutes: 10+ run: sudo snap install snapcraft --classic --channel=9.x/stable++ - name: Validate scoped Store credential+ id: scope+ timeout-minutes: 5+ env:+ SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}+ run: python3 scripts/verify_snap_credential_scope.py --channel latest/edge --github-output "$GITHUB_OUTPUT"++ - name: Reverify both Store hashes before changing edge+ timeout-minutes: 5+ env:+ SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}+ run: |+ # shellcheck disable=SC2016+ snap run --shell snapcraft -c 'exec "$SNAP/bin/python" scripts/upload_snap_revision.py verify'++ # Snapcraft's "promote" command re-reads a mutable source channel and+ # releases each architecture separately. This compensating release+ # helper instead binds the captured revisions, closes the target before+ # mutation, and restores the previous mapping after a normal failure.+ - name: Release exact build set to edge+ timeout-minutes: 45+ env:+ SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}+ SNAPCRAFT_CHANNEL: ${{ steps.scope.outputs.snapcraft_channel }}+ EXPECTED_VERSION: ${{ inputs.expected_version }}+ run: |+ set -euo pipefail+ revisions="$(+ # JavaScript source must not be expanded by Bash.+ # shellcheck disable=SC2016+ node --input-type=module -e '+ import { readFileSync } from "node:fs"+ const value = JSON.parse(readFileSync(process.argv[1], "utf8"))+ for (const arch of ["amd64", "arm64"]) {+ if (!/^[1-9]\d*$/.test(value[arch] ?? "")) {+ throw new Error(`Invalid ${arch} revision`)+ }+ }+ process.stdout.write(`${value.amd64} ${value.arm64}`)+ ' "$SNAP_REVISION_FILE"+ )"+ read -r amd64_revision arm64_revision <<< "$revisions"+ node scripts/release-snap-build-set.mjs \+ --snap motrix \+ --channel latest/edge \+ --version "$EXPECTED_VERSION" \+ --amd64-revision "$amd64_revision" \+ --arm64-revision "$arm64_revision" \+ --snapcraft-channel "$SNAPCRAFT_CHANNEL" \+ --snapcraft /snap/bin/snapcraft \+ --snapcraft-timeout-ms 120000 \+ --attempts 12 \+ --delay-ms 10000++ - name: Verify public edge channel+ timeout-minutes: 10+ env:+ EXPECTED_VERSION: ${{ inputs.expected_version }}+ run: >-+ node scripts/verify-snap-store-channel.mjs+ --snap motrix+ --channel latest/edge+ --version "$EXPECTED_VERSION"+ --architectures amd64,arm64+ --expected-revisions "$SNAP_REVISION_FILE"+ --attempts 12+ --delay-ms 10000++ # This immutable, run-associated artifact is the only trusted revision+ # provenance accepted by snap-promote.yml.+ - name: Preserve trusted revision record+ timeout-minutes: 5+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2+ with:+ name: snap-release-revisions-${{ github.run_attempt }}+ path: |+ ${{ env.SNAP_REVISION_FILE }}+ release/snap-provenance.json+ if-no-files-found: error+ retention-days: 90diff --git a/.github/workflows/snap.yml b/.github/workflows/snap.ymlindex 6365402c..efcb7aa4 100644--- a/.github/workflows/snap.yml+++ b/.github/workflows/snap.yml@@ -5,8 +5,7 @@# - pull requests and ordinary manual builds never receive Store credentials;# - protected stable and beta release tags publish a complete# two-architecture build set to latest/edge only;-# - an explicit protected-main manual run can recover edge publication-# without moving or replacing an immutable release tag;+# - snap-publish.yml can recover original tag artifacts from protected main;# - candidate and stable receive that exact build set through snap-promote.yml.name: Snap@@ -17,36 +16,15 @@ on:tags:- 'v*'workflow_dispatch:- inputs:- publish_edge:- description: Publish the protected main build to latest/edge- required: true- default: false- type: booleanpermissions:contents: read+ actions: read-# Store-changing workflows share one non-cancelling lock. Pull-request builds-# retain their usual per-ref cancellation without blocking Store operations.+# The publication workflow owns the shared Store lock, including recovery.concurrency:- group: >-- ${{- (- (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v'))- || (- github.event_name == 'workflow_dispatch'- && inputs.publish_edge == true- )- )- && 'snap-store-publication'- || format('snap-{0}-{1}', github.event_name, github.ref)- }}- cancel-in-progress: >-- ${{- !startsWith(github.ref, 'refs/tags/v')- && inputs.publish_edge != true- }}+ group: snap-build-${{ github.event_name }}-${{ github.ref }}+ cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/v') }}jobs:preflight:@@ -226,6 +204,11 @@ jobs:build-info: truesnapcraft-channel: 9.x/stable+ - name: Verify publication client compatibility without Store credentials+ run: |+ # shellcheck disable=SC2016+ snap run --shell snapcraft -c 'exec "$SNAP/bin/python" scripts/upload_snap_revision.py check-client'+- name: Verify Snap artifactrun: >-node scripts/verify-snap-artifact.mjs@@ -242,270 +225,14 @@ jobs:release/size-reports/linux-${{ matrix.electron_arch }}.jsonif-no-files-found: errorcompression-level: 0- retention-days: 7+ retention-days: ${{ startsWith(github.ref, 'refs/tags/v') && 90 || 7 }}publish-edge:name: Publish complete build set to edge- if: >-- (- github.event_name == 'push' &&- startsWith(github.ref, 'refs/tags/v') &&- github.ref_protected == true- ) || (- github.event_name == 'workflow_dispatch' &&- inputs.publish_edge == true &&- github.ref == 'refs/heads/main' &&- github.ref_protected == true- )+ if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') && github.ref_protected == trueneeds: [preflight, build]- runs-on: ubuntu-24.04- # Bounded pre-mutation steps plus a 45-minute release/rollback window.- timeout-minutes: 180- environment:- name: snap-store-edge- env:- SNAP_REVISION_FILE: >-- ${{ github.workspace }}/release/motrix-snap-revisions.json- steps:- - name: Checkout verification tools- timeout-minutes: 10- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- with:- persist-credentials: false-- - name: Setup pnpm for verification- timeout-minutes: 5- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0- with:- version: 12.16.1- run_install: false-- - name: Setup Node.js for verification- timeout-minutes: 5- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0- with:- node-version: 24- cache: pnpm-- - name: Install verifier dependencies- timeout-minutes: 10- run: pnpm install --frozen-lockfile --ignore-scripts- env:- MOTRIX_SKIP_ELECTRON_REBUILD: '1'- MOTRIX_SKIP_ENGINE_FETCH: '1'-- - name: Download both architecture artifacts- timeout-minutes: 10- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2- with:- pattern: snap-input-*- path: release/snap-upload- merge-multiple: true-- - name: Install artifact inspection tools- timeout-minutes: 10- run: |- sudo apt-get update- sudo apt-get install --yes squashfs-tools-- - name: Verify complete upload set- timeout-minutes: 5- shell: bash- env:- EXPECTED_VERSION: ${{ needs.preflight.outputs.version }}- run: |- set -euo pipefail- download_root='release/snap-upload'- verified_root='release/snap-verified'- downloaded_snaps=()- while IFS= read -r -d '' snap; do- downloaded_snaps+=("$snap")- done < <(find "$download_root" -name '*.snap' -print0)- if (( ${#downloaded_snaps[@]} != 2 )); then- echo "Expected exactly two Snap artifacts, found ${#downloaded_snaps[@]}" >&2- exit 1- fi- if [[ -e "$verified_root" || -L "$verified_root" ]]; then- echo "Verified Snap staging path already exists" >&2- exit 1- fi- mkdir "$verified_root"- first_basename=''- for arch in amd64 arm64; do- arch_root="${download_root}/snap-${arch}"- if [[ ! -d "$arch_root" ]]; then- echo "Missing downloaded ${arch} artifact directory" >&2- exit 1- fi- matches=()- while IFS= read -r -d '' snap; do- matches+=("$snap")- done < <(find "$arch_root" -type f -name '*.snap' -print0)- if (( ${#matches[@]} != 1 )); then- echo "Expected exactly one ${arch} Snap artifact" >&2- exit 1- fi- snap="${matches[0]}"- basename="$(basename "$snap")"- if [[ -n "$first_basename" && "$basename" == "$first_basename" ]]; then- echo "Duplicate Snap artifact basename: $basename" >&2- exit 1- fi- first_basename="$basename"- if [[ ! "$basename" =~ _${arch}\.snap$ ]]; then- echo "Unexpected ${arch} Snap artifact name: $basename" >&2- exit 1- fi- node scripts/verify-snap-artifact.mjs \- --snap "$snap" \- --arch "$arch" \- --version "$EXPECTED_VERSION"- install -m 0644 -- \- "$snap" "${verified_root}/motrix_verified_${arch}.snap"- done- verified_snaps=()- while IFS= read -r -d '' snap; do- verified_snaps+=("$snap")- done < <(find "$verified_root" -type f -name '*.snap' -print0)- if (( ${#verified_snaps[@]} != 2 )); then- echo "Expected exactly two verified Snap artifacts" >&2- exit 1- fi-- - name: Install Snapcraft 9- timeout-minutes: 10- run: sudo snap install snapcraft --classic --channel=9.x/stable-- - name: Validate scoped Store credential- timeout-minutes: 5- env:- SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}- run: |- set -euo pipefail- if [[ -z "${SNAPCRAFT_STORE_CREDENTIALS:-}" ]]; then- echo "Missing snap-store-edge SNAPCRAFT_STORE_CREDENTIALS" >&2- exit 1- fi- snapcraft whoami- snapcraft status motrix-- # Upload first without releasing. Only the exact revisions returned by- # these two uploads may cross the latest/edge boundary.- - name: Upload complete build set- timeout-minutes: 20- env:- SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}- shell: bash- run: |- set -euo pipefail- declare -A revisions- for arch in amd64 arm64; do- snap="release/snap-verified/motrix_verified_${arch}.snap"- if [[ ! -f "$snap" || -L "$snap" ]]; then- echo "Missing verified ${arch} Snap artifact" >&2- exit 1- fi- upload_log="${RUNNER_TEMP}/snap-upload-${arch}.log"- LC_ALL=C.UTF-8 snapcraft upload "$snap" 2>&1 | tee "$upload_log"- revisions["$arch"]="$(- # JavaScript source must not be expanded by Bash.- # shellcheck disable=SC2016- node --input-type=module -e '- import { readFileSync } from "node:fs"- const output = readFileSync(process.argv[1], "utf8")- const found = new Set(- [...output.matchAll(/\bRevision\s+([1-9]\d*)\b/gi)]- .map((match) => match[1])- )- if (found.size !== 1) {- throw new Error(- `Expected one uploaded revision, found ${found.size}`- )- }- process.stdout.write([...found][0])- ' "$upload_log"- )"- done- # JavaScript source must not be expanded by Bash.- # shellcheck disable=SC2016- REVISION_AMD64="${revisions[amd64]}" \- REVISION_ARM64="${revisions[arm64]}" \- node --input-type=module -e '- import { writeFileSync } from "node:fs"- const revisions = {- amd64: process.env.REVISION_AMD64,- arm64: process.env.REVISION_ARM64,- }- for (const [arch, revision] of Object.entries(revisions)) {- if (!/^[1-9]\d*$/.test(revision ?? "")) {- throw new Error(`Invalid ${arch} revision: ${revision}`)- }- }- writeFileSync(- process.env.SNAP_REVISION_FILE,- `${JSON.stringify(revisions)}\n`,- { encoding: "utf8", mode: 0o600 }- )- '-- # Snapcraft's "promote" command re-reads a mutable source channel and- # releases each architecture separately. This compensating release- # helper instead binds the captured revisions, closes the target before- # mutation, and restores the previous mapping after a normal failure.- - name: Release exact build set to edge- timeout-minutes: 45- env:- SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}- EXPECTED_VERSION: ${{ needs.preflight.outputs.version }}- run: |- set -euo pipefail- revisions="$(- # JavaScript source must not be expanded by Bash.- # shellcheck disable=SC2016- node --input-type=module -e '- import { readFileSync } from "node:fs"- const value = JSON.parse(readFileSync(process.argv[1], "utf8"))- for (const arch of ["amd64", "arm64"]) {- if (!/^[1-9]\d*$/.test(value[arch] ?? "")) {- throw new Error(`Invalid ${arch} revision`)- }- }- process.stdout.write(`${value.amd64} ${value.arm64}`)- ' "$SNAP_REVISION_FILE"- )"- read -r amd64_revision arm64_revision <<< "$revisions"- node scripts/release-snap-build-set.mjs \- --snap motrix \- --channel latest/edge \- --version "$EXPECTED_VERSION" \- --amd64-revision "$amd64_revision" \- --arm64-revision "$arm64_revision" \- --snapcraft /snap/bin/snapcraft \- --snapcraft-timeout-ms 120000 \- --attempts 12 \- --delay-ms 10000-- - name: Verify public edge channel- timeout-minutes: 10- env:- EXPECTED_VERSION: ${{ needs.preflight.outputs.version }}- run: >-- node scripts/verify-snap-store-channel.mjs- --snap motrix- --channel latest/edge- --version "$EXPECTED_VERSION"- --architectures amd64,arm64- --expected-revisions "$SNAP_REVISION_FILE"- --attempts 12- --delay-ms 10000-- # This immutable, run-associated artifact is the only trusted revision- # provenance accepted by snap-promote.yml.- - name: Preserve trusted revision record- timeout-minutes: 5- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2- with:- name: snap-release-revisions-${{ github.run_attempt }}- path: ${{ env.SNAP_REVISION_FILE }}- if-no-files-found: error- retention-days: 90+ uses: ./.github/workflows/snap-publish.yml+ with:+ expected_version: ${{ needs.preflight.outputs.version }}+ source_run_id: ${{ github.run_id }}+ secrets: inheritdiff --git a/scripts/snap_publication.py b/scripts/snap_publication.pynew file mode 100644index 00000000..567731df--- /dev/null+++ b/scripts/snap_publication.py@@ -0,0 +1,239 @@+#!/usr/bin/env python3+"""Authenticate original Snap artifacts and assemble resumable publication evidence.++Only GitHub-hosted artifacts from successful jobs of the exact tag build are+accepted. Recovery runs execute tools from protected main, never artifact code.+"""+import hashlib+import json+import os+from pathlib import Path, PurePosixPath+import re+import stat+import subprocess+import sys+import tempfile+import zipfile++ARCHES = ("amd64", "arm64")+++class PublicationError(ValueError):+ """A sanitized publication validation failure safe to expose in CI."""+++def require(condition, message):+ if not condition:+ raise PublicationError(message)+++def positive(value):+ require(re.fullmatch(r"[1-9][0-9]*", str(value)) is not None, "Invalid positive ID")+ return str(value)+++def command(args):+ return subprocess.check_output(args, text=True, timeout=120).strip()+++def api(repo, endpoint, pages=False):+ args = ["gh", "api", f"repos/{repo}/{endpoint}"]+ if pages:+ args += ["--paginate", "--slurp"]+ return json.loads(command(args))+++def workflow_run(repo, run_id, workflow):+ run = api(repo, f"actions/runs/{positive(run_id)}")+ identity = api(repo, f"actions/workflows/{workflow}")+ require(run["path"] == f".github/workflows/{workflow}" and+ run["workflow_id"] == identity["id"] and+ run["head_repository"]["full_name"] == repo, "Untrusted source workflow")+ require(re.fullmatch(r"[0-9a-f]{40}", run["head_sha"]) is not None, "Invalid source SHA")+ return run+++def check_ancestry(sha):+ command(["git", "fetch", "--no-tags", "origin", "refs/heads/main:refs/remotes/origin/main"])+ command(["git", "merge-base", "--is-ancestor", sha, "refs/remotes/origin/main"])+++def validate_source(run, jobs, artifacts, repo, version, tag_sha):+ require(run["event"] == "push" and run["head_branch"] == f"v{version}" and+ run["head_sha"] == tag_sha, "Source is not the requested release tag")+ require(any(j["name"] == "Validate Snap source" and j["conclusion"] == "success"+ for j in jobs), "Protected tag preflight did not succeed")+ chosen = {}+ for arch in ARCHES:+ matches = [a for a in artifacts if a["name"] == f"snap-input-{arch}"]+ require(len(matches) == 1, "Missing or ambiguous original artifact")+ a = matches[0]+ require(not a["expired"] and re.fullmatch(r"sha256:[0-9a-f]{64}", a.get("digest", "")),+ "Expired artifact or missing archive digest")+ require(a["workflow_run"]["id"] == run["id"] and+ a["workflow_run"]["head_sha"] == tag_sha, "Artifact source mismatch")+ matching_jobs = [j for j in jobs if j["name"] == f"Build Snap / {arch}" and+ j["conclusion"] == "success" and+ j["started_at"] <= a["created_at"] <= j["completed_at"]]+ # GitHub repeats successful jobs in later failed-job attempts. Bind the+ # original execution interval, not the carried-forward attempt number.+ require(len({(j["started_at"], j["completed_at"]) for j in matching_jobs}) == 1,+ "Artifact is not from a successful architecture build")+ chosen[arch] = {"id": positive(a["id"]), "digest": a["digest"],+ "build_attempt": min(j["run_attempt"] for j in matching_jobs)}+ return {"repository": repo, "run_id": positive(run["id"]), "sha": tag_sha,+ "version": version, "artifacts": chosen}+++def original_source(repo, run_id, version):+ require(re.fullmatch(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-beta\.[1-9][0-9]*)?", version),+ "Invalid release version")+ run = workflow_run(repo, run_id, "snap.yml")+ check_ancestry(run["head_sha"])+ command(["git", "fetch", "--no-tags", "--force", "origin",+ f"refs/tags/v{version}:refs/remotes/origin/snap-recovery-tag"])+ tag_sha = command(["git", "rev-parse", "refs/remotes/origin/snap-recovery-tag^{commit}"])+ package = json.loads(command(["git", "show", f"{tag_sha}:package.json"]))+ require(package["version"] == version, "Tag package version mismatch")+ jobs = [j for page in api(repo, f"actions/runs/{run_id}/jobs?filter=all&per_page=100", True)+ for j in page["jobs"]]+ artifacts = [a for page in api(repo, f"actions/runs/{run_id}/artifacts?per_page=100", True)+ for a in page["artifacts"]]+ return validate_source(run, jobs, artifacts, repo, version, tag_sha)+++def archive(repo, artifact):+ """Authenticate the zip before interpreting any of its contents."""+ require(re.fullmatch(r"sha256:[0-9a-f]{64}", artifact["digest"]), "Invalid archive digest")+ with tempfile.TemporaryFile() as target:+ subprocess.run(["gh", "api", f"repos/{repo}/actions/artifacts/{positive(artifact['id'])}/zip"],+ stdout=target, check=True, timeout=300)+ target.seek(0)+ require("sha256:" + hashlib.file_digest(target, "sha256").hexdigest() == artifact["digest"],+ "GitHub artifact archive digest mismatch")+ target.seek(0)+ with zipfile.ZipFile(target) as zipped:+ result = {}+ for entry in zipped.infolist():+ p = PurePosixPath(entry.filename)+ require(not p.is_absolute() and ".." not in p.parts and+ not stat.S_ISLNK(entry.external_attr >> 16), "Unsafe artifact entry")+ if entry.is_dir():+ continue+ require(entry.file_size <= 1024 ** 3, "Oversized artifact entry")+ require(entry.filename not in result, "Duplicate artifact entry")+ result[entry.filename] = zipped.read(entry)+ return result+++def download_snap(source, arch):+ files = archive(source["repository"], source["artifacts"][arch])+ snaps = [(name, data) for name, data in files.items() if name.endswith(".snap")]+ require(len(snaps) == 1 and snaps[0][0].endswith(f"_{arch}.snap"), "Invalid architecture artifact")+ target = Path(f"release/snap-verified/motrix_verified_{arch}.snap")+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(snaps[0][1])+ return hashlib.sha3_384(snaps[0][1]).hexdigest(), len(snaps[0][1])+++def artifact_json(repo, a, filename):+ files = archive(repo, a)+ require(filename in files, "Missing publication evidence")+ return json.loads(files[filename])+++def validate_receipt(receipt, source, arch, run_id, digest, size):+ require(receipt["source"] == source and receipt["architecture"] == arch and+ receipt["publication_run_id"] == str(run_id) and+ receipt["sha3_384"] == digest and receipt["size"] == size and+ receipt["status"] == "verified", "Architecture receipt identity mismatch")+ return positive(receipt["revision"])+++def aggregate(source, repo, run_id):+ artifacts = [a for page in api(repo, f"actions/runs/{run_id}/artifacts?per_page=100", True)+ for a in page["artifacts"]]+ receipts, revisions = {}, {}+ for arch in ARCHES:+ pattern = rf"snap-upload-{run_id}-{arch}-([1-9][0-9]*)"+ candidates = [(int(m[1]), a) for a in artifacts+ if (m := re.fullmatch(pattern, a["name"])) and not a["expired"]]+ require(candidates, "Missing successful architecture receipt")+ attempt, a = max(candidates, key=lambda pair: pair[0])+ require(attempt <= int(os.environ["GITHUB_RUN_ATTEMPT"]), "Future upload receipt")+ receipt = artifact_json(repo, a, "snap-upload-receipt.json")+ digest, size = download_snap(source, arch)+ revisions[arch] = validate_receipt(receipt, source, arch, run_id, digest, size)+ receipts[arch] = receipt+ require(len(set(revisions.values())) == 2, "Architectures share a revision")+ write_json(Path(os.environ["SNAP_REVISION_FILE"]), revisions)+ write_json(Path("release/snap-provenance.json"),+ {"source": source, "publication_run_id": run_id, "receipts": receipts})+++def verify_recovery_promotion(repo, run_id, attempt, version):+ run = workflow_run(repo, run_id, "snap-publish.yml")+ require(run["event"] == "workflow_dispatch" and run["head_branch"] == "main" and+ run["status"] == "completed" and run["conclusion"] == "success" and+ str(run["run_attempt"]) == attempt, "Untrusted recovery publication")+ check_ancestry(run["head_sha"])+ artifacts = [a for page in api(repo, f"actions/runs/{run_id}/artifacts?per_page=100", True)+ for a in page["artifacts"]]+ matches = [a for a in artifacts if a["name"] == f"snap-release-revisions-{attempt}" and not a["expired"]]+ require(len(matches) == 1, "Missing recovery provenance")+ files = archive(repo, matches[0])+ proof = json.loads(files["snap-provenance.json"])+ revisions = json.loads(files["motrix-snap-revisions.json"])+ source = original_source(repo, proof["source"]["run_id"], version)+ require(proof["source"] == source and proof["publication_run_id"] == run_id,+ "Recovery is not bound to original tag artifacts")+ require(set(revisions) == set(ARCHES) and len(set(revisions.values())) == 2,+ "Incomplete revision set")+ for arch in ARCHES:+ digest, size = download_snap(source, arch)+ revision = validate_receipt(proof["receipts"][arch], source, arch, run_id, digest, size)+ require(revisions[arch] == revision, "Recovery revision mismatch")+++def write_json(path, value):+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(value, sort_keys=True) + "\n", encoding="utf-8")+++def main():+ repo = os.environ["GITHUB_REPOSITORY"]+ require(re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repo), "Invalid repository")+ mode = sys.argv[1]+ if mode == "source":+ require(os.environ["RELEASE_REF_PROTECTED"] == "true", "Publication requires protected ref")+ event, ref = os.environ["GITHUB_EVENT_NAME"], os.environ["GITHUB_REF"]+ require((event == "push" and ref == "refs/tags/v" + os.environ["EXPECTED_VERSION"] and+ os.environ["SOURCE_RUN_ID"] == os.environ["GITHUB_RUN_ID"]) or+ (event == "workflow_dispatch" and ref == "refs/heads/main"),+ "Publication requires exact protected tag or protected-main recovery")+ source = original_source(repo, positive(os.environ["SOURCE_RUN_ID"]), os.environ["EXPECTED_VERSION"])+ with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output:+ output.write("source=" + json.dumps(source, sort_keys=True) + "\n")+ elif mode == "promotion":+ verify_recovery_promotion(repo, positive(os.environ["SOURCE_RUN_ID"]),+ positive(os.environ["SOURCE_RUN_ATTEMPT"]), os.environ["EXPECTED_VERSION"])+ else:+ source = json.loads(os.environ["SNAP_SOURCE"])+ require(source["repository"] == repo, "Repository mismatch")+ if mode == "download":+ arch = os.environ["SNAP_ARCH"]+ require(arch in ARCHES, "Unknown architecture")+ download_snap(source, arch)+ elif mode == "aggregate":+ aggregate(source, repo, positive(os.environ["GITHUB_RUN_ID"]))+ else:+ raise ValueError("Unknown publication operation")+++if __name__ == "__main__":+ try:+ main()+ except Exception as error:+ # Avoid printing subprocess output, HTTP bodies, or authentication state.+ print(f"Snap provenance verification failed: {error if isinstance(error, PublicationError) else type(error).__name__}", file=sys.stderr)+ sys.exit(1)diff --git a/scripts/upload_snap_revision.py b/scripts/upload_snap_revision.pynew file mode 100644index 00000000..a1259992--- /dev/null+++ b/scripts/upload_snap_revision.py@@ -0,0 +1,172 @@+#!/usr/bin/env python3+"""Reconcile immutable Snap bytes with Store revisions before any upload.++Uses Snapcraft 9's bundled authentication client for the documented v2 API:+https://dashboard.snapcraft.io/docs/reference/v2/en/snaps.html+Never retries an ambiguous write. Subsequent attempts first query Store hashes.+"""+import hashlib+import json+import os+from pathlib import Path+import subprocess+import sys+import time+from urllib.parse import urljoin, urlparse++from snap_publication import PublicationError, positive, require, write_json++BASE = "https://dashboard.snapcraft.io"+ENDPOINT = BASE + "/api/v2/snaps/motrix/releases"+READY = {"Published", "Unpublished"}+++def list_revisions(get):+ url, seen, revisions = ENDPOINT + "?size=500", set(), {}+ for _ in range(100):+ require(url not in seen, "Store pagination loop")+ seen.add(url)+ data = get(url)+ require(data["snap"]["name"] == "motrix" and isinstance(data["revisions"], list),+ "Unexpected Store snapshot")+ for revision in data["revisions"]:+ identity = positive(revision["revision"])+ # Pagination may repeat revisions in overlapping release contexts.+ require(identity not in revisions or revisions[identity] == revision,+ "Store changed during pagination")+ revisions[identity] = revision+ next_link = data["_links"].get("next")+ if not next_link:+ return list(revisions.values())+ url = urljoin(url, next_link)+ parsed = urlparse(url)+ require(parsed.scheme == "https" and parsed.netloc == "dashboard.snapcraft.io" and+ parsed.path == "/api/v2/snaps/motrix/releases" and not parsed.fragment,+ "Unsafe Store pagination link")+ raise PublicationError("Store pagination exceeded limit")+++def matching_revision(revisions, digest, size, arch, version):+ matches = [r for r in revisions if r.get("sha3-384") == digest]+ require(len(matches) <= 1, "Ambiguous Store hash match")+ if not matches:+ return None+ revision = matches[0]+ require(revision["size"] == size and revision["architectures"] == [arch] and+ revision["version"] == version and revision["confinement"] == "strict" and+ revision["grade"] == "stable", "Store hash metadata mismatch")+ positive(revision["revision"])+ return revision+++def reconcile(*, lookup, upload, save_state, sleep=time.sleep):+ """At most one write, even when upload succeeds remotely but loses its response."""+ revision = lookup() # Read failure must prevent upload.+ if revision is not None:+ save_state({"state": "existing", "revision": positive(revision["revision"]),+ "store_status": revision["status"]})+ require(revision["status"] in READY, "Existing revision requires Store review; do not reupload")+ return revision+ save_state({"state": "upload_started"})+ try:+ upload()+ except Exception:+ # The server may have accepted the bytes. Reconcile without another POST.+ save_state({"state": "upload_outcome_unknown"})+ for attempt in range(4):+ if attempt:+ sleep(10)+ try:+ revision = lookup()+ except Exception:+ continue+ if revision is not None:+ save_state({"state": "reconciled", "revision": positive(revision["revision"]),+ "store_status": revision["status"]})+ require(revision["status"] in READY, "Uploaded revision requires Store review")+ return revision+ raise PublicationError("Upload unresolved; inspect Store processing before another attempt")+++def store_getter():+ # Fail closed if the installed Snapcraft API changes. Never implement or log+ # macaroon handling ourselves, and never send credentials to pagination hosts.+ from snapcraft.store.client import get_client+ client = get_client()++ def get(url):+ try:+ response = client.request("GET", url, headers={"Accept": "application/json"},+ timeout=60, allow_redirects=False)+ except Exception as error:+ status = getattr(getattr(error, "response", None), "status_code", None)+ detail = str(status) if isinstance(status, int) else "unavailable"+ raise PublicationError(f"Store read failed (HTTP {detail})") from None+ require(response.status_code == 200, f"Store read failed (HTTP {response.status_code})")+ return response.json()+ return get+++def identity(path):+ require(path.is_file() and not path.is_symlink(), "Missing regular Snap file")+ with path.open("rb") as payload:+ return hashlib.file_digest(payload, "sha3_384").hexdigest(), path.stat().st_size+++def verify_before_release(get):+ proof = json.loads(Path("release/snap-provenance.json").read_text())+ revisions = json.loads(Path(os.environ["SNAP_REVISION_FILE"]).read_text())+ snapshot = list_revisions(get)+ for arch in ("amd64", "arm64"):+ receipt = proof["receipts"][arch]+ found = matching_revision(snapshot, receipt["sha3_384"], receipt["size"], arch,+ proof["source"]["version"])+ require(found is not None and found["status"] in READY and+ positive(found["revision"]) == revisions[arch], "Store receipt no longer releaseable")+++def main():+ if sys.argv[1:] == ["check-client"]:+ from snapcraft.store.client import get_client+ require(callable(get_client), "Snapcraft client adapter is unavailable")+ print("Snapcraft authenticated Store adapter import passed")+ return+ get = store_getter()+ if len(sys.argv) == 2 and sys.argv[1] == "verify":+ verify_before_release(get)+ return+ arch = os.environ["SNAP_ARCH"]+ require(arch in ("amd64", "arm64"), "Invalid architecture")+ source = json.loads(os.environ["SNAP_SOURCE"])+ version = os.environ["EXPECTED_VERSION"]+ require(source["version"] == version, "Source version mismatch")+ path = Path(f"release/snap-verified/motrix_verified_{arch}.snap")+ digest, size = identity(path)+ state_path = Path("release/snap-upload-state.json")++ def lookup():+ return matching_revision(list_revisions(get), digest, size, arch, version)++ def upload():+ # Do not persist raw Snapcraft logs: they can contain authentication or+ # upload URLs. The durable state contains only fixed status and identity.+ subprocess.run(["/snap/bin/snapcraft", "upload", str(path)],+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,+ check=True, timeout=600)++ revision = reconcile(lookup=lookup, upload=upload,+ save_state=lambda state: write_json(state_path, state))+ write_json(Path("release/snap-upload-receipt.json"), {+ "source": source, "publication_run_id": positive(os.environ["GITHUB_RUN_ID"]),+ "architecture": arch, "sha3_384": digest, "size": size,+ "revision": positive(revision["revision"]), "status": "verified",+ })+ print(f"Verified {arch} revision {positive(revision['revision'])} against original artifact hash")+++if __name__ == "__main__":+ try:+ main()+ except Exception as error:+ print(f"Snap upload reconciliation stopped: {error if isinstance(error, PublicationError) else type(error).__name__}; inspect sanitized state", file=sys.stderr)+ sys.exit(1)diff --git a/scripts/verify_snap_credential_scope.py b/scripts/verify_snap_credential_scope.pyindex 6f0a6d8a..1f4e2e75 100644--- a/scripts/verify_snap_credential_scope.py+++ b/scripts/verify_snap_credential_scope.py@@ -65,7 +65,7 @@ def scope_items(value: str) -> list[str] | None:return items-def verify_scope(output: str, channel: str) -> str:+def verify_scope(output: str, channel: str, require_upload: bool = False) -> str:match = re.fullmatch(r"([A-Za-z0-9][A-Za-z0-9._-]*)/(stable|candidate|beta|edge)", channel)@@ -87,6 +87,14 @@ def verify_scope(output: str, channel: str) -> str:"Snap credential does not permit releasing existing revisions","release_permission_denied",)+ if require_upload and permissions is not None and (+ "package_access" not in permissions or+ not {"package_push", "package_upload"}.intersection(permissions)+ ):+ raise ScopeError(+ "Snap credential does not permit upload and revision inspection",+ "upload_permission_denied",+ )# Store channel restrictions use Python fnmatch against the release request.# https://dashboard.snapcraft.io/docs/reference/v1/snap.htmlfor release_channel in release_channels:@@ -138,6 +146,7 @@ def main() -> None:parser.add_argument("--snapcraft", default="/snap/bin/snapcraft")parser.add_argument("--channel", required=True)parser.add_argument("--github-output")+ parser.add_argument("--require-upload", action="store_true")options = parser.parse_args()try:result = subprocess.run(@@ -163,7 +172,7 @@ def main() -> None:"Snapcraft whoami emitted diagnostics; credential scope was not verified")try:- release_channel = verify_scope(result.stdout, options.channel)+ release_channel = verify_scope(result.stdout, options.channel, options.require_upload)except ScopeError:emit_diagnostics("scope_rejected", result, options.channel)raisediff --git a/tests/scripts/snap-publication.test.ts b/tests/scripts/snap-publication.test.tsnew file mode 100644index 00000000..fff1af50--- /dev/null+++ b/tests/scripts/snap-publication.test.ts@@ -0,0 +1,17 @@+import { spawnSync } from 'node:child_process'+import { expect, it } from 'vitest'++it.skipIf(process.platform === 'win32')(+ 'recovers Snap uploads without duplicate writes or mixed provenance',+ () => {+ const result = spawnSync(+ 'python3',+ ['tests/scripts/test_snap_publication.py'],+ {+ encoding: 'utf8',+ env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1' },+ }+ )+ expect(result.status, result.stdout + result.stderr).toBe(0)+ }+)diff --git a/tests/scripts/test_snap_publication.py b/tests/scripts/test_snap_publication.pynew file mode 100644index 00000000..b0eee7e7--- /dev/null+++ b/tests/scripts/test_snap_publication.py@@ -0,0 +1,217 @@+"""Offline fault-injection tests for Store uploads and artifact provenance."""+import hashlib+import io+import json+from pathlib import Path+import subprocess+import sys+import unittest+from unittest.mock import Mock, patch+import zipfile++sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts"))+import snap_publication as publication+import upload_snap_revision as upload+from verify_snap_credential_scope import verify_scope+++def revision(**changes):+ return {"revision": 119, "sha3-384": "a" * 96, "size": 12,+ "version": "2.2.0", "architectures": ["amd64"], "confinement": "strict",+ "grade": "stable", "status": "Unpublished", **changes}+++class UploadRecoveryTests(unittest.TestCase):+ def run_reconcile(self, lookups, error=False):+ lookup = Mock(side_effect=lookups)+ mutation = Mock(side_effect=RuntimeError("response lost") if error else None)+ states = []+ result = upload.reconcile(lookup=lookup, upload=mutation, save_state=states.append, sleep=lambda _: None)+ return result, mutation, states++ def test_upload_scope_requires_push_and_read_permissions(self):+ def whoami(permissions):+ return f"email: [email protected]\nusername: publisher\nid: 1\npermissions: {permissions}\nchannels: edge\nexpires: 2027-01-01T00:00:00Z\n"+ self.assertEqual(verify_scope(whoami("package_access, package_push, package_release"), "latest/edge", True), "edge")+ for permissions in ["package_release", "package_access, package_release", "package_push, package_release"]:+ with self.subTest(permissions=permissions), self.assertRaises(ValueError):+ verify_scope(whoami(permissions), "latest/edge", True)++ def test_existing_hash_never_uploads_again(self):+ result, mutation, _ = self.run_reconcile([revision()])+ self.assertEqual(result["revision"], 119)+ mutation.assert_not_called()++ def test_fresh_upload_records_store_verified_revision(self):+ _, mutation, states = self.run_reconcile([None, revision()])+ mutation.assert_called_once()+ self.assertEqual(states[-1]["state"], "reconciled")++ def test_lost_response_recovers_without_second_write(self):+ _, mutation, states = self.run_reconcile([None, None, revision()], True)+ mutation.assert_called_once()+ self.assertEqual(states[1]["state"], "upload_outcome_unknown")++ def test_read_error_prevents_upload(self):+ mutation = Mock()+ with self.assertRaises(RuntimeError):+ upload.reconcile(lookup=Mock(side_effect=RuntimeError()), upload=mutation, save_state=Mock())+ mutation.assert_not_called()++ def test_ambiguous_write_is_not_retried(self):+ mutation = Mock(side_effect=RuntimeError())+ with self.assertRaisesRegex(ValueError, 'unresolved'):+ upload.reconcile(lookup=Mock(return_value=None), upload=mutation, save_state=Mock(), sleep=lambda _: None)+ mutation.assert_called_once()++ def test_pending_or_rejected_revision_blocks_reupload(self):+ for status in ["ManualReviewPending", "NeedsInformation", "AutomaticallyRejected", "Rejected", "unknown"]:+ with self.subTest(status=status):+ mutation = Mock()+ with self.assertRaises(ValueError):+ upload.reconcile(lookup=lambda: revision(status=status), upload=mutation, save_state=Mock())+ mutation.assert_not_called()++ def test_hash_match_requires_arch_version_size_and_policy(self):+ for changes in [{"size": 13}, {"architectures": ["arm64"]}, {"version": "2.2.1"},+ {"confinement": "classic"}, {"grade": "devel"}, {"revision": 0}]:+ with self.subTest(changes=changes), self.assertRaises(ValueError):+ upload.matching_revision([revision(**changes)], "a" * 96, 12, "amd64", "2.2.0")+ with self.assertRaises(ValueError):+ upload.matching_revision([revision(), revision(revision=120)], "a" * 96, 12, "amd64", "2.2.0")+ self.assertIsNone(upload.matching_revision([revision()], "b" * 96, 12, "amd64", "2.2.0"))++ def test_reads_all_pages_including_unreleased_revisions(self):+ get = Mock(side_effect=[+ {"snap": {"name": "motrix"}, "revisions": [revision()], "_links": {"next": "?page=2"}},+ {"snap": {"name": "motrix"}, "revisions": [revision(revision=120)], "_links": {}},+ ])+ self.assertEqual(len(upload.list_revisions(get)), 2)+ self.assertEqual(get.call_args.args[0], upload.ENDPOINT + "?page=2")++ def test_pagination_never_sends_credentials_to_other_hosts(self):+ for link in ["https://evil.example/api", "//evil.example/path", "http://dashboard.snapcraft.io/x", "/other"]:+ get = Mock(return_value={"snap": {"name": "motrix"}, "revisions": [], "_links": {"next": link}})+ with self.subTest(link=link), self.assertRaises(ValueError):+ upload.list_revisions(get)+ get.assert_called_once()++ def test_changed_or_looping_snapshot_stops(self):+ data = {"snap": {"name": "motrix"}, "revisions": [revision()], "_links": {"next": "?size=500"}}+ with self.assertRaises(ValueError):+ upload.list_revisions(Mock(return_value=data))+++class SourceTests(unittest.TestCase):+ def setUp(self):+ self.run = {"id": 42, "event": "push", "head_branch": "v2.2.0", "head_sha": "a" * 40}+ self.jobs = [{"name": "Validate Snap source", "conclusion": "success"}]+ self.artifacts = []+ for index, arch in enumerate(publication.ARCHES):+ self.jobs.append({"name": f"Build Snap / {arch}", "conclusion": "success", "run_attempt": 1,+ "started_at": "2026-11-01T01:00:00Z", "completed_at": "2026-11-01T01:10:00Z"})+ self.artifacts.append({"name": f"snap-input-{arch}", "id": index + 1, "expired": False,+ "digest": "sha256:" + "b" * 64, "workflow_run": {"id": 42, "head_sha": "a" * 40},+ "created_at": "2026-11-01T01:09:00Z"})++ def validate(self):+ return publication.validate_source(self.run, self.jobs, self.artifacts, "agalwood/Motrix", "2.2.0", "a" * 40)++ def test_failed_publication_can_reuse_successful_original_builds(self):+ self.run["conclusion"] = "failure"+ self.assertEqual(self.validate()["run_id"], "42")++ def test_carried_forward_jobs_keep_original_build_attempt(self):+ for j in self.jobs[1:].copy():+ self.jobs.append({**j, "run_attempt": 2})+ self.assertEqual(self.validate()["artifacts"]["amd64"]["build_attempt"], 1)++ def test_rejects_wrong_tag_commit_or_event(self):+ for key, value in [("event", "pull_request"), ("event", "workflow_dispatch"),+ ("head_branch", "main"), ("head_sha", "b" * 40)]:+ with self.subTest(key=key, value=value), patch.dict(self.run, {key: value}), self.assertRaises(ValueError):+ self.validate()++ def test_rejects_expired_mutated_or_unbound_artifact(self):+ for changes in [{"expired": True}, {"digest": ""}, {"created_at": "2026-11-02T01:09:00Z"},+ {"workflow_run": {"id": 43, "head_sha": "a" * 40}}]:+ with self.subTest(changes=changes), patch.dict(self.artifacts[0], changes), self.assertRaises(ValueError):+ self.validate()++ def test_rejects_incomplete_or_failed_builds(self):+ with patch.dict(self.jobs[1], {"conclusion": "failure"}), self.assertRaises(ValueError):+ self.validate()+ self.artifacts.pop()+ with self.assertRaises(ValueError):+ self.validate()++ def test_receipts_cannot_mix_builds_architectures_or_publication_runs(self):+ source = self.validate()+ receipt = {"source": source, "architecture": "amd64", "publication_run_id": "45",+ "sha3_384": "c" * 96, "size": 12, "status": "verified", "revision": "119"}+ self.assertEqual(publication.validate_receipt(receipt, source, "amd64", "45", "c" * 96, 12), "119")+ for changes in [{"source": {}}, {"architecture": "arm64"}, {"publication_run_id": "46"},+ {"sha3_384": "d" * 96}, {"size": 13}, {"status": "pending"}]:+ with self.subTest(changes=changes), patch.dict(receipt, changes), self.assertRaises(ValueError):+ publication.validate_receipt(receipt, source, "amd64", "45", "c" * 96, 12)++ def test_archive_digest_checked_before_extracting(self):+ payload = io.BytesIO()+ with zipfile.ZipFile(payload, "w") as zipped:+ zipped.writestr("snap-amd64/motrix_2.2.0_amd64.snap", b"original snap")+ data = payload.getvalue()+ artifact = {"id": 1, "digest": "sha256:" + hashlib.sha256(data).hexdigest()}+ def download(args, **kwargs):+ kwargs["stdout"].write(data)+ with patch.object(subprocess, "run", side_effect=download):+ self.assertEqual(len(publication.archive("agalwood/Motrix", artifact)), 1)+ artifact["digest"] = "sha256:" + "0" * 64+ with self.assertRaisesRegex(ValueError, "digest mismatch"):+ publication.archive("agalwood/Motrix", artifact)++ def test_zip_paths_cannot_escape_destination(self):+ payload = io.BytesIO()+ with zipfile.ZipFile(payload, "w") as zipped:+ zipped.writestr("../escape.snap", b"invalid")+ data = payload.getvalue()+ def download(args, **kwargs):+ kwargs["stdout"].write(data)+ with patch.object(subprocess, "run", side_effect=download), self.assertRaises(ValueError):+ publication.archive("agalwood/Motrix", {"id": 1, "digest": "sha256:" + hashlib.sha256(data).hexdigest()})+++class PromotionRecoveryTests(unittest.TestCase):+ def test_recovery_requires_successful_protected_main_workflow_and_exact_receipts(self):+ run = {"event": "workflow_dispatch", "head_branch": "main", "status": "completed",+ "conclusion": "success", "run_attempt": 2, "head_sha": "b" * 40}+ source = {"run_id": "42", "version": "2.2.0"}+ receipts = {arch: {"source": source, "architecture": arch, "publication_run_id": "45",+ "sha3_384": "c" * 96, "size": 12, "status": "verified", "revision": str(119 + index)}+ for index, arch in enumerate(publication.ARCHES)}+ proof = {"source": source, "publication_run_id": "45", "receipts": receipts}+ revisions = {arch: receipt["revision"] for arch, receipt in receipts.items()}+ def files(*_):+ return {"snap-provenance.json": json.dumps(proof), "motrix-snap-revisions.json": json.dumps(revisions)}+ with patch.object(publication, "workflow_run", return_value=run), \+ patch.object(publication, "check_ancestry"), \+ patch.object(publication, "api", return_value=[{"artifacts": [{"name": "snap-release-revisions-2", "expired": False}]}]), \+ patch.object(publication, "archive", side_effect=files), \+ patch.object(publication, "original_source", return_value=source), \+ patch.object(publication, "download_snap", return_value=("c" * 96, 12)):+ def verify():+ publication.verify_recovery_promotion("agalwood/Motrix", "45", "2", "2.2.0")+ verify()+ for change in [{"event": "pull_request"}, {"head_branch": "feature"}, {"status": "in_progress"},+ {"conclusion": "failure"}, {"run_attempt": 1}]:+ with self.subTest(change=change), patch.dict(run, change), self.assertRaises(ValueError):+ verify()+ with patch.dict(revisions, {"arm64": "121"}), self.assertRaises(ValueError):+ verify()+ with patch.dict(proof, {"publication_run_id": "46"}), self.assertRaises(ValueError):+ verify()+ with patch.dict(receipts["amd64"], {"sha3_384": "d" * 96}), self.assertRaises(ValueError):+ verify()+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/scripts/workflow-snap.test.ts b/tests/scripts/workflow-snap.test.tsindex 9378df06..e85c363f 100644--- a/tests/scripts/workflow-snap.test.ts+++ b/tests/scripts/workflow-snap.test.ts@@ -1,13 +1,5 @@import { spawnSync } from 'node:child_process'-import {- chmodSync,- mkdirSync,- mkdtempSync,- readdirSync,- readFileSync,- rmSync,- writeFileSync,-} from 'node:fs'+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { createRequire } from 'node:module'import { tmpdir } from 'node:os'import path from 'node:path'@@ -139,342 +131,84 @@ describe('Snap build workflow contract', () => {expect(snapSource).not.toContain('pull_request_target')})- it('publishes protected tags and explicit protected-main recovery runs through the edge environment', () => {- const preflight = workflowJob(snapWorkflow, 'preflight')- const preflightOutputs = asRecord(preflight.outputs, 'preflight outputs')- const build = workflowJob(snapWorkflow, 'build')+ it('delegates only protected tags to the resumable publisher', () => {const publish = workflowJob(snapWorkflow, 'publish-edge')- const condition = stringField(publish, 'if')- const environment = asRecord(publish.environment, 'publish environment')-- expect(stringField(preflightOutputs, 'version')).toBe(- `\${{ steps.metadata.outputs.version }}`- )- expect(build).not.toHaveProperty('if')- expect(condition).toContain("github.event_name == 'push'")- expect(condition).toContain("startsWith(github.ref, 'refs/tags/v')")- expect(condition).toContain("github.event_name == 'workflow_dispatch'")- expect(condition).toContain('inputs.publish_edge == true')- expect(condition).toContain("github.ref == 'refs/heads/main'")- expect(condition).toContain('github.ref_protected == true')- expect(snapSource).not.toContain(- "needs.preflight.outputs.prerelease == 'false'"- )- expect(stringField(environment, 'name')).toBe('snap-store-edge')- expect(jobNeeds(publish)).toEqual(- expect.arrayContaining(['preflight', 'build'])- )- expect(publish['timeout-minutes']).toBeGreaterThanOrEqual(- boundedStepMinutes(publish) + 30- )-- const triggers = asRecord(snapWorkflow.on, 'Snap triggers')- expect(asRecord(triggers.push, 'push trigger')).toEqual({- tags: ['v*'],- })- expect(triggers).toHaveProperty('workflow_call')- const manual = asRecord(- triggers.workflow_dispatch,- 'workflow dispatch trigger'- )- const manualInputs = asRecord(manual.inputs, 'workflow dispatch inputs')- expect(asRecord(manualInputs.publish_edge, 'publish edge input')).toEqual({- description: 'Publish the protected main build to latest/edge',- required: true,- default: false,- type: 'boolean',- })- const concurrency = asRecord(snapWorkflow.concurrency, 'Snap concurrency')- expect(stringField(concurrency, 'group')).toContain(- 'inputs.publish_edge == true'- )- expect(stringField(concurrency, 'cancel-in-progress')).toContain(- 'inputs.publish_edge != true'- )+ expect(publish.uses).toBe('./.github/workflows/snap-publish.yml')+ expect(jobNeeds(publish)).toEqual(['preflight', 'build'])+ expect(publish.if).toContain("github.event_name == 'push'")+ expect(publish.if).toContain('github.ref_protected == true')+ expect(publish.if).not.toContain('workflow_dispatch')+ expect(publish.secrets).toBe('inherit')})+})- it('installs pinned verifier dependencies before verification and Store mutation', () => {- const steps = jobSteps(workflowJob(snapWorkflow, 'publish-edge'))- const checkout = steps.find(- (step) => step.name === 'Checkout verification tools'- )- const setupPnpm = steps.find(- (step) => step.name === 'Setup pnpm for verification'- )- const setupNode = steps.find(- (step) => step.name === 'Setup Node.js for verification'- )- const install = steps.find(- (step) => step.name === 'Install verifier dependencies'- )- const download = steps.find(- (step) => step.name === 'Download both architecture artifacts'- )- const completeness = steps.find(- (step) => step.name === 'Verify complete upload set'- )- const credentialValidation = steps.find(- (step) => step.name === 'Validate scoped Store credential'- )+const publicationWorkflow = asRecord(+ parseYaml(+ readFileSync(path.join(ROOT, '.github/workflows/snap-publish.yml'), 'utf8')+ ),+ 'Snap artifact publication'+)- expect(stringField(setupPnpm as LooseRecord, 'uses')).toBe(- 'pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413'- )- expect(asRecord(setupPnpm?.with, 'pnpm setup inputs')).toEqual({- version: '12.16.1',- run_install: false,+describe('Resumable Snap publication boundaries', () => {+ it('serializes Store operations while allowing failed uploads to resume independently', () => {+ expect(publicationWorkflow.concurrency).toEqual({+ group: 'snap-store-publication',+ 'cancel-in-progress': false,})- expect(stringField(setupNode as LooseRecord, 'uses')).toBe(- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'- )- expect(asRecord(setupNode?.with, 'Node setup inputs')).toEqual({- 'node-version': 24,- cache: 'pnpm',+ const upload = workflowJob(publicationWorkflow, 'upload')+ expect(upload.environment).toBe('snap-store-edge')+ expect(upload.strategy).toEqual({+ 'fail-fast': false,+ 'max-parallel': 1,+ matrix: { arch: ['amd64', 'arm64'] },})-- const installCommand = stringField(install as LooseRecord, 'run')- expect(installCommand).toBe(- 'pnpm install --frozen-lockfile --ignore-scripts'- )- expect(asRecord(install?.env, 'verifier install environment')).toEqual({- MOTRIX_SKIP_ELECTRON_REBUILD: '1',- MOTRIX_SKIP_ENGINE_FETCH: '1',- })-- expect(steps.indexOf(checkout as LooseRecord)).toBeLessThan(- steps.indexOf(setupPnpm as LooseRecord)- )- expect(steps.indexOf(setupPnpm as LooseRecord)).toBeLessThan(- steps.indexOf(setupNode as LooseRecord)- )- expect(steps.indexOf(setupNode as LooseRecord)).toBeLessThan(- steps.indexOf(install as LooseRecord)- )- expect(steps.indexOf(install as LooseRecord)).toBeLessThan(- steps.indexOf(download as LooseRecord)+ expect(jobNeeds(upload)).toEqual(['preflight'])+ const steps = jobSteps(upload)+ const lookup = steps.findIndex(+ (s) => s.name === 'Reconcile Store hash and upload at most once')- expect(steps.indexOf(install as LooseRecord)).toBeLessThan(- steps.indexOf(completeness as LooseRecord)- )- expect(steps.indexOf(completeness as LooseRecord)).toBeLessThan(- steps.indexOf(credentialValidation as LooseRecord)- )- for (const mutation of [- 'Upload complete build set',- 'Release exact build set to edge',- ]) {- const mutationStep = steps.find((step) => step.name === mutation)- expect(steps.indexOf(completeness as LooseRecord)).toBeLessThan(- steps.indexOf(mutationStep as LooseRecord)+ expect(+ steps.findIndex((s) => s.name === 'Verify edge credential scope')+ ).toBeLessThan(lookup)+ expect(+ steps.findIndex(+ (s) => s.name === 'Verify architecture package before Store access')- }- })-- it('uploads before releasing only the captured exact edge revisions', () => {- const steps = jobSteps(workflowJob(snapWorkflow, 'publish-edge'))- const inspectionTools = steps.find(- (step) => step.name === 'Install artifact inspection tools'- )- const completeness = steps.find(- (step) => step.name === 'Verify complete upload set'- )- const upload = steps.find(- (step) => step.name === 'Upload complete build set'- )- const release = steps.find(- (step) => step.name === 'Release exact build set to edge'- )- const publicVerification = steps.find(- (step) => step.name === 'Verify public edge channel'+ ).toBeLessThan(lookup)+ const record = steps.find(+ (s) => s.name === 'Preserve architecture receipt immediately')- const revisionRecord = steps.find(- (step) => step.name === 'Preserve trusted revision record'+ expect(record?.if).toContain('always()')+ expect(asRecord(record?.with, 'receipt').name).toContain(+ 'github.run_attempt')+ })- expect(stringField(inspectionTools as LooseRecord, 'run')).toContain(- 'squashfs-tools'- )- expect(steps.indexOf(inspectionTools as LooseRecord)).toBeLessThan(- steps.indexOf(completeness as LooseRecord)+ it('requires both receipts and Store revalidation before transactional edge release', () => {+ const publish = workflowJob(publicationWorkflow, 'publish-edge')+ expect(jobNeeds(publish)).toEqual(['preflight', 'upload'])+ const steps = jobSteps(publish)+ const release = steps.findIndex(+ (s) => s.name === 'Release exact build set to edge'+ )+ for (const name of [+ 'Aggregate verified architecture receipts',+ 'Validate scoped Store credential',+ 'Reverify both Store hashes before changing edge',+ ]) {+ const index = steps.findIndex((s) => s.name === name)+ expect(index).toBeGreaterThanOrEqual(0)+ expect(index).toBeLessThan(release)+ }+ expect(stringField(steps[release], 'run')).toContain(+ '--snapcraft-channel "$SNAPCRAFT_CHANNEL"')- const completenessCommand = stringField(completeness as LooseRecord, 'run')- expect(completenessCommand).toContain('for arch in amd64 arm64')- expect(completenessCommand).toContain('scripts/verify-snap-artifact.mjs')-- const uploadEnvironment = asRecord(upload?.env, 'upload environment')expect(- stringField(uploadEnvironment, 'SNAPCRAFT_STORE_CREDENTIALS')- ).toContain('secrets.SNAPCRAFT_STORE_CREDENTIALS')- const uploadCommand = stringField(upload as LooseRecord, 'run')- expect(uploadCommand).toContain(- `release/snap-verified/motrix_verified_\${arch}.snap`+ steps.findIndex((s) => s.name === 'Verify public edge channel')+ ).toBeLessThan(+ steps.findIndex((s) => s.name === 'Preserve trusted revision record'))- expect(uploadCommand).toContain('snapcraft upload "$snap"')- expect(uploadCommand).not.toContain('--release')- expect(uploadCommand).toContain('matchAll(/\\bRevision')- expect(uploadCommand).toContain('SNAP_REVISION_FILE')-- const releaseCommand = stringField(release as LooseRecord, 'run')- expect(release?.['timeout-minutes']).toBeGreaterThanOrEqual(45)- expect(releaseCommand).toContain('release-snap-build-set.mjs')- expect(releaseCommand).toContain('--channel latest/edge')- expect(releaseCommand).toContain('--amd64-revision')- expect(releaseCommand).toContain('--arm64-revision')- expect(releaseCommand).toContain('--snapcraft /snap/bin/snapcraft')- expect(releaseCommand).toContain('--snapcraft-timeout-ms 120000')- expect(releaseCommand).not.toContain('snapcraft promote')- expect(steps.indexOf(upload as LooseRecord)).toBeLessThan(- steps.indexOf(release as LooseRecord)- )-- const verification = stringField(publicVerification as LooseRecord, 'run')- expect(verification).toContain('verify-snap-store-channel.mjs')- expect(verification).toContain('--architectures amd64,arm64')- expect(verification).toContain('--expected-revisions "$SNAP_REVISION_FILE"')- expect(steps.indexOf(publicVerification as LooseRecord)).toBeLessThan(- steps.indexOf(revisionRecord as LooseRecord)- )- const recordInputs = asRecord(- revisionRecord?.with,- 'revision record inputs'- )- expect(stringField(recordInputs, 'name')).toContain('github.run_attempt')- expect(stringField(recordInputs, 'path')).toContain('SNAP_REVISION_FILE')- })-- it('normalizes the real nested artifact layout into one exact verified set', () => {- const fixture = createSnapUploadFixture()- try {- writeNestedSnap(- fixture.root,- 'amd64',- 'motrix_2.0.0-beta.2_amd64.snap',- 'amd64-payload'- )- writeNestedSnap(- fixture.root,- 'arm64',- 'motrix_2.0.0-beta.2_arm64.snap',- 'arm64-payload'- )- const reportDirectory = path.join(- fixture.root,- 'release',- 'snap-upload',- 'size-reports'- )- mkdirSync(reportDirectory, { recursive: true })- writeFileSync(path.join(reportDirectory, 'linux-x64.json'), '{}')-- const result = runSnapSetVerification(fixture)-- expect(result.status, result.stderr).toBe(0)- const verifiedDirectory = path.join(- fixture.root,- 'release',- 'snap-verified'- )- expect(readdirSync(verifiedDirectory).sort()).toEqual([- 'motrix_verified_amd64.snap',- 'motrix_verified_arm64.snap',- ])- expect(- readFileSync(- path.join(verifiedDirectory, 'motrix_verified_amd64.snap'),- 'utf8'- )- ).toBe('amd64-payload')- expect(- readFileSync(- path.join(verifiedDirectory, 'motrix_verified_arm64.snap'),- 'utf8'- )- ).toBe('arm64-payload')- expect(- readFileSync(fixture.verificationLog, 'utf8').trim().split('\n')- ).toEqual([- 'scripts/verify-snap-artifact.mjs --snap release/snap-upload/snap-amd64/motrix_2.0.0-beta.2_amd64.snap --arch amd64 --version 2.0.0-beta.2',- 'scripts/verify-snap-artifact.mjs --snap release/snap-upload/snap-arm64/motrix_2.0.0-beta.2_arm64.snap --arch arm64 --version 2.0.0-beta.2',- ])- } finally {- rmSync(fixture.root, { recursive: true, force: true })- }- })-- it.each([- {- label: 'a missing architecture',- prepare(root: string) {- writeNestedSnap(- root,- 'amd64',- 'motrix_2.0.0-beta.2_amd64.snap',- 'amd64'- )- },- error: /Expected exactly two Snap artifacts, found 1/,- },- {- label: 'an extra Snap',- prepare(root: string) {- writeNestedSnap(- root,- 'amd64',- 'motrix_2.0.0-beta.2_amd64.snap',- 'amd64'- )- writeNestedSnap(- root,- 'arm64',- 'motrix_2.0.0-beta.2_arm64.snap',- 'arm64'- )- writeFileSync(- path.join(root, 'release', 'snap-upload', 'unexpected.snap'),- 'extra'- )- },- error: /Expected exactly two Snap artifacts, found 3/,- },- {- label: 'a duplicate basename',- prepare(root: string) {- for (const arch of ['amd64', 'arm64'] as const) {- writeNestedSnap(root, arch, 'motrix_2.0.0-beta.2_amd64.snap', arch)- }- },- error: /Duplicate Snap artifact basename/,- },- {- label: 'an architecture-mismatched name',- prepare(root: string) {- writeNestedSnap(- root,- 'amd64',- 'motrix_2.0.0-beta.2_amd64.snap',- 'amd64'- )- writeNestedSnap(- root,- 'arm64',- 'motrix_2.0.0-beta.2_s390x.snap',- 'arm64'- )- },- error: /Unexpected arm64 Snap artifact name/,- },- ])('rejects $label before upload', ({ prepare, error }) => {- const fixture = createSnapUploadFixture()- try {- prepare(fixture.root)-- const result = runSnapSetVerification(fixture)-- expect(result.status).not.toBe(0)- expect(result.stderr).toMatch(error)- } finally {- rmSync(fixture.root, { recursive: true, force: true })- }+ expect(JSON.stringify(publish)).not.toContain('snapcraft upload')})})@@ -524,7 +258,9 @@ describe('Snap promotion workflow contract', () => {)expect(stringField(concurrency, 'group')).toBe('snap-store-publication')expect(concurrency['cancel-in-progress']).toBe(false)- expect(snapSource).toContain("'snap-store-publication'")+ expect(+ asRecord(publicationWorkflow.concurrency, 'publication lock').group+ ).toBe('snap-store-publication')const preflight = workflowJob(promotionWorkflow, 'preflight')expect(preflight['timeout-minutes']).toBeGreaterThanOrEqual(15)@@ -1133,62 +869,6 @@ function runPromotionSourceValidation(}}-interface SnapUploadFixture {- root: string- verificationLog: string-}--function createSnapUploadFixture(): SnapUploadFixture {- const root = mkdtempSync(path.join(tmpdir(), 'motrix-snap-workflow-'))- const binaryDirectory = path.join(root, 'bin')- const verificationLog = path.join(root, 'verification.log')- // Dependency provisioning is covered by the static publish-edge contract;- // this stub isolates artifact layout and verifier invocation behavior.- const nodeStub = path.join(binaryDirectory, 'node')- mkdirSync(binaryDirectory, { recursive: true })- mkdirSync(path.join(root, 'release', 'snap-upload'), { recursive: true })- writeFileSync(- nodeStub,- [- '#!/usr/bin/env bash',- 'set -euo pipefail',- `printf '%s\\n' "$*" >> "$VERIFY_LOG"`,- '',- ].join('\n')- )- chmodSync(nodeStub, 0o755)- return { root, verificationLog }-}--function writeNestedSnap(- root: string,- arch: 'amd64' | 'arm64',- name: string,- contents: string-): void {- const directory = path.join(root, 'release', 'snap-upload', `snap-${arch}`)- mkdirSync(directory, { recursive: true })- writeFileSync(path.join(directory, name), contents)-}--function runSnapSetVerification(fixture: SnapUploadFixture) {- const completeness = jobSteps(workflowJob(snapWorkflow, 'publish-edge')).find(- (step) => step.name === 'Verify complete upload set'- )- const command = stringField(completeness as LooseRecord, 'run')- const binaryDirectory = path.join(fixture.root, 'bin')- return spawnSync('bash', ['-c', command], {- cwd: fixture.root,- encoding: 'utf8',- env: {- ...process.env,- EXPECTED_VERSION: '2.0.0-beta.2',- PATH: `${binaryDirectory}:${process.env.PATH ?? ''}`,- VERIFY_LOG: fixture.verificationLog,- },- })-}-function asRecord(value: unknown, label: string): LooseRecord {if (value === null || typeof value !== 'object' || Array.isArray(value)) {throw new TypeError(`${label} must be an object`)