From 0a39516aea3aa1164edcced3d2b703a9347dea5d Mon Sep 17 00:00:00 2001 From: beasty Date: Fri, 23 Oct 2026 01:13:22 +0200 Subject: [PATCH 1/9] ci: reuse verify tree proof in releases and smoke-check rollout --- .github/workflows/build-images.yml | 39 ++++- .github/workflows/verify.yml | 18 +++ backend/stream-canvas/src/app.ts | 4 + backend/stream-canvas/src/config.ts | 1 + backend/stream-canvas/src/version.test.ts | 25 ++++ docs/releasing.md | 22 ++- scripts/delivery-changes.test.ts | 83 +++++++++-- scripts/rollout-smoke.test.ts | 170 ++++++++++++++++++++++ scripts/rollout-smoke.ts | 170 ++++++++++++++++++++++ scripts/verify-proof.test.ts | 96 ++++++++++++ scripts/verify-proof.ts | 147 +++++++++++++++++++ 11 files changed, 757 insertions(+), 18 deletions(-) create mode 100644 backend/stream-canvas/src/version.test.ts create mode 100644 scripts/rollout-smoke.test.ts create mode 100644 scripts/rollout-smoke.ts create mode 100644 scripts/verify-proof.test.ts create mode 100644 scripts/verify-proof.ts diff --git a/.github/workflows/build-images.yml b/.github/workflows/build-images.yml index dac57ec..e2df003 100644 --- a/.github/workflows/build-images.yml +++ b/.github/workflows/build-images.yml @@ -9,12 +9,34 @@ permissions: contents: read jobs: + gate: + if: '!cancelled()' + runs-on: arc-moddrop + timeout-minutes: 5 + permissions: + actions: read + contents: read + outputs: + reuse: ${{ steps.proof.outputs.reuse }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version-file: .node-version + - name: Find successful verification of this tree + id: proof + env: + GH_TOKEN: ${{ github.token }} + run: node scripts/verify-proof.ts + verify: + needs: gate + if: "!cancelled() && (needs.gate.result != 'success' || needs.gate.outputs.reuse != 'true')" uses: ./.github/workflows/verify.yml build: - needs: verify - if: startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main' + needs: [gate, verify] + if: "!cancelled() && ((needs.gate.result == 'success' && needs.gate.outputs.reuse == 'true' && needs.verify.result == 'skipped') || needs.verify.result == 'success') && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main')" runs-on: arc-moddrop permissions: contents: read @@ -69,3 +91,16 @@ jobs: NEXT_PUBLIC_TLDRAW_LICENSE_KEY=${{ secrets.NEXT_PUBLIC_TLDRAW_LICENSE_KEY }} secrets: | glitchtip_auth_token=${{ secrets.GLITCHTIP_AUTH_TOKEN }} + + smoke: + needs: build + if: "!cancelled() && needs.build.result == 'success' && startsWith(github.ref, 'refs/tags/v')" + runs-on: arc-moddrop + timeout-minutes: 35 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version-file: .node-version + - name: Wait for Flux rollout and check production + run: node scripts/rollout-smoke.ts https://moddrop.live "${GITHUB_REF_NAME#v}" diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 00b7f69..20a79fa 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -39,3 +39,21 @@ jobs: - run: pnpm install --frozen-lockfile --ignore-scripts - run: pnpm exec playwright install --with-deps chromium - run: bash scripts/verify.sh + - name: Record verified checkout + id: proof + run: | + git config --global --add safe.directory "$GITHUB_WORKSPACE" + node --input-type=module <<'NODE' + import { execFileSync } from 'node:child_process'; + import { appendFileSync, writeFileSync } from 'node:fs'; + const git = (ref) => execFileSync('git', ['rev-parse', ref], { encoding: 'utf8' }).trim(); + const proof = { commit: git('HEAD'), tree: git('HEAD^{tree}') }; + writeFileSync('verify-proof.json', JSON.stringify(proof)); + appendFileSync(process.env.GITHUB_OUTPUT, `tree=${proof.tree}\n`); + NODE + - uses: actions/upload-artifact@v4 + with: + name: verify-proof-${{ steps.proof.outputs.tree }} + path: verify-proof.json + if-no-files-found: error + retention-days: 14 diff --git a/backend/stream-canvas/src/app.ts b/backend/stream-canvas/src/app.ts index 3e04c4a..292dc7e 100644 --- a/backend/stream-canvas/src/app.ts +++ b/backend/stream-canvas/src/app.ts @@ -17,6 +17,10 @@ app.onError((error, c) => { }); app.use("*", cors({ origin: config.corsOrigins })); app.get("/health", (c) => c.json({ status: "ok" })); +app.get("/version", (c) => { + c.header("Cache-Control", "no-store"); + return c.json({ release: config.appRelease }); +}); app.get("/ready", async (c) => { if (!leaderState.isLeader) { return c.json({ status: "standby", role: "standby" }, 503); diff --git a/backend/stream-canvas/src/config.ts b/backend/stream-canvas/src/config.ts index 2f47ea5..9d73bd9 100644 --- a/backend/stream-canvas/src/config.ts +++ b/backend/stream-canvas/src/config.ts @@ -16,6 +16,7 @@ const uploadsDir = process.env.UPLOADS_DIR ?? "data/uploads"; export const config = { nodeEnv, + appRelease: process.env.APP_RELEASE || null, port: numberEnv("PORT", 8003, { min: 1, max: 65535 }), databaseUrl: process.env.DATABASE_URL ?? diff --git a/backend/stream-canvas/src/version.test.ts b/backend/stream-canvas/src/version.test.ts new file mode 100644 index 0000000..58b6946 --- /dev/null +++ b/backend/stream-canvas/src/version.test.ts @@ -0,0 +1,25 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +// Match the app integration tests: tldraw disables its browser channel in test mode. +process.env.NODE_ENV = "test"; +const { app } = await import("./app.ts"); +const { config } = await import("./config.ts"); +const { closeDatabase } = await import("./db.ts"); +const { leaderState } = await import("./leader.ts"); + +test("version is public and uncached on standbys, with null when unset", async (t) => { + t.after(closeDatabase); + assert.equal(leaderState.isLeader, false); + const original = config.appRelease; + t.after(() => { + Object.defineProperty(config, "appRelease", { value: original }); + }); + for (const release of ["moddrop@0.9.0", null]) { + Object.defineProperty(config, "appRelease", { value: release }); + const response = await app.request("/version"); + assert.equal(response.status, 200); + assert.equal(response.headers.get("Cache-Control"), "no-store"); + assert.deepEqual(await response.json(), { release }); + } +}); diff --git a/docs/releasing.md b/docs/releasing.md index 6f2aade..c5d8214 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,10 +1,22 @@ # Release and deployment notes -Pushing a `vX.Y.Z` tag runs the GitHub container-image workflow. The workflow -verifies the repository and builds the frontend -and stream-canvas images on the `arc-moddrop` runner. The current workflow -publishes both images to GHCR; check the downstream deployment configuration -before assuming a tag has reached production. +Pushing a `vX.Y.Z` tag runs the GitHub container-image workflow. Verify records +the checked-out commit and tree in a JSON artifact after the full suite passes, +retained for 14 days. The release gate reuses proof only for the exact release +tree from a completed, successful Verify run in this repository. Fork PR runs +cannot supply proof. Missing, expired, invalid or unavailable proof falls back +to the full Verify workflow. Both production images still build on `arc-moddrop` +and publish to GHCR after verification succeeds. + +For tags, a rollout smoke job waits up to 30 minutes for Flux to deploy both +components. It polls `/telemetry-config` and `/canvas-api/version` at +`https://moddrop.live` every 20 seconds until both report `moddrop@`, +then checks `/` and retries `/canvas-api/ready` for up to a minute. The overall +deadline includes readiness retries. A newer semver on either component marks +the release as superseded and skips remaining checks. Timeouts fail with each +endpoint's last observation. For manual use, run +`node scripts/rollout-smoke.ts [timeout-ms]`; the timeout +also accepts `ROLLOUT_TIMEOUT_MS`. The frontend image receives its public configuration at build time. The GitHub repository variable `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` must exist and contain the diff --git a/scripts/delivery-changes.test.ts b/scripts/delivery-changes.test.ts index cda9030..6052b99 100644 --- a/scripts/delivery-changes.test.ts +++ b/scripts/delivery-changes.test.ts @@ -15,17 +15,78 @@ test("GitHub releases use the PR verification gate before production actions", ( expect(verification.on).toHaveProperty("workflow_call"); expect(verification.jobs.verify["runs-on"]).toBe("arc-moddrop"); const job = workflow.jobs.build; - expect(job.needs).toBe("verify"); - const allowed = (ref: string) => - Function( - "github", - "startsWith", - `return (${job.if})`, - )({ ref }, (value: string, prefix: string) => value.startsWith(prefix)); - expect(allowed("refs/heads/feature")).toBe(false); - expect(allowed("refs/heads/main")).toBe(true); - expect(allowed("refs/tags/v0.6.2")).toBe(true); - expect(job.if).not.toContain("always()"); + expect(job.needs).toEqual(["gate", "verify"]); + expect(workflow.jobs.verify.needs).toBe("gate"); + expect(workflow.jobs.smoke.needs).toBe("build"); + expect(workflow.jobs.gate.permissions).toEqual({ + actions: "read", + contents: "read", + }); + expect(verification.jobs.verify.services.postgres).toBeDefined(); + const steps = verification.jobs.verify.steps; + const verifyIndex = steps.findIndex( + (step: { run?: string }) => step.run === "bash scripts/verify.sh", + ); + expect(verifyIndex).toBeGreaterThan(-1); + expect(steps.at(-1).uses).toBe("actions/upload-artifact@v4"); + for (const step of steps.slice(verifyIndex + 1)) + expect(step.if).toBeUndefined(); // Default success() protects the proof. + + const results = ["success", "failure", "cancelled", "skipped"]; + for (const gate of results) + for (const reuse of ["true", "false", ""]) + for (const verify of results) + for (const cancelled of [true, false]) + for (const ref of [ + "refs/heads/feature", + "refs/heads/main", + "refs/tags/v0.6.2", + "refs/tags/other", + "refs/pull/1/merge", + ]) { + const needs = { + gate: { result: gate, outputs: { reuse } }, + verify: { result: verify }, + }; + const evaluate = ( + condition: string, + dependencies: object = needs, + ) => + Function( + "needs", + "github", + "cancelled", + "always", + "startsWith", + `return (${condition});`, + )( + dependencies, + { ref }, + () => cancelled, + () => true, + (value: string, prefix: string) => value.startsWith(prefix), + ); + expect(evaluate(workflow.jobs.gate.if)).toBe(!cancelled); + expect(evaluate(workflow.jobs.verify.if)).toBe( + !cancelled && (gate !== "success" || reuse !== "true"), + ); + const safe = + !cancelled && + (ref === "refs/heads/main" || ref.startsWith("refs/tags/v")) && + (verify === "success" || + (gate === "success" && + reuse === "true" && + verify === "skipped")); + expect(evaluate(job.if)).toBe(safe); + for (const build of results) + expect( + evaluate(workflow.jobs.smoke.if, { build: { result: build } }), + ).toBe( + !cancelled && + build === "success" && + ref.startsWith("refs/tags/v"), + ); + } }); test.each(["pnpm-lock.yaml", "pnpm-workspace.yaml", "package.json", ".npmrc"])( diff --git a/scripts/rollout-smoke.test.ts b/scripts/rollout-smoke.test.ts new file mode 100644 index 0000000..c482eee --- /dev/null +++ b/scripts/rollout-smoke.test.ts @@ -0,0 +1,170 @@ +import { expect, test, vi } from "vitest"; +import { compareVersions, rolloutSmoke } from "./rollout-smoke"; + +const old = "moddrop@0.8.0"; +const expected = "moddrop@0.9.0"; +const newer = "moddrop@0.10.0"; +type Reply = string | number | Error | { malformed: true }; +function fixture(frontend: Reply[], backend: Reply[], ready: Reply[] = [200]) { + let now = 0; + const queues: Record = { + "/telemetry-config": [...frontend], + "/canvas-api/version": [...backend], + "/": [200], + "/canvas-api/ready": [...ready], + }; + const request = vi.fn(async (input) => { + const path = new URL(String(input)).pathname; + const queue = queues[path]; + if (!queue?.length) throw new Error(`Unexpected request ${path}`); + const reply = queue.length > 1 ? queue.shift() : queue[0]; + if (reply instanceof Error) throw reply; + if (typeof reply === "number") return new Response("", { status: reply }); + if (typeof reply === "object") return new Response("not JSON"); + return Response.json({ release: reply }); + }); + const log = vi.fn(); + return { + request, + log, + queues, + options: { + baseUrl: "https://fixture.invalid", + version: "0.9.0", + timeoutMs: 100, + pollMs: 20, + readyTimeoutMs: 40, + now: () => now, + sleep: async (ms: number) => { + now += ms; + }, + fetch: request, + log, + }, + }; +} + +test.each([ + [ + [old, expected], + [old, expected], + ], + [[expected], [old, expected]], + [[old, expected], [expected]], + [[404, expected], [expected]], + [ + [500, expected], + [503, expected], + ], + [[new Error("offline"), expected], [expected]], + [[{ malformed: true }, expected], [expected]], + [["not-a-release", expected], [expected]], +] satisfies [Reply[], Reply[]][])( + "waits for both versions, then checks homepage and retries readiness: %j / %j", + async (frontend, backend) => { + const { options, request } = fixture(frontend, backend, [503, 200]); + expect(await rolloutSmoke(options)).toBe("healthy"); + const paths = request.mock.calls.map( + ([url]) => new URL(String(url)).pathname, + ); + expect(paths.slice(-3)).toEqual([ + "/", + "/canvas-api/ready", + "/canvas-api/ready", + ]); + expect( + request.mock.calls.every(([, init]) => init?.cache === "no-store"), + ).toBe(true); + }, +); + +test.each([ + [[newer], [expected]], + [[expected], [newer]], + [[newer], [old]], + [[404], [newer]], +] satisfies [Reply[], Reply[]][])( + "newer component supersedes the rollout: %j / %j", + async (frontend, backend) => { + const { options, request, log } = fixture(frontend, backend); + expect(await rolloutSmoke(options)).toBe("superseded"); + expect(request).toHaveBeenCalledTimes(2); + expect(log).toHaveBeenCalledWith( + expect.stringContaining("::notice::Rollout superseded"), + ); + }, +); + +test("timeout includes the last observation from each endpoint", async () => { + const { options, request } = fixture([old], [404]); + await expect(rolloutSmoke(options)).rejects.toThrow( + 'Rollout timed out: {"/telemetry-config":"moddrop@0.8.0","/canvas-api/version":"HTTP 404"}', + ); + expect(request).toHaveBeenCalledTimes(10); +}); + +test("deadline reached as matching versions arrive retains both observations", async () => { + const { options, request } = fixture([expected], [expected]); + const fetchAtDeadline: typeof fetch = async (url, init) => { + const response = await request(url, init); + await options.sleep(100); + return response; + }; + await expect( + rolloutSmoke({ ...options, fetch: fetchAtDeadline }), + ).rejects.toThrow( + 'Rollout timed out: {"/telemetry-config":"moddrop@0.9.0","/canvas-api/version":"moddrop@0.9.0"}', + ); + expect(request).toHaveBeenCalledTimes(2); +}); + +test.each([ + [{ malformed: true }], + [new Error("offline")], + ["moddrop@invalid"], +] satisfies [Reply][])( + "malformed and network responses stay pending until timeout: %j", + async (replies) => { + const { options } = fixture([replies], [expected]); + await expect(rolloutSmoke(options)).rejects.toThrow("Rollout timed out"); + }, +); + +test("homepage failure fails after matching releases", async () => { + const { options, queues } = fixture([expected], [expected]); + queues["/"] = [502]; + await expect(rolloutSmoke(options)).rejects.toThrow( + "Homepage returned HTTP 502", + ); +}); + +test("readiness retries are bounded by the short window and overall deadline", async () => { + const { options, request } = fixture([expected], [expected], [503]); + await expect(rolloutSmoke({ ...options, timeoutMs: 30 })).rejects.toThrow( + "Readiness timed out: HTTP 503", + ); + expect(request).toHaveBeenCalledTimes(5); +}); + +test.each([ + ["0.10.0", "0.9.0", 1], + ["1.0.0", "1.0.0-rc.1", 1], + ["1.0.0-rc.10", "1.0.0-rc.2", 1], + ["1.0.0-alpha", "1.0.0-alpha.1", -1], + ["1.0.0-1", "1.0.0-alpha", -1], + ["1.0.0+build.2", "1.0.0+build.1", 0], +] as const)("compares semver %s and %s", (a, b, expectedOrder) => { + expect(compareVersions(a, b)).toBe(expectedOrder); +}); + +test("invalid versions and deadlines fail before any request", async () => { + const { options, request } = fixture([expected], [expected]); + for (const version of ["bad", "01.0.0", "1.0.0-01"]) + await expect(rolloutSmoke({ ...options, version })).rejects.toThrow( + "Invalid semver", + ); + await expect( + rolloutSmoke({ ...options, timeoutMs: Number.NaN }), + ).rejects.toThrow("durations"); + expect(request).not.toHaveBeenCalled(); +}); diff --git a/scripts/rollout-smoke.ts b/scripts/rollout-smoke.ts new file mode 100644 index 0000000..b56930b --- /dev/null +++ b/scripts/rollout-smoke.ts @@ -0,0 +1,170 @@ +import { setTimeout as sleep } from "node:timers/promises"; + +function semver(version: string) { + const match = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?(?:\+[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?$/.exec( + version, + ); + if (!match) throw new Error(`Invalid semver: ${version}`); + const prerelease = match[4]?.split(".") ?? []; + if (prerelease.some((part) => /^\d+$/.test(part) && /^0\d/.test(part))) + throw new Error(`Invalid semver: ${version}`); + return { core: match.slice(1, 4).map(BigInt), prerelease }; +} + +export function compareVersions(left: string, right: string): number { + const a = semver(left); + const b = semver(right); + for (let i = 0; i < 3; i++) { + if (a.core[i] !== b.core[i]) return a.core[i] > b.core[i] ? 1 : -1; + } + if (!a.prerelease.length || !b.prerelease.length) + return Number(!a.prerelease.length) - Number(!b.prerelease.length); + for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i++) { + const x = a.prerelease[i]; + const y = b.prerelease[i]; + if (x === undefined) return -1; + if (y === undefined) return 1; + if (x === y) continue; + const numericX = /^\d+$/.test(x); + const numericY = /^\d+$/.test(y); + if (numericX && numericY) return BigInt(x) > BigInt(y) ? 1 : -1; + if (numericX !== numericY) return numericX ? -1 : 1; + return x > y ? 1 : -1; + } + return 0; +} + +type SmokeOptions = { + baseUrl: string; + version: string; + timeoutMs?: number; + pollMs?: number; + readyTimeoutMs?: number; + fetch?: typeof fetch; + now?: () => number; + sleep?: (ms: number) => Promise; + log?: (message: string) => void; +}; + +export async function rolloutSmoke(options: SmokeOptions) { + const { + baseUrl, + version, + timeoutMs = 30 * 60_000, + pollMs = 20_000, + readyTimeoutMs = 60_000, + fetch: request = fetch, + now = Date.now, + sleep: pause = sleep, + log = console.log, + } = options; + semver(version); + for (const duration of [timeoutMs, pollMs, readyTimeoutMs]) { + if (!Number.isFinite(duration) || duration <= 0) + throw new Error("Rollout durations must be positive finite milliseconds"); + } + const deadline = now() + timeoutMs; + const paths = ["/telemetry-config", "/canvas-api/version"]; + const last = new Map(paths.map((path) => [path, "not checked"])); + const expected = `moddrop@${version}`; + const timedOut = () => + new Error(`Rollout timed out: ${JSON.stringify(Object.fromEntries(last))}`); + async function get(path: string, end = deadline) { + if (now() >= deadline) throw timedOut(); + if (now() >= end) throw new Error("deadline reached"); + return request(new URL(path, baseUrl), { + cache: "no-store", + signal: AbortSignal.timeout(Math.max(1, Math.min(10_000, end - now()))), + }); + } + const wait = async (end: number) => { + const remaining = end - now(); + if (remaining > 0) await pause(Math.min(pollMs, remaining)); + }; + while (now() < deadline) { + // Inspect both responses before health checks, so a newer component wins + // even when the other component is still rolling out or unavailable. + const releases = await Promise.all( + paths.map(async (path) => { + try { + const response = await get(path); + if (!response.ok) { + last.set(path, `HTTP ${response.status}`); + return null; + } + const body: unknown = await response.json(); + if ( + !body || + typeof body !== "object" || + !("release" in body) || + typeof body.release !== "string" || + !body.release.startsWith("moddrop@") + ) + throw new Error("missing release"); + const release = body.release; + semver(release.slice("moddrop@".length)); + last.set(path, release); + return release; + } catch { + last.set(path, "network error, invalid JSON or invalid release"); + return null; + } + }), + ); + const newer = releases.find( + (release) => release && compareVersions(release.slice(8), version) > 0, + ); + if (newer) { + log( + `::notice::Rollout superseded: expected ${expected}, observed ${newer}. Skipping remaining checks.`, + ); + return "superseded"; + } + log(paths.map((path) => `${path}: ${last.get(path)}`).join("; ")); + if (releases.every((release) => release === expected)) { + const home = await get("/").catch((error: unknown) => { + if (now() >= deadline) throw timedOut(); + throw error; + }); + if (!home.ok) throw new Error(`Homepage returned HTTP ${home.status}`); + const readyDeadline = Math.min(deadline, now() + readyTimeoutMs); + let ready = "not checked"; + while (now() < readyDeadline) { + try { + const response = await get("/canvas-api/ready", readyDeadline); + ready = `HTTP ${response.status}`; + if (response.status === 200) { + log(`Rollout healthy: both components report ${expected}.`); + return "healthy"; + } + } catch { + ready = "network error"; + } + await wait(readyDeadline); + } + throw new Error( + `Readiness timed out: ${ready}; ${JSON.stringify(Object.fromEntries(last))}`, + ); + } + await wait(deadline); + } + throw timedOut(); +} + +if (import.meta.main) { + try { + await rolloutSmoke({ + baseUrl: process.argv[2] ?? "https://moddrop.live", + version: process.argv[3] ?? "", + timeoutMs: Number( + process.argv[4] ?? process.env.ROLLOUT_TIMEOUT_MS ?? 1_800_000, + ), + }); + } catch (error) { + console.error( + error instanceof Error ? error.message : "Rollout check failed", + ); + process.exitCode = 1; + } +} diff --git a/scripts/verify-proof.test.ts b/scripts/verify-proof.test.ts new file mode 100644 index 0000000..1e9a2db --- /dev/null +++ b/scripts/verify-proof.test.ts @@ -0,0 +1,96 @@ +import { expect, test, vi } from "vitest"; +import { canReuseVerify, type ProofApi } from "./verify-proof"; + +const tree = "a".repeat(40); +const commit = "b".repeat(40); +const repository = "owner/moddrop"; +function fixture() { + const artifact: Awaited>[number] = { + id: 1, + name: `verify-proof-${tree}`, + expired: false, + expires_at: "2099-01-01T00:00:00Z", + workflow_run: { id: 2 }, + }; + const run: Awaited> = { + path: ".github/workflows/verify.yml", + status: "completed", + conclusion: "success", + head_repository: { full_name: repository }, + }; + const api = { + artifacts: vi.fn(async () => [artifact]), + run: vi.fn(async () => run), + download: vi.fn(async () => JSON.stringify({ tree, commit })), + } satisfies ProofApi; + return { artifact, run, api }; +} + +test("accepts matching tree from a successful same-repository Verify run, regardless of commit", async () => { + const { api } = fixture(); + expect(await canReuseVerify(api, repository, tree)).toBe(true); + expect(api.artifacts).toHaveBeenCalledWith(`verify-proof-${tree}`, 1); + expect(api.run).toHaveBeenCalledWith(2); +}); + +test.each([ + { path: ".github/workflows/build-images.yml" }, + { status: "in_progress" }, + { conclusion: "failure" }, + { conclusion: "cancelled" }, + { conclusion: "skipped" }, + { head_repository: { full_name: "fork/moddrop" } }, + { head_repository: null }, +])("rejects untrusted/unsuccessful run %j", async (override) => { + const { api, run } = fixture(); + api.run.mockResolvedValue({ ...run, ...override }); + expect(await canReuseVerify(api, repository, tree)).toBe(false); + expect(api.download).not.toHaveBeenCalled(); +}); + +test.each([ + { expired: true }, + { expires_at: "2000-01-01T00:00:00Z" }, + { expires_at: "invalid" }, + { name: "verify-proof-other" }, + { workflow_run: undefined }, +])("rejects unusable artifact %j", async (override) => { + const { api, artifact } = fixture(); + api.artifacts.mockResolvedValue([{ ...artifact, ...override }]); + expect(await canReuseVerify(api, repository, tree)).toBe(false); +}); + +test.each([ + "not JSON", + "null", + "[]", + JSON.stringify({ tree: "c".repeat(40), commit }), + JSON.stringify({ tree: "x".repeat(40), commit }), + JSON.stringify({ tree, commit: "invalid" }), + JSON.stringify({ tree }), + "process.exit(0)", +])("parses proof strictly as data and rejects %s", async (body) => { + const { api } = fixture(); + api.download.mockResolvedValue(body); + expect(await canReuseVerify(api, repository, tree)).toBe(false); +}); + +test("missing proof, invalid expected SHA and API/archive errors fall back", async () => { + const { api } = fixture(); + expect(await canReuseVerify(api, repository, "invalid")).toBe(false); + api.artifacts.mockResolvedValueOnce([]); + expect(await canReuseVerify(api, repository, tree)).toBe(false); + for (const method of [api.artifacts, api.run, api.download]) { + method.mockRejectedValueOnce(new Error("unavailable")); + expect(await canReuseVerify(api, repository, tree)).toBe(false); + } +}); + +test("paginates named artifacts until a valid proof is found", async () => { + const { api, artifact } = fixture(); + api.artifacts.mockResolvedValueOnce( + Array.from({ length: 100 }, () => ({ ...artifact, expired: true })), + ); + expect(await canReuseVerify(api, repository, tree)).toBe(true); + expect(api.artifacts).toHaveBeenLastCalledWith(`verify-proof-${tree}`, 2); +}); diff --git a/scripts/verify-proof.ts b/scripts/verify-proof.ts new file mode 100644 index 0000000..f622580 --- /dev/null +++ b/scripts/verify-proof.ts @@ -0,0 +1,147 @@ +import { execFileSync } from "node:child_process"; +import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +type Artifact = { + id: number; + name: string; + expired: boolean; + expires_at: string; + workflow_run?: { id: number }; +}; +type Run = { + path: string; + status: string; + conclusion: string | null; + head_repository: { full_name: string } | null; +}; +export type ProofApi = { + artifacts: (name: string, page: number) => Promise; + run: (id: number) => Promise; + download: (id: number) => Promise; +}; +const sha = /^[0-9a-f]{40}$/; + +export async function canReuseVerify( + api: ProofApi, + repository: string, + tree: string, + now = Date.now(), +): Promise { + try { + if (!sha.test(tree)) return false; + const name = `verify-proof-${tree}`; + for (let page = 1; ; page++) { + const artifacts = await api.artifacts(name, page); + for (const artifact of artifacts) { + if ( + artifact.name !== name || + artifact.expired || + !(Date.parse(artifact.expires_at) > now) || + !artifact.workflow_run + ) + continue; + const run = await api.run(artifact.workflow_run.id); + if ( + run.path !== ".github/workflows/verify.yml" || + run.status !== "completed" || + run.conclusion !== "success" || + run.head_repository?.full_name !== repository + ) + continue; + const proof: unknown = JSON.parse(await api.download(artifact.id)); + if ( + proof !== null && + typeof proof === "object" && + "tree" in proof && + typeof proof.tree === "string" && + sha.test(proof.tree) && + proof.tree === tree && + "commit" in proof && + typeof proof.commit === "string" && + sha.test(proof.commit) + ) + return true; + } + if (artifacts.length < 100) return false; + } + } catch { + // An unavailable API, invalid archive or malformed proof requires full verify. + return false; + } +} + +export function githubProofApi( + repository: string, + token: string, + apiUrl = "https://api.github.com", +): ProofApi { + const root = `${apiUrl}/repos/${repository}`; + async function request(path: string) { + const response = await fetch(`${root}${path}`, { + headers: { + Authorization: `Bearer ${token}`, + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + }, + signal: AbortSignal.timeout(15_000), + }); + if (!response.ok) throw new Error("GitHub proof lookup failed"); + return response; + } + return { + async artifacts(name, page) { + const response = await request( + `/actions/artifacts?name=${encodeURIComponent(name)}&per_page=100&page=${page}`, + ); + return (await response.json()).artifacts; + }, + async run(id) { + return (await request(`/actions/runs/${id}`)).json(); + }, + async download(id) { + const response = await request(`/actions/artifacts/${id}/zip`); + const directory = mkdtempSync(join(tmpdir(), "verify-proof-")); + try { + const archive = join(directory, "proof.zip"); + writeFileSync(archive, Buffer.from(await response.arrayBuffer())); + // Read one fixed member as data. Never extract paths or execute archive contents. + return execFileSync("unzip", ["-p", archive, "verify-proof.json"], { + encoding: "utf8", + timeout: 5_000, + maxBuffer: 16_384, + stdio: ["ignore", "pipe", "ignore"], + }); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }, + }; +} + +if (import.meta.main) { + let reuse = false; + try { + const tree = execFileSync( + "git", + ["rev-parse", `${process.env.GITHUB_SHA}^{tree}`], + { encoding: "utf8", timeout: 5_000 }, + ).trim(); + const repository = process.env.GITHUB_REPOSITORY; + const token = process.env.GH_TOKEN; + if (repository && token) + reuse = await canReuseVerify( + githubProofApi(repository, token, process.env.GITHUB_API_URL), + repository, + tree, + ); + } catch { + // Checkout or git failures also fall back to the existing workflow. + } + console.log( + reuse ? "Reusing successful Verify tree proof." : "Full Verify required.", + ); + if (process.env.GITHUB_OUTPUT) + appendFileSync(process.env.GITHUB_OUTPUT, `reuse=${reuse}\n`); +} From 88523f71e15a2d81ab0e9b439ebc786a40dd032c Mon Sep 17 00:00:00 2001 From: beasty Date: Fri, 23 Oct 2026 01:18:24 +0200 Subject: [PATCH 2/9] ci: explain verify-proof fallbacks and retry homepage smoke --- .github/workflows/verify.yml | 2 +- docs/releasing.md | 8 +- scripts/delivery-changes.test.ts | 4 +- scripts/rollout-smoke.test.ts | 50 +++++++++-- scripts/rollout-smoke.ts | 23 +++-- scripts/verify-proof.test.ts | 139 ++++++++++++++++++++++++++++++- scripts/verify-proof.ts | 99 ++++++++++++++++++---- 7 files changed, 286 insertions(+), 39 deletions(-) diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 20a79fa..4b2080a 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -51,7 +51,7 @@ jobs: writeFileSync('verify-proof.json', JSON.stringify(proof)); appendFileSync(process.env.GITHUB_OUTPUT, `tree=${proof.tree}\n`); NODE - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 with: name: verify-proof-${{ steps.proof.outputs.tree }} path: verify-proof.json diff --git a/docs/releasing.md b/docs/releasing.md index c5d8214..11debf2 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -5,13 +5,15 @@ the checked-out commit and tree in a JSON artifact after the full suite passes, retained for 14 days. The release gate reuses proof only for the exact release tree from a completed, successful Verify run in this repository. Fork PR runs cannot supply proof. Missing, expired, invalid or unavailable proof falls back -to the full Verify workflow. Both production images still build on `arc-moddrop` -and publish to GHCR after verification succeeds. +to the full Verify workflow. The gate logs the fallback reason as a notice, +or a warning for API, download and unzip errors. Both production images still +build on `arc-moddrop` and publish to GHCR after verification succeeds. For tags, a rollout smoke job waits up to 30 minutes for Flux to deploy both components. It polls `/telemetry-config` and `/canvas-api/version` at `https://moddrop.live` every 20 seconds until both report `moddrop@`, -then checks `/` and retries `/canvas-api/ready` for up to a minute. The overall +then retries `/` until successful and checks `/canvas-api/ready` for HTTP 200. +Both checks share a one-minute retry window. The overall deadline includes readiness retries. A newer semver on either component marks the release as superseded and skips remaining checks. Timeouts fail with each endpoint's last observation. For manual use, run diff --git a/scripts/delivery-changes.test.ts b/scripts/delivery-changes.test.ts index 6052b99..c2c1231 100644 --- a/scripts/delivery-changes.test.ts +++ b/scripts/delivery-changes.test.ts @@ -28,7 +28,9 @@ test("GitHub releases use the PR verification gate before production actions", ( (step: { run?: string }) => step.run === "bash scripts/verify.sh", ); expect(verifyIndex).toBeGreaterThan(-1); - expect(steps.at(-1).uses).toBe("actions/upload-artifact@v4"); + expect(steps.at(-1).uses).toBe("actions/upload-artifact@v7"); + expect(steps.at(-1).with.path).toBe("verify-proof.json"); + expect(steps.at(-1).with.archive).toBeUndefined(); // v7 defaults to a ZIP. for (const step of steps.slice(verifyIndex + 1)) expect(step.if).toBeUndefined(); // Default success() protects the proof. diff --git a/scripts/rollout-smoke.test.ts b/scripts/rollout-smoke.test.ts index c482eee..84813b8 100644 --- a/scripts/rollout-smoke.test.ts +++ b/scripts/rollout-smoke.test.ts @@ -130,22 +130,56 @@ test.each([ }, ); -test("homepage failure fails after matching releases", async () => { - const { options, queues } = fixture([expected], [expected]); - queues["/"] = [502]; - await expect(rolloutSmoke(options)).rejects.toThrow( - "Homepage returned HTTP 502", - ); -}); +test.each([ + [502, "HTTP 502"], + [new Error("offline"), "network error"], +] as const)( + "homepage failure retries after matching releases: %j", + async (reply, observation) => { + const { options, queues, request } = fixture([expected], [expected]); + queues["/"] = [reply]; + await expect(rolloutSmoke(options)).rejects.toThrow( + `Readiness timed out: /: ${observation}; /canvas-api/ready: not checked`, + ); + expect( + request.mock.calls.slice(2).map(([url]) => new URL(String(url)).pathname), + ).toEqual(["/", "/"]); + expect(options.now()).toBe(40); + }, +); + +test.each([502, new Error("offline")])( + "homepage recovers from a transient failure: %j", + async (reply) => { + const { options, queues, request } = fixture([expected], [expected]); + queues["/"] = [reply, 200]; + expect(await rolloutSmoke(options)).toBe("healthy"); + expect( + request.mock.calls.slice(2).map(([url]) => new URL(String(url)).pathname), + ).toEqual(["/", "/", "/canvas-api/ready"]); + }, +); test("readiness retries are bounded by the short window and overall deadline", async () => { const { options, request } = fixture([expected], [expected], [503]); await expect(rolloutSmoke({ ...options, timeoutMs: 30 })).rejects.toThrow( - "Readiness timed out: HTTP 503", + "Readiness timed out: /: HTTP 200; /canvas-api/ready: HTTP 503", ); expect(request).toHaveBeenCalledTimes(5); }); +test("homepage retries share the readiness window and overall deadline", async () => { + const { options, queues, request } = fixture([expected], [expected], [503]); + queues["/"] = [502, 200]; + await expect(rolloutSmoke({ ...options, timeoutMs: 30 })).rejects.toThrow( + "Readiness timed out: /: HTTP 200; /canvas-api/ready: HTTP 503", + ); + expect(options.now()).toBe(30); + expect( + request.mock.calls.slice(2).map(([url]) => new URL(String(url)).pathname), + ).toEqual(["/", "/", "/canvas-api/ready"]); +}); + test.each([ ["0.10.0", "0.9.0", 1], ["1.0.0", "1.0.0-rc.1", 1], diff --git a/scripts/rollout-smoke.ts b/scripts/rollout-smoke.ts index b56930b..8f7c8ac 100644 --- a/scripts/rollout-smoke.ts +++ b/scripts/rollout-smoke.ts @@ -123,14 +123,25 @@ export async function rolloutSmoke(options: SmokeOptions) { } log(paths.map((path) => `${path}: ${last.get(path)}`).join("; ")); if (releases.every((release) => release === expected)) { - const home = await get("/").catch((error: unknown) => { - if (now() >= deadline) throw timedOut(); - throw error; - }); - if (!home.ok) throw new Error(`Homepage returned HTTP ${home.status}`); + if (now() >= deadline) throw timedOut(); const readyDeadline = Math.min(deadline, now() + readyTimeoutMs); + let homeOk = false; + let home = "not checked"; let ready = "not checked"; while (now() < readyDeadline) { + if (!homeOk) { + try { + const response = await get("/", readyDeadline); + home = `HTTP ${response.status}`; + homeOk = response.ok; + } catch { + home = "network error"; + } + if (!homeOk) { + await wait(readyDeadline); + continue; + } + } try { const response = await get("/canvas-api/ready", readyDeadline); ready = `HTTP ${response.status}`; @@ -144,7 +155,7 @@ export async function rolloutSmoke(options: SmokeOptions) { await wait(readyDeadline); } throw new Error( - `Readiness timed out: ${ready}; ${JSON.stringify(Object.fromEntries(last))}`, + `Readiness timed out: /: ${home}; /canvas-api/ready: ${ready}; ${JSON.stringify(Object.fromEntries(last))}`, ); } await wait(deadline); diff --git a/scripts/verify-proof.test.ts b/scripts/verify-proof.test.ts index 1e9a2db..0578002 100644 --- a/scripts/verify-proof.test.ts +++ b/scripts/verify-proof.test.ts @@ -1,5 +1,12 @@ -import { expect, test, vi } from "vitest"; -import { canReuseVerify, type ProofApi } from "./verify-proof"; +import { execFileSync } from "node:child_process"; +import { afterEach, expect, test, vi } from "vitest"; +import { canReuseVerify, githubProofApi, type ProofApi } from "./verify-proof"; + +vi.mock("node:child_process", () => ({ execFileSync: vi.fn() })); +afterEach(() => { + vi.unstubAllGlobals(); + vi.mocked(execFileSync).mockReset(); +}); const tree = "a".repeat(40); const commit = "b".repeat(40); @@ -94,3 +101,131 @@ test("paginates named artifacts until a valid proof is found", async () => { expect(await canReuseVerify(api, repository, tree)).toBe(true); expect(api.artifacts).toHaveBeenLastCalledWith(`verify-proof-${tree}`, 2); }); + +test.each([ + "no artifact named for this tree", + "artifact expired or invalid expiry", + "run not successful/completed", + "wrong workflow path", + "foreign head repository", + "malformed proof", + "tree mismatch", +])("reports a concise notice for %s", async (reason) => { + const { api, artifact, run } = fixture(); + const report = vi.fn(); + switch (reason) { + case "no artifact named for this tree": + api.artifacts.mockResolvedValue([]); + break; + case "artifact expired or invalid expiry": + artifact.expired = true; + break; + case "run not successful/completed": + run.conclusion = "failure"; + break; + case "wrong workflow path": + run.path = ".github/workflows/build-images.yml"; + break; + case "foreign head repository": + run.head_repository = { full_name: "fork/moddrop" }; + break; + case "malformed proof": + api.download.mockResolvedValue("not JSON"); + break; + case "tree mismatch": + api.download.mockResolvedValue( + JSON.stringify({ tree: "c".repeat(40), commit }), + ); + break; + } + expect(await canReuseVerify(api, repository, tree, Date.now(), report)).toBe( + false, + ); + expect(report).toHaveBeenCalledExactlyOnceWith(reason, "notice"); +}); + +test("reports API errors by class without exposing the error message", async () => { + const { api } = fixture(); + const report = vi.fn(); + api.artifacts.mockRejectedValue(new TypeError("private diagnostic")); + expect(await canReuseVerify(api, repository, tree, Date.now(), report)).toBe( + false, + ); + expect(report).toHaveBeenCalledExactlyOnceWith( + "API artifact lookup failed (TypeError)", + "warning", + ); +}); + +test.each([401, 403, 404])( + "reports HTTP %s from API lookup or artifact download without response bodies", + async (status) => { + const { artifact, run } = fixture(); + for (const stage of [0, 1, 2]) { + let calls = 0; + vi.stubGlobal( + "fetch", + vi.fn(async () => { + if (calls++ === stage) + return new Response("private response", { status }); + return Response.json(calls === 1 ? { artifacts: [artifact] } : run); + }), + ); + const report = vi.fn(); + expect( + await canReuseVerify( + githubProofApi( + repository, + "fixture-token", + "https://fixture.invalid", + ), + repository, + tree, + Date.now(), + report, + ), + ).toBe(false); + expect(report).toHaveBeenCalledExactlyOnceWith( + `GitHub proof API HTTP ${status}`, + "warning", + ); + } + }, +); + +test.each([ + [ + Object.assign(new Error("private command diagnostic"), { code: "ENOENT" }), + "unzip not available on runner (ENOENT)", + ], + [new Error("private archive diagnostic"), "artifact unzip failed (Error)"], +] as const)("reports unzip failures safely: %j", async (error, reason) => { + const { artifact, run } = fixture(); + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValueOnce(Response.json({ artifacts: [artifact] })) + .mockResolvedValueOnce(Response.json(run)) + .mockResolvedValueOnce(new Response("fixture archive")), + ); + vi.mocked(execFileSync).mockImplementation(() => { + throw error; + }); + const report = vi.fn(); + expect( + await canReuseVerify( + githubProofApi(repository, "fixture-token", "https://fixture.invalid"), + repository, + tree, + Date.now(), + report, + ), + ).toBe(false); + expect(report).toHaveBeenCalledExactlyOnceWith(reason, "warning"); + expect(execFileSync).toHaveBeenCalledWith( + "unzip", + ["-p", expect.any(String), "verify-proof.json"], + expect.objectContaining({ stdio: ["ignore", "pipe", "ignore"] }), + ); +}); diff --git a/scripts/verify-proof.ts b/scripts/verify-proof.ts index f622580..3e01ff2 100644 --- a/scripts/verify-proof.ts +++ b/scripts/verify-proof.ts @@ -22,17 +22,35 @@ export type ProofApi = { download: (id: number) => Promise; }; const sha = /^[0-9a-f]{40}$/; +type Report = (reason: string, level: "notice" | "warning") => void; + +class ProofLookupError extends Error {} + +function errorClass(error: unknown) { + if (error instanceof TypeError) return "TypeError"; + if (error instanceof SyntaxError) return "SyntaxError"; + if (error instanceof DOMException) return "DOMException"; + return error instanceof Error ? "Error" : "unknown error"; +} export async function canReuseVerify( api: ProofApi, repository: string, tree: string, now = Date.now(), + report: Report = () => {}, ): Promise { + const fallback = (reason: string, level: "notice" | "warning" = "notice") => { + report(reason, level); + return false; + }; + let reason = "no artifact named for this tree"; + let operation = "API artifact lookup"; try { - if (!sha.test(tree)) return false; + if (!sha.test(tree)) return fallback("invalid release tree"); const name = `verify-proof-${tree}`; for (let page = 1; ; page++) { + operation = "API artifact lookup"; const artifacts = await api.artifacts(name, page); for (const artifact of artifacts) { if ( @@ -40,17 +58,34 @@ export async function canReuseVerify( artifact.expired || !(Date.parse(artifact.expires_at) > now) || !artifact.workflow_run - ) + ) { + if (artifact.name === name) + reason = + artifact.expired || !(Date.parse(artifact.expires_at) > now) + ? "artifact expired or invalid expiry" + : "artifact has no workflow run"; continue; + } + operation = "API run lookup"; const run = await api.run(artifact.workflow_run.id); if ( run.path !== ".github/workflows/verify.yml" || run.status !== "completed" || run.conclusion !== "success" || run.head_repository?.full_name !== repository - ) + ) { + reason = + run.path !== ".github/workflows/verify.yml" + ? "wrong workflow path" + : run.status !== "completed" || run.conclusion !== "success" + ? "run not successful/completed" + : "foreign head repository"; continue; - const proof: unknown = JSON.parse(await api.download(artifact.id)); + } + operation = "artifact download"; + const contents = await api.download(artifact.id); + operation = "proof parsing"; + const proof: unknown = JSON.parse(contents); if ( proof !== null && typeof proof === "object" && @@ -63,12 +98,27 @@ export async function canReuseVerify( sha.test(proof.commit) ) return true; + reason = + proof !== null && + typeof proof === "object" && + "tree" in proof && + typeof proof.tree === "string" && + sha.test(proof.tree) && + proof.tree !== tree + ? "tree mismatch" + : "malformed proof"; } - if (artifacts.length < 100) return false; + if (artifacts.length < 100) return fallback(reason); } - } catch { + } catch (error) { // An unavailable API, invalid archive or malformed proof requires full verify. - return false; + if (operation === "proof parsing") return fallback("malformed proof"); + return fallback( + error instanceof ProofLookupError + ? error.message + : `${operation} failed (${errorClass(error)})`, + "warning", + ); } } @@ -87,7 +137,8 @@ export function githubProofApi( }, signal: AbortSignal.timeout(15_000), }); - if (!response.ok) throw new Error("GitHub proof lookup failed"); + if (!response.ok) + throw new ProofLookupError(`GitHub proof API HTTP ${response.status}`); return response; } return { @@ -107,12 +158,20 @@ export function githubProofApi( const archive = join(directory, "proof.zip"); writeFileSync(archive, Buffer.from(await response.arrayBuffer())); // Read one fixed member as data. Never extract paths or execute archive contents. - return execFileSync("unzip", ["-p", archive, "verify-proof.json"], { - encoding: "utf8", - timeout: 5_000, - maxBuffer: 16_384, - stdio: ["ignore", "pipe", "ignore"], - }); + try { + return execFileSync("unzip", ["-p", archive, "verify-proof.json"], { + encoding: "utf8", + timeout: 5_000, + maxBuffer: 16_384, + stdio: ["ignore", "pipe", "ignore"], + }); + } catch (error) { + throw new ProofLookupError( + error instanceof Error && "code" in error && error.code === "ENOENT" + ? "unzip not available on runner (ENOENT)" + : `artifact unzip failed (${errorClass(error)})`, + ); + } } finally { rmSync(directory, { recursive: true, force: true }); } @@ -122,6 +181,8 @@ export function githubProofApi( if (import.meta.main) { let reuse = false; + const report: Report = (reason, level) => + console.log(`::${level}::Full Verify required: ${reason}.`); try { const tree = execFileSync( "git", @@ -135,13 +196,15 @@ if (import.meta.main) { githubProofApi(repository, token, process.env.GITHUB_API_URL), repository, tree, + Date.now(), + report, ); - } catch { + else report("missing GitHub repository or token", "warning"); + } catch (error) { // Checkout or git failures also fall back to the existing workflow. + report(`checkout tree lookup failed (${errorClass(error)})`, "warning"); } - console.log( - reuse ? "Reusing successful Verify tree proof." : "Full Verify required.", - ); + if (reuse) console.log("Reusing successful Verify tree proof."); if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `reuse=${reuse}\n`); } From b301eac7877cb287af22c952afeaa56f2d804855 Mon Sep 17 00:00:00 2001 From: beasty Date: Fri, 23 Oct 2026 02:32:34 +0200 Subject: [PATCH 3/9] ci: bind verify proof to the release verify workflow --- .github/workflows/verify.yml | 1 + docs/releasing.md | 3 +- scripts/delivery-changes.test.ts | 1 + scripts/verify-proof.test.ts | 191 ++++++++++++++++++++++++++++--- scripts/verify-proof.ts | 36 +++++- 5 files changed, 212 insertions(+), 20 deletions(-) diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 4b2080a..4ae1c65 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -55,5 +55,6 @@ jobs: with: name: verify-proof-${{ steps.proof.outputs.tree }} path: verify-proof.json + overwrite: true if-no-files-found: error retention-days: 14 diff --git a/docs/releasing.md b/docs/releasing.md index 11debf2..2d13aaa 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -3,7 +3,8 @@ Pushing a `vX.Y.Z` tag runs the GitHub container-image workflow. Verify records the checked-out commit and tree in a JSON artifact after the full suite passes, retained for 14 days. The release gate reuses proof only for the exact release -tree from a completed, successful Verify run in this repository. Fork PR runs +tree from a completed, successful Verify run in this repository. Proof is reused +only when the Verify run used the same `verify.yml` as the release. Fork PR runs cannot supply proof. Missing, expired, invalid or unavailable proof falls back to the full Verify workflow. The gate logs the fallback reason as a notice, or a warning for API, download and unzip errors. Both production images still diff --git a/scripts/delivery-changes.test.ts b/scripts/delivery-changes.test.ts index c2c1231..19e14ce 100644 --- a/scripts/delivery-changes.test.ts +++ b/scripts/delivery-changes.test.ts @@ -30,6 +30,7 @@ test("GitHub releases use the PR verification gate before production actions", ( expect(verifyIndex).toBeGreaterThan(-1); expect(steps.at(-1).uses).toBe("actions/upload-artifact@v7"); expect(steps.at(-1).with.path).toBe("verify-proof.json"); + expect(steps.at(-1).with.overwrite).toBe(true); expect(steps.at(-1).with.archive).toBeUndefined(); // v7 defaults to a ZIP. for (const step of steps.slice(verifyIndex + 1)) expect(step.if).toBeUndefined(); // Default success() protects the proof. diff --git a/scripts/verify-proof.test.ts b/scripts/verify-proof.test.ts index 0578002..7263cdb 100644 --- a/scripts/verify-proof.test.ts +++ b/scripts/verify-proof.test.ts @@ -10,6 +10,7 @@ afterEach(() => { const tree = "a".repeat(40); const commit = "b".repeat(40); +const workflowBlob = "d".repeat(40); const repository = "owner/moddrop"; function fixture() { const artifact: Awaited>[number] = { @@ -20,6 +21,7 @@ function fixture() { workflow_run: { id: 2 }, }; const run: Awaited> = { + head_sha: commit, path: ".github/workflows/verify.yml", status: "completed", conclusion: "success", @@ -28,16 +30,19 @@ function fixture() { const api = { artifacts: vi.fn(async () => [artifact]), run: vi.fn(async () => run), + workflowBlob: vi.fn(async () => workflowBlob), download: vi.fn(async () => JSON.stringify({ tree, commit })), } satisfies ProofApi; return { artifact, run, api }; } -test("accepts matching tree from a successful same-repository Verify run, regardless of commit", async () => { +test("accepts matching tree and workflow blob from a successful same-repository Verify run, regardless of commit", async () => { const { api } = fixture(); - expect(await canReuseVerify(api, repository, tree)).toBe(true); + expect(await canReuseVerify(api, repository, tree, workflowBlob)).toBe(true); expect(api.artifacts).toHaveBeenCalledWith(`verify-proof-${tree}`, 1); expect(api.run).toHaveBeenCalledWith(2); + expect(api.workflowBlob).toHaveBeenCalledWith(commit); + expect(api.download).toHaveBeenCalledWith(1); }); test.each([ @@ -51,10 +56,128 @@ test.each([ ])("rejects untrusted/unsuccessful run %j", async (override) => { const { api, run } = fixture(); api.run.mockResolvedValue({ ...run, ...override }); - expect(await canReuseVerify(api, repository, tree)).toBe(false); + expect(await canReuseVerify(api, repository, tree, workflowBlob)).toBe(false); + expect(api.workflowBlob).not.toHaveBeenCalled(); expect(api.download).not.toHaveBeenCalled(); }); +test("rejects a different Verify workflow before downloading proof", async () => { + const { api } = fixture(); + const report = vi.fn(); + api.workflowBlob.mockResolvedValue("e".repeat(40)); + expect( + await canReuseVerify( + api, + repository, + tree, + workflowBlob, + Date.now(), + report, + ), + ).toBe(false); + expect(report).toHaveBeenCalledExactlyOnceWith( + "verify workflow differs from release", + "notice", + ); + expect(api.download).not.toHaveBeenCalled(); +}); + +test.each(["invalid", "x".repeat(40), "a".repeat(39), "a".repeat(41)])( + "rejects invalid run head SHA %s before looking up the workflow", + async (head_sha) => { + const { api, run } = fixture(); + const report = vi.fn(); + run.head_sha = head_sha; + expect( + await canReuseVerify( + api, + repository, + tree, + workflowBlob, + Date.now(), + report, + ), + ).toBe(false); + expect(report).toHaveBeenCalledExactlyOnceWith( + "invalid run head SHA", + "notice", + ); + expect(api.workflowBlob).not.toHaveBeenCalled(); + expect(api.download).not.toHaveBeenCalled(); + }, +); + +test.each(["invalid", "x".repeat(40), "a".repeat(39), "a".repeat(41)])( + "rejects invalid release or run workflow blob %s", + async (blob) => { + const { api } = fixture(); + const report = vi.fn(); + expect( + await canReuseVerify(api, repository, tree, blob, Date.now(), report), + ).toBe(false); + expect(report).toHaveBeenCalledExactlyOnceWith( + "invalid release workflow blob", + "notice", + ); + expect(api.artifacts).not.toHaveBeenCalled(); + + report.mockClear(); + api.workflowBlob.mockResolvedValue(blob); + expect( + await canReuseVerify( + api, + repository, + tree, + workflowBlob, + Date.now(), + report, + ), + ).toBe(false); + expect(report).toHaveBeenCalledExactlyOnceWith( + "invalid verify workflow blob", + "notice", + ); + expect(api.download).not.toHaveBeenCalled(); + }, +); + +test("reports a contents API error as a warning before downloading proof", async () => { + const { api } = fixture(); + const report = vi.fn(); + api.workflowBlob.mockRejectedValue(new TypeError("private diagnostic")); + expect( + await canReuseVerify( + api, + repository, + tree, + workflowBlob, + Date.now(), + report, + ), + ).toBe(false); + expect(report).toHaveBeenCalledExactlyOnceWith( + "API workflow blob lookup failed (TypeError)", + "warning", + ); + expect(api.download).not.toHaveBeenCalled(); +}); + +test("looks up the Verify workflow blob at the run head SHA using the contents API", async () => { + const fetch = vi.fn(async () => Response.json({ sha: workflowBlob })); + vi.stubGlobal("fetch", fetch); + expect( + await githubProofApi( + repository, + "fixture-token", + "https://fixture.invalid", + ).workflowBlob(commit), + ).toBe(workflowBlob); + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `https://fixture.invalid/repos/${repository}/contents/.github/workflows/verify.yml?ref=${commit}`, + expect.any(Object), + ); +}); + test.each([ { expired: true }, { expires_at: "2000-01-01T00:00:00Z" }, @@ -64,7 +187,7 @@ test.each([ ])("rejects unusable artifact %j", async (override) => { const { api, artifact } = fixture(); api.artifacts.mockResolvedValue([{ ...artifact, ...override }]); - expect(await canReuseVerify(api, repository, tree)).toBe(false); + expect(await canReuseVerify(api, repository, tree, workflowBlob)).toBe(false); }); test.each([ @@ -79,17 +202,26 @@ test.each([ ])("parses proof strictly as data and rejects %s", async (body) => { const { api } = fixture(); api.download.mockResolvedValue(body); - expect(await canReuseVerify(api, repository, tree)).toBe(false); + expect(await canReuseVerify(api, repository, tree, workflowBlob)).toBe(false); }); test("missing proof, invalid expected SHA and API/archive errors fall back", async () => { const { api } = fixture(); - expect(await canReuseVerify(api, repository, "invalid")).toBe(false); + expect(await canReuseVerify(api, repository, "invalid", workflowBlob)).toBe( + false, + ); api.artifacts.mockResolvedValueOnce([]); - expect(await canReuseVerify(api, repository, tree)).toBe(false); - for (const method of [api.artifacts, api.run, api.download]) { + expect(await canReuseVerify(api, repository, tree, workflowBlob)).toBe(false); + for (const method of [ + api.artifacts, + api.run, + api.workflowBlob, + api.download, + ]) { method.mockRejectedValueOnce(new Error("unavailable")); - expect(await canReuseVerify(api, repository, tree)).toBe(false); + expect(await canReuseVerify(api, repository, tree, workflowBlob)).toBe( + false, + ); } }); @@ -98,7 +230,7 @@ test("paginates named artifacts until a valid proof is found", async () => { api.artifacts.mockResolvedValueOnce( Array.from({ length: 100 }, () => ({ ...artifact, expired: true })), ); - expect(await canReuseVerify(api, repository, tree)).toBe(true); + expect(await canReuseVerify(api, repository, tree, workflowBlob)).toBe(true); expect(api.artifacts).toHaveBeenLastCalledWith(`verify-proof-${tree}`, 2); }); @@ -138,9 +270,16 @@ test.each([ ); break; } - expect(await canReuseVerify(api, repository, tree, Date.now(), report)).toBe( - false, - ); + expect( + await canReuseVerify( + api, + repository, + tree, + workflowBlob, + Date.now(), + report, + ), + ).toBe(false); expect(report).toHaveBeenCalledExactlyOnceWith(reason, "notice"); }); @@ -148,9 +287,16 @@ test("reports API errors by class without exposing the error message", async () const { api } = fixture(); const report = vi.fn(); api.artifacts.mockRejectedValue(new TypeError("private diagnostic")); - expect(await canReuseVerify(api, repository, tree, Date.now(), report)).toBe( - false, - ); + expect( + await canReuseVerify( + api, + repository, + tree, + workflowBlob, + Date.now(), + report, + ), + ).toBe(false); expect(report).toHaveBeenCalledExactlyOnceWith( "API artifact lookup failed (TypeError)", "warning", @@ -161,14 +307,20 @@ test.each([401, 403, 404])( "reports HTTP %s from API lookup or artifact download without response bodies", async (status) => { const { artifact, run } = fixture(); - for (const stage of [0, 1, 2]) { + for (const stage of [0, 1, 2, 3]) { let calls = 0; vi.stubGlobal( "fetch", vi.fn(async () => { if (calls++ === stage) return new Response("private response", { status }); - return Response.json(calls === 1 ? { artifacts: [artifact] } : run); + return Response.json( + calls === 1 + ? { artifacts: [artifact] } + : calls === 2 + ? run + : { sha: workflowBlob }, + ); }), ); const report = vi.fn(); @@ -181,6 +333,7 @@ test.each([401, 403, 404])( ), repository, tree, + workflowBlob, Date.now(), report, ), @@ -207,6 +360,7 @@ test.each([ .fn() .mockResolvedValueOnce(Response.json({ artifacts: [artifact] })) .mockResolvedValueOnce(Response.json(run)) + .mockResolvedValueOnce(Response.json({ sha: workflowBlob })) .mockResolvedValueOnce(new Response("fixture archive")), ); vi.mocked(execFileSync).mockImplementation(() => { @@ -218,6 +372,7 @@ test.each([ githubProofApi(repository, "fixture-token", "https://fixture.invalid"), repository, tree, + workflowBlob, Date.now(), report, ), diff --git a/scripts/verify-proof.ts b/scripts/verify-proof.ts index 3e01ff2..3f59d67 100644 --- a/scripts/verify-proof.ts +++ b/scripts/verify-proof.ts @@ -11,6 +11,7 @@ type Artifact = { workflow_run?: { id: number }; }; type Run = { + head_sha: string; path: string; status: string; conclusion: string | null; @@ -19,6 +20,7 @@ type Run = { export type ProofApi = { artifacts: (name: string, page: number) => Promise; run: (id: number) => Promise; + workflowBlob: (ref: string) => Promise; download: (id: number) => Promise; }; const sha = /^[0-9a-f]{40}$/; @@ -37,6 +39,7 @@ export async function canReuseVerify( api: ProofApi, repository: string, tree: string, + workflowBlob: string, now = Date.now(), report: Report = () => {}, ): Promise { @@ -48,6 +51,8 @@ export async function canReuseVerify( let operation = "API artifact lookup"; try { if (!sha.test(tree)) return fallback("invalid release tree"); + if (!sha.test(workflowBlob)) + return fallback("invalid release workflow blob"); const name = `verify-proof-${tree}`; for (let page = 1; ; page++) { operation = "API artifact lookup"; @@ -82,6 +87,20 @@ export async function canReuseVerify( : "foreign head repository"; continue; } + if (!sha.test(run.head_sha)) { + reason = "invalid run head SHA"; + continue; + } + operation = "API workflow blob lookup"; + const runWorkflowBlob = await api.workflowBlob(run.head_sha); + if (!sha.test(runWorkflowBlob)) { + reason = "invalid verify workflow blob"; + continue; + } + if (runWorkflowBlob !== workflowBlob) { + reason = "verify workflow differs from release"; + continue; + } operation = "artifact download"; const contents = await api.download(artifact.id); operation = "proof parsing"; @@ -151,6 +170,12 @@ export function githubProofApi( async run(id) { return (await request(`/actions/runs/${id}`)).json(); }, + async workflowBlob(ref) { + const response = await request( + `/contents/.github/workflows/verify.yml?ref=${encodeURIComponent(ref)}`, + ); + return (await response.json()).sha; + }, async download(id) { const response = await request(`/actions/artifacts/${id}/zip`); const directory = mkdtempSync(join(tmpdir(), "verify-proof-")); @@ -189,6 +214,11 @@ if (import.meta.main) { ["rev-parse", `${process.env.GITHUB_SHA}^{tree}`], { encoding: "utf8", timeout: 5_000 }, ).trim(); + const workflowBlob = execFileSync( + "git", + ["rev-parse", `${process.env.GITHUB_SHA}:.github/workflows/verify.yml`], + { encoding: "utf8", timeout: 5_000 }, + ).trim(); const repository = process.env.GITHUB_REPOSITORY; const token = process.env.GH_TOKEN; if (repository && token) @@ -196,13 +226,17 @@ if (import.meta.main) { githubProofApi(repository, token, process.env.GITHUB_API_URL), repository, tree, + workflowBlob, Date.now(), report, ); else report("missing GitHub repository or token", "warning"); } catch (error) { // Checkout or git failures also fall back to the existing workflow. - report(`checkout tree lookup failed (${errorClass(error)})`, "warning"); + report( + `checkout tree or workflow lookup failed (${errorClass(error)})`, + "warning", + ); } if (reuse) console.log("Reusing successful Verify tree proof."); if (process.env.GITHUB_OUTPUT) From 07a2f8b057c96048bea58fee7c70d0f8a8aadfe1 Mon Sep 17 00:00:00 2001 From: beasty Date: Fri, 23 Oct 2026 02:38:08 +0200 Subject: [PATCH 4/9] ci: record verify proof in an isolated job --- .github/workflows/verify.yml | 22 ++++++++++-------- docs/releasing.md | 7 +++--- scripts/delivery-changes.test.ts | 39 +++++++++++++++++++++++++++----- 3 files changed, 50 insertions(+), 18 deletions(-) diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 4ae1c65..150f608 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -39,18 +39,22 @@ jobs: - run: pnpm install --frozen-lockfile --ignore-scripts - run: pnpm exec playwright install --with-deps chromium - run: bash scripts/verify.sh + proof: + needs: verify + runs-on: arc-moddrop + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false - name: Record verified checkout id: proof run: | - git config --global --add safe.directory "$GITHUB_WORKSPACE" - node --input-type=module <<'NODE' - import { execFileSync } from 'node:child_process'; - import { appendFileSync, writeFileSync } from 'node:fs'; - const git = (ref) => execFileSync('git', ['rev-parse', ref], { encoding: 'utf8' }).trim(); - const proof = { commit: git('HEAD'), tree: git('HEAD^{tree}') }; - writeFileSync('verify-proof.json', JSON.stringify(proof)); - appendFileSync(process.env.GITHUB_OUTPUT, `tree=${proof.tree}\n`); - NODE + commit=$(git rev-parse HEAD) + tree=$(git rev-parse 'HEAD^{tree}') + [[ "$commit" =~ ^[0-9a-fA-F]{40}$ ]] + [[ "$tree" =~ ^[0-9a-fA-F]{40}$ ]] + printf '{"commit":"%s","tree":"%s"}\n' "$commit" "$tree" > verify-proof.json + printf 'tree=%s\n' "$tree" >> "$GITHUB_OUTPUT" - uses: actions/upload-artifact@v7 with: name: verify-proof-${{ steps.proof.outputs.tree }} diff --git a/docs/releasing.md b/docs/releasing.md index 2d13aaa..354a1c5 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,8 +1,9 @@ # Release and deployment notes -Pushing a `vX.Y.Z` tag runs the GitHub container-image workflow. Verify records -the checked-out commit and tree in a JSON artifact after the full suite passes, -retained for 14 days. The release gate reuses proof only for the exact release +Pushing a `vX.Y.Z` tag runs the GitHub container-image workflow. After the full +suite passes, a separate job that runs no repository code records the checked-out +commit and tree in a JSON proof artifact retained for 14 days. +The release gate reuses proof only for the exact release tree from a completed, successful Verify run in this repository. Proof is reused only when the Verify run used the same `verify.yml` as the release. Fork PR runs cannot supply proof. Missing, expired, invalid or unavailable proof falls back diff --git a/scripts/delivery-changes.test.ts b/scripts/delivery-changes.test.ts index 19e14ce..bd320de 100644 --- a/scripts/delivery-changes.test.ts +++ b/scripts/delivery-changes.test.ts @@ -28,12 +28,39 @@ test("GitHub releases use the PR verification gate before production actions", ( (step: { run?: string }) => step.run === "bash scripts/verify.sh", ); expect(verifyIndex).toBeGreaterThan(-1); - expect(steps.at(-1).uses).toBe("actions/upload-artifact@v7"); - expect(steps.at(-1).with.path).toBe("verify-proof.json"); - expect(steps.at(-1).with.overwrite).toBe(true); - expect(steps.at(-1).with.archive).toBeUndefined(); // v7 defaults to a ZIP. - for (const step of steps.slice(verifyIndex + 1)) - expect(step.if).toBeUndefined(); // Default success() protects the proof. + expect(steps.at(-1)).toEqual({ run: "bash scripts/verify.sh" }); + for (const step of steps) { + expect(step.uses ?? "").not.toMatch(/^actions\/upload-artifact@/); + expect(step.id).not.toBe("proof"); + expect(step.run ?? "").not.toContain("verify-proof"); + } + expect(verification.permissions).toEqual({ contents: "read" }); + expect(verification.jobs.proof).toEqual({ + needs: "verify", // Default success() requires the full suite to pass. + "runs-on": "arc-moddrop", + steps: [ + { + uses: "actions/checkout@v7", + with: { "persist-credentials": false }, + }, + { + name: "Record verified checkout", + id: "proof", + run: expect.stringContaining("git rev-parse 'HEAD^{tree}'"), + }, + { + uses: "actions/upload-artifact@v7", + with: { + // biome-ignore lint/suspicious/noTemplateCurlyInString: GitHub Actions expression. + name: "verify-proof-${{ steps.proof.outputs.tree }}", + path: "verify-proof.json", + overwrite: true, + "if-no-files-found": "error", + "retention-days": 14, + }, + }, + ], + }); const results = ["success", "failure", "cancelled", "skipped"]; for (const gate of results) From fc7cb42cb1ee4253e0fdd11d83b9e57609e4e1b6 Mon Sep 17 00:00:00 2001 From: beasty Date: Fri, 23 Oct 2026 02:45:46 +0200 Subject: [PATCH 5/9] ci: bind verify proof to the run head commit tree --- docs/releasing.md | 6 +- scripts/verify-proof.test.ts | 156 +++++++++++------------------------ scripts/verify-proof.ts | 40 ++++----- 3 files changed, 65 insertions(+), 137 deletions(-) diff --git a/docs/releasing.md b/docs/releasing.md index 354a1c5..5562692 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -5,8 +5,10 @@ suite passes, a separate job that runs no repository code records the checked-ou commit and tree in a JSON proof artifact retained for 14 days. The release gate reuses proof only for the exact release tree from a completed, successful Verify run in this repository. Proof is reused -only when the Verify run used the same `verify.yml` as the release. Fork PR runs -cannot supply proof. Missing, expired, invalid or unavailable proof falls back +only when GitHub's record of the Verify run's head commit has the release tree. +The artifact is only an index. PR runs whose merge tree differs from their head +tree fall back to full verification. Fork PR runs cannot supply proof. +Missing, expired, invalid or unavailable proof falls back to the full Verify workflow. The gate logs the fallback reason as a notice, or a warning for API, download and unzip errors. Both production images still build on `arc-moddrop` and publish to GHCR after verification succeeds. diff --git a/scripts/verify-proof.test.ts b/scripts/verify-proof.test.ts index 7263cdb..3341ac8 100644 --- a/scripts/verify-proof.test.ts +++ b/scripts/verify-proof.test.ts @@ -10,7 +10,6 @@ afterEach(() => { const tree = "a".repeat(40); const commit = "b".repeat(40); -const workflowBlob = "d".repeat(40); const repository = "owner/moddrop"; function fixture() { const artifact: Awaited>[number] = { @@ -30,18 +29,18 @@ function fixture() { const api = { artifacts: vi.fn(async () => [artifact]), run: vi.fn(async () => run), - workflowBlob: vi.fn(async () => workflowBlob), + commitTree: vi.fn(async () => tree), download: vi.fn(async () => JSON.stringify({ tree, commit })), } satisfies ProofApi; return { artifact, run, api }; } -test("accepts matching tree and workflow blob from a successful same-repository Verify run, regardless of commit", async () => { +test("accepts matching artifact and run head trees from a successful same-repository Verify run, regardless of commit", async () => { const { api } = fixture(); - expect(await canReuseVerify(api, repository, tree, workflowBlob)).toBe(true); + expect(await canReuseVerify(api, repository, tree)).toBe(true); expect(api.artifacts).toHaveBeenCalledWith(`verify-proof-${tree}`, 1); expect(api.run).toHaveBeenCalledWith(2); - expect(api.workflowBlob).toHaveBeenCalledWith(commit); + expect(api.commitTree).toHaveBeenCalledWith(commit); expect(api.download).toHaveBeenCalledWith(1); }); @@ -56,124 +55,86 @@ test.each([ ])("rejects untrusted/unsuccessful run %j", async (override) => { const { api, run } = fixture(); api.run.mockResolvedValue({ ...run, ...override }); - expect(await canReuseVerify(api, repository, tree, workflowBlob)).toBe(false); - expect(api.workflowBlob).not.toHaveBeenCalled(); + expect(await canReuseVerify(api, repository, tree)).toBe(false); + expect(api.commitTree).not.toHaveBeenCalled(); expect(api.download).not.toHaveBeenCalled(); }); -test("rejects a different Verify workflow before downloading proof", async () => { +test("rejects a valid artifact claiming the release tree when the run head tree differs before downloading proof", async () => { const { api } = fixture(); const report = vi.fn(); - api.workflowBlob.mockResolvedValue("e".repeat(40)); - expect( - await canReuseVerify( - api, - repository, - tree, - workflowBlob, - Date.now(), - report, - ), - ).toBe(false); + api.commitTree.mockResolvedValue("e".repeat(40)); + expect(await canReuseVerify(api, repository, tree, Date.now(), report)).toBe( + false, + ); expect(report).toHaveBeenCalledExactlyOnceWith( - "verify workflow differs from release", + "run head tree differs from release", "notice", ); expect(api.download).not.toHaveBeenCalled(); }); test.each(["invalid", "x".repeat(40), "a".repeat(39), "a".repeat(41)])( - "rejects invalid run head SHA %s before looking up the workflow", + "rejects invalid run head SHA %s before looking up the commit tree", async (head_sha) => { const { api, run } = fixture(); const report = vi.fn(); run.head_sha = head_sha; expect( - await canReuseVerify( - api, - repository, - tree, - workflowBlob, - Date.now(), - report, - ), + await canReuseVerify(api, repository, tree, Date.now(), report), ).toBe(false); expect(report).toHaveBeenCalledExactlyOnceWith( "invalid run head SHA", "notice", ); - expect(api.workflowBlob).not.toHaveBeenCalled(); + expect(api.commitTree).not.toHaveBeenCalled(); expect(api.download).not.toHaveBeenCalled(); }, ); test.each(["invalid", "x".repeat(40), "a".repeat(39), "a".repeat(41)])( - "rejects invalid release or run workflow blob %s", - async (blob) => { + "rejects invalid run head tree %s before downloading proof", + async (invalidTree) => { const { api } = fixture(); const report = vi.fn(); + api.commitTree.mockResolvedValue(invalidTree); expect( - await canReuseVerify(api, repository, tree, blob, Date.now(), report), + await canReuseVerify(api, repository, tree, Date.now(), report), ).toBe(false); expect(report).toHaveBeenCalledExactlyOnceWith( - "invalid release workflow blob", - "notice", - ); - expect(api.artifacts).not.toHaveBeenCalled(); - - report.mockClear(); - api.workflowBlob.mockResolvedValue(blob); - expect( - await canReuseVerify( - api, - repository, - tree, - workflowBlob, - Date.now(), - report, - ), - ).toBe(false); - expect(report).toHaveBeenCalledExactlyOnceWith( - "invalid verify workflow blob", + "invalid run head tree", "notice", ); expect(api.download).not.toHaveBeenCalled(); }, ); -test("reports a contents API error as a warning before downloading proof", async () => { +test("reports a commit tree API error as a warning before downloading proof", async () => { const { api } = fixture(); const report = vi.fn(); - api.workflowBlob.mockRejectedValue(new TypeError("private diagnostic")); - expect( - await canReuseVerify( - api, - repository, - tree, - workflowBlob, - Date.now(), - report, - ), - ).toBe(false); + api.commitTree.mockRejectedValue(new TypeError("private diagnostic")); + expect(await canReuseVerify(api, repository, tree, Date.now(), report)).toBe( + false, + ); expect(report).toHaveBeenCalledExactlyOnceWith( - "API workflow blob lookup failed (TypeError)", + "API commit tree lookup failed (TypeError)", "warning", ); expect(api.download).not.toHaveBeenCalled(); }); -test("looks up the Verify workflow blob at the run head SHA using the contents API", async () => { - const fetch = vi.fn(async () => Response.json({ sha: workflowBlob })); +test("looks up the run head commit tree using the Git commits API", async () => { + const fetch = vi.fn(async () => Response.json({ tree: { sha: tree } })); vi.stubGlobal("fetch", fetch); expect( await githubProofApi( repository, "fixture-token", "https://fixture.invalid", - ).workflowBlob(commit), - ).toBe(workflowBlob); + ).commitTree(commit), + ).toBe(tree); expect(fetch).toHaveBeenCalledExactlyOnceWith( - `https://fixture.invalid/repos/${repository}/contents/.github/workflows/verify.yml?ref=${commit}`, + `https://fixture.invalid/repos/${repository}/git/commits/${commit}`, expect.any(Object), ); }); @@ -187,7 +148,7 @@ test.each([ ])("rejects unusable artifact %j", async (override) => { const { api, artifact } = fixture(); api.artifacts.mockResolvedValue([{ ...artifact, ...override }]); - expect(await canReuseVerify(api, repository, tree, workflowBlob)).toBe(false); + expect(await canReuseVerify(api, repository, tree)).toBe(false); }); test.each([ @@ -202,26 +163,17 @@ test.each([ ])("parses proof strictly as data and rejects %s", async (body) => { const { api } = fixture(); api.download.mockResolvedValue(body); - expect(await canReuseVerify(api, repository, tree, workflowBlob)).toBe(false); + expect(await canReuseVerify(api, repository, tree)).toBe(false); }); test("missing proof, invalid expected SHA and API/archive errors fall back", async () => { const { api } = fixture(); - expect(await canReuseVerify(api, repository, "invalid", workflowBlob)).toBe( - false, - ); + expect(await canReuseVerify(api, repository, "invalid")).toBe(false); api.artifacts.mockResolvedValueOnce([]); - expect(await canReuseVerify(api, repository, tree, workflowBlob)).toBe(false); - for (const method of [ - api.artifacts, - api.run, - api.workflowBlob, - api.download, - ]) { + expect(await canReuseVerify(api, repository, tree)).toBe(false); + for (const method of [api.artifacts, api.run, api.commitTree, api.download]) { method.mockRejectedValueOnce(new Error("unavailable")); - expect(await canReuseVerify(api, repository, tree, workflowBlob)).toBe( - false, - ); + expect(await canReuseVerify(api, repository, tree)).toBe(false); } }); @@ -230,7 +182,7 @@ test("paginates named artifacts until a valid proof is found", async () => { api.artifacts.mockResolvedValueOnce( Array.from({ length: 100 }, () => ({ ...artifact, expired: true })), ); - expect(await canReuseVerify(api, repository, tree, workflowBlob)).toBe(true); + expect(await canReuseVerify(api, repository, tree)).toBe(true); expect(api.artifacts).toHaveBeenLastCalledWith(`verify-proof-${tree}`, 2); }); @@ -270,16 +222,9 @@ test.each([ ); break; } - expect( - await canReuseVerify( - api, - repository, - tree, - workflowBlob, - Date.now(), - report, - ), - ).toBe(false); + expect(await canReuseVerify(api, repository, tree, Date.now(), report)).toBe( + false, + ); expect(report).toHaveBeenCalledExactlyOnceWith(reason, "notice"); }); @@ -287,16 +232,9 @@ test("reports API errors by class without exposing the error message", async () const { api } = fixture(); const report = vi.fn(); api.artifacts.mockRejectedValue(new TypeError("private diagnostic")); - expect( - await canReuseVerify( - api, - repository, - tree, - workflowBlob, - Date.now(), - report, - ), - ).toBe(false); + expect(await canReuseVerify(api, repository, tree, Date.now(), report)).toBe( + false, + ); expect(report).toHaveBeenCalledExactlyOnceWith( "API artifact lookup failed (TypeError)", "warning", @@ -319,7 +257,7 @@ test.each([401, 403, 404])( ? { artifacts: [artifact] } : calls === 2 ? run - : { sha: workflowBlob }, + : { tree: { sha: tree } }, ); }), ); @@ -333,7 +271,6 @@ test.each([401, 403, 404])( ), repository, tree, - workflowBlob, Date.now(), report, ), @@ -360,7 +297,7 @@ test.each([ .fn() .mockResolvedValueOnce(Response.json({ artifacts: [artifact] })) .mockResolvedValueOnce(Response.json(run)) - .mockResolvedValueOnce(Response.json({ sha: workflowBlob })) + .mockResolvedValueOnce(Response.json({ tree: { sha: tree } })) .mockResolvedValueOnce(new Response("fixture archive")), ); vi.mocked(execFileSync).mockImplementation(() => { @@ -372,7 +309,6 @@ test.each([ githubProofApi(repository, "fixture-token", "https://fixture.invalid"), repository, tree, - workflowBlob, Date.now(), report, ), diff --git a/scripts/verify-proof.ts b/scripts/verify-proof.ts index 3f59d67..993b580 100644 --- a/scripts/verify-proof.ts +++ b/scripts/verify-proof.ts @@ -20,7 +20,7 @@ type Run = { export type ProofApi = { artifacts: (name: string, page: number) => Promise; run: (id: number) => Promise; - workflowBlob: (ref: string) => Promise; + commitTree: (sha: string) => Promise; download: (id: number) => Promise; }; const sha = /^[0-9a-f]{40}$/; @@ -39,7 +39,6 @@ export async function canReuseVerify( api: ProofApi, repository: string, tree: string, - workflowBlob: string, now = Date.now(), report: Report = () => {}, ): Promise { @@ -51,8 +50,6 @@ export async function canReuseVerify( let operation = "API artifact lookup"; try { if (!sha.test(tree)) return fallback("invalid release tree"); - if (!sha.test(workflowBlob)) - return fallback("invalid release workflow blob"); const name = `verify-proof-${tree}`; for (let page = 1; ; page++) { operation = "API artifact lookup"; @@ -91,14 +88,18 @@ export async function canReuseVerify( reason = "invalid run head SHA"; continue; } - operation = "API workflow blob lookup"; - const runWorkflowBlob = await api.workflowBlob(run.head_sha); - if (!sha.test(runWorkflowBlob)) { - reason = "invalid verify workflow blob"; + // Artifacts are only an index: any job in a run can forge their claims. + // GitHub binds the run head to its tree, whose verify.sh/verify.yml ran. + // PR merge refs add only trusted main changes. Cheating code must come + // from this tree, which a fallback verify would also execute. + operation = "API commit tree lookup"; + const runHeadTree = await api.commitTree(run.head_sha); + if (!sha.test(runHeadTree)) { + reason = "invalid run head tree"; continue; } - if (runWorkflowBlob !== workflowBlob) { - reason = "verify workflow differs from release"; + if (runHeadTree !== tree) { + reason = "run head tree differs from release"; continue; } operation = "artifact download"; @@ -170,11 +171,9 @@ export function githubProofApi( async run(id) { return (await request(`/actions/runs/${id}`)).json(); }, - async workflowBlob(ref) { - const response = await request( - `/contents/.github/workflows/verify.yml?ref=${encodeURIComponent(ref)}`, - ); - return (await response.json()).sha; + async commitTree(sha) { + const response = await request(`/git/commits/${encodeURIComponent(sha)}`); + return (await response.json()).tree.sha; }, async download(id) { const response = await request(`/actions/artifacts/${id}/zip`); @@ -214,11 +213,6 @@ if (import.meta.main) { ["rev-parse", `${process.env.GITHUB_SHA}^{tree}`], { encoding: "utf8", timeout: 5_000 }, ).trim(); - const workflowBlob = execFileSync( - "git", - ["rev-parse", `${process.env.GITHUB_SHA}:.github/workflows/verify.yml`], - { encoding: "utf8", timeout: 5_000 }, - ).trim(); const repository = process.env.GITHUB_REPOSITORY; const token = process.env.GH_TOKEN; if (repository && token) @@ -226,17 +220,13 @@ if (import.meta.main) { githubProofApi(repository, token, process.env.GITHUB_API_URL), repository, tree, - workflowBlob, Date.now(), report, ); else report("missing GitHub repository or token", "warning"); } catch (error) { // Checkout or git failures also fall back to the existing workflow. - report( - `checkout tree or workflow lookup failed (${errorClass(error)})`, - "warning", - ); + report(`checkout tree lookup failed (${errorClass(error)})`, "warning"); } if (reuse) console.log("Reusing successful Verify tree proof."); if (process.env.GITHUB_OUTPUT) From 4ffc2cce38fcfcc65e0a46f465d71f92d11640e6 Mon Sep 17 00:00:00 2001 From: beasty Date: Fri, 23 Oct 2026 02:58:40 +0200 Subject: [PATCH 6/9] refactor(ci): split proof and rollout checks to satisfy the quality gate --- scripts/rollout-smoke.test.ts | 28 +++++ scripts/rollout-smoke.ts | 192 +++++++++++++++++++--------------- scripts/verify-proof.test.ts | 56 +++++++++- scripts/verify-proof.ts | 180 ++++++++++++++++--------------- 4 files changed, 287 insertions(+), 169 deletions(-) diff --git a/scripts/rollout-smoke.test.ts b/scripts/rollout-smoke.test.ts index 84813b8..7ad6961 100644 --- a/scripts/rollout-smoke.test.ts +++ b/scripts/rollout-smoke.test.ts @@ -202,3 +202,31 @@ test("invalid versions and deadlines fail before any request", async () => { ).rejects.toThrow("durations"); expect(request).not.toHaveBeenCalled(); }); + +test.each([ + "1.0.0+", + "1.0.0+build..1", + "1.0.0+build+1", + "1.0.0+build_1", + "1.0.0-", + "1.0.0-alpha..1", + "1.0.0-alpha_1", + "1.0.0-01+build", + "01.0.0", + "1.0.0\n", + "1.0.0-alpha\n", +])("rejects semver identifier boundary case %s", (version) => { + expect(() => compareVersions(version, "1.0.0")).toThrow( + `Invalid semver: ${version}`, + ); +}); + +test.each([ + ["1.0.0+001", "1.0.0", 0], + ["1.0.0-alpha-beta+build-1.001", "1.0.0-alpha-beta", 0], + ["1.0.0-alpha.0", "1.0.0-alpha.1", -1], + ["1.0.0-alpha.1", "1.0.0-alpha", 1], + ["1.0.0-alpha", "1.0.0-beta", -1], +] as const)("preserves semver ordering for %s and %s", (a, b, order) => { + expect(compareVersions(a, b)).toBe(order); +}); diff --git a/scripts/rollout-smoke.ts b/scripts/rollout-smoke.ts index 8f7c8ac..b230559 100644 --- a/scripts/rollout-smoke.ts +++ b/scripts/rollout-smoke.ts @@ -1,38 +1,66 @@ import { setTimeout as sleep } from "node:timers/promises"; function semver(version: string) { - const match = - /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?(?:\+[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?$/.exec( - version, - ); + const buildAt = version.indexOf("+"); + const withoutBuild = buildAt < 0 ? version : version.slice(0, buildAt); + if ( + buildAt >= 0 && + !/^[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*$/.test(version.slice(buildAt + 1)) + ) + throw new Error(`Invalid semver: ${version}`); + const prereleaseAt = withoutBuild.indexOf("-"); + const core = + prereleaseAt < 0 ? withoutBuild : withoutBuild.slice(0, prereleaseAt); + const prerelease = + prereleaseAt < 0 ? [] : withoutBuild.slice(prereleaseAt + 1).split("."); + const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(core); if (!match) throw new Error(`Invalid semver: ${version}`); - const prerelease = match[4]?.split(".") ?? []; - if (prerelease.some((part) => /^\d+$/.test(part) && /^0\d/.test(part))) + if (prerelease.some((part) => !validPrereleaseIdentifier(part))) throw new Error(`Invalid semver: ${version}`); return { core: match.slice(1, 4).map(BigInt), prerelease }; } +function validPrereleaseIdentifier(part: string) { + return ( + /^[0-9A-Za-z-]+$/.test(part) && !(/^\d+$/.test(part) && /^0\d/.test(part)) + ); +} + +function compareIdentifiers(x: string, y: string): number { + if (x === y) return 0; + const numericX = /^\d+$/.test(x); + const numericY = /^\d+$/.test(y); + if (numericX && numericY) return BigInt(x) > BigInt(y) ? 1 : -1; + if (numericX !== numericY) return numericX ? -1 : 1; + return x > y ? 1 : -1; +} + +function comparePrerelease(a: string[], b: string[]): number { + if (!a.length || !b.length) return Number(!a.length) - Number(!b.length); + for (let i = 0; i < Math.max(a.length, b.length); i++) { + const x = a[i]; + const y = b[i]; + if (x === undefined) return -1; + if (y === undefined) return 1; + const order = compareIdentifiers(x, y); + if (order) return order; + } + return 0; +} + export function compareVersions(left: string, right: string): number { const a = semver(left); const b = semver(right); for (let i = 0; i < 3; i++) { if (a.core[i] !== b.core[i]) return a.core[i] > b.core[i] ? 1 : -1; } - if (!a.prerelease.length || !b.prerelease.length) - return Number(!a.prerelease.length) - Number(!b.prerelease.length); - for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i++) { - const x = a.prerelease[i]; - const y = b.prerelease[i]; - if (x === undefined) return -1; - if (y === undefined) return 1; - if (x === y) continue; - const numericX = /^\d+$/.test(x); - const numericY = /^\d+$/.test(y); - if (numericX && numericY) return BigInt(x) > BigInt(y) ? 1 : -1; - if (numericX !== numericY) return numericX ? -1 : 1; - return x > y ? 1 : -1; - } - return 0; + return comparePrerelease(a.prerelease, b.prerelease); +} + +function findNewer(releases: (string | null)[], version: string) { + return releases.find( + (release) => release && compareVersions(release.slice(8), version) > 0, + ); } type SmokeOptions = { @@ -82,39 +110,70 @@ export async function rolloutSmoke(options: SmokeOptions) { const remaining = end - now(); if (remaining > 0) await pause(Math.min(pollMs, remaining)); }; - while (now() < deadline) { - // Inspect both responses before health checks, so a newer component wins - // even when the other component is still rolling out or unavailable. - const releases = await Promise.all( - paths.map(async (path) => { + async function readRelease(path: string) { + try { + const response = await get(path); + if (!response.ok) { + last.set(path, `HTTP ${response.status}`); + return null; + } + const body: unknown = await response.json(); + if ( + !body || + typeof body !== "object" || + !("release" in body) || + typeof body.release !== "string" || + !body.release.startsWith("moddrop@") + ) + throw new Error("missing release"); + const release = body.release; + semver(release.slice("moddrop@".length)); + last.set(path, release); + return release; + } catch { + last.set(path, "network error, invalid JSON or invalid release"); + return null; + } + } + async function checkHealth(readyDeadline: number) { + let homeOk = false; + let home = "not checked"; + let ready = "not checked"; + while (now() < readyDeadline) { + if (!homeOk) { try { - const response = await get(path); - if (!response.ok) { - last.set(path, `HTTP ${response.status}`); - return null; - } - const body: unknown = await response.json(); - if ( - !body || - typeof body !== "object" || - !("release" in body) || - typeof body.release !== "string" || - !body.release.startsWith("moddrop@") - ) - throw new Error("missing release"); - const release = body.release; - semver(release.slice("moddrop@".length)); - last.set(path, release); - return release; + const response = await get("/", readyDeadline); + home = `HTTP ${response.status}`; + homeOk = response.ok; } catch { - last.set(path, "network error, invalid JSON or invalid release"); - return null; + home = "network error"; } - }), - ); - const newer = releases.find( - (release) => release && compareVersions(release.slice(8), version) > 0, + if (!homeOk) { + await wait(readyDeadline); + continue; + } + } + try { + const response = await get("/canvas-api/ready", readyDeadline); + ready = `HTTP ${response.status}`; + if (response.status === 200) { + log(`Rollout healthy: both components report ${expected}.`); + return "healthy"; + } + } catch { + ready = "network error"; + } + await wait(readyDeadline); + } + throw new Error( + `Readiness timed out: /: ${home}; /canvas-api/ready: ${ready}; ${JSON.stringify(Object.fromEntries(last))}`, ); + } + while (now() < deadline) { + // Inspect both responses before health checks, so a newer component wins + // even when the other component is still rolling out or unavailable. + const releases = await Promise.all(paths.map(readRelease)); + const newer = findNewer(releases, version); if (newer) { log( `::notice::Rollout superseded: expected ${expected}, observed ${newer}. Skipping remaining checks.`, @@ -125,38 +184,7 @@ export async function rolloutSmoke(options: SmokeOptions) { if (releases.every((release) => release === expected)) { if (now() >= deadline) throw timedOut(); const readyDeadline = Math.min(deadline, now() + readyTimeoutMs); - let homeOk = false; - let home = "not checked"; - let ready = "not checked"; - while (now() < readyDeadline) { - if (!homeOk) { - try { - const response = await get("/", readyDeadline); - home = `HTTP ${response.status}`; - homeOk = response.ok; - } catch { - home = "network error"; - } - if (!homeOk) { - await wait(readyDeadline); - continue; - } - } - try { - const response = await get("/canvas-api/ready", readyDeadline); - ready = `HTTP ${response.status}`; - if (response.status === 200) { - log(`Rollout healthy: both components report ${expected}.`); - return "healthy"; - } - } catch { - ready = "network error"; - } - await wait(readyDeadline); - } - throw new Error( - `Readiness timed out: /: ${home}; /canvas-api/ready: ${ready}; ${JSON.stringify(Object.fromEntries(last))}`, - ); + return checkHealth(readyDeadline); } await wait(deadline); } diff --git a/scripts/verify-proof.test.ts b/scripts/verify-proof.test.ts index 3341ac8..860883b 100644 --- a/scripts/verify-proof.test.ts +++ b/scripts/verify-proof.test.ts @@ -315,8 +315,62 @@ test.each([ ).toBe(false); expect(report).toHaveBeenCalledExactlyOnceWith(reason, "warning"); expect(execFileSync).toHaveBeenCalledWith( - "unzip", + "/usr/bin/unzip", ["-p", expect.any(String), "verify-proof.json"], expect.objectContaining({ stdio: ["ignore", "pipe", "ignore"] }), ); }); + +test("expiry at the current time takes precedence over a missing workflow run", async () => { + const { api, artifact } = fixture(); + const report = vi.fn(); + artifact.workflow_run = undefined; + expect( + await canReuseVerify( + api, + repository, + tree, + Date.parse(artifact.expires_at), + report, + ), + ).toBe(false); + expect(report).toHaveBeenCalledExactlyOnceWith( + "artifact expired or invalid expiry", + "notice", + ); + expect(api.run).not.toHaveBeenCalled(); +}); + +test("the last rejection wins across pages and unrelated names do not replace it", async () => { + const { api, artifact, run } = fixture(); + const report = vi.fn(); + run.path = "wrong workflow"; + run.status = "in_progress"; + run.head_sha = "invalid"; + api.artifacts + .mockResolvedValueOnce(Array.from({ length: 100 }, () => artifact)) + .mockResolvedValueOnce([ + { ...artifact, workflow_run: undefined }, + { ...artifact, name: "unrelated", expired: true }, + ]); + expect(await canReuseVerify(api, repository, tree, Date.now(), report)).toBe( + false, + ); + expect(report).toHaveBeenCalledExactlyOnceWith( + "artifact has no workflow run", + "notice", + ); + expect(api.commitTree).not.toHaveBeenCalled(); +}); + +test("a valid different proof tree takes precedence over a malformed commit", async () => { + const { api } = fixture(); + const report = vi.fn(); + api.download.mockResolvedValue( + JSON.stringify({ tree: "c".repeat(40), commit: "invalid" }), + ); + expect(await canReuseVerify(api, repository, tree, Date.now(), report)).toBe( + false, + ); + expect(report).toHaveBeenCalledExactlyOnceWith("tree mismatch", "notice"); +}); diff --git a/scripts/verify-proof.ts b/scripts/verify-proof.ts index 993b580..42c1e59 100644 --- a/scripts/verify-proof.ts +++ b/scripts/verify-proof.ts @@ -35,6 +35,62 @@ function errorClass(error: unknown) { return error instanceof Error ? "Error" : "unknown error"; } +function artifactProblem(artifact: Artifact, now: number): string | null { + if (artifact.expired) return "artifact expired or invalid expiry"; + const expires = Date.parse(artifact.expires_at); + if (!Number.isFinite(expires) || expires <= now) + return "artifact expired or invalid expiry"; + return null; +} + +function runProblem(run: Run, repository: string): string | null { + if (run.path !== ".github/workflows/verify.yml") return "wrong workflow path"; + if (run.status !== "completed" || run.conclusion !== "success") + return "run not successful/completed"; + if (run.head_repository?.full_name !== repository) + return "foreign head repository"; + if (!sha.test(run.head_sha)) return "invalid run head SHA"; + return null; +} + +function runTreeProblem(runHeadTree: string, tree: string): string | null { + if (!sha.test(runHeadTree)) return "invalid run head tree"; + if (runHeadTree !== tree) return "run head tree differs from release"; + return null; +} + +function proofProblem(proof: unknown, tree: string): string | null { + if ( + proof === null || + typeof proof !== "object" || + !("tree" in proof) || + typeof proof.tree !== "string" || + !sha.test(proof.tree) + ) + return "malformed proof"; + if (proof.tree !== tree) return "tree mismatch"; + if ( + !("commit" in proof) || + typeof proof.commit !== "string" || + !sha.test(proof.commit) + ) + return "malformed proof"; + return null; +} + +function lookupFailure( + error: unknown, + operation: string, +): [string, "notice" | "warning"] { + if (operation === "proof parsing") return ["malformed proof", "notice"]; + return [ + error instanceof ProofLookupError + ? error.message + : `${operation} failed (${errorClass(error)})`, + "warning", + ]; +} + export async function canReuseVerify( api: ProofApi, repository: string, @@ -48,6 +104,28 @@ export async function canReuseVerify( }; let reason = "no artifact named for this tree"; let operation = "API artifact lookup"; + async function checkArtifact(artifact: Artifact): Promise { + const artifactReason = artifactProblem(artifact, now); + if (artifactReason) return artifactReason; + if (!artifact.workflow_run) return "artifact has no workflow run"; + operation = "API run lookup"; + const run = await api.run(artifact.workflow_run.id); + const runReason = runProblem(run, repository); + if (runReason) return runReason; + // Artifacts are only an index: any job in a run can forge their claims. + // GitHub binds the run head to its tree, whose verify.sh/verify.yml ran. + // PR merge refs add only trusted main changes. Cheating code must come + // from this tree, which a fallback verify would also execute. + operation = "API commit tree lookup"; + const runHeadTree = await api.commitTree(run.head_sha); + const treeReason = runTreeProblem(runHeadTree, tree); + if (treeReason) return treeReason; + operation = "artifact download"; + const contents = await api.download(artifact.id); + operation = "proof parsing"; + const proof: unknown = JSON.parse(contents); + return proofProblem(proof, tree); + } try { if (!sha.test(tree)) return fallback("invalid release tree"); const name = `verify-proof-${tree}`; @@ -55,90 +133,16 @@ export async function canReuseVerify( operation = "API artifact lookup"; const artifacts = await api.artifacts(name, page); for (const artifact of artifacts) { - if ( - artifact.name !== name || - artifact.expired || - !(Date.parse(artifact.expires_at) > now) || - !artifact.workflow_run - ) { - if (artifact.name === name) - reason = - artifact.expired || !(Date.parse(artifact.expires_at) > now) - ? "artifact expired or invalid expiry" - : "artifact has no workflow run"; - continue; - } - operation = "API run lookup"; - const run = await api.run(artifact.workflow_run.id); - if ( - run.path !== ".github/workflows/verify.yml" || - run.status !== "completed" || - run.conclusion !== "success" || - run.head_repository?.full_name !== repository - ) { - reason = - run.path !== ".github/workflows/verify.yml" - ? "wrong workflow path" - : run.status !== "completed" || run.conclusion !== "success" - ? "run not successful/completed" - : "foreign head repository"; - continue; - } - if (!sha.test(run.head_sha)) { - reason = "invalid run head SHA"; - continue; - } - // Artifacts are only an index: any job in a run can forge their claims. - // GitHub binds the run head to its tree, whose verify.sh/verify.yml ran. - // PR merge refs add only trusted main changes. Cheating code must come - // from this tree, which a fallback verify would also execute. - operation = "API commit tree lookup"; - const runHeadTree = await api.commitTree(run.head_sha); - if (!sha.test(runHeadTree)) { - reason = "invalid run head tree"; - continue; - } - if (runHeadTree !== tree) { - reason = "run head tree differs from release"; - continue; - } - operation = "artifact download"; - const contents = await api.download(artifact.id); - operation = "proof parsing"; - const proof: unknown = JSON.parse(contents); - if ( - proof !== null && - typeof proof === "object" && - "tree" in proof && - typeof proof.tree === "string" && - sha.test(proof.tree) && - proof.tree === tree && - "commit" in proof && - typeof proof.commit === "string" && - sha.test(proof.commit) - ) - return true; - reason = - proof !== null && - typeof proof === "object" && - "tree" in proof && - typeof proof.tree === "string" && - sha.test(proof.tree) && - proof.tree !== tree - ? "tree mismatch" - : "malformed proof"; + if (artifact.name !== name) continue; + const problem = await checkArtifact(artifact); + if (problem === null) return true; + reason = problem; } if (artifacts.length < 100) return fallback(reason); } } catch (error) { // An unavailable API, invalid archive or malformed proof requires full verify. - if (operation === "proof parsing") return fallback("malformed proof"); - return fallback( - error instanceof ProofLookupError - ? error.message - : `${operation} failed (${errorClass(error)})`, - "warning", - ); + return fallback(...lookupFailure(error, operation)); } } @@ -183,12 +187,16 @@ export function githubProofApi( writeFileSync(archive, Buffer.from(await response.arrayBuffer())); // Read one fixed member as data. Never extract paths or execute archive contents. try { - return execFileSync("unzip", ["-p", archive, "verify-proof.json"], { - encoding: "utf8", - timeout: 5_000, - maxBuffer: 16_384, - stdio: ["ignore", "pipe", "ignore"], - }); + return execFileSync( + "/usr/bin/unzip", + ["-p", archive, "verify-proof.json"], + { + encoding: "utf8", + timeout: 5_000, + maxBuffer: 16_384, + stdio: ["ignore", "pipe", "ignore"], + }, + ); } catch (error) { throw new ProofLookupError( error instanceof Error && "code" in error && error.code === "ENOENT" @@ -209,7 +217,7 @@ if (import.meta.main) { console.log(`::${level}::Full Verify required: ${reason}.`); try { const tree = execFileSync( - "git", + "/usr/bin/git", ["rev-parse", `${process.env.GITHUB_SHA}^{tree}`], { encoding: "utf8", timeout: 5_000 }, ).trim(); From 38f6ad0a68bec90fa3adc4cd9db36d718a839796 Mon Sep 17 00:00:00 2001 From: beasty Date: Fri, 23 Oct 2026 03:03:24 +0200 Subject: [PATCH 7/9] fix(ci): recheck supersession during readiness and make proof best-effort --- .github/workflows/verify.yml | 1 + docs/releasing.md | 3 +- scripts/delivery-changes.test.ts | 100 +++++++++++++++---------------- scripts/rollout-smoke.test.ts | 72 ++++++++++++++++++++-- scripts/rollout-smoke.ts | 58 +++++++++++------- 5 files changed, 154 insertions(+), 80 deletions(-) diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 150f608..ab2d5f1 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -41,6 +41,7 @@ jobs: - run: bash scripts/verify.sh proof: needs: verify + continue-on-error: true runs-on: arc-moddrop steps: - uses: actions/checkout@v7 diff --git a/docs/releasing.md b/docs/releasing.md index 5562692..9927a6d 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -2,7 +2,8 @@ Pushing a `vX.Y.Z` tag runs the GitHub container-image workflow. After the full suite passes, a separate job that runs no repository code records the checked-out -commit and tree in a JSON proof artifact retained for 14 days. +commit and tree in a JSON proof artifact retained for 14 days. Recording is +best-effort; failure only means the next release runs full Verify. The release gate reuses proof only for the exact release tree from a completed, successful Verify run in this repository. Proof is reused only when GitHub's record of the Verify run's head commit has the release tree. diff --git a/scripts/delivery-changes.test.ts b/scripts/delivery-changes.test.ts index bd320de..62dda7d 100644 --- a/scripts/delivery-changes.test.ts +++ b/scripts/delivery-changes.test.ts @@ -37,6 +37,7 @@ test("GitHub releases use the PR verification gate before production actions", ( expect(verification.permissions).toEqual({ contents: "read" }); expect(verification.jobs.proof).toEqual({ needs: "verify", // Default success() requires the full suite to pass. + "continue-on-error": true, "runs-on": "arc-moddrop", steps: [ { @@ -63,60 +64,55 @@ test("GitHub releases use the PR verification gate before production actions", ( }); const results = ["success", "failure", "cancelled", "skipped"]; + function checkVerification(gate: string, reuse: string, verify: string) { + for (const cancelled of [true, false]) + for (const ref of [ + "refs/heads/feature", + "refs/heads/main", + "refs/tags/v0.6.2", + "refs/tags/other", + "refs/pull/1/merge", + ]) { + const needs = { + gate: { result: gate, outputs: { reuse } }, + verify: { result: verify }, + }; + const evaluate = (condition: string, dependencies: object = needs) => + Function( + "needs", + "github", + "cancelled", + "always", + "startsWith", + `return (${condition});`, + )( + dependencies, + { ref }, + () => cancelled, + () => true, + (value: string, prefix: string) => value.startsWith(prefix), + ); + expect(evaluate(workflow.jobs.gate.if)).toBe(!cancelled); + expect(evaluate(workflow.jobs.verify.if)).toBe( + !cancelled && (gate !== "success" || reuse !== "true"), + ); + const safe = + !cancelled && + (ref === "refs/heads/main" || ref.startsWith("refs/tags/v")) && + (verify === "success" || + (gate === "success" && reuse === "true" && verify === "skipped")); + expect(evaluate(job.if)).toBe(safe); + for (const build of results) + expect( + evaluate(workflow.jobs.smoke.if, { build: { result: build } }), + ).toBe( + !cancelled && build === "success" && ref.startsWith("refs/tags/v"), + ); + } + } for (const gate of results) for (const reuse of ["true", "false", ""]) - for (const verify of results) - for (const cancelled of [true, false]) - for (const ref of [ - "refs/heads/feature", - "refs/heads/main", - "refs/tags/v0.6.2", - "refs/tags/other", - "refs/pull/1/merge", - ]) { - const needs = { - gate: { result: gate, outputs: { reuse } }, - verify: { result: verify }, - }; - const evaluate = ( - condition: string, - dependencies: object = needs, - ) => - Function( - "needs", - "github", - "cancelled", - "always", - "startsWith", - `return (${condition});`, - )( - dependencies, - { ref }, - () => cancelled, - () => true, - (value: string, prefix: string) => value.startsWith(prefix), - ); - expect(evaluate(workflow.jobs.gate.if)).toBe(!cancelled); - expect(evaluate(workflow.jobs.verify.if)).toBe( - !cancelled && (gate !== "success" || reuse !== "true"), - ); - const safe = - !cancelled && - (ref === "refs/heads/main" || ref.startsWith("refs/tags/v")) && - (verify === "success" || - (gate === "success" && - reuse === "true" && - verify === "skipped")); - expect(evaluate(job.if)).toBe(safe); - for (const build of results) - expect( - evaluate(workflow.jobs.smoke.if, { build: { result: build } }), - ).toBe( - !cancelled && - build === "success" && - ref.startsWith("refs/tags/v"), - ); - } + for (const verify of results) checkVerification(gate, reuse, verify); }); test.each(["pnpm-lock.yaml", "pnpm-workspace.yaml", "package.json", ".npmrc"])( diff --git a/scripts/rollout-smoke.test.ts b/scripts/rollout-smoke.test.ts index 7ad6961..7934812 100644 --- a/scripts/rollout-smoke.test.ts +++ b/scripts/rollout-smoke.test.ts @@ -67,9 +67,11 @@ test.each([ const paths = request.mock.calls.map( ([url]) => new URL(String(url)).pathname, ); - expect(paths.slice(-3)).toEqual([ + expect(paths.slice(-5)).toEqual([ "/", "/canvas-api/ready", + "/telemetry-config", + "/canvas-api/version", "/canvas-api/ready", ]); expect( @@ -95,6 +97,54 @@ test.each([ }, ); +test.each([ + [[expected, newer], [expected]], + [[expected], [expected, newer]], +] satisfies [Reply[], Reply[]][])( + "newer component supersedes a readiness retry: %j / %j", + async (frontend, backend) => { + const { options, request, log } = fixture(frontend, backend, [503, 200]); + expect(await rolloutSmoke(options)).toBe("superseded"); + expect( + request.mock.calls.map(([url]) => new URL(String(url)).pathname), + ).toEqual([ + "/telemetry-config", + "/canvas-api/version", + "/", + "/canvas-api/ready", + "/telemetry-config", + "/canvas-api/version", + ]); + expect(log).toHaveBeenCalledWith( + `::notice::Rollout superseded: expected ${expected}, observed ${newer}. Skipping remaining checks.`, + ); + }, +); + +test.each([ + [[expected, newer], [expected]], + [[expected], [expected, newer]], +] satisfies [Reply[], Reply[]][])( + "newer component supersedes a homepage retry: %j / %j", + async (frontend, backend) => { + const { options, queues, request, log } = fixture(frontend, backend); + queues["/"] = [502, 200]; + expect(await rolloutSmoke(options)).toBe("superseded"); + expect( + request.mock.calls.map(([url]) => new URL(String(url)).pathname), + ).toEqual([ + "/telemetry-config", + "/canvas-api/version", + "/", + "/telemetry-config", + "/canvas-api/version", + ]); + expect(log).toHaveBeenCalledWith( + `::notice::Rollout superseded: expected ${expected}, observed ${newer}. Skipping remaining checks.`, + ); + }, +); + test("timeout includes the last observation from each endpoint", async () => { const { options, request } = fixture([old], [404]); await expect(rolloutSmoke(options)).rejects.toThrow( @@ -143,7 +193,7 @@ test.each([ ); expect( request.mock.calls.slice(2).map(([url]) => new URL(String(url)).pathname), - ).toEqual(["/", "/"]); + ).toEqual(["/", "/telemetry-config", "/canvas-api/version", "/"]); expect(options.now()).toBe(40); }, ); @@ -156,7 +206,13 @@ test.each([502, new Error("offline")])( expect(await rolloutSmoke(options)).toBe("healthy"); expect( request.mock.calls.slice(2).map(([url]) => new URL(String(url)).pathname), - ).toEqual(["/", "/", "/canvas-api/ready"]); + ).toEqual([ + "/", + "/telemetry-config", + "/canvas-api/version", + "/", + "/canvas-api/ready", + ]); }, ); @@ -165,7 +221,7 @@ test("readiness retries are bounded by the short window and overall deadline", a await expect(rolloutSmoke({ ...options, timeoutMs: 30 })).rejects.toThrow( "Readiness timed out: /: HTTP 200; /canvas-api/ready: HTTP 503", ); - expect(request).toHaveBeenCalledTimes(5); + expect(request).toHaveBeenCalledTimes(7); }); test("homepage retries share the readiness window and overall deadline", async () => { @@ -177,7 +233,13 @@ test("homepage retries share the readiness window and overall deadline", async ( expect(options.now()).toBe(30); expect( request.mock.calls.slice(2).map(([url]) => new URL(String(url)).pathname), - ).toEqual(["/", "/", "/canvas-api/ready"]); + ).toEqual([ + "/", + "/telemetry-config", + "/canvas-api/version", + "/", + "/canvas-api/ready", + ]); }); test.each([ diff --git a/scripts/rollout-smoke.ts b/scripts/rollout-smoke.ts index b230559..5894e92 100644 --- a/scripts/rollout-smoke.ts +++ b/scripts/rollout-smoke.ts @@ -135,33 +135,52 @@ export async function rolloutSmoke(options: SmokeOptions) { return null; } } + function superseded(newer: string) { + log( + `::notice::Rollout superseded: expected ${expected}, observed ${newer}. Skipping remaining checks.`, + ); + return "superseded"; + } + async function readHealth(path: string, end: number) { + try { + const response = await get(path, end); + return { + ok: response.ok, + status: response.status, + observation: `HTTP ${response.status}`, + }; + } catch { + return { ok: false, status: 0, observation: "network error" }; + } + } async function checkHealth(readyDeadline: number) { let homeOk = false; let home = "not checked"; let ready = "not checked"; + let retry = false; while (now() < readyDeadline) { + if (retry) { + const newer = findNewer( + await Promise.all(paths.map(readRelease)), + version, + ); + if (newer) return superseded(newer); + } + retry = true; if (!homeOk) { - try { - const response = await get("/", readyDeadline); - home = `HTTP ${response.status}`; - homeOk = response.ok; - } catch { - home = "network error"; - } + const response = await readHealth("/", readyDeadline); + home = response.observation; + homeOk = response.ok; if (!homeOk) { await wait(readyDeadline); continue; } } - try { - const response = await get("/canvas-api/ready", readyDeadline); - ready = `HTTP ${response.status}`; - if (response.status === 200) { - log(`Rollout healthy: both components report ${expected}.`); - return "healthy"; - } - } catch { - ready = "network error"; + const response = await readHealth("/canvas-api/ready", readyDeadline); + ready = response.observation; + if (response.status === 200) { + log(`Rollout healthy: both components report ${expected}.`); + return "healthy"; } await wait(readyDeadline); } @@ -174,12 +193,7 @@ export async function rolloutSmoke(options: SmokeOptions) { // even when the other component is still rolling out or unavailable. const releases = await Promise.all(paths.map(readRelease)); const newer = findNewer(releases, version); - if (newer) { - log( - `::notice::Rollout superseded: expected ${expected}, observed ${newer}. Skipping remaining checks.`, - ); - return "superseded"; - } + if (newer) return superseded(newer); log(paths.map((path) => `${path}: ${last.get(path)}`).join("; ")); if (releases.every((release) => release === expected)) { if (now() >= deadline) throw timedOut(); From 0c5c68c73cc5510b51ea6e90796dce5ec8d1d1d8 Mon Sep 17 00:00:00 2001 From: beasty Date: Fri, 23 Oct 2026 03:14:36 +0200 Subject: [PATCH 8/9] fix(ci): resume rollout polling when versions drift during readiness --- scripts/rollout-smoke.test.ts | 67 +++++++++++++++++++++++++++++++++++ scripts/rollout-smoke.ts | 17 +++++---- 2 files changed, 78 insertions(+), 6 deletions(-) diff --git a/scripts/rollout-smoke.test.ts b/scripts/rollout-smoke.test.ts index 7934812..400c6f8 100644 --- a/scripts/rollout-smoke.test.ts +++ b/scripts/rollout-smoke.test.ts @@ -97,6 +97,73 @@ test.each([ }, ); +test.each([ + [[expected, old, expected], [expected]], + [[expected], [expected, old, expected]], + [[expected, 404, expected], [expected]], + [[expected], [expected, 404, expected]], + [[expected, new Error("offline"), expected], [expected]], + [[expected], [expected, new Error("offline"), expected]], + [[expected, { malformed: true }, expected], [expected]], + [[expected], [expected, "moddrop@invalid", expected]], +] satisfies [Reply[], Reply[]][])( + "version drift during readiness resumes polling before health checks: %j / %j", + async (frontend, backend) => { + const { options, request } = fixture(frontend, backend, [503, 200]); + expect(await rolloutSmoke(options)).toBe("healthy"); + expect( + request.mock.calls.map(([url]) => new URL(String(url)).pathname), + ).toEqual([ + "/telemetry-config", + "/canvas-api/version", + "/", + "/canvas-api/ready", + "/telemetry-config", + "/canvas-api/version", + "/telemetry-config", + "/canvas-api/version", + "/", + "/canvas-api/ready", + ]); + expect(options.now()).toBe(40); + }, +); + +test("matching versions after drift start a fresh readiness window", async () => { + const { options } = fixture( + [expected, old, expected], + [expected], + [503, 503, 200], + ); + expect(await rolloutSmoke(options)).toBe("healthy"); + expect(options.now()).toBe(60); +}); + +test.each([ + [old, expected, old, expected], + [expected, 404, expected, "HTTP 404"], +] satisfies [Reply, Reply, string, string][])( + "persistent version drift times out with the latest observations: %j / %j", + async (frontend, backend, lastFrontend, lastBackend) => { + const { options, request } = fixture( + [expected, frontend], + [expected, backend], + [503, 200], + ); + await expect(rolloutSmoke(options)).rejects.toThrow( + `Rollout timed out: ${JSON.stringify({ + "/telemetry-config": lastFrontend, + "/canvas-api/version": lastBackend, + })}`, + ); + const healthPaths = request.mock.calls + .map(([url]) => new URL(String(url)).pathname) + .filter((path) => path === "/" || path === "/canvas-api/ready"); + expect(healthPaths).toEqual(["/", "/canvas-api/ready"]); + expect(options.now()).toBe(options.timeoutMs); + }, +); + test.each([ [[expected, newer], [expected]], [[expected], [expected, newer]], diff --git a/scripts/rollout-smoke.ts b/scripts/rollout-smoke.ts index 5894e92..6b9535a 100644 --- a/scripts/rollout-smoke.ts +++ b/scripts/rollout-smoke.ts @@ -153,6 +153,13 @@ export async function rolloutSmoke(options: SmokeOptions) { return { ok: false, status: 0, observation: "network error" }; } } + async function recheckVersions() { + const releases = await Promise.all(paths.map(readRelease)); + const newer = findNewer(releases, version); + if (newer) return superseded(newer); + if (releases.some((release) => release !== expected)) return "pending"; + return null; + } async function checkHealth(readyDeadline: number) { let homeOk = false; let home = "not checked"; @@ -160,11 +167,8 @@ export async function rolloutSmoke(options: SmokeOptions) { let retry = false; while (now() < readyDeadline) { if (retry) { - const newer = findNewer( - await Promise.all(paths.map(readRelease)), - version, - ); - if (newer) return superseded(newer); + const result = await recheckVersions(); + if (result) return result; } retry = true; if (!homeOk) { @@ -198,7 +202,8 @@ export async function rolloutSmoke(options: SmokeOptions) { if (releases.every((release) => release === expected)) { if (now() >= deadline) throw timedOut(); const readyDeadline = Math.min(deadline, now() + readyTimeoutMs); - return checkHealth(readyDeadline); + const result = await checkHealth(readyDeadline); + if (result !== "pending") return result; } await wait(deadline); } From b93769361e21059124d405bd58d50f01c1445012 Mon Sep 17 00:00:00 2001 From: beasty Date: Fri, 23 Oct 2026 03:22:05 +0200 Subject: [PATCH 9/9] fix(ci): accept ref-qualified Verify workflow paths --- scripts/verify-proof.test.ts | 31 +++++++++++++++++++++++++++++++ scripts/verify-proof.ts | 10 +++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/scripts/verify-proof.test.ts b/scripts/verify-proof.test.ts index 860883b..3436724 100644 --- a/scripts/verify-proof.test.ts +++ b/scripts/verify-proof.test.ts @@ -44,6 +44,37 @@ test("accepts matching artifact and run head trees from a successful same-reposi expect(api.download).toHaveBeenCalledWith(1); }); +test.each([ + ".github/workflows/verify.yml@main", + ".github/workflows/verify.yml@refs/pull/19/merge", +])("accepts ref-qualified Verify workflow path %s", async (path) => { + const { api, run } = fixture(); + run.path = path; + expect(await canReuseVerify(api, repository, tree)).toBe(true); + expect(api.commitTree).toHaveBeenCalledWith(commit); + expect(api.download).toHaveBeenCalledWith(1); +}); + +test.each([ + ".github/workflows/verify.yml@", + ".github/workflows/verify.yml.bak", + ".github/workflows/build-images.yml@main", + "x/.github/workflows/verify.yml", +])("rejects invalid Verify workflow path %s", async (path) => { + const { api, run } = fixture(); + const report = vi.fn(); + run.path = path; + expect(await canReuseVerify(api, repository, tree, Date.now(), report)).toBe( + false, + ); + expect(report).toHaveBeenCalledExactlyOnceWith( + "wrong workflow path", + "notice", + ); + expect(api.commitTree).not.toHaveBeenCalled(); + expect(api.download).not.toHaveBeenCalled(); +}); + test.each([ { path: ".github/workflows/build-images.yml" }, { status: "in_progress" }, diff --git a/scripts/verify-proof.ts b/scripts/verify-proof.ts index 42c1e59..a7ed6df 100644 --- a/scripts/verify-proof.ts +++ b/scripts/verify-proof.ts @@ -43,8 +43,16 @@ function artifactProblem(artifact: Artifact, now: number): string | null { return null; } +function isVerifyWorkflow(path: string): boolean { + const workflow = ".github/workflows/verify.yml"; + return ( + path === workflow || + (path.startsWith(`${workflow}@`) && path.length > workflow.length + 1) + ); +} + function runProblem(run: Run, repository: string): string | null { - if (run.path !== ".github/workflows/verify.yml") return "wrong workflow path"; + if (!isVerifyWorkflow(run.path)) return "wrong workflow path"; if (run.status !== "completed" || run.conclusion !== "success") return "run not successful/completed"; if (run.head_repository?.full_name !== repository)