From a0220c6444dd327e7313e65ce10017072d0ef736 Mon Sep 17 00:00:00 2001 From: Jonathan Gangi Date: Fri, 4 Dec 2026 10:03:26 -0300 Subject: [PATCH 1/2] LWLP-4934: Pin cargo/rustc wrappers to the image Rust toolchain Crates and build backends can ship a rust-toolchain.toml (uv_build's sdist pins 1.97.1), which makes rustup install that exact toolchain at build time. Wheel builds run with network isolation, so the download can never succeed (rustup fails on DNS for static.rust-lang.org), and it is not hermetic. Export RUSTUP_TOOLCHAIN in the cargo and rustc wrappers, defaulting to the installed RUST_VERSION. The env var takes precedence over rust-toolchain.toml, so rustup uses the image toolchain. Callers can still set RUSTUP_TOOLCHAIN or use cargo + to pick another installed toolchain. The rustup wrapper is unchanged so toolchain management commands keep working. Add an image-build probe that a rust-toolchain.toml pin to an uninstalled version does not change what cargo and rustc report. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Jonathan Gangi --- build_scripts/build-rust.sh | 11 ++++++++++ tests/check_runtime.py | 43 +++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/build_scripts/build-rust.sh b/build_scripts/build-rust.sh index 4e2b350..6b3b046 100755 --- a/build_scripts/build-rust.sh +++ b/build_scripts/build-rust.sh @@ -84,12 +84,22 @@ chmod g+w /manylinux-rootfs"${PREFIX}"/rustup \ /manylinux-rootfs"${PREFIX}"/rustup/{tmp,downloads,toolchains,update-hashes} chmod g+w /manylinux-rootfs"${PREFIX}"/rustup/settings.toml +# Pin the toolchain used by the cargo and rustc wrappers to the one installed +# above. A crate or build backend that ships a rust-toolchain.toml (for example +# uv_build, whose sdist pins its own channel) would otherwise make rustup try to +# download and install that exact version at build time. Builds run with network +# isolation, so that download cannot succeed, and it would not be hermetic anyway. +# RUSTUP_TOOLCHAIN takes precedence over rust-toolchain.toml, so rustup uses the +# image toolchain instead. A caller can still set RUSTUP_TOOLCHAIN (or use cargo +# +) to select another toolchain that is already installed. The rustup +# wrapper is left alone so "rustup toolchain ..." management commands keep working. # Create wrapper scripts that set environment variables mkdir -p /manylinux-rootfs/usr/local/bin cat > /manylinux-rootfs/usr/local/bin/rustc < /manylinux-rootfs/usr/local/bin/cargo < None: for command, options in probes: run(command, options) + check_rust_toolchain_pin_ignored() + overrides = Path("/usr/local/share/fromager/overrides") if not (overrides / "settings.yaml").is_file() or not (overrides / "patches").is_dir(): raise RuntimeError("Fromager settings or patches are missing") @@ -293,6 +295,47 @@ def check_builder() -> None: ) +def check_rust_toolchain_pin_ignored() -> None: + """Verify a rust-toolchain.toml in the working tree cannot swap the toolchain. + + Wheel builds run with network isolation, so rustup must never try to install a + toolchain that a crate pins. The cargo and rustc wrappers select the image + toolchain explicitly, which has to beat a pin to a version that is not + installed. + + Raises: + RuntimeError: A pinned toolchain changes what cargo or rustc report. + """ + for tool in ("cargo", "rustc"): + baseline = subprocess.run( + [tool, "--version"], + check=True, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + cwd="/", + timeout=60, + ).stdout + with tempfile.TemporaryDirectory() as workdir: + pin = Path(workdir, "rust-toolchain.toml") + pin.write_text('[toolchain]\nchannel = "1.0.0"\n', encoding="utf-8") + pinned = subprocess.run( + [tool, "--version"], + check=False, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + cwd=workdir, + timeout=60, + ) + if pinned.returncode != 0 or pinned.stdout != baseline: + raise RuntimeError( + f"{tool} honoured a rust-toolchain.toml pin instead of the image toolchain\n" + f"image: {baseline.strip()}\npinned: {pinned.stdout.strip()}" + ) + print("OK: rust-toolchain.toml pins do not override the image toolchain", flush=True) + + def check_fromager_plugins() -> None: """Load the package overrides using Fromager's own Python environment.""" print(f"fromager=={importlib.metadata.version('fromager')}", flush=True) From 183f4874b97c6814d8beaaaa8153e9edc58527ee Mon Sep 17 00:00:00 2001 From: Jonathan Gangi Date: Fri, 4 Dec 2026 14:24:30 -0300 Subject: [PATCH 2/2] LWLP-4934: Fail the build when a Rust pin is newer than the image toolchain The cargo/rustc wrappers now use the image toolchain regardless of a crate's rust-toolchain pin. Rust is backward compatible, so that is fine for a pin that is the same as or older than the image, but a newer pin would silently build with an older compiler than the crate asks for. Add rust-pin-check.sh, called by both wrappers when RUSTUP_TOOLCHAIN is not set by the caller. It finds the nearest rust-toolchain.toml (or legacy rust-toolchain) at or above the working directory, as rustup does, and exits non-zero when the pinned version is newer than the image's RUST_VERSION. stable and partial versions (1.97) are handled; beta, nightly and unparsable channels fail closed. Unit tests cover the comparison and file lookup. The image-build probe now also checks that an older/equal/stable pin uses the image toolchain and that a newer, nightly or beta pin fails. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Jonathan Gangi --- Containerfile | 2 +- build_scripts/build-rust.sh | 13 +++- build_scripts/rust-pin-check.sh | 95 +++++++++++++++++++++++++ tests/check_runtime.py | 83 +++++++++++++--------- tests/unit/test_rust_pin_check.py | 113 ++++++++++++++++++++++++++++++ 5 files changed, 272 insertions(+), 34 deletions(-) create mode 100755 build_scripts/rust-pin-check.sh create mode 100644 tests/unit/test_rust_pin_check.py diff --git a/Containerfile b/Containerfile index f5a2cfc..52f472f 100644 --- a/Containerfile +++ b/Containerfile @@ -211,7 +211,7 @@ RUN --mount=type=bind,from=static_clang,target=/tmp/cross-compiler,ro \ FROM build_base AS build_rust -COPY build_scripts/build-rust.sh /opt/_internal/build_scripts/ +COPY build_scripts/build-rust.sh build_scripts/rust-pin-check.sh /opt/_internal/build_scripts/ # The unversioned .../rustup/dist path always serves the newest rustup, so the # version is pinned in the URL. Per-arch rustup-init sha256 digests live in # build-rust.sh (matched to this RUSTUP_VERSION). diff --git a/build_scripts/build-rust.sh b/build_scripts/build-rust.sh index 6b3b046..d6fd5e8 100755 --- a/build_scripts/build-rust.sh +++ b/build_scripts/build-rust.sh @@ -93,12 +93,20 @@ chmod g+w /manylinux-rootfs"${PREFIX}"/rustup/settings.toml # image toolchain instead. A caller can still set RUSTUP_TOOLCHAIN (or use cargo # +) to select another toolchain that is already installed. The rustup # wrapper is left alone so "rustup toolchain ..." management commands keep working. +# +# Rust is backward compatible, so using the image toolchain for an older pin is +# fine. A pin newer than the image is not, so rust-pin-check.sh makes the wrappers +# fail instead of silently building with an older compiler than the crate asks for. # Create wrapper scripts that set environment variables -mkdir -p /manylinux-rootfs/usr/local/bin +mkdir -p /manylinux-rootfs/usr/local/bin /manylinux-rootfs/usr/local/libexec +install -m 0755 "${MY_DIR}/rust-pin-check.sh" /manylinux-rootfs/usr/local/libexec/lightwell-rust-pin-check cat > /manylinux-rootfs/usr/local/bin/rustc < /manylinux-rootfs/usr/local/bin/cargo < +# +# The cargo and rustc wrappers select the image toolchain through RUSTUP_TOOLCHAIN +# instead of letting rustup install whatever a rust-toolchain(.toml) file pins (the +# build has no network, so that download cannot work). Rust is backward compatible, +# so building with an image toolchain that is the same as or newer than the pin is +# fine. A pin newer than the image is not: the build would silently use an older +# compiler than the crate asks for. This check turns that case into a clear failure. +# +# The nearest rust-toolchain.toml (or legacy rust-toolchain) at or above the current +# directory is checked, the same lookup rustup does. Exit status: +# 0 no pin, or the pin is the same as or older than the image toolchain +# 1 the pin is newer than the image, or cannot be compared (beta, nightly, ...) +# 2 bad usage or an unparsable image version +set -euo pipefail + +image_version="${1:-}" +if [ -z "${image_version}" ]; then + echo "usage: $0 " >&2 + exit 2 +fi + +# Print "major minor patch" for X.Y or X.Y.Z, optionally followed by a - +# (a target triple). A missing patch counts as 0. Returns 1 if it does not parse. +parse_version() { + local re='^([0-9]+)\.([0-9]+)(\.([0-9]+))?(-.*)?$' + if [[ "$1" =~ ${re} ]]; then + echo "${BASH_REMATCH[1]} ${BASH_REMATCH[2]} ${BASH_REMATCH[4]:-0}" + else + return 1 + fi +} + +find_pin_file() { + local dir="${PWD}" name + while true; do + for name in rust-toolchain.toml rust-toolchain; do + if [ -f "${dir}/${name}" ]; then + echo "${dir}/${name}" + return 0 + fi + done + [ "${dir}" = "/" ] && return 1 + dir="$(dirname "${dir}")" + done +} + +# Read the channel from a rust-toolchain.toml, or from a legacy rust-toolchain file, +# which holds either the same TOML or just the channel on one line. +read_channel() { + local file="$1" channel + channel="$(sed -n -E "s/^[[:space:]]*channel[[:space:]]*=[[:space:]]*[\"']([^\"']+)[\"'].*/\\1/p" "${file}" | head -n 1)" + if [ -z "${channel}" ] && [ "$(basename "${file}")" = "rust-toolchain" ]; then + channel="$(sed -n -E '/^[[:space:]]*(#|\[|$)/d; s/^[[:space:]]*([^[:space:]#]+).*/\1/p' "${file}" | head -n 1)" + fi + echo "${channel}" +} + +pin_file="$(find_pin_file)" || exit 0 +channel="$(read_channel "${pin_file}")" +# A file without a channel (components or targets only) pins no version. +[ -n "${channel}" ] || exit 0 + +# "stable" resolves to the image toolchain here, so there is nothing newer to ask for. +[ "${channel}" = "stable" ] && exit 0 + +if ! image_parts="$(parse_version "${image_version}")"; then + echo "rust-pin-check: cannot parse the image Rust version '${image_version}'" >&2 + exit 2 +fi + +if ! pin_parts="$(parse_version "${channel}")"; then + echo "rust-pin-check: ${pin_file} pins toolchain channel '${channel}', which cannot be" >&2 + echo "rust-pin-check: compared with the image toolchain ${image_version}. Only stable and" >&2 + echo "rust-pin-check: numeric versions are supported; beta and nightly pins are refused." >&2 + exit 1 +fi + +read -r image_major image_minor image_patch <<<"${image_parts}" +read -r pin_major pin_minor pin_patch <<<"${pin_parts}" + +# 10# forces base 10 so a component such as 08 is not read as octal. +image_key=$(( 10#${image_major} * 1000000 + 10#${image_minor} * 1000 + 10#${image_patch} )) +pin_key=$(( 10#${pin_major} * 1000000 + 10#${pin_minor} * 1000 + 10#${pin_patch} )) + +if [ "${pin_key}" -gt "${image_key}" ]; then + echo "rust-pin-check: ${pin_file} pins Rust ${channel}, but the builder image only" >&2 + echo "rust-pin-check: provides ${image_version}. Rust is backward compatible, so the image" >&2 + echo "rust-pin-check: toolchain must be the same as or newer than the pin. Update the Rust" >&2 + echo "rust-pin-check: version in the builder image (RUST_VERSION in the Containerfile)." >&2 + exit 1 +fi diff --git a/tests/check_runtime.py b/tests/check_runtime.py index e03c407..6ac572f 100644 --- a/tests/check_runtime.py +++ b/tests/check_runtime.py @@ -12,6 +12,7 @@ import json import os import platform +import re import shutil import subprocess import tempfile @@ -296,44 +297,62 @@ def check_builder() -> None: def check_rust_toolchain_pin_ignored() -> None: - """Verify a rust-toolchain.toml in the working tree cannot swap the toolchain. + """Verify how the cargo and rustc wrappers treat a rust-toolchain.toml pin. Wheel builds run with network isolation, so rustup must never try to install a - toolchain that a crate pins. The cargo and rustc wrappers select the image - toolchain explicitly, which has to beat a pin to a version that is not - installed. + toolchain that a crate pins. The wrappers select the image toolchain explicitly, + so a pin that is the same as or older than the image must not change what cargo + and rustc report. Rust is backward compatible, so a pin newer than the image (or + one that cannot be compared, such as nightly) must fail the build instead. Raises: - RuntimeError: A pinned toolchain changes what cargo or rustc report. + RuntimeError: A pin is honoured, or a newer or incomparable pin is accepted. """ for tool in ("cargo", "rustc"): - baseline = subprocess.run( - [tool, "--version"], - check=True, - text=True, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - cwd="/", - timeout=60, - ).stdout - with tempfile.TemporaryDirectory() as workdir: - pin = Path(workdir, "rust-toolchain.toml") - pin.write_text('[toolchain]\nchannel = "1.0.0"\n', encoding="utf-8") - pinned = subprocess.run( - [tool, "--version"], - check=False, - text=True, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - cwd=workdir, - timeout=60, - ) - if pinned.returncode != 0 or pinned.stdout != baseline: - raise RuntimeError( - f"{tool} honoured a rust-toolchain.toml pin instead of the image toolchain\n" - f"image: {baseline.strip()}\npinned: {pinned.stdout.strip()}" - ) - print("OK: rust-toolchain.toml pins do not override the image toolchain", flush=True) + baseline = _run_in(tool, "/").stdout + match = re.search(r"\b(\d+)\.(\d+)\.(\d+)\b", baseline) + if match is None: + raise RuntimeError(f"Cannot read the image Rust version from: {baseline.strip()}") + major, minor, patch = (int(part) for part in match.groups()) + accepted = ("1.0.0", f"{major}.{minor}.{patch}", f"{major}.{minor}", "stable") + refused = (f"{major}.{minor}.{patch + 1}", f"{major}.{minor + 1}.0", "nightly", "beta") + for channel in accepted: + pinned = _run_pinned(tool, channel) + if pinned.returncode != 0 or pinned.stdout != baseline: + raise RuntimeError( + f"{tool} did not use the image toolchain for a pin of {channel}\n" + f"image: {baseline.strip()}\npinned: {pinned.stdout.strip()}" + ) + for channel in refused: + pinned = _run_pinned(tool, channel) + if pinned.returncode == 0 or "rust-pin-check" not in pinned.stdout: + raise RuntimeError( + f"{tool} accepted a pin of {channel}, which is newer than the image " + f"toolchain or cannot be compared\n{pinned.stdout.strip()}" + ) + print("OK: rust-toolchain.toml pins: older or equal use the image, newer fail", flush=True) + + +def _run_pinned(tool: str, channel: str) -> subprocess.CompletedProcess[str]: + """Run ` --version` in a temporary directory pinned to a toolchain channel.""" + with tempfile.TemporaryDirectory() as workdir: + Path(workdir, "rust-toolchain.toml").write_text( + f'[toolchain]\nchannel = "{channel}"\n', encoding="utf-8" + ) + return _run_in(tool, workdir) + + +def _run_in(tool: str, cwd: str) -> subprocess.CompletedProcess[str]: + """Run ` --version` in a directory, capturing output without raising.""" + return subprocess.run( + [tool, "--version"], + check=False, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + cwd=cwd, + timeout=60, + ) def check_fromager_plugins() -> None: diff --git a/tests/unit/test_rust_pin_check.py b/tests/unit/test_rust_pin_check.py new file mode 100644 index 0000000..3b23d37 --- /dev/null +++ b/tests/unit/test_rust_pin_check.py @@ -0,0 +1,113 @@ +"""Check that a Rust toolchain pin newer than the builder image fails the build.""" + +import subprocess +from pathlib import Path + +import pytest + +SCRIPT = Path(__file__).resolve().parents[2] / "build_scripts/rust-pin-check.sh" +IMAGE_VERSION = "1.98.1" + + +def run_check( + workdir: Path, image_version: str = IMAGE_VERSION +) -> subprocess.CompletedProcess[str]: + return subprocess.run( + ["bash", str(SCRIPT), image_version], + cwd=workdir, + check=False, + text=True, + capture_output=True, + timeout=30, + ) + + +def write_pin(directory: Path, channel: str, name: str = "rust-toolchain.toml") -> None: + directory.mkdir(parents=True, exist_ok=True) + (directory / name).write_text(f'[toolchain]\nchannel = "{channel}"\n', encoding="utf-8") + + +def test_no_pin_passes(tmp_path): + assert run_check(tmp_path).returncode == 0 + + +@pytest.mark.parametrize( + "channel", + [ + "1.97.1", # the uv_build 0.11.33 pin that motivated the wrappers + "1.98.1", + "1.0.0", + "1.98", + "1.97", + "1.97.1-x86_64-unknown-linux-gnu", + "1.08.0", + "stable", + ], +) +def test_pin_same_or_older_than_image_passes(tmp_path, channel): + write_pin(tmp_path, channel) + assert run_check(tmp_path).returncode == 0 + + +@pytest.mark.parametrize("channel", ["1.98.2", "1.99.0", "1.99", "1.100.0", "2.0.0"]) +def test_pin_newer_than_image_fails(tmp_path, channel): + write_pin(tmp_path, channel) + result = run_check(tmp_path) + assert result.returncode == 1 + assert channel in result.stderr + assert IMAGE_VERSION in result.stderr + + +@pytest.mark.parametrize("channel", ["beta", "nightly", "nightly-2026-01-01", "garbage"]) +def test_incomparable_channel_fails(tmp_path, channel): + write_pin(tmp_path, channel) + result = run_check(tmp_path) + assert result.returncode == 1 + assert channel in result.stderr + + +def test_pin_is_found_in_a_parent_directory(tmp_path): + write_pin(tmp_path, "1.99.0") + nested = tmp_path / "crates" / "uv-build" + nested.mkdir(parents=True) + assert run_check(nested).returncode == 1 + + +def test_nearest_pin_wins(tmp_path): + write_pin(tmp_path, "1.99.0") + nested = tmp_path / "crates" / "uv-build" + write_pin(nested, "1.97.1") + assert run_check(nested).returncode == 0 + + +def test_legacy_rust_toolchain_file(tmp_path): + (tmp_path / "rust-toolchain").write_text("1.99.0\n", encoding="utf-8") + assert run_check(tmp_path).returncode == 1 + (tmp_path / "rust-toolchain").write_text("1.90.0\n", encoding="utf-8") + assert run_check(tmp_path).returncode == 0 + + +def test_single_quoted_channel(tmp_path): + (tmp_path / "rust-toolchain.toml").write_text( + "[toolchain]\nchannel = '1.99.0'\n", encoding="utf-8" + ) + assert run_check(tmp_path).returncode == 1 + + +def test_file_without_channel_pins_nothing(tmp_path): + (tmp_path / "rust-toolchain.toml").write_text( + '[toolchain]\ncomponents = ["rustfmt"]\n', encoding="utf-8" + ) + assert run_check(tmp_path).returncode == 0 + + +def test_unparsable_image_version_is_an_error(tmp_path): + write_pin(tmp_path, "1.97.1") + assert run_check(tmp_path, image_version="not-a-version").returncode == 2 + + +def test_missing_argument_is_an_error(tmp_path): + result = subprocess.run( + ["bash", str(SCRIPT)], cwd=tmp_path, check=False, text=True, capture_output=True, timeout=30 + ) + assert result.returncode == 2