diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 60934373..91ee7904 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,6 +31,11 @@ on: branches: [main] pull_request: workflow_dispatch: + inputs: + prepare-environment: + description: Prepare and publish CI environments instead of running the test matrix. + type: boolean + default: false permissions: contents: read @@ -41,8 +46,19 @@ concurrency: cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} jobs: + prepare-environment: + name: Prepare environments + if: >- + github.event_name == 'workflow_dispatch' && inputs.prepare-environment + && github.repository == 'webcpporg/webcpp' + permissions: + contents: read + packages: write + uses: ./.github/workflows/prepare-environments.yml + ci: name: CI + if: inputs.prepare-environment != true uses: ./.github/workflows/library.yml site: diff --git a/.github/workflows/library.yml b/.github/workflows/library.yml index 04a2fefe..089c2562 100644 --- a/.github/workflows/library.yml +++ b/.github/workflows/library.yml @@ -34,9 +34,7 @@ # emscripten lane emsdk and Node, which runs its programs, and a lane whose entry # says external the libraries its libraries need, built with the lane's compilers. # GCC 14 and Clang 18 run their b2 in a container with no network but the loopback, -# whose image (tools/ci/container/Dockerfile) they load from the cache. -# container when a lane runs in a container: builds that image once per run when the cache -# does not hold it, and saves it there; every lane waits for it. +# whose image is prepared separately and pulled by its immutable digest. # own-lanes one job per own lane of a library and target it runs on, which runs the lane # in every directory that declares it there. One that names no target, as an # oracle, runs on Linux x86-64 with Clang 18, and with Node when it runs the @@ -106,7 +104,6 @@ jobs: has-emscripten: ${{ steps.plan.outputs.has-emscripten }} external: ${{ steps.plan.outputs.external }} lint-external: ${{ steps.plan.outputs.lint-external }} - has-container: ${{ steps.plan.outputs.has-container }} steps: # The superproject is the caller's commit when it calls this workflow itself, and main # when a library does, the branch this workflow is called at. @@ -169,11 +166,6 @@ jobs: matrix="$(python3 tools/ci/matrix.py plan "${arguments[@]}")" python3 -m json.tool <<< "$matrix" echo "matrix=$matrix" >> "$GITHUB_OUTPUT" - # Whether a lane runs in a container, whose image the container job builds first. - has_container="$(python3 -c 'import json, sys - print(str(any(lane["container"] for lane in json.load(sys.stdin)["include"])).lower())' \ - <<< "$matrix")" - echo "has-container=$has_container" >> "$GITHUB_OUTPUT" own_lanes="$(python3 tools/ci/matrix.py own-lanes "${arguments[@]}")" python3 -m json.tool <<< "$own_lanes" echo "own-lanes=$own_lanes" >> "$GITHUB_OUTPUT" @@ -194,27 +186,10 @@ jobs: lint_external="$(python3 tools/ci/matrix.py external)" echo "lint-external=$lint_external" >> "$GITHUB_OUTPUT" - # The container lanes' image, built once per run when the cache does not hold it, and saved - # there before any lane starts: two lanes that missed the cache together would each build it. - container: - name: Container image - needs: plan - if: needs.plan.outputs.has-container == 'true' - runs-on: ubuntu-24.04 - timeout-minutes: 30 - steps: - - *superproject - - *superproject-for-library - - uses: ./tools/ci/actions/container - - # Every lane waits for the container job, which builds the image a container lane loads, and - # runs when that job succeeded or was not needed. + # Only a container lane obtains its prepared image; other lanes do not wait for it. lanes: name: ${{ matrix.name }} - needs: [plan, container] - if: >- - !cancelled() && needs.plan.result == 'success' - && (needs.container.result == 'success' || needs.container.result == 'skipped') + needs: plan runs-on: ${{ matrix.os }} timeout-minutes: 90 strategy: @@ -275,8 +250,8 @@ jobs: cc: ${{ matrix.cc }} emscripten: ${{ matrix.emsdk }} - # The image a container lane runs b2 in (its entry's container), which the container job - # built and cached, restored from the cache, so that the lane builds none. + # Only a container lane obtains the separately prepared immutable image. + # No ordinary lane builds images or waits for an image-building job. - if: matrix.container uses: ./tools/ci/actions/container diff --git a/.github/workflows/prepare-environments.yml b/.github/workflows/prepare-environments.yml new file mode 100644 index 00000000..eafc146c --- /dev/null +++ b/.github/workflows/prepare-environments.yml @@ -0,0 +1,143 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# Invoked explicitly through CI's prepare-environment input. Normal pull requests +# never publish packages or build images. Verified output is promoted in a source PR. +name: Prepare CI environments + +on: + workflow_call: + workflow_dispatch: + +permissions: + contents: read + +defaults: + run: + shell: bash + +jobs: + publish: + name: Publish ${{ matrix.key }} + if: github.event_name == 'workflow_dispatch' && github.repository == 'webcpporg/webcpp' + runs-on: ubuntu-24.04 + timeout-minutes: 60 + permissions: + contents: read + packages: write + strategy: + fail-fast: false + matrix: &environments + include: + - {key: native-linux-x64, tool: '', variant: ''} + - {key: wasi-sdk-linux-x64, tool: wasi-sdk, variant: ''} + - {key: wasmtime-linux-x64, tool: wasmtime, variant: ''} + - {key: wit-bindgen-linux-x64, tool: wit-bindgen, variant: ''} + - {key: wasi-wit-linux-x64, tool: wasi-wit, variant: ''} + - {key: mrdocs-linux-x64, tool: mrdocs, variant: ''} + env: + WEBCPP_PREPARE_ENVIRONMENT: '1' + TOOL: ${{ matrix.tool }} + VARIANT: ${{ matrix.variant }} + KEY: ${{ matrix.key }} + WEBCPP_DOWNLOAD_CACHE: .local/environment-archives + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + # Deliberately no cache restore in the publisher. It verifies upstream bytes afresh. + - name: Fetch and exercise the pinned installer + if: matrix.tool != '' + env: + WEBCPP_CHROME_PRODUCT: ${{ matrix.variant }} + run: bash "tools/ci/actions/$TOOL/install.sh" + + - name: Authenticate the publisher + env: + GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: printf '%s' "$GHCR_TOKEN" | docker login ghcr.io --username "$GITHUB_ACTOR" --password-stdin + + - name: Publish candidate + run: >- + python3 tools/ci/environment.py publish --tool "$TOOL" --variant "$VARIANT" + --cache "$WEBCPP_DOWNLOAD_CACHE" --out ".local/environment-candidates/$KEY.json" + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: candidate-${{ matrix.key }} + path: .local/environment-candidates/${{ matrix.key }}.json + if-no-files-found: error + retention-days: 30 + + - name: Remove registry credentials + if: always() + run: docker logout ghcr.io + + # These fresh runners have no publishing credentials. GHCR must be public before + # this succeeds; linking a package to a public repository does not make it public. + verify: + name: Verify ${{ matrix.key }} anonymously + needs: publish + runs-on: ubuntu-24.04 + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: *environments + env: + TOOL: ${{ matrix.tool }} + VARIANT: ${{ matrix.variant }} + KEY: ${{ matrix.key }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: candidate-${{ matrix.key }} + path: .local/environment-candidates + + - name: Verify anonymous pull and offline installation + run: >- + python3 tools/ci/environment.py verify --tool "$TOOL" --variant "$VARIANT" + --cache "$RUNNER_TEMP/verified-archives" + --candidate ".local/environment-candidates/$KEY.json" + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: verified-${{ matrix.key }} + path: .local/environment-candidates/${{ matrix.key }}.json + if-no-files-found: error + retention-days: 30 + + manifest: + name: Assemble verified environment pins + needs: verify + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: verified-* + path: .local/environment-candidates + merge-multiple: true + + - name: Assemble pins for review + run: >- + python3 tools/ci/environment.py merge --directory .local/environment-candidates + --out .local/prepared/environments.json + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ci-environments + path: .local/prepared/environments.json + if-no-files-found: error + retention-days: 30 diff --git a/AGENTS.md b/AGENTS.md index 6438245f..11d6457e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1516,11 +1516,6 @@ jobs: `--library` it says whether any library of `libs/` needs them: the plan's output `lint-external`, on which the lint job, which analyses every library, installs them. -- **container:** when the plan has a container lane (its output - `has-container`), the `container` action on ubuntu-24.04, which builds - the container lanes' image when the cache does not hold it and saves it - there, once per run; every lane's job waits for it (`needs: [plan, - container]`), and runs when it succeeded or was skipped. - **lanes,** one job each, which run `matrix.py lane `: it registers the lane's toolset in `.local/user-config.jam` with its version, prints the lane command and runs it, and the job uploads `.xml`: @@ -1568,13 +1563,13 @@ jobs: produced incompatible OpenSSL package versions; the image keeps all packages on the same snapshot. Consumer OpenSSL is now built from the pinned sources. Ubuntu keeps no snapshot of `ports.ubuntu.com`, so the image builds for - x86-64 alone (measured: apt 2.8.3 refuses arm64's sources). It is tagged - `webcpp-lane:`. The - `container` job, which every lane waits for, runs the `container` action - once per run, which builds it when the cache does not hold it and saves it - there under that digest; each container lane's job runs the action too, - which then loads it, and `matrix.py lane` builds it only when no image of - that tag is there. Then it runs b2 by its path, `docker run --rm --network + x86-64 alone (measured: apt 2.8.3 refuses arm64's sources). + `tools/ci/environments.json` pins the public GHCR image by its full digest + and binds it to the Dockerfile recipe. The container action pulls that + digest; a missing or stale pin fails with preparation instructions. It + never runs apt or builds an image during an ordinary lane. Every lane + depends only on the plan, so an unavailable image blocks its two consumers + while the other configurations continue. Then it runs b2 by its path, `docker run --rm --network none`, as the runner's user, with the superproject and b2's prefix, where the Boost action installs Boost's headers too, mounted at their own paths, and the variables of the external libraries passed on; the XML is the @@ -1807,12 +1802,53 @@ wrapper each quoted as one word of Jam. isolated profile trust store. Test CAs are installed only in disposable profiles; no host trust store or certificate-validation bypass is used. The drivers disable background networking and operate against local fixtures. -- `container` gives a job the container lanes' image (above): built from - `tools/ci/container/Dockerfile` when the cache does not hold it, saved - there under the Dockerfile's digest, and loaded from there otherwise. -- `tools/ci/download.sh ` downloads each pinned file, - and leaves no file and exits 1 when the download fails or the digest - differs. +- `container` gives a job the checked immutable image above. Registry access + happens before the lane; the test container still has `--network none`. +- `tool-archives` restores the SHA-256 addressed archives for wasi-sdk, + Wasmtime, wit-bindgen, WASI WIT, MrDocs and Chrome. The installer still runs + on every job, preserving its version checks and environment exports. + Cache service failures do not fail a job: a miss uses the prepared bundle, + and a failed save leaves the validated installation usable. + Linux-X64 cold caches for the five open-source tools come from the prepared + public OCI bundles. The bundle is copied from a stopped container and every + file is verified before publication in the local cache. Normal installations + of those tools require verified cache entries and never fall back to upstream. + Other supported hosts keep their checked upstream downloads. Chrome uses its + official download and the same verified cache, without public redistribution + of its binaries: the upstream maintainer distinguishes the binary terms from + the repository license in + [issue 21](https://github.com/GoogleChromeLabs/chrome-for-testing/issues/21). +- `tools/ci/download.sh ` verifies downloaded or cached + bytes, publishes complete files atomically, and leaves no output after failure. + `WEBCPP_DOWNLOAD_CACHE` selects a content-addressed cache; + `WEBCPP_DOWNLOAD_OFFLINE=1` forbids curl on a missing or corrupt entry. + Connection, transfer and retry windows are bounded. No test verdict is cached. + +**Preparing and updating environments.** An owner explicitly dispatches CI +with `prepare-environment=true` at the reviewed source commit. The preparation +workflow builds the native image from the dated Ubuntu snapshot and downloads +the pinned tool archives afresh. Only its publisher has `packages: write`. +The package `ghcr.io/webcpporg/ci-environment` must be made public once after +initial creation; a public repository does not imply public package visibility. +Separate runners prove anonymous digest pulls, offline tool installation and +native C++20 compilation before producing the `ci-environments` artifact. +Download that artifact's generated `environments.json` into `tools/ci/`, review +and commit it with the recipe changes, then run the complete normal CI. Do not +edit generated digests or merge a recipe without its verified pins. A failed +preparation leaves the previous checked-in environments in use. + +```sh +gh workflow run ci.yml --repo webcpporg/webcpp --ref \ + -f prepare-environment=true +gh run download --repo webcpporg/webcpp \ + --name ci-environments --dir tools/ci +``` + +This isolates the covered tools from upstream availability during ordinary CI, +not every dependency. Checkout, the GitHub registry/cache, setup-node and npm, +Emscripten's source fetch and the Rust/Cargo fixture remain prerequisites. +The full lane set, `b2 -a`, fresh XML and missing-result checks remain mandatory. + - `tools/ci/helpers.sh` holds what the actions share, which each `install.sh` sources beside `download.sh`: `digest`, the SHA-256 of files one after the other; `mixed`, a path as Windows programs read it; @@ -1832,7 +1868,10 @@ unpinned, and an emcc that is not 6.0.11; the emsdk action's node wrapper, `EM_CACHE`, warmed cache and system libraries; libsecp256k1's pinned archive, compiler settings, install prefixes, exports, cache key and Windows runtime; the chrome action's shell and its `--no-sandbox` wrapper; and the container -image, built and saved once, then loaded. Their refusal tests cover bad hashes +image, pulled by an immutable digest without a build fallback. +`tools/ci/environment_test.py` checks recipe identity, archive restoration and +publication boundaries; `tools/ci/download_cache_test.py` checks offline reuse, +corruption, interrupted transfers and atomic output. Their refusal tests cover bad hashes and unsupported runners. Source-provider tests live in `tools/openssl/build_test.py`, `tools/test/openssl_test.py` and `tools/test/libdatachannel_test.py`: they cover source pins, staged content, diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 3df9ef61..67ed411e 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -1384,6 +1384,21 @@ site's own decisions follow in the next sections. there, which every library's tests hold and trystero's guarantee 6 rests on; the snapshot makes one Dockerfile one set of packages. Source: `AGENTS.md` (webcpp). +- **CI preparation is explicit and separate from ordinary pull-request tests.** + A trusted dispatch publishes native and Linux-X64 tool images, then separate + jobs verify anonymous digest pulls and smoke checks. Reviewed generated pins + bind the images to their recipes. Ordinary jobs neither build missing images + nor run apt; only their two container consumers need the native image. + The full lane set and report still fail on missing test results. +- **Tool caches hold verified input archives, never test verdicts.** Each cache + read verifies SHA-256 and each write is atomic. Linux-X64 wasi-sdk, Wasmtime, + wit-bindgen, WASI WIT and MrDocs cold caches use prepared public bundles and + installation stays offline. Other hosts and Chrome retain checked upstream + downloads with bounded retries. Chrome binaries are not republished as public + packages; their terms differ from the CfT repository's license. Every original + installer still runs, so PATH, environment exports and version checks remain. + Source: `tools/ci/environment.py`, `tools/ci/download.sh`, + `.github/workflows/prepare-environments.yml`, `AGENTS.md` (webcpp). - **The native lanes are GCC 14 and 15, Clang 18 and 22 on libstdc++, Apple Clang and MSVC 14.3 and 14.5, beside one lane each for emscripten, wasip2 and wasip3.** The Clang lanes on libstdc++ stay because a regression of diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 88d6465f..2b06cc15 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -55,6 +55,8 @@ None. [#webcpp-0-1-0-tools-and-build] == Tools and build +* Changed CI to consume verified prepared environments without rebuilding images in PR jobs. +* Added verified archive caches and isolated container availability from unrelated CI lanes. * Fixed parallel builds truncating OpenSSL headers while compilers read them. * Fixed driven-test execution and descendant cleanup on Windows. * Fixed driven-test executable reuse for Windows and WASI builds. diff --git a/tools/ci/actions/chrome/action.yml b/tools/ci/actions/chrome/action.yml index 7dac8ca5..a443fa34 100644 --- a/tools/ci/actions/chrome/action.yml +++ b/tools/ci/actions/chrome/action.yml @@ -20,7 +20,7 @@ runs: using: composite steps: - name: Chrome for Testing 155.0.8059.39 - shell: bash - env: - WEBCPP_CHROME_PRODUCT: ${{ inputs.product }} - run: bash tools/ci/actions/chrome/install.sh + uses: ./tools/ci/actions/tool-archives + with: + tool: chrome + variant: ${{ inputs.product }} diff --git a/tools/ci/actions/container/action.yml b/tools/ci/actions/container/action.yml index 49f9ef58..a98693bf 100644 --- a/tools/ci/actions/container/action.yml +++ b/tools/ci/actions/container/action.yml @@ -5,40 +5,11 @@ # https://www.boost.org/LICENSE_1_0.txt) name: Container image -description: >- - Gives the job the image of the container lanes, tools/ci/container/Dockerfile's, tagged with the - start of its SHA-256: built once, from Ubuntu's snapshot of the archive that the Dockerfile - names, and saved in the cache under the Dockerfile's digest, then loaded from there by every - later lane, which then builds none. On Linux x86-64. +description: Pull the prepared Linux-X64 lane image by its checked immutable digest. runs: using: composite steps: - - name: Cache key - id: key + - name: Obtain the prepared native image shell: bash - run: bash tools/ci/actions/container/install.sh key - - - name: Restore the image - id: restore - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: .local/container/image.tar - key: ${{ steps.key.outputs.key }} - - - name: Load the image - if: steps.restore.outputs.cache-hit == 'true' - shell: bash - run: bash tools/ci/actions/container/install.sh load - - - name: Build the image - if: steps.restore.outputs.cache-hit != 'true' - shell: bash - run: bash tools/ci/actions/container/install.sh build - - - name: Save the image - if: steps.restore.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: .local/container/image.tar - key: ${{ steps.key.outputs.key }} + run: bash tools/ci/actions/container/install.sh diff --git a/tools/ci/actions/container/install.sh b/tools/ci/actions/container/install.sh index 8f791b97..93ba5656 100644 --- a/tools/ci/actions/container/install.sh +++ b/tools/ci/actions/container/install.sh @@ -5,50 +5,7 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -# The steps of tools/ci/actions/container: the image of the container lanes, built from -# tools/ci/container/Dockerfile once, saved in .local/container/image.tar, which the action caches -# under the Dockerfile's SHA-256, and loaded by every later lane, so that `tools/ci/matrix.py lane` -# finds it and builds none. The tag is webcpp-lane:, as matrix.py's CONTAINER_IMAGE: an image of another Dockerfile is never taken for it. -# -# Usage, from the superproject's root, with the variables a runner sets (RUNNER_ARCH, ImageOS, -# GITHUB_OUTPUT): -# -# install.sh key writes the tag and the cache key to GITHUB_OUTPUT; -# install.sh build builds the image, with the network, and saves it; -# install.sh load loads the image the cache restored, and fails unless it holds the tag. +# Consume the reviewed digest. A missing registry image never starts an apt/image build. +# Usage, from the superproject's root: install.sh set -euo pipefail - -dockerfile=tools/ci/container/Dockerfile -archive=.local/container/image.tar - -here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -# The functions every action shares: digest, mixed, configuration, compiler_identity. -# shellcheck source=SCRIPTDIR/../../helpers.sh -. "${here}/../../helpers.sh" - -hash="$(digest "${dockerfile}")" -tag="webcpp-lane:${hash:0:16}" - -case "${1-}" in - key) - printf 'tag=%s\nkey=container-%s-%s-%s\n' "${tag}" "${hash:0:16}" "${ImageOS:-image}" \ - "${RUNNER_ARCH}" >> "${GITHUB_OUTPUT}" - ;; - build) - docker build --tag "${tag}" "$(dirname "${dockerfile}")" - mkdir -p "$(dirname "${archive}")" - docker save --output "${archive}" "${tag}" - ;; - load) - docker load --input "${archive}" - docker image inspect "${tag}" > /dev/null 2>&1 || { - printf 'install.sh: %s holds no image %s\n' "${archive}" "${tag}" >&2 - exit 1 - } - ;; - *) - printf 'usage: install.sh key | build | load\n' >&2 - exit 2 - ;; -esac +exec python3 tools/ci/environment.py native diff --git a/tools/ci/actions/mrdocs/action.yml b/tools/ci/actions/mrdocs/action.yml index 37c5a395..2f9a7f36 100644 --- a/tools/ci/actions/mrdocs/action.yml +++ b/tools/ci/actions/mrdocs/action.yml @@ -13,5 +13,6 @@ runs: using: composite steps: - name: Install MrDocs 2026.9.29 - shell: bash - run: bash tools/ci/actions/mrdocs/install.sh + uses: ./tools/ci/actions/tool-archives + with: + tool: mrdocs diff --git a/tools/ci/actions/tool-archives/action.yml b/tools/ci/actions/tool-archives/action.yml new file mode 100644 index 00000000..4b056641 --- /dev/null +++ b/tools/ci/actions/tool-archives/action.yml @@ -0,0 +1,61 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +name: Tool archives +description: Restore verified archives for one tool, then run its pinned installer. + +inputs: + tool: + description: The pinned tool action whose installer runs. + required: true + variant: + description: The Chrome product, or empty for another tool. + default: '' + +runs: + using: composite + steps: + - name: Archive cache key + id: key + shell: bash + env: + TOOL: ${{ inputs.tool }} + VARIANT: ${{ inputs.variant }} + run: bash tools/ci/actions/tool-archives/cache.sh key "$TOOL" "$VARIANT" + + - name: Restore tool archives + continue-on-error: true + id: restore + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ steps.key.outputs.directory }} + key: ${{ steps.key.outputs.key }} + + - name: Restore prepared tool archives + if: steps.restore.outputs.cache-hit != 'true' && env.WEBCPP_PREPARE_ENVIRONMENT != '1' + shell: bash + env: + TOOL: ${{ inputs.tool }} + VARIANT: ${{ inputs.variant }} + CACHE: ${{ steps.key.outputs.directory }} + run: >- + python3 tools/ci/environment.py restore-tool + --tool "$TOOL" --variant "$VARIANT" --cache "$CACHE" + + - name: Install the pinned tool + shell: bash + env: + TOOL: ${{ inputs.tool }} + VARIANT: ${{ inputs.variant }} + run: bash tools/ci/actions/tool-archives/cache.sh install "$TOOL" "$VARIANT" + + - name: Save tool archives + continue-on-error: true + if: steps.restore.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ steps.key.outputs.directory }} + key: ${{ steps.key.outputs.key }} diff --git a/tools/ci/actions/tool-archives/cache.sh b/tools/ci/actions/tool-archives/cache.sh new file mode 100644 index 00000000..2e30e6eb --- /dev/null +++ b/tools/ci/actions/tool-archives/cache.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# Per-tool archive cache identity and installation, always from the superproject's root. +# Usage: cache.sh +# key writes directory and key to GITHUB_OUTPUT. install always runs the original installer, +# even after a cache hit, so its version check and GITHUB_PATH/GITHUB_ENV exports still run. +set -euo pipefail + +if [ "$#" -ne 3 ]; then + printf 'usage: cache.sh \n' >&2 + exit 2 +fi +operation="$1" +tool="$2" +variant="$3" +case "${operation}" in + key|install) ;; + *) printf 'cache.sh: unknown operation: %s\n' "${operation}" >&2; exit 2 ;; +esac +case "${tool}:${variant}" in + wasi-sdk:|wasmtime:|wit-bindgen:|wasi-wit:|mrdocs:|chrome:chrome|chrome:chrome-headless-shell) ;; + *) printf 'cache.sh: unsupported tool or variant: %s %s\n' "${tool}" "${variant}" >&2; exit 2 ;; +esac + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source-path=SCRIPTDIR source=../../helpers.sh +. "${here}/../../helpers.sh" +name="${tool}${variant:+-${variant}}" +directory="$(pwd)/.local/download-cache/${name}" +installer="tools/ci/actions/${tool}/install.sh" +case "${operation}" in + key) + identity="$(digest "${installer}" "tools/ci/actions/${tool}/action.yml" \ + tools/ci/download.sh tools/ci/helpers.sh "${here}/action.yml" "${here}/cache.sh" \ + tools/ci/environments.json)" + printf 'directory=%s\nkey=tool-archives-%s-%s-%s-%s\n' "${directory}" "${name}" \ + "${RUNNER_OS}" "${RUNNER_ARCH}" "${identity}" >> "${GITHUB_OUTPUT}" + ;; + install) + export WEBCPP_DOWNLOAD_CACHE="${directory}" + if [ "${tool}" != chrome ] && [ "${RUNNER_OS}-${RUNNER_ARCH}" = Linux-X64 ] && \ + [ "${WEBCPP_PREPARE_ENVIRONMENT-}" != 1 ]; then + export WEBCPP_DOWNLOAD_OFFLINE=1 + fi + if [ "${tool}" = chrome ]; then + export WEBCPP_CHROME_PRODUCT="${variant}" + fi + bash "${installer}" + ;; +esac diff --git a/tools/ci/actions/wasi-sdk/action.yml b/tools/ci/actions/wasi-sdk/action.yml index c8d7bb26..c9f20802 100644 --- a/tools/ci/actions/wasi-sdk/action.yml +++ b/tools/ci/actions/wasi-sdk/action.yml @@ -13,5 +13,6 @@ runs: using: composite steps: - name: Install wasi-sdk 34.0 - shell: bash - run: bash tools/ci/actions/wasi-sdk/install.sh + uses: ./tools/ci/actions/tool-archives + with: + tool: wasi-sdk diff --git a/tools/ci/actions/wasi-wit/action.yml b/tools/ci/actions/wasi-wit/action.yml index 587d413f..a2b40c74 100644 --- a/tools/ci/actions/wasi-wit/action.yml +++ b/tools/ci/actions/wasi-wit/action.yml @@ -15,5 +15,6 @@ runs: using: composite steps: - name: Install the WIT of WASI 0.2.12 and 0.3.0 - shell: bash - run: bash tools/ci/actions/wasi-wit/install.sh + uses: ./tools/ci/actions/tool-archives + with: + tool: wasi-wit diff --git a/tools/ci/actions/wasmtime/action.yml b/tools/ci/actions/wasmtime/action.yml index e6ced315..5753ec8c 100644 --- a/tools/ci/actions/wasmtime/action.yml +++ b/tools/ci/actions/wasmtime/action.yml @@ -14,5 +14,6 @@ runs: using: composite steps: - name: Install wasmtime 50.0.1 - shell: bash - run: bash tools/ci/actions/wasmtime/install.sh + uses: ./tools/ci/actions/tool-archives + with: + tool: wasmtime diff --git a/tools/ci/actions/wit-bindgen/action.yml b/tools/ci/actions/wit-bindgen/action.yml index 6b19c5ba..1269c6d2 100644 --- a/tools/ci/actions/wit-bindgen/action.yml +++ b/tools/ci/actions/wit-bindgen/action.yml @@ -14,5 +14,6 @@ runs: using: composite steps: - name: Install wit-bindgen 0.62.0 - shell: bash - run: bash tools/ci/actions/wit-bindgen/install.sh + uses: ./tools/ci/actions/tool-archives + with: + tool: wit-bindgen diff --git a/tools/ci/actions_test.py b/tools/ci/actions_test.py index fc38daec..9674ea0e 100755 --- a/tools/ci/actions_test.py +++ b/tools/ci/actions_test.py @@ -1440,67 +1440,47 @@ def test_chrome_refuses_a_shell_it_does_not_pin_or_a_runner_it_has_none_for(scra CONTAINER = CI / 'actions/container/install.sh' -# A stand-in of docker for the container action: each call's words to stand-in.log; `save -# --output ` writes the file, `load --input ` reads it and remembers the tag -# it held, and `image inspect ` succeeds when that tag was loaded or built. +# A controlled Docker boundary: ordinary actions may inspect and pull, never build. FAKE_IMAGE_DOCKER = r"""#!/usr/bin/env bash set -euo pipefail printf '%s\n' "docker $*" >> "${STAND_IN_LOG}" -images="${STAND_IN_LOG}.images" case "$1" in - build) printf '%s\n' "$3" >> "${images}" ;; - save) printf '%s\n' "${@: -1}" > "$3" ;; - load) cat "$3" >> "${images}" ;; - image) grep -qx "$3" "${images}" 2>/dev/null ;; - *) exit 1 ;; + image) exit 1 ;; + pull) exit "${STAND_IN_PULL_STATUS:-0}" ;; + *) exit 2 ;; esac """ -def container_tree(scratch: Path) -> tuple[Path, dict[str, str]]: - """The container action where it lives, the Dockerfile beside it, a stand-in docker, and a - runner's variables.""" +def test_container_pulls_the_pinned_image_without_building(scratch: Path) -> None: + # The historical build/load path is replaced by consumption of the checked immutable pin. directory = scratch / 'tools/ci/actions/container' directory.mkdir(parents=True) for name in ('install.sh', 'action.yml'): shutil.copy2(CONTAINER.parent / name, directory / name) place_helpers(scratch) + shutil.copy2(CI / 'environment.py', scratch / 'tools/ci/environment.py') (scratch / 'tools/ci/container').mkdir() shutil.copy2(CI / 'container/Dockerfile', scratch / 'tools/ci/container/Dockerfile') - tools = stand_ins(scratch, {'docker': FAKE_IMAGE_DOCKER}) - return directory / 'install.sh', dependency_runner(scratch, 'Linux', 'X64', tools) - - -def test_container_builds_the_image_once_and_loads_it_after(scratch: Path) -> None: - # The key and the tag are the Dockerfile's, as tools/ci/matrix.py tags the image; on a miss - # the image is built and saved where the action caches it, and on a hit loaded from there. - script, runner = container_tree(scratch) - result = dependency_step(scratch, script, runner, 'key') - assert result.returncode == 0, (result.returncode, result.stderr) - digest = hashlib.sha256((CI / 'container/Dockerfile').read_bytes()).hexdigest()[:16] - tag = f'webcpp-lane:{digest}' sys.path.insert(0, str(CI)) - import matrix - assert matrix.CONTAINER_IMAGE == tag, (matrix.CONTAINER_IMAGE, tag) - assert (scratch / 'github-output').read_text() == ( - f'tag={tag}\nkey=container-{digest}-ubuntu24-X64\n'), ( - (scratch / 'github-output').read_text()) - result = dependency_step(scratch, script, runner, 'build') + import environment as prepared_environment + image = 'ghcr.io/webcpporg/ci-environment@sha256:' + 'a' * 64 + prepared_environment.write_manifest(scratch / 'tools/ci/environments.json', { + 'native-linux-x64': {'image': image, 'recipe': prepared_environment.recipe(), + 'source': 'b' * 40, 'archives': []}}) + tools = stand_ins(scratch, {'docker': FAKE_IMAGE_DOCKER}) + runner = dependency_runner(scratch, 'Linux', 'X64', tools) + script = directory / 'install.sh' + result = dependency_step(scratch, script, runner) assert result.returncode == 0, (result.returncode, result.stderr) - archive = '.local/container/image.tar' - assert logged(scratch) == [f'docker build --tag {tag} tools/ci/container', - f'docker save --output {archive} {tag}'], logged(scratch) + assert logged(scratch) == [f'docker image inspect {image}', f'docker pull {image}'] (scratch / 'stand-in.log').unlink() - (scratch / 'stand-in.log.images').unlink() - result = dependency_step(scratch, script, runner, 'load') - assert result.returncode == 0, (result.returncode, result.stderr) - assert logged(scratch) == [f'docker load --input {archive}', f'docker image inspect {tag}'] - # An archive that holds another image fails the load, naming the tag it lacks. - (scratch / archive).write_text('webcpp-lane:0000000000000000\n') - (scratch / 'stand-in.log.images').unlink() - result = dependency_step(scratch, script, runner, 'load') + result = dependency_step(scratch, script, {**runner, 'STAND_IN_PULL_STATUS': '1'}) assert result.returncode == 1, (result.returncode, result.stderr) - assert f'install.sh: {archive} holds no image {tag}' in result.stderr, result.stderr + assert 'prepare-environments' in result.stderr, result.stderr + assert logged(scratch) == [f'docker image inspect {image}', f'docker pull {image}'] + action = (directory / 'action.yml').read_text() + assert 'actions/cache' not in action and 'install.sh build' not in action, action def test_the_shared_helpers(scratch: Path) -> None: @@ -1583,7 +1563,7 @@ def helper(call: str, **variables: str) -> str: test_secp256k1_on_windows_builds_debug_with_visual_studio, test_secp256k1_refuses_an_archive_it_does_not_pin, test_secp256k1_refuses_a_runner_it_builds_nothing_for, - test_container_builds_the_image_once_and_loads_it_after, + test_container_pulls_the_pinned_image_without_building, test_chrome_installs_the_pinned_headless_shell, test_chrome_installs_full_chrome_for_isolated_certificate_trust, test_chrome_refuses_a_shell_it_does_not_pin_or_a_runner_it_has_none_for, diff --git a/tools/ci/download.sh b/tools/ci/download.sh index 802befe6..062322be 100755 --- a/tools/ci/download.sh +++ b/tools/ci/download.sh @@ -8,6 +8,8 @@ # Downloads a pinned file and checks its SHA-256, for the actions of tools/ci/actions. # # Usage: tools/ci/download.sh +# WEBCPP_DOWNLOAD_CACHE optionally names a directory of archives, each named by its SHA-256. +# WEBCPP_DOWNLOAD_OFFLINE=1 requires a verified cache hit and never invokes curl. # Exit 0 with written and its SHA-256 the one given; 1 when the download fails or the # digest differs, which removes ; 2 on a usage error. set -euo pipefail @@ -20,26 +22,93 @@ url="$1" expected="$2" file="$3" -# A failed download can leave part of the file, which must not be taken for the whole. curl's -# --retry alone tries again only a timeout and an HTTP 408, 429 or 5xx; --retry-all-errors also -# tries again a connection the server drops, as a TLS handshake cut short does (curl's exit -# statuses 35, 52 and 56), which failed CI lanes downloading Boost. -curl -fsSL --retry 3 --retry-all-errors -o "${file}" "${url}" || { - status=$? - rm -f "${file}" - printf 'download.sh: could not download %s (curl exit status %s)\n' "${url}" "${status}" >&2 - exit 1 +if [[ ! "${expected}" =~ ^[[:xdigit:]]{64}$ ]]; then + printf 'download.sh: expected a SHA-256 digest of 64 hexadecimal digits\n' >&2 + exit 2 +fi +expected="$(printf '%s' "${expected}" | tr '[:upper:]' '[:lower:]')" +# Prefix a filename starting with '-' so it cannot become an option; keep Windows paths intact. +case "${file}" in -*) file="./${file}" ;; esac +temporary= +cache_temporary= +complete=false +cleanup() { + [ -z "${temporary}" ] || rm -f -- "${temporary}" + [ -z "${cache_temporary}" ] || rm -f -- "${cache_temporary}" + if [ "${complete}" != true ]; then + rm -f -- "${file}" + fi } -# sha256sum is GNU's (Linux, Git for Windows); macOS has shasum. -if command -v sha256sum >/dev/null 2>&1; then - actual="$(sha256sum "${file}" | cut -d ' ' -f 1)" -else - actual="$(shasum -a 256 "${file}" | cut -d ' ' -f 1)" +trap cleanup EXIT +trap 'exit 1' HUP INT TERM + +# The staged copy is hashed, not the cache path: a concurrent writer can replace a cache +# entry, but cannot change which bytes this invocation validates and delivers. +temporary="$(mktemp "${file}.tmp.XXXXXX")" +cache="${WEBCPP_DOWNLOAD_CACHE-}" +case "${cache}" in -*) cache="./${cache}" ;; esac +entry= +if [ -n "${cache}" ]; then + mkdir -p -- "${cache}" + entry="${cache}/${expected}" + if [ -f "${entry}" ]; then + cp -- "${entry}" "${temporary}" + elif [ -e "${entry}" ]; then + printf 'download.sh: cache entry is not a file: %s\n' "${entry}" >&2 + exit 1 + fi +fi + +# sha256sum is GNU's (Linux, Git for Windows); macOS has shasum. Read stdin so a filename +# containing spaces or backslashes never changes the digest's printed representation. +sha256() { + if command -v sha256sum >/dev/null 2>&1; then + sha256sum < "$1" | cut -d ' ' -f 1 + else + shasum -a 256 < "$1" | cut -d ' ' -f 1 + fi +} + +hit=false +if [ -n "${entry}" ] && [ -f "${entry}" ]; then + actual="$(sha256 "${temporary}")" + if [ "${actual}" = "${expected}" ]; then + hit=true + else + printf 'download.sh: discarding corrupt cache entry %s (SHA-256 %s)\n' \ + "${entry}" "${actual}" >&2 + rm -f -- "${entry}" + fi fi -if [ "${actual}" != "${expected}" ]; then - rm -f "${file}" - printf 'download.sh: %s has SHA-256 %s, and %s is pinned\n' "${url}" "${actual}" \ - "${expected}" >&2 - exit 1 +if [ "${hit}" != true ]; then + if [ "${WEBCPP_DOWNLOAD_OFFLINE-}" = 1 ]; then + printf 'download.sh: offline cache has no verified archive with SHA-256 %s\n' \ + "${expected}" >&2 + exit 1 + fi + # --retry-all-errors also retries dropped TLS connections. Both each transfer and the + # retry window are bounded; curl can finish one final transfer after that window ends. + curl -fsSL --connect-timeout 30 --max-time 600 --retry 3 --retry-max-time 1200 \ + --retry-all-errors -o "${temporary}" "${url}" || { + status=$? + printf 'download.sh: could not download %s (curl exit status %s)\n' \ + "${url}" "${status}" >&2 + exit 1 + } + actual="$(sha256 "${temporary}")" + if [ "${actual}" != "${expected}" ]; then + printf 'download.sh: %s has SHA-256 %s, and %s is pinned\n' "${url}" "${actual}" \ + "${expected}" >&2 + exit 1 + fi + if [ -n "${entry}" ]; then + cache_temporary="$(mktemp "${cache}/.download.XXXXXX")" + cp -- "${temporary}" "${cache_temporary}" + mv -f -- "${cache_temporary}" "${entry}" + cache_temporary= + fi fi +mv -f -- "${temporary}" "${file}" +temporary= +complete=true printf 'download.sh: %s, SHA-256 %s\n' "${url}" "${actual}" diff --git a/tools/ci/download_cache_test.py b/tools/ci/download_cache_test.py new file mode 100644 index 00000000..f6ea787a --- /dev/null +++ b/tools/ci/download_cache_test.py @@ -0,0 +1,407 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +"""Exercises pinned downloads and per-tool archive preparation through the production shell. +Every transfer uses a file URL or loopback HTTP fixture. Paths deliberately contain spaces. +Run with case names to select cases. +""" + +from __future__ import annotations + +import hashlib +import os +import shlex +import shutil +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time +from collections.abc import Callable +from pathlib import Path + +CI = Path(__file__).resolve().parent +DOWNLOAD = CI / 'download.sh' +ARCHIVES = CI / 'actions/tool-archives' +BODY = b'the pinned tool archive\n' +DIGEST = hashlib.sha256(BODY).hexdigest() + + +def run_download(scratch: Path, url: str, *, cached: bool = True, + extra_env: dict[str, str] | None = None) -> subprocess.CompletedProcess[str]: + environment = {**os.environ, 'NO_PROXY': '127.0.0.1', 'no_proxy': '127.0.0.1'} + environment.pop('WEBCPP_DOWNLOAD_CACHE', None) + environment.pop('WEBCPP_DOWNLOAD_OFFLINE', None) + if cached: + environment['WEBCPP_DOWNLOAD_CACHE'] = str(scratch / 'archive cache') + environment.update(extra_env or {}) + return subprocess.run(['bash', str(DOWNLOAD), url, DIGEST, str(scratch / 'output archive')], + capture_output=True, text=True, check=False, env=environment, + timeout=30) + + +def fixture(scratch: Path) -> Path: + source = scratch / 'source archive' + source.write_bytes(BODY) + return source + + +def cached_file(scratch: Path, body: bytes) -> Path: + path = scratch / 'archive cache' / DIGEST + path.parent.mkdir() + path.write_bytes(body) + return path + + +def test_a_cache_miss_publishes_the_archive_by_its_digest(scratch: Path) -> None: + result = run_download(scratch, fixture(scratch).as_uri()) + assert result.returncode == 0, result.stderr + assert (scratch / 'output archive').read_bytes() == BODY + assert (scratch / 'archive cache' / DIGEST).is_file() + assert (scratch / 'archive cache' / DIGEST).read_bytes() == BODY + assert sorted(path.name for path in (scratch / 'archive cache').iterdir()) == [DIGEST] + + +def test_a_cache_hit_works_offline_and_returns_an_independent_copy(scratch: Path) -> None: + archive = cached_file(scratch, BODY) + result = run_download(scratch, (scratch / 'offline').as_uri()) + assert result.returncode == 0, result.stderr + output = scratch / 'output archive' + assert output.read_bytes() == BODY + output.write_bytes(b'the installer may modify or remove its input') + assert archive.read_bytes() == BODY + + +def test_a_corrupt_cache_entry_is_replaced_from_the_verified_download(scratch: Path) -> None: + archive = cached_file(scratch, b'corrupt') + result = run_download(scratch, fixture(scratch).as_uri()) + assert result.returncode == 0, result.stderr + assert archive.read_bytes() == BODY + assert (scratch / 'output archive').read_bytes() == BODY + + +def test_a_corrupt_offline_entry_leaves_neither_cache_nor_output(scratch: Path) -> None: + archive = cached_file(scratch, b'corrupt') + output = scratch / 'output archive' + output.write_bytes(b'an earlier attempt') + result = run_download(scratch, (scratch / 'offline').as_uri()) + assert result.returncode == 1, result.stderr + assert not archive.exists() + assert not output.exists() + assert not list(scratch.glob('output archive.*')) + assert not list(archive.parent.iterdir()) + + +class PartialServer: + """Pauses after a partial HTTP body, then drops every transfer before Content-Length.""" + + def __init__(self) -> None: + self.partial = threading.Event() + self.release = threading.Event() + self.stopped = threading.Event() + self.listener = socket.create_server(('127.0.0.1', 0)) + self.listener.settimeout(0.1) + self.address = self.listener.getsockname() + self.thread = threading.Thread(target=self.serve, daemon=True) + self.thread.start() + + @property + def url(self) -> str: + return f'http://127.0.0.1:{self.address[1]}/archive' + + def serve(self) -> None: + while not self.stopped.is_set(): + try: + connection, _ = self.listener.accept() + except socket.timeout: + continue + except OSError: + return + with connection: + connection.settimeout(5) + connection.recv(65536) + connection.sendall(b'HTTP/1.1 200 OK\r\nContent-Length: 1000000\r\n' + b'Connection: close\r\n\r\n' + b'x' * 65536) + self.partial.set() + self.release.wait(5) + + def close(self) -> None: + self.stopped.set() + self.release.set() + self.listener.close() + self.thread.join(timeout=5) + assert not self.thread.is_alive() + + +def test_a_failed_transfer_never_exposes_partial_output_or_cache(scratch: Path) -> None: + server = PartialServer() + output = scratch / 'output archive' + cache = scratch / 'archive cache' + environment = {**os.environ, 'WEBCPP_DOWNLOAD_CACHE': str(cache), + 'WEBCPP_DOWNLOAD_OFFLINE': '', 'NO_PROXY': '127.0.0.1', 'no_proxy': '127.0.0.1'} + process = subprocess.Popen(['bash', str(DOWNLOAD), server.url, DIGEST, str(output)], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + env=environment, start_new_session=os.name != 'nt') + try: + assert server.partial.wait(10), 'curl did not reach the local HTTP fixture' + deadline = time.monotonic() + 5 + while not any(path.stat().st_size for path in scratch.glob('output archive*')): + assert time.monotonic() < deadline, 'curl did not start writing the fixture' + time.sleep(0.01) + assert not output.exists(), 'an unfinished download was visible at its final path' + assert not (cache / DIGEST).exists(), 'an unfinished archive entered the cache' + server.release.set() + _, error = process.communicate(timeout=30) + assert process.returncode == 1, error + assert not output.exists() + assert not list(scratch.glob('output archive.*')) + assert cache.is_dir() + assert not list(cache.iterdir()) + finally: + server.close() + if process.poll() is None: + if os.name == 'nt': + process.kill() + else: + os.killpg(process.pid, signal.SIGKILL) + process.communicate(timeout=5) + + +def test_a_download_bounds_connections_transfers_and_retries(scratch: Path) -> None: + # Wrap real curl only to observe its arguments; it still transfers the fixture's bytes. + curl = shutil.which('curl') + assert curl is not None + programs = scratch / 'programs' + programs.mkdir() + arguments = scratch / 'curl arguments' + wrapper = programs / 'curl' + wrapper.write_text('#!/bin/sh\nprintf "%s\\n" "$@" > "$CURL_ARGUMENTS"\n' + f'exec {shlex.quote(curl)} "$@"\n') + wrapper.chmod(0o755) + result = run_download(scratch, fixture(scratch).as_uri(), extra_env={ + 'PATH': f'{programs}{os.pathsep}{os.environ["PATH"]}', + 'CURL_ARGUMENTS': str(arguments), + }) + assert result.returncode == 0, result.stderr + words = arguments.read_text().splitlines() + for option, upper_bound in (('--connect-timeout', 60), ('--max-time', 900), + ('--retry-max-time', 1800), ('--retry', 5)): + assert option in words, f'curl has no {option} bound: {words}' + assert 0 < int(words[words.index(option) + 1]) <= upper_bound + assert '--retry-all-errors' in words + assert (scratch / 'output archive').read_bytes() == BODY + + +def test_a_wrong_download_digest_never_enters_the_cache(scratch: Path) -> None: + source = fixture(scratch) + source.write_bytes(b'not the pinned bytes') + result = run_download(scratch, source.as_uri()) + assert result.returncode == 1, result.stderr + assert not (scratch / 'output archive').exists() + assert (scratch / 'archive cache').is_dir() + assert not list((scratch / 'archive cache').iterdir()) + assert not list(scratch.glob('output archive.*')) + + +def test_uncached_downloads_keep_their_original_contract(scratch: Path) -> None: + source = fixture(scratch) + result = run_download(scratch, source.as_uri(), cached=False) + assert result.returncode == 0, result.stderr + assert (scratch / 'output archive').read_bytes() == BODY + source.unlink() + result = run_download(scratch, source.as_uri(), cached=False) + assert result.returncode == 1, result.stderr + assert not (scratch / 'output archive').exists() + assert not (scratch / 'archive cache').exists() + assert not list(scratch.glob('output archive.*')) + + +def test_offline_mode_rejects_missing_and_corrupt_entries_without_curl(scratch: Path) -> None: + source = fixture(scratch) + programs = scratch / 'programs' + programs.mkdir() + called = scratch / 'curl was called' + wrapper = programs / 'curl' + wrapper.write_text('#!/bin/sh\nprintf called > "$CURL_CALLED"\nexit 99\n') + wrapper.chmod(0o755) + environment = {'WEBCPP_DOWNLOAD_OFFLINE': '1', 'CURL_CALLED': str(called), + 'PATH': f'{programs}{os.pathsep}{os.environ["PATH"]}'} + for contents in (None, b'corrupt'): + cache = scratch / 'archive cache' + cache.mkdir(exist_ok=True) + if contents is not None: + (cache / DIGEST).write_bytes(contents) + result = run_download(scratch, source.as_uri(), extra_env=environment) + assert result.returncode == 1, result.stderr + assert not called.exists(), 'offline mode invoked curl' + assert 'offline' in result.stderr.lower(), result.stderr + assert not (scratch / 'output archive').exists() + assert not list(cache.iterdir()) + (cache / DIGEST).write_bytes(BODY) + result = run_download(scratch, source.as_uri(), extra_env=environment) + assert result.returncode == 0, result.stderr + assert (scratch / 'output archive').read_bytes() == BODY + assert not called.exists() + + +def action_tree(scratch: Path) -> None: + assert (ARCHIVES / 'cache.sh').is_file(), 'shared archive preparation helper is missing' + directory = scratch / 'tools/ci' + shutil.copytree(ARCHIVES, directory / 'actions/tool-archives') + for name in ('download.sh', 'helpers.sh'): + shutil.copy2(CI / name, directory / name) + (directory / 'environments.json').write_text('{"fixture": 1}\n') + for tool in ('wasi-sdk', 'wasmtime', 'wit-bindgen', 'wasi-wit', 'mrdocs', 'chrome'): + action = directory / 'actions' / tool + action.mkdir() + (action / 'action.yml').write_text(f'name: {tool}\n') + (action / 'install.sh').write_text( + '#!/bin/bash\nset -euo pipefail\n' + 'bash tools/ci/download.sh "$ARCHIVE_URL" "$ARCHIVE_DIGEST" "$RUNNER_TEMP/input"\n' + 'printf "%s\\n" "$WEBCPP_DOWNLOAD_CACHE" >> "$GITHUB_PATH"\n' + 'printf "PRODUCT=%s\\n" "${WEBCPP_CHROME_PRODUCT-}" >> "$GITHUB_ENV"\n' + 'rm "$RUNNER_TEMP/input"\n') + + +def run_action(scratch: Path, operation: str, tool: str, variant: str = '', + **variables: str) -> subprocess.CompletedProcess[str]: + environment = {**os.environ, 'RUNNER_OS': 'Linux', 'RUNNER_ARCH': 'X64', + 'RUNNER_TEMP': str(scratch), 'GITHUB_PATH': str(scratch / 'github-path'), + 'GITHUB_ENV': str(scratch / 'github-env'), + 'GITHUB_OUTPUT': str(scratch / 'github-output'), + 'WEBCPP_PREPARE_ENVIRONMENT': ''} + environment.pop('WEBCPP_DOWNLOAD_OFFLINE', None) + environment.update(variables) + return subprocess.run(['bash', 'tools/ci/actions/tool-archives/cache.sh', operation, + tool, variant], cwd=scratch, capture_output=True, text=True, + check=False, env=environment, timeout=30) + + +def cache_outputs(scratch: Path, tool: str, variant: str = '', **variables: str) -> dict[str, str]: + (scratch / 'github-output').write_text('') + result = run_action(scratch, 'key', tool, variant, **variables) + assert result.returncode == 0, result.stderr + return dict(line.split('=', 1) for line in (scratch / 'github-output').read_text().splitlines()) + + +def test_tool_keys_track_pins_platform_variant_and_bundle_manifest(scratch: Path) -> None: + action_tree(scratch) + original = cache_outputs(scratch, 'wasmtime') + assert original == cache_outputs(scratch, 'wasmtime') + assert original['directory'] != cache_outputs(scratch, 'wasi-sdk')['directory'] + assert original['key'] != cache_outputs(scratch, 'wasmtime', RUNNER_OS='macOS')['key'] + assert original['key'] != cache_outputs(scratch, 'wasmtime', RUNNER_ARCH='ARM64')['key'] + shell = cache_outputs(scratch, 'chrome', 'chrome-headless-shell') + chrome = cache_outputs(scratch, 'chrome', 'chrome') + assert shell['key'] != chrome['key'] and shell['directory'] != chrome['directory'] + other = scratch / 'tools/ci/actions/wasi-sdk/install.sh' + other.write_text(other.read_text() + '# an unrelated tool changed\n') + assert original == cache_outputs(scratch, 'wasmtime') + installer = scratch / 'tools/ci/actions/wasmtime/install.sh' + installer.write_text(installer.read_text() + '# the pinned tool changed\n') + revised = cache_outputs(scratch, 'wasmtime') + assert original['key'] != revised['key'] + (scratch / 'tools/ci/environments.json').write_text('{"fixture": 2}\n') + assert revised['key'] != cache_outputs(scratch, 'wasmtime')['key'] + + +def test_the_installer_runs_and_exports_its_environment_on_cache_hits(scratch: Path) -> None: + action_tree(scratch) + source = fixture(scratch) + variables = {'ARCHIVE_URL': source.as_uri(), 'ARCHIVE_DIGEST': DIGEST} + for tool, variant in (('wasmtime', ''), ('chrome', 'chrome')): + source.write_bytes(BODY) + outputs = cache_outputs(scratch, tool, variant) + for offline in (False, True): + if offline: + source.unlink() + for output in ('github-path', 'github-env'): + (scratch / output).write_text('') + result = run_action(scratch, 'install', tool, variant, **variables, + WEBCPP_PREPARE_ENVIRONMENT='0' if offline else '1') + assert result.returncode == 0, result.stderr + assert (Path(outputs['directory']) / DIGEST).read_bytes() == BODY + assert (scratch / 'github-path').read_text() == outputs['directory'] + '\n' + assert (scratch / 'github-env').read_text() == f'PRODUCT={variant}\n' + assert not (scratch / 'input').exists() + + +def test_linux_consumers_require_prepared_archives(scratch: Path) -> None: + for state in ('missing', 'corrupt'): + root = scratch / state + action_tree(root) + source = fixture(root) + outputs = cache_outputs(root, 'wasmtime') + cache = Path(outputs['directory']) + if state == 'corrupt': + cache.mkdir(parents=True) + (cache / DIGEST).write_bytes(b'corrupt') + result = run_action(root, 'install', 'wasmtime', ARCHIVE_URL=source.as_uri(), + ARCHIVE_DIGEST=DIGEST) + assert result.returncode == 1, result.stderr + assert 'offline' in result.stderr.lower(), result.stderr + assert not (root / 'github-path').exists() + assert not list(cache.iterdir()) + + +def test_other_hosts_can_download_their_own_pinned_archives(scratch: Path) -> None: + action_tree(scratch) + source = fixture(scratch) + result = run_action(scratch, 'install', 'wasmtime', RUNNER_OS='macOS', RUNNER_ARCH='ARM64', + ARCHIVE_URL=source.as_uri(), ARCHIVE_DIGEST=DIGEST) + assert result.returncode == 0, result.stderr + outputs = cache_outputs(scratch, 'wasmtime', RUNNER_OS='macOS', RUNNER_ARCH='ARM64') + assert (Path(outputs['directory']) / DIGEST).read_bytes() == BODY + + +def test_unknown_tools_and_unsafe_variants_are_rejected(scratch: Path) -> None: + action_tree(scratch) + for tool, variant in (('../wasmtime', ''), ('unknown', ''), ('wasmtime', 'chrome'), + ('chrome', '../chrome'), ('chrome', '')): + result = run_action(scratch, 'key', tool, variant) + assert result.returncode == 2, (tool, variant, result.stderr) + assert not (scratch / 'github-output').exists() + assert not (scratch / '.local').exists() + + +CASES: list[Callable[[Path], None]] = [ + test_a_cache_miss_publishes_the_archive_by_its_digest, + test_a_cache_hit_works_offline_and_returns_an_independent_copy, + test_a_corrupt_cache_entry_is_replaced_from_the_verified_download, + test_a_corrupt_offline_entry_leaves_neither_cache_nor_output, + test_a_failed_transfer_never_exposes_partial_output_or_cache, + test_a_download_bounds_connections_transfers_and_retries, + test_a_wrong_download_digest_never_enters_the_cache, + test_uncached_downloads_keep_their_original_contract, + test_offline_mode_rejects_missing_and_corrupt_entries_without_curl, + test_tool_keys_track_pins_platform_variant_and_bundle_manifest, + test_the_installer_runs_and_exports_its_environment_on_cache_hits, + test_linux_consumers_require_prepared_archives, + test_other_hosts_can_download_their_own_pinned_archives, + test_unknown_tools_and_unsafe_variants_are_rejected, +] + + +def main(argv: list[str]) -> int: + unknown = set(argv) - {case.__name__ for case in CASES} + if unknown: + print(f'download_cache_test: unknown cases: {", ".join(sorted(unknown))}', file=sys.stderr) + return 2 + for case in CASES: + if argv and case.__name__ not in argv: + continue + with tempfile.TemporaryDirectory(prefix='webcpp archive cache ') as scratch: + case(Path(scratch)) + print(f'{case.__name__}: ok') + print('download_cache_test: ok') + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/ci/environment.py b/tools/ci/environment.py new file mode 100644 index 00000000..be49d4ee --- /dev/null +++ b/tools/ci/environment.py @@ -0,0 +1,329 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +"""Prepare and consume immutable Linux-X64 CI images and tool archives. + +Normal jobs only pull checked digests. The explicit preparation workflow builds +candidates, verifies them with anonymous registry access, and emits a manifest +for review. Tool images hold archives only; restoration never executes them. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +from typing import TypedDict + +ROOT = Path(__file__).resolve().parents[2] +PINS = ROOT / 'tools/ci/environments.json' +PACKAGE = 'ghcr.io/webcpporg/ci-environment' +HEX = re.compile(r'[0-9a-f]{64}') +IMAGE = re.compile(re.escape(PACKAGE) + r'@sha256:[0-9a-f]{64}') +TOOLS = ('wasi-sdk', 'wasmtime', 'wit-bindgen', 'wasi-wit', 'mrdocs', 'chrome') +PREPARE = 'run the trusted prepare-environments workflow and promote its verified manifest' + + +class Failure(Exception): + """A missing, stale or unusable prepared environment.""" + + +class Artifact(TypedDict): + image: str + recipe: str + archives: list[str] + source: str + + +def identity(tool: str = '', variant: str = '') -> str: + """The manifest key, restricted to the supported Linux-X64 artifacts.""" + if tool not in ('', *TOOLS) or (tool != 'chrome' and variant) or ( + tool == 'chrome' and variant not in ('chrome', 'chrome-headless-shell')): + raise Failure(f'unsupported tool/variant: {tool!r}/{variant!r}') + return '-'.join(part for part in (tool or 'native', variant, 'linux-x64') if part) + + +def digest(path: Path) -> str: + """SHA-256 of a file, streamed so SDK archives need no matching RAM allocation.""" + value = hashlib.sha256() + with path.open('rb') as source: + for chunk in iter(lambda: source.read(1024 * 1024), b''): + value.update(chunk) + return value.hexdigest() + + +def recipe(tool: str = '', variant: str = '') -> str: + """Bind the artifact to its recipe and platform, excluding the output manifest.""" + key = identity(tool, variant) + paths = ['tools/ci/container/Dockerfile'] if not tool else [ + f'tools/ci/actions/{tool}/install.sh', 'tools/ci/download.sh', + 'tools/ci/helpers.sh'] + inputs = [(name, digest(ROOT / name)) for name in paths] + return hashlib.sha256(json.dumps([1, key, inputs], separators=(',', ':')).encode()).hexdigest() + + +def checked(value: object, tool: str = '', variant: str = '') -> Artifact: + """Reject mutable names, stale recipes and malformed manifests before Docker runs.""" + if not isinstance(value, dict) or not isinstance(value.get('image'), str) or not ( + IMAGE.fullmatch(value['image'])): + raise Failure(f'invalid immutable image for {identity(tool, variant)}; {PREPARE}') + if value.get('recipe') != recipe(tool, variant): + raise Failure(f'stale recipe for {identity(tool, variant)}; {PREPARE}') + archives = value.get('archives') + if (not isinstance(archives, list) or any(not isinstance(item, str) or not HEX.fullmatch(item) + for item in archives) + or len(set(archives)) != len(archives) or bool(archives) != bool(tool)): + raise Failure('invalid archive hashes in prepared environment') + source = value.get('source') + if not isinstance(source, str) or re.fullmatch(r'[0-9a-f]{40}', source) is None: + raise Failure('prepared environment lacks its source commit') + return {'image': value['image'], 'recipe': value['recipe'], 'archives': archives, + 'source': source} + + +def pinned(tool: str = '', variant: str = '') -> Artifact: + """Read and validate the selected artifact; a missing pin never triggers a build.""" + try: + document = json.loads(PINS.read_text()) + if document['schema'] != 1: + raise ValueError('unsupported manifest schema') + return checked(document['artifacts'][identity(tool, variant)], tool, variant) + except (OSError, ValueError, KeyError, TypeError) as error: + raise Failure(f'no usable prepared environment in {PINS}: {error}; {PREPARE}') from error + + +def docker(*arguments: str, capture: bool = False) -> subprocess.CompletedProcess: + """Run Docker with a finite bound and preserve its diagnostic on failure.""" + return subprocess.run(['docker', *arguments], cwd=ROOT, check=False, text=True, + capture_output=capture, timeout=1200) + + +def require(*arguments: str) -> None: + if docker(*arguments).returncode: + raise Failure(f'docker {arguments[0]} failed; {PREPARE}') + + +def acquire(artifact: Artifact) -> str: + """Pull an absent immutable reference, never a mutable tag or a local build.""" + image = artifact['image'] + if docker('image', 'inspect', image, capture=True).returncode: + require('pull', image) + return image + + +def native() -> str: + """The checked image for the two native container lanes.""" + return acquire(pinned()) + + +def verify_archives(directory: Path, expected: list[str]) -> None: + """Validate the complete set before exposing any bundle file to an installer.""" + if sorted(path.name for path in directory.iterdir()) != sorted(expected): + raise Failure('prepared bundle has missing or unexpected archives') + for name in expected: + path = directory / name + if path.is_symlink() or not path.is_file() or digest(path) != name: + raise Failure(f'prepared bundle SHA-256 mismatch or non-regular file: {name}') + + +def restore(artifact: Artifact, cache: Path) -> None: + """Copy a stopped image's archives, validate all of them, then install atomically.""" + image = acquire(artifact) + created = docker('create', image, '/unused', capture=True) + if created.returncode: + raise Failure(f'cannot create archive container: {created.stderr}') + container = created.stdout.strip() + if re.fullmatch(r'[a-zA-Z0-9_-]+', container) is None: + raise Failure('docker create returned no container identifier') + try: + with tempfile.TemporaryDirectory(prefix='webcpp-archives-') as temporary: + stage = Path(temporary) + require('cp', f'{container}:/archives/.', str(stage)) + verify_archives(stage, artifact['archives']) + cache.mkdir(parents=True, exist_ok=True) + for name in artifact['archives']: + with tempfile.NamedTemporaryFile(dir=cache, prefix='.prepared-', delete=False) as f: + pending = Path(f.name) + try: + shutil.copyfile(stage / name, pending) + os.replace(pending, cache / name) + finally: + pending.unlink(missing_ok=True) + finally: + require('rm', '-f', container) + + +def restore_tool(tool: str, variant: str, cache: Path) -> None: + identity(tool, variant) + if tool == 'chrome': + print('environment: Chrome uses its official download and verified archive cache') + return + host = (os.environ.get('RUNNER_OS'), os.environ.get('RUNNER_ARCH')) + if host != ('Linux', 'X64'): + print(f'environment: {host} has no published bundle; using checked upstream downloads') + return + restore(pinned(tool, variant), cache) + + +def write_manifest(path: Path, artifacts: dict[str, Artifact]) -> None: + """Write a generated pin manifest with stable formatting.""" + path.parent.mkdir(parents=True, exist_ok=True) + document = {'_comment': 'Generated by tools/ci/environment.py; do not edit.', + 'schema': 1, 'artifacts': artifacts} + path.write_text(json.dumps(document, indent=2, sort_keys=True) + '\n') + + +def smoke_native(image: str) -> None: + """Compile and run C++20 with both pinned compilers inside the isolated image.""" + require('run', '--rm', '--network', 'none', image, 'bash', '-euc', + 'printf "%s\\n" "#include " ' + '"static_assert(std::same_as); int main() {}" > /tmp/smoke.cpp; ' + 'for cc in g++-14 clang++-18; do ' + '$cc --version; $cc -std=c++20 /tmp/smoke.cpp -o /tmp/smoke; /tmp/smoke; done; ' + 'python3 --version; cmake --version; perl -v') + + +def publish(tool: str, variant: str, cache: Path | None, output: Path) -> None: + """Publish only from an explicitly dispatched organization preparation workflow.""" + if (os.environ.get('GITHUB_EVENT_NAME') != 'workflow_dispatch' + or os.environ.get('GITHUB_REPOSITORY') != 'webcpporg/webcpp' + or os.environ.get('WEBCPP_PREPARE_ENVIRONMENT') != '1'): + raise Failure('publication requires a trusted workflow_dispatch in webcpporg/webcpp') + if tool == 'chrome': + raise Failure('Chrome binaries are not published; use the official download cache') + source = os.environ.get('GITHUB_SHA', '') + if re.fullmatch(r'[0-9a-f]{40}', source) is None: + raise Failure('publication requires GITHUB_SHA of the reviewed source') + key = identity(tool, variant) + fingerprint = recipe(tool, variant) + tag = f'{PACKAGE}:{key}-{fingerprint}' + archives: list[str] = [] + labels = ['--label', 'org.opencontainers.image.source=https://github.com/webcpporg/webcpp', + '--label', f'org.opencontainers.image.revision={source}'] + if tool: + if cache is None: + raise Failure('tool publication requires --cache') + archives = sorted(path.name for path in cache.iterdir()) + if not archives or any(HEX.fullmatch(name) is None for name in archives): + raise Failure('tool cache must contain only SHA-256 named archives') + verify_archives(cache, archives) + with tempfile.TemporaryDirectory(prefix='webcpp-bundle-') as temporary: + context = Path(temporary) + shutil.copytree(cache, context / 'archives') + (context / 'Dockerfile').write_text('FROM scratch\nCOPY archives/ /archives/\n') + require('build', '--platform', 'linux/amd64', *labels, '--tag', tag, str(context)) + else: + require('build', '--platform', 'linux/amd64', *labels, '--tag', tag, + str(ROOT / 'tools/ci/container')) + smoke_native(tag) + require('push', tag) + result = docker('image', 'inspect', '--format', '{{json .RepoDigests}}', tag, capture=True) + if result.returncode: + raise Failure(f'cannot inspect pushed digest: {result.stderr}') + images = json.loads(result.stdout) + references = [image for image in images if isinstance(image, str) and IMAGE.fullmatch(image)] + if len(references) != 1: + raise Failure('publication did not resolve to one immutable package digest') + artifact: Artifact = {'image': references[0], 'recipe': fingerprint, + 'archives': archives, 'source': source} + write_manifest(output, {key: checked(artifact, tool, variant)}) + + +def verify_candidate(candidate: Path, tool: str, variant: str, cache: Path | None) -> None: + """Prove anonymous pull and offline installation before promoting a candidate.""" + document = json.loads(candidate.read_text()) + artifact = checked(document['artifacts'][identity(tool, variant)], tool, variant) + previous = os.environ.get('DOCKER_CONFIG') + try: + with tempfile.TemporaryDirectory(prefix='webcpp-anonymous-') as temporary: + os.environ['DOCKER_CONFIG'] = temporary + # Always contact the registry, even if an image is already in the daemon cache. + require('pull', artifact['image']) + if tool: + if cache is None: + raise Failure('tool verification requires --cache') + restore(artifact, cache) + installer_env = {**os.environ, 'WEBCPP_DOWNLOAD_CACHE': str(cache.resolve()), + 'WEBCPP_DOWNLOAD_OFFLINE': '1', 'WEBCPP_CHROME_PRODUCT': variant} + result = subprocess.run(['bash', f'tools/ci/actions/{tool}/install.sh'], + cwd=ROOT, env=installer_env, check=False, timeout=600) + if result.returncode: + raise Failure(f'offline installation failed for {tool}/{variant}') + else: + smoke_native(artifact['image']) + finally: + if previous is None: + os.environ.pop('DOCKER_CONFIG', None) + else: + os.environ['DOCKER_CONFIG'] = previous + + +def merge(directory: Path, output: Path) -> None: + """Assemble the complete verified workflow artifacts; never invent missing pins.""" + selections = [('', ''), *((tool, '') for tool in TOOLS if tool != 'chrome')] + expected = {identity(tool, variant): (tool, variant) for tool, variant in selections} + artifacts: dict[str, Artifact] = {} + for path in sorted(directory.glob('*.json')): + document = json.loads(path.read_text()) + if document.get('schema') != 1: + raise Failure(f'unsupported manifest schema: {path}') + for key, value in document['artifacts'].items(): + if key not in expected or key in artifacts: + raise Failure(f'unexpected or duplicate environment: {key}') + artifacts[key] = checked(value, *expected[key]) + missing = sorted(expected.keys() - artifacts.keys()) + if missing: + raise Failure('missing prepared environments: ' + ', '.join(missing)) + write_manifest(output, artifacts) + + +def main(arguments: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('command', + choices=('recipe', 'native', 'restore-tool', 'publish', 'verify', 'merge')) + parser.add_argument('--tool', default='') + parser.add_argument('--variant', default='') + parser.add_argument('--cache', type=Path) + parser.add_argument('--out', type=Path) + parser.add_argument('--candidate', type=Path) + parser.add_argument('--directory', type=Path) + args = parser.parse_args(arguments) + try: + if args.command == 'recipe': + print(recipe(args.tool, args.variant)) + elif args.command == 'native': + print(native()) + elif args.command == 'restore-tool': + if not args.tool or args.cache is None: + raise Failure('restore-tool requires --tool and --cache') + restore_tool(args.tool, args.variant, args.cache) + elif args.command == 'publish': + if args.out is None: + raise Failure('publish requires --out') + publish(args.tool, args.variant, args.cache, args.out) + elif args.command == 'verify': + if args.candidate is None: + raise Failure('verify requires --candidate') + verify_candidate(args.candidate, args.tool, args.variant, args.cache) + elif args.command == 'merge': + if args.directory is None or args.out is None: + raise Failure('merge requires --directory and --out') + merge(args.directory, args.out) + return 0 + except (Failure, OSError, ValueError, KeyError, TypeError, subprocess.TimeoutExpired) as error: + print(f'environment.py: {error}', file=sys.stderr) + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/ci/environment_test.py b/tools/ci/environment_test.py new file mode 100644 index 00000000..11b94bb6 --- /dev/null +++ b/tools/ci/environment_test.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +"""Exercises the prepared-environment CLI through a controlled Docker boundary. + +The native lane must pull an immutable image and never build on a miss. Archive +restoration copies bytes without starting a container, checks all hashes before +publishing any file, and cleans the stopped container on every exit path. +""" +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +IMAGE = 'ghcr.io/webcpporg/ci-environment@sha256:' + 'a' * 64 +DOCKER = '''#!/usr/bin/env python3 +import json, os, pathlib, shutil, sys +args = sys.argv[1:] +with open(os.environ['DOCKER_LOG'], 'a') as output: + output.write(json.dumps(args) + '\\n') +if args[:3] == ['image', 'inspect', '--format']: + print(json.dumps(['ghcr.io/webcpporg/ci-environment@sha256:' + 'a' * 64])) + sys.exit(0) +if args[:2] == ['image', 'inspect']: + sys.exit(0 if os.environ.get('IMAGE_PRESENT') else 1) +if args[0] == 'pull': + config = os.environ.get('DOCKER_CONFIG', '') + if config: + pathlib.Path(os.environ['DOCKER_LOG'] + '.config').write_text( + json.dumps([config, sorted(p.name for p in pathlib.Path(config).iterdir())])) + sys.exit(int(os.environ.get('PULL_STATUS', '0'))) +if args[0] == 'create': + print('container-fixture') +elif args[0] == 'cp': + shutil.copytree(os.environ['ARCHIVES'], args[-1], dirs_exist_ok=True, symlinks=True) +elif args[0] == 'rm': + pass +elif args[0] in ('build', 'push', 'run'): + sys.exit(int(os.environ.get(args[0].upper() + '_STATUS', '0'))) +elif args[0] != 'pull': + sys.exit('unexpected Docker operation: ' + repr(args)) +''' + + +class EnvironmentTest(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory(prefix='webcpp environment ') + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + shutil.copytree(HERE, self.root / 'tools/ci', ignore=shutil.ignore_patterns('__pycache__')) + self.binary = self.root / 'bin' + self.binary.mkdir() + docker = self.binary / 'docker' + docker.write_text(DOCKER) + docker.chmod(0o755) + self.archives = self.root / 'archives' + self.archives.mkdir() + self.log = self.root / 'docker.log' + self.cache = self.root / 'cache' + self.env = {**os.environ, 'PATH': str(self.binary) + os.pathsep + os.environ['PATH'], + 'DOCKER_LOG': str(self.log), 'ARCHIVES': str(self.archives), + 'RUNNER_OS': 'Linux', 'RUNNER_ARCH': 'X64'} + self.env.pop('WEBCPP_PREPARE_ENVIRONMENT', None) + self.pins: dict = {'schema': 1, 'artifacts': {}} + + def run_cli(self, *arguments: str) -> subprocess.CompletedProcess: + return subprocess.run([sys.executable, 'tools/ci/environment.py', *arguments], + cwd=self.root, env=self.env, text=True, capture_output=True, + check=False, timeout=20) + + def pin(self, key: str, *, tool: str = '', variant: str = '', + archives: list[str] | None = None) -> None: + command = ['recipe', '--tool', tool, '--variant', variant] if tool else ['recipe'] + recipe = self.run_cli(*command) + self.assertEqual(recipe.returncode, 0, recipe.stderr) + self.pins['artifacts'][key] = {'image': IMAGE, 'recipe': recipe.stdout.strip(), + 'archives': archives or [], 'source': 'b' * 40} + self.write_pins() + + def write_pins(self) -> None: + (self.root / 'tools/ci/environments.json').write_text(json.dumps(self.pins)) + + def calls(self) -> list[list[str]]: + return [json.loads(line) for line in self.log.read_text().splitlines()] + + def blob(self, contents: bytes) -> str: + digest = hashlib.sha256(contents).hexdigest() + (self.archives / digest).write_bytes(contents) + return digest + + def test_native_pulls_digest_and_never_builds(self) -> None: + self.pin('native-linux-x64') + result = self.run_cli('native') + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.calls(), [['image', 'inspect', IMAGE], ['pull', IMAGE]]) + self.assertIn(IMAGE, result.stdout) + + def test_unavailable_native_image_fails_without_building(self) -> None: + self.pin('native-linux-x64') + self.env['PULL_STATUS'] = '1' + result = self.run_cli('native') + self.assertNotEqual(result.returncode, 0) + self.assertIn('prepare-environments', result.stderr) + self.assertFalse(any(call[0] == 'build' for call in self.calls())) + + def test_stale_recipe_or_mutable_tag_is_rejected_before_docker(self) -> None: + self.pin('native-linux-x64') + for field, value in [('recipe', '0' * 64), ('image', 'ubuntu:latest')]: + with self.subTest(field=field): + self.pin('native-linux-x64') + self.pins['artifacts']['native-linux-x64'][field] = value + self.write_pins() + result = self.run_cli('native') + self.assertNotEqual(result.returncode, 0) + self.assertFalse(self.log.exists()) + + def test_archives_are_verified_and_copied_without_execution(self) -> None: + digest = self.blob(b'archive bytes') + self.pin('wasi-sdk-linux-x64', tool='wasi-sdk', archives=[digest]) + result = self.run_cli('restore-tool', '--tool', 'wasi-sdk', '--cache', str(self.cache)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((self.cache / digest).read_bytes(), b'archive bytes') + self.assertEqual([call[0] for call in self.calls()], + ['image', 'pull', 'create', 'cp', 'rm']) + self.assertNotIn('run', [call[0] for call in self.calls()]) + + def test_bad_bundle_does_not_publish_any_blob_and_removes_container(self) -> None: + first = self.blob(b'first') + second = self.blob(b'second') + (self.archives / second).write_bytes(b'corrupt') + self.pin('wasi-wit-linux-x64', tool='wasi-wit', archives=[first, second]) + result = self.run_cli('restore-tool', '--tool', 'wasi-wit', '--cache', str(self.cache)) + self.assertNotEqual(result.returncode, 0) + self.assertIn('SHA-256', result.stderr) + self.assertFalse(self.cache.exists() and list(self.cache.iterdir())) + self.assertEqual(self.calls()[-1][0], 'rm') + + def test_symlink_in_bundle_is_rejected(self) -> None: + digest = hashlib.sha256(b'outside').hexdigest() + outside = self.root / 'outside' + outside.write_bytes(b'outside') + (self.archives / digest).symlink_to(outside) + self.pin('wasi-sdk-linux-x64', tool='wasi-sdk', archives=[digest]) + result = self.run_cli('restore-tool', '--tool', 'wasi-sdk', '--cache', str(self.cache)) + self.assertNotEqual(result.returncode, 0) + self.assertFalse(self.cache.exists() and list(self.cache.iterdir())) + + def test_other_hosts_explicitly_use_the_existing_upstream_path(self) -> None: + self.env.update(RUNNER_OS='macOS', RUNNER_ARCH='ARM64') + result = self.run_cli('restore-tool', '--tool', 'wasi-sdk', '--cache', str(self.cache)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('upstream', result.stdout) + self.assertFalse(self.log.exists()) + + def test_missing_pins_fail_closed_on_linux(self) -> None: + (self.root / 'tools/ci/environments.json').unlink(missing_ok=True) + result = self.run_cli('restore-tool', '--tool', 'wasi-sdk', '--cache', str(self.cache)) + self.assertNotEqual(result.returncode, 0) + self.assertIn('prepare-environments', result.stderr) + self.assertFalse(self.log.exists()) + + def test_publication_is_refused_in_pull_requests_and_forks(self) -> None: + for event, repository in [('pull_request', 'webcpporg/webcpp'), + ('workflow_dispatch', 'someone/webcpp')]: + with self.subTest(event=event, repository=repository): + self.env.update(GITHUB_EVENT_NAME=event, GITHUB_REPOSITORY=repository, + WEBCPP_PREPARE_ENVIRONMENT='1', GITHUB_SHA='b' * 40) + result = self.run_cli('publish', '--out', str(self.root / 'candidate.json')) + self.assertNotEqual(result.returncode, 0) + self.assertIn('trusted workflow_dispatch', result.stderr) + self.assertFalse(self.log.exists()) + + def test_manifest_promotion_requires_every_environment(self) -> None: + directory = self.root / 'candidates' + directory.mkdir() + output = self.root / 'promoted.json' + result = self.run_cli('merge', '--directory', str(directory), '--out', str(output)) + self.assertNotEqual(result.returncode, 0) + self.assertIn('missing prepared environments', result.stderr) + self.assertFalse(output.exists()) + + def test_workflow_separates_publication_from_pull_request_jobs(self) -> None: + workflow = HERE.parents[1] / '.github/workflows/prepare-environments.yml' + self.assertTrue(workflow.is_file(), 'explicit preparation workflow is missing') + text = workflow.read_text() + self.assertIn("github.event_name == 'workflow_dispatch'", text) + self.assertIn("github.repository == 'webcpporg/webcpp'", text) + self.assertIn('packages: write', text.split(' verify:', 1)[0]) + self.assertNotIn('packages: write', text.split(' verify:', 1)[1]) + self.assertIn('environment.py verify', text) + caller = (HERE.parents[1] / '.github/workflows/ci.yml').read_text() + self.assertIn('inputs.prepare-environment != true', caller) + self.assertIn('uses: ./.github/workflows/prepare-environments.yml', caller) + + def test_chrome_remains_on_the_official_download_path(self) -> None: + result = self.run_cli('restore-tool', '--tool', 'chrome', '--variant', 'chrome', + '--cache', str(self.cache)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('official', result.stdout) + self.assertFalse(self.log.exists()) + self.env.update(GITHUB_EVENT_NAME='workflow_dispatch', GITHUB_REPOSITORY='webcpporg/webcpp', + WEBCPP_PREPARE_ENVIRONMENT='1', GITHUB_SHA='b' * 40) + result = self.run_cli('publish', '--tool', 'chrome', '--variant', 'chrome', + '--cache', str(self.cache), + '--out', str(self.root / 'candidate.json')) + self.assertNotEqual(result.returncode, 0) + self.assertIn('not published', result.stderr) + self.assertFalse(self.log.exists()) + + def test_native_publication_smokes_before_push_and_records_digest(self) -> None: + self.env.update(GITHUB_EVENT_NAME='workflow_dispatch', GITHUB_REPOSITORY='webcpporg/webcpp', + WEBCPP_PREPARE_ENVIRONMENT='1', GITHUB_SHA='b' * 40) + output = self.root / 'candidate.json' + result = self.run_cli('publish', '--out', str(output)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual([call[0] for call in self.calls()], ['build', 'run', 'push', 'image']) + value = json.loads(output.read_text())['artifacts']['native-linux-x64'] + self.assertEqual(value['image'], IMAGE) + self.assertEqual(value['source'], 'b' * 40) + self.assertEqual(value['archives'], []) + + def test_failed_smoke_never_pushes(self) -> None: + self.env.update(GITHUB_EVENT_NAME='workflow_dispatch', GITHUB_REPOSITORY='webcpporg/webcpp', + WEBCPP_PREPARE_ENVIRONMENT='1', GITHUB_SHA='b' * 40, RUN_STATUS='1') + output = self.root / 'candidate.json' + result = self.run_cli('publish', '--out', str(output)) + self.assertNotEqual(result.returncode, 0) + self.assertEqual([call[0] for call in self.calls()], ['build', 'run']) + self.assertFalse(output.exists()) + + def test_verification_pulls_with_empty_credentials_even_when_image_is_cached(self) -> None: + self.pin('native-linux-x64') + self.env['IMAGE_PRESENT'] = '1' + result = self.run_cli('verify', '--candidate', + str(self.root / 'tools/ci/environments.json')) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual([call[0] for call in self.calls()], ['pull', 'run']) + configuration, files = json.loads(Path(str(self.log) + '.config').read_text()) + self.assertEqual(files, []) + self.assertFalse(Path(configuration).exists()) + + def test_archive_cache_is_an_optional_optimization(self) -> None: + text = (HERE / 'actions/tool-archives/action.yml').read_text() + for name in ('Restore tool archives', 'Save tool archives'): + block = text.split(' - name: ' + name + '\n', 1)[1].split(' - name:', 1)[0] + self.assertIn('continue-on-error: true', block) + self.assertIn("steps.restore.outputs.cache-hit != 'true'", text) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/ci/environments.json b/tools/ci/environments.json new file mode 100644 index 00000000..805572f0 --- /dev/null +++ b/tools/ci/environments.json @@ -0,0 +1,53 @@ +{ + "_comment": "Generated by tools/ci/environment.py; do not edit.", + "artifacts": { + "mrdocs-linux-x64": { + "archives": [ + "9d96e42f303046fb0b221aa9071eabccc40b9683e0b7af2b02a929d15476ca6a" + ], + "image": "ghcr.io/webcpporg/ci-environment@sha256:bfc8d2a63423a662cc21dc7377bf1b794cff883aa52446372eab8ccdddbe8b4d", + "recipe": "1caf5163552b9ba131f4687f9321cf90a157ce02e411d8d3284faf3a63547bbf", + "source": "5b92b3b896ebaa0c0b9fd56a3c2d0bbf8fd63e42" + }, + "native-linux-x64": { + "archives": [], + "image": "ghcr.io/webcpporg/ci-environment@sha256:d97a1596cfd6b7b0c69b9285bfbe95d90b2324fed34b0108ff102e44ad90888e", + "recipe": "12e35220e73d085db6e4e6aa4fe840a58a885018600e5cb9cc976f41c5996ec3", + "source": "5b92b3b896ebaa0c0b9fd56a3c2d0bbf8fd63e42" + }, + "wasi-sdk-linux-x64": { + "archives": [ + "b761e3a0721dbae9c09a0059e5fdb2bf917d1b4a8a7b430fb3b5aafb0984b2c4" + ], + "image": "ghcr.io/webcpporg/ci-environment@sha256:b753ad1d3c1e5a437e65f55e967287211554db9b6ab5e02c0b471829b60c1f89", + "recipe": "605940eca683fa1f9da9d842779fcdd2825582e0315fc9f0da78196231a67b1e", + "source": "5b92b3b896ebaa0c0b9fd56a3c2d0bbf8fd63e42" + }, + "wasi-wit-linux-x64": { + "archives": [ + "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487", + "f1d5749fdf69bb9400562eba50f8f25f5cd800ef4b74300038b6f99ae7409674" + ], + "image": "ghcr.io/webcpporg/ci-environment@sha256:3823662eca2283c12601a4189e7adbe6c307ff011fc4f299e10b2e95cda10af0", + "recipe": "a154f6fe1adb7268d5c4f0c6a5e244166d3925fd74d3d125691709067a84209a", + "source": "5b92b3b896ebaa0c0b9fd56a3c2d0bbf8fd63e42" + }, + "wasmtime-linux-x64": { + "archives": [ + "685466455dd42a14774a86c36c8f2e45cbb9bd6d92a850139315df60a75498a5" + ], + "image": "ghcr.io/webcpporg/ci-environment@sha256:82c0aea55102da94e9931c6dc95448095f0627ab14a8c78aad10ae2236db8686", + "recipe": "3e46afc7303c53c2161bcc97ff2714fd6a0426aa61dac6cb85f4f56b33bb0101", + "source": "5b92b3b896ebaa0c0b9fd56a3c2d0bbf8fd63e42" + }, + "wit-bindgen-linux-x64": { + "archives": [ + "3e81cc6523729f7532b4aa7968648a04abf0c711b7d1677150e9121f4e6458fe" + ], + "image": "ghcr.io/webcpporg/ci-environment@sha256:9e4b762d83ae9bf098e28ef8a34a2e9f3f5ab473a7b997f91cc2f20114012aff", + "recipe": "436fd39c29f16fc56d136cad6ca2f829f984cf536a0abc83f53d8cf23049ad93", + "source": "5b92b3b896ebaa0c0b9fd56a3c2d0bbf8fd63e42" + } + }, + "schema": 1 +} diff --git a/tools/ci/matrix.py b/tools/ci/matrix.py index 1514bd51..320e6b5b 100755 --- a/tools/ci/matrix.py +++ b/tools/ci/matrix.py @@ -117,7 +117,6 @@ from __future__ import annotations import argparse -import hashlib import json import os import re @@ -125,6 +124,8 @@ import shutil import subprocess import sys + +import environment as prepared_environment from dataclasses import asdict, dataclass, field, replace from pathlib import Path @@ -169,24 +170,6 @@ # command line alone, never from the environment. EXTERNAL_VARIABLES = ('SECP256K1_ROOT', 'SECP256K1_EMSCRIPTEN_ROOT') -# The directory of the Dockerfile a container lane's image is built from, and the image, tagged -# with the start of the Dockerfile's SHA-256: an image of another Dockerfile is never taken for it. -# tools/ci/actions/container/install.sh tags the image it caches the same way. -CONTAINER_CONTEXT = ROOT / 'tools/ci/container' - - -def container_tag() -> str: - """The tag of the container lanes' image: webcpp-lane:<16 hex digits>, or the bare name when - the Dockerfile cannot be read, which then fails the build that needs it.""" - try: - digest = hashlib.sha256((CONTAINER_CONTEXT / 'Dockerfile').read_bytes()).hexdigest() - except OSError: - return 'webcpp-lane' - return f'webcpp-lane:{digest[:16]}' - - -CONTAINER_IMAGE = container_tag() - # The own lanes whose driver meets a browser, (library, lane), which the CI's chrome action gives # its pinned chrome-headless-shell, as CHROME: trystero's interop, natively and on emscripten, and # document's js, whose examples Playwright runs in Chrome, and the browser and @@ -828,29 +811,15 @@ def fresh_xml(out_dir: Path, name: str) -> Path: return xml -def container_image() -> None: - """Builds the image a container lane runs in, from CONTAINER_CONTEXT, with the network its - packages are installed from, unless an image of that tag is there: the CI's container action - loads the one it built once and cached.""" - try: - present = subprocess.run(['docker', 'image', 'inspect', CONTAINER_IMAGE], - capture_output=True, check=False).returncode == 0 - except OSError as error: - raise Failure(f'cannot run docker: {error.strerror}') from error - if present: - print(f'container: {CONTAINER_IMAGE} is there', flush=True) - return - command = ['docker', 'build', '--tag', CONTAINER_IMAGE, str(CONTAINER_CONTEXT)] - print(f'container: {shlex.join(command)}', flush=True) +def container_image() -> str: + """Obtain the pinned prepared image; normal lanes never build a missing image.""" try: - status = subprocess.run(command, cwd=ROOT, check=False).returncode - except OSError as error: - raise Failure(f'cannot run docker: {error.strerror}') from error - if status != 0: - raise Failure(f'{shlex.join(command)} exited {status}') + return prepared_environment.native() + except (prepared_environment.Failure, OSError, subprocess.TimeoutExpired) as error: + raise Failure(str(error)) from error -def contained(command: list[str], mounted: list[Path]) -> list[str]: +def contained(command: list[str], mounted: list[Path], image: str) -> list[str]: """command, whose first word is b2, run in the container image with no network but the loopback: b2 by its path, as the user who runs the lane, with ROOT, b2's prefix (the Boost action installs b2 and Boost's headers in one) and each directory of mounted at their own @@ -867,7 +836,7 @@ def contained(command: list[str], mounted: list[Path]) -> list[str]: for word in ('--volume', f'{directory}:{directory}')] return ['docker', 'run', '--rm', '--network', 'none', '--user', f'{os.getuid()}:{os.getgid()}', '--workdir', str(ROOT), *volumes, - CONTAINER_IMAGE, str(b2), *command[1:]] + image, str(b2), *command[1:]] def run_lane(lane: Lane, user_config: Path, out_dir: Path, extra: list[str]) -> int: @@ -884,8 +853,8 @@ def run_lane(lane: Lane, user_config: Path, out_dir: Path, extra: list[str]) -> xml = fresh_xml(out_dir, lane.lane) command = lane_command(lane, user_config, xml, extra) if lane.container: - container_image() - command = contained(command, [user_config.parent, xml.parent]) + image = container_image() + command = contained(command, [user_config.parent, xml.parent], image) status = run_b2(label, command) return recorded(label, lane.lane, xml, status) diff --git a/tools/ci/matrix_test.py b/tools/ci/matrix_test.py index 677da336..2921492e 100755 --- a/tools/ci/matrix_test.py +++ b/tools/ci/matrix_test.py @@ -22,15 +22,13 @@ library that needs libraries webcpp does not build say external, with the compilers to build them with, also through a library that uses one, `external` says whether a library needs them, or any library, and every job installs them by the actions of their names; an own lane whose driver -meets a browser has the pinned chrome-headless-shell; and a container lane builds its image of -the Dockerfile's tag unless it is there, which the container action restores, and runs its b2 -there with no network, or fails when the image does not build. Each +meets a browser has the pinned chrome-headless-shell; and a container lane pulls its checked +immutable image and runs its b2 there with no network, or fails when that image is unavailable. Each case runs the scratch superproject's own copy of matrix.py, with the fixture library demo, and browser_demo where it says so. Run with the names of some cases to run only those.""" from __future__ import annotations -import hashlib import json import os import re @@ -46,6 +44,7 @@ import harness import matrix +import environment as prepared_environment NATIVE = ['gcc-14', 'gcc-15', 'clang-18', 'clang-22', 'apple-clang', 'msvc-14.3', 'msvc-14.5'] @@ -1182,22 +1181,13 @@ def test_the_jobs_install_the_external_dependencies(_): assert 'emscripten: ${{ needs.plan.outputs.has-emscripten }}' in lint_secp256k1 -def test_a_container_lane_has_its_image_from_the_cache(_): - # The container job builds the image once per run, and caches it, before any lane: the lanes - # wait for it, and their container action restores the image of this Dockerfile before the - # lane runs, which then builds nothing. The plan says whether a container lane is planned. +def test_container_availability_does_not_block_other_lanes(_): + # A missing native image blocks only its own lanes; every other lane can start after plan. jobs = workflow_jobs() - plan = jobs['plan'] - assert 'has-container: ${{ steps.plan.outputs.has-container }}' in plan, plan - container_job = jobs['container'] - assert re.search(r'^ needs: plan$', container_job, re.MULTILINE), container_job - assert "if: needs.plan.outputs.has-container == 'true'" in container_job, container_job - assert len([step for step in job_steps(container_job) - if 'uses: ./tools/ci/actions/container' in step]) == 1, container_job + assert 'container' not in jobs, 'ordinary lanes still wait for an image builder' lanes_job = jobs['lanes'] - assert re.search(r'^ needs: \[plan, container\]$', lanes_job, re.MULTILINE), lanes_job - assert ("needs.container.result == 'success' || needs.container.result == 'skipped'" - in lanes_job), lanes_job + assert re.search(r'^ needs: plan$', lanes_job, re.MULTILINE), lanes_job + assert 'needs.container' not in lanes_job, lanes_job steps = job_steps(lanes_job) container = [index for index, step in enumerate(steps) if 'uses: ./tools/ci/actions/container' in step] @@ -1291,6 +1281,15 @@ def test_browser_contract_lanes_build_a_native_beast_peer(root): # A stand-in of docker: each call's words to docker.log, quoted as a shell reads them, one line # each; `image inspect` succeeds when STAND_IN_IMAGE_PRESENT is set, `build` builds nothing, and # `run` runs, on the host, the command after the image. +TEST_IMAGE = 'ghcr.io/webcpporg/ci-environment@sha256:' + 'a' * 64 + + +def pin_test_image(root: Path) -> None: + prepared_environment.write_manifest(root / 'tools/ci/environments.json', { + 'native-linux-x64': {'image': TEST_IMAGE, 'recipe': prepared_environment.recipe(), + 'source': 'b' * 40, 'archives': []}}) + + FAKE_DOCKER = r"""#!/usr/bin/env bash set -euo pipefail { printf '%q ' docker "$@"; printf '\n'; } >> "${STAND_IN_DOCKER_LOG}" @@ -1328,7 +1327,7 @@ def test_container_apt_get_retries_transient_failures(root): def test_a_container_lane_runs_b2_with_no_network(root): - # A container lane builds its image from tools/ci/container/Dockerfile, then runs the lane + # A container lane pulls its prepared Dockerfile image, then runs the lane # command's b2 by its path in it, as the user who runs the lane, with no network but the # loopback, the superproject and b2's prefix (the Boost action's, with Boost's headers) # mounted at their own paths, and the external dependencies' variables passed on. The XML is @@ -1336,7 +1335,7 @@ def test_a_container_lane_runs_b2_with_no_network(root): dockerfile = (matrix.ROOT / 'tools/ci/container/Dockerfile').read_text() assert re.search(r'^FROM ubuntu:24\.04@sha256:[0-9a-f]{64}$', dockerfile, re.MULTILINE), ( dockerfile) - # Its packages from Ubuntu's snapshot at one date, and its tag that of this Dockerfile. + # Its packages come from Ubuntu's snapshot at one date; the pin names this recipe. assert re.search(r'^ARG SNAPSHOT=\d{8}T\d{6}Z$', dockerfile, re.MULTILINE), dockerfile # Every package from the snapshot, ca-certificates included: each apt-get update and install # names it, and none reads the live archive. @@ -1346,8 +1345,7 @@ def test_a_container_lane_runs_b2_with_no_network(root): assert len(calls) == 4, calls assert all('--snapshot "${SNAPSHOT}"' in call for call in calls), calls assert re.search(r'install[^&]*--snapshot "\$\{SNAPSHOT\}" ca-certificates', code), code - digest = hashlib.sha256(dockerfile.encode()).hexdigest() - assert matrix.CONTAINER_IMAGE == f'webcpp-lane:{digest[:16]}', matrix.CONTAINER_IMAGE + pin_test_image(root) for package in ('g++-14', 'clang-18', 'python3', 'git', 'make', 'perl', 'cmake', 'pkg-config'): assert re.search(r'install\b[^&]*\s' + re.escape(package) + r'(?=\s|$)', code), ( package, code) @@ -1368,7 +1366,7 @@ def test_a_container_lane_runs_b2_with_no_network(root): for name in matrix.EXTERNAL_VARIABLES: environment.pop(name, None) environment.update(PATH=f'{tools}:{environment["PATH"]}', STAND_IN_DOCKER_LOG=str(log), - STAND_IN_IMAGE=matrix.CONTAINER_IMAGE, SECP256K1_ROOT='/somewhere') + STAND_IN_IMAGE=TEST_IMAGE, SECP256K1_ROOT='/somewhere') result = subprocess.run([sys.executable, str(root / 'tools/ci/matrix.py'), 'lane', json.dumps(entry), '--', '--build-dir=bin/lane'], cwd=root, env=environment, capture_output=True, text=True, check=False, @@ -1377,13 +1375,12 @@ def test_a_container_lane_runs_b2_with_no_network(root): b2 = Path(shutil.which('b2', path=environment['PATH']) or 'b2').resolve() resolved = root.resolve() calls = [shlex.split(line) for line in log.read_text().splitlines()] - # The image is built only when no image of this Dockerfile's tag is there. - assert calls[0] == ['docker', 'image', 'inspect', matrix.CONTAINER_IMAGE], calls - assert calls[1] == ['docker', 'build', '--tag', matrix.CONTAINER_IMAGE, - f'{resolved}/tools/ci/container'], calls + # Only an immutable registry pull is allowed when the image is absent. + assert calls[0] == ['docker', 'image', 'inspect', TEST_IMAGE], calls + assert calls[1] == ['docker', 'pull', TEST_IMAGE], calls assert len(calls) == 3 and calls[2][0] == 'docker', calls run_words = calls[2][1:] - image = run_words.index(matrix.CONTAINER_IMAGE) + image = run_words.index(TEST_IMAGE) options, command = run_words[:image], run_words[image + 1:] assert options[:4] == ['run', '--rm', '--network', 'none'], options assert ['--user', f'{os.getuid()}:{os.getgid()}'] == options[4:6], options @@ -1403,7 +1400,7 @@ def test_a_container_lane_runs_b2_with_no_network(root): version = matrix.major_version('clang++') system = 'darwin' if sys.platform == 'darwin' else 'linux' assert (resolved / f'bin/ci/clang-{system}-{version}.xml').is_file() - # With the image there, as the container action loads it from its cache, nothing is built. + # With the immutable image present, no pull or build is needed. log.unlink() result = subprocess.run([sys.executable, str(root / 'tools/ci/matrix.py'), 'lane', json.dumps(entry), '--', '--build-dir=bin/lane'], cwd=root, @@ -1423,7 +1420,8 @@ def test_a_container_lane_runs_b2_with_no_network(root): assert not log.exists(), log.read_text() -def test_a_container_lane_whose_image_does_not_build_fails(root): +def test_an_unavailable_container_image_fails_without_a_build(root): + pin_test_image(root) entry = host_lane(root) entry['container'] = True boost_only(root) @@ -1439,9 +1437,8 @@ def test_a_container_lane_whose_image_does_not_build_fails(root): json.dumps(entry)], cwd=root, env=environment, capture_output=True, text=True, check=False, timeout=harness.TIMEOUT) assert result.returncode == 1, (result.returncode, result.stdout[-2000:], result.stderr) - build = shlex.join(['docker', 'build', '--tag', matrix.CONTAINER_IMAGE, - f'{root.resolve()}/tools/ci/container']) - assert f'matrix.py: {build} exited 1' in result.stderr, result.stderr + assert 'docker pull failed' in result.stderr, result.stderr + assert 'prepare-environments' in result.stderr, result.stderr assert not (root / 'bin/ci').exists() or not list((root / 'bin/ci').iterdir()) @@ -1479,14 +1476,14 @@ def test_a_container_lane_whose_image_does_not_build_fails(root): test_a_lane_of_a_library_with_external_dependencies_says_so, test_whether_a_library_has_external_dependencies, test_the_jobs_install_the_external_dependencies, - test_a_container_lane_has_its_image_from_the_cache, + test_container_availability_does_not_block_other_lanes, test_asio_browser_lane_receives_chrome, test_a_browser_lane_has_the_pinned_chrome, test_host_tls_fixture_is_isolated_to_its_own_lane, test_browser_contract_lanes_build_a_native_beast_peer, test_container_apt_get_retries_transient_failures, test_a_container_lane_runs_b2_with_no_network, - test_a_container_lane_whose_image_does_not_build_fails, + test_an_unavailable_container_image_fails_without_a_build, ]