diff --git a/.github/actions/ci-candidate/action.yml b/.github/actions/ci-candidate/action.yml new file mode 100644 index 0000000..bd195bb --- /dev/null +++ b/.github/actions/ci-candidate/action.yml @@ -0,0 +1,27 @@ +name: Download verified CI candidate +description: Retrieve the preflight-verified archive and fail closed if its bytes changed in transit. +inputs: + digest: + description: SHA-256 of the original immutable CI artifact archive + required: true +runs: + using: composite + steps: + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: '24' + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: verified-ci-candidate + path: ci-candidate + - name: Verify the original CI archive before extraction or signing + shell: bash + env: + CI_ARTIFACT_DIGEST: ${{ inputs.digest }} + run: | + node --input-type=module -e ' + import { createHash } from "node:crypto"; + import { readFileSync } from "node:fs"; + const actual = "sha256:" + createHash("sha256").update(readFileSync("ci-candidate/ci-candidate.zip")).digest("hex"); + if (actual !== process.env.CI_ARTIFACT_DIGEST) throw new Error("CI artifact checksum mismatch"); + ' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a8296e0..319de11 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,6 +56,7 @@ jobs: run: sh scripts/test-distribution.sh check: + name: check (${{ matrix.os }}) strategy: fail-fast: false matrix: @@ -83,13 +84,19 @@ jobs: - run: cargo build --locked --all-targets - run: cargo test --locked --all-targets - run: cargo clippy --locked --all-targets -- -D warnings - - name: Validate the Intel app bundle without signing credentials - if: matrix.os == 'macos-15-intel' + - name: Build the unsigned macOS release candidate + if: runner.os == 'macOS' shell: bash + env: + MACOSX_DEPLOYMENT_TARGET: ${{ matrix.os == 'macos-15-intel' && '13.3' || '13.0' }} run: | cargo install cargo-packager --version 0.11.8 --locked cargo build --release --locked cargo packager --release --formats app + - name: Validate the Intel app bundle without signing credentials + if: matrix.os == 'macos-15-intel' + shell: bash + run: | sh scripts/prepare-intel-app.sh dist/packages/Mist.app - name: Test real Intel speech generation if: matrix.os == 'macos-15-intel' @@ -99,13 +106,27 @@ jobs: run: | dist/packages/Mist.app/Contents/MacOS/mist --install-model cargo test --release --locked --test kokoro_smoke -- --ignored --nocapture - ditto -c -k --keepParent dist/packages/Mist.app dist/packages/Mist-intel-ci.zip - - name: Retain the unsigned Intel candidate and runtime provenance - if: matrix.os == 'macos-15-intel' + - name: Archive the unsigned macOS candidate with permissions and provenance + if: runner.os == 'macOS' + run: tar -cf dist/packages/Mist.app.tar -C dist/packages Mist.app + - name: Retain the unsigned macOS candidate + if: runner.os == 'macOS' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: mist-ci-${{ matrix.os == 'macos-latest' && 'macos-aarch64' || 'macos-x86_64' }}-${{ github.sha }}-attempt-${{ github.run_attempt }} + path: dist/packages/Mist.app.tar + retention-days: 90 + if-no-files-found: error + - name: Build the unsigned Windows release candidate + if: runner.os == 'Windows' + run: cargo build --release --locked + - name: Retain the unsigned Windows candidate + if: runner.os == 'Windows' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - name: mist-intel-ci-${{ github.sha }} - path: dist/packages/Mist-intel-ci.zip + name: mist-ci-windows-x86_64-${{ github.sha }}-attempt-${{ github.run_attempt }} + path: target/release/mist.exe + retention-days: 90 if-no-files-found: error - name: Validate POSIX release installer if: runner.os != 'Windows' @@ -138,7 +159,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: ./.github/actions/linux-packages with: - artifact-name: mist-linux-validation-${{ github.sha }} + artifact-name: mist-ci-linux-${{ github.sha }}-attempt-${{ github.run_attempt }} quality: name: Quality and security gates diff --git a/.github/workflows/release-platform.yml b/.github/workflows/release-platform.yml index e42bdfb..9647038 100644 --- a/.github/workflows/release-platform.yml +++ b/.github/workflows/release-platform.yml @@ -19,6 +19,8 @@ jobs: runs-on: ubuntu-22.04 outputs: channel: ${{ steps.release.outputs.channel }} + ci-run-id: ${{ steps.ci.outputs.ci-run-id }} + artifact-digest: ${{ steps.ci.outputs.artifact-digest }} permissions: contents: read actions: read @@ -63,10 +65,18 @@ jobs: fi echo "channel=$channel" >> "$GITHUB_OUTPUT" - - name: Verify successful main CI for the exact release commit + - name: Verify platform CI and download its exact-commit candidate + id: ci env: GH_TOKEN: ${{ github.token }} + RELEASE_PLATFORM: ${{ inputs.platform }} + CI_CANDIDATE_ARCHIVE: ci-candidate.zip run: node scripts/verify-release-ci.mjs + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: verified-ci-candidate + path: ci-candidate.zip + if-no-files-found: error macos: if: startsWith(inputs.platform, 'macos-') @@ -79,12 +89,9 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.sha }} - - name: Install Rust 1.95 - run: | - rustup toolchain install 1.95.0 --profile minimal - rustup default 1.95.0 - - uses: ./.github/actions/intel-onnxruntime - if: inputs.platform == 'macos-x86_64' + - uses: ./.github/actions/ci-candidate + with: + digest: ${{ needs.preflight.outputs.artifact-digest }} - name: Require Apple release credentials shell: bash env: @@ -101,13 +108,13 @@ jobs: exit 1 fi done - - name: Install cargo-packager - run: cargo install cargo-packager --version "$CARGO_PACKAGER_VERSION" --locked - - name: Build app bundle + - name: Extract and validate the CI-built app bundle run: | - cargo build --release --locked - cargo packager --release --formats app + mkdir -p candidate dist/packages + ditto -x -k ci-candidate/ci-candidate.zip candidate + tar -xf candidate/Mist.app.tar -C dist/packages /usr/libexec/PlistBuddy -c "Print :NSServices" dist/packages/Mist.app/Contents/Info.plist >/dev/null + test "$(/usr/libexec/PlistBuddy -c 'Print :MistReleaseVersion' dist/packages/Mist.app/Contents/Info.plist)" = "$(tr -d '[:space:]' < VERSION)" binary=dist/packages/Mist.app/Contents/MacOS/mist test "$(lipo -archs "$binary")" = "${{ inputs.platform == 'macos-aarch64' && 'arm64' || 'x86_64' }}" test -f dist/packages/Mist.app/Contents/Resources/licenses/kokoro-micro-NOTICE @@ -115,7 +122,15 @@ jobs: test -f dist/packages/Mist.app/Contents/Resources/licenses/NotoSansDevanagariUI-OFL - name: Validate Intel runtime packaging if: inputs.platform == 'macos-x86_64' - run: sh scripts/prepare-intel-app.sh dist/packages/Mist.app + run: | + app=dist/packages/Mist.app + binary="$app/Contents/MacOS/mist" + test "$(vtool -show-build "$binary" | awk '$1 == "minos" { print $2 }')" = 13.3 + test "$(/usr/libexec/PlistBuddy -c 'Print :LSMinimumSystemVersion' "$app/Contents/Info.plist")" = 13.3 + test -z "$(otool -L "$binary" | awk 'NR > 1 && $1 !~ /^\/System\/Library\// && $1 !~ /^\/usr\/lib\// { print $1 }')" + for file in ONNX-Runtime-LICENSE ONNX-Runtime-ThirdPartyNotices.txt ONNX-Runtime-provenance.txt; do + test -s "$app/Contents/Resources/licenses/$file" + done - name: Import Developer ID certificate id: keychain shell: bash @@ -206,6 +221,9 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.sha }} + - uses: ./.github/actions/ci-candidate + with: + digest: ${{ needs.preflight.outputs.artifact-digest }} - name: Install Rust 1.95 shell: pwsh run: | @@ -227,11 +245,12 @@ jobs: $PSNativeCommandUseErrorActionPreference = $true choco install nsis --no-progress -y cargo install cargo-packager --version $env:CARGO_PACKAGER_VERSION --locked - - name: Build executable + - name: Extract and validate the CI-built executable shell: pwsh run: | $PSNativeCommandUseErrorActionPreference = $true - cargo build --release --locked + New-Item -ItemType Directory -Force target\release | Out-Null + Expand-Archive -LiteralPath ci-candidate\ci-candidate.zip -DestinationPath target\release $binary = [IO.File]::ReadAllBytes("target\release\mist.exe") $peOffset = [BitConverter]::ToInt32($binary, 0x3c) $machine = [BitConverter]::ToUInt16($binary, $peOffset + 4) @@ -306,9 +325,23 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.sha }} - - uses: ./.github/actions/linux-packages + - uses: ./.github/actions/ci-candidate with: - packager-version: ${{ env.CARGO_PACKAGER_VERSION }} + digest: ${{ needs.preflight.outputs.artifact-digest }} + - name: Extract the CI-validated DEB and AppImage without rebuilding + run: | + mkdir -p dist/release + unzip -q ci-candidate/ci-candidate.zip -d dist/release + test -s dist/release/Mist-linux-x86_64.deb + test -s dist/release/Mist-linux-x86_64.AppImage + chmod 755 dist/release/Mist-linux-x86_64.AppImage + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: mist-linux-x86_64 + path: | + dist/release/Mist-linux-x86_64.deb + dist/release/Mist-linux-x86_64.AppImage + if-no-files-found: error publish_preview: # Unselected builders are skipped. Override the implicit success() guard, @@ -362,4 +395,4 @@ jobs: gh release create "$GITHUB_REF_NAME" release-assets/* \ --draft --prerelease --verify-tag --latest=false \ --title "Mist $GITHUB_REF_NAME — $RELEASE_PLATFORM preview" \ - --notes "Early-access $RELEASE_PLATFORM preview built from $GITHUB_SHA after exact-commit main CI passed. Only this platform is included. Verify SHA256SUMS before installing. The curl/PowerShell installer requires explicit MIST_RELEASE=$GITHUB_REF_NAME, not latest. See the distribution guide for system requirements. Clean-machine installation and speech acceptance remain required before a stable desktop release." + --notes "Early-access $RELEASE_PLATFORM preview promoted from CI run ${{ needs.preflight.outputs.ci-run-id }} for $GITHUB_SHA after shared quality/security and this platform's CI checks passed. No application recompilation in Release. Only this platform is included. Verify SHA256SUMS before installing. The curl/PowerShell installer requires explicit MIST_RELEASE=$GITHUB_REF_NAME, not latest. See the distribution guide for system requirements. Clean-machine installation and speech acceptance remain required before a stable desktop release." diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b53b952..3fc2ff4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -79,23 +79,30 @@ signed release or clean-machine acceptance. Never commit credentials or publish an unsigned stable release. A pre-release website may show unavailable downloads or clearly labeled platform previews, following the distribution guide. Linux, Apple Silicon Mac, Intel Mac, and Windows have independent release -workflows using shared native build/signing logic. One release failure does not -block another platform's draft preview; all still require successful main CI. +workflows using shared native signing/promotion logic. One platform's failed or +unfinished CI does not block another platform's draft preview. Each release +requires the shared metadata/website and quality/security checks, plus its own +native CI checks on the exact merged commit (Linux also needs package validation). Release runs only for version-tag pushes or manual candidate runs from `main`. Tests and quality/security analysis belong to CI. Before packaging or signing, -Release verifies the latest push-to-`main` CI run for its exact commit and every -required check from `.github/rulesets/main-quality.json`. A PR merge-ref result, -another commit, a failed/skipped check, or unavailable evidence cannot authorize -a release. Rerun all integration-CI jobs on `main` if evidence is incomplete; -Release does not rerun the test suite or substitute another successful run. +Release verifies the latest push-to-`main` CI run/attempt for its exact commit and +the selected platform's required checks. Main still requires all seven checks +for merging; its ruleset is unchanged. A PR merge-ref result, another commit, +a failed/skipped/missing selected or shared check, or unavailable evidence cannot +authorize a release. CI retains optimized candidates named by platform, SHA, and +attempt. Release downloads the selected immutable artifact by ID, verifies its +SHA-256 before extraction, and promotes it without recompiling the application. +Expired or missing artifacts require a new CI run, not a rebuild in Release. +Mac signing/notarization and DMG creation, and Windows signing/NSIS assembly, +remain in Release. Linux reuses the validated DEB/AppImage byte-for-byte. Protected signing/publishing environments and draft-only publication remain. -The Linux packaging composite is shared between CI validation and Release. +The Linux packaging composite runs in CI; Release promotes its retained packages. Intel macOS additionally uses the revision-pinned source build described in [distribution](docs/DISTRIBUTION.md#intel-macos-runtime). Set its absolute `ORT_LIB_PATH` before running local checks; ordinary `ort-sys` downloads do not contain an Intel Mac runtime. The `check (macos-15-intel)` job uses the same -CPU runtime preparation as Release, validates an unsigned release-mode app, -and runs the downloaded-model multilingual smoke test. It receives no signing -credentials. The versioned ruleset and Release verifier require this check; +CPU runtime preparation used to build the release candidate, validates an unsigned +release-mode app, and runs the downloaded-model multilingual smoke test. It receives no signing +credentials. The versioned main ruleset and Intel release verifier require this check; only the owner may add its new context to the existing server ruleset. diff --git a/docs/DISTRIBUTION.md b/docs/DISTRIBUTION.md index a1dfbe7..b724cad 100644 --- a/docs/DISTRIBUTION.md +++ b/docs/DISTRIBUTION.md @@ -116,9 +116,21 @@ stable `0.1.0`; the compiled app still identifies as `0.1.0-rc.1`. Each platform can be distributed for early testing as soon as its own build and signing succeed. These independent pipelines share `release-platform.yml`; they -do not wait for another platform's release/signing jobs. They still require all -required main CI checks on the exact source commit. CI, signing, and publication -protections are unchanged; there is no combined release workflow. +do not wait for another platform's CI or release/signing jobs. Every release +requires `Repository metadata, workflows, and website` and `Quality and security +gates`, plus only its selected platform's checks on the exact source commit: + +| Platform | Additional required CI checks | +| --- | --- | +| Linux | `check (ubuntu-latest)` and `Linux package validation` | +| Apple Silicon | `check (macos-latest)` | +| Intel Mac | `check (macos-15-intel)` | +| Windows | `check (windows-latest)` | + +Main's seven-check merge protection, signing, and publication protections are +unchanged; there is no combined release workflow. CI builds optimized candidates +once for each commit/attempt. Release promotes those exact binaries/packages; +it does not recompile the app or the Intel inference runtime. | Actions workflow | Example protected tag | Installer assets | | --- | --- | --- | @@ -132,15 +144,15 @@ without creating a release. Publishing starts only when the matching protected platform tag is pushed. A common tag such as `v0.1.0-rc.1` starts no release. Changing `VERSION` alone also starts no release: preflight validates the tag against synchronized Cargo and macOS version metadata and successful exact-commit -main CI. Homebrew and Chocolatey recipe/feed publication remains separate work; +shared/platform main CI. Homebrew and Chocolatey recipe/feed publication remains separate work; no combined bundle or package-manager publication is run by these pipelines. 1. Merge the preview workflow/website changes through a PR and wait for all - required CI checks on that exact `main` commit. Do not tag the old workflow. + shared and selected-platform CI checks on that exact `main` commit. Do not tag the old workflow. 2. The release maintainer creates the chosen platform's tag from the table on that validated commit. Its full candidate version must match `VERSION`; RC numbers are positive integers. Use a new candidate for changed builds, not replacement assets. -3. Only that platform builds, validates, and (for Mac/Windows) signs. Mac requires +3. Only that platform's CI candidate is verified, promoted, and (for Mac/Windows) signed. Mac requires successful notarization and stapling; Windows requires Authenticode and the configured publisher. Linux uses the existing native package action without Apple or Windows configuration. Complete assembly and package recipes do not run. @@ -211,8 +223,9 @@ installer. ONNX Runtime 1.28.0 at source commit `da9b5e364c465de65c49d91e696cd6485270757f`, compiled natively with the CPU provider and static linkage. Apple Silicon keeps its existing Core ML runtime. -The shared `.github/actions/intel-onnxruntime` action prepares this runtime in -both CI and Release. Its exact cache key includes the compiler/SDK identity +The `.github/actions/intel-onnxruntime` action prepares this runtime only in CI. +Release reuses the CI-built app, including runtime notices and provenance, +without rebuilding ONNX Runtime. Its exact cache key includes the compiler/SDK identity and builder/action content; it does not use approximate restore keys. For a local Intel source build, install Xcode Command Line Tools and uv, then: @@ -336,16 +349,27 @@ and download its individual Actions artifacts. macOS requires the Apple signing credentials; Windows requires the Windows signing credentials. Linux can be tested while either signing setup is pending. Every candidate or tagged release validates its source/version, then verifies -successful integration CI for the exact release commit before platform packaging +successful shared/platform CI for the exact release commit before native signing or access to signing environments. CI owns audio and other tests, CRAP, Smells, OSV, and Gitleaks; Release does not repeat them. The verifier requires the latest -push-to-`main` run of `.github/workflows/ci.yml` and all required jobs in its latest -attempt to succeed. PR/merge-ref runs, wrong commits, failed/skipped/missing jobs, -API errors, incomplete pagination, and concurrent reruns fail closed. If main CI -is still running, wait and retry the candidate. For a partial or failed rerun, -rerun all CI jobs on that main commit rather than bypassing the release gate. -Linux packaging is shared between CI and Release; PR CI cannot call the -signing/publishing jobs. +push-to-`main` run of `.github/workflows/ci.yml` and the shared and selected-platform +jobs in its latest attempt to succeed. Unrelated pending/failed/cancelled jobs +do not block promotion. PR/merge-ref runs, wrong commits, failed/skipped/missing +required jobs, API errors, incomplete pagination, and concurrent reruns fail closed. +Each optimized CI candidate is named `mist-ci---attempt-`. +Release requires exactly one nonempty, unexpired artifact from that run/attempt +and repository, downloads it by immutable ID, and checks GitHub's SHA-256 digest +before extracting. The raw archive is checked again after transfer to the native +job. Missing, expired, or incomplete latest-attempt evidence requires a CI rerun; +Release never falls back to an older build or recompiles the app. Retention is +up to 90 days, subject to repository limits. + +Linux retains the validated DEB/AppImage unchanged. Mac retains a tarred unsigned +app to preserve permissions, then signs/notarizes it and creates the DMG. Windows +retains the optimized unsigned EXE, signs it, assembles NSIS around that signed +binary, and signs the installer. Packaging/signing tools may be installed, but +application compilation remains exclusively in CI. PR CI cannot call the +signing/publishing jobs, and its temporary merge-ref artifacts are never promoted. Manual runs create only that platform's Actions artifacts, not a tag or GitHub Release. There is no `all` option or cross-platform assembly dependency. Use a @@ -355,7 +379,7 @@ candidate run when troubleshooting packaging before choosing a platform tag. 1. Synchronize `VERSION`, `Cargo.toml`, `Cargo.lock`, and the macOS bundle version, then run `./scripts/release-check.sh`. -2. Wait for all required integration-CI checks on the exact commit on `main`, +2. Wait for shared and selected-platform CI checks and its retained candidate on the exact commit on `main`, and verify the chosen platform's signing prerequisites. 3. Create and push the matching `v-` tag from the table above. Only that platform packages on its native runner and creates a new diff --git a/docs/RELEASE_GATES_SPEC.md b/docs/RELEASE_GATES_SPEC.md index 42ffc39..ed47703 100644 --- a/docs/RELEASE_GATES_SPEC.md +++ b/docs/RELEASE_GATES_SPEC.md @@ -217,3 +217,37 @@ package assembly, not any CI, signing, owner-merge, or publication protection. code, credentials, server rules, tags, published assets, tap, or feed changes are part of this cleanup. Future stable channels and independent package-manager recipes are separate work, not a hidden common release trigger. + +## Platform-scoped CI gates and build-once promotion + +Requested on 2026-10-06. Review only this fix against merged main +`45615abf35872161eb2e9b5b0091e96e585f5230`. This supersedes the seven-job +release gate and recompilation in Release, not main's seven-check merge rules. + +- Each release requires successful shared metadata/website and quality/security + checks, plus its native check on the latest canonical push-to-main run/attempt + for the exact tag commit. Linux additionally requires package validation. + Unrelated platform jobs may be pending, failed, cancelled, skipped, or missing + without blocking that release. Required evidence still fails closed on those + states, duplicate jobs, wrong identity, incomplete pagination, or API errors. +- CI retains optimized candidates under platform/SHA/attempt-qualified names: + validated DEB/AppImage for Linux, permission-preserving unsigned app archives + for both Macs, and an unsigned optimized Windows EXE. PR candidates are test + artifacts only; release consumes merged-commit main CI, never a merge-ref build. +- Select exactly one unexpired nonempty candidate from the verified run and + attempt. Require its matching source/repository and SHA-256 archive digest; + download by immutable artifact ID and fail on corrupted bytes. Recheck latest + run/attempt after download, then recheck the raw archive on native handoff. + Missing or expired candidates require fresh CI, never fallback or recompilation. +- Release does not compile the app or Intel runtime or rerun application/audio + tests. It promotes Linux packages unchanged; Mac signs/notarizes/staples and + creates a DMG; Windows signs the retained EXE before NSIS assembly and signs + the installer. Keep version/platform tag validation, pinned event checkouts, + native architecture checks, protected approvals, attestations, selected asset + contract validation, draft prereleases, and refusal to overwrite releases. +- Keep all seven PR/main checks, hooks, CRAP thresholds/baseline, Smells, OSV, + Gitleaks, native audio checks, and signing identities unchanged. Do not change + credentials, server rules, app version, tags, public assets, taps, or feeds. +- Test the real gate CLI with only GitHub HTTP/storage boundaries substituted, + and the actual CI/release YAML and native archive-handoff command. Commit/push + a feature branch and open a PR; merging and tagging remain maintainer actions. diff --git a/scripts/test-release-ci.mjs b/scripts/test-release-ci.mjs index 89ff686..40804cd 100644 --- a/scripts/test-release-ci.mjs +++ b/scripts/test-release-ci.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { env as environment } from 'node:process'; @@ -27,7 +27,7 @@ function fixture(t) { id: 123, workflow_id: 456, run_attempt: 1, event: 'push', head_branch: 'main', head_sha: commit, status: 'completed', conclusion: 'success', path: '.github/workflows/ci.yml', - repository: { full_name: repository }, head_repository: { full_name: repository }, + repository: { id: 42, full_name: repository }, head_repository: { id: 42, full_name: repository }, }; const responses = { [`${prefix}/workflows/ci.yml`]: { id: 456, state: 'active', path: '.github/workflows/ci.yml' }, @@ -37,18 +37,36 @@ function fixture(t) { total_count: 7, jobs: required.map(name => ({ name, head_sha: commit, run_id: 123, run_attempt: 1, status: 'completed', conclusion: 'success' })), }, + [`${prefix}/runs/123/artifacts?page=1`]: { + total_count: 4, + artifacts: ['linux', 'macos-aarch64', 'macos-x86_64', 'windows-x86_64'].map((platform, index) => ({ + id: 789 + index, name: `mist-ci-${platform}-${commit}-attempt-1`, + size_in_bytes: 20, digest: 'sha256:03bbb0874ab942ba8e81bb2d49032b3737d834e5ee0e323f04718f233721e882', + expired: false, expires_at: '2099-01-01T00:00:00Z', + workflow_run: { id: 123, head_sha: commit, head_branch: 'main', repository_id: 42, head_repository_id: 42 }, + })), + }, }; const updates = {}; + const storage = { body: 'ci-candidate-fixture', location: 'https://storage.example/candidate.zip', status: 302 }; return { - responses, run, updates, + responses, run, updates, directory, storage, verify(overrides = {}) { const preload = path.join(directory, 'github-api.mjs'); // Mock only GitHub's external HTTP boundary, not the verification code. writeFileSync(preload, `const responses = ${JSON.stringify(responses)}; const updates = ${JSON.stringify(updates)}; -globalThis.fetch = async input => { +const storage = ${JSON.stringify(storage)}; +globalThis.fetch = async (input, options) => { const url = new URL(input); + if (url.origin === 'https://storage.example') { + if (options.headers?.Authorization) throw new Error('GitHub token leaked to storage'); + return { ok: true, body: [Buffer.from(storage.body)] }; + } if (url.origin !== 'https://api.github.com') throw new Error('Unexpected API host'); + if (/\\/artifacts\\/\\d+\\/zip$/.test(url.pathname)) { + return { status: storage.status, headers: new Headers({ location: storage.location }) }; + } const key = url.pathname + (url.searchParams.has('page') ? '?page=' + url.searchParams.get('page') : ''); if (!(key in responses)) return { ok: false, status: 404 }; const value = responses[key]; @@ -57,7 +75,8 @@ globalThis.fetch = async input => { };\n`); return spawnSync(process.execPath, ['--import', preload, 'scripts/verify-release-ci.mjs'], { cwd: root, encoding: 'utf8', - env: { ...environment, GITHUB_REPOSITORY: repository, GITHUB_SHA: commit, GH_TOKEN: 'fixture-token', ...overrides }, + env: { ...environment, GITHUB_REPOSITORY: repository, GITHUB_SHA: commit, GH_TOKEN: 'fixture-token', + RELEASE_PLATFORM: 'linux', GITHUB_OUTPUT: '', CI_CANDIDATE_ARCHIVE: '', ...overrides }, }); }, }; @@ -118,6 +137,15 @@ test('release accepts a successful main CI run with all required checks for its assert.match(result.stdout, /Verified CI/); }); +test('Apple Silicon release accepts its successful checks when unrelated Intel CI fails', t => { + const f = fixture(t); + f.run.conclusion = 'failure'; + f.responses[`${prefix}/runs/123/attempts/1/jobs?page=1`].jobs + .find(job => job.name === 'check (macos-15-intel)').conclusion = 'failure'; + const result = f.verify({ RELEASE_PLATFORM: 'macos-aarch64' }); + assert.equal(result.status, 0, result.stdout + result.stderr); +}); + for (const [name, changes] of [ ['a different commit', { head_sha: 'b'.repeat(40) }], ['a PR run rather than main integration CI', { event: 'pull_request' }], @@ -126,8 +154,7 @@ for (const [name, changes] of [ ['a different workflow path', { path: '.github/workflows/other.yml' }], ['a fork repository', { repository: { full_name: 'contributor/Mist' } }], ['a fork source', { head_repository: { full_name: 'contributor/Mist' } }], - ['unfinished CI', { status: 'in_progress', conclusion: null }], - ['failed CI', { conclusion: 'failure' }], + ['missing repository identity', { repository: { full_name: repository } }], ]) { test(`release rejects ${name} even when other CI evidence looks successful`, t => { const f = fixture(t); @@ -136,6 +163,121 @@ for (const [name, changes] of [ }); } +for (const state of ['in_progress', 'failure', 'cancelled']) { + test(`release does not depend on overall CI being green when unrelated work is ${state}`, t => { + const f = fixture(t); + Object.assign(f.run, state === 'in_progress' + ? { status: 'in_progress', conclusion: null } : { conclusion: state }); + const result = f.verify(); + assert.equal(result.status, 0, result.stdout + result.stderr); + }); +} + +test('release refuses to promote a build when its exact-commit CI artifact is missing', t => { + const f = fixture(t); + delete f.responses[`${prefix}/runs/123/artifacts?page=1`]; + const result = f.verify(); + assert.notEqual(result.status, 0, result.stdout + result.stderr); +}); + +test('release downloads the verified archive and emits its immutable artifact identity', t => { + const f = fixture(t); + const archive = path.join(f.directory, 'candidate.zip'); + const output = path.join(f.directory, 'outputs'); + const result = f.verify({ CI_CANDIDATE_ARCHIVE: archive, GITHUB_OUTPUT: output }); + assert.equal(result.status, 0, result.stdout + result.stderr); + assert.equal(readFileSync(archive, 'utf8'), 'ci-candidate-fixture'); + assert.match(readFileSync(output, 'utf8'), /ci-run-id=123\nartifact-id=789\nartifact-digest=sha256:03bbb087/); +}); + +test('release rejects corrupted archive bytes before writing a promotable candidate', t => { + const f = fixture(t); + f.storage.body = 'xi-candidate-fixture'; + const archive = path.join(f.directory, 'candidate.zip'); + const result = f.verify({ CI_CANDIDATE_ARCHIVE: archive }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /checksum or size mismatch/); + assert.equal(existsSync(archive), false); +}); + +test('release rejects a newer main CI run appearing during artifact verification', t => { + const f = fixture(t); + f.updates[`${prefix}/workflows/456/runs?page=1`] = { + total_count: 2, workflow_runs: [f.run, { ...f.run, id: 124 }], + }; + assert.notEqual(f.verify().status, 0); +}); + +for (const platform of ['', 'all', 'constructor', 'unknown']) { + test(`release refuses invalid or missing platform ${JSON.stringify(platform)}`, t => { + assert.notEqual(fixture(t).verify({ RELEASE_PLATFORM: platform }).status, 0); + }); +} + +for (const [platform, own] of [ + ['linux', ['check (ubuntu-latest)', 'Linux package validation']], + ['macos-aarch64', ['check (macos-latest)']], + ['macos-x86_64', ['check (macos-15-intel)']], + ['windows-x86_64', ['check (windows-latest)']], +]) { + test(`${platform} release requires its own native checks but does not wait for other platforms`, t => { + const f = fixture(t); + const page = f.responses[`${prefix}/runs/123/attempts/1/jobs?page=1`]; + for (const job of page.jobs) { + if (!own.includes(job.name) && job.name.startsWith('check (')) { + job.status = 'in_progress'; job.conclusion = null; + } + } + f.run.status = 'in_progress'; f.run.conclusion = null; + let result = f.verify({ RELEASE_PLATFORM: platform }); + assert.equal(result.status, 0, result.stdout + result.stderr); + for (const context of own) { + const job = page.jobs.find(job => job.name === context); + job.conclusion = 'failure'; + result = f.verify({ RELEASE_PLATFORM: platform }); + assert.notEqual(result.status, 0, context); + job.conclusion = 'success'; + } + }); +} + +for (const [name, change] of [ + ['expired flag', artifact => { artifact.expired = true; }], + ['past expiry time', artifact => { artifact.expires_at = '2000-01-01T00:00:00Z'; }], + ['missing digest', artifact => { delete artifact.digest; }], + ['empty archive', artifact => { artifact.size_in_bytes = 0; }], + ['old attempt', artifact => { artifact.name = `mist-ci-linux-${commit}-attempt-0`; }], + ['wrong commit', artifact => { artifact.workflow_run.head_sha = 'b'.repeat(40); }], + ['wrong run', artifact => { artifact.workflow_run.id = 999; }], + ['PR branch', artifact => { artifact.workflow_run.head_branch = 'topic'; }], + ['fork source', artifact => { artifact.workflow_run.head_repository_id = 999; }], +]) { + test(`release rejects CI artifact with ${name}`, t => { + const f = fixture(t); + change(f.responses[`${prefix}/runs/123/artifacts?page=1`].artifacts[0]); + assert.notEqual(f.verify().status, 0); + }); +} + +test('release rejects duplicate candidate artifacts rather than picking one', t => { + const f = fixture(t); + const page = f.responses[`${prefix}/runs/123/artifacts?page=1`]; + page.artifacts.push({ ...page.artifacts[0], id: 999 }); + page.total_count = page.artifacts.length; + assert.notEqual(f.verify().status, 0); +}); + +test('release fails closed when both run and artifact omit repository IDs', t => { + const f = fixture(t); + delete f.run.repository.id; + delete f.run.head_repository.id; + for (const artifact of f.responses[`${prefix}/runs/123/artifacts?page=1`].artifacts) { + delete artifact.workflow_run.repository_id; + delete artifact.workflow_run.head_repository_id; + } + assert.notEqual(f.verify().status, 0); +}); + test('release rejects a commit without a main CI run', t => { const f = fixture(t); f.responses[`${prefix}/workflows/456/runs?page=1`] = { total_count: 0, workflow_runs: [] }; diff --git a/scripts/test-workflows.py b/scripts/test-workflows.py index 9c84be0..68a66f3 100644 --- a/scripts/test-workflows.py +++ b/scripts/test-workflows.py @@ -6,6 +6,9 @@ import json from itertools import product +import os +import subprocess +import tempfile import unittest from pathlib import Path @@ -129,7 +132,7 @@ def test_preview_keeps_ci_and_publication_protection(self): for name in ["macos", "windows"]: self.assertEqual(jobs[name]["environment"], "release-signing") - def test_intel_build_is_required_and_uses_the_same_runtime_as_release(self): + def test_intel_build_remains_required_in_ci_and_release_promotes_it_without_rebuilding(self): ci = workflow("ci.yml") check = ci["jobs"]["check"] self.assertIn("macos-15-intel", check["strategy"]["matrix"]["os"]) @@ -141,8 +144,10 @@ def test_intel_build_is_required_and_uses_the_same_runtime_as_release(self): ] self.assertEqual(len(ci_runtime), 1) self.assertEqual(ci_runtime[0]["if"], "matrix.os == 'macos-15-intel'") - self.assertEqual(len(release_runtime), 1) - self.assertEqual(release_runtime[0]["if"], "inputs.platform == 'macos-x86_64'") + self.assertEqual(release_runtime, []) + promote = [step for step in workflow("release-platform.yml")["jobs"]["macos"]["steps"] + if step.get("uses") == "./.github/actions/ci-candidate"] + self.assertEqual(len(promote), 1) rules = json.loads((ROOT / ".github/rulesets/main-quality.json").read_text()) required = next( rule["parameters"]["required_status_checks"] @@ -150,6 +155,43 @@ def test_intel_build_is_required_and_uses_the_same_runtime_as_release(self): ) self.assertIn("check (macos-15-intel)", [check["context"] for check in required]) + def test_ci_retains_commit_and_attempt_scoped_native_candidates_without_secrets(self): + ci = workflow("ci.yml") + check = ci["jobs"]["check"] + self.assertEqual(check["name"], "check (${{ matrix.os }})") + uploads = [step for step in check["steps"] if step.get("uses", "").startswith("actions/upload-artifact@")] + self.assertEqual(len(uploads), 2) + self.assertEqual(uploads[0]["with"]["path"], "dist/packages/Mist.app.tar") + self.assertEqual(uploads[0]["if"], "runner.os == 'macOS'") + self.assertEqual(uploads[1]["with"]["path"], "target/release/mist.exe") + self.assertEqual(uploads[1]["if"], "runner.os == 'Windows'") + for step in uploads: + self.assertIn("${{ github.sha }}-attempt-${{ github.run_attempt }}", step["with"]["name"]) + self.assertEqual(step["with"]["if-no-files-found"], "error") + self.assertEqual(ci["jobs"]["packages"]["steps"][1]["with"]["artifact-name"], + "mist-ci-linux-${{ github.sha }}-attempt-${{ github.run_attempt }}") + + def test_every_native_release_verifies_the_ci_archive_before_using_it(self): + jobs = workflow("release-platform.yml")["jobs"] + for name in ["macos", "windows", "linux"]: + step = next(step for step in jobs[name]["steps"] + if step.get("uses") == "./.github/actions/ci-candidate") + self.assertEqual(step["with"]["digest"], "${{ needs.preflight.outputs.artifact-digest }}") + action = yaml.safe_load((ROOT / ".github/actions/ci-candidate/action.yml").read_text()) + verify = action["runs"]["steps"][-1] + for digest, expected in [ + ("sha256:03bbb0874ab942ba8e81bb2d49032b3737d834e5ee0e323f04718f233721e882", 0), + ("sha256:" + "0" * 64, 1), + ]: + with tempfile.TemporaryDirectory(prefix="mist-ci-archive-") as directory: + candidate = Path(directory) / "ci-candidate" + candidate.mkdir() + (candidate / "ci-candidate.zip").write_bytes(b"ci-candidate-fixture") + result = subprocess.run(["bash", "-c", verify["run"]], cwd=directory, + env={"PATH": os.environ["PATH"], "CI_ARTIFACT_DIGEST": digest}, + capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, expected, result.stderr) + def test_prs_run_ci_without_starting_a_release(self): ci = events(workflow("ci.yml")) for file in (ROOT / ".github/workflows").glob("release*.yml"): @@ -192,11 +234,16 @@ def test_release_artifacts_require_exact_commit_ci_without_rerunning_tests(self) checks = [step for step in gate["steps"] if "scripts/verify-release-ci.mjs" in step.get("run", "")] self.assertEqual(len(checks), 1) self.assertEqual(checks[0]["env"]["GH_TOKEN"], "${{ github.token }}") + self.assertEqual(checks[0]["env"]["RELEASE_PLATFORM"], "${{ inputs.platform }}") + self.assertEqual(checks[0]["env"]["CI_CANDIDATE_ARCHIVE"], "ci-candidate.zip") for name, job in jobs.items(): for step in expanded_steps(job): self.assertNotIn("continue-on-error", step) self.assertNotIn("check-quality.sh", step.get("run", "")) self.assertNotIn("cargo test", step.get("run", "")) + self.assertNotIn("cargo build", step.get("run", "")) + self.assertNotIn("./.github/actions/intel-onnxruntime", step.get("uses", "")) + self.assertNotIn("./.github/actions/linux-packages", step.get("uses", "")) if name != "preflight": self.assertIn("preflight", prerequisites(jobs, name), name) self.assertNotIn("always()", job.get("if", ""), name) diff --git a/scripts/verify-release-ci.mjs b/scripts/verify-release-ci.mjs index 1885a6e..f1499e9 100644 --- a/scripts/verify-release-ci.mjs +++ b/scripts/verify-release-ci.mjs @@ -1,7 +1,44 @@ import { env as environment } from 'node:process'; -import { readFileSync } from 'node:fs'; +import { appendFileSync, writeFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; -const { GITHUB_REPOSITORY: repository, GITHUB_SHA: commit, GH_TOKEN: token } = environment; +const { GITHUB_REPOSITORY: repository, GITHUB_SHA: commit, GH_TOKEN: token, RELEASE_PLATFORM: platform } = environment; +const platformChecks = { + linux: ['check (ubuntu-latest)', 'Linux package validation'], + 'macos-aarch64': ['check (macos-latest)'], + 'macos-x86_64': ['check (macos-15-intel)'], + 'windows-x86_64': ['check (windows-latest)'], +}; +const sharedChecks = ['Repository metadata, workflows, and website', 'Quality and security gates']; + +async function downloadCandidate(artifact) { + if (!environment.CI_CANDIDATE_ARCHIVE) return; + const redirect = await fetch(`https://api.github.com/repos/${repository}/actions/artifacts/${artifact.id}/zip`, { + headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json' }, + redirect: 'manual', signal: AbortSignal.timeout(30_000), + }); + if (redirect.status !== 302) throw new Error(`CI artifact download failed (HTTP ${redirect.status}).`); + const location = new URL(redirect.headers.get('location')); + if (location.protocol !== 'https:' || location.username || location.password) { + throw new Error('Invalid CI artifact download redirect.'); + } + // The signed storage URL does not receive the GitHub credential. + const response = await fetch(location, { redirect: 'error', signal: AbortSignal.timeout(120_000) }); + if (!response.ok) throw new Error(`CI artifact storage failed (HTTP ${response.status}).`); + const chunks = []; + let size = 0; + for await (const chunk of response.body) { + size += chunk.length; + if (size > artifact.size_in_bytes) throw new Error('CI artifact exceeds its declared size.'); + chunks.push(chunk); + } + const archive = Buffer.concat(chunks); + if (size !== artifact.size_in_bytes || + `sha256:${createHash('sha256').update(archive).digest('hex')}` !== artifact.digest) { + throw new Error('CI artifact checksum or size mismatch.'); + } + writeFileSync(environment.CI_CANDIDATE_ARCHIVE, archive, { flag: 'wx', mode: 0o600 }); +} async function api(endpoint) { const response = await fetch(`https://api.github.com/repos/${repository}/actions/${endpoint}`, { @@ -26,7 +63,18 @@ async function pages(endpoint, collection) { } } +async function latestRun(workflow) { + const runs = await pages(`workflows/${workflow.id}/runs?branch=main&event=push&head_sha=${commit}`, 'workflow_runs'); + if (runs.some(run => !Number.isSafeInteger(run.id) || run.id <= 0)) { + throw new Error('Invalid GitHub CI run identity.'); + } + const candidate = runs.sort((left, right) => right.id - left.id)[0]; + if (!candidate) throw new Error('No main CI run exists for the release commit.'); + return candidate; +} + async function verify() { + if (!Object.hasOwn(platformChecks, platform ?? '')) throw new Error('A supported RELEASE_PLATFORM is required.'); if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository ?? '') || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit ?? '') || !token) { throw new Error('Release CI verification requires a repository, exact commit SHA, and GitHub token.'); @@ -36,38 +84,51 @@ async function verify() { workflow.state !== 'active' || workflow.path !== '.github/workflows/ci.yml') { throw new Error('The required CI workflow is not active.'); } - const runs = await pages(`workflows/${workflow.id}/runs?branch=main&event=push&head_sha=${commit}`, 'workflow_runs'); - if (runs.some(run => !Number.isSafeInteger(run.id) || run.id <= 0)) { - throw new Error('Invalid GitHub CI run identity.'); - } - const candidate = runs.sort((left, right) => right.id - left.id)[0]; - if (!candidate) throw new Error('No main CI run exists for the release commit.'); + const candidate = await latestRun(workflow); const run = await api(`runs/${candidate.id}`); if (run.id !== candidate.id || !Number.isSafeInteger(run.run_attempt) || run.run_attempt <= 0 || run.workflow_id !== workflow.id || run.path !== workflow.path || run.event !== 'push' || run.head_branch !== 'main' || run.head_sha !== commit || - run.repository?.full_name !== repository || run.head_repository?.full_name !== repository) { + run.repository?.full_name !== repository || run.head_repository?.full_name !== repository || + !Number.isSafeInteger(run.repository.id) || run.repository.id <= 0 || + run.head_repository.id !== run.repository.id) { throw new Error('CI evidence does not identify the exact main commit and workflow.'); } - if (run?.status !== 'completed' || run.conclusion !== 'success') { - throw new Error('Release requires successful CI for the exact main commit.'); - } - const ruleset = JSON.parse(readFileSync(new URL('../.github/rulesets/main-quality.json', import.meta.url), 'utf8')); - const required = ruleset.rules.find(rule => rule.type === 'required_status_checks').parameters.required_status_checks; - if (!Array.isArray(required) || required.length === 0) throw new Error('No required CI checks are configured.'); + const required = [...sharedChecks, ...platformChecks[platform]]; const jobs = await pages(`runs/${run.id}/attempts/${run.run_attempt}/jobs`, 'jobs'); for (const check of required) { - const matching = jobs.filter(job => job.name === check.context); + const matching = jobs.filter(job => job.name === check); if (matching.length !== 1 || matching[0].status !== 'completed' || matching[0].conclusion !== 'success' || matching[0].head_sha !== commit || matching[0].run_id !== run.id || matching[0].run_attempt !== run.run_attempt) { - throw new Error(`CI has not passed required check: ${check.context}.`); + throw new Error(`CI has not passed required check: ${check}.`); } } + const artifacts = await pages(`runs/${run.id}/artifacts`, 'artifacts'); + const name = `mist-ci-${platform}-${commit}-attempt-${run.run_attempt}`; + const matching = artifacts.filter(artifact => artifact.name === name); + const artifact = matching[0]; + if (matching.length !== 1 || !Number.isSafeInteger(artifact.id) || artifact.id <= 0 || + artifact.expired !== false || !Number.isSafeInteger(artifact.size_in_bytes) || + artifact.size_in_bytes <= 0 || artifact.size_in_bytes > 512 * 1024 * 1024 || + !/^sha256:[a-f0-9]{64}$/.test(artifact.digest ?? '') || + !Number.isFinite(Date.parse(artifact.expires_at)) || Date.parse(artifact.expires_at) <= Date.now() || + artifact.workflow_run?.id !== run.id || artifact.workflow_run?.head_sha !== commit || + artifact.workflow_run?.head_branch !== 'main' || + artifact.workflow_run?.repository_id !== run.repository.id || + artifact.workflow_run?.head_repository_id !== run.head_repository.id) { + throw new Error(`Missing or invalid CI candidate artifact for ${platform} in the latest attempt.`); + } + await downloadCandidate(artifact); const current = await api(`runs/${run.id}`); - if (current.run_attempt !== run.run_attempt || current.status !== 'completed' || current.conclusion !== 'success') { + if (current.run_attempt !== run.run_attempt || current.head_sha !== commit || + (await latestRun(workflow)).id !== run.id) { throw new Error('CI changed while release evidence was being verified; retry after it completes.'); } - console.log(`Verified CI: https://github.com/${repository}/actions/runs/${run.id}`); + if (environment.GITHUB_OUTPUT) { + appendFileSync(environment.GITHUB_OUTPUT, + `ci-run-id=${run.id}\nartifact-id=${artifact.id}\nartifact-digest=${artifact.digest}\n`); + } + console.log(`Verified CI for ${platform}: https://github.com/${repository}/actions/runs/${run.id}`); } verify().catch(error => {