diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 88ac01447..24283a67b 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1247,7 +1247,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md` | -| gem | gem dir `-/` + gemspec materialized from `specifications/` | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair | +| gem | gem dir `-/` + gemspec materialized from `specifications/` | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock) | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | 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 c17fc7d09..6cc86ed8e 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -994,7 +994,7 @@ fn gem_vendor_transitive_dep_fresh_checkout_and_revert() { let gemfile = std::fs::read_to_string(&gemfile_path).unwrap(); let expected_gemfile = format!( "{}# >>> socket-patch vendor (managed) >>>\ngem \"{DEP}\", \"{version}\", \ - path: \"{copy_rel}\"\n# <<< socket-patch vendor (managed) <<<\n", + path: \"{copy_rel}\", require: false\n# <<< socket-patch vendor (managed) <<<\n", String::from_utf8_lossy(&gemfile_before) ); assert_eq!( @@ -1047,6 +1047,32 @@ fn gem_vendor_transitive_dep_fresh_checkout_and_revert() { "frozen install must leave the committed Gemfile.lock byte-identical" ); + // BOOT PROOF (#2084): `Bundler.require` is what an app runs at boot. It + // loads the declared `rack-test`, and must not load `rack`, which the + // Gemfile did not declare before the managed block: `rack/test` leaves + // `lib/rack.rb` (and with it the probe constant) unloaded, so only an + // auto-require of the block's own declaration defines it. + let boot = bundle( + &fresh, + &[ + "exec", + "ruby", + "-e", + "require \"bundler/setup\"\n\ + Bundler.require(:default)\n\ + abort \"rack-test was not required at boot\" unless defined?(Rack::Test)\n\ + abort \"Bundler.require loaded the vendored transitive gem\" if defined?(Rack::SOCKET_PATCH_VENDOR_E2E)\n\ + abort \"lib/rack.rb loaded at boot\" if $LOADED_FEATURES.grep(%r{/rack\\.rb\\z}).any?", + ], + false, + ); + assert!( + boot.status.success(), + "`Bundler.require` must not load a gem the Gemfile did not declare.\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&boot.stdout), + String::from_utf8_lossy(&boot.stderr), + ); + // `require "rack/test"` proves the direct dep still resolves alongside // the vendored transitive; it does not itself load `lib/rack.rb`, so the // marker is probed through an explicit `require "rack"` in the same VM. diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 73a86229f..abce7f118 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -36,7 +36,8 @@ //! The Gemfile gains `path:` on the gem's declaration (rewritten in place when //! it is a statically-parseable single top-level line, quote style and //! trailing options like `require: false` preserved) or, for a transitive -//! dependency, a managed block appended at EOF. Anything +//! dependency, a managed block appended at EOF whose declaration is +//! `require: false`, so `Bundler.require` does not start loading the gem. Anything //! the conservative line grammar cannot prove safe to rewrite is REFUSED — //! never guessed at. The one exception is OUR OWN previous wiring: a patch //! update moves the manifest to a new uuid (same purl), and a `path:` that @@ -112,6 +113,12 @@ const LOCK_CHECKSUM_WIRING_KIND: &str = "gemfile_lock_checksum"; /// Managed-block fence for transitive (not-Gemfile-declared) gems. const MANAGED_OPEN: &str = "# >>> socket-patch vendor (managed) >>>"; const MANAGED_CLOSE: &str = "# <<< socket-patch vendor (managed) <<<"; +/// The option that ends the managed block's declaration. The block declares +/// a gem the Gemfile did not, and `Bundler.require` loads every declared +/// gem of the groups it is given unless the declaration says +/// `require: false` (#2084). Hosted mode writes the same option on the line +/// it adds for such a gem. +const REQUIRE_FALSE: &str = ", require: false"; /// Everything [`vendor_gem`] decides before it can first ask the patch /// service, up to its dry-run branch: the coordinate guards, the no-op of an @@ -1381,11 +1388,13 @@ fn plan_gemfile_edit( )); } // The block takes the file's line endings: an LF block in a CRLF - // Gemfile leaves it mixed (#1821). + // Gemfile leaves it mixed (#1821). Its declaration is one the + // Gemfile did not have, so it is `require: false`: without the + // option `Bundler.require` starts loading the gem at boot (#2084). let nl = line_endings::terminator(text); return Ok(GemfilePlan::Append { block: format!( - "{MANAGED_OPEN}{nl}gem \"{name}\", \"{version}\", path: \"{rel}\"{nl}{MANAGED_CLOSE}{nl}" + "{MANAGED_OPEN}{nl}gem \"{name}\", \"{version}\", path: \"{rel}\"{REQUIRE_FALSE}{nl}{MANAGED_CLOSE}{nl}" ), }); } @@ -1417,11 +1426,6 @@ fn plan_gemfile_edit( if let Some(prev_rel) = gem_line_path_value(rest) { if is_our_vendor_rel(prev_rel, name, version) { let original_line = lines[idx].to_string(); - // The rel appears exactly once (its charset excludes quotes and - // `#`, and the code before `path:` cannot contain a `/`-bearing - // token); swapping just the value preserves quote style and - // trailing options verbatim. - let new_line = original_line.replacen(prev_rel, rel, 1); // The fence lines are matched and recorded with their own // endings, so the record is the block as it stands in the file. let fence = |i: usize, want: &str| { @@ -1429,9 +1433,30 @@ fn plan_gemfile_edit( .get(i) .is_some_and(|l| l.strip_suffix('\r').unwrap_or(l) == want) }; + let in_block = idx > 0 && fence(idx - 1, MANAGED_OPEN) && fence(idx + 1, MANAGED_CLOSE); + // The rel appears exactly once (its charset excludes quotes and + // `#`, and the code before `path:` cannot contain a `/`-bearing + // token); swapping just the value preserves quote style and + // trailing options verbatim. + let body = original_line.strip_suffix('\r').unwrap_or(&original_line); + let mut new_line = body.replacen(prev_rel, rel, 1); + // A block line that ends at its `path:` value is the one + // releases up to 5.1 appended: it gains the `require: false` + // the block is now written with (#2084). A line with anything + // after that value (an option, a comment, a modifier, a `;`) + // was edited by hand and keeps its bytes: text added behind it + // could land outside the call's arguments. So does a + // declaration outside the block, which the Gemfile had before + // the patch. + let ends_at_path = rest + .strip_suffix(['"', '\'']) + .is_some_and(|code| code.ends_with(prev_rel)); + if in_block && ends_at_path && keywords_after_path(rest).is_empty() { + new_line.push_str(REQUIRE_FALSE); + } + new_line.push_str(cr); let managed_block = - (idx > 0 && fence(idx - 1, MANAGED_OPEN) && fence(idx + 1, MANAGED_CLOSE)) - .then(|| format!("{}\n{new_line}\n{}\n", lines[idx - 1], lines[idx + 1])); + in_block.then(|| format!("{}\n{new_line}\n{}\n", lines[idx - 1], lines[idx + 1])); return Ok(GemfilePlan::RewireOurs { original_line, new_line, @@ -3734,7 +3759,7 @@ mod tests { assert_eq!( gemfile, format!( - "source \"https://rubygems.org\"\n\ngem \"puma\"\n{MANAGED_OPEN}\ngem \"rack\", \"3.2.6\", path: \"{}\"\n{MANAGED_CLOSE}\n", + "source \"https://rubygems.org\"\n\ngem \"puma\"\n{MANAGED_OPEN}\ngem \"rack\", \"3.2.6\", path: \"{}\", require: false\n{MANAGED_CLOSE}\n", copy_rel() ) ); @@ -4508,7 +4533,7 @@ mod tests { GEMFILE_TRANSITIVE, LOCK_TRANSITIVE, format!( - "{MANAGED_OPEN}\r\ngem \"rack\", \"3.2.6\", path: \"{}\"\r\n{MANAGED_CLOSE}\r\n", + "{MANAGED_OPEN}\r\ngem \"rack\", \"3.2.6\", path: \"{}\", require: false\r\n{MANAGED_CLOSE}\r\n", copy_rel() ), ), @@ -4576,7 +4601,7 @@ mod tests { assert!(r2.success, "{:?}", r2.error); let new_block = format!( - "{MANAGED_OPEN}\r\ngem \"rack\", \"3.2.6\", path: \".socket/vendor/gem/{UUID2}/rack-3.2.6\"\r\n{MANAGED_CLOSE}\r\n" + "{MANAGED_OPEN}\r\ngem \"rack\", \"3.2.6\", path: \".socket/vendor/gem/{UUID2}/rack-3.2.6\", require: false\r\n{MANAGED_CLOSE}\r\n" ); assert_eq!( tokio::fs::read_to_string(root.join(GEMFILE)).await.unwrap(), @@ -5696,7 +5721,7 @@ mod tests { let new_rel = format!(".socket/vendor/gem/{UUID2}/rack-3.2.6"); let new_block = format!( - "{MANAGED_OPEN}\ngem \"rack\", \"3.2.6\", path: \"{new_rel}\"\n{MANAGED_CLOSE}\n" + "{MANAGED_OPEN}\ngem \"rack\", \"3.2.6\", path: \"{new_rel}\", require: false\n{MANAGED_CLOSE}\n" ); assert_eq!( tokio::fs::read_to_string(root.join(GEMFILE)).await.unwrap(), @@ -5735,6 +5760,188 @@ mod tests { ); } + /// The managed block as releases up to 5.1 wrote it, without + /// `require: false` (#2084): what a project vendored by one of them + /// carries in its Gemfile and its ledger. + fn block_without_require(nl: &str) -> String { + format!( + "{MANAGED_OPEN}{nl}gem \"rack\", \"3.2.6\", path: \"{}\"{nl}{MANAGED_CLOSE}{nl}", + copy_rel() + ) + } + + /// Vendor the transitive fixture, then put the Gemfile and the ledger + /// record in the state an older release left: the block without + /// `require: false`. + async fn vendored_by_an_older_release( + nl: &str, + ) -> ( + tempfile::TempDir, + PathBuf, + PathBuf, + PathBuf, + PatchRecord, + VendorEntry, + String, + ) { + let gemfile = GEMFILE_TRANSITIVE.replace('\n', nl); + let (tmp, root, installed, blobs, record) = fixture(&gemfile, LOCK_TRANSITIVE).await; + let (r1, e1, _) = unwrap_done(run_vendor(&root, &blobs, &installed, &record, false).await); + assert!(r1.success, "{:?}", r1.error); + let mut entry = e1.unwrap(); + let old_block = block_without_require(nl); + tokio::fs::write(root.join(GEMFILE), format!("{gemfile}{old_block}")) + .await + .unwrap(); + entry.wiring[0].new = Some(Value::String(old_block)); + (tmp, root, installed, blobs, record, entry, gemfile) + } + + /// #2084: the declaration the managed block adds is one `Bundler.require` + /// must not load at boot, since the gem was not in the Gemfile before. + #[test] + fn appended_block_declares_the_gem_require_false() { + for nl in ["\n", "\r\n"] { + let text = GEMFILE_TRANSITIVE.replace('\n', nl); + let rel = copy_rel(); + let Ok(GemfilePlan::Append { block }) = plan_gemfile_edit(&text, "rack", "3.2.6", &rel) + else { + panic!("a gem the Gemfile does not declare is appended"); + }; + assert_eq!( + block, + format!( + "{MANAGED_OPEN}{nl}gem \"rack\", \"3.2.6\", path: \"{rel}\", require: false{nl}{MANAGED_CLOSE}{nl}" + ) + ); + } + } + + /// #2084: a block an older release wrote gains `require: false` when a + /// patch update re-vendors the gem, and the record holds the block as + /// written, so the revert still deletes it. + #[tokio::test] + async fn revendor_adds_require_false_to_an_older_block() { + for nl in ["\n", "\r\n"] { + let (_tmp, root, installed, blobs, record, entry1, gemfile) = + vendored_by_an_older_release(nl).await; + let mut record2 = record.clone(); + record2.uuid = UUID2.to_string(); + let (r2, e2, _) = + unwrap_done(run_vendor(&root, &blobs, &installed, &record2, false).await); + assert!(r2.success, "{:?}", r2.error); + + let new_block = format!( + "{MANAGED_OPEN}{nl}gem \"rack\", \"3.2.6\", path: \".socket/vendor/gem/{UUID2}/rack-3.2.6\", require: false{nl}{MANAGED_CLOSE}{nl}" + ); + assert_eq!( + tokio::fs::read_to_string(root.join(GEMFILE)).await.unwrap(), + format!("{gemfile}{new_block}"), + "{nl:?}" + ); + let mut entry2 = e2.unwrap(); + assert_eq!(entry2.wiring[0].action, WiringAction::Added); + assert_eq!( + entry2.wiring[0].new.as_ref().unwrap(), + &Value::String(new_block) + ); + + carry_forward_originals(&entry1, &mut entry2); + let outcome = revert_gem(&entry2, &root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert_eq!( + tokio::fs::read_to_string(root.join(GEMFILE)).await.unwrap(), + gemfile + ); + } + } + + /// #2084: the revert still takes a block an older release wrote and + /// recorded, the one without `require: false`. + #[tokio::test] + async fn revert_removes_an_older_block_without_require_false() { + for nl in ["\n", "\r\n"] { + let (_tmp, root, _installed, _blobs, _record, entry, gemfile) = + vendored_by_an_older_release(nl).await; + let outcome = revert_gem(&entry, &root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(outcome.warnings.is_empty(), "{:?}", outcome.warnings); + assert_eq!( + tokio::fs::read_to_string(root.join(GEMFILE)).await.unwrap(), + gemfile + ); + assert_eq!( + tokio::fs::read_to_string(root.join(GEMFILE_LOCK)) + .await + .unwrap(), + LOCK_TRANSITIVE + ); + } + } + + /// A managed-block line someone gave options or a comment is theirs: a + /// re-vendor repoints its `path:` and changes nothing else on it. + #[test] + fn revendor_keeps_an_edited_block_line_as_it_is() { + let new_rel = format!(".socket/vendor/gem/{UUID2}/rack-3.2.6"); + for tail in [ + ", require: \"rack/lite\"", + ", require: false", + ", group: :web", + " # pinned", + " if ENV[\"CI\"]", + " unless ENV[\"CI\"]", + " rescue nil", + ";", + "; gem \"foo\"", + " ", + ] { + let line = |rel: &str| format!("gem \"rack\", \"3.2.6\", path: \"{rel}\"{tail}"); + let text = format!( + "{GEMFILE_TRANSITIVE}{MANAGED_OPEN}\n{}\n{MANAGED_CLOSE}\n", + line(©_rel()) + ); + let Ok(GemfilePlan::RewireOurs { + new_line, + managed_block, + .. + }) = plan_gemfile_edit(&text, "rack", "3.2.6", &new_rel) + else { + panic!("our own block is rewired: {tail}"); + }; + assert_eq!(new_line, line(&new_rel), "{tail}"); + assert_eq!( + managed_block.unwrap(), + format!("{MANAGED_OPEN}\n{}\n{MANAGED_CLOSE}\n", line(&new_rel)) + ); + } + } + + /// A top-level declaration we rewired (not in the managed fence) was in + /// the Gemfile before the patch: a re-vendor never gives it + /// `require: false`. + #[test] + fn revendor_never_adds_require_false_outside_the_block() { + let new_rel = format!(".socket/vendor/gem/{UUID2}/rack-3.2.6"); + let text = format!( + "{GEMFILE_TRANSITIVE}gem \"rack\", \"3.2.6\", path: \"{}\"\n", + copy_rel() + ); + let Ok(GemfilePlan::RewireOurs { + new_line, + managed_block, + .. + }) = plan_gemfile_edit(&text, "rack", "3.2.6", &new_rel) + else { + panic!("our own declaration is rewired"); + }; + assert_eq!( + new_line, + format!("gem \"rack\", \"3.2.6\", path: \"{new_rel}\"") + ); + assert!(managed_block.is_none()); + } + /// A re-vendor must RE-SORT: the replacement PATH section lands wherever /// the NEW uuid sorts among the other vendored gems' sections, not where /// the old one sat. @@ -8842,7 +9049,7 @@ mod tests { assert_eq!( tokio::fs::read_to_string(root.join(GEMFILE)).await.unwrap(), format!( - "source \"https://rubygems.org\"\n\ngem \"puma\"\n{MANAGED_OPEN}\ngem \"rack\", \"3.2.6\", path: \"{}\"\n{MANAGED_CLOSE}\n", + "source \"https://rubygems.org\"\n\ngem \"puma\"\n{MANAGED_OPEN}\ngem \"rack\", \"3.2.6\", path: \"{}\", require: false\n{MANAGED_CLOSE}\n", copy_rel() ), "a newline is inserted before the block — never line concatenation"