From 4d15458a7694026098c772522d15797c72c485a1 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 12:21:07 -0500 Subject: [PATCH 01/11] Add a real-nokogiri end-to-end matrix for agent-mode patches tests/nokogiri/nokogiri_e2e.rb installs one nokogiri release with the real Bundler, applies a Ruby-only record, a C source record and a vendored-libxml2 patch record with the real binary, and checks what the install's Ruby loads, apply --check, vex and a byte-identical rollback. nokogiri-compatibility.yml runs it on the runner (Ruby 2.3 to 3.4 and JRuby, the precompiled gem of each line, source and system-library builds, macOS, Windows, ARM) and inside official Ruby images (Alpine, slim, the Debian releases old Rubies shipped on) with a static binary. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/nokogiri-compatibility.yml | 285 +++++++++ tests/nokogiri/nokogiri_e2e.rb | 585 +++++++++++++++++++ 2 files changed, 870 insertions(+) create mode 100644 .github/workflows/nokogiri-compatibility.yml create mode 100644 tests/nokogiri/nokogiri_e2e.rb diff --git a/.github/workflows/nokogiri-compatibility.yml b/.github/workflows/nokogiri-compatibility.yml new file mode 100644 index 000000000..0f6effe37 --- /dev/null +++ b/.github/workflows/nokogiri-compatibility.yml @@ -0,0 +1,285 @@ +name: nokogiri patch compatibility + +# Agent-mode patches to a real nokogiri install, the gem a native-extension +# patch has the most ways to miss: tests/nokogiri/nokogiri_e2e.rb installs +# one nokogiri release with the real Bundler, applies a Ruby-only record, a +# C source record and a vendored-libxml2 patch record with the real binary, +# and checks what that install's Ruby loads, `apply --check`, `vex` and a +# byte-identical `rollback`. The script's header says what each record is. +# +# What the legs cover, and why these releases: +# +# precompiled Bundler's default since nokogiri 1.11: a platform gem with +# one binary per Ruby minor, which `apply` replaces with a +# build of the source gem. 1.11.7 / 1.13.10 / 1.15.7 / +# 1.16.8 are the last releases of the lines that ship the +# `x86_64-linux` gem (Rails 5.2 to 7.1 lock them); 1.18 and +# 1.19 ship the `-gnu` and `-musl` gems. +# source RubyGems compiles the ruby platform gem with its vendored +# libxml2: the only install before 1.11 (1.6.8.1, 1.8.5 and +# 1.10.10 are the Rails 4.2 to 5.2 era, with the patch +# directory and the build script of each period), and what +# `force_ruby_platform` or a Ruby newer than the precompiled +# gem's range gives on a current release. +# system-libraries `--use-system-libraries`: the extension is rebuilt +# with the recorded build arguments. +# unavailable a precompiled install on a machine with no compiler: the +# patch must fail, name what is missing and change nothing. +# java JRuby loads no C extension: a C record is refused. +# +# The `native` legs run on the runner with setup-ruby. The `container` legs +# run the same script inside an official Ruby image, where the gems land in +# the image's own gem home (/usr/local/bundle) and the C library and +# compiler are the image's: musl on Alpine, and the Debian releases old +# Rubies were deployed on. They run the static musl binary the `static-cli` +# job builds, because a binary built on the runner needs a newer glibc than +# those images have. +# +# Every leg downloads gems from rubygems.org, and a rebuild of a precompiled +# install downloads the source gem and `mini_portile2` from it too. +# +# Not required for merge: no `merge_group` trigger, and no job here is a +# `needs` of ci.yml's `ci-ok`. + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + # Only the files of the gem native-extension rebuild and this test. A + # change to shared engine code runs the matrix on the push to main + # (when it is in the push filter below) or nightly, or on demand via + # workflow_dispatch on the PR branch. + paths: + - '.github/workflows/nokogiri-compatibility.yml' + - 'tests/nokogiri/**' + - 'crates/socket-patch-core/src/patch/gem_ext.rs' + - 'crates/socket-patch-core/src/patch/gem_source.rs' + - 'crates/socket-patch-core/src/crawlers/ruby_crawler.rs' + push: + # TEMPORARY while this workflow is developed: remove the second branch. + branches: [main, test/nokogiri-e2e] + paths: + - '.github/workflows/nokogiri-compatibility.yml' + - 'tests/nokogiri/**' + - 'Cargo.lock' + - 'Cargo.toml' + - 'crates/*/Cargo.toml' + - 'crates/socket-patch-core/src/patch/**' + - 'crates/socket-patch-core/src/crawlers/ruby_crawler.rs' + - 'crates/socket-patch-core/src/formats/gem/**' + - 'crates/socket-patch-core/src/manifest/**' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-core/src/vendor/registry_fetch.rs' + - 'crates/socket-patch-core/src/utils/http.rs' + - 'crates/socket-patch-core/src/utils/process.rs' + - 'crates/socket-patch-cli/src/commands/apply.rs' + - 'crates/socket-patch-cli/src/commands/rollback.rs' + - 'crates/socket-patch-cli/src/commands/vex*.rs' + - 'rust-toolchain.toml' + - '.cargo/**' + schedule: + # Nightly full matrix, so a main change outside the push filter still + # gets a run within a day, and so does a new image or runner toolchain. + - cron: '43 5 * * *' + workflow_dispatch: + +permissions: + contents: read + +# Supersede stale PR runs only: main runs are the only rust-cache writers +# (save-if), so push and dispatch runs are never cancelled mid-save. +concurrency: + group: nokogiri-compat-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + SOCKET_NO_CONFIG: '1' + SOCKET_NO_UPDATE_CHECK: '1' + SOCKET_TELEMETRY_DISABLED: '1' + +jobs: + native: + name: ${{ matrix.ruby }} / nokogiri ${{ matrix.nokogiri }} ${{ matrix.install }} / ${{ matrix.os }}${{ matrix.note && format(' ({0})', matrix.note) || '' }} + if: github.event.pull_request.draft != true + strategy: + fail-fast: false + matrix: + include: + # Precompiled, the x86_64-linux-gnu gem of each line. + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.19.3', install: precompiled} + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled} + - {os: ubuntu-latest, ruby: '3.3', nokogiri: '1.16.8', install: precompiled} + - {os: ubuntu-latest, ruby: '3.1', nokogiri: '1.15.7', install: precompiled} + - {os: ubuntu-latest, ruby: '3.0', nokogiri: '1.13.10', install: precompiled} + - {os: ubuntu-latest, ruby: '2.7', nokogiri: '1.11.7', install: precompiled} + # Compiled by RubyGems: the releases that have no precompiled gem, + # and a current one forced to the ruby platform. + - {os: ubuntu-latest, ruby: '2.6', nokogiri: '1.10.10', install: source} + - {os: ubuntu-latest, ruby: '2.5', nokogiri: '1.8.5', install: source} + - {os: ubuntu-latest, ruby: '2.3', nokogiri: '1.6.8.1', install: source} + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: source} + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: system-libraries} + # No compiler on PATH: nothing may change. + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, build: unavailable, args: '--hide-toolchain', note: no toolchain} + # JRuby: the Ruby-only record applies, a C record is refused. + - {os: ubuntu-latest, ruby: 'jruby-9.4', nokogiri: '1.18.10', install: java, build: refused} + # The other platform gems. + - {os: ubuntu-24.04-arm, ruby: '3.4', nokogiri: '1.18.10', install: precompiled} + - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled} + - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: source} + - {os: windows-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled} + runs-on: ${{ vars.DISABLE_DEPOT_RUNNERS != 'true' && matrix.os == 'ubuntu-latest' && 'depot-ubuntu-24.04-4' || matrix.os }} + timeout-minutes: 60 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - run: rustup show + - uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1 + with: + shared-key: dev-${{ matrix.os }} + save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Build socket-patch + run: cargo build --locked -p socket-patch-cli + - name: Setup Ruby (attempt 1) + # setup-ruby downloads the prebuilt Ruby from a github.com release + # asset; a CDN blip there is not a result. Try once more. + id: setup-ruby + uses: ruby/setup-ruby@319994f95fa847cf3fb3cd3dbe89f6dcde9f178f # v1.295.0 + continue-on-error: true + with: + ruby-version: ${{ matrix.ruby }} + - name: Setup Ruby (attempt 2) + if: steps.setup-ruby.outcome != 'success' + uses: ruby/setup-ruby@319994f95fa847cf3fb3cd3dbe89f6dcde9f178f # v1.295.0 + with: + ruby-version: ${{ matrix.ruby }} + - name: Install the system libxml2 and libxslt headers + if: matrix.install == 'system-libraries' + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libxml2-dev libxslt1-dev + - name: Patch a real nokogiri ${{ matrix.nokogiri }} install + shell: bash + env: + NOKOGIRI: ${{ matrix.nokogiri }} + INSTALL: ${{ matrix.install }} + BUILD: ${{ matrix.build || 'ok' }} + ARGS: ${{ matrix.args }} + run: | + ruby --version + # shellcheck disable=SC2086 # ARGS is a list of flags + ruby tests/nokogiri/nokogiri_e2e.rb --socket-patch target/debug/socket-patch \ + --nokogiri "$NOKOGIRI" --install "$INSTALL" --build "$BUILD" $ARGS + + static-cli: + name: static socket-patch for the container legs + if: github.event.pull_request.draft != true + runs-on: ${{ vars.DISABLE_DEPOT_RUNNERS == 'true' && 'ubuntu-latest' || 'depot-ubuntu-24.04-4' }} + timeout-minutes: 45 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - run: | + rustup show + rustup target add x86_64-unknown-linux-musl + - uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1 + with: + shared-key: nokogiri-static + save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Install cross + # The tool release.yml builds the musl targets with. + uses: taiki-e/install-action@65851e10cd6c377f11a60e600abc07cb08643468 # v2.79.3 + with: + tool: cross@0.2.5 + - name: Build + run: | + cross build --locked -p socket-patch-cli --target x86_64-unknown-linux-musl + mkdir -p static-cli + cp target/x86_64-unknown-linux-musl/debug/socket-patch static-cli/socket-patch + - uses: ./.github/actions/upload-artifact + with: + name: nokogiri-static-cli + path: static-cli/socket-patch + if-no-files-found: error + retention-days: '1' + + container: + name: ${{ matrix.image }} / nokogiri ${{ matrix.nokogiri }} ${{ matrix.install }}${{ matrix.note && format(' ({0})', matrix.note) || '' }} + if: github.event.pull_request.draft != true + needs: static-cli + strategy: + fail-fast: false + matrix: + include: + # musl: the `x86_64-linux-musl` gem, rebuilt with Alpine's compiler. + - image: 'ruby:3.4-alpine' + digest: sha256:68d60620b4458fc58c1e1d04a79ee26b85564fdd5387f3071ae077e2c56ae766 + nokogiri: '1.18.10' + install: precompiled + setup: apk add --no-cache build-base + # The Debian image a Rails app is usually built in. + - image: 'ruby:3.4-slim' + digest: sha256:65680693964528b522a38d85ec5065538c7ab9e75268802aab9770f39ee56de0 + nokogiri: '1.18.10' + install: precompiled + setup: apt-get update -qq && apt-get install -y -qq --no-install-recommends build-essential zlib1g-dev + # The same image as it ships: no compiler at all. + - image: 'ruby:3.4-slim' + digest: sha256:65680693964528b522a38d85ec5065538c7ab9e75268802aab9770f39ee56de0 + nokogiri: '1.18.10' + install: precompiled + build: unavailable + note: no toolchain + # racc is nokogiri's one dependency and has a C extension. Ruby + # 3.4 ships 1.8.1, so pinning it keeps the install from needing + # the compiler this leg is about not having. + args: --gem 'gem "racc", "1.8.1"' + # The Rubies of the Rails 4.2 to 6.0 years, on the Debian release + # and the compiler they were deployed with. + - image: 'ruby:2.7' + digest: sha256:f4420f957a9b4fae91a8d8c7fab8ba43e5a76bd640c87cb2b20ef669039e1319 + nokogiri: '1.11.7' + install: precompiled + - image: 'ruby:2.5' + digest: sha256:dde6be82028418fa39afcc712ac958af05e67dcb31879a3bd76b688453fe4149 + nokogiri: '1.8.5' + install: source + - image: 'ruby:2.3' + digest: sha256:c0d23ebb3ed63af928b7c4a954de87a5d3c1fe98a2dfcb2a44e685a3e65c3c61 + nokogiri: '1.6.8.1' + install: source + runs-on: ${{ vars.DISABLE_DEPOT_RUNNERS == 'true' && 'ubuntu-latest' || 'depot-ubuntu-24.04-4' }} + timeout-minutes: 45 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: ./.github/actions/download-artifact + with: + pattern: nokogiri-static-cli* + merge-multiple: 'true' + path: static-cli + verify: test -s static-cli/socket-patch + - name: Patch a real nokogiri ${{ matrix.nokogiri }} install in ${{ matrix.image }} + env: + IMAGE: ${{ matrix.image }}@${{ matrix.digest }} + NOKOGIRI: ${{ matrix.nokogiri }} + INSTALL: ${{ matrix.install }} + BUILD: ${{ matrix.build || 'ok' }} + SETUP: ${{ matrix.setup || 'true' }} + ARGS: ${{ matrix.args }} + # The script and the binary are mounted read-only; the project it + # builds lives in the container's own temp dir, and the gems go + # where the image's Bundler settings put them. + run: | + chmod +x static-cli/socket-patch + docker run --rm \ + -v "$PWD/tests/nokogiri:/e2e:ro" -v "$PWD/static-cli:/cli:ro" \ + -e SOCKET_NO_CONFIG -e SOCKET_NO_UPDATE_CHECK -e SOCKET_TELEMETRY_DISABLED \ + -e NOKOGIRI -e INSTALL -e BUILD -e SETUP -e ARGS \ + "$IMAGE" sh -ec ' + sh -ec "$SETUP" + ruby --version + eval "set -- $ARGS" + ruby /e2e/nokogiri_e2e.rb --socket-patch /cli/socket-patch \ + --nokogiri "$NOKOGIRI" --install "$INSTALL" --build "$BUILD" --gem-home ambient "$@" + ' diff --git a/tests/nokogiri/nokogiri_e2e.rb b/tests/nokogiri/nokogiri_e2e.rb new file mode 100644 index 000000000..918ddb2c2 --- /dev/null +++ b/tests/nokogiri/nokogiri_e2e.rb @@ -0,0 +1,585 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# End-to-end test of agent-mode patches to a real nokogiri install. +# +# nokogiri is the gem agent mode has the most ways to get wrong: since 1.11 +# Bundler installs a precompiled platform gem with one binary per Ruby minor, +# before that (and on any Ruby a precompiled gem does not cover) RubyGems +# compiles it together with a vendored libxml2 and libxslt, and a third of +# the patches Socket publishes for it change nothing but a patch file of that +# vendored libxml2. This script installs one nokogiri release with the real +# Bundler, lays hand-built patch records over it with the real `socket-patch` +# binary, and checks what the Ruby of that install then loads. +# +# It is one Ruby file with no gem dependencies, so it runs wherever the +# install under test runs: a GitHub runner, an Alpine or a ten year old +# Debian container, Windows, JRuby. Ruby 2.1 is the floor (RubyGems 2.2, the +# oldest `socket-patch` rebuilds an extension with), so no syntax newer than +# that is used here. +# +# The records are the three shapes of the published nokogiri patches: +# +# ruby a change to `lib/nokogiri.rb`. Ruby loads it as it is, so +# nothing is built. +# c a change to `ext/nokogiri/nokogiri.c`. It takes effect only in +# a rebuilt extension. +# libxml2 a new `patches/libxml2/*.patch` (`ports/patches/libxml2` before +# 1.6.7). nokogiri's build applies it to its vendored libxml2 and +# compiles the patch's name into the extension. +# +# Each scenario runs `apply --check` (not in sync), `apply`, a load of +# nokogiri through `bundle exec` in a fresh Ruby, `apply --check` (in sync), +# `apply` again (nothing to do), `vex` and `rollback`, and then compares +# every file of the gem home with the install it started from. +# +# ruby tests/nokogiri/nokogiri_e2e.rb --socket-patch target/debug/socket-patch \ +# --nokogiri 1.18.10 --install precompiled +# +# `--help` lists the options. Exit status 0 means every check passed. + +require "digest" +require "fileutils" +require "json" +require "open3" +require "optparse" +require "rbconfig" +require "tmpdir" + +RB_CONST = "SOCKET_PATCH_E2E_RB" +C_CONST = "SOCKET_PATCH_E2E_C" +LIBXML2_PATCH = "0100-socket-patch-e2e.patch" +UUID = "0e2e0e2e-0e2e-4e2e-8e2e-0e2e0e2e0e2e" +GHSA = "GHSA-e2e0-e2e0-e2e0" +PRODUCT = "pkg:generic/socket-patch-nokogiri-e2e" + +# A diff that adds one file. It applies to every libxml2 release, with `git +# apply` and with `patch -p1` (mini_portile uses whichever it finds). +LIBXML2_PATCH_BODY = [ + "diff --git a/socket-patch-e2e.txt b/socket-patch-e2e.txt", + "new file mode 100644", + "--- /dev/null", + "+++ b/socket-patch-e2e.txt", + "@@ -0,0 +1 @@", + "+Added by the socket-patch nokogiri end-to-end test.", + "" +].join("\n") + +class Failure < StandardError; end + +class NokogiriE2E + def initialize(opts) + @opts = opts + @bin = File.expand_path(opts.fetch(:socket_patch)) + @version = opts.fetch(:nokogiri) + @checks = 0 + end + + def run + @bin += ".exe" if !File.file?(@bin) && File.file?(@bin + ".exe") + raise Failure, "no socket-patch binary at #{@bin}" unless File.file?(@bin) + root = @opts[:work] ? File.expand_path(@opts[:work]) : Dir.mktmpdir("nokogiri-e2e-") + FileUtils.mkdir_p(root) + # The project path Ruby and the CLI are given has no symlink in it: + # macOS hands out its temp dir through one. + @proj = File.join(File.realpath(root), "project") + begin + FileUtils.rm_rf(@proj) + FileUtils.mkdir_p(@proj) + install + @baseline = probe + @pristine = snapshot + describe_install + @opts.fetch(:scenarios).each { |name| scenario(name) } + puts "PASS: #{@checks} checks on nokogiri #{@version} (#{@shape}), #{ruby_label}" + ensure + FileUtils.rm_rf(root) unless @opts[:work] + end + end + + private + + def ruby_label + "#{RUBY_ENGINE} #{RUBY_VERSION} on #{RUBY_PLATFORM}" + end + + # ---- running things ---------------------------------------------------- + + # What every child runs with. The Ruby under test comes first on PATH, + # and nothing of the Ruby that runs this script is passed on. With + # `--gem-home project` Bundler is configured by the project alone; with + # `--gem-home ambient` the environment's own Bundler and RubyGems + # settings stay, since they are what is under test (an official Ruby + # image sets GEM_HOME, BUNDLE_APP_CONFIG and BUNDLE_PATH). + def base_env + env = { + "RUBYOPT" => nil, "RUBYLIB" => nil, + "BUNDLE_GEMFILE" => File.join(@proj, "Gemfile"), + "BUNDLE_BIN_PATH" => nil, "BUNDLER_VERSION" => nil, + "BUNDLE_FROZEN" => nil, "BUNDLE_DEPLOYMENT" => nil, "BUNDLE_WITHOUT" => nil, + "NOKOGIRI_USE_SYSTEM_LIBRARIES" => nil, + "PATH" => [RbConfig::CONFIG["bindir"], ENV["PATH"]].join(File::PATH_SEPARATOR) + } + if project_home? + env.update("BUNDLE_APP_CONFIG" => File.join(@proj, ".bundle"), "BUNDLE_PATH" => nil, + "BUNDLE_BIN" => nil, "BUNDLE_FORCE_RUBY_PLATFORM" => nil) + ENV.each_key { |k| env[k] = nil if k.start_with?("BUNDLE_BUILD__") } + end + env + end + + def project_home? + @opts.fetch(:gem_home) == "project" + end + + def sh(env, *cmd) + out, status = Open3.capture2e(base_env.merge(env), *cmd, :chdir => @proj) + [status.exitstatus || -1, out] + end + + def sh!(env, *cmd) + code, out = sh(env, *cmd) + raise Failure, "`#{cmd.join(' ')}` exited #{code}:\n#{tail(out)}" unless code.zero? + out + end + + def bundle(*args) + [RbConfig.ruby, "-S", "bundle", *args] + end + + def tail(text, lines = 60) + all = text.to_s.lines + (all.size > lines ? ["... (#{all.size - lines} lines above)\n"] : []).concat(all.last(lines)).join + end + + # The CLI, as a CI job runs it: no saved login, no update check, and with + # `--no-build` the PATH this script was started with stripped of every + # directory that holds a compiler (see `strip_toolchain`). + def sp(*args) + env = { + "SOCKET_NO_CONFIG" => "1", "SOCKET_NO_API_TOKEN" => "1", + "SOCKET_NO_UPDATE_CHECK" => "1", "SOCKET_TELEMETRY_DISABLED" => "1" + } + env["PATH"] = strip_toolchain(base_env["PATH"]) if @opts[:hide_toolchain] + started = Time.now + out, err, status = Open3.capture3(base_env.merge(env), @bin, *args, :chdir => @proj) + [status.exitstatus || -1, out, err, Time.now - started] + end + + # PATH without the directories that hold a C compiler or `make`, except + # the Ruby's own. For a machine that has a toolchain, to see what a + # machine without one gets. + def strip_toolchain(path) + keep = RbConfig::CONFIG["bindir"] + exts = RbConfig::CONFIG["EXEEXT"].to_s.empty? ? [""] : ["", RbConfig::CONFIG["EXEEXT"]] + tools = %w[cc gcc clang make gmake] + path.split(File::PATH_SEPARATOR).reject do |dir| + next false if dir == keep + tools.any? { |t| exts.any? { |e| File.file?(File.join(dir, t + e)) } } + end.join(File::PATH_SEPARATOR) + end + + def check(ok, what, detail = nil) + @checks += 1 + return puts(" ok #{what}") if ok + raise Failure, ["FAILED: #{what}", detail].compact.join("\n") + end + + # ---- the install ------------------------------------------------------- + + def install + gemfile = ["source \"https://rubygems.org\"", "gem \"nokogiri\", \"#{@version}\""] + (@opts[:gems] || []).each { |line| gemfile << line } + File.write(File.join(@proj, "Gemfile"), gemfile.join("\n") + "\n") + want = @opts.fetch(:install) + settings = {} + settings["BUNDLE_PATH"] = "vendor/bundle" if project_home? + settings["BUNDLE_FORCE_RUBY_PLATFORM"] = "true" if %w[source system-libraries].include?(want) + settings["BUNDLE_BUILD__NOKOGIRI"] = "--use-system-libraries" if want == "system-libraries" + if project_home? + FileUtils.mkdir_p(File.join(@proj, ".bundle")) + lines = settings.map { |k, v| "#{k}: \"#{v}\"" } + File.write(File.join(@proj, ".bundle", "config"), (["---"] + lines).join("\n") + "\n") + @install_env = {} + else + # The ambient configuration is not this script's to write: the + # settings ride on the install's environment instead. + @install_env = settings + end + + puts "Installing nokogiri #{@version} (#{want}) with #{sh!({}, *bundle('--version')).strip}, #{ruby_label}" + attempts = 0 + begin + attempts += 1 + sh!(@install_env, *bundle("install", "--jobs", "4", "--retry", "3")) + rescue Failure => e + # A registry blip, not a result: one more try before giving up. + raise if attempts >= 2 || e.message !~ /Network error|Gem::RemoteFetcher|HTTP|timed out|Timeout/i + retry + end + + # The copy Bundler loads, wherever this environment keeps its gems. + where = sh!({}, *bundle("exec", RbConfig.ruby, "-e", + "puts 'sp_gem_dir\t' + Gem.loaded_specs.fetch('nokogiri').full_gem_path")) + line = where.lines.grep(/\Asp_gem_dir\t/).last + raise Failure, "Bundler did not say where nokogiri is installed:\n#{tail(where)}" unless line + @gem_dir = File.realpath(line.split("\t", 2).last.strip) + @home = File.dirname(File.dirname(@gem_dir)) + unless File.basename(File.dirname(@gem_dir)) == "gems" && File.directory?(File.join(@home, "specifications")) + raise Failure, "#{@gem_dir} is not in a RubyGems gem home" + end + inside = @gem_dir.start_with?(@proj + File::SEPARATOR) + raise Failure, "nokogiri was installed at #{@gem_dir}, not in the project" if project_home? && !inside + @full_name = File.basename(@gem_dir) + unless @full_name.start_with?("nokogiri-#{@version}") + raise Failure, "Bundler loads #{@full_name}, not nokogiri #{@version}" + end + platform = @full_name.sub("nokogiri-#{@version}", "").sub(/\A-/, "") + @java = platform == "java" + @precompiled = !platform.empty? && !@java + + File.write(File.join(@proj, "probe.rb"), PROBE) + end + + def describe_install + lib = @baseline["libxml_source"] + @shape = if @java then "java" + elsif @precompiled then "precompiled" + elsif lib == "system" then "system-libraries" + else "source" + end + puts "Installed #{@full_name}: #{@shape}, libxml2 #{@baseline['libxml_loaded']} (#{lib}), " \ + "#{@baseline['libxml_patches'].size} libxml2 patches, loads #{@baseline['binary'] || 'no native binary'}" + want = @opts.fetch(:install) + check(want == "any" || want == @shape, "the install is #{want}", "it is #{@shape}: #{@full_name}") + check(@baseline[RB_CONST].nil? && @baseline[C_CONST].nil?, "a fresh install carries no test marker") + check(leftovers.empty?, "a fresh install holds nothing of socket-patch", leftovers.inspect) + end + + # What a fresh Ruby loads through Bundler, as an application would. + def probe + out = sh!({}, *bundle("exec", RbConfig.ruby, "probe.rb")) + line = out.lines.grep(/\Asp_probe\t/).last + raise Failure, "the probe printed no result:\n#{tail(out)}" unless line + JSON.parse(line.split("\t", 2).last) + end + + # relative path => digest of every file of the nokogiri install: its gem + # dir, its spec, its built extension and its recorded build arguments. + def snapshot + files = {} + roots = [@gem_dir, File.join(@home, "specifications"), File.join(@home, "extensions"), + File.join(@home, "build_info")] + roots.each do |root| + next unless File.exist?(root) + Dir.glob(File.join(root, "**", "*"), File::FNM_DOTMATCH).each do |path| + next unless File.file?(path) && !File.symlink?(path) + rel = path[(@home.size + 1)..-1] + next if rel.start_with?("specifications/") && rel !~ %r{\Aspecifications/nokogiri-} + next if rel.start_with?("extensions/") && rel !~ %r{/nokogiri-[^/]+/} + next if rel.start_with?("build_info/") && rel !~ %r{\Abuild_info/nokogiri-} + files[rel] = Digest::SHA256.file(path).hexdigest + end + end + files + end + + # Entries socket-patch keeps in a gem home or gem dir while a native patch + # is applied; none may outlive a rollback. + def leftovers + found = Dir.glob(File.join(@home, ".socket-patch*"), File::FNM_DOTMATCH) + found.concat(Dir.glob(File.join(@gem_dir, ".socket-patch*"), File::FNM_DOTMATCH)) + found.concat(Dir.glob(File.join(@home, "extensions", "**", "*.socket-patch*"), File::FNM_DOTMATCH)) + found.map { |p| p[(@home.size + 1)..-1] } + end + + def tree_diff(now) + keys = (@pristine.keys + now.keys).uniq.sort + keys.map do |k| + if !@pristine.key?(k) then "added #{k}" + elsif !now.key?(k) then "missing #{k}" + elsif @pristine[k] != now[k] then "changed #{k}" + end + end.compact + end + + # ---- the records ------------------------------------------------------- + + def git_sha256(bytes) + Digest::SHA256.hexdigest("blob #{bytes.bytesize}\0".b + bytes.b) + end + + def purl + "pkg:gem/nokogiri@#{@version}?platform=ruby" + end + + # Writes `.socket/manifest.json` and the blobs of one record. `files` maps + # a path in the gem to [content before or nil, content after]. + def write_record(files) + socket = File.join(@proj, ".socket") + FileUtils.rm_rf(socket) + FileUtils.mkdir_p(File.join(socket, "blobs")) + entries = {} + files.each do |path, (before, after)| + [before, after].compact.each do |bytes| + File.binwrite(File.join(socket, "blobs", git_sha256(bytes)), bytes) + end + entries[path] = { "beforeHash" => before ? git_sha256(before) : "", "afterHash" => git_sha256(after) } + end + manifest = { + "patches" => { + purl => { + "uuid" => UUID, + "exportedAt" => "Mon, 16 Nov 2026 00:00:00 GMT", + "files" => entries, + "vulnerabilities" => { + GHSA => { "cves" => [], "summary" => "nokogiri end-to-end test", + "severity" => "HIGH", "description" => "nokogiri end-to-end test" } + }, + "description" => "nokogiri end-to-end test", + "license" => "MIT", + "tier" => "free" + } + } + } + File.write(File.join(socket, "manifest.json"), JSON.pretty_generate(manifest) + "\n") + end + + def installed(path) + File.binread(File.join(@gem_dir, path)) + end + + def ruby_record + before = installed("lib/nokogiri.rb") + { "lib/nokogiri.rb" => [before, before + "\nmodule Nokogiri\n #{RB_CONST} = 1\nend\n"] } + end + + def c_record + path = "ext/nokogiri/nokogiri.c" + before = installed(path) + anchor = /^[ \t]*mNokogiri[ \t]*=[ \t]*rb_define_module\("Nokogiri"\);[ \t]*\r?$/ + raise Failure, "#{path} has no `mNokogiri = rb_define_module(\"Nokogiri\");` line to patch after" unless before =~ anchor + after = before.sub(anchor) { |line| "#{line}\n rb_define_const(mNokogiri, \"#{C_CONST}\", INT2FIX(1));" } + { path => [before, after] } + end + + # The directory nokogiri's `extconf.rb` reads libxml2 patches from: the + # one this release ships them in, else the one its build script names. + def libxml2_patch_dir + return "patches/libxml2" if File.directory?(File.join(@gem_dir, "patches")) + return "ports/patches/libxml2" if File.directory?(File.join(@gem_dir, "ports", "patches")) + # A precompiled gem ships neither; its build script still says which. + extconf = installed("ext/nokogiri/extconf.rb") + return "ports/patches/libxml2" if extconf =~ /File\.join\(portsdir, *"patches"/ + return "patches/libxml2" if extconf =~ /File\.join\([A-Z_]+, *"patches"/ + nil + end + + def libxml2_record + dir = libxml2_patch_dir + return nil unless dir + { "#{dir}/#{LIBXML2_PATCH}" => [nil, LIBXML2_PATCH_BODY] } + end + + # ---- the scenarios ----------------------------------------------------- + + def scenario(name) + puts "#{name}:" + case name + when "ruby" then applied(ruby_record, :native => false) { |now| now[RB_CONST] == 1 && now[C_CONST].nil? } + when "c" + return skip("JRuby loads no C extension") && nil if @java && @opts[:build] == "ok" + native(c_record) { |now| now[C_CONST] == 1 } + when "libxml2" + record = libxml2_record + return skip("this release reads no libxml2 patch directory") && nil unless record + return skip("built against the system's libxml2, which no gem patch changes") && nil if @shape == "system-libraries" + return skip("JRuby loads no libxml2") && nil if @java && @opts[:build] == "ok" + native(record) do |now| + now["libxml_patches"].include?(LIBXML2_PATCH) && + (@baseline["libxml_patches"] - now["libxml_patches"]).empty? + end + else raise Failure, "unknown scenario #{name}" + end + end + + def skip(why) + puts " skip #{why}" + true + end + + def native(record, &effect) + case @opts.fetch(:build) + when "ok" then applied(record, :native => true, &effect) + when "unavailable" then not_applied(record, "native_extension_build_failed") + when "refused" then not_applied(record, "native_extensions_unsupported") + end + end + + def events(stdout) + JSON.parse(stdout).fetch("events", []) + rescue JSON::ParserError + [] + end + + def action(stdout) + event = events(stdout).find { |e| e["purl"].to_s.start_with?("pkg:gem/nokogiri@#{@version}") } + event ? event["action"] : nil + end + + # The `vex` statuses for nokogiri: `["not_affected"]` when the patch is + # attested, `[]` when it is left out. + def vex_statuses + out = File.join(@proj, "vex.json") + FileUtils.rm_f(out) + code, stdout, stderr, = sp("vex", "--product", PRODUCT, "--output", out) + return [code, [], stdout + stderr] unless File.file?(out) + doc = JSON.parse(File.read(out)) + statuses = (doc["statements"] || []).select { |s| s.to_s.include?("pkg:gem/nokogiri@#{@version}") } + .map { |s| s["status"] } + [code, statuses, stdout + stderr] + end + + def applied(record, native:, &effect) + write_record(record) + + code, stdout, stderr, = sp("apply", "--check", "--json") + check(code != 0, "`apply --check` reports the unapplied patch", "exit #{code}\n#{stdout}#{stderr}") + + code, stdout, stderr, secs = sp("apply", "--json") + check(code.zero? && action(stdout) == "applied", "`apply` applies it (#{secs.round}s)", + "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + + now = probe + check(effect.call(now), "Ruby loads the patched code", JSON.pretty_generate(now)) + check(now["smoke"] == @baseline["smoke"], "nokogiri still parses, queries, transforms and validates", + "before #{@baseline['smoke'].inspect}\nafter #{now['smoke'].inspect}") + if native + check(now["binary_sha256"] != @baseline["binary_sha256"], "Ruby loads a rebuilt extension") + check(now["libxml_loaded"] == @baseline["libxml_loaded"], + "the rebuilt extension has the same libxml2 (#{now['libxml_loaded']})") + else + check(now["binary_sha256"] == @baseline["binary_sha256"], "no extension was rebuilt") + end + + code, stdout, stderr, = sp("apply", "--check") + check(code.zero?, "`apply --check` is in sync", "exit #{code}\n#{stdout}#{stderr}") + + code, stdout, stderr, secs = sp("apply", "--json") + check(code.zero? && action(stdout) == "skipped", "a second `apply` has nothing to do (#{secs.round}s)", + "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + again = probe + check(again["binary_sha256"] == now["binary_sha256"], "and builds nothing") + + code, statuses, text = vex_statuses + check(code.zero? && statuses == ["not_affected"], "`vex` attests the patch", "exit #{code} #{statuses.inspect}\n#{tail(text)}") + + rolled_back + end + + def not_applied(record, reason) + write_record(record) + code, stdout, stderr, secs = sp("apply", "--json") + check(code != 0 && (stdout + stderr).include?(reason), + "`apply` fails with #{reason} (#{secs.round}s)", "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + diff = tree_diff(snapshot) + check(diff.empty?, "nothing of the install was changed", diff.join("\n")) + check(leftovers.empty?, "and nothing was left in the gem home", leftovers.join("\n")) + check(probe == @baseline, "Ruby loads what it loaded before") + + code, stdout, stderr, = sp("apply", "--check") + check(code != 0, "`apply --check` does not report it in sync", "exit #{code}\n#{stdout}#{stderr}") + _, statuses, text = vex_statuses + check(statuses.empty?, "`vex` does not attest it", "#{statuses.inspect}\n#{tail(text)}") + + code, stdout, stderr, = sp("rollback") + check(code.zero?, "`rollback` of the unapplied record succeeds", "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + end + + def rolled_back + code, stdout, stderr, = sp("rollback") + check(code.zero?, "`rollback` succeeds", "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + diff = tree_diff(snapshot) + check(diff.empty?, "every file of the install is as it was", diff.join("\n")) + check(leftovers.empty?, "nothing of socket-patch is left in the gem home", leftovers.join("\n")) + check(probe == @baseline, "Ruby loads what it loaded before the patch") + end + + # Loads nokogiri and prints one `sp_probe` line of JSON: what was loaded + # and whether it works. Old and new releases name things differently + # (`libxml2_patches` before 1.11), and JRuby has no libxml2 at all. + PROBE = <<-'RUBY' +require "json" +require "digest" +require "nokogiri" +info = Nokogiri::VERSION_INFO +lx = info["libxml"] || {} +binary = $LOADED_FEATURES.grep(/nokogiri\.(bundle|so|dll)\z/).first +patches = lx["patches"] || lx["libxml2_patches"] || [] +patches = patches.split(" ") if patches.is_a?(String) +doc = Nokogiri::XML("onetwo") +node = doc.root.add_child("").first +node["x"] = "y" +node.content = "z" +html = Nokogiri::HTML("

hi

") +xslt = Nokogiri::XSLT("" \ + "") +xsd = Nokogiri::XML::Schema("" \ + "") +smoke = [ + doc.xpath("//a").first.text, + doc.css("a").size, + doc.at_xpath("//n:b", "n" => "urn:x")["k"], + doc.at("c").to_xml, + html.at_css("p.k").text, + xslt.transform(doc).root.text, + xsd.validate(Nokogiri::XML("s")).size +] +result = { + "version" => Nokogiri::VERSION, + "binary" => binary && File.basename(File.dirname(binary)) + "/" + File.basename(binary), + "binary_sha256" => binary && Digest::SHA256.file(binary).hexdigest, + "libxml_source" => lx["source"], + "libxml_loaded" => lx["loaded"], + "libxml_patches" => patches, + "SOCKET_PATCH_E2E_RB" => Nokogiri.const_defined?(:SOCKET_PATCH_E2E_RB) ? Nokogiri::SOCKET_PATCH_E2E_RB : nil, + "SOCKET_PATCH_E2E_C" => Nokogiri.const_defined?(:SOCKET_PATCH_E2E_C) ? Nokogiri::SOCKET_PATCH_E2E_C : nil, + "smoke" => smoke +} +puts "sp_probe\t" + JSON.generate(result) + RUBY +end + +opts = { :install => "any", :build => "ok", :gem_home => "project", :scenarios => %w[ruby c libxml2], :gems => [] } +parser = OptionParser.new do |o| + o.banner = "usage: ruby nokogiri_e2e.rb --socket-patch BIN --nokogiri VERSION [options]" + o.on("--socket-patch BIN", "the socket-patch binary under test") { |v| opts[:socket_patch] = v } + o.on("--nokogiri VERSION", "the nokogiri release to install") { |v| opts[:nokogiri] = v } + o.on("--install SHAPE", %w[any precompiled source system-libraries java], + "the install to make and require: precompiled (Bundler's default where a platform gem exists),", + "source (the ruby platform gem, compiled here), system-libraries (compiled against the system's", + "libxml2), java, or any (default)") { |v| opts[:install] = v } + o.on("--build RESULT", %w[ok unavailable refused], + "what a patch that needs a rebuild must do: ok (default), unavailable (no toolchain: fail,", + "change nothing), refused (a JRuby install)") { |v| opts[:build] = v } + o.on("--hide-toolchain", "run socket-patch with no compiler or make on PATH (with --build unavailable)") do + opts[:hide_toolchain] = true + end + o.on("--gem-home WHERE", %w[project ambient], + "where Bundler installs: project (default: `vendor/bundle`, by the project's own Bundler", + "config) or ambient (wherever this environment's Bundler and RubyGems settings say, which", + "in an official Ruby image is /usr/local/bundle; only for a throwaway environment)") { |v| opts[:gem_home] = v } + o.on("--scenarios LIST", Array, "of ruby,c,libxml2 (default: all three)") { |v| opts[:scenarios] = v } + o.on("--gem LINE", "one more Gemfile line, for example 'gem \"rails\", \"7.1.5\"'") { |v| opts[:gems] << v } + o.on("--work DIR", "build the project in DIR and keep it") { |v| opts[:work] = v } +end +parser.parse! +opts[:socket_patch] ||= ENV["SOCKET_PATCH_BIN"] +abort(parser.help) unless opts[:socket_patch] && opts[:nokogiri] + +begin + NokogiriE2E.new(opts).run +rescue Failure => e + warn e.message + exit 1 +end From 77bfc4556471208361f1999c082d8494fb8a7e2b Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 12:27:54 -0500 Subject: [PATCH 02/11] Prefix the nokogiri legs' step variables libxml2's configure script reads INSTALL from the environment as the install program, so a step that set INSTALL=precompiled broke every build. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/nokogiri-compatibility.yml | 36 +++++++++++--------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/.github/workflows/nokogiri-compatibility.yml b/.github/workflows/nokogiri-compatibility.yml index 0f6effe37..cda1d2122 100644 --- a/.github/workflows/nokogiri-compatibility.yml +++ b/.github/workflows/nokogiri-compatibility.yml @@ -158,16 +158,18 @@ jobs: run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libxml2-dev libxslt1-dev - name: Patch a real nokogiri ${{ matrix.nokogiri }} install shell: bash + # The names carry a prefix because a build reads its environment: + # libxml2's configure script takes `INSTALL` for the install program. env: - NOKOGIRI: ${{ matrix.nokogiri }} - INSTALL: ${{ matrix.install }} - BUILD: ${{ matrix.build || 'ok' }} - ARGS: ${{ matrix.args }} + E2E_NOKOGIRI: ${{ matrix.nokogiri }} + E2E_INSTALL: ${{ matrix.install }} + E2E_BUILD: ${{ matrix.build || 'ok' }} + E2E_ARGS: ${{ matrix.args }} run: | ruby --version - # shellcheck disable=SC2086 # ARGS is a list of flags + # shellcheck disable=SC2086 # E2E_ARGS is a list of flags ruby tests/nokogiri/nokogiri_e2e.rb --socket-patch target/debug/socket-patch \ - --nokogiri "$NOKOGIRI" --install "$INSTALL" --build "$BUILD" $ARGS + --nokogiri "$E2E_NOKOGIRI" --install "$E2E_INSTALL" --build "$E2E_BUILD" $E2E_ARGS static-cli: name: static socket-patch for the container legs @@ -261,12 +263,12 @@ jobs: verify: test -s static-cli/socket-patch - name: Patch a real nokogiri ${{ matrix.nokogiri }} install in ${{ matrix.image }} env: - IMAGE: ${{ matrix.image }}@${{ matrix.digest }} - NOKOGIRI: ${{ matrix.nokogiri }} - INSTALL: ${{ matrix.install }} - BUILD: ${{ matrix.build || 'ok' }} - SETUP: ${{ matrix.setup || 'true' }} - ARGS: ${{ matrix.args }} + E2E_IMAGE: ${{ matrix.image }}@${{ matrix.digest }} + E2E_NOKOGIRI: ${{ matrix.nokogiri }} + E2E_INSTALL: ${{ matrix.install }} + E2E_BUILD: ${{ matrix.build || 'ok' }} + E2E_SETUP: ${{ matrix.setup || 'true' }} + E2E_ARGS: ${{ matrix.args }} # The script and the binary are mounted read-only; the project it # builds lives in the container's own temp dir, and the gems go # where the image's Bundler settings put them. @@ -275,11 +277,11 @@ jobs: docker run --rm \ -v "$PWD/tests/nokogiri:/e2e:ro" -v "$PWD/static-cli:/cli:ro" \ -e SOCKET_NO_CONFIG -e SOCKET_NO_UPDATE_CHECK -e SOCKET_TELEMETRY_DISABLED \ - -e NOKOGIRI -e INSTALL -e BUILD -e SETUP -e ARGS \ - "$IMAGE" sh -ec ' - sh -ec "$SETUP" + -e E2E_NOKOGIRI -e E2E_INSTALL -e E2E_BUILD -e E2E_SETUP -e E2E_ARGS \ + "$E2E_IMAGE" sh -ec ' + sh -ec "$E2E_SETUP" ruby --version - eval "set -- $ARGS" + eval "set -- $E2E_ARGS" ruby /e2e/nokogiri_e2e.rb --socket-patch /cli/socket-patch \ - --nokogiri "$NOKOGIRI" --install "$INSTALL" --build "$BUILD" --gem-home ambient "$@" + --nokogiri "$E2E_NOKOGIRI" --install "$E2E_INSTALL" --build "$E2E_BUILD" --gem-home ambient "$@" ' From 2a796e9e51be6e17bc0052e17549364922eff96e Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 12:33:09 -0500 Subject: [PATCH 03/11] Boot Rails on the patched nokogiri, and add the Ruby 2.1 image Each precompiled and source leg now installs the Rails of its years and checks that a booted application sanitizes HTML through the patched nokogiri. The ruby:2.3 leg names the image's manifest list, which Docker can pull, and ruby:2.1 covers the oldest RubyGems a rebuild supports. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/nokogiri-compatibility.yml | 41 +++++++++++++------- tests/nokogiri/nokogiri_e2e.rb | 33 +++++++++++++++- 2 files changed, 59 insertions(+), 15 deletions(-) diff --git a/.github/workflows/nokogiri-compatibility.yml b/.github/workflows/nokogiri-compatibility.yml index cda1d2122..e31710bc9 100644 --- a/.github/workflows/nokogiri-compatibility.yml +++ b/.github/workflows/nokogiri-compatibility.yml @@ -104,18 +104,21 @@ jobs: fail-fast: false matrix: include: - # Precompiled, the x86_64-linux-gnu gem of each line. - - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.19.3', install: precompiled} - - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled} - - {os: ubuntu-latest, ruby: '3.3', nokogiri: '1.16.8', install: precompiled} - - {os: ubuntu-latest, ruby: '3.1', nokogiri: '1.15.7', install: precompiled} - - {os: ubuntu-latest, ruby: '3.0', nokogiri: '1.13.10', install: precompiled} - - {os: ubuntu-latest, ruby: '2.7', nokogiri: '1.11.7', install: precompiled} + # Precompiled, the x86_64-linux-gnu gem of each line, in a bundle + # with the Rails of its years: the test also boots a Rails + # application on the patched nokogiri. + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.19.3', install: precompiled, rails: '~> 8.1.0'} + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, rails: '~> 8.0.0'} + - {os: ubuntu-latest, ruby: '3.3', nokogiri: '1.16.8', install: precompiled, rails: '~> 7.1.0'} + - {os: ubuntu-latest, ruby: '3.1', nokogiri: '1.15.7', install: precompiled, rails: '~> 7.0.0'} + - {os: ubuntu-latest, ruby: '3.0', nokogiri: '1.13.10', install: precompiled, rails: '~> 6.1.0'} + - {os: ubuntu-latest, ruby: '2.7', nokogiri: '1.11.7', install: precompiled, rails: '~> 6.0.0'} # Compiled by RubyGems: the releases that have no precompiled gem, - # and a current one forced to the ruby platform. - - {os: ubuntu-latest, ruby: '2.6', nokogiri: '1.10.10', install: source} - - {os: ubuntu-latest, ruby: '2.5', nokogiri: '1.8.5', install: source} - - {os: ubuntu-latest, ruby: '2.3', nokogiri: '1.6.8.1', install: source} + # and a current one forced to the ruby platform. Rails 4.2 needs + # Bundler 1. + - {os: ubuntu-latest, ruby: '2.6', nokogiri: '1.10.10', install: source, rails: '~> 5.2.0'} + - {os: ubuntu-latest, ruby: '2.5', nokogiri: '1.8.5', install: source, rails: '~> 5.1.0'} + - {os: ubuntu-latest, ruby: '2.3', nokogiri: '1.6.8.1', install: source, rails: '~> 4.2.0', bundler: '1'} - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: source} - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: system-libraries} # No compiler on PATH: nothing may change. @@ -148,11 +151,13 @@ jobs: continue-on-error: true with: ruby-version: ${{ matrix.ruby }} + bundler: ${{ matrix.bundler || 'default' }} - name: Setup Ruby (attempt 2) if: steps.setup-ruby.outcome != 'success' uses: ruby/setup-ruby@319994f95fa847cf3fb3cd3dbe89f6dcde9f178f # v1.295.0 with: ruby-version: ${{ matrix.ruby }} + bundler: ${{ matrix.bundler || 'default' }} - name: Install the system libxml2 and libxslt headers if: matrix.install == 'system-libraries' run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libxml2-dev libxslt1-dev @@ -164,12 +169,14 @@ jobs: E2E_NOKOGIRI: ${{ matrix.nokogiri }} E2E_INSTALL: ${{ matrix.install }} E2E_BUILD: ${{ matrix.build || 'ok' }} + E2E_RAILS: ${{ matrix.rails }} E2E_ARGS: ${{ matrix.args }} run: | ruby --version # shellcheck disable=SC2086 # E2E_ARGS is a list of flags ruby tests/nokogiri/nokogiri_e2e.rb --socket-patch target/debug/socket-patch \ - --nokogiri "$E2E_NOKOGIRI" --install "$E2E_INSTALL" --build "$E2E_BUILD" $E2E_ARGS + --nokogiri "$E2E_NOKOGIRI" --install "$E2E_INSTALL" --build "$E2E_BUILD" \ + ${E2E_RAILS:+--rails "$E2E_RAILS"} $E2E_ARGS static-cli: name: static socket-patch for the container legs @@ -223,7 +230,7 @@ jobs: digest: sha256:65680693964528b522a38d85ec5065538c7ab9e75268802aab9770f39ee56de0 nokogiri: '1.18.10' install: precompiled - setup: apt-get update -qq && apt-get install -y -qq --no-install-recommends build-essential zlib1g-dev + setup: apt-get update -qq && apt-get install -y -qq --no-install-recommends build-essential # The same image as it ships: no compiler at all. - image: 'ruby:3.4-slim' digest: sha256:65680693964528b522a38d85ec5065538c7ab9e75268802aab9770f39ee56de0 @@ -246,7 +253,13 @@ jobs: nokogiri: '1.8.5' install: source - image: 'ruby:2.3' - digest: sha256:c0d23ebb3ed63af928b7c4a954de87a5d3c1fe98a2dfcb2a44e685a3e65c3c61 + digest: sha256:78cc821d95c48621e577b6b0d44c9d509f0f2a4e089b9fd0ca2ae86f274773a8 + nokogiri: '1.6.8.1' + install: source + # RubyGems 2.2, the oldest that builds an extension into a dir of + # its own, which is what `apply` rebuilds. + - image: 'ruby:2.1' + digest: sha256:568664cfb53cd74147590cc86e356c4e352e00e28a0011ea1443e8664ca5bad5 nokogiri: '1.6.8.1' install: source runs-on: ${{ vars.DISABLE_DEPOT_RUNNERS == 'true' && 'ubuntu-latest' || 'depot-ubuntu-24.04-4' }} diff --git a/tests/nokogiri/nokogiri_e2e.rb b/tests/nokogiri/nokogiri_e2e.rb index 918ddb2c2..bcdee69ff 100644 --- a/tests/nokogiri/nokogiri_e2e.rb +++ b/tests/nokogiri/nokogiri_e2e.rb @@ -189,6 +189,7 @@ def check(ok, what, detail = nil) def install gemfile = ["source \"https://rubygems.org\"", "gem \"nokogiri\", \"#{@version}\""] + gemfile << "gem \"rails\", \"#{@opts[:rails]}\"" if @opts[:rails] (@opts[:gems] || []).each { |line| gemfile << line } File.write(File.join(@proj, "Gemfile"), gemfile.join("\n") + "\n") want = @opts.fetch(:install) @@ -250,6 +251,14 @@ def describe_install end puts "Installed #{@full_name}: #{@shape}, libxml2 #{@baseline['libxml_loaded']} (#{lib}), " \ "#{@baseline['libxml_patches'].size} libxml2 patches, loads #{@baseline['binary'] || 'no native binary'}" + if @opts[:rails] + puts "Rails #{@baseline['rails']} boots and sanitizes HTML through it: #{@baseline['rails_sanitize'].inspect}" + check(@baseline["rails"].to_s.start_with?(@opts[:rails].sub(/\A[^0-9]*/, "")[/\A\d+\.\d+/]), + "the bundle holds Rails #{@opts[:rails]}", "it holds #{@baseline['rails']}") + clean = @baseline["rails_sanitize"].to_s + check(clean.start_with?("

ok") && clean !~ /onclick|

") +end puts "sp_probe\t" + JSON.generate(result) RUBY end @@ -570,6 +599,8 @@ def rolled_back "config) or ambient (wherever this environment's Bundler and RubyGems settings say, which", "in an official Ruby image is /usr/local/bundle; only for a throwaway environment)") { |v| opts[:gem_home] = v } o.on("--scenarios LIST", Array, "of ruby,c,libxml2 (default: all three)") { |v| opts[:scenarios] = v } + o.on("--rails VERSION", "also install this Rails (a Gemfile requirement, for example '~> 7.1.0') and check", + "that a booted application sanitizes HTML through the patched nokogiri") { |v| opts[:rails] = v } o.on("--gem LINE", "one more Gemfile line, for example 'gem \"rails\", \"7.1.5\"'") { |v| opts[:gems] << v } o.on("--work DIR", "build the project in DIR and keep it") { |v| opts[:work] = v } end From 01d4c1ead82743537ae62a7825ed6243e3fe8fd4 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 13:07:03 -0500 Subject: [PATCH 04/11] Fix gem rebuilds that link the system's library over the packed one Two defects found with real nokogiri installs: A precompiled gem was rebuilt with the build arguments RubyGems recorded for it, which were never used to build it. Bundler's build.nokogiri --use-system-libraries, a setting many projects kept from before nokogiri shipped precompiled gems, is recorded for the platform gem too, so apply replaced the libxml2 2.13 the gem ships with the system's 2.9. A precompiled copy is now rebuilt as its publisher built it: no recorded arguments, and NOKOGIRI_USE_SYSTEM_LIBRARIES removed from the build. A gem built against the system's libraries compiles nothing of the library it packs. A record that only changes the packed library (a new patches/libxml2/*.patch, a third of the published nokogiri patches) was written, rebuilt against the same system library and attested by vex as patched. It is now refused from files alone (recorded build arguments, the build log, or the environment) with nothing written, and never attested. The nokogiri matrix covers both, and its Rails legs hold the loofah of their nokogiri's years. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/nokogiri-compatibility.yml | 21 +- crates/socket-patch-cli/CLI_CONTRACT.md | 22 +- .../tests/e2e_gem_native_ext_build.rs | 165 ++++++++++- crates/socket-patch-core/src/patch/gem_ext.rs | 280 +++++++++++++++++- docs/ecosystems.md | 10 + tests/nokogiri/nokogiri_e2e.rb | 28 +- 6 files changed, 503 insertions(+), 23 deletions(-) diff --git a/.github/workflows/nokogiri-compatibility.yml b/.github/workflows/nokogiri-compatibility.yml index e31710bc9..33ed08134 100644 --- a/.github/workflows/nokogiri-compatibility.yml +++ b/.github/workflows/nokogiri-compatibility.yml @@ -22,7 +22,12 @@ name: nokogiri patch compatibility # `force_ruby_platform` or a Ruby newer than the precompiled # gem's range gives on a current release. # system-libraries `--use-system-libraries`: the extension is rebuilt -# with the recorded build arguments. +# with the recorded build arguments, and a patch to the +# vendored libxml2, which such a build does not compile, is +# refused. The `legacy setting` leg is a precompiled install +# in a project that still carries that Bundler setting from +# the years before precompiled gems: its rebuild must keep +# the libxml2 the gem ships, not link the system's. # unavailable a precompiled install on a machine with no compiler: the # patch must fail, name what is missing and change nothing. # java JRuby loads no C extension: a C record is refused. @@ -120,7 +125,8 @@ jobs: - {os: ubuntu-latest, ruby: '2.5', nokogiri: '1.8.5', install: source, rails: '~> 5.1.0'} - {os: ubuntu-latest, ruby: '2.3', nokogiri: '1.6.8.1', install: source, rails: '~> 4.2.0', bundler: '1'} - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: source} - - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: system-libraries} + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: system-libraries, system-libxml2: true} + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, system-libxml2: true, args: '--bundle-setting BUNDLE_BUILD__NOKOGIRI=--use-system-libraries', note: legacy setting} # No compiler on PATH: nothing may change. - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, build: unavailable, args: '--hide-toolchain', note: no toolchain} # JRuby: the Ruby-only record applies, a C record is refused. @@ -129,7 +135,9 @@ jobs: - {os: ubuntu-24.04-arm, ruby: '3.4', nokogiri: '1.18.10', install: precompiled} - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled} - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: source} - - {os: windows-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled} + # A short project path: the MinGW tools stop at 260 characters, + # and a build in the stage is some 60 deeper than one in place. + - {os: windows-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, args: '--work "$RUNNER_TEMP/n"'} runs-on: ${{ vars.DISABLE_DEPOT_RUNNERS != 'true' && matrix.os == 'ubuntu-latest' && 'depot-ubuntu-24.04-4' || matrix.os }} timeout-minutes: 60 steps: @@ -159,7 +167,7 @@ jobs: ruby-version: ${{ matrix.ruby }} bundler: ${{ matrix.bundler || 'default' }} - name: Install the system libxml2 and libxslt headers - if: matrix.install == 'system-libraries' + if: matrix.system-libxml2 run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libxml2-dev libxslt1-dev - name: Patch a real nokogiri ${{ matrix.nokogiri }} install shell: bash @@ -173,10 +181,11 @@ jobs: E2E_ARGS: ${{ matrix.args }} run: | ruby --version - # shellcheck disable=SC2086 # E2E_ARGS is a list of flags + # E2E_ARGS is a shell-quoted list of flags from the matrix above. + eval "set -- $E2E_ARGS" ruby tests/nokogiri/nokogiri_e2e.rb --socket-patch target/debug/socket-patch \ --nokogiri "$E2E_NOKOGIRI" --install "$E2E_INSTALL" --build "$E2E_BUILD" \ - ${E2E_RAILS:+--rails "$E2E_RAILS"} $E2E_ARGS + ${E2E_RAILS:+--rails "$E2E_RAILS"} "$@" static-cli: name: static socket-patch for the container legs diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 6338d568b..d5ec08f42 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -954,8 +954,14 @@ name: nothing of it is run. This holds whatever lock governs the gem home. (`/.socket-patch-build/-[-]/`), by RubyGems, and must be that gem, declare extensions, and be the copy's own source (above). The record's files are laid over the staged gem, and every `beforeHash` must hold there, whatever the mismatch policy of the run. -RubyGems then builds the staged gem's extension in the stage, with the build arguments it recorded -for the installed copy (`build_info/`). A gem the staged gem depends on at runtime that is not on +RubyGems then builds the staged gem's extension in the stage. A gem RubyGems built is rebuilt the +way it was built, with the build arguments RubyGems recorded for the installed copy +(`build_info/`). A precompiled gem is rebuilt the way its publisher built it, from the libraries +the gem packs: build arguments recorded for it were never used to build it and are not used now, +and `NOKOGIRI_USE_SYSTEM_LIBRARIES` is removed from the build's environment. (Bundler's +`build.nokogiri --use-system-libraries`, which many projects kept from the years before nokogiri +shipped precompiled gems, is recorded for the platform gem too; following it would replace the +libxml2 the gem ships with the system's.) A gem the staged gem depends on at runtime that is not on the build's `GEM_PATH` (the stage home, the copy's home, the caller's `GEM_PATH`, RubyGems' defaults) is staged too: the newest ruby-platform release the requirement allows that runs on the building Ruby, downloaded from the registry under the same rules and verified against its compact @@ -969,6 +975,18 @@ library under `lib/`, a Ruby file the build generates under a require path. Such loaded from where it was built. The staged build is set aside: a gem RubyGems built is rebuilt in place (below), a precompiled gem is refused. +**A gem built against the system's libraries.** A gem that packs a library (nokogiri packs +libxml2 and libxslt) and was built against the system's copy instead compiles nothing of the +copy it packs. A record that changes the packed copy (a file under `patches/` or `ports/`, or +`dependencies.yml`: mini_portile's layout) cannot take effect in such an install, whose library is +the operating system's. It is refused with `native_extensions_unsupported` and nothing is +written, so `apply --check` and `vex` never attest it. Three things say a copy is such a build, +each read without running anything: `--use-system-libraries` or `--enable-system-libraries` +among the build arguments RubyGems recorded for it, "using system libraries" in the log of its +installed build (`gem_make.out`), or `NOKOGIRI_USE_SYSTEM_LIBRARIES` in the environment of the +run, which a rebuild would follow. A record of the gem's own sources (`ext/**`) is rebuilt +against the system's libraries as before. A precompiled gem is never such a build. + **Into the installed copy.** The record's files are written into the copy, and the build takes the place of the compiled code: diff --git a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs index 7e29451f9..0dde41a70 100644 --- a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs +++ b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs @@ -646,7 +646,7 @@ impl FakeRuby { // -e build // -e unpack // -e missing_deps - // -e stage_build + // -e stage_build [] let script = format!( r#"#!/bin/sh PATH=/usr/bin:/bin @@ -728,6 +728,8 @@ missing_deps) stage_build) full=$(basename "$4" .gemspec) ext="$5/extensions/x86_64-linux/$abi/$full" + # The installed copy whose recorded build arguments the build is given. + printf '%s\n' "$7" > "$state/stage-build-args-of" [ -e "$state/hang" ] && hang if [ -e "$state/fail-extconf" ]; then extconf_failure "$ext" >&2 @@ -857,6 +859,15 @@ esac std::fs::read_to_string(self.state.join(format!("env.{mode}"))).unwrap() } + /// The installed copy whose recorded build arguments the last staged + /// build was given; empty when it was given none. + fn stage_build_args_of(&self) -> String { + std::fs::read_to_string(self.state.join("stage-build-args-of")) + .unwrap() + .trim_end() + .to_string() + } + /// Make every later build hang. With `half_built` it first leaves a /// partial extension dir and a replaced `lib/` copy, as a build /// interrupted late does; without, it has written nothing yet. @@ -1695,6 +1706,158 @@ fn a_precompiled_copy_gets_the_build_of_its_source_gem() { assert_eq!(ruby.calls(), built, "rollback restores from the backup"); } +/// A precompiled copy is rebuilt the way its publisher built it, from the +/// libraries the gem packs. Build arguments RubyGems recorded for it were +/// never used to build it: Bundler's `build.nokogiri +/// --use-system-libraries`, a setting many projects kept from the years +/// before nokogiri shipped precompiled gems, is recorded for the platform +/// gem too, and following it (or `NOKOGIRI_USE_SYSTEM_LIBRARIES`) made +/// `apply` replace nokogiri's libxml2 2.13 with the system's 2.9. +#[cfg(unix)] +#[test] +fn a_precompiled_copy_is_rebuilt_without_the_build_arguments_recorded_for_it() { + let (_tmp, proj, gem_dir) = fake_precompiled_gem(true); + write_precompiled_record(&proj); + let home = proj.join("vendor/bundle/ruby/3.4.0"); + std::fs::create_dir_all(home.join("build_info")).unwrap(); + std::fs::write( + home.join("build_info") + .join(format!("{PRE_FULL_NAME}.info")), + "--use-system-libraries\n", + ) + .unwrap(); + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + + let env = [("NOKOGIRI_USE_SYSTEM_LIBRARIES", "1")]; + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &env); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!(event_action(&stdout), "applied", "{stdout}"); + assert_eq!( + ruby.stage_build_args_of(), + "", + "the build was given the arguments recorded for the platform gem" + ); + assert!( + !ruby + .env_seen("stage_build") + .contains("NOKOGIRI_USE_SYSTEM_LIBRARIES"), + "the build was told to use the system's libraries" + ); + assert_eq!( + std::fs::read_to_string(gem_dir.join("lib/sp_native/3.4/sp_native.so")).unwrap(), + built_from(&c_source(2)) + ); +} + +/// A gem built against the system's copy of a library compiles nothing of +/// the copy it packs, so a record that changes the packed copy (the shape +/// of a third of the published nokogiri patches: one more +/// `patches/libxml2/*.patch`) cannot take effect there. It is refused from +/// files alone, whichever way the build says what it linked, and never +/// attested: before, it was written, "rebuilt" against the same system +/// library and attested as patched. A record of the gem's own sources is +/// still rebuilt, with the arguments RubyGems recorded. +#[cfg(unix)] +#[test] +fn a_packed_library_patch_to_a_system_library_build_is_refused() { + let library_patch: [RecordFile<'_>; 1] = [("patches/libsp/0100-CVE-test.patch", None, "fix\n")]; + let new_gem = || { + let (tmp, proj, gem_dir) = fake_native_gem(true); + let home = proj.join("vendor/bundle/ruby/3.4.0"); + std::fs::create_dir_all(home.join("cache")).unwrap(); + std::fs::write(home.join("cache/sp_native-1.0.0.gem"), b"the source gem").unwrap(); + std::fs::create_dir_all(home.join("build_info")).unwrap(); + (tmp, proj, gem_dir, home) + }; + let recorded = |home: &Path| { + std::fs::write( + home.join("build_info").join(format!("{FULL_NAME}.info")), + "--with-cflags=-O2\n--use-system-libraries\n", + ) + .unwrap(); + }; + + for evidence in ["arguments", "log", "environment"] { + let (_tmp, proj, _gem_dir, home) = new_gem(); + write_record(&proj.join(".socket"), PURL, &library_patch); + let mut env = Vec::new(); + match evidence { + "arguments" => recorded(&home), + "log" => std::fs::write( + home.join("extensions/x86_64-linux/3.4.0") + .join(FULL_NAME) + .join("gem_make.out"), + "ruby extconf.rb\nBuilding sp_native using system libraries.\n", + ) + .unwrap(), + _ => env.push(("NOKOGIRI_USE_SYSTEM_LIBRARIES", "1")), + } + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + let tree_before = walk_files(&proj.join("vendor")); + + for args in [ + &["apply", "--json", "--offline"][..], + &["apply", "--json", "--offline", "--dry-run"], + ] { + let (code, stdout, stderr) = ruby.run(&proj, args, &env); + assert_eq!(code, 1, "{evidence} {args:?}: {stdout}\n{stderr}"); + let envelope = parse_json_envelope(&stdout); + let error = common::envelope::event_for(&envelope, PURL)["error"] + .as_str() + .unwrap_or_default() + .to_string(); + assert!( + error.contains("native_extensions_unsupported") + && error.contains("patches/libsp/0100-CVE-test.patch") + && error.contains("the system's copy of that library") + && error.contains("nothing was written"), + "{evidence} {args:?}: {error}" + ); + } + assert_eq!( + ruby.calls(), + Vec::::new(), + "{evidence}: Ruby ran for a patch that cannot take effect" + ); + assert_tree(&proj.join("vendor"), &tree_before, evidence); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--check"], &env); + assert_ne!(code, 0, "{evidence}: {stdout}\n{stderr}"); + assert!( + !vex_attests(|args| ruby.run(&proj, args, &env)), + "{evidence}: vex attested a patch that is compiled into nothing" + ); + } + + // The same record on a copy built from what the gem packs is built. + let (_tmp, proj, gem_dir, _home) = new_gem(); + write_record(&proj.join(".socket"), PURL, &library_patch); + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!(event_action(&stdout), "applied", "{stdout}"); + assert!(gem_dir.join("patches/libsp/0100-CVE-test.patch").is_file()); + assert!(vex_attests(|args| ruby.run(&proj, args, &[]))); + + // And a record of the gem's own sources is rebuilt against the system's + // libraries, as the installed build was. + let (_tmp, proj, _gem_dir, home) = new_gem(); + recorded(&home); + write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!(event_action(&stdout), "applied", "{stdout}"); + assert_eq!( + ruby.stage_build_args_of(), + FULL_NAME, + "the rebuild takes the arguments RubyGems recorded for the copy" + ); +} + /// Without the source gem there is nothing to build from: offline and not /// cached, the copy is refused from files alone, with what is needed (not /// "use hosted mode", which refuses platform gems); with a registry that diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 630d2759e..a2e9d8b70 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -56,8 +56,10 @@ //! 4. The record is laid over it with [`apply_package_patch`]: every //! `beforeHash` must hold in the pristine gem, or the archive is not //! the gem the patch was written for. -//! 5. RubyGems builds the staged gem's extension in the stage, with the -//! build arguments it recorded for the installed copy. A gem the build +//! 5. RubyGems builds the staged gem's extension in the stage: a gem it +//! built, with the build arguments it recorded for the installed copy; +//! a precompiled gem, as its publisher built it, with none +//! ([`RubyRun::StageBuild`]). A gem the build //! needs and the install lacks (a precompiled nokogiri has no //! `mini_portile2`) is installed into the stage home, never into the //! user's. A build that leaves what Ruby loads in the gem's own tree @@ -90,6 +92,13 @@ //! such fallback and is refused, with what it needs: network access to the //! registry once, or the source gem in the home's `cache/`. //! +//! A gem that packs a library and was built against the system's copy of +//! it (nokogiri with `--use-system-libraries`) compiles nothing of the +//! copy it packs. A record that changes that copy (`patches/**`, `ports/**`, +//! `dependencies.yml`) would be written, "rebuilt" against the same system +//! library and attested, with nothing of it in what Ruby loads. It is +//! refused from files alone instead ([`system_library_build`]). +//! //! `vex` and `apply --check` attest a copy only when its marker matches the //! record's patched sources and every recorded artifact still hashes as //! built ([`verify_native_build`]), whichever way it was built. A @@ -255,8 +264,27 @@ const BUILD_TIMEOUT: Duration = Duration::from_secs(30 * 60); /// ignores it. const BUILD_COMPLETE: &str = "gem.build_complete"; +/// The log RubyGems keeps of a build, in its extension dir. +const BUILD_LOG: &str = "gem_make.out"; + /// Files RubyGems writes into an extension dir that are not build products. -const EXT_DIR_METADATA: &[&str] = &[BUILD_COMPLETE, "gem_make.out", "mkmf.log"]; +const EXT_DIR_METADATA: &[&str] = &[BUILD_COMPLETE, BUILD_LOG, "mkmf.log"]; + +/// Build arguments that make a gem link the system's copy of a library it +/// would otherwise build from the sources it packs. mini_portile's +/// convention: nokogiri takes both spellings, sqlite3 the second. +const SYSTEM_LIBRARY_ARGS: &[&str] = &["--use-system-libraries", "--enable-system-libraries"]; + +/// The environment variable nokogiri's build takes for the same. +const SYSTEM_LIBRARY_ENV: &str = "NOKOGIRI_USE_SYSTEM_LIBRARIES"; + +/// What nokogiri's `extconf.rb` writes into the log of such a build +/// ("Building nokogiri using system libraries."). +const SYSTEM_LIBRARY_LOG: &str = "using system libraries"; + +/// How much of a build log is read for [`SYSTEM_LIBRARY_LOG`]: the line is +/// among the first an `extconf.rb` prints, and a log is not bounded. +const BUILD_LOG_HEAD: u64 = 1024 * 1024; /// Source and build-script extensions a native extension compiles. const NATIVE_SOURCE_EXTENSIONS: &[&str] = &[ @@ -352,9 +380,10 @@ const GENERATED_GRAMMAR_EXTENSIONS: &[&str] = &["y", "rl"]; /// staged gem, and of the gems that meet them, that no gem on `GEM_PATH` /// meets: what its build scripts may `require` and would not find. /// -/// `stage_build ` builds the staged gem's extensions inside the stage home, -/// with the build arguments RubyGems recorded for the installed copy. It +/// `stage_build []` builds the staged gem's extensions inside the stage home, +/// with the build arguments RubyGems recorded for the installed copy when +/// it is named (a precompiled copy is not: see [`RubyRun::StageBuild`]). It /// loads the gemspec `unpack` wrote and runs the archive's build scripts /// over the staged tree. const RUBY_SCRIPT: &str = "require 'rubygems'; mode, a, b, c, d = ARGV; \ @@ -418,7 +447,7 @@ abort(\"#{a} declares no extensions\") if spec.extensions.empty?; \ require 'rubygems/ext'; \ Gem::DefaultUserInteraction.ui = Gem::SilentUI.new; \ info = File.join(c, 'build_info', \"#{d}.info\"); \ -args = File.file?(info) ? File.readlines(info).map { |l| l.chomp } : []; \ +args = (d && File.file?(info)) ? File.readlines(info).map { |l| l.chomp } : []; \ Gem::Ext::Builder.new(spec, args).build_extensions; \ puts \"sp_built\\t#{File.expand_path(spec.extension_dir)}\"; \ else \ @@ -736,6 +765,88 @@ fn is_clearly_not_built(path: &str, require_paths: &[String]) -> bool { } } +/// Whether `path` is an input of a library the gem builds from sources it +/// packs, by mini_portile's layout (nokogiri, sqlite3): a patch for it +/// (`patches/libxml2/…`, `ports/patches/…` before nokogiri 1.6.7), its +/// archive (`ports/archives/…`), or the file that names its version and +/// checksum (`dependencies.yml`). +fn is_vendored_library_input(path: &str) -> bool { + let path = normalize_file_path(path); + path == "dependencies.yml" || path.starts_with("patches/") || path.starts_with("ports/") +} + +/// Whether the build argument `arg` asks for the system's libraries +/// ([`SYSTEM_LIBRARY_ARGS`], bare or with a value that is not a "no"). +fn is_system_library_arg(arg: &str) -> bool { + SYSTEM_LIBRARY_ARGS + .iter() + .any(|name| match arg.strip_prefix(name) { + Some("") => true, + Some(rest) => rest.strip_prefix('=').is_some_and(|value| { + !matches!(value.to_ascii_lowercase().as_str(), "no" | "false" | "0") + }), + None => false, + }) +} + +/// Whether the build log at `log` says the build used the system's +/// libraries ([`SYSTEM_LIBRARY_LOG`]). A log that cannot be read says +/// nothing. +fn log_says_system_libraries(log: &Path) -> bool { + use std::io::Read as _; + let Ok((file, _)) = crate::utils::fs::open_regular_file_sync(log) else { + return false; + }; + let mut head = Vec::new(); + if file.take(BUILD_LOG_HEAD).read_to_end(&mut head).is_err() { + return false; + } + String::from_utf8_lossy(&head).contains(SYSTEM_LIBRARY_LOG) +} + +/// What says the extension of `copy`, a gem RubyGems built, links the +/// system's libraries instead of the ones the gem packs, when something +/// does. Any of three, read from files and the environment alone: +/// +/// * the build arguments RubyGems recorded for the copy +/// (`/build_info/.info`; `gem install … -- +/// --use-system-libraries`, Bundler's `build.` setting), which a +/// rebuild is given again; +/// * the log of the build that is installed; +/// * [`SYSTEM_LIBRARY_ENV`], which a rebuild would follow. +/// +/// Such a build compiles nothing of a library the gem packs, so a record's +/// [`is_vendored_library_input`] files cannot take effect in it. +fn system_library_build(copy: &GemCopy) -> Option { + system_library_evidence(copy, std::env::var_os(SYSTEM_LIBRARY_ENV).is_some()) +} + +/// [`system_library_build`], told whether [`SYSTEM_LIBRARY_ENV`] is set. +fn system_library_evidence(copy: &GemCopy, env_set: bool) -> Option { + let info = copy + .home + .join("build_info") + .join(format!("{}.info", copy.full_name)); + if let Ok(args) = crate::utils::fs::read_regular_to_string_sync(&info) { + if let Some(arg) = args + .lines() + .map(str::trim) + .find(|a| is_system_library_arg(a)) + { + return Some(format!( + "`{arg}` is among the build arguments RubyGems recorded for it" + )); + } + } + if installed_extension_dirs(copy) + .iter() + .any(|ext| log_says_system_libraries(&ext.join(BUILD_LOG))) + { + return Some("the log of its build says so".to_string()); + } + env_set.then(|| format!("`{SYSTEM_LIBRARY_ENV}` is set, and a rebuild follows it")) +} + /// A gem record's native-extension build inputs on one installed copy. #[derive(Debug, Clone, Default, PartialEq, Eq)] struct NativeScope { @@ -1349,9 +1460,21 @@ enum RubyRun<'a> { }, /// Build the extensions of the staged gem at `spec` inside /// `stage_home`: runs the staged tree's build scripts. + /// + /// `as_installed`: the installed copy is one RubyGems built, and the + /// rebuild is made the way that build was, with the arguments RubyGems + /// recorded for it. A precompiled copy was built by its publisher from + /// the libraries the gem packs, whatever this machine is set up to + /// build with: arguments recorded for it were never used (Bundler's + /// `build.nokogiri --use-system-libraries`, left in a project from the + /// years before nokogiri shipped precompiled gems, is recorded for the + /// platform gem too), so its rebuild takes none, and not + /// [`SYSTEM_LIBRARY_ENV`] either. Following them would replace the + /// library the gem ships with whichever the system has. StageBuild { spec: &'a Path, stage_home: &'a Path, + as_installed: bool, }, } @@ -1423,13 +1546,21 @@ async fn run_ruby( } "missing_deps" } - RubyRun::StageBuild { spec, stage_home } => { + RubyRun::StageBuild { + spec, + stage_home, + as_installed, + } => { command .arg("stage_build") .arg(spec) .arg(stage_home) - .arg(©.home) - .arg(©.full_name); + .arg(©.home); + if as_installed { + command.arg(©.full_name); + } else { + command.env_remove(SYSTEM_LIBRARY_ENV); + } // The stage home first: the gems the build needs and the // install lacks were put there, and nowhere else. if let Some(gem_path) = gem_path_for(&[stage_home, ©.home]) { @@ -3798,6 +3929,9 @@ async fn build_in_stage( let run = RubyRun::StageBuild { spec: &staged.spec_path, stage_home: &stage.home, + // The source gem of a copy RubyGems built is the copy's own gem; a + // precompiled copy's is the ruby-platform gem of its version. + as_installed: source.full_name() == copy.full_name, }; stage.beat(); let stdout = run_ruby(&probe.ruby, run, copy, env, BUILD_TIMEOUT) @@ -4640,6 +4774,46 @@ pub async fn apply_gem_package_patch( ), ); } + // A gem built against the system's copy of a library compiles nothing + // of the copy it packs, and a rebuild is made the way the installed + // build was. So the inputs of the packed copy that the record changes + // would be written and never built: the library the gem loads is the + // operating system's, which no gem patch reaches. + if scope.builds_extensions { + let vendored: Vec<&str> = scope + .inputs + .iter() + .map(|key| normalize_file_path(key)) + .filter(|path| is_vendored_library_input(path)) + .collect(); + let system = if vendored.is_empty() { + None + } else { + let copy = copy.clone(); + crate::utils::fs::run_blocking(move || system_library_build(©)).await + }; + if let Some(evidence) = system { + let shown = vendored + .iter() + .take(3) + .copied() + .collect::>() + .join(", "); + let more = match vendored.len().saturating_sub(3) { + 0 => String::new(), + n => format!(" and {n} more"), + }; + return refusal( + package_key, + pkg_path, + UNSUPPORTED_CODE, + format!( + "the patch changes a library the gem packs ({shown}{more}), but {} was built against the system's copy of that library ({evidence}), so nothing the patch changes there is compiled into it and the patch cannot take effect; nothing was written. What this install runs is the library the operating system provides: update that package, or reinstall the gem without `--use-system-libraries` so that it builds the library it packs, and apply again.", + copy.full_name + ), + ); + } + } let precompiled = scope.precompiled.is_some(); let (installed_files, absent) = files_as_installed(©, &scope, files).await; @@ -6260,6 +6434,92 @@ mod tests { files(&all) } + /// The inputs of a library the gem packs are told from the gem's own + /// sources: only the former go unbuilt in a system-library build. + #[test] + fn vendored_library_inputs_are_the_packed_librarys_alone() { + for path in [ + "patches/libxml2/0100-CVE-2025-0000.patch", + "patches/libxslt/0001-fix.patch", + "ports/patches/libxml2/0001-fix.patch", + "ports/archives/libxml2-2.13.6.tar.xz", + "dependencies.yml", + ] { + assert!(is_vendored_library_input(path), "{path}"); + } + for path in [ + "ext/nokogiri/xml_node.c", + "ext/nokogiri/extconf.rb", + "ext/nokogiri/patches/a.patch", + "gumbo-parser/src/parser.c", + "lib/nokogiri/xml/node.rb", + "Manifest.txt", + "dependencies.yml.orig", + "patches", + ] { + assert!(!is_vendored_library_input(path), "{path}"); + } + } + + #[test] + fn system_library_arguments_are_told_from_the_rest() { + for arg in [ + "--use-system-libraries", + "--enable-system-libraries", + "--use-system-libraries=true", + "--enable-system-libraries=yes", + ] { + assert!(is_system_library_arg(arg), "{arg}"); + } + for arg in [ + "--use-system-libraries=false", + "--use-system-libraries=No", + "--enable-system-libraries=0", + "--disable-system-libraries", + "--use-system-librariesx", + "--with-xml2-dir=/usr", + "", + ] { + assert!(!is_system_library_arg(arg), "{arg}"); + } + } + + /// A copy RubyGems built links the system's libraries when its recorded + /// build arguments, the log of its build or the environment says so, + /// and not when none does. + #[test] + fn a_system_library_build_is_told_from_arguments_log_or_environment() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path(); + let copy = installed_gem(home, "lib"); + let log = home.join("extensions/p/3.4.0/a-1").join(BUILD_LOG); + let info = home.join("build_info/a-1.info"); + std::fs::create_dir_all(info.parent().unwrap()).unwrap(); + + // Built from what the gem packs, with arguments of another kind, + // beside a gem that was not. + std::fs::write(&log, "Building a using packaged libraries.\n").unwrap(); + std::fs::write(&info, "--with-cflags=-O2\n--use-system-libraries=false\n").unwrap(); + std::fs::write(home.join("build_info/b-1.info"), "--use-system-libraries\n").unwrap(); + assert_eq!(system_library_evidence(©, false), None); + + let by_env = system_library_evidence(©, true).unwrap(); + assert!(by_env.contains(SYSTEM_LIBRARY_ENV), "{by_env}"); + + std::fs::write( + &log, + "ruby extconf.rb\nBuilding a using system libraries.\n", + ) + .unwrap(); + let by_log = system_library_evidence(©, false).unwrap(); + assert!(by_log.contains("log"), "{by_log}"); + + std::fs::write(&log, "Building a using packaged libraries.\n").unwrap(); + std::fs::write(&info, "--with-cflags=-O2\n --enable-system-libraries\n").unwrap(); + let by_args = system_library_evidence(©, false).unwrap(); + assert!(by_args.contains("`--enable-system-libraries`"), "{by_args}"); + } + /// In the source-built gem (its gemspec declares the extension) /// everything `extconf.rb` may build from is an input, not just the C /// files under the script's dir: a record that only adds diff --git a/docs/ecosystems.md b/docs/ecosystems.md index c8f89d538..5c4001fa3 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2113,6 +2113,16 @@ instead of being reported as patched. Ruby files are never build inputs outside `ext/` and a build script's directory: a patch that only changes `.rb` or `.rbs` files needs no compiler, wherever the gem keeps them. +A gem that packs a library and was installed with `--use-system-libraries` (nokogiri with the +system's libxml2, through `gem install nokogiri -- --use-system-libraries`, Bundler's +`build.nokogiri` setting or `NOKOGIRI_USE_SYSTEM_LIBRARIES`) does not compile the library it +packs. A patch to that packed library (a file under `patches/` or `ports/`, or +`dependencies.yml`) changes nothing in such an install, so it fails with +`native_extensions_unsupported` and nothing is written: the library that install runs is the +operating system's package, and updating that package is what fixes it. A patch to the gem's own +C sources is still rebuilt, against the system's libraries. A precompiled gem always carries the +libraries it packs, and is rebuilt with them even when the project still has that Bundler setting. + The build happens in a stage directory inside the gem home (`.socket-patch-build/`), which is removed afterwards. A gem the build needs that the install lacks (a precompiled nokogiri has no `mini_portile2`) is installed into that stage, never into your gem home. The installed gem is not diff --git a/tests/nokogiri/nokogiri_e2e.rb b/tests/nokogiri/nokogiri_e2e.rb index bcdee69ff..da184045f 100644 --- a/tests/nokogiri/nokogiri_e2e.rb +++ b/tests/nokogiri/nokogiri_e2e.rb @@ -26,7 +26,9 @@ # a rebuilt extension. # libxml2 a new `patches/libxml2/*.patch` (`ports/patches/libxml2` before # 1.6.7). nokogiri's build applies it to its vendored libxml2 and -# compiles the patch's name into the extension. +# compiles the patch's name into the extension. An install built +# with `--use-system-libraries` compiles no vendored libxml2, so +# there the record must be refused and nothing written. # # Each scenario runs `apply --check` (not in sync), `apply`, a load of # nokogiri through `bundle exec` in a fresh Ruby, `apply --check` (in sync), @@ -189,7 +191,16 @@ def check(ok, what, detail = nil) def install gemfile = ["source \"https://rubygems.org\"", "gem \"nokogiri\", \"#{@version}\""] - gemfile << "gem \"rails\", \"#{@opts[:rails]}\"" if @opts[:rails] + if @opts[:rails] + gemfile << "gem \"rails\", \"#{@opts[:rails]}\"" + # loofah 2.20 and later need `Nokogiri::HTML4` (nokogiri 1.12) while + # still declaring `nokogiri >= 1.5.9`, so a fresh resolve gives an + # older nokogiri a loofah that cannot load on it. A lock of those + # years holds the loofah and the sanitizer of those years. + if Gem::Version.new(@version) < Gem::Version.new("1.12") + gemfile << "gem \"loofah\", \"< 2.20\"" << "gem \"rails-html-sanitizer\", \"< 1.5\"" + end + end (@opts[:gems] || []).each { |line| gemfile << line } File.write(File.join(@proj, "Gemfile"), gemfile.join("\n") + "\n") want = @opts.fetch(:install) @@ -197,6 +208,10 @@ def install settings["BUNDLE_PATH"] = "vendor/bundle" if project_home? settings["BUNDLE_FORCE_RUBY_PLATFORM"] = "true" if %w[source system-libraries].include?(want) settings["BUNDLE_BUILD__NOKOGIRI"] = "--use-system-libraries" if want == "system-libraries" + (@opts[:settings] || []).each do |pair| + key, value = pair.split("=", 2) + settings[key] = value.to_s + end if project_home? FileUtils.mkdir_p(File.join(@proj, ".bundle")) lines = settings.map { |k, v| "#{k}: \"#{v}\"" } @@ -402,8 +417,10 @@ def scenario(name) when "libxml2" record = libxml2_record return skip("this release reads no libxml2 patch directory") && nil unless record - return skip("built against the system's libxml2, which no gem patch changes") && nil if @shape == "system-libraries" return skip("JRuby loads no libxml2") && nil if @java && @opts[:build] == "ok" + # Built against the system's libxml2: nothing compiles the copy the + # gem packs, so a patch to that copy cannot take effect. + return not_applied(record, "native_extensions_unsupported") if @shape == "system-libraries" native(record) do |now| now["libxml_patches"].include?(LIBXML2_PATCH) && (@baseline["libxml_patches"] - now["libxml_patches"]).empty? @@ -579,7 +596,8 @@ class SocketPatchE2E < Rails::Application RUBY end -opts = { :install => "any", :build => "ok", :gem_home => "project", :scenarios => %w[ruby c libxml2], :gems => [] } +opts = { :install => "any", :build => "ok", :gem_home => "project", :scenarios => %w[ruby c libxml2], :gems => [], + :settings => [] } parser = OptionParser.new do |o| o.banner = "usage: ruby nokogiri_e2e.rb --socket-patch BIN --nokogiri VERSION [options]" o.on("--socket-patch BIN", "the socket-patch binary under test") { |v| opts[:socket_patch] = v } @@ -601,6 +619,8 @@ class SocketPatchE2E < Rails::Application o.on("--scenarios LIST", Array, "of ruby,c,libxml2 (default: all three)") { |v| opts[:scenarios] = v } o.on("--rails VERSION", "also install this Rails (a Gemfile requirement, for example '~> 7.1.0') and check", "that a booted application sanitizes HTML through the patched nokogiri") { |v| opts[:rails] = v } + o.on("--bundle-setting KEY=VALUE", "one more Bundler setting for the install, for example", + "BUNDLE_BUILD__NOKOGIRI=--use-system-libraries") { |v| opts[:settings] << v } o.on("--gem LINE", "one more Gemfile line, for example 'gem \"rails\", \"7.1.5\"'") { |v| opts[:gems] << v } o.on("--work DIR", "build the project in DIR and keep it") { |v| opts[:work] = v } end From 188e436605bcc2c8821f983741d33843be124004 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 13:19:56 -0500 Subject: [PATCH 05/11] Name SOCKET_RUBYGEMS_URL when a gem server in the lock may be a mirror A precompiled gem whose lock names a private gem server is refused with "put the source gem in cache/". Most such servers are mirrors of rubygems.org, and naming one in SOCKET_RUBYGEMS_URL is all it takes. Co-Authored-By: Claude Fable 5.2 --- .../socket-patch-core/src/patch/gem_source.rs | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/socket-patch-core/src/patch/gem_source.rs b/crates/socket-patch-core/src/patch/gem_source.rs index a4c26d7f3..612eea14c 100644 --- a/crates/socket-patch-core/src/patch/gem_source.rs +++ b/crates/socket-patch-core/src/patch/gem_source.rs @@ -242,8 +242,19 @@ impl GemSource { format!("{}.gem", id.full_name()), home.join("cache").display().to_string(), ); - if self.elsewhere.contains_key(&id.name) { - return format!("Put {file} in {cache}."); + if let Some(source) = self.elsewhere.get(&id.name) { + // A gem server the lock names may be a mirror of the registry + // (Artifactory, a pull-through cache): it serves this archive, + // and only the user can say it is one. + let mirror = if source.starts_with("http") { + format!( + ", or, if {source} is a mirror of rubygems.org, set SOCKET_RUBYGEMS_URL to \ + it and apply again" + ) + } else { + String::new() + }; + return format!("Put {file} in {cache}{mirror}."); } match &self.registry { Ok(_) => format!( @@ -839,6 +850,13 @@ mod tests { let remedy = online.remedy(&home, &private); assert!(!remedy.contains("network access"), "{remedy}"); assert!(remedy.contains("inhouse-9.9.9.gem"), "{remedy}"); + // The lock names a gem server, which may be a mirror: the remedy + // says how to name it, without its credentials. + assert!( + remedy.contains("gems.example.test") && remedy.contains("SOCKET_RUBYGEMS_URL"), + "{remedy}" + ); + assert!(!remedy.contains("secret"), "{remedy}"); // In the home's cache, even a private gem's archive is its source. std::fs::write(cache_path(&home, &private), b"private").unwrap(); assert_eq!(online.archive(&home, &private).await.unwrap(), b"private"); From 95b54a1b0ec96bf35433fc59eac1d7454c32920f Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 13:54:11 -0500 Subject: [PATCH 06/11] Rebuild a gem against the libraries its installed build linked Review of the previous commit found the system-library handling covered precompiled copies only and guessed at mkmf's rules: - A gem RubyGems built is rebuilt against what its installed build linked, read from that build's log, else from the recorded build arguments. A nokogiri installed with NOKOGIRI_USE_SYSTEM_LIBRARIES set for the install alone was rebuilt with the packed libxml2, and one built from the packed libraries was rebuilt against the system's when the variable was set at apply time. - Build arguments are read as mkmf reads them (--enable, then --disable, then --use, any value a yes), word by word, since Bundler 1 recorded a whole setting on one line. - The variable alone counts only for nokogiri, and only when neither the log nor the arguments say what the copy links. - apply --check and vex do not attest a packed-library record on a system-library build, whatever marker the copy holds. - The refusal message had lost its line continuations. - A lock's gem server and SOCKET_RUBYGEMS_URL name one server with or without credentials, and the mirror hint is given only where it can work. The x86_64 Linux legs of the nokogiri matrix run the one static binary instead of building the CLI fourteen times, a leg covers the variable-only install, and the workflow's development trigger is gone. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/nokogiri-compatibility.yml | 58 ++- crates/socket-patch-cli/CLI_CONTRACT.md | 43 +- .../tests/e2e_gem_native_ext_build.rs | 167 +++++--- crates/socket-patch-core/src/patch/gem_ext.rs | 388 ++++++++++++------ .../socket-patch-core/src/patch/gem_source.rs | 90 +++- docs/ecosystems.md | 7 +- tests/nokogiri/nokogiri_e2e.rb | 19 +- 7 files changed, 558 insertions(+), 214 deletions(-) diff --git a/.github/workflows/nokogiri-compatibility.yml b/.github/workflows/nokogiri-compatibility.yml index 33ed08134..b9f09e937 100644 --- a/.github/workflows/nokogiri-compatibility.yml +++ b/.github/workflows/nokogiri-compatibility.yml @@ -24,7 +24,11 @@ name: nokogiri patch compatibility # system-libraries `--use-system-libraries`: the extension is rebuilt # with the recorded build arguments, and a patch to the # vendored libxml2, which such a build does not compile, is -# refused. The `legacy setting` leg is a precompiled install +# refused. The `by variable` leg asks for it with +# NOKOGIRI_USE_SYSTEM_LIBRARIES set for the install alone, +# so only the build's log says what it linked, and the +# rebuild, run without the variable, must link the same. +# The `legacy setting` leg is a precompiled install # in a project that still carries that Bundler setting from # the years before precompiled gems: its rebuild must keep # the libxml2 the gem ships, not link the system's. @@ -36,9 +40,10 @@ name: nokogiri patch compatibility # run the same script inside an official Ruby image, where the gems land in # the image's own gem home (/usr/local/bundle) and the C library and # compiler are the image's: musl on Alpine, and the Debian releases old -# Rubies were deployed on. They run the static musl binary the `static-cli` -# job builds, because a binary built on the runner needs a newer glibc than -# those images have. +# Rubies were deployed on. A binary built on the runner needs a newer glibc +# than those images have, so the `static-cli` job builds one static musl +# binary, and every x86_64 Linux leg runs it, on the runner too: one build +# instead of one per leg. The macOS, Windows and ARM legs build their own. # # Every leg downloads gems from rubygems.org, and a rebuild of a precompiled # install downloads the source gem and `mini_portile2` from it too. @@ -60,8 +65,7 @@ on: - 'crates/socket-patch-core/src/patch/gem_source.rs' - 'crates/socket-patch-core/src/crawlers/ruby_crawler.rs' push: - # TEMPORARY while this workflow is developed: remove the second branch. - branches: [main, test/nokogiri-e2e] + branches: [main] paths: - '.github/workflows/nokogiri-compatibility.yml' - 'tests/nokogiri/**' @@ -126,31 +130,55 @@ jobs: - {os: ubuntu-latest, ruby: '2.3', nokogiri: '1.6.8.1', install: source, rails: '~> 4.2.0', bundler: '1'} - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: source} - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: system-libraries, system-libxml2: true} + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: system-libraries, system-libxml2: true, args: '--system-libraries-by variable', note: by variable} - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, system-libxml2: true, args: '--bundle-setting BUNDLE_BUILD__NOKOGIRI=--use-system-libraries', note: legacy setting} # No compiler on PATH: nothing may change. - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, build: unavailable, args: '--hide-toolchain', note: no toolchain} # JRuby: the Ruby-only record applies, a C record is refused. - {os: ubuntu-latest, ruby: 'jruby-9.4', nokogiri: '1.18.10', install: java, build: refused} # The other platform gems. - - {os: ubuntu-24.04-arm, ruby: '3.4', nokogiri: '1.18.10', install: precompiled} - - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled} - - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: source} + - {os: ubuntu-24.04-arm, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, cli: build} + - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, cli: build} + - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: source, cli: build} # A short project path: the MinGW tools stop at 260 characters, # and a build in the stage is some 60 deeper than one in place. - - {os: windows-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, args: '--work "$RUNNER_TEMP/n"'} + - {os: windows-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, cli: build, args: '--work "$RUNNER_TEMP/n"'} + needs: static-cli runs-on: ${{ vars.DISABLE_DEPOT_RUNNERS != 'true' && matrix.os == 'ubuntu-latest' && 'depot-ubuntu-24.04-4' || matrix.os }} timeout-minutes: 60 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false - - run: rustup show - - uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1 + # `cli: build` legs (not x86_64 Linux) build the binary they run. + - if: matrix.cli == 'build' + run: rustup show + - if: matrix.cli == 'build' + uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1 with: shared-key: dev-${{ matrix.os }} save-if: ${{ github.ref == 'refs/heads/main' }} - name: Build socket-patch - run: cargo build --locked -p socket-patch-cli + if: matrix.cli == 'build' + shell: bash + # A relative path: the Ruby of a Windows leg does not read the + # `/d/a/...` paths its shell prints. + run: | + cargo build --locked -p socket-patch-cli + echo "SOCKET_PATCH_BIN=target/debug/socket-patch" >> "$GITHUB_ENV" + - name: Download the static socket-patch + if: matrix.cli != 'build' + uses: ./.github/actions/download-artifact + with: + pattern: nokogiri-static-cli* + merge-multiple: 'true' + path: static-cli + verify: test -s static-cli/socket-patch + - name: Use the static socket-patch + if: matrix.cli != 'build' + run: | + chmod +x static-cli/socket-patch + echo "SOCKET_PATCH_BIN=static-cli/socket-patch" >> "$GITHUB_ENV" - name: Setup Ruby (attempt 1) # setup-ruby downloads the prebuilt Ruby from a github.com release # asset; a CDN blip there is not a result. Try once more. @@ -183,12 +211,12 @@ jobs: ruby --version # E2E_ARGS is a shell-quoted list of flags from the matrix above. eval "set -- $E2E_ARGS" - ruby tests/nokogiri/nokogiri_e2e.rb --socket-patch target/debug/socket-patch \ + ruby tests/nokogiri/nokogiri_e2e.rb --socket-patch "$SOCKET_PATCH_BIN" \ --nokogiri "$E2E_NOKOGIRI" --install "$E2E_INSTALL" --build "$E2E_BUILD" \ ${E2E_RAILS:+--rails "$E2E_RAILS"} "$@" static-cli: - name: static socket-patch for the container legs + name: static socket-patch for the x86_64 Linux legs if: github.event.pull_request.draft != true runs-on: ${{ vars.DISABLE_DEPOT_RUNNERS == 'true' && 'ubuntu-latest' || 'depot-ubuntu-24.04-4' }} timeout-minutes: 45 diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index d5ec08f42..91ba1ab8f 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -955,10 +955,11 @@ name: nothing of it is run. This holds whatever lock governs the gem home. declare extensions, and be the copy's own source (above). The record's files are laid over the staged gem, and every `beforeHash` must hold there, whatever the mismatch policy of the run. RubyGems then builds the staged gem's extension in the stage. A gem RubyGems built is rebuilt the -way it was built, with the build arguments RubyGems recorded for the installed copy -(`build_info/`). A precompiled gem is rebuilt the way its publisher built it, from the libraries -the gem packs: build arguments recorded for it were never used to build it and are not used now, -and `NOKOGIRI_USE_SYSTEM_LIBRARIES` is removed from the build's environment. (Bundler's +way it was built: with the build arguments RubyGems recorded for the installed copy +(`build_info/`), and against the libraries its installed build linked (below). A precompiled gem +is rebuilt the way its publisher built it, from the libraries the gem packs: build arguments +recorded for it were never used to build it and are not used now, and +`NOKOGIRI_USE_SYSTEM_LIBRARIES` is removed from the build's environment. (Bundler's `build.nokogiri --use-system-libraries`, which many projects kept from the years before nokogiri shipped precompiled gems, is recorded for the platform gem too; following it would replace the libxml2 the gem ships with the system's.) A gem the staged gem depends on at runtime that is not on @@ -976,16 +977,30 @@ loaded from where it was built. The staged build is set aside: a gem RubyGems bu place (below), a precompiled gem is refused. **A gem built against the system's libraries.** A gem that packs a library (nokogiri packs -libxml2 and libxslt) and was built against the system's copy instead compiles nothing of the -copy it packs. A record that changes the packed copy (a file under `patches/` or `ports/`, or -`dependencies.yml`: mini_portile's layout) cannot take effect in such an install, whose library is -the operating system's. It is refused with `native_extensions_unsupported` and nothing is -written, so `apply --check` and `vex` never attest it. Three things say a copy is such a build, -each read without running anything: `--use-system-libraries` or `--enable-system-libraries` -among the build arguments RubyGems recorded for it, "using system libraries" in the log of its -installed build (`gem_make.out`), or `NOKOGIRI_USE_SYSTEM_LIBRARIES` in the environment of the -run, which a rebuild would follow. A record of the gem's own sources (`ext/**`) is rebuilt -against the system's libraries as before. A precompiled gem is never such a build. +libxml2 and libxslt) can be built against the system's copy instead, and then compiles nothing of +the copy it packs. What the installed build of a gem RubyGems built linked is read from files, +without running anything: the log of that build (`gem_make.out`, where nokogiri writes "using +system libraries" or "using packaged libraries"), else the build arguments RubyGems recorded for +the copy, read as mkmf reads them (`--enable-system-libraries`, then +`--disable-system-libraries`, then `--use-system-libraries`, each with any value; a line that +holds several arguments, as Bundler 1 recorded a `build.` setting, is read word by word). + +- A rebuild links what the installed build linked, whatever `NOKOGIRI_USE_SYSTEM_LIBRARIES` is + when `apply` runs: the variable is set for the build of a copy built against the system's + libraries, removed for one built from the libraries it packs, and left as it is when neither + the log nor the arguments say. +- A record that changes the packed library (a file under `patches/` or `ports/`, or + `dependencies.yml`: mini_portile's layout) cannot take effect in a copy built against the + system's libraries, whose library is the operating system's. It is refused with + `native_extensions_unsupported` and nothing is written. So is one for a nokogiri whose log and + arguments say nothing while `NOKOGIRI_USE_SYSTEM_LIBRARIES` is set, which its rebuild would + follow. `apply --check` and `vex` do not attest such a record on a copy built against the + system's libraries, whatever marker the copy holds. A record of the gem's own sources + (`ext/**`) is rebuilt, against the system's libraries. + +A precompiled gem is never such a build. Gems that keep a packed library elsewhere (rugged's +`vendor/libgit2`, ffi's `ext/ffi_c/libffi`) are not recognised: a record for the packed library +of one built against the system's is still rebuilt and attested. **Into the installed copy.** The record's files are written into the copy, and the build takes the place of the compiled code: diff --git a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs index 0dde41a70..5d285aa6b 100644 --- a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs +++ b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs @@ -1729,7 +1729,7 @@ fn a_precompiled_copy_is_rebuilt_without_the_build_arguments_recorded_for_it() { let ruby = FakeRuby::new(); ruby.serve_source_gem(&c_source(1)); - let env = [("NOKOGIRI_USE_SYSTEM_LIBRARIES", "1")]; + let env = [(SYSTEM_LIBRARIES, "1")]; let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &env); assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); assert_eq!(event_action(&stdout), "applied", "{stdout}"); @@ -1739,9 +1739,7 @@ fn a_precompiled_copy_is_rebuilt_without_the_build_arguments_recorded_for_it() { "the build was given the arguments recorded for the platform gem" ); assert!( - !ruby - .env_seen("stage_build") - .contains("NOKOGIRI_USE_SYSTEM_LIBRARIES"), + !ruby.env_seen("stage_build").contains(SYSTEM_LIBRARIES), "the build was told to use the system's libraries" ); assert_eq!( @@ -1750,48 +1748,61 @@ fn a_precompiled_copy_is_rebuilt_without_the_build_arguments_recorded_for_it() { ); } +/// The variable nokogiri's build reads for linking the system's libxml2. +const SYSTEM_LIBRARIES: &str = "NOKOGIRI_USE_SYSTEM_LIBRARIES"; + +/// [`fake_native_gem`] with its source gem in the home's `cache/`, and its +/// gem home. +#[cfg(unix)] +fn built_gem_with_its_archive() -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf) { + let (tmp, proj, gem_dir) = fake_native_gem(true); + let home = proj.join("vendor/bundle/ruby/3.4.0"); + std::fs::create_dir_all(home.join("cache")).unwrap(); + std::fs::write(home.join("cache/sp_native-1.0.0.gem"), b"the source gem").unwrap(); + std::fs::create_dir_all(home.join("build_info")).unwrap(); + (tmp, proj, gem_dir, home) +} + +/// Say, in the log of the installed build, which libraries it linked. +#[cfg(unix)] +fn write_build_log(home: &Path, libraries: &str) { + std::fs::write( + home.join("extensions/x86_64-linux/3.4.0") + .join(FULL_NAME) + .join("gem_make.out"), + format!("ruby extconf.rb\nBuilding sp_native using {libraries} libraries.\n"), + ) + .unwrap(); +} + /// A gem built against the system's copy of a library compiles nothing of /// the copy it packs, so a record that changes the packed copy (the shape /// of a third of the published nokogiri patches: one more /// `patches/libxml2/*.patch`) cannot take effect there. It is refused from -/// files alone, whichever way the build says what it linked, and never -/// attested: before, it was written, "rebuilt" against the same system -/// library and attested as patched. A record of the gem's own sources is -/// still rebuilt, with the arguments RubyGems recorded. +/// files alone, whichever way the installed build says what it linked, and +/// never attested: before, it was written, "rebuilt" against the same +/// system library and attested as patched. The same record on a copy built +/// from what the gem packs is built. #[cfg(unix)] #[test] fn a_packed_library_patch_to_a_system_library_build_is_refused() { let library_patch: [RecordFile<'_>; 1] = [("patches/libsp/0100-CVE-test.patch", None, "fix\n")]; - let new_gem = || { - let (tmp, proj, gem_dir) = fake_native_gem(true); - let home = proj.join("vendor/bundle/ruby/3.4.0"); - std::fs::create_dir_all(home.join("cache")).unwrap(); - std::fs::write(home.join("cache/sp_native-1.0.0.gem"), b"the source gem").unwrap(); - std::fs::create_dir_all(home.join("build_info")).unwrap(); - (tmp, proj, gem_dir, home) - }; - let recorded = |home: &Path| { - std::fs::write( - home.join("build_info").join(format!("{FULL_NAME}.info")), - "--with-cflags=-O2\n--use-system-libraries\n", - ) - .unwrap(); - }; - for evidence in ["arguments", "log", "environment"] { - let (_tmp, proj, _gem_dir, home) = new_gem(); + for evidence in ["arguments", "arguments in one line", "log"] { + let (_tmp, proj, _gem_dir, home) = built_gem_with_its_archive(); write_record(&proj.join(".socket"), PURL, &library_patch); - let mut env = Vec::new(); + let info = home.join("build_info").join(format!("{FULL_NAME}.info")); match evidence { - "arguments" => recorded(&home), - "log" => std::fs::write( - home.join("extensions/x86_64-linux/3.4.0") - .join(FULL_NAME) - .join("gem_make.out"), - "ruby extconf.rb\nBuilding sp_native using system libraries.\n", + "arguments" => { + std::fs::write(info, "--with-cflags=-O2\n--use-system-libraries\n").unwrap() + } + // As Bundler 1 recorded a `build.` setting. + "arguments in one line" => std::fs::write( + info, + "--use-system-libraries --with-sp-include=/usr/include\n", ) .unwrap(), - _ => env.push(("NOKOGIRI_USE_SYSTEM_LIBRARIES", "1")), + _ => write_build_log(&home, "system"), } let ruby = FakeRuby::new(); ruby.serve_source_gem(&c_source(1)); @@ -1801,7 +1812,7 @@ fn a_packed_library_patch_to_a_system_library_build_is_refused() { &["apply", "--json", "--offline"][..], &["apply", "--json", "--offline", "--dry-run"], ] { - let (code, stdout, stderr) = ruby.run(&proj, args, &env); + let (code, stdout, stderr) = ruby.run(&proj, args, &[]); assert_eq!(code, 1, "{evidence} {args:?}: {stdout}\n{stderr}"); let envelope = parse_json_envelope(&stdout); let error = common::envelope::event_for(&envelope, PURL)["error"] @@ -1811,10 +1822,14 @@ fn a_packed_library_patch_to_a_system_library_build_is_refused() { assert!( error.contains("native_extensions_unsupported") && error.contains("patches/libsp/0100-CVE-test.patch") - && error.contains("the system's copy of that library") - && error.contains("nothing was written"), + && error.contains("was built against the system's copy of that library") + && error.contains("cannot take effect; nothing was written"), "{evidence} {args:?}: {error}" ); + assert!( + !error.contains(" "), + "the message has a gap in it: {error}" + ); } assert_eq!( ruby.calls(), @@ -1822,40 +1837,100 @@ fn a_packed_library_patch_to_a_system_library_build_is_refused() { "{evidence}: Ruby ran for a patch that cannot take effect" ); assert_tree(&proj.join("vendor"), &tree_before, evidence); - let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--check"], &env); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--check"], &[]); assert_ne!(code, 0, "{evidence}: {stdout}\n{stderr}"); assert!( - !vex_attests(|args| ruby.run(&proj, args, &env)), + !vex_attests(|args| ruby.run(&proj, args, &[])), "{evidence}: vex attested a patch that is compiled into nothing" ); } - // The same record on a copy built from what the gem packs is built. - let (_tmp, proj, gem_dir, _home) = new_gem(); + // A copy built from what the gem packs builds the same record, with the + // variable set or not: its log says what it links. + let (_tmp, proj, gem_dir, home) = built_gem_with_its_archive(); + write_build_log(&home, "packaged"); write_record(&proj.join(".socket"), PURL, &library_patch); let ruby = FakeRuby::new(); ruby.serve_source_gem(&c_source(1)); - let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + let env = [(SYSTEM_LIBRARIES, "1")]; + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &env); assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); assert_eq!(event_action(&stdout), "applied", "{stdout}"); assert!(gem_dir.join("patches/libsp/0100-CVE-test.patch").is_file()); - assert!(vex_attests(|args| ruby.run(&proj, args, &[]))); + assert!(vex_attests(|args| ruby.run(&proj, args, &env))); + // Applied and built: a second run has nothing to refuse. + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &env); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!(event_action(&stdout), "skipped", "{stdout}"); - // And a record of the gem's own sources is rebuilt against the system's - // libraries, as the installed build was. - let (_tmp, proj, _gem_dir, home) = new_gem(); - recorded(&home); + // A marker over a build that links the system's libraries attests + // nothing of the packed library, whoever wrote it. + write_build_log(&home, "system"); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--check"], &[]); + assert_ne!(code, 0, "{stdout}\n{stderr}"); + assert!(!vex_attests(|args| ruby.run(&proj, args, &[]))); +} + +/// A record of the gem's own sources is rebuilt against the libraries the +/// installed build linked, whatever the environment says by the time +/// `apply` runs: a gem installed with the variable set for that one +/// command is rebuilt with it, and a gem built from the libraries it packs +/// is rebuilt without it. The arguments RubyGems recorded are given again. +#[cfg(unix)] +#[test] +fn a_rebuild_links_the_libraries_the_installed_build_linked() { + // Built against the system's, by the variable alone; `apply` runs + // without it. + let (_tmp, proj, _gem_dir, home) = built_gem_with_its_archive(); + write_build_log(&home, "system"); write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); let ruby = FakeRuby::new(); ruby.serve_source_gem(&c_source(1)); let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); assert_eq!(event_action(&stdout), "applied", "{stdout}"); + assert!( + ruby.env_seen("stage_build") + .contains(&format!("{SYSTEM_LIBRARIES}=1")), + "the rebuild of a system-library build was not told to link them" + ); + assert_eq!(ruby.stage_build_args_of(), FULL_NAME); + + // Built from what the gem packs; `apply` runs with the variable set. + let (_tmp, proj, _gem_dir, home) = built_gem_with_its_archive(); + write_build_log(&home, "packaged"); + std::fs::write( + home.join("build_info").join(format!("{FULL_NAME}.info")), + "--with-cflags=-O2\n", + ) + .unwrap(); + write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + let env = [(SYSTEM_LIBRARIES, "1")]; + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &env); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert!( + !ruby.env_seen("stage_build").contains(SYSTEM_LIBRARIES), + "the rebuild of a packaged build was told to link the system's libraries" + ); assert_eq!( ruby.stage_build_args_of(), FULL_NAME, "the rebuild takes the arguments RubyGems recorded for the copy" ); + + // The in-place rebuild (no source gem to stage) is made the same way. + let (_tmp, proj, _gem_dir) = fake_native_gem(true); + let home = proj.join("vendor/bundle/ruby/3.4.0"); + write_build_log(&home, "system"); + write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); + let ruby = FakeRuby::new(); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert!(ruby + .env_seen("build") + .contains(&format!("{SYSTEM_LIBRARIES}=1"))); } /// Without the source gem there is nothing to build from: offline and not diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index a2e9d8b70..f9f6a79af 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -97,7 +97,9 @@ //! copy it packs. A record that changes that copy (`patches/**`, `ports/**`, //! `dependencies.yml`) would be written, "rebuilt" against the same system //! library and attested, with nothing of it in what Ruby loads. It is -//! refused from files alone instead ([`system_library_build`]). +//! refused from files alone instead ([`links_system_libraries`]), and a +//! rebuild of the gem's own sources links what the installed build linked +//! ([`link_libraries`]). //! //! `vex` and `apply --check` attest a copy only when its marker matches the //! record's patched sources and every recorded artifact still hashes as @@ -270,20 +272,25 @@ const BUILD_LOG: &str = "gem_make.out"; /// Files RubyGems writes into an extension dir that are not build products. const EXT_DIR_METADATA: &[&str] = &[BUILD_COMPLETE, BUILD_LOG, "mkmf.log"]; -/// Build arguments that make a gem link the system's copy of a library it -/// would otherwise build from the sources it packs. mini_portile's -/// convention: nokogiri takes both spellings, sqlite3 the second. -const SYSTEM_LIBRARY_ARGS: &[&str] = &["--use-system-libraries", "--enable-system-libraries"]; +/// The build argument nokogiri and sqlite3 take for linking the system's +/// copy of a library the gem packs (mini_portile's convention), the one +/// that takes it back, and nokogiri's older spelling of the first. +const ENABLE_SYSTEM_LIBRARIES: &str = "--enable-system-libraries"; +const DISABLE_SYSTEM_LIBRARIES: &str = "--disable-system-libraries"; +const USE_SYSTEM_LIBRARIES: &str = "--use-system-libraries"; -/// The environment variable nokogiri's build takes for the same. +/// The environment variable nokogiri's build takes for the same, when no +/// argument says either way. const SYSTEM_LIBRARY_ENV: &str = "NOKOGIRI_USE_SYSTEM_LIBRARIES"; -/// What nokogiri's `extconf.rb` writes into the log of such a build -/// ("Building nokogiri using system libraries."). +/// What nokogiri's `extconf.rb` writes into the log of a build, one or the +/// other: "Building nokogiri using system libraries." / "… using packaged +/// libraries." const SYSTEM_LIBRARY_LOG: &str = "using system libraries"; +const PACKED_LIBRARY_LOG: &str = "using packaged libraries"; -/// How much of a build log is read for [`SYSTEM_LIBRARY_LOG`]: the line is -/// among the first an `extconf.rb` prints, and a log is not bounded. +/// How much of a build log is read for those lines: they are among the +/// first an `extconf.rb` prints, and a log is not bounded. const BUILD_LOG_HEAD: u64 = 1024 * 1024; /// Source and build-script extensions a native extension compiles. @@ -775,76 +782,127 @@ fn is_vendored_library_input(path: &str) -> bool { path == "dependencies.yml" || path.starts_with("patches/") || path.starts_with("ports/") } -/// Whether the build argument `arg` asks for the system's libraries -/// ([`SYSTEM_LIBRARY_ARGS`], bare or with a value that is not a "no"). -fn is_system_library_arg(arg: &str) -> bool { - SYSTEM_LIBRARY_ARGS - .iter() - .any(|name| match arg.strip_prefix(name) { - Some("") => true, - Some(rest) => rest.strip_prefix('=').is_some_and(|value| { - !matches!(value.to_ascii_lowercase().as_str(), "no" | "false" | "0") - }), - None => false, +/// Which copy of a library the gem packs an extension is built against. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +enum Libraries { + /// Nothing says: the build's arguments and environment decide, as they + /// did when the gem was installed. + #[default] + Unsaid, + /// The copy the gem packs. + Packed, + /// The system's. + System, +} + +/// What build arguments say of the libraries a build links, in the order +/// mkmf asks for them in nokogiri's `extconf.rb`: +/// [`ENABLE_SYSTEM_LIBRARIES`], then [`DISABLE_SYSTEM_LIBRARIES`], then +/// [`USE_SYSTEM_LIBRARIES`]. Each counts bare or with any value: mkmf +/// takes the value as it is, and `=false` is a string, which is true. +/// +/// `args` is a `build_info` file. A current RubyGems writes one argument a +/// line; Bundler 1 handed RubyGems a whole `build.` setting as one +/// argument, so a line can hold several, and each is read word by word. +fn libraries_by_args(args: &str) -> Libraries { + let has = |flag: &str| { + args.split_whitespace().any(|word| { + word.strip_prefix(flag) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('=')) }) + }; + if has(ENABLE_SYSTEM_LIBRARIES) { + Libraries::System + } else if has(DISABLE_SYSTEM_LIBRARIES) { + Libraries::Packed + } else if has(USE_SYSTEM_LIBRARIES) { + Libraries::System + } else { + Libraries::Unsaid + } } -/// Whether the build log at `log` says the build used the system's -/// libraries ([`SYSTEM_LIBRARY_LOG`]). A log that cannot be read says -/// nothing. -fn log_says_system_libraries(log: &Path) -> bool { +/// What the build log at `log` says of the libraries its build linked +/// ([`SYSTEM_LIBRARY_LOG`], [`PACKED_LIBRARY_LOG`]). A log that cannot be +/// read says nothing. +fn libraries_by_log(log: &Path) -> Libraries { use std::io::Read as _; let Ok((file, _)) = crate::utils::fs::open_regular_file_sync(log) else { - return false; + return Libraries::Unsaid; }; let mut head = Vec::new(); if file.take(BUILD_LOG_HEAD).read_to_end(&mut head).is_err() { - return false; + return Libraries::Unsaid; + } + let head = String::from_utf8_lossy(&head); + if head.contains(SYSTEM_LIBRARY_LOG) { + Libraries::System + } else if head.contains(PACKED_LIBRARY_LOG) { + Libraries::Packed + } else { + Libraries::Unsaid } - String::from_utf8_lossy(&head).contains(SYSTEM_LIBRARY_LOG) } -/// What says the extension of `copy`, a gem RubyGems built, links the -/// system's libraries instead of the ones the gem packs, when something -/// does. Any of three, read from files and the environment alone: +/// The libraries the installed extension of `copy`, a gem RubyGems built, +/// links, and what says so. Read from files alone: /// -/// * the build arguments RubyGems recorded for the copy -/// (`/build_info/.info`; `gem install … -- +/// * the log of the build that is installed (or parked while a rebuild +/// runs), which is the build itself speaking; +/// * else the build arguments RubyGems recorded for the copy +/// (`/build_info/.info`: `gem install … -- /// --use-system-libraries`, Bundler's `build.` setting), which a -/// rebuild is given again; -/// * the log of the build that is installed; -/// * [`SYSTEM_LIBRARY_ENV`], which a rebuild would follow. +/// rebuild is given again. /// -/// Such a build compiles nothing of a library the gem packs, so a record's -/// [`is_vendored_library_input`] files cannot take effect in it. -fn system_library_build(copy: &GemCopy) -> Option { - system_library_evidence(copy, std::env::var_os(SYSTEM_LIBRARY_ENV).is_some()) -} - -/// [`system_library_build`], told whether [`SYSTEM_LIBRARY_ENV`] is set. -fn system_library_evidence(copy: &GemCopy, env_set: bool) -> Option { +/// A gem installed with [`SYSTEM_LIBRARY_ENV`] alone has only its log to +/// say so, and one whose log was pruned and whose arguments say nothing is +/// [`Libraries::Unsaid`]. +fn installed_libraries(copy: &GemCopy) -> (Libraries, String) { + for ext in extension_dir_slots(copy) { + for dir in [ext.clone(), parked_build_path(&ext)] { + let said = libraries_by_log(&dir.join(BUILD_LOG)); + if said != Libraries::Unsaid { + return (said, "the log of its build says so".to_string()); + } + } + } let info = copy .home .join("build_info") .join(format!("{}.info", copy.full_name)); - if let Ok(args) = crate::utils::fs::read_regular_to_string_sync(&info) { - if let Some(arg) = args - .lines() - .map(str::trim) - .find(|a| is_system_library_arg(a)) - { - return Some(format!( - "`{arg}` is among the build arguments RubyGems recorded for it" - )); - } + let said = crate::utils::fs::read_regular_to_string_sync(&info) + .map(|args| libraries_by_args(&args)) + .unwrap_or_default(); + ( + said, + "the build arguments RubyGems recorded for it say so".to_string(), + ) +} + +/// Why nothing of a library `copy` packs is compiled into its extension, +/// when that is so: it links the system's ([`installed_libraries`]), or it +/// is nokogiri, nothing says what it links, and [`SYSTEM_LIBRARY_ENV`] is +/// set (`env_set`), which its rebuild would follow. A record's +/// [`is_vendored_library_input`] files cannot take effect in such a build. +fn links_system_libraries(copy: &GemCopy, env_set: bool) -> Option { + match installed_libraries(copy) { + (Libraries::System, evidence) => Some(evidence), + (Libraries::Unsaid, _) if env_set && gem_name_of(©.full_name) == "nokogiri" => Some( + format!("`{SYSTEM_LIBRARY_ENV}` is set, and nothing of its build says otherwise"), + ), + _ => None, } - if installed_extension_dirs(copy) +} + +/// The record's build inputs that are [`is_vendored_library_input`]s. +fn vendored_library_inputs(scope: &NativeScope) -> Vec { + scope + .inputs .iter() - .any(|ext| log_says_system_libraries(&ext.join(BUILD_LOG))) - { - return Some("the log of its build says so".to_string()); - } - env_set.then(|| format!("`{SYSTEM_LIBRARY_ENV}` is set, and a rebuild follows it")) + .map(|key| normalize_file_path(key)) + .filter(|path| is_vendored_library_input(path)) + .map(str::to_string) + .collect() } /// A gem record's native-extension build inputs on one installed copy. @@ -1269,7 +1327,14 @@ pub async fn verify_native_build( }; let files = files.clone(); let holds = crate::utils::fs::run_blocking(move || { - read_marker_sync(©.gem_dir).is_some_and(|m| marker_holds(&m, ©, &scope, &files)) + // A marker over a build that links the system's libraries says + // nothing of a library the gem packs: none of it was built. + let unbuilt = scope.builds_extensions + && !vendored_library_inputs(&scope).is_empty() + && installed_libraries(©).0 == Libraries::System; + !unbuilt + && read_marker_sync(©.gem_dir) + .is_some_and(|m| marker_holds(&m, ©, &scope, &files)) }) .await; if holds { @@ -1318,6 +1383,28 @@ struct Probe { lib_dir: PathBuf, /// What `ruby` said of itself, when it did. facts: Option, + /// The libraries a rebuild of the copy links ([`link_libraries`]): the + /// ones its installed build links, and for a precompiled copy the ones + /// the gem packs, which its publisher built it from. + libraries: Libraries, +} + +/// Make the build `command` link `libraries`, where nokogiri's build takes +/// that from the environment: a rebuild is made the way the installed +/// build was, whatever [`SYSTEM_LIBRARY_ENV`] is by the time `apply` runs. +/// A gem built with the variable set for its install alone (`RUN +/// NOKOGIRI_USE_SYSTEM_LIBRARIES=1 bundle install`) is rebuilt with it, and +/// one built from the libraries it packs is rebuilt without. +fn link_libraries(command: &mut std::process::Command, libraries: Libraries) { + match libraries { + Libraries::Packed => { + command.env_remove(SYSTEM_LIBRARY_ENV); + } + Libraries::System => { + command.env(SYSTEM_LIBRARY_ENV, "1"); + } + Libraries::Unsaid => {} + } } /// What a Ruby says of itself in a [`RubyRun::ExtensionsDir`] run. @@ -1461,20 +1548,22 @@ enum RubyRun<'a> { /// Build the extensions of the staged gem at `spec` inside /// `stage_home`: runs the staged tree's build scripts. /// - /// `as_installed`: the installed copy is one RubyGems built, and the - /// rebuild is made the way that build was, with the arguments RubyGems - /// recorded for it. A precompiled copy was built by its publisher from - /// the libraries the gem packs, whatever this machine is set up to - /// build with: arguments recorded for it were never used (Bundler's - /// `build.nokogiri --use-system-libraries`, left in a project from the - /// years before nokogiri shipped precompiled gems, is recorded for the - /// platform gem too), so its rebuild takes none, and not - /// [`SYSTEM_LIBRARY_ENV`] either. Following them would replace the + /// `recorded_args`: the installed copy is one RubyGems built, and the + /// rebuild is given the arguments RubyGems recorded for it. A + /// precompiled copy was built by its publisher from the libraries the + /// gem packs, whatever this machine is set up to build with: arguments + /// recorded for it were never used (Bundler's `build.nokogiri + /// --use-system-libraries`, left in a project from the years before + /// nokogiri shipped precompiled gems, is recorded for the platform gem + /// too), so its rebuild takes none. Following them would replace the /// library the gem ships with whichever the system has. + /// + /// `libraries`: [`Probe::libraries`]. StageBuild { spec: &'a Path, stage_home: &'a Path, - as_installed: bool, + recorded_args: bool, + libraries: Libraries, }, } @@ -1506,6 +1595,7 @@ async fn run_ruby( .arg(©.spec_path) .arg(&probe.extension_dir) .arg(&probe.require_path); + link_libraries(&mut command, probe.libraries); if let Some(gem_path) = gem_path_for(&[©.home]) { command.env("GEM_PATH", gem_path); } @@ -1549,18 +1639,18 @@ async fn run_ruby( RubyRun::StageBuild { spec, stage_home, - as_installed, + recorded_args, + libraries, } => { command .arg("stage_build") .arg(spec) .arg(stage_home) .arg(©.home); - if as_installed { + if recorded_args { command.arg(©.full_name); - } else { - command.env_remove(SYSTEM_LIBRARY_ENV); } + link_libraries(&mut command, libraries); // The stage home first: the gems the build needs and the // install lacks were put there, and nowhere else. if let Some(gem_path) = gem_path_for(&[stage_home, ©.home]) { @@ -2151,6 +2241,13 @@ async fn find_ruby( reasons.push(why); continue; } + let libraries = match platform { + Some(_) => Libraries::Packed, + None => { + let copy = copy.clone(); + crate::utils::fs::run_blocking(move || installed_libraries(©).0).await + } + }; return Ok(Probe { ruby, gem_dir: copy.gem_dir.clone(), @@ -2159,6 +2256,7 @@ async fn find_ruby( require_path, require_paths, facts, + libraries, }); } Err(format!( @@ -3931,7 +4029,8 @@ async fn build_in_stage( stage_home: &stage.home, // The source gem of a copy RubyGems built is the copy's own gem; a // precompiled copy's is the ruby-platform gem of its version. - as_installed: source.full_name() == copy.full_name, + recorded_args: source.full_name() == copy.full_name, + libraries: probe.libraries, }; stage.beat(); let stdout = run_ruby(&probe.ruby, run, copy, env, BUILD_TIMEOUT) @@ -4780,26 +4879,16 @@ pub async fn apply_gem_package_patch( // would be written and never built: the library the gem loads is the // operating system's, which no gem patch reaches. if scope.builds_extensions { - let vendored: Vec<&str> = scope - .inputs - .iter() - .map(|key| normalize_file_path(key)) - .filter(|path| is_vendored_library_input(path)) - .collect(); + let vendored = vendored_library_inputs(&scope); let system = if vendored.is_empty() { None } else { - let copy = copy.clone(); - crate::utils::fs::run_blocking(move || system_library_build(©)).await + let (copy, env_set) = (copy.clone(), std::env::var_os(SYSTEM_LIBRARY_ENV).is_some()); + crate::utils::fs::run_blocking(move || links_system_libraries(©, env_set)).await }; if let Some(evidence) = system { - let shown = vendored - .iter() - .take(3) - .copied() - .collect::>() - .join(", "); - let more = match vendored.len().saturating_sub(3) { + let shown = vendored.iter().take(3).cloned().collect::>(); + let more = match vendored.len().saturating_sub(shown.len()) { 0 => String::new(), n => format!(" and {n} more"), }; @@ -4808,7 +4897,14 @@ pub async fn apply_gem_package_patch( pkg_path, UNSUPPORTED_CODE, format!( - "the patch changes a library the gem packs ({shown}{more}), but {} was built against the system's copy of that library ({evidence}), so nothing the patch changes there is compiled into it and the patch cannot take effect; nothing was written. What this install runs is the library the operating system provides: update that package, or reinstall the gem without `--use-system-libraries` so that it builds the library it packs, and apply again.", + "the patch changes a library the gem packs ({}{more}), but {} was built \ + against the system's copy of that library ({evidence}), so nothing the \ + patch changes there is compiled into it and the patch cannot take effect; \ + nothing was written. What this install runs is the library the operating \ + system provides: update that package, or reinstall the gem without \ + `--use-system-libraries` so that it builds the library it packs, and \ + apply again.", + shown.join(", "), copy.full_name ), ); @@ -6115,6 +6211,7 @@ mod tests { require_paths: vec!["lib".to_string()], lib_dir: copy.gem_dir.join("lib"), facts: None, + libraries: Libraries::default(), }; let aside = set_aside(©, &probe).unwrap(); @@ -6461,63 +6558,112 @@ mod tests { } } + /// mkmf's reading of the arguments, not a guess at it: any value is a + /// yes, `--enable` beats `--disable`, which beats `--use`, and a line + /// Bundler 1 wrote holds several arguments. #[test] - fn system_library_arguments_are_told_from_the_rest() { - for arg in [ + fn build_arguments_say_which_libraries_a_build_links() { + for args in [ "--use-system-libraries", "--enable-system-libraries", "--use-system-libraries=true", - "--enable-system-libraries=yes", + "--use-system-libraries=false", + "--enable-system-libraries=no", + "--with-cflags=-O2\n --enable-system-libraries\n", + "--use-system-libraries --with-xml2-include=/usr/include/libxml2", + "--disable-system-libraries\n--enable-system-libraries", ] { - assert!(is_system_library_arg(arg), "{arg}"); + assert_eq!(libraries_by_args(args), Libraries::System, "{args}"); } - for arg in [ - "--use-system-libraries=false", - "--use-system-libraries=No", - "--enable-system-libraries=0", + for args in [ "--disable-system-libraries", - "--use-system-librariesx", - "--with-xml2-dir=/usr", + "--use-system-libraries\n--disable-system-libraries", + ] { + assert_eq!(libraries_by_args(args), Libraries::Packed, "{args}"); + } + for args in [ "", + "--with-xml2-dir=/usr", + "--use-system-librariesx", + "--with-opt=--use-system-libraries-not", ] { - assert!(!is_system_library_arg(arg), "{arg}"); + assert_eq!(libraries_by_args(args), Libraries::Unsaid, "{args}"); } } - /// A copy RubyGems built links the system's libraries when its recorded - /// build arguments, the log of its build or the environment says so, - /// and not when none does. + /// What the installed build of a copy RubyGems built links is read from + /// its log first, then from the arguments RubyGems recorded, and the + /// environment of the run counts only for nokogiri, and only when + /// neither says. #[test] - fn a_system_library_build_is_told_from_arguments_log_or_environment() { + fn the_installed_build_says_which_libraries_it_links() { let tmp = tempfile::tempdir().unwrap(); let home = tmp.path(); let copy = installed_gem(home, "lib"); let log = home.join("extensions/p/3.4.0/a-1").join(BUILD_LOG); let info = home.join("build_info/a-1.info"); std::fs::create_dir_all(info.parent().unwrap()).unwrap(); - - // Built from what the gem packs, with arguments of another kind, - // beside a gem that was not. - std::fs::write(&log, "Building a using packaged libraries.\n").unwrap(); - std::fs::write(&info, "--with-cflags=-O2\n--use-system-libraries=false\n").unwrap(); + // Another gem's arguments are not this one's. std::fs::write(home.join("build_info/b-1.info"), "--use-system-libraries\n").unwrap(); - assert_eq!(system_library_evidence(©, false), None); - let by_env = system_library_evidence(©, true).unwrap(); - assert!(by_env.contains(SYSTEM_LIBRARY_ENV), "{by_env}"); + // Nothing says, and the gem is not nokogiri: the variable is not + // about it. + assert_eq!(installed_libraries(©).0, Libraries::Unsaid); + assert_eq!(links_system_libraries(©, true), None); + std::fs::write(&info, "--with-cflags=-O2\n--use-system-libraries\n").unwrap(); + assert_eq!(installed_libraries(©).0, Libraries::System); + let by_args = links_system_libraries(©, false).unwrap(); + assert!(by_args.contains("arguments"), "{by_args}"); + + // The build's own log outranks them, either way. + std::fs::write( + &log, + "ruby extconf.rb\nBuilding a using packaged libraries.\n", + ) + .unwrap(); + assert_eq!(installed_libraries(©).0, Libraries::Packed); + assert_eq!(links_system_libraries(©, true), None); + std::fs::remove_file(&info).unwrap(); std::fs::write( &log, "ruby extconf.rb\nBuilding a using system libraries.\n", ) .unwrap(); - let by_log = system_library_evidence(©, false).unwrap(); + assert_eq!(installed_libraries(©).0, Libraries::System); + let by_log = links_system_libraries(©, false).unwrap(); assert!(by_log.contains("log"), "{by_log}"); - std::fs::write(&log, "Building a using packaged libraries.\n").unwrap(); - std::fs::write(&info, "--with-cflags=-O2\n --enable-system-libraries\n").unwrap(); - let by_args = system_library_evidence(©, false).unwrap(); - assert!(by_args.contains("`--enable-system-libraries`"), "{by_args}"); + // A build parked while its rebuild runs still says what it linked. + let ext = home.join("extensions/p/3.4.0/a-1"); + std::fs::rename(&ext, parked_build_path(&ext)).unwrap(); + assert_eq!(installed_libraries(©).0, Libraries::System); + } + + /// nokogiri with nothing to say what it links (its log pruned, no + /// arguments recorded) follows the variable when it is rebuilt, so a + /// patch to the libxml2 it packs is not known to be built. + #[test] + fn the_variable_counts_for_nokogiri_when_nothing_else_says() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path(); + let gem_dir = home.join("gems/nokogiri-1.18.10"); + std::fs::create_dir_all(&gem_dir).unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + std::fs::write(home.join("specifications/nokogiri-1.18.10.gemspec"), "").unwrap(); + let copy = GemCopy::of(&gem_dir).unwrap(); + assert_eq!(links_system_libraries(©, false), None); + let by_env = links_system_libraries(©, true).unwrap(); + assert!(by_env.contains(SYSTEM_LIBRARY_ENV), "{by_env}"); + + let ext = home.join("extensions/p/3.4.0/nokogiri-1.18.10"); + std::fs::create_dir_all(&ext).unwrap(); + std::fs::write( + ext.join(BUILD_LOG), + "Building nokogiri using packaged libraries.\n", + ) + .unwrap(); + assert_eq!(links_system_libraries(©, true), None); } /// In the source-built gem (its gemspec declares the extension) @@ -6880,6 +7026,7 @@ mod tests { platform: "arm64-darwin-25".to_string(), runs_platform: Some(true), }), + libraries: Libraries::Packed, } } @@ -7163,6 +7310,7 @@ mod tests { require_paths: vec!["lib".to_string()], lib_dir: copy.gem_dir.join("lib"), facts: None, + libraries: Libraries::default(), }; let stage = open_stage(©).unwrap(); assert!(stage.home.starts_with(&home), "staged inside the gem home"); diff --git a/crates/socket-patch-core/src/patch/gem_source.rs b/crates/socket-patch-core/src/patch/gem_source.rs index 612eea14c..e2c52448f 100644 --- a/crates/socket-patch-core/src/patch/gem_source.rs +++ b/crates/socket-patch-core/src/patch/gem_source.rs @@ -99,6 +99,39 @@ impl GemId { } } +/// `url` without the `user:password@` of its authority. A lock names a gem +/// server without the credentials Bundler keeps in its own config, while +/// `SOCKET_RUBYGEMS_URL` carries them: both name one server. +fn without_userinfo(url: &str) -> String { + let Some((scheme, rest)) = url.split_once("://") else { + return url.to_string(); + }; + let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); + match rest[..authority_end].rfind('@') { + Some(at) => format!("{scheme}://{}", &rest[at + 1..]), + None => url.to_string(), + } +} + +/// Whether `remote`, a lock's `remote:`, is the default registry +/// ([`is_rubygems_remote`]), with or without the credentials +/// `SOCKET_RUBYGEMS_URL` names it with. +fn is_registry_remote(remote: &str) -> bool { + is_rubygems_remote(remote) + || crate::formats::gem::same_remote( + &without_userinfo(remote), + &without_userinfo(&rubygems_base()), + ) +} + +/// Whether `source`, a lock's source as [`resolved_elsewhere`] names it, +/// is a gem server that could be a mirror of the registry and could be +/// named in `SOCKET_RUBYGEMS_URL`: reached over https (a download is taken +/// over nothing else), and not Socket's patch registry. +fn may_be_a_mirror(source: &str) -> bool { + source.starts_with("https://") && !source.contains("/patch-registry/") +} + /// The gems a Bundler lock resolves from somewhere that is not the default /// registry, each with that source as the lock names it (credentials /// redacted): whatever version it pins, the registry's gem of that name is @@ -113,7 +146,7 @@ pub(crate) fn resolved_elsewhere(lock: &str) -> HashMap { let source = if section.header == "GEM" { match section .remote_bases() - .find(|remote| !is_rubygems_remote(remote)) + .find(|remote| !is_registry_remote(remote)) { Some(remote) => crate::utils::redact::redact_urls_in(remote).into_owned(), None => continue, @@ -245,14 +278,15 @@ impl GemSource { if let Some(source) = self.elsewhere.get(&id.name) { // A gem server the lock names may be a mirror of the registry // (Artifactory, a pull-through cache): it serves this archive, - // and only the user can say it is one. - let mirror = if source.starts_with("http") { - format!( - ", or, if {source} is a mirror of rubygems.org, set SOCKET_RUBYGEMS_URL to \ - it and apply again" - ) + // and only the user can say it is one. Said only where naming + // it can work: a download is allowed in this run, and the + // server is one a download is taken from (https, and not + // Socket's patch registry, which serves patched gems only). + let mirror = if !self.offline && may_be_a_mirror(source) { + ", or, if that server is a mirror of rubygems.org, set SOCKET_RUBYGEMS_URL to \ + its URL and apply again" } else { - String::new() + "" }; return format!("Put {file} in {cache}{mirror}."); } @@ -762,6 +796,39 @@ mod tests { racc (1.8.1) sha256=4a7f6929691dbec8b5209a0b373bc2614882b55fc5d2e447a21aaa691303d62f\n\n\ BUNDLED WITH\n 4.0.15\n"; + /// A lock names a gem server without the credentials + /// `SOCKET_RUBYGEMS_URL` names it with, and the hint to name a mirror + /// is for a server a download could be taken from. + #[test] + fn a_server_is_the_same_with_or_without_credentials() { + for (with, without) in [ + ( + "https://user:tok@gems.example.test/api/gems/", + "https://gems.example.test/api/gems/", + ), + ("https://tok@gems.example.test", "https://gems.example.test"), + ( + "https://gems.example.test/a@b", + "https://gems.example.test/a@b", + ), + ("not a url", "not a url"), + ] { + assert_eq!(without_userinfo(with), without); + } + assert!(may_be_a_mirror("https://gems.example.test/api/gems")); + assert!(may_be_a_mirror( + "https://@gems.example.test/private" + )); + for source in [ + "http://gems.example.test", + "a git source", + "a path source", + "https://patch.socket.dev/patch-registry/gem/token/uuid", + ] { + assert!(!may_be_a_mirror(source), "{source}"); + } + } + /// A gem locked only as platform gems is still the registry's gem, so /// its ruby-platform archive may be fetched there. A gem any section /// resolves from another source is not, whatever version is asked for: @@ -851,11 +918,8 @@ mod tests { assert!(!remedy.contains("network access"), "{remedy}"); assert!(remedy.contains("inhouse-9.9.9.gem"), "{remedy}"); // The lock names a gem server, which may be a mirror: the remedy - // says how to name it, without its credentials. - assert!( - remedy.contains("gems.example.test") && remedy.contains("SOCKET_RUBYGEMS_URL"), - "{remedy}" - ); + // says how to name it. + assert!(remedy.contains("SOCKET_RUBYGEMS_URL"), "{remedy}"); assert!(!remedy.contains("secret"), "{remedy}"); // In the home's cache, even a private gem's archive is its source. std::fs::write(cache_path(&home, &private), b"private").unwrap(); diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 5c4001fa3..577c28e29 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2120,8 +2120,11 @@ packs. A patch to that packed library (a file under `patches/` or `ports/`, or `dependencies.yml`) changes nothing in such an install, so it fails with `native_extensions_unsupported` and nothing is written: the library that install runs is the operating system's package, and updating that package is what fixes it. A patch to the gem's own -C sources is still rebuilt, against the system's libraries. A precompiled gem always carries the -libraries it packs, and is rebuilt with them even when the project still has that Bundler setting. +C sources is still rebuilt, against the system's libraries: a rebuild links what the installed +build linked (its build log and recorded build arguments say which), even when +`NOKOGIRI_USE_SYSTEM_LIBRARIES` was set only for the install. A precompiled gem always carries +the libraries it packs, and is rebuilt with them even when the project still has that Bundler +setting. The build happens in a stage directory inside the gem home (`.socket-patch-build/`), which is removed afterwards. A gem the build needs that the install lacks (a precompiled nokogiri has no diff --git a/tests/nokogiri/nokogiri_e2e.rb b/tests/nokogiri/nokogiri_e2e.rb index da184045f..645d69cd3 100644 --- a/tests/nokogiri/nokogiri_e2e.rb +++ b/tests/nokogiri/nokogiri_e2e.rb @@ -207,7 +207,8 @@ def install settings = {} settings["BUNDLE_PATH"] = "vendor/bundle" if project_home? settings["BUNDLE_FORCE_RUBY_PLATFORM"] = "true" if %w[source system-libraries].include?(want) - settings["BUNDLE_BUILD__NOKOGIRI"] = "--use-system-libraries" if want == "system-libraries" + by_variable = @opts[:system_libraries_by] == "variable" + settings["BUNDLE_BUILD__NOKOGIRI"] = "--use-system-libraries" if want == "system-libraries" && !by_variable (@opts[:settings] || []).each do |pair| key, value = pair.split("=", 2) settings[key] = value.to_s @@ -217,6 +218,10 @@ def install lines = settings.map { |k, v| "#{k}: \"#{v}\"" } File.write(File.join(@proj, ".bundle", "config"), (["---"] + lines).join("\n") + "\n") @install_env = {} + # For the install alone, as `RUN NOKOGIRI_USE_SYSTEM_LIBRARIES=1 bundle + # install` sets it: RubyGems records no build argument, and nothing + # that runs later sees the variable. + @install_env["NOKOGIRI_USE_SYSTEM_LIBRARIES"] = "1" if want == "system-libraries" && by_variable else # The ambient configuration is not this script's to write: the # settings ride on the install's environment instead. @@ -229,8 +234,10 @@ def install attempts += 1 sh!(@install_env, *bundle("install", "--jobs", "4", "--retry", "3")) rescue Failure => e - # A registry blip, not a result: one more try before giving up. - raise if attempts >= 2 || e.message !~ /Network error|Gem::RemoteFetcher|HTTP|timed out|Timeout/i + # A registry blip, not a result: one more try before giving up. (Not + # "HTTP": Bundler names https://rubygems.org in every failure.) + blip = /Network error|Gem::RemoteFetcher::FetchError|Net::(Open|Read)Timeout|Could not (reach|fetch)/ + raise if attempts >= 2 || e.message !~ blip retry end @@ -597,7 +604,7 @@ class SocketPatchE2E < Rails::Application end opts = { :install => "any", :build => "ok", :gem_home => "project", :scenarios => %w[ruby c libxml2], :gems => [], - :settings => [] } + :settings => [], :system_libraries_by => "setting" } parser = OptionParser.new do |o| o.banner = "usage: ruby nokogiri_e2e.rb --socket-patch BIN --nokogiri VERSION [options]" o.on("--socket-patch BIN", "the socket-patch binary under test") { |v| opts[:socket_patch] = v } @@ -606,6 +613,10 @@ class SocketPatchE2E < Rails::Application "the install to make and require: precompiled (Bundler's default where a platform gem exists),", "source (the ruby platform gem, compiled here), system-libraries (compiled against the system's", "libxml2), java, or any (default)") { |v| opts[:install] = v } + o.on("--system-libraries-by HOW", %w[setting variable], + "how a system-libraries install is asked for: setting (default: Bundler's `build.nokogiri", + "--use-system-libraries`, which RubyGems records) or variable (NOKOGIRI_USE_SYSTEM_LIBRARIES", + "set for the install alone; only with --gem-home project)") { |v| opts[:system_libraries_by] = v } o.on("--build RESULT", %w[ok unavailable refused], "what a patch that needs a rebuild must do: ok (default), unavailable (no toolchain: fail,", "change nothing), refused (a JRuby install)") { |v| opts[:build] = v } From ab3bba818a5aef2a0994dc2cfea71800898a5410 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 16:01:38 -0500 Subject: [PATCH 07/11] Tell a build of the patch from one that read none of it, for any gem The system-library handling knew nokogiri: its environment variable, the wording of its build log, mini_portile's directories and a check on the gem's name. It is replaced by what holds for every gem. A compiler reads what it compiles, and a build script reads the patch files it applies. The record's build inputs are given an access time in the past before the build, staged or in place, and a build that exits cleanly having read none of them is not a build of the patch: the copy is left as it was and is never attested. That is the case of a gem built against the system's copy of a library it packs, without the CLI knowing any gem's switches. One read is enough, since a record also carries files no build opens, and nothing is concluded where the filesystem records no reads. What stays is the rule about RubyGems' own record: a copy RubyGems built is rebuilt with the arguments recorded for it, and a precompiled copy, which its publisher built, with none. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/nokogiri-compatibility.yml | 6 +- crates/socket-patch-cli/CLI_CONTRACT.md | 53 +- .../tests/e2e_gem_native_ext_build.rs | 316 +++++----- crates/socket-patch-core/src/patch/gem_ext.rs | 596 ++++++------------ docs/ecosystems.md | 27 +- tests/nokogiri/nokogiri_e2e.rb | 25 +- 6 files changed, 407 insertions(+), 616 deletions(-) diff --git a/.github/workflows/nokogiri-compatibility.yml b/.github/workflows/nokogiri-compatibility.yml index b9f09e937..d738e3094 100644 --- a/.github/workflows/nokogiri-compatibility.yml +++ b/.github/workflows/nokogiri-compatibility.yml @@ -24,10 +24,7 @@ name: nokogiri patch compatibility # system-libraries `--use-system-libraries`: the extension is rebuilt # with the recorded build arguments, and a patch to the # vendored libxml2, which such a build does not compile, is -# refused. The `by variable` leg asks for it with -# NOKOGIRI_USE_SYSTEM_LIBRARIES set for the install alone, -# so only the build's log says what it linked, and the -# rebuild, run without the variable, must link the same. +# refused: its build reads nothing of the patch. # The `legacy setting` leg is a precompiled install # in a project that still carries that Bundler setting from # the years before precompiled gems: its rebuild must keep @@ -130,7 +127,6 @@ jobs: - {os: ubuntu-latest, ruby: '2.3', nokogiri: '1.6.8.1', install: source, rails: '~> 4.2.0', bundler: '1'} - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: source} - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: system-libraries, system-libxml2: true} - - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: system-libraries, system-libxml2: true, args: '--system-libraries-by variable', note: by variable} - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, system-libxml2: true, args: '--bundle-setting BUNDLE_BUILD__NOKOGIRI=--use-system-libraries', note: legacy setting} # No compiler on PATH: nothing may change. - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, build: unavailable, args: '--hide-toolchain', note: no toolchain} diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 91ba1ab8f..9324fb749 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -954,15 +954,12 @@ name: nothing of it is run. This holds whatever lock governs the gem home. (`/.socket-patch-build/-[-]/`), by RubyGems, and must be that gem, declare extensions, and be the copy's own source (above). The record's files are laid over the staged gem, and every `beforeHash` must hold there, whatever the mismatch policy of the run. -RubyGems then builds the staged gem's extension in the stage. A gem RubyGems built is rebuilt the -way it was built: with the build arguments RubyGems recorded for the installed copy -(`build_info/`), and against the libraries its installed build linked (below). A precompiled gem -is rebuilt the way its publisher built it, from the libraries the gem packs: build arguments -recorded for it were never used to build it and are not used now, and -`NOKOGIRI_USE_SYSTEM_LIBRARIES` is removed from the build's environment. (Bundler's -`build.nokogiri --use-system-libraries`, which many projects kept from the years before nokogiri -shipped precompiled gems, is recorded for the platform gem too; following it would replace the -libxml2 the gem ships with the system's.) A gem the staged gem depends on at runtime that is not on +RubyGems then builds the staged gem's extension in the stage. A gem RubyGems built is given the +build arguments RubyGems recorded for the installed copy (`build_info/`), as `gem pristine` gives +them. A precompiled gem was built by its publisher, not on this machine: arguments recorded for +it were never used to build it (Bundler records its `build.` setting for a platform gem +too), so its rebuild takes none. Either build runs in the environment `apply` was started in, as +`gem install` would. A gem the staged gem depends on at runtime that is not on the build's `GEM_PATH` (the stage home, the copy's home, the caller's `GEM_PATH`, RubyGems' defaults) is staged too: the newest ruby-platform release the requirement allows that runs on the building Ruby, downloaded from the registry under the same rules and verified against its compact @@ -976,31 +973,19 @@ library under `lib/`, a Ruby file the build generates under a require path. Such loaded from where it was built. The staged build is set aside: a gem RubyGems built is rebuilt in place (below), a precompiled gem is refused. -**A gem built against the system's libraries.** A gem that packs a library (nokogiri packs -libxml2 and libxslt) can be built against the system's copy instead, and then compiles nothing of -the copy it packs. What the installed build of a gem RubyGems built linked is read from files, -without running anything: the log of that build (`gem_make.out`, where nokogiri writes "using -system libraries" or "using packaged libraries"), else the build arguments RubyGems recorded for -the copy, read as mkmf reads them (`--enable-system-libraries`, then -`--disable-system-libraries`, then `--use-system-libraries`, each with any value; a line that -holds several arguments, as Bundler 1 recorded a `build.` setting, is read word by word). - -- A rebuild links what the installed build linked, whatever `NOKOGIRI_USE_SYSTEM_LIBRARIES` is - when `apply` runs: the variable is set for the build of a copy built against the system's - libraries, removed for one built from the libraries it packs, and left as it is when neither - the log nor the arguments say. -- A record that changes the packed library (a file under `patches/` or `ports/`, or - `dependencies.yml`: mini_portile's layout) cannot take effect in a copy built against the - system's libraries, whose library is the operating system's. It is refused with - `native_extensions_unsupported` and nothing is written. So is one for a nokogiri whose log and - arguments say nothing while `NOKOGIRI_USE_SYSTEM_LIBRARIES` is set, which its rebuild would - follow. `apply --check` and `vex` do not attest such a record on a copy built against the - system's libraries, whatever marker the copy holds. A record of the gem's own sources - (`ext/**`) is rebuilt, against the system's libraries. - -A precompiled gem is never such a build. Gems that keep a packed library elsewhere (rugged's -`vendor/libgit2`, ffi's `ext/ffi_c/libffi`) are not recognised: a record for the packed library -of one built against the system's is still rebuilt and attested. +**A build that reads nothing of the patch.** A build that exits cleanly has not always built +the patch: what a gem compiles depends on how its build is configured. A gem set up to link the +system's copy of a library it packs (nokogiri installed with `--use-system-libraries`) never +opens the packed copy's sources, so a record that changes only those would be written, rebuilt +and attested with nothing of it in what Ruby loads. `apply` knows no gem's switches. It gives +the record's build inputs an access time in the past before the build, staged or in place, and +looks at them right after it: a build that read NONE of them did not build the patch. One read +is enough, because a record also carries files no build opens. From the stage this fails the +package with `native_extensions_unsupported` and nothing is written; from the installed tree +it fails with `native_extension_build_failed` and the sources and the previous build are put +back. Either way the copy is never attested. Where a read leaves no trace in a file's access +time (a `noatime` mount, Windows by default), which `apply` tests with a file of its own, +nothing is concluded and the build is taken as it is. **Into the installed copy.** The record's files are written into the copy, and the build takes the place of the compiled code: diff --git a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs index 5d285aa6b..65314018b 100644 --- a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs +++ b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs @@ -740,6 +740,11 @@ stage_build) exit 1 fi mkdir -p "$ext/sp_native" "$5/gems/$full/lib/sp_native" + # A build that applies the patch files the gem packs reads them; one set + # up to link the system's copy of that library never opens them. + if [ -e "$state/applies-patches" ]; then + find "$5/gems/$full/patches" -type f -exec cat {{}} + > /dev/null 2>&1 + fi # What was "compiled": the staged source, so a test can tell the build # came from the patched tree. {{ printf 'rebuilt from: '; cat "$5/gems/$full/ext/sp_native/sp_native.c"; }} > "$ext/sp_native/sp_native.so" @@ -775,6 +780,8 @@ build) exit 1 fi mkdir -p "$ext/sp_native" "$lib/sp_native" + # A compiler reads what it compiles. + cat "$home/gems/$full/ext/sp_native/sp_native.c" > /dev/null 2>&1 printf 'rebuilt' > "$ext/sp_native/sp_native.so" cp "$ext/sp_native/sp_native.so" "$lib/sp_native/sp_native.so" : > "$ext/gem.build_complete" @@ -835,6 +842,12 @@ esac std::fs::write(self.state.join("fail-extconf"), b"").unwrap(); } + /// From now on a staged build applies the patch files the gem packs, + /// as the build of a gem that compiles its packed library does. + fn apply_patch_files(&self) { + std::fs::write(self.state.join("applies-patches"), b"").unwrap(); + } + /// Stand in for Ruby 3.3 from now on (3.4 until then). fn become_ruby_33(&self) { std::fs::write(self.state.join("ruby-3.3"), b"").unwrap(); @@ -1706,13 +1719,14 @@ fn a_precompiled_copy_gets_the_build_of_its_source_gem() { assert_eq!(ruby.calls(), built, "rollback restores from the backup"); } -/// A precompiled copy is rebuilt the way its publisher built it, from the -/// libraries the gem packs. Build arguments RubyGems recorded for it were -/// never used to build it: Bundler's `build.nokogiri -/// --use-system-libraries`, a setting many projects kept from the years -/// before nokogiri shipped precompiled gems, is recorded for the platform -/// gem too, and following it (or `NOKOGIRI_USE_SYSTEM_LIBRARIES`) made -/// `apply` replace nokogiri's libxml2 2.13 with the system's 2.9. +/// A precompiled copy was built by its publisher, not on this machine: +/// build arguments RubyGems recorded for it were never used to build it, +/// and its rebuild takes none. Bundler records its `build.` setting +/// for a platform gem too, and a project that kept `build.nokogiri +/// --use-system-libraries` from the years before nokogiri shipped +/// precompiled gems had `apply` replace the libxml2 2.13 the gem ships with +/// the system's 2.9. A gem RubyGems built is given its recorded arguments +/// again. #[cfg(unix)] #[test] fn a_precompiled_copy_is_rebuilt_without_the_build_arguments_recorded_for_it() { @@ -1728,9 +1742,7 @@ fn a_precompiled_copy_is_rebuilt_without_the_build_arguments_recorded_for_it() { .unwrap(); let ruby = FakeRuby::new(); ruby.serve_source_gem(&c_source(1)); - - let env = [(SYSTEM_LIBRARIES, "1")]; - let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &env); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); assert_eq!(event_action(&stdout), "applied", "{stdout}"); assert_eq!( @@ -1738,18 +1750,25 @@ fn a_precompiled_copy_is_rebuilt_without_the_build_arguments_recorded_for_it() { "", "the build was given the arguments recorded for the platform gem" ); - assert!( - !ruby.env_seen("stage_build").contains(SYSTEM_LIBRARIES), - "the build was told to use the system's libraries" - ); assert_eq!( std::fs::read_to_string(gem_dir.join("lib/sp_native/3.4/sp_native.so")).unwrap(), built_from(&c_source(2)) ); -} -/// The variable nokogiri's build reads for linking the system's libxml2. -const SYSTEM_LIBRARIES: &str = "NOKOGIRI_USE_SYSTEM_LIBRARIES"; + // A copy RubyGems built: its recorded arguments are the build's. + let (_tmp, proj, _gem_dir, home) = built_gem_with_its_archive(); + std::fs::write( + home.join("build_info").join(format!("{FULL_NAME}.info")), + "--with-cflags=-O2\n", + ) + .unwrap(); + write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!(ruby.stage_build_args_of(), FULL_NAME); +} /// [`fake_native_gem`] with its source gem in the home's `cache/`, and its /// gem home. @@ -1763,174 +1782,147 @@ fn built_gem_with_its_archive() -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf (tmp, proj, gem_dir, home) } -/// Say, in the log of the installed build, which libraries it linked. +/// Whether a read of a file under `dir` shows in its access time, as the +/// CLI asks before it concludes anything from a file nobody read. A +/// filesystem mounted `noatime` records none, and there the check under +/// test cannot run. #[cfg(unix)] -fn write_build_log(home: &Path, libraries: &str) { - std::fs::write( - home.join("extensions/x86_64-linux/3.4.0") - .join(FULL_NAME) - .join("gem_make.out"), - format!("ruby extconf.rb\nBuilding sp_native using {libraries} libraries.\n"), - ) - .unwrap(); -} - -/// A gem built against the system's copy of a library compiles nothing of -/// the copy it packs, so a record that changes the packed copy (the shape -/// of a third of the published nokogiri patches: one more -/// `patches/libxml2/*.patch`) cannot take effect there. It is refused from -/// files alone, whichever way the installed build says what it linked, and -/// never attested: before, it was written, "rebuilt" against the same -/// system library and attested as patched. The same record on a copy built -/// from what the gem packs is built. +fn records_reads(dir: &Path) -> bool { + let probe = dir.join("read-probe"); + std::fs::write(&probe, b"probe").unwrap(); + let old = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000_000); + let file = std::fs::OpenOptions::new() + .write(true) + .open(&probe) + .unwrap(); + file.set_times(std::fs::FileTimes::new().set_accessed(old)) + .unwrap(); + drop(file); + std::fs::read(&probe).unwrap(); + let recorded = std::fs::metadata(&probe).unwrap().accessed().unwrap() != old; + std::fs::remove_file(&probe).unwrap(); + recorded +} + +/// A build that exits cleanly has not always built the patch: a gem set up +/// to link the system's copy of a library it packs never opens the packed +/// copy's sources. A record that changes only those (a third of the +/// published nokogiri patches add one `patches/libxml2/*.patch`) was +/// written, "rebuilt" and attested on such an install, with nothing of it +/// in what Ruby loads. The CLI knows no gem's switches: it marks the +/// record's build inputs unread, and a build that read none of them is not +/// a build of the patch. The copy is left as it was, and nothing attests +/// it. The same record is built by a build that applies the patch file. #[cfg(unix)] #[test] -fn a_packed_library_patch_to_a_system_library_build_is_refused() { +fn a_build_that_reads_nothing_of_the_patch_does_not_apply_it() { let library_patch: [RecordFile<'_>; 1] = [("patches/libsp/0100-CVE-test.patch", None, "fix\n")]; - - for evidence in ["arguments", "arguments in one line", "log"] { - let (_tmp, proj, _gem_dir, home) = built_gem_with_its_archive(); - write_record(&proj.join(".socket"), PURL, &library_patch); - let info = home.join("build_info").join(format!("{FULL_NAME}.info")); - match evidence { - "arguments" => { - std::fs::write(info, "--with-cflags=-O2\n--use-system-libraries\n").unwrap() - } - // As Bundler 1 recorded a `build.` setting. - "arguments in one line" => std::fs::write( - info, - "--use-system-libraries --with-sp-include=/usr/include\n", - ) - .unwrap(), - _ => write_build_log(&home, "system"), - } - let ruby = FakeRuby::new(); - ruby.serve_source_gem(&c_source(1)); - let tree_before = walk_files(&proj.join("vendor")); - - for args in [ - &["apply", "--json", "--offline"][..], - &["apply", "--json", "--offline", "--dry-run"], - ] { - let (code, stdout, stderr) = ruby.run(&proj, args, &[]); - assert_eq!(code, 1, "{evidence} {args:?}: {stdout}\n{stderr}"); - let envelope = parse_json_envelope(&stdout); - let error = common::envelope::event_for(&envelope, PURL)["error"] - .as_str() - .unwrap_or_default() - .to_string(); - assert!( - error.contains("native_extensions_unsupported") - && error.contains("patches/libsp/0100-CVE-test.patch") - && error.contains("was built against the system's copy of that library") - && error.contains("cannot take effect; nothing was written"), - "{evidence} {args:?}: {error}" - ); - assert!( - !error.contains(" "), - "the message has a gap in it: {error}" - ); - } - assert_eq!( - ruby.calls(), - Vec::::new(), - "{evidence}: Ruby ran for a patch that cannot take effect" - ); - assert_tree(&proj.join("vendor"), &tree_before, evidence); - let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--check"], &[]); - assert_ne!(code, 0, "{evidence}: {stdout}\n{stderr}"); - assert!( - !vex_attests(|args| ruby.run(&proj, args, &[])), - "{evidence}: vex attested a patch that is compiled into nothing" - ); - } - - // A copy built from what the gem packs builds the same record, with the - // variable set or not: its log says what it links. let (_tmp, proj, gem_dir, home) = built_gem_with_its_archive(); - write_build_log(&home, "packaged"); + if !records_reads(&home) { + eprintln!("SKIP: this filesystem does not record reads in access times"); + return; + } write_record(&proj.join(".socket"), PURL, &library_patch); let ruby = FakeRuby::new(); ruby.serve_source_gem(&c_source(1)); - let env = [(SYSTEM_LIBRARIES, "1")]; - let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &env); - assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); - assert_eq!(event_action(&stdout), "applied", "{stdout}"); - assert!(gem_dir.join("patches/libsp/0100-CVE-test.patch").is_file()); - assert!(vex_attests(|args| ruby.run(&proj, args, &env))); - // Applied and built: a second run has nothing to refuse. - let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &env); - assert_eq!(code, 0, "{stdout}\n{stderr}"); - assert_eq!(event_action(&stdout), "skipped", "{stdout}"); + let tree_before = walk_files(&proj.join("vendor")); - // A marker over a build that links the system's libraries attests - // nothing of the packed library, whoever wrote it. - write_build_log(&home, "system"); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + assert_eq!(code, 1, "ruby ran {:?}\n{stdout}\n{stderr}", ruby.calls()); + let envelope = parse_json_envelope(&stdout); + let error = common::envelope::event_for(&envelope, PURL)["error"] + .as_str() + .unwrap_or_default() + .to_string(); + assert!( + error.contains("native_extensions_unsupported") + && error.contains("without reading any file the patch changes") + && error.contains("patches/libsp/0100-CVE-test.patch") + && error.contains("nothing was written"), + "{error}" + ); + assert!( + !error.contains(" "), + "the message has a gap in it: {error}" + ); + assert_eq!( + ruby.calls(), + ["extensions_dir", "unpack", "missing_deps", "stage_build"], + "one build in the stage, and none of the installed tree after it" + ); + assert_tree(&proj.join("vendor"), &tree_before, ""); let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--check"], &[]); assert_ne!(code, 0, "{stdout}\n{stderr}"); - assert!(!vex_attests(|args| ruby.run(&proj, args, &[]))); -} + assert!( + !vex_attests(|args| ruby.run(&proj, args, &[])), + "vex attested a patch that is compiled into nothing" + ); -/// A record of the gem's own sources is rebuilt against the libraries the -/// installed build linked, whatever the environment says by the time -/// `apply` runs: a gem installed with the variable set for that one -/// command is rebuilt with it, and a gem built from the libraries it packs -/// is rebuilt without it. The arguments RubyGems recorded are given again. -#[cfg(unix)] -#[test] -fn a_rebuild_links_the_libraries_the_installed_build_linked() { - // Built against the system's, by the variable alone; `apply` runs - // without it. - let (_tmp, proj, _gem_dir, home) = built_gem_with_its_archive(); - write_build_log(&home, "system"); - write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); - let ruby = FakeRuby::new(); - ruby.serve_source_gem(&c_source(1)); + // A build that applies the gem's patch files reads this one. + ruby.apply_patch_files(); let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); assert_eq!(event_action(&stdout), "applied", "{stdout}"); - assert!( - ruby.env_seen("stage_build") - .contains(&format!("{SYSTEM_LIBRARIES}=1")), - "the rebuild of a system-library build was not told to link them" - ); - assert_eq!(ruby.stage_build_args_of(), FULL_NAME); + assert!(gem_dir.join("patches/libsp/0100-CVE-test.patch").is_file()); + assert!(vex_attests(|args| ruby.run(&proj, args, &[]))); - // Built from what the gem packs; `apply` runs with the variable set. - let (_tmp, proj, _gem_dir, home) = built_gem_with_its_archive(); - write_build_log(&home, "packaged"); - std::fs::write( - home.join("build_info").join(format!("{FULL_NAME}.info")), - "--with-cflags=-O2\n", - ) - .unwrap(); - write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); + // One input read is enough: a record carries files no build opens (a + // manifest that lists what it adds) beside the ones it compiles. + let (_tmp, proj, _gem_dir, _home) = built_gem_with_its_archive(); + let (before, after) = (c_source(1), c_source(2)); + write_record( + &proj.join(".socket"), + PURL, + &[ + (C_KEY, Some(&before), &after), + ("patches/libsp/0100-CVE-test.patch", None, "fix\n"), + ], + ); let ruby = FakeRuby::new(); ruby.serve_source_gem(&c_source(1)); - let env = [(SYSTEM_LIBRARIES, "1")]; - let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &env); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); - assert!( - !ruby.env_seen("stage_build").contains(SYSTEM_LIBRARIES), - "the rebuild of a packaged build was told to link the system's libraries" - ); - assert_eq!( - ruby.stage_build_args_of(), - FULL_NAME, - "the rebuild takes the arguments RubyGems recorded for the copy" - ); + assert_eq!(event_action(&stdout), "applied", "{stdout}"); +} - // The in-place rebuild (no source gem to stage) is made the same way. - let (_tmp, proj, _gem_dir) = fake_native_gem(true); +/// The rebuild of an installed tree (no source gem to stage) is held to the +/// same: a build that read nothing of the patch is undone, sources and +/// previous build put back. +#[cfg(unix)] +#[test] +fn an_in_place_build_that_reads_nothing_of_the_patch_is_undone() { + let (_tmp, proj, gem_dir) = fake_native_gem(true); let home = proj.join("vendor/bundle/ruby/3.4.0"); - write_build_log(&home, "system"); - write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); + if !records_reads(&home) { + eprintln!("SKIP: this filesystem does not record reads in access times"); + return; + } + // A build input the installed tree holds and the stand-in build never + // opens. + std::fs::create_dir_all(gem_dir.join("patches/libsp")).unwrap(); + std::fs::write(gem_dir.join("patches/libsp/0001-base.patch"), "base\n").unwrap(); + write_record( + &proj.join(".socket"), + PURL, + &[( + "patches/libsp/0001-base.patch", + Some("base\n"), + "base, fixed\n", + )], + ); let ruby = FakeRuby::new(); + let tree_before = walk_files(&proj.join("vendor")); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); - assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); - assert!(ruby - .env_seen("build") - .contains(&format!("{SYSTEM_LIBRARIES}=1"))); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!( + stdout.contains("native_extension_build_failed") + && stdout.contains("without reading any file the patch changes"), + "{stdout}" + ); + assert_eq!(ruby.calls(), ["extensions_dir", "build"]); + assert_tree(&proj.join("vendor"), &tree_before, ""); + assert!(!vex_attests(|args| ruby.run(&proj, args, &[]))); } /// Without the source gem there is nothing to build from: offline and not diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index f9f6a79af..37e647be2 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -92,14 +92,15 @@ //! such fallback and is refused, with what it needs: network access to the //! registry once, or the source gem in the home's `cache/`. //! -//! A gem that packs a library and was built against the system's copy of -//! it (nokogiri with `--use-system-libraries`) compiles nothing of the -//! copy it packs. A record that changes that copy (`patches/**`, `ports/**`, -//! `dependencies.yml`) would be written, "rebuilt" against the same system -//! library and attested, with nothing of it in what Ruby loads. It is -//! refused from files alone instead ([`links_system_libraries`]), and a -//! rebuild of the gem's own sources links what the installed build linked -//! ([`link_libraries`]). +//! A build that exits cleanly has not always built the patch. A gem's +//! build takes what it compiles from its configuration: one set up to link +//! the system's copy of a library the gem packs (nokogiri installed with +//! `--use-system-libraries`) never opens the packed copy's sources, so a +//! record that changes only those would be written, "rebuilt" and attested +//! with nothing of it in what Ruby loads. So the record's build inputs are +//! marked unread before the build, and a build that read none of them is +//! not taken for a build of the patch (`unread_inputs`): the copy is left +//! as it was. //! //! `vex` and `apply --check` attest a copy only when its marker matches the //! record's patched sources and every recorded artifact still hashes as @@ -266,32 +267,8 @@ const BUILD_TIMEOUT: Duration = Duration::from_secs(30 * 60); /// ignores it. const BUILD_COMPLETE: &str = "gem.build_complete"; -/// The log RubyGems keeps of a build, in its extension dir. -const BUILD_LOG: &str = "gem_make.out"; - /// Files RubyGems writes into an extension dir that are not build products. -const EXT_DIR_METADATA: &[&str] = &[BUILD_COMPLETE, BUILD_LOG, "mkmf.log"]; - -/// The build argument nokogiri and sqlite3 take for linking the system's -/// copy of a library the gem packs (mini_portile's convention), the one -/// that takes it back, and nokogiri's older spelling of the first. -const ENABLE_SYSTEM_LIBRARIES: &str = "--enable-system-libraries"; -const DISABLE_SYSTEM_LIBRARIES: &str = "--disable-system-libraries"; -const USE_SYSTEM_LIBRARIES: &str = "--use-system-libraries"; - -/// The environment variable nokogiri's build takes for the same, when no -/// argument says either way. -const SYSTEM_LIBRARY_ENV: &str = "NOKOGIRI_USE_SYSTEM_LIBRARIES"; - -/// What nokogiri's `extconf.rb` writes into the log of a build, one or the -/// other: "Building nokogiri using system libraries." / "… using packaged -/// libraries." -const SYSTEM_LIBRARY_LOG: &str = "using system libraries"; -const PACKED_LIBRARY_LOG: &str = "using packaged libraries"; - -/// How much of a build log is read for those lines: they are among the -/// first an `extconf.rb` prints, and a log is not bounded. -const BUILD_LOG_HEAD: u64 = 1024 * 1024; +const EXT_DIR_METADATA: &[&str] = &[BUILD_COMPLETE, "gem_make.out", "mkmf.log"]; /// Source and build-script extensions a native extension compiles. const NATIVE_SOURCE_EXTENSIONS: &[&str] = &[ @@ -772,139 +749,6 @@ fn is_clearly_not_built(path: &str, require_paths: &[String]) -> bool { } } -/// Whether `path` is an input of a library the gem builds from sources it -/// packs, by mini_portile's layout (nokogiri, sqlite3): a patch for it -/// (`patches/libxml2/…`, `ports/patches/…` before nokogiri 1.6.7), its -/// archive (`ports/archives/…`), or the file that names its version and -/// checksum (`dependencies.yml`). -fn is_vendored_library_input(path: &str) -> bool { - let path = normalize_file_path(path); - path == "dependencies.yml" || path.starts_with("patches/") || path.starts_with("ports/") -} - -/// Which copy of a library the gem packs an extension is built against. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -enum Libraries { - /// Nothing says: the build's arguments and environment decide, as they - /// did when the gem was installed. - #[default] - Unsaid, - /// The copy the gem packs. - Packed, - /// The system's. - System, -} - -/// What build arguments say of the libraries a build links, in the order -/// mkmf asks for them in nokogiri's `extconf.rb`: -/// [`ENABLE_SYSTEM_LIBRARIES`], then [`DISABLE_SYSTEM_LIBRARIES`], then -/// [`USE_SYSTEM_LIBRARIES`]. Each counts bare or with any value: mkmf -/// takes the value as it is, and `=false` is a string, which is true. -/// -/// `args` is a `build_info` file. A current RubyGems writes one argument a -/// line; Bundler 1 handed RubyGems a whole `build.` setting as one -/// argument, so a line can hold several, and each is read word by word. -fn libraries_by_args(args: &str) -> Libraries { - let has = |flag: &str| { - args.split_whitespace().any(|word| { - word.strip_prefix(flag) - .is_some_and(|rest| rest.is_empty() || rest.starts_with('=')) - }) - }; - if has(ENABLE_SYSTEM_LIBRARIES) { - Libraries::System - } else if has(DISABLE_SYSTEM_LIBRARIES) { - Libraries::Packed - } else if has(USE_SYSTEM_LIBRARIES) { - Libraries::System - } else { - Libraries::Unsaid - } -} - -/// What the build log at `log` says of the libraries its build linked -/// ([`SYSTEM_LIBRARY_LOG`], [`PACKED_LIBRARY_LOG`]). A log that cannot be -/// read says nothing. -fn libraries_by_log(log: &Path) -> Libraries { - use std::io::Read as _; - let Ok((file, _)) = crate::utils::fs::open_regular_file_sync(log) else { - return Libraries::Unsaid; - }; - let mut head = Vec::new(); - if file.take(BUILD_LOG_HEAD).read_to_end(&mut head).is_err() { - return Libraries::Unsaid; - } - let head = String::from_utf8_lossy(&head); - if head.contains(SYSTEM_LIBRARY_LOG) { - Libraries::System - } else if head.contains(PACKED_LIBRARY_LOG) { - Libraries::Packed - } else { - Libraries::Unsaid - } -} - -/// The libraries the installed extension of `copy`, a gem RubyGems built, -/// links, and what says so. Read from files alone: -/// -/// * the log of the build that is installed (or parked while a rebuild -/// runs), which is the build itself speaking; -/// * else the build arguments RubyGems recorded for the copy -/// (`/build_info/.info`: `gem install … -- -/// --use-system-libraries`, Bundler's `build.` setting), which a -/// rebuild is given again. -/// -/// A gem installed with [`SYSTEM_LIBRARY_ENV`] alone has only its log to -/// say so, and one whose log was pruned and whose arguments say nothing is -/// [`Libraries::Unsaid`]. -fn installed_libraries(copy: &GemCopy) -> (Libraries, String) { - for ext in extension_dir_slots(copy) { - for dir in [ext.clone(), parked_build_path(&ext)] { - let said = libraries_by_log(&dir.join(BUILD_LOG)); - if said != Libraries::Unsaid { - return (said, "the log of its build says so".to_string()); - } - } - } - let info = copy - .home - .join("build_info") - .join(format!("{}.info", copy.full_name)); - let said = crate::utils::fs::read_regular_to_string_sync(&info) - .map(|args| libraries_by_args(&args)) - .unwrap_or_default(); - ( - said, - "the build arguments RubyGems recorded for it say so".to_string(), - ) -} - -/// Why nothing of a library `copy` packs is compiled into its extension, -/// when that is so: it links the system's ([`installed_libraries`]), or it -/// is nokogiri, nothing says what it links, and [`SYSTEM_LIBRARY_ENV`] is -/// set (`env_set`), which its rebuild would follow. A record's -/// [`is_vendored_library_input`] files cannot take effect in such a build. -fn links_system_libraries(copy: &GemCopy, env_set: bool) -> Option { - match installed_libraries(copy) { - (Libraries::System, evidence) => Some(evidence), - (Libraries::Unsaid, _) if env_set && gem_name_of(©.full_name) == "nokogiri" => Some( - format!("`{SYSTEM_LIBRARY_ENV}` is set, and nothing of its build says otherwise"), - ), - _ => None, - } -} - -/// The record's build inputs that are [`is_vendored_library_input`]s. -fn vendored_library_inputs(scope: &NativeScope) -> Vec { - scope - .inputs - .iter() - .map(|key| normalize_file_path(key)) - .filter(|path| is_vendored_library_input(path)) - .map(str::to_string) - .collect() -} - /// A gem record's native-extension build inputs on one installed copy. #[derive(Debug, Clone, Default, PartialEq, Eq)] struct NativeScope { @@ -1327,14 +1171,7 @@ pub async fn verify_native_build( }; let files = files.clone(); let holds = crate::utils::fs::run_blocking(move || { - // A marker over a build that links the system's libraries says - // nothing of a library the gem packs: none of it was built. - let unbuilt = scope.builds_extensions - && !vendored_library_inputs(&scope).is_empty() - && installed_libraries(©).0 == Libraries::System; - !unbuilt - && read_marker_sync(©.gem_dir) - .is_some_and(|m| marker_holds(&m, ©, &scope, &files)) + read_marker_sync(©.gem_dir).is_some_and(|m| marker_holds(&m, ©, &scope, &files)) }) .await; if holds { @@ -1383,28 +1220,6 @@ struct Probe { lib_dir: PathBuf, /// What `ruby` said of itself, when it did. facts: Option, - /// The libraries a rebuild of the copy links ([`link_libraries`]): the - /// ones its installed build links, and for a precompiled copy the ones - /// the gem packs, which its publisher built it from. - libraries: Libraries, -} - -/// Make the build `command` link `libraries`, where nokogiri's build takes -/// that from the environment: a rebuild is made the way the installed -/// build was, whatever [`SYSTEM_LIBRARY_ENV`] is by the time `apply` runs. -/// A gem built with the variable set for its install alone (`RUN -/// NOKOGIRI_USE_SYSTEM_LIBRARIES=1 bundle install`) is rebuilt with it, and -/// one built from the libraries it packs is rebuilt without. -fn link_libraries(command: &mut std::process::Command, libraries: Libraries) { - match libraries { - Libraries::Packed => { - command.env_remove(SYSTEM_LIBRARY_ENV); - } - Libraries::System => { - command.env(SYSTEM_LIBRARY_ENV, "1"); - } - Libraries::Unsaid => {} - } } /// What a Ruby says of itself in a [`RubyRun::ExtensionsDir`] run. @@ -1549,21 +1364,18 @@ enum RubyRun<'a> { /// `stage_home`: runs the staged tree's build scripts. /// /// `recorded_args`: the installed copy is one RubyGems built, and the - /// rebuild is given the arguments RubyGems recorded for it. A - /// precompiled copy was built by its publisher from the libraries the - /// gem packs, whatever this machine is set up to build with: arguments - /// recorded for it were never used (Bundler's `build.nokogiri - /// --use-system-libraries`, left in a project from the years before - /// nokogiri shipped precompiled gems, is recorded for the platform gem - /// too), so its rebuild takes none. Following them would replace the - /// library the gem ships with whichever the system has. - /// - /// `libraries`: [`Probe::libraries`]. + /// rebuild is given the arguments RubyGems recorded for it, as `gem + /// pristine` gives them. A precompiled copy was built by its publisher, + /// not here: arguments recorded for it were never used to build it + /// (Bundler's `build.` setting is recorded for a platform gem + /// too), so its rebuild takes none. Given them, a setting a project + /// kept from the years a gem had no precompiled build + /// (`build.nokogiri --use-system-libraries`) made the rebuild replace + /// the library the gem ships with whichever the system has. StageBuild { spec: &'a Path, stage_home: &'a Path, recorded_args: bool, - libraries: Libraries, }, } @@ -1595,7 +1407,6 @@ async fn run_ruby( .arg(©.spec_path) .arg(&probe.extension_dir) .arg(&probe.require_path); - link_libraries(&mut command, probe.libraries); if let Some(gem_path) = gem_path_for(&[©.home]) { command.env("GEM_PATH", gem_path); } @@ -1640,7 +1451,6 @@ async fn run_ruby( spec, stage_home, recorded_args, - libraries, } => { command .arg("stage_build") @@ -1650,7 +1460,6 @@ async fn run_ruby( if recorded_args { command.arg(©.full_name); } - link_libraries(&mut command, libraries); // The stage home first: the gems the build needs and the // install lacks were put there, and nowhere else. if let Some(gem_path) = gem_path_for(&[stage_home, ©.home]) { @@ -2241,13 +2050,6 @@ async fn find_ruby( reasons.push(why); continue; } - let libraries = match platform { - Some(_) => Libraries::Packed, - None => { - let copy = copy.clone(); - crate::utils::fs::run_blocking(move || installed_libraries(©).0).await - } - }; return Ok(Probe { ruby, gem_dir: copy.gem_dir.clone(), @@ -2256,7 +2058,6 @@ async fn find_ruby( require_path, require_paths, facts, - libraries, }); } Err(format!( @@ -3111,6 +2912,105 @@ fn in_tree_artifacts( rels } +/// The access time a build input is given before its build: earlier than +/// any file's modification time, so that a filesystem that records reads +/// lazily (Linux `relatime`, APFS) records the first read after it. +fn unread_time() -> std::time::SystemTime { + std::time::UNIX_EPOCH + Duration::from_secs(1_000_000_000) +} + +fn accessed(path: &Path) -> Option { + std::fs::symlink_metadata(path).ok()?.accessed().ok() +} + +/// Give `path` the access time [`unread_time`]. `false` when the file +/// cannot take it, or the filesystem does not keep it as given. +fn mark_unread(path: &Path) -> bool { + let times = std::fs::FileTimes::new().set_accessed(unread_time()); + // A file's owner sets its times through any handle on Unix, and a + // patched file can be read-only (it keeps the gem's mode); Windows + // wants a handle opened for writing. Opening a file is not a read. + let set = [false, true].into_iter().any(|write| { + std::fs::OpenOptions::new() + .read(!write) + .write(write) + .open(path) + .is_ok_and(|file| file.set_times(times).is_ok()) + }); + set && accessed(path) == Some(unread_time()) +} + +/// Mark the record's build inputs under `gem_dir` unread, right before a +/// build of them, and name those that took the mark. An input the record +/// deletes is not there to mark. +fn mark_inputs_unread(gem_dir: &Path, scope: &NativeScope) -> Vec { + scope + .inputs + .iter() + .map(|key| normalize_file_path(key).to_string()) + .filter(|rel| is_safe_relative_subpath(rel) && mark_unread(&gem_dir.join(rel))) + .collect() +} + +/// Whether a read of a file in `dir` shows in its access time. A +/// filesystem mounted `noatime`, and Windows by default, record none. +fn records_reads(dir: &Path) -> bool { + let probe = dir.join(".socket-patch-read-probe"); + let recorded = std::fs::write(&probe, b"probe").is_ok() + && mark_unread(&probe) + && std::fs::read(&probe).is_ok() + && accessed(&probe).is_some_and(|at| at != unread_time()); + let _ = std::fs::remove_file(&probe); + recorded +} + +/// The build inputs of a record that a build which has just exited cleanly +/// did not read, when it read NONE of them and that can be told +/// (`marked`: [`mark_inputs_unread`]'s answer for `gem_dir`; `probe_dir`: a +/// writable dir on the same filesystem). +/// +/// A compiler reads what it compiles, and a build script reads the patch +/// files it applies. A build that opened none of the files the patch +/// changes compiled the same code it would have without them: the gem is +/// set up not to build that part of itself (the packed library of a gem +/// built against the system's copy), and the patch is not in what Ruby +/// loads. One read is enough to pass: the classification of inputs is +/// broad on purpose, and a build does not read every file a record +/// carries (a manifest listing the files it adds). +/// +/// `None` wherever a read leaves no trace: nothing is concluded from +/// silence the filesystem imposes. +fn unread_inputs(gem_dir: &Path, marked: &[String], probe_dir: &Path) -> Option> { + if marked.is_empty() { + return None; + } + let read_any = marked + .iter() + .any(|rel| accessed(&gem_dir.join(rel)) != Some(unread_time())); + if read_any || !records_reads(probe_dir) { + return None; + } + Some(marked.to_vec()) +} + +/// What a refusal says of a build that read none of the record's inputs. +fn unread_detail(unread: &[String]) -> String { + let shown = unread.iter().take(3).cloned().collect::>(); + let more = match unread.len().saturating_sub(shown.len()) { + 0 => String::new(), + n => format!(" and {n} more"), + }; + format!( + "the build exited cleanly without reading any file the patch changes ({}{more}), so \ + nothing of the patch is compiled into the extension: this install's build does not \ + use them. A gem set up to build against the system's copy of a library it packs \ + (`--use-system-libraries`) does this to a patch for the packed copy; what the install \ + runs is then the operating system's library, and updating that package is what fixes \ + it", + shown.join(", ") + ) +} + /// Why a build that exited cleanly is not one of the sources on disk, when /// that shows in the files it left: `None` when nothing does. /// @@ -3257,6 +3157,15 @@ async fn rebuild( }) .await? }; + // Nothing reads the tree between here and the check after the build + // but the build. A rebuild without record files (a rollback's, of the + // original sources) has no patch to look for. + let marked = if files.is_empty() { + Vec::new() + } else { + let (gem_dir, scope) = (copy.gem_dir.clone(), scope.clone()); + crate::utils::fs::run_blocking(move || mark_inputs_unread(&gem_dir, &scope)).await + }; let built = run_ruby(&probe.ruby, RubyRun::Build(probe), copy, env, BUILD_TIMEOUT).await; let (copy, probe, scope, files) = (copy.clone(), probe.clone(), scope.clone(), files.clone()); crate::utils::fs::run_blocking(move || { @@ -3269,7 +3178,11 @@ async fn rebuild( "the build exited cleanly but left no extension in {}", probe.extension_dir.display() )), - Ok(_) => { + Ok(_) => match unread_inputs(©.gem_dir, &marked, &snapshot.dir) { + // Before anything else reads the tree: a build that read + // nothing of the patch is undone like a failed one. + Some(unread) => Err(unread_detail(&unread)), + None => { let changes = tree_changes(©, &snapshot); match stale_build(©, &probe, &removed, &snapshot, &changes) { Some(why) => Err(why), @@ -3288,7 +3201,8 @@ async fn rebuild( ) }), } - } + } + }, Err(diagnostic) => Err(diagnostic), }; let diagnostic = match committed { @@ -3532,6 +3446,10 @@ enum StageFailure { Dependencies(String), /// RubyGems' builder failed: the build's diagnostic. Build(String), + /// The build read none of the record's build inputs ([`unread_inputs`]): + /// it is no build of the patch, and neither would one of the installed + /// tree be. + NotRead(Vec), /// The build leaves what Ruby loads in the gem's own tree /// ([`in_tree_products`]), where a build staged elsewhere cannot stand /// in for it. @@ -3561,6 +3479,7 @@ impl StageFailure { StageFailure::Build(diagnostic) => { format!("the source gem did not build:\n{diagnostic}") } + StageFailure::NotRead(unread) => unread_detail(unread), StageFailure::InTree { products, .. } => format!( "the source gem's build leaves {} in the gem's own tree, which is where it is \ loaded from, and a build staged elsewhere cannot take its place", @@ -4030,12 +3949,27 @@ async fn build_in_stage( // The source gem of a copy RubyGems built is the copy's own gem; a // precompiled copy's is the ruby-platform gem of its version. recorded_args: source.full_name() == copy.full_name, - libraries: probe.libraries, }; stage.beat(); + // Nothing reads the staged tree between here and the check below but + // the build. + let marked = match record { + Some(record) => { + let (gem_dir, scope) = (staged.gem_dir.clone(), record.scope.clone()); + crate::utils::fs::run_blocking(move || mark_inputs_unread(&gem_dir, &scope)).await + } + None => Vec::new(), + }; let stdout = run_ruby(&probe.ruby, run, copy, env, BUILD_TIMEOUT) .await .map_err(StageFailure::Build)?; + let unread = { + let (gem_dir, root) = (staged.gem_dir.clone(), stage.root.clone()); + crate::utils::fs::run_blocking(move || unread_inputs(&gem_dir, &marked, &root)).await + }; + if let Some(unread) = unread { + return Err(StageFailure::NotRead(unread)); + } let reported = tagged_lines(&stdout, "sp_built") .into_iter() .find_map(|fields| fields.first().map(PathBuf::from)) @@ -4873,43 +4807,6 @@ pub async fn apply_gem_package_patch( ), ); } - // A gem built against the system's copy of a library compiles nothing - // of the copy it packs, and a rebuild is made the way the installed - // build was. So the inputs of the packed copy that the record changes - // would be written and never built: the library the gem loads is the - // operating system's, which no gem patch reaches. - if scope.builds_extensions { - let vendored = vendored_library_inputs(&scope); - let system = if vendored.is_empty() { - None - } else { - let (copy, env_set) = (copy.clone(), std::env::var_os(SYSTEM_LIBRARY_ENV).is_some()); - crate::utils::fs::run_blocking(move || links_system_libraries(©, env_set)).await - }; - if let Some(evidence) = system { - let shown = vendored.iter().take(3).cloned().collect::>(); - let more = match vendored.len().saturating_sub(shown.len()) { - 0 => String::new(), - n => format!(" and {n} more"), - }; - return refusal( - package_key, - pkg_path, - UNSUPPORTED_CODE, - format!( - "the patch changes a library the gem packs ({}{more}), but {} was built \ - against the system's copy of that library ({evidence}), so nothing the \ - patch changes there is compiled into it and the patch cannot take effect; \ - nothing was written. What this install runs is the library the operating \ - system provides: update that package, or reinstall the gem without \ - `--use-system-libraries` so that it builds the library it packs, and \ - apply again.", - shown.join(", "), - copy.full_name - ), - ); - } - } let precompiled = scope.precompiled.is_some(); let (installed_files, absent) = files_as_installed(©, &scope, files).await; @@ -5164,6 +5061,18 @@ pub async fn apply_gem_package_patch( match failure { // Another run is building this gem: nothing else is tried. StageFailure::Busy(why) => unbuildable(why), + // A build of the installed tree would read as little: the patch + // has nothing to take effect in on this install. + StageFailure::NotRead(unread) => refusal( + package_key, + pkg_path, + UNSUPPORTED_CODE, + format!( + "the patch changes native-extension sources ({inputs}), and they cannot take \ + effect on this install: {}; nothing was written.", + unread_detail(&unread) + ), + ), // A gem RubyGems built can still be built where it is installed, // as it was before there was a stage: nothing was written yet. failure if !precompiled => { @@ -6211,7 +6120,6 @@ mod tests { require_paths: vec!["lib".to_string()], lib_dir: copy.gem_dir.join("lib"), facts: None, - libraries: Libraries::default(), }; let aside = set_aside(©, &probe).unwrap(); @@ -6531,139 +6439,51 @@ mod tests { files(&all) } - /// The inputs of a library the gem packs are told from the gem's own - /// sources: only the former go unbuilt in a system-library build. - #[test] - fn vendored_library_inputs_are_the_packed_librarys_alone() { - for path in [ - "patches/libxml2/0100-CVE-2025-0000.patch", - "patches/libxslt/0001-fix.patch", - "ports/patches/libxml2/0001-fix.patch", - "ports/archives/libxml2-2.13.6.tar.xz", - "dependencies.yml", - ] { - assert!(is_vendored_library_input(path), "{path}"); - } - for path in [ - "ext/nokogiri/xml_node.c", - "ext/nokogiri/extconf.rb", - "ext/nokogiri/patches/a.patch", - "gumbo-parser/src/parser.c", - "lib/nokogiri/xml/node.rb", - "Manifest.txt", - "dependencies.yml.orig", - "patches", - ] { - assert!(!is_vendored_library_input(path), "{path}"); - } - } - - /// mkmf's reading of the arguments, not a guess at it: any value is a - /// yes, `--enable` beats `--disable`, which beats `--use`, and a line - /// Bundler 1 wrote holds several arguments. + /// A build that read none of a record's inputs is told from one that + /// read any of them, by access times, and nothing is concluded where a + /// read leaves no trace or nothing could be marked. #[test] - fn build_arguments_say_which_libraries_a_build_links() { - for args in [ - "--use-system-libraries", - "--enable-system-libraries", - "--use-system-libraries=true", - "--use-system-libraries=false", - "--enable-system-libraries=no", - "--with-cflags=-O2\n --enable-system-libraries\n", - "--use-system-libraries --with-xml2-include=/usr/include/libxml2", - "--disable-system-libraries\n--enable-system-libraries", - ] { - assert_eq!(libraries_by_args(args), Libraries::System, "{args}"); - } - for args in [ - "--disable-system-libraries", - "--use-system-libraries\n--disable-system-libraries", - ] { - assert_eq!(libraries_by_args(args), Libraries::Packed, "{args}"); - } - for args in [ - "", - "--with-xml2-dir=/usr", - "--use-system-librariesx", - "--with-opt=--use-system-libraries-not", - ] { - assert_eq!(libraries_by_args(args), Libraries::Unsaid, "{args}"); - } - } - - /// What the installed build of a copy RubyGems built links is read from - /// its log first, then from the arguments RubyGems recorded, and the - /// environment of the run counts only for nokogiri, and only when - /// neither says. - #[test] - fn the_installed_build_says_which_libraries_it_links() { + fn a_build_that_read_none_of_the_inputs_is_told_from_one_that_read_any() { let tmp = tempfile::tempdir().unwrap(); - let home = tmp.path(); - let copy = installed_gem(home, "lib"); - let log = home.join("extensions/p/3.4.0/a-1").join(BUILD_LOG); - let info = home.join("build_info/a-1.info"); - std::fs::create_dir_all(info.parent().unwrap()).unwrap(); - // Another gem's arguments are not this one's. - std::fs::write(home.join("build_info/b-1.info"), "--use-system-libraries\n").unwrap(); - - // Nothing says, and the gem is not nokogiri: the variable is not - // about it. - assert_eq!(installed_libraries(©).0, Libraries::Unsaid); - assert_eq!(links_system_libraries(©, true), None); - - std::fs::write(&info, "--with-cflags=-O2\n--use-system-libraries\n").unwrap(); - assert_eq!(installed_libraries(©).0, Libraries::System); - let by_args = links_system_libraries(©, false).unwrap(); - assert!(by_args.contains("arguments"), "{by_args}"); - - // The build's own log outranks them, either way. - std::fs::write( - &log, - "ruby extconf.rb\nBuilding a using packaged libraries.\n", - ) - .unwrap(); - assert_eq!(installed_libraries(©).0, Libraries::Packed); - assert_eq!(links_system_libraries(©, true), None); - std::fs::remove_file(&info).unwrap(); - std::fs::write( - &log, - "ruby extconf.rb\nBuilding a using system libraries.\n", - ) - .unwrap(); - assert_eq!(installed_libraries(©).0, Libraries::System); - let by_log = links_system_libraries(©, false).unwrap(); - assert!(by_log.contains("log"), "{by_log}"); + if !records_reads(tmp.path()) { + eprintln!("SKIP: this filesystem does not record reads in access times"); + return; + } + let gem_dir = tmp.path().join("gem"); + std::fs::create_dir_all(gem_dir.join("patches/lib")).unwrap(); + std::fs::create_dir_all(gem_dir.join("ext/a")).unwrap(); + std::fs::write(gem_dir.join("ext/a/a.c"), "int a;\n").unwrap(); + std::fs::write(gem_dir.join("patches/lib/0001.patch"), "fix\n").unwrap(); + let scope = NativeScope { + inputs: vec![ + "ext/a/a.c".to_string(), + "ext/a/deleted.c".to_string(), + "patches/lib/0001.patch".to_string(), + ], + builds_extensions: true, + ..NativeScope::default() + }; - // A build parked while its rebuild runs still says what it linked. - let ext = home.join("extensions/p/3.4.0/a-1"); - std::fs::rename(&ext, parked_build_path(&ext)).unwrap(); - assert_eq!(installed_libraries(©).0, Libraries::System); - } + // An input the record deletes is not there to mark. + let marked = mark_inputs_unread(&gem_dir, &scope); + assert_eq!(marked, ["ext/a/a.c", "patches/lib/0001.patch"]); + assert_eq!( + unread_inputs(&gem_dir, &marked, tmp.path()), + Some(marked.clone()) + ); + // Looking at a file, or listing its dir, is not reading it. + std::fs::metadata(gem_dir.join("ext/a/a.c")).unwrap(); + assert_eq!(std::fs::read_dir(gem_dir.join("ext/a")).unwrap().count(), 1); + assert!(unread_inputs(&gem_dir, &marked, tmp.path()).is_some()); + assert!(unread_detail(&marked).contains("ext/a/a.c, patches/lib/0001.patch")); - /// nokogiri with nothing to say what it links (its log pruned, no - /// arguments recorded) follows the variable when it is rebuilt, so a - /// patch to the libxml2 it packs is not known to be built. - #[test] - fn the_variable_counts_for_nokogiri_when_nothing_else_says() { - let tmp = tempfile::tempdir().unwrap(); - let home = tmp.path(); - let gem_dir = home.join("gems/nokogiri-1.18.10"); - std::fs::create_dir_all(&gem_dir).unwrap(); - std::fs::create_dir_all(home.join("specifications")).unwrap(); - std::fs::write(home.join("specifications/nokogiri-1.18.10.gemspec"), "").unwrap(); - let copy = GemCopy::of(&gem_dir).unwrap(); - assert_eq!(links_system_libraries(©, false), None); - let by_env = links_system_libraries(©, true).unwrap(); - assert!(by_env.contains(SYSTEM_LIBRARY_ENV), "{by_env}"); + // One read is a build of something the patch changes. + std::fs::read(gem_dir.join("patches/lib/0001.patch")).unwrap(); + assert_eq!(unread_inputs(&gem_dir, &marked, tmp.path()), None); - let ext = home.join("extensions/p/3.4.0/nokogiri-1.18.10"); - std::fs::create_dir_all(&ext).unwrap(); - std::fs::write( - ext.join(BUILD_LOG), - "Building nokogiri using packaged libraries.\n", - ) - .unwrap(); - assert_eq!(links_system_libraries(©, true), None); + // Nothing marked, nothing concluded. + assert_eq!(unread_inputs(&gem_dir, &[], tmp.path()), None); + assert!(!tmp.path().join(".socket-patch-read-probe").exists()); } /// In the source-built gem (its gemspec declares the extension) @@ -7026,7 +6846,6 @@ mod tests { platform: "arm64-darwin-25".to_string(), runs_platform: Some(true), }), - libraries: Libraries::Packed, } } @@ -7310,7 +7129,6 @@ mod tests { require_paths: vec!["lib".to_string()], lib_dir: copy.gem_dir.join("lib"), facts: None, - libraries: Libraries::default(), }; let stage = open_stage(©).unwrap(); assert!(stage.home.starts_with(&home), "staged inside the gem home"); diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 577c28e29..96596b7ca 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2113,18 +2113,21 @@ instead of being reported as patched. Ruby files are never build inputs outside `ext/` and a build script's directory: a patch that only changes `.rb` or `.rbs` files needs no compiler, wherever the gem keeps them. -A gem that packs a library and was installed with `--use-system-libraries` (nokogiri with the -system's libxml2, through `gem install nokogiri -- --use-system-libraries`, Bundler's -`build.nokogiri` setting or `NOKOGIRI_USE_SYSTEM_LIBRARIES`) does not compile the library it -packs. A patch to that packed library (a file under `patches/` or `ports/`, or -`dependencies.yml`) changes nothing in such an install, so it fails with -`native_extensions_unsupported` and nothing is written: the library that install runs is the -operating system's package, and updating that package is what fixes it. A patch to the gem's own -C sources is still rebuilt, against the system's libraries: a rebuild links what the installed -build linked (its build log and recorded build arguments say which), even when -`NOKOGIRI_USE_SYSTEM_LIBRARIES` was set only for the install. A precompiled gem always carries -the libraries it packs, and is rebuilt with them even when the project still has that Bundler -setting. +A rebuild is only taken for a build of the patch when the build read at least one of the files +the patch changes. How a gem builds depends on its configuration: nokogiri installed with +`--use-system-libraries` links the operating system's libxml2 and never opens the copy it packs, +so a patch that only adds a fix to that packed copy changes nothing there. `apply` then fails +the package (`native_extensions_unsupported`, or `native_extension_build_failed` when the gem +was rebuilt in place) and leaves the gem as it was, instead of reporting a patch that is in no +compiled code: on such an install the library is the operating system's package, and updating +that package is what fixes it. A patch to the gem's own C sources is rebuilt as usual. The check +needs a filesystem that records file reads; on one that does not (a `noatime` mount, Windows by +default) the build is taken as it is. + +A gem RubyGems compiled is rebuilt with the build arguments RubyGems recorded when it was +installed. A precompiled gem is rebuilt with none: arguments Bundler recorded for it (a +`build.nokogiri --use-system-libraries` setting kept from before nokogiri shipped precompiled +gems) were never used to build it, and following them would replace the libraries the gem ships. The build happens in a stage directory inside the gem home (`.socket-patch-build/`), which is removed afterwards. A gem the build needs that the install lacks (a precompiled nokogiri has no diff --git a/tests/nokogiri/nokogiri_e2e.rb b/tests/nokogiri/nokogiri_e2e.rb index 645d69cd3..d18bec264 100644 --- a/tests/nokogiri/nokogiri_e2e.rb +++ b/tests/nokogiri/nokogiri_e2e.rb @@ -207,8 +207,7 @@ def install settings = {} settings["BUNDLE_PATH"] = "vendor/bundle" if project_home? settings["BUNDLE_FORCE_RUBY_PLATFORM"] = "true" if %w[source system-libraries].include?(want) - by_variable = @opts[:system_libraries_by] == "variable" - settings["BUNDLE_BUILD__NOKOGIRI"] = "--use-system-libraries" if want == "system-libraries" && !by_variable + settings["BUNDLE_BUILD__NOKOGIRI"] = "--use-system-libraries" if want == "system-libraries" (@opts[:settings] || []).each do |pair| key, value = pair.split("=", 2) settings[key] = value.to_s @@ -218,10 +217,6 @@ def install lines = settings.map { |k, v| "#{k}: \"#{v}\"" } File.write(File.join(@proj, ".bundle", "config"), (["---"] + lines).join("\n") + "\n") @install_env = {} - # For the install alone, as `RUN NOKOGIRI_USE_SYSTEM_LIBRARIES=1 bundle - # install` sets it: RubyGems records no build argument, and nothing - # that runs later sees the variable. - @install_env["NOKOGIRI_USE_SYSTEM_LIBRARIES"] = "1" if want == "system-libraries" && by_variable else # The ambient configuration is not this script's to write: the # settings ride on the install's environment instead. @@ -425,9 +420,13 @@ def scenario(name) record = libxml2_record return skip("this release reads no libxml2 patch directory") && nil unless record return skip("JRuby loads no libxml2") && nil if @java && @opts[:build] == "ok" - # Built against the system's libxml2: nothing compiles the copy the - # gem packs, so a patch to that copy cannot take effect. - return not_applied(record, "native_extensions_unsupported") if @shape == "system-libraries" + # Built against the system's libxml2: the build never opens the copy + # the gem packs, so a patch to that copy cannot take effect. (Where + # the filesystem records no reads the CLI cannot tell, and the leg + # says so with --unread-check off.) + if @shape == "system-libraries" + return @opts[:unread_check] ? not_applied(record, "native_extensions_unsupported") : skip("no read tracking here") + end native(record) do |now| now["libxml_patches"].include?(LIBXML2_PATCH) && (@baseline["libxml_patches"] - now["libxml_patches"]).empty? @@ -604,7 +603,7 @@ class SocketPatchE2E < Rails::Application end opts = { :install => "any", :build => "ok", :gem_home => "project", :scenarios => %w[ruby c libxml2], :gems => [], - :settings => [], :system_libraries_by => "setting" } + :settings => [], :unread_check => true } parser = OptionParser.new do |o| o.banner = "usage: ruby nokogiri_e2e.rb --socket-patch BIN --nokogiri VERSION [options]" o.on("--socket-patch BIN", "the socket-patch binary under test") { |v| opts[:socket_patch] = v } @@ -613,10 +612,8 @@ class SocketPatchE2E < Rails::Application "the install to make and require: precompiled (Bundler's default where a platform gem exists),", "source (the ruby platform gem, compiled here), system-libraries (compiled against the system's", "libxml2), java, or any (default)") { |v| opts[:install] = v } - o.on("--system-libraries-by HOW", %w[setting variable], - "how a system-libraries install is asked for: setting (default: Bundler's `build.nokogiri", - "--use-system-libraries`, which RubyGems records) or variable (NOKOGIRI_USE_SYSTEM_LIBRARIES", - "set for the install alone; only with --gem-home project)") { |v| opts[:system_libraries_by] = v } + o.on("--[no-]unread-check", "whether this filesystem records file reads (default: yes), which is what tells", + "socket-patch that a system-libraries build read nothing of a libxml2 patch") { |v| opts[:unread_check] = v } o.on("--build RESULT", %w[ok unavailable refused], "what a patch that needs a rebuild must do: ok (default), unavailable (no toolchain: fail,", "change nothing), refused (a JRuby install)") { |v| opts[:build] = v } From 9d28fdc9ef3a4d47f11de663a3f0e5ac519aae6a Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 16:35:48 -0500 Subject: [PATCH 08/11] Watch a build's inputs with inotify on Linux Access times say whether a build read a file only where the filesystem records reads. This repo's own CI runners are mounted noatime, and so are many container hosts, so there the check concluded nothing and a patch that was compiled into nothing was still attested. On Linux the kernel says which of the watched files were opened, whatever the mount options; access times stay as the way to tell elsewhere. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 14 +- .../tests/e2e_gem_native_ext_build.rs | 16 +- crates/socket-patch-core/src/patch/gem_ext.rs | 192 +++++++++++++----- docs/ecosystems.md | 7 +- 4 files changed, 167 insertions(+), 62 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 9324fb749..5d2fcccd9 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -977,15 +977,17 @@ place (below), a precompiled gem is refused. the patch: what a gem compiles depends on how its build is configured. A gem set up to link the system's copy of a library it packs (nokogiri installed with `--use-system-libraries`) never opens the packed copy's sources, so a record that changes only those would be written, rebuilt -and attested with nothing of it in what Ruby loads. `apply` knows no gem's switches. It gives -the record's build inputs an access time in the past before the build, staged or in place, and -looks at them right after it: a build that read NONE of them did not build the patch. One read +and attested with nothing of it in what Ruby loads. `apply` knows no gem's switches. It watches +the record's build inputs during the build, staged or in place: on Linux with a kernel watch on +those files being opened (inotify, which works whatever the mount options), elsewhere by giving +them an access time in the past and looking at it right after. A build that read NONE of them +did not build the patch. One read is enough, because a record also carries files no build opens. From the stage this fails the package with `native_extensions_unsupported` and nothing is written; from the installed tree it fails with `native_extension_build_failed` and the sources and the previous build are put -back. Either way the copy is never attested. Where a read leaves no trace in a file's access -time (a `noatime` mount, Windows by default), which `apply` tests with a file of its own, -nothing is concluded and the build is taken as it is. +back. Either way the copy is never attested. Off Linux, where a read leaves no trace in a +file's access time (a `noatime` mount, Windows by default), which `apply` tests with a file of +its own, nothing is concluded and the build is taken as it is. **Into the installed copy.** The record's files are written into the copy, and the build takes the place of the compiled code: diff --git a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs index 65314018b..0c03a2d1f 100644 --- a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs +++ b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs @@ -1782,12 +1782,16 @@ fn built_gem_with_its_archive() -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf (tmp, proj, gem_dir, home) } -/// Whether a read of a file under `dir` shows in its access time, as the -/// CLI asks before it concludes anything from a file nobody read. A -/// filesystem mounted `noatime` records none, and there the check under -/// test cannot run. +/// Whether the CLI can tell that a build read a file under `dir`: always +/// on Linux, where the kernel says which files were opened; elsewhere when +/// a read shows in a file's access time, which a filesystem mounted +/// `noatime` does not record. Without either the check under test cannot +/// run. #[cfg(unix)] fn records_reads(dir: &Path) -> bool { + if cfg!(target_os = "linux") { + return true; + } let probe = dir.join("read-probe"); std::fs::write(&probe, b"probe").unwrap(); let old = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000_000); @@ -1819,7 +1823,7 @@ fn a_build_that_reads_nothing_of_the_patch_does_not_apply_it() { let library_patch: [RecordFile<'_>; 1] = [("patches/libsp/0100-CVE-test.patch", None, "fix\n")]; let (_tmp, proj, gem_dir, home) = built_gem_with_its_archive(); if !records_reads(&home) { - eprintln!("SKIP: this filesystem does not record reads in access times"); + eprintln!("SKIP: no way to tell here whether a build read a file"); return; } write_record(&proj.join(".socket"), PURL, &library_patch); @@ -1894,7 +1898,7 @@ fn an_in_place_build_that_reads_nothing_of_the_patch_is_undone() { let (_tmp, proj, gem_dir) = fake_native_gem(true); let home = proj.join("vendor/bundle/ruby/3.4.0"); if !records_reads(&home) { - eprintln!("SKIP: this filesystem does not record reads in access times"); + eprintln!("SKIP: no way to tell here whether a build read a file"); return; } // A build input the installed tree holds and the stand-in build never diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 37e647be2..b1cfc76d0 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -2940,18 +2940,6 @@ fn mark_unread(path: &Path) -> bool { set && accessed(path) == Some(unread_time()) } -/// Mark the record's build inputs under `gem_dir` unread, right before a -/// build of them, and name those that took the mark. An input the record -/// deletes is not there to mark. -fn mark_inputs_unread(gem_dir: &Path, scope: &NativeScope) -> Vec { - scope - .inputs - .iter() - .map(|key| normalize_file_path(key).to_string()) - .filter(|rel| is_safe_relative_subpath(rel) && mark_unread(&gem_dir.join(rel))) - .collect() -} - /// Whether a read of a file in `dir` shows in its access time. A /// filesystem mounted `noatime`, and Windows by default, record none. fn records_reads(dir: &Path) -> bool { @@ -2964,9 +2952,103 @@ fn records_reads(dir: &Path) -> bool { recorded } +/// A kernel watch on files for being opened or read (Linux inotify). It +/// sees a read whatever the mount options: CI runners and container hosts +/// are often mounted `noatime`, where an access time says nothing. +#[cfg(target_os = "linux")] +struct OpenWatch(std::os::fd::OwnedFd); + +#[cfg(target_os = "linux")] +impl OpenWatch { + /// A watch on every one of `paths`, or none at all: a file that cannot + /// be watched could be the one the build reads. + fn on(paths: &[PathBuf]) -> Option { + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + use std::os::unix::ffi::OsStrExt; + // SAFETY: a plain syscall; the fd it returns is owned from here on. + let raw = unsafe { libc::inotify_init1(libc::IN_NONBLOCK | libc::IN_CLOEXEC) }; + if raw < 0 { + return None; + } + // SAFETY: `raw` is a fresh fd nothing else holds. + let fd = unsafe { OwnedFd::from_raw_fd(raw) }; + for path in paths { + let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?; + // SAFETY: `c_path` is a NUL-terminated string that outlives the call. + let watch = unsafe { + libc::inotify_add_watch( + fd.as_raw_fd(), + c_path.as_ptr(), + libc::IN_OPEN | libc::IN_ACCESS, + ) + }; + if watch < 0 { + return None; + } + } + Some(OpenWatch(fd)) + } + + /// Whether any watched file was opened, read or replaced since the + /// watch was set (a replaced file ends its watch, which is an event + /// too: nothing is concluded about a file that is no longer the one + /// watched). + fn fired(&self) -> bool { + use std::os::fd::AsRawFd; + let mut events = [0u8; 4096]; + // SAFETY: the buffer is valid for `events.len()` bytes; the fd is + // non-blocking, so a queue with no event returns at once. + let read = + unsafe { libc::read(self.0.as_raw_fd(), events.as_mut_ptr().cast(), events.len()) }; + read > 0 + } +} + +/// What tells, after a build, whether it read any of a record's build +/// inputs ([`watch_inputs`]). +struct InputWatch { + /// The record's build inputs that are files under the gem dir (one the + /// record deletes is not there to read). + inputs: Vec, + /// Those given the access time [`unread_time`]. + marked: Vec, + #[cfg(target_os = "linux")] + opens: Option, +} + +/// Start watching the record's build inputs under `gem_dir` for a read, +/// right before a build of them: a kernel watch where there is one +/// ([`OpenWatch`]), and an access time in the past everywhere, for the +/// filesystems that record reads. +fn watch_inputs(gem_dir: &Path, scope: &NativeScope) -> InputWatch { + let inputs: Vec = scope + .inputs + .iter() + .map(|key| normalize_file_path(key).to_string()) + .filter(|rel| is_safe_relative_subpath(rel) && is_real_file(&gem_dir.join(rel))) + .collect(); + let marked = inputs + .iter() + .filter(|rel| mark_unread(&gem_dir.join(rel))) + .cloned() + .collect(); + // After the marks: setting one opens the file. + #[cfg(target_os = "linux")] + let opens = { + let paths: Vec = inputs.iter().map(|rel| gem_dir.join(rel)).collect(); + (!paths.is_empty()).then(|| OpenWatch::on(&paths)).flatten() + }; + InputWatch { + inputs, + marked, + #[cfg(target_os = "linux")] + opens, + } +} + /// The build inputs of a record that a build which has just exited cleanly -/// did not read, when it read NONE of them and that can be told -/// (`marked`: [`mark_inputs_unread`]'s answer for `gem_dir`; `probe_dir`: a +/// did not read, when it read NONE of them and that can be told (`watch`: +/// [`watch_inputs`]'s, set on `gem_dir` before the build; `probe_dir`: a /// writable dir on the same filesystem). /// /// A compiler reads what it compiles, and a build script reads the patch @@ -2978,19 +3060,24 @@ fn records_reads(dir: &Path) -> bool { /// broad on purpose, and a build does not read every file a record /// carries (a manifest listing the files it adds). /// -/// `None` wherever a read leaves no trace: nothing is concluded from -/// silence the filesystem imposes. -fn unread_inputs(gem_dir: &Path, marked: &[String], probe_dir: &Path) -> Option> { - if marked.is_empty() { +/// `None` wherever a read leaves no trace (no kernel watch, and a +/// filesystem that records no access): nothing is concluded from silence. +fn unread_inputs(gem_dir: &Path, watch: &InputWatch, probe_dir: &Path) -> Option> { + #[cfg(target_os = "linux")] + if let Some(opens) = &watch.opens { + return (!opens.fired()).then(|| watch.inputs.clone()); + } + if watch.marked.is_empty() { return None; } - let read_any = marked + let read_any = watch + .marked .iter() .any(|rel| accessed(&gem_dir.join(rel)) != Some(unread_time())); if read_any || !records_reads(probe_dir) { return None; } - Some(marked.to_vec()) + Some(watch.marked.clone()) } /// What a refusal says of a build that read none of the record's inputs. @@ -3160,11 +3247,11 @@ async fn rebuild( // Nothing reads the tree between here and the check after the build // but the build. A rebuild without record files (a rollback's, of the // original sources) has no patch to look for. - let marked = if files.is_empty() { - Vec::new() + let watch = if files.is_empty() { + None } else { let (gem_dir, scope) = (copy.gem_dir.clone(), scope.clone()); - crate::utils::fs::run_blocking(move || mark_inputs_unread(&gem_dir, &scope)).await + Some(crate::utils::fs::run_blocking(move || watch_inputs(&gem_dir, &scope)).await) }; let built = run_ruby(&probe.ruby, RubyRun::Build(probe), copy, env, BUILD_TIMEOUT).await; let (copy, probe, scope, files) = (copy.clone(), probe.clone(), scope.clone(), files.clone()); @@ -3178,7 +3265,10 @@ async fn rebuild( "the build exited cleanly but left no extension in {}", probe.extension_dir.display() )), - Ok(_) => match unread_inputs(©.gem_dir, &marked, &snapshot.dir) { + Ok(_) => match watch + .as_ref() + .and_then(|watch| unread_inputs(©.gem_dir, watch, &snapshot.dir)) + { // Before anything else reads the tree: a build that read // nothing of the patch is undone like a failed one. Some(unread) => Err(unread_detail(&unread)), @@ -3953,22 +4043,23 @@ async fn build_in_stage( stage.beat(); // Nothing reads the staged tree between here and the check below but // the build. - let marked = match record { + let watch = match record { Some(record) => { let (gem_dir, scope) = (staged.gem_dir.clone(), record.scope.clone()); - crate::utils::fs::run_blocking(move || mark_inputs_unread(&gem_dir, &scope)).await + Some(crate::utils::fs::run_blocking(move || watch_inputs(&gem_dir, &scope)).await) } - None => Vec::new(), + None => None, }; let stdout = run_ruby(&probe.ruby, run, copy, env, BUILD_TIMEOUT) .await .map_err(StageFailure::Build)?; - let unread = { + if let Some(watch) = watch { let (gem_dir, root) = (staged.gem_dir.clone(), stage.root.clone()); - crate::utils::fs::run_blocking(move || unread_inputs(&gem_dir, &marked, &root)).await - }; - if let Some(unread) = unread { - return Err(StageFailure::NotRead(unread)); + let unread = + crate::utils::fs::run_blocking(move || unread_inputs(&gem_dir, &watch, &root)).await; + if let Some(unread) = unread { + return Err(StageFailure::NotRead(unread)); + } } let reported = tagged_lines(&stdout, "sp_built") .into_iter() @@ -6440,12 +6531,14 @@ mod tests { } /// A build that read none of a record's inputs is told from one that - /// read any of them, by access times, and nothing is concluded where a - /// read leaves no trace or nothing could be marked. + /// read any of them, and nothing is concluded where a read leaves no + /// trace. #[test] fn a_build_that_read_none_of_the_inputs_is_told_from_one_that_read_any() { let tmp = tempfile::tempdir().unwrap(); - if !records_reads(tmp.path()) { + // A kernel watch on Linux, access times elsewhere when the + // filesystem keeps them. + if !cfg!(target_os = "linux") && !records_reads(tmp.path()) { eprintln!("SKIP: this filesystem does not record reads in access times"); return; } @@ -6463,26 +6556,31 @@ mod tests { builds_extensions: true, ..NativeScope::default() }; + let both = [ + "ext/a/a.c".to_string(), + "patches/lib/0001.patch".to_string(), + ]; - // An input the record deletes is not there to mark. - let marked = mark_inputs_unread(&gem_dir, &scope); - assert_eq!(marked, ["ext/a/a.c", "patches/lib/0001.patch"]); - assert_eq!( - unread_inputs(&gem_dir, &marked, tmp.path()), - Some(marked.clone()) - ); + // An input the record deletes is not there to watch. + let watch = watch_inputs(&gem_dir, &scope); + assert_eq!(watch.inputs, both); // Looking at a file, or listing its dir, is not reading it. std::fs::metadata(gem_dir.join("ext/a/a.c")).unwrap(); assert_eq!(std::fs::read_dir(gem_dir.join("ext/a")).unwrap().count(), 1); - assert!(unread_inputs(&gem_dir, &marked, tmp.path()).is_some()); - assert!(unread_detail(&marked).contains("ext/a/a.c, patches/lib/0001.patch")); + assert_eq!( + unread_inputs(&gem_dir, &watch, tmp.path()), + Some(both.to_vec()) + ); + assert!(unread_detail(&both).contains("ext/a/a.c, patches/lib/0001.patch")); // One read is a build of something the patch changes. + let watch = watch_inputs(&gem_dir, &scope); std::fs::read(gem_dir.join("patches/lib/0001.patch")).unwrap(); - assert_eq!(unread_inputs(&gem_dir, &marked, tmp.path()), None); + assert_eq!(unread_inputs(&gem_dir, &watch, tmp.path()), None); - // Nothing marked, nothing concluded. - assert_eq!(unread_inputs(&gem_dir, &[], tmp.path()), None); + // Nothing to watch, nothing concluded. + let none = watch_inputs(&gem_dir, &NativeScope::default()); + assert_eq!(unread_inputs(&gem_dir, &none, tmp.path()), None); assert!(!tmp.path().join(".socket-patch-read-probe").exists()); } diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 96596b7ca..46ae2945a 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2120,9 +2120,10 @@ so a patch that only adds a fix to that packed copy changes nothing there. `appl the package (`native_extensions_unsupported`, or `native_extension_build_failed` when the gem was rebuilt in place) and leaves the gem as it was, instead of reporting a patch that is in no compiled code: on such an install the library is the operating system's package, and updating -that package is what fixes it. A patch to the gem's own C sources is rebuilt as usual. The check -needs a filesystem that records file reads; on one that does not (a `noatime` mount, Windows by -default) the build is taken as it is. +that package is what fixes it. A patch to the gem's own C sources is rebuilt as usual. On Linux +the check asks the kernel which files the build opened. Elsewhere it needs a filesystem that +records file reads; on one that does not (a `noatime` mount, Windows by default) the build is +taken as it is. A gem RubyGems compiled is rebuilt with the build arguments RubyGems recorded when it was installed. A precompiled gem is rebuilt with none: arguments Bundler recorded for it (a From 7ec2d77b2c2d8a2e6404c923cd77f41d726a9fb9 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 16:40:51 -0500 Subject: [PATCH 09/11] Conclude nothing unless every input took the mark Without a kernel watch, an input whose access time could not be set may be the one the build read. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/patch/gem_ext.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index b1cfc76d0..be1677fdf 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -3067,7 +3067,9 @@ fn unread_inputs(gem_dir: &Path, watch: &InputWatch, probe_dir: &Path) -> Option if let Some(opens) = &watch.opens { return (!opens.fired()).then(|| watch.inputs.clone()); } - if watch.marked.is_empty() { + // Every input must have taken the mark: one that did not may be the + // one the build read. + if watch.inputs.is_empty() || watch.marked.len() != watch.inputs.len() { return None; } let read_any = watch @@ -3077,7 +3079,7 @@ fn unread_inputs(gem_dir: &Path, watch: &InputWatch, probe_dir: &Path) -> Option if read_any || !records_reads(probe_dir) { return None; } - Some(watch.marked.clone()) + Some(watch.inputs.clone()) } /// What a refusal says of a build that read none of the record's inputs. From 6835ada45c06a9e2cf7bcaacadc21f29becbde04 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 17:47:17 -0500 Subject: [PATCH 10/11] Write a native gem patch whose build compiled nothing of it, and say so A gem's build does not always compile what a patch changes. One built against the system's copy of a library it packs never opens the packed copy, and one whose extension script downloads the binary it runs (passenger's agent) compiles nothing at all. apply reported such a patch as applied, and vex attested it, while the code the gem runs was unchanged (#2144). Since the read check it was refused with nothing written, which also kept the patch's Ruby files out. apply now writes the record's files, leaves the compiled code as it was installed, and warns with native_extension_not_rebuilt when a clean build read none of the record's build inputs or left no compiled file. No build marker is written, so apply --check reports the package as not in sync and vex does not attest it. A record that changes a build input the installed copy no longer holds is still refused: only a build from the source gem accounts for a file added that way. An in-place build that kept the library it found is still a failed build: that reason is reported ahead of the read check, which the real-toolchain test of it expects. A build can run for many minutes with nothing printed. Each one now says on stderr when it starts and how it ended (not under --json or --silent). Fixes #2144 Co-Authored-By: Claude Fable 5.2 --- .github/workflows/nokogiri-compatibility.yml | 3 +- crates/socket-patch-cli/CLI_CONTRACT.md | 44 ++- crates/socket-patch-cli/src/args.rs | 11 + crates/socket-patch-cli/src/commands/apply.rs | 1 + .../src/commands/gem_refresh.rs | 2 + .../socket-patch-cli/src/commands/rollback.rs | 1 + .../tests/e2e_gem_native_ext_build.rs | 276 +++++++++++++--- crates/socket-patch-core/src/patch/gem_ext.rs | 304 ++++++++++++++---- .../src/patch/gem_refresh.rs | 2 + docs/ecosystems.md | 31 +- tests/nokogiri/nokogiri_e2e.rb | 39 ++- 11 files changed, 588 insertions(+), 126 deletions(-) diff --git a/.github/workflows/nokogiri-compatibility.yml b/.github/workflows/nokogiri-compatibility.yml index d738e3094..1ff58230d 100644 --- a/.github/workflows/nokogiri-compatibility.yml +++ b/.github/workflows/nokogiri-compatibility.yml @@ -24,7 +24,8 @@ name: nokogiri patch compatibility # system-libraries `--use-system-libraries`: the extension is rebuilt # with the recorded build arguments, and a patch to the # vendored libxml2, which such a build does not compile, is -# refused: its build reads nothing of the patch. +# written and not attested: its build reads nothing of the +# patch, and `apply` says so. # The `legacy setting` leg is a precompiled install # in a project that still carries that Bundler setting from # the years before precompiled gems: its rebuild must keep diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 5d2fcccd9..ce2119ac0 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -973,21 +973,37 @@ library under `lib/`, a Ruby file the build generates under a require path. Such loaded from where it was built. The staged build is set aside: a gem RubyGems built is rebuilt in place (below), a precompiled gem is refused. -**A build that reads nothing of the patch.** A build that exits cleanly has not always built +**A build that builds nothing of the patch.** A build that exits cleanly has not always built the patch: what a gem compiles depends on how its build is configured. A gem set up to link the system's copy of a library it packs (nokogiri installed with `--use-system-libraries`) never opens the packed copy's sources, so a record that changes only those would be written, rebuilt -and attested with nothing of it in what Ruby loads. `apply` knows no gem's switches. It watches -the record's build inputs during the build, staged or in place: on Linux with a kernel watch on -those files being opened (inotify, which works whatever the mount options), elsewhere by giving -them an access time in the past and looking at it right after. A build that read NONE of them -did not build the patch. One read -is enough, because a record also carries files no build opens. From the stage this fails the -package with `native_extensions_unsupported` and nothing is written; from the installed tree -it fails with `native_extension_build_failed` and the sources and the previous build are put -back. Either way the copy is never attested. Off Linux, where a read leaves no trace in a -file's access time (a `noatime` mount, Windows by default), which `apply` tests with a file of -its own, nothing is concluded and the build is taken as it is. +and attested with nothing of it in what Ruby loads. A gem whose extension script downloads the +binary it runs (passenger's agent) compiles nothing at all. `apply` knows no gem's switches. It +watches the record's build inputs during the build, staged or in place: on Linux with a kernel +watch on those files being opened (inotify, which works whatever the mount options), elsewhere +by giving them an access time in the past and looking at it right after. A build that read NONE +of them did not build the patch. One read is enough, because a record also carries files no +build opens. Neither did a build that left no compiled file: nothing in RubyGems' extension +directory, and nothing Ruby loads in the gem's own tree. + +In both cases the record's files are written into the installed copy and its compiled code is +left as it was installed: the package's event is `applied`, the run exits 0, and it carries a +`native_extension_not_rebuilt` warning that names the files and says why. The patch's Ruby files +are in effect, and a source the gem compiles later on its own (passenger builds its agent the +first time it starts without one) is the patched one. No build marker is written, so +`apply --check` reports the package as not in sync and `vex` never attests it. A later `apply` +runs the build again and says the same. The one exception is a record that changes a build input +the installed copy no longer holds: only a build from the source gem accounts for a file added +that way, so that package fails with `native_extensions_unsupported` and nothing is written. + +Off Linux, where a read leaves no trace in a file's access time (a `noatime` mount, Windows by +default), which `apply` tests with a file of its own, nothing is concluded from the reads and +the build is taken as it is. + +**What a build prints.** A build can take many minutes. Each one prints a line to stderr when +it starts (`Rebuilding the native extension of from ; this can take several +minutes.`) and one when it ends (`The build of finished after