From d16acc6f383c209b7d7952adca21f3d1f34bba37 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:23:42 +0000 Subject: [PATCH 1/5] Start fix for vendored unwind of agent gem Refs #2093 Assisted-by: Claude Code:claude-fable-5-2 From 46d8a303e1d78a2eb048e90fbcc90da23d9f4a27 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:26:45 +0000 Subject: [PATCH 2/5] Test vendored unwind of an agent-patched gem Four tests fail: rollback, remove and vendor --revert of a gem that agent mode patched in place and a vendored scan then took over leave the installed copy on the patched files and say nothing, with or without the upstream archive in the gem home. Refs #2093 Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeQy1d8enbEzCjPrQua --- .../tests/e2e_redirect_gem_stale_install.rs | 228 ++++++++++++++++++ 1 file changed, 228 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 f15166818..d296b2163 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 @@ -3249,6 +3249,234 @@ async fn vendored_unwind_leaves_an_upstream_install_alone() { } } +/// A project whose gem agent mode patched in place and a vendored scan +/// then took over: the takeover moved the manifest record into the vendor +/// ledger and left the installed copy (patched files, upstream archive in +/// the gem home's `cache/`) alone. Returns the installed gem dir and that +/// archive. +async fn agent_then_vendored(server: &MockServer, proj: &Path) -> (PathBuf, PathBuf) { + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(server, None, &sha256_of(&patched)).await; + serve_upstream_gem(server, &upstream).await; + mount_vendored_grant(server, &patched).await; + std::fs::create_dir_all(proj).unwrap(); + write_manifest_pair(proj); + let home = project_home(proj); + let gem_dir = agent_patched_install(proj, &home); + let archive = home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem")); + + let uri = server.uri(); + let (code, stdout, stderr) = unwind_run( + proj, + &uri, + &["scan", "--mode", "vendored", "--yes", "--json"], + ); + assert_eq!(code, 0, "takeover:\n{stdout}\n{stderr}"); + let gemfile = std::fs::read_to_string(proj.join("Gemfile")).unwrap(); + assert!( + gemfile.contains(".socket/vendor/gem/"), + "premise:\n{gemfile}" + ); + let manifest = std::fs::read_to_string(proj.join(".socket").join("manifest.json")).unwrap(); + assert!( + stdout.contains("vendor_manifest_record_migrated") && !manifest.contains(PURL), + "premise: the takeover owns the record now:\n{stdout}\n{manifest}" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise"); + assert_eq!(std::fs::read(&archive).unwrap(), upstream, "premise"); + (gem_dir, archive) +} + +/// The gem downloads (`/gems/.gem`, from any registry) among the +/// requests `server` received after the first `skip`. +async fn gem_downloads_since(server: &MockServer, skip: usize) -> Vec { + server + .received_requests() + .await + .unwrap_or_default() + .iter() + .skip(skip) + .map(|request| request.url.path().to_string()) + .filter(|path| path.contains("/gems/")) + .collect() +} + +/// #2093: a vendored takeover of a gem agent mode patched in place drops +/// the manifest record and keeps the patched files in the installed copy. +/// Once the vendored gem is unwound Bundler loads that copy again, and no +/// record is left that could undo the patch. The unwind therefore puts +/// the upstream gem back, from the upstream archive RubyGems kept in the +/// gem home (nothing is downloaded), and leaves nothing of agent mode's +/// in the gem dir. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_restores_an_install_agent_mode_patched() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, archive) = agent_then_vendored(&server, &proj).await; + let asked_before = server.received_requests().await.unwrap().len(); + + let mut args = unwind.to_vec(); + args.push("--json"); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); + let pair = format!( + "{}{}", + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap() + ); + assert!( + !pair.contains(".socket/vendor/"), + "{unwind:?}: the gem is back on its upstream entry:\n{pair}" + ); + assert_eq!( + installed_lib(&gem_dir), + UPSTREAM_LIB, + "{unwind:?}: the installed copy is the upstream build again: {env}" + ); + assert!( + !gem_dir.join(".socket-patch-kept").exists(), + "{unwind:?}: the copy is a fresh install of the upstream gem: {env}" + ); + assert_eq!( + std::fs::read(&archive).unwrap(), + real_gem(UPSTREAM_LIB), + "{unwind:?}: the upstream archive is untouched: {env}" + ); + let fetched = gem_downloads_since(&server, asked_before).await; + assert!(fetched.is_empty(), "{unwind:?}: downloaded {fetched:?}"); + let text = env.to_string(); + assert!( + text.contains("upstream_gem_install_refreshed") + && !text.contains("upstream_gem_stale_install"), + "{unwind:?}: {env}" + ); + } +} + +/// The same with the gem home's `cache/` pruned (Bundler 4.1 `prune`, a +/// Docker image's `rm -rf ruby/*/cache`): the ledger's record still proves +/// the installed files are the patched ones, so the upstream gem is +/// downloaded and installed over them. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_restores_an_agent_patched_install_without_its_archive() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, archive) = agent_then_vendored(&server, &proj).await; + std::fs::remove_dir_all(archive.parent().unwrap()).unwrap(); + let asked_before = server.received_requests().await.unwrap().len(); + + let mut args = unwind.to_vec(); + args.push("--json"); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); + assert_eq!( + installed_lib(&gem_dir), + UPSTREAM_LIB, + "{unwind:?}: the installed copy is the upstream build again: {env}" + ); + assert_eq!( + gem_downloads_since(&server, asked_before).await, + [format!("/upstream/gems/{DEP}-{DEP_VERSION}.gem")], + "{unwind:?}: one download, of the upstream gem" + ); + let text = env.to_string(); + assert!( + text.contains("upstream_gem_install_refreshed") + && !text.contains("upstream_gem_stale_install"), + "{unwind:?}: {env}" + ); + } +} + +/// An agent-patched copy the unwind may not replace +/// (`--no-gem-install-refresh`) or cannot (`--offline` with the archive +/// pruned) is left exactly as it was and named with the files to remove, +/// not passed over as if it were the upstream build. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_names_an_agent_patched_install_it_leaves() { + for (unwind, opt_out) in VENDORED_UNWINDS + .into_iter() + .flat_map(|unwind| [(unwind, true), (unwind, false)]) + { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, archive) = agent_then_vendored(&server, &proj).await; + let home = project_home(&proj); + if !opt_out { + std::fs::remove_dir_all(archive.parent().unwrap()).unwrap(); + } + let held_before = snapshot(&home); + + let mut args = unwind.to_vec(); + args.push("--json"); + args.push(if opt_out { + "--no-gem-install-refresh" + } else { + "--offline" + }); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env = common::parse_json_envelope(&stdout); + let case = format!("{unwind:?} opt_out={opt_out}"); + assert_eq!(code, 0, "{case}: {env}\nstderr:\n{stderr}"); + assert!( + snapshot(&home) == held_before, + "{case}: the gem home changed: {env}" + ); + let text = env.to_string(); + let spec = home + .join("specifications") + .join(format!("{DEP}-{DEP_VERSION}.gemspec")); + for needle in [ + "upstream_gem_stale_install", + gem_dir.to_str().unwrap(), + spec.to_str().unwrap(), + "bundle install", + ] { + // The envelope JSON-escapes a Windows path's backslashes. + let needle = needle.replace('\\', "\\\\"); + assert!(text.contains(&needle), "{case}: no {needle:?} in {env}"); + } + assert!( + !text.contains("upstream_gem_install_refreshed"), + "{case}: {env}" + ); + } +} + +/// The human run says what it replaced, and rollback's "keeps its patched +/// bytes" note no longer counts the gem. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_reports_the_agent_patched_refresh_in_a_human_run() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, _) = agent_then_vendored(&server, &proj).await; + + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), unwind); + assert_eq!(code, 0, "{unwind:?}: {stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "{unwind:?}"); + assert!( + stdout.contains(&format!( + "Replaced the installed copy of 1 gem with the upstream build: {DEP} \ + {DEP_VERSION}." + )), + "{unwind:?}: {stdout}\n{stderr}" + ); + assert!( + !stdout.contains("keeps its patched bytes") && !stderr.contains("still holds"), + "{unwind:?}: {stdout}\n{stderr}" + ); + } +} + /// What `scan --mode agent` leaves of the fixture gem under `home`: the /// upstream install with its lib patched in place, the upstream archive /// still in the home's `cache/`, and the manifest record (with both blobs) From 3dc990f169e5e0fe914e9fa6af5667ab78800bb7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:29:43 +0000 Subject: [PATCH 3/5] Test the agent-patched unwind on real Bundler Fails on rollback, remove and vendor --revert: the installed copy keeps agent mode's patched files after the vendored gem is unwound. Refs #2093 Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeQy1d8enbEzCjPrQua --- .../tests/e2e_redirect_gem_build.rs | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) 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 bfa6545c0..f4d1b93f5 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -5786,6 +5786,139 @@ async fn gem_vendored_unwind_restores_an_install_the_hosted_scan_patched() { } } +/// #2093 through one vendored unwind `command`: agent mode patched the +/// installed gem in place, and a vendored takeover then moved its manifest +/// record into the vendor ledger and left the patched files (the vendored +/// copy is loaded instead). The later unwind puts the pair back on the +/// upstream `GEM` entry, where bundler loads the installed copy again, +/// and nothing is left that records the patch. The unwind must put the +/// upstream gem back: the app then loads the upstream code, and every +/// kind of reinstall succeeds and keeps it. +fn vendored_unwind_restores_an_agent_patched_gem(fx: &RedirectFixture, command: &str) { + let dir = stage_warm_install(fx, &format!("agent-vendored-{command}")); + let installed = fresh_installed_lib(&dir, &format!("{DEP}-{DEP_VERSION}"), "vuln_gem.rb"); + assert!( + std::fs::read(&installed).unwrap() == orig_lib().into_bytes(), + "{command}: premise: the upstream gem is installed" + ); + // What `scan --mode agent` leaves: the lib patched in place, the + // record of it, and both blobs. + std::fs::write(&installed, patched_lib()).unwrap(); + common::write_in_place_patch_record( + &dir.join(".socket"), + PURL, + UUID, + "lib/vuln_gem.rb", + orig_lib().as_bytes(), + patched_lib().as_bytes(), + ); + + let api = fx._server.uri(); + let upstream = format!("{api}/upstream"); + let cwd = dir.to_str().expect("utf8 tmp path"); + let common = [ + "--json", + "--cwd", + cwd, + "--api-url", + &api, + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + &api, + ]; + let envs = [("SOCKET_RUBYGEMS_URL", upstream.as_str())]; + let mut takeover = vec!["get", UUID, "--mode", "vendored", "--yes"]; + takeover.extend(common); + let (code, stdout, stderr) = run_socket_env(&dir, &takeover, &envs); + assert_eq!( + code, 0, + "{command}: takeover:\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert!( + stdout.contains("vendor_manifest_record_migrated"), + "{command}: premise: the takeover owns the record now:\n{stdout}" + ); + let vendored = bundle(&dir, &["install"]); + assert!( + vendored.status.success(), + "{command}: vendored install:\n{}", + String::from_utf8_lossy(&vendored.stderr) + ); + assert!( + std::fs::read(&installed).unwrap() == patched_lib().into_bytes(), + "{command}: premise: the takeover and its install leave the installed copy" + ); + + let mut argv: Vec<&str> = match command { + "vendor --revert" => vec!["vendor", "--revert", "--yes"], + "remove" => vec!["remove", PURL, "--yes"], + _ => vec![command, PURL], + }; + argv.extend(common); + let (code, stdout, stderr) = run_socket_env(&dir, &argv, &envs); + let env: serde_json::Value = serde_json::from_str(&stdout).unwrap_or_else(|e| { + panic!("{command}: not JSON: {e}\nstdout:\n{stdout}\nstderr:\n{stderr}") + }); + assert_eq!(code, 0, "{command}: {env}\nstderr:\n{stderr}"); + assert!( + env.to_string().contains("upstream_gem_install_refreshed") + && !env.to_string().contains("upstream_gem_stale_install"), + "{command}: {env}" + ); + assert!( + std::fs::read(&installed).unwrap() == orig_lib().into_bytes(), + "{command}: the installed copy is the upstream gem again: {env}" + ); + + let redownload = if fx.bundler.at_least(2, 0) { + "--redownload" + } else { + "--force" + }; + let probe = "require \"vuln_gem\"; print VulnGem.status"; + for args in [&["install"][..], &["install", redownload], &["pristine"]] { + let out = bundle(&dir, args); + assert!( + out.status.success(), + "{command}: bundle {args:?} after the unwind:\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + let run = bundle(&dir, &["exec", "ruby", "-e", probe]); + assert_eq!( + String::from_utf8_lossy(&run.stdout), + "VULNERABLE", + "{command}: bundle {args:?} leaves the upstream code loaded:\n{}", + String::from_utf8_lossy(&run.stderr) + ); + } +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 1.17); the unpinned `test` \ + job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_vendored_unwind_restores_an_install_agent_mode_patched() { + let Some(fx) = redirect_scanned_project( + "agent-vendored-unwind", + Spelling::Gemfile, + false, + true, + None, + Driver::ScanVex, + ) + .await + else { + return; + }; + mount_vendored_grant(&fx).await; + for command in ["remove", "rollback", "vendor --revert"] { + vendored_unwind_restores_an_agent_patched_gem(&fx, command); + } +} + /// #1831: a hosted redirect over a CRLF Gemfile (a Windows checkout, or /// `core.autocrlf=true`) keeps it CRLF throughout: the edit is the option /// alone, the real bundler installs the pair frozen and has nothing to From ffaa6f37f3549f04b6b8f3755f88c046ed0389a8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:34:12 +0000 Subject: [PATCH 4/5] Restore an agent-patched gem on vendored unwind A vendored takeover of a gem that agent mode patched in place moves the manifest record into the vendor ledger and keeps the patched files, because Bundler loads the vendored copy from then on. The vendored unwind judged an installed copy only by the archive in its gem home, which for such a copy is the upstream one. So rollback, remove and vendor --revert left the patched files in the copy Bundler loads again, with no record left to undo them. The unwind's gem refresh now also judges each installed copy against the patch record the unwind ends: a copy whose files hash to the record's afterHash values is reinstalled from the upstream gem. That is the archive RubyGems kept beside it, so nothing is downloaded unless the gem home's cache was pruned. A copy the run may not or cannot replace is named by upstream_gem_stale_install. The record is the detached ledger entry's. For a gem standalone vendor took from an agent manifest it is the manifest record, and only in rollback and remove, which drop it without restoring a file. vendor --revert keeps that record, so the copy stays patched. Fixes #2093 Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeQy1d8enbEzCjPrQua --- crates/socket-patch-cli/CLI_CONTRACT.md | 6 +- .../src/commands/gem_refresh.rs | 101 ++++++++++++++---- .../socket-patch-cli/src/commands/remove.rs | 6 +- .../socket-patch-cli/src/commands/rollback.rs | 6 +- .../src/commands/vendored_backend/mod.rs | 84 ++++++++++++++- .../tests/e2e_redirect_gem_stale_install.rs | 76 +++++++++++++ docs/ecosystems.md | 6 +- 7 files changed, 252 insertions(+), 33 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 74e5e02d1..889adb345 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -460,7 +460,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 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. 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; 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, 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. 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. The same holds for a gem standalone `vendor` vendored from an agent-mode manifest once `rollback` or `remove` unwinds it: they drop its manifest record with the vendored gem and restore no file from the record's blobs. `vendor --revert` keeps that manifest record, so the in-place patch stays agent mode's and the installed copy is not judged. 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 the unwind ends, which is the detached ledger entry's own or the manifest record `rollback` / `remove` drop: 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. @@ -2251,8 +2251,8 @@ command's integration tests check its output. | `redirect_gem_stale_install` | `warnings[]` (warning) | scan / get `--mode hosted` (gem): a stale UNPATCHED materialization (installed gem, or committed archive in bundler's cache dir — `vendor/cache` unless `cache_path` moves it) that `bundle install` will reuse instead of fetching the redirected patch, and that the run did not refresh: it is in a shared gem home, or the refresh could not be done (the detail says why) or is turned off. The detail carries the remedy. A human run prints one warning for all of them. Full rules and flavors: the "Gem stale-install guard" section. | | `redirect_gem_install_refreshed` | `warnings[]` (note) | scan / get `--mode hosted` (gem): a stale materialization the run replaced with the sha256-verified patched gem (the detail names the purl and the path). A human run prints a progress line instead. See the "Gem stale-install guard" section. | | `redirect_gem_install_would_refresh` | `warnings[]` (note) | scan / get `--mode hosted --dry-run` (gem): a stale materialization a wet run would replace. Nothing was written or downloaded. | -| `upstream_gem_stale_install` | `warnings[]` (warning); remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events for a vendored unwind | rollback / remove / a withdrawn-patch restore (gem), and a wet vendored gem unwind (`rollback`, `remove`, `vendor --revert`, `vendor`'s reconcile; #2083): an installed copy of a gem that is back on its upstream entry still holds the PATCHED gem and was not refreshed (a shared gem home, a failed or disabled refresh). Bundler keeps using it. Also: the copy could not be checked against the upstream gem, because the registry that would say what that is was refused (plain-http `SOCKET_RUBYGEMS_URL`); it still holds the patched build if it was installed before the unwind. The detail carries the reason and the remedy; a human run prints one warning for all of them. | -| `upstream_gem_install_refreshed` | `warnings[]` (note); remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events for a vendored unwind | rollback / remove / a withdrawn-patch restore (gem): an installed copy or cache-dir archive the unwind replaced with the sha256-verified upstream gem. A wet vendored gem unwind (#2083): an installed copy only. A human run prints a progress line instead. | +| `upstream_gem_stale_install` | `warnings[]` (warning); remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events for a vendored unwind | rollback / remove / a withdrawn-patch restore (gem), and a wet vendored gem unwind (`rollback`, `remove`, `vendor --revert`, `vendor`'s reconcile; #2083, and a copy agent mode patched in place before the gem was vendored, #2093): an installed copy of a gem that is back on its upstream entry still holds the PATCHED gem and was not refreshed (a shared gem home, a failed or disabled refresh). Bundler keeps using it. Also: the copy could not be checked against the upstream gem, because the registry that would say what that is was refused (plain-http `SOCKET_RUBYGEMS_URL`); it still holds the patched build if it was installed before the unwind. The detail carries the reason and the remedy; a human run prints one warning for all of them. | +| `upstream_gem_install_refreshed` | `warnings[]` (note); remove / `vendor --revert` / `vendor` (manifest reconcile) advisory events for a vendored unwind | rollback / remove / a withdrawn-patch restore (gem): an installed copy or cache-dir archive the unwind replaced with the sha256-verified upstream gem. A wet vendored gem unwind (#2083, #2093): an installed copy only. A human run prints a progress line instead. | | `upstream_gem_install_would_refresh` | `warnings[]` (note) | the same on `--dry-run`: what a wet unwind would replace. | | `redirect_gem_version_not_locked` | `warnings[]` (warning) | scan `--mode hosted` (gem): the crawled gem version is installed on the machine but no `GEM` section of the project's lock resolves it (another project's copy in the shared gem home). The gem is skipped and the Gemfile and lock stay byte-identical. | | `redirect_gem_no_checksums_section` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock has no `CHECKSUMS` section (Bundler < 2.6 does not write one), so it cannot record the sha256 of the patched gems. They are redirected all the same (manifest and lock converged, frozen installs accept the pair) and pinned by source alone. Reported once per run, naming the gems; relock with Bundler ≥ 2.6 (`bundle lock --add-checksums`) and re-run to pin the checksums too. | diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 3a46fe529..8fb615cf0 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -11,6 +11,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use socket_patch_core::crawlers::Ecosystem; +use socket_patch_core::manifest::schema::PatchRecord; use socket_patch_core::patch::gem_ext::RubyEnv; use socket_patch_core::patch::gem_refresh::{refresh, Source, Target, Wanted}; @@ -831,31 +832,42 @@ enum Scope { /// upstream sha256; a purl without an entry is not judged. A purl whose /// sha256 is `None` (the registry that would give it was refused) cannot /// be judged either, and every installed copy of it is listed. +/// +/// `records` holds the patch record of each gem that has one to judge by +/// (a vendored unwind's ledger entry). An installed copy whose files are +/// that record's patched ones is stale whatever its archive says, and +/// whether or not `upstream` has its purl: agent mode patched it in place +/// beside the upstream archive (#2093). async fn stale_after_restore( common: &GlobalArgs, upstream: &BTreeMap>, + records: &BTreeMap, scope: Scope, ) -> Vec { use socket_patch_core::vendor::file_sha256_hex; - let purls: Vec = upstream.keys().cloned().collect(); + let purls: Vec = upstream + .keys() + .chain(records.keys()) + .collect::>() + .into_iter() + .cloned() + .collect(); let mut out = Vec::new(); for copy in installed_with_archives(common, &purls).await { - let Some(sha) = upstream.get(©.purl) else { - continue; - }; // With no upstream sha256 (the registry that would give it was // refused) nothing can be judged, so the copy is listed whether // or not its archive is still in the home's cache. With one, // only a readable archive that is not the upstream gem makes // the copy stale. - let listed = match sha { - None => true, - Some(sha) => { + let listed = match upstream.get(©.purl) { + None => false, + Some(None) => true, + Some(Some(sha)) => { matches!(file_sha256_hex(©.archive).await, Some(got) if &got != sha) } }; - if listed { + if listed || holds_patch(©, records).await { out.push(StaleGem { purl: copy.purl, leaf: copy.leaf, @@ -895,6 +907,20 @@ async fn stale_after_restore( out } +/// Whether the files of the installed `copy` are the patched ones of its +/// gem's record in `records`: every file the record lists hashes to its +/// `afterHash`. `false` for a gem with no record. +async fn holds_patch(copy: &InstalledCopy, records: &BTreeMap) -> bool { + match records.get(©.purl) { + Some(record) => { + socket_patch_core::vex::verify::judge_installed_record(©.dir, record) + .await + .patched + } + None => false, + } +} + /// What an unwind's refresh did, for [`crate::commands::hosted_unwind`] /// and the vendored unwind ([`crate::commands::vendored_backend`]). #[derive(Debug, Default)] @@ -919,13 +945,19 @@ pub(crate) async fn after_restore( restored: &[String], staged: &BTreeMap>, ) -> RestoreRefresh { - refresh_restored(common, restored, staged, Scope::All).await + refresh_restored(common, restored, staged, &BTreeMap::new(), Scope::All).await } /// After a wet vendored unwind put the gems `unwound` back on their /// upstream entries (the lock on disk says so): Bundler loads their /// installed copies again, and a copy that a hosted scan replaced with the /// patched build before the gem was vendored is still that build (#2083). +/// So is a copy agent mode patched in place before the gem was vendored: +/// the takeover moved its manifest record into the vendor ledger and kept +/// the patched files, so once the ledger entry is gone nothing else could +/// undo them (#2093). `records` is each unwound gem's ledger record, by +/// purl; a copy whose files are the record's patched ones is such a copy, +/// whatever archive its gem home holds. /// Those copies are brought back to the upstream gem exactly as /// [`after_restore`] does it. An archive in Bundler's cache dir is not /// touched: the vendored unwind names it (`upstream_gem_stale_cache`). @@ -936,24 +968,33 @@ pub(crate) async fn after_restore( pub(crate) async fn after_vendored_unwind( common: &GlobalArgs, unwound: &[String], + records: &BTreeMap, ) -> RestoreRefresh { - let installed: BTreeSet = installed_with_archives(common, unwound) - .await - .into_iter() - .filter(|copy| copy.archive.is_file()) - .map(|copy| copy.purl) - .collect(); + let mut installed: BTreeSet = BTreeSet::new(); + for copy in installed_with_archives(common, unwound).await { + if copy.archive.is_file() || holds_patch(©, records).await { + installed.insert(copy.purl); + } + } if installed.is_empty() { return RestoreRefresh::default(); } let installed: Vec = installed.into_iter().collect(); - refresh_restored(common, &installed, &BTreeMap::new(), Scope::Installed).await + refresh_restored( + common, + &installed, + &BTreeMap::new(), + records, + Scope::Installed, + ) + .await } async fn refresh_restored( common: &GlobalArgs, restored: &[String], staged: &BTreeMap>, + records: &BTreeMap, scope: Scope, ) -> RestoreRefresh { use socket_patch_core::patch::redirect::upstream::{gem_upstream_archive, UpstreamArchive}; @@ -966,6 +1007,12 @@ async fn refresh_restored( // The gems whose upstream sha256 the registry is not asked for, each // with why: their installed copies are reported, not passed over. let mut unverified: BTreeMap = BTreeMap::new(); + // The records an installed copy is judged by as well: those of the + // gems known to be back on their upstream entries. A copy holding its + // record's patch is stale even when nothing proves the upstream + // sha256 (`--offline` under a lock without `CHECKSUMS`): it is then + // reported, not refreshed. + let mut judged: BTreeMap = BTreeMap::new(); for purl in restored .iter() .filter(|p| Ecosystem::from_purl(p) == Some(Ecosystem::Gem)) @@ -984,21 +1031,33 @@ async fn refresh_restored( } shas.insert(purl.clone(), Some(sha256)); urls.insert(purl.clone(), url); + judged.extend( + records + .get_key_value(purl) + .map(|(k, v)| (k.clone(), v.clone())), + ); } // (Only a gem the lock resolves from rubygems.org comes back // unverified, so the vendored unwind's rule holds for it too.) Some(UpstreamArchive::Unverified(why)) => { unverified.insert(purl.clone(), why); } - None => {} + None => { + judged.extend( + records + .get_key_value(purl) + .map(|(k, v)| (k.clone(), v.clone())), + ); + } } } - if shas.is_empty() && unverified.is_empty() { + if shas.is_empty() && unverified.is_empty() && judged.is_empty() { return RestoreRefresh::default(); } - let stale = stale_after_restore(common, &shas, scope).await; + let stale = stale_after_restore(common, &shas, &judged, scope).await; let unjudged = unverified.keys().map(|purl| (purl.clone(), None)).collect(); - let unchecked = stale_after_restore(common, &unjudged, Scope::Installed).await; + let unchecked = + stale_after_restore(common, &unjudged, &BTreeMap::new(), Scope::Installed).await; if stale.is_empty() && unchecked.is_empty() { return RestoreRefresh::default(); } @@ -1020,7 +1079,7 @@ async fn refresh_restored( }; let mut pass = attempt(&stale, wanted, &source, &policy, direction).await; let still = if pass.changed(&policy) { - stale_after_restore(common, &shas, scope).await + stale_after_restore(common, &shas, &judged, scope).await } else { stale }; diff --git a/crates/socket-patch-cli/src/commands/remove.rs b/crates/socket-patch-cli/src/commands/remove.rs index 1a79c5247..b08ce3194 100644 --- a/crates/socket-patch-cli/src/commands/remove.rs +++ b/crates/socket-patch-cli/src/commands/remove.rs @@ -1399,7 +1399,11 @@ async fn revert_vendored_matches( let mut leg = RemoveVendorLeg::default(); // Stops at the first hard failure: remove aborts there, leaving the // remaining matches (and the manifest) untouched. - let backend = VendoredBackend::new(&args.common, None); + let mut backend = VendoredBackend::new(&args.common, None); + if !args.preserve_state { + // The manifest record of an unwound package is removed with it. + backend = backend.dropping_manifest_records(); + } let reverted = backend.revert(keys, state, opts, true).await; for (key, w) in backend.go_undo_warnings(&reverted).await { if loud { diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index d312d38ba..f7c089334 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -1026,7 +1026,11 @@ async fn run_vendored_leg( keep_artifact: preserve, }; let loud = !common.json && !common.silent; - let backend = VendoredBackend::new(common, None); + let mut backend = VendoredBackend::new(common, None); + if !preserve { + // The manifest cleanup drops an unwound package's record. + backend = backend.dropping_manifest_records(); + } let reverted = backend.revert(keys, state, opts, false).await; for (_, w) in backend.go_undo_warnings(&reverted).await { if loud { diff --git a/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs b/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs index fa9b006f8..17390e3ad 100644 --- a/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs +++ b/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs @@ -52,6 +52,8 @@ pub(crate) struct VendoredBackend<'a> { pub(crate) service: Option<&'a VendorServiceConfig>, /// See [`VendoredBackend::with_closing_lines`]. pub(crate) closing_lines: Option<&'a ClosingLines<'a>>, + /// See [`VendoredBackend::dropping_manifest_records`]. + pub(crate) drops_manifest_records: bool, } /// Lines for the human close of a vendor run to print under its summary @@ -90,9 +92,21 @@ impl<'a> VendoredBackend<'a> { common: common.at_project_root(), service, closing_lines: None, + drops_manifest_records: false, } } + /// The caller removes the `.socket/manifest.json` record of every + /// package [`VendoredBackend::revert`] unwinds, without restoring the + /// files that record patched in place (`rollback` and `remove` leave a + /// vendored package to the vendored unwind alone). The unwind's gem + /// refresh then treats such a record as one the unwind ends: an + /// installed copy holding its patch is put back on the upstream gem. + pub(crate) fn dropping_manifest_records(mut self) -> Self { + self.drops_manifest_records = true; + self + } + /// Have [`VendoredBackend::apply`]'s human close print what `lines` /// returns under its summary line. `scan --mode vendored` uses it to /// say which advisories each vendored patch fixes. @@ -159,8 +173,11 @@ impl<'a> VendoredBackend<'a> { ) -> Vec { let mut out = Vec::with_capacity(keys.len()); // The gems a wet revert put back on their upstream entries: the - // index of each one's element in `out`, and its purl. + // index of each one's element in `out`, and its purl. With the + // patch record of each one the ledger alone owned (a detached + // entry), which the entry takes with it. let mut unwound_gems: Vec<(usize, String)> = Vec::new(); + let mut gem_records = std::collections::BTreeMap::new(); for key in keys { let Some(entry) = state.entries.get(key).cloned() else { out.push(RevertedEntry { @@ -228,6 +245,9 @@ impl<'a> VendoredBackend<'a> { .await; if is_gem(&entry.ecosystem) { unwound_gems.push((out.len(), entry.base_purl.clone())); + if let (true, Some(record)) = (entry.detached, &entry.record) { + gem_records.insert(entry.base_purl.clone(), record.clone()); + } } } } @@ -243,7 +263,8 @@ impl<'a> VendoredBackend<'a> { break; } } - self.refresh_unwound_gems(&unwound_gems, &mut out).await; + self.refresh_unwound_gems(&unwound_gems, &gem_records, &mut out) + .await; out } @@ -251,7 +272,10 @@ impl<'a> VendoredBackend<'a> { /// that a hosted scan replaced with the patched build before the gem /// was vendored still is that build, so the app would keep running the /// patch under an upstream lock, and `bundle pristine` would fail on - /// the upstream checksum (#2083). Bring those copies back to the + /// the upstream checksum (#2083). One that agent mode patched in place + /// before the gem was vendored still holds the patched files, and + /// `records` (the record of each unwound gem that the ledger alone + /// owned) is the last thing that can tell (#2093). Bring those copies back to the /// upstream gem as the hosted unwind does, and name what is left (the /// "Gem stale-install guard" section of CLI_CONTRACT.md). /// @@ -259,14 +283,22 @@ impl<'a> VendoredBackend<'a> { /// one, on the entry of its gem. A human run gets the progress lines on /// the last unwound gem's entry, so they print once every revert is /// reported, and ONE warning for the gems still on their patched build. - async fn refresh_unwound_gems(&self, unwound: &[(usize, String)], out: &mut [RevertedEntry]) { + async fn refresh_unwound_gems( + &self, + unwound: &[(usize, String)], + records: &std::collections::BTreeMap, + out: &mut [RevertedEntry], + ) { let Some((first, _)) = unwound.first() else { return; }; let (first, last) = (*first, unwound[unwound.len() - 1].0); let purls: Vec = unwound.iter().map(|(_, purl)| purl.clone()).collect(); + let records = self.ended_records(&purls, records).await; + let records = &records; let refresh = - crate::commands::gem_refresh::after_vendored_unwind(&self.common, &purls).await; + crate::commands::gem_refresh::after_vendored_unwind(&self.common, &purls, records) + .await; for (index, purl) in unwound { if refresh.refreshed_installs.contains(purl) { out[*index].gem_install_refreshed = true; @@ -297,6 +329,48 @@ impl<'a> VendoredBackend<'a> { } } + /// The patch record each unwound gem's installed copies are judged by: + /// the one this unwind ends, after which nothing records an in-place + /// patch of the gem. For a gem `.socket/manifest.json` has no record + /// for, that is the ledger's own (`ledger`, from a detached entry). A + /// manifest record means the in-place patch is agent mode's: the + /// record is the one judged by when the caller drops it + /// ([`Self::dropping_manifest_records`]), and the gem is not judged at + /// all when it stays (`vendor --revert` leaves the patch applied and + /// on record). A manifest that cannot be read proves nothing, so no + /// gem is judged then. + async fn ended_records( + &self, + unwound: &[String], + ledger: &std::collections::BTreeMap, + ) -> std::collections::BTreeMap { + use socket_patch_core::utils::purl::strip_purl_qualifiers; + let manifest = socket_patch_core::manifest::operations::read_manifest( + &self.common.resolved_manifest_path(), + ) + .await; + let manifest = match manifest { + Ok(Some(manifest)) => manifest, + Ok(None) => return ledger.clone(), + Err(_) => return Default::default(), + }; + let mut out = ledger.clone(); + for (purl, record) in &manifest.patches { + let base = strip_purl_qualifiers(purl); + let Some(gem) = unwound + .iter() + .find(|gem| strip_purl_qualifiers(gem) == base) + else { + continue; + }; + out.remove(gem); + if self.drops_manifest_records { + out.insert(gem.clone(), record.clone()); + } + } + out + } + /// Dropping a vendored Go `replace` leaves a committed /// vendor/modules.txt still recording it, which breaks every default /// build until `go mod vendor` runs. The undo commands 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 d296b2163..304bf396b 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 @@ -3450,6 +3450,82 @@ async fn vendored_unwind_names_an_agent_patched_install_it_leaves() { } } +/// Standalone `vendor` works from the manifest and leaves the record in +/// it, so the in-place patch is still agent mode's. +/// +/// `vendor --revert` undoes the vendoring only: the manifest keeps the +/// record and the installed copy keeps the patch it describes, untouched. +/// +/// `rollback` and `remove` drop that record with the vendored gem (they +/// leave a vendored package to the vendored unwind and restore no file +/// from its blobs), so for them it is the same case as #2093: nothing +/// would record the patch any more, and the unwind puts the upstream gem +/// back. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_follows_the_manifest_record_of_a_standalone_vendor() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_upstream_gem(&server, &upstream).await; + mount_vendored_grant(&server, &patched).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = project_home(&proj); + let gem_dir = agent_patched_install(&proj, &home); + let uri = server.uri(); + let (code, stdout, stderr) = unwind_run(&proj, &uri, &["vendor", "--yes", "--json"]); + assert_eq!(code, 0, "vendor:\n{stdout}\n{stderr}"); + let manifest_path = proj.join(".socket").join("manifest.json"); + let recorded = || { + std::fs::read_to_string(&manifest_path) + .unwrap() + .contains(PURL) + }; + assert!( + std::fs::read_to_string(proj.join("Gemfile")) + .unwrap() + .contains(".socket/vendor/gem/") + && recorded(), + "premise: vendored, and the manifest keeps the record:\n{stdout}" + ); + + let mut args = unwind.to_vec(); + args.push("--json"); + let (code, stdout, stderr) = unwind_run(&proj, &uri, &args); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); + let text = env.to_string(); + assert!( + !text.contains("upstream_gem_stale_install"), + "{unwind:?}: {env}" + ); + let keeps_record = unwind[0] == "vendor"; + assert_eq!(recorded(), keeps_record, "{unwind:?}: {env}"); + assert_eq!( + installed_lib(&gem_dir), + if keeps_record { + PATCHED_LIB + } else { + UPSTREAM_LIB + }, + "{unwind:?}: {env}" + ); + assert_eq!( + gem_dir.join(".socket-patch-kept").is_file(), + keeps_record, + "{unwind:?}: only a copy with no record left is reinstalled: {env}" + ); + assert_eq!( + text.contains("upstream_gem_install_refreshed"), + !keeps_record, + "{unwind:?}: {env}" + ); + } +} + /// The human run says what it replaced, and rollback's "keeps its patched /// bytes" note no longer counts the gem. #[tokio::test(flavor = "multi_thread")] diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 317516802..bf7381068 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1967,8 +1967,10 @@ and every kind of reinstall keeps it. `rollback` and `remove` do the same with t 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. A gem that was only ever vendored still has the upstream -build installed, and its unwind changes nothing in the gem home. +puts the upstream gem back there too. The same holds for a gem that agent mode patched in place +before it was vendored: the unwind reinstalls the upstream gem over the patched files. A gem that +was only ever vendored still has the upstream build installed, and its unwind changes nothing in +the gem home. Nothing is changed when the patched gem cannot be downloaded or verified: the run still exits 0 and warns (`redirect_gem_stale_install`), naming the files to remove by hand. `--dry-run` only From 9389ca97853638bfc5d7b59cd57385cb6102855a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:50:47 +0000 Subject: [PATCH 5/5] Judge only ledger-owned gems from rubygems.org Review follow-ups for the vendored unwind's record judgment. A gem the manifest still has a record for is not judged: its in-place patch is agent mode's and on record there (standalone vendor keeps the record), so vendor --revert leaves the installed copy as it is. Only a detached ledger entry's record is used, and the manifest is matched by PurlKey as the takeover does. With no sha256 for the upstream gem (an offline run or a registry error under a lock without CHECKSUMS), a copy is judged by its record only when the lock resolves the gem from rubygems.org. A gem from another remote stays unjudged, as in every unwind refresh. Refs #2093 Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeQy1d8enbEzCjPrQua --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../src/commands/gem_refresh.rs | 31 +-- .../socket-patch-cli/src/commands/remove.rs | 6 +- .../socket-patch-cli/src/commands/rollback.rs | 6 +- .../src/commands/vendored_backend/mod.rs | 62 ++---- .../tests/e2e_redirect_gem_stale_install.rs | 178 ++++++++++++------ .../src/patch/redirect/upstream/gem.rs | 14 ++ .../src/patch/redirect/upstream/mod.rs | 8 + docs/ecosystems.md | 7 +- 9 files changed, 188 insertions(+), 126 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 889adb345..4f7754aa6 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -460,7 +460,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. The same holds for a gem standalone `vendor` vendored from an agent-mode manifest once `rollback` or `remove` unwinds it: they drop its manifest record with the vendored gem and restore no file from the record's blobs. `vendor --revert` keeps that manifest record, so the in-place patch stays agent mode's and the installed copy is not judged. 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 the unwind ends, which is the detached ledger entry's own or the manifest record `rollback` / `remove` drop: 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 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 8fb615cf0..9f0a78ff5 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -997,7 +997,9 @@ async fn refresh_restored( records: &BTreeMap, scope: Scope, ) -> RestoreRefresh { - use socket_patch_core::patch::redirect::upstream::{gem_upstream_archive, UpstreamArchive}; + use socket_patch_core::patch::redirect::upstream::{ + gem_resolves_from_rubygems, gem_upstream_archive, UpstreamArchive, + }; use socket_patch_core::vendor::registry_fetch::SecureRegistryClient; let policy = Policy::of(common); @@ -1008,10 +1010,11 @@ async fn refresh_restored( // with why: their installed copies are reported, not passed over. let mut unverified: BTreeMap = BTreeMap::new(); // The records an installed copy is judged by as well: those of the - // gems known to be back on their upstream entries. A copy holding its - // record's patch is stale even when nothing proves the upstream - // sha256 (`--offline` under a lock without `CHECKSUMS`): it is then - // reported, not refreshed. + // gems the lock resolves from rubygems.org, which are back on their + // upstream entries. A copy holding its record's patch is stale even + // when nothing proves the upstream sha256 (`--offline` or a registry + // error, under a lock without `CHECKSUMS`): it is then reported, not + // refreshed. let mut judged: BTreeMap = BTreeMap::new(); for purl in restored .iter() @@ -1031,11 +1034,9 @@ async fn refresh_restored( } shas.insert(purl.clone(), Some(sha256)); urls.insert(purl.clone(), url); - judged.extend( - records - .get_key_value(purl) - .map(|(k, v)| (k.clone(), v.clone())), - ); + if let Some(record) = records.get(purl) { + judged.insert(purl.clone(), record.clone()); + } } // (Only a gem the lock resolves from rubygems.org comes back // unverified, so the vendored unwind's rule holds for it too.) @@ -1043,11 +1044,11 @@ async fn refresh_restored( unverified.insert(purl.clone(), why); } None => { - judged.extend( - records - .get_key_value(purl) - .map(|(k, v)| (k.clone(), v.clone())), - ); + if let Some(record) = records.get(purl) { + if gem_resolves_from_rubygems(&common.cwd, purl).await { + judged.insert(purl.clone(), record.clone()); + } + } } } } diff --git a/crates/socket-patch-cli/src/commands/remove.rs b/crates/socket-patch-cli/src/commands/remove.rs index b08ce3194..1a79c5247 100644 --- a/crates/socket-patch-cli/src/commands/remove.rs +++ b/crates/socket-patch-cli/src/commands/remove.rs @@ -1399,11 +1399,7 @@ async fn revert_vendored_matches( let mut leg = RemoveVendorLeg::default(); // Stops at the first hard failure: remove aborts there, leaving the // remaining matches (and the manifest) untouched. - let mut backend = VendoredBackend::new(&args.common, None); - if !args.preserve_state { - // The manifest record of an unwound package is removed with it. - backend = backend.dropping_manifest_records(); - } + let backend = VendoredBackend::new(&args.common, None); let reverted = backend.revert(keys, state, opts, true).await; for (key, w) in backend.go_undo_warnings(&reverted).await { if loud { diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index f7c089334..d312d38ba 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -1026,11 +1026,7 @@ async fn run_vendored_leg( keep_artifact: preserve, }; let loud = !common.json && !common.silent; - let mut backend = VendoredBackend::new(common, None); - if !preserve { - // The manifest cleanup drops an unwound package's record. - backend = backend.dropping_manifest_records(); - } + let backend = VendoredBackend::new(common, None); let reverted = backend.revert(keys, state, opts, false).await; for (_, w) in backend.go_undo_warnings(&reverted).await { if loud { diff --git a/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs b/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs index 17390e3ad..c69952b5c 100644 --- a/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs +++ b/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs @@ -52,8 +52,6 @@ pub(crate) struct VendoredBackend<'a> { pub(crate) service: Option<&'a VendorServiceConfig>, /// See [`VendoredBackend::with_closing_lines`]. pub(crate) closing_lines: Option<&'a ClosingLines<'a>>, - /// See [`VendoredBackend::dropping_manifest_records`]. - pub(crate) drops_manifest_records: bool, } /// Lines for the human close of a vendor run to print under its summary @@ -92,21 +90,9 @@ impl<'a> VendoredBackend<'a> { common: common.at_project_root(), service, closing_lines: None, - drops_manifest_records: false, } } - /// The caller removes the `.socket/manifest.json` record of every - /// package [`VendoredBackend::revert`] unwinds, without restoring the - /// files that record patched in place (`rollback` and `remove` leave a - /// vendored package to the vendored unwind alone). The unwind's gem - /// refresh then treats such a record as one the unwind ends: an - /// installed copy holding its patch is put back on the upstream gem. - pub(crate) fn dropping_manifest_records(mut self) -> Self { - self.drops_manifest_records = true; - self - } - /// Have [`VendoredBackend::apply`]'s human close print what `lines` /// returns under its summary line. `scan --mode vendored` uses it to /// say which advisories each vendored patch fixes. @@ -294,7 +280,7 @@ impl<'a> VendoredBackend<'a> { }; let (first, last) = (*first, unwound[unwound.len() - 1].0); let purls: Vec = unwound.iter().map(|(_, purl)| purl.clone()).collect(); - let records = self.ended_records(&purls, records).await; + let records = self.ended_records(records).await; let records = &records; let refresh = crate::commands::gem_refresh::after_vendored_unwind(&self.common, &purls, records) @@ -330,45 +316,33 @@ impl<'a> VendoredBackend<'a> { } /// The patch record each unwound gem's installed copies are judged by: - /// the one this unwind ends, after which nothing records an in-place - /// patch of the gem. For a gem `.socket/manifest.json` has no record - /// for, that is the ledger's own (`ledger`, from a detached entry). A - /// manifest record means the in-place patch is agent mode's: the - /// record is the one judged by when the caller drops it - /// ([`Self::dropping_manifest_records`]), and the gem is not judged at - /// all when it stays (`vendor --revert` leaves the patch applied and - /// on record). A manifest that cannot be read proves nothing, so no - /// gem is judged then. + /// `ledger` (the records of detached entries, which the ledger alone + /// owned) without the gems `.socket/manifest.json` has a record for. + /// The in-place patch of such a gem is agent mode's and on record + /// there, so this unwind does not end it. A manifest that cannot be + /// read proves nothing, so no gem is judged then. async fn ended_records( &self, - unwound: &[String], ledger: &std::collections::BTreeMap, ) -> std::collections::BTreeMap { - use socket_patch_core::utils::purl::strip_purl_qualifiers; + use socket_patch_core::utils::purl_key::PurlKey; + if ledger.is_empty() { + return Default::default(); + } let manifest = socket_patch_core::manifest::operations::read_manifest( &self.common.resolved_manifest_path(), ) .await; - let manifest = match manifest { - Ok(Some(manifest)) => manifest, - Ok(None) => return ledger.clone(), + let in_manifest: std::collections::HashSet = match manifest { + Ok(Some(manifest)) => manifest.patches.keys().map(|k| PurlKey::new(k)).collect(), + Ok(None) => Default::default(), Err(_) => return Default::default(), }; - let mut out = ledger.clone(); - for (purl, record) in &manifest.patches { - let base = strip_purl_qualifiers(purl); - let Some(gem) = unwound - .iter() - .find(|gem| strip_purl_qualifiers(gem) == base) - else { - continue; - }; - out.remove(gem); - if self.drops_manifest_records { - out.insert(gem.clone(), record.clone()); - } - } - out + ledger + .iter() + .filter(|(purl, _)| !in_manifest.contains(&PurlKey::new(purl))) + .map(|(purl, record)| (purl.clone(), record.clone())) + .collect() } /// Dropping a vendored Go `replace` leaves a committed 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 304bf396b..e1045f6ec 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 @@ -3255,12 +3255,30 @@ async fn vendored_unwind_leaves_an_upstream_install_alone() { /// the gem home's `cache/`) alone. Returns the installed gem dir and that /// archive. async fn agent_then_vendored(server: &MockServer, proj: &Path) -> (PathBuf, PathBuf) { + agent_then_vendored_from(server, proj, "https://rubygems.org").await +} + +/// [`agent_then_vendored`], with `remote` as the pair's gem source. +async fn agent_then_vendored_from( + server: &MockServer, + proj: &Path, + remote: &str, +) -> (PathBuf, PathBuf) { let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); mount_api_for(server, None, &sha256_of(&patched)).await; serve_upstream_gem(server, &upstream).await; mount_vendored_grant(server, &patched).await; std::fs::create_dir_all(proj).unwrap(); write_manifest_pair(proj); + for file in ["Gemfile", "Gemfile.lock"] { + let text = std::fs::read_to_string(proj.join(file)).unwrap(); + assert!(text.contains("https://rubygems.org"), "premise: {text}"); + std::fs::write( + proj.join(file), + text.replace("https://rubygems.org", remote), + ) + .unwrap(); + } let home = project_home(proj); let gem_dir = agent_patched_install(proj, &home); let archive = home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem")); @@ -3450,79 +3468,133 @@ async fn vendored_unwind_names_an_agent_patched_install_it_leaves() { } } -/// Standalone `vendor` works from the manifest and leaves the record in -/// it, so the in-place patch is still agent mode's. -/// -/// `vendor --revert` undoes the vendoring only: the manifest keeps the -/// record and the installed copy keeps the patch it describes, untouched. -/// -/// `rollback` and `remove` drop that record with the vendored gem (they -/// leave a vendored package to the vendored unwind and restore no file -/// from its blobs), so for them it is the same case as #2093: nothing -/// would record the patch any more, and the unwind puts the upstream gem -/// back. +/// A manifest record for the gem means its in-place patch is agent mode's +/// and still on record, so a vendored unwind does not end it: +/// `vendor --revert` undoes the vendoring only and leaves the installed +/// copy as it is. Two ways there: standalone `vendor`, which works from +/// the manifest and keeps the record in it, and an agent-mode record +/// written again after a vendored takeover. #[tokio::test(flavor = "multi_thread")] -async fn vendored_unwind_follows_the_manifest_record_of_a_standalone_vendor() { - for unwind in VENDORED_UNWINDS { +async fn vendored_unwind_leaves_an_install_the_manifest_still_records() { + for standalone in [true, false] { let server = MockServer::start().await; - let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); - mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_upstream_gem(&server, &upstream).await; - mount_vendored_grant(&server, &patched).await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - std::fs::create_dir_all(&proj).unwrap(); - write_manifest_pair(&proj); let home = project_home(&proj); - let gem_dir = agent_patched_install(&proj, &home); let uri = server.uri(); - let (code, stdout, stderr) = unwind_run(&proj, &uri, &["vendor", "--yes", "--json"]); - assert_eq!(code, 0, "vendor:\n{stdout}\n{stderr}"); - let manifest_path = proj.join(".socket").join("manifest.json"); - let recorded = || { - std::fs::read_to_string(&manifest_path) - .unwrap() - .contains(PURL) + let gem_dir = if standalone { + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_upstream_gem(&server, &upstream).await; + mount_vendored_grant(&server, &patched).await; + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let gem_dir = agent_patched_install(&proj, &home); + let (code, stdout, stderr) = unwind_run(&proj, &uri, &["vendor", "--yes", "--json"]); + assert_eq!(code, 0, "vendor:\n{stdout}\n{stderr}"); + gem_dir + } else { + let (gem_dir, _) = agent_then_vendored(&server, &proj).await; + common::write_in_place_patch_record( + &proj.join(".socket"), + PURL, + UUID, + "lib/stale_probe_gem.rb", + UPSTREAM_LIB.as_bytes(), + PATCHED_LIB.as_bytes(), + ); + gem_dir }; + let case = format!("standalone={standalone}"); + let manifest_path = proj.join(".socket").join("manifest.json"); assert!( std::fs::read_to_string(proj.join("Gemfile")) .unwrap() .contains(".socket/vendor/gem/") - && recorded(), - "premise: vendored, and the manifest keeps the record:\n{stdout}" + && std::fs::read_to_string(&manifest_path) + .unwrap() + .contains(PURL), + "{case}: premise: vendored, with the record in the manifest" ); + let held_before = snapshot(&home); + + let (code, stdout, stderr) = + unwind_run(&proj, &uri, &["vendor", "--revert", "--yes", "--json"]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{case}: {env}\nstderr:\n{stderr}"); + assert!( + !std::fs::read_to_string(proj.join("Gemfile")) + .unwrap() + .contains(".socket/vendor/"), + "{case}: the vendoring is undone: {env}" + ); + assert!( + snapshot(&home) == held_before, + "{case}: the gem home changed: {env}" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{case}"); + assert!( + std::fs::read_to_string(&manifest_path) + .unwrap() + .contains(PURL), + "{case}: the manifest keeps the record: {env}" + ); + let text = env.to_string(); + for code in [ + "upstream_gem_install_refreshed", + "upstream_gem_stale_install", + ] { + assert!(!text.contains(code), "{case}: {code} in {env}"); + } + } +} + +/// A gem the lock resolves from another remote is not judged, as in every +/// unwind refresh: nothing proves its restored entry is the upstream one, +/// and rubygems.org is not asked about a gem that is not its own. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_does_not_judge_an_agent_patched_gem_from_another_remote() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, _) = + agent_then_vendored_from(&server, &proj, "https://gems.example.test").await; + let home = project_home(&proj); + let held_before = snapshot(&home); + let asked_before = server.received_requests().await.unwrap().len(); let mut args = unwind.to_vec(); args.push("--json"); - let (code, stdout, stderr) = unwind_run(&proj, &uri, &args); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); let env = common::parse_json_envelope(&stdout); assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); - let text = env.to_string(); assert!( - !text.contains("upstream_gem_stale_install"), - "{unwind:?}: {env}" - ); - let keeps_record = unwind[0] == "vendor"; - assert_eq!(recorded(), keeps_record, "{unwind:?}: {env}"); - assert_eq!( - installed_lib(&gem_dir), - if keeps_record { - PATCHED_LIB - } else { - UPSTREAM_LIB - }, - "{unwind:?}: {env}" - ); - assert_eq!( - gem_dir.join(".socket-patch-kept").is_file(), - keeps_record, - "{unwind:?}: only a copy with no record left is reinstalled: {env}" + std::fs::read_to_string(proj.join("Gemfile.lock")) + .unwrap() + .contains("remote: https://gems.example.test/"), + "{unwind:?}: premise: back on the other remote" ); - assert_eq!( - text.contains("upstream_gem_install_refreshed"), - !keeps_record, - "{unwind:?}: {env}" + assert!( + snapshot(&home) == held_before, + "{unwind:?}: the gem home changed: {env}" ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{unwind:?}"); + let upstream_asked = server + .received_requests() + .await + .unwrap() + .iter() + .skip(asked_before) + .any(|request| request.url.path().starts_with("/upstream/")); + assert!(!upstream_asked, "{unwind:?}: the unwind asked rubygems.org"); + let text = env.to_string(); + for code in [ + "upstream_gem_install_refreshed", + "upstream_gem_stale_install", + ] { + assert!(!text.contains(code), "{unwind:?}: {code} in {env}"); + } } } diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs b/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs index 8bd6e4bc9..3324cf632 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/gem.rs @@ -1122,6 +1122,20 @@ pub(super) async fn upstream_archive( }) } +/// Whether the lock at `root` resolves the ruby-platform gem `purl` from +/// rubygems.org ([`rubygems_locked`]). `false` with no readable lock. +pub(super) async fn resolves_from_rubygems(root: &std::path::Path, purl: &str) -> bool { + let Some((_, name, version)) = crate::utils::purl::purl_parts(purl) else { + return false; + }; + for file in BUNDLER_LOCKS { + if let Ok(text) = crate::utils::fs::read_regular_to_string(&root.join(file)).await { + return rubygems_locked(&to_lf(&text), &name, &version); + } + } + false +} + /// Whether `lock` resolves `name (version)` from a `GEM` section whose /// remote is rubygems.org (or the `SOCKET_RUBYGEMS_URL` stand-in). fn rubygems_locked(lock: &str, name: &str, version: &str) -> bool { diff --git a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs index 83b247c81..fb0054d4a 100644 --- a/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/upstream/mod.rs @@ -970,6 +970,14 @@ pub async fn gem_upstream_archive( gem::upstream_archive(root, restored, purl, offline).await } +/// Whether the lock on disk at `root` resolves the ruby-platform gem `purl` +/// from rubygems.org: the gem is then on its upstream registry entry, also +/// where [`gem_upstream_archive`] is `None` because nothing proves the +/// archive's sha256 (an offline run, a registry error). +pub async fn gem_resolves_from_rubygems(root: &Path, purl: &str) -> bool { + gem::resolves_from_rubygems(root, purl).await +} + /// Restore every pin in `pins` to its default upstream registry entry. /// See the module docs for the contract. pub async fn restore_upstream( diff --git a/docs/ecosystems.md b/docs/ecosystems.md index bf7381068..2bdc413b3 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1968,9 +1968,10 @@ Vendoring a gem that was hosted (`vendor`, `scan --mode vendored`) leaves the in 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 -before it was vendored: the unwind reinstalls the upstream gem over the patched files. A gem that -was only ever vendored still has the upstream build installed, and its unwind changes nothing in -the gem home. +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 +has the upstream build installed, and its unwind changes nothing in the gem home. Nothing is changed when the patched gem cannot be downloaded or verified: the run still exits 0 and warns (`redirect_gem_stale_install`), naming the files to remove by hand. `--dry-run` only