diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index a1d543d5e..767d13854 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -494,7 +494,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm *What never refreshes.* A hosted → vendored takeover (`vendor`, `scan` / `get --mode vendored` over a hosted pin) puts the gem on its upstream entry only on its way to the vendored `path:` source, which is what Bundler loads from then on. The copies Bundler already holds are unused leftovers there, so the takeover changes none of them and downloads no gem for them: resetting the installed copy to the upstream build would cost a registry download in the mode that needs none, and would turn a patched leftover into an unpatched one that `vex` reports against the vendored artifact (`vendored_tree_out_of_sync`, whose gem wording names the copy and how to remove it). Its `upstream_gem_stale_cache` advisory about a patched cache-dir archive is as before. A vendored unwind (`remove`, `rollback`, `vendor --revert`, `scan --prune`, `vendor`'s reconcile of a vendored gem) likewise only names that archive, and never replaces it. -*A vendored unwind after a hosted or an agent scan.* Once a vendored gem is unwound, Bundler loads its installed copy again, so the leftover is in use: if a hosted scan made that copy the patched build before the gem was vendored, the patched code would keep running under the upstream lock, and on bundler ≥ 2.6 `bundle pristine` would fail on the upstream checksum. If agent mode patched that copy in place before the gem was vendored (#2093), the takeover moved its manifest record into the vendor ledger and kept the patched files, so the patched code would keep running with no record left that `rollback` or `apply --check` could act on. A gem `.socket/manifest.json` still has a record for is different: its in-place patch is agent mode's and on record (standalone `vendor` works from the manifest and keeps the record), so the vendored unwind does not judge its installed copy by a record. A wet `rollback`, `remove`, `vendor --revert` or `vendor` reconcile that put a vendored gem back on its upstream entry therefore applies the unwind direction's refresh to the gem's INSTALLED copies (of every build the restored lock names: a gem vendored from prebuilt platform gems is installed as `--`, #2174) when the lock now resolves the gem from rubygems.org (a gem from another remote is not judged: nothing proves its entry is the upstream one), under the same rules (staleness judged by `/cache/.gem` against the upstream sha256, and by the patch record of a detached ledger entry (`scan` / `get --mode vendored`) whose gem the manifest has no record for: a copy whose files all hash to the record's `afterHash` values is stale whatever archive its gem home holds, or when it holds none; a project-local gem home only, unless `--gem-refresh-shared`; `--no-gem-install-refresh`; an archive on disk, else rubygems.org unless `--offline`), with the same `upstream_gem_install_refreshed` note and `upstream_gem_stale_install` warning. `--json` carries them where the command carries a vendored revert's advisories (rollback `warnings[]`; `remove` / `vendor` advisory events); a human run prints the progress line after the gem's own line and one warning for the gems left on the patched build. The upstream sha256 is looked up only for a gem that has an installed copy with its archive, or one holding the record's patched files, so the unwind of a gem that is not installed needs no network. A gem that was only ever vendored has the upstream archive there: nothing is downloaded or changed. A copy agent mode patched is reinstalled from the upstream archive RubyGems kept beside it, so nothing is downloaded for it either unless that archive is gone (a pruned `cache/`); the reinstall also removes what agent mode kept in the gem dir. When nothing proves the upstream sha256 for such a copy (`--offline` under a lock without `CHECKSUMS`), it is left as it is and named by `upstream_gem_stale_install`. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry is refused (a plain-`http` `SOCKET_RUBYGEMS_URL`, see the unwind direction), such an installed copy is reported as one that could not be checked, whichever of the two it is: nothing tells them apart. A `--dry-run` does not preview this (the lock on disk is still the vendored one), and `scan --prune` does not refresh. +*A vendored unwind after a hosted or an agent scan.* Once a vendored gem is unwound, Bundler loads its installed copy again, so the leftover is in use: if a hosted scan made that copy the patched build before the gem was vendored, the patched code would keep running under the upstream lock, and on bundler ≥ 2.6 `bundle pristine` would fail on the upstream checksum. If agent mode patched that copy in place before the gem was vendored (#2093), the takeover moved its manifest record into the vendor ledger and kept the patched files, so the patched code would keep running with no record left that `rollback` or `apply --check` could act on. A gem `.socket/manifest.json` still has a record for is different: its in-place patch is agent mode's and on record (standalone `vendor` works from the manifest and keeps the record), so the vendored unwind does not judge its installed copy by a record. A wet `rollback`, `remove`, `vendor --revert` or `vendor` reconcile that put a vendored gem back on its upstream entry therefore applies the unwind direction's refresh to the gem's INSTALLED copies (of every build the restored lock names: a gem vendored from prebuilt platform gems is installed as `--`, #2174) when the lock now resolves the gem from rubygems.org (a gem from another remote is not judged: nothing proves its entry is the upstream one), under the same rules (staleness judged by `/cache/.gem` against the upstream sha256, and by the patch record of a detached ledger entry (`scan` / `get --mode vendored`) whose gem the manifest has no record for: a copy whose files all hash to the record's `afterHash` values is stale whatever archive its gem home holds, or when it holds none; a project-local gem home only, unless `--gem-refresh-shared`; `--no-gem-install-refresh`; an archive on disk, else rubygems.org unless `--offline`), with the same `upstream_gem_install_refreshed` note and `upstream_gem_stale_install` warning. `--json` carries them where the command carries a vendored revert's advisories (rollback `warnings[]`; `remove` / `vendor` advisory events); a human run prints the progress line after the gem's own line and one warning for the gems left on the patched build. The upstream sha256 is looked up only for a gem that has an installed copy with its archive, or one holding the record's patched files, so the unwind of a gem that is not installed needs no network. A gem that was only ever vendored has the upstream archive there: nothing is downloaded or changed. Rollback's "keep their patched bytes" note and its `reinstall_required` warning do not count a vendored gem whose installed copies are all proven to be the upstream build (#2214): each has, in its gem home, the archive with the verified upstream sha256, and every file the gem's ledger record lists is in its pre-patch state there (it hashes to its `beforeHash`, or the patch adds it and it is absent). Anything short of that proof keeps the gem in the count: a gem with no installed copy the run can find, a gem from another remote, a pruned `cache/`, no verified sha256, a ledger entry with no record (standalone `vendor` before v5), a file that is patched, edited or unreadable. A `--dry-run`, which does not judge the installed copies, counts every vendored gem it would unwind. A copy agent mode patched is reinstalled from the upstream archive RubyGems kept beside it, so nothing is downloaded for it either unless that archive is gone (a pruned `cache/`); the reinstall also removes what agent mode kept in the gem dir. When nothing proves the upstream sha256 for such a copy (`--offline` under a lock without `CHECKSUMS`), it is left as it is and named by `upstream_gem_stale_install`. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry is refused (a plain-`http` `SOCKET_RUBYGEMS_URL`, see the unwind direction), such an installed copy is reported as one that could not be checked, whichever of the two it is: nothing tells them apart. A `--dry-run` does not preview this (the lock on disk is still the vendored one), and `scan --prune` does not refresh. **Pipenv hosted redirect (`Pipfile.lock`, pipfile-spec 6)**: every category other than `_meta` (`default`, `develop`, and Pipenv 2022+ named categories) that pins the package at the patched version is rewritten to the hosted reference — `{"file" | "path": "#sha256=", "hashes": ["sha256:"]}` with `markers`/`extras`/`index` kept exactly as Pipenv wrote them (present or absent: whether Pipenv records `index` depends on its release, the Pipfile spelling and the locking environment, so only the entry itself knows) and `version` dropped; `_meta` (the Pipfile content hash) and the Pipfile itself are never touched, so `pipenv install --deploy`/`sync`/`verify` keep passing. The reference KEY depends on the installing Pipenv: releases 7–11 only install `path` references, 2018 and later `file` ones (0–6 write pipfile-spec < 6 and are refused). The release is probed once per command with `pipenv --version`, resolved on ABSOLUTE `PATH` entries only (a relative entry would run a `pipenv` planted in the scanned repository; `.bat`/`.cmd` shims are found through `PATHEXT` on Windows), only when a pypi patch actually targets an entry of the lock, and `SOCKET_PIPENV_MAJOR=` pins the answer without spawning anything. An unknown installer selects `file` and warns `redirect_pipenv_installer_unknown` only when the lock was rewritten. **Refusal scope**: a pin/source CONFLICT (another version pinned, a foreign `file`/`path` source, a VCS/editable dependency) refuses the whole dependency atomically across categories as `redirect_pipenv_refused` AND vetoes the sibling Python rewriters (requirements.txt / uv.lock / pyproject) for that patch — the project's Pipenv install could not pick the patch up, so a half-redirected checkout is refused; anything else (no entry for the package, an old pipfile-spec, an unparseable lock, a digest-less patch) is `redirect_pipenv_skipped` and leaves the siblings alone (a stale Pipfile.lock in a uv/Poetry/requirements project must not block them). The veto applies to a LIVE lock only: a `Pipfile.lock` with no `Pipfile` beside it is abandoned, so its conflict refuses that file but never the siblings. Hash enforcement at install time is split by era — the `#sha256=` URL fragment is what Pipenv 2023+ verifies, the `hashes` list what 2018–2022 verify, Pipenv 11 either — so both are load-bearing. **Pipenv stale-install guard**: Pipenv never reinstalls a release that is already present (`pipenv install`, `install --deploy` and `sync` all exit 0 and keep the installed bytes — measured on 11.10.4, 2018.11.26 and 2026.8.0, hosted and vendored), so after the rewrite the run probes the Python crawler's site-packages (VIRTUAL_ENV, `./.venv`, `./venv`, Pipenv's out-of-tree `WORKON_HOME` venv; `--global`/`--global-prefix` honoured) for each confirmed Pipfile.lock redirect with the Python stale-install guard's evidence (the pinned patched wheel, else the patch record; STALE needs positive evidence, read-only, skipped on `--dry-run`, stale purls excluded from the same-run `--vex` `assume_applied` set) and the Python stale-install guard (`redirect_pypi_stale_install`, see above) names the site-packages dir and the Pipenv-specific verified remedy: `pipenv run pip uninstall -y && pipenv sync` (or `pipenv --rm && pipenv sync`), with the `sync` arguments following the lock, since plain `pipenv sync` installs only `default`: the targeted form re-syncs the categories that pin the package (`--dev` for `develop`, `--categories ""` for a named category) and the `--rm` form re-syncs every non-empty category — NOT `pipenv uninstall`, which rewrites the Pipfile and re-locks the patch away. The vendored backend emits the twin `pypi_pipenv_stale_install` (`skipped` warning event). **Rollback** (v5.0, upstream restore): each hosted entry gets its registry shape back — `"version": "=="`, the entry's own `index` carried back unchanged (refused unless it — and the Pipfile's explicit `index`, if any — names a PyPI source in `_meta.sources`), and every release file's sha256 from PyPI's JSON API (`SOCKET_PYPI_JSON_API`), sorted by filename as Pipenv records them; an entry that pins another version beside the hosted reference is refused with the `git checkout` remedy (see "Hosted unwind coverage"). A Pipfile names no project, so a same-run `--vex` on a Pipenv project needs `--vex-product` (or a git remote) to detect a product purl. **Discovery**: `Pipfile.lock` is part of the lockfile inventory (every category's `==` pins, with the lock's digest set as `Sha256AnyOf` integrity so a lock-only checkout can be vendored by fetching the pure wheel through PyPI's JSON API — only when `_meta.sources` name the public index; a private-index lock stays discovery-only and never reaches pypi.org), and Socket's own hosted / vendored references stay discoverable as the package they replace, so a re-scan of an already-redirected or already-vendored lock-only checkout re-confirms it (`--vex` attests, vendored reports `already_vendored`) instead of finding nothing. @@ -2430,7 +2430,7 @@ command's integration tests check its output. | `hosted_revert_failed` | top-level error | remove (v5.0): a matched hosted pin could not be restored to its upstream registry entry (`--offline`, a registry that does not answer, `bun.lockb`, a lock shape the restore refuses — see "Hosted unwind coverage"), or writing the restored files failed; the message names the `git checkout -- ` remedy. The manifest was not modified, exit 1. Rollback's counterpart is a `failed` `hosted_restore_refused` event (exit 1). v4's `hosted_revert_unsupported` is no longer emitted (every ecosystem has a restore). | | `pypi_installed_patch_kept` | `scan --prune`/`--sync` top-level `warnings[]` (human: `GC: …`) | a PyPI manifest entry the crawl does not report was NOT pruned because an installed copy still carries the agent-mode patch: a package a project with no environment of its own stopped declaring, or a copy in another interpreter or a tool's environment that an earlier release's project scan patched. The record holds the only blobs that can restore it. The detail names the purl and `socket-patch rollback ` (with `--global` when the copy is outside the interpreter the project installs into), which restores the copy and drops the entry. Never affects the exit. | | `cargo_cache_patch_kept` | `scan --prune`/`--sync` top-level `warnings[]` (human: `GC: …`) | a Cargo manifest entry the crawl no longer reports (the lock bumped or dropped the crate) was NOT pruned because its copy in the shared `$CARGO_HOME/registry/src` cache still carries the agent-mode patch; the record holds the only blobs that can restore it. The detail names the purl and `socket-patch rollback ` (with `--global` when a `cargo vendor` dir hides the registry cache from the project crawl), which restores the copy and drops the entry. Never affects the exit. | -| `reinstall_required` | rollback `warnings[]` | rollback (v5.0): vendored/hosted wiring was unwound, but installed trees keep their patched bytes until the next package-manager install — the stale-install advisory. When the run also emits a Bun advisory (`vendor_bun_reinstall_required` / `redirect_bun_reinstall_required`) the detail and the human note add " (Bun: a plain `bun install` keeps them; run `bun install --force`)". When it emits a PyPI advisory (`vendor_pypi_reinstall_required` / `redirect_pypi_reinstall_required`) they add " (pip, PDM, uv and Pipenv keep a same-version install through a plain install or sync: run the reinstall the pypi_reinstall_required warning names)". When it emits `upstream_gem_stale_install` (a gem left on its patched build) they add " (Bundler: `bundle install` keeps an installed gem; see the gem warning for what to run)". | +| `reinstall_required` | rollback `warnings[]` | rollback (v5.0): vendored/hosted wiring was unwound, but installed trees keep their patched bytes until the next package-manager install — the stale-install advisory. Emitted when the human run prints its "keep their patched bytes" note: at least one unwired package is not also restored in place (or found original there), and is not a gem whose installed copies the unwind refreshed or found to be the upstream build. When the run also emits a Bun advisory (`vendor_bun_reinstall_required` / `redirect_bun_reinstall_required`) the detail and the human note add " (Bun: a plain `bun install` keeps them; run `bun install --force`)". When it emits a PyPI advisory (`vendor_pypi_reinstall_required` / `redirect_pypi_reinstall_required`) they add " (pip, PDM, uv and Pipenv keep a same-version install through a plain install or sync: run the reinstall the pypi_reinstall_required warning names)". When it emits `upstream_gem_stale_install` (a gem left on its patched build) they add " (Bundler: `bundle install` keeps an installed gem; see the gem warning for what to run)". | | `hosted_state_not_preservable` | rollback / remove `warnings[]` | rollback `--preserve-state` (v5.0): hosted pins were restored to upstream anyway — the lockfile pins are hosted mode's only record, so there is no local state to preserve; re-run `scan --mode hosted` to re-wire. (`remove --preserve-state` reports the same code in its `warnings[]` — manifest-backed and hosted-only alike — and prints it as a `Note:` on stderr in human mode.) | | `out_of_scope_copies_restored` | rollback `warnings[]` | path-scoped rollback (v5.0): a selected patch had installed copies outside the given patterns; ALL copies were restored (patches are per-package). Informational — never flips the exit. | | `patched_in_other_scope` | rollback `warnings[]` | the manifest records no scope, so before a rollback drops a record it restored, found already original, or found not installed in its own scope, it checks the other scope (the project at `--cwd` for a `-g` / `--global-prefix` run, the default global install otherwise). A copy there that still holds the patch's afterHash bytes, or has a patched file that exists but cannot be hashed, keeps the record (with its variant group) and its blobs. This warning names the purl, the copy and the rollback of just that purl that restores it (`socket-patch rollback ` or `socket-patch rollback -g`, plus `--cwd` when the run used one). Never flips the exit (#450). | diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index f2e74e3fc..2aa74e510 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -1039,6 +1039,12 @@ pub(crate) struct RestoreRefresh { /// be) with none left on the patched build: nothing of theirs is left /// for a reinstall. pub(crate) refreshed_installs: BTreeSet, + /// The upstream sha256 the refresh verified for each build it judged, + /// by leaf. + upstream_sha256: BTreeMap, + /// A vendored unwind's gems whose installed copies are all proven to + /// be the upstream build ([`upstream_installs`]). + pub(crate) upstream_installs: BTreeSet, } /// After a hosted unwind restored the gems of `pins` to their upstream @@ -1240,6 +1246,7 @@ pub(crate) async fn after_vendored_unwind( common: &GlobalArgs, unwound: &[String], records: &BTreeMap, + ledger: &BTreeMap, ) -> RestoreRefresh { use socket_patch_core::patch::redirect::upstream::gem_upstream; @@ -1250,24 +1257,89 @@ pub(crate) async fn after_vendored_unwind( // lock asks no registry. let lock = gem_upstream(&common.cwd, &BTreeMap::new(), true).await; let builds = build_leaves(&named_builds(&lock, unwound), |_| true); - for copy in installed_builds(common, &builds).await { - if copy.archive.is_file() || holds_patch(©, records).await { - installed.insert(copy.purl); + let copies = installed_builds(common, &builds).await; + for copy in &copies { + if copy.archive.is_file() || holds_patch(copy, records).await { + installed.insert(copy.purl.clone()); } } - if installed.is_empty() { - return RestoreRefresh::default(); + let mut refresh = if installed.is_empty() { + RestoreRefresh::default() + } else { + let installed: Vec = installed.into_iter().collect(); + refresh_restored( + common, + &installed, + &BTreeMap::new(), + records, + None, + Scope::Installed, + ) + .await + }; + refresh.upstream_installs = + upstream_installs(unwound, &copies, &refresh.upstream_sha256, ledger).await; + refresh +} + +/// The gems of `unwound` whose installed copies are proven to hold no +/// patched byte once the refresh ran (#2214): vendoring never wrote to a +/// gem home, so a gem that was only ever vendored is one of them. +/// `copies` is every installed copy of their builds. A gem is listed when +/// it has an installed copy and each one is proven to be the upstream +/// build twice over: the archive RubyGems installed it from hashes to the +/// build's verified upstream sha256 (`upstream`, by leaf), and every file +/// of the gem's ledger record (`ledger`, by purl) is in its pre-patch +/// state there. Anything short of that keeps the gem out: no copy found +/// (the gem home may be one this run cannot see), no verified sha256, an +/// unreadable archive, no record, a file that is patched, edited or +/// unreadable. +async fn upstream_installs( + unwound: &[String], + copies: &[InstalledCopy], + upstream: &BTreeMap, + ledger: &BTreeMap, +) -> BTreeSet { + use socket_patch_core::vendor::file_sha256_hex; + + let mut proven: BTreeMap<&str, bool> = BTreeMap::new(); + for copy in copies { + let is_upstream = match (upstream.get(©.leaf), ledger.get(©.purl)) { + (Some(sha), Some(record)) => { + file_sha256_hex(©.archive).await.as_ref() == Some(sha) + && is_unpatched(©.dir, record).await + } + _ => false, + }; + *proven.entry(copy.purl.as_str()).or_insert(true) &= is_upstream; } - let installed: Vec = installed.into_iter().collect(); - refresh_restored( - common, - &installed, - &BTreeMap::new(), - records, - None, - Scope::Installed, - ) - .await + unwound + .iter() + .filter(|purl| proven.get(purl.as_str()) == Some(&true)) + .cloned() + .collect() +} + +/// Whether every file `record` lists is in its pre-patch state in the +/// installed gem `dir`: it hashes to its `beforeHash`, or the patch adds +/// it and it is not there. A record that lists no file proves nothing. +async fn is_unpatched(dir: &Path, record: &PatchRecord) -> bool { + use socket_patch_core::patch::apply::{verify_file_patch, VerifyStatus}; + + if record.files.is_empty() { + return false; + } + for (name, info) in &record.files { + let verified = verify_file_patch(dir, name, info).await; + // `Ready` also covers a file the patch adds that is there with + // other content (apply overwrites it): only its absence proves + // the copy never got it. + let added_but_present = info.before_hash.is_empty() && verified.current_hash.is_some(); + if verified.status != VerifyStatus::Ready || added_but_present { + return false; + } + } + true } /// The builds of each gem of `gems` that are this project's: the ones the @@ -1440,8 +1512,15 @@ async fn refresh_restored( Scope::Installed, ) .await; + let upstream_sha256: BTreeMap = shas + .iter() + .filter_map(|(leaf, build)| Some((leaf.clone(), build.sha256.clone()?))) + .collect(); if stale.is_empty() && unchecked.is_empty() && no_record.is_empty() { - return RestoreRefresh::default(); + return RestoreRefresh { + upstream_sha256, + ..RestoreRefresh::default() + }; } let wanted = |gem: &StaleGem| { Some(Wanted { @@ -1499,6 +1578,8 @@ async fn refresh_restored( } RestoreRefresh { refreshed_installs, + upstream_sha256, + upstream_installs: BTreeSet::new(), report: report(direction, &installed, &pass, &policy), replaced_archives: if policy.dry_run { Vec::new() @@ -1512,6 +1593,64 @@ async fn refresh_restored( mod tests { use super::*; + /// #2214: what proves an installed gem never got its patch. Each record + /// file is at its `beforeHash`, or the patch adds it and it is absent. + #[tokio::test] + async fn is_unpatched_needs_every_record_file_in_its_pre_patch_state() { + use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes as hash; + use socket_patch_core::manifest::schema::PatchFileInfo; + + let record = |files: &[(&str, &[u8], &[u8])]| PatchRecord { + uuid: "u".into(), + exported_at: String::new(), + files: files + .iter() + .map(|(name, before, after)| { + let info = PatchFileInfo { + before_hash: if before.is_empty() { + String::new() + } else { + hash(before) + }, + after_hash: hash(after), + }; + (name.to_string(), info) + }) + .collect(), + vulnerabilities: Default::default(), + description: String::new(), + license: String::new(), + tier: String::new(), + }; + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + std::fs::write(dir.join("a.rb"), b"before").unwrap(); + let changed = record(&[("a.rb", b"before", b"after")]); + let with_added = record(&[("a.rb", b"before", b"after"), ("new.rb", b"", b"added")]); + + assert!(is_unpatched(dir, &changed).await); + assert!( + is_unpatched(dir, &with_added).await, + "the added file is absent" + ); + assert!(!is_unpatched(dir, &record(&[])).await, "no file, no proof"); + + // The added file is there, with the patch's content or any other. + for leftover in [&b"added"[..], b"something else"] { + std::fs::write(dir.join("new.rb"), leftover).unwrap(); + assert!(!is_unpatched(dir, &with_added).await, "{leftover:?}"); + } + std::fs::remove_file(dir.join("new.rb")).unwrap(); + + // The changed file is patched, edited or gone. + for content in [&b"after"[..], b"edited"] { + std::fs::write(dir.join("a.rb"), content).unwrap(); + assert!(!is_unpatched(dir, &changed).await, "{content:?}"); + } + std::fs::remove_file(dir.join("a.rb")).unwrap(); + assert!(!is_unpatched(dir, &changed).await, "a missing file"); + } + fn policy(root: &Path, enabled: bool, shared: bool, dry_run: bool) -> Policy { Policy { enabled, diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index 2cefed2cc..4529e1138 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -1100,10 +1100,10 @@ struct VendoredLegOutcome { /// could not be saved. failed: Vec<(String, &'static str, String)>, warnings: Vec<(String, String)>, - /// The gems (ledger keys) whose installed copies the unwind brought - /// back to the upstream build: nothing of theirs is left for a - /// reinstall. - refreshed_installs: std::collections::BTreeSet, + /// The gems (ledger keys) with no installed copy left on the patched + /// build, brought back to the upstream one or found to be it already: + /// nothing of theirs is left for a reinstall. + upstream_installs: std::collections::BTreeSet, /// `removed` / `vendor_orphan_removed` events for the orphan uuid /// dirs (no ledger entry) swept, also on dry-run. orphans_removed: Vec, @@ -1136,13 +1136,13 @@ async fn run_vendored_leg( key, warnings, progress, - gem_install_refreshed, + gem_install_upstream, step, .. } in reverted { - if gem_install_refreshed { - out.refreshed_installs.insert(key.clone()); + if gem_install_upstream { + out.upstream_installs.insert(key.clone()); } for w in &warnings { if loud { @@ -2745,9 +2745,6 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { let gc_bytes_freed = gc.map_or(0, |gc| gc.bytes_freed); // ── run-level warnings ─────────────────────────────────────── - let unwired_any = !vendored_leg.reverted.is_empty() - || !vendored_leg.preserved.is_empty() - || !hosted_leg.reverted.is_empty(); let advised = ReinstallAdvised::of( vendored_leg .warnings @@ -2755,7 +2752,33 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { .chain(hosted_leg.warnings.iter()) .map(|(code, _)| code.as_str()), ); - if unwired_any { + // Only packages that are NOT also handled in place keep + // patched bytes. A successful in-place result that verified + // files leaves the installed tree original: restored now, + // restorable (dry run), or already original (never + // patched). None of those has anything left to reinstall. + let restored = handled_in_place(&results); + let base_of = |key: &str| { + vendor_entries + .iter() + .find(|(k, _)| k == key) + .map(|(_, e)| e.base_purl.clone()) + }; + let still_patched = vendored_leg + .reverted + .iter() + .chain(vendored_leg.preserved.iter()) + .chain(hosted_leg.reverted.iter()) + .filter(|key| { + !restored.contains(strip_purl_qualifiers(key)) + && !base_of(key).is_some_and(|b| restored.contains(b.as_str())) + // A gem the unwind brought back to its upstream + // build, or found on it already (#2214). + && !hosted_leg.refreshed_installs.contains(key.as_str()) + && !vendored_leg.upstream_installs.contains(key.as_str()) + }) + .count(); + if still_patched > 0 { run_warnings.push(( "reinstall_required".into(), format!( @@ -3052,32 +3075,6 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { } println!("{}", format_gc_freed(gc_bytes_freed, args.common.dry_run)); } - // Only packages that are NOT also handled in place keep - // patched bytes. A successful in-place result that verified - // files leaves the installed tree original: restored now, - // restorable (dry run), or already original (never - // patched). None of those has anything left to reinstall. - let restored = handled_in_place(&results); - let base_of = |key: &str| { - vendor_entries - .iter() - .find(|(k, _)| k == key) - .map(|(_, e)| e.base_purl.clone()) - }; - let still_patched = vendored_leg - .reverted - .iter() - .chain(vendored_leg.preserved.iter()) - .chain(hosted_leg.reverted.iter()) - .filter(|key| { - !restored.contains(strip_purl_qualifiers(key)) - && !base_of(key).is_some_and(|b| restored.contains(b.as_str())) - // A gem the hosted leg already brought back to - // its upstream build. - && !hosted_leg.refreshed_installs.contains(key.as_str()) - && !vendored_leg.refreshed_installs.contains(key.as_str()) - }) - .count(); if still_patched > 0 { println!( "\n{}", @@ -7084,7 +7081,7 @@ mod tests { "boom".to_string(), )], warnings: Vec::new(), - refreshed_installs: Default::default(), + upstream_installs: Default::default(), orphans_removed: Vec::new(), }; let hosted = HostedLegOutcome { diff --git a/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs b/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs index d454aa0d3..f9242c30a 100644 --- a/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs +++ b/crates/socket-patch-cli/src/commands/vendored_backend/mod.rs @@ -164,6 +164,9 @@ impl<'a> VendoredBackend<'a> { // entry), which the entry takes with it. let mut unwound_gems: Vec<(usize, String)> = Vec::new(); let mut gem_records = std::collections::BTreeMap::new(); + // The ledger's record of every unwound gem that has one, detached + // or not: what proves an installed copy unpatched (#2214). + let mut gem_ledger_records = std::collections::BTreeMap::new(); for key in keys { let Some(entry) = state.entries.get(key).cloned() else { out.push(RevertedEntry { @@ -171,7 +174,7 @@ impl<'a> VendoredBackend<'a> { flavor: None, warnings: Vec::new(), progress: Vec::new(), - gem_install_refreshed: false, + gem_install_upstream: false, step: VendorRevertStep::Missing, }); continue; @@ -231,8 +234,11 @@ impl<'a> VendoredBackend<'a> { .await; if is_gem(&entry.ecosystem) { unwound_gems.push((out.len(), entry.base_purl.clone())); - if let (true, Some(record)) = (entry.detached, &entry.record) { - gem_records.insert(entry.base_purl.clone(), record.clone()); + if let Some(record) = &entry.record { + gem_ledger_records.insert(entry.base_purl.clone(), record.clone()); + if entry.detached { + gem_records.insert(entry.base_purl.clone(), record.clone()); + } } } } @@ -242,14 +248,14 @@ impl<'a> VendoredBackend<'a> { flavor, warnings, progress: Vec::new(), - gem_install_refreshed: false, + gem_install_upstream: false, step, }); if stop_on_failure && hard_failure { break; } } - self.refresh_unwound_gems(&unwound_gems, &gem_records, &mut out) + self.refresh_unwound_gems(&unwound_gems, &gem_records, &gem_ledger_records, &mut out) .await; out } @@ -263,7 +269,9 @@ impl<'a> VendoredBackend<'a> { /// `records` (the record of each unwound gem that the ledger alone /// owned) is the last thing that can tell (#2093). Bring those copies back to the /// upstream gem as the hosted unwind does, and name what is left (the - /// "Gem stale-install guard" section of CLI_CONTRACT.md). + /// "Gem stale-install guard" section of CLI_CONTRACT.md). `ledger` is + /// the ledger's record of every unwound gem that has one: it proves a + /// copy that was never patched to be the upstream build. /// /// `--json` gets a note per refreshed copy and a warning per stale /// one, on the entry of its gem. A human run gets the progress lines on @@ -273,6 +281,7 @@ impl<'a> VendoredBackend<'a> { &self, unwound: &[(usize, String)], records: &std::collections::BTreeMap, + ledger: &std::collections::BTreeMap, out: &mut [RevertedEntry], ) { let Some((first, _)) = unwound.first() else { @@ -282,12 +291,17 @@ impl<'a> VendoredBackend<'a> { let purls: Vec = unwound.iter().map(|(_, purl)| purl.clone()).collect(); let records = self.ended_records(records).await; let records = &records; - let refresh = - crate::commands::gem_refresh::after_vendored_unwind(&self.common, &purls, records) - .await; + let refresh = crate::commands::gem_refresh::after_vendored_unwind( + &self.common, + &purls, + records, + ledger, + ) + .await; for (index, purl) in unwound { - if refresh.refreshed_installs.contains(purl) { - out[*index].gem_install_refreshed = true; + if refresh.refreshed_installs.contains(purl) || refresh.upstream_installs.contains(purl) + { + out[*index].gem_install_upstream = true; } } let report = refresh.report; @@ -425,10 +439,11 @@ pub(crate) struct RevertedEntry { /// Lines a human run prints to stdout after its own line for the /// entry: what the gem refresh replaced in the installed tree. pub(crate) progress: Vec, - /// The gem's installed copies were brought back to the upstream build, - /// with none left on the patched one: nothing of it is left for a - /// reinstall. - pub(crate) gem_install_refreshed: bool, + /// No installed copy of the gem is left on the patched build: the + /// unwind brought them back to the upstream one, or found them to be + /// it already (a gem that was only ever vendored, #2214). Nothing of + /// it is left for a reinstall. + pub(crate) gem_install_upstream: bool, pub(crate) step: VendorRevertStep, } 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 d332644ab..51f6f58c3 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 @@ -4162,6 +4162,11 @@ async fn vendored_unwind_restores_an_install_a_hosted_scan_patched() { && !text.contains("upstream_gem_stale_install"), "{unwind:?}: {env}" ); + // Nothing of the gem is left on its patched build (#2214). + assert!( + details_with_code(&env, "reinstall_required").is_empty(), + "{unwind:?}: {env}" + ); } } @@ -4418,6 +4423,161 @@ async fn vendored_unwind_leaves_an_upstream_install_alone() { } } +/// #2214: rollback's "keeps its patched bytes" note, and the +/// `reinstall_required` warning `--json` carries for it, are about the +/// installed trees. Vendored mode never touches a gem home, so a gem that +/// was only ever vendored has nothing patched there once its pair is +/// restored: its installed copy is the upstream build, which its archive +/// in the gem home and the ledger record's pre-patch hashes prove. +#[tokio::test(flavor = "multi_thread")] +async fn rollback_of_an_only_vendored_gem_names_no_reinstall() { + for json in [true, false] { + let case = format!("json={json}"); + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_upstream_gem(&server, &upstream).await; + mount_vendored_grant(&server, &patched).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let pair_before = ( + std::fs::read(proj.join("Gemfile")).unwrap(), + std::fs::read(proj.join("Gemfile.lock")).unwrap(), + ); + let home = project_home(&proj); + install_real_gem(&home, UPSTREAM_LIB); + let uri = server.uri(); + let (code, stdout, stderr) = unwind_run( + &proj, + &uri, + &["scan", "--mode", "vendored", "--yes", "--json"], + ); + assert_eq!(code, 0, "{case}: vendored scan:\n{stdout}\n{stderr}"); + assert!( + std::fs::read_to_string(proj.join("Gemfile")) + .unwrap() + .contains(".socket/vendor/gem/"), + "{case}: premise: the gem is vendored" + ); + let held_before = snapshot(&home); + + let mut args = vec!["rollback", "--yes"]; + if json { + args.push("--json"); + } + let (code, stdout, stderr) = unwind_run(&proj, &uri, &args); + assert_eq!(code, 0, "{case}:\n{stdout}\n{stderr}"); + let pair_after = ( + std::fs::read(proj.join("Gemfile")).unwrap(), + std::fs::read(proj.join("Gemfile.lock")).unwrap(), + ); + assert!(pair_after == pair_before, "{case}: the pair is restored"); + assert!( + snapshot(&home) == held_before, + "{case}: the gem home is untouched" + ); + if json { + let env = common::parse_json_envelope(&stdout); + assert_eq!(env["status"], "success", "{case}: {env}"); + assert!( + details_with_code(&env, "reinstall_required").is_empty(), + "{case}: no installed tree holds patched bytes: {env}" + ); + } else { + assert!( + stdout.contains(&format!("Reverted vendoring for {PURL}")), + "{case}:\n{stdout}" + ); + assert!( + !stdout.contains("patched bytes in installed trees") + && !stderr.contains("Warning:"), + "{case}: nothing is left to reinstall:\n{stdout}\n{stderr}" + ); + } + } +} + +/// The other side of #2214: an installed copy the unwind could not prove +/// to be the upstream build is still counted. Here agent mode patched the +/// copy before the gem was vendored, and the gem comes from a remote the +/// unwind does not judge, so the patched files stay. +#[tokio::test(flavor = "multi_thread")] +async fn rollback_still_names_a_reinstall_for_an_install_it_could_not_judge() { + for json in [true, false] { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, _) = + agent_then_vendored_from(&server, &proj, "https://gems.example.test").await; + + let mut args = vec!["rollback", "--yes"]; + if json { + args.push("--json"); + } + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + assert_eq!(code, 0, "json={json}:\n{stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "json={json}: premise"); + if json { + let env = common::parse_json_envelope(&stdout); + assert_eq!( + details_with_code(&env, "reinstall_required").len(), + 1, + "{env}" + ); + } else { + assert!( + stdout.contains("1 unwired package keeps its patched bytes in installed trees"), + "{stdout}\n{stderr}" + ); + } + } +} + +/// #2214, a copy the gem home's archive alone would call upstream: agent +/// mode patched it in place, beside the upstream archive, and standalone +/// `vendor` then vendored the gem from the manifest. Rollback may only +/// drop its reinstall warning when the installed copy no longer holds the +/// patched file. +#[tokio::test(flavor = "multi_thread")] +async fn rollback_never_calls_an_agent_patched_install_upstream() { + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_upstream_gem(&server, &upstream).await; + mount_vendored_grant(&server, &patched).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = project_home(&proj); + let gem_dir = agent_patched_install(&proj, &home); + let uri = server.uri(); + let (code, stdout, stderr) = unwind_run(&proj, &uri, &["vendor", "--yes", "--json"]); + assert_eq!(code, 0, "vendor:\n{stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise"); + assert_eq!( + std::fs::read(home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem"))).unwrap(), + upstream, + "premise: the archive beside it is the upstream one" + ); + + let (code, stdout, stderr) = unwind_run(&proj, &uri, &["rollback", "--yes", "--json"]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!( + installed_lib(&gem_dir), + PATCHED_LIB, + "premise: this rollback leaves the installed copy patched: {env}" + ); + assert_eq!( + details_with_code(&env, "reinstall_required").len(), + 1, + "the copy is left patched, so the warning stays: {env}" + ); +} + /// A project whose gem agent mode patched in place and a vendored scan /// then took over: the takeover moved the manifest record into the vendor /// ledger and left the installed copy (patched files, upstream archive in diff --git a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs index 4a143fdfe..3fc8862a8 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -1559,6 +1559,58 @@ async fn gem_get_uuid_vendored_fresh_checkout_bundle_install() { }) }); }); + + // ROLLBACK (#2214): the gem was only ever vendored, so Bundler's own + // install in `vendor/bundle` is still the upstream build. Once the + // pair is restored no patched byte is left anywhere, and rollback + // must not name a reinstall. + let (code, stdout, stderr) = run_socket( + &proj, + &[ + "rollback", + "--yes", + "--json", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + &api_url, + "--org", + ORG, + "--api-token", + "fake", + ], + ); + assert_eq!( + code, 0, + "rollback failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env = parse_json_envelope(&stdout); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!( + std::fs::read(&gemfile_path).unwrap(), + gemfile_before, + "rollback must restore the Gemfile byte for byte" + ); + assert_eq!( + std::fs::read(&lock_path).unwrap(), + lock_before, + "rollback must restore Gemfile.lock byte for byte" + ); + assert_eq!( + std::fs::read(&installed_rb).unwrap(), + orig, + "the installed gem was upstream all along" + ); + let reinstall: Vec<&serde_json::Value> = env["warnings"] + .as_array() + .into_iter() + .flatten() + .filter(|w| w["code"] == "reinstall_required") + .collect(); + assert!( + reinstall.is_empty(), + "nothing is left to reinstall after an only-vendored gem's rollback: {env}" + ); } /// A real `rack ~> 3.1` project installed into `vendor/bundle`, with a diff --git a/docs/ecosystems.md b/docs/ecosystems.md index ab1b93d10..46b480943 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -3055,7 +3055,11 @@ platform gem of the build that is installed). The same holds for a gem that agen before `scan --mode vendored` (or `get --mode vendored`) took it over: the unwind reinstalls the upstream gem over the patched files in the project's own gem home, and warns about a copy it leaves (a shared gem home, `--no-gem-install-refresh`). A gem that was only ever vendored still -has the upstream build installed, and its unwind changes nothing in the gem home. +has the upstream build installed, and its unwind changes nothing in the gem home. When +`rollback` can prove that (the installed copy's archive in the gem home is the upstream gem +from rubygems.org, and the files the patch changes are unpatched), it does not count the gem in +its "keeps its patched bytes in installed trees" note or its `reinstall_required` warning: +there is nothing to reinstall. Nothing is changed when the patched gem cannot be downloaded or verified: the run still exits 0 and warns (`redirect_gem_stale_install`), naming the files to remove by hand. `--dry-run` only