From 2e93e254d6cc49c5a2b2eedafedc8a17c29cc3e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 05:21:57 +0000 Subject: [PATCH 1/5] Start the vendored gem unwind platform fix Claims #2174: the vendored unwind judges only the ruby-platform build of an unwound gem, so a precompiled platform build that a hosted scan replaced stays patched. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeQwRPCRjnzyQ3rqcZr From e3208b281bfae201c86cfaf503538c82643d2d69 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 05:28:23 +0000 Subject: [PATCH 2/5] Test the vendored unwind of a platform gem A gem locked as precompiled platform gems that a hosted scan patched and a vendored run then took over keeps its patched installed copy after rollback, remove and vendor --revert (#2174). The takeover leg of the platform prebuild capstone fails on that until the unwind follows the lock's builds. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeQwRPCRjnzyQ3rqcZr --- .../tests/e2e_redirect_gem_build.rs | 251 +++++++++++++++++- 1 file changed, 244 insertions(+), 7 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs index 27ae623c7..c42c8a8f3 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -6663,13 +6663,25 @@ fn own_and_foreign_platform() -> (String, String) { /// installed copy back on the upstream platform gem; /// 6. standalone `vex` attests the gem from the lock, hash-verified /// against the installed platform build. +/// +/// With `takeover` (#2174), a vendored run takes the gem over before step +/// 5, which leaves the patched platform copy the hosted scan installed. +/// Step 5 is then a vendored unwind, and `remove` and `vendor --revert` +/// run over copies of the project as well: each must put the installed +/// platform copy back on the upstream platform gem. async fn platform_prebuilds_install_frozen_and_roll_back( tag: &str, checksums_lock: bool, ruby_entry: bool, + takeover: bool, ) { - // Bundler locks the specific platform's gem from 2.2; `CHECKSUMS` from 2.6. - let floor = if checksums_lock { (2, 6) } else { (2, 2) }; + // Bundler locks the specific platform's gem from 2.2; `CHECKSUMS` from + // 2.6. Vendor takes platform gems from a lock bundler 2.3 or newer wrote. + let floor = match (checksums_lock, takeover) { + (true, _) => (2, 6), + (false, true) => (2, 3), + (false, false) => (2, 2), + }; let Some(bundler) = bundler_e2e::gate("e2e_redirect_gem_build", tag, floor, &|c| { cache_env::isolate(c); }) else { @@ -7144,6 +7156,88 @@ async fn platform_prebuilds_install_frozen_and_roll_back( let text = std::fs::read_to_string(&path).unwrap(); std::fs::write(&path, as_committed(&text)).unwrap(); } + if takeover { + mount_vendored_platform_grant(&fx, &hosted_url, &patched_builds, &platforms).await; + let (code, stdout, stderr) = run_socket_env( + &fx.proj, + &[ + "get", + UUID, + "--mode", + "vendored", + "--yes", + "--json", + "--cwd", + proj_str, + "--api-url", + &api, + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + &api, + ], + &[("SOCKET_RUBYGEMS_URL", &upstream)], + ); + assert_eq!(code, 0, "takeover:\nstdout:\n{stdout}\nstderr:\n{stderr}"); + let vendored_lock = std::fs::read_to_string(fx.proj.join("Gemfile.lock")).unwrap(); + assert!( + vendored_lock.starts_with("PATH\n remote: .socket/vendor/gem/"), + "premise: the gem is vendored:\n{vendored_lock}\nstdout:\n{stdout}" + ); + assert_eq!( + std::fs::read_to_string(&warm_lib).unwrap(), + patched, + "premise: the takeover leaves the patched platform copy installed" + ); + // `remove` and `vendor --revert`, each over its own copy of the + // project; `rollback` runs on the project itself below. + for command in ["remove", "vendor --revert"] { + let dir = fx.tmp.path().join(format!("unwind-{}", &command[..6])); + copy_dir_recursive(&fx.proj, &dir); + let cwd = dir.to_str().expect("utf8 tmp path"); + let mut argv: Vec<&str> = match command { + "remove" => vec!["remove", PURL, "--yes"], + _ => vec!["vendor", "--revert", "--yes"], + }; + argv.extend([ + "--json", + "--cwd", + cwd, + "--api-url", + &api, + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + &api, + ]); + let (code, stdout, stderr) = + run_socket_env(&dir, &argv, &[("SOCKET_RUBYGEMS_URL", &upstream)]); + assert_eq!( + code, 0, + "{command}:\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_eq!( + std::fs::read_to_string(dir.join("Gemfile.lock")).unwrap(), + as_committed(&pristine_lock), + "{command} must hand the lock back byte for byte" + ); + assert_eq!( + std::fs::read_to_string(fresh_installed_lib(&dir, &own_leaf, "vuln_gem.rb")) + .unwrap(), + orig, + "{command}: the installed platform copy is the upstream build again:\n{stdout}" + ); + assert!( + stdout.contains("upstream_gem_install_refreshed") + && !stdout.contains("upstream_gem_stale_install"), + "{command}: the copy is refreshed, and nothing is left patched:\n{stdout}" + ); + } + } let (code, stdout, stderr) = run_socket_env( &fx.proj, &[ @@ -7184,30 +7278,173 @@ async fn platform_prebuilds_install_frozen_and_roll_back( && !stdout.contains("upstream_gem_stale_cache"), "nothing is left on the patched build:\n{stdout}" ); + // The arm whose pair still names the mock upstream: bundler loads the + // upstream code, and a reinstall from the gem home's archive succeeds. + if takeover && !checksums_lock { + let probe = "require \"vuln_gem\"; print VulnGem.status"; + for args in [&["install"][..], &["pristine"]] { + let out = bundle(&fx.proj, args); + assert!( + out.status.success(), + "bundle {args:?} after the unwind:\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + let run = bundle(&fx.proj, &["exec", "ruby", "-e", probe]); + assert_eq!( + String::from_utf8_lossy(&run.stdout), + "VULNERABLE", + "bundle {args:?} leaves the upstream code loaded:\n{}", + String::from_utf8_lossy(&run.stderr) + ); + } + } // 6. Standalone VEX over the fresh checkout bundler installed. manifestless_vex_matrix(&fx, &fresh).await; } +/// The grant of [`UUID`] as the patch service answers it once the patch has +/// prebuilds a vendored run can take: the hosted reference +/// [`platform_prebuilds_install_frozen_and_roll_back`] mounts, plus each +/// prebuild's sha512 and its stub gemspec. +async fn mount_vendored_platform_grant( + fx: &RedirectFixture, + hosted_url: &str, + patched_builds: &[IndexBuild], + platforms: &[&str], +) { + let server = &fx._server; + let gem_of = |token: &str| { + let build = patched_builds.iter().find(|b| b.name == DEP && b.token == token); + &build.expect("build").gem + }; + let ruby_gem = gem_of(DEP_VERSION); + let ruby_sha = sha256_hex(ruby_gem); + let stubs = format!("/artifacts/{UUID}"); + let mut served = vec![(format!("{DEP}-{DEP_VERSION}.gemspec"), stub_gemspec(ruby_gem))]; + let mut artifacts = vec![ + serde_json::json!({ + "kind": "tarball", "url": hosted_url, + "integrity": { "sha512": sri(ruby_gem), "sha256": ruby_sha } + }), + serde_json::json!({ + "kind": "gem-stub-gemspec", + "url": format!("{}{stubs}/{DEP}-{DEP_VERSION}.gemspec", server.uri()), + "integrity": { "sha512": sri(&served[0].1) } + }), + ]; + let mut gem_platforms = Vec::new(); + for platform in platforms { + let leaf = format!("{DEP}-{DEP_VERSION}-{platform}"); + let gem = gem_of(&format!("{DEP_VERSION}-{platform}")); + let stub = stub_gemspec(gem); + let sha = sha256_hex(gem); + artifacts.push(serde_json::json!({ + "kind": "gem-platform", "platform": platform, + "url": format!("{}gems/{leaf}.gem", fx.index_url), + "contentType": "application/octet-stream", "sizeBytes": gem.len(), + "integrity": { "sha512": sri(gem), "sha256": sha } + })); + artifacts.push(serde_json::json!({ + "kind": "gem-platform-stub-gemspec", "platform": platform, + "url": format!("{}{stubs}/{leaf}.gemspec", server.uri()), + "integrity": { "sha512": sri(&stub) } + })); + gem_platforms.push(serde_json::json!({ "platform": platform, "gemChecksumSha256": sha })); + served.push((format!("{leaf}.gemspec"), stub)); + } + 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: { + "status": "granted", + "url": hosted_url, + "purl": PURL, + "artifacts": artifacts, + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": fx.index_url, + "identifiers": { + "name": DEP, + "version": DEP_VERSION, + "gemChecksumSha256": ruby_sha, + "gemPlatforms": gem_platforms, + } + } + } + } + }))) + .with_priority(1) + .mount(server) + .await; + for (leaf, bytes) in served { + Mock::given(method("GET")) + .and(path(format!("{stubs}/{leaf}"))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .mount(server) + .await; + } +} + #[tokio::test(flavor = "multi_thread")] #[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] async fn gem_hosted_platform_prebuilds_install_frozen_and_roll_back() { - platform_prebuilds_install_frozen_and_roll_back("platform-prebuilds-checksums", true, false) - .await; + platform_prebuilds_install_frozen_and_roll_back( + "platform-prebuilds-checksums", + true, + false, + false, + ) + .await; } #[tokio::test(flavor = "multi_thread")] #[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] async fn gem_hosted_platform_prebuilds_beside_the_ruby_entry_install_frozen_and_roll_back() { - platform_prebuilds_install_frozen_and_roll_back("platform-prebuilds-ruby-entry", true, true) - .await; + platform_prebuilds_install_frozen_and_roll_back( + "platform-prebuilds-ruby-entry", + true, + true, + false, + ) + .await; } #[tokio::test(flavor = "multi_thread")] #[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.2); \ the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] async fn gem_hosted_platform_prebuilds_without_checksums_install_frozen_and_roll_back() { - platform_prebuilds_install_frozen_and_roll_back("platform-prebuilds", false, false).await; + platform_prebuilds_install_frozen_and_roll_back("platform-prebuilds", false, false, false) + .await; +} + +/// #2174: a platform gem that went from hosted to vendored, then unwound. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_vendored_unwind_restores_a_platform_install_the_hosted_scan_patched() { + platform_prebuilds_install_frozen_and_roll_back( + "platform-prebuilds-takeover-checksums", + true, + false, + true, + ) + .await; +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.3); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_vendored_unwind_restores_a_platform_install_without_checksums() { + platform_prebuilds_install_frozen_and_roll_back( + "platform-prebuilds-takeover", + false, + false, + true, + ) + .await; } From 84a6d2bc1667d25e9a13cd253c51fe10174c2161 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 05:31:40 +0000 Subject: [PATCH 3/5] Refresh platform builds on a vendored gem unwind After a vendored unwind put a gem back on its upstream entry, the refresh looked only for the ruby-platform installed copy (-). A gem vendored from prebuilt platform gems is installed as --, so a copy a hosted scan had replaced with the patched build stayed in the gem home: the app kept loading the patch, and bundle pristine failed on the restored checksum. Look for the builds the restored lock names instead, as the refresh that follows already does, and fall back to the ruby-platform gem when the lock names none. Fixes #2174 Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeQwRPCRjnzyQ3rqcZr --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../src/commands/gem_refresh.rs | 50 +++++++++++-------- .../tests/e2e_redirect_gem_build.rs | 14 +++--- docs/ecosystems.md | 3 +- 4 files changed, 41 insertions(+), 28 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index cdcae4bc9..f76a2a8b3 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -475,7 +475,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm *What never refreshes.* A hosted → vendored takeover (`vendor`, `scan` / `get --mode vendored` over a hosted pin) puts the gem on its upstream entry only on its way to the vendored `path:` source, which is what Bundler loads from then on. The copies Bundler already holds are unused leftovers there, so the takeover changes none of them and downloads no gem for them: resetting the installed copy to the upstream build would cost a registry download in the mode that needs none, and would turn a patched leftover into an unpatched one that `vex` reports against the vendored artifact (`vendored_tree_out_of_sync`, whose gem wording names the copy and how to remove it). Its `upstream_gem_stale_cache` advisory about a patched cache-dir archive is as before. A vendored unwind (`remove`, `rollback`, `vendor --revert`, `scan --prune`, `vendor`'s reconcile of a vendored gem) likewise only names that archive, and never replaces it. -*A vendored unwind after a hosted or an agent scan.* Once a vendored gem is unwound, Bundler loads its installed copy again, so the leftover is in use: if a hosted scan made that copy the patched build before the gem was vendored, the patched code would keep running under the upstream lock, and on bundler ≥ 2.6 `bundle pristine` would fail on the upstream checksum. If agent mode patched that copy in place before the gem was vendored (#2093), the takeover moved its manifest record into the vendor ledger and kept the patched files, so the patched code would keep running with no record left that `rollback` or `apply --check` could act on. A gem `.socket/manifest.json` still has a record for is different: its in-place patch is agent mode's and on record (standalone `vendor` works from the manifest and keeps the record), so the vendored unwind does not judge its installed copy by a record. A wet `rollback`, `remove`, `vendor --revert` or `vendor` reconcile that put a vendored gem back on its upstream entry therefore applies the unwind direction's refresh to the gem's INSTALLED copies when the lock now resolves the gem from rubygems.org (a gem from another remote is not judged: nothing proves its entry is the upstream one), under the same rules (staleness judged by `/cache/.gem` against the upstream sha256, and by the patch record of a detached ledger entry (`scan` / `get --mode vendored`) whose gem the manifest has no record for: a copy whose files all hash to the record's `afterHash` values is stale whatever archive its gem home holds, or when it holds none; a project-local gem home only, unless `--gem-refresh-shared`; `--no-gem-install-refresh`; an archive on disk, else rubygems.org unless `--offline`), with the same `upstream_gem_install_refreshed` note and `upstream_gem_stale_install` warning. `--json` carries them where the command carries a vendored revert's advisories (rollback `warnings[]`; `remove` / `vendor` advisory events); a human run prints the progress line after the gem's own line and one warning for the gems left on the patched build. The upstream sha256 is looked up only for a gem that has an installed copy with its archive, or one holding the record's patched files, so the unwind of a gem that is not installed needs no network. A gem that was only ever vendored has the upstream archive there: nothing is downloaded or changed. A copy agent mode patched is reinstalled from the upstream archive RubyGems kept beside it, so nothing is downloaded for it either unless that archive is gone (a pruned `cache/`); the reinstall also removes what agent mode kept in the gem dir. When nothing proves the upstream sha256 for such a copy (`--offline` under a lock without `CHECKSUMS`), it is left as it is and named by `upstream_gem_stale_install`. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry is refused (a plain-`http` `SOCKET_RUBYGEMS_URL`, see the unwind direction), such an installed copy is reported as one that could not be checked, whichever of the two it is: nothing tells them apart. A `--dry-run` does not preview this (the lock on disk is still the vendored one), and `scan --prune` does not refresh. +*A vendored unwind after a hosted or an agent scan.* Once a vendored gem is unwound, Bundler loads its installed copy again, so the leftover is in use: if a hosted scan made that copy the patched build before the gem was vendored, the patched code would keep running under the upstream lock, and on bundler ≥ 2.6 `bundle pristine` would fail on the upstream checksum. If agent mode patched that copy in place before the gem was vendored (#2093), the takeover moved its manifest record into the vendor ledger and kept the patched files, so the patched code would keep running with no record left that `rollback` or `apply --check` could act on. A gem `.socket/manifest.json` still has a record for is different: its in-place patch is agent mode's and on record (standalone `vendor` works from the manifest and keeps the record), so the vendored unwind does not judge its installed copy by a record. A wet `rollback`, `remove`, `vendor --revert` or `vendor` reconcile that put a vendored gem back on its upstream entry therefore applies the unwind direction's refresh to the gem's INSTALLED copies (of every build the restored lock names: a gem vendored from prebuilt platform gems is installed as `--`, #2174) when the lock now resolves the gem from rubygems.org (a gem from another remote is not judged: nothing proves its entry is the upstream one), under the same rules (staleness judged by `/cache/.gem` against the upstream sha256, and by the patch record of a detached ledger entry (`scan` / `get --mode vendored`) whose gem the manifest has no record for: a copy whose files all hash to the record's `afterHash` values is stale whatever archive its gem home holds, or when it holds none; a project-local gem home only, unless `--gem-refresh-shared`; `--no-gem-install-refresh`; an archive on disk, else rubygems.org unless `--offline`), with the same `upstream_gem_install_refreshed` note and `upstream_gem_stale_install` warning. `--json` carries them where the command carries a vendored revert's advisories (rollback `warnings[]`; `remove` / `vendor` advisory events); a human run prints the progress line after the gem's own line and one warning for the gems left on the patched build. The upstream sha256 is looked up only for a gem that has an installed copy with its archive, or one holding the record's patched files, so the unwind of a gem that is not installed needs no network. A gem that was only ever vendored has the upstream archive there: nothing is downloaded or changed. A copy agent mode patched is reinstalled from the upstream archive RubyGems kept beside it, so nothing is downloaded for it either unless that archive is gone (a pruned `cache/`); the reinstall also removes what agent mode kept in the gem dir. When nothing proves the upstream sha256 for such a copy (`--offline` under a lock without `CHECKSUMS`), it is left as it is and named by `upstream_gem_stale_install`. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry is refused (a plain-`http` `SOCKET_RUBYGEMS_URL`, see the unwind direction), such an installed copy is reported as one that could not be checked, whichever of the two it is: nothing tells them apart. A `--dry-run` does not preview this (the lock on disk is still the vendored one), and `scan --prune` does not refresh. **Pipenv hosted redirect (`Pipfile.lock`, pipfile-spec 6)**: every category other than `_meta` (`default`, `develop`, and Pipenv 2022+ named categories) that pins the package at the patched version is rewritten to the hosted reference — `{"file" | "path": "#sha256=", "hashes": ["sha256:"]}` with `markers`/`extras`/`index` kept exactly as Pipenv wrote them (present or absent: whether Pipenv records `index` depends on its release, the Pipfile spelling and the locking environment, so only the entry itself knows) and `version` dropped; `_meta` (the Pipfile content hash) and the Pipfile itself are never touched, so `pipenv install --deploy`/`sync`/`verify` keep passing. The reference KEY depends on the installing Pipenv: releases 7–11 only install `path` references, 2018 and later `file` ones (0–6 write pipfile-spec < 6 and are refused). The release is probed once per command with `pipenv --version`, resolved on ABSOLUTE `PATH` entries only (a relative entry would run a `pipenv` planted in the scanned repository; `.bat`/`.cmd` shims are found through `PATHEXT` on Windows), only when a pypi patch actually targets an entry of the lock, and `SOCKET_PIPENV_MAJOR=` pins the answer without spawning anything. An unknown installer selects `file` and warns `redirect_pipenv_installer_unknown` only when the lock was rewritten. **Refusal scope**: a pin/source CONFLICT (another version pinned, a foreign `file`/`path` source, a VCS/editable dependency) refuses the whole dependency atomically across categories as `redirect_pipenv_refused` AND vetoes the sibling Python rewriters (requirements.txt / uv.lock / pyproject) for that patch — the project's Pipenv install could not pick the patch up, so a half-redirected checkout is refused; anything else (no entry for the package, an old pipfile-spec, an unparseable lock, a digest-less patch) is `redirect_pipenv_skipped` and leaves the siblings alone (a stale Pipfile.lock in a uv/Poetry/requirements project must not block them). The veto applies to a LIVE lock only: a `Pipfile.lock` with no `Pipfile` beside it is abandoned, so its conflict refuses that file but never the siblings. Hash enforcement at install time is split by era — the `#sha256=` URL fragment is what Pipenv 2023+ verifies, the `hashes` list what 2018–2022 verify, Pipenv 11 either — so both are load-bearing. **Pipenv stale-install guard**: Pipenv never reinstalls a release that is already present (`pipenv install`, `install --deploy` and `sync` all exit 0 and keep the installed bytes — measured on 11.10.4, 2018.11.26 and 2026.8.0, hosted and vendored), so after the rewrite the run probes the Python crawler's site-packages (VIRTUAL_ENV, `./.venv`, `./venv`, Pipenv's out-of-tree `WORKON_HOME` venv; `--global`/`--global-prefix` honoured) for each confirmed Pipfile.lock redirect with the Python stale-install guard's evidence (the pinned patched wheel, else the patch record; STALE needs positive evidence, read-only, skipped on `--dry-run`, stale purls excluded from the same-run `--vex` `assume_applied` set) and the Python stale-install guard (`redirect_pypi_stale_install`, see above) names the site-packages dir and the Pipenv-specific verified remedy: `pipenv run pip uninstall -y && pipenv sync` (or `pipenv --rm && pipenv sync`), with the `sync` arguments following the lock, since plain `pipenv sync` installs only `default`: the targeted form re-syncs the categories that pin the package (`--dev` for `develop`, `--categories ""` for a named category) and the `--rm` form re-syncs every non-empty category — NOT `pipenv uninstall`, which rewrites the Pipfile and re-locks the patch away. The vendored backend emits the twin `pypi_pipenv_stale_install` (`skipped` warning event). **Rollback** (v5.0, upstream restore): each hosted entry gets its registry shape back — `"version": "=="`, the entry's own `index` carried back unchanged (refused unless it — and the Pipfile's explicit `index`, if any — names a PyPI source in `_meta.sources`), and every release file's sha256 from PyPI's JSON API (`SOCKET_PYPI_JSON_API`), sorted by filename as Pipenv records them; an entry that pins another version beside the hosted reference is refused with the `git checkout` remedy (see "Hosted unwind coverage"). A Pipfile names no project, so a same-run `--vex` on a Pipenv project needs `--vex-product` (or a git remote) to detect a product purl. **Discovery**: `Pipfile.lock` is part of the lockfile inventory (every category's `==` pins, with the lock's digest set as `Sha256AnyOf` integrity so a lock-only checkout can be vendored by fetching the pure wheel through PyPI's JSON API — only when `_meta.sources` name the public index; a private-index lock stays discovery-only and never reaches pypi.org), and Socket's own hosted / vendored references stay discoverable as the package they replace, so a re-scan of an already-redirected or already-vendored lock-only checkout re-confirms it (`--vex` attests, vendored reports `already_vendored`) instead of finding nothing. diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 09e59f8ee..50b530905 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -1241,14 +1241,16 @@ pub(crate) async fn after_vendored_unwind( unwound: &[String], records: &BTreeMap, ) -> RestoreRefresh { + use socket_patch_core::patch::redirect::upstream::gem_upstream; + let mut installed: BTreeSet = BTreeSet::new(); - // A vendored gem is the ruby-platform gem: a platform build installed - // beside it was never the vendored copy's stand-in. - let ruby_builds: Vec<(String, String)> = unwound - .iter() - .filter_map(|purl| Some((purl.clone(), GemBuild::ruby(purl)?.leaf))) - .collect(); - for copy in installed_builds(common, &ruby_builds).await { + // The builds the restored lock names: a gem vendored from prebuilt + // platform gems is back on its platform entries, and the copy Bundler + // loads again is `--` (#2174). Reading the + // lock asks no registry. + let lock = gem_upstream(&common.cwd, &BTreeMap::new(), true).await; + let builds = build_leaves(&named_builds(&lock, unwound), |_| true); + for copy in installed_builds(common, &builds).await { if copy.archive.is_file() || holds_patch(©, records).await { installed.insert(copy.purl); } @@ -1268,6 +1270,26 @@ pub(crate) async fn after_vendored_unwind( .await } +/// The builds of each gem of `gems` that are this project's: the ones the +/// restored lock (`upstream`) names. A lock that names none (it could not +/// be read) leaves the ruby-platform gem, the one build an unwind looked +/// at before platform builds were followed. +fn named_builds( + upstream: &socket_patch_core::patch::redirect::upstream::GemUpstream, + gems: &[String], +) -> BTreeMap> { + let mut named = BTreeMap::new(); + for (purl, builds) in gems.iter().zip(upstream.builds(gems)) { + let builds = if builds.is_empty() { + GemBuild::ruby(purl).into_iter().collect() + } else { + builds + }; + named.insert(purl.clone(), builds); + } + named +} + async fn refresh_restored( common: &GlobalArgs, restored: &[String], @@ -1308,19 +1330,7 @@ async fn refresh_restored( // The restored lock, read once, and one registry client for every // lookup below. let upstream = gem_upstream(&common.cwd, staged, common.offline).await; - // The builds of each restored gem that are this project's: the ones the - // restored lock names. A lock that names none (it could not be read) - // leaves the ruby-platform gem, the one build an unwind looked at - // before platform builds were followed. - let mut named: BTreeMap> = BTreeMap::new(); - for (purl, builds) in gems.iter().zip(upstream.builds(&gems)) { - let builds = if builds.is_empty() { - GemBuild::ruby(purl).into_iter().collect() - } else { - builds - }; - named.insert(purl.clone(), builds); - } + let named = named_builds(&upstream, &gems); // A lock names a platform build for every platform the project // supports, and this machine holds one of them: only a platform build // that is installed in a gem home Bundler uses or (in [`Scope::All`]) diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs index c42c8a8f3..4f0449c61 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -7216,10 +7216,7 @@ async fn platform_prebuilds_install_frozen_and_roll_back( ]); let (code, stdout, stderr) = run_socket_env(&dir, &argv, &[("SOCKET_RUBYGEMS_URL", &upstream)]); - assert_eq!( - code, 0, - "{command}:\nstdout:\n{stdout}\nstderr:\n{stderr}" - ); + assert_eq!(code, 0, "{command}:\nstdout:\n{stdout}\nstderr:\n{stderr}"); assert_eq!( std::fs::read_to_string(dir.join("Gemfile.lock")).unwrap(), as_committed(&pristine_lock), @@ -7316,13 +7313,18 @@ async fn mount_vendored_platform_grant( ) { let server = &fx._server; let gem_of = |token: &str| { - let build = patched_builds.iter().find(|b| b.name == DEP && b.token == token); + let build = patched_builds + .iter() + .find(|b| b.name == DEP && b.token == token); &build.expect("build").gem }; let ruby_gem = gem_of(DEP_VERSION); let ruby_sha = sha256_hex(ruby_gem); let stubs = format!("/artifacts/{UUID}"); - let mut served = vec![(format!("{DEP}-{DEP_VERSION}.gemspec"), stub_gemspec(ruby_gem))]; + let mut served = vec![( + format!("{DEP}-{DEP_VERSION}.gemspec"), + stub_gemspec(ruby_gem), + )]; let mut artifacts = vec![ serde_json::json!({ "kind": "tarball", "url": hosted_url, diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 43dcb2fd9..7ecc2d5ff 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2616,7 +2616,8 @@ files to remove before `bundle install`. Vendoring a gem that was hosted (`vendor`, `scan --mode vendored`) leaves the installed copies as they are: Bundler loads the vendored copy from then on. When that vendored gem is later unwound (`rollback`, `remove`, `vendor --revert`), Bundler loads the installed copy again, so the unwind -puts the upstream gem back there too. The same holds for a gem that agent mode patched in place +puts the upstream gem back there too (for a gem locked as precompiled platform gems, the upstream +platform gem of the build that is installed). The same holds for a gem that agent mode patched in place before `scan --mode vendored` (or `get --mode vendored`) took it over: the unwind reinstalls the upstream gem over the patched files in the project's own gem home, and warns about a copy it leaves (a shared gem home, `--no-gem-install-refresh`). A gem that was only ever vendored still From a01cba660ba2bf5ca355b4d2a42f50fe5bedd1c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 05:52:46 +0000 Subject: [PATCH 4/5] Name platform archives on a vendored gem unwind The vendored unwind's check of Bundler's cache dir judged only -.gem, and stopped when the lock had no ruby-platform entry: always, for a gem vendored from prebuilt platform gems. A patched --.gem that a bundle cache took under the hosted pin went unnamed, and the next install took it first. Judge the archive of every build the restored lock names, as the hosted restore does, with one warning per archive. Refs #2174 Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeQwRPCRjnzyQ3rqcZr --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../src/commands/vendored_backend/mod.rs | 7 +- .../tests/e2e_redirect_gem_build.rs | 13 ++- .../src/patch/redirect/upstream/gem.rs | 102 ++++++++++++++---- .../src/patch/redirect/upstream/mod.rs | 9 +- 5 files changed, 106 insertions(+), 27 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index f76a2a8b3..795c8e4b8 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2351,7 +2351,7 @@ command's integration tests check its output. | `hosted_resolution_orphaned` | rollback/remove `warnings[]`; list `warnings[]` (human: `Warning: …` on stderr) | yarn berry (#1203): the root `package.json` keeps a Socket-hosted `resolutions` selector that no live `yarn.lock` entry resolves and no lock descriptor matches (left behind by `yarn remove` / `yarn up`). `rollback` / `remove` removed it (the lock is untouched; an emptied `resolutions` object is dropped). uv (#1445): `pyproject.toml` (or a script's PEP 723 block) keeps a hosted `override-dependencies` pin and its `[tool.uv.sources]` URL for a transitive package the lock no longer holds (left behind by `uv remove ` / `uv lock --upgrade-package `). `rollback` / `remove` removed both lines and the lock's `[manifest]` record of them (emptied tables are dropped). `list` only reports either and names the scoped `remove ` that retires it alone. Never flips the exit. | | `upstream_registry_fallback` | rollback/remove `warnings[]`; vendor advisory event (takeover) | upstream restore: a yarn berry, pnpm or vlt entry is restored from the version document of the registry the project resolves it against (yarn berry: `npmScopes` / `YARN_NPM_REGISTRY_SERVER` / `npmRegistryServer` from the `.yarnrc.yml` chain, as above, the pnpm lock's sibling `.npmrc` `registry` / `@scope:registry` or pnpm-workspace.yaml `registry` / `registries`, vlt's node registry); that registry could not be read (e.g. it needs credentials) or, for yarn berry, could not be determined (an rc value referencing an environment variable that is set, or an unset one with no default; a flow-style `npmScopes`), so the default registry's document was used and the restored tarball URL may not be the mirror's. | | `upstream_gem_declaration_pinned` | rollback/remove `warnings[]`; vendor advisory event (takeover) | upstream restore (gem): a pin socket-patch 5.0 / 5.1 wrote as a `source "" do … end` block was undone. That block does not hold the declaration it replaced, so the gem came back as the exact pin `gem "", ""`. Reported once per manifest; the detail names each declaration and says that a version range (for example `~> 2.2`), the original quoting and the comment have to be put back by hand, followed by `bundle lock`. A pin in the `source:` option form is restored byte for byte and never warns. | -| `upstream_gem_stale_cache` | rollback/remove `warnings[]`; a vendored unwind's rollback `warnings[]`, remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events and `scan --prune` `gc.warnings[]`; vendor advisory event (takeover) | upstream restore (#1260), or a wet vendored gem unwind (`remove`, `rollback`, `vendor --revert`, `scan --prune`, `vendor`'s reconcile) that puts the gem back on its upstream entry (#1594; a gem locked from a remote other than rubygems.org with no `CHECKSUMS` sha is not judged): a restored gem's `-.gem` is still in Bundler's cache dir (`cache_path`, default `vendor/cache`, resolved as for the Gem stale-install guard) and its sha256 is not the upstream one (the restored `CHECKSUMS` entry, else the rubygems.org compact index), or it could not be checked (`--offline`, a registry error). Bundler installs from that dir first, so a `bundle cache` taken while the hosted pin was live makes every later install fail on the upstream checksum (exit 37) or, on bundler < 2.6 frozen installs, keep installing the patched bytes. The detail names the file. Remedy: delete it, then run `bundle cache` to cache the upstream gem in its place (or `bundle install` if the project does not commit its cache; with the cache dir committed, a frozen install reads only the cache). A hosted unwind replaces the archive with the verified upstream gem when it can (the "Gem stale-install guard" section, unwind direction) and then raises nothing; from it, this warning is for an archive it left: the upstream gem could not be fetched or verified, the archive is outside the project, or `--no-gem-install-refresh` is set. A vendored unwind and a hosted → vendored takeover never replace the archive and always name it. Nothing ever deletes it. Not raised for an archive whose sha256 matches upstream. The takeover's copy adds that the vendored copy is installed instead while the gem stays vendored, and that the vendored unwind names the archive again. | +| `upstream_gem_stale_cache` | rollback/remove `warnings[]`; a vendored unwind's rollback `warnings[]`, remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events and `scan --prune` `gc.warnings[]`; vendor advisory event (takeover) | upstream restore (#1260), or a wet vendored gem unwind (`remove`, `rollback`, `vendor --revert`, `scan --prune`, `vendor`'s reconcile) that puts the gem back on its upstream entry (#1594; a gem locked from a remote other than rubygems.org with no `CHECKSUMS` sha is not judged): a restored gem's `-.gem` is still in Bundler's cache dir (`cache_path`, default `vendor/cache`, resolved as for the Gem stale-install guard) and its sha256 is not the upstream one (the restored `CHECKSUMS` entry, else the rubygems.org compact index), or it could not be checked (`--offline`, a registry error). Bundler installs from that dir first, so a `bundle cache` taken while the hosted pin was live makes every later install fail on the upstream checksum (exit 37) or, on bundler < 2.6 frozen installs, keep installing the patched bytes. The detail names the file. Remedy: delete it, then run `bundle cache` to cache the upstream gem in its place (or `bundle install` if the project does not commit its cache; with the cache dir committed, a frozen install reads only the cache). A hosted unwind replaces the archive with the verified upstream gem when it can (the "Gem stale-install guard" section, unwind direction) and then raises nothing; from it, this warning is for an archive it left: the upstream gem could not be fetched or verified, the archive is outside the project, or `--no-gem-install-refresh` is set. A vendored unwind and a hosted → vendored takeover never replace the archive and always name it, the archive of each platform build the lock names included (`--.gem`, #2174). Nothing ever deletes it. Not raised for an archive whose sha256 matches upstream. The takeover's copy adds that the vendored copy is installed instead while the gem stays vendored, and that the vendored unwind names the archive again. | | `upstream_uv_entry_rebuilt` | rollback/remove `warnings[]`; vendor advisory event (takeover) | upstream restore: every registry package of a `uv.lock` / script lock was hosted, so no other entry showed the registry or the artifact fields uv records, and the restored entries were rebuilt from PyPI on the default index with the fields uv writes at the lock's `revision` (see "Hosted unwind coverage"). The detail names the lock, the entries, the fields and the check to run (`uv lock --check`, for a script lock `uv lock --check --script