From e3202918b4dfb6fa7d5deef0f8492b7b5b1a76d2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 09:23:26 +0000 Subject: [PATCH 01/20] Start fix for gem apply in unused gem homes Agent apply writes gem copies in gem env homes that Bundler never loads for a project with an explicit install path. Work in progress for #2313. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aePyMvbD6rKimV9v2pL From d621826684dc2a2640d5cb02f21dea8a680a04d2 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 15:23:03 -0500 Subject: [PATCH 02/20] Lift the gem home rule of vex and apply --check into one helper `find_manifest_package_copies_reusing` dropped the gem copies Bundler never loads for the project inline: a copy in a `gem env` home under an explicit or deployment `path`, unless it is a default gem. Move that into `retain_bundler_loaded_gem_copies`, beside the Cargo twin, so the forward writer can use the same rule (#2313). The helper returns before the `gem env` probe when every copy sits in one of the project's own Bundler stores. No behaviour change. Co-Authored-By: Claude Fable 5.2 --- .../src/ecosystem_dispatch.rs | 66 +++++++++++++------ 1 file changed, 46 insertions(+), 20 deletions(-) diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index e5c28f452e..cf8c8bceda 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -896,6 +896,50 @@ async fn retain_locked_cargo_copies( copies.retain(|purl, _| !is_cargo(purl) || locked.contains_purl(purl)); } +/// Drop the gem copies Bundler never loads for a local project: a copy in +/// a `gem env` home (the system gems, an rbenv or asdf home, `~/.gem`) +/// while the project installs into an explicit or deployment `path` +/// (`RubyCrawler::bundler_unused_system_gem_homes`). Bundler fetches every +/// non-default gem into that path, so such a copy is not one the project +/// runs, and an unpatched one must not block an attestation (#1098). +/// Default gems stay: Bundler loads those from the system home under any +/// path. A purl left with no copy is dropped. Only the read-only +/// verifiers (`vex`, `apply --check`) call this. +async fn retain_bundler_loaded_gem_copies( + copies: &mut HashMap>, + options: &CrawlerOptions, +) { + let is_gem = |purl: &str| Ecosystem::from_purl(purl) == Some(Ecosystem::Gem); + if options.global || options.global_prefix.is_some() || !copies.keys().any(|p| is_gem(p)) { + return; + } + // A copy in one of the project's own Bundler stores is always loaded. + // With every copy there (a populated `vendor/bundle`, where the crawler + // never asked `gem env` either) there is no home to ask it for. + let stores = RubyCrawler::discover_bundle_stores(&options.cwd) + .await + .stores; + let in_store = |path: &PathBuf| stores.iter().any(|store| path.starts_with(store)); + if copies + .iter() + .filter(|(purl, _)| is_gem(purl)) + .all(|(_, paths)| paths.iter().all(in_store)) + { + return; + } + let unused = RubyCrawler.bundler_unused_system_gem_homes(options).await; + if unused.is_empty() { + return; + } + for (_, paths) in copies.iter_mut().filter(|(purl, _)| is_gem(purl)) { + paths.retain(|path| { + !unused.iter().any(|home| path.starts_with(home)) + || socket_patch_core::crawlers::ruby_crawler::is_default_gem_copy(path) + }); + } + copies.retain(|_, paths| !paths.is_empty()); +} + /// Multi-copy variant of `find_packages_for_rollback` (qualified-aware /// merge). Used by `rollback`, which restores every physical copy. pub async fn find_all_packages_for_rollback( @@ -1371,26 +1415,8 @@ pub async fn find_manifest_package_copies_reusing( .map(|(_, paths)| paths), ) .await; - // A `gem env` home Bundler never loads this project's gems from (an - // explicit or deployment `path`) holds no copy the project runs, so an - // unpatched one there must not block the attestation (#1098). Default - // gems stay: Bundler loads those from the system home under any path. - if partitioned.contains_key(&Ecosystem::Gem) { - let unused = RubyCrawler - .bundler_unused_system_gem_homes(&crawler_options) - .await; - if !unused.is_empty() { - for (_, paths) in copies - .iter_mut() - .filter(|(purl, _)| purl.starts_with("pkg:gem/")) - { - paths.retain(|path| { - !unused.iter().any(|home| path.starts_with(home)) - || socket_patch_core::crawlers::ruby_crawler::is_default_gem_copy(path) - }); - } - } - } + // Only the gem copies Bundler loads for the project. + retain_bundler_loaded_gem_copies(&mut copies, &crawler_options).await; copies.retain(|_, paths| !paths.is_empty()); // Verification also READS a `.bundle/config` bundle path the crawler // refused as a write root (it resolves outside the project): bundler From d8e11ced2e8684320e339deffd658b84ef8b9b00 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 15:23:15 -0500 Subject: [PATCH 03/20] Leave gem copies Bundler does not load unwritten in agent apply (#2313) Under an explicit Bundler `path` (app config, `BUNDLE_PATH`) or deployment mode, Bundler installs every non-default gem into that path and never loads one from a `gem env` home (the system gems, an rbenv or asdf home, `~/.gem`). Agent `apply`, and the apply that `get` and `scan --mode agent` run, still wrote every copy of the patched version it found in those homes: a gem that belongs to other projects on the machine. On a fresh clone, with nothing in the path yet, it printed "N of N targeted patches applied" while the project had no patched gem. `find_all_packages_for_purls` now drops those copies by the rule `vex` and `apply --check` already follow: a copy in a `gem env` home Bundler does not load from is a write target only when it is a default gem. A gem left with no copy is `package_not_installed`, as any package that is not installed: a calm skip when the lock resolves it, the all-miss error when nothing does. `vendor` asks the same resolver whether a gem already holds its patch in agent mode, so it keeps agreeing with what `apply` writes. `rollback` and `remove` resolve without the rule and still restore such a copy, which an earlier release may have patched. Unchanged: a populated `vendor/bundle`, Bundler using system gems, default gems, `--global` runs, and the agent scan's discovery crawl. The fallback-home tests pinned the old write scope. They now pin the new one, and keep the best-effort failure semantics on the copies that are still written (a default gem beside a store copy). Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/apply.rs | 27 +- .../src/ecosystem_dispatch.rs | 22 +- .../apply/in_process_gem_fallback_home.rs | 584 ++++++++++++++---- .../src/crawlers/ruby_crawler.rs | 26 +- 4 files changed, 518 insertions(+), 141 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 91bc47e414..feb156324f 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -3657,18 +3657,21 @@ async fn apply_patches_inner( _ => std::slice::from_ref(pkg_path), }; - // Copy CLASS decides FAILURE semantics (never write scope — - // patching a shared home's vulnerable copy is fine when it - // works): bundle-path store copies are PRIMARY and loud-fail; - // `gem env` fallback-home copies (rvm `@global`, system gem - // dirs — often root-owned, shared machine-wide) are - // BEST-EFFORT once a store copy applied — a mismatch or write - // failure there becomes a non-fatal per-copy Skipped warning, - // because the copy bundler actually loads is already patched. - // With NO store copy the fallback home IS the primary install - // (the historic pre-bundle-path layout, and every --global - // run) and keeps loud-fail parity. Store copies run first so - // best-effort is decidable when the fallback copies come up. + // Write scope is the resolver's: a `gem env` home copy that + // Bundler does not load for the project (a non-default gem + // under an explicit or deployment `path`) belongs to other + // projects and is not in `copy_paths` (#2313). Copy CLASS + // decides the FAILURE semantics of the copies that are: + // bundle-path store copies are PRIMARY and loud-fail; + // `gem env` home copies (rvm `@global`, system gem dirs — + // often root-owned, shared machine-wide) are BEST-EFFORT once + // a store copy applied — a mismatch or write failure there + // becomes a non-fatal per-copy Skipped warning, because the + // copy bundler actually loads is already patched. With NO store + // copy the home copy IS the primary install (Bundler using + // system gems, a default gem, and every --global run) and + // keeps loud-fail parity. Store copies run first so + // best-effort is decidable when the home copies come up. let (store_copies, home_copies): (Vec<&PathBuf>, Vec<&PathBuf>) = copy_paths .iter() .partition(|p| gem_store_dirs.iter().any(|s| p.starts_with(s))); diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index cf8c8bceda..b839197917 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -845,8 +845,10 @@ pub(crate) fn collapse_to_first(multi: HashMap>) -> HashMap /// For each ecosystem in the partitioned map, create the crawler, discover /// source paths, and look up the given PURLs. Returns a unified `purl -> -/// [paths]` map carrying EVERY physical copy (npm nests duplicates). Used -/// by `apply`, which patches all copies. +/// [paths]` map carrying EVERY physical copy (npm nests duplicates) the +/// project consumes: a Cargo or gem copy it never builds or loads is left +/// out (see the two `retain_*` calls). Used by `apply`, which patches all +/// of them, and by `vendor` to ask whether they all hold a patch. pub async fn find_all_packages_for_purls( partitioned: &HashMap>, options: &CrawlerOptions, @@ -871,6 +873,7 @@ pub async fn find_all_packages_for_purls( ) .await; retain_locked_cargo_copies(&mut found, options).await; + retain_bundler_loaded_gem_copies(&mut found, options).await; found } @@ -900,11 +903,14 @@ async fn retain_locked_cargo_copies( /// a `gem env` home (the system gems, an rbenv or asdf home, `~/.gem`) /// while the project installs into an explicit or deployment `path` /// (`RubyCrawler::bundler_unused_system_gem_homes`). Bundler fetches every -/// non-default gem into that path, so such a copy is not one the project -/// runs, and an unpatched one must not block an attestation (#1098). -/// Default gems stay: Bundler loads those from the system home under any -/// path. A purl left with no copy is dropped. Only the read-only -/// verifiers (`vex`, `apply --check`) call this. +/// non-default gem into that path, so such a copy belongs to other +/// projects on the machine: patching it would change their code and +/// nothing this project runs (#2313), and an unpatched one must not block +/// an attestation (#1098). Default gems stay: Bundler loads those from the +/// system home under any path. A purl left with no copy is dropped, so it +/// reads as not installed. Only the commands that patch or attest call +/// this: rollback and remove still find the copy, since an earlier release +/// may have patched it. async fn retain_bundler_loaded_gem_copies( copies: &mut HashMap>, options: &CrawlerOptions, @@ -1415,7 +1421,7 @@ pub async fn find_manifest_package_copies_reusing( .map(|(_, paths)| paths), ) .await; - // Only the gem copies Bundler loads for the project. + // Only the gem copies Bundler loads for the project, as for `apply`. retain_bundler_loaded_gem_copies(&mut copies, &crawler_options).await; copies.retain(|_, paths| !paths.is_empty()); // Verification also READS a `.bundle/config` bundle path the crawler diff --git a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs index 851ef7fb99..da2a97c14e 100644 --- a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs +++ b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs @@ -1,22 +1,36 @@ -//! Store-class semantics for the gem multi-copy fan-out. +//! Which gem copies agent `apply` writes in the `gem env` homes (the +//! system gems, rvm `@global`, `--user-install`), and how a failure on +//! one of them is reported. //! -//! `get_gem_paths` appends the `gem env` fallback homes (rvm `@global`, -//! `--user-install`, system gem dirs) after the project's bundle-path -//! stores, and the multi-copy fan-out patches EVERY copy. Patching a -//! shared home's copy is fine (vulnerable bytes are vulnerable bytes) — -//! but its FAILURE semantics must not cross store classes: +//! `get_gem_paths` appends the `gem env` homes after the project's +//! bundle-path stores, because default gems (rexml, json, …) only live +//! there. Whether a copy found in such a home is written follows what +//! Bundler loads for the project (#2313): //! -//! * copies in bundle-path stores are PRIMARY — loud-fail (unchanged); -//! * copies in gem-env fallback homes are BEST-EFFORT once at least one -//! bundle-store copy applied: a variant mismatch or write failure -//! there becomes a per-copy non-fatal `Skipped` event -//! (`gem_fallback_home_skipped`, with the path and reason), never a -//! run failure — the copy bundler actually loads was patched; -//! * with NO bundle-store copy (the historic fallback-only layout) the -//! home copy IS primary: loud-fail exactly as plain apply always -//! behaved. +//! * under an explicit Bundler `path` (app config, `BUNDLE_PATH`) or +//! deployment mode, Bundler installs every non-default gem into that +//! path and never loads one from a `gem env` home. A non-default copy +//! there belongs to other projects on the machine, so `apply` leaves +//! it alone. With no other copy the gem is not installed; +//! * a default gem (its spec under `specifications/default/`) is loaded +//! from the system home under any path, so it is still written; +//! * with no explicit path Bundler installs into and loads from the +//! `gem env` homes, so every copy there is written; +//! * `rollback` and `remove` find every copy either way: an earlier +//! release may have patched one, and it must stay restorable. //! -//! Unix-only: the fallback homes come from a fake `gem` binary on PATH. +//! FAILURE semantics of the copies that are written: +//! +//! * copies in bundle-path stores are PRIMARY — loud-fail; +//! * a `gem env` home copy is BEST-EFFORT once at least one bundle-store +//! copy applied: a variant mismatch or write failure there becomes a +//! per-copy non-fatal `Skipped` event (`gem_fallback_home_skipped`, +//! with the path and reason), never a run failure — the copy bundler +//! actually loads was patched; +//! * with NO bundle-store copy the home copy IS primary: loud-fail +//! exactly as plain apply always behaved. +//! +//! Unix-only: the `gem env` home comes from a fake `gem` binary on PATH. #![cfg(unix)] @@ -31,6 +45,7 @@ use super::apply_fixture::{ use crate::common::git_sha256; const SKIP_CODE: &str = "gem_fallback_home_skipped"; +const NOT_INSTALLED: &str = "package_not_installed"; const ORIGINAL: &[u8] = b"module Rack\n VERSION = 'VULNERABLE'\nend\n"; const MARKER: &[u8] = b"# SOCKET-PATCHED-FALLBACK\n"; @@ -42,7 +57,7 @@ fn patched_bytes() -> Vec { } /// Fake `gem` answering `env gemdir` with `home` (and an empty `gempath` -/// failure), so the crawler's fallback resolves to exactly one home. +/// failure), so the crawler's `gem env` homes resolve to exactly one. fn install_fake_gem(bin_dir: &Path, home: &Path) { use std::os::unix::fs::PermissionsExt; let script = format!( @@ -68,31 +83,71 @@ fn stage_copy(root: &Path, bytes: &[u8]) -> PathBuf { file } +/// Where Bundler installs the project's gems. +#[derive(Clone, Copy, PartialEq)] +enum Store { + /// No `path` setting: Bundler installs into, and loads from, the + /// `gem env` homes. + SystemGems, + /// `BUNDLE_PATH` names a store with nothing installed in it yet (a + /// fresh clone before `bundle install`). + ExplicitEmpty, + /// `BUNDLE_PATH` names a store holding a pristine copy. + Explicit, + /// No `path` setting, and the default `vendor/bundle` holds a + /// pristine copy (a deployment-style install). + VendorBundle, +} + +/// The home copy is an ordinary installed gem, or one of Ruby's default +/// gems (spec under `specifications/default/`). +#[derive(Clone, Copy, PartialEq)] +enum Home { + Installed, + DefaultGem, +} + struct Fixture { project: tempfile::TempDir, store_file: Option, home_file: PathBuf, bin_dir: PathBuf, - store_root: Option, + /// The `BUNDLE_PATH` the runs export, when the store is explicit. + bundle_path: Option, } -/// Project with a Gemfile; optionally an env-`BUNDLE_PATH` store copy -/// (pristine); a gem-env fallback home copy with `home_bytes`; manifest -/// keyed by `purl`. -fn build_fixture(with_store: bool, home_bytes: &[u8], purl: &str) -> Fixture { +/// Project with a Gemfile; a bundle store per `store`; a `gem env` home +/// copy with `home_bytes`; manifest keyed by `purl`, with the patched and +/// the original blob staged (apply reads the first, rollback the second). +fn build_fixture(store: Store, home: Home, home_bytes: &[u8], purl: &str) -> Fixture { let project = tempfile::tempdir().unwrap(); let root = project.path(); std::fs::write(root.join("Gemfile"), b"source 'https://rubygems.org'\n").unwrap(); - let store_root = with_store.then(|| root.join("bundle-store")); - let store_file = store_root.as_ref().map(|s| stage_copy(s, ORIGINAL)); - - let home = root.join("gem-home"); - let home_file = stage_copy(&home, home_bytes); + let store_root = match store { + Store::SystemGems => None, + Store::ExplicitEmpty | Store::Explicit => Some(root.join("bundle-store")), + Store::VendorBundle => Some(root.join("vendor").join("bundle")), + }; + let store_file = match store { + Store::Explicit | Store::VendorBundle => { + Some(stage_copy(store_root.as_ref().unwrap(), ORIGINAL)) + } + Store::SystemGems | Store::ExplicitEmpty => None, + }; + let bundle_path = store_root.filter(|_| store != Store::VendorBundle); + + let home_root = root.join("gem-home"); + let home_file = stage_copy(&home_root, home_bytes); + if home == Home::DefaultGem { + let default_specs = home_root.join("specifications").join("default"); + std::fs::create_dir_all(&default_specs).unwrap(); + std::fs::write(default_specs.join("rack-3.1.0.gemspec"), b"").unwrap(); + } let bin_dir = root.join("fake-bin"); std::fs::create_dir_all(&bin_dir).unwrap(); - install_fake_gem(&bin_dir, &home); + install_fake_gem(&bin_dir, &home_root); let patched = patched_bytes(); write_manifest( @@ -103,60 +158,396 @@ fn build_fixture(with_store: bool, home_bytes: &[u8], purl: &str) -> Fixture { )}), ); stage_blob(root, &git_sha256(&patched), &patched); + stage_blob(root, &git_sha256(ORIGINAL), ORIGINAL); Fixture { project, store_file, home_file, bin_dir, - store_root, + bundle_path, } } -/// Run apply with the hermetic SOCKET_* env and BUNDLE_* scrubbed, PATH = -/// the fake-gem bin dir only, and BUNDLE_PATH set to the store root when -/// present. -fn run_apply(fx: &Fixture, extra: &[&str]) -> (i32, String, String) { +/// A `Gemfile.lock` that resolves the fixture's gem. +fn write_lock(fx: &Fixture) { + std::fs::write( + fx.project.path().join("Gemfile.lock"), + "GEM\n remote: https://rubygems.org/\n specs:\n rack (3.1.0)\n\n\ + PLATFORMS\n ruby\n\nDEPENDENCIES\n rack\n\nBUNDLED WITH\n 2.5.22\n", + ) + .unwrap(); +} + +/// Run ` --offline --ecosystems gem --cwd ` with +/// the hermetic SOCKET_* env and BUNDLE_* scrubbed, PATH = the fake-gem +/// bin dir only, and BUNDLE_PATH set when the fixture's store is explicit. +fn run_command(fx: &Fixture, command: &[&str], extra: &[&str]) -> (i32, String, String) { let cwd = fx.project.path().to_str().unwrap(); - let mut argv = vec!["apply", "--offline", "--ecosystems", "gem", "--cwd", cwd]; + let mut argv = command.to_vec(); + argv.extend_from_slice(&["--offline", "--ecosystems", "gem", "--cwd", cwd]); argv.extend_from_slice(extra); let bin_dir = fx.bin_dir.to_str().unwrap(); let mut env = vec![("PATH", bin_dir)]; - if let Some(store_root) = &fx.store_root { - env.push(("BUNDLE_PATH", store_root.to_str().unwrap())); + if let Some(bundle_path) = &fx.bundle_path { + env.push(("BUNDLE_PATH", bundle_path.to_str().unwrap())); } run_gem(Path::new("."), &argv, &env) } +fn run_apply(fx: &Fixture, extra: &[&str]) -> (i32, String, String) { + run_command(fx, &["apply"], extra) +} + fn parse_env(stdout: &str) -> serde_json::Value { serde_json::from_str(stdout.trim()) - .unwrap_or_else(|e| panic!("apply must emit JSON: {e}; stdout={stdout}")) + .unwrap_or_else(|e| panic!("the run must emit JSON: {e}; stdout={stdout}")) } -fn find_skip_event(env: &serde_json::Value) -> Option<&serde_json::Value> { +/// The first event with `action` and `errorCode` = `code` (`with_reason` +/// serializes its stable tag as `errorCode`). +fn find_event<'a>( + env: &'a serde_json::Value, + action: &str, + code: &str, +) -> Option<&'a serde_json::Value> { env["events"].as_array().and_then(|events| { events.iter().find(|e| { - e["action"] == "skipped" - // `with_reason` serializes its stable tag as `errorCode`. - && e.get("errorCode").and_then(|c| c.as_str()) == Some(SKIP_CODE) + e["action"] == action && e.get("errorCode").and_then(|c| c.as_str()) == Some(code) }) }) } -/// (a) Store copy patched + home copy that matches NO variant (foreign -/// bytes, qualified record): the home copy becomes a per-copy non-fatal -/// `Skipped` event naming its path — exit 0, `applied` counts the store -/// copy. Before the fix this failed the WHOLE run ("no matching variant -/// found", exit 1) even though the copy bundler loads patched fine. +fn find_skip_event(env: &serde_json::Value) -> Option<&serde_json::Value> { + find_event(env, "skipped", SKIP_CODE) +} + +fn home_dir(fx: &Fixture) -> PathBuf { + fx.project.path().join("gem-home") +} + +// ── Write scope ───────────────────────────────────────────────────────── + +/// Explicit path with the gem installed in it, and a same-version copy in +/// the `gem env` home: only the project's copy is written. Bundler never +/// loads the home copy for this project, and other projects may (#2313). +#[test] +fn explicit_path_leaves_the_gem_env_home_copy_alone() { + let fx = build_fixture(Store::Explicit, Home::Installed, ORIGINAL, QUALIFIED_PURL); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!( + env["summary"]["applied"], 1, + "only the project's copy counts.\nenvelope: {env}" + ); + assert_eq!( + std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), + patched_bytes(), + "the project's copy must be patched" + ); + assert_eq!( + std::fs::read(&fx.home_file).unwrap(), + ORIGINAL, + "the gem env home copy must be left untouched" + ); + assert!( + !stdout.contains(&home_dir(&fx).display().to_string()), + "no event names the home copy: it is not a copy of this project.\nenvelope: {env}" + ); + assert!(find_skip_event(&env).is_none(), "envelope: {env}"); + + // `apply --check` agrees: the tree is in sync. + let (code, stdout, stderr) = run_apply(&fx, &["--check"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); +} + +/// The human render of the same run: one patched package, one summary +/// line, and no line about the home copy. +#[test] +fn explicit_path_human_run_lists_only_the_project_copy() { + let fx = build_fixture(Store::Explicit, Home::Installed, ORIGINAL, QUALIFIED_PURL); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + stdout.contains( + "Summary: 1 of 1 targeted patch applied, 0 already patched, 0 not found on disk" + ), + "stdout={stdout}" + ); + let out = format!("{stdout}{stderr}"); + assert!( + !out.contains(&home_dir(&fx).display().to_string()), + "the home copy is not mentioned; output={out}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// Explicit path with nothing installed in it yet (a fresh clone before +/// `bundle install`) and no lock: the home copy is not this project's, so +/// nothing is written and the gem is not installed. As for any all-miss +/// run with no lock evidence, that fails. +#[test] +fn explicit_path_with_nothing_installed_reports_not_installed() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!( + std::fs::read(&fx.home_file).unwrap(), + ORIGINAL, + "the gem env home copy must be left untouched" + ); + assert_eq!( + env["summary"]["applied"], 0, + "nothing was applied.\nenvelope: {env}" + ); + let skip = find_event(&env, "skipped", NOT_INSTALLED) + .unwrap_or_else(|| panic!("the gem must be reported as {NOT_INSTALLED}.\nenvelope: {env}")); + assert_eq!(skip["purl"], QUALIFIED_PURL, "envelope: {env}"); + assert_eq!( + code, 1, + "an all-miss run with no lock evidence fails.\nenvelope: {env}\nstderr:\n{stderr}" + ); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 1, "stdout={stdout}\nstderr={stderr}"); + assert!( + stderr.contains("Error: The targeted manifest patch matched no installed package:"), + "stderr={stderr}" + ); + assert!( + stdout.contains( + "Summary: 0 of 1 targeted patch applied, 0 already patched, 1 not found on disk" + ), + "stdout={stdout}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// The same fresh clone with a `Gemfile.lock` that resolves the gem: a +/// calm lockfile-only skip, exit 0. The `bundle install` that follows puts +/// the gem in the project's path, and the next `apply` patches it there. +#[test] +fn explicit_path_with_nothing_installed_is_a_calm_skip_under_a_lock() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + write_lock(&fx); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!(env["summary"]["applied"], 0, "envelope: {env}"); + let skip = find_event(&env, "skipped", NOT_INSTALLED) + .unwrap_or_else(|| panic!("the gem must be reported as {NOT_INSTALLED}.\nenvelope: {env}")); + assert_eq!(skip["purl"], QUALIFIED_PURL, "envelope: {env}"); + assert!( + skip["reason"] + .as_str() + .unwrap_or_default() + .contains("lockfile-only"), + "envelope: {env}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + stderr.contains( + "Note: 1 manifest patch targets a package not installed on this host \ + (resolved by the project lockfile; skipped):" + ), + "stderr={stderr}" + ); + assert!( + stdout.contains( + "Summary: 0 of 1 targeted patch applied, 0 already patched, 1 not found on disk" + ), + "stdout={stdout}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// A default gem only ever lives in the system home, and Bundler loads it +/// from there under any path: it is still patched. +#[test] +fn default_gem_in_the_gem_env_home_is_still_patched() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::DefaultGem, + ORIGINAL, + QUALIFIED_PURL, + ); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!(env["summary"]["applied"], 1, "envelope: {env}"); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched_bytes()); + + let (code, stdout, stderr) = run_apply(&fx, &["--check"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); +} + +/// A default gem beside the same version in the project's path: both +/// copies are patched (the multi-copy guarantee), exit 0, applied counts +/// both. +#[test] +fn default_gem_home_copy_is_patched_beside_the_store_copy() { + let fx = build_fixture(Store::Explicit, Home::DefaultGem, ORIGINAL, QUALIFIED_PURL); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + env["summary"]["applied"], 2, + "both copies count.\nenvelope: {env}" + ); + assert_eq!( + std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), + patched_bytes() + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched_bytes()); + assert!( + find_skip_event(&env).is_none(), + "healthy home copies are patched, never best-effort-skipped.\nenvelope: {env}" + ); +} + +/// With no explicit path Bundler installs into and loads from the +/// `gem env` homes: the copy there is the project's, and is patched. +#[test] +fn system_gems_home_copy_is_patched() { + let fx = build_fixture(Store::SystemGems, Home::Installed, ORIGINAL, QUALIFIED_PURL); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!(env["summary"]["applied"], 1, "envelope: {env}"); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched_bytes()); + + // The human render, on a fresh tree. + let fx = build_fixture(Store::SystemGems, Home::Installed, ORIGINAL, QUALIFIED_PURL); + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + stdout.contains( + "Summary: 1 of 1 targeted patch applied, 0 already patched, 0 not found on disk" + ), + "stdout={stdout}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched_bytes()); +} + +/// A deployment-style install under the default `vendor/bundle`: that +/// store is the project's one gem source, so the `gem env` home is not +/// searched and its copy is left alone. +#[test] +fn vendor_bundle_store_leaves_the_gem_env_home_copy_alone() { + let fx = build_fixture( + Store::VendorBundle, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "envelope: {env}"); + assert_eq!( + std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), + patched_bytes() + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// A copy in the `gem env` home that an earlier release patched under an +/// explicit path stays restorable: `rollback` finds and restores it, with +/// the project's copy. +#[test] +fn rollback_restores_a_home_copy_an_earlier_run_patched() { + let patched = patched_bytes(); + let fx = build_fixture(Store::Explicit, Home::Installed, &patched, QUALIFIED_PURL); + std::fs::write(fx.store_file.as_ref().unwrap(), &patched).unwrap(); + + let (code, stdout, stderr) = run_command(&fx, &["rollback"], &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + std::fs::read(&fx.home_file).unwrap(), + ORIGINAL, + "the home copy must be restored.\nenvelope: {env}" + ); + assert_eq!( + std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), + ORIGINAL, + "the project's copy must be restored.\nenvelope: {env}" + ); +} + +/// `remove` restores such a copy too, and drops the record. #[test] -fn mismatched_fallback_home_copy_is_nonfatal_when_store_patched() { +fn remove_restores_a_home_copy_an_earlier_run_patched() { + let patched = patched_bytes(); + let fx = build_fixture(Store::Explicit, Home::Installed, &patched, QUALIFIED_PURL); + std::fs::write(fx.store_file.as_ref().unwrap(), &patched).unwrap(); + + let (code, stdout, stderr) = run_command(&fx, &["remove", BASE_PURL], &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + std::fs::read(&fx.home_file).unwrap(), + ORIGINAL, + "the home copy must be restored.\nenvelope: {env}" + ); + assert_eq!( + std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), + ORIGINAL, + "the project's copy must be restored.\nenvelope: {env}" + ); + let manifest: serde_json::Value = serde_json::from_slice( + &std::fs::read(fx.project.path().join(".socket").join("manifest.json")).unwrap(), + ) + .unwrap(); + assert!( + manifest["patches"] + .as_object() + .is_some_and(|patches| patches.is_empty()), + "the record must be dropped; manifest: {manifest}" + ); +} + +// ── Failure semantics of a home copy that is written ──────────────────── + +/// Store copy patched + a default gem's home copy that matches NO variant +/// (foreign bytes, qualified record): the home copy becomes a per-copy +/// non-fatal `Skipped` event naming its path — exit 0, `applied` counts +/// the store copy. +#[test] +fn mismatched_home_copy_is_nonfatal_when_store_patched() { let foreign = b"totally different bytes\n"; - let fx = build_fixture(true, foreign, QUALIFIED_PURL); + let fx = build_fixture(Store::Explicit, Home::DefaultGem, foreign, QUALIFIED_PURL); let (code, stdout, stderr) = run_apply(&fx, &["--json"]); let env = parse_env(&stdout); assert_eq!( code, 0, - "a mismatched fallback-home copy must not fail the run.\nenvelope: {env}\nstderr:\n{stderr}" + "a mismatched home copy must not fail the run.\nenvelope: {env}\nstderr:\n{stderr}" ); assert_eq!(env["status"], "success", "envelope: {env}"); assert_eq!( @@ -180,26 +571,23 @@ fn mismatched_fallback_home_copy_is_nonfatal_when_store_patched() { assert_eq!(skip["purl"], BASE_PURL, "envelope: {env}"); let reason = skip["reason"].as_str().unwrap_or_default(); assert!( - reason.contains( - &fx.home_file - .parent() - .unwrap() - .parent() - .unwrap() - .display() - .to_string() - ) || reason.contains(&fx.home_file.display().to_string()), - "skip reason must name the fallback-home copy path; got: {reason}" + reason.contains(&home_dir(&fx).display().to_string()), + "skip reason must name the home copy path; got: {reason}" ); } /// `apply --check` uses the same copy classes: once the store copy is -/// patched, a fallback-home copy no variant matches is no drift — `apply` -/// left it alone and exited 0, so the check must not send CI back to an -/// `apply` that will never act on it. +/// patched, a home copy no variant matches is no drift — `apply` left it +/// alone and exited 0, so the check must not send CI back to an `apply` +/// that will never act on it. #[test] -fn check_ignores_a_mismatched_fallback_home_copy_when_store_patched() { - let fx = build_fixture(true, b"totally different bytes\n", QUALIFIED_PURL); +fn check_ignores_a_mismatched_home_copy_when_store_patched() { + let fx = build_fixture( + Store::Explicit, + Home::DefaultGem, + b"totally different bytes\n", + QUALIFIED_PURL, + ); let (code, _, stderr) = run_apply(&fx, &["--json"]); assert_eq!(code, 0, "stderr:\n{stderr}"); @@ -210,18 +598,23 @@ fn check_ignores_a_mismatched_fallback_home_copy_when_store_patched() { ); } -/// (b) Parity pin: with NO bundle-store copy, the fallback-home copy IS -/// the primary install — a mismatch there is a loud failure (exit 1), as -/// in plain apply. +/// Parity pin: with NO bundle-store copy (Bundler uses system gems), the +/// home copy IS the primary install — a mismatch there is a loud failure +/// (exit 1), as in plain apply. #[test] -fn fallback_only_mismatch_keeps_loud_failure_parity() { - let fx = build_fixture(false, b"totally different bytes\n", QUALIFIED_PURL); +fn home_only_mismatch_keeps_loud_failure_parity() { + let fx = build_fixture( + Store::SystemGems, + Home::Installed, + b"totally different bytes\n", + QUALIFIED_PURL, + ); let (code, stdout, _stderr) = run_apply(&fx, &["--json"]); let env = parse_env(&stdout); assert_ne!( code, 0, - "fallback-only mismatch must still fail the run (parity).\nenvelope: {env}" + "a home-only mismatch must still fail the run (parity).\nenvelope: {env}" ); assert!( find_skip_event(&env).is_none(), @@ -249,51 +642,25 @@ fn fallback_only_mismatch_keeps_loud_failure_parity() { ); } -/// (c) Both copies healthy: both patched (the multi-copy guarantee is -/// unchanged by the class split), exit 0, applied counts both. -#[test] -fn writable_fallback_home_copy_still_patched() { - let fx = build_fixture(true, ORIGINAL, QUALIFIED_PURL); - - let (code, stdout, stderr) = run_apply(&fx, &["--json"]); - let env = parse_env(&stdout); - assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); - assert_eq!( - env["summary"]["applied"], 2, - "both copies count.\nenvelope: {env}" - ); - assert_eq!( - std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), - patched_bytes() - ); - assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched_bytes()); - assert!( - find_skip_event(&env).is_none(), - "healthy home copies are patched, never best-effort-skipped.\nenvelope: {env}" - ); -} - -/// An ATTEMPTED apply that FAILS on the fallback-home copy converts to +/// An ATTEMPTED apply that FAILS on a default gem's home copy converts to /// the same non-fatal per-copy skip when the store copy applied. The /// deterministic non-root failure: an UNQUALIFIED record's home copy with /// locally-diverged bytes under `--strict` — the singleton exemption /// drives it past the variant gate into `apply_package_patch`, whose -/// strict mismatch policy then refuses the write. (A root-owned rvm -/// `@global` EACCES is the production shape; owner-run tests can't +/// strict mismatch policy then refuses the write. (A root-owned system +/// gem dir's EACCES is the production shape; owner-run tests can't /// produce it — `DirWriteGuard` defeats read-only-dir setups by design.) -/// Before the fix: a `Failed` event + exit 1 even though the copy bundler -/// loads patched fine. #[test] -fn failing_fallback_home_copy_write_is_nonfatal_when_store_patched() { +fn failing_home_copy_write_is_nonfatal_when_store_patched() { let mut diverged = ORIGINAL.to_vec(); diverged.extend_from_slice(b"# local tweak\n"); - let fx = build_fixture(true, &diverged, BASE_PURL); + let fx = build_fixture(Store::Explicit, Home::DefaultGem, &diverged, BASE_PURL); let (code, stdout, stderr) = run_apply(&fx, &["--json", "--strict"]); let env = parse_env(&stdout); assert_eq!( code, 0, - "a failing fallback-home write must not fail the run once the store copy applied.\nenvelope: {env}\nstderr:\n{stderr}" + "a failing home copy write must not fail the run once the store copy applied.\nenvelope: {env}\nstderr:\n{stderr}" ); assert_eq!(env["status"], "success", "envelope: {env}"); assert_eq!( @@ -330,12 +697,12 @@ fn failing_fallback_home_copy_write_is_nonfatal_when_store_patched() { ); } -/// The human render of (a): the per-copy warning names the skipped -/// copy's path and says why the skip is safe. +/// The human render of the mismatch skip: the per-copy warning names the +/// skipped copy's path and says why the skip is safe. #[test] -fn mismatched_fallback_home_copy_warns_on_human_stderr() { +fn mismatched_home_copy_warns_on_human_stderr() { let foreign = b"totally different bytes\n"; - let fx = build_fixture(true, foreign, QUALIFIED_PURL); + let fx = build_fixture(Store::Explicit, Home::DefaultGem, foreign, QUALIFIED_PURL); let (code, _stdout, stderr) = run_apply(&fx, &[]); assert_eq!(code, 0, "stderr={stderr}"); @@ -343,10 +710,9 @@ fn mismatched_fallback_home_copy_warns_on_human_stderr() { stderr.contains("Warning: ") && stderr.contains("was not patched"), "the best-effort skip must print its human warning; stderr={stderr}" ); - let home = fx.project.path().join("gem-home"); assert!( - stderr.contains(&format!("gem-env home copy at {}", home.display())), - "the warning must name the fallback-home copy; stderr={stderr}" + stderr.contains(&format!("gem-env home copy at {}", home_dir(&fx).display())), + "the warning must name the home copy; stderr={stderr}" ); assert!( stderr.contains("bundle-path copy — the one bundler loads — is patched"), diff --git a/crates/socket-patch-core/src/crawlers/ruby_crawler.rs b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs index c829bc7fd2..5c732878bb 100644 --- a/crates/socket-patch-core/src/crawlers/ruby_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs @@ -832,14 +832,15 @@ impl RubyCrawler { ) } - /// The `gem env` homes Bundler never loads this project's gems from, - /// for read-only verifiers (`vex`): [`Self::get_gem_paths`] keeps them - /// as apply write targets for default gems, but under an explicit or - /// deployment `path` Bundler fetches every other gem into that path, so - /// an unpatched copy there is not one the project runs (#1098). Empty - /// in global / `--global-prefix` mode and whenever Bundler uses system - /// gems. A home that is also one of the project's Bundler stores is - /// never listed. + /// The `gem env` homes Bundler never loads this project's gems from. + /// [`Self::get_gem_paths`] keeps them for default gems, but under an + /// explicit or deployment `path` Bundler fetches every other gem into + /// that path, so a non-default copy there is not one the project runs: + /// `apply` does not write it (#2313), and the read-only verifiers + /// (`vex`, `apply --check`) do not judge it (#1098). Empty in global / + /// `--global-prefix` mode and whenever Bundler uses system gems. A + /// home that is also one of the project's Bundler stores is never + /// listed. pub async fn bundler_unused_system_gem_homes(&self, options: &CrawlerOptions) -> Vec { if options.global || options.global_prefix.is_some() { return Vec::new(); @@ -859,8 +860,8 @@ impl RubyCrawler { /// gem homes for the project at `cwd`: a Ruby project with no /// deployment store under the default `vendor/bundle` and no explicit /// install `path` ([`bundler_sets_explicit_path`], which also counts - /// `deployment`). The one answer both the stale-install guard - /// ([`Self::bundler_install_homes`]) and `vex` + /// `deployment`). The one answer the stale-install guard + /// ([`Self::bundler_install_homes`]), `apply` and `vex` /// ([`Self::bundler_unused_system_gem_homes`]) use. async fn bundler_uses_system_gems(cwd: &Path, discovery: &BundleStoreDiscovery) -> bool { if discovery.default_root_has_stores || !Self::has_bundler_manifest(cwd).await { @@ -1506,8 +1507,9 @@ pub(crate) fn bundler_sets_explicit_path(tiers: BundlerPathTiers) -> bool { /// Whether the installed gem dir `copy` (`/gems/-`) /// is a default gem: its spec sits in `/specifications/default/`. /// Bundler loads a default gem from the system home even under an explicit -/// `path`, so a verifier that drops the unused `gem env` homes -/// ([`RubyCrawler::bundler_unused_system_gem_homes`]) still judges it. +/// `path`, so `apply` still patches it and a verifier still judges it +/// where they drop every other copy in the unused `gem env` homes +/// ([`RubyCrawler::bundler_unused_system_gem_homes`]). pub fn is_default_gem_copy(copy: &Path) -> bool { let (Some(dir_name), Some(home)) = (copy.file_name(), copy.parent().and_then(Path::parent)) else { From 1345567549c184c0357d9decd08ec5b1c7d71b4e Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 15:23:23 -0500 Subject: [PATCH 04/20] Document the gem write scope of agent apply CLI_CONTRACT.md's "Copy classes" paragraph said a copy in a `gem env` fallback home is patched whenever it matches and is writable. Say when it is a write target (Bundler using system gems, or a default gem), what a gem with no copy left reports, and that `rollback`, `remove` and `--global` runs are unchanged. The best-effort failure rule now reads on the copies that are still written. Both texts also say what was already true and unwritten: once the default `vendor/bundle` holds the project's gems, no local run searches the `gem env` homes, so a default gem there is not patched and `rollback` names `rollback -g` for a copy left patched there. Add the agent-mode rule to "Ruby gems: gems already installed" in docs/ecosystems.md, beside the hosted-mode rule for shared gem homes. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 44 ++++++++++++++++++++----- docs/ecosystems.md | 28 ++++++++++++++++ 2 files changed, 63 insertions(+), 9 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 4fb98ba4f3..dfb6d5b79c 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -498,7 +498,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm - When several confirmed variant purls resolve to one installed dir, ANY of them judging it patched keeps it quiet. - Staleness needs **positive evidence** — bytes actually read that are not the patched state — so missing or unreadable files never mark a copy stale. - A committed cache-dir archive whose sha256 is readable and differs from the patched artifact's is stale by itself, even with no installed dir at all (a fresh checkout with a committed stale cache). That covers the ruby gem's `-.gem` and each platform build's `--.gem`. -- Standalone `vex` and `apply --check` judge gem copies by the same rule (#1098): when Bundler doesn't use system gems, a copy in a `gem env` home is not one the project loads and is not verified, unless it is a default gem (its spec under `specifications/default/`), which Bundler loads from the system home under any path. +- Standalone `vex` and `apply --check` judge gem copies by the same rule (#1098): when Bundler doesn't use system gems, a copy in a `gem env` home is not one the project loads and is not verified, unless it is a default gem (its spec under `specifications/default/`), which Bundler loads from the system home under any path. Agent `apply` writes by that rule too (#2313): it leaves such a copy alone (see "Copy classes"). *The refresh* (default; `--no-gem-install-refresh`, env `SOCKET_NO_GEM_INSTALL_REFRESH`, turns it off). @@ -1509,7 +1509,8 @@ the model is **not uniform** today: "nothing installed" absence the hosted lockfile basis excuses), while `apply`/`rollback` never touch it (#709). Explicit env/config/standalone roots only count when `--cwd` holds a Bundler manifest/lockfile. When the default `vendor/bundle` root holds no store, the gem homes `gem env` - reports are appended (default gems like rexml/json only ever live there). When the Bundler tier that + reports are appended (default gems like rexml/json only ever live there); which of the copies + found there are written is the "Copy classes" rule below. When the Bundler tier that decides the install path (the first of the app config, the environment and the global config that sets `path`, `path.system` or `disable_shared_gems`) sets a truthy `path.system` (Bundler's own coercion: anything but `false`/`f`/`no`/`n`/`0`/empty), bundler installs into and loads from the @@ -1546,13 +1547,38 @@ the model is **not uniform** today: *Copy classes (additive to the multi-copy vocabulary):* a copy under a **bundle-path store** (config/env/default root) is PRIMARY — a variant mismatch or write failure there fails the run, as always. A copy in a **`gem env` fallback home** (rvm `@global`, `--user-install`, system gem - dirs — shared, often root-owned) is patched too when it matches and is writable, but becomes - BEST-EFFORT once at least one bundle-store copy applied: its mismatch/write failure surfaces as a - non-fatal `skipped` event (`errorCode: gem_fallback_home_skipped`, detail names the copy's path - and reason; gated stderr twin on the human path) instead of failing a run whose loaded copy is - patched. With **no** bundle-store copy (the historic fallback-only layout, and every `--global` - run) the fallback-home copy IS the primary install and keeps loud-fail parity with pre-bundle-path - `apply`. + dirs — shared, often root-owned) is found only while the default `vendor/bundle` root holds no + store (above). It is a write target of `apply`, and of the apply that `get` and + `scan --mode agent` run, only when Bundler loads it for the project (#2313): + + - when Bundler uses system gems (the rule under "Gem stale-install guard": no deployment store + under `vendor/bundle`, and no explicit or deployment `path`), every copy there is the + project's and is patched; + - under an explicit or deployment `path`, only a default gem (its spec under + `specifications/default/`) is patched there: Bundler loads it from the system home under any + path. Bundler installs every other gem into the path, so a non-default copy in a `gem env` + home belongs to other projects on the machine. It is never written and gets no event. A gem + with no other copy is `package_not_installed`, as any package that is not installed: a calm + skip (exit 0) when the project's lock resolves it, which is a fresh clone before + `bundle install`, and the all-miss error (exit 1) when no lock resolves it and no other + targeted patch matched. The discovery crawl of `scan --mode agent` is not narrowed by this + rule: it can still select and download a patch for such a copy, which the apply then reports + as not installed. + + `apply --check` and `vex` judge the same copies. `rollback` and `remove` resolve without this + rule: they restore every copy they find in the `gem env` homes, because a release before this + rule may have patched one. A `--global` run patches the `gem env` homes as before. Once the + default `vendor/bundle` root holds a store, no local run searches those homes: a default gem + there is not patched, and `rollback` leaves a copy an earlier run patched there, keeps its + manifest record and names `socket-patch rollback -g` in a warning. + + A fallback-home copy that is written becomes BEST-EFFORT once at least one bundle-store copy + applied: its mismatch/write failure surfaces as a non-fatal `skipped` event + (`errorCode: gem_fallback_home_skipped`, detail names the copy's path and reason; gated stderr + twin on the human path) instead of failing a run whose loaded copy is patched. With **no** + bundle-store copy (Bundler using system gems, a default gem that is in no store, and every + `--global` run) the fallback-home copy IS the primary install and keeps loud-fail parity with + pre-bundle-path `apply`. **Intended (gap):** the cwd-only ecosystems *should* also auto-discover per-subproject lockfiles when run from the repo root, matching the npm workspace model. The npm-vs-others asymmetry is a known diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 7a93fa819e..184861a9ca 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5123,6 +5123,34 @@ A shared gem home also holds gem versions this project doesn't use: the gems Rub mode warns `redirect_gem_version_not_locked`, vendored mode reports a `skipped` event with `vendor_gem_version_not_locked` and doesn't download its patch. The run exits 0. +Agent mode (`apply`, and the apply step of `scan --mode agent`) patches installed gems in place, +and follows the same principle. It writes the copies Bundler loads for the project and no other: + +- With a Bundler `path` (`bundle config set --local path vendor/gems`, `BUNDLE_PATH`) or + deployment mode, Bundler installs the project's gems into that path, and `apply` patches them + there. A copy of the same gem version in a shared gem home is left alone: Bundler never loads it + for this project, and another project may. The exception is a default gem, one that ships with + Ruby (`json`, `rexml`, ...). Bundler loads it from Ruby's own gem home under any path, so + `apply` patches it there. That stops once `vendor/bundle`, the default path, holds the + project's gems: `apply` then looks only there, and a default gem is not patched. +- With no `path`, Bundler installs into the shared gem homes and loads the project's gems from + them, so `apply` patches them there. Another project that uses the same gem version then runs + the patched code too. Set a `path` (the `bundle config` line above) to keep the patch inside the + project. + +On a fresh clone with a `path`, run `bundle install` before `apply`. Before it the path holds no +gem, so `apply` patches nothing and reports the gems as not installed (`0 of 1 targeted patch +applied, 0 already patched, 1 not found on disk`). It exits 0 when `Gemfile.lock` lists them. +With no lock that does, a run that matched no installed package at all exits 1, as it does for +any package that is not installed. + +Releases up to 5.1.0 patched a copy in a shared gem home under a `path` as well. `rollback` and +`remove` still restore such a copy when they find it. Once `vendor/bundle` holds the project's +gems they look only there too: `rollback` then keeps the patch recorded and warns that the shared +copy is still patched, naming the command that restores it (`socket-patch rollback -g`). +`apply --global` patches the gems in the shared gem homes whatever the project's Bundler settings +are. + ## Ruby gems: gems vendored mode refuses Vendored mode rewrites one top-level `gem` line to a `path:` source, and Bundler builds nothing From df967e68d4df160e3aa5b3d16ec458f8dfca5ed6 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 15:49:49 -0500 Subject: [PATCH 05/20] Leave another project's gems out of an agent-mode scan (#2313) Agent `apply` no longer writes a non-default gem in a `gem env` home that Bundler does not load for the project. The scan's crawl still found such a gem, so `scan --mode agent` selected its patch, downloaded and recorded it, and its apply step then reported it as not installed. With no other patch matched the scan exited 1 where it exited 0 before, and so did every later `apply`, over a gem the project does not use. The scan now drops such a gem from its candidates when the project's lock does not list it either: it is not counted, queried or shown, and nothing is downloaded or recorded for it. The question is put to `apply`'s own resolver (`gems_apply_never_writes`), so the scan cannot select what `apply` will not write. The filter runs after the prune universe is captured: a prune still counts the copy as installed and keeps a record an earlier release wrote for it, which `rollback` restores. Unchanged: a gem the lock lists (a fresh clone before `bundle install`) is still selected and recorded, and the apply step reports it as not installed on this host, exit 0. So are default gems, Bundler using system gems, a populated `vendor/bundle`, and hosted and vendored scans. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/scan/discovery.rs | 45 +++ .../socket-patch-cli/src/commands/scan/mod.rs | 31 +- .../src/ecosystem_dispatch.rs | 38 ++ crates/socket-patch-cli/tests/scan/main.rs | 1 + .../tests/scan/scan_gem_unloaded_homes.rs | 328 ++++++++++++++++++ 5 files changed, 434 insertions(+), 9 deletions(-) create mode 100644 crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs diff --git a/crates/socket-patch-cli/src/commands/scan/discovery.rs b/crates/socket-patch-cli/src/commands/scan/discovery.rs index 478df431a3..43278377ab 100644 --- a/crates/socket-patch-cli/src/commands/scan/discovery.rs +++ b/crates/socket-patch-cli/src/commands/scan/discovery.rs @@ -61,6 +61,51 @@ pub(crate) struct LockfileSupplement { pub(crate) stale_hub_pins: Vec, } +impl LockfileSupplement { + /// Every purl the project's lockfiles resolve: `entries`, and the + /// gems the Bundler lock holds only as precompiled platform builds, + /// which the inventory leaves out and the lock names all the same. + pub(crate) fn locked_purls(&self) -> impl Iterator { + self.entries + .iter() + .map(|entry| entry.purl.as_str()) + .chain(self.platform_gems.iter().map(String::as_str)) + } +} + +/// `crawled` without the gems an agent-mode scan leaves alone: a gem that +/// `apply` has no copy to write for +/// ([`crate::ecosystem_dispatch::gems_apply_never_writes`]: its every copy +/// sits in a `gem env` home Bundler never loads the project's gems from, +/// so it is another project's) and that the project's lock does not list. +/// Selecting its patch would download and record one the apply step then +/// reports as not installed (#2313). A gem the lock lists stays, so its +/// record is there for the `bundle install` that puts it in the project's +/// path. A supplement (`supplement_purls`) stays too: its path is a +/// placeholder. +pub(crate) async fn without_unloaded_gems( + crawled: Vec, + supplement_purls: &HashSet, + lockfile_only: &LockfileSupplement, + options: &socket_patch_core::crawlers::CrawlerOptions, +) -> Vec { + let locked: HashSet = lockfile_only.locked_purls().map(PurlKey::new).collect(); + let unlisted = crawled + .iter() + .filter(|pkg| { + !supplement_purls.contains(&pkg.purl) && !locked.contains(&PurlKey::new(&pkg.purl)) + }) + .map(|pkg| (pkg.purl.clone(), pkg.path.clone())); + let unloaded = crate::ecosystem_dispatch::gems_apply_never_writes(unlisted, options).await; + if unloaded.is_empty() { + return crawled; + } + crawled + .into_iter() + .filter(|pkg| !unloaded.contains(&pkg.purl)) + .collect() +} + /// Inventory the project's lockfile(s) and fabricate crawl entries for /// dependencies that are not installed. The fabricated `path` is the /// WOULD-BE install dir — every consumer degrades safely on a nonexistent diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 85571f984f..7085143a1e 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -2748,6 +2748,25 @@ async fn scan_project( .filter(|pkg| args.common.purl_ecosystem_selected(&pkg.purl)) .collect(); + // Agent mode patches installed copies in place, and its apply step + // leaves alone a gem copy Bundler never loads for the project (another + // project's gem in a `gem env` home, under an explicit or deployment + // `path`). A gem with no other copy, and not in the lock, is not this + // project's: it is not a candidate (#2313). Strictly AFTER the + // `scanned_purls` capture, so a prune still counts the copy as + // installed and keeps a record an earlier release wrote for it. + let filtered_crawled = if apply { + discovery::without_unloaded_gems( + filtered_crawled, + &supplement_purls, + &lockfile_only, + &crawler_options, + ) + .await + } else { + filtered_crawled + }; + let package_specs: Vec<&String> = args .packages .iter() @@ -3991,15 +4010,9 @@ async fn scan_project( // direct dependencies, so PyPI packages always count. The lockfile // inventory leaves out a gem the Bundler lock holds only as // precompiled platform builds; the lock names it too. - let locked_purls = || { - lockfile_only - .entries - .iter() - .map(|entry| entry.purl.as_str()) - .chain(lockfile_only.platform_gems.iter().map(String::as_str)) - }; - let locked: HashSet = locked_purls().map(PurlKey::new).collect(); - let complete_locks: HashSet = locked_purls() + let locked: HashSet = lockfile_only.locked_purls().map(PurlKey::new).collect(); + let complete_locks: HashSet = lockfile_only + .locked_purls() .filter_map(Ecosystem::from_purl) .filter(|eco| *eco != Ecosystem::Pypi) .collect(); diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index b839197917..ca0f5105bf 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -946,6 +946,44 @@ async fn retain_bundler_loaded_gem_copies( copies.retain(|_, paths| !paths.is_empty()); } +/// The gems of `crawled` (a purl and the copy of it a crawl found) that +/// agent `apply` has no copy to write for: every installed copy is one +/// Bundler never loads for the project +/// ([`retain_bundler_loaded_gem_copies`]). For an agent-mode scan, which +/// must not select a patch its apply step then reports as not installed +/// (#2313). A crawl reports one copy per gem, so a gem that copy rules out +/// is looked up again the way `apply` looks it up: another gem home may +/// hold it as a default gem. +pub(crate) async fn gems_apply_never_writes( + crawled: impl IntoIterator, + options: &CrawlerOptions, +) -> HashSet { + let mut copies: HashMap> = crawled + .into_iter() + .filter(|(purl, _)| Ecosystem::from_purl(purl) == Some(Ecosystem::Gem)) + .map(|(purl, path)| (purl, vec![path])) + .collect(); + let crawled: Vec = copies.keys().cloned().collect(); + retain_bundler_loaded_gem_copies(&mut copies, options).await; + let ruled_out: Vec = crawled + .into_iter() + .filter(|purl| !copies.contains_key(purl)) + .collect(); + if ruled_out.is_empty() { + return HashSet::new(); + } + let written: HashSet = + find_all_packages_for_purls(&partition_purls(&ruled_out, None), options, true) + .await + .keys() + .map(|purl| PurlKey::new(purl)) + .collect(); + ruled_out + .into_iter() + .filter(|purl| !written.contains(&PurlKey::new(purl))) + .collect() +} + /// Multi-copy variant of `find_packages_for_rollback` (qualified-aware /// merge). Used by `rollback`, which restores every physical copy. pub async fn find_all_packages_for_rollback( diff --git a/crates/socket-patch-cli/tests/scan/main.rs b/crates/socket-patch-cli/tests/scan/main.rs index 4233b89fce..13ca652ca0 100644 --- a/crates/socket-patch-cli/tests/scan/main.rs +++ b/crates/socket-patch-cli/tests/scan/main.rs @@ -33,6 +33,7 @@ mod scan_batch_sizing_e2e; mod scan_ecosystems_scope_e2e; mod scan_failure_paths; mod scan_fixture; +mod scan_gem_unloaded_homes; mod scan_invariants; mod scan_nested_project_e2e; mod scan_ordered_concurrency_e2e; diff --git a/crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs b/crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs new file mode 100644 index 0000000000..548ca52cd9 --- /dev/null +++ b/crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs @@ -0,0 +1,328 @@ +//! `scan --mode agent` and a gem that only a `gem env` home holds (#2313). +//! +//! Under an explicit Bundler `path` the project's gems are installed into +//! that path, and a gem in the system gems (an rbenv or asdf home, +//! `~/.gem`) is another project's: Bundler never loads it for this one, +//! and the apply step leaves it alone. The scan's crawl still finds it, so +//! the scan must not select it either: its patch would be downloaded and +//! recorded for the apply step to report as not installed, which fails a +//! run that matched nothing else. +//! +//! * a gem the project's lock does not list is no candidate: it is not +//! queried, nothing is downloaded or recorded, and the run exits 0; +//! * a gem the lock lists stays one (a fresh clone before +//! `bundle install`): its record is kept and the apply step reports it +//! as not installed on this host, exit 0; +//! * a default gem (its spec under `specifications/default/`) is loaded +//! from the system home under any path, so it is still patched there. +//! +//! Unix-only: the `gem env` home comes from a fake `gem` binary on PATH. + +#![cfg(unix)] + +use std::path::{Path, PathBuf}; + +use base64::Engine; +use wiremock::matchers::{body_string_contains, method, path, path_regex}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +use super::scan_fixture::{api_args, batch_bodies, mount_empty_batch, recorded, ORG_SLUG, UUID}; +use crate::common::envelope::{event_purls, has_event, parse_json_envelope}; +use crate::common::hermetic::{self, Extra}; +use crate::common::{binary, git_sha256, hermetic_command, jvm_env}; + +const RACK: &str = "pkg:gem/rack@3.1.0"; +const RACK_RUBY: &str = "pkg:gem/rack@3.1.0?platform=ruby"; + +const ORIGINAL: &[u8] = b"module Rack\n VERSION = 'VULNERABLE'\nend\n"; +const PATCHED: &[u8] = b"module Rack\n VERSION = 'VULNERABLE'\nend\n# SOCKET-PATCHED\n"; + +/// Stage `/gems/-/lib/.rb` = `bytes` plus the +/// `specifications/` marker of a gem home; returns the staged file. +fn stage_gem(home: &Path, name: &str, version: &str, bytes: &[u8]) -> PathBuf { + let file = home + .join("gems") + .join(format!("{name}-{version}")) + .join("lib") + .join(format!("{name}.rb")); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, bytes).unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + file +} + +struct Fixture { + project: tempfile::TempDir, + /// `rack-3.1.0/lib/rack.rb` in the `gem env` home. + home_file: PathBuf, +} + +/// A project whose Bundler `path` is `bundle-store` (exported as +/// `BUNDLE_PATH` by [`scan`]), with `rack 3.1.0` in the `gem env` home +/// `gem-home` that a fake `gem` reports. `lock` is the `specs:` lines of +/// its `Gemfile.lock`. +fn build_fixture(lock: &[&str]) -> Fixture { + use std::os::unix::fs::PermissionsExt; + let project = tempfile::tempdir().unwrap(); + let root = project.path(); + std::fs::write(root.join("Gemfile"), "source \"https://rubygems.org\"\n").unwrap(); + let specs: String = lock.iter().map(|spec| format!(" {spec}\n")).collect(); + std::fs::write( + root.join("Gemfile.lock"), + format!( + "GEM\n remote: https://rubygems.org/\n specs:\n{specs}\n\ + PLATFORMS\n ruby\n\nDEPENDENCIES\n\nBUNDLED WITH\n 2.5.22\n" + ), + ) + .unwrap(); + + let home = root.join("gem-home"); + let home_file = stage_gem(&home, "rack", "3.1.0", ORIGINAL); + + let bin_dir = root.join("fake-bin"); + std::fs::create_dir_all(&bin_dir).unwrap(); + let gem = bin_dir.join("gem"); + std::fs::write( + &gem, + format!( + "#!/bin/sh\nif [ \"$1\" = env ] && [ \"$2\" = gemdir ]; then\n printf '%s\\n' \"{}\"\n exit 0\nfi\nexit 1\n", + home.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&gem, std::fs::Permissions::from_mode(0o755)).unwrap(); + Fixture { project, home_file } +} + +/// The patch API: `rack 3.1.0` has one free patch, offered only to a batch +/// query that names the gem. Any other query finds nothing. +async fn mount_rack_patch(mock: &MockServer) { + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch"))) + .and(body_string_contains(RACK)) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [{ + "purl": RACK, + "patches": [{ + "uuid": UUID, "purl": RACK_RUBY, "tier": "free", + "cveIds": [], "ghsaIds": [], "severity": "high", "title": "rack", + }], + }], + "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(mock) + .await; + mount_empty_batch(mock).await; + Mock::given(method("GET")) + .and(path_regex(format!( + "^/v0/orgs/{ORG_SLUG}/patches/by-package/.+$" + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": [{ + "uuid": UUID, "purl": RACK_RUBY, "publishedAt": "2024-01-01T00:00:00Z", + "description": "rack", "license": "MIT", "tier": "free", "vulnerabilities": {}, + }], + "canAccessPaidPatches": false, + }))) + .mount(mock) + .await; + let b64 = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes); + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/view/{UUID}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "uuid": UUID, + "purl": RACK_RUBY, + "publishedAt": "2024-01-01T00:00:00Z", + "files": { + "lib/rack.rb": { + "beforeHash": git_sha256(ORIGINAL), + "afterHash": git_sha256(PATCHED), + "blobContent": b64(PATCHED), + "beforeBlobContent": b64(ORIGINAL), + } + }, + "vulnerabilities": {}, + "description": "rack", + "license": "MIT", + "tier": "free", + }))) + .mount(mock) + .await; +} + +/// Run `socket-patch --ecosystems gem --cwd ` in +/// the hermetic env with the ambient `BUNDLE_*` scrubbed, PATH = the +/// fake-gem bin dir only, and `BUNDLE_PATH` naming the project's store. +fn run(fx: &Fixture, command: &str, args: &[&str]) -> (i32, String, String) { + let root = fx.project.path(); + let mut cmd = hermetic_command(&binary()); + cmd.arg(command) + .args(["--ecosystems", "gem", "--cwd"]) + .arg(root) + .args(args); + jvm_env::isolate_cli(&mut cmd); + hermetic::scrub_extra(&mut cmd, &[Extra::Bundle]); + cmd.env("PATH", root.join("fake-bin")) + .env("BUNDLE_PATH", root.join("bundle-store")); + let out = cmd.output().expect("run socket-patch"); + ( + out.status.code().unwrap_or(-1), + String::from_utf8_lossy(&out.stdout).to_string(), + String::from_utf8_lossy(&out.stderr).to_string(), + ) +} + +/// `scan --mode agent ` against the mock API. +fn scan(fx: &Fixture, api_url: &str, extra: &[&str]) -> (i32, String, String) { + let mut args = vec!["--mode", "agent"]; + args.extend(api_args(api_url)); + args.extend_from_slice(extra); + run(fx, "scan", &args) +} + +fn manifest_purls(fx: &Fixture) -> Vec { + let path = fx.project.path().join(".socket").join("manifest.json"); + let Ok(raw) = std::fs::read(&path) else { + return Vec::new(); + }; + let manifest: serde_json::Value = serde_json::from_slice(&raw).unwrap(); + manifest["patches"] + .as_object() + .map(|patches| patches.keys().cloned().collect()) + .unwrap_or_default() +} + +async fn queried_rack(mock: &MockServer) -> bool { + batch_bodies(&recorded(mock).await) + .iter() + .any(|body| body.contains(RACK)) +} + +/// The project's own gem is installed in its path, and `rack` is only in +/// the `gem env` home and not in the lock: another project's copy. The +/// scan does not ask about it, downloads and records nothing, and exits 0; +/// so does the `apply` after it. +#[tokio::test] +async fn foreign_gem_in_a_gem_env_home_is_not_selected() { + let fx = build_fixture(&["colorize (1.1.0)"]); + let store = fx.project.path().join("bundle-store"); + stage_gem(&store, "colorize", "1.1.0", b"module Colorize\nend\n"); + let mock = MockServer::start().await; + mount_rack_patch(&mock).await; + + let (code, stdout, stderr) = scan(&fx, &mock.uri(), &["--json"]); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!( + env["scannedPackages"], 1, + "only the project's own gem counts.\nenvelope: {env}" + ); + assert!( + !stdout.contains(RACK), + "the envelope must not name the foreign gem.\nenvelope: {env}" + ); + let bodies = batch_bodies(&recorded(&mock).await); + assert!( + bodies.iter().any(|body| body.contains("colorize")), + "the project's own gem is still scanned; batch bodies: {bodies:?}" + ); + assert!( + !bodies.iter().any(|body| body.contains(RACK)), + "the foreign gem must not be queried; batch bodies: {bodies:?}" + ); + assert_eq!(manifest_purls(&fx), Vec::::new()); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); + + let (code, stdout, stderr) = run(&fx, "apply", &["--offline"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// The human run of the same project: no error, no failed apply, and +/// nothing about the foreign gem. +#[tokio::test] +async fn foreign_gem_in_a_gem_env_home_leaves_the_human_run_clean() { + let fx = build_fixture(&["colorize (1.1.0)"]); + let store = fx.project.path().join("bundle-store"); + stage_gem(&store, "colorize", "1.1.0", b"module Colorize\nend\n"); + let mock = MockServer::start().await; + mount_rack_patch(&mock).await; + + let (code, stdout, stderr) = scan(&fx, &mock.uri(), &[]); + let out = format!("{stdout}{stderr}"); + assert_eq!(code, 0, "output={out}"); + assert!( + out.contains("No patches available for installed packages."), + "output={out}" + ); + assert!( + !out.contains("rack") && !out.contains("Error:"), + "output={out}" + ); + assert!(!queried_rack(&mock).await); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// A fresh clone before `bundle install`: the lock lists `rack`, the path +/// holds nothing yet, and the `gem env` home has the same version. The +/// gem is the project's, so its patch is still selected and recorded; the +/// apply step writes nothing and reports it as not installed on this host. +#[tokio::test] +async fn locked_gem_not_installed_yet_keeps_its_record() { + let fx = build_fixture(&["rack (3.1.0)"]); + let mock = MockServer::start().await; + mount_rack_patch(&mock).await; + + let (code, stdout, stderr) = scan(&fx, &mock.uri(), &["--json"]); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert!(queried_rack(&mock).await, "the locked gem is a candidate"); + assert!( + has_event(&env, "skipped", "package_not_installed", RACK_RUBY), + "envelope: {env}" + ); + assert_eq!(env["summary"]["applied"], 0, "envelope: {env}"); + assert_eq!(manifest_purls(&fx), vec![RACK_RUBY.to_string()]); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); + + // The `apply` a later run does is the same calm skip. + let (code, stdout, stderr) = run(&fx, "apply", &["--offline"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + stderr.contains("not installed on this host (resolved by the project lockfile; skipped)"), + "stderr={stderr}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// A default gem the lock does not list is still a candidate: Bundler +/// loads it from the system home under any path, and the apply step +/// patches it there. +#[tokio::test] +async fn default_gem_in_a_gem_env_home_is_still_patched() { + let fx = build_fixture(&["colorize (1.1.0)"]); + let default_specs = fx + .project + .path() + .join("gem-home") + .join("specifications") + .join("default"); + std::fs::create_dir_all(&default_specs).unwrap(); + std::fs::write(default_specs.join("rack-3.1.0.gemspec"), b"").unwrap(); + let mock = MockServer::start().await; + mount_rack_patch(&mock).await; + + let (code, stdout, stderr) = scan(&fx, &mock.uri(), &["--json"]); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + event_purls(&env, "applied"), + vec![RACK_RUBY.to_string()], + "envelope: {env}" + ); + assert_eq!(manifest_purls(&fx), vec![RACK_RUBY.to_string()]); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), PATCHED); +} From 476fac464ca72d4ac63167afa95235f306bba553 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 15:49:50 -0500 Subject: [PATCH 06/20] Document what an agent-mode scan selects for gems The "Copy classes" paragraph of CLI_CONTRACT.md said the scan's discovery was not narrowed by the write rule. Say that it selects by the same rule: a gem only another project's gem home holds, and that the lock does not list, is no candidate, while a gem the lock lists is still recorded. docs/ecosystems.md says the same for users, and what to do with a record an earlier release wrote for such a gem. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 13 ++++++++++--- docs/ecosystems.md | 11 +++++++++-- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index dfb6d5b79c..52ef48d59d 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1561,9 +1561,16 @@ the model is **not uniform** today: with no other copy is `package_not_installed`, as any package that is not installed: a calm skip (exit 0) when the project's lock resolves it, which is a fresh clone before `bundle install`, and the all-miss error (exit 1) when no lock resolves it and no other - targeted patch matched. The discovery crawl of `scan --mode agent` is not narrowed by this - rule: it can still select and download a patch for such a copy, which the apply then reports - as not installed. + targeted patch matched. + + `scan --mode agent` selects by the same rule, so that it never records a patch its apply step + then reports as not installed. A gem whose every copy is one `apply` does not write, and that + the project's lock does not list, is another project's and is no candidate: it is not counted + (`scannedPackages`), queried or shown, and nothing is downloaded or recorded for it. A gem the + lock does list stays a candidate: its patch is recorded, and the apply step reports it + `package_not_installed` (lockfile-only, exit 0) until `bundle install` puts it in the path. The + prune pass (`--prune` / `--sync`) still counts such a copy as installed, so a record an earlier + release wrote for it is kept until `rollback` or `remove` restores the copy. `apply --check` and `vex` judge the same copies. `rollback` and `remove` resolve without this rule: they restore every copy they find in the `gem env` homes, because a release before this diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 184861a9ca..06d5602732 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5138,6 +5138,11 @@ and follows the same principle. It writes the copies Bundler loads for the proje the patched code too. Set a `path` (the `bundle config` line above) to keep the patch inside the project. +An agent-mode scan selects patches by the same rule. A gem that is only in a shared gem home, +and that `Gemfile.lock` doesn't list, is another project's: the scan doesn't report it, and +downloads and records no patch for it. A gem the lock does list is the project's even before it +is installed, so the scan records its patch. + On a fresh clone with a `path`, run `bundle install` before `apply`. Before it the path holds no gem, so `apply` patches nothing and reports the gems as not installed (`0 of 1 targeted patch applied, 0 already patched, 1 not found on disk`). It exits 0 when `Gemfile.lock` lists them. @@ -5148,8 +5153,10 @@ Releases up to 5.1.0 patched a copy in a shared gem home under a `path` as well. `remove` still restore such a copy when they find it. Once `vendor/bundle` holds the project's gems they look only there too: `rollback` then keeps the patch recorded and warns that the shared copy is still patched, naming the command that restores it (`socket-patch rollback -g`). -`apply --global` patches the gems in the shared gem homes whatever the project's Bundler settings -are. +A manifest written by such a release may still record a patch for a gem of another project: +`apply` now reports it as not installed, and `socket-patch rollback ` restores that copy +and removes the record. `apply --global` patches the gems in the shared gem homes whatever the +project's Bundler settings are. ## Ruby gems: gems vendored mode refuses From 678a5dfa0fcc4854dd594c81e627d8f8135f30f7 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 16:42:57 -0500 Subject: [PATCH 07/20] Keep Bundler in a gem env home as a copy the project loads Bundler is never installed into a project's `path`. A Bundler updated with `gem install bundler` lives in the system gem home with its spec outside `specifications/default/`, and `bundle exec` loads it from there under any path (checked with Bundler 2.6.9 on Ruby 3.4 under `path vendor/gems`). The rule that drops the gem copies Bundler does not load treated it as another project's gem, so `apply` stopped patching it and `vex` and `apply --check` stopped judging it. `retain_bundler_loaded_gem_copies` now keeps a `bundler-` copy in a `gem env` home, as it keeps a default gem, so every command that uses the rule agrees. Every installed version is kept: which one runs also depends on the lock's `BUNDLED WITH`, on `BUNDLER_VERSION` and on Bundler's own switch to the locked version, and a wrong guess would leave the running Bundler unpatched. `bundler-audit` and the like are ordinary gems. Two crawler comments gave rexml as an example of a default gem; it has been a bundled gem since Ruby 3.0, so they now name json and uri. Co-Authored-By: Claude Fable 5.2 --- .../src/ecosystem_dispatch.rs | 27 +++++++------ .../src/crawlers/ruby_crawler.rs | 40 ++++++++++++++++--- 2 files changed, 50 insertions(+), 17 deletions(-) diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index ca0f5105bf..7dfb19d499 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -906,12 +906,13 @@ async fn retain_locked_cargo_copies( /// non-default gem into that path, so such a copy belongs to other /// projects on the machine: patching it would change their code and /// nothing this project runs (#2313), and an unpatched one must not block -/// an attestation (#1098). Default gems stay: Bundler loads those from the -/// system home under any path. A purl left with no copy is dropped, so it -/// reads as not installed. Only the commands that patch or attest call -/// this: rollback and remove still find the copy, since an earlier release -/// may have patched it. -async fn retain_bundler_loaded_gem_copies( +/// an attestation (#1098). Default gems stay, and so does Bundler itself: +/// Bundler loads those from the gem home they are installed in under any +/// path. A purl left with no copy is dropped: the gem is not installed +/// for this project. The commands that patch, attest or select a patch +/// call this; rollback and remove restore a copy an earlier release +/// patched, and use it to tell that copy from one nothing touched. +pub(crate) async fn retain_bundler_loaded_gem_copies( copies: &mut HashMap>, options: &CrawlerOptions, ) { @@ -937,10 +938,12 @@ async fn retain_bundler_loaded_gem_copies( if unused.is_empty() { return; } + use socket_patch_core::crawlers::ruby_crawler::{is_bundler_copy, is_default_gem_copy}; for (_, paths) in copies.iter_mut().filter(|(purl, _)| is_gem(purl)) { paths.retain(|path| { !unused.iter().any(|home| path.starts_with(home)) - || socket_patch_core::crawlers::ruby_crawler::is_default_gem_copy(path) + || is_default_gem_copy(path) + || is_bundler_copy(path) }); } copies.retain(|_, paths| !paths.is_empty()); @@ -949,11 +952,11 @@ async fn retain_bundler_loaded_gem_copies( /// The gems of `crawled` (a purl and the copy of it a crawl found) that /// agent `apply` has no copy to write for: every installed copy is one /// Bundler never loads for the project -/// ([`retain_bundler_loaded_gem_copies`]). For an agent-mode scan, which -/// must not select a patch its apply step then reports as not installed -/// (#2313). A crawl reports one copy per gem, so a gem that copy rules out -/// is looked up again the way `apply` looks it up: another gem home may -/// hold it as a default gem. +/// ([`retain_bundler_loaded_gem_copies`]). For an agent-mode `scan` or +/// `get`, to which such a gem is not installed: selecting its patch would +/// record one the apply step has nowhere to write (#2313). A crawl reports +/// one copy per gem, so a gem that copy rules out is looked up again the +/// way `apply` looks it up: another gem home may hold it as a default gem. pub(crate) async fn gems_apply_never_writes( crawled: impl IntoIterator, options: &CrawlerOptions, diff --git a/crates/socket-patch-core/src/crawlers/ruby_crawler.rs b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs index 5c732878bb..a83f56e94e 100644 --- a/crates/socket-patch-core/src/crawlers/ruby_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs @@ -34,7 +34,7 @@ impl RubyCrawler { /// a store (a deployment-style install), those stores are the whole /// answer; otherwise, if the cwd holds a Bundler manifest or lockfile, /// the gem homes `gem env` reports are appended (deduped) — default - /// gems (rexml, json, …) never live in a bundle path, so an + /// gems (json, uri, …) never live in a bundle path, so an /// env/config-rooted project still needs them. /// /// In global mode, queries `gem env gemdir` and `gem env gempath`, plus @@ -124,7 +124,7 @@ impl RubyCrawler { // `vendor/bundle` probe: a deployment-style install is the // project's one gem source, so the ambient gem homes don't apply. // Stores found via an env/config root do NOT suppress the fallback - // below: default gems (rexml, json, …) never live in a bundle path + // below: default gems (json, uri, …) never live in a bundle path // — they ship with ruby in the DEFAULT/system gem homes — so an // env-`BUNDLE_PATH` project still needs the `gem env` homes to see // them (the explicit-roots feature briefly suppressed that @@ -835,9 +835,11 @@ impl RubyCrawler { /// The `gem env` homes Bundler never loads this project's gems from. /// [`Self::get_gem_paths`] keeps them for default gems, but under an /// explicit or deployment `path` Bundler fetches every other gem into - /// that path, so a non-default copy there is not one the project runs: - /// `apply` does not write it (#2313), and the read-only verifiers - /// (`vex`, `apply --check`) do not judge it (#1098). Empty in global / + /// that path, so a copy there that is neither a default gem nor + /// Bundler ([`is_default_gem_copy`], [`is_bundler_copy`]) is not one + /// the project runs: `apply` does not write it (#2313), and the + /// read-only verifiers (`vex`, `apply --check`) do not judge it + /// (#1098). Empty in global / /// `--global-prefix` mode and whenever Bundler uses system gems. A /// home that is also one of the project's Bundler stores is never /// listed. @@ -1523,6 +1525,22 @@ pub fn is_default_gem_copy(copy: &Path) -> bool { .is_file() } +/// Whether the installed gem dir `copy` (`/gems/-`) +/// is Bundler itself. Bundler is never installed into a project's `path`: +/// the one that runs is loaded from the gem home it was installed into +/// (`gem install bundler`, `gem update bundler`), where its spec sits +/// outside `specifications/default/`. So a copy of it in a `gem env` home +/// is one the project loads under any `path`, like a default gem. Which +/// version runs is not decided here (the lock's `BUNDLED WITH`, +/// `BUNDLER_VERSION` and Bundler's own switch to the locked version all +/// have a say), so every installed version counts. +pub fn is_bundler_copy(copy: &Path) -> bool { + copy.file_name() + .and_then(OsStr::to_str) + .and_then(|leaf| leaf.strip_prefix("bundler-")) + .is_some_and(|version| version.starts_with(|c: char| c.is_ascii_digit())) +} + /// `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. @@ -5257,6 +5275,18 @@ mod tests { assert!(!is_default_gem_copy(Path::new("json-2.7.2"))); } + /// Bundler is told by its gem dir's name, whatever its version; a gem + /// whose name only starts with `bundler-` is another gem. + #[test] + fn is_bundler_copy_matches_bundler_alone() { + let gems = Path::new("/home/gems"); + assert!(is_bundler_copy(&gems.join("bundler-2.6.9"))); + assert!(is_bundler_copy(&gems.join("bundler-4.0.0.beta1"))); + assert!(!is_bundler_copy(&gems.join("bundler-audit-0.9.2"))); + assert!(!is_bundler_copy(&gems.join("bundler"))); + assert!(!is_bundler_copy(&gems.join("rack-3.1.8"))); + } + /// #1109: with no tier setting `path`, `path.system` or /// `disable_shared_gems`, a truthy `deployment` makes `vendor/bundle` /// the explicit path (`Settings#path`, Bundler 2.5 and 4.0 alike). The From 9d5ba4d5473d1c58ca7067e8dafe56f66f6cb594 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 16:42:57 -0500 Subject: [PATCH 08/20] Skip another project's gem in apply instead of failing A manifest record for a gem whose only copy sits in a `gem env` home that Bundler does not load for the project made `apply` exit 1 with "matched no installed package" and "Check that the packages are installed and --cwd points to the right directory". Both are wrong: the gem is installed, for another project, and the record is one an earlier release wrote when it patched that copy, or one `get` of the exact purl wrote. The remedy is `socket-patch rollback `. Such a record is now a skip of its own. For the gems `apply` found no copy to write and no lock lists, it asks `rollback`'s resolver, which does not apply the rule, whether a copy exists. One that does is a `skipped` event with the existing `gem_fallback_home_skipped` code: the detail names the copy, says why it was left, and gives the `rollback` command, which is true whether or not the copy was ever patched. The human run prints it as a warning and counts the patch as "not applicable". It never flips the exit code and is not an all-miss. A gem with no copy anywhere and no lock entry keeps the all-miss exit 1, and one the lock lists keeps the lockfile-only skip. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/apply.rs | 135 +++++++++- .../apply/in_process_gem_fallback_home.rs | 245 ++++++++++++++++-- 2 files changed, 348 insertions(+), 32 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index efd6c232cb..ed819ec7e6 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -1812,6 +1812,7 @@ fn collect_apply_outcomes( ) -> (Vec, Vec) { let mut applied = Vec::new(); skipped.extend(caveats.not_in_build.iter().map(LeftCopy::event)); + skipped.extend(caveats.other_project.iter().map(OtherProjectCopy::event)); for result in results { let event = caveats.event_of(result, dry_run); match event.action { @@ -2171,6 +2172,9 @@ pub(crate) async fn run_locked( for skip in &fallback_skips { eprintln!("Warning: {}", skip.detail()); } + for copy in &caveats.other_project { + eprintln!("Warning: {}: {}", normalize_purl(©.purl), copy.detail); + } // A gem build that holds none of a patch's files (the JRuby // build of a gem patched in its C code): nothing to do, said // in plain words, each distinct one once. It is the copy's @@ -2385,9 +2389,14 @@ pub(crate) async fn run_locked( for skip in &fallback_skips { env.record( PatchEvent::new(PatchAction::Skipped, skip.purl.clone()) - .with_reason("gem_fallback_home_skipped", skip.detail()), + .with_reason(FALLBACK_HOME_SKIPPED, skip.detail()), ); } + // Another project's gems: the same code, and never a + // failure either. + for copy in &caveats.other_project { + env.record(copy.event()); + } // Run-level advisories (the gem config-root containment // skip, the sources-unavailable reason): the envelope's // `warnings[]` is their machine channel — stderr is @@ -2852,7 +2861,8 @@ struct ApplyTally { vendored: usize, /// No copy had anything to patch: every one is a build of the package /// that holds none of the code the patch changes - /// ([`gem_ext::GemCaveat::NotInBuild`]). Nothing is left to do. + /// ([`gem_ext::GemCaveat::NotInBuild`]), or is another project's gem + /// ([`OtherProjectCopy`]). Nothing is left to do. not_applicable: usize, /// Some copy's patch is incomplete: its files are written (or the /// copy holds none of them), and the compiled code it runs is not the @@ -2889,6 +2899,7 @@ fn tally_results(results: &[ApplyResult], caveats: &GemCaveats) -> ApplyTally { .not_in_build .iter() .map(|copy| copy.purl.as_str()) + .chain(caveats.other_project.iter().map(|copy| copy.purl.as_str())) .filter(|purl| { !by_purl.contains_key(purl) && !vendored.contains(purl) && !not_in_effect.contains(purl) }) @@ -3243,6 +3254,10 @@ struct GemCaveats { /// Installed copies whose files match no record of their release /// (gem or PyPI). Each has a failed result, keyed by the base purl. no_variant: Vec, + /// Gems installed only where Bundler does not load the project's gems + /// from, and in no lock of the project: skipped. They have no result + /// and do not fail the run. + other_project: Vec, } impl GemCaveats { @@ -3300,6 +3315,90 @@ fn format_patch_incomplete(purl: &str, what: &str) -> String { format!("Error: Patch of {purl} is incomplete: {what}") } +/// `errorCode` of a gem copy in a `gem env` home that `apply` left +/// unpatched without failing: a best-effort copy ([`FallbackHomeSkip`]), or +/// another project's gem ([`OtherProjectCopy`]). +const FALLBACK_HOME_SKIPPED: &str = "gem_fallback_home_skipped"; + +/// One gem `apply` left as it was because its every copy sits in a +/// `gem env` home Bundler does not load the project's gems from, and no +/// lock of the project lists it: another project's gem (#2313). A record +/// for it is one an earlier release wrote when it patched such a copy, or +/// one a `get` of its purl wrote. It is a `Skipped` event of the patch, +/// not an apply result, and never fails the run. +struct OtherProjectCopy { + /// The manifest key of the patch. + purl: String, + /// Which copy, why it was left, and the `rollback` that drops the + /// record: in words. + detail: String, +} + +impl OtherProjectCopy { + fn event(&self) -> PatchEvent { + PatchEvent::new(PatchAction::Skipped, self.purl.clone()) + .with_reason(FALLBACK_HOME_SKIPPED, self.detail.as_str()) + } +} + +/// The gems of `unresolved` (the manifest keys with no copy to patch and +/// no lock entry) that are another project's: `rollback`'s resolver finds +/// a copy of them where this run's (`all_packages`, the copies `apply` +/// writes) found none, so each sits in a `gem env` home Bundler does not +/// load the project's gems from. The detail holds for a copy an earlier +/// release patched and for one nothing ever touched. +async fn other_project_gem_copies( + common: &GlobalArgs, + unresolved: &[String], + all_packages: &HashMap>, +) -> Vec { + if common.is_global() { + return Vec::new(); + } + let candidates: Vec = unresolved + .iter() + .filter(|purl| { + Ecosystem::from_purl(purl) == Some(Ecosystem::Gem) + && !all_packages.contains_key(strip_purl_qualifiers(purl)) + }) + .cloned() + .collect(); + if candidates.is_empty() { + return Vec::new(); + } + let mut found = crate::ecosystem_dispatch::find_all_packages_for_rollback( + &partition_purls(&candidates, None), + &common.crawler_options(), + true, + ) + .await; + candidates + .into_iter() + .filter_map(|purl| { + let path = found.remove(&purl)?.into_iter().next()?; + let mut command = format!( + "socket-patch rollback {}", + crate::ui::shell_word(strip_purl_qualifiers(&purl)) + ); + if common.cwd != Path::new(".") { + command.push_str(&format!( + " --cwd {}", + crate::ui::shell_word(&common.cwd.to_string_lossy()) + )); + } + let detail = format!( + "gem-env home copy at {} was not patched: Bundler does not load this \ + project's gems from that gem home, and the project's lock does not list \ + the gem, so it belongs to another project. Run `{command}` to remove the \ + patch from the manifest; it also restores the copy if an earlier release \ + patched it", + path.display() + ); + Some(OtherProjectCopy { purl, detail }) + }) + .collect() +} + /// One gem-env fallback-home copy the fan-out skipped best-effort (a /// bundle-store copy applied; this shared-home copy mismatched or failed /// to write). Carries what the warning must name: the package, the copy's @@ -3551,6 +3650,16 @@ async fn apply_patches_inner( unmatched.sort(); let lockfile_only = Box::pin(lockfile_resolved(&args.common, &unmatched)).await; let unresolved = unresolved_purls(&unmatched, &lockfile_only); + // Another project's gems are a skip of their own: neither "not + // installed" nor a reason to fail. + let other_project = Box::pin(other_project_gem_copies( + &args.common, + &unresolved, + &all_packages, + )) + .await; + unmatched.retain(|purl| !other_project.iter().any(|copy| copy.purl == *purl)); + let unresolved = unresolved_purls(&unmatched, &lockfile_only); // This diagnostic flips the exit code, so it is an error — and it // prints even under --silent ("errors only", never a mute exit 1); // `--json` @@ -3570,7 +3679,10 @@ async fn apply_patches_inner( run_warnings, fallback_skips, unreported, - caveats: GemCaveats::default(), + caveats: GemCaveats { + other_project, + ..GemCaveats::default() + }, targeted: target_manifest_purls.len(), show_summary: true, }); @@ -3724,9 +3836,10 @@ async fn apply_patches_inner( }; // Write scope is the resolver's: a `gem env` home copy that - // Bundler does not load for the project (a non-default gem - // under an explicit or deployment `path`) belongs to other - // projects and is not in `copy_paths` (#2313). Copy CLASS + // Bundler does not load for the project (under an explicit or + // deployment `path`, any gem but a default gem and Bundler) + // belongs to other projects and is not in `copy_paths` + // (#2313). Copy CLASS // decides the FAILURE semantics of the copies that are: // bundle-path store copies are PRIMARY and loud-fail; // `gem env` home copies (rvm `@global`, system gem dirs — @@ -4302,6 +4415,16 @@ async fn apply_patches_inner( Box::pin(lockfile_resolved(&args.common, &unmatched)).await }; let unresolved = unresolved_purls(&unmatched, &lockfile_only); + // Another project's gems are a skip of their own: neither "not + // installed" nor a reason to fail. + caveats.other_project = Box::pin(other_project_gem_copies( + &args.common, + &unresolved, + &all_packages, + )) + .await; + unmatched.retain(|purl| !caveats.other_project.iter().any(|copy| copy.purl == *purl)); + let unresolved = unresolved_purls(&unmatched, &lockfile_only); // Nothing matched and some purl has no lock evidence either: this // fails the run, so it is an error — and errors print even under diff --git a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs index da2a97c14e..53c2bce083 100644 --- a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs +++ b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs @@ -3,17 +3,22 @@ //! one of them is reported. //! //! `get_gem_paths` appends the `gem env` homes after the project's -//! bundle-path stores, because default gems (rexml, json, …) only live +//! bundle-path stores, because default gems (json, uri, …) only live //! there. Whether a copy found in such a home is written follows what //! Bundler loads for the project (#2313): //! //! * under an explicit Bundler `path` (app config, `BUNDLE_PATH`) or -//! deployment mode, Bundler installs every non-default gem into that -//! path and never loads one from a `gem env` home. A non-default copy -//! there belongs to other projects on the machine, so `apply` leaves -//! it alone. With no other copy the gem is not installed; -//! * a default gem (its spec under `specifications/default/`) is loaded -//! from the system home under any path, so it is still written; +//! deployment mode, Bundler installs every other gem into that path +//! and never loads one from a `gem env` home. A copy there belongs to +//! other projects on the machine, so `apply` leaves it alone. With no +//! other copy, a gem the lock lists is not installed yet (the calm +//! lockfile-only skip), and one it does not list is another project's +//! gem: a skip of its own that names the copy and the `rollback` that +//! drops the record, never a failure; +//! * a default gem (its spec under `specifications/default/`) and +//! Bundler itself are loaded from the gem home they are installed in +//! under any path, so they are still written. A bundled gem (rexml, +//! rake, …) has an ordinary spec and follows the ordinary rule; //! * with no explicit path Bundler installs into and loads from the //! `gem env` homes, so every copy there is written; //! * `rollback` and `remove` find every copy either way: an earlier @@ -225,6 +230,18 @@ fn home_dir(fx: &Fixture) -> PathBuf { fx.project.path().join("gem-home") } +/// The keys of the fixture's `.socket/manifest.json`. +fn manifest_purls(fx: &Fixture) -> Vec { + let manifest: serde_json::Value = serde_json::from_slice( + &std::fs::read(fx.project.path().join(".socket").join("manifest.json")).unwrap(), + ) + .unwrap(); + manifest["patches"] + .as_object() + .map(|patches| patches.keys().cloned().collect()) + .unwrap_or_default() +} + // ── Write scope ───────────────────────────────────────────────────────── /// Explicit path with the gem installed in it, and a same-version copy in @@ -285,12 +302,13 @@ fn explicit_path_human_run_lists_only_the_project_copy() { assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); } -/// Explicit path with nothing installed in it yet (a fresh clone before -/// `bundle install`) and no lock: the home copy is not this project's, so -/// nothing is written and the gem is not installed. As for any all-miss -/// run with no lock evidence, that fails. +/// Explicit path with nothing installed in it, and no lock entry for the +/// gem: the copy in the `gem env` home is another project's. Nothing is +/// written, and the record is a skip of its own that names the copy and +/// the `rollback` that drops the record. It is not "not installed", and +/// it does not fail the run. #[test] -fn explicit_path_with_nothing_installed_reports_not_installed() { +fn explicit_path_with_only_another_projects_copy_is_a_calm_skip() { let fx = build_fixture( Store::ExplicitEmpty, Home::Installed, @@ -300,6 +318,8 @@ fn explicit_path_with_nothing_installed_reports_not_installed() { let (code, stdout, stderr) = run_apply(&fx, &["--json"]); let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); assert_eq!( std::fs::read(&fx.home_file).unwrap(), ORIGINAL, @@ -309,13 +329,67 @@ fn explicit_path_with_nothing_installed_reports_not_installed() { env["summary"]["applied"], 0, "nothing was applied.\nenvelope: {env}" ); + assert!( + find_event(&env, "skipped", NOT_INSTALLED).is_none(), + "the gem is installed, elsewhere.\nenvelope: {env}" + ); + let skip = find_skip_event(&env) + .unwrap_or_else(|| panic!("the copy must be a {SKIP_CODE} skip.\nenvelope: {env}")); + assert_eq!(skip["purl"], QUALIFIED_PURL, "envelope: {env}"); + let reason = skip["reason"].as_str().unwrap_or_default(); + let rollback = format!( + "socket-patch rollback {BASE_PURL} --cwd {}", + fx.project.path().display() + ); + assert!( + reason.contains(&home_dir(&fx).display().to_string()) && reason.contains(&rollback), + "the skip must name the copy and the rollback; got: {reason}" + ); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + stderr.contains(&format!("Warning: {QUALIFIED_PURL}: gem-env home copy at ")) + && stderr.contains("belongs to another project") + && stderr.contains(&rollback), + "stderr={stderr}" + ); + assert!(!stderr.contains("Error:"), "stderr={stderr}"); + assert!( + stdout.contains( + "Summary: 0 of 1 targeted patch applied, 0 already patched, 1 not applicable, \ + 0 not found on disk" + ), + "stdout={stdout}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); + + // `--silent` is errors only, and this is not one. + let (code, stdout, stderr) = run_apply(&fx, &["--silent"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!(format!("{stdout}{stderr}"), ""); +} + +/// The gem in no gem home at all, and in no lock: nothing says where it +/// is, so this stays the all-miss failure of any package that is not +/// installed. +#[test] +fn gem_with_no_copy_anywhere_and_no_lock_entry_still_fails() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + std::fs::remove_dir_all(home_dir(&fx).join("gems").join("rack-3.1.0")).unwrap(); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 1, "envelope: {env}\nstderr:\n{stderr}"); let skip = find_event(&env, "skipped", NOT_INSTALLED) .unwrap_or_else(|| panic!("the gem must be reported as {NOT_INSTALLED}.\nenvelope: {env}")); assert_eq!(skip["purl"], QUALIFIED_PURL, "envelope: {env}"); - assert_eq!( - code, 1, - "an all-miss run with no lock evidence fails.\nenvelope: {env}\nstderr:\n{stderr}" - ); + assert!(find_skip_event(&env).is_none(), "envelope: {env}"); let (code, stdout, stderr) = run_apply(&fx, &[]); assert_eq!(code, 1, "stdout={stdout}\nstderr={stderr}"); @@ -329,7 +403,56 @@ fn explicit_path_with_nothing_installed_reports_not_installed() { ), "stdout={stdout}" ); - assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// The other project's copy beside a gem of this project that is patched: +/// the run still succeeds, the copy has its skip, and nothing is reported +/// as having no installed package. +#[test] +fn another_projects_copy_beside_a_patched_gem_is_a_skip_not_a_warning() { + let fx = build_fixture(Store::Explicit, Home::DefaultGem, ORIGINAL, QUALIFIED_PURL); + // A second record, for a gem only the gem env home holds. + let other = home_dir(&fx) + .join("gems") + .join("thor-1.3.0") + .join("lib") + .join("thor.rb"); + std::fs::create_dir_all(other.parent().unwrap()).unwrap(); + std::fs::write(&other, ORIGINAL).unwrap(); + let patched = patched_bytes(); + write_manifest( + fx.project.path(), + json!({ + QUALIFIED_PURL: patch_record( + "66616c6c-6261-4b63-8368-6f6d65000000", + one_file("lib/rack.rb", ORIGINAL, &patched), + ), + "pkg:gem/thor@1.3.0?platform=ruby": patch_record( + "66616c6c-6261-4b63-8368-6f6d65000001", + one_file("lib/thor.rb", ORIGINAL, &patched), + ), + }), + ); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + stdout.contains( + "Summary: 1 of 2 targeted patches applied, 0 already patched, 1 not applicable, \ + 0 not found on disk" + ), + "stdout={stdout}" + ); + assert!( + stderr.contains("Warning: pkg:gem/thor@1.3.0?platform=ruby: gem-env home copy at "), + "stderr={stderr}" + ); + assert!( + !stderr.contains("had no matching installed package"), + "stderr={stderr}" + ); + assert_eq!(std::fs::read(&other).unwrap(), ORIGINAL); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched); } /// The same fresh clone with a `Gemfile.lock` that resolves the gem: a @@ -453,6 +576,81 @@ fn system_gems_home_copy_is_patched() { assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched_bytes()); } +/// Bundler is never installed into the project's path: the copy that +/// `gem install bundler` put in the gem home, with its spec outside +/// `specifications/default/`, is the one the project runs. `apply` +/// patches it, and `apply --check` judges it: drift before, in sync after. +#[test] +fn bundler_in_the_gem_env_home_is_patched_and_checked() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + let home = home_dir(&fx); + std::fs::remove_dir_all(home.join("gems").join("rack-3.1.0")).unwrap(); + let file = home + .join("gems") + .join("bundler-2.6.9") + .join("lib") + .join("bundler.rb"); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, ORIGINAL).unwrap(); + std::fs::write( + home.join("specifications").join("bundler-2.6.9.gemspec"), + b"", + ) + .unwrap(); + // A gem whose name only starts with `bundler-` is an ordinary gem. + let audit = home + .join("gems") + .join("bundler-audit-0.9.2") + .join("lib") + .join("bundler-audit.rb"); + std::fs::create_dir_all(audit.parent().unwrap()).unwrap(); + std::fs::write(&audit, ORIGINAL).unwrap(); + let patched = patched_bytes(); + const BUNDLER: &str = "pkg:gem/bundler@2.6.9?platform=ruby"; + const AUDIT: &str = "pkg:gem/bundler-audit@0.9.2?platform=ruby"; + write_manifest( + fx.project.path(), + json!({ + BUNDLER: patch_record( + "66616c6c-6261-4b63-8368-6f6d65000002", + one_file("lib/bundler.rb", ORIGINAL, &patched), + ), + AUDIT: patch_record( + "66616c6c-6261-4b63-8368-6f6d65000003", + one_file("lib/bundler-audit.rb", ORIGINAL, &patched), + ), + }), + ); + + let (code, stdout, stderr) = run_apply(&fx, &["--check"]); + assert_eq!( + code, 1, + "the unpatched Bundler is drift.\nstdout={stdout}\nstderr={stderr}" + ); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "envelope: {env}"); + assert_eq!(std::fs::read(&file).unwrap(), patched); + assert_eq!( + std::fs::read(&audit).unwrap(), + ORIGINAL, + "bundler-audit is another project's gem" + ); + let skip = find_skip_event(&env) + .unwrap_or_else(|| panic!("bundler-audit must be a {SKIP_CODE} skip.\nenvelope: {env}")); + assert_eq!(skip["purl"], AUDIT, "envelope: {env}"); + + let (code, stdout, stderr) = run_apply(&fx, &["--check"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); +} + /// A deployment-style install under the default `vendor/bundle`: that /// store is the project's one gem source, so the `gem env` home is not /// searched and its copy is left alone. @@ -520,15 +718,10 @@ fn remove_restores_a_home_copy_an_earlier_run_patched() { ORIGINAL, "the project's copy must be restored.\nenvelope: {env}" ); - let manifest: serde_json::Value = serde_json::from_slice( - &std::fs::read(fx.project.path().join(".socket").join("manifest.json")).unwrap(), - ) - .unwrap(); - assert!( - manifest["patches"] - .as_object() - .is_some_and(|patches| patches.is_empty()), - "the record must be dropped; manifest: {manifest}" + assert_eq!( + manifest_purls(&fx), + Vec::::new(), + "the record must be dropped" ); } From 6e3c83b56b90f8c74c92e76e3f6085ac14b5074b Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 16:42:58 -0500 Subject: [PATCH 09/20] Treat a gem only another project's home holds as not installed in scan and get Two gaps were left after the scan stopped selecting another project's gems. A gem the lock lists, with a copy only in a `gem env` home Bundler does not load, was shown as installed, downloaded and recorded, then reported as not installed by the apply step of the same run, and its recorded variant was picked by hashing the other project's copy. The same gem with no copy at all is lockfile-only: flagged `notInstalled` and skipped before any download. An agent-mode scan now takes the gems `apply` has no copy to write out of the crawl before the lockfile supplement, so both fresh-clone states go down the lockfile-only path and a gem the lock does not list is no candidate. Their purls stay in the prune universe, so a record an earlier release wrote is kept until `rollback` drops it. `get` in agent mode still took such a gem for an installed package: `get ` resolved it from the crawl, and `get ` kept its version when narrowing to what is installed. Both now ask the same question as the scan. An exact purl is not narrowed for any package and is left alone. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/get.rs | 31 +- .../src/commands/scan/discovery.rs | 45 --- .../socket-patch-cli/src/commands/scan/mod.rs | 63 ++-- .../tests/common/gem_env_home.rs | 288 ++++++++++++++ .../tests/get/get_gem_unloaded_homes.rs | 158 ++++++++ crates/socket-patch-cli/tests/get/main.rs | 3 + crates/socket-patch-cli/tests/scan/main.rs | 2 + .../tests/scan/scan_gem_unloaded_homes.rs | 354 ++++++------------ 8 files changed, 638 insertions(+), 306 deletions(-) create mode 100644 crates/socket-patch-cli/tests/common/gem_env_home.rs create mode 100644 crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index 9b758fea19..a4d3213623 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -1044,7 +1044,21 @@ async fn filter_to_installed_purls( .collect() }; let partitioned = partition_purls(&bases, None); - let found = find_packages_for_rollback(&partitioned, &common.crawler_options(), true).await; + let mut found = find_packages_for_rollback(&partitioned, &common.crawler_options(), true).await; + // Agent mode patches installed copies in place: a gem `apply` has no + // copy to write for (another project's, in a `gem env` home Bundler + // does not load this project's gems from) is not installed here, as in + // `scan --mode agent` (#2313). + if mode == super::scan::ScanMode::Agent { + let unloaded = crate::ecosystem_dispatch::gems_apply_never_writes( + found + .iter() + .map(|(purl, path)| (purl.clone(), path.clone())), + &common.crawler_options(), + ) + .await; + found.retain(|purl, _| !unloaded.contains(purl)); + } let mut present: HashSet = found.keys().map(|k| PurlKey::new(k)).collect(); let ctx = super::context::ProjectContext::new(common); @@ -1611,8 +1625,21 @@ pub async fn run(args: GetArgs) -> i32 { // no environment of its own is otherwise crawled only for the // packages it declares. let only = args.common.ecosystems.as_deref().filter(|l| !l.is_empty()); - let (all_packages, _, _) = + let (mut all_packages, _, _) = crawl_ecosystems_for_name(&args.common.crawler_options(), only).await; + // Agent mode patches installed copies in place: a gem `apply` + // has no copy to write for is not installed for this project, + // so its name resolves to nothing (#2313). + if mode == super::scan::ScanMode::Agent { + let unloaded = crate::ecosystem_dispatch::gems_apply_never_writes( + all_packages + .iter() + .map(|pkg| (pkg.purl.clone(), pkg.path.clone())), + &args.common.crawler_options(), + ) + .await; + all_packages.retain(|pkg| !unloaded.contains(&pkg.purl)); + } if all_packages.is_empty() { status.finish(); diff --git a/crates/socket-patch-cli/src/commands/scan/discovery.rs b/crates/socket-patch-cli/src/commands/scan/discovery.rs index 43278377ab..478df431a3 100644 --- a/crates/socket-patch-cli/src/commands/scan/discovery.rs +++ b/crates/socket-patch-cli/src/commands/scan/discovery.rs @@ -61,51 +61,6 @@ pub(crate) struct LockfileSupplement { pub(crate) stale_hub_pins: Vec, } -impl LockfileSupplement { - /// Every purl the project's lockfiles resolve: `entries`, and the - /// gems the Bundler lock holds only as precompiled platform builds, - /// which the inventory leaves out and the lock names all the same. - pub(crate) fn locked_purls(&self) -> impl Iterator { - self.entries - .iter() - .map(|entry| entry.purl.as_str()) - .chain(self.platform_gems.iter().map(String::as_str)) - } -} - -/// `crawled` without the gems an agent-mode scan leaves alone: a gem that -/// `apply` has no copy to write for -/// ([`crate::ecosystem_dispatch::gems_apply_never_writes`]: its every copy -/// sits in a `gem env` home Bundler never loads the project's gems from, -/// so it is another project's) and that the project's lock does not list. -/// Selecting its patch would download and record one the apply step then -/// reports as not installed (#2313). A gem the lock lists stays, so its -/// record is there for the `bundle install` that puts it in the project's -/// path. A supplement (`supplement_purls`) stays too: its path is a -/// placeholder. -pub(crate) async fn without_unloaded_gems( - crawled: Vec, - supplement_purls: &HashSet, - lockfile_only: &LockfileSupplement, - options: &socket_patch_core::crawlers::CrawlerOptions, -) -> Vec { - let locked: HashSet = lockfile_only.locked_purls().map(PurlKey::new).collect(); - let unlisted = crawled - .iter() - .filter(|pkg| { - !supplement_purls.contains(&pkg.purl) && !locked.contains(&PurlKey::new(&pkg.purl)) - }) - .map(|pkg| (pkg.purl.clone(), pkg.path.clone())); - let unloaded = crate::ecosystem_dispatch::gems_apply_never_writes(unlisted, options).await; - if unloaded.is_empty() { - return crawled; - } - crawled - .into_iter() - .filter(|pkg| !unloaded.contains(&pkg.purl)) - .collect() -} - /// Inventory the project's lockfile(s) and fabricate crawl entries for /// dependencies that are not installed. The fabricated `path` is the /// WOULD-BE install dir — every consumer degrades safely on a nonexistent diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 7085143a1e..7dbc063efe 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -2515,6 +2515,29 @@ async fn scan_project( None => crawl.await, }; + // Agent mode patches installed copies in place, and its apply step + // leaves alone a gem copy Bundler never loads for the project (another + // project's gem in a `gem env` home, under an explicit or deployment + // `path`). A gem with no other copy is not installed for this project + // (#2313): it leaves the crawl here, so one the lock lists is found + // again below as lockfile-only, like a gem with no copy at all, and + // one the lock does not list is no candidate. The purls are kept for + // the prune universe: the copies are on disk, and a record an earlier + // release wrote for one must stay until `rollback` restores it. + let unloaded_gems = if apply { + let unloaded = crate::ecosystem_dispatch::gems_apply_never_writes( + all_crawled + .iter() + .map(|pkg| (pkg.purl.clone(), pkg.path.clone())), + &crawler_options, + ) + .await; + all_crawled.retain(|pkg| !unloaded.contains(&pkg.purl)); + unloaded + } else { + HashSet::new() + }; + // Lockfile supplement: dependencies the project's lockfile resolves // that have NO installed copy (fresh clone, partial install). They join // discovery and are flagged "not yet installed". Scoped to the crawled @@ -2614,8 +2637,13 @@ async fn scan_project( // `--package` / PATH filters: prune must judge manifest entries against // the full installed set, or `scan --ecosystems npm --prune` would // delete every other ecosystem's entries. Lockfile-only purls are - // included so a wiped node_modules does not prune them. - let scanned_purls: HashSet = all_crawled.iter().map(|p| p.purl.clone()).collect(); + // included so a wiped node_modules does not prune them, and so are the + // gems an agent run left out of the crawl above. + let scanned_purls: HashSet = all_crawled + .iter() + .map(|p| p.purl.clone()) + .chain(unloaded_gems) + .collect(); // Vendor-ledger purl keys, shared by the prune exemption (a vendored // package's normal state is absent from the crawl) and the @@ -2748,25 +2776,6 @@ async fn scan_project( .filter(|pkg| args.common.purl_ecosystem_selected(&pkg.purl)) .collect(); - // Agent mode patches installed copies in place, and its apply step - // leaves alone a gem copy Bundler never loads for the project (another - // project's gem in a `gem env` home, under an explicit or deployment - // `path`). A gem with no other copy, and not in the lock, is not this - // project's: it is not a candidate (#2313). Strictly AFTER the - // `scanned_purls` capture, so a prune still counts the copy as - // installed and keeps a record an earlier release wrote for it. - let filtered_crawled = if apply { - discovery::without_unloaded_gems( - filtered_crawled, - &supplement_purls, - &lockfile_only, - &crawler_options, - ) - .await - } else { - filtered_crawled - }; - let package_specs: Vec<&String> = args .packages .iter() @@ -4010,9 +4019,15 @@ async fn scan_project( // direct dependencies, so PyPI packages always count. The lockfile // inventory leaves out a gem the Bundler lock holds only as // precompiled platform builds; the lock names it too. - let locked: HashSet = lockfile_only.locked_purls().map(PurlKey::new).collect(); - let complete_locks: HashSet = lockfile_only - .locked_purls() + let locked_purls = || { + lockfile_only + .entries + .iter() + .map(|entry| entry.purl.as_str()) + .chain(lockfile_only.platform_gems.iter().map(String::as_str)) + }; + let locked: HashSet = locked_purls().map(PurlKey::new).collect(); + let complete_locks: HashSet = locked_purls() .filter_map(Ecosystem::from_purl) .filter(|eco| *eco != Ecosystem::Pypi) .collect(); diff --git a/crates/socket-patch-cli/tests/common/gem_env_home.rs b/crates/socket-patch-cli/tests/common/gem_env_home.rs new file mode 100644 index 0000000000..76e4133322 --- /dev/null +++ b/crates/socket-patch-cli/tests/common/gem_env_home.rs @@ -0,0 +1,288 @@ +//! A Ruby project with an explicit Bundler `path`, beside a `gem env` home +//! that a fake `gem` binary reports, and a mock patch API for its gems. +//! For the suites of #2313: which gems agent mode selects and writes when +//! a gem sits in a gem home Bundler does not load the project's gems from. +//! +//! Pulled in per test binary with +//! `#[path = "../common/gem_env_home.rs"] mod gem_env_home;` beside +//! `mod common;`. Unix-only: the fake `gem` is a shell script. + +#![cfg(unix)] +#![allow(dead_code)] + +use std::path::{Path, PathBuf}; + +use base64::Engine; +use wiremock::matchers::{body_string_contains, method, path, path_regex}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +use crate::common::hermetic::{self, Extra}; +use crate::common::{binary, git_sha256, hermetic_command, jvm_env}; + +/// The org of the mock patch API. +pub const ORG: &str = "test-org"; + +/// Stage `/gems/-/lib/.rb` = `bytes` plus the +/// `specifications/` marker of a gem home; returns the staged file. +pub fn stage_gem(home: &Path, name: &str, version: &str, bytes: &[u8]) -> PathBuf { + let file = home + .join("gems") + .join(format!("{name}-{version}")) + .join("lib") + .join(format!("{name}.rb")); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, bytes).unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + file +} + +/// Make the staged `-` of `home` one of Ruby's default +/// gems: its spec under `specifications/default/`. +pub fn mark_default_gem(home: &Path, name: &str, version: &str) { + let specs = home.join("specifications").join("default"); + std::fs::create_dir_all(&specs).unwrap(); + std::fs::write(specs.join(format!("{name}-{version}.gemspec")), b"").unwrap(); +} + +/// The project: a `Gemfile`, a `Gemfile.lock`, the Bundler path +/// `bundle-store` (exported as `BUNDLE_PATH` by [`GemProject::run`]) and +/// the `gem env` home `gem-home`. +pub struct GemProject { + dir: tempfile::TempDir, +} + +impl GemProject { + /// `lock` is the `specs:` lines of the `Gemfile.lock` + /// (`"rack (3.1.0)"`). Neither the path nor the home holds a gem yet. + pub fn new(lock: &[&str]) -> Self { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::write(root.join("Gemfile"), "source \"https://rubygems.org\"\n").unwrap(); + let specs: String = lock.iter().map(|spec| format!(" {spec}\n")).collect(); + std::fs::write( + root.join("Gemfile.lock"), + format!( + "GEM\n remote: https://rubygems.org/\n specs:\n{specs}\n\ + PLATFORMS\n ruby\n\nDEPENDENCIES\n\nBUNDLED WITH\n 2.5.22\n" + ), + ) + .unwrap(); + let home = root.join("gem-home"); + std::fs::create_dir_all(home.join("gems")).unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + let bin_dir = root.join("fake-bin"); + std::fs::create_dir_all(&bin_dir).unwrap(); + let gem = bin_dir.join("gem"); + std::fs::write( + &gem, + format!( + "#!/bin/sh\nif [ \"$1\" = env ] && [ \"$2\" = gemdir ]; then\n printf '%s\\n' \"{}\"\n exit 0\nfi\nexit 1\n", + home.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&gem, std::fs::Permissions::from_mode(0o755)).unwrap(); + Self { dir } + } + + pub fn root(&self) -> &Path { + self.dir.path() + } + + /// The `gem env` home: another project's gems, Ruby's default gems, + /// and Bundler. + pub fn home(&self) -> PathBuf { + self.root().join("gem-home") + } + + /// The project's Bundler `path`. + pub fn store(&self) -> PathBuf { + self.root().join("bundle-store") + } + + /// Run `socket-patch --ecosystems gem --cwd ` + /// in the hermetic env with the ambient `BUNDLE_*` scrubbed, PATH = the + /// fake-gem bin dir only, and `BUNDLE_PATH` naming the store. + pub fn run(&self, command: &[&str], args: &[&str]) -> (i32, String, String) { + let mut cmd = hermetic_command(&binary()); + cmd.args(command) + .args(["--ecosystems", "gem", "--cwd"]) + .arg(self.root()) + .args(args); + jvm_env::isolate_cli(&mut cmd); + hermetic::scrub_extra(&mut cmd, &[Extra::Bundle]); + cmd.env("PATH", self.root().join("fake-bin")) + .env("BUNDLE_PATH", self.store()); + let out = cmd.output().expect("run socket-patch"); + ( + out.status.code().unwrap_or(-1), + String::from_utf8_lossy(&out.stdout).to_string(), + String::from_utf8_lossy(&out.stderr).to_string(), + ) + } + + /// The keys of `.socket/manifest.json`, sorted; empty with no manifest. + pub fn manifest_purls(&self) -> Vec { + let path = self.root().join(".socket").join("manifest.json"); + let Ok(raw) = std::fs::read(&path) else { + return Vec::new(); + }; + let manifest: serde_json::Value = serde_json::from_slice(&raw).unwrap(); + let mut purls: Vec = manifest["patches"] + .as_object() + .map(|patches| patches.keys().cloned().collect()) + .unwrap_or_default(); + purls.sort(); + purls + } +} + +/// The flags pointing a run at the mock API with a fake token and [`ORG`]. +pub fn api_args(api_url: &str) -> Vec<&str> { + vec![ + "--api-url", + api_url, + "--api-token", + "fake-token-for-test", + "--org", + ORG, + ] +} + +/// One free patch of `lib/.rb` in ` `. +pub struct GemPatch { + pub name: &'static str, + pub version: &'static str, + pub uuid: &'static str, + /// The advisory the patch fixes (`by-ghsa/` serves it). + pub ghsa: &'static str, +} + +impl GemPatch { + /// The file as published. + pub fn before(&self) -> Vec { + format!("module {}\n VERSION = 'VULNERABLE'\nend\n", self.name).into_bytes() + } + + /// The file as patched. + pub fn after(&self) -> Vec { + let mut bytes = self.before(); + bytes.extend_from_slice(b"# SOCKET-PATCHED\n"); + bytes + } + + /// `pkg:gem/@`. + pub fn purl(&self) -> String { + format!("pkg:gem/{}@{}", self.name, self.version) + } + + /// The record's key: [`Self::purl`] with `?platform=ruby`. + pub fn record(&self) -> String { + format!("{}?platform=ruby", self.purl()) + } + + fn search_result(&self) -> serde_json::Value { + serde_json::json!({ + "uuid": self.uuid, "purl": self.record(), "publishedAt": "2024-01-01T00:00:00Z", + "description": self.name, "license": "MIT", "tier": "free", "vulnerabilities": {}, + }) + } + + /// Mount the patch API for this patch: the batch lookup offers it only + /// to a query that names the gem (any other query finds nothing), and + /// the by-package search, the advisory search and the view serve it. + pub async fn mount(&self, mock: &MockServer) { + let found = |patches: serde_json::Value| { + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": patches, + "canAccessPaidPatches": false, + })) + }; + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .and(body_string_contains(self.purl())) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [{ + "purl": self.purl(), + "patches": [{ + "uuid": self.uuid, "purl": self.record(), "tier": "free", + "cveIds": [], "ghsaIds": [self.ghsa], "severity": "high", + "title": self.name, + }], + }], + "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(mock) + .await; + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [], + "canAccessPaidPatches": false, + }))) + .mount(mock) + .await; + Mock::given(method("GET")) + .and(path_regex(format!( + "^/v0/orgs/{ORG}/patches/by-package/.*{}.*$", + self.name + ))) + .respond_with(found(serde_json::json!([self.search_result()]))) + .mount(mock) + .await; + Mock::given(method("GET")) + .and(path(format!( + "/v0/orgs/{ORG}/patches/by-ghsa/{}", + self.ghsa + ))) + .respond_with(found(serde_json::json!([self.search_result()]))) + .mount(mock) + .await; + let b64 = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes); + let file = format!("lib/{}.rb", self.name); + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{}", self.uuid))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "uuid": self.uuid, + "purl": self.record(), + "publishedAt": "2024-01-01T00:00:00Z", + "files": { + file: { + "beforeHash": git_sha256(&self.before()), + "afterHash": git_sha256(&self.after()), + "blobContent": b64(&self.after()), + "beforeBlobContent": b64(&self.before()), + } + }, + "vulnerabilities": {}, + "description": self.name, + "license": "MIT", + "tier": "free", + }))) + .mount(mock) + .await; + } +} + +/// Every request the mock received. +pub async fn requests(mock: &MockServer) -> Vec { + mock.received_requests().await.unwrap_or_default() +} + +/// Whether some batch lookup named `purl`. +pub async fn batch_queried(mock: &MockServer, purl: &str) -> bool { + requests(mock).await.iter().any(|r| { + r.url.path().ends_with("/patches/batch") && String::from_utf8_lossy(&r.body).contains(purl) + }) +} + +/// How many times the view of the patch `uuid` was fetched: the download. +pub async fn view_gets(mock: &MockServer, uuid: &str) -> usize { + requests(mock) + .await + .iter() + .filter(|r| r.url.path().ends_with(&format!("/patches/view/{uuid}"))) + .count() +} diff --git a/crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs b/crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs new file mode 100644 index 0000000000..eda8ed7d92 --- /dev/null +++ b/crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs @@ -0,0 +1,158 @@ +//! `get` in agent mode and a gem that only a `gem env` home holds (#2313). +//! +//! Under an explicit Bundler `path` a gem in the system gems is another +//! project's: Bundler never loads it for this one, and the apply step +//! leaves it alone. So `get` must not take it for an installed package: +//! +//! * a package NAME resolves among the installed packages, and such a +//! gem is not one of them; +//! * an ADVISORY is narrowed to the versions installed here, and such a +//! gem's version is not one of them: a calm `package_not_installed` +//! skip, as for a version that is installed nowhere; +//! * an exact PURL is never narrowed, for any package: its patch is +//! recorded, and the apply step says where the gem is and why it was +//! left alone; +//! * Bundler itself is loaded from the gem home it is installed in under +//! any path, so its name still resolves and it is patched there. +//! +//! Unix-only: the `gem env` home comes from a fake `gem` binary on PATH. + +#![cfg(unix)] + +use std::path::PathBuf; + +use wiremock::MockServer; + +use crate::common::envelope::{event_purls, has_event, parse_json_envelope}; +use crate::gem_env_home::{api_args, stage_gem, view_gets, GemPatch, GemProject}; + +const RACK: GemPatch = GemPatch { + name: "rack", + version: "3.1.0", + uuid: "11111111-1111-4111-8111-111111111111", + ghsa: "GHSA-aaaa-bbbb-cccc", +}; + +const BUNDLER: GemPatch = GemPatch { + name: "bundler", + version: "2.6.9", + uuid: "22222222-2222-4222-8222-222222222222", + ghsa: "GHSA-dddd-eeee-ffff", +}; + +/// `get --mode agent ` against the mock API. +fn get( + project: &GemProject, + api_url: &str, + identifier: &str, + extra: &[&str], +) -> (i32, String, String) { + let mut args = vec!["--mode", "agent", "--yes"]; + args.extend(api_args(api_url)); + args.extend_from_slice(extra); + project.run(&["get", identifier], &args) +} + +/// A project whose own gem is installed in its path and whose lock lists +/// nothing else, with `patch`'s gem, as published, only in the `gem env` +/// home. Returns the home copy's file. +fn project_beside(patch: &GemPatch) -> (GemProject, PathBuf) { + let project = GemProject::new(&["colorize (1.1.0)"]); + stage_gem( + &project.store(), + "colorize", + "1.1.0", + b"module Colorize\nend\n", + ); + let file = stage_gem(&project.home(), patch.name, patch.version, &patch.before()); + (project, file) +} + +/// `get rack`, with `rack` only in the gem home: the name matches no +/// package of this project. Nothing is downloaded or recorded, exit 0. +#[tokio::test] +async fn name_of_a_foreign_gem_matches_no_installed_package() { + let (project, home_file) = project_beside(&RACK); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let (code, stdout, stderr) = get(&project, &mock.uri(), "rack", &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + stdout.contains("No packages matching \"rack\" found."), + "stdout={stdout}" + ); + assert_eq!(view_gets(&mock, RACK.uuid).await, 0); + assert_eq!(project.manifest_purls(), Vec::::new()); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); +} + +/// `get ` for an advisory patched in `rack 3.1.0`, with that version +/// only in the gem home: narrowed away as not installed here, the calm +/// skip a version installed nowhere gets. No download, no record, exit 0. +#[tokio::test] +async fn advisory_for_a_foreign_gem_is_narrowed_as_not_installed() { + let (project, home_file) = project_beside(&RACK); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let (code, stdout, stderr) = get(&project, &mock.uri(), RACK.ghsa, &["--json"]); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert!( + has_event(&env, "skipped", "package_not_installed", &RACK.record()), + "envelope: {env}" + ); + assert_eq!(view_gets(&mock, RACK.uuid).await, 0); + assert_eq!(project.manifest_purls(), Vec::::new()); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); + + // The version installed in no gem home at all reads the same. + std::fs::remove_dir_all(project.home().join("gems").join("rack-3.1.0")).unwrap(); + let (again, stdout, stderr) = get(&project, &mock.uri(), RACK.ghsa, &["--json"]); + let absent = parse_json_envelope(&stdout); + assert_eq!(again, 0, "envelope: {absent}\nstderr:\n{stderr}"); + assert_eq!(absent["events"], env["events"]); +} + +/// `get pkg:gem/rack@3.1.0`: an exact purl is not narrowed to what is +/// installed. The patch is recorded, and the apply step leaves the other +/// project's copy alone with the skip that names it, exit 0. +#[tokio::test] +async fn exact_purl_of_a_foreign_gem_is_recorded_and_its_copy_left_alone() { + let (project, home_file) = project_beside(&RACK); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let (code, stdout, stderr) = get(&project, &mock.uri(), &RACK.purl(), &["--json"]); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert!( + has_event(&env, "skipped", "gem_fallback_home_skipped", &RACK.record()), + "envelope: {env}" + ); + assert!(event_purls(&env, "applied").is_empty(), "envelope: {env}"); + assert_eq!(project.manifest_purls(), vec![RACK.record()]); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); +} + +/// `get bundler`: Bundler is never installed into the project's path. The +/// copy in the gem home is the one the project runs, so the name resolves +/// to it and it is patched. +#[tokio::test] +async fn name_of_bundler_resolves_to_the_gem_home_copy() { + let (project, home_file) = project_beside(&BUNDLER); + let mock = MockServer::start().await; + BUNDLER.mount(&mock).await; + + let (code, stdout, stderr) = get(&project, &mock.uri(), "bundler", &["--json"]); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + event_purls(&env, "applied"), + vec![BUNDLER.record()], + "envelope: {env}" + ); + assert_eq!(project.manifest_purls(), vec![BUNDLER.record()]); + assert_eq!(std::fs::read(&home_file).unwrap(), BUNDLER.after()); +} diff --git a/crates/socket-patch-cli/tests/get/main.rs b/crates/socket-patch-cli/tests/get/main.rs index e5da1bf593..10f4b923f2 100644 --- a/crates/socket-patch-cli/tests/get/main.rs +++ b/crates/socket-patch-cli/tests/get/main.rs @@ -6,6 +6,8 @@ #[path = "../common/mod.rs"] mod common; +#[path = "../common/gem_env_home.rs"] +mod gem_env_home; #[path = "../npm_e2e_common/manifestless.rs"] mod npm_e2e_common; #[path = "../prebuilt_common/mod.rs"] @@ -24,6 +26,7 @@ mod get_edge_cases_e2e; mod get_envelope_shape; mod get_failure_paths; mod get_fixture; +mod get_gem_unloaded_homes; mod get_invariants; mod get_modes_e2e; mod get_nested_apply_api_flags_e2e; diff --git a/crates/socket-patch-cli/tests/scan/main.rs b/crates/socket-patch-cli/tests/scan/main.rs index 13ca652ca0..00a6db5cf4 100644 --- a/crates/socket-patch-cli/tests/scan/main.rs +++ b/crates/socket-patch-cli/tests/scan/main.rs @@ -8,6 +8,8 @@ #[path = "../common/mod.rs"] mod common; +#[path = "../common/gem_env_home.rs"] +mod gem_env_home; #[path = "../prebuilt_common/mod.rs"] mod prebuilt_common; #[path = "../common/pty_io.rs"] diff --git a/crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs b/crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs index 548ca52cd9..6053985cfb 100644 --- a/crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs +++ b/crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs @@ -4,214 +4,75 @@ //! that path, and a gem in the system gems (an rbenv or asdf home, //! `~/.gem`) is another project's: Bundler never loads it for this one, //! and the apply step leaves it alone. The scan's crawl still finds it, so -//! the scan must not select it either: its patch would be downloaded and -//! recorded for the apply step to report as not installed, which fails a -//! run that matched nothing else. +//! the scan must treat it as not installed for this project. Selecting it +//! would download and record a patch the apply step then writes nowhere. //! //! * a gem the project's lock does not list is no candidate: it is not //! queried, nothing is downloaded or recorded, and the run exits 0; -//! * a gem the lock lists stays one (a fresh clone before -//! `bundle install`): its record is kept and the apply step reports it -//! as not installed on this host, exit 0; -//! * a default gem (its spec under `specifications/default/`) is loaded -//! from the system home under any path, so it is still patched there. +//! * a gem the lock lists is lockfile-only (a fresh clone before +//! `bundle install`), exactly as when no gem home holds it: reported +//! as not installed, and skipped before any download; +//! * a default gem (its spec under `specifications/default/`) and +//! Bundler itself are loaded from the gem home they are installed in +//! under any path, so they are still selected and patched there. //! //! Unix-only: the `gem env` home comes from a fake `gem` binary on PATH. #![cfg(unix)] -use std::path::{Path, PathBuf}; +use wiremock::MockServer; -use base64::Engine; -use wiremock::matchers::{body_string_contains, method, path, path_regex}; -use wiremock::{Mock, MockServer, ResponseTemplate}; - -use super::scan_fixture::{api_args, batch_bodies, mount_empty_batch, recorded, ORG_SLUG, UUID}; use crate::common::envelope::{event_purls, has_event, parse_json_envelope}; -use crate::common::hermetic::{self, Extra}; -use crate::common::{binary, git_sha256, hermetic_command, jvm_env}; - -const RACK: &str = "pkg:gem/rack@3.1.0"; -const RACK_RUBY: &str = "pkg:gem/rack@3.1.0?platform=ruby"; - -const ORIGINAL: &[u8] = b"module Rack\n VERSION = 'VULNERABLE'\nend\n"; -const PATCHED: &[u8] = b"module Rack\n VERSION = 'VULNERABLE'\nend\n# SOCKET-PATCHED\n"; - -/// Stage `/gems/-/lib/.rb` = `bytes` plus the -/// `specifications/` marker of a gem home; returns the staged file. -fn stage_gem(home: &Path, name: &str, version: &str, bytes: &[u8]) -> PathBuf { - let file = home - .join("gems") - .join(format!("{name}-{version}")) - .join("lib") - .join(format!("{name}.rb")); - std::fs::create_dir_all(file.parent().unwrap()).unwrap(); - std::fs::write(&file, bytes).unwrap(); - std::fs::create_dir_all(home.join("specifications")).unwrap(); - file -} - -struct Fixture { - project: tempfile::TempDir, - /// `rack-3.1.0/lib/rack.rb` in the `gem env` home. - home_file: PathBuf, -} - -/// A project whose Bundler `path` is `bundle-store` (exported as -/// `BUNDLE_PATH` by [`scan`]), with `rack 3.1.0` in the `gem env` home -/// `gem-home` that a fake `gem` reports. `lock` is the `specs:` lines of -/// its `Gemfile.lock`. -fn build_fixture(lock: &[&str]) -> Fixture { - use std::os::unix::fs::PermissionsExt; - let project = tempfile::tempdir().unwrap(); - let root = project.path(); - std::fs::write(root.join("Gemfile"), "source \"https://rubygems.org\"\n").unwrap(); - let specs: String = lock.iter().map(|spec| format!(" {spec}\n")).collect(); - std::fs::write( - root.join("Gemfile.lock"), - format!( - "GEM\n remote: https://rubygems.org/\n specs:\n{specs}\n\ - PLATFORMS\n ruby\n\nDEPENDENCIES\n\nBUNDLED WITH\n 2.5.22\n" - ), - ) - .unwrap(); - - let home = root.join("gem-home"); - let home_file = stage_gem(&home, "rack", "3.1.0", ORIGINAL); - - let bin_dir = root.join("fake-bin"); - std::fs::create_dir_all(&bin_dir).unwrap(); - let gem = bin_dir.join("gem"); - std::fs::write( - &gem, - format!( - "#!/bin/sh\nif [ \"$1\" = env ] && [ \"$2\" = gemdir ]; then\n printf '%s\\n' \"{}\"\n exit 0\nfi\nexit 1\n", - home.display() - ), - ) - .unwrap(); - std::fs::set_permissions(&gem, std::fs::Permissions::from_mode(0o755)).unwrap(); - Fixture { project, home_file } -} - -/// The patch API: `rack 3.1.0` has one free patch, offered only to a batch -/// query that names the gem. Any other query finds nothing. -async fn mount_rack_patch(mock: &MockServer) { - Mock::given(method("POST")) - .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch"))) - .and(body_string_contains(RACK)) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "packages": [{ - "purl": RACK, - "patches": [{ - "uuid": UUID, "purl": RACK_RUBY, "tier": "free", - "cveIds": [], "ghsaIds": [], "severity": "high", "title": "rack", - }], - }], - "canAccessPaidPatches": false, - }))) - .with_priority(1) - .mount(mock) - .await; - mount_empty_batch(mock).await; - Mock::given(method("GET")) - .and(path_regex(format!( - "^/v0/orgs/{ORG_SLUG}/patches/by-package/.+$" - ))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "patches": [{ - "uuid": UUID, "purl": RACK_RUBY, "publishedAt": "2024-01-01T00:00:00Z", - "description": "rack", "license": "MIT", "tier": "free", "vulnerabilities": {}, - }], - "canAccessPaidPatches": false, - }))) - .mount(mock) - .await; - let b64 = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes); - Mock::given(method("GET")) - .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/view/{UUID}"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "uuid": UUID, - "purl": RACK_RUBY, - "publishedAt": "2024-01-01T00:00:00Z", - "files": { - "lib/rack.rb": { - "beforeHash": git_sha256(ORIGINAL), - "afterHash": git_sha256(PATCHED), - "blobContent": b64(PATCHED), - "beforeBlobContent": b64(ORIGINAL), - } - }, - "vulnerabilities": {}, - "description": "rack", - "license": "MIT", - "tier": "free", - }))) - .mount(mock) - .await; -} - -/// Run `socket-patch --ecosystems gem --cwd ` in -/// the hermetic env with the ambient `BUNDLE_*` scrubbed, PATH = the -/// fake-gem bin dir only, and `BUNDLE_PATH` naming the project's store. -fn run(fx: &Fixture, command: &str, args: &[&str]) -> (i32, String, String) { - let root = fx.project.path(); - let mut cmd = hermetic_command(&binary()); - cmd.arg(command) - .args(["--ecosystems", "gem", "--cwd"]) - .arg(root) - .args(args); - jvm_env::isolate_cli(&mut cmd); - hermetic::scrub_extra(&mut cmd, &[Extra::Bundle]); - cmd.env("PATH", root.join("fake-bin")) - .env("BUNDLE_PATH", root.join("bundle-store")); - let out = cmd.output().expect("run socket-patch"); - ( - out.status.code().unwrap_or(-1), - String::from_utf8_lossy(&out.stdout).to_string(), - String::from_utf8_lossy(&out.stderr).to_string(), - ) -} +use crate::gem_env_home::{ + api_args, batch_queried, mark_default_gem, stage_gem, view_gets, GemPatch, GemProject, +}; + +const RACK: GemPatch = GemPatch { + name: "rack", + version: "3.1.0", + uuid: "11111111-1111-4111-8111-111111111111", + ghsa: "GHSA-aaaa-bbbb-cccc", +}; + +const BUNDLER: GemPatch = GemPatch { + name: "bundler", + version: "2.6.9", + uuid: "22222222-2222-4222-8222-222222222222", + ghsa: "GHSA-dddd-eeee-ffff", +}; /// `scan --mode agent ` against the mock API. -fn scan(fx: &Fixture, api_url: &str, extra: &[&str]) -> (i32, String, String) { +fn scan(project: &GemProject, api_url: &str, extra: &[&str]) -> (i32, String, String) { let mut args = vec!["--mode", "agent"]; args.extend(api_args(api_url)); args.extend_from_slice(extra); - run(fx, "scan", &args) + project.run(&["scan"], &args) } -fn manifest_purls(fx: &Fixture) -> Vec { - let path = fx.project.path().join(".socket").join("manifest.json"); - let Ok(raw) = std::fs::read(&path) else { - return Vec::new(); - }; - let manifest: serde_json::Value = serde_json::from_slice(&raw).unwrap(); - manifest["patches"] - .as_object() - .map(|patches| patches.keys().cloned().collect()) - .unwrap_or_default() -} - -async fn queried_rack(mock: &MockServer) -> bool { - batch_bodies(&recorded(mock).await) - .iter() - .any(|body| body.contains(RACK)) +/// A project whose own gem is installed in its path, with `patch`'s gem, +/// as published, only in the `gem env` home. Returns the home copy's file. +fn project_beside(patch: &GemPatch, lock: &[&str]) -> (GemProject, std::path::PathBuf) { + let project = GemProject::new(lock); + stage_gem( + &project.store(), + "colorize", + "1.1.0", + b"module Colorize\nend\n", + ); + let file = stage_gem(&project.home(), patch.name, patch.version, &patch.before()); + (project, file) } -/// The project's own gem is installed in its path, and `rack` is only in -/// the `gem env` home and not in the lock: another project's copy. The -/// scan does not ask about it, downloads and records nothing, and exits 0; -/// so does the `apply` after it. +/// `rack` is only in the `gem env` home and not in the lock: another +/// project's copy. The scan does not ask about it, downloads and records +/// nothing, and exits 0; so does the `apply` after it. #[tokio::test] async fn foreign_gem_in_a_gem_env_home_is_not_selected() { - let fx = build_fixture(&["colorize (1.1.0)"]); - let store = fx.project.path().join("bundle-store"); - stage_gem(&store, "colorize", "1.1.0", b"module Colorize\nend\n"); + let (project, home_file) = project_beside(&RACK, &["colorize (1.1.0)"]); let mock = MockServer::start().await; - mount_rack_patch(&mock).await; + RACK.mount(&mock).await; - let (code, stdout, stderr) = scan(&fx, &mock.uri(), &["--json"]); + let (code, stdout, stderr) = scan(&project, &mock.uri(), &["--json"]); let env = parse_json_envelope(&stdout); assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); assert_eq!(env["status"], "success", "envelope: {env}"); @@ -220,37 +81,35 @@ async fn foreign_gem_in_a_gem_env_home_is_not_selected() { "only the project's own gem counts.\nenvelope: {env}" ); assert!( - !stdout.contains(RACK), + !stdout.contains(&RACK.purl()), "the envelope must not name the foreign gem.\nenvelope: {env}" ); - let bodies = batch_bodies(&recorded(&mock).await); assert!( - bodies.iter().any(|body| body.contains("colorize")), - "the project's own gem is still scanned; batch bodies: {bodies:?}" + batch_queried(&mock, "colorize").await, + "the project's own gem is still scanned" ); assert!( - !bodies.iter().any(|body| body.contains(RACK)), - "the foreign gem must not be queried; batch bodies: {bodies:?}" + !batch_queried(&mock, &RACK.purl()).await, + "the foreign gem must not be queried" ); - assert_eq!(manifest_purls(&fx), Vec::::new()); - assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); + assert_eq!(view_gets(&mock, RACK.uuid).await, 0); + assert_eq!(project.manifest_purls(), Vec::::new()); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); - let (code, stdout, stderr) = run(&fx, "apply", &["--offline"]); + let (code, stdout, stderr) = project.run(&["apply"], &["--offline"]); assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); - assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); } /// The human run of the same project: no error, no failed apply, and /// nothing about the foreign gem. #[tokio::test] async fn foreign_gem_in_a_gem_env_home_leaves_the_human_run_clean() { - let fx = build_fixture(&["colorize (1.1.0)"]); - let store = fx.project.path().join("bundle-store"); - stage_gem(&store, "colorize", "1.1.0", b"module Colorize\nend\n"); + let (project, home_file) = project_beside(&RACK, &["colorize (1.1.0)"]); let mock = MockServer::start().await; - mount_rack_patch(&mock).await; + RACK.mount(&mock).await; - let (code, stdout, stderr) = scan(&fx, &mock.uri(), &[]); + let (code, stdout, stderr) = scan(&project, &mock.uri(), &[]); let out = format!("{stdout}{stderr}"); assert_eq!(code, 0, "output={out}"); assert!( @@ -261,41 +120,52 @@ async fn foreign_gem_in_a_gem_env_home_leaves_the_human_run_clean() { !out.contains("rack") && !out.contains("Error:"), "output={out}" ); - assert!(!queried_rack(&mock).await); - assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); + assert!(!batch_queried(&mock, &RACK.purl()).await); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); } /// A fresh clone before `bundle install`: the lock lists `rack`, the path /// holds nothing yet, and the `gem env` home has the same version. The -/// gem is the project's, so its patch is still selected and recorded; the -/// apply step writes nothing and reports it as not installed on this host. +/// home copy is not the project's, so the gem is lockfile-only, as when no +/// gem home holds it: reported as not installed, with no download and no +/// record, exit 0. #[tokio::test] -async fn locked_gem_not_installed_yet_keeps_its_record() { - let fx = build_fixture(&["rack (3.1.0)"]); +async fn locked_gem_with_only_a_foreign_copy_is_lockfile_only() { + let project = GemProject::new(&["rack (3.1.0)"]); + let home_file = stage_gem(&project.home(), RACK.name, RACK.version, &RACK.before()); let mock = MockServer::start().await; - mount_rack_patch(&mock).await; + RACK.mount(&mock).await; - let (code, stdout, stderr) = scan(&fx, &mock.uri(), &["--json"]); + let (code, stdout, stderr) = scan(&project, &mock.uri(), &["--json"]); let env = parse_json_envelope(&stdout); assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); assert_eq!(env["status"], "success", "envelope: {env}"); - assert!(queried_rack(&mock).await, "the locked gem is a candidate"); assert!( - has_event(&env, "skipped", "package_not_installed", RACK_RUBY), - "envelope: {env}" + batch_queried(&mock, &RACK.purl()).await, + "the locked gem is still looked up" ); - assert_eq!(env["summary"]["applied"], 0, "envelope: {env}"); - assert_eq!(manifest_purls(&fx), vec![RACK_RUBY.to_string()]); - assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); - - // The `apply` a later run does is the same calm skip. - let (code, stdout, stderr) = run(&fx, "apply", &["--offline"]); - assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); assert!( - stderr.contains("not installed on this host (resolved by the project lockfile; skipped)"), - "stderr={stderr}" + has_event(&env, "skipped", "package_not_installed", &RACK.record()), + "envelope: {env}" + ); + assert_eq!( + view_gets(&mock, RACK.uuid).await, + 0, + "nothing is downloaded for a gem that is not installed.\nenvelope: {env}" ); - assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); + assert_eq!(project.manifest_purls(), Vec::::new()); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); + + // The same project with no copy in any gem home reports the same. + std::fs::remove_dir_all(project.home().join("gems").join("rack-3.1.0")).unwrap(); + let (again, stdout, stderr) = scan(&project, &mock.uri(), &["--json"]); + let without = parse_json_envelope(&stdout); + assert_eq!(again, 0, "envelope: {without}\nstderr:\n{stderr}"); + assert_eq!( + without["events"], env["events"], + "both fresh-clone states report the same events" + ); + assert_eq!(without["scannedPackages"], env["scannedPackages"]); } /// A default gem the lock does not list is still a candidate: Bundler @@ -303,26 +173,40 @@ async fn locked_gem_not_installed_yet_keeps_its_record() { /// patches it there. #[tokio::test] async fn default_gem_in_a_gem_env_home_is_still_patched() { - let fx = build_fixture(&["colorize (1.1.0)"]); - let default_specs = fx - .project - .path() - .join("gem-home") - .join("specifications") - .join("default"); - std::fs::create_dir_all(&default_specs).unwrap(); - std::fs::write(default_specs.join("rack-3.1.0.gemspec"), b"").unwrap(); + let (project, home_file) = project_beside(&RACK, &["colorize (1.1.0)"]); + mark_default_gem(&project.home(), RACK.name, RACK.version); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let (code, stdout, stderr) = scan(&project, &mock.uri(), &["--json"]); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + event_purls(&env, "applied"), + vec![RACK.record()], + "envelope: {env}" + ); + assert_eq!(project.manifest_purls(), vec![RACK.record()]); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.after()); +} + +/// Bundler is never installed into the project's path, and the lock names +/// it only under `BUNDLED WITH`: the copy `gem install bundler` put in the +/// gem home is the one the project runs, so it is selected and patched. +#[tokio::test] +async fn bundler_in_a_gem_env_home_is_still_patched() { + let (project, home_file) = project_beside(&BUNDLER, &["colorize (1.1.0)"]); let mock = MockServer::start().await; - mount_rack_patch(&mock).await; + BUNDLER.mount(&mock).await; - let (code, stdout, stderr) = scan(&fx, &mock.uri(), &["--json"]); + let (code, stdout, stderr) = scan(&project, &mock.uri(), &["--json"]); let env = parse_json_envelope(&stdout); assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); assert_eq!( event_purls(&env, "applied"), - vec![RACK_RUBY.to_string()], + vec![BUNDLER.record()], "envelope: {env}" ); - assert_eq!(manifest_purls(&fx), vec![RACK_RUBY.to_string()]); - assert_eq!(std::fs::read(&fx.home_file).unwrap(), PATCHED); + assert_eq!(project.manifest_purls(), vec![BUNDLER.record()]); + assert_eq!(std::fs::read(&home_file).unwrap(), BUNDLER.after()); } From 1b52b44ea589d5a08e65d97ecebe40ea501ad72b Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 16:42:58 -0500 Subject: [PATCH 10/20] Leave another project's untouched gem copy out of rollback `rollback` and `remove` resolve gem copies without the rule `apply` follows, so that a copy an earlier release patched in a `gem env` home stays restorable. That also made them judge a copy `apply` never wrote: one holding neither side of the patch (another project's edit, or another build) failed the rollback with `hash_mismatch`, and `apply` no longer says anything about such a copy. It also meant the `rollback` that `apply` now names for another project's gem failed on exactly those copies. A copy that Bundler does not load for the project and that holds nothing of the patch is now left out of the rollback targets, whatever it holds. One that holds the patch stays, under every record of its release, so the variant narrowing still sees it. With no copy left the record is dropped as for a package that is not installed. The patched-content test is the one `patched_in_other_scope` already used, lifted into `copy_holds_patch`. Co-Authored-By: Claude Fable 5.2 --- .../socket-patch-cli/src/commands/rollback.rs | 96 +++++++++++++++---- .../apply/in_process_gem_fallback_home.rs | 62 +++++++++++- 2 files changed, 139 insertions(+), 19 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index 1d045b4b2f..ffe76c7186 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -361,34 +361,89 @@ async fn patched_in_other_scope( let (Some(record), Some(paths)) = (manifest.patches.get(purl), found.get(purl)) else { continue; }; - 'copies: for path in paths { + for path in paths { // Both scopes can resolve to one tree (a `--cwd` inside the // global root): this run already verified that copy. if this_scope.contains(path.to_string_lossy().as_ref()) { continue; } - for (file, info) in &record.files { - let v = verify_file_rollback(path, file, info, &blobs).await; - // A file that is there but cannot be hashed may still hold - // the patched bytes: keep the record rather than strand it. - let unverifiable = v.current_hash.is_none() - && v.status != VerifyRollbackStatus::AlreadyOriginal - && !v.is_absent(); - // `Ready` also covers npm's LF-shebang form of a patched - // bin, whose hash is not the afterHash. - if unverifiable - || v.status == VerifyRollbackStatus::Ready - || v.current_hash.as_deref() == Some(info.after_hash.as_str()) - { - patched.push((purl.clone(), path.clone())); - break 'copies; - } + if copy_holds_patch(path, record, &blobs).await { + patched.push((purl.clone(), path.clone())); + break; } } } patched } +/// Whether some file of `record` in the copy at `path` still holds the +/// patch's afterHash content, or cannot be read to tell. +async fn copy_holds_patch(path: &Path, record: &PatchRecord, blobs: &Path) -> bool { + for (file, info) in &record.files { + let v = verify_file_rollback(path, file, info, blobs).await; + // A file that is there but cannot be hashed may still hold + // the patched bytes: keep the record rather than strand it. + let unverifiable = v.current_hash.is_none() + && v.status != VerifyRollbackStatus::AlreadyOriginal + && !v.is_absent(); + // `Ready` also covers npm's LF-shebang form of a patched + // bin, whose hash is not the afterHash. + if unverifiable + || v.status == VerifyRollbackStatus::Ready + || v.current_hash.as_deref() == Some(info.after_hash.as_str()) + { + return true; + } + } + false +} + +/// Drop from `copies` the gem copies this run has nothing to restore in: +/// a copy Bundler never loads for the project (another project's, in a +/// `gem env` home) that holds nothing of the patch. `apply` does not write +/// such a copy (#2313), so its content, as published or not, is neither +/// this project's to restore nor a failure of the rollback. A copy that +/// holds the patch stays, under every record of its release: an earlier +/// release patched it there, and the variant narrowing has to see it. +async fn drop_untouched_unloaded_gem_copies( + copies: &mut HashMap>, + manifest: &PatchManifest, + options: &CrawlerOptions, + blobs: &Path, +) { + let is_gem = |purl: &str| Ecosystem::from_purl(purl) == Some(Ecosystem::Gem); + let mut loaded: HashMap> = copies + .iter() + .filter(|(purl, _)| is_gem(purl)) + .map(|(purl, paths)| (purl.clone(), paths.clone())) + .collect(); + if loaded.is_empty() { + return; + } + crate::ecosystem_dispatch::retain_bundler_loaded_gem_copies(&mut loaded, options).await; + let is_loaded = |purl: &str, path: &PathBuf| loaded.get(purl).is_some_and(|l| l.contains(path)); + // (base purl, copy) of the unloaded copies that hold the patch. + let mut patched: HashSet<(String, PathBuf)> = HashSet::new(); + for (purl, paths) in copies.iter().filter(|(purl, _)| is_gem(purl)) { + let Some(record) = manifest.patches.get(purl) else { + continue; + }; + for path in paths.iter().filter(|path| !is_loaded(purl, path)) { + let key = (strip_purl_qualifiers(purl).to_string(), path.clone()); + if !patched.contains(&key) && copy_holds_patch(path, record, blobs).await { + patched.insert(key); + } + } + } + for (purl, paths) in copies.iter_mut().filter(|(purl, _)| is_gem(purl)) { + let base = strip_purl_qualifiers(purl).to_string(); + paths.retain(|path| { + is_loaded(purl, path) || patched.contains(&(base.clone(), path.clone())) + }); + } + copies.retain(|_, paths| !paths.is_empty()); +} + /// `rollback`'s pointer at the scope that still holds a patched copy: a /// rollback of just that purl, naming `--cwd` when the run used one (the record lives in that /// project's manifest). The command names the release without the record's @@ -3419,6 +3474,13 @@ pub(crate) async fn rollback_patches_inner( common.silent || common.json, ) .await; + drop_untouched_unloaded_gem_copies( + &mut all_packages_multi, + &scoped_manifest, + &crawler_options, + &socket_dir.join("blobs"), + ) + .await; // The shared-cache copies of the vendored Cargo crates restored above // (#336), including those a `cargo vendor` dir hides from the crawl. let cache_purls: Vec = cache_patched diff --git a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs index 53c2bce083..d33da5aaac 100644 --- a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs +++ b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs @@ -21,8 +21,8 @@ //! rake, …) has an ordinary spec and follows the ordinary rule; //! * with no explicit path Bundler installs into and loads from the //! `gem env` homes, so every copy there is written; -//! * `rollback` and `remove` find every copy either way: an earlier -//! release may have patched one, and it must stay restorable. +//! * `rollback` and `remove` still restore a copy there that holds the +//! patch: an earlier release may have patched it. //! //! FAILURE semantics of the copies that are written: //! @@ -698,6 +698,64 @@ fn rollback_restores_a_home_copy_an_earlier_run_patched() { ); } +/// The `rollback` that `apply` names for another project's copy works +/// whatever that copy holds: one an earlier release patched is restored, +/// and one nothing ever wrote (as published, or with other content) is +/// left as it is. The record goes each time, and the run exits 0. +#[test] +fn rollback_of_another_projects_copy_drops_the_record_whatever_it_holds() { + let patched = patched_bytes(); + let mut diverged = ORIGINAL.to_vec(); + diverged.extend_from_slice(b"# another project's edit\n"); + for (held, left) in [ + (patched.as_slice(), ORIGINAL), + (ORIGINAL, ORIGINAL), + (diverged.as_slice(), diverged.as_slice()), + ] { + let fx = build_fixture(Store::ExplicitEmpty, Home::Installed, held, QUALIFIED_PURL); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), held); + + let (code, stdout, stderr) = run_command(&fx, &["rollback"], &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + std::fs::read(&fx.home_file).unwrap(), + left, + "envelope: {env}" + ); + assert_eq!(manifest_purls(&fx), Vec::::new(), "envelope: {env}"); + } +} + +/// A copy of another project that holds neither side of the patch, beside +/// the project's own patched copy: `rollback` restores the project's copy +/// and does not fail on a copy `apply` never wrote. +#[test] +fn rollback_does_not_fail_on_another_projects_diverged_copy() { + let mut diverged = ORIGINAL.to_vec(); + diverged.extend_from_slice(b"# another project's edit\n"); + let fx = build_fixture(Store::Explicit, Home::Installed, &diverged, QUALIFIED_PURL); + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!( + std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), + patched_bytes() + ); + + let (code, stdout, stderr) = run_command(&fx, &["rollback"], &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + std::fs::read(fx.store_file.as_ref().unwrap()).unwrap(), + ORIGINAL + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), diverged); + assert_eq!(manifest_purls(&fx), Vec::::new(), "envelope: {env}"); +} + /// `remove` restores such a copy too, and drops the record. #[test] fn remove_restores_a_home_copy_an_earlier_run_patched() { From 8016bd8e50c94f70314de51eaa403f02ba3ee14d Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 16:42:58 -0500 Subject: [PATCH 11/20] Document the gem rules for Bundler, other projects' gems and rollback CLI_CONTRACT.md "Copy classes" and the Ruby section of docs/ecosystems.md now say: Bundler and default gems are patched in the gem home they are installed in; a record for another project's gem is a `gem_fallback_home_skipped` skip that names `rollback`, exit 0; a gem the lock lists with no copy `apply` writes is lockfile-only in a scan, with nothing recorded; `get` by name or advisory follows the scan; `rollback` and `remove` leave out a copy that holds nothing of the patch. The contract's code table gains the `gem_fallback_home_skipped` row it never had. Both also state that a copy another project patched with the same patch in system-gems mode cannot be told from one this project patched, so `rollback` and `remove` restore it too. `rexml` was given as an example of a default gem. Since Ruby 3.0 it is a bundled gem with an ordinary spec, so it follows the ordinary rule: the examples are now `json`, `uri` and `set`. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 81 ++++++++++++++++--------- docs/ecosystems.md | 59 +++++++++++------- 2 files changed, 88 insertions(+), 52 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 7fed673931..ddd0f60574 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -507,7 +507,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm - When several confirmed variant purls resolve to one installed dir, ANY of them judging it patched keeps it quiet. - Staleness needs **positive evidence** — bytes actually read that are not the patched state — so missing or unreadable files never mark a copy stale. - A committed cache-dir archive whose sha256 is readable and differs from the patched artifact's is stale by itself, even with no installed dir at all (a fresh checkout with a committed stale cache). That covers the ruby gem's `-.gem` and each platform build's `--.gem`. -- Standalone `vex` and `apply --check` judge gem copies by the same rule (#1098): when Bundler doesn't use system gems, a copy in a `gem env` home is not one the project loads and is not verified, unless it is a default gem (its spec under `specifications/default/`), which Bundler loads from the system home under any path. Agent `apply` writes by that rule too (#2313): it leaves such a copy alone (see "Copy classes"). +- Standalone `vex` and `apply --check` judge gem copies by the same rule (#1098): when Bundler doesn't use system gems, a copy in a `gem env` home is not one the project loads and is not verified, unless it is a default gem (its spec under `specifications/default/`) or Bundler itself, which Bundler loads from the system home under any path. Agent `apply` writes by that rule too (#2313): it leaves such a copy alone (see "Copy classes"). *The refresh* (default; `--no-gem-install-refresh`, env `SOCKET_NO_GEM_INSTALL_REFRESH`, turns it off). @@ -1518,7 +1518,7 @@ the model is **not uniform** today: "nothing installed" absence the hosted lockfile basis excuses), while `apply`/`rollback` never touch it (#709). Explicit env/config/standalone roots only count when `--cwd` holds a Bundler manifest/lockfile. When the default `vendor/bundle` root holds no store, the gem homes `gem env` - reports are appended (default gems like rexml/json only ever live there); which of the copies + reports are appended (default gems like json/uri only ever live there); which of the copies found there are written is the "Copy classes" rule below. When the Bundler tier that decides the install path (the first of the app config, the environment and the global config that sets `path`, `path.system` or `disable_shared_gems`) sets a truthy `path.system` (Bundler's own @@ -1563,38 +1563,60 @@ the model is **not uniform** today: - when Bundler uses system gems (the rule under "Gem stale-install guard": no deployment store under `vendor/bundle`, and no explicit or deployment `path`), every copy there is the project's and is patched; - - under an explicit or deployment `path`, only a default gem (its spec under - `specifications/default/`) is patched there: Bundler loads it from the system home under any - path. Bundler installs every other gem into the path, so a non-default copy in a `gem env` - home belongs to other projects on the machine. It is never written and gets no event. A gem - with no other copy is `package_not_installed`, as any package that is not installed: a calm - skip (exit 0) when the project's lock resolves it, which is a fresh clone before - `bundle install`, and the all-miss error (exit 1) when no lock resolves it and no other - targeted patch matched. - - `scan --mode agent` selects by the same rule, so that it never records a patch its apply step - then reports as not installed. A gem whose every copy is one `apply` does not write, and that - the project's lock does not list, is another project's and is no candidate: it is not counted - (`scannedPackages`), queried or shown, and nothing is downloaded or recorded for it. A gem the - lock does list stays a candidate: its patch is recorded, and the apply step reports it - `package_not_installed` (lockfile-only, exit 0) until `bundle install` puts it in the path. The - prune pass (`--prune` / `--sync`) still counts such a copy as installed, so a record an earlier - release wrote for it is kept until `rollback` or `remove` restores the copy. - - `apply --check` and `vex` judge the same copies. `rollback` and `remove` resolve without this - rule: they restore every copy they find in the `gem env` homes, because a release before this - rule may have patched one. A `--global` run patches the `gem env` homes as before. Once the - default `vendor/bundle` root holds a store, no local run searches those homes: a default gem - there is not patched, and `rollback` leaves a copy an earlier run patched there, keeps its - manifest record and names `socket-patch rollback -g` in a warning. + - under an explicit or deployment `path`, two kinds of copy are patched there, because Bundler + loads them from the gem home they are installed in under any path: a default gem (its spec + under `specifications/default/`: `json`, `uri`, `set`), and Bundler itself (a `bundler-` + dir, as `gem install bundler` leaves it; every installed version, since which one runs also + depends on `BUNDLED WITH`, `BUNDLER_VERSION` and Bundler's own version switch). A bundled gem + (`rexml`, `rake`) has an ordinary spec and follows the ordinary rule: Bundler installs it, + like every other gem, into the path, so a copy of it in a `gem env` home belongs to other + projects on the machine and is never written. + + A gem with no copy `apply` writes is one of two things: + + - **in the project's lock**: not installed yet (a fresh clone before `bundle install`). It is + `package_not_installed` with the lockfile-only detail, a calm skip, exit 0; + - **not in the lock, with a copy in a `gem env` home**: another project's gem. Its record (one + an earlier release wrote when it patched that copy, or one a `get` of the exact purl wrote) is + a `skipped` event with `errorCode: gem_fallback_home_skipped`, whose detail names the copy, + says why it was left, and gives the command that drops the record + (`socket-patch rollback `, with `--cwd` when the run had one); the human run prints it + as a `Warning:`, and the summary counts the patch as `not applicable`. It never fails the + run and is not counted as an all-miss. A gem with no copy anywhere and no lock entry keeps the + all-miss error (exit 1). + + `scan --mode agent` and `get` in agent mode select by the same rule, so that neither records a + patch its apply step has no copy to write. A gem whose every copy is one `apply` does not write + is not installed for the project. The scan leaves it out of the crawl: one the lock lists is + then lockfile-only, exactly as when no gem home holds it (`notInstalled`, skipped as + `package_not_installed` before any download, nothing recorded), and one the lock does not list + is no candidate at all (not counted in `scannedPackages`, not queried, not shown). `get ` + resolves a name among the installed packages, so such a gem's name matches nothing, and + `get ` narrows it away as `package_not_installed`. An exact purl is never narrowed, + for any package: `get pkg:gem/@` records the patch, and the apply step reports + one of the two cases above. The prune pass (`--prune` / `--sync`) still counts such a copy as + installed, so a record an earlier release wrote for it is kept until `rollback` or `remove` + drops it. + + `apply --check` and `vex` judge the copies `apply` writes. `rollback` and `remove` restore a copy + in a `gem env` home that holds the patch, because a release before this rule may have patched it + there; a copy there that `apply` does not write and that holds nothing of the patch is left out, + whatever its content, and its record is dropped as for a package that is not installed (never a + `hash_mismatch` failure over another project's edit). A copy in a shared gem home that another + project patched with the same patch, in system-gems mode, cannot be told from one this + project's earlier release patched, so `rollback` and `remove` here restore it too. A `--global` + run patches the `gem env` homes as before. Once the default `vendor/bundle` root holds a store, + no local run searches those homes: a default gem there is not patched, and `rollback` leaves a + copy an earlier run patched there, keeps its manifest record and names + `socket-patch rollback -g` in a warning. A fallback-home copy that is written becomes BEST-EFFORT once at least one bundle-store copy applied: its mismatch/write failure surfaces as a non-fatal `skipped` event (`errorCode: gem_fallback_home_skipped`, detail names the copy's path and reason; gated stderr twin on the human path) instead of failing a run whose loaded copy is patched. With **no** - bundle-store copy (Bundler using system gems, a default gem that is in no store, and every - `--global` run) the fallback-home copy IS the primary install and keeps loud-fail parity with - pre-bundle-path `apply`. + bundle-store copy (Bundler using system gems, a default gem or Bundler that is in no store, and + every `--global` run) the fallback-home copy IS the primary install and keeps loud-fail parity + with pre-bundle-path `apply`. **Intended (gap):** the cwd-only ecosystems *should* also auto-discover per-subproject lockfiles when run from the repo root, matching the npm workspace model. The npm-vs-others asymmetry is a known @@ -2507,6 +2529,7 @@ command's integration tests check its output. |---------------------------|------------------|---------| | `already_patched` | `skipped` | apply: every file's hash already matches `afterHash`. | | `not_in_platform_build` | `skipped` | apply (gem): the installed copy is the JRuby (`java`) build of the gem and no file of the patch is part of that build (a patch to the C extension or a library it packs). Nothing was written and nothing is left to do: the code the patch changes is not in that build, `apply --check` is in sync and `vex` attests the package (`vulnerable_code_not_present`), and a nested `scan --mode agent` counts the patch among those in place, as it counts `already_patched`. `reason` says so in plain words. rollback (gem): the same copy; nothing of the patch was applied to it, so nothing was restored. See "The JRuby build of a gem". | +| `gem_fallback_home_skipped` | `skipped` | apply (gem), and the apply that `get` / `scan --mode agent` run: a copy in a `gem env` home (the system gems, `~/.gem`, an rbenv or asdf home) was left unpatched and the run stands. Either the copy is best-effort (a bundle-path copy of the gem applied, and this one matched no variant or could not be written), or it is another project's gem (Bundler does not load the project's gems from that home, no lock of the project lists the gem, and no other copy exists): the detail then gives `socket-patch rollback `, which drops the record and restores the copy if an earlier release patched it. Never flips status or exit; the human summary counts the second kind as `not applicable`. See "Copy classes". | | `package_not_installed` | `skipped` | apply: manifest entry has no matching installed package (an installed gem or PyPI copy that holds a patched file with content no record of its release was made for is `no_matching_variant` instead). When the project's lockfiles resolve the purl (a platform-gated optional dependency, a devDependency under `--omit=dev`), the detail says it is lockfile-only and the entry never fails the run, even when no other patch matched; only an all-miss run with an unmatched purl that no lock resolves exits 1 (`partialFailure`). **Cargo is never lockfile-only (v5.0, #616)**: `cargo fetch` unpacks every `Cargo.lock` entry (target-gated ones included), so a locked crate missing from `$CARGO_HOME/registry/src` was simply not fetched yet (a cold CI cache, a pruned `registry/src`) and the next `cargo build` would compile it unpatched; it counts as an unresolved purl (an all-miss run exits 1, as in 4.x) and its detail, the human error and the human warning say to run `cargo fetch` first. A crate `Cargo.lock` takes from a path, git, `[patch]` or `[replace]` source is never looked up in the registry cache (#506): cargo does not build that copy, so the same detail also names that case. | | `apply_failed` | `failed` | apply: hash mismatch, write error, archive read error. Also a manifest key that is not a purl (see `invalid_purl`). The copy is left as it was: every file is staged (its blob read and hash-checked, with the file's final mode and owner) before the first is renamed into place, and a rename that fails puts the files already replaced back. The `error` names the file (`Cannot apply patch: - `); a blob that does not hold its hash's bytes is named with the remedy (`blob is corrupt … Run \`socket-patch repair\``). Only when putting a file back fails too does the `error` end with the files left changed; the original of such a file is kept beside it as `.socket-kept--`, a name no later run removes. A run killed between two renames can still leave some files patched; the next `apply` finishes it. A killed run also leaves `.socket-stage--` / `.socket-orig--` files beside the patch's files (staged content and the second names of the files being replaced, never the package's own content); an `apply` or `rollback` of that package removes them once they are ten minutes old. | | `native_extension_not_rebuilt` | `failed` | apply (gem), and the apply that `get` / `scan --mode agent` run: the patch is incomplete. Its files were written into the installed copy and are left there (unlike `apply_failed`, where the copy is as it was), and the compiled code the copy runs is not the patch's: the build compiled nothing of it, or, on the JRuby build of a gem, the patch changes sources of the gem's jars and does not bring the jars. `error` says what was written and what is not in effect; `files` lists what this run wrote. The run exits 1 (`partialFailure`), the patch stays recorded, `apply --check` is out of sync and `vex` does not attest it; `rollback` restores the files. The same code is a `warnings[]` entry of the run, and the `apply --check` / `vex` tag of such a copy. See "A build that builds nothing of the patch". | diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 2ad2df1ebb..6929e99370 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5126,40 +5126,53 @@ A shared gem home also holds gem versions this project doesn't use: the gems Rub mode warns `redirect_gem_version_not_locked`, vendored mode reports a `skipped` event with `vendor_gem_version_not_locked` and doesn't download its patch. The run exits 0. -Agent mode (`apply`, and the apply step of `scan --mode agent`) patches installed gems in place, -and follows the same principle. It writes the copies Bundler loads for the project and no other: +Agent mode (`apply`, and the apply step of `scan --mode agent` and `get`) patches installed gems +in place, and follows the same principle. It writes the copies Bundler loads for the project and +no other: - With a Bundler `path` (`bundle config set --local path vendor/gems`, `BUNDLE_PATH`) or deployment mode, Bundler installs the project's gems into that path, and `apply` patches them there. A copy of the same gem version in a shared gem home is left alone: Bundler never loads it - for this project, and another project may. The exception is a default gem, one that ships with - Ruby (`json`, `rexml`, ...). Bundler loads it from Ruby's own gem home under any path, so - `apply` patches it there. That stops once `vendor/bundle`, the default path, holds the - project's gems: `apply` then looks only there, and a default gem is not patched. + for this project, and another project may. Two kinds of gem are the exception, because Bundler + loads them from the gem home they are installed in under any path, so `apply` patches them + there: a default gem, one Ruby ships as part of itself (`json`, `uri`, `set`), and Bundler + (every installed version of it). A bundled gem (`rexml`, `rake`) is an ordinary gem that Ruby + merely ships along, and follows the ordinary rule. The exception stops once `vendor/bundle`, + the default path, holds the project's gems: `apply` then looks only there, and neither a + default gem nor Bundler is patched. - With no `path`, Bundler installs into the shared gem homes and loads the project's gems from them, so `apply` patches them there. Another project that uses the same gem version then runs the patched code too. Set a `path` (the `bundle config` line above) to keep the patch inside the project. -An agent-mode scan selects patches by the same rule. A gem that is only in a shared gem home, -and that `Gemfile.lock` doesn't list, is another project's: the scan doesn't report it, and -downloads and records no patch for it. A gem the lock does list is the project's even before it -is installed, so the scan records its patch. +An agent-mode scan, and `get` by package name or by advisory, select patches by the same rule. A +gem that is only in a shared gem home is not installed for this project. If `Gemfile.lock` lists +it, the scan reports it as not installed yet and records nothing, as it does when no gem home +holds it. If the lock doesn't list it, it is another project's: the scan doesn't report it, a +name finds no package, and an advisory skips that version as not installed. On a fresh clone with a `path`, run `bundle install` before `apply`. Before it the path holds no -gem, so `apply` patches nothing and reports the gems as not installed (`0 of 1 targeted patch -applied, 0 already patched, 1 not found on disk`). It exits 0 when `Gemfile.lock` lists them. -With no lock that does, a run that matched no installed package at all exits 1, as it does for -any package that is not installed. - -Releases up to 5.1.0 patched a copy in a shared gem home under a `path` as well. `rollback` and -`remove` still restore such a copy when they find it. Once `vendor/bundle` holds the project's -gems they look only there too: `rollback` then keeps the patch recorded and warns that the shared -copy is still patched, naming the command that restores it (`socket-patch rollback -g`). -A manifest written by such a release may still record a patch for a gem of another project: -`apply` now reports it as not installed, and `socket-patch rollback ` restores that copy -and removes the record. `apply --global` patches the gems in the shared gem homes whatever the -project's Bundler settings are. +gem, so `apply` patches nothing and reports the gems `Gemfile.lock` lists as not installed (`0 of +1 targeted patch applied, 0 already patched, 1 not found on disk`), with exit 0. A recorded patch +for a gem that no lock lists and no gem home holds makes a run that matched nothing exit 1, as +for any package that is not installed. + +Releases up to 5.1.0 patched a copy in a shared gem home under a `path` as well, and their scans +recorded patches for other projects' gems. `apply` skips such a record with a warning that names +the copy and the command to run (`1 not applicable` in the summary, exit 0): + +``` +socket-patch rollback pkg:gem/rack@2.2.8 +``` + +It removes the patch from the manifest and restores the copy if it still holds the patch. A copy +that doesn't hold it is left as it is, whatever it holds, since it is another project's. Another +project that patched the same copy with the same patch, with no `path` of its own, can't be told +apart: its copy is restored too, and its own `apply` patches it again. Once `vendor/bundle` holds +the project's gems, `rollback` and `remove` look only there: `rollback` then keeps the patch +recorded and warns that the shared copy is still patched, naming the command that restores it +(`socket-patch rollback -g`). `apply --global` patches the gems in the shared gem homes +whatever the project's Bundler settings are. ## Ruby gems: gems vendored mode refuses From 6f344ae9ebb704a052f441241e802801f57bea8f Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 16:51:55 -0500 Subject: [PATCH 12/20] Keep a gem the lock holds as platform builds out of the other-project skip The skip for another project's gem asks whether the lock lists the gem through the lock inventory, which leaves out a gem `Gemfile.lock` holds only as precompiled platform builds (`nokogiri (1.18.10-x86_64-linux)`). On a fresh clone with the same version in a gem home, `apply` then said the gem belongs to another project and named the `rollback` of a patch the project needs. Such a gem is the project's. It is taken out of the candidates, so it keeps the not-installed result it had. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 4 ++- crates/socket-patch-cli/src/commands/apply.rs | 19 ++++++++-- .../apply/in_process_gem_fallback_home.rs | 35 +++++++++++++++++++ 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index ddd0f60574..de78fd1614 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1576,7 +1576,9 @@ the model is **not uniform** today: - **in the project's lock**: not installed yet (a fresh clone before `bundle install`). It is `package_not_installed` with the lockfile-only detail, a calm skip, exit 0; - - **not in the lock, with a copy in a `gem env` home**: another project's gem. Its record (one + - **not in the lock, with a copy in a `gem env` home**: another project's gem. (A gem the lock + holds only as precompiled platform builds is in the lock: it stays `package_not_installed`, + with the result a package that is not installed has.) Its record (one an earlier release wrote when it patched that copy, or one a `get` of the exact purl wrote) is a `skipped` event with `errorCode: gem_fallback_home_skipped`, whose detail names the copy, says why it was left, and gives the command that drops the record diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index ed819ec7e6..4ec8526960 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -3342,7 +3342,8 @@ impl OtherProjectCopy { } /// The gems of `unresolved` (the manifest keys with no copy to patch and -/// no lock entry) that are another project's: `rollback`'s resolver finds +/// none in the lock inventory) that are another project's: the lock does +/// not name them as platform builds either, and `rollback`'s resolver finds /// a copy of them where this run's (`all_packages`, the copies `apply` /// writes) found none, so each sits in a `gem env` home Bundler does not /// load the project's gems from. The detail holds for a copy an earlier @@ -3355,7 +3356,7 @@ async fn other_project_gem_copies( if common.is_global() { return Vec::new(); } - let candidates: Vec = unresolved + let mut candidates: Vec = unresolved .iter() .filter(|purl| { Ecosystem::from_purl(purl) == Some(Ecosystem::Gem) @@ -3366,6 +3367,20 @@ async fn other_project_gem_copies( if candidates.is_empty() { return Vec::new(); } + // The lock names a gem it holds only as precompiled platform builds, + // though the lock inventory behind `unresolved` leaves it out: that + // gem is the project's, and stays not installed. + let ctx = crate::commands::context::ProjectContext::new(common); + let platform_only: HashSet = ctx + .gem_platform_only_purls() + .await + .iter() + .map(|purl| PurlKey::new(purl)) + .collect(); + candidates.retain(|purl| !platform_only.contains(&PurlKey::new(purl))); + if candidates.is_empty() { + return Vec::new(); + } let mut found = crate::ecosystem_dispatch::find_all_packages_for_rollback( &partition_purls(&candidates, None), &common.crawler_options(), diff --git a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs index d33da5aaac..71689bf69c 100644 --- a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs +++ b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs @@ -405,6 +405,41 @@ fn gem_with_no_copy_anywhere_and_no_lock_entry_still_fails() { ); } +/// A gem the lock holds only as a precompiled platform build is the +/// project's, though the lock inventory leaves it out. With the path +/// still empty and a copy of the version in the `gem env` home, it is not +/// another project's gem: it stays the not-installed failure it was, and +/// nothing tells the user to roll back a patch the project needs. +#[test] +fn gem_the_lock_holds_as_a_platform_build_is_not_another_projects() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + std::fs::write( + fx.project.path().join("Gemfile.lock"), + "GEM\n remote: https://rubygems.org/\n specs:\n rack (3.1.0-x86_64-linux)\n\n\ + PLATFORMS\n x86_64-linux\n\nDEPENDENCIES\n rack\n\nBUNDLED WITH\n 2.5.22\n", + ) + .unwrap(); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert!( + find_skip_event(&env).is_none(), + "the gem is the project's.\nenvelope: {env}" + ); + assert!( + find_event(&env, "skipped", NOT_INSTALLED).is_some(), + "envelope: {env}" + ); + assert_eq!(code, 1, "envelope: {env}\nstderr:\n{stderr}"); + assert!(!stdout.contains("rollback"), "envelope: {env}"); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + /// The other project's copy beside a gem of this project that is patched: /// the run still succeeds, the copy has its skip, and nothing is reported /// as having no installed package. From 2eeab37398f4543bcd167064257fc2e40d6a5bb8 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 16:51:55 -0500 Subject: [PATCH 13/20] Pin that scan --sync keeps a record for another project's gem An agent-mode scan takes the gems `apply` has no copy to write out of its crawl. Their purls must stay in the prune universe: the copy is on disk and may hold a patch an earlier release wrote, and a prune that dropped the record and its blobs would leave nothing for `rollback` to restore it with. Co-Authored-By: Claude Fable 5.2 --- .../tests/scan/scan_gem_unloaded_homes.rs | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs b/crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs index 6053985cfb..16c5c7258d 100644 --- a/crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs +++ b/crates/socket-patch-cli/tests/scan/scan_gem_unloaded_homes.rs @@ -124,6 +124,34 @@ async fn foreign_gem_in_a_gem_env_home_leaves_the_human_run_clean() { assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); } +/// A record an earlier release wrote for another project's gem survives +/// `scan --sync`: the copy is on disk and may hold the patch, so the prune +/// counts the gem as installed and `rollback` can still restore it. +#[tokio::test] +async fn sync_keeps_a_record_for_a_foreign_gem() { + let (project, home_file) = project_beside(&RACK, &["colorize (1.1.0)"]); + super::scan_fixture::seed_manifest(project.root(), &[(&RACK.record(), RACK.uuid)]); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let api_url = mock.uri(); + let mut args = vec!["--sync", "--json"]; + args.extend(api_args(&api_url)); + let (code, stdout, stderr) = project.run(&["scan"], &args); + let env = parse_json_envelope(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!( + project.manifest_purls(), + vec![RACK.record()], + "the record must not be pruned.\nenvelope: {env}" + ); + assert!( + !batch_queried(&mock, &RACK.purl()).await, + "the foreign gem is still no candidate" + ); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); +} + /// A fresh clone before `bundle install`: the lock lists `rack`, the path /// holds nothing yet, and the `gem env` home has the same version. The /// home copy is not the project's, so the gem is lockfile-only, as when no From bc498174b5ac825f6657e2d2127a9fd061a72468 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 18:01:28 -0500 Subject: [PATCH 14/20] Identify Bundler by the purl's gem name `is_bundler_copy` told Bundler by its gem dir: the prefix `bundler-` followed by a digit. A gem named like `bundler-2fa` passes that test, so its copy in a `gem env` home would have been kept as one the project loads and patched there. `retain_bundler_loaded_gem_copies` has the purl as its map key, so it now compares the gem name in it to `bundler`, and the directory test is gone. Co-Authored-By: Claude Fable 5.2 --- .../src/ecosystem_dispatch.rs | 23 ++++++++++--- .../src/crawlers/ruby_crawler.rs | 34 ++----------------- 2 files changed, 22 insertions(+), 35 deletions(-) diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index 7dfb19d499..b314e3f8ad 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -917,6 +917,14 @@ pub(crate) async fn retain_bundler_loaded_gem_copies( options: &CrawlerOptions, ) { let is_gem = |purl: &str| Ecosystem::from_purl(purl) == Some(Ecosystem::Gem); + // The gem named `bundler` itself, whatever its version or qualifiers: + // `bundler-audit` and `bundler-2fa` are other gems. + let is_bundler = |purl: &str| { + strip_purl_qualifiers(purl) + .strip_prefix("pkg:gem/") + .and_then(|coordinate| coordinate.rsplit_once('@')) + .is_some_and(|(name, _)| name == "bundler") + }; if options.global || options.global_prefix.is_some() || !copies.keys().any(|p| is_gem(p)) { return; } @@ -938,12 +946,19 @@ pub(crate) async fn retain_bundler_loaded_gem_copies( if unused.is_empty() { return; } - use socket_patch_core::crawlers::ruby_crawler::{is_bundler_copy, is_default_gem_copy}; - for (_, paths) in copies.iter_mut().filter(|(purl, _)| is_gem(purl)) { + for (purl, paths) in copies.iter_mut().filter(|(purl, _)| is_gem(purl)) { + // Bundler is never installed into a project's `path`: the one that + // runs is loaded from the gem home it was installed into, with its + // spec outside `specifications/default/`. Which version runs is not + // decided here (the lock's `BUNDLED WITH`, `BUNDLER_VERSION` and + // Bundler's own switch to the locked version all have a say), so + // every installed version stays. + if is_bundler(purl) { + continue; + } paths.retain(|path| { !unused.iter().any(|home| path.starts_with(home)) - || is_default_gem_copy(path) - || is_bundler_copy(path) + || socket_patch_core::crawlers::ruby_crawler::is_default_gem_copy(path) }); } copies.retain(|_, paths| !paths.is_empty()); diff --git a/crates/socket-patch-core/src/crawlers/ruby_crawler.rs b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs index a83f56e94e..288418faa9 100644 --- a/crates/socket-patch-core/src/crawlers/ruby_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/ruby_crawler.rs @@ -835,9 +835,9 @@ impl RubyCrawler { /// The `gem env` homes Bundler never loads this project's gems from. /// [`Self::get_gem_paths`] keeps them for default gems, but under an /// explicit or deployment `path` Bundler fetches every other gem into - /// that path, so a copy there that is neither a default gem nor - /// Bundler ([`is_default_gem_copy`], [`is_bundler_copy`]) is not one - /// the project runs: `apply` does not write it (#2313), and the + /// that path, so a copy there that is neither a default gem + /// ([`is_default_gem_copy`]) nor Bundler itself is not one the + /// project runs: `apply` does not write it (#2313), and the /// read-only verifiers (`vex`, `apply --check`) do not judge it /// (#1098). Empty in global / /// `--global-prefix` mode and whenever Bundler uses system gems. A @@ -1525,22 +1525,6 @@ pub fn is_default_gem_copy(copy: &Path) -> bool { .is_file() } -/// Whether the installed gem dir `copy` (`/gems/-`) -/// is Bundler itself. Bundler is never installed into a project's `path`: -/// the one that runs is loaded from the gem home it was installed into -/// (`gem install bundler`, `gem update bundler`), where its spec sits -/// outside `specifications/default/`. So a copy of it in a `gem env` home -/// is one the project loads under any `path`, like a default gem. Which -/// version runs is not decided here (the lock's `BUNDLED WITH`, -/// `BUNDLER_VERSION` and Bundler's own switch to the locked version all -/// have a say), so every installed version counts. -pub fn is_bundler_copy(copy: &Path) -> bool { - copy.file_name() - .and_then(OsStr::to_str) - .and_then(|leaf| leaf.strip_prefix("bundler-")) - .is_some_and(|version| version.starts_with(|c: char| c.is_ascii_digit())) -} - /// `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. @@ -5275,18 +5259,6 @@ mod tests { assert!(!is_default_gem_copy(Path::new("json-2.7.2"))); } - /// Bundler is told by its gem dir's name, whatever its version; a gem - /// whose name only starts with `bundler-` is another gem. - #[test] - fn is_bundler_copy_matches_bundler_alone() { - let gems = Path::new("/home/gems"); - assert!(is_bundler_copy(&gems.join("bundler-2.6.9"))); - assert!(is_bundler_copy(&gems.join("bundler-4.0.0.beta1"))); - assert!(!is_bundler_copy(&gems.join("bundler-audit-0.9.2"))); - assert!(!is_bundler_copy(&gems.join("bundler"))); - assert!(!is_bundler_copy(&gems.join("rack-3.1.8"))); - } - /// #1109: with no tier setting `path`, `path.system` or /// `disable_shared_gems`, a truthy `deployment` makes `vendor/bundle` /// the explicit path (`Settings#path`, Bundler 2.5 and 4.0 alike). The From 7b3951402896b5b0e314050ccafe3b49e9fe27f2 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 18:01:28 -0500 Subject: [PATCH 15/20] Record by name with get --save-only as before `--save-only` forces agent mode, so `get --save-only` ran the filter that leaves out a gem `apply` has no copy to write, and printed "No packages matching" for a gem that only a `gem env` home holds. It applies nothing, and `get --save-only` and an exact purl still recorded the patch. The name path skips the filter under `--save-only`. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/get.rs | 6 ++++-- .../tests/get/get_gem_unloaded_homes.rs | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index a4d3213623..ecec6ad630 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -1629,8 +1629,10 @@ pub async fn run(args: GetArgs) -> i32 { crawl_ecosystems_for_name(&args.common.crawler_options(), only).await; // Agent mode patches installed copies in place: a gem `apply` // has no copy to write for is not installed for this project, - // so its name resolves to nothing (#2313). - if mode == super::scan::ScanMode::Agent { + // so its name resolves to nothing (#2313). `--save-only` + // applies nothing, and records by name as it does by purl or + // advisory. + if mode == super::scan::ScanMode::Agent && !args.save_only { let unloaded = crate::ecosystem_dispatch::gems_apply_never_writes( all_packages .iter() diff --git a/crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs b/crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs index eda8ed7d92..9f3f648092 100644 --- a/crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs +++ b/crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs @@ -87,6 +87,21 @@ async fn name_of_a_foreign_gem_matches_no_installed_package() { assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); } +/// `get rack --save-only` records a patch and applies nothing, so it has +/// no installed copy to ask for: the name resolves from the crawl as it +/// always did, and the patch is recorded, as by advisory or by purl. +#[tokio::test] +async fn save_only_records_a_foreign_gem_by_name() { + let (project, home_file) = project_beside(&RACK); + let mock = MockServer::start().await; + RACK.mount(&mock).await; + + let (code, stdout, stderr) = get(&project, &mock.uri(), "rack", &["--save-only"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!(project.manifest_purls(), vec![RACK.record()]); + assert_eq!(std::fs::read(&home_file).unwrap(), RACK.before()); +} + /// `get ` for an advisory patched in `rack 3.1.0`, with that version /// only in the gem home: narrowed away as not installed here, the calm /// skip a version installed nowhere gets. No download, no record, exit 0. From 461debf047d39fbbfb895c4b79f2362d6ffc2a7b Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 18:01:29 -0500 Subject: [PATCH 16/20] Call a gem another project's only when a Bundler lock was read `apply` took "not in the lock inventory" as proof that a gem whose only copy sits in a `gem env` home is another project's. The inventory is also empty when no lock was read: a project with no lock yet (a gem library that commits none), and the layouts reported as `gem_lock_unsupported` (an unsupported `BUNDLE_GEMFILE` or `BUNDLE_LOCKFILE`, a `Gemfile` + `gems.rb` twin). There `apply` said the lock does not list the gem and advised a `rollback` that removes a patch the project may need. The skip now needs a Bundler lock that was read (`gem_lock_read_in`) and does not list the gem. Without one the gem keeps the `package_not_installed` result. The fixtures of the other-project cases get a lock, and the lockless case is pinned. `scan` and `get` do not use the lock to drop such a gem: to them a gem `apply` has no copy to write is not installed, with or without a lock, and the lock only decides whether it is reported as lockfile-only. They are unchanged. The skip also gets its own code, `gem_other_project_copy_skipped`. It shared `gem_fallback_home_skipped` with the best-effort skip, which is keyed by the base purl and means the patch is in effect on the copy bundler loads; this one is keyed by the manifest key and means nothing was applied, and a consumer could not tell them apart. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/apply.rs | 39 +++-- .../socket-patch-cli/src/commands/context.rs | 9 + .../socket-patch-cli/src/commands/scan/mod.rs | 3 +- crates/socket-patch-cli/src/json_envelope.rs | 1 + .../apply/in_process_gem_fallback_home.rs | 158 ++++++++++++++---- .../tests/get/get_gem_unloaded_homes.rs | 7 +- .../src/vendor/lock_inventory/gem.rs | 11 ++ .../src/vendor/lock_inventory/mod.rs | 2 +- 8 files changed, 186 insertions(+), 44 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 49da7a1700..6133a4b340 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -2454,8 +2454,8 @@ pub(crate) async fn run_locked( .with_reason(FALLBACK_HOME_SKIPPED, skip.detail()), ); } - // Another project's gems: the same code, and never a - // failure either. + // Another project's gems: a code of their own, and never + // a failure either. for copy in &caveats.other_project { env.record(copy.event()); } @@ -3389,8 +3389,8 @@ struct GemCaveats { /// (gem or PyPI). Each has a failed result, keyed by the base purl. no_variant: Vec, /// Gems installed only where Bundler does not load the project's gems - /// from, and in no lock of the project: skipped. They have no result - /// and do not fail the run. + /// from, and not in the Bundler lock the project has: skipped. They + /// have no result and do not fail the run. other_project: Vec, } @@ -3447,14 +3447,19 @@ fn format_patch_incomplete(purl: &str, what: &str) -> String { format!("Error: Patch of {purl} is incomplete: {what}") } -/// `errorCode` of a gem copy in a `gem env` home that `apply` left -/// unpatched without failing: a best-effort copy ([`FallbackHomeSkip`]), or -/// another project's gem ([`OtherProjectCopy`]). +/// `errorCode` of a best-effort gem copy in a `gem env` home that `apply` +/// left unpatched ([`FallbackHomeSkip`]): the patch is in effect on the +/// copy bundler loads. Keyed by the base purl. const FALLBACK_HOME_SKIPPED: &str = "gem_fallback_home_skipped"; +/// `errorCode` of a record for another project's gem +/// ([`OtherProjectCopy`]): nothing was applied. Keyed by the manifest key. +const OTHER_PROJECT_COPY_SKIPPED: &str = "gem_other_project_copy_skipped"; + /// One gem `apply` left as it was because its every copy sits in a -/// `gem env` home Bundler does not load the project's gems from, and no -/// lock of the project lists it: another project's gem (#2313). A record +/// `gem env` home Bundler does not load the project's gems from, and the +/// Bundler lock the project has does not list it: another project's gem +/// (#2313). A record /// for it is one an earlier release wrote when it patched such a copy, or /// one a `get` of its purl wrote. It is a `Skipped` event of the patch, /// not an apply result, and never fails the run. @@ -3469,13 +3474,14 @@ struct OtherProjectCopy { impl OtherProjectCopy { fn event(&self) -> PatchEvent { PatchEvent::new(PatchAction::Skipped, self.purl.clone()) - .with_reason(FALLBACK_HOME_SKIPPED, self.detail.as_str()) + .with_reason(OTHER_PROJECT_COPY_SKIPPED, self.detail.as_str()) } } /// The gems of `unresolved` (the manifest keys with no copy to patch and -/// none in the lock inventory) that are another project's: the lock does -/// not name them as platform builds either, and `rollback`'s resolver finds +/// none in the lock inventory) that are another project's: a Bundler lock +/// was read, it does not name them as platform builds either, and +/// `rollback`'s resolver finds /// a copy of them where this run's (`all_packages`, the copies `apply` /// writes) found none, so each sits in a `gem env` home Bundler does not /// load the project's gems from. The detail holds for a copy an earlier @@ -3499,10 +3505,17 @@ async fn other_project_gem_copies( if candidates.is_empty() { return Vec::new(); } + // Only a Bundler lock that was read can say the project does not use + // a gem. With none (a gem library that commits no lock, a layout whose + // lock is not read) the gem may be the project's own, not installed in + // its path yet: it stays not installed. + let ctx = crate::commands::context::ProjectContext::new(common); + if !ctx.gem_lock_read().await { + return Vec::new(); + } // The lock names a gem it holds only as precompiled platform builds, // though the lock inventory behind `unresolved` leaves it out: that // gem is the project's, and stays not installed. - let ctx = crate::commands::context::ProjectContext::new(common); let platform_only: HashSet = ctx .gem_platform_only_purls() .await diff --git a/crates/socket-patch-cli/src/commands/context.rs b/crates/socket-patch-cli/src/commands/context.rs index ade912e2ba..c0ad7a59c2 100644 --- a/crates/socket-patch-cli/src/commands/context.rs +++ b/crates/socket-patch-cli/src/commands/context.rs @@ -99,6 +99,15 @@ impl<'a> ProjectContext<'a> { .await } + /// Whether bundler loads a lock in the project that socket-patch read + /// (`gem_lock_read_in`), through the same snapshot as [`Self::locks`]. + pub(crate) async fn gem_lock_read(&self) -> bool { + socket_patch_core::vendor::lock_inventory::gem_lock_read_in(&ProjectView::Snapshot( + &self.snapshot, + )) + .await + } + /// The lockfile wiring discovery of `--cwd` ([`super::discover_wiring_in`]). pub(crate) async fn discovery(&self) -> &Discovery { &self.recorded_discovery().await.0 diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 7dbc063efe..02090a4a99 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -2521,7 +2521,8 @@ async fn scan_project( // `path`). A gem with no other copy is not installed for this project // (#2313): it leaves the crawl here, so one the lock lists is found // again below as lockfile-only, like a gem with no copy at all, and - // one the lock does not list is no candidate. The purls are kept for + // any other is no candidate, like a gem installed nowhere. Nothing + // here says whose the gem is, so no lock is needed. The purls are kept for // the prune universe: the copies are on disk, and a record an earlier // release wrote for one must stay until `rollback` restores it. let unloaded_gems = if apply { diff --git a/crates/socket-patch-cli/src/json_envelope.rs b/crates/socket-patch-cli/src/json_envelope.rs index e399cb2917..9ec545005f 100644 --- a/crates/socket-patch-cli/src/json_envelope.rs +++ b/crates/socket-patch-cli/src/json_envelope.rs @@ -1415,6 +1415,7 @@ mod tests { Some("package_not_installed"), Some("vendored"), Some("gem_fallback_home_skipped"), + Some("gem_other_project_copy_skipped"), None, ] { assert!(!skip_leaves_patched(code), "{code:?}"); diff --git a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs index 71689bf69c..f4d624333f 100644 --- a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs +++ b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs @@ -12,9 +12,11 @@ //! and never loads one from a `gem env` home. A copy there belongs to //! other projects on the machine, so `apply` leaves it alone. With no //! other copy, a gem the lock lists is not installed yet (the calm -//! lockfile-only skip), and one it does not list is another project's -//! gem: a skip of its own that names the copy and the `rollback` that -//! drops the record, never a failure; +//! lockfile-only skip), and one a lock that was read does not list is +//! another project's gem: a skip of its own +//! (`gem_other_project_copy_skipped`) that names the copy and the +//! `rollback` that drops the record, never a failure. With no lock +//! read, nothing says whose the gem is: it stays not installed; //! * a default gem (its spec under `specifications/default/`) and //! Bundler itself are loaded from the gem home they are installed in //! under any path, so they are still written. A bundled gem (rexml, @@ -50,6 +52,7 @@ use super::apply_fixture::{ use crate::common::git_sha256; const SKIP_CODE: &str = "gem_fallback_home_skipped"; +const OTHER_PROJECT: &str = "gem_other_project_copy_skipped"; const NOT_INSTALLED: &str = "package_not_installed"; const ORIGINAL: &[u8] = b"module Rack\n VERSION = 'VULNERABLE'\nend\n"; @@ -183,6 +186,16 @@ fn write_lock(fx: &Fixture) { .unwrap(); } +/// A `Gemfile.lock` of the project that does not list the fixture's gem. +fn write_lock_without_the_gem(fx: &Fixture) { + std::fs::write( + fx.project.path().join("Gemfile.lock"), + "GEM\n remote: https://rubygems.org/\n specs:\n colorize (1.1.0)\n\n\ + PLATFORMS\n ruby\n\nDEPENDENCIES\n colorize\n\nBUNDLED WITH\n 2.5.22\n", + ) + .unwrap(); +} + /// Run ` --offline --ecosystems gem --cwd ` with /// the hermetic SOCKET_* env and BUNDLE_* scrubbed, PATH = the fake-gem /// bin dir only, and BUNDLE_PATH set when the fixture's store is explicit. @@ -226,6 +239,11 @@ fn find_skip_event(env: &serde_json::Value) -> Option<&serde_json::Value> { find_event(env, "skipped", SKIP_CODE) } +/// The skip of a record for another project's gem. +fn find_other_project_skip(env: &serde_json::Value) -> Option<&serde_json::Value> { + find_event(env, "skipped", OTHER_PROJECT) +} + fn home_dir(fx: &Fixture) -> PathBuf { fx.project.path().join("gem-home") } @@ -302,11 +320,11 @@ fn explicit_path_human_run_lists_only_the_project_copy() { assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); } -/// Explicit path with nothing installed in it, and no lock entry for the -/// gem: the copy in the `gem env` home is another project's. Nothing is -/// written, and the record is a skip of its own that names the copy and -/// the `rollback` that drops the record. It is not "not installed", and -/// it does not fail the run. +/// Explicit path with nothing installed in it, and a lock that does not +/// list the gem: the copy in the `gem env` home is another project's. +/// Nothing is written, and the record is a skip of its own that names the +/// copy and the `rollback` that drops the record. It is not "not +/// installed", and it does not fail the run. #[test] fn explicit_path_with_only_another_projects_copy_is_a_calm_skip() { let fx = build_fixture( @@ -315,6 +333,7 @@ fn explicit_path_with_only_another_projects_copy_is_a_calm_skip() { ORIGINAL, QUALIFIED_PURL, ); + write_lock_without_the_gem(&fx); let (code, stdout, stderr) = run_apply(&fx, &["--json"]); let env = parse_env(&stdout); @@ -333,9 +352,10 @@ fn explicit_path_with_only_another_projects_copy_is_a_calm_skip() { find_event(&env, "skipped", NOT_INSTALLED).is_none(), "the gem is installed, elsewhere.\nenvelope: {env}" ); - let skip = find_skip_event(&env) - .unwrap_or_else(|| panic!("the copy must be a {SKIP_CODE} skip.\nenvelope: {env}")); + let skip = find_other_project_skip(&env) + .unwrap_or_else(|| panic!("the copy must be a {OTHER_PROJECT} skip.\nenvelope: {env}")); assert_eq!(skip["purl"], QUALIFIED_PURL, "envelope: {env}"); + assert!(find_skip_event(&env).is_none(), "envelope: {env}"); let reason = skip["reason"].as_str().unwrap_or_default(); let rollback = format!( "socket-patch rollback {BASE_PURL} --cwd {}", @@ -370,8 +390,53 @@ fn explicit_path_with_only_another_projects_copy_is_a_calm_skip() { assert_eq!(format!("{stdout}{stderr}"), ""); } -/// The gem in no gem home at all, and in no lock: nothing says where it -/// is, so this stays the all-miss failure of any package that is not +/// A project with no `Gemfile.lock` (a gem library that commits none): +/// nothing was read that could say the project does not use the gem, so +/// the copy in the `gem env` home is not called another project's and no +/// `rollback` is advised. The gem may be the project's own, not installed +/// in its path yet: it keeps the not-installed result, which fails a run +/// that matched nothing. +#[test] +fn lockless_project_keeps_the_not_installed_result() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + assert!(!fx.project.path().join("Gemfile.lock").exists()); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 1, "envelope: {env}\nstderr:\n{stderr}"); + let skip = find_event(&env, "skipped", NOT_INSTALLED) + .unwrap_or_else(|| panic!("the gem must be reported as {NOT_INSTALLED}.\nenvelope: {env}")); + assert_eq!(skip["purl"], QUALIFIED_PURL, "envelope: {env}"); + assert!(find_other_project_skip(&env).is_none(), "envelope: {env}"); + assert!(!stdout.contains("rollback"), "envelope: {env}"); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 1, "stdout={stdout}\nstderr={stderr}"); + assert!( + stderr.contains("Error: The targeted manifest patch matched no installed package:"), + "stderr={stderr}" + ); + assert!( + !stderr.contains("another project") && !stderr.contains("rollback"), + "stderr={stderr}" + ); + assert!( + stdout.contains( + "Summary: 0 of 1 targeted patch applied, 0 already patched, 1 not found on disk" + ), + "stdout={stdout}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// The gem in no gem home at all, and not in the lock: nothing says where +/// it is, so this stays the all-miss failure of any package that is not /// installed. #[test] fn gem_with_no_copy_anywhere_and_no_lock_entry_still_fails() { @@ -381,6 +446,7 @@ fn gem_with_no_copy_anywhere_and_no_lock_entry_still_fails() { ORIGINAL, QUALIFIED_PURL, ); + write_lock_without_the_gem(&fx); std::fs::remove_dir_all(home_dir(&fx).join("gems").join("rack-3.1.0")).unwrap(); let (code, stdout, stderr) = run_apply(&fx, &["--json"]); @@ -389,7 +455,7 @@ fn gem_with_no_copy_anywhere_and_no_lock_entry_still_fails() { let skip = find_event(&env, "skipped", NOT_INSTALLED) .unwrap_or_else(|| panic!("the gem must be reported as {NOT_INSTALLED}.\nenvelope: {env}")); assert_eq!(skip["purl"], QUALIFIED_PURL, "envelope: {env}"); - assert!(find_skip_event(&env).is_none(), "envelope: {env}"); + assert!(find_other_project_skip(&env).is_none(), "envelope: {env}"); let (code, stdout, stderr) = run_apply(&fx, &[]); assert_eq!(code, 1, "stdout={stdout}\nstderr={stderr}"); @@ -428,7 +494,7 @@ fn gem_the_lock_holds_as_a_platform_build_is_not_another_projects() { let (code, stdout, stderr) = run_apply(&fx, &["--json"]); let env = parse_env(&stdout); assert!( - find_skip_event(&env).is_none(), + find_other_project_skip(&env).is_none(), "the gem is the project's.\nenvelope: {env}" ); assert!( @@ -446,6 +512,7 @@ fn gem_the_lock_holds_as_a_platform_build_is_not_another_projects() { #[test] fn another_projects_copy_beside_a_patched_gem_is_a_skip_not_a_warning() { let fx = build_fixture(Store::Explicit, Home::DefaultGem, ORIGINAL, QUALIFIED_PURL); + write_lock(&fx); // A second record, for a gem only the gem env home holds. let other = home_dir(&fx) .join("gems") @@ -623,6 +690,7 @@ fn bundler_in_the_gem_env_home_is_patched_and_checked() { ORIGINAL, QUALIFIED_PURL, ); + write_lock_without_the_gem(&fx); let home = home_dir(&fx); std::fs::remove_dir_all(home.join("gems").join("rack-3.1.0")).unwrap(); let file = home @@ -637,17 +705,18 @@ fn bundler_in_the_gem_env_home_is_patched_and_checked() { b"", ) .unwrap(); - // A gem whose name only starts with `bundler-` is an ordinary gem. - let audit = home + // A gem whose name only starts with `bundler-` is an ordinary gem, + // even when a digit follows. + let other = home .join("gems") - .join("bundler-audit-0.9.2") + .join("bundler-2fa-1.0.0") .join("lib") - .join("bundler-audit.rb"); - std::fs::create_dir_all(audit.parent().unwrap()).unwrap(); - std::fs::write(&audit, ORIGINAL).unwrap(); + .join("bundler-2fa.rb"); + std::fs::create_dir_all(other.parent().unwrap()).unwrap(); + std::fs::write(&other, ORIGINAL).unwrap(); let patched = patched_bytes(); const BUNDLER: &str = "pkg:gem/bundler@2.6.9?platform=ruby"; - const AUDIT: &str = "pkg:gem/bundler-audit@0.9.2?platform=ruby"; + const OTHER: &str = "pkg:gem/bundler-2fa@1.0.0?platform=ruby"; write_manifest( fx.project.path(), json!({ @@ -655,9 +724,9 @@ fn bundler_in_the_gem_env_home_is_patched_and_checked() { "66616c6c-6261-4b63-8368-6f6d65000002", one_file("lib/bundler.rb", ORIGINAL, &patched), ), - AUDIT: patch_record( + OTHER: patch_record( "66616c6c-6261-4b63-8368-6f6d65000003", - one_file("lib/bundler-audit.rb", ORIGINAL, &patched), + one_file("lib/bundler-2fa.rb", ORIGINAL, &patched), ), }), ); @@ -674,13 +743,13 @@ fn bundler_in_the_gem_env_home_is_patched_and_checked() { assert_eq!(env["summary"]["applied"], 1, "envelope: {env}"); assert_eq!(std::fs::read(&file).unwrap(), patched); assert_eq!( - std::fs::read(&audit).unwrap(), + std::fs::read(&other).unwrap(), ORIGINAL, - "bundler-audit is another project's gem" + "bundler-2fa is another project's gem" ); - let skip = find_skip_event(&env) - .unwrap_or_else(|| panic!("bundler-audit must be a {SKIP_CODE} skip.\nenvelope: {env}")); - assert_eq!(skip["purl"], AUDIT, "envelope: {env}"); + let skip = find_other_project_skip(&env) + .unwrap_or_else(|| panic!("bundler-2fa must be a {OTHER_PROJECT} skip.\nenvelope: {env}")); + assert_eq!(skip["purl"], OTHER, "envelope: {env}"); let (code, stdout, stderr) = run_apply(&fx, &["--check"]); assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); @@ -733,6 +802,38 @@ fn rollback_restores_a_home_copy_an_earlier_run_patched() { ); } +/// A copy in the `gem env` home that an earlier release patched BESIDE +/// the project's own copy stays patched, and `apply` says nothing of it. +/// `rollback --preserve-state` restores both and keeps the record, and +/// the `apply` after it patches the project's copy alone. +#[test] +fn rollback_preserving_state_then_apply_unpatches_only_the_shared_copy() { + let patched = patched_bytes(); + let fx = build_fixture(Store::Explicit, Home::Installed, &patched, QUALIFIED_PURL); + write_lock(&fx); + let store_file = fx.store_file.as_ref().unwrap(); + std::fs::write(store_file, &patched).unwrap(); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + !format!("{stdout}{stderr}").contains(&home_dir(&fx).display().to_string()), + "apply does not mention the shared copy.\nstdout={stdout}\nstderr={stderr}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), patched); + + let (code, stdout, stderr) = run_command(&fx, &["rollback"], &["--preserve-state"]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!(std::fs::read(store_file).unwrap(), ORIGINAL); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); + assert_eq!(manifest_purls(&fx), vec![QUALIFIED_PURL.to_string()]); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!(std::fs::read(store_file).unwrap(), patched); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + /// The `rollback` that `apply` names for another project's copy works /// whatever that copy holds: one an earlier release patched is restored, /// and one nothing ever wrote (as published, or with other content) is @@ -748,6 +849,7 @@ fn rollback_of_another_projects_copy_drops_the_record_whatever_it_holds() { (diverged.as_slice(), diverged.as_slice()), ] { let fx = build_fixture(Store::ExplicitEmpty, Home::Installed, held, QUALIFIED_PURL); + write_lock_without_the_gem(&fx); let (code, stdout, stderr) = run_apply(&fx, &["--json"]); assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); diff --git a/crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs b/crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs index 9f3f648092..cc65b57fbc 100644 --- a/crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs +++ b/crates/socket-patch-cli/tests/get/get_gem_unloaded_homes.rs @@ -143,7 +143,12 @@ async fn exact_purl_of_a_foreign_gem_is_recorded_and_its_copy_left_alone() { let env = parse_json_envelope(&stdout); assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); assert!( - has_event(&env, "skipped", "gem_fallback_home_skipped", &RACK.record()), + has_event( + &env, + "skipped", + "gem_other_project_copy_skipped", + &RACK.record() + ), "envelope: {env}" ); assert!(event_purls(&env, "applied").is_empty(), "envelope: {env}"); diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs b/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs index 63f0110092..22f8b87e9d 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs @@ -74,6 +74,17 @@ pub async fn gem_platform_only_purls_in(view: &ProjectView<'_>) -> Vec { } } +/// Whether bundler loads a lock here and socket-patch read it. `false` for +/// a project with no lock yet (a gem library that commits none) and for the +/// layouts [`unsupported_gem_layout_in`] reports. Only a lock that was read +/// can say that the project does not use a gem. +pub async fn gem_lock_read_in(view: &ProjectView<'_>) -> bool { + match bundler_loaded_lock_in(view).await { + Some(lock) => view.read_text(lock).await.is_ok(), + None => false, + } +} + /// The builds the Bundler lock bundler loads names for each gem of `purls` /// ([`locked_gem_builds`](crate::formats::gem::locked_gem_builds)): element /// `i` answers `purls[i]`. Empty for every gem when bundler loads no lock diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs b/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs index 6104bdc1df..b79ab405cb 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs @@ -76,7 +76,7 @@ pub(crate) mod vlt; pub(crate) mod yarn; pub use self::bun::{bun_binary_lock_drives, bun_text_lock_drives}; -pub use self::gem::{gem_locked_builds_in, gem_platform_only_purls_in}; +pub use self::gem::{gem_lock_read_in, gem_locked_builds_in, gem_platform_only_purls_in}; pub(crate) use self::npm::{ npm_lock_bundled_nodes, npm_lock_entries, npm_lock_legacy_mirror_nodes, npm_lock_located_nodes, NpmLockEntry, NpmLockNode, NpmLockSection, From bc3fe4e4a7c3dc3ce2f8510f12d4e0d15920b9db Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 18:01:29 -0500 Subject: [PATCH 17/20] Document the lock condition, the new skip code and two gaps CLI_CONTRACT.md and docs/ecosystems.md follow the code: a gem is called another project's only under a lock that was read, the skip is `gem_other_project_copy_skipped` with its own table row, and `get --save-only` records by name. Two things are stated and not changed. A copy in a shared gem home that a release up to 5.1.0 patched beside the project's own copy stays patched after an upgrade, and `apply` does not mention it: `rollback --preserve-state` restores both copies and keeps the record, and the `apply` after it patches the project's copy alone. And an agent-mode scan does not report a gem the lock holds only as precompiled platform builds as not installed, with or without a copy in a `gem env` home. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 58 +++++++++++++++---------- docs/ecosystems.md | 28 ++++++++---- 2 files changed, 55 insertions(+), 31 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 8a50e7bab5..2b33b128f8 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1572,33 +1572,42 @@ the model is **not uniform** today: like every other gem, into the path, so a copy of it in a `gem env` home belongs to other projects on the machine and is never written. - A gem with no copy `apply` writes is one of two things: + A gem with no copy `apply` writes is one of three things: - **in the project's lock**: not installed yet (a fresh clone before `bundle install`). It is `package_not_installed` with the lockfile-only detail, a calm skip, exit 0; - - **not in the lock, with a copy in a `gem env` home**: another project's gem. (A gem the lock - holds only as precompiled platform builds is in the lock: it stays `package_not_installed`, - with the result a package that is not installed has.) Its record (one - an earlier release wrote when it patched that copy, or one a `get` of the exact purl wrote) is - a `skipped` event with `errorCode: gem_fallback_home_skipped`, whose detail names the copy, - says why it was left, and gives the command that drops the record - (`socket-patch rollback `, with `--cwd` when the run had one); the human run prints it - as a `Warning:`, and the summary counts the patch as `not applicable`. It never fails the - run and is not counted as an all-miss. A gem with no copy anywhere and no lock entry keeps the - all-miss error (exit 1). + - **not in a lock that was read, with a copy in a `gem env` home**: another project's gem. Its + record (one an earlier release wrote when it patched that copy, or one a `get` of the exact + purl wrote) is a `skipped` event with `errorCode: gem_other_project_copy_skipped`, keyed by + the manifest key, whose detail names the copy, says why it was left, and gives the command + that drops the record (`socket-patch rollback `, with `--cwd` when the run had one); the + human run prints it as a `Warning:`, and the summary counts the patch as `not applicable`. It + never fails the run and is not counted as an all-miss; + - **anything else**: `package_not_installed`, with the result a package that is not installed + has (the all-miss error, exit 1, when no targeted patch matched). That covers a gem with no + copy anywhere, a gem the lock holds only as precompiled platform builds (the lock names it, + so it is the project's), and every gem of a project whose Bundler lock was not read: a + project with no lock yet (a gem library that commits none), and the layouts reported as + `gem_lock_unsupported` (an unsupported `BUNDLE_GEMFILE` / `BUNDLE_LOCKFILE`, a `Gemfile` + + `gems.rb` twin). Only a lock that was read can say the project does not use a gem, so no + `rollback` is advised there. `scan --mode agent` and `get` in agent mode select by the same rule, so that neither records a patch its apply step has no copy to write. A gem whose every copy is one `apply` does not write - is not installed for the project. The scan leaves it out of the crawl: one the lock lists is - then lockfile-only, exactly as when no gem home holds it (`notInstalled`, skipped as - `package_not_installed` before any download, nothing recorded), and one the lock does not list - is no candidate at all (not counted in `scannedPackages`, not queried, not shown). `get ` + is not installed for the project, whether or not a lock was read. The scan leaves it out of the + crawl: one the lock lists is then lockfile-only, exactly as when no gem home holds it + (`notInstalled`, skipped as `package_not_installed` before any download, nothing recorded), and + any other is no candidate at all (not counted in `scannedPackages`, not queried, not shown), + like a gem that is installed nowhere. That includes a gem the lock holds only as precompiled + platform builds: an agent-mode scan's lockfile supplement never names those, so such a gem is + not reported as not installed, with or without a copy in a `gem env` home. `get ` resolves a name among the installed packages, so such a gem's name matches nothing, and - `get ` narrows it away as `package_not_installed`. An exact purl is never narrowed, - for any package: `get pkg:gem/@` records the patch, and the apply step reports - one of the two cases above. The prune pass (`--prune` / `--sync`) still counts such a copy as - installed, so a record an earlier release wrote for it is kept until `rollback` or `remove` - drops it. + `get ` narrows it away as `package_not_installed`. `--save-only` applies nothing and + is not narrowed: by name, advisory or purl it records the patch. An exact purl is never + narrowed, for any package: `get pkg:gem/@` records the patch, and the apply + step reports one of the three cases above. The prune pass (`--prune` / `--sync`) still counts + such a copy as installed, so a record an earlier release wrote for it is kept until `rollback` + or `remove` drops it. `apply --check` and `vex` judge the copies `apply` writes. `rollback` and `remove` restore a copy in a `gem env` home that holds the patch, because a release before this rule may have patched it @@ -1606,7 +1615,11 @@ the model is **not uniform** today: whatever its content, and its record is dropped as for a package that is not installed (never a `hash_mismatch` failure over another project's edit). A copy in a shared gem home that another project patched with the same patch, in system-gems mode, cannot be told from one this - project's earlier release patched, so `rollback` and `remove` here restore it too. A `--global` + project's earlier release patched, so `rollback` and `remove` here restore it too. A copy there + that an earlier release patched BESIDE the project's own bundle-path copy stays patched after an + upgrade, and `apply` says nothing of it: the project's copy is the one it writes and reports. + `socket-patch rollback --preserve-state` restores both copies and keeps the record, and + the `socket-patch apply` after it patches the project's copy alone. A `--global` run patches the `gem env` homes as before. Once the default `vendor/bundle` root holds a store, no local run searches those homes: a default gem there is not patched, and `rollback` leaves a copy an earlier run patched there, keeps its manifest record and names @@ -2533,7 +2546,8 @@ command's integration tests check its output. |---------------------------|------------------|---------| | `already_patched` | `skipped` | apply: every file's hash already matches `afterHash`. | | `not_in_platform_build` | `skipped` | apply (gem): the installed copy is the JRuby (`java`) build of the gem and no file of the patch is part of that build (a patch to the C extension or a library it packs). Nothing was written and nothing is left to do: the code the patch changes is not in that build, `apply --check` is in sync and `vex` attests the package (`vulnerable_code_not_present`), and a nested `scan --mode agent` counts the patch among those in place, as it counts `already_patched`. `reason` says so in plain words. rollback (gem): the same copy; nothing of the patch was applied to it, so nothing was restored. See "The JRuby build of a gem". | -| `gem_fallback_home_skipped` | `skipped` | apply (gem), and the apply that `get` / `scan --mode agent` run: a copy in a `gem env` home (the system gems, `~/.gem`, an rbenv or asdf home) was left unpatched and the run stands. Either the copy is best-effort (a bundle-path copy of the gem applied, and this one matched no variant or could not be written), or it is another project's gem (Bundler does not load the project's gems from that home, no lock of the project lists the gem, and no other copy exists): the detail then gives `socket-patch rollback `, which drops the record and restores the copy if an earlier release patched it. Never flips status or exit; the human summary counts the second kind as `not applicable`. See "Copy classes". | +| `gem_fallback_home_skipped` | `skipped` | apply (gem), and the apply that `get` / `scan --mode agent` run: a best-effort copy in a `gem env` home (the system gems, `~/.gem`, an rbenv or asdf home) was left unpatched, because it matched no variant or could not be written, while a bundle-path copy of the gem applied. The patch IS in effect on the copy bundler loads. Keyed by the base purl; the detail names the copy's path and the reason. Never flips status or exit. See "Copy classes". | +| `gem_other_project_copy_skipped` | `skipped` | apply (gem), and the apply that `get` / `scan --mode agent` run: the record is for another project's gem. Its every copy sits in a `gem env` home Bundler does not load the project's gems from, and the project's Bundler lock, which was read, does not list it. Nothing was applied. Keyed by the manifest key; the detail names the copy and gives `socket-patch rollback `, which drops the record and restores the copy if an earlier release patched it. Never flips status or exit; the human summary counts the patch as `not applicable`. With no lock read the gem is `package_not_installed` instead. See "Copy classes". | | `package_not_installed` | `skipped` | apply: manifest entry has no matching installed package (an installed gem or PyPI copy that holds a patched file with content no record of its release was made for is `no_matching_variant` instead). When the project's lockfiles resolve the purl (a platform-gated optional dependency, a devDependency under `--omit=dev`), the detail says it is lockfile-only and the entry never fails the run, even when no other patch matched; only an all-miss run with an unmatched purl that no lock resolves exits 1 (`partialFailure`). **Cargo is never lockfile-only (v5.0, #616)**: `cargo fetch` unpacks every `Cargo.lock` entry (target-gated ones included), so a locked crate missing from `$CARGO_HOME/registry/src` was simply not fetched yet (a cold CI cache, a pruned `registry/src`) and the next `cargo build` would compile it unpatched; it counts as an unresolved purl (an all-miss run exits 1, as in 4.x) and its detail, the human error and the human warning say to run `cargo fetch` first. A crate `Cargo.lock` takes from a path, git, `[patch]` or `[replace]` source is never looked up in the registry cache (#506): cargo does not build that copy, so the same detail also names that case. | | `apply_failed` | `failed` | apply: hash mismatch, write error, archive read error. Also a manifest key that is not a purl (see `invalid_purl`). The copy is left as it was: every file is staged (its blob read and hash-checked, with the file's final mode and owner) before the first is renamed into place, and a rename that fails puts the files already replaced back. The `error` names the file (`Cannot apply patch: - `); a blob that does not hold its hash's bytes is named with the remedy (`blob is corrupt … Run \`socket-patch repair\``). Only when putting a file back fails too does the `error` end with the files left changed; the original of such a file is kept beside it as `.socket-kept--`, a name no later run removes. A run killed between two renames can still leave some files patched; the next `apply` finishes it. A killed run also leaves `.socket-stage--` / `.socket-orig--` files beside the patch's files (staged content and the second names of the files being replaced, never the package's own content); an `apply` or `rollback` of that package removes them once they are ten minutes old. | | `native_extension_not_rebuilt` | `failed` | apply (gem), and the apply that `get` / `scan --mode agent` run: the patch is incomplete. Its files were written into the installed copy and are left there (unlike `apply_failed`, where the copy is as it was), and the compiled code the copy runs is not the patch's: the build compiled nothing of it, or, on the JRuby build of a gem, the patch changes sources of the gem's jars and does not bring the jars. `error` says what was written and what is not in effect; `files` lists what this run wrote. The run exits 1 (`partialFailure`), the patch stays recorded, `apply --check` is out of sync and `vex` does not attest it; `rollback` restores the files. The same code is a `warnings[]` entry of the run, and the `apply --check` / `vex` tag of such a copy. See "A build that builds nothing of the patch". | diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 8b3394cf51..ebc040afba 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5309,8 +5309,9 @@ no other: An agent-mode scan, and `get` by package name or by advisory, select patches by the same rule. A gem that is only in a shared gem home is not installed for this project. If `Gemfile.lock` lists it, the scan reports it as not installed yet and records nothing, as it does when no gem home -holds it. If the lock doesn't list it, it is another project's: the scan doesn't report it, a -name finds no package, and an advisory skips that version as not installed. +holds it. Otherwise the scan doesn't report it, a name finds no package, and an advisory skips +that version as not installed. (`get --save-only` only records a patch, so it still finds the gem +by name.) On a fresh clone with a `path`, run `bundle install` before `apply`. Before it the path holds no gem, so `apply` patches nothing and reports the gems `Gemfile.lock` lists as not installed (`0 of @@ -5319,8 +5320,9 @@ for a gem that no lock lists and no gem home holds makes a run that matched noth for any package that is not installed. Releases up to 5.1.0 patched a copy in a shared gem home under a `path` as well, and their scans -recorded patches for other projects' gems. `apply` skips such a record with a warning that names -the copy and the command to run (`1 not applicable` in the summary, exit 0): +recorded patches for other projects' gems. When `Gemfile.lock` doesn't list the gem, `apply` +skips such a record with a warning that names the copy and the command to run (`1 not applicable` +in the summary, exit 0): ``` socket-patch rollback pkg:gem/rack@2.2.8 @@ -5329,11 +5331,19 @@ socket-patch rollback pkg:gem/rack@2.2.8 It removes the patch from the manifest and restores the copy if it still holds the patch. A copy that doesn't hold it is left as it is, whatever it holds, since it is another project's. Another project that patched the same copy with the same patch, with no `path` of its own, can't be told -apart: its copy is restored too, and its own `apply` patches it again. Once `vendor/bundle` holds -the project's gems, `rollback` and `remove` look only there: `rollback` then keeps the patch -recorded and warns that the shared copy is still patched, naming the command that restores it -(`socket-patch rollback -g`). `apply --global` patches the gems in the shared gem homes -whatever the project's Bundler settings are. +apart: its copy is restored too, and its own `apply` patches it again. A project with no +`Gemfile.lock` can't tell `apply` that the gem is not its own, so there the record is reported +as not installed, like any other, and the same command removes it. + +A shared copy that such a release patched beside the project's own copy of the same gem stays +patched after the upgrade, and `apply` doesn't mention it. To restore it, run +`socket-patch rollback --preserve-state`, which restores both copies and keeps the patch +recorded, and then `socket-patch apply`, which patches the project's copy alone. + +Once `vendor/bundle` holds the project's gems, `rollback` and `remove` look only there: +`rollback` then keeps the patch recorded and warns that the shared copy is still patched, naming +the command that restores it (`socket-patch rollback -g`). `apply --global` patches the +gems in the shared gem homes whatever the project's Bundler settings are. ## Ruby gems: gems vendored mode refuses From a32963e674a65e1d58885bb4f39a1476e940bdb9 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 18:07:24 -0500 Subject: [PATCH 18/20] Pin a lock on disk that bundler may not load With a `gems.rb` beside the `Gemfile`, which pair loads depends on the Bundler that runs, so the `Gemfile.lock` on disk is not read. A gem whose only copy sits in a `gem env` home then keeps the not-installed result, as in a project with no lock: nothing calls it another project's, and no `rollback` is advised. Co-Authored-By: Claude Fable 5.2 --- .../apply/in_process_gem_fallback_home.rs | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs index f4d624333f..bf5739974a 100644 --- a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs +++ b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs @@ -435,6 +435,37 @@ fn lockless_project_keeps_the_not_installed_result() { assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); } +/// A lock on disk that bundler may not load is not a lock that was read: +/// with a `gems.rb` beside the `Gemfile`, which pair loads depends on the +/// Bundler that runs, so the `Gemfile.lock` here says nothing of the gem. +/// It keeps the not-installed result, and no `rollback` is advised. +#[test] +fn unread_lock_of_a_twin_manifest_keeps_the_not_installed_result() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + write_lock_without_the_gem(&fx); + std::fs::write( + fx.project.path().join("gems.rb"), + b"source 'https://rubygems.org'\n", + ) + .unwrap(); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 1, "envelope: {env}\nstderr:\n{stderr}"); + assert!( + find_event(&env, "skipped", NOT_INSTALLED).is_some(), + "envelope: {env}" + ); + assert!(find_other_project_skip(&env).is_none(), "envelope: {env}"); + assert!(!stdout.contains("rollback"), "envelope: {env}"); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + /// The gem in no gem home at all, and not in the lock: nothing says where /// it is, so this stays the all-miss failure of any package that is not /// installed. From bad4acf47fd2519182451e222b3ea875e2897628 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 19:47:13 -0500 Subject: [PATCH 19/20] Box the gem home checks out of the long-lived command frames On Windows the in-process test `remove_base_purl_clears_all_platforms_and_rolls_back` overflowed its 2 MiB test thread stack on this branch and not on main. The branch awaited its new gem checks inline in `scan_project`, `rollback_patches_inner`, `apply_patches_inner` and `get`, and inside `find_all_packages_for_purls`, whose future those callers build in their own frames. A debug build keeps room in the caller's poll frame for each such future, also behind an inline `Box::pin(..)`, and those frames stay on the stack for the whole run, under the deepest chain. Each of those awaits now goes through `boxed`, which builds the future in its own frame so the caller holds a pointer: the candidate filter in scan and get, the rollback target filter, the other-project skip in apply, and the three calls of the shared rule in the resolvers. Measured on macOS as the smallest `RUST_MIN_STACK` at which a test passes (KiB; main, branch before, branch after): the remove test and an in-process rollback test 1972, 1988, 1972; an in-process scan and apply 1892, 1908, 1892. The CLI's main thread (`ulimit -s`) for a gem rollback: 1412, 1428, 1412; for a gem apply 1668 throughout. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/apply.rs | 20 ++++-------- crates/socket-patch-cli/src/commands/get.rs | 32 ++++++++++++------- .../socket-patch-cli/src/commands/rollback.rs | 17 ++++++---- .../socket-patch-cli/src/commands/scan/mod.rs | 16 ++++++---- .../src/ecosystem_dispatch.rs | 8 +++-- 5 files changed, 52 insertions(+), 41 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 6133a4b340..642266935b 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -36,8 +36,8 @@ use crate::commands::vex::{ generate_vex_from_manifest_path, generate_vex_without_manifest, ManifestlessVex, VexEmbedArgs, }; use crate::ecosystem_dispatch::{ - distinct_install_dirs, distinct_npm_copies, find_all_packages_for_purls, partition_purls, - unsupported_ecosystem_report, unsupported_keys, JvmScope, UnsupportedKey, + boxed, distinct_install_dirs, distinct_npm_copies, find_all_packages_for_purls, + partition_purls, unsupported_ecosystem_report, unsupported_keys, JvmScope, UnsupportedKey, }; use crate::json_envelope::{ AppliedVia, Command, Envelope, EnvelopeError, PatchAction, PatchEvent, PatchEventFile, @@ -3815,12 +3815,8 @@ async fn apply_patches_inner( let unresolved = unresolved_purls(&unmatched, &lockfile_only); // Another project's gems are a skip of their own: neither "not // installed" nor a reason to fail. - let other_project = Box::pin(other_project_gem_copies( - &args.common, - &unresolved, - &all_packages, - )) - .await; + let other_project = + boxed(|| other_project_gem_copies(&args.common, &unresolved, &all_packages)).await; unmatched.retain(|purl| !other_project.iter().any(|copy| copy.purl == *purl)); let unresolved = unresolved_purls(&unmatched, &lockfile_only); // This diagnostic flips the exit code, so it is an error — and it @@ -4610,12 +4606,8 @@ async fn apply_patches_inner( let unresolved = unresolved_purls(&unmatched, &lockfile_only); // Another project's gems are a skip of their own: neither "not // installed" nor a reason to fail. - caveats.other_project = Box::pin(other_project_gem_copies( - &args.common, - &unresolved, - &all_packages, - )) - .await; + caveats.other_project = + boxed(|| other_project_gem_copies(&args.common, &unresolved, &all_packages)).await; unmatched.retain(|purl| !caveats.other_project.iter().any(|copy| copy.purl == *purl)); let unresolved = unresolved_purls(&unmatched, &lockfile_only); diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index 190c41c8a5..9a6c0e60ac 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -1050,12 +1050,16 @@ async fn filter_to_installed_purls( // does not load this project's gems from) is not installed here, as in // `scan --mode agent` (#2313). if mode == super::scan::ScanMode::Agent { - let unloaded = crate::ecosystem_dispatch::gems_apply_never_writes( - found - .iter() - .map(|(purl, path)| (purl.clone(), path.clone())), - &common.crawler_options(), - ) + let options = common.crawler_options(); + // Boxed: the caller's frame holds a pointer, not the future. + let unloaded = crate::ecosystem_dispatch::boxed(|| { + crate::ecosystem_dispatch::gems_apply_never_writes( + found + .iter() + .map(|(purl, path)| (purl.clone(), path.clone())), + &options, + ) + }) .await; found.retain(|purl, _| !unloaded.contains(purl)); } @@ -1649,12 +1653,16 @@ pub async fn run(args: GetArgs) -> i32 { // applies nothing, and records by name as it does by purl or // advisory. if mode == super::scan::ScanMode::Agent && !args.save_only { - let unloaded = crate::ecosystem_dispatch::gems_apply_never_writes( - all_packages - .iter() - .map(|pkg| (pkg.purl.clone(), pkg.path.clone())), - &args.common.crawler_options(), - ) + let options = args.common.crawler_options(); + // Boxed: `run`'s frame holds a pointer, not the future. + let unloaded = crate::ecosystem_dispatch::boxed(|| { + crate::ecosystem_dispatch::gems_apply_never_writes( + all_packages + .iter() + .map(|pkg| (pkg.purl.clone(), pkg.path.clone())), + &options, + ) + }) .await; all_packages.retain(|pkg| !unloaded.contains(&pkg.purl)); } diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index f39394b5c0..daa48cbd42 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -3482,12 +3482,17 @@ pub(crate) async fn rollback_patches_inner( common.silent || common.json, ) .await; - drop_untouched_unloaded_gem_copies( - &mut all_packages_multi, - &scoped_manifest, - &crawler_options, - &socket_dir.join("blobs"), - ) + // Boxed, so this frame, which stays on the stack for the whole + // rollback, holds a pointer and not the future (see `boxed`). + let blobs_dir = socket_dir.join("blobs"); + crate::ecosystem_dispatch::boxed(|| { + drop_untouched_unloaded_gem_copies( + &mut all_packages_multi, + &scoped_manifest, + &crawler_options, + &blobs_dir, + ) + }) .await; // The shared-cache copies of the vendored Cargo crates restored above // (#336), including those a `cargo vendor` dir hides from the crawl. diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 95fbe93bec..489d3b17bb 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -2601,12 +2601,16 @@ async fn scan_project( // the prune universe: the copies are on disk, and a record an earlier // release wrote for one must stay until `rollback` restores it. let unloaded_gems = if apply { - let unloaded = crate::ecosystem_dispatch::gems_apply_never_writes( - all_crawled - .iter() - .map(|pkg| (pkg.purl.clone(), pkg.path.clone())), - &crawler_options, - ) + // Boxed, so this frame, which stays on the stack for the whole + // scan, holds a pointer and not the future (see `boxed`). + let unloaded = boxed(|| { + crate::ecosystem_dispatch::gems_apply_never_writes( + all_crawled + .iter() + .map(|pkg| (pkg.purl.clone(), pkg.path.clone())), + &crawler_options, + ) + }) .await; all_crawled.retain(|pkg| !unloaded.contains(&pkg.purl)); unloaded diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index b314e3f8ad..0004acc1a4 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -873,7 +873,9 @@ pub async fn find_all_packages_for_purls( ) .await; retain_locked_cargo_copies(&mut found, options).await; - retain_bundler_loaded_gem_copies(&mut found, options).await; + // Boxed, so that this future, which its callers build in their own + // frames, does not grow by the gem probes. + boxed(|| retain_bundler_loaded_gem_copies(&mut found, options)).await; found } @@ -982,7 +984,7 @@ pub(crate) async fn gems_apply_never_writes( .map(|(purl, path)| (purl, vec![path])) .collect(); let crawled: Vec = copies.keys().cloned().collect(); - retain_bundler_loaded_gem_copies(&mut copies, options).await; + boxed(|| retain_bundler_loaded_gem_copies(&mut copies, options)).await; let ruled_out: Vec = crawled .into_iter() .filter(|purl| !copies.contains_key(purl)) @@ -1478,7 +1480,7 @@ pub async fn find_manifest_package_copies_reusing( ) .await; // Only the gem copies Bundler loads for the project, as for `apply`. - retain_bundler_loaded_gem_copies(&mut copies, &crawler_options).await; + boxed(|| retain_bundler_loaded_gem_copies(&mut copies, &crawler_options)).await; copies.retain(|_, paths| !paths.is_empty()); // Verification also READS a `.bundle/config` bundle path the crawler // refused as a write root (it resolves outside the project): bundler From 1c74732b23fa7abd002b69a6ee55986bdeba929c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 01:35:09 +0000 Subject: [PATCH 20/20] Box the hand-offs of the scan to gem apply chain The Windows run of this branch still overflowed the 2 MiB test thread in `remove_base_purl_clears_all_platforms_and_rolls_back`. The overflow is in the test's first step, the in-process scan that downloads and applies, not in the remove: scan -> download -> nested apply -> apply loop -> gem patch is the deepest chain of the CLI, and a debug build keeps each callee's future in its caller's poll frame. That chain had no room left before this branch. Measured on Linux as the smallest `RUST_MIN_STACK` at which the test passes, main needs 1996 KiB of the 2048 and this branch needed 1999, which is enough to tip a Windows debug build over. The four hand-offs of the chain now go through `boxed`, so each caller's frame holds a pointer: the download and apply in scan, the nested apply in the download engine, `apply_patches_inner`, and the gem patch in the apply loop. The same test now needs 1816 KiB, 180 below main. Nothing else changes: the same futures run in the same order. The shipped binary was never at risk, its main thread has 8 MiB on every platform. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeRtYGshMQUt3iHo5jY Assisted-by: Claude Code:claude-fable-5-2 --- .../src/commands/agent_download.rs | 23 ++++++---- crates/socket-patch-cli/src/commands/apply.rs | 43 ++++++++++++------- .../socket-patch-cli/src/commands/scan/mod.rs | 12 +++--- 3 files changed, 47 insertions(+), 31 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/agent_download.rs b/crates/socket-patch-cli/src/commands/agent_download.rs index 52175644d2..02661a20d2 100644 --- a/crates/socket-patch-cli/src/commands/agent_download.rs +++ b/crates/socket-patch-cli/src/commands/agent_download.rs @@ -2586,16 +2586,21 @@ pub async fn download_and_apply_patches_into( // Past the network, about to write to installed packages: a // hot-patch pass is no longer dropped at its time limit. crate::hot_patch::mark_apply_started(); + // Boxed: this frame stays under the whole nested apply (see + // `boxed`). + let command = telemetry_command(env); apply_report = Some( - run_nested_apply( - telemetry_command(env), - nested_apply_args_from_params(params, run, &manifest_path), - params.json, - !params.user_patch_skips_reported, - &recorded, - run.api_client, - lock, - ) + crate::ecosystem_dispatch::boxed(|| { + run_nested_apply( + command, + nested_apply_args_from_params(params, run, &manifest_path), + params.json, + !params.user_patch_skips_reported, + &recorded, + run.api_client, + lock, + ) + }) .await, ); } diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 642266935b..899b664147 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -2061,7 +2061,12 @@ pub(crate) async fn run_locked( NpmPkgManager::Npm | NpmPkgManager::YarnClassic | NpmPkgManager::Unknown => {} } - match apply_patches_inner(&args, manifest, &user_patched, client).await { + // Boxed: this frame stays under the whole apply (see `boxed`). + let outcome = crate::ecosystem_dispatch::boxed(|| { + apply_patches_inner(&args, manifest, &user_patched, client) + }) + .await; + match outcome { Ok(ApplyOutcome { success, results, @@ -4209,21 +4214,27 @@ async fn apply_patches_inner( // fails the run (#2144). The JRuby build of a gem takes // the files that are part of it, and builds nothing. let result = if Ecosystem::from_purl(purl) == Some(Ecosystem::Gem) { - let outcome = gem_ext::apply_gem_package_patch( - args.common.read_scope(), - variant_purl, - pkg_path, - &patch.files, - &sources, - args.common.dry_run, - policy, - &gem_ext::RubyEnv { - cwd: args.common.cwd.clone(), - rebuild: !args.common.no_gem_native_rebuild, - offline: args.common.offline, - progress: args.common.gem_build_progress(), - }, - ) + let ruby_env = gem_ext::RubyEnv { + cwd: args.common.cwd.clone(), + rebuild: !args.common.no_gem_native_rebuild, + offline: args.common.offline, + progress: args.common.gem_build_progress(), + }; + // Boxed: the gem future is the largest this loop + // awaits, and this frame is under its whole + // rebuild (see `boxed`). + let outcome = crate::ecosystem_dispatch::boxed(|| { + gem_ext::apply_gem_package_patch( + args.common.read_scope(), + variant_purl, + pkg_path, + &patch.files, + &sources, + args.common.dry_run, + policy, + &ruby_env, + ) + }) .await; // A best-effort fallback-home copy's refusal, or // its incomplete patch, is its per-copy skip below, diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 489d3b17bb..ba243b791f 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -3944,12 +3944,12 @@ async fn scan_project( ); // The engine records into `env` and never prints: one JSON // document per run, a hard engine error included. - apply_code = download_and_apply_patches_into( - &selected, - ¶ms, - &download_run(&args, &api_client), - &mut env, - ) + // Boxed: this frame is under the whole download and apply + // chain, the deepest of a scan (see `boxed`). + let run = download_run(&args, &api_client); + apply_code = crate::ecosystem_dispatch::boxed(|| { + download_and_apply_patches_into(&selected, ¶ms, &run, &mut env) + }) .await; if env.error.is_some() { env.extra.remove("rollout");