diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 5e3fe0690..982fc4d71 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( - ledger, - candidate, - record, - group.candidates.len() == 1, - (self.hosted_pinned)(candidate), - ) { - return CandidateVerdict::Skip; + let sole_candidate = group.candidates.len() == 1; + let hosted_pinned = (self.hosted_pinned)(candidate); + // 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; } - superseded = true; } } } else if group.candidates.len() > 1 @@ -5453,6 +5475,75 @@ 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)); + } + + /// #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 65ff715e9..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, @@ -4167,3 +4184,206 @@ 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 beside the hosted +/// override. +async fn mount_newer_patch(server: &MockServer) { + let patched = real_gem(NEWER_PATCHED_LIB); + mount_patch_api( + server, + NEWER_UUID, + NEWER_PATCHED_LIB, + None, + &sha256_of(&patched), + ) + .await; + mount_vendored_grant_of(server, NEWER_UUID, &patched).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, 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 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 (code, stdout, stderr) = unwind_run( + &proj, + &server.uri(), + &["scan", "--mode", "vendored", "--yes", "--json"], + ); + let env = common::parse_json_envelope(&stdout); + let events = gem_events(&env); + assert!( + 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 hosted pin stays" + ); + assert!(!proj.join(".socket").join("vendor").exists()); +}