Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Containerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
24 changes: 23 additions & 1 deletion build_scripts/build-rust.sh
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,30 @@ 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
# +<toolchain>) 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 <<EOF
#!/bin/bash
export RUSTUP_HOME="${PREFIX}/rustup"
export CARGO_HOME="${PREFIX}/cargo"
if [ -z "\${RUSTUP_TOOLCHAIN:-}" ]; then
/usr/local/libexec/lightwell-rust-pin-check "${RUST_VERSION}" || exit 1
fi
export RUSTUP_TOOLCHAIN="\${RUSTUP_TOOLCHAIN:-${RUST_VERSION}}"
exec "${PREFIX}/cargo/bin/rustc" "\$@"
EOF
chmod +x /manylinux-rootfs/usr/local/bin/rustc
Expand All @@ -98,6 +116,10 @@ cat > /manylinux-rootfs/usr/local/bin/cargo <<EOF
#!/bin/bash
export RUSTUP_HOME="${PREFIX}/rustup"
export CARGO_HOME="${PREFIX}/cargo"
if [ -z "\${RUSTUP_TOOLCHAIN:-}" ]; then
/usr/local/libexec/lightwell-rust-pin-check "${RUST_VERSION}" || exit 1
fi
export RUSTUP_TOOLCHAIN="\${RUSTUP_TOOLCHAIN:-${RUST_VERSION}}"
exec "${PREFIX}/cargo/bin/cargo" "\$@"
EOF
chmod +x /manylinux-rootfs/usr/local/bin/cargo
Expand Down
95 changes: 95 additions & 0 deletions build_scripts/rust-pin-check.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
#!/bin/bash
# Refuse to build when a crate pins a Rust toolchain newer than the builder image.
#
# Usage: rust-pin-check.sh <image-rust-version>
#
# 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 <image-rust-version>" >&2
exit 2
fi

# Print "major minor patch" for X.Y or X.Y.Z, optionally followed by a -<suffix>
# (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
62 changes: 62 additions & 0 deletions tests/check_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import json
import os
import platform
import re
import shutil
import subprocess
import tempfile
Expand Down Expand Up @@ -278,6 +279,8 @@ def check_builder() -> 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")
Expand All @@ -293,6 +296,65 @@ def check_builder() -> None:
)


def check_rust_toolchain_pin_ignored() -> None:
"""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 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 pin is honoured, or a newer or incomparable pin is accepted.
"""
for tool in ("cargo", "rustc"):
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 `<tool> --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 `<tool> --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:
"""Load the package overrides using Fromager's own Python environment."""
print(f"fromager=={importlib.metadata.version('fromager')}", flush=True)
Expand Down
113 changes: 113 additions & 0 deletions tests/unit/test_rust_pin_check.py
Original file line number Diff line number Diff line change
@@ -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