From 6a97066dd25545967b7d454e7c363f9de27dd698 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:23:31 +0000 Subject: [PATCH 1/6] Start hosted gem unwind fix for a pruned cache Refs #2092. Opens the draft PR that claims the issue. Assisted-by: Claude Code:claude-fable-5-2 From f392882710d9e0b4f216cae116bed7bb7e76226c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:30:25 +0000 Subject: [PATCH 2/6] Test hosted gem unwind in a home with no cache dir Four end-to-end tests for #2092, in a gem home whose cache/ dir is gone: rollback and remove put the upstream gem back, a human run reports it, a copy no patch record can judge is named, and an upstream copy is left alone. The first three fail: the unwind judges an installed copy by its cached archive alone. Assisted-by: Claude Code:claude-fable-5-2 --- .../tests/e2e_redirect_gem_stale_install.rs | 244 ++++++++++++++++++ 1 file changed, 244 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 e1045f6ec..c6bc99793 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 @@ -2663,6 +2663,250 @@ async fn refused_registry_leaves_the_copy_reported(cached_archive: bool) { ); } +/// The commands that unwind a hosted gem. +const HOSTED_UNWINDS: [&[&str]; 2] = [&["rollback", "--yes"], &["remove", PURL, "--yes"]]; + +/// A project whose gem a hosted scan pinned, with the lock as `bundle +/// install` leaves it, in a gem home that has no `cache/` dir (Bundler +/// 4.1's `prune` setting, the `rm -rf "${BUNDLE_PATH}"/ruby/*/cache` of the +/// Dockerfile Rails generates, `gem cleanup`). With `refreshed` the scan +/// replaced the installed copy with the patched build; without, it was told +/// not to (`--no-gem-install-refresh`) and the copy is still the upstream +/// one. Returns the installed gem dir and the gem home. +async fn hosted_with_pruned_home_cache( + server: &MockServer, + proj: &Path, + refreshed: bool, +) -> (PathBuf, PathBuf) { + std::fs::create_dir_all(proj).unwrap(); + write_manifest_pair(proj); + let home = project_home(proj); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let uri = server.uri(); + let flags: &[&str] = if refreshed { + &["--json"] + } else { + &["--json", "--no-gem-install-refresh"] + }; + let (code, _, stderr) = common::run_with_env(proj, &scan_args(proj, &uri, flags), &[]); + assert_eq!(code, 0, "{stderr}"); + let expected = if refreshed { PATCHED_LIB } else { UPSTREAM_LIB }; + assert_eq!(installed_lib(&gem_dir), expected, "premise"); + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + std::fs::remove_dir_all(home.join("cache")).unwrap(); + (gem_dir, home) +} + +/// Every `detail` (a warning's) or `reason` (an event's) that `--json` +/// output carries under `code`, wherever the command puts it. +fn details_with_code(env: &serde_json::Value, code: &str) -> Vec { + fn walk(value: &serde_json::Value, code: &str, out: &mut Vec) { + match value { + serde_json::Value::Object(map) => { + if map + .get("code") + .or(map.get("errorCode")) + .and_then(|c| c.as_str()) + == Some(code) + { + let detail = map.get("detail").or(map.get("reason")); + out.push( + detail + .and_then(|d| d.as_str()) + .unwrap_or_default() + .to_string(), + ); + } + map.values().for_each(|v| walk(v, code, out)); + } + serde_json::Value::Array(items) => items.iter().for_each(|v| walk(v, code, out)), + _ => {} + } + } + let mut out = Vec::new(); + walk(env, code, &mut out); + out +} + +/// #2092: a gem home with no `cache/` dir has no archive to judge the +/// installed copy by. The hosted unwind judges it by the pin's patch record +/// instead, as the scan does in that home, and puts the upstream gem back: +/// otherwise the app keeps loading the patch under the restored lock, and +/// no later `bundle install` changes that. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_restores_an_install_whose_home_cache_was_pruned() { + for command in HOSTED_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_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, home) = hosted_with_pruned_home_cache(&server, &proj, true).await; + let views_before = view_requests(&server).await; + + let mut args = command.to_vec(); + args.push("--json"); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("{command:?}: not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "{command:?}: {env}\n{stderr}"); + let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + assert!(!lock.contains("/patch-registry/"), "{command:?}:\n{lock}"); + assert_eq!( + installed_lib(&gem_dir), + UPSTREAM_LIB, + "{command:?}: the upstream gem is back: {env}" + ); + assert_eq!( + details_with_code(&env, "upstream_gem_install_refreshed").len(), + 1, + "{command:?}: {env}" + ); + assert!( + details_with_code(&env, "upstream_gem_stale_install").is_empty(), + "{command:?}: nothing is left on the patched build: {env}" + ); + assert!( + !home.join("cache").exists(), + "{command:?}: a pruned cache dir is not created" + ); + assert_eq!( + view_requests(&server).await - views_before, + 1, + "{command:?}: one patch record, for that pin" + ); + } +} + +/// The same in a human run: the refresh is a progress line, and the gem is +/// not counted among the packages that keep their patched bytes. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_reports_the_pruned_home_refresh_in_a_human_run() { + 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_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, _) = hosted_with_pruned_home_cache(&server, &proj, true).await; + + // A dry run says what it would do and changes nothing. + let would = format!( + "Would replace the installed copy of 1 gem with the upstream build: {DEP} {DEP_VERSION}." + ); + let (code, stdout, stderr) = + unwind_run(&proj, &server.uri(), &["rollback", "--yes", "--dry-run"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains(&would), "{stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "{stdout}\n{stderr}"); + assert!( + stdout.contains(&format!( + "Replaced the installed copy of 1 gem with the upstream build: {DEP} {DEP_VERSION}." + )), + "{stdout}\n{stderr}" + ); + assert!( + !stdout.contains("patched bytes") && !stderr.contains("still"), + "nothing is left to reinstall:\n{stdout}\n{stderr}" + ); +} + +/// #2092: when no patch record can be had for such a copy (the API fails, +/// or `--offline`), nothing tells it from the patched build. It is left as +/// it is and named as a copy that could not be checked, with the reason and +/// the files to remove: never passed over in silence. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_names_a_pruned_home_install_no_record_can_judge() { + for (offline, reason) in [ + (false, "its patch record could not be fetched"), + (true, "`--offline` is set"), + ] { + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + // The view answers 500. + mount_api_for(&server, Some(0), &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, home) = hosted_with_pruned_home_cache(&server, &proj, true).await; + let before = snapshot(&home); + + let mut args = vec!["rollback", "--yes", "--json"]; + if offline { + args.push("--offline"); + } + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("offline={offline}: not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "offline={offline}: {env}\n{stderr}"); + assert_eq!(snapshot(&home), before, "offline={offline}: left as it is"); + assert!( + details_with_code(&env, "upstream_gem_install_refreshed").is_empty(), + "offline={offline}: {env}" + ); + let unchecked = details_with_code(&env, "upstream_gem_stale_install"); + assert_eq!(unchecked.len(), 1, "offline={offline}: reported: {env}"); + let spec = home + .join("specifications") + .join(format!("{DEP}-{DEP_VERSION}.gemspec")); + for needle in [ + PURL, + "could not be checked against the upstream gem", + reason, + "it still holds the patched build", + "run `bundle install`", + gem_dir.to_str().unwrap(), + spec.to_str().unwrap(), + ] { + assert!( + unchecked[0].contains(needle), + "offline={offline}: missing {needle:?}: {}", + unchecked[0] + ); + } + } +} + +/// The record judges, it does not assume: an installed copy that is still +/// the upstream gem (the scan was told not to refresh it) is left alone in +/// a home with no `cache/` dir too, with no warning and no gem download. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_leaves_an_upstream_install_in_a_pruned_home_alone() { + 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_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (_, home) = hosted_with_pruned_home_cache(&server, &proj, false).await; + let before = snapshot(&home); + let asked_before = server.received_requests().await.unwrap().len(); + + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes", "--json"]); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert_eq!(snapshot(&home), before, "nothing changed"); + assert!( + details_with_code(&env, "upstream_gem_install_refreshed").is_empty() + && details_with_code(&env, "upstream_gem_stale_install").is_empty(), + "{env}" + ); + assert!( + gem_downloads_since(&server, asked_before).await.is_empty(), + "no gem was downloaded" + ); +} + /// The vendored half of the patch API for the fixture's patch: the grant /// names the patched `.gem` and the stub gemspec a path source loads, each /// with its sha512, beside the hosted registry override. Priority 1, so it From 383e7e93d885c24eda62668f5e57c2f78844d063 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:33:56 +0000 Subject: [PATCH 3/6] Test pruned-home gem unwind with a real Bundler A capstone for #2092 in the real-Bundler suite: after a hosted install whose gem home lost its cache/ dir, rollback and remove must leave the upstream gem installed and bundle install must keep it. It fails: the patched copy stays. The mock-registry test of a copy no record can judge drops its offline arm, which no hosted unwind reaches (see the fix). Assisted-by: Claude Code:claude-fable-5-2 --- .../tests/e2e_redirect_gem_build.rs | 97 ++++++++++++++++ .../tests/e2e_redirect_gem_stale_install.rs | 106 ++++++++++-------- 2 files changed, 154 insertions(+), 49 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 f4d1b93f5..099c72bd1 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -5270,6 +5270,103 @@ async fn gem_hosted_unwind_names_a_patched_archive_in_vendor_cache() { } } +/// #2092 against a real Bundler: the gem home has no `cache/` dir (Bundler +/// 4.1's `prune` setting, the `rm -rf "${BUNDLE_PATH}"/ruby/*/cache` of the +/// Dockerfile Rails generates), so the unwind has no archive to judge the +/// installed patched gem by. It judges the copy by the pin's patch record +/// and puts the upstream gem back. Left alone, `bundle install` would call +/// the bundle complete and keep the patched copy under the upstream lock. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 1.17; CHECKSUMS arm >= 2.6); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_unwind_restores_an_install_whose_home_cache_was_pruned() { + let Some(fx) = redirect_scanned_project( + "pruned-unwind", + Spelling::Gemfile, + false, + true, + None, + Driver::ScanVex, + ) + .await + else { + return; + }; + for command in ["rollback", "remove"] { + let dir = stage_fresh_checkout(&fx, &format!("pruned-{command}")); + let install = bundle(&dir, &["install"]); + assert!( + install.status.success(), + "{command}: hosted install:\n{}", + String::from_utf8_lossy(&install.stderr) + ); + let installed = fresh_installed_lib(&dir, &format!("{DEP}-{DEP_VERSION}"), "vuln_gem.rb"); + assert_eq!( + std::fs::read(&installed).unwrap(), + fx.patched, + "{command}: the patched gem is installed (test premise)" + ); + // /gems//lib/ + let home = installed.ancestors().nth(4).unwrap(); + std::fs::remove_dir_all(home.join("cache")).unwrap(); + + let api = fx._server.uri(); + let upstream = format!("{api}/upstream"); + let cwd = dir.to_str().expect("utf8 tmp path"); + let mut argv = vec![command, PURL, "--json", "--cwd", cwd]; + if command == "remove" { + argv.push("--yes"); + } + argv.extend([ + "--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)]); + 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}"); + let lock = std::fs::read_to_string(dir.join(fx.lock_name)).unwrap(); + assert!( + !lock.contains(&fx.index_url), + "{command}: the lock is back on upstream:\n{lock}" + ); + assert_eq!( + std::fs::read(&installed).unwrap(), + orig_lib().into_bytes(), + "{command}: the installed gem is the upstream one again: {env}" + ); + assert!( + env.to_string().contains("upstream_gem_install_refreshed") + && !env.to_string().contains("upstream_gem_stale_install"), + "{command}: {env}" + ); + assert!( + !home.join("cache").exists(), + "{command}: a pruned cache dir is not created" + ); + // The restored project installs as it is, and keeps the upstream gem. + let install = bundle(&dir, &["install"]); + assert!( + install.status.success(), + "{command}: bundle install after the unwind:\n{}", + String::from_utf8_lossy(&install.stderr) + ); + assert_eq!( + std::fs::read(&installed).unwrap(), + orig_lib().into_bytes(), + "{command}: bundle install keeps the upstream bytes" + ); + } +} + /// A warm project: the pre-redirect pair installed from the mock upstream /// into the project's `vendor/bundle`, as on a developer machine or a CI /// job with a restored bundle cache. 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 c6bc99793..4bc674c9a 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 @@ -2818,61 +2818,69 @@ async fn hosted_unwind_reports_the_pruned_home_refresh_in_a_human_run() { ); } -/// #2092: when no patch record can be had for such a copy (the API fails, -/// or `--offline`), nothing tells it from the patched build. It is left as -/// it is and named as a copy that could not be checked, with the reason and -/// the files to remove: never passed over in silence. +/// #2092: when no patch record can be had for such a copy (the API fails), +/// nothing tells it from the patched build. It is left as it is and named +/// as a copy that could not be checked, with the reason and the files to +/// remove: never passed over in silence. #[tokio::test(flavor = "multi_thread")] async fn hosted_unwind_names_a_pruned_home_install_no_record_can_judge() { - for (offline, reason) in [ - (false, "its patch record could not be fetched"), - (true, "`--offline` is set"), - ] { - let server = MockServer::start().await; - let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); - // The view answers 500. - mount_api_for(&server, Some(0), &sha256_of(&patched)).await; - serve_patched_gem(&server, patched.clone()).await; - serve_upstream_gem(&server, &upstream).await; - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - let (gem_dir, home) = hosted_with_pruned_home_cache(&server, &proj, true).await; - let before = snapshot(&home); + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + // The view answers 500. + mount_api_for(&server, Some(0), &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, home) = hosted_with_pruned_home_cache(&server, &proj, true).await; + let before = snapshot(&home); + let asked_before = server.received_requests().await.unwrap().len(); - let mut args = vec!["rollback", "--yes", "--json"]; - if offline { - args.push("--offline"); - } - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); - let env: serde_json::Value = serde_json::from_str(&stdout) - .unwrap_or_else(|e| panic!("offline={offline}: not JSON: {e}\n{stdout}\n{stderr}")); - assert_eq!(code, 0, "offline={offline}: {env}\n{stderr}"); - assert_eq!(snapshot(&home), before, "offline={offline}: left as it is"); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes", "--json"]); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert_eq!(snapshot(&home), before, "left as it is"); + assert!( + details_with_code(&env, "upstream_gem_install_refreshed").is_empty(), + "{env}" + ); + assert!( + gem_downloads_since(&server, asked_before).await.is_empty(), + "no gem was downloaded for a copy nothing judged" + ); + let unchecked = details_with_code(&env, "upstream_gem_stale_install"); + assert_eq!(unchecked.len(), 1, "the copy is reported: {env}"); + let spec = home + .join("specifications") + .join(format!("{DEP}-{DEP_VERSION}.gemspec")); + for needle in [ + PURL, + "could not be checked against the upstream gem", + "its gem home has no archive of it and its patch record could not be fetched", + "it still holds the patched build", + "run `bundle install`", + gem_dir.to_str().unwrap(), + spec.to_str().unwrap(), + ] { assert!( - details_with_code(&env, "upstream_gem_install_refreshed").is_empty(), - "offline={offline}: {env}" + unchecked[0].contains(needle), + "missing {needle:?}: {}", + unchecked[0] ); - let unchecked = details_with_code(&env, "upstream_gem_stale_install"); - assert_eq!(unchecked.len(), 1, "offline={offline}: reported: {env}"); - let spec = home - .join("specifications") - .join(format!("{DEP}-{DEP_VERSION}.gemspec")); - for needle in [ - PURL, - "could not be checked against the upstream gem", - reason, - "it still holds the patched build", - "run `bundle install`", - gem_dir.to_str().unwrap(), - spec.to_str().unwrap(), - ] { - assert!( - unchecked[0].contains(needle), - "offline={offline}: missing {needle:?}: {}", - unchecked[0] - ); - } } + + // A human run counts it apart, in one warning. + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + hosted_with_pruned_home_cache(&server, &proj, true).await; + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stderr.contains("1 gem on disk could not be checked") + && stderr.contains("its patch record could not be fetched"), + "{stdout}\n{stderr}" + ); } /// The record judges, it does not assume: an installed copy that is still From 131f1bc03f4113bdd139dbd1fd6d18f01756ed2c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:37:45 +0000 Subject: [PATCH 4/6] Judge a gem with no cached archive by its patch A hosted unwind (rollback, remove, a withdrawn-patch restore) judged an installed gem only by /cache/.gem. In a gem home with no cache dir (Bundler 4.1 prune, a slim image, gem cleanup) the copy the hosted scan had replaced with the patched build was passed over: no refresh and no warning, and no later bundle install replaced it. The unwind now fetches the record of the patch such a gem was pinned to, as the scan direction does, and judges the copy by its afterHash map through the records mechanism the vendored unwind uses. A copy holding the patch is replaced with the upstream gem. When the record cannot be fetched the copy is left alone and reported as one that could not be checked, with the files to remove. An unwind with no such copy fetches nothing. Fixes #2092 Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 4 +- .../src/commands/gem_refresh.rs | 127 +++++++++++++++++- .../src/commands/hosted_unwind.rs | 16 ++- .../src/commands/scan/hosted.rs | 10 +- docs/ecosystems.md | 5 + 5 files changed, 144 insertions(+), 18 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 6338d568b..37ea995dd 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -456,7 +456,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm - A human run prints ONE warning for all of them: how many gems, which gems in which gem home (or why they were not refreshed), why in one sentence, and the remedy as a command. Its headline is `N gems are still unpatched on disk after the switch to hosted patches` when none of the gems it covers was patched in place; when every one was, `N gems patched in place still have their upstream archives on disk after the switch to hosted patches`; and with both kinds, `N gems still have unpatched files or archives on disk after the switch to hosted patches`. - A stale-flagged purl is additionally **excluded from the same run's `--vex` `assume_applied` set** — the envelope must never attest a CVE its own warning says is live; the purl falls back to normal installed-tree verification (a patched install still attests, a stale one is omitted). A same-run `--vex` may still fail on "nothing to attest" per the embedded-VEX contract. -*The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk). An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive (ruby-platform gems only: the lock's checksum names that archive). Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. +*The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk). An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive (ruby-platform gems only: the lock's checksum names that archive). A copy whose gem home has no readable archive of it (a pruned `cache/`: Bundler 4.1's `prune` setting, a slim image, `gem cleanup`) is judged as the scan direction judges it (#2092): the unwind fetches the record of the patch the gem was pinned to (`…/patches/view/`, for that gem only, and only when the upstream sha256 is known) and the copy is stale when every file the record lists hashes to its `afterHash`; it is then replaced from the upstream archive like any other, and no `cache/` dir is created for it. When that record cannot be fetched, nothing tells the copy from the patched build: it is left as it is and reported under `upstream_gem_stale_install` as one that could not be checked, with that reason and the files to remove. An unwind with no such copy fetches no patch record. Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. *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. @@ -2269,7 +2269,7 @@ 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, 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_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`), or because its gem home has no archive of it and the pin's patch record could not be fetched (#2092); 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. | diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 9f0a78ff5..b1048e1a6 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -940,12 +940,124 @@ pub(crate) struct RestoreRefresh { /// the restore's staged text (the restored lock). Only installed copies /// are reported as still stale here: the restore itself names an archive /// left in Bundler's cache dir (`upstream_gem_stale_cache`). +/// +/// `pins` is the patch uuid each restored gem was pinned to, by purl. An +/// installed copy whose gem home keeps no readable archive of it (a pruned +/// `cache/`: Bundler 4.1's `prune`, a slim image, `gem cleanup`) is judged +/// by that patch's record, as the hosted scan judges it (#2092): see +/// [`pinned_records`]. pub(crate) async fn after_restore( common: &GlobalArgs, restored: &[String], staged: &BTreeMap>, + pins: &BTreeMap, ) -> RestoreRefresh { - refresh_restored(common, restored, staged, &BTreeMap::new(), Scope::All).await + refresh_restored(common, restored, staged, &BTreeMap::new(), pins, Scope::All).await +} + +/// `uuid`'s patch record as the patch API's view gives it; `None` when +/// there is none to judge by (a failed or not-found fetch, another patch's +/// record, or one listing no files). +pub(crate) async fn view_record( + api: &socket_patch_core::api::client::ApiClient, + uuid: &str, +) -> Option { + api.fetch_patch(uuid) + .await + .ok() + .flatten() + .map(|view| socket_patch_core::manifest::records::record_from_patch_response(&view).1) + .filter(|record| record.uuid == uuid && !record.files.is_empty()) +} + +/// The patch record ([`view_record`]) of the patch `uuid` a gem was pinned +/// to, to judge an installed copy by, or why there is none: the reason +/// completes "could not be checked against the upstream gem (…)". +/// `--offline` fetches nothing. `client` is the run's API client for these +/// lookups, built on the first one. +async fn pinned_record( + common: &GlobalArgs, + client: &mut Option, + uuid: &str, +) -> Result { + let record = if common.offline { + None + } else { + let client = match client { + Some(client) => client, + None => client.insert( + socket_patch_core::api::client::get_api_client_with_overrides( + common.api_client_overrides(), + ) + .await + .0, + ), + }; + view_record(client, uuid).await + }; + record.ok_or_else(|| { + "its gem home has no archive of it and its patch record could not be fetched".to_string() + }) +} + +/// What judges the installed copies a hosted unwind's archive check cannot +/// (#2092): those of the gems `upstream` has a sha256 for whose gem home +/// keeps no readable `/cache/.gem`. Nothing else tells such a +/// copy from the patched build the hosted scan may have replaced it with, +/// and no later `bundle install` replaces it. +/// +/// Each such gem's patch record (`pins`: its patch uuid, by purl) is added +/// to `judged`, for [`holds_patch`]. The copies of a gem with no record to +/// be had are returned, each with why: they are reported as not checked. +/// A run with no such copy fetches nothing. +async fn pinned_records( + common: &GlobalArgs, + upstream: &BTreeMap>, + pins: &BTreeMap, + judged: &mut BTreeMap, +) -> Vec<(StaleGem, String)> { + let purls: Vec = upstream + .iter() + .filter(|(purl, sha)| sha.is_some() && pins.contains_key(*purl)) + .map(|(purl, _)| purl.clone()) + .collect(); + if purls.is_empty() { + return Vec::new(); + } + let mut client = None; + let mut no_record: BTreeMap = BTreeMap::new(); + let mut unjudged = Vec::new(); + for copy in installed_with_archives(common, &purls).await { + if socket_patch_core::vendor::file_sha256_hex(©.archive) + .await + .is_some() + { + continue; + } + if !judged.contains_key(©.purl) && !no_record.contains_key(©.purl) { + match pinned_record(common, &mut client, &pins[©.purl]).await { + Ok(record) => { + judged.insert(copy.purl.clone(), record); + } + Err(why) => { + no_record.insert(copy.purl.clone(), why); + } + } + } + if let Some(why) = no_record.get(©.purl) { + unjudged.push(( + StaleGem { + purl: copy.purl, + leaf: copy.leaf, + installed: Some((copy.dir, copy.project_local)), + cache_archive: None, + in_place: false, + }, + why.clone(), + )); + } + } + unjudged } /// After a wet vendored unwind put the gems `unwound` back on their @@ -985,6 +1097,7 @@ pub(crate) async fn after_vendored_unwind( &installed, &BTreeMap::new(), records, + &BTreeMap::new(), Scope::Installed, ) .await @@ -995,6 +1108,7 @@ async fn refresh_restored( restored: &[String], staged: &BTreeMap>, records: &BTreeMap, + pins: &BTreeMap, scope: Scope, ) -> RestoreRefresh { use socket_patch_core::patch::redirect::upstream::{ @@ -1055,11 +1169,14 @@ async fn refresh_restored( if shas.is_empty() && unverified.is_empty() && judged.is_empty() { return RestoreRefresh::default(); } + // A hosted unwind's copies with no archive to judge them by: judged by + // their pin's patch record, or reported when there is none (#2092). + let no_record = pinned_records(common, &shas, pins, &mut judged).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, &BTreeMap::new(), Scope::Installed).await; - if stale.is_empty() && unchecked.is_empty() { + if stale.is_empty() && unchecked.is_empty() && no_record.is_empty() { return RestoreRefresh::default(); } let wanted = |gem: &StaleGem| { @@ -1103,6 +1220,12 @@ async fn refresh_restored( installed.push(gem); } } + for (gem, why) in no_record { + if let Some((dir, _)) = &gem.installed { + pass.left.insert(dir.clone(), Why::Unverified(why)); + installed.push(gem); + } + } RestoreRefresh { refreshed_installs, report: report(direction, &installed, &pass, &policy), diff --git a/crates/socket-patch-cli/src/commands/hosted_unwind.rs b/crates/socket-patch-cli/src/commands/hosted_unwind.rs index 20c451fdb..7de64b4ff 100644 --- a/crates/socket-patch-cli/src/commands/hosted_unwind.rs +++ b/crates/socket-patch-cli/src/commands/hosted_unwind.rs @@ -85,15 +85,21 @@ async fn refresh_restored_gems( use crate::commands::gem_refresh::{after_restore, Direction}; use socket_patch_core::patch::redirect::upstream::GEM_STALE_CACHE; - let restored: Vec = outcome + // Each restored gem with the patch it was pinned to (the first pin's, + // for a gem two pins named). + let mut pins: std::collections::BTreeMap = Default::default(); + for pin in outcome .restored() .filter(|pin| pin.purl.starts_with("pkg:gem/")) - .map(|pin| pin.purl.clone()) - .collect(); - if restored.is_empty() { + { + pins.entry(pin.purl.clone()) + .or_insert_with(|| pin.uuid.clone()); + } + if pins.is_empty() { return; } - let refresh = after_restore(common, &restored, &outcome.staged_text).await; + let restored: Vec = pins.keys().cloned().collect(); + let refresh = after_restore(common, &restored, &outcome.staged_text, &pins).await; out.warnings.retain(|(code, detail)| { code != GEM_STALE_CACHE || !refresh diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index b60266f5c..2a2f11aba 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -241,15 +241,7 @@ impl<'a> ViewFallback<'a> { ) -> Option<&socket_patch_core::manifest::schema::PatchRecord> { if !self.fetched.contains_key(uuid) { let record = match self.api { - Some(api) => api - .fetch_patch(uuid) - .await - .ok() - .flatten() - .map(|view| { - socket_patch_core::manifest::records::record_from_patch_response(&view).1 - }) - .filter(|record| record.uuid == uuid && !record.files.is_empty()), + Some(api) => gem_refresh::view_record(api, uuid).await, None => None, }; self.fetched.insert(uuid.to_string(), record); diff --git a/docs/ecosystems.md b/docs/ecosystems.md index c8f89d538..761b7823f 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2030,6 +2030,11 @@ with a native extension is installed into a staging directory by RubyGems, with owns the installed copy, and swapped in once it has compiled; with no such Ruby, or with `--no-gem-native-rebuild`, it is left alone. After the scan `bundle exec` runs the patched code, and every kind of reinstall keeps it. `rollback` and `remove` do the same with the upstream gem. +That holds in a gem home with no `cache/` directory too (Bundler 4.1's `prune` setting, an image +that deletes it, `gem cleanup`): with no archive to compare, the installed files are checked +against the patch itself, in both directions. If the patch can't be looked up during a `rollback` +or `remove`, the copy is left alone and the run warns (`upstream_gem_stale_install`), naming the +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 From 1de2023076daff90b8c8519349ac27453a37ef38 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:48:21 +0000 Subject: [PATCH 5/6] Judge each archive-less gem copy on its own files Review of the #2092 fix found that the record judgment was keyed by purl and bolted on beside the archive check: - a gem two pins named was judged by the first pin's record only; - the fetched record then judged every copy of the gem, so whether a copy with its archive was replaced depended on a sibling gem home; - an unreachable API cost one timeout per gem; - a copy was still passed over when nothing proved the upstream sha256 (a lock without CHECKSUMS, offline or a registry error); - a gem with one refreshed and one unchecked copy was reported as needing no reinstall, and one with a stale and an unchecked copy lost its place in the warning's headline count; - the leg built an API client of its own. PinJudge now judges each installed copy that has no readable archive by the record of any patch its gem was pinned to, stops asking after the first fetch the API does not answer, and uses the run's API client, which run_hosted_leg now takes. Without an upstream sha256 a copy proven patched is reported as left on the patched build. Refs #2092 Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../src/commands/gem_refresh.rs | 438 +++++++++++++----- .../src/commands/hosted_unwind.rs | 27 +- .../socket-patch-cli/src/commands/remove.rs | 17 +- .../socket-patch-cli/src/commands/rollback.rs | 2 +- .../src/commands/scan/hosted.rs | 6 +- .../src/commands/scan/withdrawn.rs | 5 +- .../socket-patch-cli/src/commands/vendor.rs | 7 +- .../tests/e2e_redirect_gem_stale_install.rs | 64 +++ 9 files changed, 434 insertions(+), 134 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 37ea995dd..fc309e602 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -456,7 +456,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm - A human run prints ONE warning for all of them: how many gems, which gems in which gem home (or why they were not refreshed), why in one sentence, and the remedy as a command. Its headline is `N gems are still unpatched on disk after the switch to hosted patches` when none of the gems it covers was patched in place; when every one was, `N gems patched in place still have their upstream archives on disk after the switch to hosted patches`; and with both kinds, `N gems still have unpatched files or archives on disk after the switch to hosted patches`. - A stale-flagged purl is additionally **excluded from the same run's `--vex` `assume_applied` set** — the envelope must never attest a CVE its own warning says is live; the purl falls back to normal installed-tree verification (a patched install still attests, a stale one is omitted). A same-run `--vex` may still fail on "nothing to attest" per the embedded-VEX contract. -*The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk). An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive (ruby-platform gems only: the lock's checksum names that archive). A copy whose gem home has no readable archive of it (a pruned `cache/`: Bundler 4.1's `prune` setting, a slim image, `gem cleanup`) is judged as the scan direction judges it (#2092): the unwind fetches the record of the patch the gem was pinned to (`…/patches/view/`, for that gem only, and only when the upstream sha256 is known) and the copy is stale when every file the record lists hashes to its `afterHash`; it is then replaced from the upstream archive like any other, and no `cache/` dir is created for it. When that record cannot be fetched, nothing tells the copy from the patched build: it is left as it is and reported under `upstream_gem_stale_install` as one that could not be checked, with that reason and the files to remove. An unwind with no such copy fetches no patch record. Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. +*The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk). An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive (ruby-platform gems only: the lock's checksum names that archive). A copy whose gem home has no readable archive of it (a pruned `cache/`: Bundler 4.1's `prune` setting, a slim image, `gem cleanup`) is judged as the scan direction judges it (#2092): the unwind fetches the record of each patch the gem was pinned to (`…/patches/view/`, for that gem only, through the run's API client) and the copy is stale when every file a record lists hashes to its `afterHash`. Each such copy is judged on its own files, and it is then replaced from the upstream archive like any other; no `cache/` dir is created for it. When a record cannot be fetched (`--offline`, an API error, a patch the API no longer serves) and no other record proves the copy patched, nothing tells it from the patched build: it is left as it is and reported under `upstream_gem_stale_install` as one that could not be checked, with that reason and the files to remove. After the first fetch the API does not answer, no other record is asked for. A wet unwind judges such a copy the same way when nothing proves the upstream sha256 (a lock without `CHECKSUMS`, with `--offline` or a registry error) and the restored lock resolves the gem from rubygems.org: a copy proven patched is then reported as left on the patched build, since there is no verified archive to replace it with. An unwind with no such copy fetches no patch record. Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. *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. diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index b1048e1a6..1409ab5d0 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -15,7 +15,7 @@ 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}; -use crate::args::GlobalArgs; +use crate::args::{GlobalArgs, RunApiClient}; use crate::ui::plural; /// What the lock now pins: the hosted patch, or the upstream registry @@ -657,18 +657,24 @@ pub(crate) fn report( } } // A gem whose copy could not be checked is not known to be stale: it - // is counted apart from the ones that are. - let unchecked: BTreeSet<&str> = local - .iter() - .filter(|(why, _)| matches!(why, Why::Unverified(_))) - .flat_map(|(_, gems)| gems.iter().map(|gem| gem.purl.as_str())) + // is counted apart from the ones that are. A gem with a copy of each + // kind (two gem homes) is known to be stale. + let purls_where = |unverified: bool| { + local + .iter() + .filter(move |(why, _)| matches!(why, Why::Unverified(_)) == unverified) + .flat_map(|(_, gems)| gems.iter().map(|gem| gem.purl.as_str())) + }; + let known_stale: BTreeSet<&str> = shared + .values() + .flatten() + .copied() + .chain(purls_where(false)) .collect(); - let count = stale - .iter() - .map(|gem| gem.purl.as_str()) - .filter(|purl| !unchecked.contains(purl)) - .collect::>() - .len(); + let unchecked: BTreeSet<&str> = purls_where(true) + .filter(|purl| !known_stale.contains(purl)) + .collect(); + let count = known_stale.len(); let switch = match direction { Direction::Patched => "the switch to hosted patches", Direction::Upstream => "the switch back to the upstream registry", @@ -941,123 +947,161 @@ pub(crate) struct RestoreRefresh { /// are reported as still stale here: the restore itself names an archive /// left in Bundler's cache dir (`upstream_gem_stale_cache`). /// -/// `pins` is the patch uuid each restored gem was pinned to, by purl. An -/// installed copy whose gem home keeps no readable archive of it (a pruned -/// `cache/`: Bundler 4.1's `prune`, a slim image, `gem cleanup`) is judged -/// by that patch's record, as the hosted scan judges it (#2092): see -/// [`pinned_records`]. +/// `pins` is the patch uuids each restored gem was pinned to, by purl. An +/// installed copy whose gem home keeps no archive of it (a pruned `cache/`: +/// Bundler 4.1's `prune`, a slim image, `gem cleanup`) is judged by those +/// patches' records, as the hosted scan judges it (#2092): see +/// [`PinJudge`]. `api` is the run's API client, built only if such a copy +/// needs a record. pub(crate) async fn after_restore( common: &GlobalArgs, restored: &[String], staged: &BTreeMap>, - pins: &BTreeMap, + pins: &BTreeMap>, + api: &RunApiClient, ) -> RestoreRefresh { - refresh_restored(common, restored, staged, &BTreeMap::new(), pins, Scope::All).await + let judge = PinJudge { + common, + api, + pins, + fetched: BTreeMap::new(), + unreachable: false, + }; + refresh_restored( + common, + restored, + staged, + &BTreeMap::new(), + Some(judge), + Scope::All, + ) + .await } -/// `uuid`'s patch record as the patch API's view gives it; `None` when -/// there is none to judge by (a failed or not-found fetch, another patch's +/// The patch record a `/patches/view/` response gives for `uuid`; +/// `None` when it has none to judge by (no such patch, another patch's /// record, or one listing no files). -pub(crate) async fn view_record( - api: &socket_patch_core::api::client::ApiClient, +pub(crate) fn view_record( + view: Option, uuid: &str, ) -> Option { - api.fetch_patch(uuid) - .await - .ok() - .flatten() - .map(|view| socket_patch_core::manifest::records::record_from_patch_response(&view).1) + view.map(|view| socket_patch_core::manifest::records::record_from_patch_response(&view).1) .filter(|record| record.uuid == uuid && !record.files.is_empty()) } -/// The patch record ([`view_record`]) of the patch `uuid` a gem was pinned -/// to, to judge an installed copy by, or why there is none: the reason -/// completes "could not be checked against the upstream gem (…)". -/// `--offline` fetches nothing. `client` is the run's API client for these -/// lookups, built on the first one. -async fn pinned_record( - common: &GlobalArgs, - client: &mut Option, - uuid: &str, -) -> Result { - let record = if common.offline { - None - } else { - let client = match client { - Some(client) => client, - None => client.insert( - socket_patch_core::api::client::get_api_client_with_overrides( - common.api_client_overrides(), - ) - .await - .0, - ), - }; - view_record(client, uuid).await - }; - record.ok_or_else(|| { - "its gem home has no archive of it and its patch record could not be fetched".to_string() - }) +/// Whether `path` is a file this run can open: an archive +/// [`stale_after_restore`] can judge an installed copy by. +async fn readable_file(path: &Path) -> bool { + path.is_file() && tokio::fs::File::open(path).await.is_ok() } /// What judges the installed copies a hosted unwind's archive check cannot -/// (#2092): those of the gems `upstream` has a sha256 for whose gem home -/// keeps no readable `/cache/.gem`. Nothing else tells such a -/// copy from the patched build the hosted scan may have replaced it with, -/// and no later `bundle install` replaces it. -/// -/// Each such gem's patch record (`pins`: its patch uuid, by purl) is added -/// to `judged`, for [`holds_patch`]. The copies of a gem with no record to -/// be had are returned, each with why: they are reported as not checked. -/// A run with no such copy fetches nothing. -async fn pinned_records( - common: &GlobalArgs, - upstream: &BTreeMap>, - pins: &BTreeMap, - judged: &mut BTreeMap, -) -> Vec<(StaleGem, String)> { - let purls: Vec = upstream - .iter() - .filter(|(purl, sha)| sha.is_some() && pins.contains_key(*purl)) - .map(|(purl, _)| purl.clone()) - .collect(); - if purls.is_empty() { - return Vec::new(); +/// (#2092): those whose gem home keeps no readable `/cache/.gem`. +/// Nothing else tells such a copy from the patched build the hosted scan +/// may have replaced it with, and no later `bundle install` replaces it. +/// Each is judged on its own files, by the record of a patch its gem was +/// pinned to (`pins`): a copy whose files all hash to a record's +/// `afterHash` values holds that patch. +struct PinJudge<'a> { + common: &'a GlobalArgs, + api: &'a RunApiClient, + pins: &'a BTreeMap>, + /// The record fetched for each uuid asked for so far; `None` when there + /// is none to judge by. + fetched: BTreeMap>, + /// A fetch failed without an answer from the API: no other is tried, + /// so an unreachable API costs one timeout, not one per gem. + unreachable: bool, +} + +impl PinJudge<'_> { + /// `uuid`'s patch record, fetched at most once. `--offline` fetches + /// nothing. + async fn record(&mut self, uuid: &str) -> Option<&PatchRecord> { + if !self.fetched.contains_key(uuid) { + let record = if self.common.offline || self.unreachable { + None + } else { + match self + .common + .api_client(self.api) + .await + .fetch_patch(uuid) + .await + { + Ok(view) => view_record(view, uuid), + Err(_) => { + self.unreachable = true; + None + } + } + }; + self.fetched.insert(uuid.to_string(), record); + } + self.fetched.get(uuid).and_then(Option::as_ref) } - let mut client = None; - let mut no_record: BTreeMap = BTreeMap::new(); - let mut unjudged = Vec::new(); - for copy in installed_with_archives(common, &purls).await { - if socket_patch_core::vendor::file_sha256_hex(©.archive) - .await - .is_some() - { - continue; + + /// The installed copies of `purls` with no readable archive in their + /// gem home: those that hold a pinned patch (stale), and those no + /// record could judge, each with why (the reason completes "could not + /// be checked against the upstream gem (…)"). A copy every pinned + /// patch's record judged, and none found patched, is neither. A run + /// with no such copy fetches nothing. + async fn probe(&mut self, purls: &[String]) -> (Vec, Vec<(StaleGem, String)>) { + let (mut stale, mut unjudged) = (Vec::new(), Vec::new()); + let purls: Vec = purls + .iter() + .filter(|purl| self.pins.contains_key(*purl)) + .cloned() + .collect(); + if purls.is_empty() { + return (stale, unjudged); } - if !judged.contains_key(©.purl) && !no_record.contains_key(©.purl) { - match pinned_record(common, &mut client, &pins[©.purl]).await { - Ok(record) => { - judged.insert(copy.purl.clone(), record); - } - Err(why) => { - no_record.insert(copy.purl.clone(), why); + for copy in installed_with_archives(self.common, &purls).await { + if readable_file(©.archive).await { + continue; + } + let (mut patched, mut missing) = (false, false); + for uuid in self.pins.get(©.purl).into_iter().flatten() { + match self.record(uuid).await { + Some(record) => { + if socket_patch_core::vex::verify::judge_installed_record(©.dir, record) + .await + .patched + { + patched = true; + break; + } + } + None => missing = true, } } + if !patched && !missing { + continue; + } + let gem = StaleGem { + purl: copy.purl, + leaf: copy.leaf, + installed: Some((copy.dir, copy.project_local)), + cache_archive: None, + in_place: false, + }; + if patched { + stale.push(gem); + } else { + let fetch = if self.common.offline { + "`--offline` is set, so its patch record was not fetched" + } else { + "its patch record could not be fetched" + }; + unjudged.push(( + gem, + format!("its gem home has no archive of it and {fetch}"), + )); + } } - if let Some(why) = no_record.get(©.purl) { - unjudged.push(( - StaleGem { - purl: copy.purl, - leaf: copy.leaf, - installed: Some((copy.dir, copy.project_local)), - cache_archive: None, - in_place: false, - }, - why.clone(), - )); - } + (stale, unjudged) } - unjudged } /// After a wet vendored unwind put the gems `unwound` back on their @@ -1097,7 +1141,7 @@ pub(crate) async fn after_vendored_unwind( &installed, &BTreeMap::new(), records, - &BTreeMap::new(), + None, Scope::Installed, ) .await @@ -1108,7 +1152,7 @@ async fn refresh_restored( restored: &[String], staged: &BTreeMap>, records: &BTreeMap, - pins: &BTreeMap, + mut pin_judge: Option>, scope: Scope, ) -> RestoreRefresh { use socket_patch_core::patch::redirect::upstream::{ @@ -1130,6 +1174,9 @@ async fn refresh_restored( // error, under a lock without `CHECKSUMS`): it is then reported, not // refreshed. let mut judged: BTreeMap = BTreeMap::new(); + // The gems a hosted unwind's [`PinJudge`] covers: back on their + // upstream entries, like the ones `judged` holds a record for. + let mut pinned: Vec = Vec::new(); for purl in restored .iter() .filter(|p| Ecosystem::from_purl(p) == Some(Ecosystem::Gem)) @@ -1151,6 +1198,7 @@ async fn refresh_restored( if let Some(record) = records.get(purl) { judged.insert(purl.clone(), record.clone()); } + pinned.push(purl.clone()); } // (Only a gem the lock resolves from rubygems.org comes back // unverified, so the vendored unwind's rule holds for it too.) @@ -1163,16 +1211,28 @@ async fn refresh_restored( judged.insert(purl.clone(), record.clone()); } } + // A wet hosted unwind wrote the restored lock, so the lock + // on disk says where the gem resolves from. + if pin_judge.is_some() + && !policy.dry_run + && gem_resolves_from_rubygems(&common.cwd, purl).await + { + pinned.push(purl.clone()); + } } } } - if shas.is_empty() && unverified.is_empty() && judged.is_empty() { + if shas.is_empty() && unverified.is_empty() && judged.is_empty() && pinned.is_empty() { return RestoreRefresh::default(); } - // A hosted unwind's copies with no archive to judge them by: judged by - // their pin's patch record, or reported when there is none (#2092). - let no_record = pinned_records(common, &shas, pins, &mut judged).await; - let stale = stale_after_restore(common, &shas, &judged, scope).await; + // A hosted unwind's copies with no archive to judge them by: stale + // when they hold a pinned patch, reported when no record says (#2092). + let (pin_stale, no_record) = match &mut pin_judge { + Some(judge) => judge.probe(&pinned).await, + None => Default::default(), + }; + let mut stale = stale_after_restore(common, &shas, &judged, scope).await; + stale.extend(pin_stale); let unjudged = unverified.keys().map(|purl| (purl.clone(), None)).collect(); let unchecked = stale_after_restore(common, &unjudged, &BTreeMap::new(), Scope::Installed).await; @@ -1197,7 +1257,11 @@ 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, &judged, scope).await + let mut still = stale_after_restore(common, &shas, &judged, scope).await; + if let Some(judge) = &mut pin_judge { + still.extend(judge.probe(&pinned).await.0); + } + still } else { stale }; @@ -1209,7 +1273,9 @@ async fn refresh_restored( .refreshed .iter() .filter(|(purl, target)| { - matches!(target, Target::Installed(_)) && !installed.iter().any(|gem| &gem.purl == purl) + matches!(target, Target::Installed(_)) + && !installed.iter().any(|gem| &gem.purl == purl) + && !no_record.iter().any(|(gem, _)| &gem.purl == purl) }) .map(|(purl, _)| purl.clone()) .collect(); @@ -1425,6 +1491,146 @@ mod tests { assert!(out.summary.is_none()); } + /// A gem with a copy known to be stale in one gem home and a copy + /// that could not be checked in another is counted once, as stale: + /// the headline never drops a copy known to hold the patched build. + #[tokio::test] + async fn a_gem_with_a_stale_copy_and_an_unchecked_one_counts_as_stale() { + let tmp = tempfile::tempdir().unwrap(); + let stale = installed("rack", &tmp.path().join("vendor/bundle/ruby/3.4.0"), true); + let unchecked = installed("rack", &tmp.path().join("gems/ruby/3.4.0"), true); + let policy = policy(tmp.path(), true, false, false); + let mut pass = attempt( + std::slice::from_ref(&stale), + unobtainable, + &Source::DiskOnly, + &policy, + Direction::Upstream, + ) + .await; + let (dir, _) = unchecked.installed.clone().unwrap(); + pass.left + .insert(dir, Why::Unverified("no record".to_string())); + + let out = report(Direction::Upstream, &[stale, unchecked], &pass, &policy); + assert_eq!(out.warnings.len(), 2); + let summary = out.summary.expect("a summary"); + assert_eq!( + summary.headline, + "1 gem still holds the patched build on disk after the switch back to the upstream \ + registry" + ); + assert_eq!(summary.bullets.len(), 2, "{:?}", summary.bullets); + } + + /// #2092: [`PinJudge`] judges each installed copy with no archive in + /// its gem home on its own files, by the record of any patch its gem + /// was pinned to. A copy with its archive is the archive check's. + #[tokio::test] + async fn pin_judge_judges_an_archiveless_copy_by_any_of_its_pins() { + use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes as git_sha; + use socket_patch_core::manifest::schema::PatchFileInfo; + + const PURL: &str = "pkg:gem/rack@1.0.0"; + let record = |uuid: &str, after: &str| PatchRecord { + uuid: uuid.to_string(), + exported_at: String::new(), + files: [( + "lib/rack.rb".to_string(), + PatchFileInfo { + before_hash: git_sha(b"upstream\n"), + after_hash: git_sha(after.as_bytes()), + }, + )] + .into(), + vulnerabilities: Default::default(), + description: String::new(), + license: String::new(), + tier: String::new(), + }; + // A project whose own gem home holds `rack 1.0.0` with `lib`. + let project = |lib: &str, archive: bool| { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("vendor/bundle/ruby/3.4.0"); + let gem = home.join("gems/rack-1.0.0"); + std::fs::create_dir_all(gem.join("lib")).unwrap(); + std::fs::write(gem.join("lib/rack.rb"), lib).unwrap(); + std::fs::create_dir_all(home.join("specifications")).unwrap(); + std::fs::write( + home.join("specifications/rack-1.0.0.gemspec"), + "Gem::Specification.new do |s|\n s.name = \"rack\"\n s.version = \"1.0.0\"\nend\n", + ) + .unwrap(); + if archive { + std::fs::create_dir_all(home.join("cache")).unwrap(); + std::fs::write(home.join("cache/rack-1.0.0.gem"), b"archive").unwrap(); + } + tmp + }; + let pins = BTreeMap::from([( + PURL.to_string(), + vec!["uuid-a".to_string(), "uuid-b".to_string()], + )]); + // `--offline`: only the records seeded below are there to judge by. + let probe = |tmp: &tempfile::TempDir, fetched: Vec<(&str, Option)>| { + let common = GlobalArgs { + cwd: tmp.path().to_path_buf(), + offline: true, + ..GlobalArgs::default() + }; + let pins = pins.clone(); + let fetched: BTreeMap> = fetched + .into_iter() + .map(|(uuid, record)| (uuid.to_string(), record)) + .collect(); + async move { + let api = RunApiClient::new(); + let mut judge = PinJudge { + common: &common, + api: &api, + pins: &pins, + fetched, + unreachable: false, + }; + let (stale, unjudged) = judge.probe(&[PURL.to_string()]).await; + assert!(api.get().is_none(), "an offline probe builds no client"); + (stale.len(), unjudged) + } + }; + let (a, b) = (record("uuid-a", "patch a\n"), record("uuid-b", "patch b\n")); + let both = || vec![("uuid-a", Some(a.clone())), ("uuid-b", Some(b.clone()))]; + + // The copy holds the second pin's patch. + let tmp = project("patch b\n", false); + let (stale, unjudged) = probe(&tmp, both()).await; + assert_eq!((stale, unjudged.len()), (1, 0)); + + // Every record judged it, and it holds neither patch. + let tmp = project("upstream\n", false); + let (stale, unjudged) = probe(&tmp, both()).await; + assert_eq!((stale, unjudged.len()), (0, 0)); + + // One pin has no record, and the other's patch is not the copy's: + // nothing says the copy is not the first pin's patched build. + let (stale, unjudged) = probe(&tmp, vec![("uuid-b", Some(b.clone()))]).await; + assert_eq!((stale, unjudged.len()), (0, 1)); + assert_eq!( + unjudged[0].1, + "its gem home has no archive of it and `--offline` is set, so its patch record \ + was not fetched" + ); + + // A record that proves the patch settles it, whatever is missing. + let tmp = project("patch b\n", false); + let (stale, unjudged) = probe(&tmp, vec![("uuid-b", Some(b.clone()))]).await; + assert_eq!((stale, unjudged.len()), (1, 0)); + + // A copy with its archive is judged by the archive, not here. + let tmp = project("patch b\n", true); + let (stale, unjudged) = probe(&tmp, both()).await; + assert_eq!((stale, unjudged.len()), (0, 0)); + } + /// A project-local copy the refresh could not fix says why and names /// the two files whose removal makes Bundler fetch the gem. #[tokio::test] diff --git a/crates/socket-patch-cli/src/commands/hosted_unwind.rs b/crates/socket-patch-cli/src/commands/hosted_unwind.rs index 7de64b4ff..57a3d1497 100644 --- a/crates/socket-patch-cli/src/commands/hosted_unwind.rs +++ b/crates/socket-patch-cli/src/commands/hosted_unwind.rs @@ -5,7 +5,7 @@ use socket_patch_core::patch::redirect::upstream::HostedPin; -use crate::args::GlobalArgs; +use crate::args::{GlobalArgs, RunApiClient}; /// What the hosted leg did. #[derive(Default)] @@ -65,6 +65,8 @@ pub(crate) fn patch_server_origins_of(patch_server_url: Option<&str>) -> Vec = Default::default(); + // Each restored gem with the patches it was pinned to. + let mut pins: std::collections::BTreeMap> = Default::default(); for pin in outcome .restored() .filter(|pin| pin.purl.starts_with("pkg:gem/")) { pins.entry(pin.purl.clone()) - .or_insert_with(|| pin.uuid.clone()); + .or_default() + .push(pin.uuid.clone()); } if pins.is_empty() { return; } let restored: Vec = pins.keys().cloned().collect(); - let refresh = after_restore(common, &restored, &outcome.staged_text, &pins).await; + let refresh = after_restore(common, &restored, &outcome.staged_text, &pins, api).await; out.warnings.retain(|(code, detail)| { code != GEM_STALE_CACHE || !refresh @@ -134,8 +137,14 @@ async fn refresh_restored_gems( /// Restore the in-scope hosted pins to their default upstream registry /// entries (core `patch::redirect::upstream`): v5 hosted mode keeps no /// ledger, so each pin's lock entry is re-resolved from the registry, and a -/// pin that cannot be is refused with the `git checkout` remedy. -pub(crate) async fn run_hosted_leg(common: &GlobalArgs, pins: &[HostedPin]) -> HostedLegOutcome { +/// pin that cannot be is refused with the `git checkout` remedy. `api` is +/// the run's API client, built only when the gem leg needs a patch record +/// (see `refresh_restored_gems`). +pub(crate) async fn run_hosted_leg( + common: &GlobalArgs, + pins: &[HostedPin], + api: &RunApiClient, +) -> HostedLegOutcome { use socket_patch_core::patch::redirect::upstream::{ restore_upstream, PinStatus, RestoreOptions, }; @@ -273,7 +282,7 @@ pub(crate) async fn run_hosted_leg(common: &GlobalArgs, pins: &[HostedPin]) -> H // names: bring the project's installed copies and cached archives // of the restored gems back to the upstream gem, and say what is // still the patched build. - refresh_restored_gems(common, &outcome, &mut out).await; + refresh_restored_gems(common, &outcome, &mut out, api).await; } let unwound: Vec<_> = vlt_targets .into_iter() diff --git a/crates/socket-patch-cli/src/commands/remove.rs b/crates/socket-patch-cli/src/commands/remove.rs index 1a79c5247..d5fcbbd3e 100644 --- a/crates/socket-patch-cli/src/commands/remove.rs +++ b/crates/socket-patch-cli/src/commands/remove.rs @@ -577,7 +577,14 @@ pub async fn run(args: RemoveArgs) -> i32 { // per-purl exit path (restoring the upstream entry IS the removal). let hosted_matches = hosted_pins_matching(&hosted_pins, &target, &[]); if !hosted_matches.is_empty() { - return remove_hosted_only(&args, hosted_matches, &telemetry, commit_recovery).await; + return remove_hosted_only( + &args, + hosted_matches, + &telemetry, + commit_recovery, + &api_client, + ) + .await; } let msg = format!("No patch found matching identifier: {}", args.identifier); @@ -943,7 +950,7 @@ pub async fn run(args: RemoveArgs) -> i32 { if !args.skip_rollback { let hosted_matches = hosted_pins_matching(&hosted_pins, &target, &matched_keys); if !hosted_matches.is_empty() { - let leg = match unwind_hosted(&args.common, &hosted_matches).await { + let leg = match unwind_hosted(&args.common, &hosted_matches, &api_client).await { Ok(leg) => { hosted_leg_warnings.extend(leg.warnings.iter().cloned()); leg @@ -1603,8 +1610,9 @@ async fn sweep_target_orphans( async fn unwind_hosted( common: &GlobalArgs, hosted_matches: &[HostedPin], + api_client: &RunApiClient, ) -> Result { - let leg = run_hosted_leg(common, hosted_matches).await; + let leg = run_hosted_leg(common, hosted_matches, api_client).await; // Printed as soon as the leg returns, so a human run that then fails // still says what it did to the files. print_run_warnings(common, &leg.warnings); @@ -1674,6 +1682,7 @@ async fn remove_hosted_only( hosted_matches: Vec, telemetry: &TelemetryAuth, commit_recovery: Option, + api_client: &RunApiClient, ) -> i32 { let loud = !args.common.json && !args.common.silent; if args.skip_rollback { @@ -1726,7 +1735,7 @@ async fn remove_hosted_only( return 0; } - let leg = match unwind_hosted(&args.common, &hosted_matches).await { + let leg = match unwind_hosted(&args.common, &hosted_matches, api_client).await { Ok(leg) => leg, Err(err) => { track_patch_remove_failed("hosted redirect revert failed", telemetry).await; diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index a146c5bbd..1822eb803 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -2389,7 +2389,7 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { .filter(|pin| hosted_scope.contains(&pin.purl)) .cloned() .collect(); - let hosted_leg = run_hosted_leg(&args.common, &in_scope).await; + let hosted_leg = run_hosted_leg(&args.common, &in_scope, &api_client).await; // An unscoped rollback promises to unwind EVERY hosted patch: // contested wiring it cannot restore fails the leg (a scoped run // names its own targets and leaves unrelated wiring alone). diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 2a2f11aba..2cbaaaa08 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -241,7 +241,11 @@ impl<'a> ViewFallback<'a> { ) -> Option<&socket_patch_core::manifest::schema::PatchRecord> { if !self.fetched.contains_key(uuid) { let record = match self.api { - Some(api) => gem_refresh::view_record(api, uuid).await, + Some(api) => api + .fetch_patch(uuid) + .await + .ok() + .and_then(|view| gem_refresh::view_record(view, uuid)), None => None, }; self.fetched.insert(uuid.to_string(), record); diff --git a/crates/socket-patch-cli/src/commands/scan/withdrawn.rs b/crates/socket-patch-cli/src/commands/scan/withdrawn.rs index c9b711797..7c65359b6 100644 --- a/crates/socket-patch-cli/src/commands/scan/withdrawn.rs +++ b/crates/socket-patch-cli/src/commands/scan/withdrawn.rs @@ -246,7 +246,10 @@ pub(super) async fn sweep( }; let to_restore: Vec = gone.iter().map(|(pin, _)| pin.clone()).collect(); - let leg = crate::commands::hosted_unwind::run_hosted_leg(common, &to_restore).await; + // The scan's own client, for a patch record the gem leg may need. + let run_client = crate::args::RunApiClient::new_with(Some(api_client.clone())); + let leg = + crate::commands::hosted_unwind::run_hosted_leg(common, &to_restore, &run_client).await; out.half_restored = leg.half_applied().map(str::to_string); let action = if common.dry_run { diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 19c3557ef..8a9469eb2 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -4910,7 +4910,12 @@ async fn run_revert(args: &VendorArgs, env: &mut Envelope) -> i32 { .filter(|pin| reverted.contains(&PurlKey::new(&pin.purl))) .collect(); if !rehosted.is_empty() { - let leg = crate::commands::hosted_unwind::run_hosted_leg(common, &rehosted).await; + let leg = crate::commands::hosted_unwind::run_hosted_leg( + common, + &rehosted, + &crate::args::RunApiClient::new(), + ) + .await; for purl in &leg.reverted { record_warning( env, 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 4bc674c9a..65ff715e9 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 @@ -2883,6 +2883,70 @@ async fn hosted_unwind_names_a_pruned_home_install_no_record_can_judge() { ); } +/// #2092 where nothing proves the upstream gem's sha256 (a lock without +/// `CHECKSUMS`, with `--offline` or a registry that does not answer): the +/// copy cannot be replaced, but it is not passed over. Offline no record is +/// fetched and the copy is named as one that could not be checked; with the +/// API in reach the record proves it patched and it is named as stale. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_names_a_pruned_home_install_with_no_upstream_sha256() { + for (offline, needles) in [ + ( + true, + [ + "could not be checked against the upstream gem", + "`--offline` is set, so its patch record was not fetched", + ], + ), + ( + false, + [ + "its patched install at", + "nothing pins the sha256 of the upstream gem", + ], + ), + ] { + let server = MockServer::start().await; + let patched = real_gem(PATCHED_LIB); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + // No rubygems.org stand-in: the compact index is a 404. + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, home) = hosted_with_pruned_home_cache(&server, &proj, true).await; + let before = snapshot(&home); + let views_before = view_requests(&server).await; + + let mut args = vec!["rollback", "--yes", "--json"]; + if offline { + args.push("--offline"); + } + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("offline={offline}: not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "offline={offline}: {env}\n{stderr}"); + assert_eq!(snapshot(&home), before, "offline={offline}: left as it is"); + let left = details_with_code(&env, "upstream_gem_stale_install"); + assert_eq!(left.len(), 1, "offline={offline}: reported: {env}"); + for needle in + needles + .into_iter() + .chain([PURL, "run `bundle install`", gem_dir.to_str().unwrap()]) + { + assert!( + left[0].contains(needle), + "offline={offline}: missing {needle:?}: {}", + left[0] + ); + } + assert_eq!( + view_requests(&server).await - views_before, + usize::from(!offline), + "offline={offline}: an offline run fetches no record" + ); + } +} + /// The record judges, it does not assume: an installed copy that is still /// the upstream gem (the scan was told not to refresh it) is left alone in /// a home with no `cache/` dir too, with no warning and no gem download. From 10a4c863ba17a25dc41cc037b40e430df65d6937 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 18:00:05 +0000 Subject: [PATCH 6/6] Report an archive-less gem copy no record judged A second review of the #2092 fix: - any API error stopped every later record fetch. Only a request the API did not answer (a network error) does now; - a copy missing a file its record lists was taken as free of the patch. A record judges only files it could read, so such a copy is reported as not checked; - a gem restored to a remote other than rubygems.org was not judged when nothing proved its upstream sha256. The restore that ran is what says the gem is back on its upstream entry; - the reason told a user to expect a fetch failure when the API had answered that it has no record of the patch; - the judge and the archive check now use one test for a readable archive, and after_restore takes the pins alone. Refs #2092 Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../src/commands/gem_refresh.rs | 197 +++++++++++------- .../src/commands/hosted_unwind.rs | 3 +- 3 files changed, 120 insertions(+), 82 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index fc309e602..cbcef0001 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -456,7 +456,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm - A human run prints ONE warning for all of them: how many gems, which gems in which gem home (or why they were not refreshed), why in one sentence, and the remedy as a command. Its headline is `N gems are still unpatched on disk after the switch to hosted patches` when none of the gems it covers was patched in place; when every one was, `N gems patched in place still have their upstream archives on disk after the switch to hosted patches`; and with both kinds, `N gems still have unpatched files or archives on disk after the switch to hosted patches`. - A stale-flagged purl is additionally **excluded from the same run's `--vex` `assume_applied` set** — the envelope must never attest a CVE its own warning says is live; the purl falls back to normal installed-tree verification (a patched install still attests, a stale one is omitted). A same-run `--vex` may still fail on "nothing to attest" per the embedded-VEX contract. -*The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk). An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive (ruby-platform gems only: the lock's checksum names that archive). A copy whose gem home has no readable archive of it (a pruned `cache/`: Bundler 4.1's `prune` setting, a slim image, `gem cleanup`) is judged as the scan direction judges it (#2092): the unwind fetches the record of each patch the gem was pinned to (`…/patches/view/`, for that gem only, through the run's API client) and the copy is stale when every file a record lists hashes to its `afterHash`. Each such copy is judged on its own files, and it is then replaced from the upstream archive like any other; no `cache/` dir is created for it. When a record cannot be fetched (`--offline`, an API error, a patch the API no longer serves) and no other record proves the copy patched, nothing tells it from the patched build: it is left as it is and reported under `upstream_gem_stale_install` as one that could not be checked, with that reason and the files to remove. After the first fetch the API does not answer, no other record is asked for. A wet unwind judges such a copy the same way when nothing proves the upstream sha256 (a lock without `CHECKSUMS`, with `--offline` or a registry error) and the restored lock resolves the gem from rubygems.org: a copy proven patched is then reported as left on the patched build, since there is no verified archive to replace it with. An unwind with no such copy fetches no patch record. Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. +*The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk). An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive (ruby-platform gems only: the lock's checksum names that archive). A copy whose gem home has no readable archive of it (a pruned `cache/`: Bundler 4.1's `prune` setting, a slim image, `gem cleanup`) is judged as the scan direction judges it (#2092): the unwind fetches the record of each patch the gem was pinned to (`…/patches/view/`, for that gem only, through the run's API client) and the copy is stale when every file a record lists hashes to its `afterHash`. Each such copy is judged on its own files, and it is then replaced from the upstream archive like any other; no `cache/` dir is created for it. When no record proves the copy patched and one of them could not judge it (`--offline`, a failed fetch, a patch the API has no record of, record files missing from the copy), nothing tells it from the patched build: it is left as it is and reported under `upstream_gem_stale_install` as one that could not be checked, with that reason and the files to remove. After a request the API does not answer (a network error), no other record is asked for. Such a copy is judged the same way when nothing proves the upstream sha256 (a lock without `CHECKSUMS`, with `--offline` or a registry error): one proven patched is then reported as left on the patched build, since there is no verified archive to replace it with. An unwind with no such copy fetches no patch record. Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. *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. diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 1409ab5d0..db3311adf 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -774,13 +774,17 @@ async fn installed_with_archives(common: &GlobalArgs, purls: &[String]) -> Vec, } -/// After a hosted unwind restored the gems `restored` to their upstream +/// After a hosted unwind restored the gems of `pins` to their upstream /// entries: bring their installed copies and cached archives back to the /// upstream gem, and report what is still the patched build. `staged` is /// the restore's staged text (the restored lock). Only installed copies @@ -955,7 +959,6 @@ pub(crate) struct RestoreRefresh { /// needs a record. pub(crate) async fn after_restore( common: &GlobalArgs, - restored: &[String], staged: &BTreeMap>, pins: &BTreeMap>, api: &RunApiClient, @@ -967,9 +970,10 @@ pub(crate) async fn after_restore( fetched: BTreeMap::new(), unreachable: false, }; + let restored: Vec = pins.keys().cloned().collect(); refresh_restored( common, - restored, + &restored, staged, &BTreeMap::new(), Some(judge), @@ -989,10 +993,16 @@ pub(crate) fn view_record( .filter(|record| record.uuid == uuid && !record.files.is_empty()) } -/// Whether `path` is a file this run can open: an archive -/// [`stale_after_restore`] can judge an installed copy by. -async fn readable_file(path: &Path) -> bool { - path.is_file() && tokio::fs::File::open(path).await.is_ok() +/// Why a hosted unwind has no patch record to judge an installed copy by. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum NoRecord { + /// `--offline`: nothing is fetched. + Offline, + /// The fetch failed, or was not tried after one the API did not answer. + Unfetched, + /// The API answered, with no record of that patch to judge by (a + /// withdrawn patch, one listing no files). + NotServed, } /// What judges the installed copies a hosted unwind's archive check cannot @@ -1006,79 +1016,89 @@ struct PinJudge<'a> { common: &'a GlobalArgs, api: &'a RunApiClient, pins: &'a BTreeMap>, - /// The record fetched for each uuid asked for so far; `None` when there - /// is none to judge by. - fetched: BTreeMap>, - /// A fetch failed without an answer from the API: no other is tried, - /// so an unreachable API costs one timeout, not one per gem. + /// The record fetched for each uuid asked for so far, or why there is + /// none. + fetched: BTreeMap>, + /// A request got no answer from the API (a network error, a timeout): + /// no other is sent, so an API out of reach costs one timeout, not one + /// per gem. unreachable: bool, } impl PinJudge<'_> { - /// `uuid`'s patch record, fetched at most once. `--offline` fetches - /// nothing. - async fn record(&mut self, uuid: &str) -> Option<&PatchRecord> { + /// `uuid`'s patch record, fetched at most once. + async fn record(&mut self, uuid: &str) -> Result<&PatchRecord, NoRecord> { + use socket_patch_core::api::client::ApiError; if !self.fetched.contains_key(uuid) { - let record = if self.common.offline || self.unreachable { - None + let record = if self.common.offline { + Err(NoRecord::Offline) + } else if self.unreachable { + Err(NoRecord::Unfetched) } else { - match self - .common - .api_client(self.api) - .await - .fetch_patch(uuid) - .await - { - Ok(view) => view_record(view, uuid), - Err(_) => { - self.unreachable = true; - None + let api = self.common.api_client(self.api).await; + match api.fetch_patch(uuid).await { + Ok(view) => view_record(view, uuid).ok_or(NoRecord::NotServed), + Err(e) => { + self.unreachable = matches!(e, ApiError::Network(_)); + Err(NoRecord::Unfetched) } } }; self.fetched.insert(uuid.to_string(), record); } - self.fetched.get(uuid).and_then(Option::as_ref) + match self.fetched.get(uuid) { + Some(Ok(record)) => Ok(record), + Some(Err(why)) => Err(*why), + None => Err(NoRecord::Unfetched), + } } /// The installed copies of `purls` with no readable archive in their - /// gem home: those that hold a pinned patch (stale), and those no - /// record could judge, each with why (the reason completes "could not - /// be checked against the upstream gem (…)"). A copy every pinned - /// patch's record judged, and none found patched, is neither. A run - /// with no such copy fetches nothing. + /// gem home: those that hold a pinned patch (stale), and those nothing + /// could judge, each with why (the reason completes "could not be + /// checked against the upstream gem (…)"). A copy is neither when a + /// record judged it and found files that are not its patch's, and no + /// other pin of its gem is left unjudged. A run with no such copy + /// fetches nothing. async fn probe(&mut self, purls: &[String]) -> (Vec, Vec<(StaleGem, String)>) { + use socket_patch_core::vendor::file_sha256_hex; + use socket_patch_core::vex::verify::judge_installed_record; + let (mut stale, mut unjudged) = (Vec::new(), Vec::new()); - let purls: Vec = purls - .iter() - .filter(|purl| self.pins.contains_key(*purl)) - .cloned() - .collect(); - if purls.is_empty() { - return (stale, unjudged); - } - for copy in installed_with_archives(self.common, &purls).await { - if readable_file(©.archive).await { + for copy in installed_with_archives(self.common, purls).await { + // The same test as `stale_after_restore`'s: an archive it can + // hash is its to judge the copy by. + if file_sha256_hex(©.archive).await.is_some() { continue; } - let (mut patched, mut missing) = (false, false); + // Why the copy is not known to be free of a pinned patch: a pin + // with no record, or a record whose files could not be read. + let (mut patched, mut open) = (false, None); for uuid in self.pins.get(©.purl).into_iter().flatten() { match self.record(uuid).await { - Some(record) => { - if socket_patch_core::vex::verify::judge_installed_record(©.dir, record) - .await - .patched - { + Ok(record) => { + let judged = judge_installed_record(©.dir, record).await; + if judged.patched { patched = true; break; } + if !judged.stale_evidence { + open.get_or_insert( + "the files its patch record lists could not be read", + ); + } + } + Err(why) => { + open.get_or_insert(match why { + NoRecord::Offline => { + "`--offline` is set, so its patch record was not fetched" + } + NoRecord::Unfetched => "its patch record could not be fetched", + NoRecord::NotServed => "the patch API has no record of its patch", + }); } - None => missing = true, } } - if !patched && !missing { - continue; - } let gem = StaleGem { purl: copy.purl, leaf: copy.leaf, @@ -1086,18 +1106,12 @@ impl PinJudge<'_> { cache_archive: None, in_place: false, }; - if patched { - stale.push(gem); - } else { - let fetch = if self.common.offline { - "`--offline` is set, so its patch record was not fetched" - } else { - "its patch record could not be fetched" - }; - unjudged.push(( - gem, - format!("its gem home has no archive of it and {fetch}"), - )); + match (patched, open) { + (true, _) => stale.push(gem), + (false, Some(why)) => { + unjudged.push((gem, format!("its gem home has no archive of it and {why}"))) + } + (false, None) => {} } } (stale, unjudged) @@ -1174,8 +1188,9 @@ async fn refresh_restored( // error, under a lock without `CHECKSUMS`): it is then reported, not // refreshed. let mut judged: BTreeMap = BTreeMap::new(); - // The gems a hosted unwind's [`PinJudge`] covers: back on their - // upstream entries, like the ones `judged` holds a record for. + // The gems a hosted unwind's [`PinJudge`] covers. Each is back on its + // upstream entry, whatever remote that is and whether or not anything + // proves the upstream sha256: the restore that ran says so. let mut pinned: Vec = Vec::new(); for purl in restored .iter() @@ -1198,7 +1213,9 @@ async fn refresh_restored( if let Some(record) = records.get(purl) { judged.insert(purl.clone(), record.clone()); } - pinned.push(purl.clone()); + if pin_judge.is_some() { + pinned.push(purl.clone()); + } } // (Only a gem the lock resolves from rubygems.org comes back // unverified, so the vendored unwind's rule holds for it too.) @@ -1211,12 +1228,7 @@ async fn refresh_restored( judged.insert(purl.clone(), record.clone()); } } - // A wet hosted unwind wrote the restored lock, so the lock - // on disk says where the gem resolves from. - if pin_judge.is_some() - && !policy.dry_run - && gem_resolves_from_rubygems(&common.cwd, purl).await - { + if pin_judge.is_some() { pinned.push(purl.clone()); } } @@ -1231,6 +1243,7 @@ async fn refresh_restored( Some(judge) => judge.probe(&pinned).await, None => Default::default(), }; + let pin_stale_any = !pin_stale.is_empty(); let mut stale = stale_after_restore(common, &shas, &judged, scope).await; stale.extend(pin_stale); let unjudged = unverified.keys().map(|purl| (purl.clone(), None)).collect(); @@ -1258,7 +1271,8 @@ async fn refresh_restored( let mut pass = attempt(&stale, wanted, &source, &policy, direction).await; let still = if pass.changed(&policy) { let mut still = stale_after_restore(common, &shas, &judged, scope).await; - if let Some(judge) = &mut pin_judge { + // (A copy no record judged is not one the pass could change.) + if let Some(judge) = pin_judge.as_mut().filter(|_| pin_stale_any) { still.extend(judge.probe(&pinned).await.0); } still @@ -1573,14 +1587,16 @@ mod tests { )]); // `--offline`: only the records seeded below are there to judge by. let probe = |tmp: &tempfile::TempDir, fetched: Vec<(&str, Option)>| { + let fetched = fetched + .into_iter() + .map(|(uuid, record)| (uuid, record.ok_or(NoRecord::NotServed))); let common = GlobalArgs { cwd: tmp.path().to_path_buf(), offline: true, ..GlobalArgs::default() }; let pins = pins.clone(); - let fetched: BTreeMap> = fetched - .into_iter() + let fetched: BTreeMap> = fetched .map(|(uuid, record)| (uuid.to_string(), record)) .collect(); async move { @@ -1625,6 +1641,29 @@ mod tests { let (stale, unjudged) = probe(&tmp, vec![("uuid-b", Some(b.clone()))]).await; assert_eq!((stale, unjudged.len()), (1, 0)); + // The API has no record of one pin's patch: the reason says so. + let tmp = project("upstream\n", false); + let (_, unjudged) = probe(&tmp, vec![("uuid-a", None), ("uuid-b", Some(b.clone()))]).await; + assert_eq!( + unjudged[0].1, + "its gem home has no archive of it and the patch API has no record of its patch" + ); + + // A record judges only files it could read: a copy without the file + // the record lists is not known to be free of the patch. + std::fs::remove_file( + tmp.path() + .join("vendor/bundle/ruby/3.4.0/gems/rack-1.0.0/lib/rack.rb"), + ) + .unwrap(); + let (stale, unjudged) = probe(&tmp, both()).await; + assert_eq!(stale, 0); + assert_eq!( + unjudged[0].1, + "its gem home has no archive of it and the files its patch record lists could not \ + be read" + ); + // A copy with its archive is judged by the archive, not here. let tmp = project("patch b\n", true); let (stale, unjudged) = probe(&tmp, both()).await; diff --git a/crates/socket-patch-cli/src/commands/hosted_unwind.rs b/crates/socket-patch-cli/src/commands/hosted_unwind.rs index 57a3d1497..cfe31abfd 100644 --- a/crates/socket-patch-cli/src/commands/hosted_unwind.rs +++ b/crates/socket-patch-cli/src/commands/hosted_unwind.rs @@ -101,8 +101,7 @@ async fn refresh_restored_gems( if pins.is_empty() { return; } - let restored: Vec = pins.keys().cloned().collect(); - let refresh = after_restore(common, &restored, &outcome.staged_text, &pins, api).await; + let refresh = after_restore(common, &outcome.staged_text, &pins, api).await; out.warnings.retain(|(code, detail)| { code != GEM_STALE_CACHE || !refresh