diff --git a/.github/workflows/ci-master.yml b/.github/workflows/ci-master.yml index d8c412576f..de2ac59ae9 100644 --- a/.github/workflows/ci-master.yml +++ b/.github/workflows/ci-master.yml @@ -177,23 +177,9 @@ jobs: - name: Install Playwright Chromium and WebKit run: pnpm --filter @deepseek-ai/dsh-web-frontend exec playwright install chromium webkit - - name: Restore verified bubblewrap archive - id: bubblewrap-cache - uses: actions/cache/restore@v6.1.0 - with: - path: ~/.cache/dsh-ci/bubblewrap - key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }} - - name: Prepare bubblewrap (unrestrict userns) run: bash scripts/prepare-ci-bubblewrap.sh - - name: Save verified bubblewrap archive - if: steps.bubblewrap-cache.outputs.cache-hit != 'true' - uses: actions/cache/save@v6.1.0 - with: - path: ~/.cache/dsh-ci/bubblewrap - key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }} - - name: Run complete unsharded primary Node CI serially env: DSH_ARCHIVE_BASE_REF: ${{ github.event.before }} @@ -509,13 +495,9 @@ jobs: console.log(JSON.stringify({ arch: process.arch, cpus: os.cpus().length, memoryGiB: Math.round(os.totalmem() / 2 ** 30) }))" - - name: Restore verified bubblewrap archive - id: bubblewrap-cache - uses: actions/cache/restore@v6.1.0 - with: - path: ~/.cache/dsh-ci/bubblewrap - key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }} - + # No archive cache: this manual matrix includes the persistent 64/96-core + # fleet rows, and a `~` cache written by an ephemeral runner does not + # restore into the preparation directory there. - name: Install and prepare Linux if: matrix.platform == 'linux' run: | @@ -530,13 +512,6 @@ jobs: if (( install_status != 0 )); then exit "$install_status"; fi exit "$sandbox_status" - - name: Save verified bubblewrap archive - if: steps.bubblewrap-cache.outputs.cache-hit != 'true' - uses: actions/cache/save@v6.1.0 - with: - path: ~/.cache/dsh-ci/bubblewrap - key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }} - - name: Install (immutable) if: matrix.platform == 'windows' shell: pwsh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc174147ea..01ec607012 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -179,8 +179,11 @@ jobs: restore-keys: | ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + # The persistent self-hosted pool keeps ~/.cache between jobs on its own + # layout, so the archive cache follows the hosted-only pnpm store guard. - name: Restore verified bubblewrap archive id: bubblewrap-cache + if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' uses: actions/cache/restore@v6.1.0 with: path: ~/.cache/dsh-ci/bubblewrap @@ -199,8 +202,11 @@ jobs: if (( install_status != 0 )); then exit "$install_status"; fi exit "$sandbox_status" + # The save step is skipped on a hit. A restored archive whose digest fails + # is re-downloaded but not re-saved (the key already exists), so a tampered + # entry survives until eviction; that needs deliberate cache poisoning. - name: Save verified bubblewrap archive - if: steps.bubblewrap-cache.outputs.cache-hit != 'true' + if: (vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]') && steps.bubblewrap-cache.outputs.cache-hit != 'true' uses: actions/cache/save@v6.1.0 with: path: ~/.cache/dsh-ci/bubblewrap @@ -420,8 +426,11 @@ jobs: restore-keys: | ${{ runner.os }}-playwright- + # The persistent self-hosted pool keeps ~/.cache between jobs on its own + # layout, so the archive cache follows the hosted-only pnpm store guard. - name: Restore verified bubblewrap archive id: bubblewrap-cache + if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' uses: actions/cache/restore@v6.1.0 with: path: ~/.cache/dsh-ci/bubblewrap @@ -441,7 +450,7 @@ jobs: exit "$sandbox_status" - name: Save verified bubblewrap archive - if: steps.bubblewrap-cache.outputs.cache-hit != 'true' + if: (vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]') && steps.bubblewrap-cache.outputs.cache-hit != 'true' uses: actions/cache/save@v6.1.0 with: path: ~/.cache/dsh-ci/bubblewrap @@ -560,8 +569,11 @@ jobs: - name: Install (immutable) run: pnpm install --frozen-lockfile + # The persistent self-hosted pool keeps ~/.cache between jobs on its own + # layout, so the archive cache follows the hosted-only pnpm store guard. - name: Restore verified bubblewrap archive id: bubblewrap-cache + if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' uses: actions/cache/restore@v6.1.0 with: path: ~/.cache/dsh-ci/bubblewrap @@ -571,7 +583,7 @@ jobs: run: bash scripts/prepare-ci-bubblewrap.sh - name: Save verified bubblewrap archive - if: steps.bubblewrap-cache.outputs.cache-hit != 'true' + if: (vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]') && steps.bubblewrap-cache.outputs.cache-hit != 'true' uses: actions/cache/save@v6.1.0 with: path: ~/.cache/dsh-ci/bubblewrap diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 39f9bf5aac..474ec71c21 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -92,6 +92,9 @@ jobs: - name: Prepare bubblewrap (unrestrict userns) run: bash scripts/prepare-ci-bubblewrap.sh + # A restored archive whose digest fails is re-downloaded but not re-saved + # (the hit key already exists), so a tampered entry survives until + # eviction; that needs deliberate cache poisoning. - name: Save verified bubblewrap archive if: steps.bubblewrap-cache.outputs.cache-hit != 'true' uses: actions/cache/save@v6.1.0 diff --git a/scripts/ci-compatible-selfhosted.spec.ts b/scripts/ci-compatible-selfhosted.spec.ts index e968645123..5d12db93d3 100644 --- a/scripts/ci-compatible-selfhosted.spec.ts +++ b/scripts/ci-compatible-selfhosted.spec.ts @@ -108,7 +108,11 @@ describe('Node compatibility self-hosted routing', () => { ) } expect(job.steps[0]?.with).toEqual({ 'persist-credentials': false }) - expect(job.steps.some(step => step.uses?.startsWith('actions/cache/'))).toBe(false) + // The verified bubblewrap archive is the one remote cache this job restores + // and saves; it must stay excluded from the persistent self-hosted pool. + const remoteCaches = job.steps.filter(step => step.uses?.startsWith('actions/cache/')) + expect(remoteCaches.length).toBeGreaterThan(0) + for (const step of remoteCaches) expect(step.if).toContain("vars.DSH_CI_FAILOVER_LINUX != 'selfhosted'") }) it('overrides runner exports inside setup-node without affecting later Node processes', () => { diff --git a/scripts/ci-verified-download.sh b/scripts/ci-verified-download.sh index 4cbae35be6..94837897bc 100644 --- a/scripts/ci-verified-download.sh +++ b/scripts/ci-verified-download.sh @@ -1,13 +1,36 @@ # shellcheck shell=bash # Sourced by CI preparation scripts; defines functions only. -# Succeeds when has the SHA-256 digest . +# Prints the SHA-256 digest of . +# +# CI runners do not all provide the same tool: GNU coreutils ships `sha256sum`, +# while macOS ships `shasum -a 256`. Probing both keeps a missing tool from +# being reported as a digest mismatch, which would discard a verified cached +# archive and send the next run back to a possibly unavailable download host. +sha256_digest() { + local output + if command -v sha256sum >/dev/null 2>&1; then + output="$(sha256sum < "$1")" + elif command -v shasum >/dev/null 2>&1; then + output="$(shasum -a 256 < "$1")" + else + echo 'No SHA-256 tool found: need sha256sum or shasum -a 256' >&2 + return 2 + fi + printf '%s\n' "${output%% *}" +} + +# Succeeds when has the SHA-256 digest . Returns 2, reporting the +# missing tool on stderr, when neither digest tool exists. # # Usage: verified_sha256 verified_sha256() { - local actual - actual="$(sha256sum < "$2")" || return 1 - [[ "${actual%% *}" == "$1" ]] + local actual status=0 + actual="$(sha256_digest "$2")" || status=$? + if (( status != 0 )); then + return "$status" + fi + [[ "$actual" == "$1" ]] } # Leaves a copy of whose SHA-256 digest is at . @@ -15,37 +38,68 @@ verified_sha256() { # A cached file with the expected digest is used without network access, so a # restored Actions cache keeps CI independent of the download host. A cached # file with any other digest is discarded. A download is verified before it -# replaces atomically; on failure nothing is left at -# and the function reports the URL on stderr and returns 1. -# Each attempt is bounded so a stalled host fails within minutes. +# replaces atomically, so the cache only ever holds a verified +# payload. A failed download or verification leaves nothing at and +# reports the URL on stderr. A missing SHA-256 tool returns 2 instead of +# treating the payload as mismatched. Each attempt is bounded so a stalled host +# fails within minutes. # # Usage: acquire_verified_archive acquire_verified_archive() { - local url="$1" sha256="$2" cache_file="$3" + local url="$1" sha256="$2" cache_file="$3" cache_dir + cache_dir="$(dirname -- "$cache_file")" + + # Probe before the network work: a runner without a digest tool must fail + # immediately instead of downloading a payload it cannot verify. + sha256_digest /dev/null >/dev/null + if [[ -f "$cache_file" ]]; then - if verified_sha256 "$sha256" "$cache_file"; then + local cache_status=0 + verified_sha256 "$sha256" "$cache_file" || cache_status=$? + if (( cache_status == 0 )); then echo "Using verified cached archive $cache_file" return 0 fi + if (( cache_status != 1 )); then + return "$cache_status" + fi echo "Discarding cached archive $cache_file: SHA-256 mismatch" >&2 rm -f -- "$cache_file" fi - mkdir -p -- "$(dirname -- "$cache_file")" + if ! mkdir -p -- "$cache_dir"; then + echo "Failed to create $cache_dir while preparing $url" >&2 + return 1 + fi local partial - partial="$(mktemp "${cache_file}.partial.XXXXXX")" + if ! partial="$(mktemp "${cache_file}.partial.XXXXXX")"; then + echo "Failed to create a temporary file in $cache_dir while preparing $url" >&2 + return 1 + fi + # A cancelled job must not leave a partial payload in the directory that + # actions/cache/save uploads. + trap 'rm -f -- "$partial"' EXIT + if ! curl --fail --silent --show-error --location \ --connect-timeout 15 --max-time 60 \ - --retry 8 --retry-all-errors --retry-max-time 300 \ + --retry 8 --retry-all-errors --retry-max-time 240 \ --output "$partial" "$url"; then rm -f -- "$partial" + trap - EXIT echo "Failed to download $url and no verified cached copy exists at $cache_file" >&2 return 1 fi - if ! verified_sha256 "$sha256" "$partial"; then + local download_status=0 + verified_sha256 "$sha256" "$partial" || download_status=$? + if (( download_status != 0 )); then rm -f -- "$partial" + trap - EXIT + if (( download_status != 1 )); then + return "$download_status" + fi echo "Downloaded $url does not have SHA-256 $sha256" >&2 return 1 fi mv -f -- "$partial" "$cache_file" + trap - EXIT } diff --git a/scripts/ci-verified-download.spec.ts b/scripts/ci-verified-download.spec.ts index e521ca3db7..e3aba625b1 100644 --- a/scripts/ci-verified-download.spec.ts +++ b/scripts/ci-verified-download.spec.ts @@ -1,6 +1,8 @@ import { spawnSync } from 'node:child_process' import { createHash } from 'node:crypto' -import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { + chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync, +} from 'node:fs' import { tmpdir } from 'node:os' import { delimiter, join, resolve } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' @@ -9,6 +11,7 @@ const library = resolve(import.meta.dirname, 'ci-verified-download.sh') const url = 'https://downloads.invalid/payload.deb' const payload = Buffer.from('verified payload\n') const payloadSha256 = createHash('sha256').update(payload).digest('hex') +const bash = ['/bin/bash', '/usr/bin/bash'].find(candidate => existsSync(candidate)) ?? 'bash' // Records each invocation, then copies FAKE_CURL_SOURCE to the --output path // or fails as curl does for an HTTP error when no source is configured. @@ -60,11 +63,11 @@ function createFixture(served?: Buffer): Fixture { return { root, cacheDir, cacheFile: join(cacheDir, 'payload.deb'), curlLog, env } } -function acquire(fixture: Fixture): { status: number | null; signal: NodeJS.Signals | null; stderr: string } { +function acquire(fixture: Fixture, env: NodeJS.ProcessEnv = fixture.env): { status: number | null; signal: NodeJS.Signals | null; stderr: string } { const result = spawnSync( - 'bash', + bash, ['-c', 'set -euo pipefail; source "$1"; acquire_verified_archive "$2" "$3" "$4"', 'acquire', library, url, payloadSha256, fixture.cacheFile], - { encoding: 'utf8', env: fixture.env, timeout: 30_000 }, + { encoding: 'utf8', env, timeout: 30_000 }, ) return { status: result.status, signal: result.signal, stderr: result.stderr } } @@ -78,8 +81,26 @@ function seedCache(fixture: Fixture, content: Buffer): void { writeFileSync(fixture.cacheFile, content) } -// The library targets Linux CI runners and needs bash with sha256sum. -describe.skipIf(process.platform === 'win32')('acquire_verified_archive', () => { +// Builds a PATH that reaches only the named executables plus the fixture's fake +// curl, so a child can run on a host that provides a SHA-256 tool but see none. +function restrictedPath(fixture: Fixture, names: readonly string[]): string { + const bin = join(fixture.root, 'restricted-bin') + mkdirSync(bin, { recursive: true }) + for (const name of names) { + const resolved = spawnSync('sh', ['-c', `command -v ${name}`], { encoding: 'utf8' }).stdout.trim() + if (resolved === '') throw new Error(`the test host does not provide ${name}`) + symlinkSync(resolved, join(bin, name)) + } + return [bin, join(fixture.root, 'bin')].join(delimiter) +} + +function hasDigestTool(): boolean { + return spawnSync('sh', ['-c', 'command -v sha256sum || command -v shasum'], { stdio: 'ignore' }).status === 0 +} + +// The library targets Linux CI runners; the suite needs bash and a SHA-256 tool +// (sha256sum or shasum -a 256) and skips elsewhere. +describe.skipIf(process.platform === 'win32' || !hasDigestTool())('acquire_verified_archive', () => { it('uses a verified cached archive without contacting the download host', () => { const fixture = createFixture() seedCache(fixture, payload) @@ -110,12 +131,28 @@ describe.skipIf(process.platform === 'win32')('acquire_verified_archive', () => expect(acquire(fixture).status).toBe(0) const [call] = curlCalls(fixture) - expect(call).toMatch(/--connect-timeout \d+ /u) - expect(call).toMatch(/--max-time \d+ /u) - expect(call).toMatch(/--retry-max-time \d+ /u) + expect(call).toContain('--connect-timeout 15 ') + expect(call).toContain('--max-time 60 ') + expect(call).toContain('--retry 8 ') + // The last attempt may still run for its full --max-time, so the bounded + // failure time is this window plus 60 seconds. + expect(call).toContain('--retry-max-time 240 ') expect(call).toContain(url) }) + it('fails immediately and reports the missing tool instead of a digest mismatch', () => { + const fixture = createFixture(payload) + const env = { ...fixture.env, PATH: restrictedPath(fixture, ['bash', 'dirname', 'mkdir', 'mktemp', 'mv', 'rm']) } + + const result = acquire(fixture, env) + + expect(result.signal).toBeNull() + expect(result.status).toBe(2) + expect(result.stderr).toContain('No SHA-256 tool found') + expect(curlCalls(fixture)).toEqual([]) + expect(existsSync(fixture.cacheFile)).toBe(false) + }) + it('replaces a cached archive whose digest does not match with a verified download', () => { const fixture = createFixture(payload) seedCache(fixture, Buffer.from('corrupted payload\n')) diff --git a/scripts/ci-workflow.spec.ts b/scripts/ci-workflow.spec.ts index fc0aec5178..f92873eb19 100644 --- a/scripts/ci-workflow.spec.ts +++ b/scripts/ci-workflow.spec.ts @@ -1120,8 +1120,23 @@ describe('bubblewrap preparation script', () => { expect(script).toContain('acquire_verified_archive "$BUBBLEWRAP_URL" "$BUBBLEWRAP_SHA256" "$archive"') }) + // Ephemeral runners share a `~` layout: GitHub-hosted runners and Blacksmith + // (whose runners register as self-hosted but keep /home/runner as HOME). The + // in-house `vm-backup` pool keeps `~/.cache` on a different, persistent + // layout, so lanes that can select it must not restore or save this cache. + // `ci-master.yml` prepares bubblewrap only on lanes that can select the + // persistent runners, and the manual benchmark matrix includes their 64/96-core + // rows, so neither carries cache steps. + const hostedOnly = "vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'" + const cachedJobs = new Map([ + ['ci.yml:node-24-coverage', hostedOnly], + ['ci.yml:node-24-consumers', hostedOnly], + ['ci.yml:node-compat', hostedOnly], + ['e2e.yml:e2e', undefined], + ]) + it.each(['ci.yml', 'ci-master.yml', 'e2e.yml'])( - '%s restores the verified archive cache before preparation and saves it after a miss', + '%s caches the verified archive only on the lanes that run on ephemeral runners', (name) => { const script = readFileSync(resolve(root, 'scripts/prepare-ci-bubblewrap.sh'), 'utf8') expect(script).toContain('readonly BUBBLEWRAP_CACHE_DIR="${HOME}/.cache/dsh-ci/bubblewrap"') @@ -1133,22 +1148,33 @@ describe('bubblewrap preparation script', () => { if (!isRecord(workflow.jobs)) throw new TypeError(`${name} must define jobs`) let preparations = 0 - for (const job of Object.values(workflow.jobs)) { + for (const [jobName, job] of Object.entries(workflow.jobs)) { if (!isRecord(job) || !Array.isArray(job.steps)) continue const steps = job.steps.filter(isRecord) const preparation = steps.findIndex(step => typeof step.run === 'string' && step.run.includes('bash scripts/prepare-ci-bubblewrap.sh')) if (preparation < 0) continue preparations += 1 + const key = `${name}:${jobName}` + if (!cachedJobs.has(key)) { + expect( + steps.filter(step => typeof step.uses === 'string' && step.uses.startsWith('actions/cache/')), + key, + ).toEqual([]) + continue + } + const guard = cachedJobs.get(key) + const cacheHit = "steps.bubblewrap-cache.outputs.cache-hit != 'true'" expect(steps[preparation - 1]).toEqual({ name: 'Restore verified bubblewrap archive', id: 'bubblewrap-cache', + ...(guard === undefined ? {} : { if: guard }), uses: 'actions/cache/restore@v6.1.0', with: cache, }) expect(steps[preparation + 1]).toEqual({ name: 'Save verified bubblewrap archive', - if: "steps.bubblewrap-cache.outputs.cache-hit != 'true'", + if: guard === undefined ? cacheHit : `(${guard}) && ${cacheHit}`, uses: 'actions/cache/save@v6.1.0', with: cache, }) diff --git a/scripts/prepare-ci-bubblewrap.sh b/scripts/prepare-ci-bubblewrap.sh index cb04c64b4c..39c500bb2f 100755 --- a/scripts/prepare-ci-bubblewrap.sh +++ b/scripts/prepare-ci-bubblewrap.sh @@ -9,8 +9,9 @@ readonly BUBBLEWRAP_VERSION='0.12.0-1' readonly BUBBLEWRAP_SHA256='db4d572a7927bfd34cc9b8e24b56983efa8e0483d03da6c810f6caae081dcc36' # The recorded build remains addressable after Ubuntu prunes its live package pool. readonly BUBBLEWRAP_URL="https://launchpad.net/ubuntu/+source/bubblewrap/${BUBBLEWRAP_VERSION}/+build/33546835/+files/bubblewrap_${BUBBLEWRAP_VERSION}_amd64.deb" -# Workflows restore and save this directory as `~/.cache/dsh-ci/bubblewrap` -# with actions/cache, so a warm cache needs no Launchpad request. +# Workflows that run on ephemeral runners restore and save this directory as +# `~/.cache/dsh-ci/bubblewrap` with actions/cache, so a warm cache needs no +# Launchpad request; the persistent self-hosted pool keeps the directory itself. readonly BUBBLEWRAP_CACHE_DIR="${HOME}/.cache/dsh-ci/bubblewrap" # shellcheck source=scripts/ci-verified-download.sh