From 1d75c8af6fa5c4269148f19a1088fa3126412e22 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Thu, 3 Dec 2026 20:06:31 -0500 Subject: [PATCH 1/3] Attest a hosted platform-locked gem by each build's own patch in `vex` A hosted move of a gem Bundler locks as platform builds was followed by a standalone `vex` that attested nothing: the document was empty and the command exited 1. Three causes, each fixed here. The patch of a locked build was looked up by the purl its package reference states. The patch service states the gem alone there (`pkg:gem/nokogiri@1.18.9`), without the `platform` qualifier, for every gem patch, so no patch matched a locked platform build. The lookup now takes a patch's platform from the patch search, which lists each patch under its own purl, and reads the reference's purl only for a patch the search does not list. For the same reason a hosted `scan` / `get` reported a platform build's event under the gem's bare purl. The event keeps the build's own purl when the reference names the gem alone. Each hosted build's record was checked against every installed copy of the gem version. The patches of one fix have bytes of their own per build, so on a lock naming more than one build (`nokogiri (1.18.9)` beside `nokogiri (1.18.9-x86_64-linux-gnu)`) the installed copy failed the check of every build but its own. A hosted gem build is now judged by the copies of its own build, as the record check already did. A build this machine does not install is attested from the lock's pin, but not while an installed build of the same gem fails its own patch's check. The capstone fixtures now serve references in both shapes, and a patch per build with its own bytes. One new arm names the ruby gem's patch `?platform=ruby` in the search, its view and its reference. Released 5.2.0 keeps failing on such a lock until the reference states the build's own purl, which needs a matching change in Socket's backend. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- crates/socket-patch-cli/src/commands/vex.rs | 130 +++++++++- .../tests/e2e_redirect_gem_build.rs | 176 +++++++++++--- crates/socket-patch-core/src/hosted/engine.rs | 64 ++++- .../socket-patch-core/src/hosted/gem_fixes.rs | 229 ++++++++++++++++-- docs/ecosystems.md | 8 +- 6 files changed, 546 insertions(+), 63 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index a14c8e681..205d58258 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -546,7 +546,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm **Non-UTF-8 candidate files (#721)**: the rewriters edit UTF-8 text only. A candidate file that exists but is not UTF-8 (for example a UTF-16 `requirements.txt`, which is what Windows PowerShell 5.1's `pip freeze >` writes and which pip installs from) is never read as absent. When a candidate of its ecosystem could rewrite it, the run is refused with `candidate_file_unreadable` (exit 1, `--dry-run` included), the message names the file, and nothing is written; the remedy is to re-save the file as UTF-8. Two exceptions keep their own refusals. A Gradle build file the Gradle planner reaches gets that planner's per-build refusal (`redirect_gradle_build_file_unreadable`, exit 0) and the rest of the run goes ahead, and with no readable Gradle build a stray Gradle file (a lock, a nested script) is never rewritten, so it does not refuse the run, while a non-UTF-8 root `settings.gradle(.kts)` or `build.gradle(.kts)` still refuses it (it may be the build itself). An unreadable `socket-patch.sbt` is refused with `redirect_sbt_owned_file_unreadable`. A vendored→hosted takeover checks this before it reverts anything, so a refused run leaves the vendored wiring, ledger entry and artifact byte-identical. Vendored mode likewise refuses a non-UTF-8 `requirements.txt` or `-r` include by name (`pypi_no_requirements`) instead of wiring around it. Lock-only discovery reads `requirements.txt` and its in-root `-r` includes the way pip decodes them (a UTF-16 or UTF-32 byte-order mark selects that encoding), so such a project's pins are still found instead of reporting "No packages found". -**Gem hosted wiring**: for a gem the manifest (`Gemfile` / `gems.rb`) declares, hosted mode appends ONE option to the user's own declaration, `, source: ""`, after its last argument, and changes nothing else of it: version requirement(s), quote style, other options, trailing comment, position, enclosing `group` / `platforms` / `install_if` block and indentation stay byte for byte. This covers a parenthesized call (the option goes inside the parentheses), a declaration continued over several lines (after the last argument, on its line), several version requirements, `%w` / symbol option values, a trailing `if` / `unless` / `while` / `until` / `rescue` modifier (the option goes before the modifier) and a declaration followed by another statement after a `;`. For a gem the manifest does not declare (a transitive dependency: the lock's `DEPENDENCIES` does not list it) hosted mode adds exactly one line at the end of the manifest, `gem "", "", source: "", require: false # added by socket-patch (transitive dependency)`, after one blank line, in the file's own line ending and keeping whether the file ends on one. `require: false` keeps `Bundler.require` from loading a gem it did not load before the line existed; the marker comment is what tells the unwind the whole line is socket-patch's. **The lock always follows** (the pair is what the Bundler that wrote the lock writes for that manifest, so frozen / deployment installs accept it as committed): on a lock written by Bundler ≥ 2.2 the gem's spec moves to a `GEM` section of its own whose `remote:` is the index URL (sections ordered as Bundler orders them); on a lock written by Bundler 1.17–2.1 the index URL joins the `remote:` lines of the one merged `GEM` section, in the order Bundler derives from the manifest's sources; the `DEPENDENCIES` entry keeps the requirement the manifest declares and gains `!` (a transitive gem gets ` (= )!`); and where the lock has a `CHECKSUMS` section the gem's entry is set to the patched artifact's sha256. A lock with no `CHECKSUMS` section (Bundler < 2.6) is converged the same way and pins the gem by source alone; the run reports that ONCE, naming the gems, as `redirect_gem_no_checksums_section`. **Precompiled platform gems**: a gem Bundler locks as platform builds has one lock entry per platform (`nokogiri (1.18.10-arm64-darwin)`, `nokogiri (1.18.10-x86_64-linux-gnu)`) and usually no ruby-platform `nokogiri (1.18.10)`. A fix for such a gem is one patch per gem: the patch of the ruby gem (the fix's **source patch**) and one patch per platform gem that was built from it, each with its own uuid, its own record under the gem's purl with a `platform` qualifier (`pkg:gem/nokogiri@1.18.10?platform=arm64-darwin`; the ruby gem's is `?platform=ruby`) and a package reference like any gem patch's (a `tarball`, a `registryOverride` with its own index URL and `identifiers.gemChecksumSha256`). A platform patch's reference names its source in `rebuiltFromUuid` (absent or null on a source patch); the fix a patch belongs to is `rebuiltFromUuid ?? uuid`. A platform gem's patch is the upstream platform gem's name, gemspec and file list with the fix's files replaced, and the registry of any patch of a fix lists and serves every gem of that fix. The scan takes one patch per build the lock names, by the build's qualified purl, and all of them from ONE fix (the one the project is already on unless the first-ranked fix supersedes it, else the fix the ruby gem's selection ranks first, else the first that covers every locked build); patches of platforms the lock does not name are not selected. When EVERY entry of the gem at the patched version has a usable patch of that fix, the gem is wired like any other: the manifest edit is the same, with the index URL of the **source patch's** registry (the same URL whichever platforms the lock names, so adding a platform never changes the manifest line; when the lock has no ruby-platform entry the source patch's reference is asked for too, and that patch is reported in no event). Which registry is the anchor, in order: the one the lock already takes the gem from, when it is the source patch's or that of a build the lock still names (a pair that works is never rewritten for another URL of the same fix); the source patch's, where the run has it; and where the source patch is not available to the run (not offered to the organisation, not granted), the registry of the first locked build's own patch, platforms in the lock's sorted order. That last choice moves the gem all the same and adds the warning `redirect_gem_member_registry`: ``Gemfile.lock takes from the patch registry of its `` gem's patch (): the patch its builds were built from () is not available to this run, and every patch registry of a fix serves every build of it. The `source:` in Gemfile names that registry, so the line changes if `` leaves Gemfile.lock``. A gem moved that way stays on that registry once the source patch turns up (no rewrite, no warning), and is re-anchored by the same order when that platform leaves the lock, every entry of that version (each spec line with its dependency sub-lines, verbatim and in the lock's order, plus a ruby-platform entry when one sits beside them) moves to that registry's `GEM` section, `DEPENDENCIES` is pinned the same way, and each `CHECKSUMS` entry of the gem is set to the sha256 its own patch's reference states; a lock with no `CHECKSUMS` section gets none. Before anything is written the run reads `/info/` of that registry (one request per platform-locked gem) and requires it to list every locked build with the sha256 about to be pinned. A frozen `bundle install` of that pair fetches the one platform gem of the machine from the patch registry, compiles nothing and leaves the lock byte-identical (verified on Bundler 4.0.15), and `bundle lock --add-platform ` on that pair adds the new platform's patched gem from the same registry without touching the manifest. Each locked build is reported under its own patch: one `applied` event per build (`purl` with its `platform` qualifier, `uuid` of that build's patch, each counted in `summary.applied`), those uuids in the package's `selectedUuids` (beside the source patch's), and each build attested by its own patch uuid in the run's `--vex` (a later standalone `vex` reads the lock, which holds the one registry, and names the patch that registry belongs to); the human summary counts the gem as one package. A patch of the gem that the lock has no entry for (another platform's, or the ruby gem's where the lock has no ruby-platform entry) has nothing to pin and gets no event. The gem is skipped with `redirect_gem_platform_unsupported`, with neither file changed, when a locked build has no usable patch (none on offer, a reference that is `pending_build`, `withdrawn` or otherwise not granted: that patch gets its own `skipped` event with the reference's status), when its builds are patched only by different fixes, when the registry does not list what the lock would pin or could not be read, or for a platform build in the merged layout of Bundler < 2.2; the detail names the builds the lock holds and which case it is, and for a lock that already takes the gem from a patch registry it adds the way back (`socket-patch rollback pkg:gem/@`). A reference that still carries the retired `gemPlatforms` list or `gem-platform` artifacts is read as the ruby gem's patch alone. `get --mode hosted|vendored` for one patch of a platform-locked gem selects the whole fix: that patch plus the fix's patch of every other locked build and its source patch (one search and one reference request). A lock does not record which Bundler installs it, only which one wrote it (`BUNDLED WITH`), so the pair is converged for that one; when it is the merged layout of Bundler < 2.2, which later Bundlers deprecate and from 2.5 on refuse under frozen / deployment mode, the run that writes the lock adds `redirect_gem_merged_lock_layout` naming the Bundler the pair is for. A rollout that defers a build of such a gem (`--max-new-patches`) defers the fix whole, its source patch included: nothing of it is written and no platform warning is given. **Never a half-applied pair**: each gem is planned on a copy of the pair and committed only when the planned manifest and lock agree about it (the manifest gives it the index URL as its one source; the lock resolves it from a `GEM` section naming that remote, with a source-pinned `DEPENDENCIES` entry). A gem whose declaration cannot take the option, or whose lock cannot follow, is refused with neither file changed for it, and the warning's detail gives the reason and the way out: `redirect_gem_unrecognized_declaration` (the declaration cannot be edited in place — a heredoc or `do` block among its arguments, code before it on its line, a string spanning lines, a last argument that is not a literal and may be an options hash: it is taken for a version requirement only when the lock shows one requirement per positional argument, every other positional is a single quoted string, and the manifest has no `gemspec` directive, whose own requirement for the gem bundler folds into the lock entry, …), `redirect_gem_source_option` (it already selects a source: a `source:` / `git:` / `github:` / `path:` option or one a `**opts` splat may hold, a declaration inside a `source` / `git` / `github` / `path` block, a `DEPENDENCIES` entry that is already source-pinned, or a lock that resolves the gem from a `GIT` / `PATH` section), `redirect_gem_declared_more_than_once`, `redirect_gem_declaration_not_visible` (a direct dependency declared in an `eval_gemfile`d file, a loop or a gemspec; vendored mode refuses it for the same reason, so the way out is a literal `gem` line or `--mode agent`), `redirect_gem_dependency_not_locked` (declared, but the lock's `DEPENDENCIES` does not list it), `redirect_gem_lock_unconvergeable` (no `BUNDLED WITH` section to say which layout the lock's Bundler accepts, a merged Bundler < 2.2 section whose remotes the manifest's sources do not explain, or the one multi-remote `GEM` section Bundler 2.2 to 2.7 write for a manifest with more than one top-level `source` line, where the detail names that cause and the remedy: move each extra source into a `source "" do … end` block, then `bundle lock`), `redirect_gem_platform_unsupported` (a gem locked as platform builds with no one fix that has a usable patch for every locked build, above) and `redirect_gem_inconsistent_plan` (the self-check above failed; a bug guard, never expected). A re-scan recognizes its own option (the grant-token and patch-uuid path levels of the URL rotate, so they are matched as wildcards) and refreshes the URL in place, in the manifest and the lock together; a re-scan of an unchanged project writes nothing. A lock reverted or regenerated without its manifest (the option still there, the lock back on the registry) is converged again by the next hosted scan. **Pins written by socket-patch 5.0 / 5.1** used a `source "" do … end` block in the declaration's place and, on a lock with no `CHECKSUMS` section, left the lock alone. That form is never written any more but stays recognized everywhere (re-scan, `list`, `vex`, `rollback` / `remove`, the takeovers): a re-scan keeps the block as it is, refreshes its URL like the option's, and converges a lock that never followed it; only where that lock cannot be converged does the run still warn `redirect_gem_frozen_install`. Human mode prints one line after the summary naming the declarations changed, e.g. ``Added `source:` to 3 gem declarations in Gemfile (puma, rack, and rexml); added 1 line for the transitive dependency nokogiri.`` **Update hold**: a gem wired this way has the patch registry as its only source, and that source serves the one patched version, so `bundle outdated` no longer lists the gem and `bundle update` cannot move it (a range requirement included) until its pin is rolled back. When a run newly wires at least one gem (an option appended or a line added, not a refreshed URL), human mode prints one more stdout line under that one, naming those gems once each: ``Bundler now takes rack from its Socket patch source only, which serves the patched version and no other: `bundle outdated` no longer lists it and `bundle update` cannot move it. To move it to a newer release, run `socket-patch rollback pkg:gem/rack@3.1.8`, then `bundle update rack`, then `socket-patch scan` again.`` The rollback step always names a purl (the gem's own for one gem, as `rollback` selects its pin: without the patch record's qualifiers such as `?platform=ruby`, so a shell passes it on whole; the shape `pkg:gem/@` for several), never a bare `rollback`, which would unwind every patch; after `get` the last step reads "then patch the new version the same way"; `--dry-run` words the first sentence as what the run would hold and prints no steps. `--json` and `--silent` output are unchanged (no warning code). Pinned against real Bundler by `tests/e2e_redirect_gem_build.rs`. See `docs/ecosystems.md` ("Ruby gems: hosted mode") for the user-facing description. +**Gem hosted wiring**: for a gem the manifest (`Gemfile` / `gems.rb`) declares, hosted mode appends ONE option to the user's own declaration, `, source: ""`, after its last argument, and changes nothing else of it: version requirement(s), quote style, other options, trailing comment, position, enclosing `group` / `platforms` / `install_if` block and indentation stay byte for byte. This covers a parenthesized call (the option goes inside the parentheses), a declaration continued over several lines (after the last argument, on its line), several version requirements, `%w` / symbol option values, a trailing `if` / `unless` / `while` / `until` / `rescue` modifier (the option goes before the modifier) and a declaration followed by another statement after a `;`. For a gem the manifest does not declare (a transitive dependency: the lock's `DEPENDENCIES` does not list it) hosted mode adds exactly one line at the end of the manifest, `gem "", "", source: "", require: false # added by socket-patch (transitive dependency)`, after one blank line, in the file's own line ending and keeping whether the file ends on one. `require: false` keeps `Bundler.require` from loading a gem it did not load before the line existed; the marker comment is what tells the unwind the whole line is socket-patch's. **The lock always follows** (the pair is what the Bundler that wrote the lock writes for that manifest, so frozen / deployment installs accept it as committed): on a lock written by Bundler ≥ 2.2 the gem's spec moves to a `GEM` section of its own whose `remote:` is the index URL (sections ordered as Bundler orders them); on a lock written by Bundler 1.17–2.1 the index URL joins the `remote:` lines of the one merged `GEM` section, in the order Bundler derives from the manifest's sources; the `DEPENDENCIES` entry keeps the requirement the manifest declares and gains `!` (a transitive gem gets ` (= )!`); and where the lock has a `CHECKSUMS` section the gem's entry is set to the patched artifact's sha256. A lock with no `CHECKSUMS` section (Bundler < 2.6) is converged the same way and pins the gem by source alone; the run reports that ONCE, naming the gems, as `redirect_gem_no_checksums_section`. **Precompiled platform gems**: a gem Bundler locks as platform builds has one lock entry per platform (`nokogiri (1.18.10-arm64-darwin)`, `nokogiri (1.18.10-x86_64-linux-gnu)`) and usually no ruby-platform `nokogiri (1.18.10)`. A fix for such a gem is one patch per gem: the patch of the ruby gem (the fix's **source patch**) and one patch per platform gem that was built from it, each with its own uuid, its own record under the gem's purl with a `platform` qualifier (`pkg:gem/nokogiri@1.18.10?platform=arm64-darwin`; the ruby gem's is `?platform=ruby`) and a package reference like any gem patch's (a `tarball`, a `registryOverride` with its own index URL and `identifiers.gemChecksumSha256`). A platform patch's reference names its source in `rebuiltFromUuid` (absent or null on a source patch); the fix a patch belongs to is `rebuiltFromUuid ?? uuid`. A platform gem's patch is the upstream platform gem's name, gemspec and file list with the fix's files replaced, and the registry of any patch of a fix lists and serves every gem of that fix. The scan takes one patch per build the lock names, by the build's qualified purl, and all of them from ONE fix (the one the project is already on unless the first-ranked fix supersedes it, else the fix the ruby gem's selection ranks first, else the first that covers every locked build); patches of platforms the lock does not name are not selected. When EVERY entry of the gem at the patched version has a usable patch of that fix, the gem is wired like any other: the manifest edit is the same, with the index URL of the **source patch's** registry (the same URL whichever platforms the lock names, so adding a platform never changes the manifest line; when the lock has no ruby-platform entry the source patch's reference is asked for too, and that patch is reported in no event). Which registry is the anchor, in order: the one the lock already takes the gem from, when it is the source patch's or that of a build the lock still names (a pair that works is never rewritten for another URL of the same fix); the source patch's, where the run has it; and where the source patch is not available to the run (not offered to the organisation, not granted), the registry of the first locked build's own patch, platforms in the lock's sorted order. That last choice moves the gem all the same and adds the warning `redirect_gem_member_registry`: ``Gemfile.lock takes from the patch registry of its `` gem's patch (): the patch its builds were built from () is not available to this run, and every patch registry of a fix serves every build of it. The `source:` in Gemfile names that registry, so the line changes if `` leaves Gemfile.lock``. A gem moved that way stays on that registry once the source patch turns up (no rewrite, no warning), and is re-anchored by the same order when that platform leaves the lock, every entry of that version (each spec line with its dependency sub-lines, verbatim and in the lock's order, plus a ruby-platform entry when one sits beside them) moves to that registry's `GEM` section, `DEPENDENCIES` is pinned the same way, and each `CHECKSUMS` entry of the gem is set to the sha256 its own patch's reference states; a lock with no `CHECKSUMS` section gets none. Before anything is written the run reads `/info/` of that registry (one request per platform-locked gem) and requires it to list every locked build with the sha256 about to be pinned. A frozen `bundle install` of that pair fetches the one platform gem of the machine from the patch registry, compiles nothing and leaves the lock byte-identical (verified on Bundler 4.0.15), and `bundle lock --add-platform ` on that pair adds the new platform's patched gem from the same registry without touching the manifest. Each locked build is reported under its own patch: one `applied` event per build (`purl` with its `platform` qualifier, `uuid` of that build's patch, each counted in `summary.applied`), those uuids in the package's `selectedUuids` (beside the source patch's), and each build attested by its own patch uuid in the run's `--vex` (a later standalone `vex` attests each locked build by its own patch uuid too: the lock holds the one registry, so it looks the builds' patches up online, by the platform the patch search gives each patch of the fix, the reference's purl only for a patch the search does not list, since a reference may name the gem without its `platform`; the installed copy is verified against its own build's record only, a build this machine does not install is attested from the lock's pin, and no build of the gem is attested from the pin while an installed build fails its record's check); the human summary counts the gem as one package. A patch of the gem that the lock has no entry for (another platform's, or the ruby gem's where the lock has no ruby-platform entry) has nothing to pin and gets no event. The gem is skipped with `redirect_gem_platform_unsupported`, with neither file changed, when a locked build has no usable patch (none on offer, a reference that is `pending_build`, `withdrawn` or otherwise not granted: that patch gets its own `skipped` event with the reference's status), when its builds are patched only by different fixes, when the registry does not list what the lock would pin or could not be read, or for a platform build in the merged layout of Bundler < 2.2; the detail names the builds the lock holds and which case it is, and for a lock that already takes the gem from a patch registry it adds the way back (`socket-patch rollback pkg:gem/@`). A reference that still carries the retired `gemPlatforms` list or `gem-platform` artifacts is read as the ruby gem's patch alone. `get --mode hosted|vendored` for one patch of a platform-locked gem selects the whole fix: that patch plus the fix's patch of every other locked build and its source patch (one search and one reference request). A lock does not record which Bundler installs it, only which one wrote it (`BUNDLED WITH`), so the pair is converged for that one; when it is the merged layout of Bundler < 2.2, which later Bundlers deprecate and from 2.5 on refuse under frozen / deployment mode, the run that writes the lock adds `redirect_gem_merged_lock_layout` naming the Bundler the pair is for. A rollout that defers a build of such a gem (`--max-new-patches`) defers the fix whole, its source patch included: nothing of it is written and no platform warning is given. **Never a half-applied pair**: each gem is planned on a copy of the pair and committed only when the planned manifest and lock agree about it (the manifest gives it the index URL as its one source; the lock resolves it from a `GEM` section naming that remote, with a source-pinned `DEPENDENCIES` entry). A gem whose declaration cannot take the option, or whose lock cannot follow, is refused with neither file changed for it, and the warning's detail gives the reason and the way out: `redirect_gem_unrecognized_declaration` (the declaration cannot be edited in place — a heredoc or `do` block among its arguments, code before it on its line, a string spanning lines, a last argument that is not a literal and may be an options hash: it is taken for a version requirement only when the lock shows one requirement per positional argument, every other positional is a single quoted string, and the manifest has no `gemspec` directive, whose own requirement for the gem bundler folds into the lock entry, …), `redirect_gem_source_option` (it already selects a source: a `source:` / `git:` / `github:` / `path:` option or one a `**opts` splat may hold, a declaration inside a `source` / `git` / `github` / `path` block, a `DEPENDENCIES` entry that is already source-pinned, or a lock that resolves the gem from a `GIT` / `PATH` section), `redirect_gem_declared_more_than_once`, `redirect_gem_declaration_not_visible` (a direct dependency declared in an `eval_gemfile`d file, a loop or a gemspec; vendored mode refuses it for the same reason, so the way out is a literal `gem` line or `--mode agent`), `redirect_gem_dependency_not_locked` (declared, but the lock's `DEPENDENCIES` does not list it), `redirect_gem_lock_unconvergeable` (no `BUNDLED WITH` section to say which layout the lock's Bundler accepts, a merged Bundler < 2.2 section whose remotes the manifest's sources do not explain, or the one multi-remote `GEM` section Bundler 2.2 to 2.7 write for a manifest with more than one top-level `source` line, where the detail names that cause and the remedy: move each extra source into a `source "" do … end` block, then `bundle lock`), `redirect_gem_platform_unsupported` (a gem locked as platform builds with no one fix that has a usable patch for every locked build, above) and `redirect_gem_inconsistent_plan` (the self-check above failed; a bug guard, never expected). A re-scan recognizes its own option (the grant-token and patch-uuid path levels of the URL rotate, so they are matched as wildcards) and refreshes the URL in place, in the manifest and the lock together; a re-scan of an unchanged project writes nothing. A lock reverted or regenerated without its manifest (the option still there, the lock back on the registry) is converged again by the next hosted scan. **Pins written by socket-patch 5.0 / 5.1** used a `source "" do … end` block in the declaration's place and, on a lock with no `CHECKSUMS` section, left the lock alone. That form is never written any more but stays recognized everywhere (re-scan, `list`, `vex`, `rollback` / `remove`, the takeovers): a re-scan keeps the block as it is, refreshes its URL like the option's, and converges a lock that never followed it; only where that lock cannot be converged does the run still warn `redirect_gem_frozen_install`. Human mode prints one line after the summary naming the declarations changed, e.g. ``Added `source:` to 3 gem declarations in Gemfile (puma, rack, and rexml); added 1 line for the transitive dependency nokogiri.`` **Update hold**: a gem wired this way has the patch registry as its only source, and that source serves the one patched version, so `bundle outdated` no longer lists the gem and `bundle update` cannot move it (a range requirement included) until its pin is rolled back. When a run newly wires at least one gem (an option appended or a line added, not a refreshed URL), human mode prints one more stdout line under that one, naming those gems once each: ``Bundler now takes rack from its Socket patch source only, which serves the patched version and no other: `bundle outdated` no longer lists it and `bundle update` cannot move it. To move it to a newer release, run `socket-patch rollback pkg:gem/rack@3.1.8`, then `bundle update rack`, then `socket-patch scan` again.`` The rollback step always names a purl (the gem's own for one gem, as `rollback` selects its pin: without the patch record's qualifiers such as `?platform=ruby`, so a shell passes it on whole; the shape `pkg:gem/@` for several), never a bare `rollback`, which would unwind every patch; after `get` the last step reads "then patch the new version the same way"; `--dry-run` words the first sentence as what the run would hold and prints no steps. `--json` and `--silent` output are unchanged (no warning code). Pinned against real Bundler by `tests/e2e_redirect_gem_build.rs`. See `docs/ecosystems.md` ("Ruby gems: hosted mode") for the user-facing description. **Gem stale-install guard (the canonical narrative; other mentions point here)**: the gem hosted rewrite is pure Gemfile/lock text, and Bundler keeps a gem it already holds whatever source the lock names. So after the rewrite a hosted run looks for the gems the project already has on disk, replaces the project's own stale copies with the patched gem itself, and warns about the rest. The unwind (`rollback`, `remove`, a withdrawn-patch restore) does the same in the other direction. Exit code and `status` never change: a refresh that cannot be done leaves everything as it was and falls back to the warning. diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 6a8f0792d..e8af80d88 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -1024,7 +1024,7 @@ async fn generate_vex( let hosted = crate::commands::vex_consumed::hosted_consumed_copies( common, &plan.hosted, - &copies, + &with_gem_copies_by_build(&copies, &package_paths), params.npm_prior.as_ref(), &mut live_stores, ) @@ -1100,12 +1100,17 @@ async fn generate_vex( let composer_unread = socket_patch_core::crawlers::composer_crawler::local_install_unread(&common.cwd); let unread = |purl: &str| purl.starts_with("pkg:composer/") && composer_unread; + // Nor is the lock's pin evidence for one build of a gem while an + // installed build of the same gem fails its own patch's check: the + // copy this machine runs is then not the patched one. + let gem_build_fails = gems_with_a_failing_build(&outcome.failed); let pin_excuses = |f: &FailedPatch| { f.reason == "package_not_found" && plan.lockfile_basis.contains(&f.purl) && !mirror_refused(&f.purl) && crawled(&f.purl) && !hidden(&f.purl) + && !gem_build_fails.contains(gem_of_build(&f.purl)) }; for f in outcome.failed.iter_mut() { if pin_excuses(f) && unread(&f.purl) { @@ -1776,6 +1781,50 @@ pub(crate) async fn vex_copy_sets( sets } +/// The installed copies a hosted purl is judged by: `copies` (every copy +/// of every purl), with each gem's taken from `by_build`, the sets the +/// record check uses ([`narrow_gem_variant_copies`]). +/// +/// A gem fix has one patch per platform gem, each with bytes of its own, +/// and a lock can name several of them (`nokogiri (1.19.3)` beside +/// `nokogiri (1.19.3-x86_64-linux-gnu)`) where a machine installs one. The +/// installed copy is that one gem's: judged by the patch of another build +/// it matches neither the original nor the patched content. +fn with_gem_copies_by_build( + copies: &HashMap>, + by_build: &HashMap>, +) -> HashMap> { + copies + .iter() + .map(|(purl, paths)| { + let paths = by_build + .get(purl) + .filter(|_| purl.starts_with("pkg:gem/")) + .unwrap_or(paths); + (purl.clone(), paths.clone()) + }) + .collect() +} + +/// The gem a gem patch purl is a build of: the purl without its +/// qualifiers. Any other purl as it is. +fn gem_of_build(purl: &str) -> &str { + match purl.starts_with("pkg:gem/") { + true => socket_patch_core::utils::purl::strip_purl_qualifiers(purl), + false => purl, + } +} + +/// The gems ([`gem_of_build`]) with a build in `failed` that an installed +/// copy failed on: any reason but `package_not_found`. +fn gems_with_a_failing_build(failed: &[FailedPatch]) -> HashSet { + failed + .iter() + .filter(|f| f.purl.starts_with("pkg:gem/") && f.reason != "package_not_found") + .map(|f| gem_of_build(&f.purl).to_string()) + .collect() +} + /// RubyGems: give each qualified variant key (`?platform=`…) only the /// copies holding its distribution. One gem home can hold several builds of /// a version (`x-1.0/` beside `x-1.0-x86_64-linux/`, #1092), each patched @@ -3368,6 +3417,85 @@ mod tests { } } + /// A hosted gem purl is judged by the copies of its own build, every + /// other purl by every copy the crawl found. + #[test] + fn a_hosted_gem_is_judged_by_the_copies_of_its_own_build() { + let ruby = "pkg:gem/nokogiri@1.19.3?platform=ruby".to_string(); + let linux = "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu".to_string(); + let npm = "pkg:npm/left-pad@1.3.0".to_string(); + let copy = PathBuf::from("/gems/nokogiri-1.19.3-x86_64-linux-gnu"); + let node = PathBuf::from("/node_modules/left-pad"); + let copies = HashMap::from([ + (ruby.clone(), vec![copy.clone()]), + (linux.clone(), vec![copy.clone()]), + (npm.clone(), vec![node.clone()]), + ]); + let by_build = HashMap::from([ + (ruby.clone(), Vec::new()), + (linux.clone(), vec![copy.clone()]), + (npm.clone(), Vec::new()), + ]); + let judged = with_gem_copies_by_build(&copies, &by_build); + assert!(judged[&ruby].is_empty(), "no ruby gem is installed"); + assert_eq!(judged[&linux], [copy]); + assert_eq!(judged[&npm], [node], "only a gem's copies are narrowed"); + } + + /// A build of a gem that an installed copy fails on marks the gem; a + /// build that is not installed, and any other ecosystem, marks nothing. + #[test] + fn a_gem_is_marked_by_a_build_an_installed_copy_fails_on() { + let fails = gems_with_a_failing_build(&[ + failed( + "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu", + "not_applied", + ), + failed("pkg:gem/nokogiri@1.19.3?platform=ruby", "package_not_found"), + failed("pkg:gem/rack@3.1.8", "package_not_found"), + failed("pkg:npm/left-pad@1.3.0", "hash_mismatch"), + ]); + assert_eq!( + fails, + HashSet::from(["pkg:gem/nokogiri@1.19.3".to_string()]) + ); + assert!(fails.contains(gem_of_build("pkg:gem/nokogiri@1.19.3?platform=ruby"))); + assert_eq!(gem_of_build("pkg:npm/a@1?x=y"), "pkg:npm/a@1?x=y"); + } + + /// The run holds the ruby build's record alone: the patch of the build + /// this machine installed could not be fetched. The installed copy + /// holds neither the original nor the patched content of the ruby + /// build's record, so it stays on that build's key, where it fails the + /// check. The ruby build is then not "nowhere installed", and the + /// lock's pin does not attest it over a copy no record verified. + #[tokio::test] + async fn an_installed_gem_copy_no_record_matches_stays_on_the_build_that_has_one() { + use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes as hash; + let tmp = tempfile::tempdir().unwrap(); + let copy = tmp.path().join("gems/nokogiri-1.19.3-x86_64-linux-gnu"); + std::fs::create_dir_all(copy.join("lib")).unwrap(); + std::fs::write(copy.join("lib/nokogiri.rb"), b"the platform patch's bytes").unwrap(); + let ruby = "pkg:gem/nokogiri@1.19.3?platform=ruby".to_string(); + let record: socket_patch_core::manifest::schema::PatchRecord = + serde_json::from_value(serde_json::json!({ + "uuid": "00000000-0000-4000-8000-000000000000", + "exportedAt": "2026-01-01T00:00:00Z", + "files": {"lib/nokogiri.rb": { + "beforeHash": hash(b"the original"), + "afterHash": hash(b"the ruby patch's bytes"), + }}, + "vulnerabilities": {}, + "description": "test", "license": "MIT", "tier": "free" + })) + .unwrap(); + let mut manifest = PatchManifest::new(); + manifest.patches.insert(ruby.clone(), record); + let mut sets = HashMap::from([(ruby.clone(), vec![copy.clone()])]); + narrow_gem_variant_copies(&manifest, &mut sets).await; + assert_eq!(sets[&ruby], [copy]); + } + /// The reported flood: a project that has not installed its patched /// packages yet got one line per package. The patches left out are one /// line per reason, largest first, with the count and the first few 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 e70edbc57..422cae145 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -6852,10 +6852,10 @@ fn build_marked(lib: String) -> String { /// Author and `gem build` one build of the fixture gem: the ruby gem, or, /// with `platform`, a platform gem. A platform gem needs no binary: a /// pure-Ruby gem whose gemspec sets `s.platform` is one. Every build -/// carries the same `lib/vuln_gem.rb` (`lib`, the file the patch replaces) -/// and its own `lib/vuln_gem/build.rb`, which says which build Ruby loaded: -/// a real prebuild differs from the ruby gem only outside the patched -/// files, so one patch record's hashes hold for every build. +/// carries `lib/vuln_gem.rb` (`lib`, the file the patch replaces) and its +/// own `lib/vuln_gem/build.rb`, which says which build Ruby loaded. +/// Upstream's builds hold the same `lib`; a patched build holds the one +/// its own patch wrote. fn build_gem_build(stage: &Path, tag: &str, platform: Option<&str>, lib: &str) -> Vec { let build = platform.unwrap_or("ruby"); let dir = stage.join(format!("{DEP}-{tag}-{build}-src")); @@ -6956,6 +6956,7 @@ async fn platform_prebuilds_install_frozen_and_roll_back( checksums_lock: bool, ruby_entry: bool, takeover: bool, + reference_purls: ReferencePurls, ) { // Bundler locks the specific platform's gem from 2.2; `CHECKSUMS` from // 2.6. Vendor takes platform gems from a lock bundler 2.3 or newer wrote. @@ -6974,22 +6975,34 @@ async fn platform_prebuilds_install_frozen_and_roll_back( let tmp = tempfile::tempdir().unwrap(); let stage = tmp.path().join("gem-stage"); let (orig, patched) = (build_marked(orig_lib()), build_marked(patched_lib())); - let builds_of = |tag: &str, lib: &str| -> Vec { + // Each patch of a fix has bytes of its own in the file it patches (the + // patch service writes the patch's own header into it), so the patched + // ruby gem and the patched foreign platform gem differ from this + // machine's patched gem, whose file is `patched`. + let own_token = format!("{DEP_VERSION}-{own}"); + let patched_of = |token: &str| match token == own_token { + true => patched.clone(), + false => format!("{patched}# the patch of {DEP}-{token}\n"), + }; + let builds_of = |tag: &str, lib_of: &dyn Fn(&str) -> String| -> Vec { [None, Some(own.as_str()), Some(foreign.as_str())] .into_iter() - .map(|platform| IndexBuild { - name: DEP, - token: match platform { + .map(|platform| { + let token = match platform { Some(p) => format!("{DEP_VERSION}-{p}"), None => DEP_VERSION.to_string(), - }, - deps: vec![format!("{TRANSITIVE}:>= 0")], - gem: build_gem_build(&stage, tag, platform, lib), + }; + IndexBuild { + name: DEP, + deps: vec![format!("{TRANSITIVE}:>= 0")], + gem: build_gem_build(&stage, tag, platform, &lib_of(&token)), + token, + } }) .collect() }; - let mut upstream_builds = builds_of("orig", &orig); - let patched_builds = builds_of("patched", &patched); + let mut upstream_builds = builds_of("orig", &|_| orig.clone()); + let patched_builds = builds_of("patched", &patched_of); let sha_of = |builds: &[IndexBuild], token: &str| { let build = builds.iter().find(|b| b.token == token).expect("build"); sha256_hex(&build.gem) @@ -7020,9 +7033,10 @@ async fn platform_prebuilds_install_frozen_and_roll_back( &server, &patched_builds, &platforms, - (&orig, &patched), + (&orig, &patched_of), false, 5, + reference_purls, ) .await; @@ -7145,7 +7159,12 @@ async fn platform_prebuilds_install_frozen_and_roll_back( .map(|p| (format!("{PURL}?platform={p}"), platform_uuid(p))) .collect(); if ruby_entry { - expected.push((PURL.to_string(), UUID.to_string())); + // An event names its patch as the patch's reference does. + let ruby = match reference_purls { + ReferencePurls::QualifiedWithRuby => format!("{PURL}?platform=ruby"), + ReferencePurls::Qualified | ReferencePurls::GemOnly => PURL.to_string(), + }; + expected.push((ruby, UUID.to_string())); } expected.sort(); assert_eq!( @@ -7391,9 +7410,10 @@ async fn platform_prebuilds_install_frozen_and_roll_back( &fx._server, &patched_builds, &platforms, - (&orig, &patched), + (&orig, &patched_of), true, 1, + reference_purls, ) .await; // By the fix's source patch on one arm (`get ` takes the @@ -7616,7 +7636,26 @@ async fn platform_prebuilds_install_frozen_and_roll_back( } } - // 6. Standalone VEX over the fresh checkout bundler installed. + // 6. Standalone VEX over the fresh checkout bundler installed. First + // with the installed build put back on upstream's bytes: it fails + // its own patch's check, and the lock's pin is then no evidence for + // the builds this machine does not install either, so no build of + // the gem is attested. + { + use vex_e2e_common::{assert_absent, assert_not_attested, run_vex}; + std::fs::write(&installed, &orig).unwrap(); + let out = run_vex(&binary(), &fresh, &vex_run(&fx)); + assert_eq!(out.code, Some(1), "unpatched installed build: {out}"); + for (purl, _) in &expected { + let reason = match purl.ends_with(&format!("?platform={own}")) { + true => "not_applied", + false => "package_not_found", + }; + assert_not_attested(&out.envelope, purl, reason); + assert_absent(out.doc.as_ref(), purl); + } + std::fs::write(&installed, &patched).unwrap(); + } manifestless_vex_matrix_for(&fx, &fresh, &expected).await; } @@ -7652,22 +7691,34 @@ async fn gem_hosted_lock_gaining_a_platform_keeps_the_gemfile_line() { let tmp = tempfile::tempdir().unwrap(); let stage = tmp.path().join("gem-stage"); let (orig, patched) = (build_marked(orig_lib()), build_marked(patched_lib())); - let builds_of = |tag: &str, lib: &str| -> Vec { + // Each patch of a fix has bytes of its own in the file it patches (the + // patch service writes the patch's own header into it), so the patched + // ruby gem and the patched foreign platform gem differ from this + // machine's patched gem, whose file is `patched`. + let own_token = format!("{DEP_VERSION}-{own}"); + let patched_of = |token: &str| match token == own_token { + true => patched.clone(), + false => format!("{patched}# the patch of {DEP}-{token}\n"), + }; + let builds_of = |tag: &str, lib_of: &dyn Fn(&str) -> String| -> Vec { [None, Some(own.as_str()), Some(foreign.as_str())] .into_iter() - .map(|platform| IndexBuild { - name: DEP, - token: match platform { + .map(|platform| { + let token = match platform { Some(p) => format!("{DEP_VERSION}-{p}"), None => DEP_VERSION.to_string(), - }, - deps: vec![format!("{TRANSITIVE}:>= 0")], - gem: build_gem_build(&stage, tag, platform, lib), + }; + IndexBuild { + name: DEP, + deps: vec![format!("{TRANSITIVE}:>= 0")], + gem: build_gem_build(&stage, tag, platform, &lib_of(&token)), + token, + } }) .collect() }; - let mut upstream_builds = builds_of("orig", &orig); - let patched_builds = builds_of("patched", &patched); + let mut upstream_builds = builds_of("orig", &|_| orig.clone()); + let patched_builds = builds_of("patched", &patched_of); let token = |platform: &str| format!("{DEP_VERSION}-{platform}"); let patched_sha = |platform: &str| { let build = patched_builds.iter().find(|b| b.token == token(platform)); @@ -7693,9 +7744,10 @@ async fn gem_hosted_lock_gaining_a_platform_keeps_the_gemfile_line() { &server, &patched_builds, &platforms, - (&orig, &patched), + (&orig, &|_| patched.clone()), false, 5, + ReferencePurls::Qualified, ) .await; @@ -7882,22 +7934,41 @@ fn platform_uuid(platform: &str) -> String { format!("{}{:012x}", &UUID[..24], tail & 0xffff_ffff_ffff) } +/// What the package reference of a gem patch states as its `purl`. The +/// search always lists a patch under its own purl; the reference is where +/// the two shapes differ, and a run has to place a patch of either. +#[derive(Clone, Copy)] +enum ReferencePurls { + /// The patch's own purl, with the `platform` qualifier of a platform + /// gem's patch. + Qualified, + /// The gem alone ([`PURL`]) for every patch of the fix, a platform + /// gem's included: what the patch service states. + GemOnly, + /// The patch's own purl, and the ruby gem's patch is `?platform=ruby` + /// wherever it is named: the search, its view and its reference. + QualifiedWithRuby, +} + /// The patches API of one fix of [`DEP`]: the patch of the ruby gem /// ([`UUID`], the fix's source) and the patch of each platform gem in /// `platforms` ([`platform_uuid`]), built from it. Each patch is found /// under its own purl (`?platform=`), and its reference is a gem /// patch's: a `tarball`, its registry and its sha256. With `vendorable`, /// the references also state each gem's sha512 and serve a stub gemspec, -/// which a vendored run takes. `(orig, patched)` are the lib's two texts, -/// for the patch views. `priority`: the mocks' wiremock priority (lower +/// which a vendored run takes. `(orig, patched_of)` are the lib's text +/// before the patch and, by a build's index token, after its patch, for +/// the patch views. `priority`: the mocks' wiremock priority (lower /// wins), so a later mount can take over from an earlier one. +/// `reference_purls`: what each reference states as its `purl`. async fn mount_gem_fix_api( server: &MockServer, patched_builds: &[IndexBuild], platforms: &[&str], - (orig, patched): (&str, &str), + (orig, patched_of): (&str, &dyn Fn(&str) -> String), vendorable: bool, priority: u8, + reference_purls: ReferencePurls, ) { let gem_of = |token: &str| { let build = patched_builds @@ -7906,8 +7977,12 @@ async fn mount_gem_fix_api( &build.expect("build").gem }; // `(purl, uuid, token)` of each patch, the source first. + let source = match reference_purls { + ReferencePurls::QualifiedWithRuby => format!("{PURL}?platform=ruby"), + ReferencePurls::Qualified | ReferencePurls::GemOnly => PURL.to_string(), + }; let mut patches: Vec<(String, String, String)> = - vec![(PURL.to_string(), UUID.to_string(), DEP_VERSION.to_string())]; + vec![(source, UUID.to_string(), DEP_VERSION.to_string())]; for platform in platforms { patches.push(( format!("{PURL}?platform={platform}"), @@ -7996,7 +8071,12 @@ async fn mount_gem_fix_api( serde_json::json!({ "status": "granted", "url": url, - "purl": purl, + "purl": match reference_purls { + ReferencePurls::Qualified | ReferencePurls::QualifiedWithRuby => { + purl.as_str() + } + ReferencePurls::GemOnly => PURL, + }, "rebuiltFromUuid": (uuid.as_str() != UUID).then_some(UUID), "artifacts": artifacts, "registryOverride": { @@ -8027,7 +8107,8 @@ async fn mount_gem_fix_api( .with_priority(priority) .mount(server) .await; - for (purl, uuid, _) in &patches { + for (purl, uuid, token) in &patches { + let patched = patched_of(token); Mock::given(method("GET")) .and(path(format!("/v0/orgs/{ORG}/patches/view/{uuid}"))) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ @@ -8065,6 +8146,7 @@ async fn gem_hosted_platform_prebuilds_install_frozen_and_roll_back() { true, false, false, + ReferencePurls::GemOnly, ) .await; } @@ -8078,6 +8160,22 @@ async fn gem_hosted_platform_prebuilds_beside_the_ruby_entry_install_frozen_and_ true, true, false, + ReferencePurls::GemOnly, + ) + .await; +} + +/// The ruby gem's patch named `?platform=ruby` by its reference too. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_platform_prebuilds_beside_a_ruby_entry_named_by_platform() { + platform_prebuilds_install_frozen_and_roll_back( + "platform-prebuilds-ruby-named", + true, + true, + false, + ReferencePurls::QualifiedWithRuby, ) .await; } @@ -8086,8 +8184,14 @@ async fn gem_hosted_platform_prebuilds_beside_the_ruby_entry_install_frozen_and_ #[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.2); \ the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] async fn gem_hosted_platform_prebuilds_without_checksums_install_frozen_and_roll_back() { - platform_prebuilds_install_frozen_and_roll_back("platform-prebuilds", false, false, false) - .await; + platform_prebuilds_install_frozen_and_roll_back( + "platform-prebuilds", + false, + false, + false, + ReferencePurls::Qualified, + ) + .await; } /// #2174: a platform gem that went from hosted to vendored, then unwound. @@ -8100,6 +8204,7 @@ async fn gem_vendored_unwind_restores_a_platform_install_the_hosted_scan_patched true, false, true, + ReferencePurls::GemOnly, ) .await; } @@ -8113,6 +8218,7 @@ async fn gem_vendored_unwind_restores_a_platform_install_without_checksums() { false, false, true, + ReferencePurls::Qualified, ) .await; } diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index 524e2edf4..f1d028982 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -440,7 +440,24 @@ fn candidate_of( if reference.status != "granted" && reference.status != "reused" { return Err(skip(sel_purl, &reference.status)); } - let purl = reference.purl.as_deref().unwrap_or(sel_purl); + let served = reference.purl.as_deref().unwrap_or(sel_purl); + // The patch of a platform gem is reported under that gem's purl. Its + // reference may name the gem alone (`pkg:gem/nokogiri@1.19.3` for the + // patch of `?platform=x86_64-linux-gnu`); the selection's purl, which + // the search listed the patch under, then says which gem it is of. + let platform_gem = match crate::utils::purl::gem_platform_qualifier(sel_purl) { + Some(platform) + if Ecosystem::from_purl(served) == Some(Ecosystem::Gem) + && crate::utils::purl::gem_platform_qualifier(served).is_none() => + { + Some(format!( + "{}?platform={platform}", + crate::utils::purl::strip_purl_qualifiers(served) + )) + } + _ => None, + }; + let purl = platform_gem.as_deref().unwrap_or(served); let Some((ecosystem, name, version)) = purl_parts(purl) else { return Err(skip(purl, "bad_purl")); }; @@ -7702,6 +7719,51 @@ mod tests { assert!(missing_gem_sources(&refs).is_empty()); } + /// The patch service states the gem alone as the purl of every gem + /// reference, a platform gem's patch included. The candidate of such a + /// patch is still that platform gem's: it is reported under the purl + /// the search listed the patch under, and the ruby gem's patch stays + /// under the gem's plain purl. + #[test] + fn a_platform_gem_candidate_keeps_its_purl_when_the_reference_names_the_gem_alone() { + use crate::patch::redirect::gem_platform; + let bare = |uuid: &str, platform: Option<&str>, source: Option<&str>| { + let mut reference = gem_reference(uuid, platform, source); + reference.purl = Some("pkg:gem/nokogiri@1.19.3".to_string()); + reference + }; + let refs = HashMap::from([ + (GEM_SOURCE.to_string(), bare(GEM_SOURCE, None, None)), + ( + GEM_LINUX.to_string(), + bare(GEM_LINUX, Some("x86_64-linux-gnu"), Some(GEM_SOURCE)), + ), + ]); + let selected = vec![ + ( + "pkg:gem/nokogiri@1.19.3?platform=ruby".to_string(), + GEM_SOURCE.to_string(), + ), + ( + "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu".to_string(), + GEM_LINUX.to_string(), + ), + ]; + let (mut skipped, mut warnings) = (Vec::new(), Vec::new()); + let candidates = build_candidates(&selected, &refs, &[], &mut skipped, &mut warnings); + assert!(skipped.is_empty() && warnings.is_empty(), "{skipped:?}"); + let [source, linux] = candidates.as_slice() else { + panic!("two candidates: {candidates:?}"); + }; + assert_eq!(source.purl, "pkg:gem/nokogiri@1.19.3"); + assert_eq!(gem_platform(&source.dep), None); + assert_eq!( + linux.purl, + "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu" + ); + assert_eq!(gem_platform(&linux.dep), Some("x86_64-linux-gnu")); + } + /// A lock of platform builds alone selects no patch of the ruby gem, /// and the registry of the fix's source patch is still the gem's one /// source: the run asks for that patch's reference too, and it joins diff --git a/crates/socket-patch-core/src/hosted/gem_fixes.rs b/crates/socket-patch-core/src/hosted/gem_fixes.rs index 1fa9e785b..4d9456b25 100644 --- a/crates/socket-patch-core/src/hosted/gem_fixes.rs +++ b/crates/socket-patch-core/src/hosted/gem_fixes.rs @@ -605,6 +605,50 @@ pub fn hosted_platform_builds( Ok(builds.into_values().collect()) } +/// The granted patch of the wired fix for one locked build: the patch of +/// `wired`'s family that is for the build's platform and whose gem has the +/// sha256 `digest`, which the fix's registry lists for the build. +/// +/// `searched` is the platform of each patch the search offers for the gem, +/// by uuid. A patch's purl there states its platform; the purl of its +/// package reference may name the gem alone (`pkg:gem/nokogiri@1.19.3` for +/// the patch of `?platform=x86_64-linux-gnu`), so it is read only for a +/// patch the search does not list. +fn locked_build_patch<'r>( + build: &HostedGemBuild, + digest: &str, + gem: &(String, String), + wired: &str, + refs: &'r HashMap, + searched: &HashMap<&str, Option>, +) -> Result<&'r str, String> { + let platform_of = |uuid: &str, reference: &PackageVendorResult| match searched.get(uuid) { + Some(platform) => Some(platform.clone()), + None => reference + .purl + .as_deref() + .and_then(gem_of) + .filter(|(named, _)| named == gem) + .map(|(_, platform)| platform), + }; + let mut matches = refs.iter().filter(|(uuid, r)| { + usable(uuid, refs) + && family_of(uuid, refs) == family_of(wired, refs) + && platform_of(uuid, r).is_some_and(|platform| platform == build.platform) + && r.registry_override + .as_ref() + .and_then(|o| o.identifiers.gem_checksum_sha256.as_deref()) + == Some(digest) + }); + let (uuid, _) = matches + .next() + .ok_or_else(|| format!("no granted patch matches {}", build.token))?; + if matches.next().is_some() { + return Err(format!("ambiguous patches for {}", build.token)); + } + Ok(uuid) +} + /// Resolve every locked build to a granted patch of the wired family whose /// digest matches both its registry and any checksum in the lock. pub async fn hosted_build_records( @@ -619,12 +663,14 @@ pub async fn hosted_build_records( .search_patches_by_package(crate::utils::purl::strip_purl_qualifiers(purl)) .await .map_err(|_| "gem patch search failed")?; - let mut uuids: Vec<_> = found + let searched: HashMap<&str, Option> = found .patches .iter() - .filter(|p| gem_of(&p.purl).is_some_and(|(g, _)| g == gem)) - .map(|p| p.uuid.clone()) + .filter_map(|p| Some((p.uuid.as_str(), gem_of(&p.purl)?))) + .filter(|(_, (named, _))| *named == gem) + .map(|(uuid, (_, platform))| (uuid, platform)) .collect(); + let mut uuids: Vec = searched.keys().map(|uuid| (*uuid).to_owned()).collect(); uuids.push(wired.to_owned()); uuids.sort(); uuids.dedup(); @@ -648,25 +694,8 @@ pub async fn hosted_build_records( b.token )); } - let mut matches = refs.iter().filter(|(uuid, r)| { - usable(uuid, &refs) - && family_of(uuid, &refs) == family_of(wired, &refs) - && r.purl - .as_deref() - .and_then(gem_of) - .is_some_and(|(g, p)| g == gem && p == b.platform) - && r.registry_override - .as_ref() - .and_then(|o| o.identifiers.gem_checksum_sha256.as_deref()) - == Some(&digest) - }); - let (uuid, _) = matches - .next() - .ok_or_else(|| format!("no granted patch matches {}", b.token))?; - if matches.next().is_some() { - return Err(format!("ambiguous patches for {}", b.token)); - } - Ok((uuid.clone(), b.pin.clone())) + let uuid = locked_build_patch(b, &digest, &gem, wired, &refs, &searched)?; + Ok((uuid.to_owned(), b.pin.clone())) }) .collect() } @@ -1408,4 +1437,160 @@ mod tests { assert_eq!(offers.selected[RUBY].uuid, SRC_A); assert_eq!(offers.selected[LINUX].uuid, A_LINUX); } + + /// A granted gem reference with `purl` and the sha256 of its gem. + fn gem_reference(purl: &str, source: Option<&str>, sha256: &str) -> PackageVendorResult { + serde_json::from_value(serde_json::json!({ + "status": "granted", + "purl": purl, + "rebuiltFromUuid": source, + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://patch.example/patch-registry/gem/t/u/", + "identifiers": { + "name": "nokogiri", + "version": "1.19.3", + "gemChecksumSha256": sha256, + } + }, + })) + .unwrap() + } + + fn locked_build(platform: Option<&str>) -> HostedGemBuild { + HostedGemBuild { + token: match platform { + Some(platform) => format!("1.19.3-{platform}"), + None => "1.19.3".to_string(), + }, + platform: platform.map(str::to_string), + pin: None, + } + } + + /// The references of fix A as the patch service states them: the purl + /// of every reference names the gem alone, the platform patch's + /// included. `qualified` gives each its patch's own purl instead. + fn fix_a_references(qualified: bool) -> HashMap { + let purl = |own: &str| match qualified { + true => own.to_string(), + false => "pkg:gem/nokogiri@1.19.3".to_string(), + }; + HashMap::from([ + ( + SRC_A.to_string(), + gem_reference(&purl(RUBY), None, "sha-ruby"), + ), + ( + A_LINUX.to_string(), + gem_reference(&purl(LINUX), Some(SRC_A), "sha-linux"), + ), + ( + A_DARWIN.to_string(), + gem_reference(&purl(DARWIN), Some(SRC_A), "sha-darwin"), + ), + ]) + } + + fn searched_platforms(found: &[PatchSearchResult]) -> HashMap<&str, Option> { + found + .iter() + .map(|p| (p.uuid.as_str(), gem_of(&p.purl).unwrap().1)) + .collect() + } + + /// A locked build is matched to the patch of its own platform whether + /// the package reference names that platform in its purl or leaves it + /// out: the patch service states the gem alone there, and the search + /// is what says which platform a patch is for. + #[test] + fn a_locked_build_finds_its_patch_when_the_reference_purl_names_no_platform() { + let gem = ("nokogiri".to_string(), "1.19.3".to_string()); + let found = fix_a(); + let searched = searched_platforms(&found); + for qualified in [false, true] { + let refs = fix_a_references(qualified); + for (platform, digest, uuid) in [ + (Some("x86_64-linux-gnu"), "sha-linux", A_LINUX), + (Some("arm64-darwin"), "sha-darwin", A_DARWIN), + (None, "sha-ruby", SRC_A), + ] { + assert_eq!( + locked_build_patch( + &locked_build(platform), + digest, + &gem, + SRC_A, + &refs, + &searched + ), + Ok(uuid), + "{platform:?}, qualified reference purls: {qualified}" + ); + } + // The registry lists another gem for the build than any patch + // of the fix states: nothing is attested by a guess. + assert_eq!( + locked_build_patch( + &locked_build(Some("x86_64-linux-gnu")), + "sha-darwin", + &gem, + SRC_A, + &refs, + &searched + ), + Err("no granted patch matches 1.19.3-x86_64-linux-gnu".to_string()) + ); + } + } + + /// A patch the search does not list (one that is no longer on offer) + /// is placed by its reference's purl, and a reference that names + /// another gem is no patch of this one. + #[test] + fn a_patch_the_search_does_not_list_is_placed_by_its_reference() { + let gem = ("nokogiri".to_string(), "1.19.3".to_string()); + let refs = fix_a_references(true); + let none = HashMap::new(); + assert_eq!( + locked_build_patch( + &locked_build(Some("x86_64-linux-gnu")), + "sha-linux", + &gem, + SRC_A, + &refs, + &none + ), + Ok(A_LINUX) + ); + let mut other = refs.clone(); + other.insert( + A_LINUX.to_string(), + gem_reference( + "pkg:gem/racc@1.19.3?platform=x86_64-linux-gnu", + Some(SRC_A), + "sha-linux", + ), + ); + assert!(locked_build_patch( + &locked_build(Some("x86_64-linux-gnu")), + "sha-linux", + &gem, + SRC_A, + &other, + &none + ) + .is_err()); + // With bare purls and no search, a platform build has no patch + // that says it is for that platform. + assert!(locked_build_patch( + &locked_build(Some("x86_64-linux-gnu")), + "sha-linux", + &gem, + SRC_A, + &fix_a_references(false), + &none + ) + .is_err()); + } } diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 1425438fa..46980d139 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5493,9 +5493,11 @@ such gem) and moves the gem only when the registry serves every locked build wit the lock is about to pin. `bundle install` then fetches the one patched platform gem of the machine it runs on and compiles nothing, in frozen and deployment mode too. The run reports each locked build under its own patch: `--json` has one `applied` event per build, and the run's -`--vex` attests each build by its own patch UUID. A later `socket-patch vex` reads the lock, -which holds the one registry: it attests the gem by the patch that registry belongs to, the -ruby gem's. +`--vex` attests each build by its own patch UUID. A later `socket-patch vex` does the same. The +lock holds the one registry, so the command asks the patch service which patch each locked build +belongs to (it needs the network for such a gem). It checks the build this machine installed +against that build's own patch, and attests the builds this machine does not install from the +lock's pin. While the installed build fails its check, it attests no build of the gem. When the patch of the ruby gem is not available to the run (it is not offered to the organisation, say) while every locked build has its own, the gem is moved all the same: any From 01dd5eed6390856ac7c46a662a10a0684d05bb4a Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Thu, 3 Dec 2026 20:29:19 -0500 Subject: [PATCH 2/3] Check a gem reference against the search, and pin the service's purl shapes Review follow-ups to the hosted platform-gem `vex` fix. A patch the search lists is still held to its reference: one that names another gem, or carries the `platform` of another build, matches no locked build. The two spellings of the glibc Linux platform are one. A platform gem's patch the search does not list, whose reference names the gem alone, is no longer read as the ruby gem's patch: nothing states its platform, so it matches no build. A hosted candidate takes the selection's platform only where its reference names none. A reference that says `?platform=ruby` is reported as it states. The capstone fixture for bare references now lists the ruby gem's patch under `?platform=ruby` in the search and its view, as the patch service does, and the lock-gaining test serves views that match the gems it builds. The docs of the hosted copy lookup say a gem build's purl gets the copies of its own build. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/vex_consumed.rs | 5 +- .../tests/e2e_redirect_gem_build.rs | 12 +- crates/socket-patch-core/src/hosted/engine.rs | 22 +++- .../socket-patch-core/src/hosted/gem_fixes.rs | 123 ++++++++++++++++-- 4 files changed, 145 insertions(+), 17 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vex_consumed.rs b/crates/socket-patch-cli/src/commands/vex_consumed.rs index de1cb3c30..26d3d7790 100644 --- a/crates/socket-patch-cli/src/commands/vex_consumed.rs +++ b/crates/socket-patch-cli/src/commands/vex_consumed.rs @@ -25,7 +25,7 @@ //! | maven | `///-socket./` (the version the pom or the hosted Gradle wiring pins) in `~/.m2` and every Gradle `files-2.1` holding it (hash dirs expanded), its artifact files matched under the suffixed name | the `` version dir | //! | npm | every `node_modules` copy the crawler finds (pnpm and vlt store copies included), every peer / modifier / registry variant of those in the same `.pnpm` / `.vlt` store, alias installs (`node_modules/` holding the package) in the root's and every workspace member's tree included | — each serves some dependent: ALL must verify | //! | pypi | every copy in the crawler's environment set (the project's venvs when it has any, else the interpreters) | — any may be the one that runs the project: ALL must verify | -//! | gem | every copy in bundler's gem path; under an explicit or deployment `path` the `gem env` homes hold only default gems bundler loads | a non-default gem's `gem env` copy when bundler doesn't use system gems; otherwise bundler loads whichever `Gem.path` home it hits first: ALL must verify | +//! | gem | every copy in bundler's gem path; under an explicit or deployment `path` the `gem env` homes hold only default gems bundler loads. A purl that names one build of a gem (`?platform=`) is given the copies of that build alone, and a copy that matches no build's record stays on every build's purl (the caller narrows them, `vex`'s `narrow_gem_variant_copies`) | a non-default gem's `gem env` copy when bundler doesn't use system gems; otherwise bundler loads whichever `Gem.path` home it hits first: ALL must verify | //! //! composer and nuget have ONE install location shared by every source //! (`vendor/`, the global packages folder — which restore reuses whatever @@ -66,7 +66,8 @@ use crate::ecosystem_dispatch::{ /// the installed-tree lookup. `installed` is that lookup's every-copy /// result ([`crate::ecosystem_dispatch::find_manifest_package_copies_reusing`] over /// the record view, which holds every hosted purl), including npm store -/// variants, and `live` the judgement of the npm stores' live entries that +/// variants, with each gem build's purl narrowed to the copies of its own +/// build, and `live` the judgement of the npm stores' live entries that /// lookup made, which this one shares: it drops no copy that lookup kept. /// The shared-location ecosystems read it instead of crawling /// the tree a second time. `prior` 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 422cae145..2a3cfe3f2 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -7744,7 +7744,7 @@ async fn gem_hosted_lock_gaining_a_platform_keeps_the_gemfile_line() { &server, &patched_builds, &platforms, - (&orig, &|_| patched.clone()), + (&orig, &patched_of), false, 5, ReferencePurls::Qualified, @@ -7943,7 +7943,9 @@ enum ReferencePurls { /// gem's patch. Qualified, /// The gem alone ([`PURL`]) for every patch of the fix, a platform - /// gem's included: what the patch service states. + /// gem's included, while the search and the view name each patch by + /// its own purl, the ruby gem's as `?platform=ruby`: what the patch + /// service states. GemOnly, /// The patch's own purl, and the ruby gem's patch is `?platform=ruby` /// wherever it is named: the search, its view and its reference. @@ -7978,8 +7980,10 @@ async fn mount_gem_fix_api( }; // `(purl, uuid, token)` of each patch, the source first. let source = match reference_purls { - ReferencePurls::QualifiedWithRuby => format!("{PURL}?platform=ruby"), - ReferencePurls::Qualified | ReferencePurls::GemOnly => PURL.to_string(), + ReferencePurls::QualifiedWithRuby | ReferencePurls::GemOnly => { + format!("{PURL}?platform=ruby") + } + ReferencePurls::Qualified => PURL.to_string(), }; let mut patches: Vec<(String, String, String)> = vec![(source, UUID.to_string(), DEP_VERSION.to_string())]; diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index f1d028982..da9e46693 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -448,7 +448,7 @@ fn candidate_of( let platform_gem = match crate::utils::purl::gem_platform_qualifier(sel_purl) { Some(platform) if Ecosystem::from_purl(served) == Some(Ecosystem::Gem) - && crate::utils::purl::gem_platform_qualifier(served).is_none() => + && crate::utils::purl::purl_qualifier(served, "platform").is_none() => { Some(format!( "{}?platform={platform}", @@ -7762,6 +7762,26 @@ mod tests { "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu" ); assert_eq!(gem_platform(&linux.dep), Some("x86_64-linux-gnu")); + + // A reference that names a platform itself, the ruby one included, + // is reported as it states: the selection's platform fills in only + // where the reference names none. + let named = |purl: &str| { + let mut reference = + gem_reference(GEM_LINUX, Some("x86_64-linux-gnu"), Some(GEM_SOURCE)); + reference.purl = Some(purl.to_string()); + let refs = HashMap::from([(GEM_LINUX.to_string(), reference)]); + let (mut skipped, mut warnings) = (Vec::new(), Vec::new()); + let candidates = + build_candidates(&selected[1..], &refs, &[], &mut skipped, &mut warnings); + candidates[0].purl.clone() + }; + for stated in [ + "pkg:gem/nokogiri@1.19.3?platform=ruby", + "pkg:gem/nokogiri@1.19.3?platform=arm64-darwin", + ] { + assert_eq!(named(stated), stated); + } } /// A lock of platform builds alone selects no patch of the ruby gem, diff --git a/crates/socket-patch-core/src/hosted/gem_fixes.rs b/crates/socket-patch-core/src/hosted/gem_fixes.rs index 4d9456b25..41c9b9bb9 100644 --- a/crates/socket-patch-core/src/hosted/gem_fixes.rs +++ b/crates/socket-patch-core/src/hosted/gem_fixes.rs @@ -605,6 +605,16 @@ pub fn hosted_platform_builds( Ok(builds.into_values().collect()) } +/// Whether two gem platforms (`None`: ruby) are one. RubyGems spells the +/// glibc Linux platform with and without `-gnu`. +fn same_platform(a: &Option, b: &Option) -> bool { + let plain = |p: &Option| { + p.as_deref() + .map(|p| p.to_ascii_lowercase().trim_end_matches("-gnu").to_string()) + }; + plain(a) == plain(b) +} + /// The granted patch of the wired fix for one locked build: the patch of /// `wired`'s family that is for the build's platform and whose gem has the /// sha256 `digest`, which the fix's registry lists for the build. @@ -612,8 +622,12 @@ pub fn hosted_platform_builds( /// `searched` is the platform of each patch the search offers for the gem, /// by uuid. A patch's purl there states its platform; the purl of its /// package reference may name the gem alone (`pkg:gem/nokogiri@1.19.3` for -/// the patch of `?platform=x86_64-linux-gnu`), so it is read only for a -/// patch the search does not list. +/// the patch of `?platform=x86_64-linux-gnu`), so it places only a patch +/// the search does not list. Such a patch that was built from another +/// (`rebuiltFromUuid`) and whose reference names the gem alone is a +/// platform gem's with no platform stated anywhere: it matches no build. +/// A reference that contradicts the search (another gem, or a `platform` +/// qualifier naming another platform) matches none either. fn locked_build_patch<'r>( build: &HostedGemBuild, digest: &str, @@ -622,14 +636,35 @@ fn locked_build_patch<'r>( refs: &'r HashMap, searched: &HashMap<&str, Option>, ) -> Result<&'r str, String> { - let platform_of = |uuid: &str, reference: &PackageVendorResult| match searched.get(uuid) { - Some(platform) => Some(platform.clone()), - None => reference + let platform_of = |uuid: &str, reference: &PackageVendorResult| { + // What the reference itself says: the gem, and a platform when its + // purl carries the qualifier. + let stated = reference.purl.as_deref().and_then(gem_of); + let qualifier = reference .purl .as_deref() - .and_then(gem_of) - .filter(|(named, _)| named == gem) - .map(|(_, platform)| platform), + .and_then(|purl| crate::utils::purl::purl_qualifier(purl, "platform")); + let built = reference + .rebuilt_from_uuid + .as_deref() + .is_some_and(|source| !source.is_empty()); + match (searched.get(uuid), stated) { + // A reference that names another gem, or another platform than + // the search does, is no patch of this build. + (Some(_), Some((named, _))) if named != *gem => None, + (Some(listed), Some((_, platform))) + if qualifier.is_some() && !same_platform(&platform, listed) => + { + None + } + (Some(listed), _) => Some(listed.clone()), + (None, Some((named, _))) if named != *gem => None, + // A platform gem's patch whose reference names the gem alone: + // nothing says which platform it is for. + (None, Some((_, None))) if built && qualifier.is_none() => None, + (None, Some((_, platform))) => Some(platform), + (None, None) => None, + } }; let mut matches = refs.iter().filter(|(uuid, r)| { usable(uuid, refs) @@ -1582,15 +1617,83 @@ mod tests { ) .is_err()); // With bare purls and no search, a platform build has no patch - // that says it is for that platform. + // that says it is for that platform, and a platform gem's patch + // is not read as the ruby gem's: nothing states its platform. + let bare = fix_a_references(false); assert!(locked_build_patch( &locked_build(Some("x86_64-linux-gnu")), "sha-linux", &gem, SRC_A, - &fix_a_references(false), + &bare, &none ) .is_err()); + assert_eq!( + locked_build_patch(&locked_build(None), "sha-linux", &gem, SRC_A, &bare, &none), + Err("no granted patch matches 1.19.3".to_string()) + ); + // The ruby gem's own patch is placed by its bare reference. + assert_eq!( + locked_build_patch(&locked_build(None), "sha-ruby", &gem, SRC_A, &bare, &none), + Ok(SRC_A) + ); + } + + /// A reference that contradicts what the search says of its patch is + /// no patch of the build: one that names another gem, or carries the + /// `platform` of another build. The two spellings of the glibc Linux + /// platform are one, and so are `?platform=ruby` and no qualifier. + #[test] + fn a_reference_that_contradicts_the_search_matches_no_build() { + let gem = ("nokogiri".to_string(), "1.19.3".to_string()); + let found = fix_a(); + let searched = searched_platforms(&found); + let linux = locked_build(Some("x86_64-linux-gnu")); + let with = |uuid: &str, purl: &str, source: Option<&str>, sha: &str| { + let mut refs = fix_a_references(true); + refs.insert(uuid.to_string(), gem_reference(purl, source, sha)); + refs + }; + let placed = |refs: &HashMap| { + locked_build_patch(&linux, "sha-linux", &gem, SRC_A, refs, &searched) + .map(str::to_string) + }; + for contradicting in [ + "pkg:gem/racc@1.19.3?platform=x86_64-linux-gnu", + "pkg:gem/nokogiri@1.19.2?platform=x86_64-linux-gnu", + "pkg:gem/nokogiri@1.19.3?platform=arm64-darwin", + "pkg:gem/nokogiri@1.19.3?platform=ruby", + ] { + let refs = with(A_LINUX, contradicting, Some(SRC_A), "sha-linux"); + assert!(placed(&refs).is_err(), "{contradicting}"); + } + for agreeing in [ + "pkg:gem/nokogiri@1.19.3", + "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux", + "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu", + ] { + let refs = with(A_LINUX, agreeing, Some(SRC_A), "sha-linux"); + assert_eq!(placed(&refs), Ok(A_LINUX.to_string()), "{agreeing}"); + } + // The ruby gem's patch, named either way. + for ruby in [ + "pkg:gem/nokogiri@1.19.3", + "pkg:gem/nokogiri@1.19.3?platform=ruby", + ] { + let refs = with(SRC_A, ruby, None, "sha-ruby"); + assert_eq!( + locked_build_patch( + &locked_build(None), + "sha-ruby", + &gem, + SRC_A, + &refs, + &searched + ), + Ok(SRC_A), + "{ruby}" + ); + } } } From 36877941a34c28d004fe54eea6d98788b2f7f189 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 04:21:57 +0000 Subject: [PATCH 3/3] Match a locked build to its patch under either glibc spelling `locked_build_patch` already treats `x86_64-linux` and `x86_64-linux-gnu` (and case) as one platform when deciding whether a reference contradicts the search, but the lock match itself compared exactly. A patch stated as `x86_64-linux` then matched no `x86_64-linux-gnu` build, and standalone `vex` attested nothing for it. Fold the platform there too; the registry digest still pins the build's exact bytes. Found by Cursor Bugbot. Assisted-by: Claude Code:claude-opus-5-5 --- .../socket-patch-core/src/hosted/gem_fixes.rs | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/crates/socket-patch-core/src/hosted/gem_fixes.rs b/crates/socket-patch-core/src/hosted/gem_fixes.rs index 41c9b9bb9..dbcce01c0 100644 --- a/crates/socket-patch-core/src/hosted/gem_fixes.rs +++ b/crates/socket-patch-core/src/hosted/gem_fixes.rs @@ -669,7 +669,8 @@ fn locked_build_patch<'r>( let mut matches = refs.iter().filter(|(uuid, r)| { usable(uuid, refs) && family_of(uuid, refs) == family_of(wired, refs) - && platform_of(uuid, r).is_some_and(|platform| platform == build.platform) + && platform_of(uuid, r) + .is_some_and(|platform| same_platform(&platform, &build.platform)) && r.registry_override .as_ref() .and_then(|o| o.identifiers.gem_checksum_sha256.as_deref()) @@ -1640,6 +1641,43 @@ mod tests { ); } + /// The lock and the patch's purl may spell the glibc Linux platform + /// differently (`x86_64-linux` against `x86_64-linux-gnu`), or in + /// another case: the build still finds its patch, whose bytes the + /// digest pins. + #[test] + fn a_locked_build_finds_its_patch_under_either_glibc_spelling() { + let gem = ("nokogiri".to_string(), "1.19.3".to_string()); + let none = HashMap::new(); + for (locked, stated) in [ + ("x86_64-linux-gnu", "x86_64-linux"), + ("x86_64-linux", "x86_64-linux-gnu"), + ("x86_64-linux-gnu", "X86_64-Linux-GNU"), + ] { + let mut refs = fix_a_references(true); + refs.insert( + A_LINUX.to_string(), + gem_reference( + &format!("pkg:gem/nokogiri@1.19.3?platform={stated}"), + Some(SRC_A), + "sha-linux", + ), + ); + assert_eq!( + locked_build_patch( + &locked_build(Some(locked)), + "sha-linux", + &gem, + SRC_A, + &refs, + &none + ), + Ok(A_LINUX), + "{locked} against {stated}" + ); + } + } + /// A reference that contradicts what the search says of its patch is /// no patch of the build: one that names another gem, or carries the /// `platform` of another build. The two spellings of the glibc Linux