From 84dafc9ff2de8032f590bd311fb9f41370a0c1fe Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:22:51 +0000 Subject: [PATCH 1/5] Start fix for gem dir counted without gemspec Refs #2087. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeSRKgiJ4152hMeivxR From 8b949099e760a7c464139b7b6ff2cdd740d3c0dd Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:52:46 +0000 Subject: [PATCH 2/5] Test a leftover gem build dir is not a copy Failing tests for #2087. A gem home lists the ruby-platform build of a gem version and holds the dir of a precompiled build it has no gemspec for (what the stale-install remedy leaves behind). Nothing loads that dir, yet the crawler returns it as an installed copy and vex refuses the patched gem over it (not_applied). Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeSRKgiJ4152hMeivxR --- .../tests/apply/in_process_gem_multicopy.rs | 55 ++++++++++++ .../src/crawlers/ruby_crawler.rs | 83 +++++++++++++++++++ 2 files changed, 138 insertions(+) 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..766a6a50f 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,61 @@ 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, `apply --check` reports it in sync, and `apply` leaves the dir +/// alone. With its gemspec back, the platform build is a copy again and +/// both gates refuse it (#1092). +#[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}" + ); + let (code, v) = run_json(&root, &["apply"]); + assert_eq!(code, 0, "apply; envelope={v}"); + assert_eq!( + std::fs::read(&platform_file).unwrap(), + original, + "apply must not write to a dir that is not installed; envelope={v}" + ); + + // 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}" + ); +} + /// #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-core/src/crawlers/ruby_crawler.rs b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs index 224b6ed46..b085c5b24 100644 --- a/crates/socket-patch-core/src/crawlers/ruby_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs @@ -5965,6 +5965,89 @@ mod tests { assert_eq!(one[&purl].path, exact); } + /// #2087: in a gem home that lists one build of a gem version, the + /// dir of another build with no `specifications` entry of its own is a + /// leftover nothing loads, not an installed copy. A default gem's entry + /// is under `specifications/default/`. A version the home lists no + /// build of is not judged. + #[tokio::test] + async fn find_all_by_purls_skips_the_leftover_dir_of_an_unlisted_build() { + let tmp = tempfile::tempdir().unwrap(); + let gems = tmp.path().join("gems"); + let specs = tmp.path().join("specifications"); + std::fs::create_dir_all(specs.join("default")).unwrap(); + let dir = |leaf: &str| { + std::fs::create_dir_all(gems.join(leaf).join("lib")).unwrap(); + gems.join(leaf) + }; + let purls: Vec = ["nokogiri@1.16.0", "ffi@1.17.2", "json@2.7.2", "rack@3.1.8"] + .iter() + .map(|g| format!("pkg:gem/{g}")) + .collect(); + + // The ruby build is installed; the platform dir lost its gemspec. + let nokogiri = dir("nokogiri-1.16.0"); + dir("nokogiri-1.16.0-x86_64-linux"); + std::fs::write(specs.join("nokogiri-1.16.0.gemspec"), "").unwrap(); + // The reverse: only the platform build is installed. + dir("ffi-1.17.2"); + let ffi = dir("ffi-1.17.2-x86_64-linux-gnu"); + std::fs::write(specs.join("ffi-1.17.2-x86_64-linux-gnu.gemspec"), "").unwrap(); + // A default gem, beside a leftover platform dir. + let json = dir("json-2.7.2"); + dir("json-2.7.2-java"); + std::fs::write(specs.join("default").join("json-2.7.2.gemspec"), "").unwrap(); + // The home lists no build of this version (a directory is not a + // gemspec): nothing says what is installed, so both dirs stay. + let rack = dir("rack-3.1.8"); + let rack_java = dir("rack-3.1.8-java"); + std::fs::create_dir_all(specs.join("rack-3.1.8-java.gemspec")).unwrap(); + + let crawler = RubyCrawler::new(); + let all = crawler.find_all_by_purls(&gems, &purls).await.unwrap(); + let paths = |purl: &str| -> Vec { + all.get(purl) + .map(|copies| copies.iter().map(|p| p.path.clone()).collect()) + .unwrap_or_default() + }; + assert_eq!(paths(&purls[0]), vec![nokogiri.clone()]); + assert_eq!(paths(&purls[1]), vec![ffi.clone()]); + assert_eq!(paths(&purls[2]), vec![json.clone()]); + assert_eq!(paths(&purls[3]), vec![rack.clone(), rack_java]); + + // The one-copy lookups agree. + let each = crawler.find_each_by_purl(&gems, &purls).await; + let each: Vec> = each.into_iter().map(|p| p.map(|p| p.path)).collect(); + assert_eq!( + each, + vec![ + Some(nokogiri.clone()), + Some(ffi.clone()), + Some(json.clone()), + Some(rack.clone()) + ] + ); + + // And so does the scan's discovery: each gem is found at a dir + // the lookups resolve it to, never at a leftover. + let options = CrawlerOptions { + cwd: tmp.path().to_path_buf(), + global: false, + global_prefix: Some(gems.clone()), + }; + let crawled: HashMap = crawler + .crawl_all(&options) + .await + .into_iter() + .map(|p| (p.purl, p.path)) + .collect(); + assert_eq!(crawled.len(), 4, "{crawled:?}"); + assert_eq!(crawled[&purls[0]], nokogiri); + assert_eq!(crawled[&purls[1]], ffi); + assert_eq!(crawled[&purls[2]], json); + assert!(crawled[&purls[3]].starts_with(&gems), "{crawled:?}"); + } + /// A dir that merely starts with `--` is not a platform /// copy when it parses as another gem (`foo-1.0` at `2.0`). #[test] From 09e05dfa71998c1bdb4fab255b6f623d22faa731 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:52:46 +0000 Subject: [PATCH 3/5] Skip the leftover dir of an unlisted gem build The Ruby crawler counted every gems/-[-] dir with a lib/ as an installed copy. RubyGems and Bundler load a gem by its specifications entry alone, so the dir of a build whose gemspec is gone is one nothing loads. The hosted scan's remedy for a stale precompiled build (rm its gemspec and archive, then bundle install) leaves exactly that beside the patched ruby-platform build, and vex then refused the gem as not_applied. A build's dir is now skipped when its gem home has no gemspec for it but has one for another build of the same version. A version the home lists no build of is not judged, so nothing changes where the home does not say what is installed. The scan's discovery follows the same rule, so it never names a dir the lookups skip. Fixes #2087. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeSRKgiJ4152hMeivxR --- crates/socket-patch-cli/CLI_CONTRACT.md | 9 ++- .../src/crawlers/ruby_crawler.rs | 62 ++++++++++++++++++- docs/ecosystems.md | 6 ++ 3 files changed, 74 insertions(+), 3 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 74e5e02d1..eade5ce50 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1211,7 +1211,14 @@ 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. A build's dir is not a copy when its gem home has no gemspec for it + (`specifications/.gemspec`, or `specifications/default/.gemspec`) but has one for + another build of the same version: 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. No command patches, restores or verifies it, and `vex` does not withhold a statement + over it (#2087); `bundle clean --force` removes it. A version the home has no gemspec for at + all is not judged this way. 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-core/src/crawlers/ruby_crawler.rs b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs index b085c5b24..887a82d0e 100644 --- a/crates/socket-patch-core/src/crawlers/ruby_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs @@ -1094,6 +1094,13 @@ impl RubyCrawler { if !self.verify_gem_at_path(&gem_dir).await { continue; } + // Nor is the leftover dir of a build the gem home no + // longer lists (#2087), which `find_by_purls` would not + // find again. + let (dir, n, v) = (gem_dir.clone(), name.clone(), version.clone()); + if run_blocking(move || is_leftover_build_sync(&dir, &n, &v)).await { + continue; + } let purl = crate::utils::purl::build_gem_purl(&name, &version); @@ -1255,6 +1262,9 @@ impl RubyCrawler { /// append a `-` suffix (`--x86_64-linux/`). A gem /// home can hold several of them at once, so every verifying one is /// returned: the plain dir first, then the platform dirs in name order. +/// +/// The leftover dir of a build the gem home no longer lists is not an +/// installed copy ([`is_leftover_build_sync`]). fn locate_gem_dirs_sync( gem_path: &Path, name: &str, @@ -1263,7 +1273,7 @@ fn locate_gem_dirs_sync( ) -> Vec { let mut dirs = Vec::new(); let exact = gem_path.join(format!("{name}-{version}")); - if verify_gem_at_path_sync(&exact) { + if verify_gem_at_path_sync(&exact) && !is_leftover_build_sync(&exact, name, version) { dirs.push(exact); } let names = super::listing::names_memoized(gem_path, names); @@ -1276,11 +1286,59 @@ fn locate_gem_dirs_sync( siblings .into_iter() .map(|dir_name| gem_path.join(dir_name)) - .filter(|dir| verify_gem_at_path_sync(dir)), + .filter(|dir| { + verify_gem_at_path_sync(dir) && !is_leftover_build_sync(dir, name, version) + }), ); dirs } +/// Whether the gem dir `/gems/`, a build of `name` `version`, +/// is a leftover: its gem home has no gemspec for it +/// (`specifications/.gemspec`, or the same file under +/// `specifications/default/` for a default gem) but has one for another +/// build of that version. +/// +/// RubyGems and Bundler find a gem by its gemspec alone, so nothing loads +/// such a dir. It 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. Counting it as an installed copy made `vex` refuse the +/// patched gem over the unpatched files of a dir that is not installed +/// (#2087). +/// +/// A dir is judged only against a home that lists its gem version: where +/// the home has no `specifications/` dir, or no gemspec for any build of +/// the version, nothing says what is installed, and the dir stays a copy. +fn is_leftover_build_sync(gem_dir: &Path, name: &str, version: &str) -> bool { + use crate::utils::fs::is_dir_sync; + let (Some(leaf), Some(home)) = (gem_dir.file_name(), gem_dir.parent().and_then(Path::parent)) + else { + return false; + }; + let specs = home.join("specifications"); + if !is_dir_sync(&specs) { + return false; + } + let spec_dirs = [specs.join("default"), specs]; + let mut own = leaf.to_os_string(); + own.push(".gemspec"); + if spec_dirs.iter().any(|dir| dir.join(&own).is_file()) { + return false; + } + let exact = format!("{name}-{version}"); + spec_dirs.iter().any(|dir| { + super::listing::list_dir_sync(dir).iter().any(|entry| { + entry + .name + .to_str() + .and_then(|file| file.strip_suffix(".gemspec")) + .is_some_and(|build| build == exact || is_platform_dir_of(build, name, version)) + && dir.join(&entry.name).is_file() + }) + }) +} + /// Blocking twin of `RubyCrawler::verify_gem_at_path`: a directory holding /// `lib/` or a `.gemspec`. fn verify_gem_at_path_sync(path: &Path) -> bool { 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 From d29c1010cf9b9a66c445519fe5067a20d69b8140 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 02:38:09 +0000 Subject: [PATCH 4/5] Leave leftover gem dirs out of vex and check only The first fix skipped a leftover build dir in the crawler, which every mode resolves through. Review found that too wide: rollback and remove would stop restoring such a dir after agent mode had patched it, a standalone bundle can still load it through bundler/setup.rb, and is_file() took any stat error for an absent gemspec. The crawler is back to what main has. is_leftover_gem_build is now applied where vex and apply --check collect copies, beside the filters of #1098 and #599, so the write paths see every dir as before. It calls a dir a leftover only on proof: the gemspec is not found (no other stat error counts), another build of the version is listed, and no standalone setup.rb names the dir. Adds the hosted-mode vex test for the state #2087 reports, for a bundle path inside the project and one outside it. Fixes #2087. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeSRKgiJ4152hMeivxR --- crates/socket-patch-cli/CLI_CONTRACT.md | 18 +- .../src/ecosystem_dispatch.rs | 14 + .../tests/apply/in_process_gem_multicopy.rs | 31 +- .../tests/e2e_vex_redirect.rs | 71 ++++ .../src/crawlers/ruby_crawler.rs | 332 +++++++++++------- 5 files changed, 320 insertions(+), 146 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index eade5ce50..754195caa 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1211,14 +1211,16 @@ 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. A build's dir is not a copy when its gem home has no gemspec for it - (`specifications/.gemspec`, or `specifications/default/.gemspec`) but has one for - another build of the same version: 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. No command patches, restores or verifies it, and `vex` does not withhold a statement - over it (#2087); `bundle clean --force` removes it. A version the home has no gemspec for at - all is not judged this way. PyPI follows the every-copy rule too: 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`) but has one for another build of the same version. + 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 the home has no gemspec for any build of the version, 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..a5e42dce9 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 another build + // 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 (purl, paths) in copies + .iter_mut() + .filter(|(purl, _)| purl.starts_with("pkg:gem/")) + { + paths.retain(|path| { + !socket_patch_core::crawlers::ruby_crawler::is_leftover_gem_build(path, purl) + }); + } + 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 766a6a50f..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 @@ -350,10 +350,11 @@ fn vex_and_check_refuse_an_unpatched_platform_variant_copy() { /// 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, `apply --check` reports it in sync, and `apply` leaves the dir -/// alone. With its gemspec back, the platform build is a copy again and -/// both gates refuse it (#1092). +/// 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(); @@ -376,13 +377,7 @@ fn the_leftover_dir_of_an_unlisted_platform_build_is_not_a_copy() { code, 0, "apply --check\nstdout:\n{stdout}\nstderr:\n{stderr}" ); - let (code, v) = run_json(&root, &["apply"]); - assert_eq!(code, 0, "apply; envelope={v}"); - assert_eq!( - std::fs::read(&platform_file).unwrap(), - original, - "apply must not write to a dir that is not installed; envelope={v}" - ); + 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. @@ -399,6 +394,20 @@ fn the_leftover_dir_of_an_unlisted_platform_build_is_not_a_copy() { "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 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 887a82d0e..0d1f09028 100644 --- a/crates/socket-patch-core/src/crawlers/ruby_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs @@ -1094,13 +1094,6 @@ impl RubyCrawler { if !self.verify_gem_at_path(&gem_dir).await { continue; } - // Nor is the leftover dir of a build the gem home no - // longer lists (#2087), which `find_by_purls` would not - // find again. - let (dir, n, v) = (gem_dir.clone(), name.clone(), version.clone()); - if run_blocking(move || is_leftover_build_sync(&dir, &n, &v)).await { - continue; - } let purl = crate::utils::purl::build_gem_purl(&name, &version); @@ -1262,9 +1255,6 @@ impl RubyCrawler { /// append a `-` suffix (`--x86_64-linux/`). A gem /// home can hold several of them at once, so every verifying one is /// returned: the plain dir first, then the platform dirs in name order. -/// -/// The leftover dir of a build the gem home no longer lists is not an -/// installed copy ([`is_leftover_build_sync`]). fn locate_gem_dirs_sync( gem_path: &Path, name: &str, @@ -1273,7 +1263,7 @@ fn locate_gem_dirs_sync( ) -> Vec { let mut dirs = Vec::new(); let exact = gem_path.join(format!("{name}-{version}")); - if verify_gem_at_path_sync(&exact) && !is_leftover_build_sync(&exact, name, version) { + if verify_gem_at_path_sync(&exact) { dirs.push(exact); } let names = super::listing::names_memoized(gem_path, names); @@ -1286,59 +1276,11 @@ fn locate_gem_dirs_sync( siblings .into_iter() .map(|dir_name| gem_path.join(dir_name)) - .filter(|dir| { - verify_gem_at_path_sync(dir) && !is_leftover_build_sync(dir, name, version) - }), + .filter(|dir| verify_gem_at_path_sync(dir)), ); dirs } -/// Whether the gem dir `/gems/`, a build of `name` `version`, -/// is a leftover: its gem home has no gemspec for it -/// (`specifications/.gemspec`, or the same file under -/// `specifications/default/` for a default gem) but has one for another -/// build of that version. -/// -/// RubyGems and Bundler find a gem by its gemspec alone, so nothing loads -/// such a dir. It 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. Counting it as an installed copy made `vex` refuse the -/// patched gem over the unpatched files of a dir that is not installed -/// (#2087). -/// -/// A dir is judged only against a home that lists its gem version: where -/// the home has no `specifications/` dir, or no gemspec for any build of -/// the version, nothing says what is installed, and the dir stays a copy. -fn is_leftover_build_sync(gem_dir: &Path, name: &str, version: &str) -> bool { - use crate::utils::fs::is_dir_sync; - let (Some(leaf), Some(home)) = (gem_dir.file_name(), gem_dir.parent().and_then(Path::parent)) - else { - return false; - }; - let specs = home.join("specifications"); - if !is_dir_sync(&specs) { - return false; - } - let spec_dirs = [specs.join("default"), specs]; - let mut own = leaf.to_os_string(); - own.push(".gemspec"); - if spec_dirs.iter().any(|dir| dir.join(&own).is_file()) { - return false; - } - let exact = format!("{name}-{version}"); - spec_dirs.iter().any(|dir| { - super::listing::list_dir_sync(dir).iter().any(|entry| { - entry - .name - .to_str() - .and_then(|file| file.strip_suffix(".gemspec")) - .is_some_and(|build| build == exact || is_platform_dir_of(build, name, version)) - && dir.join(&entry.name).is_file() - }) - }) -} - /// Blocking twin of `RubyCrawler::verify_gem_at_path`: a directory holding /// `lib/` or a `.gemspec`. fn verify_gem_at_path_sync(path: &Path) -> bool { @@ -1562,6 +1504,79 @@ pub fn is_default_gem_copy(copy: &Path) -> bool { .is_file() } +/// Whether the installed-looking gem dir `copy` (`/gems/`), a +/// build of the gem `purl` names, is a leftover nothing loads: its gem home has +/// no gemspec for it (`specifications/.gemspec`, or the same file +/// under `specifications/default/` for a default gem) but has one for +/// another build of that version. +/// +/// 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 the dir a copy: +/// - a home with no `specifications/` dir, or with no gemspec for any build +/// of the version, does not say what is installed; +/// - only "not found" proves the dir's own gemspec absent, never another +/// stat error; +/// - a `bundle install --standalone` tree loads gems by the paths in +/// `/bundler/setup.rb`, not by gemspec, so a dir that file +/// names (or might name: the file cannot be read) is loaded. +pub fn is_leftover_gem_build(copy: &Path, purl: &str) -> bool { + let base = crate::utils::purl::strip_purl_qualifiers(purl); + let Some((name, version)) = crate::utils::purl::parse_gem_purl(base) else { + return false; + }; + let (name, version) = (name.as_ref(), version.as_ref()); + let (Some(leaf), Some(home)) = ( + copy.file_name().and_then(OsStr::to_str), + copy.parent().and_then(Path::parent), + ) else { + return false; + }; + let specs = home.join("specifications"); + let spec_dirs = [specs.join("default"), specs]; + let own = format!("{leaf}.gemspec"); + let own_absent = spec_dirs.iter().all(|dir| { + matches!(std::fs::metadata(dir.join(&own)), Err(e) if e.kind() == std::io::ErrorKind::NotFound) + }); + if !own_absent { + return false; + } + let exact = format!("{name}-{version}"); + let another_build_listed = spec_dirs.iter().any(|dir| { + super::listing::list_dir_sync(dir).iter().any(|entry| { + entry + .name + .to_str() + .and_then(|file| file.strip_suffix(".gemspec")) + .is_some_and(|build| { + build != leaf && (build == exact || is_platform_dir_of(build, name, version)) + }) + && dir.join(&entry.name).is_file() + }) + }); + if !another_build_listed { + return false; + } + // `//` is the home; the standalone setup file + // is `/bundler/setup.rb`. + let Some(setup) = home + .parent() + .and_then(Path::parent) + .map(|bundle| bundle.join("bundler").join("setup.rb")) + else { + return true; + }; + match crate::utils::fs::read_regular_to_string_sync(&setup) { + Ok(text) => !text.contains(&format!("/gems/{leaf}/")), + Err(e) => e.kind() == std::io::ErrorKind::NotFound, + } +} + /// One gem home from [`RubyCrawler::bundler_install_homes`]. #[derive(Debug, Clone, PartialEq, Eq)] pub struct BundlerGemHome { @@ -6025,85 +6040,148 @@ mod tests { /// #2087: in a gem home that lists one build of a gem version, the /// dir of another build with no `specifications` entry of its own is a - /// leftover nothing loads, not an installed copy. A default gem's entry - /// is under `specifications/default/`. A version the home lists no - /// build of is not judged. - #[tokio::test] - async fn find_all_by_purls_skips_the_leftover_dir_of_an_unlisted_build() { + /// leftover nothing loads. A default gem's entry is under + /// `specifications/default/`. A version the home lists no build of is + /// not judged, nor is a dir outside a gem home. + #[test] + fn is_leftover_gem_build_needs_another_build_listed_and_none_of_its_own() { let tmp = tempfile::tempdir().unwrap(); - let gems = tmp.path().join("gems"); - let specs = tmp.path().join("specifications"); + let home = tmp.path().join("vendor/bundle/ruby/3.3.0"); + let gems = home.join("gems"); + let specs = home.join("specifications"); std::fs::create_dir_all(specs.join("default")).unwrap(); let dir = |leaf: &str| { std::fs::create_dir_all(gems.join(leaf).join("lib")).unwrap(); gems.join(leaf) }; - let purls: Vec = ["nokogiri@1.16.0", "ffi@1.17.2", "json@2.7.2", "rack@3.1.8"] - .iter() - .map(|g| format!("pkg:gem/{g}")) - .collect(); + let spec = |leaf: &str| std::fs::write(specs.join(format!("{leaf}.gemspec")), "").unwrap(); // The ruby build is installed; the platform dir lost its gemspec. - let nokogiri = dir("nokogiri-1.16.0"); - dir("nokogiri-1.16.0-x86_64-linux"); - std::fs::write(specs.join("nokogiri-1.16.0.gemspec"), "").unwrap(); + spec("nokogiri-1.16.0"); + assert!(is_leftover_gem_build( + &dir("nokogiri-1.16.0-x86_64-linux"), + "pkg:gem/nokogiri@1.16.0" + )); + assert!(!is_leftover_gem_build( + &dir("nokogiri-1.16.0"), + "pkg:gem/nokogiri@1.16.0" + )); + // A purl carrying a `?platform=` qualifier names the same gem. + assert!(is_leftover_gem_build( + &dir("nokogiri-1.16.0-x86_64-linux"), + "pkg:gem/nokogiri@1.16.0?platform=x86_64-linux" + )); + assert!(!is_leftover_gem_build( + &dir("nokogiri-1.16.0-x86_64-linux"), + "pkg:npm/nokogiri@1.16.0" + )); // The reverse: only the platform build is installed. - dir("ffi-1.17.2"); - let ffi = dir("ffi-1.17.2-x86_64-linux-gnu"); - std::fs::write(specs.join("ffi-1.17.2-x86_64-linux-gnu.gemspec"), "").unwrap(); - // A default gem, beside a leftover platform dir. - let json = dir("json-2.7.2"); - dir("json-2.7.2-java"); + spec("ffi-1.17.2-x86_64-linux-gnu"); + assert!(is_leftover_gem_build( + &dir("ffi-1.17.2"), + "pkg:gem/ffi@1.17.2" + )); + assert!(!is_leftover_gem_build( + &dir("ffi-1.17.2-x86_64-linux-gnu"), + "pkg:gem/ffi@1.17.2" + )); + // A default gem is listed under `default/`, and vouches for + // itself only. std::fs::write(specs.join("default").join("json-2.7.2.gemspec"), "").unwrap(); - // The home lists no build of this version (a directory is not a - // gemspec): nothing says what is installed, so both dirs stay. - let rack = dir("rack-3.1.8"); - let rack_java = dir("rack-3.1.8-java"); - std::fs::create_dir_all(specs.join("rack-3.1.8-java.gemspec")).unwrap(); + assert!(!is_leftover_gem_build( + &dir("json-2.7.2"), + "pkg:gem/json@2.7.2" + )); + assert!(is_leftover_gem_build( + &dir("json-2.7.2-java"), + "pkg:gem/json@2.7.2" + )); + // Both builds installed (#1092): neither is a leftover. + spec("rack-3.1.0"); + spec("rack-3.1.0-x86_64-linux"); + assert!(!is_leftover_gem_build( + &dir("rack-3.1.0"), + "pkg:gem/rack@3.1.0" + )); + assert!(!is_leftover_gem_build( + &dir("rack-3.1.0-x86_64-linux"), + "pkg:gem/rack@3.1.0" + )); + // The home lists no build of this version: another version's + // gemspec, another gem sharing the prefix and a directory named + // like a gemspec say nothing about it. + spec("puma-6.4.20"); + spec("puma-6.4.2.1"); + spec("puma-6.4.2-1.0"); + spec("puma-plugin-6.4.2"); + std::fs::create_dir_all(specs.join("puma-6.4.2-java.gemspec")).unwrap(); + assert!(!is_leftover_gem_build( + &dir("puma-6.4.2"), + "pkg:gem/puma@6.4.2" + )); + assert!(!is_leftover_gem_build( + &dir("puma-6.4.2-java"), + "pkg:gem/puma@6.4.2" + )); + // Not a gem home, and a path with no home at all. + let bare = tmp.path().join("bare/gems/nokogiri-1.16.0-x86_64-linux"); + std::fs::create_dir_all(bare.join("lib")).unwrap(); + assert!(!is_leftover_gem_build(&bare, "pkg:gem/nokogiri@1.16.0")); + assert!(!is_leftover_gem_build( + Path::new("nokogiri-1.16.0-x86_64-linux"), + "pkg:gem/nokogiri@1.16.0" + )); + } - let crawler = RubyCrawler::new(); - let all = crawler.find_all_by_purls(&gems, &purls).await.unwrap(); - let paths = |purl: &str| -> Vec { - all.get(purl) - .map(|copies| copies.iter().map(|p| p.path.clone()).collect()) - .unwrap_or_default() - }; - assert_eq!(paths(&purls[0]), vec![nokogiri.clone()]); - assert_eq!(paths(&purls[1]), vec![ffi.clone()]); - assert_eq!(paths(&purls[2]), vec![json.clone()]); - assert_eq!(paths(&purls[3]), vec![rack.clone(), rack_java]); - - // The one-copy lookups agree. - let each = crawler.find_each_by_purl(&gems, &purls).await; - let each: Vec> = each.into_iter().map(|p| p.map(|p| p.path)).collect(); - assert_eq!( - each, - vec![ - Some(nokogiri.clone()), - Some(ffi.clone()), - Some(json.clone()), - Some(rack.clone()) - ] - ); + /// 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)] + #[test] + fn is_leftover_gem_build_keeps_a_dir_whose_gemspec_cannot_be_probed() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("ruby/3.3.0"); + let copy = home.join("gems/nokogiri-1.16.0-x86_64-linux"); + std::fs::create_dir_all(copy.join("lib")).unwrap(); + let specs = home.join("specifications"); + std::fs::create_dir_all(&specs).unwrap(); + std::fs::write(specs.join("nokogiri-1.16.0.gemspec"), "").unwrap(); + assert!(is_leftover_gem_build(©, "pkg:gem/nokogiri@1.16.0")); + std::fs::write(specs.join("default"), "").unwrap(); + assert!(!is_leftover_gem_build(©, "pkg:gem/nokogiri@1.16.0")); + } - // And so does the scan's discovery: each gem is found at a dir - // the lookups resolve it to, never at a leftover. - let options = CrawlerOptions { - cwd: tmp.path().to_path_buf(), - global: false, - global_prefix: Some(gems.clone()), - }; - let crawled: HashMap = crawler - .crawl_all(&options) - .await - .into_iter() - .map(|p| (p.purl, p.path)) - .collect(); - assert_eq!(crawled.len(), 4, "{crawled:?}"); - assert_eq!(crawled[&purls[0]], nokogiri); - assert_eq!(crawled[&purls[1]], ffi); - assert_eq!(crawled[&purls[2]], json); - assert!(crawled[&purls[3]].starts_with(&gems), "{crawled:?}"); + /// A `bundle install --standalone` tree loads the dirs its + /// `bundler/setup.rb` names, gemspec or not. + #[test] + fn is_leftover_gem_build_keeps_a_dir_a_standalone_setup_loads() { + let tmp = tempfile::tempdir().unwrap(); + let bundle = tmp.path().join("bundle"); + let home = bundle.join("ruby/3.3.0"); + let copy = home.join("gems/nokogiri-1.16.0-x86_64-linux"); + std::fs::create_dir_all(copy.join("lib")).unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + std::fs::write(home.join("specifications/nokogiri-1.16.0.gemspec"), "").unwrap(); + std::fs::create_dir_all(bundle.join("bundler")).unwrap(); + let setup = bundle.join("bundler/setup.rb"); + + // A setup file that loads the ruby build only. + std::fs::write( + &setup, + "$:.unshift File.expand_path(\"#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/nokogiri-1.16.0/lib\")\n", + ) + .unwrap(); + assert!(is_leftover_gem_build(©, "pkg:gem/nokogiri@1.16.0")); + // One that still loads the platform build. + std::fs::write( + &setup, + "$:.unshift File.expand_path(\"#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/nokogiri-1.16.0-x86_64-linux/lib\")\n", + ) + .unwrap(); + assert!(!is_leftover_gem_build(©, "pkg:gem/nokogiri@1.16.0")); + // One that cannot be read (here: not UTF-8) might. + std::fs::write(&setup, [0xff, 0xfe]).unwrap(); + assert!(!is_leftover_gem_build(©, "pkg:gem/nokogiri@1.16.0")); } /// A dir that merely starts with `--` is not a platform From 640b52bbf9f9c96e552417afe4c03d42d64492b2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 03:00:27 +0000 Subject: [PATCH 5/5] Drop a leftover gem dir only beside a listed copy Second review pass on the verify-only filter: - The listed build had to exist only as a gemspec. With its dir missing, a gem could lose every copy and the hosted lock pin would attest with nothing hashed. The filter now takes the copies of one gem version and drops a dir only when another of them in the same home has its gemspec. - A standalone setup.rb was looked for two levels above the home only, and matched only with a slash after the dir. A flat home keeps it in /bundler, and a gem loaded from its root has no slash. - A dir whose parent is not gems/ is not judged. - The probes run in one blocking task per gem. Refs #2087. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeSRKgiJ4152hMeivxR --- crates/socket-patch-cli/CLI_CONTRACT.md | 13 +- .../src/ecosystem_dispatch.rs | 20 +- .../src/crawlers/ruby_crawler.rs | 462 ++++++++++-------- 3 files changed, 287 insertions(+), 208 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 754195caa..5989b0728 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1213,14 +1213,15 @@ the model is **not uniform** today: untouched, fails `apply` (`no matching variant found`) and withholds the `vex` statement, and `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`) but has one for another build of the same version. - 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 + `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 the home has no gemspec for any build of the version, 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 + 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 a5e42dce9..4f8b85c33 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -1314,18 +1314,18 @@ pub async fn find_manifest_package_copies_reusing( } } } - // The dir of a gem build whose gemspec is gone, beside another build - // 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 (purl, paths) in copies + // 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, _)| purl.starts_with("pkg:gem/")) + .filter(|(purl, paths)| purl.starts_with("pkg:gem/") && paths.len() > 1) { - paths.retain(|path| { - !socket_patch_core::crawlers::ruby_crawler::is_leftover_gem_build(path, purl) - }); + *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-core/src/crawlers/ruby_crawler.rs b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs index 0d1f09028..eda602093 100644 --- a/crates/socket-patch-core/src/crawlers/ruby_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs @@ -1504,77 +1504,103 @@ pub fn is_default_gem_copy(copy: &Path) -> bool { .is_file() } -/// Whether the installed-looking gem dir `copy` (`/gems/`), a -/// build of the gem `purl` names, is a leftover nothing loads: its gem home has -/// no gemspec for it (`specifications/.gemspec`, or the same file -/// under `specifications/default/` for a default gem) but has one for -/// another build of that version. +/// `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. /// -/// 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). +/// 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 the dir a copy: -/// - a home with no `specifications/` dir, or with no gemspec for any build -/// of the version, does not say what is installed; -/// - only "not found" proves the dir's own gemspec absent, never another -/// stat error; -/// - a `bundle install --standalone` tree loads gems by the paths in -/// `/bundler/setup.rb`, not by gemspec, so a dir that file -/// names (or might name: the file cannot be read) is loaded. -pub fn is_leftover_gem_build(copy: &Path, purl: &str) -> bool { - let base = crate::utils::purl::strip_purl_qualifiers(purl); - let Some((name, version)) = crate::utils::purl::parse_gem_purl(base) else { - return false; - }; - let (name, version) = (name.as_ref(), version.as_ref()); +/// 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 false; + return true; }; - let specs = home.join("specifications"); - let spec_dirs = [specs.join("default"), specs]; - let own = format!("{leaf}.gemspec"); - let own_absent = spec_dirs.iter().all(|dir| { - matches!(std::fs::metadata(dir.join(&own)), Err(e) if e.kind() == std::io::ErrorKind::NotFound) - }); - if !own_absent { - return false; - } - let exact = format!("{name}-{version}"); - let another_build_listed = spec_dirs.iter().any(|dir| { - super::listing::list_dir_sync(dir).iter().any(|entry| { - entry - .name - .to_str() - .and_then(|file| file.strip_suffix(".gemspec")) - .is_some_and(|build| { - build != leaf && (build == exact || is_platform_dir_of(build, name, version)) - }) - && dir.join(&entry.name).is_file() + 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)) }) - }); - if !another_build_listed { - return false; - } - // `//` is the home; the standalone setup file - // is `/bundler/setup.rb`. - let Some(setup) = home - .parent() - .and_then(Path::parent) - .map(|bundle| bundle.join("bundler").join("setup.rb")) - else { - return true; }; - match crate::utils::fs::read_regular_to_string_sync(&setup) { - Ok(text) => !text.contains(&format!("/gems/{leaf}/")), - Err(e) => e.kind() == std::io::ErrorKind::NotFound, - } + 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`]. @@ -6038,150 +6064,202 @@ mod tests { assert_eq!(one[&purl].path, exact); } - /// #2087: in a gem home that lists one build of a gem version, the - /// dir of another build with no `specifications` entry of its own is a - /// leftover nothing loads. A default gem's entry is under - /// `specifications/default/`. A version the home lists no build of is - /// not judged, nor is a dir outside a gem home. - #[test] - fn is_leftover_gem_build_needs_another_build_listed_and_none_of_its_own() { + /// 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 = tmp.path().join("vendor/bundle/ruby/3.3.0"); - let gems = home.join("gems"); - let specs = home.join("specifications"); - std::fs::create_dir_all(specs.join("default")).unwrap(); - let dir = |leaf: &str| { - std::fs::create_dir_all(gems.join(leaf).join("lib")).unwrap(); - gems.join(leaf) - }; - let spec = |leaf: &str| std::fs::write(specs.join(format!("{leaf}.gemspec")), "").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. - spec("nokogiri-1.16.0"); - assert!(is_leftover_gem_build( - &dir("nokogiri-1.16.0-x86_64-linux"), - "pkg:gem/nokogiri@1.16.0" - )); - assert!(!is_leftover_gem_build( - &dir("nokogiri-1.16.0"), - "pkg:gem/nokogiri@1.16.0" - )); - // A purl carrying a `?platform=` qualifier names the same gem. - assert!(is_leftover_gem_build( - &dir("nokogiri-1.16.0-x86_64-linux"), - "pkg:gem/nokogiri@1.16.0?platform=x86_64-linux" - )); - assert!(!is_leftover_gem_build( - &dir("nokogiri-1.16.0-x86_64-linux"), - "pkg:npm/nokogiri@1.16.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"); + 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. - spec("ffi-1.17.2-x86_64-linux-gnu"); - assert!(is_leftover_gem_build( - &dir("ffi-1.17.2"), - "pkg:gem/ffi@1.17.2" - )); - assert!(!is_leftover_gem_build( - &dir("ffi-1.17.2-x86_64-linux-gnu"), - "pkg:gem/ffi@1.17.2" - )); - // A default gem is listed under `default/`, and vouches for - // itself only. - std::fs::write(specs.join("default").join("json-2.7.2.gemspec"), "").unwrap(); - assert!(!is_leftover_gem_build( - &dir("json-2.7.2"), - "pkg:gem/json@2.7.2" - )); - assert!(is_leftover_gem_build( - &dir("json-2.7.2-java"), - "pkg:gem/json@2.7.2" - )); - // Both builds installed (#1092): neither is a leftover. - spec("rack-3.1.0"); - spec("rack-3.1.0-x86_64-linux"); - assert!(!is_leftover_gem_build( - &dir("rack-3.1.0"), - "pkg:gem/rack@3.1.0" - )); - assert!(!is_leftover_gem_build( - &dir("rack-3.1.0-x86_64-linux"), - "pkg:gem/rack@3.1.0" - )); - // The home lists no build of this version: another version's - // gemspec, another gem sharing the prefix and a directory named - // like a gemspec say nothing about it. - spec("puma-6.4.20"); - spec("puma-6.4.2.1"); - spec("puma-6.4.2-1.0"); - spec("puma-plugin-6.4.2"); - std::fs::create_dir_all(specs.join("puma-6.4.2-java.gemspec")).unwrap(); - assert!(!is_leftover_gem_build( - &dir("puma-6.4.2"), - "pkg:gem/puma@6.4.2" - )); - assert!(!is_leftover_gem_build( - &dir("puma-6.4.2-java"), - "pkg:gem/puma@6.4.2" - )); - // Not a gem home, and a path with no home at all. - let bare = tmp.path().join("bare/gems/nokogiri-1.16.0-x86_64-linux"); - std::fs::create_dir_all(bare.join("lib")).unwrap(); - assert!(!is_leftover_gem_build(&bare, "pkg:gem/nokogiri@1.16.0")); - assert!(!is_leftover_gem_build( - Path::new("nokogiri-1.16.0-x86_64-linux"), - "pkg:gem/nokogiri@1.16.0" - )); + 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)] - #[test] - fn is_leftover_gem_build_keeps_a_dir_whose_gemspec_cannot_be_probed() { + #[tokio::test] + async fn retain_loaded_gem_builds_keeps_a_dir_whose_gemspec_cannot_be_probed() { let tmp = tempfile::tempdir().unwrap(); - let home = tmp.path().join("ruby/3.3.0"); - let copy = home.join("gems/nokogiri-1.16.0-x86_64-linux"); - std::fs::create_dir_all(copy.join("lib")).unwrap(); - let specs = home.join("specifications"); - std::fs::create_dir_all(&specs).unwrap(); - std::fs::write(specs.join("nokogiri-1.16.0.gemspec"), "").unwrap(); - assert!(is_leftover_gem_build(©, "pkg:gem/nokogiri@1.16.0")); - std::fs::write(specs.join("default"), "").unwrap(); - assert!(!is_leftover_gem_build(©, "pkg:gem/nokogiri@1.16.0")); + 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. - #[test] - fn is_leftover_gem_build_keeps_a_dir_a_standalone_setup_loads() { - let tmp = tempfile::tempdir().unwrap(); - let bundle = tmp.path().join("bundle"); - let home = bundle.join("ruby/3.3.0"); - let copy = home.join("gems/nokogiri-1.16.0-x86_64-linux"); - std::fs::create_dir_all(copy.join("lib")).unwrap(); - std::fs::create_dir_all(home.join("specifications")).unwrap(); - std::fs::write(home.join("specifications/nokogiri-1.16.0.gemspec"), "").unwrap(); - std::fs::create_dir_all(bundle.join("bundler")).unwrap(); - let setup = bundle.join("bundler/setup.rb"); - - // A setup file that loads the ruby build only. - std::fs::write( - &setup, - "$:.unshift File.expand_path(\"#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/nokogiri-1.16.0/lib\")\n", - ) - .unwrap(); - assert!(is_leftover_gem_build(©, "pkg:gem/nokogiri@1.16.0")); - // One that still loads the platform build. - std::fs::write( - &setup, - "$:.unshift File.expand_path(\"#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/nokogiri-1.16.0-x86_64-linux/lib\")\n", - ) - .unwrap(); - assert!(!is_leftover_gem_build(©, "pkg:gem/nokogiri@1.16.0")); - // One that cannot be read (here: not UTF-8) might. - std::fs::write(&setup, [0xff, 0xfe]).unwrap(); - assert!(!is_leftover_gem_build(©, "pkg:gem/nokogiri@1.16.0")); + /// `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