diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 74e5e02d1..5989b0728 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1211,7 +1211,17 @@ the model is **not uniform** today: is matched to its own release variant. A build is then not the only candidate, so the default mismatch policy never overwrites it: a build whose bytes match no manifest variant is left untouched, fails `apply` (`no matching variant found`) and withholds the `vex` statement, and - `rollback` skips it. PyPI follows the same rule: when the crawler resolves + `rollback` skips it. `vex` and `apply --check` leave out one kind of dir: a build whose gem + home has no gemspec for it (`specifications/.gemspec`, or + `specifications/default/.gemspec`) while another copy of the same version in that home has + its own. RubyGems and Bundler load a gem by that file alone, so nothing loads the dir. It is what + the stale-install remedy (`rm -f specifications/.gemspec … && bundle install`) leaves of a + precompiled build once the `ruby` platform build is installed beside it, and an unpatched one + no longer withholds the `vex` statement (#2087); `bundle clean --force` removes it. The dir + stays a copy when no copy of the version in its home has a gemspec (so a gem never loses its + last copy in a home this way), when its own gemspec cannot be probed, and when a standalone + bundle's `bundler/setup.rb` names it. `apply` and `rollback` write and restore it like any + other dir. PyPI follows the every-copy rule too: when the crawler resolves one release in several site-packages dirs (a Pipenv WORKON_HOME venv beside an auto-detected `./.venv`, or the user site beside a system dir in global scope), agent `apply` patches **every** copy, one summary event per copy, because any of them may be the one the interpreter imports. diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index 951f46fcf..4f8b85c33 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -1314,6 +1314,20 @@ pub async fn find_manifest_package_copies_reusing( } } } + // The dir of a gem build whose gemspec is gone, beside a copy of the + // version that the gem home does list, is no copy RubyGems or Bundler + // loads, so an unpatched one must not block the attestation (#2087). + // Rollback and remove, which resolve without this, still restore it. + for (_, paths) in copies + .iter_mut() + .filter(|(purl, paths)| purl.starts_with("pkg:gem/") && paths.len() > 1) + { + *paths = socket_patch_core::crawlers::ruby_crawler::retain_loaded_gem_builds( + std::mem::take(paths), + ) + .await; + } + copies.retain(|_, paths| !paths.is_empty()); copies } diff --git a/crates/socket-patch-cli/tests/apply/in_process_gem_multicopy.rs b/crates/socket-patch-cli/tests/apply/in_process_gem_multicopy.rs index abceea6b0..39d9442eb 100644 --- a/crates/socket-patch-cli/tests/apply/in_process_gem_multicopy.rs +++ b/crates/socket-patch-cli/tests/apply/in_process_gem_multicopy.rs @@ -346,6 +346,70 @@ fn vex_and_check_refuse_an_unpatched_platform_variant_copy() { ); } +/// #2087: the hosted scan's stale-install remedy (`rm -f +/// specifications/.gemspec cache/.gem && bundle install`) +/// leaves the old platform build's `gems//` dir behind with no +/// gemspec, beside the installed ruby-platform build. RubyGems and Bundler +/// load a gem by its gemspec alone, so that dir is not an installed copy: +/// `vex` attests the patched ruby-platform build and `apply --check` +/// reports it in sync. With its gemspec back, the platform build is a copy +/// again and both gates refuse it (#1092). `apply` and `rollback` write and +/// restore the dir either way. +#[test] +fn the_leftover_dir_of_an_unlisted_platform_build_is_not_a_copy() { + let tmp = tempfile::tempdir().unwrap(); + let (root, plain_file, platform_file, original, patched) = + build_platform_variant_project(tmp.path()); + let specs = root.join("vendor/bundle/ruby/3.2.0/specifications"); + std::fs::create_dir_all(&specs).unwrap(); + std::fs::write(specs.join("rack-3.1.0.gemspec"), "").unwrap(); + std::fs::write(&plain_file, &patched).unwrap(); + + let (code, stdout, stderr) = run_raw(&root, &["vex", "--product", "pkg:gem/app@1.0.0"]); + assert_eq!(code, 0, "vex\nstdout:\n{stdout}\nstderr:\n{stderr}"); + assert!(stdout.contains("not_affected"), "vex doc:\n{stdout}"); + assert!( + !stderr.contains("not_applied"), + "vex must not judge the dir nothing loads\nstderr:\n{stderr}" + ); + let (code, stdout, stderr) = run_raw(&root, &["apply", "--check"]); + assert_eq!( + code, 0, + "apply --check\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_eq!(std::fs::read(&platform_file).unwrap(), original); + + // The platform build installed again (its gemspec is back): RubyGems + // loads it, and it is unpatched. + std::fs::write(specs.join("rack-3.1.0-x86_64-linux.gemspec"), "").unwrap(); + let (code, stdout, stderr) = run_raw(&root, &["vex", "--product", "pkg:gem/app@1.0.0"]); + assert!( + !stdout.contains("not_affected"), + "vex must not attest an unpatched installed platform copy (exit {code})\ + \nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let (code, stdout, stderr) = run_raw(&root, &["apply", "--check"]); + assert_ne!( + code, 0, + "apply --check must flag the installed platform copy\ + \nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + + // The write paths never skipped the dir: with its gemspec gone again, + // `apply` still patches it and `rollback` still restores it, so no + // patched file is left that nothing tracks. + std::fs::remove_file(specs.join("rack-3.1.0-x86_64-linux.gemspec")).unwrap(); + std::fs::write(&plain_file, &original).unwrap(); + let (code, v) = run_json(&root, &["apply"]); + assert_eq!(code, 0, "apply; envelope={v}"); + assert_eq!(std::fs::read(&plain_file).unwrap(), patched); + assert_eq!(std::fs::read(&platform_file).unwrap(), patched); + let (code, v) = run_json(&root, &["rollback", "--yes"]); + assert_eq!(code, 0, "rollback; envelope={v}"); + assert_eq!(std::fs::read(&plain_file).unwrap(), original); + assert_eq!(std::fs::read(&platform_file).unwrap(), original); +} + /// #1092, global mode: `apply -g --global-prefix /gems` patches /// the platform build too (plain RubyGems activates it, no Bundler needed). #[test] diff --git a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs index 39d773b77..965f43c5f 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs @@ -2808,3 +2808,74 @@ fn gem_hosted_ref_is_verified_under_an_out_of_tree_config_bundle_path() { // Read-only: vex never writes the refused root. assert_eq!(std::fs::read(bundle.join(installed)).unwrap(), patched); } + +/// Gem (#2087): a project that moved from a precompiled build to the +/// `ruby` platform build so hosted mode could patch it, then ran the scan's +/// remedy (`rm -f specifications/.gemspec cache/.gem && bundle +/// install`), has the patched `rails-7.0.0/` beside a `rails-7.0.0- +/// x86_64-linux/` dir with no gemspec. Nothing loads that dir, so `vex` +/// attests the gem, in the project's bundle path and in an out-of-tree +/// one alike. With its gemspec back the platform build is installed and +/// unpatched, and `vex` refuses again (#1092). +#[test] +fn gem_hosted_ref_is_attested_beside_a_leftover_platform_dir_with_no_gemspec() { + const U: &str = "77777777-7777-7777-7777-777777777777"; + let purl = "pkg:gem/rails@7.0.0"; + let (pristine, patched) = ( + &b"module Rails; STATUS = :vulnerable; end\n"[..], + &b"module Rails; STATUS = :patched; end\n"[..], + ); + for out_of_tree in [false, true] { + let tmp = tempfile::tempdir().unwrap(); + let cwd = tmp.path().join("app"); + std::fs::create_dir_all(&cwd).unwrap(); + for file in ["Gemfile", "Gemfile.lock"] { + let text = redirect_fixture(&format!("gem/bundler/basic/expected/{file}")); + std::fs::write(cwd.join(file), text).unwrap(); + } + let (bundle, configured) = if out_of_tree { + let bundle = tmp.path().join("outside bundle"); + (bundle.clone(), bundle.display().to_string()) + } else { + (cwd.join("vendor/bundle"), "vendor/bundle".to_string()) + }; + put( + &cwd, + ".bundle/config", + format!("---\nBUNDLE_PATH: \"{configured}\"\n").as_bytes(), + ); + let (_rt, server) = serve_patch_views(vec![( + U.to_string(), + one_file_view(U, purl, "lib/rails.rb", pristine, patched), + )]); + let args = ["--proxy-url", &server.uri()]; + let home = bundle.join("ruby/3.3.0"); + put(&home, "gems/rails-7.0.0/lib/rails.rb", patched); + put(&home, "specifications/rails-7.0.0.gemspec", b""); + let leftover = "gems/rails-7.0.0-x86_64-linux/lib/rails.rb"; + put(&home, leftover, pristine); + + let (code, env) = vex_json(&cwd, &args); + let label = format!("leftover platform dir (out of tree: {out_of_tree})"); + assert_attested(&cwd, code, &env, U, &label); + // Read-only: the leftover dir is not touched. + assert_eq!(std::fs::read(home.join(leftover)).unwrap(), pristine); + + put( + &home, + "specifications/rails-7.0.0-x86_64-linux.gemspec", + b"", + ); + let (code, env) = vex_json(&cwd, &args); + assert_eq!( + code, + Some(1), + "an installed unpatched platform build (out of tree: {out_of_tree}): {env}" + ); + let reason = skipped_reason(&env, purl); + assert!( + reason == "not_applied" || reason == "hash_mismatch", + "the platform build was read and failed verification, got {reason}: {env}" + ); + } +} diff --git a/crates/socket-patch-core/src/crawlers/ruby_crawler.rs b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs index 224b6ed46..eda602093 100644 --- a/crates/socket-patch-core/src/crawlers/ruby_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs @@ -1504,6 +1504,105 @@ pub fn is_default_gem_copy(copy: &Path) -> bool { .is_file() } +/// `copies` (the installed-looking dirs of ONE gem version, as +/// [`RubyCrawler::find_all_by_purls`] returns them) without the leftover +/// dirs nothing loads, for a read-only check of what the project runs. +/// +/// A dir `/gems/` is a leftover when its gem home has no +/// gemspec for it (`specifications/.gemspec`, or the same file under +/// `specifications/default/` for a default gem) while another of `copies` +/// in that home has its own. RubyGems and Bundler find a gem by its +/// gemspec alone. Such a dir is what `rm specifications/.gemspec && +/// bundle install` (the stale-install remedy) leaves of a precompiled +/// build once the project moved to the `ruby` platform build, which is +/// installed beside it. A check that counts it as an installed copy +/// refuses a patched gem over the unpatched files of a dir that is not +/// installed (#2087). +/// +/// Everything short of proof keeps a dir: +/// - a home in which no copy of the version has a gemspec does not say +/// what is installed, so a gem never loses its last copy in a home; +/// - only "not found" proves a gemspec absent, never another stat error; +/// - a `bundle install --standalone` tree loads gems by the paths in its +/// `bundler/setup.rb`, not by gemspec, so a dir that file names (or might +/// name: the file cannot be read) is loaded. +pub async fn retain_loaded_gem_builds(copies: Vec) -> Vec { + run_blocking(move || { + let listed: Vec> = copies.iter().map(|copy| home_lists_copy(copy)).collect(); + let mut index = 0; + let mut copies = copies; + let all = copies.clone(); + copies.retain(|copy| { + let own = listed[index]; + index += 1; + let leftover = own == Some(false) + && all + .iter() + .zip(&listed) + .any(|(other, own)| *own == Some(true) && other.parent() == copy.parent()) + && !standalone_setup_may_load(copy); + !leftover + }); + copies + }) + .await +} + +/// Whether the gem home of the gem dir `/gems/` has a gemspec +/// for it, under `specifications/` or `specifications/default/`. `None` +/// where that cannot be told: the dir is not in a `gems/` dir, or a probe +/// failed with anything but "not found". +fn home_lists_copy(copy: &Path) -> Option { + let gems = copy.parent()?; + if gems.file_name() != Some(OsStr::new("gems")) { + return None; + } + let specs = gems.parent()?.join("specifications"); + let mut own = copy.file_name()?.to_os_string(); + own.push(".gemspec"); + let mut listed = Some(false); + for spec in [specs.join(&own), specs.join("default").join(&own)] { + match std::fs::metadata(&spec) { + Ok(meta) if meta.is_file() => return Some(true), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + _ => listed = None, + } + } + listed +} + +/// Whether a standalone bundle's `bundler/setup.rb` names the gem dir +/// `/gems/`, or cannot be read to tell. The file sits in the +/// bundle path: `/bundler/` for a flat home, two levels up for the +/// scoped `//` home. An entry is the dir's path +/// up to a require path, or the dir itself for a gem that loads from its +/// root. +fn standalone_setup_may_load(copy: &Path) -> bool { + let (Some(leaf), Some(home)) = ( + copy.file_name().and_then(OsStr::to_str), + copy.parent().and_then(Path::parent), + ) else { + return true; + }; + let needle = format!("/gems/{leaf}"); + let names = |text: &str| { + text.match_indices(&needle).any(|(at, _)| { + // The leaf ends here: the next character is not one a longer + // dir name (`-gnu`, `.1`) would continue with. + !text[at + needle.len()..] + .starts_with(|c: char| c.is_ascii_alphanumeric() || "-._".contains(c)) + }) + }; + let bundle_paths = [Some(home), home.parent().and_then(Path::parent)]; + bundle_paths.into_iter().flatten().any(|bundle| { + let setup = bundle.join("bundler").join("setup.rb"); + match crate::utils::fs::read_regular_to_string_sync(&setup) { + Ok(text) => names(&text), + Err(e) => e.kind() != std::io::ErrorKind::NotFound, + } + }) +} + /// One gem home from [`RubyCrawler::bundler_install_homes`]. #[derive(Debug, Clone, PartialEq, Eq)] pub struct BundlerGemHome { @@ -5965,6 +6064,204 @@ mod tests { assert_eq!(one[&purl].path, exact); } + /// A gem home under `root` with a `specifications/` dir; `dir` makes + /// a gem dir in it and `spec` its gemspec. + struct LeftoverHome { + home: PathBuf, + } + impl LeftoverHome { + fn new(home: PathBuf) -> Self { + std::fs::create_dir_all(home.join("specifications/default")).unwrap(); + Self { home } + } + fn dir(&self, leaf: &str) -> PathBuf { + let dir = self.home.join("gems").join(leaf); + std::fs::create_dir_all(dir.join("lib")).unwrap(); + dir + } + fn spec(&self, leaf: &str) { + let spec = self.home.join(format!("specifications/{leaf}.gemspec")); + std::fs::write(spec, "").unwrap(); + } + } + + /// #2087: among the copies of a gem version in one gem home, a dir + /// with no `specifications` entry is a leftover nothing loads once + /// another copy has its own. A default gem's entry is under + /// `specifications/default/`. + #[tokio::test] + async fn retain_loaded_gem_builds_drops_a_dir_with_no_gemspec_beside_a_listed_build() { + let tmp = tempfile::tempdir().unwrap(); + let home = LeftoverHome::new(tmp.path().join("vendor/bundle/ruby/3.3.0")); + + // The ruby build is installed; the platform dir lost its gemspec. + let (plain, platform) = ( + home.dir("nokogiri-1.16.0"), + home.dir("nokogiri-1.16.0-x86_64-linux"), + ); + home.spec("nokogiri-1.16.0"); + assert_eq!( + retain_loaded_gem_builds(vec![plain.clone(), platform.clone()]).await, + vec![plain.clone()] + ); + // Both builds installed (#1092): both are copies, in order. + home.spec("nokogiri-1.16.0-x86_64-linux"); + assert_eq!( + retain_loaded_gem_builds(vec![plain.clone(), platform.clone()]).await, + vec![plain.clone(), platform.clone()] + ); + // The reverse: only the platform build is installed. + std::fs::remove_file(home.home.join("specifications/nokogiri-1.16.0.gemspec")).unwrap(); + assert_eq!( + retain_loaded_gem_builds(vec![plain.clone(), platform.clone()]).await, + vec![platform.clone()] + ); + + // A default gem is listed under `default/`. + let (json, json_java) = (home.dir("json-2.7.2"), home.dir("json-2.7.2-java")); + std::fs::write( + home.home.join("specifications/default/json-2.7.2.gemspec"), + "", + ) + .unwrap(); + assert_eq!( + retain_loaded_gem_builds(vec![json.clone(), json_java]).await, + vec![json] + ); + } + + /// Everything short of proof keeps a dir: a gem never loses its last + /// copy in a home, another home's gemspec says nothing, and neither + /// does a dir outside a `gems/` dir. + #[tokio::test] + async fn retain_loaded_gem_builds_keeps_what_no_gemspec_proves_a_leftover() { + let tmp = tempfile::tempdir().unwrap(); + let home = LeftoverHome::new(tmp.path().join("a/ruby/3.3.0")); + let other = LeftoverHome::new(tmp.path().join("b/ruby/3.3.0")); + + // No copy of the version is listed: a directory is not a gemspec, + // and another version's or another gem's entry is not this one's. + let (plain, java) = (home.dir("puma-6.4.2"), home.dir("puma-6.4.2-java")); + home.spec("puma-6.4.20"); + home.spec("puma-plugin-6.4.2"); + std::fs::create_dir_all(home.home.join("specifications/puma-6.4.2-java.gemspec")).unwrap(); + assert_eq!( + retain_loaded_gem_builds(vec![plain.clone(), java.clone()]).await, + vec![plain.clone(), java.clone()] + ); + // A lone copy is never dropped, listed or not. + assert_eq!( + retain_loaded_gem_builds(vec![plain.clone()]).await, + vec![plain.clone()] + ); + // The listed copy is in ANOTHER home. + let elsewhere = other.dir("puma-6.4.2"); + other.spec("puma-6.4.2"); + assert_eq!( + retain_loaded_gem_builds(vec![elsewhere.clone(), plain.clone(), java.clone()]).await, + vec![elsewhere, plain, java] + ); + // The listed build's own dir is not among the copies (it is + // missing, or the crawler did not take it for a gem): the dir + // beside it is all there is to judge. + let lone = home.dir("ffi-1.17.2-x86_64-linux-gnu"); + home.spec("ffi-1.17.2"); + assert_eq!( + retain_loaded_gem_builds(vec![lone.clone()]).await, + vec![lone] + ); + // Not in a `gems/` dir (a custom `--global-prefix`). + let prefix = tmp.path().join("prefix"); + let (a, b) = (prefix.join("rack-3.1.0"), prefix.join("rack-3.1.0-java")); + std::fs::create_dir_all(tmp.path().join("specifications")).unwrap(); + std::fs::write(tmp.path().join("specifications/rack-3.1.0.gemspec"), "").unwrap(); + assert_eq!( + retain_loaded_gem_builds(vec![a.clone(), b.clone()]).await, + vec![a, b] + ); + assert_eq!( + retain_loaded_gem_builds(Vec::new()).await, + Vec::::new() + ); + } + + /// A gemspec that cannot be probed is not proof the build is gone: only + /// "not found" is. Here the probe fails because `specifications/default` + /// is a file, so a path under it is "not a directory". + #[cfg(unix)] + #[tokio::test] + async fn retain_loaded_gem_builds_keeps_a_dir_whose_gemspec_cannot_be_probed() { + let tmp = tempfile::tempdir().unwrap(); + let home = LeftoverHome::new(tmp.path().join("ruby/3.3.0")); + let (plain, platform) = ( + home.dir("nokogiri-1.16.0"), + home.dir("nokogiri-1.16.0-x86_64-linux"), + ); + home.spec("nokogiri-1.16.0"); + std::fs::remove_dir(home.home.join("specifications/default")).unwrap(); + std::fs::write(home.home.join("specifications/default"), "").unwrap(); + assert_eq!( + retain_loaded_gem_builds(vec![plain.clone(), platform.clone()]).await, + vec![plain, platform] + ); + } + + /// A `bundle install --standalone` tree loads the dirs its + /// `bundler/setup.rb` names, gemspec or not: in the bundle path of a + /// scoped home and of a flat one, with or without a require path + /// after the dir. + #[tokio::test] + async fn retain_loaded_gem_builds_keeps_a_dir_a_standalone_setup_loads() { + let entry = |leaf: &str, tail: &str| { + format!( + "$:.unshift File.expand_path(\"#{{__dir__}}/../#{{RUBY_ENGINE}}/\ + #{{Gem.ruby_api_version}}/gems/{leaf}{tail}\")\n" + ) + }; + for (home_rel, bundle_rel) in [("bundle/ruby/3.3.0", "bundle"), ("flat", "flat")] { + let tmp = tempfile::tempdir().unwrap(); + let home = LeftoverHome::new(tmp.path().join(home_rel)); + let (plain, platform) = ( + home.dir("nokogiri-1.16.0"), + home.dir("nokogiri-1.16.0-x86_64-linux"), + ); + home.spec("nokogiri-1.16.0"); + let both = vec![plain.clone(), platform.clone()]; + let setup = tmp.path().join(bundle_rel).join("bundler/setup.rb"); + std::fs::create_dir_all(setup.parent().unwrap()).unwrap(); + + // A setup file that loads the ruby build, and a longer-named + // build that is not this dir. + let other = entry("nokogiri-1.16.0", "/lib") + + &entry("nokogiri-1.16.0-x86_64-linux-gnu", "/lib") + + &entry("nokogiri-1.16.0-x86_64-linux.1", ""); + std::fs::write(&setup, &other).unwrap(); + assert_eq!( + retain_loaded_gem_builds(both.clone()).await, + vec![plain.clone()], + "{home_rel}" + ); + // One that still loads the platform build, from a require + // path or from the gem's root. + for tail in ["/lib", ""] { + let text = other.clone() + &entry("nokogiri-1.16.0-x86_64-linux", tail); + std::fs::write(&setup, text).unwrap(); + assert_eq!( + retain_loaded_gem_builds(both.clone()).await, + both, + "{home_rel} {tail:?}" + ); + } + // One that cannot be read (here: not UTF-8) might. + std::fs::write(&setup, [0xff, 0xfe]).unwrap(); + assert_eq!( + retain_loaded_gem_builds(both.clone()).await, + both, + "{home_rel}" + ); + } + } + /// A dir that merely starts with `--` is not a platform /// copy when it parses as another gem (`foo-1.0` at `2.0`). #[test] diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 317516802..9bf16bef8 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1975,6 +1975,12 @@ and warns (`redirect_gem_stale_install`), naming the files to remove by hand. `- says what it would replace. `--no-gem-install-refresh` (or `SOCKET_NO_GEM_INSTALL_REFRESH=1`) turns the refresh off. +Removing those files can leave a gem directory behind with no gemspec: after a project moves from +a precompiled build to the `ruby` platform build, `gems/nokogiri-1.16.0-x86_64-linux/` stays next +to the patched `gems/nokogiri-1.16.0/`. RubyGems and Bundler load a gem by its +`specifications/` entry, so nothing loads that directory, and `socket-patch vex` and +`apply --check` don't count it as an installed copy. `bundle clean --force` deletes it. + Gems in a gem home **outside** the project (the system gems, `~/.gem`, an rbenv or asdf home) are not touched: another project on the machine may use the same copy. The run prints one warning naming them. Either install the project's gems into the project, where Bundler fetches the patched