From 7c572ab4322c0db723444c87376ae8a707e9b6dc Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 21:22:59 +0000 Subject: [PATCH 1/4] Start fix for superseded hosted gem takeover Refs #2129. Empty commit that opens the draft PR; the failing test and the fix follow. Assisted-by: Claude Code:claude-fable-5-2 From 81d12e1df4297c92479dcf874b1fdbacf28f4689 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 01:28:44 +0000 Subject: [PATCH 2/4] Test vendoring a hosted gem on a superseded patch Two failing hermetic cases for #2129: a hosted-pinned gem whose installed copy holds an older patch's bytes must be vendored at the newer patch, and a native gem in that state must be refused for its extension. Both report package_not_installed today. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeT7HWFSwgbuzoQv6kJ --- .../tests/e2e_redirect_gem_stale_install.rs | 299 ++++++++++++++++++ 1 file changed, 299 insertions(+) diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index 65ff715e9..a128346ce 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -4167,3 +4167,302 @@ async fn an_agent_patched_install_the_run_may_not_replace_is_warned_about() { assert_eq!(std::fs::read(&cache).unwrap(), patched); assert!(gem_dir.join(".socket-patch-kept").is_file()); } + +// ── a hosted gem whose patch was superseded, taken over by vendored ─── + +/// The newer patch the service publishes for the fixture gem once the +/// project is hosted on [`UUID`]. +const NEWER_UUID: &str = "9b0c1d2e-3f4a-4b5c-8d7e-8f9a0b1c2d3e"; +const NEWER_PATCHED_LIB: &str = + "module StaleProbeGem\n def self.status\n \"PATCHED AGAIN\"\n end\nend\n"; + +/// The patch API once [`NEWER_UUID`] supersedes [`UUID`] (mount it on a +/// reset server): discovery, selection and the view name only the newer +/// patch, and its grant carries the vendored artifacts (the patched `.gem` +/// and the stub gemspec a path source loads) beside the hosted override. +async fn mount_newer_patch(server: &MockServer) { + use base64::Engine as _; + use sha2::Digest as _; + let sri = |bytes: &[u8]| { + format!( + "sha512-{}", + base64::engine::general_purpose::STANDARD.encode(sha2::Sha512::digest(bytes)) + ) + }; + let patched = real_gem(NEWER_PATCHED_LIB); + let stub = format!( + "Gem::Specification.new do |s|\n s.name = \"{DEP}\".freeze\n s.version = \ + \"{DEP_VERSION}\".freeze\n s.authors = [\"e2e\".freeze]\n s.summary = \ + \"fixture\".freeze\n s.files = [\"lib/stale_probe_gem.rb\".freeze]\n s.require_paths \ + = [\"lib\".freeze]\nend\n" + ) + .into_bytes(); + let leaf = format!("{DEP}-{DEP_VERSION}"); + let base = format!("/artifacts/{NEWER_UUID}"); + let gem_url = format!("{}{base}/{leaf}.gem", server.uri()); + let stub_url = format!("{}{base}/{leaf}.gemspec", server.uri()); + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [{ + "purl": PURL, + "patches": [{ + "uuid": NEWER_UUID, "purl": PURL, "tier": "free", + "cveIds": [], "ghsaIds": [], "severity": "high", + "title": "gem stale-install fixture, newer patch" + }] + }], + "canAccessPaidPatches": false, + }))) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path_regex(format!( + "^/v0/orgs/{ORG}/patches/by-package/.+$" + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": [{ + "uuid": NEWER_UUID, "purl": PURL, + "publishedAt": "2026-02-01T00:00:00Z", + "description": "x", "license": "MIT", "tier": "free", + "vulnerabilities": {} + }], + "canAccessPaidPatches": false, + }))) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{NEWER_UUID}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "uuid": NEWER_UUID, + "purl": PURL, + "publishedAt": "2026-02-01T00:00:00Z", + "files": { + "lib/stale_probe_gem.rb": { + "beforeHash": compute_git_sha256_from_bytes(UPSTREAM_LIB.as_bytes()), + "afterHash": compute_git_sha256_from_bytes(NEWER_PATCHED_LIB.as_bytes()), + } + }, + "vulnerabilities": { + GHSA: { + "cves": ["CVE-2026-4444"], + "summary": "gem stale-install fixture vuln", + "severity": "high", + "description": "d" + } + }, + "description": "x", "license": "MIT", "tier": "free" + }))) + .mount(server) + .await; + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "results": { + NEWER_UUID: { + "status": "granted", + "url": gem_url, + "purl": PURL, + "artifacts": [ + { "kind": "tarball", "url": gem_url, + "integrity": { "sha512": sri(&patched), "sha256": sha256_of(&patched) } }, + { "kind": "gem-stub-gemspec", "url": stub_url, + "integrity": { "sha512": sri(&stub) } } + ], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": format!( + "{}/patch-registry/gem/{TOKEN}/{NEWER_UUID}/", + server.uri() + ), + "identifiers": { + "name": DEP, + "version": DEP_VERSION, + "gemChecksumSha256": sha256_of(&patched), + } + } + } + } + }))) + .mount(server) + .await; + for (file, bytes) in [ + (format!("{leaf}.gem"), patched), + (format!("{leaf}.gemspec"), stub), + ] { + Mock::given(method("GET")) + .and(path(format!("{base}/{file}"))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .mount(server) + .await; + } + serve_upstream_gem(server, &real_gem(UPSTREAM_LIB)).await; +} + +/// A project hosted on [`UUID`], with the lock as `bundle install` leaves +/// it and the installed copy holding that patch's bytes, after the service +/// replaced the patch with [`NEWER_UUID`]. Returns the gem home. +async fn hosted_on_a_superseded_patch(server: &MockServer, proj: &Path) -> PathBuf { + let patched = real_gem(PATCHED_LIB); + mount_api_for(server, None, &sha256_of(&patched)).await; + serve_patched_gem(server, patched).await; + std::fs::create_dir_all(proj).unwrap(); + write_manifest_pair(proj); + let home = project_home(proj); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let uri = server.uri(); + let (code, _, stderr) = common::run_with_env(proj, &scan_args(proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "hosted scan:\n{stderr}"); + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise"); + server.reset().await; + mount_newer_patch(server).await; + home +} + +/// The events of `env` that name the fixture gem, as `action/errorCode`. +fn gem_events(env: &serde_json::Value) -> Vec { + env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["purl"].as_str().is_some_and(|p| p.starts_with(PURL))) + .map(|e| { + format!( + "{}/{}", + e["action"].as_str().unwrap_or_default(), + e["errorCode"].as_str().unwrap_or_default() + ) + }) + .collect() +} + +/// #2129: a gem on a hosted patch whose installed copy holds that patch's +/// bytes, after a newer patch was published for the same version. The +/// installed copy matches neither side of the newer patch, but the gem is +/// installed and its lock entry is ours: `scan --mode vendored` vendors +/// the newer patch, as it does on a checkout with no gems installed, and +/// leaves the installed copy alone. The dry run previews the same. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_takeover_of_a_hosted_gem_whose_patch_was_superseded() { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let home = hosted_on_a_superseded_patch(&server, &proj).await; + let uri = server.uri(); + let held_before = snapshot(&home); + let pair_before = ( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + ); + + let (code, stdout, stderr) = unwind_run( + &proj, + &uri, + &["scan", "--mode", "vendored", "--yes", "--json", "--dry-run"], + ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "dry run: {env}\nstderr:\n{stderr}"); + assert!( + !env.to_string().contains("package_not_installed"), + "dry run: {env}" + ); + assert_eq!( + ( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + ), + pair_before, + "the dry run wrote nothing" + ); + assert!(!proj.join(".socket").join("vendor").exists()); + + let (code, stdout, stderr) = unwind_run( + &proj, + &uri, + &["scan", "--mode", "vendored", "--yes", "--json"], + ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert!( + !env.to_string().contains("package_not_installed"), + "the gem is installed: {env}" + ); + let copy_rel = format!(".socket/vendor/gem/{NEWER_UUID}/{DEP}-{DEP_VERSION}"); + let pair = format!( + "{}{}", + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap() + ); + assert!( + pair.matches(©_rel).count() >= 2 && !pair.contains("/patch-registry/"), + "the pair names the newer patch's copy and no hosted pin:\n{pair}\n{env}" + ); + assert_eq!( + installed_lib(&proj.join(©_rel)), + NEWER_PATCHED_LIB, + "the vendored copy is the newer patch" + ); + assert!( + snapshot(&home) == held_before, + "the takeover left the installed copy alone: {env}" + ); +} + +/// #2129, the native-extension half: a hosted gem that builds an +/// extension cannot be vendored, superseded patch or not. The refusal +/// names that (`native_extensions_unsupported`), not a gem that is "not +/// installed", and the hosted pin stays. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_takeover_of_a_superseded_native_gem_names_the_extension() { + for dry_run in [true, false] { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let home = hosted_on_a_superseded_patch(&server, &proj).await; + let spec = home + .join("specifications") + .join(format!("{DEP}-{DEP_VERSION}.gemspec")); + let text = std::fs::read_to_string(&spec).unwrap(); + std::fs::write( + &spec, + text.replace( + " s.require_paths", + " s.extensions = [\"ext/probe/extconf.rb\".freeze]\n s.require_paths", + ), + ) + .unwrap(); + let pair_before = ( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + ); + + let mut args = vec!["scan", "--mode", "vendored", "--yes", "--json"]; + if dry_run { + args.push("--dry-run"); + } + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env = common::parse_json_envelope(&stdout); + let events = gem_events(&env); + assert!( + events + .iter() + .any(|e| e.ends_with("/native_extensions_unsupported")), + "dry_run={dry_run}: {events:?}\n{env}\nstderr:\n{stderr}" + ); + assert!( + !env.to_string().contains("package_not_installed"), + "dry_run={dry_run}: {env}" + ); + assert_ne!(code, 0, "dry_run={dry_run}: {env}"); + assert_eq!( + ( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + ), + pair_before, + "dry_run={dry_run}: the hosted pin stays" + ); + assert!(!proj.join(".socket").join("vendor").exists()); + } +} From abff7a2111ffe30b5c790dd806000697811fb4ed Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 01:31:12 +0000 Subject: [PATCH 3/4] Vendor a hosted gem whose patch was superseded A gem on a hosted patch has that patch's bytes installed. Once a newer patch is published, those bytes match neither side of the new record, so the vendored variant probe skipped the gem and the run reported it as package_not_installed, though it is installed and the dry run previewed success. A sole gem candidate under a live hosted pin now passes the probe with its installed dir as the source. The gem backend takes no file from that dir (the copy is the service's build) and still reads its name and gemspec, so a platform gem or a native extension is refused for what it is. PyPI got the matching exemption earlier. Fixes #2129 Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeT7HWFSwgbuzoQv6kJ --- .../socket-patch-cli/src/commands/vendor.rs | 46 +++- .../tests/e2e_redirect_gem_stale_install.rs | 205 +++++++++--------- 2 files changed, 147 insertions(+), 104 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 5e3fe0690..0d6df2603 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -2860,8 +2860,8 @@ impl StagedSource { /// story after a hosted scan (#1105): `uv sync` / `poetry install` from /// the hosted lock installs a hosted patch's bytes, whichever generation /// the pin names now. The pin names no release variant, so it only answers -/// for a sole candidate; gems keep their installed dir, which the gem -/// backend reads to refuse a platform gem. +/// for a sole candidate. A gem in that state is not superseded but +/// [`hosted_gem_install`]: it keeps its installed dir. fn superseded_install( ledger: &VendorState, candidate: &str, @@ -2876,6 +2876,22 @@ fn superseded_install( && matches!(Ecosystem::from_purl(candidate), Some(Ecosystem::Pypi))) } +/// Whether an installed gem that fails `candidate`'s variant probe is still +/// `candidate` itself, under a live hosted pin (#2129): a hosted scan or a +/// `bundle install` from the hosted lock put a hosted patch's bytes there, +/// and the patch has since been superseded, so they match neither side of +/// this record. The gem backend takes no file of the installed copy (the +/// vendored copy is the service's build), so the candidate goes on with +/// its installed dir as the source: the backend still reads that dir's +/// name and gemspec to refuse a platform gem or a native extension. As for +/// PyPI, the pin names no release variant, so it only answers for a sole +/// candidate. +fn hosted_gem_install(candidate: &str, sole_candidate: bool, hosted_pinned: bool) -> bool { + sole_candidate + && hosted_pinned + && matches!(Ecosystem::from_purl(candidate), Some(Ecosystem::Gem)) +} + /// The stand-in source of a superseded install (see [`superseded_install`]), /// relative to the project root: a path that never exists, so the backend /// takes the pristine artifact from the lock, the registry or the service @@ -3004,16 +3020,22 @@ impl<'a> CandidateGates<'a> { if !variant_matches_installed(Some( &verify_file_patch(dir, file, info).await.status, )) { - if !superseded_install( + let sole_candidate = group.candidates.len() == 1; + let hosted_pinned = (self.hosted_pinned)(candidate); + if hosted_gem_install(candidate, sole_candidate, hosted_pinned) { + // Vendored from the installed dir, as a gem + // the probe matched. + } else if superseded_install( ledger, candidate, record, - group.candidates.len() == 1, - (self.hosted_pinned)(candidate), + sole_candidate, + hosted_pinned, ) { + superseded = true; + } else { return CandidateVerdict::Skip; } - superseded = true; } } } else if group.candidates.len() > 1 @@ -5453,6 +5475,18 @@ mod plan_gate_tests { )); } + /// #2129: a live hosted pin lets a sole gem candidate past a failed + /// variant probe with its installed dir as the source. Other ecosystems + /// and a gem with several variant records are not its business. + #[test] + fn hosted_pin_keeps_a_gem_install_as_the_source() { + let gem = "pkg:gem/rack@3.2.8"; + assert!(hosted_gem_install(gem, true, true)); + assert!(!hosted_gem_install(gem, false, true)); + assert!(!hosted_gem_install(gem, true, false)); + assert!(!hosted_gem_install("pkg:pypi/six@1.16.0", true, true)); + } + /// Gates with no vendored refusals, no hosted pins and no `--force`. pub(super) fn gates<'a>( root: &'a Path, diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index a128346ce..ba75c8c58 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -4342,15 +4342,109 @@ fn gem_events(env: &serde_json::Value) -> Vec { /// installed copy matches neither side of the newer patch, but the gem is /// installed and its lock entry is ours: `scan --mode vendored` vendors /// the newer patch, as it does on a checkout with no gems installed, and -/// leaves the installed copy alone. The dry run previews the same. +/// leaves the installed copy alone. The dry run previews the same, and a +/// second run finds nothing left to do. `get --mode vendored` takes the +/// same path. #[tokio::test(flavor = "multi_thread")] async fn vendored_takeover_of_a_hosted_gem_whose_patch_was_superseded() { + let takeovers: [&[&str]; 2] = [ + &["scan", "--mode", "vendored"], + &["get", NEWER_UUID, "--mode", "vendored"], + ]; + for takeover in takeovers { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let home = hosted_on_a_superseded_patch(&server, &proj).await; + let uri = server.uri(); + let held_before = snapshot(&home); + let read_pair = || { + format!( + "{}{}", + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap() + ) + }; + let pair_before = read_pair(); + let run = |extra: &[&str]| { + let mut args = takeover.to_vec(); + args.extend(["--yes", "--json"]); + args.extend(extra); + let (code, stdout, stderr) = unwind_run(&proj, &uri, &args); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{takeover:?} {extra:?}: {env}\nstderr:\n{stderr}"); + assert!( + !env.to_string().contains("package_not_installed"), + "{takeover:?} {extra:?}: the gem is installed: {env}" + ); + env + }; + + run(&["--dry-run"]); + assert_eq!( + read_pair(), + pair_before, + "{takeover:?}: the dry run wrote nothing" + ); + assert!( + !proj.join(".socket").join("vendor").exists(), + "{takeover:?}" + ); + + let env = run(&[]); + let copy_rel = format!(".socket/vendor/gem/{NEWER_UUID}/{DEP}-{DEP_VERSION}"); + let pair = read_pair(); + assert!( + pair.matches(©_rel).count() >= 2 && !pair.contains("/patch-registry/"), + "{takeover:?}: the pair names the newer patch's copy and no hosted pin:\n{pair}\n{env}" + ); + assert_eq!( + installed_lib(&proj.join(©_rel)), + NEWER_PATCHED_LIB, + "{takeover:?}: the vendored copy is the newer patch" + ); + assert!( + snapshot(&home) == held_before, + "{takeover:?}: the takeover left the installed copy alone: {env}" + ); + + let env = run(&[]); + assert_eq!( + read_pair(), + pair, + "{takeover:?}: the re-run changed the pair: {env}" + ); + assert!( + snapshot(&home) == held_before, + "{takeover:?}: the re-run changed the installed copy: {env}" + ); + } +} + +/// #2129, the native-extension half: a hosted gem that builds an +/// extension cannot be vendored, superseded patch or not. The refusal +/// names that (`native_extensions_unsupported`), not a gem that is "not +/// installed", and the hosted pin stays. (A dry run of the scan previews +/// no native-extension refusal for any hosted gem, so only the real run is +/// held to this.) +#[tokio::test(flavor = "multi_thread")] +async fn vendored_takeover_of_a_superseded_native_gem_names_the_extension() { let server = MockServer::start().await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); let home = hosted_on_a_superseded_patch(&server, &proj).await; - let uri = server.uri(); - let held_before = snapshot(&home); + let spec = home + .join("specifications") + .join(format!("{DEP}-{DEP_VERSION}.gemspec")); + let text = std::fs::read_to_string(&spec).unwrap(); + std::fs::write( + &spec, + text.replace( + " s.require_paths", + " s.extensions = [\"ext/probe/extconf.rb\".freeze]\n s.require_paths", + ), + ) + .unwrap(); let pair_before = ( std::fs::read_to_string(proj.join("Gemfile")).unwrap(), std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), @@ -4358,111 +4452,26 @@ async fn vendored_takeover_of_a_hosted_gem_whose_patch_was_superseded() { let (code, stdout, stderr) = unwind_run( &proj, - &uri, - &["scan", "--mode", "vendored", "--yes", "--json", "--dry-run"], + &server.uri(), + &["scan", "--mode", "vendored", "--yes", "--json"], ); let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "dry run: {env}\nstderr:\n{stderr}"); + let events = gem_events(&env); assert!( - !env.to_string().contains("package_not_installed"), - "dry run: {env}" + events + .iter() + .any(|e| e.ends_with("/native_extensions_unsupported")), + "{events:?}\n{env}\nstderr:\n{stderr}" ); + assert!(!env.to_string().contains("package_not_installed"), "{env}"); + assert_ne!(code, 0, "{env}"); assert_eq!( ( std::fs::read_to_string(proj.join("Gemfile")).unwrap(), std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), ), pair_before, - "the dry run wrote nothing" + "the hosted pin stays" ); assert!(!proj.join(".socket").join("vendor").exists()); - - let (code, stdout, stderr) = unwind_run( - &proj, - &uri, - &["scan", "--mode", "vendored", "--yes", "--json"], - ); - let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); - assert!( - !env.to_string().contains("package_not_installed"), - "the gem is installed: {env}" - ); - let copy_rel = format!(".socket/vendor/gem/{NEWER_UUID}/{DEP}-{DEP_VERSION}"); - let pair = format!( - "{}{}", - std::fs::read_to_string(proj.join("Gemfile")).unwrap(), - std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap() - ); - assert!( - pair.matches(©_rel).count() >= 2 && !pair.contains("/patch-registry/"), - "the pair names the newer patch's copy and no hosted pin:\n{pair}\n{env}" - ); - assert_eq!( - installed_lib(&proj.join(©_rel)), - NEWER_PATCHED_LIB, - "the vendored copy is the newer patch" - ); - assert!( - snapshot(&home) == held_before, - "the takeover left the installed copy alone: {env}" - ); -} - -/// #2129, the native-extension half: a hosted gem that builds an -/// extension cannot be vendored, superseded patch or not. The refusal -/// names that (`native_extensions_unsupported`), not a gem that is "not -/// installed", and the hosted pin stays. -#[tokio::test(flavor = "multi_thread")] -async fn vendored_takeover_of_a_superseded_native_gem_names_the_extension() { - for dry_run in [true, false] { - let server = MockServer::start().await; - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - let home = hosted_on_a_superseded_patch(&server, &proj).await; - let spec = home - .join("specifications") - .join(format!("{DEP}-{DEP_VERSION}.gemspec")); - let text = std::fs::read_to_string(&spec).unwrap(); - std::fs::write( - &spec, - text.replace( - " s.require_paths", - " s.extensions = [\"ext/probe/extconf.rb\".freeze]\n s.require_paths", - ), - ) - .unwrap(); - let pair_before = ( - std::fs::read_to_string(proj.join("Gemfile")).unwrap(), - std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), - ); - - let mut args = vec!["scan", "--mode", "vendored", "--yes", "--json"]; - if dry_run { - args.push("--dry-run"); - } - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); - let env = common::parse_json_envelope(&stdout); - let events = gem_events(&env); - assert!( - events - .iter() - .any(|e| e.ends_with("/native_extensions_unsupported")), - "dry_run={dry_run}: {events:?}\n{env}\nstderr:\n{stderr}" - ); - assert!( - !env.to_string().contains("package_not_installed"), - "dry_run={dry_run}: {env}" - ); - assert_ne!(code, 0, "dry_run={dry_run}: {env}"); - assert_eq!( - ( - std::fs::read_to_string(proj.join("Gemfile")).unwrap(), - std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), - ), - pair_before, - "dry_run={dry_run}: the hosted pin stays" - ); - assert!(!proj.join(".socket").join("vendor").exists()); - } } From 2f618d278e8917ce635fd1b80f01eb35c91d2ade Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 01:43:57 +0000 Subject: [PATCH 4/4] Test the hosted-gem gate at judge; share mocks Review follow-ups: a unit test drives CandidateGates::judge for a hosted-pinned gem (with and without an older ledger entry), and the suite's API mocks take the patch uuid so the newer-patch fixture reuses them instead of copying them. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeT7HWFSwgbuzoQv6kJ --- .../socket-patch-cli/src/commands/vendor.rs | 81 +++++++-- .../tests/e2e_redirect_gem_stale_install.rs | 166 ++++-------------- 2 files changed, 108 insertions(+), 139 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 0d6df2603..982fc4d71 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -3022,19 +3022,19 @@ impl<'a> CandidateGates<'a> { )) { let sole_candidate = group.candidates.len() == 1; let hosted_pinned = (self.hosted_pinned)(candidate); - if hosted_gem_install(candidate, sole_candidate, hosted_pinned) { - // Vendored from the installed dir, as a gem - // the probe matched. - } else if superseded_install( - ledger, - candidate, - record, - sole_candidate, - hosted_pinned, - ) { + // The hosted gem is asked first: it goes on from + // its installed dir, whatever the ledger records. + if !hosted_gem_install(candidate, sole_candidate, hosted_pinned) { + if !superseded_install( + ledger, + candidate, + record, + sole_candidate, + hosted_pinned, + ) { + return CandidateVerdict::Skip; + } superseded = true; - } else { - return CandidateVerdict::Skip; } } } @@ -5487,6 +5487,63 @@ mod plan_gate_tests { assert!(!hosted_gem_install("pkg:pypi/six@1.16.0", true, true)); } + /// #2129 at the gate: an installed gem that matches neither side of + /// the record is skipped, unless the lockfiles pin it hosted. Then it + /// is vendored from its installed dir (never the stand-in a superseded + /// install gets), even when the ledger also records it at an older + /// uuid, so the backend still sees the dir's name and gemspec. + #[tokio::test] + async fn judge_sends_a_hosted_gem_on_from_its_installed_dir() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let purl = "pkg:gem/rack@3.2.8"; + let dir = root.join("gems/rack-3.2.8"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("index.php"), "an older patch's bytes").unwrap(); + let all_packages = vec![(purl.to_string(), StagedSource::Installed(dir))]; + let records = HashMap::from([(purl.to_string(), record(UUID_B))]); + let none = HashSet::new(); + let groups = candidate_groups(&all_packages, &HashMap::new()); + let unpinned = gates(root, &records, &none); + let pinned = CandidateGates { + hosted_pinned: &|_| true, + ..gates(root, &records, &none) + }; + let mut older = VendorState::default(); + older.entries.insert( + purl.to_string(), + VendorEntry::new( + "gem".to_string(), + purl.to_string(), + UUID_A.to_string(), + socket_patch_core::vendor::state::VendorArtifact { + yarn_berry10c0: None, + path: format!(".socket/vendor/gem/{UUID_A}/rack-3.2.8"), + sha256: String::new(), + size: None, + platform_locked: None, + file_inventory: None, + }, + Vec::new(), + ), + ); + let fresh = VendorState::default(); + + assert!(matches!( + unpinned.judge(&fresh, &groups[0], purl).await, + CandidateVerdict::Skip + )); + for ledger in [&fresh, &older] { + assert!(matches!( + pinned.judge(ledger, &groups[0], purl).await, + CandidateVerdict::Vendor { + superseded: false, + .. + } + )); + } + } + /// Gates with no vendored refusals, no hosted pins and no `--force`. pub(super) fn gates<'a>( root: &'a Path, diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index ba75c8c58..95330e388 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -84,18 +84,30 @@ async fn mount_api(server: &MockServer, view_budget: Option) { /// [`mount_api`] with the grant naming `patched_sha` as the patched /// archive's sha256. async fn mount_api_for(server: &MockServer, view_budget: Option, patched_sha: &str) { + mount_patch_api(server, UUID, PATCHED_LIB, view_budget, patched_sha).await; +} + +/// [`mount_api_for`] for the patch `uuid`, whose patched lib is +/// `patched_lib`. +async fn mount_patch_api( + server: &MockServer, + uuid: &str, + patched_lib: &str, + view_budget: Option, + patched_sha: &str, +) { let hosted_url = format!( - "{}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{UUID}/{DEP}-{DEP_VERSION}.gem", + "{}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{uuid}/{DEP}-{DEP_VERSION}.gem", server.uri() ); - let index_url = format!("{}/patch-registry/gem/{TOKEN}/{UUID}/", server.uri()); + let index_url = format!("{}/patch-registry/gem/{TOKEN}/{uuid}/", server.uri()); Mock::given(method("POST")) .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "packages": [{ "purl": PURL, "patches": [{ - "uuid": UUID, "purl": PURL, "tier": "free", + "uuid": uuid, "purl": PURL, "tier": "free", "cveIds": [], "ghsaIds": [], "severity": "high", "title": "gem stale-install fixture" }] @@ -110,7 +122,7 @@ async fn mount_api_for(server: &MockServer, view_budget: Option, patched_sh ))) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "patches": [{ - "uuid": UUID, "purl": PURL, + "uuid": uuid, "purl": PURL, "publishedAt": "2026-01-01T00:00:00Z", "description": "x", "license": "MIT", "tier": "free", "vulnerabilities": {} @@ -123,7 +135,7 @@ async fn mount_api_for(server: &MockServer, view_budget: Option, patched_sh .and(path(format!("/v0/orgs/{ORG}/patches/package"))) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "results": { - UUID: { + uuid: { "status": "granted", "url": hosted_url, "purl": PURL, @@ -147,15 +159,15 @@ async fn mount_api_for(server: &MockServer, view_budget: Option, patched_sh .mount(server) .await; let view = Mock::given(method("GET")) - .and(path(format!("/v0/orgs/{ORG}/patches/view/{UUID}"))) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{uuid}"))) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "uuid": UUID, + "uuid": uuid, "purl": PURL, "publishedAt": "2026-01-01T00:00:00Z", "files": { "lib/stale_probe_gem.rb": { "beforeHash": compute_git_sha256_from_bytes(UPSTREAM_LIB.as_bytes()), - "afterHash": compute_git_sha256_from_bytes(PATCHED_LIB.as_bytes()), + "afterHash": compute_git_sha256_from_bytes(patched_lib.as_bytes()), } }, "vulnerabilities": { @@ -175,7 +187,7 @@ async fn mount_api_for(server: &MockServer, view_budget: Option, patched_sh } // After the budget: transient server failure — the re-fire arm. Mock::given(method("GET")) - .and(path(format!("/v0/orgs/{ORG}/patches/view/{UUID}"))) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{uuid}"))) .respond_with(ResponseTemplate::new(500)) .mount(server) .await; @@ -2985,6 +2997,11 @@ async fn hosted_unwind_leaves_an_upstream_install_in_a_pruned_home_alone() { /// answers `patches/package` in place of [`mount_api_for`]'s hosted-only /// grant. async fn mount_vendored_grant(server: &MockServer, patched: &[u8]) { + mount_vendored_grant_of(server, UUID, patched).await; +} + +/// [`mount_vendored_grant`] for the patch `uuid`. +async fn mount_vendored_grant_of(server: &MockServer, uuid: &str, patched: &[u8]) { use base64::Engine as _; use sha2::Digest as _; let sri = |bytes: &[u8]| { @@ -3001,14 +3018,14 @@ async fn mount_vendored_grant(server: &MockServer, patched: &[u8]) { ) .into_bytes(); let leaf = format!("{DEP}-{DEP_VERSION}"); - let base = format!("/artifacts/{UUID}"); + let base = format!("/artifacts/{uuid}"); let gem_url = format!("{}{base}/{leaf}.gem", server.uri()); let stub_url = format!("{}{base}/{leaf}.gemspec", server.uri()); Mock::given(method("POST")) .and(path(format!("/v0/orgs/{ORG}/patches/package"))) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "results": { - UUID: { + uuid: { "status": "granted", "url": gem_url, "purl": PURL, @@ -3020,7 +3037,7 @@ async fn mount_vendored_grant(server: &MockServer, patched: &[u8]) { ], "registryOverride": { "kind": "rubygems-compact-index", - "indexUrl": format!("{}/patch-registry/gem/{TOKEN}/{UUID}/", server.uri()), + "indexUrl": format!("{}/patch-registry/gem/{TOKEN}/{uuid}/", server.uri()), "identifiers": { "name": DEP, "version": DEP_VERSION, @@ -4178,124 +4195,19 @@ const NEWER_PATCHED_LIB: &str = /// The patch API once [`NEWER_UUID`] supersedes [`UUID`] (mount it on a /// reset server): discovery, selection and the view name only the newer -/// patch, and its grant carries the vendored artifacts (the patched `.gem` -/// and the stub gemspec a path source loads) beside the hosted override. +/// patch, and its grant carries the vendored artifacts beside the hosted +/// override. async fn mount_newer_patch(server: &MockServer) { - use base64::Engine as _; - use sha2::Digest as _; - let sri = |bytes: &[u8]| { - format!( - "sha512-{}", - base64::engine::general_purpose::STANDARD.encode(sha2::Sha512::digest(bytes)) - ) - }; let patched = real_gem(NEWER_PATCHED_LIB); - let stub = format!( - "Gem::Specification.new do |s|\n s.name = \"{DEP}\".freeze\n s.version = \ - \"{DEP_VERSION}\".freeze\n s.authors = [\"e2e\".freeze]\n s.summary = \ - \"fixture\".freeze\n s.files = [\"lib/stale_probe_gem.rb\".freeze]\n s.require_paths \ - = [\"lib\".freeze]\nend\n" + mount_patch_api( + server, + NEWER_UUID, + NEWER_PATCHED_LIB, + None, + &sha256_of(&patched), ) - .into_bytes(); - let leaf = format!("{DEP}-{DEP_VERSION}"); - let base = format!("/artifacts/{NEWER_UUID}"); - let gem_url = format!("{}{base}/{leaf}.gem", server.uri()); - let stub_url = format!("{}{base}/{leaf}.gemspec", server.uri()); - Mock::given(method("POST")) - .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "packages": [{ - "purl": PURL, - "patches": [{ - "uuid": NEWER_UUID, "purl": PURL, "tier": "free", - "cveIds": [], "ghsaIds": [], "severity": "high", - "title": "gem stale-install fixture, newer patch" - }] - }], - "canAccessPaidPatches": false, - }))) - .mount(server) - .await; - Mock::given(method("GET")) - .and(path_regex(format!( - "^/v0/orgs/{ORG}/patches/by-package/.+$" - ))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "patches": [{ - "uuid": NEWER_UUID, "purl": PURL, - "publishedAt": "2026-02-01T00:00:00Z", - "description": "x", "license": "MIT", "tier": "free", - "vulnerabilities": {} - }], - "canAccessPaidPatches": false, - }))) - .mount(server) - .await; - Mock::given(method("GET")) - .and(path(format!("/v0/orgs/{ORG}/patches/view/{NEWER_UUID}"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "uuid": NEWER_UUID, - "purl": PURL, - "publishedAt": "2026-02-01T00:00:00Z", - "files": { - "lib/stale_probe_gem.rb": { - "beforeHash": compute_git_sha256_from_bytes(UPSTREAM_LIB.as_bytes()), - "afterHash": compute_git_sha256_from_bytes(NEWER_PATCHED_LIB.as_bytes()), - } - }, - "vulnerabilities": { - GHSA: { - "cves": ["CVE-2026-4444"], - "summary": "gem stale-install fixture vuln", - "severity": "high", - "description": "d" - } - }, - "description": "x", "license": "MIT", "tier": "free" - }))) - .mount(server) - .await; - Mock::given(method("POST")) - .and(path(format!("/v0/orgs/{ORG}/patches/package"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "results": { - NEWER_UUID: { - "status": "granted", - "url": gem_url, - "purl": PURL, - "artifacts": [ - { "kind": "tarball", "url": gem_url, - "integrity": { "sha512": sri(&patched), "sha256": sha256_of(&patched) } }, - { "kind": "gem-stub-gemspec", "url": stub_url, - "integrity": { "sha512": sri(&stub) } } - ], - "registryOverride": { - "kind": "rubygems-compact-index", - "indexUrl": format!( - "{}/patch-registry/gem/{TOKEN}/{NEWER_UUID}/", - server.uri() - ), - "identifiers": { - "name": DEP, - "version": DEP_VERSION, - "gemChecksumSha256": sha256_of(&patched), - } - } - } - } - }))) - .mount(server) - .await; - for (file, bytes) in [ - (format!("{leaf}.gem"), patched), - (format!("{leaf}.gemspec"), stub), - ] { - Mock::given(method("GET")) - .and(path(format!("{base}/{file}"))) - .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) - .mount(server) - .await; - } + .await; + mount_vendored_grant_of(server, NEWER_UUID, &patched).await; serve_upstream_gem(server, &real_gem(UPSTREAM_LIB)).await; }