From 7e02ef8948a0c2a652968682069cdbded6432f86 Mon Sep 17 00:00:00 2001 From: Joseph Mearman Date: Thu, 26 Nov 2026 16:35:34 +0000 Subject: [PATCH] feat(tool-images): add a Rust tool image with cross-compilation tools A tool-cache image for linux/amd64 and linux/arm64 holding a pinned stable Rust toolchain with rustfmt, clippy and the standard libraries of the macOS, Linux musl and Windows gnullvm targets, and Zig, cargo-zigbuild and cargo-deny, each checked against its published checksum. It holds no Apple SDK and nothing of Microsoft's. Its zig adds -lunwind to a link that asks for LLVM's libunwind, which zig cc ignores and cargo-zigbuild does not translate, so the gnullvm targets link. The published tag is the Rust release followed by an image revision, since the other pins can change while the release does not. A workflow builds the image on both architectures, cross-compiles a crate with a C source for every target, checks each executable's headers (an Apple one loads nothing outside /usr/lib) and fails a change to the image that keeps its tag. Closes #273 --- .github/workflows/publish-tool-images.yml | 12 +- .github/workflows/rust-toolchain.yml | 76 +++++++++++ docs/build-and-test.md | 1 + docs/releases.md | 2 +- roles/github_runner_arc/README.md | 19 ++- scripts/ci/check_tool_image_tag.sh | 34 +++++ scripts/ci/tool_image_tag.sh | 21 ++++ tests/rust_toolchain/checks.sh | 60 +++++++++ tests/rust_toolchain/crate/Cargo.lock | 32 +++++ tests/rust_toolchain/crate/Cargo.toml | 12 ++ tests/rust_toolchain/crate/build.rs | 4 + tests/rust_toolchain/crate/c/answer.c | 5 + tests/rust_toolchain/crate/deny.toml | 3 + tests/rust_toolchain/crate/src/main.rs | 34 +++++ tests/rust_toolchain/inspect_binary.py | 140 +++++++++++++++++++++ tests/rust_toolchain/run.sh | 113 +++++++++++++++++ tests/unit/test_publish_tool_images.py | 12 ++ tests/unit/test_rust_toolchain_binaries.py | 110 ++++++++++++++++ tests/unit/test_rust_toolchain_zig_shim.py | 48 +++++++ tests/unit/test_tool_image_tag.py | 75 +++++++++++ tool-images/rust/Dockerfile | 77 ++++++++++++ tool-images/rust/zig.sh | 14 +++ 22 files changed, 894 insertions(+), 10 deletions(-) create mode 100644 .github/workflows/rust-toolchain.yml create mode 100755 scripts/ci/check_tool_image_tag.sh create mode 100755 scripts/ci/tool_image_tag.sh create mode 100755 tests/rust_toolchain/checks.sh create mode 100644 tests/rust_toolchain/crate/Cargo.lock create mode 100644 tests/rust_toolchain/crate/Cargo.toml create mode 100644 tests/rust_toolchain/crate/build.rs create mode 100644 tests/rust_toolchain/crate/c/answer.c create mode 100644 tests/rust_toolchain/crate/deny.toml create mode 100644 tests/rust_toolchain/crate/src/main.rs create mode 100755 tests/rust_toolchain/inspect_binary.py create mode 100755 tests/rust_toolchain/run.sh create mode 100644 tests/unit/test_rust_toolchain_binaries.py create mode 100644 tests/unit/test_rust_toolchain_zig_shim.py create mode 100644 tests/unit/test_tool_image_tag.py create mode 100644 tool-images/rust/Dockerfile create mode 100755 tool-images/rust/zig.sh diff --git a/.github/workflows/publish-tool-images.yml b/.github/workflows/publish-tool-images.yml index 888aae71..21b2cf34 100644 --- a/.github/workflows/publish-tool-images.yml +++ b/.github/workflows/publish-tool-images.yml @@ -1,6 +1,6 @@ name: Publish tool images -# Builds the reference images in tool-images/ (the tool-cache and system-library capability images, see the ARC role README's Capabilities section, and the build runner image, the stock runner image with a C toolchain) for linux/amd64 and linux/arm64 and pushes them to this repository owner's GitHub Container Registry namespace, as ghcr.io//github-runner-toolcache-, ghcr.io//github-runner-sysroot- and ghcr.io//github-runner-runner-, each tagged with the version its Dockerfile pins (its ARG _VERSION default; for the build runner image, the runner version it extends). A version tag that already exists is left alone, so a published version never changes under anyone pinning it and a run publishes only the images whose pinned version is new. The job summary lists each pushed image by digest, the reference to pin in a capability or as a runner image. A build runner entry with a runner_id builds the same Dockerfile with RUNNER_UID and RUNNER_GID set to it and tags it -uid: the runner user at that id, for a fleet whose nodes give the stock id (1001) to an account of their own and reserve this one for the runner (tool-images/build/Dockerfile says why the id reaches the nodes). Each entry's digest artifacts are named with the architecture before the tag, so one tag's download pattern never matches another's artifacts. +# Builds the reference images in tool-images/ (the tool-cache and system-library capability images, see the ARC role README's Capabilities section, and the build runner image, the stock runner image with a C toolchain) for linux/amd64 and linux/arm64 and pushes them to this repository owner's GitHub Container Registry namespace, as ghcr.io//github-runner-toolcache-, ghcr.io//github-runner-sysroot- and ghcr.io//github-runner-runner-, each tagged with the version its Dockerfile pins (its ARG _VERSION default, followed by -r where it declares one, as scripts/ci/tool_image_tag.sh prints it; for the build runner image, the runner version it extends). A version tag that already exists is left alone, so a published version never changes under anyone pinning it and a run publishes only the images whose pinned version is new. The job summary lists each pushed image by digest, the reference to pin in a capability or as a runner image. A build runner entry with a runner_id builds the same Dockerfile with RUNNER_UID and RUNNER_GID set to it and tags it -uid: the runner user at that id, for a fleet whose nodes give the stock id (1001) to an account of their own and reserve this one for the runner (tool-images/build/Dockerfile says why the id reaches the nodes). Each entry's digest artifacts are named with the architecture before the tag, so one tag's download pattern never matches another's artifacts. # # Runs only when started by hand or by pushing a tag named tool-images-; the release workflow does not build these images. Each architecture is built natively, on GitHub's amd64 and arm64 hosted runners, and pushed by digest, and a second job joins the two into one multi-architecture tag (https://docs.docker.com/build/ci/github-actions/multi-platform/), because compiling the system libraries under emulation is far slower than natively. @@ -34,6 +34,7 @@ jobs: - {name: tflint, kind: toolcache} - {name: awscli, kind: toolcache} - {name: strace, kind: toolcache} + - {name: rust, kind: toolcache} - {name: openmpi, kind: sysroot} - {name: highs, kind: sysroot} - {name: libpq, kind: sysroot} @@ -56,11 +57,7 @@ jobs: RUNNER_ID: ${{ matrix.image.runner_id }} run: | set -euo pipefail - version="$(sed -n 's/^ARG [A-Z_]*_VERSION=//p' "tool-images/${NAME}/Dockerfile")" - if [ -z "$version" ] || [ "$(wc -l <<<"$version")" != 1 ]; then - echo "tool-images/${NAME}/Dockerfile must pin exactly one ARG _VERSION" >&2 - exit 1 - fi + version="$(scripts/ci/tool_image_tag.sh "tool-images/${NAME}/Dockerfile")" echo "repository=ghcr.io/${OWNER,,}/github-runner-${KIND}-${NAME}" >>"$GITHUB_OUTPUT" echo "version=${version}${RUNNER_ID:+-uid${RUNNER_ID}}" >>"$GITHUB_OUTPUT" @@ -136,6 +133,7 @@ jobs: - {name: tflint, kind: toolcache} - {name: awscli, kind: toolcache} - {name: strace, kind: toolcache} + - {name: rust, kind: toolcache} - {name: openmpi, kind: sysroot} - {name: highs, kind: sysroot} - {name: libpq, kind: sysroot} @@ -155,7 +153,7 @@ jobs: RUNNER_ID: ${{ matrix.image.runner_id }} run: | set -euo pipefail - version="$(sed -n 's/^ARG [A-Z_]*_VERSION=//p' "tool-images/${NAME}/Dockerfile")" + version="$(scripts/ci/tool_image_tag.sh "tool-images/${NAME}/Dockerfile")" echo "repository=ghcr.io/${OWNER,,}/github-runner-${KIND}-${NAME}" >>"$GITHUB_OUTPUT" echo "version=${version}${RUNNER_ID:+-uid${RUNNER_ID}}" >>"$GITHUB_OUTPUT" diff --git a/.github/workflows/rust-toolchain.yml b/.github/workflows/rust-toolchain.yml new file mode 100644 index 00000000..21385ec7 --- /dev/null +++ b/.github/workflows/rust-toolchain.yml @@ -0,0 +1,76 @@ +name: Rust toolchain + +# Builds the Rust tool image (tool-images/rust) natively on amd64 and arm64 and proves it works (tests/rust_toolchain/run.sh): its tool cache is filled as the role's init container fills it, the role's own job-started hook puts the toolchain on PATH inside the reference build runner image, and a small crate with a C source is formatted, linted, tested, checked by cargo-deny and cross-compiled for every target the image carries, each executable then checked for its target (an Apple one loading no framework). A pull request that changes what the image builds without changing the tag it is published under fails. Only on changes that can affect it. Builds nothing it publishes. + +on: + pull_request: + paths: + - tool-images/rust/** + - tool-images/build/** + - tests/rust_toolchain/** + - tests/capabilities/render.yml + - roles/github_runner_arc/files/job-started.sh + - roles/github_runner_arc/tasks/render_scale_set_values.yml + - plugins/filter/arc.py + - scripts/ci/tool_image_tag.sh + - scripts/ci/check_tool_image_tag.sh + - .github/workflows/rust-toolchain.yml + workflow_dispatch: + +concurrency: + group: rust-toolchain-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + tag: + name: Published tag follows the image + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 2 + + - name: Compare with the base branch's image + # The checkout is the pull request merged into its base, so the first parent is the base the change would land on. + run: | + set -euo pipefail + image=tool-images/rust + if [ -z "$(git ls-tree --name-only HEAD^1 -- "${image}/Dockerfile")" ]; then + echo "${image} is new: nothing is published under its tag yet" + exit 0 + fi + mkdir -p "${RUNNER_TEMP}/base" + git archive HEAD^1 "$image" | tar -x -C "${RUNNER_TEMP}/base" + scripts/ci/check_tool_image_tag.sh "${RUNNER_TEMP}/base/${image}" "$image" + + toolchain: + name: Every target builds (${{ matrix.platform.arch }}) + runs-on: ${{ matrix.platform.runner }} + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + platform: + - {arch: amd64, runner: ubuntu-latest} + - {arch: arm64, runner: ubuntu-24.04-arm} + steps: + - uses: actions/checkout@v7 + + - name: Install Ansible + run: | + set -euo pipefail + if ! python3 -m venv "${RUNNER_TEMP}/venv" 2>/dev/null; then + sudo apt-get update -qq + sudo apt-get install -y -qq python3-venv + python3 -m venv "${RUNNER_TEMP}/venv" + fi + "${RUNNER_TEMP}/venv/bin/pip" install --quiet --prefer-binary ansible-core pyyaml + echo "${RUNNER_TEMP}/venv/bin" >> "$GITHUB_PATH" + + - name: Run the toolchain test + run: tests/rust_toolchain/run.sh diff --git a/docs/build-and-test.md b/docs/build-and-test.md index 62036a24..043d5cbd 100644 --- a/docs/build-and-test.md +++ b/docs/build-and-test.md @@ -15,6 +15,7 @@ ``` - **Confirm no disk accumulates across repeated runner jobs:** the Docker host's disk usage (inside the VM, on a host that runs Docker in one) must stay flat across repeated `test-arc-runner.yml` runs. - **Test capabilities:** `tests/capabilities/run.sh` builds the reference Node.js tool image and libpq system-library image, renders a profile with capabilities through the ARC role and the scale-set chart, and runs a pod from the chart's runner template in a throwaway kind cluster to check that the tool reaches the tool cache and `PATH` and the library reaches the sysroot and its search paths; `.github/workflows/capabilities.yml` runs it on pull requests. `tests/system_libraries/run.sh [openmpi|highs|libpq|glpk|libmariadb]...` proves each reference system-library image works relocated: it copies the payload to `/opt/sysroot` as the role's init container does, applies the role's job-started hook, and runs the payload's programs in the stock `actions-runner` image and a program compiled against it in the reference build runner image (`tool-images/build`, the stock image with `build-essential` and `pkg-config`), including a two-process `mpirun` for Open MPI; `.github/workflows/system-libraries.yml` runs it on amd64 and arm64 on pull requests. The images under `tool-images/` build with `docker buildx build --platform linux/arm64,linux/amd64 tool-images/`; `.github/workflows/publish-tool-images.yml` publishes them (see Releases), and the release workflow does not. +- **Test the Rust tool image:** `tests/rust_toolchain/run.sh` builds `tool-images/rust` and cross-compiles a small crate for every target it carries in the reference build runner image (see [The Rust tool image](../roles/github_runner_arc/README.md#the-rust-tool-image)); `.github/workflows/rust-toolchain.yml` runs it on amd64 and arm64 on pull requests. - **Test the build runner image's ids:** `tests/runner_build/run.sh` builds `tool-images/build` with its default runner ids and with `RUNNER_UID` and `RUNNER_GID` set to another, and checks the runner user in each; `.github/workflows/runner-build.yml` runs it on amd64 and arm64 for changes to the image. - **Canary a published fleet-role image:** `gh workflow run published-image-canary.yml --ref main -f image='ghcr.io/exadev/github-runner-fleet-role@sha256:' -f scenario=role_controller` runs the chosen role-controller scenario in the disposable mesh on a GitHub-hosted Linux amd64 runner. The image must be publicly pullable and digest-pinned. The scenario choices are `role_controller`, `role_controller_swap`, `role_swap`, `role_swap_paused`, `role_swap_blocked_peer` and `role_swap_refused`; each tests only its own behaviour and the image selected for that runner's architecture, not other platform images. - **Compare two published fleet-role images:** `gh workflow run published-image-canary.yml --ref main -f image='ghcr.io/exadev/github-runner-fleet-role@sha256:' -f comparison_image='ghcr.io/exadev/github-runner-fleet-role@sha256:' -f scenario=role_controller` runs the selected scenario in ABBA order on one GitHub-hosted runner, rebuilding the disposable mesh each time. The `published-image-comparison` artifact contains each run's log and a TSV of image, scenario, outcome and elapsed seconds. The run fails if any scenario fails; timings include mesh setup and teardown, may reflect caching and runner contention, and are not a fleet benchmark. The job's GitHub-hosted limit can end a comparison before all runs finish. diff --git a/docs/releases.md b/docs/releases.md index 93e26c3f..5b43d9f4 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -14,6 +14,6 @@ A release: The `[skip ci]` in the release commit message is deliberate: the image build already happens in this same run using the exact version semantic-release just decided, so there is nothing useful for a second, separately-triggered run of this workflow (or of `ci.yml`) to do against a commit that only changed a version stamp and a changelog - `ci.yml`'s own lint jobs already ran against every commit before it reached `main`. -The reference capability images in `tool-images/` are not part of a release. `.github/workflows/publish-tool-images.yml` builds each one natively on amd64 and arm64 runners and pushes it to `ghcr.io//github-runner-toolcache-`, `ghcr.io//github-runner-sysroot-` or `ghcr.io//github-runner-runner-build`, tagged with the version its Dockerfile pins, when started by hand (`gh workflow run publish-tool-images.yml`) or by pushing a `tool-images-` tag. It leaves a version tag that already exists alone, and its run summary gives each pushed image's `:@sha256:` reference to pin in a capability or as a runner image. A new GitHub Container Registry package starts private; make it public in its package settings so pods can pull it without a credential. A build runner entry with a `runner_id` publishes the same image with its runner user at that uid and gid, tagged `-uid` (the ARC role README says when a fleet needs one). +The reference capability images in `tool-images/` are not part of a release. `.github/workflows/publish-tool-images.yml` builds each one natively on amd64 and arm64 runners and pushes it to `ghcr.io//github-runner-toolcache-`, `ghcr.io//github-runner-sysroot-` or `ghcr.io//github-runner-runner-build`, tagged with the version its Dockerfile pins (followed by `-r` where it declares an `IMAGE_REVISION`), when started by hand (`gh workflow run publish-tool-images.yml`) or by pushing a `tool-images-` tag. It leaves a version tag that already exists alone, and its run summary gives each pushed image's `:@sha256:` reference to pin in a capability or as a runner image. A new GitHub Container Registry package starts private; make it public in its package settings so pods can pull it without a credential. A build runner entry with a `runner_id` publishes the same image with its runner user at that uid and gid, tagged `-uid` (the ARC role README says when a fleet needs one). **What the release push needs:** a deploy key with write access on `ExaDev/github-runner`, whose private key is the `RELEASE_DEPLOY_KEY` repository secret `release.yml` checks out with. If `main` gains a ruleset, add deploy keys as its bypass actor so the release commit can land. Publishing to Ansible Galaxy additionally needs a `GALAXY_API_KEY` repository secret (an API key from `https://galaxy.ansible.com/me/preferences`); without it, the publish step logs that it's skipping and the release still completes. diff --git a/roles/github_runner_arc/README.md b/roles/github_runner_arc/README.md index ae3c7af5..c2cbb9d9 100644 --- a/roles/github_runner_arc/README.md +++ b/roles/github_runner_arc/README.md @@ -255,7 +255,7 @@ A tool image is any image that has: `` and `` are what the consuming setup action looks up: `node` and the plain version (`24.21.0`, no leading `v`) for `actions/setup-node`, `tflint` and the version without its `v` for `setup-tflint`. `` is named the way that action names the architecture, and actions differ: `actions/setup-node` uses Node's `os.arch()` (`x64`, `arm64`), while `setup-tflint` maps `x64` to `amd64` (`amd64`, `arm64`). For a tool used only through `path` the name does not matter, since `path` finds whichever architecture is there; the reference images use `os.arch()` names, the tool cache's own default. A multi-architecture image holds, for each platform, only that platform's `` directory, so the tool cache in any one pod has one architecture per tool, which is what `path` relies on. `path` adds `//[/]` for the one `` with a `.complete` marker, and the job fails at its start if there is none or more than one. -`tool-images/` holds Dockerfiles for reference images following this contract: Node.js, Terraform, TFLint, the AWS CLI and strace. Each downloads the official release for the target architecture in a first stage (strace builds its source release into one static executable), verifies it (against the release's checksums, and for Terraform, the AWS CLI and strace against the vendor's signing key, pinned by fingerprint), lays it out under `/toolcache`, and copies that into `busybox`, which supplies `sh`, `cp` and `rm`. To build one yourself, for both architectures: +`tool-images/` holds Dockerfiles for reference images following this contract: Node.js, Terraform, TFLint, the AWS CLI, strace and a Rust toolchain (see [The Rust tool image](#the-rust-tool-image)). Each downloads the official release for the target architecture in a first stage (strace builds its source release into one static executable), verifies it (against the release's checksums, and for Terraform, the AWS CLI and strace against the vendor's signing key, pinned by fingerprint), lays it out under `/toolcache`, and copies that into `busybox`, which supplies `sh`, `cp` and `rm`. To build one yourself, for both architectures: ```sh docker buildx build --platform linux/amd64,linux/arm64 --build-arg NODE_VERSION=24.21.0 \ @@ -273,6 +273,21 @@ RUN touch "/toolcache/example-cli/1.2.3/${TARGETARCH}.complete" && chmod -R a+rX and is declared as `{image: ghcr.io/example/toolcache-example-cli:1.2.3, path: example-cli/1.2.3}`. +### The Rust tool image + +`tool-images/rust` holds one pinned stable Rust toolchain (rustc, cargo, rustfmt and clippy) with the standard libraries of the image's own platform and of `aarch64-apple-darwin`, `x86_64-apple-darwin`, `aarch64-unknown-linux-musl`, `x86_64-unknown-linux-musl`, `x86_64-pc-windows-gnullvm` and `aarch64-pc-windows-gnullvm`, and Zig, cargo-zigbuild and cargo-deny. Each archive is checked against a checksum its project publishes, and the Rust ones against the Rust release signing key too. It is published as `ghcr.io//github-runner-toolcache-rust:-r`, so a job can compare the toolchain with the release its `rust-toolchain.toml` names, and the revision rises when anything else in the image changes. Declare it with the bin directory on `PATH`, since rustup does not look in the tool cache: + +```yaml +github_runner_arc_capabilities: + rust: + image: ghcr.io/exadev/github-runner-toolcache-rust:-r@sha256: + path: rust//bin +``` + +A job then runs `cargo zigbuild --target ` for any of those targets. The profile's runner image must have a C compiler (`cc`), which cargo uses for build scripts, procedural macros and the runner's own platform, and the stock `actions-runner` image has none: use the build runner image above or one of your own. A runner image that brings rustup puts its own `cargo` behind this one on `PATH`, so a repository's `rust-toolchain.toml` does not select a toolchain there: the job should fail when `rustc --version` differs from the release it expects. The macOS targets link against the system library stubs Zig carries, so a program that needs an Apple framework does not link, and the image holds no Apple SDK; the Windows targets are the gnullvm ones, linked against Zig's MinGW-w64 libraries, so it holds nothing of Microsoft's. The payload is large and every pod start copies it, so `capability_store: true` (see [The capability store](#the-capability-store)) suits a profile that carries it. + +`tests/rust_toolchain/run.sh` builds the image, fills a tool cache as the role does, runs the role's job-started hook in the build runner image, and there formats, lints, tests and checks with cargo-deny a small crate with a C source and builds it for every target; it then checks each executable's own headers (an Apple one loads nothing outside `/usr/lib`, a Linux one is static, each is for its processor) and runs the Linux one for the machine's processor. `.github/workflows/rust-toolchain.yml` runs it on amd64 and arm64 on pull requests that can affect it, and fails one that changes the image without changing its tag. + ### The system-library payload contract A system-library image is any image that has: @@ -324,7 +339,7 @@ Then prove it the way `tests/system_libraries/run.sh` does before relying on it: ### Publishing the reference images -`.github/workflows/publish-tool-images.yml` builds every reference image in `tool-images/` natively for `linux/amd64` and `linux/arm64` and pushes it to the repository owner's GitHub Container Registry namespace, as `ghcr.io//github-runner-toolcache-`, `ghcr.io//github-runner-sysroot-` and, for the build runner image, `ghcr.io//github-runner-runner-build`, tagged with the version its Dockerfile pins (for the build runner image, the stock runner version it extends, so a new runner release is a new tag). It runs only when started by hand (`gh workflow run publish-tool-images.yml`) or by pushing a tag named `tool-images-`; the release workflow does not build these images. A version tag that already exists is left alone, so a published version never changes under anyone using it, and a run publishes only the images whose pinned version is new; to publish a new version, change the Dockerfile's version (and, where it pins one, its checksum) and run it again. The run's summary prints each pushed image as `:@sha256:`, the reference to put in a capability. A newly created GitHub Container Registry package is private until its visibility is changed to public in the package's settings, which pods without a pull credential need. A build runner entry with a `runner_id` publishes the same image with its runner user at that uid and gid, tagged `-uid` (see the build runner image's ids above). +`.github/workflows/publish-tool-images.yml` builds every reference image in `tool-images/` natively for `linux/amd64` and `linux/arm64` and pushes it to the repository owner's GitHub Container Registry namespace, as `ghcr.io//github-runner-toolcache-`, `ghcr.io//github-runner-sysroot-` and, for the build runner image, `ghcr.io//github-runner-runner-build`, tagged with the version its Dockerfile pins, followed by `-r` where it declares an `IMAGE_REVISION` (for the build runner image, the stock runner version it extends, so a new runner release is a new tag). It runs only when started by hand (`gh workflow run publish-tool-images.yml`) or by pushing a tag named `tool-images-`; the release workflow does not build these images. A version tag that already exists is left alone, so a published version never changes under anyone using it, and a run publishes only the images whose pinned version is new; to publish a new version, change the Dockerfile's version (and, where it pins one, its checksum) and run it again. The run's summary prints each pushed image as `:@sha256:`, the reference to put in a capability. A newly created GitHub Container Registry package is private until its visibility is changed to public in the package's settings, which pods without a pull credential need. A build runner entry with a `runner_id` publishes the same image with its runner user at that uid and gid, tagged `-uid` (see the build runner image's ids above). ### The job-started hook diff --git a/scripts/ci/check_tool_image_tag.sh b/scripts/ci/check_tool_image_tag.sh new file mode 100755 index 00000000..a6bc3a6e --- /dev/null +++ b/scripts/ci/check_tool_image_tag.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Fails when a change to a tool image's directory changes what it builds but not the tag it is published under. publish-tool-images.yml leaves a tag that already exists alone, so such a change would never be published. +# +# Usage: scripts/ci/check_tool_image_tag.sh . What an image builds is every file in its directory, the Dockerfile without its comment and blank lines. +set -euo pipefail + +old="${1:?usage: check_tool_image_tag.sh }" +new="${2:?usage: check_tool_image_tag.sh }" +here="$(dirname "$0")" + +instructions() { + sed -e '/^[[:space:]]*#/d' -e '/^[[:space:]]*$/d' "$1" +} + +old_instructions="$(instructions "${old}/Dockerfile")" +new_instructions="$(instructions "${new}/Dockerfile")" +# diff exits 1 for a difference and 2 when it could not compare, which must not read as either answer. +others=0 +diff -r -q -x Dockerfile "$old" "$new" >/dev/null || others=$? +if [ "$others" -gt 1 ]; then + echo "could not compare ${old} with ${new}" >&2 + exit 2 +fi +if [ "$old_instructions" = "$new_instructions" ] && [ "$others" -eq 0 ]; then + echo "${new}: what the image builds is unchanged" + exit 0 +fi +old_tag="$("${here}/tool_image_tag.sh" "${old}/Dockerfile")" +new_tag="$("${here}/tool_image_tag.sh" "${new}/Dockerfile")" +if [ "$old_tag" = "$new_tag" ]; then + echo "${new} changes what the image builds but is still published as ${new_tag}, which is never rebuilt: raise ARG IMAGE_REVISION or the version" >&2 + exit 1 +fi +echo "${new}: published as ${new_tag}, was ${old_tag}" diff --git a/scripts/ci/tool_image_tag.sh b/scripts/ci/tool_image_tag.sh new file mode 100755 index 00000000..7338adbd --- /dev/null +++ b/scripts/ci/tool_image_tag.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Prints the version tag publish-tool-images.yml publishes a tool image under: the default of the Dockerfile's one ARG _VERSION, followed by -r where the Dockerfile also declares ARG IMAGE_REVISION (an image holding several tools, whose other pins can change while the version that names it does not). +# +# Usage: scripts/ci/tool_image_tag.sh . Fails unless the Dockerfile declares exactly one ARG _VERSION with a default, and at most one ARG IMAGE_REVISION, whose default is a number. +set -euo pipefail + +dockerfile="${1:?usage: tool_image_tag.sh }" +version="$(sed -n 's/^ARG [A-Z_]*_VERSION=//p' "$dockerfile")" +if [ -z "$version" ] || [ "$(wc -l <<<"$version")" -ne 1 ]; then + echo "${dockerfile} must pin exactly one ARG _VERSION" >&2 + exit 1 +fi +if grep -q '^ARG IMAGE_REVISION' "$dockerfile"; then + revision="$(sed -n 's/^ARG IMAGE_REVISION=//p' "$dockerfile")" + if ! [[ "$revision" =~ ^[0-9]+$ ]]; then + echo "${dockerfile} must give ARG IMAGE_REVISION one number" >&2 + exit 1 + fi + version="${version}-r${revision}" +fi +echo "$version" diff --git a/tests/rust_toolchain/checks.sh b/tests/rust_toolchain/checks.sh new file mode 100755 index 00000000..141a96cb --- /dev/null +++ b/tests/rust_toolchain/checks.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# What tests/rust_toolchain/run.sh runs inside the runner image: the job-started hook, as the runner runs it before a job's first step, then the toolchain's checks. Reads the pins from the environment, the crate from /crate, and writes each target's executable to /output//. +set -euo pipefail + +# The executables are removed by the user who ran the test, who is not this one. +trap 'chmod -R a+rwX /output/* 2>/dev/null || true' EXIT + +GITHUB_PATH="$(mktemp)" +GITHUB_ENV="$(mktemp)" +export GITHUB_PATH GITHUB_ENV +bash -e "$ACTIONS_RUNNER_HOOK_JOB_STARTED" +while IFS= read -r directory; do PATH="${directory}:${PATH}"; done <"$GITHUB_PATH" +export PATH + +# Fails unless the first line a tool prints names exactly the release. +reports() { + local release="$1" line + shift + line="$("$@" | head -n 1)" + echo "$line" + case " ${line} " in + *" ${release} "*) ;; + *) echo "expected release ${release} from: $*" >&2; exit 1 ;; + esac +} +for tool in rustc rustdoc cargo rustfmt cargo-clippy clippy-driver cargo-zigbuild cargo-deny zig; do + case "$(command -v "$tool")" in + "${RUNNER_TOOL_CACHE}"/*) ;; + *) echo "${tool} does not come from the tool cache" >&2; exit 1 ;; + esac +done +reports "$RUST_VERSION" rustc --version +reports "$RUST_VERSION" cargo --version +reports "$ZIG_RELEASE" zig version +reports "$CARGO_ZIGBUILD_RELEASE" cargo-zigbuild --version +reports "$CARGO_DENY_RELEASE" cargo deny --version + +cp -R /crate "${HOME}/crate" +cd "${HOME}/crate" +cargo fmt --check +cargo clippy --locked --all-targets -- -D warnings +cargo test --locked +cargo deny --locked check licenses bans sources + +for target in $RUST_TARGETS; do + echo "==> cargo zigbuild --target ${target}" + cargo zigbuild --locked --release --target "$target" 2>&1 | tee "${HOME}/build.log" + # rustc only warns when it cannot strip an executable, so the warning is what shows the toolchain's own strip tool does not run. + if grep -q 'rust-objcopy` failed' "${HOME}/build.log"; then + echo "the toolchain's rust-objcopy did not run for ${target}" >&2 + exit 1 + fi + mkdir "/output/${target}" + case "$target" in + *-windows-*) name=cross-check.exe ;; + *) name=cross-check ;; + esac + cp "target/${target}/release/${name}" "/output/${target}/${name}" +done +echo RUST-TOOLCHAIN-OK diff --git a/tests/rust_toolchain/crate/Cargo.lock b/tests/rust_toolchain/crate/Cargo.lock new file mode 100644 index 00000000..7cf3ced2 --- /dev/null +++ b/tests/rust_toolchain/crate/Cargo.lock @@ -0,0 +1,32 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cross-check" +version = "0.0.0" +dependencies = [ + "cc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" diff --git a/tests/rust_toolchain/crate/Cargo.toml b/tests/rust_toolchain/crate/Cargo.toml new file mode 100644 index 00000000..6c0845e7 --- /dev/null +++ b/tests/rust_toolchain/crate/Cargo.toml @@ -0,0 +1,12 @@ +# A crate small enough to build for every target quickly that still needs what a real one does: a C source compiled and linked for the target, and the parts of the standard library that link the platform's own libraries (threads and sockets). +[package] +name = "cross-check" +version = "0.0.0" +edition = "2024" +license = "MIT" +publish = false + +[build-dependencies] +cc = "=1.11.3" + +[workspace] diff --git a/tests/rust_toolchain/crate/build.rs b/tests/rust_toolchain/crate/build.rs new file mode 100644 index 00000000..c1895e41 --- /dev/null +++ b/tests/rust_toolchain/crate/build.rs @@ -0,0 +1,4 @@ +fn main() { + println!("cargo::rerun-if-changed=c/answer.c"); + cc::Build::new().file("c/answer.c").compile("answer"); +} diff --git a/tests/rust_toolchain/crate/c/answer.c b/tests/rust_toolchain/crate/c/answer.c new file mode 100644 index 00000000..8cbfd28a --- /dev/null +++ b/tests/rust_toolchain/crate/c/answer.c @@ -0,0 +1,5 @@ +#include +#include + +/* Six times seven, with one factor taken from the C library so the object needs its headers and symbols. */ +int32_t answer(const char *text) { return (int32_t)(strlen(text) * 7); } diff --git a/tests/rust_toolchain/crate/deny.toml b/tests/rust_toolchain/crate/deny.toml new file mode 100644 index 00000000..f69d1378 --- /dev/null +++ b/tests/rust_toolchain/crate/deny.toml @@ -0,0 +1,3 @@ +[licenses] +allow = ["Apache-2.0", "MIT"] +private = { ignore = true } diff --git a/tests/rust_toolchain/crate/src/main.rs b/tests/rust_toolchain/crate/src/main.rs new file mode 100644 index 00000000..758dd189 --- /dev/null +++ b/tests/rust_toolchain/crate/src/main.rs @@ -0,0 +1,34 @@ +use std::ffi::{CStr, c_char}; +use std::net::TcpListener; +use std::thread; + +unsafe extern "C" { + fn answer(text: *const c_char) -> i32; +} + +fn ask(text: &CStr) -> i32 { + // SAFETY: `answer` only reads the NUL-terminated string it is given. + unsafe { answer(text.as_ptr()) } +} + +fn main() -> std::io::Result<()> { + // A socket and a thread make the executable link what the platform keeps them in. + let listener = TcpListener::bind("127.0.0.1:0")?; + let asked = thread::spawn(|| ask(c"answer")); + let answered = asked + .join() + .map_err(|_| std::io::Error::other("the thread panicked"))?; + drop(listener); + println!("answer {answered}"); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::ask; + + #[test] + fn the_c_object_is_linked() { + assert_eq!(ask(c"answer"), 42); + } +} diff --git a/tests/rust_toolchain/inspect_binary.py b/tests/rust_toolchain/inspect_binary.py new file mode 100755 index 00000000..b8d1cdba --- /dev/null +++ b/tests/rust_toolchain/inspect_binary.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Check that a cross-compiled executable is what its Rust target calls for, from the file's own headers, so a binary no machine here can run is still checked. + + inspect_binary.py TARGET FILE + +For an Apple target FILE must be a 64-bit Mach-O executable of the target's processor that loads only libraries under /usr/lib: the system library has a stub in Zig, while a framework (or any other library) needs Apple's SDK, so loading one fails the check. At least one library must be loaded, so a file whose load commands could not be read never passes as loading nothing. For a Linux musl target it must be a 64-bit little-endian ELF of the target's processor with no interpreter and no needed shared library. For a Windows target it must be a PE image of the target's processor. +""" + +from __future__ import annotations + +import struct +import sys +from pathlib import Path + +# : the 64-bit magic, the executable file type, and the load commands that name a library to load. +_MACHO_MAGIC_64 = 0xFEEDFACF +_MACHO_EXECUTE = 2 +_MACHO_LOAD_DYLIB = frozenset({0xC, 0x20, 0x80000018, 0x8000001F, 0x80000023}) +_MACHO_CPU = {"aarch64": 0x0100000C, "x86_64": 0x01000007} +_MACHO_SYSTEM_LIBRARIES = "/usr/lib/" + +# The ELF specification: machine numbers, and the program header and dynamic section tags a dynamically linked executable has. +_ELF_MACHINE = {"aarch64": 183, "x86_64": 62} +_ELF_PT_DYNAMIC = 2 +_ELF_PT_INTERP = 3 +_ELF_DT_NULL = 0 +_ELF_DT_NEEDED = 1 + +# The PE format's IMAGE_FILE_MACHINE values. +_PE_MACHINE = {"aarch64": 0xAA64, "x86_64": 0x8664} + + +class BinaryError(Exception): + """The file is not what its target calls for.""" + + +def macho_libraries(data: bytes, processor: str) -> list[str]: + """The libraries a Mach-O executable of the processor loads, in load command order. Raises BinaryError for any other file.""" + if len(data) < 32: + raise BinaryError("too short for a Mach-O header") + magic, cpu, _, file_type, command_count, _, _, _ = struct.unpack_from(" len(data): + raise BinaryError(f"load command at {offset} has an impossible size {size}") + if command in _MACHO_LOAD_DYLIB: + (name_offset,) = struct.unpack_from(" str: + libraries = macho_libraries(data, processor) + if not libraries: + raise BinaryError("loads no library at all, not even the system library") + outside = [library for library in libraries if not library.startswith(_MACHO_SYSTEM_LIBRARIES) or ".framework/" in library] + if outside: + raise BinaryError(f"loads an Apple framework or a library outside {_MACHO_SYSTEM_LIBRARIES}: {', '.join(outside)}") + return f"Mach-O {processor}, loads {', '.join(libraries)}" + + +def check_elf(data: bytes, processor: str) -> str: + # \x02\x01 is the 64-bit class and little-endian data encoding. + if len(data) < 64 or data[:6] != b"\x7fELF\x02\x01": + raise BinaryError("not a 64-bit little-endian ELF file") + (machine,) = struct.unpack_from(" str: + if len(data) < 64 or data[:2] != b"MZ": + raise BinaryError("not a PE file (no MZ header)") + (header,) = struct.unpack_from(" str: + """A description of the file when it is what the target calls for; raises BinaryError when it is not, or ValueError for a target there is no check for.""" + processor = target.split("-", 1)[0] + if processor in _MACHO_CPU: + if target.endswith("-apple-darwin"): + return check_macho(data, processor) + if target.endswith("-unknown-linux-musl"): + return check_elf(data, processor) + if target.endswith("-pc-windows-gnullvm"): + return check_pe(data, processor) + raise ValueError(f"no check for target {target}") + + +def main(arguments: list[str]) -> int: + if len(arguments) != 2: + print("usage: inspect_binary.py TARGET FILE", file=sys.stderr) + return 2 + target, path = arguments + try: + description = check(target, Path(path).read_bytes()) + except BinaryError as error: + print(f"{target}: {path}: {error}", file=sys.stderr) + return 1 + print(f"{target}: {description}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tests/rust_toolchain/run.sh b/tests/rust_toolchain/run.sh new file mode 100755 index 00000000..08c2e0d0 --- /dev/null +++ b/tests/rust_toolchain/run.sh @@ -0,0 +1,113 @@ +#!/usr/bin/env bash +# Integration test for the Rust tool image (tool-images/rust). Builds the image for this machine's architecture, copies its /toolcache into a volume at the tool cache exactly as the role's init container does (the same command, as the runner's uid, into a world-writable directory like an emptyDir), renders the job-started hook data for a profile declaring it with path: rust//bin through the role's own tasks, and then, in the reference build runner image (tool-images/build: the stock actions-runner image with a C compiler) as the runner user, runs the role's job-started dispatcher, applies the GITHUB_PATH it wrote as the runner does, and runs checks.sh: the tools report the pinned releases, the small crate in crate/ passes rustfmt, clippy, its test and cargo-deny, and cargo-zigbuild builds it for every target in the image's RUST_TARGETS. Every executable is then checked on this machine by inspect_binary.py (an Apple one loads no framework, a Linux one is static, each is for its target's processor), and the Linux one for this machine's processor is run. +# +# Usage: tests/rust_toolchain/run.sh. Needs Docker, python3 and ansible-playbook (ANSIBLE_PLAYBOOK overrides which); reaches the network for the toolchain, the runner image, its distribution's packages and crates.io. Leaves the built image (grtest/toolcache-rust:test) in place so a rerun reuses its build cache; removes its volume and files on exit. +set -euo pipefail + +repo_root="$(cd "$(dirname "$0")/../.." && pwd)" +here="${repo_root}/tests/rust_toolchain" +ansible_playbook="${ANSIBLE_PLAYBOOK:-ansible-playbook}" +dockerfile="${repo_root}/tool-images/rust/Dockerfile" +image=grtest/toolcache-rust:test +runner_image=grtest/runner-build:test +tool_cache=/opt/hostedtoolcache +hooks_dir=/etc/github-runner/hooks +runner_uid=1001 +volume="grtest-toolcache-rust-$$" +work="$(mktemp -d "${TMPDIR:-/tmp}/grtest-rust-toolchain.XXXXXX")" + +log() { echo "==> $*"; } +fail() { + echo "FAIL: $*" >&2 + exit 1 +} +cleanup() { + docker volume rm -f "$volume" >/dev/null 2>&1 || true + rm -rf "${work:?}" +} +trap cleanup EXIT + +# The default of one of the Dockerfile's ARG pins, without the quotes a list is written in. +pin() { + local value + value="$(sed -n "s/^ARG $1=//p" "$dockerfile" | tr -d '"')" + [ -n "$value" ] || fail "${dockerfile} pins no $1" + echo "$value" +} +rust_version="$(pin RUST_VERSION)" +targets="$(pin RUST_TARGETS)" + +log "Building ${image} from tool-images/rust" +docker build -t "$image" "${repo_root}/tool-images/rust" +log "Building ${runner_image} from tool-images/build" +docker build -q -t "$runner_image" "${repo_root}/tool-images/build" >/dev/null + +log "Copying its tool cache into ${tool_cache} as the init container does" +docker volume create "$volume" >/dev/null +# An emptyDir is world-writable, so the init container, running as the runner's uid, can write to it; a fresh Docker volume is root's, so it is opened up first. +docker run --rm -v "${volume}:${tool_cache}" --entrypoint /bin/sh "$image" -c "chmod 0777 ${tool_cache}" +docker run --rm --user "${runner_uid}:${runner_uid}" -v "${volume}:${tool_cache}" --entrypoint /bin/sh "$image" -c 'cp -R /toolcache/. "$1"/' copy-toolcache "$tool_cache" + +log "Rendering the job-started hook data through the role" +hooks="${work}/hooks" +mkdir -p "$hooks" +python3 - "${repo_root}/plugins/filter/arc.py" "${work}/extra.json" "$image" "rust/${rust_version}/bin" "${work}/rendered.json" <<'EOF' +import importlib.util, json, sys +plugin, extra, image, path, output = sys.argv[1:] +spec = importlib.util.spec_from_file_location("arc", plugin) +arc = importlib.util.module_from_spec(spec) +spec.loader.exec_module(arc) +result = arc.arc_profiles([{"name": "Example", "image": "unused:1", "scale_set_profiles": [{"max_runners": 1, "capabilities": ["rust"]}]}], require_app_id=False) +assert result["errors"] == [], result["errors"] +catalogue = {"rust": {"image": image, "path": path}} +errors = arc.arc_capability_errors(result["profiles"], catalogue) +assert errors == [], errors +with open(extra, "w") as out: + json.dump({"profile": result["profiles"][0], "github_runner_arc_capabilities": catalogue, "render_output": output}, out) +EOF +ANSIBLE_COLLECTIONS_PATH="${repo_root}/playbooks/collections" ANSIBLE_LOCALHOST_WARNING=false ANSIBLE_INVENTORY_UNPARSED_WARNING=false \ + "$ansible_playbook" "${repo_root}/tests/capabilities/render.yml" -e "@${work}/extra.json" >/dev/null +# The ConfigMap's files, laid out as the role's volume mounts them. +python3 - "${work}/rendered.json" "$hooks" "$tool_cache" <<'EOF' +import json, os, sys +rendered, hooks, tool_cache = sys.argv[1:] +values = json.load(open(rendered))["values"] +data = json.load(open(rendered))["job_started"] +mounts = {mount["name"]: mount["mountPath"] for container in values["template"]["spec"]["containers"] if container["name"] == "runner" for mount in container["volumeMounts"]} +assert tool_cache in mounts.values(), mounts +for key, content in data.items(): + with open(os.path.join(hooks, key), "w") as out: + out.write(content) +EOF +[ -f "${hooks}/tool-paths" ] || fail "the role rendered no tool-paths" + +# The container writes the executables here as the runner's uid, which is not this user's. +output="${work}/output" +mkdir -p "$output" +chmod 0777 "$output" + +log "Running the checks in ${runner_image} with the toolchain on PATH" +docker run --rm --user "${runner_uid}:${runner_uid}" \ + -v "${volume}:${tool_cache}" -v "${hooks}:${hooks_dir}:ro" \ + -v "${here}/crate:/crate:ro" -v "${here}/checks.sh:/checks.sh:ro" -v "${output}:/output" \ + -e "ACTIONS_RUNNER_HOOK_JOB_STARTED=${hooks_dir}/job-started.sh" -e "RUNNER_TOOL_CACHE=${tool_cache}" \ + -e "RUST_VERSION=${rust_version}" -e "RUST_TARGETS=${targets}" \ + -e "ZIG_RELEASE=$(pin ZIG_RELEASE)" -e "CARGO_ZIGBUILD_RELEASE=$(pin CARGO_ZIGBUILD_RELEASE)" -e "CARGO_DENY_RELEASE=$(pin CARGO_DENY_RELEASE)" \ + --entrypoint bash "$runner_image" /checks.sh | tee "${work}/checks.log" +grep -qx RUST-TOOLCHAIN-OK "${work}/checks.log" || fail "the checks did not reach their end" + +log "Checking each executable" +failed=0 +for target in $targets; do + executables=("${output}/${target}"/*) + [ "${#executables[@]}" -eq 1 ] && [ -f "${executables[0]}" ] || fail "expected one executable for ${target}, found ${executables[*]}" + python3 "${here}/inspect_binary.py" "$target" "${executables[0]}" || failed=1 +done +[ "$failed" -eq 0 ] || fail "an executable is not what its target calls for" + +native="$(uname -m)" +[ "$native" != arm64 ] || native=aarch64 +log "Running the ${native} Linux executable" +ran="$(docker run --rm -v "${output}/${native}-unknown-linux-musl:/run-native:ro" --entrypoint /run-native/cross-check "$runner_image")" +[ "$ran" = "answer 42" ] || fail "the native musl executable printed '${ran}'" +log "PASS: the Rust tool image builds every target" diff --git a/tests/unit/test_publish_tool_images.py b/tests/unit/test_publish_tool_images.py index f9c73cb0..d3fd1ffd 100644 --- a/tests/unit/test_publish_tool_images.py +++ b/tests/unit/test_publish_tool_images.py @@ -93,6 +93,18 @@ def test_a_runner_id_reaches_the_dockerfile_and_the_tag(self) -> None: if "runner_id" not in entry: self.assertEqual([line for line in expression(build_args, entry).splitlines() if line.strip()], [], f"{entry} gets build arguments") + def test_a_revision_follows_the_version_in_the_tag(self) -> None: + dockerfile = (ROOT / "tool-images" / "rust" / "Dockerfile").read_text() + version = re.search(r"^ARG RUST_VERSION=(\S+)$", dockerfile, re.MULTILINE) + revision = re.search(r"^ARG IMAGE_REVISION=(\d+)$", dockerfile, re.MULTILINE) + assert version is not None and revision is not None + entry = next(entry for entry in self.build_entries if entry["name"] == "rust") + for job in ("build", "merge"): + self.assertEqual(version_of(self.workflow, job, entry), f"{version.group(1)}-r{revision.group(1)}") + + def test_every_image_directory_is_published(self) -> None: + self.assertEqual({entry["name"] for entry in self.build_entries}, {path.parent.name for path in (ROOT / "tool-images").glob("*/Dockerfile")}) + def test_each_tag_downloads_only_its_own_digests(self) -> None: upload = step_with(self.workflow, "build", "uses", "actions/upload-artifact@v7")["with"]["name"] download = step_with(self.workflow, "merge", "uses", "actions/download-artifact@v8")["with"]["pattern"] diff --git a/tests/unit/test_rust_toolchain_binaries.py b/tests/unit/test_rust_toolchain_binaries.py new file mode 100644 index 00000000..b300e15f --- /dev/null +++ b/tests/unit/test_rust_toolchain_binaries.py @@ -0,0 +1,110 @@ +"""Tests of tests/rust_toolchain/inspect_binary.py, which stands between the Rust tool image's cross-compiled executables and a pass: each format is accepted as the target calls for it and refused for a framework or other library outside /usr/lib, a dynamic link, or another processor.""" + +from __future__ import annotations + +import importlib.util +import struct +import sys +import unittest +from pathlib import Path +from types import ModuleType + +ROOT = Path(__file__).resolve().parents[2] + + +def load() -> ModuleType: + spec = importlib.util.spec_from_file_location("inspect_binary", ROOT / "tests" / "rust_toolchain" / "inspect_binary.py") + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +inspect_binary = load() + +ARM64_MACHO = 0x0100000C +SYSTEM = "/usr/lib/libSystem.B.dylib" +FRAMEWORK = "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation" +LC_LOAD_DYLIB = 0xC +LC_LOAD_WEAK_DYLIB = 0x80000018 + + +def macho(*libraries: tuple[int, str], cpu: int = ARM64_MACHO) -> bytes: + commands = b"" + for command, library in libraries: + name = library.encode() + b"\0" + name += b"\0" * (-len(name) % 8) + commands += struct.pack(" bytes: + dynamic_offset = 64 + 56 * len(segments) + dynamic = b"".join(struct.pack(" bytes: + return b"MZ" + b"\0" * 58 + struct.pack(" None: + self.assertIn(SYSTEM, inspect_binary.check("aarch64-apple-darwin", macho((LC_LOAD_DYLIB, SYSTEM)))) + + def test_a_framework_is_refused_however_it_is_loaded(self) -> None: + for command in (LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB, 0x20, 0x8000001F, 0x80000023): + with self.subTest(command=hex(command)), self.assertRaisesRegex(inspect_binary.BinaryError, "CoreFoundation"): + inspect_binary.check("aarch64-apple-darwin", macho((LC_LOAD_DYLIB, SYSTEM), (command, FRAMEWORK))) + + def test_a_library_outside_the_system_directory_is_refused(self) -> None: + with self.assertRaisesRegex(inspect_binary.BinaryError, "libfoo"): + inspect_binary.check("aarch64-apple-darwin", macho((LC_LOAD_DYLIB, SYSTEM), (LC_LOAD_DYLIB, "@rpath/libfoo.dylib"))) + + def test_no_library_at_all_is_refused(self) -> None: + with self.assertRaisesRegex(inspect_binary.BinaryError, "no library"): + inspect_binary.check("aarch64-apple-darwin", macho()) + + def test_another_processor_is_refused(self) -> None: + with self.assertRaisesRegex(inspect_binary.BinaryError, "x86_64"): + inspect_binary.check("x86_64-apple-darwin", macho((LC_LOAD_DYLIB, SYSTEM))) + + +class ElfTest(unittest.TestCase): + def test_static_executables_pass(self) -> None: + for data in (elf([1]), elf([1, 2], dynamic_tags=(5,))): + self.assertIn("static", inspect_binary.check("x86_64-unknown-linux-musl", data)) + + def test_an_interpreter_is_refused(self) -> None: + with self.assertRaisesRegex(inspect_binary.BinaryError, "interpreter"): + inspect_binary.check("x86_64-unknown-linux-musl", elf([1, 3])) + + def test_a_needed_library_is_refused(self) -> None: + with self.assertRaisesRegex(inspect_binary.BinaryError, "shared library"): + inspect_binary.check("x86_64-unknown-linux-musl", elf([1, 2], dynamic_tags=(5, 1))) + + def test_another_processor_is_refused(self) -> None: + with self.assertRaisesRegex(inspect_binary.BinaryError, "aarch64"): + inspect_binary.check("aarch64-unknown-linux-musl", elf([1])) + + +class PeTest(unittest.TestCase): + def test_the_target_processor_passes(self) -> None: + self.assertEqual(inspect_binary.check("x86_64-pc-windows-gnullvm", pe(0x8664)), "PE x86_64") + self.assertEqual(inspect_binary.check("aarch64-pc-windows-gnullvm", pe(0xAA64)), "PE aarch64") + + def test_another_processor_or_format_is_refused(self) -> None: + for data in (pe(0x8664), elf([1])): + with self.assertRaises(inspect_binary.BinaryError): + inspect_binary.check("aarch64-pc-windows-gnullvm", data) + + def test_an_unknown_target_is_an_error(self) -> None: + with self.assertRaises(ValueError): + inspect_binary.check("x86_64-pc-windows-msvc", pe(0x8664)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/test_rust_toolchain_zig_shim.py b/tests/unit/test_rust_toolchain_zig_shim.py new file mode 100644 index 00000000..ddc14563 --- /dev/null +++ b/tests/unit/test_rust_toolchain_zig_shim.py @@ -0,0 +1,48 @@ +"""Tests of tool-images/rust/zig.sh, the zig on the Rust tool image's PATH: it passes every argument on unchanged, and adds -lunwind exactly when a link asks for LLVM's libunwind, in its arguments or in a response file.""" + +from __future__ import annotations + +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +SHIM = Path(__file__).resolve().parents[2] / "tool-images" / "rust" / "zig.sh" + + +class ZigShimTest(unittest.TestCase): + def setUp(self) -> None: + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + (self.root / "bin").mkdir() + (self.root / "zig").mkdir() + shutil.copy(SHIM, self.root / "bin" / "zig") + # A stand-in for Zig that prints each argument it receives on a line of its own. + stand_in = self.root / "zig" / "zig" + stand_in.write_text('#!/bin/sh\nfor argument in "$@"; do printf "%s\\n" "$argument"; done\n') + stand_in.chmod(0o755) + + def received(self, *arguments: str) -> list[str]: + result = subprocess.run(["sh", str(self.root / "bin" / "zig"), *arguments], capture_output=True, text=True, check=True) + return result.stdout.splitlines() + + def test_other_invocations_are_unchanged(self) -> None: + for arguments in (["version"], ["cc", "-o", "a b", "main.o"], ["cc", "--unwindlib=libgcc"]): + self.assertEqual(self.received(*arguments), arguments) + + def test_libunwind_is_added_once_at_the_end(self) -> None: + arguments = ["cc", "--unwindlib=libunwind", "main.o", "--unwindlib=libunwind"] + self.assertEqual(self.received(*arguments), [*arguments, "-lunwind"]) + + def test_a_response_file_is_searched(self) -> None: + asking, other = self.root / "asking", self.root / "other" + asking.write_text('"-nolibc"\n"--unwindlib=libunwind"\n') + other.write_text('"-nolibc"\n') + self.assertEqual(self.received("cc", f"@{asking}"), ["cc", f"@{asking}", "-lunwind"]) + self.assertEqual(self.received("cc", f"@{other}"), ["cc", f"@{other}"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/test_tool_image_tag.py b/tests/unit/test_tool_image_tag.py new file mode 100644 index 00000000..34d614f9 --- /dev/null +++ b/tests/unit/test_tool_image_tag.py @@ -0,0 +1,75 @@ +"""Tests of scripts/ci/tool_image_tag.sh, which names the tag a tool image is published under, and scripts/ci/check_tool_image_tag.sh, which refuses a change to what an image builds under a tag that stays the same.""" + +from __future__ import annotations + +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +TAG = ROOT / "scripts" / "ci" / "tool_image_tag.sh" +CHECK = ROOT / "scripts" / "ci" / "check_tool_image_tag.sh" +BASE = "# A comment.\nFROM busybox\nARG TOOL_VERSION=1.0\nARG IMAGE_REVISION=1\nARG OTHER_RELEASE=2\n" + + +def tag(dockerfile: str) -> subprocess.CompletedProcess[str]: + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "Dockerfile" + path.write_text(dockerfile) + return subprocess.run(["bash", str(TAG), str(path)], capture_output=True, text=True) + + +def check(old: dict[str, str], new: dict[str, str]) -> subprocess.CompletedProcess[str]: + """The check's result for two image directories, each given as its files' names and contents.""" + with tempfile.TemporaryDirectory() as directory: + paths = [] + for name, files in (("old", old), ("new", new)): + path = Path(directory) / name + path.mkdir() + for file, content in files.items(): + (path / file).write_text(content) + paths.append(str(path)) + return subprocess.run(["bash", str(CHECK), *paths], capture_output=True, text=True) + + +class ToolImageTagTest(unittest.TestCase): + def test_the_version_alone(self) -> None: + self.assertEqual(tag("ARG TOOL_VERSION=1.0\n").stdout, "1.0\n") + + def test_the_revision_follows_the_version(self) -> None: + self.assertEqual(tag(BASE).stdout, "1.0-r1\n") + + def test_anything_but_one_version_and_a_numeric_revision_fails(self) -> None: + for dockerfile in ("FROM busybox\n", "ARG A_VERSION=1\nARG B_VERSION=2\n", "ARG A_VERSION=1\nARG IMAGE_REVISION=\n", "ARG A_VERSION=1\nARG IMAGE_REVISION=two\n"): + with self.subTest(dockerfile=dockerfile): + self.assertNotEqual(tag(dockerfile).returncode, 0) + + +class CheckToolImageTagTest(unittest.TestCase): + def test_a_dockerfile_comment_change_needs_no_new_tag(self) -> None: + files = {"Dockerfile": BASE, "shim.sh": "true\n"} + self.assertEqual(check(files, {**files, "Dockerfile": BASE.replace("A comment.", "Another.") + "\n# More.\n"}).returncode, 0) + + def test_a_change_under_the_same_tag_fails(self) -> None: + old = {"Dockerfile": BASE, "shim.sh": "true\n"} + changes = { + "a pin": {**old, "Dockerfile": BASE.replace("OTHER_RELEASE=2", "OTHER_RELEASE=3")}, + "another file": {**old, "shim.sh": "false\n"}, + "an added file": {**old, "more.sh": "true\n"}, + "a removed file": {"Dockerfile": BASE}, + } + for what, new in changes.items(): + with self.subTest(what=what): + result = check(old, new) + self.assertEqual(result.returncode, 1) + self.assertIn("1.0-r1", result.stderr) + + def test_a_change_under_a_new_tag_passes(self) -> None: + old = {"Dockerfile": BASE, "shim.sh": "true\n"} + for dockerfile in (BASE.replace("IMAGE_REVISION=1", "IMAGE_REVISION=2"), BASE.replace("TOOL_VERSION=1.0", "TOOL_VERSION=1.1")): + self.assertEqual(check(old, {"Dockerfile": dockerfile, "shim.sh": "false\n"}).returncode, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tool-images/rust/Dockerfile b/tool-images/rust/Dockerfile new file mode 100644 index 00000000..145601dd --- /dev/null +++ b/tool-images/rust/Dockerfile @@ -0,0 +1,77 @@ +# Tool-cache capability image for Rust with cross-compilation tools, following the tool-image contract in roles/github_runner_arc/README.md (Capabilities): /toolcache/rust/// holds one toolchain, with .complete beside it, and is Node's os.arch() name (x64 or arm64), the tool cache's own default. bin/ holds rustc, rustdoc, cargo, rustfmt, cargo-clippy (with clippy-driver), cargo-zigbuild, cargo-deny and zig (zig.sh, which runs the Zig in zig/, whose lib/ Zig finds beside its own executable), and lib/rustlib/ holds the standard library of the image's own platform and of every target in RUST_TARGETS. No setup action looks this toolchain up in the tool cache (rustup does not use it), so the capability is meant to be declared with path: rust//bin, which puts every tool on PATH at job start. The runner image must supply a C compiler (cc), which links build scripts, procedural macros and the runner's own platform. The macOS targets are built against the system library stubs Zig carries and the Windows targets are the gnullvm ones, linked against Zig's MinGW-w64 import libraries, so the image holds no Apple SDK and nothing of Microsoft's. The final stage is busybox, which supplies the sh, cp, rm and chmod the role's init containers run. +# +# The published tag is -r, so a job can compare the toolchain with its rust-toolchain.toml. A published tag is never rebuilt, so raise IMAGE_REVISION when any instruction here or another file in this directory changes and RUST_VERSION does not (set it back to 1 when RUST_VERSION is raised); the Rust toolchain workflow fails a pull request that does not. +# +# Build for both architectures: docker buildx build --platform linux/amd64,linux/arm64 -t /: tool-images/rust +FROM alpine:3.22 AS fetch +SHELL ["/bin/ash", "-eo", "pipefail", "-c"] +ARG RUST_VERSION=1.100.0 +ARG IMAGE_REVISION=1 +ARG RUST_TARGETS="aarch64-apple-darwin x86_64-apple-darwin aarch64-unknown-linux-musl x86_64-unknown-linux-musl x86_64-pc-windows-gnullvm aarch64-pc-windows-gnullvm" +# The Rust project's release signing key, by fingerprint, as published at https://forge.rust-lang.org/infra/other-installation-methods.html. +ARG RUST_KEY_FINGERPRINT=108F66205EAEB0AAA8DD5E1C85AB96E6FA1BE5FE +# Zig's checksums are those https://ziglang.org/download/index.json publishes for the release, and cargo-zigbuild's and cargo-deny's are those of the .sha256 file each release publishes beside its archive. All are to be re-derived when a release is raised. +ARG ZIG_RELEASE=0.17.1 +ARG ZIG_SHA256_AMD64=3581863e3cbcfd0fce0efc682ce7e9e93da96668a977791d356a26d2a7e9b17a +ARG ZIG_SHA256_ARM64=a1546d5646eb184437918d6635ca6b762a0e889eac09cef720ee7a1ed3fe7795 +ARG CARGO_ZIGBUILD_RELEASE=0.24.1 +ARG CARGO_ZIGBUILD_SHA256_AMD64=32581c8e13f27a807bb244aaaac870522f5b51263c766cf77b1a99771ce9fa5c +ARG CARGO_ZIGBUILD_SHA256_ARM64=70bb4c9cc71a6d16211b9079996e3cd588671053312adeff4d043499ed887601 +ARG CARGO_DENY_RELEASE=0.22.1 +ARG CARGO_DENY_SHA256_AMD64=13f7e825e9cb811c2f8de63f29b0f45851dfb53004029f0f2501af524728364d +ARG CARGO_DENY_SHA256_ARM64=0bac0838a1653ce693e4602b8634d15ca179edd2198e438af9c35ab1c551d509 +ARG TARGETARCH +# bash runs the install.sh each Rust component ships. +RUN apk add --no-cache bash curl gnupg tar xz +COPY zig.sh /zig.sh +WORKDIR /fetch +# rustup's proxies put lib/ on the loader's path, which nothing does here, and rust-objcopy (which strips the macOS targets' executables) looks for LLVM only beside lib/rustlib//, so LLVM is linked there. +# Each Rust component is checked against the .sha256 file published beside it and against its detached signature by the key with the fingerprint above, so a changed archive cannot pass with a matching checksum file. +RUN case "${TARGETARCH}" in amd64) arch=x64; host=x86_64-unknown-linux-gnu ;; arm64) arch=arm64; host=aarch64-unknown-linux-gnu ;; *) echo "unsupported architecture: ${TARGETARCH}" >&2; exit 1 ;; esac \ + && curl -fsSL https://static.rust-lang.org/rust-key.gpg.ascii | gpg --batch --import \ + && gpg --batch --with-colons --fingerprint | grep -q "^fpr:::::::::${RUST_KEY_FINGERPRINT}:" \ + && destination="/toolcache/rust/${RUST_VERSION}/${arch}" \ + && components="rustc-${RUST_VERSION}-${host} cargo-${RUST_VERSION}-${host} rustfmt-${RUST_VERSION}-${host} clippy-${RUST_VERSION}-${host} rust-std-${RUST_VERSION}-${host}" \ + && for target in ${RUST_TARGETS}; do \ + if [ "${target}" != "${host}" ]; then components="${components} rust-std-${RUST_VERSION}-${target}"; fi; \ + done \ + && for component in ${components}; do \ + archive="${component}.tar.xz"; \ + curl -fsSLO "https://static.rust-lang.org/dist/${archive}"; \ + curl -fsSLO "https://static.rust-lang.org/dist/${archive}.sha256"; \ + curl -fsSLO "https://static.rust-lang.org/dist/${archive}.asc"; \ + sha256sum -c "${archive}.sha256"; \ + gpg --batch --verify "${archive}.asc" "${archive}"; \ + tar -xJf "${archive}"; \ + "./${component}/install.sh" --prefix="${destination}" --disable-ldconfig; \ + rm -rf "${component}" "${archive}" "${archive}.sha256" "${archive}.asc"; \ + done \ + && mkdir -p "${destination}/lib/rustlib/${host}/lib" \ + && for llvm in "${destination}"/lib/libLLVM.so.*; do \ + ln -s "../../../${llvm##*/}" "${destination}/lib/rustlib/${host}/lib/${llvm##*/}"; \ + done +RUN case "${TARGETARCH}" in amd64) arch=x64; machine=x86_64; zig_sha256="${ZIG_SHA256_AMD64}"; zigbuild_sha256="${CARGO_ZIGBUILD_SHA256_AMD64}"; deny_sha256="${CARGO_DENY_SHA256_AMD64}" ;; arm64) arch=arm64; machine=aarch64; zig_sha256="${ZIG_SHA256_ARM64}"; zigbuild_sha256="${CARGO_ZIGBUILD_SHA256_ARM64}"; deny_sha256="${CARGO_DENY_SHA256_ARM64}" ;; *) echo "unsupported architecture: ${TARGETARCH}" >&2; exit 1 ;; esac \ + && destination="/toolcache/rust/${RUST_VERSION}/${arch}" \ + && zig="zig-${machine}-linux-${ZIG_RELEASE}" \ + && curl -fsSLO "https://ziglang.org/download/${ZIG_RELEASE}/${zig}.tar.xz" \ + && echo "${zig_sha256} ${zig}.tar.xz" | sha256sum -c - \ + && mkdir -p "${destination}/zig" \ + && tar -xJf "${zig}.tar.xz" -C "${destination}/zig" --strip-components=1 \ + && cp /zig.sh "${destination}/bin/zig" \ + && zigbuild="cargo-zigbuild-${machine}-unknown-linux-gnu" \ + && curl -fsSLO "https://github.com/rust-cross/cargo-zigbuild/releases/download/v${CARGO_ZIGBUILD_RELEASE}/${zigbuild}.tar.xz" \ + && echo "${zigbuild_sha256} ${zigbuild}.tar.xz" | sha256sum -c - \ + && mkdir zigbuild \ + && tar -xJf "${zigbuild}.tar.xz" -C zigbuild \ + && find zigbuild -type f -name cargo-zigbuild -exec cp {} "${destination}/bin/cargo-zigbuild" \; \ + && deny="cargo-deny-${CARGO_DENY_RELEASE}-${machine}-unknown-linux-musl" \ + && curl -fsSLO "https://github.com/EmbarkStudios/cargo-deny/releases/download/${CARGO_DENY_RELEASE}/${deny}.tar.gz" \ + && echo "${deny_sha256} ${deny}.tar.gz" | sha256sum -c - \ + && tar -xzf "${deny}.tar.gz" \ + && cp "${deny}/cargo-deny" "${destination}/bin/cargo-deny" \ + && chmod 0755 "${destination}/bin/zig" "${destination}/bin/cargo-zigbuild" "${destination}/bin/cargo-deny" \ + && touch "${destination}.complete" \ + && chmod -R a+rX /toolcache + +FROM busybox:1.37 +COPY --from=fetch /toolcache /toolcache diff --git a/tool-images/rust/zig.sh b/tool-images/rust/zig.sh new file mode 100755 index 00000000..f5b11574 --- /dev/null +++ b/tool-images/rust/zig.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# The zig on PATH in the Rust tool image: it runs the Zig beside it with the arguments it was given, adding -lunwind to a link that asks for LLVM's libunwind. rustc links its gnullvm Windows targets with -nolibc and --unwindlib=libunwind and relies on the compiler driver to add the library, as clang does. zig cc ignores --unwindlib, and cargo-zigbuild does not translate it, so without this every such link fails with undefined _Unwind_* symbols. rustc passes a long command line in a response file (@), which is searched too. tests/rust_toolchain/run.sh links both Windows targets; this script can go once it passes without it. +set -eu + +for argument in "$@"; do + case "$argument" in + --unwindlib=libunwind) ;; + @*) grep -qF -e --unwindlib=libunwind "${argument#@}" 2>/dev/null || continue ;; + *) continue ;; + esac + set -- "$@" -lunwind + break +done +exec "$(dirname "$(readlink -f "$0")")/../zig/zig" "$@"