diff --git a/.github/workflows/nokogiri-compatibility.yml b/.github/workflows/nokogiri-compatibility.yml index 1aba3f0f9..498d7befa 100644 --- a/.github/workflows/nokogiri-compatibility.yml +++ b/.github/workflows/nokogiri-compatibility.yml @@ -55,15 +55,16 @@ name: nokogiri patch compatibility # The `hosted` legs run the script's hosted scenario instead: a hosted scan # of a lock that pins nokogiri as platform gems, against a stand-in for the # patch service (tests/nokogiri/patch_service.rb) that serves a patched build -# of each real platform gem; then a frozen install from a fresh checkout, -# `vex` and a byte-identical `rollback`. On JRuby the platform is `java`. +# of each real platform gem, each as a patch of its own built from the ruby +# gem's patch, whose registry serves them all; then a frozen install from a +# fresh checkout, `vex` and a byte-identical `rollback`. On JRuby the +# platform is `java`. # # The `vendored` legs run the script's vendored scenario instead: a vendored -# scan of a lock that pins nokogiri as platform gems, against a stand-in for -# the patch service (tests/nokogiri/patch_service.rb) that serves a patched -# build of each real platform gem; then a frozen install from a fresh -# checkout with the service unreachable, `vex` and a `rollback` to the lock -# as it was. On JRuby the platform is `java`. +# scan of a lock that pins nokogiri as platform gems, against the same +# stand-in; then a frozen install from a fresh checkout with the service +# unreachable, `vex` and a `rollback` to the lock as it was. On JRuby the +# platform is `java`. # # Every leg downloads gems from rubygems.org, and a rebuild of a precompiled # install downloads the source gem and `mini_portile2` from it too. @@ -90,6 +91,9 @@ on: - 'crates/socket-patch-core/src/patch/redirect/grant.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/gem.rs' - 'crates/socket-patch-cli/src/commands/gem_refresh.rs' + # Which patches a run takes for a gem locked as platform gems. + - 'crates/socket-patch-core/src/hosted/gem_fixes.rs' + - 'crates/socket-patch-core/src/hosted/gem_index.rs' # Vendored mode's gem backend. - 'crates/socket-patch-core/src/vendor/gem.rs' - 'crates/socket-patch-core/src/vendor/verify.rs' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 311962014..0e5b1c80a 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -466,7 +466,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)`. The patch registry serves a patched platform gem (a "prebuild": the upstream platform gem's name, gemspec and file list, with the patch's files replaced) for each platform the patch's grant lists (`registryOverride.identifiers.gemPlatforms`, `{platform, gemChecksumSha256}` each; absent or empty when it has none). When EVERY platform entry of the gem at the patched version has a prebuild there, the gem is wired like any other: the manifest edit is the same, 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 the patch registry's `GEM` section, `DEPENDENCIES` is pinned the same way, and each `CHECKSUMS` entry of the gem is set to the sha256 of its own build (a platform entry to its prebuild's, the ruby-platform entry to `gemChecksumSha256`); a lock with no `CHECKSUMS` section gets none. 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). When a locked platform has no prebuild the gem is skipped with `redirect_gem_platform_unsupported`, which names the builds the lock holds, the ones the patch has no patched build for, and what the registry serves; so is a platform build in the merged layout of Bundler < 2.2. 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. **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 locked platform build the patch has no prebuild for, 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` 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 locked platform build the patch has no prebuild for, 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. @@ -487,7 +487,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm *How a copy is judged.* -- An installed dir is judged by the archive RubyGems installed it from, `/cache/.gem`: an archive whose sha256 is a patched artifact's (the grant's `gemChecksumSha256`, else its tarball sha256, or a prebuild's sha256 from `gemPlatforms`) is already patched and never warns, any other readable archive is stale, and a missing or unreadable one is never evidence by itself. A gem installed as a precompiled platform gem is judged the same way under its own leaf (`gems/nokogiri-1.18.10-arm64-darwin`, `cache/nokogiri-1.18.10-arm64-darwin.gem`): once its archive is the patched platform gem it is patched, never warned about again, and not withheld from `--vex`. +- An installed dir is judged by the archive RubyGems installed it from, `/cache/.gem`: an archive whose sha256 is a patched artifact's (the grant's `gemChecksumSha256`, else its tarball sha256; for a platform gem, those of that platform's own patch) is already patched and never warns, any other readable archive is stale, and a missing or unreadable one is never evidence by itself. A gem installed as a precompiled platform gem is judged the same way under its own leaf (`gems/nokogiri-1.18.10-arm64-darwin`, `cache/nokogiri-1.18.10-arm64-darwin.gem`): once its archive is the patched platform gem it is patched, never warned about again, and not withheld from `--vex`. - When there is no readable archive (a pruned `cache/`, `gem cleanup`) or no patched sha to compare it with, and no agent-mode record (below), the scan fetches that patch's record (`…/patches/view/`, for that purl only) and judges the dir by its `afterHash` map; if that fetch fails too, the dir is unjudged: no warning, but the same run's `--vex` withholds the purl (`stale_install_unverified`) instead of assuming it patched. Otherwise hosted mode fetches no patch record. - An agent-mode manifest record of the same patch judges the dir's files by its `afterHash` file map instead. An in-place patch keeps the upstream archive in `/cache/`, and that archive is what `bundle pristine` and `bundle install --redownload` reinstall from (#2089): with a `CHECKSUMS` section in the lock Bundler removes the gem and fails on the pinned checksum (exit 37, and every later `bundle install` fails too), without one it reinstalls the unpatched gem. So files the record proves patched beside a readable archive that is not a patched artifact's are stale as well, by that archive alone: the refresh replaces the archive with the verified patched one under the same rules as an installed copy (project-local by default, a shared gem home only with `--gem-refresh-shared`) and never touches the gem dir, where agent mode keeps a native gem's original build; left alone, the warning says that the files are patched in place and names the archive as the one file to remove. With the patched archive beside them, with no readable archive, or with no patched sha256 to compare it with, the record's verdict stands and an agent→hosted migration stays quiet. - Which copies are judged is the lock's to say. Every build of the gem the project's lock names (the ruby-platform `-`, each `--`) is looked for under its own leaf in every gem home Bundler uses, and each one found is judged and refreshed on its own. A gem home can hold several builds of one version (the ruby-platform gem beside a precompiled one, another project's copy in a shared home): a build the lock does not name is never judged, reported or replaced, and it never stands in for one the lock does name. Only where no lock names the gem is the first installed copy of the version judged. @@ -500,7 +500,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm - **What is refreshed**: a stale installed gem whose gem home is the project's own and physically inside the project directory (`vendor/bundle`, a `BUNDLE_PATH` or `GEM_HOME` under the project root, compared on absolute paths so the default `--cwd .` counts) — its gem dir, its `/cache/.gem` and, for a gem that builds a native extension, its `/extensions///` — and a stale archive in bundler's cache dir inside the project. The installed `specifications` entry is kept: the patched gem carries the upstream gemspec byte for byte. After the run, with no further command, `bundle exec` loads the patched code, and `bundle install`, `bundle install --redownload`, `bundle pristine`, and a frozen, deployment or `--local` install all succeed and keep it. - **What is not, by default**: a gem home outside the project (the system gems, `~/.gem`, an rbenv or asdf home) — another project on the machine may pin the upstream bytes of the same `name-version`, and its `bundle pristine` would then fail on the replaced archive's checksum — and a project path that resolves outside the project directory (a `.bundle/config` `path` or `cache_path` naming another directory, a `vendor/bundle` that is a symlink), because the repository chooses that path. `--gem-refresh-shared` (env `SOCKET_GEM_REFRESH_SHARED`) refreshes both the same way. -- **The only source is the verified archive**: the patched `.gem`, whose sha256 must be one the grant pins (the lock's `CHECKSUMS` entry), checked before any byte of it is used. It is taken from disk when another materialization already holds it, else downloaded from the patch registry (`/gems/.gem`, the URL bundler itself would fetch, then the grant's own artifact URL). A platform copy (`--`) is refreshed from the patched platform gem the registry serves under that leaf, checked against that platform's own sha256 (`gemPlatforms`); a platform gem declares no extensions, so nothing is built. No `bundle` or `gem` command is run, and nothing else is contacted. `--offline` uses only an archive already on disk. With no verified archive, nothing is changed. +- **The only source is the verified archive**: the patched `.gem`, whose sha256 must be one the grant pins (the lock's `CHECKSUMS` entry), checked before any byte of it is used. It is taken from disk when another materialization already holds it, else downloaded from the patch registry (`/gems/.gem`, the URL bundler itself would fetch, then the grant's own artifact URL). A platform copy (`--`) is refreshed from the patched platform gem the registry serves under that leaf, checked against the sha256 of that platform's own patch; a platform gem declares no extensions, so nothing is built. No `bundle` or `gem` command is run, and nothing else is contacted. `--offline` uses only an archive already on disk. With no verified archive, nothing is changed. - **The archive must be that gem**: its gemspec's name, version and platform must be the materialization's, it must agree with the installed gemspec on whether the gem builds extensions, and, when the archive the copy was installed from is still in the home's `cache/`, both must carry the same gemspec. An archive holding a symlink, hardlink or device entry is refused (RubyGems would create it; the refresh never writes one). - **Nothing is ever missing or half-done**: the new gem dir (and extension dir) is built in a stage dir inside the gem home (`/.socket-patch-refresh/`, removed afterwards) and exchanged with the installed one — one atomic exchange where the platform has it (Linux `renameat2`, macOS `renamex_np`), else two renames — and a step that fails puts the earlier ones back. The home's cached `.gem` is replaced together with the gem dir, never without it (that archive is what the next run judges the copy by), and is not created in a home whose `cache/` was pruned. No file is deleted before its verified replacement is in place. - **Native extensions**: RubyGems itself installs the verified archive into a stage home with the Ruby that owns the installed copy (found as agent mode finds it: the Ruby whose extension dir for the gem is the installed one; never a Ruby inside the project), compiling the extension from the archive's own sources and build scripts with the build arguments RubyGems recorded for the installed copy, and the gem dir and extension dir are swapped in together. The compiled extension therefore always matches its sources. With no such Ruby, a failed build, or `--no-gem-native-rebuild`, the copy is left exactly as it was, with the warning. @@ -612,7 +612,7 @@ patches: **The trust boundary holds.** No key names an endpoint, a credential, an org, a mode, a download format or a safety switch — such keys are unknown keys and fail validation. Every key only removes candidates or (`maxNewPatches`) delays them; none can add a package or bypass the tier filter, the agent partition, reference grants, containment checks or any refusal. -**Narrowing never removes.** The policy runs after the `--prune` universe is captured, so `--prune` still judges the full crawl. A package that already carries a recorded patch (the merged recorded view: manifest > hosted lockfile pins > vendor ledger) and is now excluded by paths, ecosystems, packages or `enabled: false` is **retained**: never handed to the hosted rewriters, the vendor engine or agent apply, never upgraded, left byte-identical, and listed under `policy.retained[]` with `upgradeAvailable`. A recorded package whose patches all fall below a new floor keeps its recorded patch, and the floor never replaces a recorded patch that outranks every admitted one. Removing a patch is only ever `rollback` / `remove`, or the dependency leaving the lockfile. +**Narrowing never removes.** The policy runs after the `--prune` universe is captured, so `--prune` still judges the full crawl. A package that already carries a recorded patch (the merged recorded view: manifest > hosted lockfile pins > vendor ledger) and is now excluded by paths, ecosystems, packages or `enabled: false` is **retained**: never handed to the hosted rewriters, the vendor engine or agent apply, never upgraded, left byte-identical, and listed under `policy.retained[]` with `upgradeAvailable`. A recorded package whose patches all fall below a new floor keeps its recorded patch, and the floor never replaces a recorded patch that outranks every admitted one. For a gem the Bundler lock names as precompiled platform builds, what is recorded is one fix with a patch per locked build, and it is kept whole: the fix's patch for every locked build stays selected, also the ones the floor refuses now, so the gem is left as it is instead of being judged as a fix with a build missing. Removing a patch is only ever `rollback` / `remove`, or the dependency leaving the lockfile. **`enabled: false`.** Discovery and the table still run; nothing is written (the `--prune` GC is skipped too); every candidate is reported `policy_disabled` (recorded ones as retained); warning `patches_disabled`; exit 0. @@ -1739,7 +1739,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`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` or the lock already names a vendored copy (see that code) | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked prebuilt platform gem per locked platform, `-//`, each with its gemspec, plus `/.gitignore` (`!*`: re-includes the prebuilt binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a prebuilt platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **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. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patch's prebuilt platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform; EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. Every locked platform needs a prebuild: while the patch service lists none for one of them the gem is skipped (`vendor_prebuilt_platform_pending`, no failure) with nothing written. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no prebuilt tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. 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. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the project is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked patched platform gem per locked platform, `-//`, each from that platform's own patch and with its gemspec, under the `` of the fix's source patch (the ruby gem's), plus `/.gitignore` (`!*`: re-includes the prebuilt binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a prebuilt platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **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. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems of one fix. Each platform gem has a patch of its own (record `pkg:gem/@?platform=`, artifacts `tarball` and `gem-stub-gemspec`, `rebuiltFromUuid` naming the patch of the ruby gem), and the gem is vendored as ONE unit led by that source patch: the vendored dir and the ledger entry carry the source patch's uuid (so the dir does not move when the lock's platforms change). Where the source patch is not among the run's records the unit is led by the patch of the first locked platform instead, and a gem already vendored keeps the lead its ledger entry names while that patch is still one of them, so a copy that works is not moved when the source patch turns up. Whichever leads, the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform; EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. The ledger entry records each tree in `gemBuilds`: `{platform, uuid, gemIntegrity, gemspecIntegrity, record}`, the platform's own patch uuid, the sha512 of the `.gem` and of the stub gemspec it was unpacked from, and that patch's record. Events: as in hosted mode, the gem's outcome (`applied`, `skipped` / `already_vendored`, a skip or a failure) is one event per platform gem that has a patch (`purl` with its `platform` qualifier, its own `uuid`), each counted in `summary`, with `details.gemFix` (the uuid of the patch the gem is vendored through) tying the events of one gem together; the human lines and the vendored count of telemetry take the gem as one package. The patch the gem is vendored through has an event of its own only when no platform gem has a patch. `vendor --check` reports its verdict per platform gem the same way. Every locked platform needs a usable patch of the same fix: while one has none the gem is skipped (`vendor_prebuilt_platform_pending`, no failure) with nothing written. A re-run of a copy whose locked platforms no longer all have a patch, while the committed trees still match the ledger, keeps the copy and reports `vendor_gem_builds_kept`; a lock that gained a platform entry under the vendored `PATH` section gets that platform's tree added in the same directory. An entry an earlier development build wrote names the platforms alone (`gemPlatforms`, read-only): it still verifies against its one patch, is attested by it, reverts byte for byte, is kept (`vendor_gem_builds_kept`) while the platforms have no patch, and is rebuilt in place from the per-platform patches, with `gemBuilds` recorded, by the first run that has one for every locked platform. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no prebuilt tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. 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. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the project is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | | 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). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | | 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 | @@ -2518,7 +2518,8 @@ command's integration tests check its output. | `vendor_maven_selection_undetermined` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): what the build selects for the artifact cannot be read (the reason says why: typically a pom the local repository does not hold, because the project was never resolved) and no declaration names the patch's base version, so nothing is pinned on a guess and no file is written. The reason carries the remedy that fits its cause (resolve the project once and re-run when a pom is missing from the local repository; otherwise declare the artifact at the base version). The vendored twin of `redirect_maven_selection_undetermined`. | | `vendor_maven_pin_would_move_module` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven reactor): the only poms that resolve the artifact at the patch's base version are parent poms above a module that resolves another version. A `` pin in the parent is inherited by that module and would move it, and Maven has no management that reaches a parent and not its children, so nothing is pinned and no file is written; the reason names the parent, the module and its version. When a sibling module does select the base version it is pinned and the same sentence is the `vendor_jvm_degraded` reason `pin_would_move_module`. | | `vendor_prebuilt_pending` / `vendor_prebuilt_unavailable` | `skipped` | vendor / scan / get `--mode vendored` (every ecosystem, #954, #1235): the package is already vendored at another patch uuid, and the patch service has no prebuilt artifact for the selected (superseding) uuid — still building (`pending_build`) / not served (`build_failed`, `not_found`, `withdrawn`, no usable artifact). Nothing is touched: the older patch's artifact, wiring and ledger entry stay in force, the detail names both uuids (`kept the vendored patch : prebuilt is still building for patch `, where `` is the backend's artifact kind: `artifact` for the npm family, `.gem`, `crate`, `module zip`, `dist zip`, `wheel`, `.jar`, `.nupkg`, …), and the run does not fail (exit 0), the way hosted mode keeps its pin and lists the upgrade in `redirect.skipped[]`. A re-run picks the new patch up once the service serves it. A package with no vendored patch to keep still fails (`failed`, error `prebuilt is still building` / `prebuilt unavailable: `; outside the npm family under `vendor_prebuilt_required`), as does a request/transport failure. | -| `vendor_prebuilt_platform_pending` | `skipped` | vendor / scan / get `--mode vendored` (gem): `Gemfile.lock` pins the gem as precompiled platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the patch service lists no prebuilt platform gem (or no stub gemspec) for at least one locked platform. The service lists a prebuild only once it is built, so "not built yet" and "never built" look the same: the detail names the gem, the platforms with no prebuild and the ones that have one, nothing is downloaded or written, and the run does not fail (exit 0), with or without an older vendored patch. With one, it stays in force and the detail names both uuids (`kept the vendored patch : … for patch `). A re-run vendors the gem once every locked platform has a prebuild. Two cases stay failures (`vendor_prebuilt_required`): a copy the lock is already wired to that is missing or damaged and cannot be rebuilt, by a re-run or by `repair`; and an eject of the gem's hosted pin (plain `vendor`), which is all-or-nothing and keeps the pin. | +| `vendor_prebuilt_platform_pending` | `skipped` | vendor / scan / get `--mode vendored` (gem): `Gemfile.lock` pins the gem as precompiled platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and at least one locked platform has no usable patch of the fix: no patch on offer for it (a platform's patch is listed only once it is published and built, so "not built yet" and "never built" look the same), a reference that says its patched gem is still being built or is not available, a patch that serves no stub gemspec, or a patch that belongs to another fix. The detail names the gem, each such platform with its reason and the platforms that have a patch, nothing is downloaded or written, and the run does not fail (exit 0), with or without an older vendored patch. With one, it stays in force and the detail names both uuids (`kept the vendored patch : … for patch `). A re-run vendors the gem once every locked platform has a patch. Two cases stay failures (`vendor_prebuilt_required`): a copy the lock is already wired to that is missing or damaged and cannot be rebuilt, by a re-run or by `repair`; and an eject of the gem's hosted pin (plain `vendor`), which is all-or-nothing and keeps the pin. An eject reads the fix's platform patches from the patch API (the lock's pin names the source patch alone), so a hosted platform gem ejects when every locked platform has one. | +| `vendor_gem_builds_kept` | `skipped` | vendor / scan / get `--mode vendored` (gem): a gem already vendored as platform gems, on a run that has no patch of the fix for one of the locked platforms (a patch withdrawn or not offered to this run, or a copy an earlier development build vendored, whose platforms have no patch yet). The committed trees still match what the ledger records, so the copy stays in force: nothing is downloaded or written and the run does not fail. The detail names the copy and the platforms. A later run brings the copy up to date once every locked platform has a patch. | | `unsafe_coordinates` | `failed` | vendor: purl/uuid would escape `.socket/vendor/` (tampered manifest/state); refused before any write. | | `revert_failed` | `failed` | vendor --revert: a recorded entry could not be reverted. | | `vendor_ledger_missing` | `failed` (artifact-level: `uuid` + `details.{ecosystem,path}`, no purl) | repair (v5.0) and `vendor --check`: a lockfile references `.socket/vendor///` but the vendor ledger has no entry for it; repair no longer rebuilds ledger entries from lockfiles. Recovery: restore `.socket/vendor/state.json` from version control and re-run `repair`, or `git checkout -- ` and re-vendor. | @@ -2604,7 +2605,7 @@ command's integration tests check its output. | `vendor_dep_manifest_unlocked` | refused | vendor (yarn classic): the patch rewrites the package's own `package.json` to depend on a descriptor (`name@range`) no `yarn.lock` block is keyed by — an added dependency, or an existing one moved to a new range. A descriptor every wired block's sub-map already names is not counted: yarn keys those blocks by the registry packument's ranges, which can differ from the tarball's `package.json` (#1578). yarn 1 builds its install graph from the lock, so the rewired block would name a dependency it never resolves: online frozen installs fetch it unpinned, `--offline` installs fail and every plain `yarn install` re-saves the lock (#591). Refused after staging and before any wiring is written (the staged uuid dir is removed); the detail names the descriptors. Remedy: lock them first (for example `yarn add `), then re-run. A dry run, which stages nothing, does not foresee it. Also `failed` on `repair` (and `vendor_check_failed` on `vendor --check`) for a lock an older release already vendored that way, with a block wired to the entry naming a descriptor no block locks and the recorded pre-vendor block did not (#1379); the lock is left as it is. Remedy: `yarn install` (without `--frozen-lockfile`) to lock them, then commit `yarn.lock`. | | `redirect_yarn_classic_dep_manifest_unlocked` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` depends on a descriptor no `yarn.lock` block is keyed by and that the sub-maps of the registry blocks being pinned don't already name (yarn keys those by the packument's ranges, #1578). yarn 1 installs only what the lock names, so a pin would install the patched package without that dependency (#591). The dep is not pinned and never confirmed; the lock is left as it was. The served tarball is read on every run, so a pin an earlier release wrote without this check (#1462) gets the same warning and is never confirmed either; it stays in the lock until the dependency is locked or the pin is rolled back. Same remedy as `vendor_dep_manifest_unlocked`. | | `redirect_yarn_classic_dep_manifest_rewritten` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` declares other dependencies than the pinned block's sub-maps, every descriptor already locked; the block's `dependencies:` / `optionalDependencies:` sub-maps are rewritten to match, in the shape yarn 1 writes for that manifest (#591, #1558). | -| `vendor_artifact_gitignored` | `failed` | vendor (vlt, the npm-family tarball flavors — npm, pnpm, bun, yarn classic, yarn berry — NuGet, every PyPI flavor, a gem vendored as prebuilt platform gems, and the JVM trees of Maven, Gradle, sbt and scala-cli): inside a git work tree, `git check-ignore --no-index` reports the new artifact's uuid directory (JVM: its tree root, such as `.socket/vendor/maven2`) as ignored by a rule its own `.gitignore` cannot override (such as a root `.socket/` or `vendor/` rule; the detail names the rule). Remedy: drop that rule for `.socket/vendor/`. Refused before any write, dry run included. A file rule such as `*.tgz`, `*.nupkg`, `*.whl` or `*.jar` is overridden by the `!*` `.gitignore` vendoring writes into the uuid dir or tree root (PyPI's uuid dir also gets the `.gitattributes` that unsets a `*.whl filter=lfs` rule); if a written tarball, directory payload, nupkg or wheel still reads as ignored, the run refuses and removes the uuid dir it created. | +| `vendor_artifact_gitignored` | `failed` | vendor (vlt, the npm-family tarball flavors — npm, pnpm, bun, yarn classic, yarn berry — NuGet, every PyPI flavor, a gem vendored as platform gems, and the JVM trees of Maven, Gradle, sbt and scala-cli): inside a git work tree, `git check-ignore --no-index` reports the new artifact's uuid directory (JVM: its tree root, such as `.socket/vendor/maven2`) as ignored by a rule its own `.gitignore` cannot override (such as a root `.socket/` or `vendor/` rule; the detail names the rule). Remedy: drop that rule for `.socket/vendor/`. Refused before any write, dry run included. A file rule such as `*.tgz`, `*.nupkg`, `*.whl` or `*.jar` is overridden by the `!*` `.gitignore` vendoring writes into the uuid dir or tree root (PyPI's uuid dir also gets the `.gitattributes` that unsets a `*.whl filter=lfs` rule); if a written tarball, directory payload, nupkg or wheel still reads as ignored, the run refuses and removes the uuid dir it created. | | `vendor_artifact_gitignore_unchecked` | warning | vendor (vlt, the npm-family tarball flavors, NuGet and every PyPI flavor): git is installed but could not answer the ignore check for the written vendored directory (it failed to start, ran past 30 s, or `rev-parse` / `check-ignore` exited with an error); the package is vendored and the detail names what failed. Remedy: make sure no ignore rule covers `.socket/` before committing. Git absent, or a project outside any work tree, raises nothing. | | `vendor_ledger_gitignored` | top-level error (exit 1) | vendor / scan / get `--mode vendored` (every backend) and the hosted→vendored eject: inside a git work tree, `git check-ignore` reports the vendor ledger `.socket/vendor/state.json` as ignored by a file rule (such as `state.json`, `*.json` or `**/state.json`; the message names it), so the commit the run asks for would leave it out and no other checkout could `rollback`, `list` or `vendor --revert` the patches (#1638). A ledger git already tracks is never refused. Refused before any write, dry run included. Remedy: drop the rule or add `!.socket/vendor/state.json`. A rule that ignores `.socket/` or `.socket/vendor/` as a directory is `vendor_artifact_gitignored`: per package from the backends that check it themselves (the npm family, NuGet, PyPI, the JVM trees), and as this same run-level refusal when the run includes any other ecosystem. | | `vendor_ledger_entry_missing` | `failed` | vendor (vlt): the only installed copy is vlt's link to a committed vendored directory, but the vendor ledger has no entry for the package; restore `.socket/vendor/state.json` from version control (v5.0: `repair` no longer re-synthesizes it). Replaces the `package_not_installed` skip. | @@ -2619,7 +2620,7 @@ command's integration tests check its output. | `vendor_uuid_mismatch` | `skipped` | repair: the manifest's patch uuid moved past the vendored artifact — a re-vendor (`vendor` / `scan --mode vendored`) is pending; repair does not cross patch generations. | | `content_mismatch_overwritten` | `skipped` (warning) | apply (explicit `--allow-patch-conflicts` / `--force`): a file matched NEITHER beforeHash nor afterHash and was overwritten with the full verified patched content. This includes a file the patch adds (empty beforeHash) that already exists with other content. `--strict` turns this case into a `failed` event instead. Agent-mode `get` / `scan --json` carry it as a `(content_mismatch_overwritten) …` `warnings[]` entry (#1004). | | `vendor_lock_checksums_unsupported` / `vendor_stale_lock_checksum` | `failed` | vendor (gem): an ambiguous/platform CHECKSUMS entry, or a v1-wired lock whose stale token blocks the hot path (run `vendor --revert` + re-vendor). | -| `platform_gem_unsupported` | `failed` | vendor / scan / get `--mode vendored` (gem): a precompiled platform gem that cannot be vendored. `Gemfile.lock` pins the gem as platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and also holds the plain ` ()` entry of the `ruby` platform, which no prebuilt tree serves (the detail names it; `bundle lock --remove-platform ruby` drops it); or it pins the gem as platform gems and its `BUNDLED WITH` is absent or names a Bundler older than 2.3, the oldest the vendored layout is verified on (the detail names the version needed; `bundle update --bundler` re-locks); or the installed copy is a platform gem and the lock names no platform for the gem; or the patch record is for one platform's build (`?platform=`). Nothing is written. A locked platform the patch service has no prebuild for is not this failure: see `vendor_prebuilt_platform_pending`. | +| `platform_gem_unsupported` | `failed` | vendor / scan / get `--mode vendored` (gem): a precompiled platform gem that cannot be vendored. `Gemfile.lock` pins the gem as platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and also holds the plain ` ()` entry of the `ruby` platform, which no platform tree serves (the detail names it; `bundle lock --remove-platform ruby` drops it); or it pins the gem as platform gems and its `BUNDLED WITH` is absent or names a Bundler older than 2.3, the oldest the vendored layout is verified on (the detail names the version needed; `bundle update --bundler` re-locks); or the installed copy is a platform gem and the lock names no platform for the gem; or the patch record is for one platform's gem (`?platform=`) and is not vendored as part of its fix: the lock does not pin the gem as platform gems. Nothing is written. A locked platform with no patch of the fix is not this failure: see `vendor_prebuilt_platform_pending`. | | `redirect_unattributable` | `skipped` (hosted event) | scan/get `--mode hosted`: the rewriters would pin the patch, but lockfile discovery over the result reads that pin as contested (another lock or requirements file resolves the same version elsewhere, or the pin is not one the package manager consumes), so `vex`, `rollback`, `remove` and `vendor` would refuse it. The candidate is left out of the rewrite, so nothing is written for it; the detail carries discovery's findings. Exit code unchanged. | | `redirect_mirror_unsupported` / `redirect_mirror_url_refused` | `skipped` (hosted event) + `warnings[]` | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: the patch's ecosystem cannot be served through a mirror (`redirect_mirror_unsupported`: Cargo, NuGet; use `--mode vendored`), or its reference could not be moved onto the mirror (`redirect_mirror_url_refused`). Nothing is written for it. See "Patch mirror (experimental)". | | `redirect_mirror_unavailable` | `skipped` (hosted event) + `warnings[]` | **Experimental** (patch mirror). scan/get `--mode hosted` with `--patch-mirror-url`: the mirror did not serve the reference the run asked it for, or could not be reached. That reference is skipped and nothing is written for it. One warning per package, or a single warning about the mirror when it served none of the references it was asked about. | @@ -2654,7 +2655,9 @@ command's integration tests check its output. | `redirect_gem_source_option` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the gem already has a source of its own (an option on its declaration, an enclosing `source` / `git` / `github` / `path` block, a source-pinned `DEPENDENCIES` entry, or a `GIT` / `PATH` lock section) and Bundler allows one per gem. The gem is skipped, nothing written for it. When the source is socket-patch's own vendored `path:`, the detail names the un-vendor step instead. | | `redirect_gem_dependency_not_locked` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the manifest declares the gem but the lock's `DEPENDENCIES` does not list it (an out-of-date lock, or a conditional declaration). The gem is skipped, nothing written for it; run `bundle lock` and re-run. | | `redirect_gem_lock_unconvergeable` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock cannot be edited into the one Bundler writes for the redirected manifest (no `BUNDLED WITH` section, or a merged Bundler < 2.2 `GEM` section whose remotes the manifest's sources do not explain), and Bundler refuses a manifest whose sources its lock does not record under frozen / deployment mode. The gem is refused whole: neither file changes for it. The detail names the lock shape and the way out (`bundle lock` with the current Bundler, then re-run; or `--mode vendored` / `--mode agent`). For a manifest with more than one top-level `source` line, which Bundler 2.2 to 2.7 lock into one `GEM` section naming every source and `bundle lock` does not change, the detail names that cause instead, and the way out is to keep the source that serves the gem as the one top-level `source`, move each other one into a `source "" do … end` block, run `bundle lock` (with Bundler 2.2.25 or later, which the detail says when the lock was written by an earlier 2.2 release, since those keep the one section) and re-run, or `--mode agent`; it does not print the source URLs. The gate counts block-less `source` calls outside every other construct, a computed URL included; a `source` inside a conditional is not counted and keeps the generic detail. | -| `redirect_gem_platform_unsupported` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock holds precompiled platform builds of the gem (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the patch has no patched platform gem ("prebuild", the grant's `gemPlatforms`) for at least one of them, or the lock is the merged layout of Bundler < 2.2. The detail names the locked builds, the ones with no prebuild and what the patch registry serves. The gem is skipped and the manifest and lock stay byte-identical for it. With a prebuild for every locked platform the gem is redirected and no warning is given. | +| `redirect_gem_member_registry` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): a gem locked as platform builds was moved, with every build pinned to its own patch, through the registry of one locked build's patch, because the patch its builds were built from is not available to the run. The detail names the gem, the platform and both patches, and says the manifest's `source:` changes if that platform leaves the lock. Not given for a gem that merely stays on such a registry while the source patch is available. | +| `gem_fix_unsettled` | `warnings[]` (warning) | scan/get `--mode hosted` and `--mode vendored` (gem): the request that says which fix each platform patch belongs to failed, so the gems the lock names as platform builds were left out of this run's selection (a selection ranked purl by purl could take one build's patch from each fix). The detail names the gems and the failure; nothing is written for them, and a re-run settles them. | +| `redirect_gem_platform_unsupported` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock holds precompiled platform builds of the gem (`nokogiri (1.18.10-x86_64-linux-gnu)`) and no one fix has a usable patch for every one of them (each platform gem has a patch of its own): a locked build has no patch, the builds are patched only by different fixes, the fix's source patch is not available, or its registry does not list what the lock would pin, could not be read, or was not read by the run (a gem is never pinned to a registry the run did not look at); or the lock is the merged layout of Bundler < 2.2. The detail names the locked builds and the case (the builds with no patch and the ones that have one; which fix patches which; what the registry lists), and, for a lock that already takes the gem from a patch registry, the `rollback` command that puts it back upstream. The gem is skipped and the manifest and lock stay byte-identical for it. With a patch of one fix for every locked build the gem is redirected and no warning is given. | | `redirect_gem_inconsistent_plan` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the rewriter's self-check found the planned manifest and lock disagreeing about the gem, a pair Bundler refuses frozen. Nothing is written for it. Not expected; report it. | | `redirect_gem_frozen_install` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): a pin socket-patch 5.0 / 5.1 wrote as a `source … do` block sits beside a lock that still records the upstream source and that this run changed but could not converge; Bundler rejects the pair under frozen / deployment mode until an unfrozen `bundle install` records the source. Never raised for the `source:` option form, whose lock always follows. | | `redirect_gem_no_lockfile` | `warnings[]` (warning) | scan `--mode hosted` (gem): the project has a `Gemfile` / `gems.rb` but no lock, so the version it resolves is unknown (#1125). Every gem is skipped and the Gemfile stays byte-identical; run `bundle lock` (or `bundle install`), commit the lock, and re-run. | diff --git a/crates/socket-patch-cli/src/commands/agent_download.rs b/crates/socket-patch-cli/src/commands/agent_download.rs index 4d5926dcf..9c0cacdd7 100644 --- a/crates/socket-patch-cli/src/commands/agent_download.rs +++ b/crates/socket-patch-cli/src/commands/agent_download.rs @@ -669,13 +669,7 @@ pub(crate) async fn filter_to_installed_releases( (kept, warnings, views) } -/// Order a patch selection the way every other collection in the JSON -/// envelope is ordered: by purl, uuid breaking a tie (a release-variant -/// base can keep several qualified purls, and `--all-releases` can keep -/// several patches for one purl). -pub(crate) fn sort_by_purl(patches: &mut [PatchSearchResult]) { - patches.sort_by(|a, b| a.purl.cmp(&b.purl).then_with(|| a.uuid.cmp(&b.uuid))); -} +pub(crate) use socket_patch_core::api::ranking::sort_by_purl; /// Which state store the shared fetch loop classifies each selected patch /// against — the one non-presentational difference between the vendored @@ -1276,9 +1270,7 @@ pub(crate) fn detached_ledger_record<'a>( let RecordStore::Ledger(entries) = store else { return None; }; - lookup_entry(entries, purl) - .filter(|e| e.detached && e.uuid == uuid) - .and_then(|e| e.record.as_ref()) + socket_patch_core::vendor::detached_record_at(entries, purl, uuid) } /// The fetch loop both download engines share: installed-release @@ -1305,14 +1297,39 @@ pub(crate) async fn fetch_selected_patches( // once selection (and get's confirm prompt) is done. let mut status = crate::ui::StatusLine::stderr(params.json, params.silent); status.set("Preparing download"); - let (selected, warnings, views) = filter_to_installed_releases( - selected, + // Vendored mode commits what the project's Bundler lock names, on + // every platform it names: the patches of a gem the lock names go by + // its builds (each platform gem has a patch of its own), not by the + // one copy installed on this machine. + let (locked_gems, selected): (Vec, Vec) = + if matches!(store, RecordStore::Ledger(_)) { + let cwd = params.crawler_options().cwd; + let view = socket_patch_core::vendor::lock_inventory::ProjectView::Disk(&cwd); + let lock = socket_patch_core::hosted::gem_fixes::GemLock::read( + &view, + selected.iter().map(|patch| patch.purl.as_str()), + ) + .await; + let (gems, rest): (Vec<_>, Vec<_>) = selected + .iter() + .cloned() + .partition(|patch| lock.names_gem(&patch.purl)); + (lock.narrow_selected(gems), rest) + } else { + (Vec::new(), selected.to_vec()) + }; + let (mut selected, warnings, views) = filter_to_installed_releases( + &selected, params.all_releases, ¶ms.crawler_options(), quiet, api_client, ) .await; + if !locked_gems.is_empty() { + selected.extend(locked_gems); + sort_by_purl(&mut selected); + } // Agent mode writes into the installed copies. A patch no copy can // take, because conda built each of them as something other than the // pure-Python PyPI release, is left out here instead of being recorded @@ -1479,12 +1496,14 @@ pub(crate) async fn fetch_selected_patches( RecordStore::Manifest(manifest) => { decide_patch_action(manifest, &patch.purl, &patch.uuid) } - RecordStore::Ledger(entries) => match lookup_entry(entries, &patch.purl) { - Some(entry) if entry.uuid != patch.uuid => PatchAction::Updated { - old_uuid: entry.uuid.clone(), - }, - _ => PatchAction::Added, - }, + RecordStore::Ledger(entries) => { + match socket_patch_core::vendor::vendored_uuid(entries, &patch.purl) { + Some(old) if old != patch.uuid => PatchAction::Updated { + old_uuid: old.to_string(), + }, + _ => PatchAction::Added, + } + } }; if action == PatchAction::Skipped { // No line of its own: the caller has listed the patch, and the diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index c418c32af..1cbeeef44 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -1473,7 +1473,23 @@ pub async fn run(args: GetArgs) -> i32 { &telemetry, ) .await; - let selected = vec![search_result_from_response(&patch)]; + // Hosted and vendored mode change what Bundler installs: a + // gem the lock names as platform builds moves on every + // platform or on none. + let selected = if mode == super::scan::ScanMode::Agent { + vec![search_result_from_response(&patch)] + } else { + status.set("Reading the project's locked gems..."); + let selected = with_gem_fix_builds( + &args.common.cwd, + &api_client, + use_public_proxy, + &patch, + ) + .await; + status.finish(); + selected + }; let user_patch_warnings = match super::user_patches::check(&args.common, [&patch.purl]).await { Ok(warnings) => { @@ -1898,6 +1914,33 @@ pub async fn run(args: GetArgs) -> i32 { Err(code) => return code, }; + // Hosted and vendored mode change what Bundler installs: a gem the lock + // names as platform builds takes one fix for every locked build. + // Settled before anything is said of the selection, so that what is + // printed as chosen, and what is reported as waiting for a merged + // patch, is the selection the run uses. + let selected = if mode == super::scan::ScanMode::Agent { + selected + } else { + let (settled, unsettled) = socket_patch_core::hosted::gem_fixes::settle( + &socket_patch_core::vendor::lock_inventory::ProjectView::Disk(&args.common.cwd), + &api_client, + &accessible, + selected, + ) + .await; + if let Some(detail) = unsettled { + if !quiet { + eprintln!("Warning: {detail}"); + } + narrow_warnings.push(( + socket_patch_core::hosted::gem_fixes::GEM_FIX_UNSETTLED.to_string(), + detail, + )); + } + settled + }; + // The candidates can hold several patches per package and the pick // was made without the user (paid auto-pick, `--yes`, non-TTY): say // which will be installed. A menu pick is not echoed back, and paid @@ -1935,7 +1978,26 @@ pub async fn run(args: GetArgs) -> i32 { // engines. Hosted runs and agent previews need the same narrowing here. let agent_preview = args.common.dry_run && mode == super::scan::ScanMode::Agent; let selected = if agent_preview || mode == super::scan::ScanMode::Hosted { - let (selected, variant_warnings, _) = filter_to_installed_releases( + // A hosted run pins what the project's Bundler lock names, on + // every platform it names: the patches of a gem the lock names go + // by its builds (each platform gem has a patch of its own), not by + // the one copy installed on this machine. + let (locked_gems, selected) = if mode == super::scan::ScanMode::Hosted { + let view = + socket_patch_core::vendor::lock_inventory::ProjectView::Disk(&args.common.cwd); + let lock = socket_patch_core::hosted::gem_fixes::GemLock::read( + &view, + selected.iter().map(|patch| patch.purl.as_str()), + ) + .await; + let (gems, rest): (Vec<_>, Vec<_>) = selected + .into_iter() + .partition(|patch| lock.names_gem(&patch.purl)); + (lock.narrow_selected(gems), rest) + } else { + (Vec::new(), selected) + }; + let (mut selected, variant_warnings, _) = filter_to_installed_releases( &selected, args.all_releases, &args.common.crawler_options(), @@ -1948,6 +2010,10 @@ pub async fn run(args: GetArgs) -> i32 { .into_iter() .map(|w| (RELEASE_NARROWING.to_string(), w)), ); + if !locked_gems.is_empty() { + selected.extend(locked_gems); + crate::commands::agent_download::sort_by_purl(&mut selected); + } selected } else { selected @@ -2490,6 +2556,33 @@ fn get_download_params(args: &GetArgs, save_only: bool, persist_blobs: bool) -> } } +/// What `get ` selects for `patch` in hosted and vendored mode: the +/// patch itself and, for a gem the project's Bundler lock names as platform +/// builds, the other patches of its fix that the lock has a build for +/// ([`socket_patch_core::hosted::gem_fixes::fix_siblings`]). Asking for one +/// patch of such a gem is asking for its fix: a run that changes what +/// Bundler installs moves every locked build or none. +async fn with_gem_fix_builds( + cwd: &Path, + api_client: &ApiClient, + use_public_proxy: bool, + patch: &PatchResponse, +) -> Vec { + let mut selected = vec![search_result_from_response(patch)]; + selected.extend( + socket_patch_core::hosted::gem_fixes::fix_siblings( + &socket_patch_core::vendor::lock_inventory::ProjectView::Disk(cwd), + api_client, + use_public_proxy, + &patch.purl, + &patch.uuid, + ) + .await, + ); + crate::commands::agent_download::sort_by_purl(&mut selected); + selected +} + /// `get … --mode hosted`: hand the selected (purl, uuid) pairs to scan's /// hosted engine ([`super::scan::boxed_run_redirect_selected`]) — lockfile /// rewrite only, no manifest, no blobs, no ledger — so the on-disk result diff --git a/crates/socket-patch-cli/src/commands/scan/discovery.rs b/crates/socket-patch-cli/src/commands/scan/discovery.rs index 478df431a..ac112d279 100644 --- a/crates/socket-patch-cli/src/commands/scan/discovery.rs +++ b/crates/socket-patch-cli/src/commands/scan/discovery.rs @@ -365,7 +365,6 @@ pub(super) async fn preverify_vendor_baselines( use socket_patch_core::crawlers::gradle_cache; use socket_patch_core::manifest::schema::PatchFileInfo; use socket_patch_core::patch::apply::{verify_file_patch, VerifyStatus}; - use socket_patch_core::vendor::lookup_entry; let mut mismatched: HashSet = HashSet::new(); let mut views: HashMap = HashMap::new(); @@ -390,13 +389,18 @@ pub(super) async fn preverify_vendor_baselines( return None; } let pkg = crawled.iter().find(|c| PurlKey::same(&c.purl, base))?; + // A platform gem's patch says what that platform's gem holds: + // the one copy installed here is another platform's for every + // other build the lock names, and differs from them by design. + if !gem_patch_is_of_copy(&patch.purl, &pkg.path) { + return None; + } // The same predicate as the download phase's ledger // idempotency skip: its no-fetch set and this one must be // the same set. - let embedded = vendor - .and_then(|entries| lookup_entry(entries, &patch.purl)) - .filter(|e| e.detached && e.uuid == patch.uuid) - .and_then(|e| e.record.as_ref()); + let embedded = vendor.and_then(|entries| { + socket_patch_core::vendor::detached_record_at(entries, &patch.purl, &patch.uuid) + }); Some((pkg, embedded)) }) .collect(); @@ -1041,8 +1045,49 @@ pub(crate) async fn nested_project_skips( (skipped, warnings) } +/// Whether the installed copy at `copy` is the gem that the patch purl +/// `patch_purl` is a patch of. Always for a patch of a ruby-platform gem +/// (and of any other ecosystem); for a platform gem's patch +/// (`?platform=`), only a copy installed as that platform's gem +/// (`--`). +fn gem_patch_is_of_copy(patch_purl: &str, copy: &std::path::Path) -> bool { + let Some(platform) = socket_patch_core::utils::purl::gem_platform_qualifier(patch_purl) else { + return true; + }; + let Some(leaf) = copy.file_name().and_then(|leaf| leaf.to_str()) else { + return false; + }; + // `None` for a purl that is no gem's: its qualifier is not ours to read. + match socket_patch_core::formats::gem::GemBuild::ruby(patch_purl) { + None => true, + Some(_) => socket_patch_core::formats::gem::GemBuild::of_leaf(patch_purl, leaf) + .is_some_and(|build| build.platform.as_deref() == Some(platform)), + } +} + #[cfg(test)] mod tests { + /// A platform gem's patch is compared only with a copy of its own + /// platform: on an x86_64 machine the aarch64 patch of the same lock + /// has no copy here, and must not be held against the x86_64 one. + #[test] + fn a_platform_gems_patch_is_compared_with_its_own_platform_only() { + let copy = |leaf: &str| std::path::PathBuf::from("/home/gems").join(leaf); + let x86 = copy("nokogiri-1.18.10-x86_64-linux-gnu"); + let ruby = copy("nokogiri-1.18.10"); + let patch = |platform: &str| format!("pkg:gem/nokogiri@1.18.10?platform={platform}"); + assert!(gem_patch_is_of_copy(&patch("x86_64-linux-gnu"), &x86)); + assert!(!gem_patch_is_of_copy(&patch("aarch64-linux-gnu"), &x86)); + assert!(!gem_patch_is_of_copy(&patch("x86_64-linux-gnu"), &ruby)); + // The ruby gem's patch, and any other ecosystem's, as before. + assert!(gem_patch_is_of_copy(&patch("ruby"), &x86)); + assert!(gem_patch_is_of_copy("pkg:gem/nokogiri@1.18.10", &ruby)); + assert!(gem_patch_is_of_copy( + "pkg:pypi/numpy@2.4.4?platform=aarch64-linux-gnu", + ©("numpy") + )); + } + use super::*; use socket_patch_core::api::types::BatchPatchInfo; use socket_patch_core::ledgers::merge_ledger_records_for_updates; diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 40a94ae94..eaf5c507b 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -623,8 +623,8 @@ fn stale_cache_gem(purl: &str, cache_path: &Path) -> StaleGem { /// a project-local warning's delete list, or warned alone. /// * A gem locked as precompiled platform builds is installed as /// `--`, and cached under that name: each is -/// judged the same way, against the patched artifacts of the gem, which -/// include its prebuilds. +/// judged the same way, against the patched gem of that platform's own +/// patch. /// * Which copies are judged is the lock's to say: every build of the gem /// the project's lock names is looked for under its own leaf, in every /// gem home. A gem home can hold several builds of one version (the @@ -717,6 +717,35 @@ async fn gem_stale_install_warnings( &stripped, ) .await; + // The gems no lock names: the first installed copy stands for each. + let unlocked: Vec = named.iter().map(Vec::is_empty).collect(); + // Each platform gem has a patch of its own: the patch of a platform + // gem judges that platform's copies, and the ruby gem's patch every + // build that no other candidate is the patch of. + let platform_of = socket_patch_core::hosted::gem_fixes::GemLock::platform_of; + let own_patch = |base: &str, platform: &str| { + candidates + .iter() + .zip(&stripped) + .any(|((purl, _, _), other)| { + other == base && platform_of(purl).as_deref() == Some(platform) + }) + }; + let named: Vec> = named + .into_iter() + .zip(candidates.iter().zip(&stripped)) + .map(|(builds, ((purl, _, _), base))| { + let judged = |build: &socket_patch_core::formats::gem::GemBuild| match ( + platform_of(purl), + build.platform.as_deref(), + ) { + (Some(own), built) => built == Some(own.as_str()), + (None, Some(built)) => !own_patch(base, built), + (None, None) => true, + }; + builds.into_iter().filter(judged).collect() + }) + .collect(); let leaves: Vec = named .iter() .flatten() @@ -724,8 +753,8 @@ async fn gem_stale_install_warnings( .collect(); let unnamed: Vec = stripped .iter() - .zip(&named) - .filter(|(_, builds)| builds.is_empty()) + .zip(&unlocked) + .filter(|(_, unlocked)| **unlocked) .map(|(purl, _)| purl.clone()) .collect(); // Per home: each candidate's installed dirs. @@ -741,8 +770,9 @@ async fn gem_stale_install_warnings( .into_iter(); let dirs: Vec> = named .iter() - .map(|builds| { - if builds.is_empty() { + .zip(&unlocked) + .map(|(builds, unlocked)| { + if *unlocked { let pkg = first.next().flatten(); pkg.map(|pkg| pkg.path).into_iter().collect() } else { @@ -899,9 +929,9 @@ async fn gem_stale_install_warnings( let Some(want_shas) = gem_artifact_shas.get(&gem_sha_key(purl)) else { continue; }; - let builds = match named[index].as_slice() { - [] => GemBuild::ruby(purl).into_iter().collect(), - builds => builds.to_vec(), + let builds = match unlocked[index] { + true => GemBuild::ruby(purl).into_iter().collect(), + false => named[index].clone(), }; for cache_path in builds .iter() @@ -1021,36 +1051,39 @@ async fn refresh_stale_gems( // The patched archive: what bundler itself would download from the // patch registry (`/gems/.gem`), else the grant's own // artifact, verified against the sha256 the lock pins. A platform - // build (`--`) is the patch's prebuild for - // that platform, pinned by its own sha256; a platform gem declares no - // extensions, so replacing one builds nothing. + // build (`--`) is the gem of that platform's + // own patch, pinned by its own sha256; a platform gem declares no + // extensions, so replacing one builds nothing. The registry of any + // patch of the fix serves every build of it; the build's own patch is + // asked first. let wanted = |gem: &StaleGem| { let (name, version) = gem_sha_key(&gem.purl); let build = GemBuild::of_leaf(&gem.purl, &gem.leaf); let platform = build.as_ref().and_then(|build| build.platform.as_deref()); - let prebuilt: std::collections::BTreeSet = overrides - .iter() - .filter(|o| o.ecosystem == "gem" && o.name == name && o.version == version) - .filter_map(|o| o.registry_override.as_ref()) - .flat_map(|ro| &ro.identifiers.gem_platforms) - .filter(|prebuild| Some(prebuild.platform.as_str()) == platform) - .map(|prebuild| prebuild.gem_checksum_sha256.to_ascii_lowercase()) + let of_gem = || { + overrides + .iter() + .filter(|o| o.ecosystem == "gem" && o.name == name && o.version == version) + }; + let own = + |o: &&DepOverride| socket_patch_core::patch::redirect::gem_platform(o) == platform; + let of_build: std::collections::BTreeSet = of_gem() + .filter(own) + .filter_map(gem_patch_sha256) + .map(|sha| sha.to_ascii_lowercase()) .collect(); - let sha256 = if prebuilt.is_empty() { + let sha256 = if of_build.is_empty() { gem_artifact_shas .get(&(name.clone(), version.clone()))? .iter() .map(|sha| sha.to_ascii_lowercase()) .collect() } else { - prebuilt + of_build }; let file = format!("{}.gem", gem.leaf); let mut urls: Vec = Vec::new(); - for o in overrides - .iter() - .filter(|o| o.ecosystem == "gem" && o.name == name && o.version == version) - { + for o in of_gem().filter(own).chain(of_gem().filter(|o| !own(o))) { // Downloaded from where the patch server serves them: a // mirrored reference names the operator's mirror, which may // want credentials this run does not have. @@ -1137,6 +1170,8 @@ fn pipenv_probe_certain<'a>( socket_patch_core::patch::redirect::pipenv_lock_targets(files, &kept) } +use socket_patch_core::patch::redirect::gem_patch_sha256; + /// The `(name, version)` key the gem artifact-sha map uses — derived from /// the purl so overrides (which carry no purl) and confirmed purls meet on /// neutral ground. @@ -1177,7 +1212,7 @@ pub(super) async fn run_redirect( // entries the run took out. prune: bool, ) -> i32 { - let discovered = match discover_selected( + let mut discovered = match discover_selected( api_client, all_packages_with_patches, can_access_paid_patches, @@ -1186,6 +1221,10 @@ pub(super) async fn run_redirect( false, false, Some(&mut scan_result), + Some(super::GemFixScope { + cwd: &args.common.cwd, + recorded: &recorded.index, + }), ) .await { @@ -1201,6 +1240,7 @@ pub(super) async fn run_redirect( return code; } }; + let gem_references = std::mem::take(&mut discovered.references); let rows = super::classified_rows( stage, &discovered, @@ -1230,7 +1270,7 @@ pub(super) async fn run_redirect( stage, rows, prior, - references, + references: super::withdrawn::KnownReferences::with(references, gem_references), plan: Vec::new(), report: None, }), @@ -1487,6 +1527,18 @@ async fn run_redirect_selected_untracked( return 1; } }; + // The source patch of a gem fix whose platform builds alone were + // selected (a lock with no ruby-platform entry): its registry is + // the gem's one source, so its reference is asked for too. One + // more request, and only then; a failed one leaves the gem as it + // is, with the gem rewriter's warning. + let mut references = references; + let sources = engine::missing_gem_sources(&references); + if !sources.is_empty() { + if let Ok(found) = api_client.fetch_registry_references(&sources).await { + references.extend(found); + } + } // Deferred rows need no reference: a failed lookup that only hit // them builds nothing (and records no `not_found` for them). if rollout @@ -1610,7 +1662,11 @@ async fn run_redirect_selected_untracked( view, &origins, ) .await; - super::rollout::mark_pinned(&mut gate.rows, &pins); + super::rollout::mark_pinned( + &mut gate.rows, + &pins, + &engine::gem_fixes_of(&candidates), + ); } } } @@ -1987,6 +2043,20 @@ async fn run_redirect_selected_untracked( } } } + // A gem the lock names as platform builds is pinned to the registry of + // one fix, each build to the sha256 of its own patch: what that + // registry lists is read first (one small document per such gem), from + // the patch server also when the pin goes through a mirror. + let mut gem_indexes: Vec<(String, Result)> = Vec::new(); + for url in engine::gem_index_targets(&candidates, &read.files) { + status.set("Reading the gem patch registry"); + let document = socket_patch_core::hosted::gem_index::fetch_gem_index( + api_client, + &mirror_sources.fetch_url(&url), + ) + .await; + gem_indexes.push((url, document)); + } status.finish(); candidates.retain(|c| !unavailable_python_artifacts.contains(&c.dep.artifact_url)); // The Pipfile.lock reference shape depends on the installing Pipenv @@ -2093,6 +2163,8 @@ async fn run_redirect_selected_untracked( prior_discovery, } }; + let mut read = read; + engine::record_gem_index(&mut read, &gem_indexes); // The rollout gate plans again without its deferred rows: keep what // the second pass needs. let second_pass = rollout @@ -2133,7 +2205,9 @@ async fn run_redirect_selected_untracked( let deferred = gate.stage.deferred_keys(); skipped.extend(gate.stage.deferred_skips()); let before = candidates.len(); - candidates.retain(|c| !deferred.contains(&(sel_purl(c), c.dep.patch_uuid.clone()))); + engine::drop_deferred(&mut candidates, |c| { + deferred.contains(&(sel_purl(c), c.dep.patch_uuid.clone())) + }); if candidates.len() != before { done = crate::ui::busy( common, @@ -2161,12 +2235,13 @@ async fn run_redirect_selected_untracked( &mut skipped, ) .await; - let read = if candidates.is_empty() { + let mut read = if candidates.is_empty() { CandidateFiles::default() } else { engine::read_candidate_files(&view, &std::collections::BTreeSet::new(), &candidates) .await }; + engine::record_gem_index(&mut read, &gem_indexes); done = engine::rewrite( &view, read, @@ -2233,6 +2308,17 @@ async fn run_redirect_selected_untracked( } let rewrite = &done.rewrite; + // For each patch this run pinned a platform build of a gem to: the + // uuid the lock names for that gem, the patch whose registry is the + // gem's one source (the fix's source patch, or one build's own where + // that one is not available). Lockfile discovery reads that one uuid, + // so the in-run VEX and the "already hosted" count go by it. + let gem_fixes: std::collections::HashMap = rewrite + .gem_anchor_uuids + .iter() + .filter(|(uuid, anchor)| uuid != anchor) + .map(|(uuid, anchor)| (uuid.clone(), anchor.clone())) + .collect(); // Paths whose existence the commit below changes as discovery's reads // around the overlaid view (directory listings) see the disk: written // paths that are not a regular file there yet, and takeover-reverted @@ -2328,26 +2414,16 @@ async fn run_redirect_selected_untracked( // refresh: nothing was rewritten, so nothing is stale yet. // // purl-coordinate → every PATCHED .gem artifact's sha256 (registry - // override identifier, tarball integrity fallback; one per platform - // variant, and one per prebuild: the patched platform gem a lock that - // names platform builds is pinned to) — judges the installed and - // committed archives, and verifies the archive a refresh installs. + // override identifier, tarball integrity fallback): one per patch of + // the gem version, and each platform gem a lock names has a patch of + // its own — judges the installed and committed archives, and verifies + // the archive a refresh installs. let mut gem_artifact_shas: std::collections::BTreeMap< (String, String), std::collections::BTreeSet, > = std::collections::BTreeMap::new(); for o in done.overrides.iter().filter(|o| o.ecosystem == "gem") { - let sha = o - .registry_override - .as_ref() - .and_then(|ro| ro.identifiers.gem_checksum_sha256.clone()) - .or_else(|| o.integrity.sha256.clone()); - let prebuilds = o - .registry_override - .iter() - .flat_map(|ro| &ro.identifiers.gem_platforms) - .map(|prebuild| prebuild.gem_checksum_sha256.clone()); - for sha in sha.into_iter().chain(prebuilds) { + if let Some(sha) = gem_patch_sha256(o) { gem_artifact_shas .entry((o.name.clone(), o.version.clone())) .or_default() @@ -2534,6 +2610,9 @@ async fn run_redirect_selected_untracked( // v5 keeps no hosted ledger: the in-run attestation fetches the // records of the pins this run confirmed. params.hosted_uuids = confirmed.iter().map(|(_, uuid)| uuid.clone()).collect(); + // A gem the lock names as platform builds: each build is attested + // by its own patch, through the one pin the lock holds. + params.hosted_gem_fixes = gem_fixes.clone(); // The gem intake gate withholds every gem file. VEX independently // rediscovers older pins too, so a candidate-only set would miss some // refused hosted gems. Keep their actual installed-byte verification, @@ -2661,6 +2740,7 @@ async fn run_redirect_selected_untracked( &candidates, &confirmed, &skipped, + &engine::quiet_candidates(&candidates, selected, rewrite), ); // Sent before the result prints: a consumer that closes stdout early // (SIGPIPE on the first write) must not lose it. @@ -2771,14 +2851,27 @@ async fn run_redirect_selected_untracked( .into_iter() .map(|pin| pin.uuid) .collect(); - confirmed + let pinned = |uuid: &String| { + in_place.contains(uuid) + || gem_fixes + .get(uuid) + .is_some_and(|fix| in_place.contains(fix)) + }; + let already: Vec<(String, String)> = confirmed .iter() - .filter(|(_, uuid)| in_place.contains(uuid)) - .count() + .filter(|(_, uuid)| pinned(uuid)) + .cloned() + .collect(); + hosted_package_count(&already, &rewrite.confirmed_gem_uuids) }); println!( "{}", - format_hosted_summary(confirmed.len(), already, human_files.len(), common.dry_run) + format_hosted_summary( + hosted_package_count(&confirmed, &rewrite.confirmed_gem_uuids), + already, + human_files.len(), + common.dry_run + ) ); // Under it, one row per package on a hosted patch: what the // patch fixes and how much it leaves unpatched. The same call @@ -3476,6 +3569,25 @@ fn format_gem_hold_note( Some(note) } +/// How many packages the pins `confirmed` (`(purl, uuid)`) stand for: one +/// each, except that the builds of one gem the lock names as platform +/// builds are one package. Each of those builds is pinned to a patch of its +/// own (`gem_builds`: the uuids of such pins), all through one source. +fn hosted_package_count( + confirmed: &[(String, String)], + gem_builds: &std::collections::BTreeSet, +) -> usize { + let mut gems: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new(); + confirmed + .iter() + .filter(|(purl, uuid)| { + // The first pin of a gem's builds counts for the gem. + !gem_builds.contains(uuid) + || gems.insert(socket_patch_core::utils::purl::strip_purl_qualifiers(purl)) + }) + .count() +} + /// [`format_redirect_summary`] for a run that confirmed `confirmed` /// packages, `already` of them on their hosted patch before it started. /// Those were not switched by this run, so they leave the count and get a @@ -5734,6 +5846,34 @@ mod tests { } } + /// A gem the lock names as platform builds is pinned once per build, + /// each by its own patch, through one source: the summary counts it as + /// one package, beside every other pin. + #[test] + fn hosted_summary_counts_the_builds_of_one_gem_as_one_package() { + let pin = |purl: &str, uuid: &str| (purl.to_string(), uuid.to_string()); + let confirmed = [ + pin("pkg:gem/nokogiri@1.18.10?platform=arm64-darwin", "darwin"), + pin( + "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", + "linux", + ), + pin("pkg:gem/rack@3.1.8", "rack"), + pin("pkg:gem/ffi@1.17.2?platform=arm64-darwin", "ffi-darwin"), + pin("pkg:gem/ffi@1.17.2", "ffi"), + ]; + let builds: std::collections::BTreeSet = ["darwin", "linux", "ffi-darwin", "ffi"] + .iter() + .map(|uuid| uuid.to_string()) + .collect(); + assert_eq!(super::hosted_package_count(&confirmed, &builds), 3); + // No gem pinned by build: one package per pin. + assert_eq!( + super::hosted_package_count(&confirmed, &Default::default()), + 5 + ); + } + #[test] fn hosted_summary_does_not_count_packages_already_hosted_as_switched() { assert_eq!( diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 41fcf0150..b69e91304 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -17,6 +17,7 @@ use socket_patch_core::crawlers::ruby_crawler::{ config_path_ignored_warning, stale_plugin_registration_warning, }; use socket_patch_core::crawlers::Ecosystem; +use socket_patch_core::hosted::gem_fixes::GemLock; use socket_patch_core::ledgers::merge_ledger_records_for_updates; use socket_patch_core::manifest::schema::PatchManifest; use socket_patch_core::telemetry::{ @@ -553,6 +554,14 @@ async fn embed_vex_human( /// `false, false`). `json_warnings` is the JSON callers' envelope: a /// partial failure adds one [`PATCH_DETAILS_FAILED`] warning per failed /// package to it, and [`Discovered::failed`] lists each failed purl. +/// +/// `gem_fixes` is given by a run that changes what Bundler installs (hosted +/// and vendored mode): the selection is then settled for the gems the +/// project's Bundler lock names as platform builds, each of which has a +/// patch of its own ([`GemLock`]). Patches of platform gems the lock does +/// not name leave it, and every locked build of a gem takes the patch of +/// one fix. That reads the package references of the patches on offer for +/// those builds: one request, and none for a project with no such gem. #[allow(clippy::too_many_arguments)] async fn discover_selected( api_client: &socket_patch_core::api::client::ApiClient, @@ -563,6 +572,7 @@ async fn discover_selected( warn: bool, detail_error_line: bool, json_warnings: Option<&mut Envelope>, + gem_fixes: Option>, ) -> Result { let (all_search_results, failures) = fetch_patch_details(api_client, packages, show_progress, warn).await; @@ -583,7 +593,43 @@ async fn discover_selected( // Some queries failed, some succeeded: a `--json` run has no stderr // warning (`warn` is human-only), so each failed package becomes a // run-level `warnings[]` entry — never a silent drop from the envelope. - let offers = select_accessible(all_search_results, can_access_paid_patches, policy); + let mut offers = select_accessible(all_search_results, can_access_paid_patches, policy); + // `Some` for a run that settles the builds of a gem together. + let mut gem_builds = gem_fixes.is_some().then(HashMap::new); + // Said when the gems of such a run could not be settled. + let mut unsettled: Option = None; + let mut references = HashMap::new(); + if let Some(scope) = gem_fixes { + let view = socket_patch_core::vendor::lock_inventory::ProjectView::Disk(scope.cwd); + let lock = GemLock::read(&view, offers.unfiltered.keys().map(String::as_str)).await; + lock.narrow(&mut offers); + let uuids = lock.reference_uuids(&offers, scope.recorded); + if !uuids.is_empty() { + // The fix of such a gem is settled here, once, and the writers + // follow it. A failed lookup settles nothing, and a selection + // ranked purl by purl is no decision to write from: the gem is + // left as it is, and the run says so. + match api_client.fetch_registry_references(&uuids).await { + Ok(found) => { + gem_builds = Some(lock.choose(&mut offers, &found, scope.recorded)); + references = found; + references.retain(|uuid, _| uuids.contains(uuid)); + } + Err(error) => { + let left = lock.unsettle(&mut offers); + if !left.is_empty() { + unsettled = Some(socket_patch_core::hosted::gem_fixes::unsettled_detail( + &left, + &error.to_string(), + )); + } + } + } + } + } + if let (Some(detail), true, true) = (&unsettled, warn, json_warnings.is_none()) { + eprintln!("Warning: {detail}"); + } if let Some(env) = json_warnings { for (purl, e) in &failures { env.warn( @@ -591,15 +637,31 @@ async fn discover_selected( format!("could not fetch details for {purl}: {e}"), ); } + if let Some(detail) = &unsettled { + env.warn( + socket_patch_core::hosted::gem_fixes::GEM_FIX_UNSETTLED, + detail.as_str(), + ); + } policy.fold_into_envelope(env); } Ok(Discovered { offers, failed: failures, paid_access: can_access_paid_patches, + gem_builds, + references, }) } +/// What [`discover_selected`] settles the patches of platform-locked gems +/// by: the project (its Bundler lock) and what is recorded for it. +#[derive(Clone, Copy)] +struct GemFixScope<'a> { + cwd: &'a std::path::Path, + recorded: &'a rollout::RecordedIndex, +} + /// [`discover_selected`]'s result: the offers, each failed detail query /// as `(purl, error)` (a failure for a package with no recorded patch /// makes a capped run's data incomplete), and whether the account can @@ -608,6 +670,14 @@ struct Discovered { offers: rollout::Offers, failed: Vec<(String, String)>, paid_access: bool, + /// How the rows of the builds of a gem are classified, by patch purl, + /// where [`GemLock::choose`] decided them together. `None` for a run + /// that does not settle them (agent mode, a report-only scan): its + /// rows are classified each by its own purl. + gem_builds: Option>, + /// The package references read to settle them, by uuid: a hosted run + /// asks only about the selected uuids these do not answer. + references: HashMap, } impl Discovered { @@ -658,7 +728,12 @@ fn classified_rows( .map(|(purl, _)| purl.clone()) .collect(); stage.incomplete = rollout::lookup_incomplete(&recorded.index, &failed, batch_failed); - let rows = rollout::classify(&discovered.offers, &recorded.index, &stage.project); + let rows = rollout::classify_with( + &discovered.offers, + &recorded.index, + discovered.gem_builds.as_ref(), + &stage.project, + ); if let Some(env) = result { let updates = offer_updates(&rows, discovered, recorded, packages); env.set_extra("updates", serde_json::Value::Array(updates_json(&updates))); @@ -3728,6 +3803,7 @@ async fn scan_project( false, false, Some(&mut env), + None, ) .await { @@ -3759,6 +3835,7 @@ async fn scan_project( false, false, Some(&mut env), + None, ) .await { @@ -4011,6 +4088,9 @@ async fn scan_project( // of the packages it patched under its result line, and counts the // rest as left to patch. let mut plan = Vec::new(); + // The package references read to settle the patches of platform-locked + // gems, for the hosted flow to reuse. + let mut gem_references = HashMap::new(); let rows: Vec = if !fetch_details { plan = report::plan( &all_packages_with_patches, @@ -4034,10 +4114,16 @@ async fn scan_project( !silent, !hosted, None, + // Hosted and vendored runs change what Bundler installs. + (hosted || vendor).then_some(GemFixScope { + cwd: &args.common.cwd, + recorded: &recorded.index, + }), ) .await { - Ok(discovered) => { + Ok(mut discovered) => { + gem_references = std::mem::take(&mut discovered.references); let rows = classified_rows( &mut stage, &discovered, @@ -4116,7 +4202,7 @@ async fn scan_project( stage: &mut stage, rows, prior: prior_discovery, - references: sweep_references, + references: withdrawn::KnownReferences::with(sweep_references, gem_references), plan, report: Some(report), }), diff --git a/crates/socket-patch-cli/src/commands/scan/policy.rs b/crates/socket-patch-cli/src/commands/scan/policy.rs index 616ccac1a..8223bc5fa 100644 --- a/crates/socket-patch-cli/src/commands/scan/policy.rs +++ b/crates/socket-patch-cli/src/commands/scan/policy.rs @@ -683,6 +683,11 @@ impl ScanPolicy { } offers.selected.insert(purl.clone(), group[i].clone()); } + for (i, offer) in group.iter().enumerate() { + if admits(i).is_err() { + offers.refused.insert((purl.clone(), offer.uuid.clone())); + } + } for (offer, reason) in group.iter().zip(withheld) { if reason.is_some() { offers.withheld.insert((purl.clone(), offer.uuid.clone())); @@ -1158,6 +1163,42 @@ mod tests { .collect() } + /// What a later step may pick instead of the winner (a gem fix is taken + /// whole, for every build the lock names) is told which offers no + /// filter admits: the ones below the severity floor and the withheld + /// ones. Without that, a package the floor leaves out could be picked + /// back in. + #[test] + fn offers_name_what_no_filter_admits() { + let high = offer(B1, &[(HIGH, "high")]); + let critical = offer(A1, &[(CRIT, "critical")]); + let floor = "version: 2\npatches:\n minSeverity: critical\n"; + // Below the floor, alone: nothing selected, and the offer refused. + let policy = filtered_policy(floor, r#"{"version": 1}"#, None); + let offers = policy.select(vec![high.clone()]); + assert!(offers.selected.is_empty()); + assert_eq!( + offers.refused, + BTreeSet::from([(ALPHA.to_string(), B1.to_string())]) + ); + // Beside an admitted one: only the one below the floor is refused. + let offers = policy.select(vec![high.clone(), critical.clone()]); + assert_eq!(offers.selected[ALPHA].uuid, A1); + assert_eq!( + offers.refused, + BTreeSet::from([(ALPHA.to_string(), B1.to_string())]) + ); + // A withheld offer is refused too, and no policy refuses nothing. + let policy = filtered_policy("", &unreachable(CRIT), None); + let offers = policy.select(vec![critical.clone(), high.clone()]); + assert_eq!( + offers.refused, + BTreeSet::from([(ALPHA.to_string(), A1.to_string())]) + ); + let plain = filtered_policy("", r#"{"version": 1}"#, None); + assert!(plain.select(vec![critical, high]).refused.is_empty()); + } + /// The filter never changes how patches rank: a merged patch that fixes /// one needed advisory is wanted whole, its unreachable critical /// included, and wins as it always would. Only a patch that fixes diff --git a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs index ea9c84a1c..86a33d3f2 100644 --- a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs +++ b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs @@ -23,7 +23,7 @@ use socket_patch_core::manifest::schema::PatchRecord; use socket_patch_core::telemetry::{track_patch_vendor_failed, TelemetryAuth}; use socket_patch_core::utils::purl_key::PurlKey; use socket_patch_core::vendor::refusals::{vendor_refusals, RefusalScope, VendorRefusal}; -use socket_patch_core::vendor::{load_state, lookup_entry, save_state, VendorState}; +use socket_patch_core::vendor::{load_state, save_state, VendorState}; use std::collections::{HashMap, HashSet}; use std::path::Path; use std::time::Duration; @@ -357,7 +357,10 @@ async fn preview_vendor_with( let mut rows: Vec = selected .iter() .map(|p| { - let verdict = match lookup_entry(&state.entries, &p.purl) { + // The patch of a platform gem is recorded with its tree, in + // the entry of the gem's fix. + let vendored = socket_patch_core::vendor::vendored_uuid(&state.entries, &p.purl); + let verdict = match vendored { // Refusal takes priority: a preserved ledger can name this // UUID even after rollback has removed its live wiring. _ if refusals.contains_key(&p.purl) => { @@ -372,9 +375,9 @@ async fn preview_vendor_with( let (code, detail) = &pypi_refusals[&p.purl]; refuse(code, detail) } - Some(e) if e.uuid == p.uuid => PreviewVerdict::AlreadyVendored, - Some(e) => PreviewVerdict::WouldRevendor { - old_uuid: e.uuid.clone(), + Some(uuid) if uuid == p.uuid => PreviewVerdict::AlreadyVendored, + Some(uuid) => PreviewVerdict::WouldRevendor { + old_uuid: uuid.to_string(), }, None => PreviewVerdict::WouldVendor, }; @@ -836,6 +839,12 @@ async fn run_vendor_json_path( false, false, Some(&mut *env), + // Vendored mode changes what Bundler installs: one fix for every + // build of a gem the lock names as platform builds. + Some(super::GemFixScope { + cwd: &args.common.cwd, + recorded: &recorded.index, + }), ) .await { @@ -2450,7 +2459,8 @@ mod npm_lock_entry_refusal_tests { .to_string(), ); let state = load_state(root).await.expect("the seeded ledger parses"); - let entry = lookup_entry(&state.entries, LEFT_PAD).expect("seeded entry"); + let entry = socket_patch_core::vendor::lookup_entry(&state.entries, LEFT_PAD) + .expect("seeded entry"); assert!(entry.uuid == UUID && !entry.detached); let preview = preview_vendor_with(root, &[sel(LEFT_PAD)], &[], &HashMap::new()).await; match &preview.rows[0].verdict { diff --git a/crates/socket-patch-cli/src/commands/scan/withdrawn.rs b/crates/socket-patch-cli/src/commands/scan/withdrawn.rs index 6264b93a6..9294264ba 100644 --- a/crates/socket-patch-cli/src/commands/scan/withdrawn.rs +++ b/crates/socket-patch-cli/src/commands/scan/withdrawn.rs @@ -104,6 +104,22 @@ impl KnownReferences { KnownReferences(results) } + /// `known`, with the settled answers of `results` (a reference + /// response, by the uuid asked about) added: the references a scan read + /// to settle the patches of platform-locked gems. `None` when neither + /// holds an answer. + pub(crate) fn with( + known: Option, + results: HashMap, + ) -> Option { + let asked: Vec = results.keys().cloned().collect(); + let mut answers = Self::settled(&asked, results).0; + if let Some(known) = known { + answers.extend(known.0); + } + (!answers.is_empty()).then_some(KnownReferences(answers)) + } + /// The uuids in `uuids` with no known answer. pub(crate) fn unknown(&self, uuids: &[String]) -> Vec { uuids diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 4d255c855..2f9fbe63e 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -134,9 +134,10 @@ use socket_patch_core::vendor::refusals::refusal_is_benign; /// /// One unserved refusal is a skip with nothing to keep as well: /// [`vendor::VENDOR_PREBUILT_PLATFORM_PENDING`], a gem locked as platform -/// gems whose prebuild for one of the locked platforms the service does -/// not list. A prebuild is listed only once built, so the run cannot tell -/// "not yet" from "never", and the project is exactly as it was. +/// gems with no usable patch of the fix for one of the locked platforms. +/// A platform's patch is listed only once it is published and built, so +/// the run cannot tell "not yet" from "never", and the project is exactly +/// as it was. /// /// [`Discovery::vendor_entry_live`]: socket_patch_core::vex::discover::Discovery::vendor_entry_live async fn keep_older_vendored_patch( @@ -274,6 +275,7 @@ async fn takeover_dry_refusal( service: Option<&VendorServiceConfig>, pipenv_version: &tokio::sync::OnceCell>, installed_sites: &vendor::pypi::InstalledSiteListings, + gem_builds: &[vendor::gem::GemBuildPatch<'_>], ) -> Option<(&'static str, String)> { if !restored_text_previewable(restore) { return None; @@ -307,6 +309,7 @@ async fn takeover_dry_refusal( service, pipenv_version, installed_sites, + gem_builds, )) .await; drop(probe); @@ -359,6 +362,9 @@ pub(crate) async fn dispatch_vendor_one( service: Option<&VendorServiceConfig>, pipenv_version: &tokio::sync::OnceCell>, installed_sites: &vendor::pypi::InstalledSiteListings, + // gem: the patches of the platform gems of `purl`'s gem (see + // `GemUnits`); empty for every other purl. + gem_builds: &[vendor::gem::GemBuildPatch<'_>], ) -> Option { let eco = ecosystem_dir_for_purl(purl)?; // Before any backend write: a linked vendor dir is never ours, and the @@ -422,7 +428,21 @@ pub(crate) async fn dispatch_vendor_one( ) .await } - "gem" => vend!(vendor::gem::vendor_gem, pkg_path), + "gem" => { + vendor::gem::vendor_gem_builds( + purl, + pkg_path, + project_root, + record, + gem_builds, + sources, + vendored_at, + dry_run, + force, + service, + ) + .await + } "cargo" => vend!(vendor::cargo::vendor_cargo_crate, pkg_path), "golang" => vend!(vendor::golang::vendor_go_module, pkg_path), "composer" => vend!(vendor::composer_lock::vendor_composer, pkg_path), @@ -763,6 +783,37 @@ pub(crate) fn format_state_unreadable(err: &str) -> String { } } +/// `details` key of the events of a gem vendored as platform gems: the +/// uuid of the patch the gem was vendored through (the one its directory +/// and ledger entry are named after). Such a gem is ONE vendored package +/// with one event per platform gem, each under that gem's own patch and +/// each counted in `summary`, as hosted mode counts them; the key ties +/// those events together, so a count of packages takes them once. +const GEM_FIX_DETAIL: &str = "gemFix"; + +/// How many of the events `counted` picks stand for a gem that an earlier +/// one of them already stands for ([`GEM_FIX_DETAIL`]): what a count of +/// events is over a count of packages. +fn gem_fix_repeats(env: &Envelope, counted: impl Fn(&PatchEvent) -> bool) -> u32 { + let mut gems: HashSet<&str> = HashSet::new(); + env.events + .iter() + .filter(|event| counted(event)) + .filter_map(|event| event.details.as_ref()?.get(GEM_FIX_DETAIL)?.as_str()) + .filter(|fix| !gems.insert(fix)) + .count() as u32 +} + +/// How many packages `env` reports as vendored: its `applied` events, a +/// gem vendored as platform gems once. +fn vendored_packages(env: &Envelope) -> u32 { + env.summary + .applied + .saturating_sub(gem_fix_repeats(env, |event| { + event.action == PatchAction::Applied + })) +} + /// Per-outcome counts behind the human vendor summary line. #[derive(Debug, Default, Clone, PartialEq, Eq)] struct VendorTally { @@ -782,20 +833,23 @@ impl VendorTally { /// dry-run previews whose ledger entry already records the patch (the /// backends preview those as `verified`, like a fresh vendor). fn from_envelope(env: &Envelope, dry_run: bool, dry_in_sync: u32) -> Self { + // Packages, not events: a gem vendored as platform gems has one + // event per platform gem and is one package. + let repeats = |action: PatchAction| gem_fix_repeats(env, |e| e.action == action); let code_count = |code: &str| { - env.events - .iter() - .filter(|e| { - e.action == PatchAction::Skipped && e.error_code.as_deref() == Some(code) - }) - .count() as u32 + let coded = |e: &PatchEvent| { + e.action == PatchAction::Skipped && e.error_code.as_deref() == Some(code) + }; + let events = env.events.iter().filter(|e| coded(e)).count() as u32; + events.saturating_sub(gem_fix_repeats(env, coded)) }; let already_wet = code_count("already_vendored"); let not_installed = code_count("package_not_installed"); let vendored = if dry_run { - (env.summary.applied + env.summary.verified).saturating_sub(dry_in_sync) + (vendored_packages(env) + env.summary.verified) + .saturating_sub(repeats(PatchAction::Verified) + dry_in_sync) } else { - env.summary.applied + vendored_packages(env) }; VendorTally { vendored, @@ -804,8 +858,11 @@ impl VendorTally { skipped: env .summary .skipped - .saturating_sub(already_wet + not_installed), - failed: env.summary.failed, + .saturating_sub(repeats(PatchAction::Skipped) + already_wet + not_installed), + failed: env + .summary + .failed + .saturating_sub(repeats(PatchAction::Failed)), } } } @@ -1504,13 +1561,36 @@ async fn run_check(args: &VendorArgs) -> i32 { if !args.common.json && (!args.common.silent || event.action == PatchAction::Failed) { println!("{}: {}", key, event.reason.as_deref().unwrap_or("verified")); } - env.record(event); + // A gem vendored as platform gems: the verdict of its directory, + // once per platform gem and under that gem's own patch. + if entry.ecosystem == "gem" && !entry.gem_builds.is_empty() { + let base = strip_purl_qualifiers(&entry.base_purl); + for built in &entry.gem_builds { + let mut event = event.clone(); + event.purl = Some(format!("{base}?platform={}", built.platform)); + event.uuid = Some(built.uuid.clone()); + event.details = Some(serde_json::json!({ GEM_FIX_DETAIL: entry.uuid })); + env.record(event); + } + } else { + env.record(event); + } } + // A gem vendored as platform gems is one ledger entry, the patch its + // platform gems were built from, which records the patch of each + // platform's tree: the manifest records of those patches are vendored + // through that entry, and were checked with it above. + let built_through: HashSet<&str> = state + .entries + .values() + .flat_map(|entry| entry.gem_builds.iter().map(|built| built.uuid.as_str())) + .collect(); let mut unledgered_uuids: HashSet<&str> = HashSet::new(); for (key, record) in manifest .patches .iter() .filter(|(k, _)| !state.entries.contains_key(*k)) + .filter(|(_, record)| !built_through.contains(record.uuid.as_str())) { unledgered_uuids.insert(record.uuid.as_str()); if !args.common.json { @@ -2176,6 +2256,71 @@ async fn run_eject( } } + // A gem the lock names as platform gems is pinned through the registry + // of its fix's source patch, the one uuid the lock holds, while each + // platform gem has a patch of its own: the eject vendors those with it. + // A platform patch that cannot be read is left out, and the plan below + // then keeps the gem hosted, naming the platform. + // The lock is read once for all of them, and the lookups run together. + let gem_pins: Vec<&HostedPin> = pins + .iter() + .filter(|pin| pin.purl.starts_with("pkg:gem/") && records.contains_key(&pin.purl)) + .collect(); + let gem_lock = { + use socket_patch_core::hosted::gem_fixes::GemLock; + let view = socket_patch_core::vendor::lock_inventory::ProjectView::Disk(&common.cwd); + GemLock::read(&view, gem_pins.iter().map(|pin| pin.purl.as_str())).await + }; + let at_once = socket_patch_core::utils::concurrent::api_concurrency_for( + client.uses_public_proxy(), + gem_pins.len(), + ); + let mut siblings: Vec = Vec::new(); + { + let mut found = std::pin::pin!(ordered_concurrent(gem_pins.iter(), at_once, |pin| { + let (client, gem_lock) = (&client, &gem_lock); + async move { + socket_patch_core::hosted::gem_fixes::fix_siblings_in( + gem_lock, + client, + use_public_proxy, + &pin.purl, + &pin.uuid, + ) + .await + } + })); + while let Some(of_pin) = found.next().await { + siblings.extend(of_pin); + } + } + { + let at_once = socket_patch_core::utils::concurrent::api_concurrency_for( + client.uses_public_proxy(), + siblings.len(), + ); + let mut views = std::pin::pin!(ordered_concurrent(siblings.iter(), at_once, |sibling| { + let client = &client; + async move { client.fetch_patch(&sibling.uuid).await } + })); + while let Some(view) = views.next().await { + if let Ok(Some(patch)) = view { + let (purl, record) = + socket_patch_core::manifest::records::record_from_patch_response(&patch); + records.entry(purl).or_insert(record); + } + } + } + let mut eject_groups: HashMap> = HashMap::new(); + for purl in records.keys().filter(|purl| purl.starts_with("pkg:gem/")) { + eject_groups + .entry(strip_purl_qualifiers(purl).to_string()) + .or_default() + .push(purl.clone()); + } + // A hosted gem has no vendored copy to stay with. + let gem_units = GemUnits::with_lock(&gem_lock, &mut eject_groups, &records, &HashMap::new()); + // All or nothing: a record the API cannot serve refuses the whole eject // before anything is touched, so every package stays hosted. if !fetch_failures.is_empty() { @@ -2269,6 +2414,9 @@ async fn run_eject( Some(&service), &pipenv_version, &installed_sites, + // The patches of the platform gems of a gem locked as + // platform gems, read above. + &gem_units.patches(&pin.purl, &records), ) .await { @@ -2781,7 +2929,14 @@ pub(crate) async fn track_outcomes_for_vendor( ) .await; } else { - track_patch_vendored(command, env.summary.applied, dry_run, &patches, telemetry).await; + track_patch_vendored( + command, + vendored_packages(env), + dry_run, + &patches, + telemetry, + ) + .await; } } @@ -3275,6 +3430,156 @@ struct CandidateGates<'a> { refusals: &'a VendorRefusals, /// Whether the lockfiles still pin the purl hosted. hosted_pinned: &'a dyn Fn(&str) -> bool, + /// The gems vendored as platform gems: what is vendored for one is the + /// lock's to say, never the installed copy's. + gem_units: &'a GemUnits, +} + +/// The gems of a vendor run that the project's Bundler lock pins as +/// precompiled platform gems, each as one unit. Each platform gem of a fix +/// has a patch of its own (`pkg:gem/@?platform=`), +/// built from the patch of the ruby gem; the gem is vendored through that +/// patch (the unit's lead, whose uuid names the vendored dir), with one +/// tree per locked platform from that platform's patch. +#[derive(Debug, Default)] +struct GemUnits { + /// Lead purl → `(platform, patch purl)` of each platform gem the lock + /// names that this run has a patch for, in lock order. + builds: HashMap>, +} + +impl GemUnits { + /// Group the gem `records` of each gem the lock at `cwd` pins as + /// platform gems, and take the other patches of the gem out of + /// `variant_groups` (the candidates the vendor loop judges): the patch + /// of a locked platform is vendored with its unit's lead, and the patch + /// of a platform the lock does not name has nothing here to vendor. + /// The lead is the patch of the ruby gem where the run has it, else the + /// patch of the first locked platform; a gem already vendored + /// (`ledger`) keeps the lead it has while that patch is still one of + /// them, so its directory does not move. + async fn of( + cwd: &Path, + variant_groups: &mut HashMap>, + records: &HashMap, + ledger: &HashMap, + ) -> GemUnits { + use socket_patch_core::hosted::gem_fixes::GemLock; + let gems: Vec<&String> = variant_groups + .keys() + .filter(|base| base.starts_with("pkg:gem/")) + .collect(); + if gems.is_empty() { + return GemUnits::default(); + } + let view = socket_patch_core::vendor::lock_inventory::ProjectView::Disk(cwd); + let lock = GemLock::read(&view, gems.iter().map(|base| base.as_str())).await; + GemUnits::with_lock(&lock, variant_groups, records, ledger) + } + + /// [`Self::of`] against a lock already read for the gems of + /// `variant_groups`. + fn with_lock( + lock: &socket_patch_core::hosted::gem_fixes::GemLock, + variant_groups: &mut HashMap>, + records: &HashMap, + ledger: &HashMap, + ) -> GemUnits { + use socket_patch_core::hosted::gem_fixes::GemLock; + let mut units = GemUnits::default(); + for (base, candidates) in variant_groups.iter_mut() { + let platforms = lock.platforms_of(base); + if platforms.is_empty() { + continue; + } + let of_platform = |purl: &String| GemLock::platform_of(purl); + let builds: Vec<(String, String)> = platforms + .iter() + .filter_map(|platform| { + let mut patches: Vec<&String> = candidates + .iter() + .filter(|purl| of_platform(purl).as_deref() == Some(platform.as_str())) + .filter(|purl| records.contains_key(*purl)) + .collect(); + patches.sort(); + Some((platform.clone(), (*patches.first()?).clone())) + }) + .collect(); + // The patch the gem is vendored through, whose uuid names its + // directory. Any patch of the fix would do (each tree comes + // from its own platform's patch), so the choice only decides + // where the directory is. In order: the patch the ledger says + // the gem is vendored through, while it is still one of these + // (a copy that works is not moved); the patch of the ruby gem, + // which stays the same whichever platforms the lock names; and + // where that one is not available, the patch of the first + // platform the lock names. + let eligible = |purl: &&String| { + (of_platform(purl).is_none() && records.contains_key(*purl)) + || builds.iter().any(|(_, patch)| patch == *purl) + }; + let vendored_through = ledger + .values() + .find(|entry| entry.ecosystem == "gem" && PurlKey::same(&entry.base_purl, base)) + .map(|entry| entry.uuid.as_str()); + let in_use = candidates + .iter() + .filter(eligible) + .find(|purl| vendored_through.is_some_and(|uuid| records[*purl].uuid == uuid)); + let mut sources: Vec<&String> = candidates + .iter() + .filter(|purl| of_platform(purl).is_none() && records.contains_key(*purl)) + .collect(); + sources.sort(); + let first_build = builds.first().map(|(_, patch)| patch); + let Some(lead) = in_use.or(sources.first().copied()).or(first_build).cloned() else { + continue; + }; + // The other patches of the gem are vendored with the lead, or + // have nothing here to vendor: none is a candidate of its own. + match of_platform(&lead) { + Some(_) => candidates.retain(|purl| *purl == lead), + None => candidates.retain(|purl| of_platform(purl).is_none()), + } + units.builds.insert(lead, builds); + } + units + } + + /// Whether `purl` is the lead of a gem vendored as platform gems. + fn leads(&self, purl: &str) -> bool { + self.builds.contains_key(purl) + } + + /// The patches of the platform gems of the unit `lead` leads (none for + /// any other purl), for the backend. + fn patches<'r>( + &'r self, + lead: &str, + records: &'r HashMap, + ) -> Vec> { + self.builds + .get(lead) + .into_iter() + .flatten() + .filter_map(|(platform, purl)| { + Some(vendor::gem::GemBuildPatch { + platform: platform.as_str(), + record: records.get(purl)?, + }) + }) + .collect() + } + + /// `(patch purl, patch uuid)` of those platform patches. + fn members(&self, lead: &str, records: &HashMap) -> Vec<(String, String)> { + self.builds + .get(lead) + .into_iter() + .flatten() + .filter_map(|(_, purl)| Some((purl.clone(), records.get(purl)?.uuid.clone()))) + .collect() + } } impl<'a> CandidateGates<'a> { @@ -3298,8 +3603,11 @@ impl<'a> CandidateGates<'a> { // dir, so it only works when those files are EXTRACTED on disk. // Maven's patch targets live INSIDE the un-extracted jar and its // vendor takes the single main jar regardless, so it is skipped. + // Nor for a gem vendored as platform gems: the lock names the + // platforms, and the installed copy is one of them at most. let probe_applicable = group.is_variant_eco - && !matches!(Ecosystem::from_purl(candidate), Some(Ecosystem::Maven)); + && !matches!(Ecosystem::from_purl(candidate), Some(Ecosystem::Maven)) + && !self.gem_units.leads(candidate); // A deferred source was deferred because the ledger covers the // purl at this record's uuid: the variant the ledger vendored is // the installed one's by construction, so it answers the probe @@ -3709,6 +4017,13 @@ pub(crate) async fn vendor_records_reusing( } } + // A gem the Bundler lock pins as platform gems: each platform gem has a + // patch of its own, and the gem is vendored once, through the patch of + // its ruby gem, with the tree of each locked platform built from that + // platform's patch (see `GemUnits`). The platform patches are not + // candidates of their own. + let gem_units = GemUnits::of(&common.cwd, &mut variant_groups, records, &state.entries).await; + let mut matched: HashSet = HashSet::new(); // The lockfiles' hosted pins, for cross-mode takeovers: vendoring a purl @@ -3803,6 +4118,7 @@ pub(crate) async fn vendor_records_reusing( refused: &fetch_failed, refusals: &refusals, hosted_pinned: &hosted_pinned, + gem_units: &gem_units, }; // Candidates the loop refuses as `vendor_variant_ambiguous`, joined to // `fetch_failed` once the loop is done. @@ -3905,6 +4221,12 @@ pub(crate) async fn vendor_records_reusing( } else { pkg_source }; + // A gem vendored as platform gems: the patch of each platform + // gem the lock names, vendored with this candidate. + let gem_builds = gem_units.patches(candidate, records); + for (member, _) in gem_units.members(candidate, records) { + matched.insert(member); + } // Cross-mode takeover: vendoring over a LIVE hosted pin must // first restore the upstream registry entry (v5 keeps no hosted @@ -4087,6 +4409,7 @@ pub(crate) async fn vendor_records_reusing( service, &pipenv_version, &installed_sites, + &gem_builds, ) .await { @@ -4253,6 +4576,7 @@ pub(crate) async fn vendor_records_reusing( index + 1, total, )); + // Where this candidate's own outcome lands among the events. let outcome = dispatch_vendor_one( candidate, candidate_source, @@ -4265,6 +4589,7 @@ pub(crate) async fn vendor_records_reusing( service, &pipenv_version, &installed_sites, + &gem_builds, ) .await; status.finish(); @@ -4286,6 +4611,10 @@ pub(crate) async fn vendor_records_reusing( let outcome = keep_older_vendored_patch(outcome, &state, candidate, &record.uuid, common).await; + // Where the candidate's outcome event goes: each arm below + // records it first. Advisories about the candidate may sit + // before it (a takeover's restore is said above) and after it. + let outcome_event_at = env.events.len(); match outcome { None => { env.record( @@ -4445,6 +4774,39 @@ pub(crate) async fn vendor_records_reusing( } } } + // A gem vendored as platform gems is reported per platform + // gem, as hosted mode reports it: the outcome of the candidate + // it was vendored through becomes one event per platform gem, + // each under that gem's own patch and each counted. The + // candidate itself (the patch the directory is named after) + // keeps the event only when no platform gem has a patch here. + let members = gem_units.members(candidate, records); + let lead_at = env + .events + .get(outcome_event_at) + .filter(|event| event.purl.as_deref() == Some(candidate.as_str())) + .map(|_| outcome_event_at); + if let (Some(at), false) = (lead_at, members.is_empty()) { + let outcome = env.events[at].clone(); + for (nth, (member, uuid)) in members.into_iter().enumerate() { + let mut event = outcome.clone(); + event.purl = Some(member); + event.uuid = Some(uuid); + // The patch the gem was vendored through ties the + // events of one gem together. + let mut details = event + .details + .take() + .filter(serde_json::Value::is_object) + .unwrap_or_else(|| serde_json::json!({})); + details[GEM_FIX_DETAIL] = serde_json::json!(record.uuid); + event.details = Some(details); + match nth { + 0 => env.events[at] = event, + _ => env.record_at(at + nth, event), + } + } + } // The reverted hosted pin is gone either way: a vendored purl // is healed against its new wiring, a failed one against the // restored registry pin. @@ -4494,11 +4856,14 @@ pub(crate) async fn vendor_records_reusing( let group = match group { Some(group) if eject_group => { let ledger = load_state(&common.cwd).await.ok(); + // The patch of a platform gem is vendored as a tree of its + // fix's entry. let complete = !has_errors && records.keys().all(|purl| { - ledger - .as_ref() - .is_some_and(|l| lookup_entry(&l.entries, purl).is_some()) + ledger.as_ref().is_some_and(|l| { + lookup_entry(&l.entries, purl).is_some() + || vendor::lookup_gem_build(&l.entries, purl).is_some() + }) }); if complete { Some(group) @@ -5771,6 +6136,7 @@ mod dispatch_tests { Some(&service), &tokio::sync::OnceCell::new(), &Default::default(), + &[], ) .await; // The backend itself may refuse (nothing is installed in the @@ -5909,6 +6275,7 @@ mod plan_gate_tests { refused: &'a HashSet, ) -> CandidateGates<'a> { static NONE: VendorRefusals = VendorRefusals::new(); + static NO_GEM_UNITS: std::sync::OnceLock = std::sync::OnceLock::new(); CandidateGates { cwd: root, force: false, @@ -5916,6 +6283,7 @@ mod plan_gate_tests { refused, refusals: &NONE, hosted_pinned: &|_| false, + gem_units: NO_GEM_UNITS.get_or_init(GemUnits::default), } } @@ -8507,6 +8875,76 @@ mod ui_format_tests { ); } + /// A gem vendored as platform gems has one counted event per platform + /// gem, each under that gem's own patch, as in hosted mode. It is one + /// package all the same: the human tally takes the events of one gem + /// once, whatever their outcome. + #[test] + fn tally_counts_a_gem_vendored_as_platform_gems_once() { + let builds = |env: &mut Envelope, event: &PatchEvent| { + for (platform, uuid) in [("arm64-darwin", "darwin"), ("x86_64-linux-gnu", "linux")] { + let mut event = event.clone(); + event.purl = Some(format!("pkg:gem/nokogiri@1.18.10?platform={platform}")); + event.uuid = Some(uuid.to_string()); + event.details = Some(serde_json::json!({ GEM_FIX_DETAIL: "source" })); + env.record(event); + } + }; + let event = |action| PatchEvent::new(action, "pkg:gem/nokogiri@1.18.10?platform=ruby"); + let cases = [ + ( + event(PatchAction::Skipped).with_reason("already_vendored", "in sync"), + tally(0, 1, 0, 0, 0), + "1 package is already vendored; nothing to do.", + ), + ( + event(PatchAction::Applied), + tally(1, 0, 0, 0, 0), + "Vendored 1 package.", + ), + ( + event(PatchAction::Skipped).with_reason("vendor_prebuilt_platform_pending", "x"), + tally(0, 0, 0, 1, 0), + "Vendored 0 packages; 1 skipped.", + ), + ( + event(PatchAction::Failed).with_error("x", "y"), + tally(0, 0, 0, 0, 1), + "Vendored 0 packages; 1 failed.", + ), + ]; + for (outcome, expected, line) in cases { + let mut alone = Envelope::new(Command::Vendor); + builds(&mut alone, &outcome); + let counted = VendorTally::from_envelope(&alone, false, 0); + assert_eq!(counted, expected, "{line}"); + assert_eq!(format_vendor_summary(false, &counted), line); + // Each platform gem's event is counted in the summary. + let events = alone.summary.applied + alone.summary.skipped + alone.summary.failed; + assert_eq!(events, 2, "{line}"); + // Another package beside the gem is counted by itself. + alone.record(PatchEvent::new(PatchAction::Applied, "pkg:gem/rack@3.1.8")); + let mut with_rack = expected; + with_rack.vendored += 1; + assert_eq!( + VendorTally::from_envelope(&alone, false, 0), + with_rack, + "{line}" + ); + } + // A dry run previews each platform gem as `verified`. + let mut dry = Envelope::new(Command::Vendor); + builds(&mut dry, &event(PatchAction::Verified)); + assert_eq!( + VendorTally::from_envelope(&dry, true, 0), + tally(1, 0, 0, 0, 0) + ); + assert_eq!( + VendorTally::from_envelope(&dry, true, 1), + tally(0, 1, 0, 0, 0) + ); + } + #[test] fn advisories_are_tiered() { assert_eq!( diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 8e8f5adff..3ae8ed030 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -209,6 +209,7 @@ impl VexEmbedArgs { flag_prefix: "--vex-", npm_prior: None, hosted_uuids: Vec::new(), + hosted_gem_fixes: Default::default(), warnings_printed: Default::default(), } } @@ -279,6 +280,13 @@ pub(crate) struct VexBuildParams { /// standalone `vex` finds them through the lockfiles instead). Empty /// everywhere else. pub hosted_uuids: Vec, + /// Embedded hosted `scan --vex` only: for each patch this run pinned a + /// platform build of a gem to, the uuid the lock names for the gem + /// (the source patch of the fix, whose registry is the gem's one + /// source). The lock's one pin then attests every build's own patch + /// (see [`crate::commands::vex_sources::Sources::hosted_gem_fixes`]). + /// Empty everywhere else. + pub hosted_gem_fixes: std::collections::HashMap, /// The run's API client (see [`RunApiClient`]): seeded by a host /// command, else built at most once when the plan must fetch records. /// Telemetry reads its route when it exists. @@ -434,6 +442,7 @@ pub async fn run(args: VexArgs) -> i32 { flag_prefix: "--", npm_prior: None, hosted_uuids: Vec::new(), + hosted_gem_fixes: Default::default(), api_client: RunApiClient::new(), warnings_printed: Default::default(), }; @@ -2392,6 +2401,7 @@ async fn generate_vex_from_manifest_path_inner( discovery, // Their records join a pre-v5 ledger's as the hosted record source. hosted_uuids: params.hosted_uuids.clone(), + hosted_gem_fixes: params.hosted_gem_fixes.clone(), }; if sources.is_empty() { // A discovery diagnostic (an unparseable lock, a rejected reference) @@ -3825,6 +3835,7 @@ mod npm_prior_tests { flag_prefix: "--vex-", npm_prior: prior, hosted_uuids: Vec::new(), + hosted_gem_fixes: Default::default(), api_client: RunApiClient::new(), warnings_printed: Default::default(), }; diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index f650a8199..4d9a6f156 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -144,6 +144,16 @@ pub(crate) struct Sources { /// v5 hosted mode keeps no ledger, so [`plan`] fetches their records /// and files them as hosted records. Empty everywhere else. pub hosted_uuids: Vec, + /// Embedded hosted `scan --vex` only: patch uuid → the uuid the + /// Bundler lock names, for each patch that run pinned a platform build + /// of a gem to. Each platform gem of a fix has a patch of its own, and + /// the lock names the registry of one patch (the fix's source) for all + /// of them, so lockfile discovery yields that one uuid. [`plan`] reads + /// its reference as the wiring of every patch mapped to it here: each + /// build is then attested by the patch that patched it. Empty + /// everywhere else: a standalone `vex` attests the pin by the patch + /// the lock names. + pub hosted_gem_fixes: HashMap, } impl Sources { @@ -557,6 +567,7 @@ pub(crate) async fn plan( mut redirect, discovery, hosted_uuids, + hosted_gem_fixes, } = sources; let mut notes = Vec::new(); // The in-run hosted pins' records, filed under the API's purl like a @@ -587,6 +598,12 @@ pub(crate) async fn plan( let mut gated: Vec = Vec::new(); let mut cands = build_candidates(&manifest, &vendor, redirect.as_ref()); + // A gem vendored as platform gems is one ledger entry and one wired + // directory, and each of its trees is the platform gem of a patch of + // its own: each is attested by that patch, through the directory's one + // lockfile reference. + let mut gem_fixes = hosted_gem_fixes; + expand_vendored_gem_builds(&mut cands, &mut gem_fixes); let conflicts = wiring_conflicts(&discovery); if !conflicts.is_empty() { // Gate every candidate for a conflicting package BEFORE anything can @@ -627,7 +644,7 @@ pub(crate) async fn plan( }); } } - let superseded = attach_discovered(&mut cands, &discovery, &vendor, &conflicts); + let superseded = attach_discovered(&mut cands, &discovery, &vendor, &conflicts, &gem_fixes); // Wired, but a build bypasses the pin (`Unattested`: a Gradle lock // above the hosted base resolves the newer upstream release, a pnpm // bundled copy, a deno.lock copy, an npm shrinkwrap with no @@ -998,6 +1015,66 @@ fn build_candidates( .collect() } +/// Replace the candidate of each gem vendored as platform gems +/// ([`VendorEntry::gem_builds`]) with one candidate per platform gem: its +/// own patch purl (`…?platform=`), patch uuid and record, all +/// verified against the one vendored directory. `gem_fixes` gains each of +/// those uuids, mapped to the uuid the directory (and its lockfile +/// reference) is named after. A build the ledger holds no record for +/// stays with the entry's own candidate, which is then kept. +fn expand_vendored_gem_builds(cands: &mut Vec, gem_fixes: &mut HashMap) { + let mut expanded: Vec = Vec::new(); + let mut i = 0; + while i < cands.len() { + // The entry's own candidate (the patch the directory is named + // after), not a platform gem's that was given the entry below. + let own_uuid = cands[i].uuid.as_str(); + let unit = cands[i] + .vendor_entry + .as_ref() + .filter(|entry| entry.ecosystem == "gem" && !entry.gem_builds.is_empty()) + .filter(|entry| entry.uuid == own_uuid) + .filter(|entry| entry.gem_builds.iter().all(|built| built.record.is_some())) + .cloned(); + let Some(entry) = unit else { + i += 1; + continue; + }; + let lead = cands.remove(i); + let base = strip_purl_qualifiers(&entry.base_purl); + for built in &entry.gem_builds { + let key = format!("{base}?platform={}", built.platform); + gem_fixes.insert(built.uuid.clone(), entry.uuid.clone()); + // A manifest record of the same platform gem keeps its key. + let own = cands + .iter_mut() + .chain(expanded.iter_mut()) + .find(|c| PurlKey::qualified(&c.key) == PurlKey::qualified(&key)); + match own { + Some(cand) => { + if cand.uuid != built.uuid { + cand.uuid = built.uuid.clone(); + cand.record = built.record.clone(); + } + cand.vendor_entry = Some(entry.clone()); + } + None => expanded.push(Cand { + key, + uuid: built.uuid.clone(), + record: built.record.clone(), + alts: Vec::new(), + manifest_owned: lead.manifest_owned, + redirected: false, + vendor_entry: Some(entry.clone()), + discovered: Vec::new(), + lockfile_only: false, + }), + } + } + } + cands.extend(expanded); +} + /// Packages the discovered references wire to MORE than one patch uuid /// (any mix of modes and files), mapped to a human description of the /// disagreeing wiring (` (), …`) for the note. @@ -1058,6 +1135,7 @@ fn attach_discovered( discovery: &Discovery, vendor: &VendorState, conflicts: &BTreeMap, + gem_fixes: &HashMap, ) -> Vec<(String, String, String)> { let mut groups: BTreeMap<&str, Vec<&PatchedRef>> = BTreeMap::new(); for r in &discovery.refs { @@ -1072,7 +1150,13 @@ fn attach_discovered( let idxs: Vec = (0..cands.len()) .filter(|&i| PurlKey::same(&cands[i].key, pkg)) .collect(); - // Pass 1: the candidate already attests the wired uuid. + // Pass 1: the candidate already attests the wired uuid. A gem the + // lock names as platform builds is wired by one patch for every + // build (hosted: the registry of its fix's source patch; vendored: + // the directory named after it), each of which has a patch of its + // own (`gem_fixes`: `Sources::hosted_gem_fixes` and the vendor + // ledger's `gemBuilds`): the reference is the wiring of each of + // those patches. let mut unmatched: Vec<&PatchedRef> = Vec::new(); for r in &refs { let mut matched = false; @@ -1080,6 +1164,18 @@ fn attach_discovered( if cands[i].uuid == r.uuid { cands[i].discovered.push((*r).clone()); matched = true; + } else if gem_fixes.get(&cands[i].uuid) == Some(&r.uuid) { + // A hosted reference stands for the build's own patch; + // a vendored one keeps naming the directory it wires. + let uuid = match r.mode { + WiringMode::Hosted => cands[i].uuid.clone(), + _ => r.uuid.clone(), + }; + cands[i].discovered.push(PatchedRef { + uuid, + ..(*r).clone() + }); + matched = true; } } if !matched { @@ -1712,6 +1808,7 @@ mod tests { redirect: Some(redirect), discovery: discovery(vec![hosted_ref("pkg:npm/x@1.0.0", U2, true)]), hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert_eq!(plan.view.patches["pkg:npm/x@1.0.0"].uuid, U2); @@ -1768,6 +1865,7 @@ mod tests { redirect: Some(redirect), discovery: discovery(refs), hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert_eq!(plan.redirected, vec![key.to_string()], "{what}"); @@ -1792,6 +1890,7 @@ mod tests { redirect: None, discovery: discovery(vec![hosted_ref("pkg:npm/x@1.0.0", U2, true)]), hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert!( @@ -1828,6 +1927,7 @@ mod tests { redirect: Some(redirect), discovery: discovery(vec![hosted_ref("pkg:npm/x@1.0.0", U1, true)]), hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert!(plan @@ -1871,6 +1971,7 @@ mod tests { hosted_ref("pkg:npm/y@1.0.0", U2, true), ]), hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert_eq!(plan.gated, vec![failed("pkg:npm/x@1.0.0", WIRING_CONFLICT)]); @@ -1920,6 +2021,7 @@ mod tests { redirect: Some(redirect.clone()), discovery: Discovery::default(), hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }; let live = plan( &common(tmp.path()), @@ -2038,6 +2140,7 @@ mod tests { redirect: Some(redirect.clone()), discovery, hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }; // Control — nothing recognized: the hosted ledger's own recorded @@ -2125,6 +2228,7 @@ mod tests { redirect: Some(redirect), discovery: discovery(vec![hosted_ref("pkg:npm/x@1.0.0", U1, true)]), hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; let wiring = &plan.hosted["pkg:npm/x@1.0.0"]; @@ -2157,6 +2261,7 @@ mod tests { redirect: Some(redirect.clone()), discovery, hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }; let gated = plan( &common(tmp.path()), @@ -2258,6 +2363,7 @@ mod tests { redirect: Some(redirect.clone()), discovery, hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }; let mut both = discovery(vec![ go_ref(PURL, U1, "go.work"), @@ -2310,6 +2416,7 @@ mod tests { redirect: Some(redirect), discovery: found, hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert_eq!(plan.hosted[PURL].uuid, U1); @@ -2349,6 +2456,7 @@ mod tests { redirect: Some(redirect), discovery: found, hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }, &[], &RunApiClient::new(), @@ -2405,6 +2513,7 @@ mod tests { redirect: None, discovery: found, hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }, &[], &RunApiClient::new(), @@ -2455,6 +2564,7 @@ mod tests { redirect: None, discovery: found, hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }, &[], &RunApiClient::new(), @@ -2491,6 +2601,7 @@ mod tests { redirect: Some(redirect), discovery: Discovery::default(), hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }; let plan = plan( &common(tmp.path()), @@ -2568,6 +2679,7 @@ mod tests { // not a discovery input: the ledger fallback decides. discovery: Discovery::default(), hosted_uuids: Vec::new(), + hosted_gem_fixes: HashMap::new(), }; let plan = plan(&common(root), sources, &[], &RunApiClient::new()).await; if gemfile_wired { diff --git a/crates/socket-patch-cli/src/json_envelope.rs b/crates/socket-patch-cli/src/json_envelope.rs index dbd6da521..522846ad7 100644 --- a/crates/socket-patch-cli/src/json_envelope.rs +++ b/crates/socket-patch-cli/src/json_envelope.rs @@ -252,6 +252,17 @@ impl Envelope { self.events.push(event); } + /// [`Self::record`] with the event placed at `index` of `events` + /// instead of at their end: for an event that belongs beside one + /// already recorded. + pub fn record_at(&mut self, index: usize, event: PatchEvent) { + self.summary.bump(event.action); + if matches!(event.action, PatchAction::Failed) { + self.mark_partial_failure(); + } + self.events.insert(index.min(self.events.len()), event); + } + /// Re-tag every `Applied` event recorded at or after index `since` as /// `action` (`Skipped` or `Failed`) with `code` and `message`, keeping /// the summary in step: for packages a later step of the same run 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 93f020012..ca1ab670a 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -6961,107 +6961,24 @@ async fn platform_prebuilds_install_frozen_and_roll_back( mount_build_index(&server, "/upstream", &upstream_builds).await; let registry_base = format!("/patch-registry/gem/{TOKEN}/{UUID}"); let index_url = format!("{}{registry_base}/", server.uri()); + // A fix is one patch per gem: the ruby gem's ([`UUID`], the source) and + // one per platform gem, built from it. The registry of any of them + // lists and serves every gem of the fix. mount_build_index(&server, ®istry_base, &patched_builds).await; - Mock::given(method("POST")) - .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "packages": [{ - "purl": PURL, - "patches": [{ - "uuid": UUID, "purl": PURL, "tier": "free", - "cveIds": [], "ghsaIds": [], "severity": "high", - "title": "gem prebuild capstone fixture" - }] - }], - "canAccessPaidPatches": false, - }))) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path_regex(format!( - "^/v0/orgs/{ORG}/patches/by-package/.+$" - ))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "patches": [{ - "uuid": UUID, "purl": PURL, - "publishedAt": "2026-01-01T00:00:00Z", - "description": "x", "license": "MIT", "tier": "free", - "vulnerabilities": {} - }], - "canAccessPaidPatches": false, - }))) - .mount(&server) - .await; - // The reference of a patch that has prebuilds: a `gem-platform` - // artifact per prebuild (with `platform`) and `gemPlatforms` in the - // override's identifiers. - let hosted_url = format!( - "{}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{UUID}/{DEP}-{DEP_VERSION}.gem", - server.uri() - ); - let ruby_sha = sha_of(&patched_builds, DEP_VERSION); - let mut artifacts = vec![serde_json::json!({ - "kind": "tarball", "url": hosted_url, "integrity": { "sha256": ruby_sha } - })]; - let mut gem_platforms = Vec::new(); for platform in platforms { - let sha = sha_of(&patched_builds, &token(platform)); - artifacts.push(serde_json::json!({ - "kind": "gem-platform", "platform": platform, - "url": format!("{index_url}gems/{DEP}-{DEP_VERSION}-{platform}.gem"), - "contentType": "application/octet-stream", "sizeBytes": 4096, - "integrity": { "sha256": sha } - })); - gem_platforms.push(serde_json::json!({ "platform": platform, "gemChecksumSha256": sha })); + let base = format!("/patch-registry/gem/{TOKEN}/{}", platform_uuid(platform)); + mount_build_index(&server, &base, &patched_builds).await; } - Mock::given(method("POST")) - .and(path(format!("/v0/orgs/{ORG}/patches/package"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "results": { - UUID: { - "status": "granted", - "url": hosted_url, - "purl": PURL, - "artifacts": artifacts, - "registryOverride": { - "kind": "rubygems-compact-index", - "indexUrl": index_url, - "identifiers": { - "name": DEP, - "version": DEP_VERSION, - "gemChecksumSha256": ruby_sha, - "gemPlatforms": gem_platforms, - } - } - } - } - }))) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path(format!("/v0/orgs/{ORG}/patches/view/{UUID}"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "uuid": UUID, - "purl": PURL, - "publishedAt": "2026-01-01T00:00:00Z", - "files": { - "lib/vuln_gem.rb": { - "beforeHash": compute_git_sha256_from_bytes(orig.as_bytes()), - "afterHash": compute_git_sha256_from_bytes(patched.as_bytes()), - } - }, - "vulnerabilities": { - GHSA: { - "cves": ["CVE-2026-3333"], - "summary": "gem redirect capstone vuln", - "severity": "high", - "description": "d" - } - }, - "description": "x", "license": "MIT", "tier": "free" - }))) - .mount(&server) - .await; + let ruby_sha = sha_of(&patched_builds, DEP_VERSION); + mount_gem_fix_api( + &server, + &patched_builds, + &platforms, + (&orig, &patched), + false, + 5, + ) + .await; // 1. The project, locked and installed by the real bundler. let proj = tmp.path().join("proj"); @@ -7164,7 +7081,36 @@ async fn platform_prebuilds_install_frozen_and_roll_back( let env: serde_json::Value = serde_json::from_str(&stdout) .unwrap_or_else(|e| panic!("scan --json is not JSON: {e}\nstdout:\n{stdout}")); assert_eq!(env["status"], "success", "envelope: {env}"); - assert_eq!(env["summary"]["applied"], 1, "one gem redirected: {env}"); + // One pin per build the lock names, each under its own patch; the + // ruby-platform entry, where the lock has one, under the source patch. + let mut pinned: Vec<(String, String)> = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["details"]["mode"] == "hosted" && e["action"] == "applied") + .map(|e| { + let field = |key: &str| e[key].as_str().unwrap_or_default().to_string(); + (field("purl"), field("uuid")) + }) + .collect(); + pinned.sort(); + let mut expected: Vec<(String, String)> = platforms + .iter() + .map(|p| (format!("{PURL}?platform={p}"), platform_uuid(p))) + .collect(); + if ruby_entry { + expected.push((PURL.to_string(), UUID.to_string())); + } + expected.sort(); + assert_eq!( + pinned, expected, + "each locked build is pinned by its own patch: {env}" + ); + assert_eq!( + env["summary"]["applied"], + expected.len(), + "one applied event per locked build: {env}" + ); let warning_codes: Vec<&str> = env["warnings"] .as_array() .into_iter() @@ -7393,30 +7339,98 @@ async fn platform_prebuilds_install_frozen_and_roll_back( std::fs::write(&path, as_committed(&text)).unwrap(); } if takeover { - mount_vendored_platform_grant(&fx, &hosted_url, &patched_builds, &platforms).await; - let (code, stdout, stderr) = run_socket_env( - &fx.proj, - &[ - "get", - UUID, - "--mode", - "vendored", - "--yes", - "--json", - "--cwd", - proj_str, - "--api-url", - &api, - "--org", - ORG, - "--api-token", - "fake", - "--patch-server-url", - &api, - ], - &[("SOCKET_RUBYGEMS_URL", &upstream)], - ); + // From here on the references are the ones a vendored run takes: + // each gem's sha512 and its stub gemspec. + mount_gem_fix_api( + &fx._server, + &patched_builds, + &platforms, + (&orig, &patched), + true, + 1, + ) + .await; + // By the fix's source patch on one arm (`get ` takes the + // fix's patch of every locked build with it), by a scan on the + // other. + let by: &[&str] = match checksums_lock { + true => &["get", UUID], + false => &["scan"], + }; + let mut argv = by.to_vec(); + argv.extend([ + "--mode", + "vendored", + "--yes", + "--json", + "--cwd", + proj_str, + "--api-url", + &api, + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + &api, + ]); + let (code, stdout, stderr) = + run_socket_env(&fx.proj, &argv, &[("SOCKET_RUBYGEMS_URL", &upstream)]); assert_eq!(code, 0, "takeover:\nstdout:\n{stdout}\nstderr:\n{stderr}"); + // The takeover says once that it restored the hosted pin, and + // reports the vendoring per platform gem, each under its own + // patch: the restore's advisory names the same purl and comes + // first, and is not what each platform gem is reported as. + let taken: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("takeover --json is not JSON: {e}\nstdout:\n{stdout}")); + let events = |code: Option<&str>, action: &str| -> Vec<(String, String)> { + let mut found: Vec<(String, String)> = taken["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["action"] == action && e["details"]["mode"] == "vendored") + .filter(|e| code.is_none_or(|code| e["errorCode"] == code)) + .map(|e| { + let field = |key: &str| e[key].as_str().unwrap_or_default().to_string(); + (field("purl"), field("uuid")) + }) + .collect(); + found.sort(); + found + }; + let mut vendored: Vec<(String, String)> = platforms + .iter() + .map(|p| (format!("{PURL}?platform={p}"), platform_uuid(p))) + .collect(); + vendored.sort(); + assert_eq!(events(None, "applied"), vendored, "{taken}"); + assert_eq!( + events(Some("vendor_takeover_reverted_redirect"), "skipped").len(), + 1, + "the restore is said once: {taken}" + ); + // Each platform's tree is recorded with its own patch. + let ledger: serde_json::Value = serde_json::from_slice( + &std::fs::read(fx.proj.join(".socket/vendor/state.json")).expect("vendor ledger"), + ) + .unwrap(); + let mut built: Vec<(String, String)> = ledger["entries"] + .as_object() + .into_iter() + .flat_map(|entries| entries.values()) + .flat_map(|entry| entry["gemBuilds"].as_array().into_iter().flatten()) + .map(|b| { + let field = |key: &str| b[key].as_str().unwrap_or_default().to_string(); + (field("platform"), field("uuid")) + }) + .collect(); + built.sort(); + let mut expected: Vec<(String, String)> = platforms + .iter() + .map(|p| (p.to_string(), platform_uuid(p))) + .collect(); + expected.sort(); + assert_eq!(built, expected, "the ledger's platform trees: {ledger}"); let vendored_lock = std::fs::read_to_string(fx.proj.join("Gemfile.lock")).unwrap(); assert!( vendored_lock.starts_with("PATH\n remote: .socket/vendor/gem/"), @@ -7560,90 +7574,437 @@ async fn platform_prebuilds_install_frozen_and_roll_back( manifestless_vex_matrix(&fx, &fresh).await; } -/// The grant of [`UUID`] as the patch service answers it once the patch has -/// prebuilds a vendored run can take: the hosted reference -/// [`platform_prebuilds_install_frozen_and_roll_back`] mounts, plus each -/// prebuild's sha512 and its stub gemspec. -async fn mount_vendored_platform_grant( - fx: &RedirectFixture, - hosted_url: &str, +/// A lock that gains a platform after the gem moved to its patch registry, +/// against the REAL bundler: +/// +/// 1. the project locks the gem as this machine's platform gem alone, and +/// the hosted scan moves that one entry to the registry of the fix's +/// source patch, pinned to its own patch's sha256; +/// 2. `bundle lock --add-platform `: bundler resolves the gem +/// from its one source, the patch registry, which serves every gem of +/// the fix, and adds the foreign platform gem's entry itself, with +/// that gem's sha256. The Gemfile is not touched, and the lock gains +/// exactly that entry (its spec lines, its `PLATFORMS` line, its +/// `CHECKSUMS` line); +/// 3. the next scan leaves both files byte for byte as bundler wrote +/// them (the Gemfile's `source:` is the source patch's registry +/// whichever platforms the lock names) and reports the new build +/// under its own patch. +#[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_lock_gaining_a_platform_keeps_the_gemfile_line() { + let Some(bundler) = + bundler_e2e::gate("e2e_redirect_gem_build", "platform-gained", (2, 6), &|c| { + cache_env::isolate(c); + }) + else { + return; + }; + let (own, foreign) = own_and_foreign_platform(); + let platforms = [own.as_str(), foreign.as_str()]; + 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 { + [None, Some(own.as_str()), Some(foreign.as_str())] + .into_iter() + .map(|platform| IndexBuild { + name: DEP, + 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), + }) + .collect() + }; + let mut upstream_builds = builds_of("orig", &orig); + let patched_builds = builds_of("patched", &patched); + let token = |platform: &str| format!("{DEP_VERSION}-{platform}"); + let patched_sha = |platform: &str| { + let build = patched_builds.iter().find(|b| b.token == token(platform)); + sha256_hex(&build.expect("build").gem) + }; + + let server = MockServer::start().await; + upstream_builds.push(IndexBuild { + name: TRANSITIVE, + token: "1.0.0".to_string(), + deps: vec![], + gem: build_gem(&stage, TRANSITIVE, "1.0.0", "tiny_dep.rb", TINY_LIB, &[]), + }); + mount_build_index(&server, "/upstream", &upstream_builds).await; + let registry_base = format!("/patch-registry/gem/{TOKEN}/{UUID}"); + let index_url = format!("{}{registry_base}/", server.uri()); + mount_build_index(&server, ®istry_base, &patched_builds).await; + for platform in platforms { + let base = format!("/patch-registry/gem/{TOKEN}/{}", platform_uuid(platform)); + mount_build_index(&server, &base, &patched_builds).await; + } + mount_gem_fix_api( + &server, + &patched_builds, + &platforms, + (&orig, &patched), + false, + 5, + ) + .await; + + // 1. The project, locked for this machine's platform alone. + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write( + proj.join("Gemfile"), + format!("source \"{}/upstream\"\n\ngem \"{DEP}\"\n", server.uri()), + ) + .unwrap(); + let bundle_ok = |args: &[&str]| { + let out = bundle(&proj, args); + assert!( + out.status.success(), + "bundle {args:?} failed:\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); + }; + let config_args = bundler.config_local_args("path", "vendor/bundle"); + let config_args: Vec<&str> = config_args.iter().map(String::as_str).collect(); + bundle_ok(&config_args); + bundle_ok(&["install"]); + let read_lock = || std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + // Bundler adds platforms by itself where every locked gem has a gem + // for them (4.0.15 locks `x86_64-linux` beside this machine's, and + // `ruby`): the fixture starts from this machine's platform alone. + for platform in ["ruby", foreign.as_str()] { + if read_lock().contains(&format!("\n {platform}\n")) { + bundle_ok(&["lock", "--remove-platform", platform]); + } + } + bundle_ok(&["lock", "--add-checksums"]); + let pristine_gemfile = std::fs::read_to_string(proj.join("Gemfile")).unwrap(); + let pristine_lock = read_lock(); + let entries = |lock: &str| lock.matches(&format!(" {DEP} (")).count(); + assert!( + pristine_lock.contains(&format!(" {DEP} ({})\n", token(&own))) + && entries(&pristine_lock) == 1 + && pristine_lock.contains("\nCHECKSUMS\n"), + "the fixture lock must pin this machine's platform gem alone:\n{pristine_lock}" + ); + + let api = server.uri(); + let proj_str = proj.to_str().expect("utf8 tmp path"); + let scan = || { + let (code, stdout, stderr) = run_socket( + &proj, + &[ + "scan", + "--mode", + "hosted", + "--json", + "--yes", + "--cwd", + proj_str, + "--api-url", + &api, + "--org", + ORG, + "--api-token", + "fake", + ], + ); + assert_eq!( + code, 0, + "scan failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("scan --json is not JSON: {e}\nstdout:\n{stdout}")); + assert!( + !stdout.contains("redirect_gem_platform_unsupported"), + "every locked build has a patch of the fix: {env}" + ); + // `(purl, uuid)` of each hosted pin the run reports. + let mut pinned: Vec<(String, String)> = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| { + e["details"]["mode"] == "hosted" + && (e["action"] == "applied" || e["action"] == "verified") + }) + .map(|e| { + let field = |key: &str| e[key].as_str().unwrap_or_default().to_string(); + (field("purl"), field("uuid")) + }) + .collect(); + pinned.sort(); + pinned + }; + let pin_of = |platform: &str| { + ( + format!("{PURL}?platform={platform}"), + platform_uuid(platform), + ) + }; + + // The scan moves the one locked build, by its own patch, to the + // registry of the patch it was built from. + assert_eq!(scan(), [pin_of(&own)]); + let gemfile = std::fs::read_to_string(proj.join("Gemfile")).unwrap(); + assert_eq!( + gemfile, + with_source_option(&pristine_gemfile, &format!("gem \"{DEP}\""), &index_url), + "the Gemfile names the registry of the fix's source patch" + ); + let lock = read_lock(); + let section_of = |lock: &str| -> String { + lock.split("\n\n") + .find(|section| section.contains(&format!("remote: {index_url}"))) + .unwrap_or_else(|| panic!("no patch-registry GEM section:\n{lock}")) + .to_string() + }; + assert!( + entries(&lock) == 1 + && section_of(&lock).contains(&format!(" {DEP} ({})\n", token(&own))) + && lock.contains(&format!( + " {DEP} ({}) sha256={}\n", + token(&own), + patched_sha(&own) + )), + "the locked build sits under the patch registry, pinned to its own patch:\n{lock}" + ); + + // 2. Bundler adds the foreign platform from the gem's one source. + bundle_ok(&["lock", "--add-platform", &foreign]); + let gained = read_lock(); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + gemfile, + "adding a platform leaves the Gemfile alone" + ); + let added: Vec<&str> = gained + .lines() + .filter(|line| !lock.lines().any(|had| had == *line)) + .collect(); + let lost: Vec<&str> = lock + .lines() + .filter(|line| !gained.lines().any(|has| has == *line)) + .collect(); + assert_eq!( + added, + [ + format!(" {DEP} ({})", token(&foreign)), + format!(" {foreign}"), + format!( + " {DEP} ({}) sha256={}", + token(&foreign), + patched_sha(&foreign) + ), + ], + "the lock gains the one entry, from the patch registry:\n{gained}" + ); + assert_eq!(lost, Vec::<&str>::new(), "and loses nothing:\n{gained}"); + assert_eq!( + section_of(&gained).matches(&format!(" {DEP} (")).count(), + 2, + "both builds sit under the patch registry:\n{gained}" + ); + + // 3. The next scan changes neither file and reports both builds, each + // under its own patch. + let mut both = vec![pin_of(&own), pin_of(&foreign)]; + both.sort(); + assert_eq!(scan(), both); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + gemfile, + "the Gemfile line is unchanged" + ); + assert_eq!(read_lock(), gained, "the lock is as bundler wrote it"); +} + +/// The uuid of the patch of the platform gem `platform` of the fix whose +/// source patch is [`UUID`]: each platform gem has a patch of its own. +fn platform_uuid(platform: &str) -> String { + let tail = platform + .bytes() + .fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| { + (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3) + }); + format!("{}{:012x}", &UUID[..24], tail & 0xffff_ffff_ffff) +} + +/// 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 +/// wins), so a later mount can take over from an earlier one. +async fn mount_gem_fix_api( + server: &MockServer, patched_builds: &[IndexBuild], platforms: &[&str], + (orig, patched): (&str, &str), + vendorable: bool, + priority: u8, ) { - let server = &fx._server; let gem_of = |token: &str| { let build = patched_builds .iter() .find(|b| b.name == DEP && b.token == token); &build.expect("build").gem }; - let ruby_gem = gem_of(DEP_VERSION); - let ruby_sha = sha256_hex(ruby_gem); - let stubs = format!("/artifacts/{UUID}"); - let mut served = vec![( - format!("{DEP}-{DEP_VERSION}.gemspec"), - stub_gemspec(ruby_gem), - )]; - let mut artifacts = vec![ - serde_json::json!({ - "kind": "tarball", "url": hosted_url, - "integrity": { "sha512": sri(ruby_gem), "sha256": ruby_sha } - }), - serde_json::json!({ - "kind": "gem-stub-gemspec", - "url": format!("{}{stubs}/{DEP}-{DEP_VERSION}.gemspec", server.uri()), - "integrity": { "sha512": sri(&served[0].1) } - }), - ]; - let mut gem_platforms = Vec::new(); + // `(purl, uuid, token)` of each patch, the source first. + let mut patches: Vec<(String, String, String)> = + vec![(PURL.to_string(), UUID.to_string(), DEP_VERSION.to_string())]; for platform in platforms { - let leaf = format!("{DEP}-{DEP_VERSION}-{platform}"); - let gem = gem_of(&format!("{DEP_VERSION}-{platform}")); - let stub = stub_gemspec(gem); - let sha = sha256_hex(gem); - artifacts.push(serde_json::json!({ - "kind": "gem-platform", "platform": platform, - "url": format!("{}gems/{leaf}.gem", fx.index_url), - "contentType": "application/octet-stream", "sizeBytes": gem.len(), - "integrity": { "sha512": sri(gem), "sha256": sha } - })); - artifacts.push(serde_json::json!({ - "kind": "gem-platform-stub-gemspec", "platform": platform, - "url": format!("{}{stubs}/{leaf}.gemspec", server.uri()), - "integrity": { "sha512": sri(&stub) } - })); - gem_platforms.push(serde_json::json!({ "platform": platform, "gemChecksumSha256": sha })); - served.push((format!("{leaf}.gemspec"), stub)); + patches.push(( + format!("{PURL}?platform={platform}"), + platform_uuid(platform), + format!("{DEP_VERSION}-{platform}"), + )); } + let listed: Vec = patches + .iter() + .map(|(purl, uuid, _)| { + serde_json::json!({ + "uuid": uuid, "purl": purl, "tier": "free", + "cveIds": [], "ghsaIds": [], "severity": "high", + "title": "gem platform capstone fixture" + }) + }) + .collect(); Mock::given(method("POST")) - .and(path(format!("/v0/orgs/{ORG}/patches/package"))) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "results": { - UUID: { - "status": "granted", - "url": hosted_url, - "purl": PURL, - "artifacts": artifacts, - "registryOverride": { - "kind": "rubygems-compact-index", - "indexUrl": fx.index_url, - "identifiers": { - "name": DEP, - "version": DEP_VERSION, - "gemChecksumSha256": ruby_sha, - "gemPlatforms": gem_platforms, - } + "packages": [{ "purl": PURL, "patches": listed }], + "canAccessPaidPatches": false, + }))) + .with_priority(priority) + .mount(server) + .await; + let found: Vec = patches + .iter() + .map(|(purl, uuid, _)| { + serde_json::json!({ + "uuid": uuid, "purl": purl, + "publishedAt": "2026-01-01T00:00:00Z", + "description": "x", "license": "MIT", "tier": "free", + "vulnerabilities": {} + }) + }) + .collect(); + Mock::given(method("GET")) + .and(path_regex(format!( + "^/v0/orgs/{ORG}/patches/by-package/.+$" + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": found, + "canAccessPaidPatches": false, + }))) + .with_priority(priority) + .mount(server) + .await; + let mut results = serde_json::Map::new(); + for (purl, uuid, token) in &patches { + let gem = gem_of(token); + let leaf = format!("{DEP}-{token}"); + let url = format!( + "{}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{uuid}/{leaf}.gem", + server.uri() + ); + let mut artifacts = vec![serde_json::json!({ + "kind": "tarball", "url": url, + "integrity": { "sha256": sha256_hex(gem) } + })]; + if vendorable { + artifacts[0]["integrity"]["sha512"] = serde_json::json!(sri(gem)); + let stub = stub_gemspec(gem); + let stub_path = format!("/artifacts/{uuid}/{leaf}.gemspec"); + artifacts.push(serde_json::json!({ + "kind": "gem-stub-gemspec", + "url": format!("{}{stub_path}", server.uri()), + "integrity": { "sha512": sri(&stub) } + })); + Mock::given(method("GET")) + .and(path(stub_path)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(stub)) + .mount(server) + .await; + // The patched gem itself, where its reference says it is. + Mock::given(method("GET")) + .and(path(format!( + "/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{uuid}/{leaf}.gem" + ))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(gem.clone())) + .mount(server) + .await; + } + results.insert( + uuid.clone(), + serde_json::json!({ + "status": "granted", + "url": url, + "purl": purl, + "rebuiltFromUuid": (uuid.as_str() != UUID).then_some(UUID), + "artifacts": artifacts, + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": format!("{}/patch-registry/gem/{TOKEN}/{uuid}/", server.uri()), + "identifiers": { + "name": DEP, + "version": DEP_VERSION, + "gemChecksumSha256": sha256_hex(gem), } } - } - }))) - .with_priority(1) + }), + ); + } + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(move |request: &wiremock::Request| { + let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default(); + let asked: serde_json::Map = body["uuids"] + .as_array() + .into_iter() + .flatten() + .filter_map(|uuid| uuid.as_str()) + .filter_map(|uuid| Some((uuid.to_string(), results.get(uuid)?.clone()))) + .collect(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "results": asked })) + }) + .with_priority(priority) .mount(server) .await; - for (leaf, bytes) in served { + for (purl, uuid, _) in &patches { Mock::given(method("GET")) - .and(path(format!("{stubs}/{leaf}"))) - .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{uuid}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "uuid": uuid, + "purl": purl, + "publishedAt": "2026-01-01T00:00:00Z", + "files": { + "lib/vuln_gem.rb": { + "beforeHash": compute_git_sha256_from_bytes(orig.as_bytes()), + "afterHash": compute_git_sha256_from_bytes(patched.as_bytes()), + } + }, + "vulnerabilities": { + GHSA: { + "cves": ["CVE-2026-3333"], + "summary": "gem redirect capstone vuln", + "severity": "high", + "description": "d" + } + }, + "description": "x", "license": "MIT", "tier": "free" + }))) + .with_priority(priority) .mount(server) .await; } diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index 128d185b0..6e976daa7 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -101,24 +101,16 @@ async fn mount_api_for(server: &MockServer, view_budget: Option, patched_sh mount_api_with(server, view_budget, patched_sha, &[]).await; } -/// [`mount_api_for`] with the grant also listing `prebuilds`, the patch's -/// patched platform gems as `(platform, sha256)` (`gemPlatforms`; absent -/// from a grant that has none, as the service sends it). +/// [`mount_api_for`] with the fix also patching the platform gems +/// `builds`, as `(platform, sha256 of the patched platform gem)`: each has +/// a patch of its own ([`platform_patch_uuid`]), built from the ruby gem's. async fn mount_api_with( server: &MockServer, view_budget: Option, patched_sha: &str, - prebuilds: &[(&str, String)], + builds: &[(&str, String)], ) { - mount_patch_api_with( - server, - UUID, - PATCHED_LIB, - view_budget, - patched_sha, - prebuilds, - ) - .await; + mount_patch_api_with(server, UUID, PATCHED_LIB, view_budget, patched_sha, builds).await; } /// [`mount_api_for`] for the patch `uuid`, whose patched lib is @@ -133,87 +125,212 @@ async fn mount_patch_api( mount_patch_api_with(server, uuid, patched_lib, view_budget, patched_sha, &[]).await; } -/// The API of the patch `uuid`, whose patched lib is `patched_lib` and -/// whose grant lists `prebuilds`. +/// The uuid of the patch of the platform gem `platform` that was built +/// from the patch `source`: each platform gem of a fix has a patch of its +/// own. +fn platform_patch_uuid(source: &str, platform: &str) -> String { + let tail = platform + .bytes() + .fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| { + (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3) + }); + format!("{}{:012x}", &source[..24], tail & 0xffff_ffff_ffff) +} + +/// The purl the patch of the platform gem `platform` is recorded under. +fn platform_purl(platform: &str) -> String { + format!("{PURL}?platform={platform}") +} + +/// [`mount_fix_api`] with every patch of the fix usable. async fn mount_patch_api_with( server: &MockServer, uuid: &str, patched_lib: &str, view_budget: Option, patched_sha: &str, - prebuilds: &[(&str, String)], + builds: &[(&str, String)], ) { - let mut identifiers = serde_json::json!({ - "name": DEP, - "version": DEP_VERSION, - "gemChecksumSha256": patched_sha, - }); - if !prebuilds.is_empty() { - identifiers["gemPlatforms"] = prebuilds - .iter() - .map(|(platform, sha)| { - serde_json::json!({ "platform": platform, "gemChecksumSha256": sha }) - }) - .collect(); + mount_fix_api( + server, + uuid, + patched_lib, + view_budget, + patched_sha, + builds, + &[], + ) + .await; +} + +/// The API of the fix whose source patch is `uuid` (the ruby gem's patch, +/// whose patched lib is `patched_lib`), with a patch of its own for each +/// platform gem in `builds`. Every patch's registry lists every gem of the +/// fix. `unusable`: `(platform, status)` of the platform patches whose +/// package reference answers that status (`pending_build`, `withdrawn`) +/// with nothing to install, and which the registries then do not list; +/// the platform `ruby` names the fix's source patch. +async fn mount_fix_api( + server: &MockServer, + uuid: &str, + patched_lib: &str, + view_budget: Option, + patched_sha: &str, + builds: &[(&str, String)], + unusable: &[(&str, &str)], +) { + // `(purl, uuid, platform, sha256)` of each patch, the source first. + let mut patches: Vec<(String, String, Option<&str>, String)> = vec![( + PURL.to_string(), + uuid.to_string(), + None, + patched_sha.to_string(), + )]; + for (platform, sha) in builds { + patches.push(( + platform_purl(platform), + platform_patch_uuid(uuid, platform), + Some(platform), + sha.clone(), + )); } - let hosted_url = format!( - "{}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{uuid}/{DEP}-{DEP_VERSION}.gem", - server.uri() - ); - let index_url = format!("{}/patch-registry/gem/{TOKEN}/{uuid}/", server.uri()); + let index_of = |uuid: &str| format!("{}/patch-registry/gem/{TOKEN}/{uuid}/", server.uri()); + let listed: Vec = patches + .iter() + .map(|(purl, uuid, _, _)| { + serde_json::json!({ + "uuid": uuid, "purl": purl, "tier": "free", + "cveIds": [], "ghsaIds": [], "severity": "high", + "title": "gem stale-install fixture" + }) + }) + .collect(); Mock::given(method("POST")) .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "packages": [{ - "purl": PURL, - "patches": [{ - "uuid": uuid, "purl": PURL, "tier": "free", - "cveIds": [], "ghsaIds": [], "severity": "high", - "title": "gem stale-install fixture" - }] - }], + "packages": [{ "purl": PURL, "patches": listed }], "canAccessPaidPatches": false, }))) .mount(server) .await; + let found: Vec = patches + .iter() + .map(|(purl, uuid, _, _)| { + serde_json::json!({ + "uuid": uuid, "purl": purl, + "publishedAt": "2026-01-01T00:00:00Z", + "description": "x", "license": "MIT", "tier": "free", + "vulnerabilities": {} + }) + }) + .collect(); Mock::given(method("GET")) .and(path_regex(format!( "^/v0/orgs/{ORG}/patches/by-package/.+$" ))) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "patches": [{ - "uuid": uuid, "purl": PURL, - "publishedAt": "2026-01-01T00:00:00Z", - "description": "x", "license": "MIT", "tier": "free", - "vulnerabilities": {} - }], + "patches": found, "canAccessPaidPatches": false, }))) .mount(server) .await; - Mock::given(method("POST")) - .and(path(format!("/v0/orgs/{ORG}/patches/package"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "results": { - uuid: { - "status": "granted", + let mut results = serde_json::Map::new(); + let mut info = String::from("---\n"); + for (purl, patch_uuid, platform, sha) in &patches { + let token = match platform { + Some(platform) => format!("{DEP_VERSION}-{platform}"), + None => DEP_VERSION.to_string(), + }; + // `ruby` names the source patch, the ruby gem's. + let status = unusable + .iter() + .find(|(unusable, _)| *unusable == platform.unwrap_or("ruby")) + .map(|(_, status)| *status); + if let Some(status) = status { + results.insert(patch_uuid.clone(), serde_json::json!({ "status": status })); + continue; + } + info.push_str(&format!("{token} |checksum:{sha}\n")); + let hosted_url = format!( + "{}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{patch_uuid}/{DEP}-{token}.gem", + server.uri() + ); + results.insert( + patch_uuid.clone(), + serde_json::json!({ + "status": "granted", + "url": hosted_url, + "purl": purl, + "rebuiltFromUuid": platform.map(|_| uuid), + "artifacts": [{ + "kind": "tarball", "url": hosted_url, - "purl": PURL, - "artifacts": [{ - "kind": "tarball", - "url": hosted_url, - "integrity": { "sha256": patched_sha } - }], - "registryOverride": { - "kind": "rubygems-compact-index", - "indexUrl": index_url, - "identifiers": identifiers, - } + "integrity": { "sha256": sha } + }], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": index_of(patch_uuid), + "identifiers": { + "name": DEP, + "version": DEP_VERSION, + "gemChecksumSha256": sha, + }, } - } - }))) + }), + ); + } + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(move |request: &wiremock::Request| { + let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default(); + let asked: serde_json::Map = body["uuids"] + .as_array() + .into_iter() + .flatten() + .filter_map(|uuid| uuid.as_str()) + .filter_map(|uuid| Some((uuid.to_string(), results.get(uuid)?.clone()))) + .collect(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "results": asked })) + }) .mount(server) .await; + // What each patch's registry lists: every gem of the fix. + for (_, patch_uuid, _, _) in &patches { + Mock::given(method("GET")) + .and(path(format!( + "/patch-registry/gem/{TOKEN}/{patch_uuid}/info/{DEP}" + ))) + .respond_with(ResponseTemplate::new(200).set_body_string(info.clone())) + .mount(server) + .await; + } + // The view of a platform gem's patch: the same lib, under its purl. + for (purl, patch_uuid, _, _) in patches.iter().skip(1) { + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{patch_uuid}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "uuid": patch_uuid, + "purl": purl, + "publishedAt": "2026-01-01T00:00:00Z", + "files": { + "lib/stale_probe_gem.rb": { + "beforeHash": compute_git_sha256_from_bytes(UPSTREAM_LIB.as_bytes()), + "afterHash": compute_git_sha256_from_bytes(patched_lib.as_bytes()), + } + }, + "vulnerabilities": { + GHSA: { + "cves": ["CVE-2026-4444"], + "summary": "gem stale-install fixture vuln", + "severity": "high", + "description": "d" + } + }, + "description": "x", "license": "MIT", "tier": "free" + }))) + .mount(server) + .await; + } let view = Mock::given(method("GET")) .and(path(format!("/v0/orgs/{ORG}/patches/view/{uuid}"))) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ @@ -2580,7 +2697,7 @@ async fn refresh_replaces_a_stale_platform_install_with_its_prebuild() { let (code, stdout, stderr) = common::run_with_env(&proj, &args, &[]); let env = common::parse_json_envelope(&stdout); assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); - assert_eq!(hosted_pinned(&env), 1, "{env}"); + assert_eq!(hosted_pinned(&env), 2, "one pin per locked build: {env}"); assert!( !stdout.contains("redirect_gem_platform_unsupported"), "every locked platform has a prebuild: {env}" @@ -2799,7 +2916,7 @@ async fn stale_guard_follows_the_builds_the_lock_names_in_a_home_with_both() { common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &path_env); let env = common::parse_json_envelope(&stdout); assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); - assert_eq!(hosted_pinned(&env), 1, "{env}"); + assert_eq!(hosted_pinned(&env), 2, "one pin per locked build: {env}"); let stale = stale_warnings(&env); assert_eq!(stale.len(), 1, "one stale copy, the platform build: {env}"); assert!( @@ -2885,9 +3002,9 @@ async fn stale_guard_follows_the_builds_the_lock_names_in_a_home_with_both() { /// A fresh checkout: nothing is installed, and the lock names the gem only /// as platform builds. The hosted scan reads the gem from the lock alone -/// and pins every build to its prebuild. With a prebuild missing for one -/// locked platform it pins nothing, says which, and leaves both files as -/// they were. +/// and pins every build to its own patch, through the registry of the +/// patch they were built from. With no patch for one locked platform it +/// pins nothing, says which, and leaves both files as they were. #[tokio::test(flavor = "multi_thread")] async fn gem_hosted_scan_pins_platform_builds_from_the_lock_alone() { let ruby_sha = sha256_of(&real_gem(PATCHED_LIB)); @@ -2917,7 +3034,25 @@ async fn gem_hosted_scan_pins_platform_builds_from_the_lock_alone() { let after = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); let skipped = warnings_with_code(&env, "redirect_gem_platform_unsupported"); if complete { - assert_eq!(hosted_pinned(&env), 1, "{env}"); + // One pin per locked build, each by the patch of that build. + let mut pinned: Vec<(String, String)> = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["details"]["mode"] == "hosted" && e["action"] == "applied") + .map(|e| { + let field = |key: &str| e[key].as_str().unwrap_or_default().to_string(); + (field("purl"), field("uuid")) + }) + .collect(); + pinned.sort(); + let mut expected: Vec<(String, String)> = [PLATFORM, OTHER_PLATFORM] + .iter() + .map(|p| (platform_purl(p), platform_patch_uuid(UUID, p))) + .collect(); + expected.sort(); + assert_eq!(pinned, expected, "{env}"); + assert_eq!(env["summary"]["applied"], 2, "one per locked build: {env}"); assert!(skipped.is_empty(), "{env}"); assert!( after.contains(&format!( @@ -2944,8 +3079,9 @@ async fn gem_hosted_scan_pins_platform_builds_from_the_lock_alone() { }; assert!( detail.contains(&format!( - "no patched build for `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})`" - )) && detail.contains(&format!("patched builds for {PLATFORM}")), + "no patch is available for `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})` (one \ + is available for `{DEP} ({DEP_VERSION}-{PLATFORM})`)" + )), "{detail}" ); assert_eq!(after, lock, "the lock is untouched"); @@ -2958,8 +3094,747 @@ async fn gem_hosted_scan_pins_platform_builds_from_the_lock_alone() { } } +/// A locked platform whose patch cannot be used: its package reference +/// says the patched gem is still being built, or that the patch was +/// withdrawn. The gem is skipped whole and neither file changes. The +/// warning names the build with no patch, and that patch's own event says +/// what its reference answered. +#[tokio::test(flavor = "multi_thread")] +async fn gem_hosted_scan_skips_a_gem_whose_platform_patch_is_not_usable() { + let ruby_sha = sha256_of(&real_gem(PATCHED_LIB)); + let builds = [ + (PLATFORM, sha256_of(&real_gem_for(PATCHED_LIB, PLATFORM))), + ( + OTHER_PLATFORM, + sha256_of(&real_gem_for(PATCHED_LIB, OTHER_PLATFORM)), + ), + ]; + for status in ["pending_build", "withdrawn"] { + let server = MockServer::start().await; + mount_fix_api( + &server, + UUID, + PATCHED_LIB, + None, + &ruby_sha, + &builds, + &[(OTHER_PLATFORM, status)], + ) + .await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + let gemfile = + format!("source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"); + let lock = platform_lock(&"1".repeat(64), &"2".repeat(64)); + std::fs::write(proj.join("Gemfile"), &gemfile).unwrap(); + std::fs::write(proj.join("Gemfile.lock"), &lock).unwrap(); + + let (code, stdout, stderr) = hosted_scan_json(&proj, &server.uri()); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{status}: {env}\nstderr:\n{stderr}"); + assert_eq!(hosted_pinned(&env), 0, "{status}: {env}"); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + lock, + "{status}: the lock is untouched" + ); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + gemfile, + "{status}: the Gemfile is untouched" + ); + let skipped = warnings_with_code(&env, "redirect_gem_platform_unsupported"); + let [detail] = skipped.as_slice() else { + panic!("{status}: one platform skip: {env}"); + }; + assert!( + detail.contains(&format!( + "no patch is available for `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})` (one is \ + available for `{DEP} ({DEP_VERSION}-{PLATFORM})`)" + )), + "{status}: {detail}" + ); + // The patch that could not be used is accounted for by itself. + let own: Vec<&serde_json::Value> = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["uuid"] == platform_patch_uuid(UUID, OTHER_PLATFORM).as_str()) + .collect(); + let [event] = own.as_slice() else { + panic!("{status}: one event for the unusable patch: {env}"); + }; + assert_eq!(event["action"], "skipped", "{status}: {event}"); + assert_eq!( + event["purl"], + platform_purl(OTHER_PLATFORM).as_str(), + "{status}: {event}" + ); + assert_eq!(event["errorCode"], status, "{status}: {event}"); + } +} + +/// `get --mode hosted` of a gem locked as platform builds takes the whole +/// fix: asked for the fix's source patch, for one platform's patch or for +/// the package, the run pins every locked build to its own patch, through +/// the source patch's registry. +#[tokio::test(flavor = "multi_thread")] +async fn gem_hosted_get_takes_every_locked_build_of_the_fix() { + let ruby_sha = sha256_of(&real_gem(PATCHED_LIB)); + let builds = [ + (PLATFORM, sha256_of(&real_gem_for(PATCHED_LIB, PLATFORM))), + ( + OTHER_PLATFORM, + sha256_of(&real_gem_for(PATCHED_LIB, OTHER_PLATFORM)), + ), + ]; + for asked in [ + UUID.to_string(), + platform_patch_uuid(UUID, PLATFORM), + PURL.to_string(), + ] { + let server = MockServer::start().await; + mount_api_with(&server, None, &ruby_sha, &builds).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write( + proj.join("Gemfile"), + format!("source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"), + ) + .unwrap(); + std::fs::write( + proj.join("Gemfile.lock"), + platform_lock(&"1".repeat(64), &"2".repeat(64)), + ) + .unwrap(); + let uri = server.uri(); + let (code, stdout, stderr) = common::run_with_env( + &proj, + &[ + "get", + asked.as_str(), + "--mode", + "hosted", + "--json", + "--yes", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + ], + &[], + ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{asked}: {env}\nstderr:\n{stderr}"); + let mut pinned: Vec<(String, String)> = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["details"]["mode"] == "hosted" && e["action"] == "applied") + .map(|e| { + let field = |key: &str| e[key].as_str().unwrap_or_default().to_string(); + (field("purl"), field("uuid")) + }) + .collect(); + pinned.sort(); + let mut expected: Vec<(String, String)> = [PLATFORM, OTHER_PLATFORM] + .iter() + .map(|p| (platform_purl(p), platform_patch_uuid(UUID, p))) + .collect(); + expected.sort(); + assert_eq!(pinned, expected, "{asked}: {env}"); + let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + assert!( + lock.contains(&format!( + "/patch-registry/gem/{TOKEN}/{UUID}/\n specs:\n {DEP} \ + ({DEP_VERSION}-{PLATFORM})\n {DEP} ({DEP_VERSION}-{OTHER_PLATFORM})\n" + )), + "{asked}: both builds sit under the source patch's registry:\n{lock}" + ); + assert!( + warnings_with_code(&env, "redirect_gem_platform_unsupported").is_empty(), + "{asked}: {env}" + ); + } +} + +/// `get` in hosted mode settles a platform-locked gem's fix BEFORE it says +/// anything of its selection. Two fixes cover every locked build, and the +/// per-purl ranking takes fix A for the ruby gem and one platform and fix +/// B for the other platform (its patch there is the newer one). The run +/// uses fix A for every build, so: +/// +/// * the `Selected:` echo lists fix A's patch of that platform, the UUID +/// the run pins, not the ranking's; +/// * the merged-patch note is computed from that selection: every build +/// is on fix A, so the gem waits for what fix B fixes. Computed from the +/// ranking's mix it would find nothing every build leaves, and say +/// nothing. +#[tokio::test(flavor = "multi_thread")] +async fn gem_hosted_get_echoes_and_judges_the_settled_selection() { + const UUID_B: &str = "9b0c1d2e-3f4a-4b5c-8d6e-8f9a0b1c2d3e"; + const FIXED_BY_A: &str = "GHSA-aaaa-aaaa-aaaa"; + const FIXED_BY_B: &str = "GHSA-bbbb-bbbb-bbbb"; + let server = MockServer::start().await; + let sha_of = |platform: Option<&str>| match platform { + Some(platform) => sha256_of(&real_gem_for(PATCHED_LIB, platform)), + None => sha256_of(&real_gem(PATCHED_LIB)), + }; + // Each fix: its source patch and a patch per platform gem, with the + // date that ranks it within its purl (the newer one wins). + let fixes = [ + ( + UUID, + FIXED_BY_A, + [ + (None, "2026-03-01T00:00:00Z"), + (Some(PLATFORM), "2026-03-01T00:00:00Z"), + (Some(OTHER_PLATFORM), "2026-01-01T00:00:00Z"), + ], + ), + ( + UUID_B, + FIXED_BY_B, + [ + (None, "2026-02-01T00:00:00Z"), + (Some(PLATFORM), "2026-02-01T00:00:00Z"), + (Some(OTHER_PLATFORM), "2026-04-01T00:00:00Z"), + ], + ), + ]; + let uuid_of = |fix: &str, platform: Option<&str>| match platform { + Some(platform) => platform_patch_uuid(fix, platform), + None => fix.to_string(), + }; + let mut found = Vec::new(); + let mut results = serde_json::Map::new(); + for (fix, advisory, gems) in &fixes { + let mut listed = String::from("---\n"); + for (platform, published) in gems { + let uuid = uuid_of(fix, *platform); + let (purl, token) = match platform { + Some(platform) => (platform_purl(platform), format!("{DEP_VERSION}-{platform}")), + None => (PURL.to_string(), DEP_VERSION.to_string()), + }; + let sha = sha_of(*platform); + listed.push_str(&format!("{token} |checksum:{sha}\n")); + found.push(serde_json::json!({ + "uuid": uuid, "purl": purl, "publishedAt": published, + "description": "x", "license": "MIT", "tier": "free", + "vulnerabilities": { *advisory: { + "cves": [], "summary": "s", "severity": "critical", "description": "d" + }} + })); + let url = format!( + "{}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{uuid}/{DEP}-{token}.gem", + server.uri() + ); + results.insert( + uuid.clone(), + serde_json::json!({ + "status": "granted", + "url": url, + "purl": purl, + "rebuiltFromUuid": platform.map(|_| *fix), + "artifacts": [{ + "kind": "tarball", "url": url, "integrity": { "sha256": sha } + }], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": format!( + "{}/patch-registry/gem/{TOKEN}/{uuid}/", + server.uri() + ), + "identifiers": { + "name": DEP, "version": DEP_VERSION, "gemChecksumSha256": sha, + }, + } + }), + ); + } + // Every registry of a fix lists every gem of it. + for (platform, _) in gems { + let uuid = uuid_of(fix, *platform); + Mock::given(method("GET")) + .and(path(format!( + "/patch-registry/gem/{TOKEN}/{uuid}/info/{DEP}" + ))) + .respond_with(ResponseTemplate::new(200).set_body_string(listed.clone())) + .mount(&server) + .await; + } + } + Mock::given(method("GET")) + .and(path_regex(format!( + "^/v0/orgs/{ORG}/patches/by-package/.+$" + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": found, + "canAccessPaidPatches": false, + }))) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(move |request: &wiremock::Request| { + let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default(); + let asked: serde_json::Map = body["uuids"] + .as_array() + .into_iter() + .flatten() + .filter_map(|uuid| uuid.as_str()) + .filter_map(|uuid| Some((uuid.to_string(), results.get(uuid)?.clone()))) + .collect(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "results": asked })) + }) + .mount(&server) + .await; + + let (a_arm, a_linux, b_linux) = ( + uuid_of(UUID, Some(PLATFORM)), + uuid_of(UUID, Some(OTHER_PLATFORM)), + uuid_of(UUID_B, Some(OTHER_PLATFORM)), + ); + let uri = server.uri(); + let get = |json: bool| { + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write( + proj.join("Gemfile"), + format!("source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"), + ) + .unwrap(); + std::fs::write( + proj.join("Gemfile.lock"), + platform_lock(&"1".repeat(64), &"2".repeat(64)), + ) + .unwrap(); + let mut args = vec!["get", PURL, "--mode", "hosted", "--yes"]; + if json { + args.push("--json"); + } + let cwd = proj.to_str().unwrap().to_string(); + args.extend([ + "--cwd", + cwd.as_str(), + "--api-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + ]); + let (code, stdout, stderr) = common::run_with_env(&proj, &args, &[]); + let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + (code, stdout, stderr, lock) + }; + + // Human mode: the echo, and the note under it. + let (code, stdout, stderr, lock) = get(false); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let echo = stdout + .split_once("Selected:\n") + .and_then(|(_, rest)| rest.split_once("\n\n")) + .map(|(echo, _)| echo) + .unwrap_or_else(|| panic!("a `Selected:` block:\n{stdout}")); + // The echo shows each patch by the first group of its uuid, which is + // its fix's here: three lines of fix A, none of fix B (the ranking's + // pick for the other platform, premise below). + assert_ne!(a_linux[..8], b_linux[..8], "premise: the fixes show apart"); + let lines: Vec<&str> = echo.lines().collect(); + assert_eq!(lines.len(), 3, "the source patch and both builds:\n{echo}"); + assert!( + lines.iter().all(|line| line.contains(&a_linux[..8])) + && !echo.contains(&b_linux[..8]) + && echo.contains(&platform_purl(OTHER_PLATFORM)), + "the echo lists the patches the run uses:\n{echo}\nall of stdout:\n{stdout}" + ); + let after_echo = stdout.split_once("Selected:\n").unwrap().1; + assert!( + after_echo.contains(FIXED_BY_B), + "the note names what the settled selection leaves:\n{stdout}" + ); + // And those are the patches the lock is pinned to. + assert!( + lock.contains(&format!("/patch-registry/gem/{TOKEN}/{UUID}/\n")) + && lock.contains(&format!( + " {DEP} ({DEP_VERSION}-{OTHER_PLATFORM}) sha256={}\n", + sha_of(Some(OTHER_PLATFORM)) + )), + "{lock}" + ); + + // `--json`: the same selection in the events, the same note as a warning. + let (code, stdout, stderr, _) = get(true); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + let mut pinned: Vec<&str> = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["details"]["mode"] == "hosted" && e["action"] == "applied") + .filter_map(|e| e["uuid"].as_str()) + .collect(); + pinned.sort_unstable(); + let mut expected = [a_arm.as_str(), a_linux.as_str()]; + expected.sort_unstable(); + assert_eq!(pinned, expected, "{env}"); + let waiting = warnings_with_code(&env, "merged_patch_pending"); + let [detail] = waiting.as_slice() else { + panic!("one merged-patch warning: {env}"); + }; + assert!( + detail.contains(FIXED_BY_B) && !detail.contains(FIXED_BY_A), + "{detail}" + ); +} + +/// With the rollout's budget spent, a gem locked as platform builds is +/// deferred whole, its source patch included: nothing is written, the +/// builds are reported as deferred, and the run gives no platform warning +/// for a gem that was only deferred. +#[tokio::test(flavor = "multi_thread")] +async fn gem_hosted_scan_defers_a_platform_gem_whole() { + let ruby_sha = sha256_of(&real_gem(PATCHED_LIB)); + let builds = [ + (PLATFORM, sha256_of(&real_gem_for(PATCHED_LIB, PLATFORM))), + ( + OTHER_PLATFORM, + sha256_of(&real_gem_for(PATCHED_LIB, OTHER_PLATFORM)), + ), + ]; + let server = MockServer::start().await; + mount_api_with(&server, None, &ruby_sha, &builds).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + let gemfile = format!("source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"); + let lock = platform_lock(&"1".repeat(64), &"2".repeat(64)); + std::fs::write(proj.join("Gemfile"), &gemfile).unwrap(); + std::fs::write(proj.join("Gemfile.lock"), &lock).unwrap(); + let uri = server.uri(); + let (code, stdout, stderr) = common::run_with_env( + &proj, + &[ + "scan", + "--mode", + "hosted", + "--json", + "--yes", + "--max-new-patches", + "0", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + ], + &[], + ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!(hosted_pinned(&env), 0, "{env}"); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + lock + ); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + gemfile + ); + assert!( + warnings_with_code(&env, "redirect_gem_platform_unsupported").is_empty(), + "a deferred gem has every patch it needs: {env}" + ); + let deferred: Vec<&str> = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["action"] == "skipped" && e["errorCode"] == "rollout_deferred") + .filter_map(|e| e["purl"].as_str()) + .collect(); + assert!( + !deferred.is_empty() && deferred.iter().all(|purl| purl.starts_with(PURL)), + "the gem's builds are reported as deferred: {env}" + ); +} + +/// The fix's source patch is not offered to the run, while the patch of +/// every locked build is: the gem is moved all the same, through the +/// registry of the first locked build's own patch (any patch registry of a +/// fix serves every build of it), each build pinned to its own patch, and +/// a warning says which registry that is and what follows. Once the source +/// patch is offered, a re-scan leaves the working pair as it is. +#[tokio::test(flavor = "multi_thread")] +async fn gem_hosted_scan_without_the_source_patch_takes_a_builds_registry() { + let ruby_sha = sha256_of(&real_gem(PATCHED_LIB)); + let builds = [ + (PLATFORM, sha256_of(&real_gem_for(PATCHED_LIB, PLATFORM))), + ( + OTHER_PLATFORM, + sha256_of(&real_gem_for(PATCHED_LIB, OTHER_PLATFORM)), + ), + ]; + let server = MockServer::start().await; + mount_fix_api( + &server, + UUID, + PATCHED_LIB, + None, + &ruby_sha, + &builds, + &[("ruby", "forbidden")], + ) + .await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write( + proj.join("Gemfile"), + format!("source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"), + ) + .unwrap(); + std::fs::write( + proj.join("Gemfile.lock"), + platform_lock(&"1".repeat(64), &"2".repeat(64)), + ) + .unwrap(); + let pair = || { + ( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + ) + }; + // The first locked build, as Bundler sorts the platforms. + let first = PLATFORM.min(OTHER_PLATFORM); + let anchor = platform_patch_uuid(UUID, first); + let registry = format!("{}/patch-registry/gem/{TOKEN}/{anchor}/", server.uri()); + + let (code, stdout, stderr) = hosted_scan_json(&proj, &server.uri()); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!(hosted_pinned(&env), 2, "one pin per locked build: {env}"); + assert!( + warnings_with_code(&env, "redirect_gem_platform_unsupported").is_empty(), + "{env}" + ); + let said = warnings_with_code(&env, "redirect_gem_member_registry"); + let [detail] = said.as_slice() else { + panic!("one member-registry warning: {env}"); + }; + assert_eq!( + *detail, + format!( + "Gemfile.lock takes {DEP} {DEP_VERSION} from the patch registry of its `{first}` \ + gem's patch ({anchor}): the patch its builds were built from ({UUID}) 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 `{first}` \ + leaves Gemfile.lock" + ) + ); + let (gemfile, moved) = pair(); + assert!( + gemfile.contains(&format!("source: \"{registry}\"")), + "{gemfile}" + ); + assert!( + moved.contains(&format!( + " remote: {registry}\n specs:\n {DEP} ({DEP_VERSION}-{PLATFORM})\n {DEP} \ + ({DEP_VERSION}-{OTHER_PLATFORM})\n" + )), + "{moved}" + ); + for (platform, sha) in &builds { + assert!( + moved.contains(&format!( + " {DEP} ({DEP_VERSION}-{platform}) sha256={sha}\n" + )), + "{moved}" + ); + } + + // The re-scans name the patch server, so that the lock's pin on this + // loopback registry is read as the hosted pin it is. + let uri = server.uri(); + let rescan = || { + common::run_with_env( + &proj, + &[ + "scan", + "--mode", + "hosted", + "--json", + "--yes", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--patch-server-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + ], + &[], + ) + }; + // A re-scan without the source patch changes nothing and says the same. + let (code, stdout, stderr) = rescan(); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!(pair(), (gemfile.clone(), moved.clone()), "{env}"); + assert_eq!(hosted_pinned(&env), 2, "{env}"); + assert_eq!( + warnings_with_code(&env, "redirect_gem_member_registry").len(), + 1, + "{env}" + ); + assert_eq!( + env["updates"], + serde_json::json!([]), + "the gem is on its fix: no newer patch is announced: {env}" + ); + + // The source patch is offered now: the pair works, and stays as it is. + server.reset().await; + mount_api_with(&server, None, &ruby_sha, &builds).await; + let (code, stdout, stderr) = rescan(); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!(pair(), (gemfile, moved), "nothing is rewritten: {env}"); + assert_eq!(hosted_pinned(&env), 2, "{env}"); + assert_eq!( + env["updates"], + serde_json::json!([]), + "the source patch of the same fix is no newer patch: {env}" + ); + assert!( + warnings_with_code(&env, "redirect_gem_member_registry").is_empty() + && warnings_with_code(&env, "redirect_gem_platform_unsupported").is_empty(), + "{env}" + ); +} + +/// A pair that already takes the gem from its patch registry, as an +/// earlier run (or an earlier development build, which pinned every +/// platform entry under the ruby gem's patch) left it: +/// +/// * with a patch for every locked build the next scan converges: a +/// `CHECKSUMS` entry that is not its own patch's sha256 is set to it, +/// and nothing else of either file changes; +/// * once a locked build has no usable patch the pair is left exactly as +/// it is, and the warning says how to take the gem back upstream. +#[tokio::test(flavor = "multi_thread")] +async fn gem_hosted_pair_already_moved_converges_or_is_kept() { + let ruby_sha = sha256_of(&real_gem(PATCHED_LIB)); + let builds = [ + (PLATFORM, sha256_of(&real_gem_for(PATCHED_LIB, PLATFORM))), + ( + OTHER_PLATFORM, + sha256_of(&real_gem_for(PATCHED_LIB, OTHER_PLATFORM)), + ), + ]; + let server = MockServer::start().await; + mount_api_with(&server, None, &ruby_sha, &builds).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write( + proj.join("Gemfile"), + format!("source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"), + ) + .unwrap(); + std::fs::write( + proj.join("Gemfile.lock"), + platform_lock(&"1".repeat(64), &"2".repeat(64)), + ) + .unwrap(); + let pair = || { + ( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + ) + }; + let (code, stdout, stderr) = hosted_scan_json(&proj, &server.uri()); + assert_eq!(code, 0, "{stdout}\nstderr:\n{stderr}"); + let (gemfile, moved) = pair(); + assert!( + moved.contains(&format!("/patch-registry/gem/{TOKEN}/{UUID}/\n specs:\n")), + "premise: the pair takes the gem from its patch registry:\n{moved}" + ); + + // The pair as an earlier build pinned it: the same registry, and for + // one build the sha256 of an archive that is not its patch's. + let earlier = moved.replace(&builds[1].1, &"c".repeat(64)); + assert_ne!(earlier, moved); + std::fs::write(proj.join("Gemfile.lock"), &earlier).unwrap(); + let (code, stdout, stderr) = hosted_scan_json(&proj, &server.uri()); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!( + pair(), + (gemfile.clone(), moved.clone()), + "the checksum follows its patch, and nothing else changes: {env}" + ); + assert!( + warnings_with_code(&env, "redirect_gem_platform_unsupported").is_empty(), + "{env}" + ); + assert_eq!(hosted_pinned(&env), 2, "one pin per locked build: {env}"); + + // One locked build loses its patch: the pair stays, and the run says + // how to take the gem back. + for kept in [&moved, &earlier] { + std::fs::write(proj.join("Gemfile.lock"), kept).unwrap(); + server.reset().await; + mount_fix_api( + &server, + UUID, + PATCHED_LIB, + None, + &ruby_sha, + &builds, + &[(OTHER_PLATFORM, "withdrawn")], + ) + .await; + let (code, stdout, stderr) = hosted_scan_json(&proj, &server.uri()); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!( + pair(), + (gemfile.clone(), kept.clone()), + "neither file changes: {env}" + ); + let skipped = warnings_with_code(&env, "redirect_gem_platform_unsupported"); + let [detail] = skipped.as_slice() else { + panic!("one platform skip: {env}"); + }; + assert!( + detail.contains(&format!( + "no patch is available for `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})`" + )) && detail.ends_with(&format!( + "Gemfile.lock already takes {DEP} from a Socket patch registry and is left as \ + it is: run `socket-patch rollback {PURL}` to put the gem back on its upstream \ + registry, or scan again once every locked build has a patch of one fix" + )), + "{detail}" + ); + } +} + /// A lock that names the gem only as platform builds, beside a plain -/// gem, and a patch without a patched build for every locked platform: +/// gem, and a fix without a patch for every locked platform: /// the run refuses the gem. The lock still resolves it, so the closing /// totals count its advisory as left to patch, in hosted mode (which /// reads the gem from the lock alone) and in vendored mode (which reads @@ -3055,11 +3930,16 @@ async fn refused_platform_gem_is_counted_as_left_to_patch() { &[], ); assert_eq!(code, 0, "{mode}\nstdout:\n{stdout}\nstderr:\n{stderr}"); - // The premise: the run refused the gem for a platform the patch - // has no build for. + // The premise: the run refused the gem for a platform that has + // no patch. let refusal = match mode { - "hosted" => format!("no patched build for `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})`"), - _ => format!("the patch service has no prebuilt platform gem of `{DEP}`"), + "hosted" => { + format!("no patch is available for `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})`") + } + _ => format!( + "no patch of this fix is available for every platform gem of `{DEP}` that \ + Gemfile.lock locks (`{OTHER_PLATFORM}`: no patch on offer" + ), }; assert!( stderr.contains(&refusal), 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 14ffd294a..3cb5e41df 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -161,30 +161,52 @@ fn b64(bytes: &[u8]) -> String { /// Write `.socket/manifest.json` + the after-hash blob (with a vulnerability /// so the VEX leg has a statement to emit) so vendor runs fully offline. fn stage_patch_with_vuln(proj: &Path, purl: &str, file_key: &str, before: &[u8], after: &[u8]) { + stage_patches_with_vuln( + proj, + &[(purl.to_string(), UUID.to_string())], + file_key, + before, + after, + ); +} + +/// [`stage_patch_with_vuln`] for several patches of the same change, each +/// `(purl, uuid)`: the patches of one fix of a gem, one per platform gem. +fn stage_patches_with_vuln( + proj: &Path, + patches: &[(String, String)], + file_key: &str, + before: &[u8], + after: &[u8], +) { let socket = proj.join(".socket"); std::fs::create_dir_all(socket.join("blobs")).unwrap(); - let manifest = serde_json::json!({ - "patches": { purl: { - "uuid": UUID, - "exportedAt": "2026-01-01T00:00:00Z", - "files": { file_key: { - "beforeHash": git_sha256(before), - "afterHash": git_sha256(after), - }}, - "vulnerabilities": { GHSA: { - "cves": ["CVE-2026-55555"], - "summary": "gem capstone vex vuln", - "severity": "high", - "description": "d", - }}, - "description": "capstone marker patch", - "license": "MIT", - "tier": "free", - }} - }); + let records: serde_json::Map = patches + .iter() + .map(|(purl, uuid)| { + let record = serde_json::json!({ + "uuid": uuid, + "exportedAt": "2026-01-01T00:00:00Z", + "files": { file_key: { + "beforeHash": git_sha256(before), + "afterHash": git_sha256(after), + }}, + "vulnerabilities": { GHSA: { + "cves": ["CVE-2026-55555"], + "summary": "gem capstone vex vuln", + "severity": "high", + "description": "d", + }}, + "description": "capstone marker patch", + "license": "MIT", + "tier": "free", + }); + (purl.clone(), record) + }) + .collect(); std::fs::write( socket.join("manifest.json"), - serde_json::to_string_pretty(&manifest).unwrap(), + serde_json::to_string_pretty(&serde_json::json!({ "patches": records })).unwrap(), ) .unwrap(); std::fs::write(socket.join("blobs").join(git_sha256(after)), after).unwrap(); @@ -2824,72 +2846,126 @@ end File.write("platforms", platforms.join("\n")) "##; -/// A patch service answering for the patch `uuid` the way the wire -/// contract of gem prebuilds has it: the ruby gem as the `tarball` (with -/// its stub), and a `gem-platform` gem + `gem-platform-stub-gemspec` for -/// each of `prebuilds`, each naming its `platform`. The URLs name the -/// production host, so the run reaches them only through -/// `--patch-server-url`. +/// The uuid of the patch of the platform gem `platform` of the fix whose +/// source patch (the ruby gem's) is `source`: each platform gem has a +/// patch of its own. +fn build_uuid(source: &str, platform: &str) -> String { + let tail = source + .bytes() + .chain(platform.bytes()) + .fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| { + (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3) + }); + format!("{}{:012x}", &source[..24], tail & 0xffff_ffff_ffff) +} + +/// The patches of the fix `source` of the fixture gem, as `(purl, uuid)`: +/// the ruby gem's (the source, `?platform=ruby`) and one per platform gem +/// in `platforms`. +fn fix_patches(source: &str, platforms: &[String]) -> Vec<(String, String)> { + let base = format!("pkg:gem/{PLAT}@{PLAT_VERSION}"); + let mut patches = vec![(format!("{base}?platform=ruby"), source.to_string())]; + for platform in platforms { + patches.push(( + format!("{base}?platform={platform}"), + build_uuid(source, platform), + )); + } + patches +} + +/// A patch service answering for the fix `source` of the fixture gem: one +/// patch per gem, each with its own uuid. The ruby gem's patch (`source`) +/// and the patch of each platform gem in `built` ([`build_uuid`]) answer +/// `granted` with the gem as the `tarball` and its stub gemspec; a platform +/// patch also states the patch it was built from (`rebuiltFromUuid`). The +/// patch of each platform in `pending` answers that it is still being +/// built, and any other uuid is not found. The URLs name the production +/// host, so the run reaches them only through `--patch-server-url`. async fn platform_patch_service( service: &Path, - purl: &str, - uuid: &str, - prebuilds: &[String], + source: &str, + built: &[String], + pending: &[String], ) -> MockServer { use base64::Engine as _; use sha2::{Digest as _, Sha512}; let server = MockServer::start().await; - let leaf = format!("{PLAT}-{PLAT_VERSION}"); - let mut served: Vec<(&str, Option<&str>, String)> = vec![ - ("tarball", None, format!("{leaf}.gem")), - ("gem-stub-gemspec", None, format!("{leaf}.gemspec")), - ]; - for platform in prebuilds { - served.push(( - "gem-platform", - Some(platform.as_str()), - format!("{leaf}-{platform}.gem"), - )); - served.push(( - "gem-platform-stub-gemspec", - Some(platform.as_str()), - format!("{leaf}-{platform}.gemspec"), - )); - } - let mut artifacts = Vec::new(); - for (kind, platform, file) in served { - let bytes = std::fs::read(service.join(&file)).unwrap(); - let route = format!("/patch/gem/{PLAT}/{PLAT_VERSION}/grant-token/{uuid}/{file}"); - let mut artifact = serde_json::json!({ - "kind": kind, - "url": format!("https://patch.socket.dev{route}"), - "contentType": "application/octet-stream", - "sizeBytes": bytes.len(), - "integrity": { "sha512": format!( - "sha512-{}", - base64::engine::general_purpose::STANDARD.encode(Sha512::digest(&bytes)) - ) }, - }); - if let Some(platform) = platform { - artifact["platform"] = serde_json::json!(platform); + let base = format!("pkg:gem/{PLAT}@{PLAT_VERSION}"); + let mut results = serde_json::Map::new(); + let gems = std::iter::once(None).chain(built.iter().map(Some)); + for platform in gems { + let (uuid, leaf, purl) = match platform { + Some(platform) => ( + build_uuid(source, platform), + format!("{PLAT}-{PLAT_VERSION}-{platform}"), + format!("{base}?platform={platform}"), + ), + None => ( + source.to_string(), + format!("{PLAT}-{PLAT_VERSION}"), + format!("{base}?platform=ruby"), + ), + }; + let mut artifacts = Vec::new(); + for (kind, file) in [ + ("tarball", format!("{leaf}.gem")), + ("gem-stub-gemspec", format!("{leaf}.gemspec")), + ] { + let bytes = std::fs::read(service.join(&file)).unwrap(); + let route = format!("/patch/gem/{PLAT}/{PLAT_VERSION}/grant-token/{uuid}/{file}"); + artifacts.push(serde_json::json!({ + "kind": kind, + "url": format!("https://patch.socket.dev{route}"), + "contentType": "application/octet-stream", + "sizeBytes": bytes.len(), + "integrity": { "sha512": format!( + "sha512-{}", + base64::engine::general_purpose::STANDARD.encode(Sha512::digest(&bytes)) + ) }, + })); + Mock::given(method("GET")) + .and(path(route)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .mount(&server) + .await; } - artifacts.push(artifact); - Mock::given(method("GET")) - .and(path(route)) - .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) - .mount(&server) - .await; - } - Mock::given(method("POST")) - .and(path_regex(r"/(patch|patches)/package$")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "results": { uuid: { + results.insert( + uuid, + serde_json::json!({ "status": "granted", "purl": purl, "url": artifacts[0]["url"], + "rebuiltFromUuid": platform.map(|_| source), "artifacts": artifacts, - }} - }))) + }), + ); + } + for platform in pending { + results.insert( + build_uuid(source, platform), + serde_json::json!({ "status": "pending_build" }), + ); + } + Mock::given(method("POST")) + .and(path_regex(r"/(patch|patches)/package$")) + .respond_with(move |request: &wiremock::Request| { + let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default(); + let asked: serde_json::Map = body["uuids"] + .as_array() + .into_iter() + .flatten() + .filter_map(|uuid| uuid.as_str()) + .map(|uuid| { + let result = results + .get(uuid) + .cloned() + .unwrap_or_else(|| serde_json::json!({ "status": "not_found" })); + (uuid.to_string(), result) + }) + .collect(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "results": asked })) + }) .mount(&server) .await; server @@ -2924,26 +3000,30 @@ async fn service_requests(server: &MockServer) -> usize { /// A gem bundler locks as PRECOMPILED PLATFORM gems (the shape of /// nokogiri: one lock entry per platform, no plain `name (version)`), which /// cannot be vendored as its own tree because bundler never builds a -/// `path:` gem's extensions. Vendor takes the patch service's prebuild of -/// EVERY locked platform instead: +/// `path:` gem's extensions. A fix of such a gem is one patch per platform +/// gem, each with its own uuid, built from the patch of the ruby gem (the +/// fix's source). Vendor takes the patch of EVERY locked platform: /// /// 1. the REAL bundler resolves the fixture gem from a local source that /// publishes it as platform gems only, and locks this machine's /// platform and two foreign ones; -/// 2. while the service lacks one platform's prebuild the gem is -/// skipped, by that platform's name: the run does not fail, downloads -/// no gem and writes nothing; -/// 3. with every prebuild served, `vendor` unpacks one tree per platform -/// (each with its stub gemspec), moves every platform block into one -/// `PATH` section and wires the Gemfile; -/// 4. `vex` attests the patch `(vendored)`, and `vendor --check` covers -/// every platform's tree (a tampered FOREIGN tree fails it); +/// 2. while one locked platform has no patch the gem is skipped, by that +/// platform's name: the run does not fail, downloads no gem and +/// writes nothing; +/// 3. with a patch for every platform, `vendor` unpacks one tree per +/// platform (each from its own patch, with its stub gemspec) under +/// the directory named after the source patch, moves every platform +/// block into one `PATH` section and wires the Gemfile; the ledger +/// records each platform's own patch; +/// 4. `vex` attests each platform gem by its own patch `(vendored)`, and +/// `vendor --check` covers every platform's tree (a tampered FOREIGN +/// tree fails it); /// 5. a fresh checkout — the committable files only, and no request to /// the patch service — installs frozen with a byte-stable lock, loads /// the PATCHED file from the tree of the running platform, and an /// unfrozen install and `bundle lock` regenerate the same lock; /// 6. a second `vendor` run changes nothing and asks the service nothing, -/// and a newer patch whose prebuild for one platform is not built yet +/// and a newer fix whose patch for one platform is still being built /// keeps the vendored one; /// 7. `vendor --revert` restores the Gemfile and the lock byte for byte /// (the registry CHECKSUMS tokens included) and removes the trees. @@ -3066,15 +3146,20 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) "bundler installs this machine's platform gem into a platform-suffixed dir" ); - // The patch record is the ruby gem's, as the patch service publishes it. + // The patch records, as the patch service publishes a fix: the ruby + // gem's (the source) and one per platform gem. The third platform's + // patch is not published yet. let purl = format!("pkg:gem/{PLAT}@{PLAT_VERSION}?platform=ruby"); - stage_patch_with_vuln( - &proj, - &purl, - "lib/sockplat.rb", - PLAT_PRISTINE.as_bytes(), - patched.as_bytes(), - ); + let stage = |source: &str, platforms: &[String]| { + stage_patches_with_vuln( + &proj, + &fix_patches(source, platforms), + "lib/sockplat.rb", + PLAT_PRISTINE.as_bytes(), + patched.as_bytes(), + ); + }; + stage(UUID, &platforms[..2]); let vendor = |server: &MockServer| { let uri = server.uri(); run_socket( @@ -3090,15 +3175,16 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) ) }; - // 2. One locked platform without a prebuild (the service lists one - // only once it is built): the gem is skipped, by name, the run does - // not fail, no gem is downloaded and nothing is written. + // 2. One locked platform without a patch (a platform's patch is + // listed only once it is published and built): the gem is skipped, + // by name, the run does not fail, no gem is downloaded and nothing + // is written. let partial = - platform_patch_service(&fixture.join("service"), &purl, UUID, &platforms[..2]).await; + platform_patch_service(&fixture.join("service"), UUID, &platforms[..2], &[]).await; let (code, stdout, stderr) = vendor(&partial); assert_eq!( code, 0, - "a prebuild that is not built yet is no failure.\nstdout:\n{stdout}\nstderr:\n{stderr}" + "a platform with no patch yet is no failure.\nstdout:\n{stdout}\nstderr:\n{stderr}" ); let env = parse_json_envelope(&stdout); assert_eq!(env["summary"]["applied"], 0, "nothing vendored: {env}"); @@ -3112,8 +3198,9 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) assert_eq!(skipped["action"], "skipped", "{skipped}"); let said = skipped.to_string(); assert!( - said.contains(&format!("`{PLAT}`")) && said.contains(&format!("`{}`", platforms[2])), - "the skip names the gem and the platform with no prebuild: {skipped}" + said.contains(&format!("`{PLAT}`")) + && said.contains(&format!("`{}`: no patch on offer", platforms[2])), + "the skip names the gem and the platform with no patch: {skipped}" ); assert_eq!( artifact_downloads(&partial).await, @@ -3128,8 +3215,9 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) ); drop(partial); - // 3. Every prebuild served: vendor. - let server = platform_patch_service(&fixture.join("service"), &purl, UUID, &platforms).await; + // 3. A patch for every locked platform: vendor. + stage(UUID, &platforms); + let server = platform_patch_service(&fixture.join("service"), UUID, &platforms, &[]).await; let (code, stdout, stderr) = vendor(&server); assert_eq!( code, 0, @@ -3137,10 +3225,31 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) ); let env = parse_json_envelope(&stdout); assert_eq!(env["status"], "success", "envelope: {env}"); - assert_eq!(env["summary"]["applied"], 1, "one package vendored: {env}"); + // One applied event per platform gem, each under its own patch (the + // human summary counts the gem as one package). + assert_eq!( + env["summary"]["applied"], + platforms.len(), + "one applied event per platform gem: {env}" + ); + let mut applied: Vec<(String, String)> = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["action"] == "applied") + .map(|e| { + assert_eq!(e["details"]["gemFix"], UUID, "{e}"); + let field = |key: &str| e[key].as_str().unwrap_or_default().to_string(); + (field("purl"), field("uuid")) + }) + .collect(); + applied.sort(); + let mut expected_events = fix_patches(UUID, &platforms)[1..].to_vec(); + expected_events.sort(); + assert_eq!(applied, expected_events, "{env}"); assert_eq!(env["summary"]["failed"], 0, "no failures: {env}"); - // The prebuilds and their stubs are all that is downloaded: the ruby - // gem the same reference names is not. + // The platform gems and their stubs are all that is downloaded: the + // ruby gem of the source patch is not. let mut downloaded = artifact_downloads(&server).await; downloaded.sort(); let mut prebuilds: Vec = platforms @@ -3150,7 +3259,8 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) prebuilds.sort(); assert_eq!(downloaded, prebuilds); - // One prebuild tree per platform, each with its own stub gemspec. + // One tree per platform, each with its own stub gemspec, under the + // directory named after the fix's source patch. let copy_rel = format!(".socket/vendor/gem/{UUID}/{PLAT}-{PLAT_VERSION}"); for platform in &platforms { let tree = proj.join(©_rel).join(platform); @@ -3210,9 +3320,34 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) .and_then(|entries| entries.values().next()) .unwrap_or_else(|| panic!("a ledger entry: {state}")); assert_eq!( - entry["gemPlatforms"], - serde_json::json!(sorted), - "the ledger records the platform trees: {entry}" + entry["uuid"], UUID, + "the entry is the source patch's: {entry}" + ); + let recorded: Vec<(String, String)> = entry["gemBuilds"] + .as_array() + .into_iter() + .flatten() + .map(|built| { + let field = |key: &str| built[key].as_str().unwrap_or_default().to_string(); + assert!( + field("gemIntegrity").starts_with("sha512-") + && field("gemspecIntegrity").starts_with("sha512-"), + "each platform's gem and stub are recorded by checksum: {built}" + ); + (field("platform"), field("uuid")) + }) + .collect(); + let expected: Vec<(String, String)> = sorted + .iter() + .map(|platform| (platform.clone(), build_uuid(UUID, platform))) + .collect(); + assert_eq!( + recorded, expected, + "the ledger records each platform tree with its own patch: {entry}" + ); + assert!( + entry.get("gemPlatforms").is_none(), + "one record of the platform trees: {entry}" ); // 4. VEX attests the patch against the committed trees, and `--check` @@ -3280,6 +3415,281 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) "an unpatched tree of a FOREIGN platform must fail the check.\nstdout:\n{stdout}\nstderr:\n{stderr}" ); + // What an earlier development build left: it vendored such a gem with + // every tree under the ruby gem's one patch, and its ledger entry + // names the platforms alone (`gemPlatforms`). Such a project is still + // read, checked, attested and reverted; a run that finds no patch for + // the platforms keeps the copy and says so, and a run with a patch for + // every platform brings the entry to the per-platform record without + // changing a committed file. + let earlier_build = |name: &str, platform_patches: bool| -> PathBuf { + let dir = base.join(name); + common::fs_tree::copy_tree(&proj, &dir); + let path = dir.join(".socket/vendor/state.json"); + let mut state: serde_json::Value = + serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + for entry in state["entries"].as_object_mut().unwrap().values_mut() { + let entry = entry.as_object_mut().unwrap(); + let built = entry.remove("gemBuilds").expect("gemBuilds"); + let platforms: Vec = built + .as_array() + .into_iter() + .flatten() + .map(|built| built["platform"].clone()) + .collect(); + entry.insert("gemPlatforms".into(), platforms.into()); + } + std::fs::write(&path, serde_json::to_string_pretty(&state).unwrap()).unwrap(); + if !platform_patches { + // Its manifest held the one record. + stage_patch_with_vuln( + &dir, + &purl, + "lib/sockplat.rb", + PLAT_PRISTINE.as_bytes(), + patched.as_bytes(), + ); + } + dir + }; + let run_in = |dir: &Path, args: &[&str], service: Option<&MockServer>| { + let mut argv: Vec = args.iter().map(|arg| arg.to_string()).collect(); + argv.extend(["--cwd".to_string(), dir.to_str().unwrap().to_string()]); + if let Some(service) = service { + argv.extend(["--patch-server-url".to_string(), service.uri()]); + } + let argv: Vec<&str> = argv.iter().map(String::as_str).collect(); + run_socket(dir, &argv) + }; + let pair_of = |dir: &Path| { + ( + std::fs::read(dir.join("Gemfile")).unwrap(), + std::fs::read(dir.join("Gemfile.lock")).unwrap(), + ) + }; + let wired_pair = pair_of(&proj); + let source_only = platform_patch_service(&fixture.join("service"), UUID, &[], &[]).await; + { + // No patch for the platforms: checked, kept, attested, reverted. + let kept = earlier_build("earlier-kept", false); + let state_before = std::fs::read(kept.join(".socket/vendor/state.json")).unwrap(); + let (code, stdout, stderr) = + run_in(&kept, &["vendor", "--check", "--json"], Some(&source_only)); + assert_eq!( + code, 0, + "an earlier build's copy still checks.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let (code, stdout, stderr) = run_in(&kept, &["vendor", "--json"], Some(&source_only)); + assert_eq!( + code, 0, + "a run with no patch for the platforms is no failure.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env = parse_json_envelope(&stdout); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + let said = env["events"] + .as_array() + .unwrap() + .iter() + .find(|e| e["errorCode"] == "vendor_gem_builds_kept") + .unwrap_or_else(|| panic!("a vendor_gem_builds_kept event: {env}")); + assert_eq!(said["action"], "skipped", "{said}"); + assert_eq!(pair_of(&kept), wired_pair, "the pair is untouched"); + assert_eq!( + std::fs::read(kept.join(".socket/vendor/state.json")).unwrap(), + state_before, + "and so is the ledger" + ); + assert_eq!( + artifact_downloads(&source_only).await, + Vec::::new(), + "nothing is downloaded" + ); + let out = kept.join("out.vex.json"); + let (code, stdout, stderr) = run_in( + &kept, + &[ + "vex", + "--output", + out.to_str().unwrap(), + "--product", + PRODUCT, + ], + None, + ); + assert_eq!(code, 0, "vex.\nstdout:\n{stdout}\nstderr:\n{stderr}"); + let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(&out).unwrap()).unwrap(); + let stmts = doc["statements"].as_array().unwrap(); + assert_eq!(stmts.len(), 1, "{doc}"); + assert!( + stmts[0]["impact_statement"] + .as_str() + .unwrap() + .contains(&format!("Patched via Socket patch {UUID} (vendored)")), + "attested by the one patch the copy came with: {doc}" + ); + for (name, args) in [ + ("earlier-reverted", &["vendor", "--revert", "--json"][..]), + ("earlier-rolled-back", &["rollback", "--json"][..]), + ] { + let dir = earlier_build(name, false); + let (code, stdout, stderr) = run_in(&dir, args, None); + assert_eq!( + code, 0, + "{args:?} of an earlier build's copy.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_eq!( + pair_of(&dir), + (gemfile_before.clone(), lock_before.clone()), + "{args:?} restores the pair byte for byte" + ); + assert!( + !dir.join(".socket/vendor/gem").exists(), + "{args:?} removes the trees" + ); + } + } + { + // A patch for every platform: the entry is brought to the + // per-platform record, and no committed file changes. + let converted = earlier_build("earlier-converted", true); + let (code, stdout, stderr) = run_in(&converted, &["vendor", "--json"], Some(&server)); + assert_eq!( + code, 0, + "bringing an earlier build's copy up to date.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env = parse_json_envelope(&stdout); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + assert_eq!( + pair_of(&converted), + wired_pair, + "the pair is untouched: {env}" + ); + let state: serde_json::Value = serde_json::from_slice( + &std::fs::read(converted.join(".socket/vendor/state.json")).unwrap(), + ) + .unwrap(); + let entry = state["entries"] + .as_object() + .and_then(|entries| entries.values().next()) + .unwrap_or_else(|| panic!("a ledger entry: {state}")); + let built: Vec<(&str, &str)> = entry["gemBuilds"] + .as_array() + .into_iter() + .flatten() + .filter_map(|b| Some((b["platform"].as_str()?, b["uuid"].as_str()?))) + .collect(); + let expected: Vec<(String, String)> = sorted + .iter() + .map(|platform| (platform.clone(), build_uuid(UUID, platform))) + .collect(); + assert_eq!( + built, + expected + .iter() + .map(|(p, u)| (p.as_str(), u.as_str())) + .collect::>(), + "each tree is recorded with its own patch: {entry}" + ); + assert!(entry.get("gemPlatforms").is_none(), "{entry}"); + let (code, stdout, stderr) = + run_in(&converted, &["vendor", "--check", "--json"], Some(&server)); + assert_eq!( + code, 0, + "the converted copy checks.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + } + drop(source_only); + + // The fix without its source patch (the ruby gem's patch is not + // offered to the run): the gem is vendored through the patch of the + // first locked platform, whose uuid names the directory. It stays + // there once the source patch turns up, and reverts like any other. + { + let sourceless = base.join("sourceless"); + common::fs_tree::copy_tree(&proj, &sourceless); + let (code, stdout, stderr) = run_in(&sourceless, &["vendor", "--revert", "--json"], None); + assert_eq!( + code, 0, + "premise: revert.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_eq!( + pair_of(&sourceless), + (gemfile_before.clone(), lock_before.clone()) + ); + let stage_in = |patches: &[(String, String)]| { + stage_patches_with_vuln( + &sourceless, + patches, + "lib/sockplat.rb", + PLAT_PRISTINE.as_bytes(), + patched.as_bytes(), + ); + }; + let fix = fix_patches(UUID, &platforms); + stage_in(&fix[1..]); + let lead = build_uuid(UUID, &sorted[0]); + let lead_dir = format!(".socket/vendor/gem/{lead}/{PLAT}-{PLAT_VERSION}"); + let (code, stdout, stderr) = run_in(&sourceless, &["vendor", "--json"], Some(&server)); + assert_eq!( + code, 0, + "vendoring without the source patch.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env = parse_json_envelope(&stdout); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + assert_eq!( + env["summary"]["applied"], + platforms.len(), + "one applied event per platform gem: {env}" + ); + for platform in &platforms { + let tree = sourceless.join(&lead_dir).join(platform); + assert_eq!( + std::fs::read_to_string(tree.join("lib/sockplat.rb")).unwrap(), + patched, + "{platform}: its tree sits under the first platform's patch" + ); + } + let lock = std::fs::read_to_string(sourceless.join("Gemfile.lock")).unwrap(); + assert!( + lock.starts_with(&format!("PATH\n remote: {lead_dir}\n")), + "{lock}" + ); + let (code, stdout, stderr) = + run_in(&sourceless, &["vendor", "--check", "--json"], Some(&server)); + assert_eq!(code, 0, "check.\nstdout:\n{stdout}\nstderr:\n{stderr}"); + // The source patch turns up: the copy works, and stays where it is. + let wired = pair_of(&sourceless); + let state_wired = std::fs::read(sourceless.join(".socket/vendor/state.json")).unwrap(); + stage_in(&fix); + let (code, stdout, stderr) = run_in(&sourceless, &["vendor", "--json"], Some(&server)); + assert_eq!(code, 0, "re-run.\nstdout:\n{stdout}\nstderr:\n{stderr}"); + let env = parse_json_envelope(&stdout); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + assert_eq!( + env["summary"]["applied"], 0, + "nothing is vendored again: {env}" + ); + assert_eq!(pair_of(&sourceless), wired, "{env}"); + assert_eq!( + std::fs::read(sourceless.join(".socket/vendor/state.json")).unwrap(), + state_wired, + "{env}" + ); + assert!( + !sourceless + .join(format!(".socket/vendor/gem/{UUID}")) + .exists(), + "the copy is not moved under the source patch" + ); + let (code, stdout, stderr) = run_in(&sourceless, &["vendor", "--revert", "--json"], None); + assert_eq!(code, 0, "revert.\nstdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!( + pair_of(&sourceless), + (gemfile_before.clone(), lock_before.clone()) + ); + assert!(!sourceless.join(".socket/vendor/gem").exists()); + } + // 5. FRESH CHECKOUT: only the committable files, and no patch service. let fresh = base.join("fresh"); std::fs::create_dir_all(&fresh).unwrap(); @@ -3348,9 +3758,11 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) ); // Manifest-less VEX over the fresh checkout: attested from the lock's - // PATH wiring and the vendor ledger, and, with the ledgers gone too, - // from the lock and the patch API alone (the platform trees are then - // read off the committed directory). On a plain thread: PatchApi runs + // PATH wiring and the vendor ledger, each platform gem by its own + // patch, and, with the ledgers gone too, from the lock and the patch + // API alone (the platform trees are then read off the committed + // directory, which is named after the patch they were built from: that + // is the patch the statement names). On a plain thread: PatchApi runs // its own runtime, which cannot be started (or dropped) from inside // this test's async context. std::thread::scope(|scope| { @@ -3376,7 +3788,12 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) strip_manifest(&fresh); let out = run_vex(&binary(), &fresh, &run(VexRun::offline())); assert_eq!(out.code, Some(0), "manifest-less vex: {out}"); - assert_attested(out.doc(), &base_purl, UUID, Marker::Vendored, VULNS); + for platform in &platforms { + let built = build_uuid(UUID, platform); + let attested = + assert_attested(out.doc(), &base_purl, &built, Marker::Vendored, VULNS); + assert_eq!(attested.len(), 1, "one statement for the gem: {out}"); + } strip_ledgers(&fresh); let out = run_vex(&binary(), &fresh, &run(VexRun::online(&api))); assert_eq!(out.code, Some(0), "ledger-less vex: {out}"); @@ -3406,14 +3823,19 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) "an in-sync re-run downloads nothing" ); - // A newer patch of the gem whose prebuild for one platform is not - // built yet: the vendored patch stays in force, and the run says so - // and does not fail. + // A newer fix of the gem whose patch for one platform is still being + // built: the vendored fix stays in force, and the run says so and does + // not fail. let manifest_path = proj.join(".socket/manifest.json"); let manifest = std::fs::read_to_string(&manifest_path).unwrap(); - std::fs::write(&manifest_path, manifest.replace(UUID, UUID_NEXT)).unwrap(); - let update = - platform_patch_service(&fixture.join("service"), &purl, UUID_NEXT, &platforms[..2]).await; + stage(UUID_NEXT, &platforms); + let update = platform_patch_service( + &fixture.join("service"), + UUID_NEXT, + &platforms[..2], + &platforms[2..], + ) + .await; let (code, stdout, stderr) = vendor(&update); assert_eq!( code, 0, @@ -3431,7 +3853,10 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) let said = kept.to_string(); assert!( said.contains(&format!("kept the vendored patch {UUID}")) - && said.contains(&format!("`{}`", platforms[2])) + && said.contains(&format!( + "`{}`: its patched gem is still being built", + platforms[2] + )) && said.contains(UUID_NEXT), "the skip names the kept patch, the new one and the platform: {kept}" ); diff --git a/crates/socket-patch-cli/tests/hosted_memory_common/mod.rs b/crates/socket-patch-cli/tests/hosted_memory_common/mod.rs index 8429d58d9..e77169792 100644 --- a/crates/socket-patch-cli/tests/hosted_memory_common/mod.rs +++ b/crates/socket-patch-cli/tests/hosted_memory_common/mod.rs @@ -66,7 +66,14 @@ pub fn patches_from_overrides(overrides: &Path, rewrite_host: Option<&str>) -> V _ => name, }; let version = o["version"].as_str().unwrap(); - let purl = format!("pkg:{eco}/{full}@{version}"); + // A gem patch is the patch of one platform gem, which its + // package URL names; the ruby gem's is the bare one here. + let ids = &o["registryOverride"]["identifiers"]; + let purl = match ids["gemPlatform"].as_str() { + Some(platform) => format!("pkg:{eco}/{full}@{version}?platform={platform}"), + None => format!("pkg:{eco}/{full}@{version}"), + }; + let rebuilt_from = ids["gemRebuiltFromUuid"].clone(); let uuid = o["patchUuid"].as_str().unwrap().to_string(); let fix = |v: &Value| -> Value { match (v.as_str(), rewrite_host) { @@ -86,6 +93,16 @@ pub fn patches_from_overrides(overrides: &Path, rewrite_host: Option<&str>) -> V if let Some(index) = registry_override.get("indexUrl").cloned() { registry_override["indexUrl"] = fix(&index); } + // The patch API states neither among an override's + // identifiers: the platform is in the package URL, the source + // patch in `rebuiltFromUuid`. + if let Some(ids) = registry_override + .get_mut("identifiers") + .and_then(Value::as_object_mut) + { + ids.remove("gemPlatform"); + ids.remove("gemRebuiltFromUuid"); + } Patch { purl, uuid, @@ -93,6 +110,7 @@ pub fn patches_from_overrides(overrides: &Path, rewrite_host: Option<&str>) -> V "status": "granted", "url": url, "purl": null, + "rebuiltFromUuid": rebuilt_from, "artifacts": artifacts, "registryOverride": registry_override, }), @@ -146,6 +164,11 @@ impl Respond for ByPackage { .iter() .filter(|p| purl_key(&p.purl) == purl_key(&purl)) .map(|p| { + // A release variant's record is keyed by its own purl. + let purl = match p.purl.contains('?') { + true => &p.purl, + false => &purl, + }; serde_json::json!({ "uuid": p.uuid, "purl": purl, "publishedAt": "2024-01-01T00:00:00Z", "description": "fixture", "license": "MIT", "tier": "free", @@ -217,6 +240,56 @@ pub async fn mount_api(server: &MockServer, patches: &[Patch]) { .respond_with(View(patches.to_vec())) .mount(server) .await; + mount_gem_registries(server, patches).await; +} + +/// What the patch registry of each gem patch lists: `info/` names +/// every patch of its fix (the patches built from one source patch, and +/// that patch), one `[-] |checksum:` line each. +async fn mount_gem_registries(server: &MockServer, patches: &[Patch]) { + let fix = |p: &Patch| -> String { + p.reference["rebuiltFromUuid"] + .as_str() + .unwrap_or(&p.uuid) + .to_string() + }; + let gems: Vec<&Patch> = patches + .iter() + .filter(|p| p.purl.starts_with("pkg:gem/")) + .collect(); + for patch in &gems { + let Some(index) = patch.reference["registryOverride"]["indexUrl"].as_str() else { + continue; + }; + let Some(index_path) = index.strip_prefix(&server.uri()) else { + continue; + }; + let ids = &patch.reference["registryOverride"]["identifiers"]; + let (Some(name), Some(version)) = (ids["name"].as_str(), ids["version"].as_str()) else { + continue; + }; + let mut body = String::from("---\n"); + for member in gems.iter().filter(|m| fix(m) == fix(patch)) { + let member_ids = &member.reference["registryOverride"]["identifiers"]; + let Some(sha) = member_ids["gemChecksumSha256"].as_str() else { + continue; + }; + let platform = socket_patch_core::utils::purl::purl_qualifier(&member.purl, "platform"); + let token = match platform { + Some(platform) => format!("{version}-{platform}"), + None => version.to_string(), + }; + body.push_str(&format!("{token} |checksum:{sha}\n")); + } + Mock::given(method("GET")) + .and(path(format!( + "{}/info/{name}", + index_path.trim_end_matches('/') + ))) + .respond_with(ResponseTemplate::new(200).set_body_string(body)) + .mount(server) + .await; + } } pub fn client(server: &MockServer) -> Arc { diff --git a/crates/socket-patch-cli/tests/hosted_memory_parity.rs b/crates/socket-patch-cli/tests/hosted_memory_parity.rs index c999d245a..abbc8e449 100644 --- a/crates/socket-patch-cli/tests/hosted_memory_parity.rs +++ b/crates/socket-patch-cli/tests/hosted_memory_parity.rs @@ -300,10 +300,51 @@ async fn parity_gemfile() { /// A gem the lock resolves only as precompiled platform builds. The lock /// inventory has no ruby-platform entry to list it by, so both hosted /// engines find it through the lock's platform specs (nothing is -/// installed here), and both move every build to its prebuild. +/// installed here). Each platform gem has a patch of its own: both engines +/// take the fix that covers every locked build, wire its source patch's +/// registry and report each build's own patch. #[tokio::test] -async fn parity_gemfile_platform_prebuilds() { - assert_parity(case("gem/bundler/platform-prebuilds")).await; +async fn parity_gemfile_platform_builds() { + let redirect = assert_parity(case("gem/bundler/platform-builds")).await; + let pinned: Vec<(&str, &str)> = redirect["patches"] + .as_array() + .into_iter() + .flatten() + .filter(|p| p["action"] == "pinned") + .filter_map(|p| Some((p["purl"].as_str()?, p["uuid"].as_str()?))) + .collect(); + assert_eq!( + pinned, + [ + ( + "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin", + "77777777-7777-7777-7777-77777777777a" + ), + ( + "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", + "77777777-7777-7777-7777-77777777777b" + ), + ], + "each build is reported under its own patch: {redirect}" + ); + // The fix's source patch lends its registry and is not reported. + assert_eq!(redirect["patches"].as_array().map(Vec::len), Some(2)); +} + +/// The same lock with a patch for one of the two builds only, and with +/// the builds patched by two different fixes: neither engine changes a +/// file, and both say why. +#[tokio::test] +async fn parity_gemfile_platform_builds_that_cannot_move() { + for fixture in [ + "gem/bundler/platform-build-missing", + "gem/bundler/platform-builds-two-fixes", + "gem/bundler/platform-retired-fields", + ] { + let mut case = case(fixture); + case.expect_redirect = false; + assert_parity(case).await; + } } /// The gem fixture as the root of a Bazel workspace whose rules_ruby hub diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index fb137ea93..35a35bd4f 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -1683,19 +1683,21 @@ impl ApiClient { } /// Step 1 of [`Self::fetch_vendor_package`] on its own: what the - /// service lists for the patch besides its archive (the per-platform - /// gem prebuilds and their stub gemspecs), each with its host-rewritten - /// URL and sha512, and NO archive download. A backend that takes only - /// those artifacts learns here which exist. Same grant, statuses, retry - /// ladder and circuit breaker as the full fetch; a uuid the attached - /// plan names is answered from its reference batch. + /// service says of the patch without its archive: the patch it was + /// built from and the artifacts it serves besides the archive, each + /// with its host-rewritten URL and sha512. NO archive download. The gem + /// backend asks this of the patch of each platform gem a lock names, + /// to learn whether every one of them can be vendored before it + /// downloads any. Same grant, statuses, retry ladder and circuit + /// breaker as the full fetch; a uuid the attached plan names is + /// answered from its reference batch. pub(crate) async fn fetch_vendor_reference( &self, uuid: &str, free_only: bool, vendor_url: Option<&str>, patch_server_url: Option<&str>, - ) -> VendorServiceOutcome> { + ) -> VendorServiceOutcome { if let Some(refused) = self.vendor_request_refused(uuid) { return VendorServiceOutcome::Failed(refused); } @@ -1705,10 +1707,10 @@ impl ApiClient { { Ok(result) => ( reference_miss(&result.status).unwrap_or_else(|| { - VendorServiceOutcome::Ready(served_secondary_artifacts( - &result, - patch_server_url, - )) + VendorServiceOutcome::Ready(VendorReference { + rebuilt_from_uuid: result.rebuilt_from_uuid.clone(), + artifacts: served_secondary_artifacts(&result, patch_server_url), + }) }), false, ), @@ -2405,14 +2407,22 @@ pub(crate) struct FetchedVendorPackage { pub prestaged: crate::vendor::prestage::Prestaged, } +/// What the service says of a patch without its archive +/// ([`ApiClient::fetch_vendor_reference`]). +#[derive(Debug, Clone)] +pub(crate) struct VendorReference { + /// The uuid of the patch this one was built from (`rebuiltFromUuid`); + /// `None` for a patch that is itself a source. + pub rebuilt_from_uuid: Option, + /// The served artifacts besides the archive. + pub artifacts: Vec, +} + /// A non-tarball served artifact reference (e.g. `gem-stub-gemspec`): its kind, /// final download URL, and sha512 SRI. Bytes are fetched + verified on demand. #[derive(Debug, Clone)] pub(crate) struct SecondaryArtifact { pub kind: String, - /// The gem platform a `gem-platform` / `gem-platform-stub-gemspec` - /// artifact is for; `None` on every other kind. - pub platform: Option, pub url: String, /// Normalized `sha512-` of the artifact bytes. pub integrity_sri: String, @@ -2517,7 +2527,7 @@ fn reference_miss(status: &str) -> Option> { } /// The served artifacts of a granted reference OTHER than the archive (the -/// gem path-source stub gemspec, the per-platform gem prebuilds, …) — their +/// gem path-source stub gemspec, …) — their /// host-rewritten URL + normalized sha512 — so a backend that needs one can /// download + verify it lazily. Each is skipped unless it carries both a /// url and a sha512. @@ -2542,7 +2552,6 @@ fn served_secondary_artifacts( }; secondary_artifacts.push(SecondaryArtifact { kind: a.kind.clone(), - platform: a.platform.clone(), url, integrity_sri: normalize_sha512_sri(sha512), prefetched: None, diff --git a/crates/socket-patch-core/src/api/ranking.rs b/crates/socket-patch-core/src/api/ranking.rs index 1652d9d25..ccb1947a6 100644 --- a/crates/socket-patch-core/src/api/ranking.rs +++ b/crates/socket-patch-core/src/api/ranking.rs @@ -194,6 +194,14 @@ pub fn cmp_batch_infos(a: &BatchPatchInfo, b: &BatchPatchInfo) -> Ordering { rank_batch_info(a).cmp(&rank_batch_info(b)) } +/// Order a patch selection the way every other collection in the JSON +/// envelope is ordered: by purl, uuid breaking a tie (a release-variant +/// base can keep several qualified purls, and `--all-releases` can keep +/// several patches for one purl). +pub fn sort_by_purl(patches: &mut [PatchSearchResult]) { + patches.sort_by(|a, b| a.purl.cmp(&b.purl).then_with(|| a.uuid.cmp(&b.uuid))); +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/socket-patch-core/src/api/types.rs b/crates/socket-patch-core/src/api/types.rs index cbb947141..590f0822f 100644 --- a/crates/socket-patch-core/src/api/types.rs +++ b/crates/socket-patch-core/src/api/types.rs @@ -311,29 +311,31 @@ pub struct PackageVendorResult { /// other shape reads as no address. #[serde(default)] pub npm_registry_url: Option, + /// The uuid of the patch this one was built from, `null` (or absent) + /// for a patch that is itself a source. The patch of a platform gem + /// (`pkg:gem/@?platform=`) names the patch of + /// the ruby-platform gem it was rebuilt from. Patches whose + /// `rebuiltFromUuid ?? uuid` is equal are the builds of one fix, and + /// the patch registry of any of them lists and serves all of them. A + /// value that is no string reads as absent, where a strict reading + /// would cost every package of the response its grant. + #[serde(default, deserialize_with = "lenient_string")] + pub rebuilt_from_uuid: Option, } /// One served artifact: the native tarball (`kind: "tarball"`), or a -/// second artifact — npm's yarn-berry cache zip (`kind: "yarn-berry-zip"`), -/// gem's path-source stub gemspec (`kind: "gem-stub-gemspec"`), or, per -/// platform a gem patch has a prebuild for, the patched platform gem -/// (`kind: "gem-platform"`) and its stub gemspec -/// (`kind: "gem-platform-stub-gemspec"`). `url` is null only when the -/// artifact isn't stored yet (e.g. an unbuilt berry zip). +/// second artifact — npm's yarn-berry cache zip (`kind: "yarn-berry-zip"`) +/// or gem's path-source stub gemspec (`kind: "gem-stub-gemspec"`). The +/// patch of a platform gem serves the same two kinds as the patch of the +/// ruby gem: its `tarball` is the patched platform `.gem`. `url` is null +/// only when the artifact isn't stored yet (e.g. an unbuilt berry zip). An +/// artifact of a kind this build does not know is read and never used. #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PackageVendorArtifact { pub kind: String, #[serde(default)] pub url: Option, - /// The gem platform the artifact is for (`x86_64-linux-gnu`, - /// `arm64-darwin`, `java`: `Gem::Platform#to_s` as `Gemfile.lock` - /// spells it, never `ruby`). Present exactly on the two `gem-platform*` - /// kinds; a patch with no prebuild serves neither. A value that is no - /// string reads as absent instead of failing the whole response: that - /// artifact is then the prebuild of no platform. - #[serde(default, deserialize_with = "lenient_string")] - pub platform: Option, /// Every ecosystem's tarball populates `sha512` (npm SRI form /// `sha512-`) + `sha1` + `md5`; golang additionally `dirhash_h1` /// (`h1:`); the npm yarn-berry zip carries only `yarn_berry10c0` @@ -580,45 +582,51 @@ mod tests { ); } - /// A gem patch with prebuilds serves, beside the ruby gem's `tarball` - /// and stub, one `gem-platform` gem and stub per built platform; the - /// artifacts every patch served before carry no `platform`. + /// The patch of a platform gem is referenced like any gem patch: a + /// `tarball` (the patched platform `.gem`), a `gem-stub-gemspec`, and + /// `rebuiltFromUuid` naming the ruby-platform gem's patch it was built + /// from. A source patch states `null`. #[test] - fn package_vendor_result_reads_the_gem_platform_artifacts() { + fn package_vendor_result_reads_a_platform_gem_patch() { let json = r#"{ "status": "granted", - "purl": "pkg:gem/nokogiri@1.18.10?platform=ruby", - "url": "https://patch.example/nokogiri-1.18.10.gem", + "purl": "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu", + "url": "https://patch.example/nokogiri-1.19.3-x86_64-linux-gnu.gem", + "rebuiltFromUuid": "11111111-1111-4111-8111-111111111111", "artifacts": [ - { "kind": "tarball", "url": "https://patch.example/nokogiri-1.18.10.gem", - "integrity": { "sha512": "sha512-ruby" } }, - { "kind": "gem-platform", "platform": "x86_64-linux-gnu", - "url": "https://patch.example/nokogiri-1.18.10-x86_64-linux-gnu.gem", + { "kind": "tarball", + "url": "https://patch.example/nokogiri-1.19.3-x86_64-linux-gnu.gem", "contentType": "application/octet-stream", "sizeBytes": 4000000, - "integrity": { "sha512": "sha512-prebuild" } }, - { "kind": "gem-platform-stub-gemspec", "platform": "x86_64-linux-gnu", - "url": "https://patch.example/nokogiri-1.18.10-x86_64-linux-gnu.gemspec", + "integrity": { "sha512": "sha512-platform" } }, + { "kind": "gem-stub-gemspec", + "url": "https://patch.example/nokogiri-1.19.3-x86_64-linux-gnu.gemspec", "integrity": { "sha512": "sha512-stub" } } ] }"#; let result: PackageVendorResult = serde_json::from_str(json).unwrap(); - let artifacts = result.artifacts.unwrap(); - let seen: Vec<(&str, Option<&str>)> = artifacts - .iter() - .map(|a| (a.kind.as_str(), a.platform.as_deref())) - .collect(); assert_eq!( - seen, - [ - ("tarball", None), - ("gem-platform", Some("x86_64-linux-gnu")), - ("gem-platform-stub-gemspec", Some("x86_64-linux-gnu")), - ] + result.rebuilt_from_uuid.as_deref(), + Some("11111111-1111-4111-8111-111111111111") ); + let artifacts = result.artifacts.unwrap(); + let kinds: Vec<&str> = artifacts.iter().map(|a| a.kind.as_str()).collect(); + assert_eq!(kinds, ["tarball", "gem-stub-gemspec"]); assert_eq!( - artifacts[1].integrity.sha512.as_deref(), - Some("sha512-prebuild") + artifacts[0].integrity.sha512.as_deref(), + Some("sha512-platform") ); + + let source: PackageVendorResult = serde_json::from_str( + r#"{ "status": "granted", "url": "https://patch.example/a.gem", + "rebuiltFromUuid": null }"#, + ) + .unwrap(); + assert_eq!(source.rebuilt_from_uuid, None); + let unstated: PackageVendorResult = serde_json::from_str( + r#"{ "status": "granted", "url": "https://patch.example/a.gem" }"#, + ) + .unwrap(); + assert_eq!(unstated.rebuilt_from_uuid, None); } #[test] @@ -762,90 +770,31 @@ mod tests { ); } - /// A gem patch with a built prebuild: the per-platform artifacts carry - /// `platform`, and the override lists each platform's sha256 under - /// `gemPlatforms`. Both are absent from a patch with no prebuild, which - /// reads as none. - #[test] - fn package_vendor_result_reads_gem_prebuilds() { - let sha = "ab".repeat(32); - let json = serde_json::json!({ - "status": "granted", - "purl": "pkg:gem/nokogiri@1.18.10?platform=ruby", - "url": "https://patch.socket.dev/patch/gem/nokogiri-1.18.10.gem", - "artifacts": [ - { "kind": "tarball", "url": "https://patch.socket.dev/a.gem", - "integrity": { "sha256": sha } }, - { "kind": "gem-platform", "platform": "x86_64-linux-gnu", - "url": "https://patch.socket.dev/a-x86_64-linux-gnu.gem", - "contentType": "application/octet-stream", "sizeBytes": 4000000, - "integrity": { "sha256": sha } }, - { "kind": "gem-platform-stub-gemspec", "platform": "x86_64-linux-gnu", - "url": "https://patch.socket.dev/a-x86_64-linux-gnu.gemspec", - "integrity": {} } - ], - "registryOverride": { - "kind": "rubygems-compact-index", - "indexUrl": "https://patch.socket.dev/patch-registry/gem/t/u/", - "identifiers": { - "name": "nokogiri", "version": "1.18.10", - "gemChecksumSha256": sha, - "gemPlatforms": [ - { "platform": "x86_64-linux-gnu", "gemChecksumSha256": sha } - ] - } - } - }); - let result: PackageVendorResult = serde_json::from_value(json.clone()).unwrap(); - let artifacts = result.artifacts.as_deref().unwrap(); - let platforms: Vec<_> = artifacts - .iter() - .map(|a| (a.kind.as_str(), a.platform.as_deref())) - .collect(); - assert_eq!( - platforms, - [ - ("tarball", None), - ("gem-platform", Some("x86_64-linux-gnu")), - ("gem-platform-stub-gemspec", Some("x86_64-linux-gnu")), - ] - ); - let ids = result.registry_override.unwrap().identifiers; - assert_eq!(ids.gem_platforms.len(), 1); - assert_eq!(ids.gem_platforms[0].platform, "x86_64-linux-gnu"); - assert_eq!(ids.gem_platforms[0].gem_checksum_sha256, sha); - - let mut bare = json; - bare["registryOverride"]["identifiers"] - .as_object_mut() - .unwrap() - .remove("gemPlatforms"); - let result: PackageVendorResult = serde_json::from_value(bare).unwrap(); - assert!(result - .registry_override - .unwrap() - .identifiers - .gem_platforms - .is_empty()); - } - - /// One reference response answers for every package of a batch. A - /// `gemPlatforms` the service sends as `null`, or with an entry that - /// lacks its platform or its checksum, must not cost the other packages - /// (or the gem itself) their grants: `null` is no prebuild, and such an - /// entry is dropped, leaving that platform without one. + /// A response that still carries what the patch service once listed + /// for a gem patch's platform builds (`gem-platform` and + /// `gem-platform-stub-gemspec` artifacts with a `platform`, and + /// `gemPlatforms` among the override's identifiers) reads as the patch + /// of the ruby gem alone: the retired fields are ignored, in whatever + /// shape they come. #[test] - fn a_malformed_gem_platforms_field_never_fails_the_batch() { + fn package_vendor_result_ignores_the_retired_platform_fields() { let sha = "ab".repeat(32); let gem = |platforms: serde_json::Value| { serde_json::json!({ "status": "granted", - "url": "https://patch.socket.dev/patch/gem/a.gem", + "purl": "pkg:gem/nokogiri@1.18.10?platform=ruby", + "url": "https://patch.socket.dev/patch/gem/nokogiri-1.18.10.gem", "artifacts": [ { "kind": "tarball", "url": "https://patch.socket.dev/a.gem", "integrity": { "sha256": sha } }, - { "kind": "gem-platform", "platform": null, "url": null }, - { "kind": "gem-platform", "platform": 7 } + { "kind": "gem-platform", "platform": "x86_64-linux-gnu", + "url": "https://patch.socket.dev/a-x86_64-linux-gnu.gem", + "contentType": "application/octet-stream", "sizeBytes": 4000000, + "integrity": { "sha256": sha } }, + { "kind": "gem-platform-stub-gemspec", "platform": 7, + "url": "https://patch.socket.dev/a-x86_64-linux-gnu.gemspec", + "integrity": {} }, + { "kind": "gem-platform", "platform": null, "url": null } ], "registryOverride": { "kind": "rubygems-compact-index", @@ -860,41 +809,69 @@ mod tests { }; let response: PackageVendorResponse = serde_json::from_value(serde_json::json!({ "results": { + "listed": gem(serde_json::json!([ + { "platform": "x86_64-linux-gnu", "gemChecksumSha256": sha } + ])), "null-list": gem(serde_json::Value::Null), "no-list": gem(serde_json::json!("x86_64-linux-gnu")), "holes": gem(serde_json::json!([ { "platform": "arm64-darwin", "gemChecksumSha256": null }, - { "platform": "java" }, - { "gemChecksumSha256": sha }, - { "platform": "", "gemChecksumSha256": sha }, - { "platform": 3, "gemChecksumSha256": sha }, - "x86_64-linux-gnu", - null, - { "platform": "x86_64-linux-gnu", "gemChecksumSha256": sha } + { "platform": 3 }, "x86_64-linux-gnu", null ])), "npm": { "status": "granted", "url": "https://patch.socket.dev/x.tgz" } } })) - .expect("the batch reads whatever one gem's prebuild list holds"); - assert_eq!(response.results.len(), 4, "no package lost its result"); - let prebuilds = |uuid: &str| { + .expect("the batch reads whatever the retired fields hold"); + assert_eq!(response.results.len(), 5, "no package lost its result"); + for uuid in ["listed", "null-list", "no-list", "holes"] { let result = &response.results[uuid]; assert_eq!(result.status, "granted"); + assert_eq!(result.rebuilt_from_uuid, None); let ids = &result.registry_override.as_ref().unwrap().identifiers; assert_eq!(ids.gem_checksum_sha256.as_deref(), Some(sha.as_str())); - ids.gem_platforms + assert_eq!(ids.gem_platform, None); + let kinds: Vec<&str> = result + .artifacts .iter() - .map(|p| (p.platform.clone(), p.gem_checksum_sha256.clone())) - .collect::>() - }; - assert!(prebuilds("null-list").is_empty()); - assert!(prebuilds("no-list").is_empty()); + .flatten() + .map(|a| a.kind.as_str()) + .collect(); + assert_eq!( + kinds, + [ + "tarball", + "gem-platform", + "gem-platform-stub-gemspec", + "gem-platform" + ], + "the artifacts are read; nothing looks the retired kinds up" + ); + } + } + + /// One reference response answers for every package of a batch. A + /// `rebuiltFromUuid` that is no string must not cost the other packages + /// (or the patch itself) their grants: it reads as a source patch. + #[test] + fn a_malformed_rebuilt_from_uuid_never_fails_the_batch() { + let response: PackageVendorResponse = serde_json::from_value(serde_json::json!({ + "results": { + "number": { "status": "granted", "url": "https://patch.socket.dev/a.gem", + "rebuiltFromUuid": 7 }, + "object": { "status": "granted", "url": "https://patch.socket.dev/b.gem", + "rebuiltFromUuid": { "uuid": "x" } }, + "string": { "status": "granted", "url": "https://patch.socket.dev/c.gem", + "rebuiltFromUuid": "22222222-2222-4222-8222-222222222222" }, + "npm": { "status": "granted", "url": "https://patch.socket.dev/x.tgz" } + } + })) + .expect("the batch reads whatever one patch's `rebuiltFromUuid` holds"); + assert_eq!(response.results.len(), 4, "no package lost its result"); + assert_eq!(response.results["number"].rebuilt_from_uuid, None); + assert_eq!(response.results["object"].rebuilt_from_uuid, None); assert_eq!( - prebuilds("holes"), - [("x86_64-linux-gnu".to_string(), sha.clone())], - "only the entry that names a platform and a checksum is a prebuild" + response.results["string"].rebuilt_from_uuid.as_deref(), + Some("22222222-2222-4222-8222-222222222222") ); - let artifacts = response.results["holes"].artifacts.as_deref().unwrap(); - assert!(artifacts.iter().all(|a| a.platform.is_none())); } } diff --git a/crates/socket-patch-core/src/formats/gem/mod.rs b/crates/socket-patch-core/src/formats/gem/mod.rs index 9cd230b25..c5cc0652a 100644 --- a/crates/socket-patch-core/src/formats/gem/mod.rs +++ b/crates/socket-patch-core/src/formats/gem/mod.rs @@ -409,6 +409,45 @@ pub fn locked_gem_builds(lock: &str, purls: &[String]) -> Vec> { .collect() } +/// The builds the Bundler lock text `lock` resolves each gem of `purls` to, +/// read from every source section: the `GEM` sections, and `PATH` / `GIT` / +/// `PLUGIN SOURCE` too. A gem vendored as platform gems holds one entry +/// per platform in a `PATH` section, and those are still the builds the +/// project installs: a run that selects patches for the project's builds +/// asks this, where [`locked_gem_builds`] answers which builds a registry +/// serves. Element `i` answers `purls[i]`, the ruby-platform gem first. +pub fn resolved_gem_builds(lock: &str, purls: &[String]) -> Vec> { + let lock = crate::utils::line_endings::to_lf(lock); + let parsed = parse(&lock); + purls + .iter() + .map(|purl| { + let Some((name, version)) = gem_coordinates(purl) else { + return Vec::new(); + }; + let mut builds = LockedBuilds::default(); + let specs = parsed + .sections + .iter() + .flat_map(|section| section.specs.iter().filter_map(|line| line.parsed)) + .filter(|spec| spec.name == name && spec.version == version); + for spec in specs { + match spec.platform { + Some(platform) => { + builds.platforms.insert(platform); + } + None => builds.ruby = true, + } + } + builds + .ids(&name, &version) + .iter() + .map(GemBuild::of) + .collect() + }) + .collect() +} + impl<'t> GemfileLock<'t> { /// Parse a lock text ([`parse`]). pub fn parse(text: &'t str) -> Self { @@ -917,6 +956,26 @@ mod tests { vec![], ] ); + // What the project resolves, in whichever section: the `PATH` + // section's platform entry too (a gem vendored as platform gems). + let resolved: Vec> = resolved_gem_builds(&text, &purls) + .into_iter() + .map(|builds| builds.into_iter().map(|build| build.leaf).collect()) + .collect(); + assert_eq!( + resolved, + [ + vec![ + "nokogiri-1.18.10-aarch64-linux-musl".to_string(), + "nokogiri-1.18.10-arm64-darwin".to_string(), + "nokogiri-1.18.10-x86_64-linux-gnu".to_string() + ], + vec![], + vec![], + vec![], + ], + "every section's specs, and no CHECKSUMS entry" + ); let purl = "pkg:gem/nokogiri@1.18.10"; assert_eq!( GemBuild::of_leaf(purl, "nokogiri-1.18.10-arm64-darwin") diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index 4c08062ed..a4b80e632 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -115,10 +115,14 @@ pub struct Candidate { /// reason). Candidate order. The disk and memory paths both report these /// as the `unpinned` rows of the `redirect` block, and the disk path's /// human output lists them as "Not hosted". +/// +/// `quiet` are the candidates with nothing in the project to pin +/// ([`quiet_candidates`]): they are not reported at all. pub fn unconfirmed_candidates( candidates: &[Candidate], confirmed: &[(String, String)], skipped: &[SkippedPatch], + quiet: &BTreeSet, ) -> Vec<(String, String)> { candidates .iter() @@ -128,10 +132,70 @@ pub fn unconfirmed_candidates( .any(|(purl, uuid)| *purl == c.purl && *uuid == c.dep.patch_uuid) }) .filter(|c| !skipped.iter().any(|s| s.uuid == c.dep.patch_uuid)) + .filter(|c| !quiet.contains(&c.dep.patch_uuid)) .map(|c| (c.purl.clone(), c.dep.patch_uuid.clone())) .collect() } +/// The fix each gem patch among `candidates` belongs to, by patch uuid: the +/// uuid of the patch it was built from, or its own +/// ([`gem_family`](crate::patch::redirect::gem_family)). +pub fn gem_fixes_of(candidates: &[Candidate]) -> HashMap { + candidates + .iter() + .filter(|c| c.dep.ecosystem == "gem") + .map(|c| { + let fix = crate::patch::redirect::gem_family(&c.dep); + ( + c.dep.patch_uuid.to_ascii_lowercase(), + fix.to_ascii_lowercase(), + ) + }) + .collect() +} + +/// Take the candidates a rollout deferred out of `candidates`, each fix +/// whole. A gem fix has one patch per platform gem, and its source patch +/// only lends the registry: it has no row of its own to defer, and left +/// behind alone it would be judged as a fix with no patch for the locked +/// builds. So every patch of a gem version goes with a deferred one. +pub fn drop_deferred(candidates: &mut Vec, deferred: impl Fn(&Candidate) -> bool) { + let gems: HashSet<(String, String)> = candidates + .iter() + .filter(|c| c.dep.ecosystem == "gem" && deferred(c)) + .map(|c| (c.dep.name.clone(), c.dep.version.clone())) + .collect(); + candidates.retain(|c| { + let of_deferred_gem = + c.dep.ecosystem == "gem" && gems.contains(&(c.dep.name.clone(), c.dep.version.clone())); + !deferred(c) && !of_deferred_gem + }); +} + +/// The uuids of the candidates that have nothing in the project to pin, +/// which a run neither confirms nor reports as left unpinned: +/// +/// * a gem patch the Bundler lock has no build for +/// ([`RewriteResult::gem_idle_uuids`]): the patch of a platform the lock +/// does not name, or the source patch of a fix whose registry a lock of +/// platform builds takes as its source; +/// * a candidate the run did not select (`selected`: the run's +/// `(purl, uuid)` selection): the source patch of a gem fix, which +/// [`build_candidates`] adds for its registry. +pub fn quiet_candidates( + candidates: &[Candidate], + selected: &[(String, String)], + rewrite: &RewriteResult, +) -> BTreeSet { + let selected: HashSet<&str> = selected.iter().map(|(_, uuid)| uuid.as_str()).collect(); + candidates + .iter() + .map(|c| c.dep.patch_uuid.as_str()) + .filter(|uuid| rewrite.gem_idle_uuids.contains(*uuid) || !selected.contains(uuid)) + .map(str::to_string) + .collect() +} + /// A selected patch that was not redirected, and why (the `skipped[]` /// entries of the `redirect` block). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -273,125 +337,223 @@ pub fn build_candidates( skipped: &mut Vec, warnings: &mut Vec, ) -> Vec { - use crate::patch::redirect::grant::{self, Flaw}; let mut candidates = Vec::new(); for (sel_purl, sel_uuid) in selected { - let Some(reference) = references.get(sel_uuid) else { - skipped.push(SkippedPatch::new(sel_purl, sel_uuid, "not_found")); - continue; - }; - if reference.status != "granted" && reference.status != "reused" { - skipped.push(SkippedPatch::new(sel_purl, sel_uuid, &reference.status)); - continue; + match candidate_of(sel_purl, sel_uuid, references, patch_server_origins) { + Ok(candidate) => candidates.push(candidate), + Err(refused) => { + let (skip, warned) = *refused; + warnings.extend(warned); + skipped.push(skip); + } } - let purl = reference.purl.as_deref().unwrap_or(sel_purl); - let Some((ecosystem, name, version)) = purl_parts(purl) else { - skipped.push(SkippedPatch::new(purl, sel_uuid, "bad_purl")); - continue; + } + // A gem fix has one patch per platform gem, and the registry of its + // source patch is the one Bundler source of them all. A selection of + // platform patches alone (a lock with no ruby-platform entry) does not + // hold that patch, so it joins the candidates for its registry: it + // pins nothing and is never reported (see [`gem_family_sources`]). A + // source whose reference is not usable is left out, and the gem + // rewriter then leaves the gem alone and says why. + for source in gem_family_sources(&candidates) { + let member = |c: &&Candidate| { + crate::patch::redirect::gem_family(&c.dep) == source && c.dep.patch_uuid != source }; - let Some(url) = reference.url.clone() else { - skipped.push(SkippedPatch::new(purl, sel_uuid, "no_url")); + let Some(purl) = candidates.iter().find(member).map(|c| { + format!( + "{}?platform=ruby", + crate::utils::purl::strip_purl_qualifiers(&c.purl) + ) + }) else { continue; }; - let mut integrity = reference - .artifacts - .iter() - .flatten() - .find(|a| a.kind == "tarball") - .map(|a| a.integrity.clone()) - .unwrap_or_default(); - // The yarn-berry cache zip carries the `yarnBerry10c0` checksum the - // berry rewriter pins (berry verifies the zip, not the tarball). - // Merge it in; the zip URL itself is never read. - let berry_zip = reference - .artifacts - .iter() - .flatten() - .find(|a| a.kind == "yarn-berry-zip"); - if let Some(c) = berry_zip.and_then(|a| a.integrity.yarn_berry10c0.clone()) { - integrity.yarn_berry10c0 = Some(c); - } - // goproxy: the hosted-Go hash pair rides the override's - // identifiers (the tarball's dirhashH1 is the original-path - // flavor, kept for vendor-mode verification); the golang rewriter - // reads the normalized integrity, so merge — the gopatch-flavor zip - // h1 REPLACES dirhashH1 here. Only both together: a half-merged - // pair would trip the rewriter's fail-closed integrity check by - // design. - if let Some(ov) = reference - .registry_override - .as_ref() - .filter(|o| o.kind == "goproxy") - { - if let (Some(zip_h1), Some(gomod_h1)) = ( - ov.identifiers.go_zip_dirhash_h1.clone(), - ov.identifiers.go_mod_h1.clone(), - ) { - integrity.dirhash_h1 = Some(zip_h1); - integrity.go_mod_h1 = Some(gomod_h1); - } + if let Ok(candidate) = candidate_of(&purl, &source, references, patch_server_origins) { + candidates.push(candidate); } - // The grant token is never a top-level reference field — it only - // rides the URLs the reference endpoint hands back, as the path - // level before the patch uuid. Recover it so the rewriters' - // rotation-idempotency guards (which wildcard the token path level - // of a previously-written URL) don't depend on it being derivable - // from the URL alone (with an empty token the gem guard does not - // recognise the `source:` a previous scan wrote as its own). - let token = reference - .registry_override - .as_ref() - .and_then(|o| crate::patch::redirect::grant_token_path_segment(&o.index_url, sel_uuid)) - .or_else(|| crate::patch::redirect::grant_token_path_segment(&url, sel_uuid)) - .unwrap_or_default(); - let mut dep = DepOverride { - ecosystem, - name, - namespace: None, - version, - token, - patch_uuid: sel_uuid.clone(), - artifact_url: url, - npm_registry_url: reference.npm_registry_url.clone(), - registry_override: reference.registry_override.clone(), - integrity, - }; - // A registry address pnpm could not route the artifact URL to - // reads as not served: the pin then takes the `trustLockfile` path. - dep.npm_registry_url = grant::npm_registry_url(&dep).map(str::to_string); - // The served purl is printed and recorded as it is: a line break in - // one would forge a line of the run's output. - let checked = if purl.chars().any(|c| c.is_whitespace() || c.is_control()) { - Err(Flaw::Malformed( - "its package URL holds whitespace".to_string(), - )) - } else { - grant::check(&dep, patch_server_origins) + } + candidates +} + +/// The source patches of the gem fixes among `candidates` that are not +/// candidates themselves: each a uuid some platform gem's patch was built +/// from (`rebuiltFromUuid`), sorted. The run asks the patch API for their +/// references too ([`missing_gem_sources`]), and [`build_candidates`] adds +/// the ones it can use. +fn gem_family_sources(candidates: &[Candidate]) -> Vec { + let held: HashSet<&str> = candidates + .iter() + .map(|c| c.dep.patch_uuid.as_str()) + .collect(); + let sources: BTreeSet = candidates + .iter() + .filter(|c| c.dep.ecosystem == "gem") + .map(|c| crate::patch::redirect::gem_family(&c.dep)) + .filter(|source| !held.contains(source)) + .map(str::to_string) + .collect(); + sources.into_iter().collect() +} + +/// The uuids the run must still ask the patch API about before +/// [`build_candidates`]: the source patch of each gem fix `references` +/// names (`rebuiltFromUuid`) and holds no answer for, sorted. One more +/// reference request when there are any, none otherwise: a lock of +/// platform builds alone selects no ruby-platform patch, and the registry +/// of the fix's source patch is still the gem's source. +pub fn missing_gem_sources(references: &HashMap) -> Vec { + let sources: BTreeSet = references + .values() + .filter(|reference| reference.status == "granted" || reference.status == "reused") + .filter(|reference| { + reference + .purl + .as_deref() + .is_some_and(|purl| purl.starts_with("pkg:gem/")) + }) + .filter_map(|reference| reference.rebuilt_from_uuid.clone()) + .filter(|source| { + crate::patch::path_safety::is_canonical_uuid(source) && !references.contains_key(source) + }) + .collect(); + sources.into_iter().collect() +} + +/// The candidate of one reference grant ([`build_candidates`]), or why +/// there is none: the skip to record and, for a grant refused for its +/// shape, its warning. +fn candidate_of( + sel_purl: &str, + sel_uuid: &str, + references: &HashMap, + patch_server_origins: &[String], +) -> Result)>> { + use crate::patch::redirect::grant::{self, Flaw}; + let skip = + |purl: &str, reason: &str| Box::new((SkippedPatch::new(purl, sel_uuid, reason), None)); + let Some(reference) = references.get(sel_uuid) else { + return Err(skip(sel_purl, "not_found")); + }; + 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 Some((ecosystem, name, version)) = purl_parts(purl) else { + return Err(skip(purl, "bad_purl")); + }; + let Some(url) = reference.url.clone() else { + return Err(skip(purl, "no_url")); + }; + let mut integrity = reference + .artifacts + .iter() + .flatten() + .find(|a| a.kind == "tarball") + .map(|a| a.integrity.clone()) + .unwrap_or_default(); + // The yarn-berry cache zip carries the `yarnBerry10c0` checksum the + // berry rewriter pins (berry verifies the zip, not the tarball). + // Merge it in; the zip URL itself is never read. + let berry_zip = reference + .artifacts + .iter() + .flatten() + .find(|a| a.kind == "yarn-berry-zip"); + if let Some(c) = berry_zip.and_then(|a| a.integrity.yarn_berry10c0.clone()) { + integrity.yarn_berry10c0 = Some(c); + } + // goproxy: the hosted-Go hash pair rides the override's + // identifiers (the tarball's dirhashH1 is the original-path + // flavor, kept for vendor-mode verification); the golang rewriter + // reads the normalized integrity, so merge — the gopatch-flavor zip + // h1 REPLACES dirhashH1 here. Only both together: a half-merged + // pair would trip the rewriter's fail-closed integrity check by + // design. + if let Some(ov) = reference + .registry_override + .as_ref() + .filter(|o| o.kind == "goproxy") + { + if let (Some(zip_h1), Some(gomod_h1)) = ( + ov.identifiers.go_zip_dirhash_h1.clone(), + ov.identifiers.go_mod_h1.clone(), + ) { + integrity.dirhash_h1 = Some(zip_h1); + integrity.go_mod_h1 = Some(gomod_h1); + } + } + // The grant token is never a top-level reference field — it only + // rides the URLs the reference endpoint hands back, as the path + // level before the patch uuid. Recover it so the rewriters' + // rotation-idempotency guards (which wildcard the token path level + // of a previously-written URL) don't depend on it being derivable + // from the URL alone (with an empty token the gem guard does not + // recognise the `source:` a previous scan wrote as its own). + let token = reference + .registry_override + .as_ref() + .and_then(|o| crate::patch::redirect::grant_token_path_segment(&o.index_url, sel_uuid)) + .or_else(|| crate::patch::redirect::grant_token_path_segment(&url, sel_uuid)) + .unwrap_or_default(); + let mut dep = DepOverride { + ecosystem, + name, + namespace: None, + version, + token, + patch_uuid: sel_uuid.to_string(), + artifact_url: url, + npm_registry_url: reference.npm_registry_url.clone(), + registry_override: reference.registry_override.clone(), + integrity, + }; + // A registry address pnpm could not route the artifact URL to + // reads as not served: the pin then takes the `trustLockfile` path. + dep.npm_registry_url = grant::npm_registry_url(&dep).map(str::to_string); + // A gem patch is the patch of one platform gem, which its package URL + // names, and says which patch it was built from. Both are the + // reference's to say, never the override's own fields. + let is_gem = dep.ecosystem == "gem"; + if let Some(ov) = dep.registry_override.as_mut() { + let platform = crate::utils::purl::gem_platform_qualifier(purl) + .or_else(|| crate::utils::purl::gem_platform_qualifier(sel_purl)); + ov.identifiers.gem_platform = platform.filter(|_| is_gem).map(str::to_string); + ov.identifiers.gem_rebuilt_from_uuid = reference + .rebuilt_from_uuid + .clone() + .filter(|source| is_gem && !source.is_empty() && source != sel_uuid); + } + // The served purl is printed and recorded as it is: a line break in + // one would forge a line of the run's output. + let checked = if purl.chars().any(|c| c.is_whitespace() || c.is_control()) { + Err(Flaw::Malformed( + "its package URL holds whitespace".to_string(), + )) + } else { + grant::check(&dep, patch_server_origins) + }; + if let Err(flaw) = checked { + let (code, reason) = match flaw { + Flaw::Malformed(reason) => (GRANT_MALFORMED, reason), + Flaw::InsecureUrl(reason) => (GRANT_INSECURE_URL, reason), }; - if let Err(flaw) = checked { - let (code, reason) = match flaw { - Flaw::Malformed(reason) => (GRANT_MALFORMED, reason), - Flaw::InsecureUrl(reason) => (GRANT_INSECURE_URL, reason), - }; - // Keyed and worded by the selection's purl, the spelling the - // project's own files gave: the served one is what failed. - let detail = format!( - "{sel_purl}: the patch server's reference for it was refused ({reason}); \ - nothing was written for it, so it stays unpatched" - ); - warnings.push(warning(code, detail.clone())); - skipped.push(SkippedPatch { - detail: Some(detail), + // Keyed and worded by the selection's purl, the spelling the + // project's own files gave: the served one is what failed. + let detail = format!( + "{sel_purl}: the patch server's reference for it was refused ({reason}); \ + nothing was written for it, so it stays unpatched" + ); + return Err(Box::new(( + SkippedPatch { + detail: Some(detail.clone()), ..SkippedPatch::new(sel_purl, sel_uuid, code) - }); - continue; - } - candidates.push(Candidate { - purl: purl.to_string(), - dep, - }); + }, + Some(warning(code, detail)), + ))); } - candidates + Ok(Candidate { + purl: purl.to_string(), + dep, + }) } /// Skip reason and warning code of a patch whose ecosystem cannot be served @@ -2318,6 +2480,50 @@ async fn read_gemspecs( ); } +/// The compact-index documents the gem rewriter checks a lock of platform +/// builds against, sorted: `/info/` of the registry of each gem +/// fix whose patches cover a build that the Bundler lock among `files` +/// names as a platform build. That registry becomes the gem's one source, +/// and the lock pins each build to the sha256 its own patch states: the +/// document says whether the registry serves exactly that. One small +/// request per such gem, none for a gem locked as its ruby-platform gem +/// alone. The caller reads them (from the patch server, also for a +/// mirrored candidate) and hands the answers to [`record_gem_index`]. +pub fn gem_index_targets( + candidates: &[Candidate], + files: &BTreeMap, +) -> Vec { + // The rewriter's own choice of fix and of registry. + let deps: Vec<&DepOverride> = candidates.iter().map(|c| &c.dep).collect(); + crate::patch::redirect::gem_index_urls(files, &deps) +} + +/// Hand the documents of [`gem_index_targets`] to the gem rewriter: each +/// URL with the text read from it, or why it could not be read. +pub fn record_gem_index(read: &mut CandidateFiles, documents: &[(String, Result)]) { + // Handed in for every project with a Bundler lock, also with nothing + // read: the rewriter then knows that registries are read here, and + // pins no platform-locked gem whose registry's document it lacks. + let (_, lock_name) = crate::patch::redirect::gem_pair(&read.files); + if documents.is_empty() && !read.files.contains_key(lock_name) { + return; + } + let listed: serde_json::Map = documents + .iter() + .map(|(url, document)| { + let value = match document { + Ok(body) => serde_json::json!({ "body": body }), + Err(why) => serde_json::json!({ "error": why }), + }; + (url.clone(), value) + }) + .collect(); + read.files.insert( + crate::patch::redirect::GEM_INDEX_KEY.to_string(), + serde_json::Value::Object(listed).to_string(), + ); +} + /// The pypi wheels whose metadata a native lock rewrite needs, in /// candidate order: `(override, sha256)` of every `.whl` artifact some /// `uv.lock` / PEP 723 script lock would rewrite. Each native lock is @@ -3211,12 +3417,26 @@ async fn unattributed_pins( .collect(), _ => BTreeSet::new(), }; + // A gem locked as platform builds is pinned to one patch per build, + // and the lock names the registry of one patch for all of them (the + // fix's source patch, or one build's own): discovery reads that pin, + // so each build's patch is judged by it. + let pinned_as: HashMap<&str, &str> = done + .rewrite + .gem_anchor_uuids + .iter() + .map(|(uuid, anchor)| (uuid.as_str(), anchor.as_str())) + .collect(); let vetoed = done .confirmed .iter() .filter(|(purl, uuid)| { - !attributed.contains(uuid.as_str()) - && contested.contains(uuid.as_str()) + let pin = pinned_as + .get(uuid.as_str()) + .copied() + .unwrap_or(uuid.as_str()); + !attributed.contains(pin) + && contested.contains(pin) && !done.rewrite.bundled_skipped_uuids.contains(uuid) && !done.rewrite.alias_skipped_entries.contains_key(uuid) && !exempt.contains(uuid) @@ -5902,6 +6122,9 @@ fn confirm( // report: the URL in a block that was changed by hand pins nothing. .filter(|(name, _)| name.as_str() != crate::bazel::maven::FILE) .filter(|(name, _)| !crate::patch::redirect::sbt::is_synthetic_key(name)) + // What a patch registry lists, read for the gem rewriter: its key + // holds the registry's URL and pins nothing. + .filter(|(name, _)| name.as_str() != crate::patch::redirect::GEM_INDEX_KEY) .map(|(name, content)| (name.as_str(), rewrite.files.get(name).unwrap_or(content))) .chain( rewrite @@ -5939,6 +6162,18 @@ fn confirm( { return ProbeStep::Decided(false); } + // A gem the lock names as platform builds has one patch per + // build and one registry for all of them (the fix's source + // patch's), so the gem rewriter's own report says which build + // is pinned to which patch: the registry URL in the lock + // proves nothing about one of them. A gem patch the lock has + // no build for pins nothing. + if rewrite.gem_family_uuids.contains(uuid) { + return ProbeStep::Decided(rewrite.confirmed_gem_uuids.contains(uuid)); + } + if rewrite.gem_idle_uuids.contains(uuid) { + return ProbeStep::Decided(false); + } // An sbt build's Maven pins are confirmed by the sbt rewriter's // own report: the generated file names the index URL whether or // not the pin was verified against the build's evidence (so it @@ -7092,70 +7327,230 @@ mod tests { ); } - /// One reference response answers for a whole batch. A prebuild entry - /// that IS a platform and a checksum, but not in the shape the lock - /// takes, fails the grant it rides in and no other: the gem is skipped - /// with the field named, and the other package keeps its candidate. + /// A granted reference of a patch of the gem nokogiri 1.19.3: the + /// patch of the platform gem `platform` (`None`: of the ruby gem), + /// built from `source` when given. + fn gem_reference( + uuid: &str, + platform: Option<&str>, + source: Option<&str>, + ) -> PackageVendorResult { + let suffix = platform.map(|p| format!("-{p}")).unwrap_or_default(); + reference(serde_json::json!({ + "status": "granted", + "url": format!("https://patch.example/patch/gem/t/{uuid}/nokogiri-1.19.3{suffix}.gem"), + "purl": format!("pkg:gem/nokogiri@1.19.3?platform={}", platform.unwrap_or("ruby")), + "rebuiltFromUuid": source, + "artifacts": [ + {"kind": "tarball", "url": null, "integrity": {"sha256": "a".repeat(64)}}, + {"kind": "gem-stub-gemspec", "url": null, "integrity": {}} + ], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": format!("https://patch.example/patch-registry/gem/t/{uuid}/"), + "identifiers": { + "name": "nokogiri", "version": "1.19.3", + "gemChecksumSha256": "a".repeat(64) + } + } + })) + } + + const GEM_SOURCE: &str = "5e6f7081-92a3-4b4c-8d5e-6f708192a3b4"; + const GEM_LINUX: &str = "5e6f7081-92a3-4b4c-8d5e-6f708192a3b5"; + const GEM_DARWIN: &str = "5e6f7081-92a3-4b4c-8d5e-6f708192a3b6"; + + /// Each platform gem of a fix has a patch of its own. A candidate says + /// which gem its patch is of (the reference's package URL) and which + /// patch it was built from (`rebuiltFromUuid`); nothing an override's + /// own identifiers say about either is taken. #[test] - fn a_wrong_gem_prebuild_fails_only_its_own_grant() { - const GEM: &str = "pkg:gem/nokogiri@1.18.10"; - const NPM: &str = "pkg:npm/c@1"; - const GEM_UUID: &str = "5e6f7081-92a3-4b4c-8d5e-6f708192a3b4"; + fn gem_candidates_carry_their_platform_and_the_patch_they_were_built_from() { + use crate::patch::redirect::{gem_family, gem_platform}; + let mut source = gem_reference(GEM_SOURCE, None, None); + // Identifiers that claim what only the reference may say. + let ids = &mut source.registry_override.as_mut().unwrap().identifiers; + ids.gem_platform = Some("java".into()); + ids.gem_rebuilt_from_uuid = Some(GEM_DARWIN.into()); let refs = HashMap::from([ + (GEM_SOURCE.to_string(), source), ( - GEM_UUID.to_string(), - reference(serde_json::json!({ - "status": "granted", - "url": format!("https://patch.example/patch/gem/t/{GEM_UUID}/nokogiri-1.18.10.gem"), - "purl": GEM, - "artifacts": [{"kind": "tarball", "url": null, "integrity": { - "sha256": "a".repeat(64) - }}], - "registryOverride": { - "kind": "rubygems-compact-index", - "indexUrl": format!("https://patch.example/patch-registry/gem/t/{GEM_UUID}/"), - "identifiers": { - "name": "nokogiri", "version": "1.18.10", - "gemChecksumSha256": "a".repeat(64), - "gemPlatforms": [ - {"platform": "arm64-darwin", "gemChecksumSha256": "not-a-digest"} - ] - } - } - })), - ), - ( - PATCH_UUID.to_string(), - reference(serde_json::json!({ - "status": "granted", - "url": format!("https://patch.example/patch/npm/c/1/tok/{PATCH_UUID}/c-1.tgz"), - "purl": NPM, - "artifacts": [{"kind": "tarball", "url": null, "integrity": { - "sha512": "sha512-x", "sha1": "a".repeat(40) - }}], - "registryOverride": null - })), + GEM_LINUX.to_string(), + gem_reference(GEM_LINUX, Some("x86_64-linux-gnu"), Some(GEM_SOURCE)), ), ]); let selected = vec![ - (GEM.to_string(), GEM_UUID.to_string()), - (NPM.to_string(), PATCH_UUID.to_string()), + ( + "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); - let kept: Vec<&str> = candidates.iter().map(|c| c.purl.as_str()).collect(); - assert_eq!(kept, [NPM], "{skipped:?}"); - assert_eq!(skipped.len(), 1, "{skipped:?}"); + assert!(skipped.is_empty() && warnings.is_empty(), "{skipped:?}"); + let [source, linux] = candidates.as_slice() else { + panic!("two candidates: {candidates:?}"); + }; + assert_eq!(gem_platform(&source.dep), None); + assert_eq!(gem_family(&source.dep), GEM_SOURCE); + assert_eq!(gem_platform(&linux.dep), Some("x86_64-linux-gnu")); + assert_eq!(gem_family(&linux.dep), GEM_SOURCE); + assert!(missing_gem_sources(&refs).is_empty()); + } + + /// 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 + /// the candidates. It was not selected, so it is never reported: not + /// as pinned, and not as left unpinned. A source the run cannot use + /// joins nothing. + #[test] + fn the_source_patch_of_a_gem_fix_joins_the_candidates_for_its_registry() { + use crate::patch::redirect::gem_family; + let mut refs = HashMap::from([ + ( + GEM_LINUX.to_string(), + gem_reference(GEM_LINUX, Some("x86_64-linux-gnu"), Some(GEM_SOURCE)), + ), + ( + GEM_DARWIN.to_string(), + gem_reference(GEM_DARWIN, Some("arm64-darwin"), Some(GEM_SOURCE)), + ), + ]); + let selected = vec![ + ( + "pkg:gem/nokogiri@1.19.3?platform=arm64-darwin".to_string(), + GEM_DARWIN.to_string(), + ), + ( + "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu".to_string(), + GEM_LINUX.to_string(), + ), + ]; + assert_eq!(missing_gem_sources(&refs), [GEM_SOURCE]); + let build = |refs: &HashMap| { + 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:?}"); + candidates + }; + // Without the source's reference there are the two builds alone. + assert_eq!(build(&refs).len(), 2); + + refs.insert( + GEM_SOURCE.to_string(), + gem_reference(GEM_SOURCE, None, None), + ); + assert!(missing_gem_sources(&refs).is_empty()); + let candidates = build(&refs); + let uuids: Vec<&str> = candidates + .iter() + .map(|c| c.dep.patch_uuid.as_str()) + .collect(); + assert_eq!(uuids, [GEM_DARWIN, GEM_LINUX, GEM_SOURCE]); + assert!(candidates.iter().all(|c| gem_family(&c.dep) == GEM_SOURCE)); + assert_eq!(candidates[2].purl, "pkg:gem/nokogiri@1.19.3?platform=ruby"); + let quiet = quiet_candidates(&candidates, &selected, &RewriteResult::default()); + assert_eq!(quiet, BTreeSet::from([GEM_SOURCE.to_string()])); assert_eq!( - (skipped[0].purl.as_str(), skipped[0].reason.as_str()), - (GEM, GRANT_MALFORMED) + unconfirmed_candidates(&candidates, &[], &[], &quiet).len(), + 2, + "the two builds are reported; the source is not" + ); + + // A withdrawn source: the builds stand alone, and the gem rewriter + // leaves the gem where it is. + refs.insert( + GEM_SOURCE.to_string(), + reference(serde_json::json!({ "status": "withdrawn" })), ); + assert_eq!(build(&refs).len(), 2); + } + + /// One reference response answers for a whole batch. What a response + /// still carries of the retired platform fields is read past, in any + /// shape, and fails no grant: the gem's reference is the ruby gem's + /// patch. A platform or a source uuid that is not in the shape the + /// run prints fails the grant it rides in and no other. + #[test] + fn a_wrong_gem_field_fails_only_its_own_grant() { + const NPM: &str = "pkg:npm/c@1"; + let mut retired = serde_json::to_value(serde_json::json!({ + "status": "granted", + "url": format!("https://patch.example/patch/gem/t/{GEM_SOURCE}/nokogiri-1.19.3.gem"), + "purl": "pkg:gem/nokogiri@1.19.3?platform=ruby", + "artifacts": [ + {"kind": "tarball", "url": null, "integrity": {"sha256": "a".repeat(64)}}, + {"kind": "gem-platform", "platform": "arm64-darwin", "url": null} + ], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": format!("https://patch.example/patch-registry/gem/t/{GEM_SOURCE}/"), + "identifiers": { + "name": "nokogiri", "version": "1.19.3", + "gemChecksumSha256": "a".repeat(64), + "gemPlatforms": [ + {"platform": "arm64-darwin", "gemChecksumSha256": "not-a-digest"} + ] + } + } + })) + .unwrap(); + let npm = reference(serde_json::json!({ + "status": "granted", + "url": format!("https://patch.example/patch/npm/c/1/tok/{PATCH_UUID}/c-1.tgz"), + "purl": NPM, + "artifacts": [{"kind": "tarball", "url": null, "integrity": { + "sha512": "sha512-x", "sha1": "a".repeat(40) + }}], + "registryOverride": null + })); + let run = |gem: serde_json::Value, gem_purl: &str| { + let refs = HashMap::from([ + (GEM_SOURCE.to_string(), reference(gem)), + (PATCH_UUID.to_string(), npm.clone()), + ]); + let selected = vec![ + (gem_purl.to_string(), GEM_SOURCE.to_string()), + (NPM.to_string(), PATCH_UUID.to_string()), + ]; + let (mut skipped, mut warnings) = (Vec::new(), Vec::new()); + let candidates = build_candidates(&selected, &refs, &[], &mut skipped, &mut warnings); + let kept: Vec = candidates.iter().map(|c| c.purl.clone()).collect(); + (kept, skipped) + }; + let ruby = "pkg:gem/nokogiri@1.19.3?platform=ruby"; + let (kept, skipped) = run(retired.clone(), ruby); + assert_eq!(kept, [ruby, NPM], "{skipped:?}"); + assert!(skipped.is_empty(), "{skipped:?}"); + + retired["rebuiltFromUuid"] = serde_json::json!("not-a-uuid"); + let (kept, skipped) = run(retired.clone(), ruby); + assert_eq!(kept, [NPM], "{skipped:?}"); + assert_eq!(skipped[0].reason, GRANT_MALFORMED); assert!( skipped[0] .detail .as_deref() .unwrap() - .contains("its gem platform checksum is not 64 hex digits"), + .contains("its source patch is not a patch UUID"), + "{skipped:?}" + ); + + retired["rebuiltFromUuid"] = serde_json::Value::Null; + retired["purl"] = serde_json::json!("pkg:gem/nokogiri@1.19.3?platform=21-darwin"); + let (kept, skipped) = run(retired, "pkg:gem/nokogiri@1.19.3?platform=21-darwin"); + assert_eq!(kept, [NPM], "{skipped:?}"); + assert!( + skipped[0] + .detail + .as_deref() + .unwrap() + .contains("its gem platform is not a plain platform name"), "{skipped:?}" ); } @@ -12840,30 +13235,82 @@ snapshots: assert!(!gem_rewrite(&p).await.0.files.contains_key(KEY)); } - /// A gem locked as precompiled platform builds, with a prebuild for - /// each: the rewrite moves every build, and lockfile discovery (what - /// `vex`, `rollback` and `remove` read) attributes them to the one pin, - /// so the engine confirms it instead of dropping the rewrite as - /// unattributable. A second run over the result confirms the same pin - /// and writes nothing. - #[tokio::test] - async fn gem_platform_builds_are_confirmed_as_one_pin() { - use crate::patch::redirect::GemPlatformChecksum; + /// The patch of the platform gem `platform` of [`gem_candidate`]'s gem, + /// built from that candidate's patch: its own uuid, registry and + /// sha256 (`digit` repeated). + fn gem_build_candidate(platform: &str, uuid: &str, digit: &str) -> Candidate { let mut candidate = gem_candidate(); + candidate.purl = format!("pkg:gem/rails@7.0.0?platform={platform}"); + let dep = &mut candidate.dep; + dep.patch_uuid = uuid.to_string(); + dep.artifact_url = format!( + "https://patch.test/patch-registry/gem/{FIXTURE_TOKEN}/{uuid}/gems/rails-7.0.0-{platform}.gem" + ); + let ov = dep.registry_override.as_mut().unwrap(); + ov.index_url = format!("https://patch.test/patch-registry/gem/{FIXTURE_TOKEN}/{uuid}/"); + ov.identifiers.gem_checksum_sha256 = Some(digit.repeat(64)); + ov.identifiers.gem_platform = Some(platform.to_string()); + ov.identifiers.gem_rebuilt_from_uuid = Some(FIXTURE_UUID.to_string()); candidate - .dep - .registry_override - .as_mut() - .unwrap() - .identifiers - .gem_platforms = ["arm64-darwin", "x86_64-linux-gnu"] - .iter() - .zip(["a", "b"]) - .map(|(platform, digit)| GemPlatformChecksum { - platform: platform.to_string(), - gem_checksum_sha256: digit.repeat(64), - }) - .collect(); + } + + /// A rollout that defers the builds of a gem defers its fix whole: the + /// source patch has no row to defer, and alone it would be rewritten + /// as a fix with no patch for the locked builds. Other candidates stay. + #[test] + fn a_deferred_gem_fix_leaves_the_candidates_whole() { + let arm = "77777777-7777-4777-8777-0000000000aa"; + let linux = "77777777-7777-4777-8777-0000000000bb"; + let mut other = gem_candidate(); + other.purl = "pkg:gem/rack@3.1.8".to_string(); + other.dep.name = "rack".to_string(); + other.dep.version = "3.1.8".to_string(); + other.dep.patch_uuid = "77777777-7777-4777-8777-0000000000cc".to_string(); + let all = || { + vec![ + gem_candidate(), + gem_build_candidate("arm64-darwin", arm, "a"), + gem_build_candidate("x86_64-linux-gnu", linux, "b"), + other.clone(), + ] + }; + let left = |deferred: &[&str]| -> Vec { + let mut candidates = all(); + drop_deferred(&mut candidates, |c| { + deferred.contains(&c.dep.patch_uuid.as_str()) + }); + candidates.into_iter().map(|c| c.dep.patch_uuid).collect() + }; + // The builds are deferred: the source goes with them. + assert_eq!(left(&[arm, linux]), [other.dep.patch_uuid.as_str()]); + // One deferred build takes the fix: no half of it is rewritten. + assert_eq!(left(&[linux]), [other.dep.patch_uuid.as_str()]); + // Another package's deferral leaves the gem alone. + assert_eq!( + left(&[other.dep.patch_uuid.as_str()]), + [FIXTURE_UUID, arm, linux] + ); + assert_eq!(left(&[]).len(), 4); + } + + const GEM_ARM_UUID: &str = "77777777-7777-4777-8777-77777777777a"; + const GEM_LINUX_UUID: &str = "77777777-7777-4777-8777-77777777777b"; + + /// A gem locked as precompiled platform builds, with a patch of one fix + /// for each: the rewrite moves every build into the section of the + /// fix's source patch's registry, and each build's own patch is + /// confirmed. Lockfile discovery (what `vex`, `rollback` and `remove` + /// read) reads the builds as the one pin of that registry, so the + /// engine keeps the rewrite instead of dropping it as unattributable. + /// The source patch pins no build of this lock and is not confirmed. A + /// second run over the result confirms the same and writes nothing. + #[tokio::test] + async fn gem_platform_builds_are_confirmed_each_by_its_own_patch() { + let candidates = vec![ + gem_candidate(), + gem_build_candidate("arm64-darwin", GEM_ARM_UUID, "a"), + gem_build_candidate("x86_64-linux-gnu", GEM_LINUX_UUID, "b"), + ]; let lock = format!( "GEM\n remote: https://rubygems.org/\n specs:\n rails (7.0.0-arm64-darwin)\n rails \ (7.0.0-x86_64-linux-gnu)\n\nPLATFORMS\n arm64-darwin\n x86_64-linux-gnu\n\nDEPENDENCIES\n \ @@ -12875,18 +13322,33 @@ snapshots: let mut p = MemoryProject::new(); p.insert_text("Gemfile", GEMFILE); p.insert_text("Gemfile.lock", lock.as_str()); - let (_, done) = gem_rewrite_of(&ProjectView::Memory(&p), vec![candidate.clone()]).await; + let (read, done) = gem_rewrite_of(&ProjectView::Memory(&p), candidates.clone()).await; assert!(done.unattributed.is_empty(), "{:?}", done.unattributed); + let builds = [ + ( + "pkg:gem/rails@7.0.0?platform=arm64-darwin".to_string(), + GEM_ARM_UUID.to_string(), + ), + ( + "pkg:gem/rails@7.0.0?platform=x86_64-linux-gnu".to_string(), + GEM_LINUX_UUID.to_string(), + ), + ]; + assert_eq!(done.confirmed, builds); + // The one registry the lock names is the source patch's. assert_eq!( - done.confirmed, - [("pkg:gem/rails@7.0.0".to_string(), FIXTURE_UUID.to_string())] + gem_index_targets(&candidates, &read.files), + [format!( + "https://patch.test/patch-registry/gem/{FIXTURE_TOKEN}/{FIXTURE_UUID}/info/rails" + )] ); let written = &done.rewrite.files["Gemfile.lock"]; assert!( - written.contains( - " specs:\n rails (7.0.0-arm64-darwin)\n rails (7.0.0-x86_64-linux-gnu)\n\nGEM\n \ + written.contains(&format!( + "GEM\n remote: https://patch.test/patch-registry/gem/{FIXTURE_TOKEN}/{FIXTURE_UUID}/\n \ + specs:\n rails (7.0.0-arm64-darwin)\n rails (7.0.0-x86_64-linux-gnu)\n\nGEM\n \ remote: https://rubygems.org/\n specs:\n\nPLATFORMS" - ), + )), "{written}" ); assert!( @@ -12898,14 +13360,83 @@ snapshots: )), "{written}" ); + for uuid in [GEM_ARM_UUID, GEM_LINUX_UUID] { + assert!(!written.contains(uuid), "no build's own registry is named"); + } + // The source patch was selected here (the first candidate), has no + // build in this lock, and is neither confirmed nor left unpinned. + let selected: Vec<(String, String)> = candidates + .iter() + .map(|c| (c.purl.clone(), c.dep.patch_uuid.clone())) + .collect(); + let quiet = quiet_candidates(&candidates, &selected, &done.rewrite); + assert_eq!(quiet, BTreeSet::from([FIXTURE_UUID.to_string()])); + assert!(unconfirmed_candidates(&candidates, &done.confirmed, &[], &quiet).is_empty()); for (rel, text) in &done.rewrite.files { p.insert_text(rel, text.as_str()); } - let (_, again) = gem_rewrite_of(&ProjectView::Memory(&p), vec![candidate]).await; + let (_, again) = gem_rewrite_of(&ProjectView::Memory(&p), candidates.clone()).await; assert!(again.rewrite.files.is_empty(), "{:?}", again.rewrite.edits); assert_eq!(again.confirmed, done.confirmed); assert!(again.unattributed.is_empty(), "{:?}", again.unattributed); + + // What the registry lists decides: with one build missing from it, + // nothing is written and nothing is confirmed. + let mut p = MemoryProject::new(); + p.insert_text("Gemfile", GEMFILE); + p.insert_text("Gemfile.lock", lock.as_str()); + let view = ProjectView::Memory(&p); + let read = read_candidate_files(&view, &BTreeSet::new(), &candidates).await; + let listed = gem_index_targets(&candidates, &read.files) + .into_iter() + .map(|url| { + let body = format!("---\n7.0.0-arm64-darwin |checksum:{}\n", "a".repeat(64)); + (url, Ok(body)) + }) + .collect::>(); + // And so does a registry nothing was read from: the engine hands + // the rewriter its documents also when it has none, and a gem is + // never pinned to a registry that was not looked at. + for (listed, why) in [(listed, "it lists no"), (Vec::new(), "was not read")] { + let mut read = read.clone(); + record_gem_index(&mut read, &listed); + assert!(read + .files + .contains_key(crate::patch::redirect::GEM_INDEX_KEY)); + let outer = OuterAllowRemote::default; + let options = RewriteOptions { + dry_run: false, + targets_pipenv_lock: false, + pipenv_major: None, + pipenv_unknown_detail: String::new(), + trust_lockfile_config: true, + npm_allow_remote_config: true, + npm_outer: &outer, + yarn_classic_outer: &OuterYarnMirror::default, + cargo_outer: &no_cargo_outer, + maven_selection: &no_maven_selection, + pnpm_env: &no_env, + blocking: false, + takeover_uuids: Default::default(), + patch_server_origins: Vec::new(), + prior_discovery: None, + }; + let unserved = rewrite(&view, read, &candidates, BTreeMap::new(), options).await; + assert!(unserved.rewrite.files.is_empty()); + assert!(unserved.confirmed.is_empty(), "{:?}", unserved.confirmed); + assert_eq!( + warning_codes(&unserved), + ["redirect_gem_platform_unsupported"] + ); + let detail = &unserved.rewrite.warnings[0].detail; + assert!(detail.contains(why), "{detail}"); + } + + // A project with no Bundler lock is handed nothing. + let mut bare = CandidateFiles::default(); + record_gem_index(&mut bare, &[]); + assert!(bare.files.is_empty()); } /// #390: `bundle config set --local gemfile Gemfile.next` makes bundler diff --git a/crates/socket-patch-core/src/hosted/gem_fixes.rs b/crates/socket-patch-core/src/hosted/gem_fixes.rs new file mode 100644 index 000000000..23b893805 --- /dev/null +++ b/crates/socket-patch-core/src/hosted/gem_fixes.rs @@ -0,0 +1,1269 @@ +//! Which patches a run selects for a gem the Bundler lock names as +//! platform builds. +//! +//! A native gem such as nokogiri is published as one gem per platform, and +//! a fix for it is published as one patch per platform gem: each patch has +//! its own uuid and its own record, keyed by the gem's package URL with a +//! `platform` qualifier (`pkg:gem/nokogiri@1.19.3?platform=arm64-darwin`; +//! the ruby-platform gem's is `?platform=ruby`). The patches of one fix +//! are one family: every patch but the source states the uuid of the +//! patch it was built from (`rebuiltFromUuid` of its package reference), +//! and the patch registry of any member lists and serves every member. +//! +//! The lock says which of those gems a project uses: +//! `nokogiri (1.19.3-arm64-darwin)`, `nokogiri (1.19.3-x86_64-linux-gnu)`, +//! and the plain `nokogiri (1.19.3)` when it also names the ruby gem. +//! Bundler takes one source per gem, so a run that changes what Bundler +//! installs (hosted and vendored mode) needs ONE fix with a patch for +//! every build the lock names. The per-package selection ranks the patches +//! of each package URL on their own, and two fixes that tie can come out +//! one ahead for one platform and the other for another (their builds are +//! published at different times). So, between the selection and its +//! classification, [`GemLock`]: +//! +//! 1. drops the patches of platform gems the lock does not name +//! ([`GemLock::narrow`]). Nothing in the project is theirs to patch. +//! The ruby gem's patch always stays: it is the fix's source, whose +//! registry a lock of platform builds takes as the gem's source; +//! 2. names the patches whose family it must know +//! ([`GemLock::reference_uuids`]), for the caller to ask the patch API +//! about: every patch on offer for a build the lock names; +//! 3. takes one fix for every build ([`GemLock::choose`]): among the +//! fixes with a usable patch for every locked build, the one the +//! project is already on, unless the fix the ruby-platform selection +//! rules rank first supersedes it; else that first-ranked fix. The +//! builds' rows are then classified together: all already in place, or +//! all an upgrade. +//! +//! When no fix covers every locked build the selection is left as it is, +//! and the mode's own writer leaves the gem alone and says which builds +//! are missing or belong to another fix. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use crate::api::ranking::search_result_supersedes; +use crate::api::types::{PackageVendorResult, PatchSearchResult}; +use crate::policy::Offers; +use crate::rollout::stage::RecordedIndex; +use crate::rollout::Recorded; +use crate::utils::purl::{gem_platform_qualifier, purl_parts}; +use crate::vendor::lock_inventory::ProjectView; + +/// Warning code of a run that left a gem locked as platform builds out of +/// its selection because it could not read which fix the gem's patches +/// belong to ([`GemLock::unsettle`]). +pub const GEM_FIX_UNSETTLED: &str = "gem_fix_unsettled"; + +/// The detail of [`GEM_FIX_UNSETTLED`] for the gems `left` out (`name +/// version` each), with `why` the lookup failed. +pub fn unsettled_detail(left: &[String], why: &str) -> String { + let (verb, pronoun) = match left.len() { + 1 => ("is", "it"), + _ => ("are", "they"), + }; + format!( + "could not read which fix the platform patches of {} belong to ({why}); a gem locked \ + as platform builds takes every build from one fix, so {pronoun} {verb} left as \ + {pronoun} {verb} by this run. Run it again", + left.join(", ") + ) +} + +/// The builds of one gem version a Bundler lock names. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +struct LockedGem { + /// The plain `name (version)` entry: the ruby-platform gem. + ruby: bool, + /// The platform of each `name (version-)` entry. + platforms: Vec, +} + +impl LockedGem { + /// Whether the lock names the gem of `platform` (`None`: the ruby gem). + fn names(&self, platform: Option<&str>) -> bool { + match platform { + Some(platform) => self.platforms.iter().any(|p| p == platform), + None => self.ruby, + } + } +} + +/// What the Bundler lock a project loads names of each gem version a run +/// has patches on offer for (module docs). +#[derive(Debug, Clone, Default)] +pub struct GemLock { + /// By `(name, version)`. A gem version the lock does not name at all + /// has no entry. + gems: HashMap<(String, String), LockedGem>, +} + +/// The patch purls of the builds of one gem version: `(platform, purl)`, +/// the ruby-platform gem's with `None`. +type BuildPurls<'o> = Vec<(Option, &'o str)>; + +/// The gem a patch purl is a patch of: its name, its version, and its +/// platform (`None` for the ruby-platform gem, which a purl names with +/// `?platform=ruby` or with no qualifier). `None` for another ecosystem's +/// purl. +fn gem_of(purl: &str) -> Option<((String, String), Option)> { + let (ecosystem, name, version) = purl_parts(purl)?; + if ecosystem != "gem" { + return None; + } + let platform = gem_platform_qualifier(purl).map(str::to_string); + Some(((name, version), platform)) +} + +/// The fix a patch belongs to, as its package reference says: the uuid of +/// the patch it was built from, or its own. +fn family_of<'a>(uuid: &'a str, references: &'a HashMap) -> &'a str { + references + .get(uuid) + .and_then(|reference| reference.rebuilt_from_uuid.as_deref()) + .filter(|source| !source.is_empty()) + .unwrap_or(uuid) +} + +/// Whether the run can use the patch `uuid`: its reference is granted. +fn usable(uuid: &str, references: &HashMap) -> bool { + references + .get(uuid) + .is_some_and(|reference| matches!(reference.status.as_str(), "granted" | "reused")) +} + +impl GemLock { + /// Read the lock `view`'s project loads for the gems among `purls` + /// (the package URLs a run has patches on offer for). Empty when + /// Bundler loads no lock there, or none of `purls` is a gem's. + pub async fn read<'p>(view: &ProjectView<'_>, purls: impl Iterator) -> Self { + let mut gems: Vec<(String, String)> = + purls.filter_map(gem_of).map(|(gem, _)| gem).collect(); + gems.sort(); + gems.dedup(); + if gems.is_empty() { + return GemLock::default(); + } + let asked: Vec = gems + .iter() + .map(|(name, version)| crate::utils::purl::build_gem_purl(name, version)) + .collect(); + // Every source section: a gem vendored as platform gems holds its + // platform entries in a `PATH` section, and they are still the + // builds this project installs. + let named = crate::vendor::lock_inventory::gem_resolved_builds_in(view, &asked).await; + let gems = gems + .into_iter() + .zip(named) + .filter(|(_, builds)| !builds.is_empty()) + .map(|(gem, builds)| { + let locked = LockedGem { + ruby: builds.iter().any(|build| build.platform.is_none()), + platforms: builds.into_iter().filter_map(|b| b.platform).collect(), + }; + (gem, locked) + }) + .collect(); + GemLock { gems } + } + + /// Whether the lock names no gem a run has patches for: nothing to do. + pub fn is_empty(&self) -> bool { + self.gems.is_empty() + } + + /// Whether the lock names a build of the gem version `purl` is a patch + /// purl of: which of its patches a run selects is then the lock's to + /// say, not an installed copy's. + pub fn names_gem(&self, purl: &str) -> bool { + gem_of(purl).is_some_and(|(gem, _)| self.gems.contains_key(&gem)) + } + + /// The platforms the lock names of the gem version `purl` is a patch + /// purl of, in lock order: empty when it names none (the gem is locked + /// as its ruby-platform gem alone, or not at all). + pub fn platforms_of(&self, purl: &str) -> &[String] { + gem_of(purl) + .and_then(|(gem, _)| self.gems.get(&gem)) + .map_or(&[], |locked| locked.platforms.as_slice()) + } + + /// The platform gem `purl` is a patch purl of: `None` for the + /// ruby-platform gem's (and for another ecosystem's purl). + pub fn platform_of(purl: &str) -> Option { + gem_of(purl).and_then(|(_, platform)| platform) + } + + /// Whether the patch purl `purl` is a patch of a platform gem the lock + /// does not name, of a gem version it does name another build of. + fn unlocked(&self, purl: &str) -> bool { + let Some((gem, Some(platform))) = gem_of(purl) else { + return false; + }; + self.gems + .get(&gem) + .is_some_and(|locked| !locked.names(Some(&platform))) + } + + /// Drop from `offers` the patches of platform gems the lock does not + /// name (module docs, step 1). + pub fn narrow(&self, offers: &mut Offers) { + if self.is_empty() { + return; + } + offers.selected.retain(|purl, _| !self.unlocked(purl)); + offers.unfiltered.retain(|purl, _| !self.unlocked(purl)); + offers.withheld.retain(|(purl, _)| !self.unlocked(purl)); + } + + /// [`Self::narrow`] for a selection that is a list of patches. + pub fn narrow_selected(&self, selected: Vec) -> Vec { + if self.is_empty() { + return selected; + } + let mut selected = selected; + selected.retain(|patch| !self.unlocked(&patch.purl)); + selected + } + + /// The offers a run may take for each patch purl of `offers`: all but + /// the ones a policy filter does not admit (withheld, or below the + /// severity floor), best first, with the filter's own winner for the + /// purl ahead of the rest (it may prefer a smaller patch over the + /// top-ranked one). + fn admitted<'o>(offers: &'o Offers, purl: &str) -> Vec<&'o PatchSearchResult> { + let refused = |offer: &&PatchSearchResult| { + let key = (purl.to_string(), offer.uuid.clone()); + offers.withheld.contains(&key) || offers.refused.contains(&key) + }; + let ranked = offers.unfiltered.get(purl).into_iter().flatten(); + let mut admitted: Vec<&PatchSearchResult> = ranked.filter(|o| !refused(o)).collect(); + let winner = offers.selected.get(purl); + if let Some(at) = winner.and_then(|w| admitted.iter().position(|o| o.uuid == w.uuid)) { + let winner = admitted.remove(at); + admitted.insert(0, winner); + } + admitted + } + + /// The gems of `offers` the lock names as platform builds, each with + /// the patch purls of the builds it names: `(platform, purl)`, the + /// ruby-platform gem's (`None`) included whether the lock names it or + /// not. Sorted by gem, then purl. + fn platform_locked<'o>( + &self, + offers: &'o Offers, + ) -> BTreeMap<(String, String), BuildPurls<'o>> { + let mut gems: BTreeMap<(String, String), BuildPurls<'o>> = BTreeMap::new(); + for purl in offers.unfiltered.keys() { + let Some((gem, platform)) = gem_of(purl) else { + continue; + }; + let Some(locked) = self.gems.get(&gem).filter(|l| !l.platforms.is_empty()) else { + continue; + }; + if platform.is_none() || locked.names(platform.as_deref()) { + gems.entry(gem).or_default().push((platform, purl.as_str())); + } + } + gems + } + + /// Leave every gem the lock names as platform builds out of the + /// selection: for a run that could not read which fix their patches + /// belong to. The fix is settled once, by [`Self::choose`], and the + /// writers follow it; a selection ranked purl by purl can take a + /// build's patch from one fix and another's from the next, or move a + /// project to a fix it would not have been moved to, so such a gem is + /// left as it is until a run can settle it. Returns each gem left + /// out, as `name version`. + pub fn unsettle(&self, offers: &mut Offers) -> Vec { + let gems: Vec<((String, String), Vec)> = self + .platform_locked(offers) + .into_iter() + .map(|(gem, purls)| { + let purls = purls.into_iter().map(|(_, purl)| purl.to_string()); + (gem, purls.collect()) + }) + .collect(); + let mut left = Vec::new(); + for ((name, version), purls) in gems { + let mut selected = false; + for purl in purls { + selected |= offers.selected.remove(&purl).is_some(); + } + if selected { + left.push(format!("{name} {version}")); + } + } + left + } + + /// The uuids whose package references [`Self::choose`] reads (module + /// docs, step 2), of each gem the lock names as platform builds: every + /// patch a run may take for a build the lock names, and what the + /// project records for the gem (`recorded`). The recorded patch says + /// which fix the project is on, also when it is no longer among the + /// offers (its platform left the lock, or a filter refuses it now); + /// for a gem with something recorded, every offer of a locked build is + /// asked about, refused ones too, since a recorded fix is kept whole. + /// Sorted. Empty for a project with no such gem, which then costs no + /// request. + pub fn reference_uuids(&self, offers: &Offers, recorded: &RecordedIndex) -> Vec { + let mut uuids: Vec = Vec::new(); + for (gem, purls) in self.platform_locked(offers) { + let locked = &self.gems[&gem]; + let base = crate::utils::purl::build_gem_purl(&gem.0, &gem.1); + let pinned = recorded.uuids(&base); + for (platform, purl) in purls { + if !locked.names(platform.as_deref()) { + continue; + } + uuids.extend(Self::admitted(offers, purl).iter().map(|o| o.uuid.clone())); + if !pinned.is_empty() { + let every = offers.unfiltered.get(purl).into_iter().flatten(); + uuids.extend(every.map(|offer| offer.uuid.clone())); + } + } + uuids.extend(pinned.iter().cloned()); + } + uuids.sort(); + uuids.dedup(); + uuids + } + + /// Take one fix for every build of each gem the lock names as platform + /// builds (module docs, step 3), by the package `references` of + /// [`Self::reference_uuids`]: `offers.selected` then holds that fix's + /// patch for each locked build (and its source patch for the ruby gem + /// when that one is on offer). Only offers a policy filter admits are + /// taken ([`Self::admitted`]), so a gem the filter leaves out stays + /// out. Returns how the row of each locked build is classified, by + /// patch purl, for a gem the project already has a patch recorded for + /// (`recorded`): [`Recorded::Same`] when what the run takes for the + /// build is of the recorded fix, else a move from it. A gem with + /// nothing recorded has no entry and is classified as any package is. + pub fn choose( + &self, + offers: &mut Offers, + references: &HashMap, + recorded: &RecordedIndex, + ) -> HashMap { + let mut classes: HashMap = HashMap::new(); + let mut chosen: Vec<(String, PatchSearchResult)> = Vec::new(); + for (gem, purls) in self.platform_locked(offers) { + let locked = &self.gems[&gem]; + // The usable patches of each locked build, best first, with + // the fix each belongs to. + let builds: Vec<(&str, Vec<(&PatchSearchResult, &str)>)> = purls + .iter() + .filter(|(platform, _)| locked.names(platform.as_deref())) + .map(|(_, purl)| { + let patches = Self::admitted(offers, purl) + .into_iter() + .filter(|offer| usable(&offer.uuid, references)) + .map(|offer| (offer, family_of(&offer.uuid, references))) + .collect(); + (*purl, patches) + }) + .collect(); + // Every locked build must have a patch purl on offer at all. + let named = usize::from(locked.ruby) + locked.platforms.len(); + let covered: HashSet> = purls + .iter() + .filter(|(platform, _)| locked.names(platform.as_deref())) + .map(|(platform, _)| platform.as_deref()) + .collect(); + // The fixes with a patch for every locked build, in the order + // they come. + let mut complete: Vec<&str> = Vec::new(); + if covered.len() == named { + for (_, family) in builds.iter().flat_map(|(_, patches)| patches) { + let everywhere = builds + .iter() + .all(|(_, patches)| patches.iter().any(|(_, f)| f == family)); + if everywhere && !complete.contains(family) { + complete.push(family); + } + } + } + // The ruby gem's patches, best first: a fix is named by its + // source patch, which is one of them. + let ruby: Vec<&PatchSearchResult> = purls + .iter() + .filter(|(platform, _)| platform.is_none()) + .flat_map(|(_, purl)| Self::admitted(offers, purl)) + .collect(); + let first_ranked = ruby + .iter() + .map(|offer| family_of(&offer.uuid, references)) + .find(|family| complete.contains(family)); + // The fix the project is on: one whose source, or whose patch + // of a locked build, some ledger or lockfile pin records. + let base = crate::utils::purl::build_gem_purl(&gem.0, &gem.1); + let pinned = recorded.uuids(&base); + // What the project records is one uuid for every build (the + // registry in its lock, the directory it is vendored under): a + // patch of one fix, read from that patch's own reference, so + // it is known also when the patch is no longer on offer. + let recorded_fix: Option = pinned + .first() + .map(|uuid| family_of(uuid, references).to_string()); + let on = complete.iter().copied().find(|family| { + recorded_fix.as_deref() == Some(*family) + || pinned.iter().any(|uuid| uuid == family) + || builds.iter().any(|(_, patches)| { + patches + .iter() + .any(|(offer, f)| f == family && pinned.contains(&offer.uuid)) + }) + }); + // How one fix's patches compare with another's: by their + // source patches where both are on offer, else by their + // patches of the first locked build. + let patch_of = |family: &str| -> Option<&PatchSearchResult> { + ruby.iter() + .copied() + .find(|offer| offer.uuid == family) + .or_else(|| { + let (_, patches) = builds.first()?; + let member = patches.iter().find(|(_, f)| *f == family)?; + Some(member.0) + }) + }; + let supersedes = |newer: &str, older: &str| match (patch_of(newer), patch_of(older)) { + (Some(newer), Some(older)) => search_result_supersedes(newer, older), + _ => false, + }; + // `None`: no fix covers every locked build, and the selection + // stays as it is ranked. + let fix: Option<&str> = match (on, first_ranked) { + _ if complete.is_empty() => None, + (Some(on), Some(first)) if on != first && supersedes(first, on) => Some(first), + (Some(on), _) => Some(on), + (None, Some(first)) => Some(first), + (None, None) => Some(complete[0]), + }; + // A recorded package keeps its patch where no filter admits + // another: the fix the project is on is kept whole, its + // patches of the locked builds with it, also the ones a filter + // refuses now (a raised severity floor). Left to the ranking, + // the one recorded patch would be kept alone and the gem + // judged as a fix with no patch for its builds. + let kept: Vec<(&str, &PatchSearchResult)> = match (&fix, recorded_fix.as_deref()) { + (None, Some(recorded_fix)) => { + let of_fix = |purl: &str| { + let offered = offers.unfiltered.get(purl).into_iter().flatten(); + offered.into_iter().find(|offer| { + usable(&offer.uuid, references) + && family_of(&offer.uuid, references) == recorded_fix + }) + }; + let found: Vec<(&str, &PatchSearchResult)> = builds + .iter() + .filter_map(|(purl, _)| Some((*purl, of_fix(purl)?))) + .collect(); + match found.len() == builds.len() && covered.len() == named { + true => found, + false => Vec::new(), + } + } + _ => Vec::new(), + }; + // A build's row is already in place when what the run takes + // for it is of the recorded fix, and a move to another fix + // otherwise, whether or not a fix was settled above. + for (purl, patches) in &builds { + let member = fix + .and_then(|fix| { + let member = patches.iter().find(|(_, family)| *family == fix)?; + Some(member.0) + }) + .or_else(|| { + let kept = kept.iter().find(|(kept, _)| kept == purl)?; + Some(kept.1) + }); + if let Some(member) = member { + chosen.push((purl.to_string(), member.clone())); + } + let taken = member.or_else(|| offers.selected.get(*purl)); + let (Some(taken), Some(recorded_fix)) = (taken, recorded_fix.as_deref()) else { + continue; + }; + let class = match family_of(&taken.uuid, references) == recorded_fix { + true => Recorded::Same, + false => Recorded::Superseded { + old_uuid: patches + .iter() + .find(|(_, family)| *family == recorded_fix) + .map_or_else(|| pinned[0].clone(), |(offer, _)| offer.uuid.clone()), + }, + }; + classes.insert(purl.to_string(), class); + } + // The fix's source patch, for a lock that does not name the + // ruby gem: its registry is the gem's source. Its row is + // judged like a build's: the lock may name the registry of a + // build's own patch (where the source patch was not available + // when the gem was moved), and the source patch of that same + // fix is then no newer patch for the project. + if !locked.ruby { + for (_, purl) in purls.iter().filter(|(platform, _)| platform.is_none()) { + let source = match (fix, kept.is_empty()) { + (Some(fix), _) => { + let mut admitted = Self::admitted(offers, purl).into_iter(); + admitted.find(|offer| offer.uuid == fix) + } + // The kept fix's source patch, refused or not. + (None, false) => { + let mut offered = offers.unfiltered.get(*purl).into_iter().flatten(); + offered + .find(|offer| Some(offer.uuid.as_str()) == recorded_fix.as_deref()) + } + (None, true) => None, + }; + if let Some(source) = source { + chosen.push((purl.to_string(), source.clone())); + } + let taken = source.or_else(|| offers.selected.get(*purl)); + let (Some(taken), Some(recorded_fix)) = (taken, recorded_fix.as_deref()) else { + continue; + }; + let class = match family_of(&taken.uuid, references) == recorded_fix { + true => Recorded::Same, + false => Recorded::Superseded { + old_uuid: pinned[0].clone(), + }, + }; + classes.insert(purl.to_string(), class); + } + } + } + offers.selected.extend(chosen); + classes + } +} + +use crate::api::ranking::sort_by_purl; + +/// The other patches of the fix that the gem patch `uuid` (found under +/// `purl`) belongs to, for the builds of the gem that the Bundler lock of +/// `view`'s project names: empty unless the lock names the gem as platform +/// builds. +/// +/// Each platform gem of a fix has a patch of its own, with its own uuid, +/// built from the patch of the ruby gem (the fix's source, whose registry +/// and vendored directory every build shares), and Bundler takes a gem +/// from one source. So a run that names one patch of such a gem (`get +/// `, the eject of a hosted pin) needs the fix's patch of every +/// locked build, and its source patch. The fix of a patch is what its +/// package reference states (`rebuiltFromUuid`, else the patch itself): +/// this costs one search and one reference request, and nothing for any +/// other patch. `free_only`: the run can take free patches alone (it goes +/// through the public proxy). When either lookup fails the answer is +/// empty, and the run says which locked builds it has no patch for. +pub async fn fix_siblings( + view: &ProjectView<'_>, + api_client: &crate::api::client::ApiClient, + free_only: bool, + purl: &str, + uuid: &str, +) -> Vec { + let lock = GemLock::read(view, std::iter::once(purl)).await; + fix_siblings_in(&lock, api_client, free_only, purl, uuid).await +} + +/// [`fix_siblings`] against a lock already read (for `purl` among others): +/// a run that asks for several gems reads the lock once. +pub async fn fix_siblings_in( + lock: &GemLock, + api_client: &crate::api::client::ApiClient, + free_only: bool, + purl: &str, + uuid: &str, +) -> Vec { + if lock.platforms_of(purl).is_empty() { + return Vec::new(); + } + let package = crate::utils::purl::strip_purl_qualifiers(purl); + let Ok(found) = api_client.search_patches_by_package(package).await else { + return Vec::new(); + }; + // The patches of the builds the lock names (the ruby gem's included), + // which this run may take. + let mut others: Vec = lock + .narrow_selected(found.patches) + .into_iter() + .filter(|other| other.uuid != uuid) + .filter(|other| !(other.tier == "paid" && free_only)) + .collect(); + if others.is_empty() { + return others; + } + let uuids: Vec = std::iter::once(uuid.to_string()) + .chain(others.iter().map(|other| other.uuid.clone())) + .collect(); + let Ok(references) = api_client.fetch_registry_references(&uuids).await else { + return Vec::new(); + }; + let fix = family_of(uuid, &references).to_string(); + let asked_platform = GemLock::platform_of(purl); + others.retain(|other| { + family_of(&other.uuid, &references) == fix + && GemLock::platform_of(&other.purl) != asked_platform + }); + sort_by_purl(&mut others); + others +} + +/// `selected` (one patch per purl, among `candidates`, every one of which +/// the run may take), settled for the gems the Bundler lock of `view`'s +/// project names as platform builds: patches of platform gems the lock +/// does not name leave it, and every locked build of a gem takes its patch +/// from one fix ([`GemLock::choose`]: the fix the ruby gem's ranking puts +/// first among those with a patch for every locked build). `scan` settles +/// its selection the same way; this is for a run that names its packages +/// (`get` in hosted and vendored mode). One reference request, and none +/// for a project with no such gem. When it fails, those gems leave the +/// selection ([`GemLock::unsettle`]) and the second value is what to say +/// ([`GEM_FIX_UNSETTLED`]). +pub async fn settle( + view: &ProjectView<'_>, + api_client: &crate::api::client::ApiClient, + candidates: &[PatchSearchResult], + selected: Vec, +) -> (Vec, Option) { + let lock = GemLock::read(view, candidates.iter().map(|patch| patch.purl.as_str())).await; + if lock.is_empty() { + return (selected, None); + } + let mut offers = crate::rollout::stage::offers_from_results(candidates, true); + offers.selected = selected + .iter() + .map(|patch| (patch.purl.clone(), patch.clone())) + .collect(); + lock.narrow(&mut offers); + let uuids = lock.reference_uuids(&offers, &RecordedIndex::default()); + let mut unsettled = None; + if !uuids.is_empty() { + match api_client.fetch_registry_references(&uuids).await { + Ok(references) => { + lock.choose(&mut offers, &references, &RecordedIndex::default()); + } + Err(error) => { + let left = lock.unsettle(&mut offers); + if !left.is_empty() { + unsettled = Some(unsettled_detail(&left, &error.to_string())); + } + } + } + } + let mut settled: Vec = offers.selected.into_values().collect(); + sort_by_purl(&mut settled); + (settled, unsettled) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::api::types::VulnerabilityResponse; + use crate::rollout::stage::offers_from_results; + use crate::vendor::lock_inventory::MemoryProject; + + const SRC_A: &str = "aaaaaaaa-0000-4000-8000-000000000001"; + const A_LINUX: &str = "aaaaaaaa-0000-4000-8000-000000000002"; + const A_DARWIN: &str = "aaaaaaaa-0000-4000-8000-000000000003"; + const SRC_B: &str = "bbbbbbbb-0000-4000-8000-000000000001"; + const B_LINUX: &str = "bbbbbbbb-0000-4000-8000-000000000002"; + const B_DARWIN: &str = "bbbbbbbb-0000-4000-8000-000000000003"; + const JAVA: &str = "cccccccc-0000-4000-8000-000000000001"; + + const RUBY: &str = "pkg:gem/nokogiri@1.19.3?platform=ruby"; + const LINUX: &str = "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu"; + const DARWIN: &str = "pkg:gem/nokogiri@1.19.3?platform=arm64-darwin"; + + fn patch(uuid: &str, purl: &str, published: &str, advisories: &[&str]) -> PatchSearchResult { + PatchSearchResult { + uuid: uuid.to_string(), + purl: purl.to_string(), + published_at: published.to_string(), + description: String::new(), + license: "MIT".to_string(), + tier: "free".to_string(), + vulnerabilities: advisories + .iter() + .map(|id| { + ( + id.to_string(), + VulnerabilityResponse { + cves: Vec::new(), + summary: String::new(), + severity: "high".to_string(), + description: String::new(), + }, + ) + }) + .collect(), + } + } + + fn reference(status: &str, source: Option<&str>) -> PackageVendorResult { + serde_json::from_value(serde_json::json!({ + "status": status, + "rebuiltFromUuid": source, + })) + .unwrap() + } + + fn granted(pairs: &[(&str, Option<&str>)]) -> HashMap { + pairs + .iter() + .map(|(uuid, source)| (uuid.to_string(), reference("granted", *source))) + .collect() + } + + async fn lock_of(specs: &[&str], offers: &Offers) -> GemLock { + let mut project = MemoryProject::new(); + project.insert_text( + "Gemfile", + "source \"https://rubygems.org\"\ngem \"nokogiri\"\n", + ); + let specs: String = specs.iter().map(|s| format!(" {s}\n")).collect(); + project.insert_text( + "Gemfile.lock", + format!( + "GEM\n remote: https://rubygems.org/\n specs:\n{specs}\nPLATFORMS\n ruby\n\n\ + DEPENDENCIES\n nokogiri\n\nBUNDLED WITH\n 2.5.23\n" + ), + ); + GemLock::read( + &ProjectView::Memory(&project), + offers.unfiltered.keys().map(String::as_str), + ) + .await + } + + const PLATFORM_ONLY: [&str; 2] = [ + "nokogiri (1.19.3-arm64-darwin)", + "nokogiri (1.19.3-x86_64-linux-gnu)", + ]; + + fn fix_a() -> Vec { + vec![ + patch(SRC_A, RUBY, "2026-01-01T00:00:00Z", &["GHSA-a"]), + patch(A_LINUX, LINUX, "2026-01-02T00:00:00Z", &["GHSA-a"]), + patch(A_DARWIN, DARWIN, "2026-01-02T00:00:00Z", &["GHSA-a"]), + ] + } + + fn fix_b() -> Vec { + vec![ + patch(SRC_B, RUBY, "2025-01-01T00:00:00Z", &["GHSA-a"]), + patch(B_LINUX, LINUX, "2025-01-02T00:00:00Z", &["GHSA-a"]), + patch(B_DARWIN, DARWIN, "2025-01-02T00:00:00Z", &["GHSA-a"]), + ] + } + + fn both_fixes() -> HashMap { + granted(&[ + (A_LINUX, Some(SRC_A)), + (A_DARWIN, Some(SRC_A)), + (B_LINUX, Some(SRC_B)), + (B_DARWIN, Some(SRC_B)), + ]) + } + + fn uuids_of(offers: &Offers) -> Vec<&str> { + offers.selected.values().map(|p| p.uuid.as_str()).collect() + } + + /// A policy filter holds for a fix as a whole. A fix whose patches the + /// filter does not admit (below the severity floor, withheld) is never + /// taken: a gem the filter leaves out stays out, with no reference + /// asked for, and beside an admitted fix only that one is taken, even + /// where the refused one ranks first. Among admitted fixes the filter's + /// own winner goes first. + #[tokio::test] + async fn a_fix_the_policy_does_not_admit_is_never_taken() { + let refuse = |offers: &mut Offers, patches: &[PatchSearchResult]| { + for patch in patches { + offers + .refused + .insert((patch.purl.clone(), patch.uuid.clone())); + } + }; + // The one fix is below the floor: the policy selected nothing. + let mut offers = offers_from_results(&fix_a(), true); + offers.selected.clear(); + refuse(&mut offers, &fix_a()); + let lock = lock_of(&PLATFORM_ONLY, &offers).await; + lock.narrow(&mut offers); + assert!(lock + .reference_uuids(&offers, &RecordedIndex::default()) + .is_empty()); + let classes = lock.choose(&mut offers, &both_fixes(), &RecordedIndex::default()); + assert!(offers.selected.is_empty(), "{:?}", uuids_of(&offers)); + assert!(classes.is_empty()); + + // Fix A ranks first and is refused; fix B is admitted and selected. + let all: Vec = fix_a().into_iter().chain(fix_b()).collect(); + let mut offers = offers_from_results(&all, true); + offers.selected = fix_b() + .into_iter() + .map(|patch| (patch.purl.clone(), patch)) + .collect(); + refuse(&mut offers, &fix_a()); + let lock = lock_of(&PLATFORM_ONLY, &offers).await; + lock.narrow(&mut offers); + assert_eq!( + lock.reference_uuids(&offers, &RecordedIndex::default()), + [B_LINUX, B_DARWIN] + ); + lock.choose(&mut offers, &both_fixes(), &RecordedIndex::default()); + let mut taken = uuids_of(&offers); + taken.sort_unstable(); + assert_eq!(taken, [SRC_B, B_LINUX, B_DARWIN]); + + // Both admitted, and the filter prefers B (its winner per purl): + // B is taken, though A ranks first. + let mut offers = offers_from_results(&all, true); + offers.selected = fix_b() + .into_iter() + .map(|patch| (patch.purl.clone(), patch)) + .collect(); + lock.choose(&mut offers, &both_fixes(), &RecordedIndex::default()); + let mut taken = uuids_of(&offers); + taken.sort_unstable(); + assert_eq!(taken, [SRC_B, B_LINUX, B_DARWIN]); + } + + /// The fix the project is on is read from the recorded patch itself, + /// so it is known when that patch is no longer on offer. The lock took + /// the gem from the registry of fix A's darwin patch; darwin has left + /// the lock since, and a tying fix B ranks first for what is left. The + /// recorded patch is asked about with the offers, the project stays on + /// fix A, and the build's row is in place. + #[tokio::test] + async fn the_recorded_fix_is_known_when_its_patch_is_no_longer_offered() { + // Fix B ties with fix A and leads on the paid tier, which ranks a + // patch first and never makes it a newer one. + let tying_b = [ + patch(SRC_B, RUBY, "2026-01-01T00:00:00Z", &["GHSA-a"]), + patch(B_LINUX, LINUX, "2026-01-02T00:00:00Z", &["GHSA-a"]), + ] + .map(|mut patch| { + patch.tier = "paid".to_string(); + patch + }); + let all: Vec = fix_a().into_iter().chain(tying_b).collect(); + let mut offers = offers_from_results(&all, true); + let lock = lock_of(&["nokogiri (1.19.3-x86_64-linux-gnu)"], &offers).await; + lock.narrow(&mut offers); + assert!( + !offers.unfiltered.contains_key(DARWIN), + "darwin left the lock" + ); + assert_eq!( + offers.selected[LINUX].uuid, B_LINUX, + "premise: B ranks first" + ); + let on_darwin = RecordedIndex::new( + None, + &[("pkg:gem/nokogiri@1.19.3".to_string(), A_DARWIN.to_string())], + ); + let asked = lock.reference_uuids(&offers, &on_darwin); + assert!(asked.contains(&A_DARWIN.to_string()), "{asked:?}"); + let classes = lock.choose(&mut offers, &both_fixes(), &on_darwin); + assert_eq!( + offers.selected[LINUX].uuid, A_LINUX, + "the project stays on fix A" + ); + assert_eq!(offers.selected[RUBY].uuid, SRC_A); + assert_eq!(classes.get(LINUX), Some(&Recorded::Same)); + assert_eq!(classes.get(RUBY), Some(&Recorded::Same)); + } + + /// A recorded package keeps its patch where no filter admits another: + /// the fix a gem is on is kept whole. With the severity floor raised + /// above it, the policy keeps the one recorded patch selected and + /// refuses the patches of the builds; left alone, that one patch would + /// be judged as a fix with no patch for the locked builds on every + /// scan. The builds' patches of the recorded fix stay with it. + #[tokio::test] + async fn a_recorded_fix_is_kept_whole_under_a_raised_floor() { + let mut offers = offers_from_results(&fix_a(), true); + for patch in fix_a() { + offers.refused.insert((patch.purl, patch.uuid)); + } + // What the policy leaves: the recorded patch, by itself. + offers.selected.retain(|purl, _| purl == RUBY); + let lock = lock_of(&PLATFORM_ONLY, &offers).await; + lock.narrow(&mut offers); + let on_a = RecordedIndex::new( + None, + &[("pkg:gem/nokogiri@1.19.3".to_string(), SRC_A.to_string())], + ); + let asked = lock.reference_uuids(&offers, &on_a); + assert!( + asked.contains(&A_LINUX.to_string()) && asked.contains(&A_DARWIN.to_string()), + "{asked:?}" + ); + let classes = lock.choose(&mut offers, &both_fixes(), &on_a); + let mut taken = uuids_of(&offers); + taken.sort_unstable(); + assert_eq!(taken, [SRC_A, A_LINUX, A_DARWIN]); + assert!(classes.values().all(|class| *class == Recorded::Same)); + assert_eq!(classes.len(), 3); + + // Nothing recorded: the filter holds, and the gem stays out. + let mut offers = offers_from_results(&fix_a(), true); + for patch in fix_a() { + offers.refused.insert((patch.purl, patch.uuid)); + } + offers.selected.clear(); + lock.choose(&mut offers, &both_fixes(), &RecordedIndex::default()); + assert!(offers.selected.is_empty()); + } + + /// A run that cannot read which fix the patches belong to settles + /// nothing, and writes from no half decision: the gem's patches leave + /// the selection (the ranking alone could take one build's patch from + /// each fix), other packages stay, and the gem is named. + #[tokio::test] + async fn an_unsettled_gem_leaves_the_selection() { + let other = "pkg:gem/rack@3.1.8"; + let mut all: Vec = fix_a().into_iter().chain(fix_b()).collect(); + all.push(patch(JAVA, other, "2026-01-01T00:00:00Z", &["GHSA-r"])); + let mut offers = offers_from_results(&all, true); + let lock = lock_of(&PLATFORM_ONLY, &offers).await; + lock.narrow(&mut offers); + let left = lock.unsettle(&mut offers); + assert_eq!(left, ["nokogiri 1.19.3"]); + let kept: Vec<&str> = offers.selected.keys().map(String::as_str).collect(); + assert_eq!(kept, [other]); + assert_eq!( + unsettled_detail(&left, "timed out"), + "could not read which fix the platform patches of nokogiri 1.19.3 belong to (timed \ + out); a gem locked as platform builds takes every build from one fix, so it is \ + left as it is by this run. Run it again" + ); + // Nothing selected for the gem: nothing to say. + assert!(lock.unsettle(&mut offers).is_empty()); + } + + /// A build's row is in place only when what the run takes for it is of + /// the fix the project records. A project on fix A whose platform + /// patches are no longer on offer, beside a fix B that covers every + /// locked build, is being moved: every row says so, and names A. + #[tokio::test] + async fn a_move_to_another_fix_is_classified_as_a_move() { + let base = "pkg:gem/nokogiri@1.19.3".to_string(); + let on_a = RecordedIndex::new(None, &[(base.clone(), SRC_A.to_string())]); + let moved = Recorded::Superseded { + old_uuid: SRC_A.to_string(), + }; + let mut offers = offers_from_results(&fix_b(), true); + let lock = lock_of(&PLATFORM_ONLY, &offers).await; + lock.narrow(&mut offers); + let classes = lock.choose(&mut offers, &both_fixes(), &on_a); + assert_eq!(classes.get(LINUX), Some(&moved)); + assert_eq!(classes.get(DARWIN), Some(&moved)); + + // On fix B already: in place. + let on_b = RecordedIndex::new(None, &[(base.clone(), SRC_B.to_string())]); + let mut offers = offers_from_results(&fix_b(), true); + let classes = lock.choose(&mut offers, &both_fixes(), &on_b); + assert_eq!(classes.get(LINUX), Some(&Recorded::Same)); + assert_eq!(classes.get(DARWIN), Some(&Recorded::Same)); + + // On a build's own registry of fix B (its source was not available + // when the gem was moved): in place too. + let on_member = RecordedIndex::new(None, &[(base, B_DARWIN.to_string())]); + let mut offers = offers_from_results(&fix_b(), true); + let classes = lock.choose(&mut offers, &both_fixes(), &on_member); + assert_eq!(classes.get(LINUX), Some(&Recorded::Same)); + // The fix's source patch, which lends nothing there and pins + // nothing, is no newer patch for the project either. + assert_eq!(classes.get(RUBY), Some(&Recorded::Same)); + + // No fix covers every locked build: what the ranking takes for a + // build is still judged by its fix. + let partial: Vec = fix_b().into_iter().take(2).collect(); + let mut offers = offers_from_results(&partial, true); + let classes = lock.choose(&mut offers, &both_fixes(), &on_a); + assert_eq!(classes.get(LINUX), Some(&moved)); + assert_eq!(classes.get(DARWIN), None); + } + + /// The patches of platform gems the lock does not name leave the + /// selection; the ruby gem's patch stays, also for a lock of platform + /// builds alone. A gem version the lock does not name keeps them all. + #[tokio::test] + async fn the_selection_is_narrowed_to_the_builds_the_lock_names() { + let java = "pkg:gem/nokogiri@1.19.3?platform=java"; + let other = "pkg:gem/ffi@1.17.0?platform=java"; + let mut offers = offers_from_results( + &[ + patch(SRC_A, RUBY, "2026-01-01T00:00:00Z", &["GHSA-a"]), + patch(A_LINUX, LINUX, "2026-01-02T00:00:00Z", &["GHSA-a"]), + patch(JAVA, java, "2026-01-02T00:00:00Z", &["GHSA-a"]), + patch(JAVA, other, "2026-01-02T00:00:00Z", &["GHSA-a"]), + ], + true, + ); + let lock = lock_of(&PLATFORM_ONLY, &offers).await; + lock.narrow(&mut offers); + let kept: Vec<&str> = offers.selected.keys().map(String::as_str).collect(); + assert_eq!(kept, [other, RUBY, LINUX]); + assert!(!offers.unfiltered.contains_key(java)); + + // A lock of the ruby gem alone: only its patch stays. + let mut offers = offers_from_results( + &[ + patch(SRC_A, RUBY, "2026-01-01T00:00:00Z", &["GHSA-a"]), + patch(A_LINUX, LINUX, "2026-01-02T00:00:00Z", &["GHSA-a"]), + ], + true, + ); + let lock = lock_of(&["nokogiri (1.19.3)"], &offers).await; + assert!( + lock.reference_uuids(&offers, &RecordedIndex::default()) + .is_empty(), + "no request" + ); + lock.narrow(&mut offers); + let kept: Vec<&str> = offers.selected.keys().map(String::as_str).collect(); + assert_eq!(kept, [RUBY]); + let narrowed = lock.narrow_selected(vec![ + patch(SRC_A, RUBY, "", &[]), + patch(A_LINUX, LINUX, "", &[]), + ]); + assert_eq!(narrowed.len(), 1); + } + + /// Two fixes that tie on severity and advisory count are ranked by + /// publication date, patch purl by patch purl, so the newest build of + /// one platform can be of another fix than the newest of the next. The + /// fix the ruby-platform selection ranks first is taken for every + /// build when it has a patch for each. + #[tokio::test] + async fn a_tie_between_two_fixes_goes_to_the_one_ranked_first_for_the_ruby_gem() { + let mut offers = offers_from_results( + &[ + patch(SRC_A, RUBY, "2026-01-01T00:00:00Z", &["GHSA-a"]), + patch(SRC_B, RUBY, "2026-02-01T00:00:00Z", &["GHSA-b"]), + // A's linux build was published after B's. + patch(A_LINUX, LINUX, "2026-03-02T00:00:00Z", &["GHSA-a"]), + patch(B_LINUX, LINUX, "2026-03-01T00:00:00Z", &["GHSA-b"]), + patch(A_DARWIN, DARWIN, "2026-03-01T00:00:00Z", &["GHSA-a"]), + patch(B_DARWIN, DARWIN, "2026-03-02T00:00:00Z", &["GHSA-b"]), + ], + true, + ); + assert_eq!(offers.selected[LINUX].uuid, A_LINUX); + assert_eq!(offers.selected[DARWIN].uuid, B_DARWIN); + let lock = lock_of(&PLATFORM_ONLY, &offers).await; + lock.narrow(&mut offers); + assert_eq!( + lock.reference_uuids(&offers, &RecordedIndex::default()), + [A_LINUX, A_DARWIN, B_LINUX, B_DARWIN], + "the ruby gem is not locked: its patches' references are not needed" + ); + let references = granted(&[ + (A_LINUX, Some(SRC_A)), + (A_DARWIN, Some(SRC_A)), + (B_LINUX, Some(SRC_B)), + (B_DARWIN, Some(SRC_B)), + ]); + let classes = lock.choose(&mut offers, &references, &RecordedIndex::default()); + assert!(classes.is_empty(), "nothing recorded: the rows are new"); + assert_eq!(offers.selected[RUBY].uuid, SRC_B); + assert_eq!(offers.selected[LINUX].uuid, B_LINUX); + assert_eq!(offers.selected[DARWIN].uuid, B_DARWIN); + } + + /// A newer fix that has no patch for one locked build yet is not + /// taken: the fix that covers every build is, and the ruby gem's own + /// selection (not a locked build here) stays the newer one. + #[tokio::test] + async fn a_fix_without_a_patch_for_every_locked_build_is_passed_over() { + let mut offers = offers_from_results( + &[ + patch(SRC_A, RUBY, "2026-01-01T00:00:00Z", &["GHSA-a"]), + patch(SRC_B, RUBY, "2026-02-01T00:00:00Z", &["GHSA-a", "GHSA-b"]), + patch(A_LINUX, LINUX, "2026-01-02T00:00:00Z", &["GHSA-a"]), + patch( + B_LINUX, + LINUX, + "2026-02-02T00:00:00Z", + &["GHSA-a", "GHSA-b"], + ), + patch(A_DARWIN, DARWIN, "2026-01-02T00:00:00Z", &["GHSA-a"]), + ], + true, + ); + let lock = lock_of(&PLATFORM_ONLY, &offers).await; + let references = granted(&[ + (A_LINUX, Some(SRC_A)), + (A_DARWIN, Some(SRC_A)), + (B_LINUX, Some(SRC_B)), + ]); + lock.choose(&mut offers, &references, &RecordedIndex::default()); + assert_eq!(offers.selected[LINUX].uuid, A_LINUX); + assert_eq!(offers.selected[DARWIN].uuid, A_DARWIN); + assert_eq!(offers.selected[RUBY].uuid, SRC_A, "the chosen fix's source"); + + // With no fix for every build, the selection is left as it was. + let mut offers = offers_from_results( + &[ + patch(SRC_A, RUBY, "2026-01-01T00:00:00Z", &["GHSA-a"]), + patch(B_LINUX, LINUX, "2026-02-02T00:00:00Z", &["GHSA-b"]), + patch(A_DARWIN, DARWIN, "2026-01-02T00:00:00Z", &["GHSA-a"]), + ], + true, + ); + let references = granted(&[(B_LINUX, Some(SRC_B)), (A_DARWIN, Some(SRC_A))]); + let before = offers.selected.clone(); + assert!(lock + .choose(&mut offers, &references, &RecordedIndex::default()) + .is_empty()); + assert_eq!( + offers.selected.keys().collect::>(), + before.keys().collect::>() + ); + assert_eq!(offers.selected[LINUX].uuid, B_LINUX); + } + + /// A patch whose reference is not granted (still building, withdrawn) + /// covers no build. + #[tokio::test] + async fn a_patch_the_run_cannot_use_covers_no_build() { + let mut offers = offers_from_results( + &[ + patch(SRC_A, RUBY, "2026-01-01T00:00:00Z", &["GHSA-a"]), + patch(A_LINUX, LINUX, "2026-01-02T00:00:00Z", &["GHSA-a"]), + patch(A_DARWIN, DARWIN, "2026-01-02T00:00:00Z", &["GHSA-a"]), + ], + true, + ); + let lock = lock_of(&PLATFORM_ONLY, &offers).await; + for status in ["pending_build", "withdrawn", "forbidden"] { + let mut references = granted(&[(A_LINUX, Some(SRC_A))]); + references.insert(A_DARWIN.to_string(), reference(status, Some(SRC_A))); + let mut again = offers.clone(); + assert!(lock + .choose(&mut again, &references, &RecordedIndex::default()) + .is_empty()); + let uuids = |offers: &Offers| -> Vec { + offers.selected.values().map(|p| p.uuid.clone()).collect() + }; + assert_eq!(uuids(&again), uuids(&offers), "{status}"); + } + // And one the response left out. + let references = granted(&[(A_LINUX, Some(SRC_A))]); + lock.choose(&mut offers, &references, &RecordedIndex::default()); + assert_eq!(offers.selected[RUBY].uuid, SRC_A); + } + + /// The project's lock names the registry of one patch for the gem (the + /// fix's source). A re-scan keeps every build on that fix while no fix + /// supersedes it, and moves every build together when one does. + #[tokio::test] + async fn the_builds_of_a_gem_already_on_a_fix_are_classified_together() { + let results = [ + patch(SRC_A, RUBY, "2026-01-01T00:00:00Z", &["GHSA-a"]), + patch(A_LINUX, LINUX, "2026-01-05T00:00:00Z", &["GHSA-a"]), + patch(A_DARWIN, DARWIN, "2026-01-05T00:00:00Z", &["GHSA-a"]), + ]; + let references = granted(&[ + (A_LINUX, Some(SRC_A)), + (A_DARWIN, Some(SRC_A)), + (B_LINUX, Some(SRC_B)), + (B_DARWIN, Some(SRC_B)), + ]); + let pins = [("pkg:gem/nokogiri@1.19.3".to_string(), SRC_A.to_string())]; + let recorded = RecordedIndex::new(None, &pins); + + let mut offers = offers_from_results(&results, true); + let lock = lock_of(&PLATFORM_ONLY, &offers).await; + let classes = lock.choose(&mut offers, &references, &recorded); + // Both builds, and the source patch that lends its registry. + assert_eq!(classes.len(), 3); + assert!(classes.values().all(|class| *class == Recorded::Same)); + + // A second fix, as severe, with as many advisories, and older. + let mut with_b = results.to_vec(); + with_b.extend([ + patch(SRC_B, RUBY, "2025-12-01T00:00:00Z", &["GHSA-b"]), + patch(B_LINUX, LINUX, "2026-01-09T00:00:00Z", &["GHSA-b"]), + patch(B_DARWIN, DARWIN, "2026-01-09T00:00:00Z", &["GHSA-b"]), + ]); + let mut offers = offers_from_results(&with_b, true); + assert_eq!(offers.selected[LINUX].uuid, B_LINUX, "the newer build"); + let classes = lock.choose(&mut offers, &references, &recorded); + assert!(classes.values().all(|class| *class == Recorded::Same)); + assert_eq!(offers.selected[LINUX].uuid, A_LINUX); + assert_eq!(offers.selected[DARWIN].uuid, A_DARWIN); + + // A fix that fixes more supersedes it for every build at once. + let mut with_more = results.to_vec(); + with_more.extend([ + patch(SRC_B, RUBY, "2026-02-01T00:00:00Z", &["GHSA-a", "GHSA-b"]), + patch( + B_LINUX, + LINUX, + "2026-02-02T00:00:00Z", + &["GHSA-a", "GHSA-b"], + ), + patch( + B_DARWIN, + DARWIN, + "2026-02-02T00:00:00Z", + &["GHSA-a", "GHSA-b"], + ), + ]); + let mut offers = offers_from_results(&with_more, true); + let classes = lock.choose(&mut offers, &references, &recorded); + assert_eq!( + classes[LINUX], + Recorded::Superseded { + old_uuid: A_LINUX.to_string() + } + ); + assert_eq!( + classes[DARWIN], + Recorded::Superseded { + old_uuid: A_DARWIN.to_string() + } + ); + assert_eq!(offers.selected[LINUX].uuid, B_LINUX); + assert_eq!(offers.selected[RUBY].uuid, SRC_B); + } + + /// A lock that names the ruby gem beside the platform builds needs the + /// fix's source patch too, and asks about the ruby gem's patches. + #[tokio::test] + async fn a_lock_with_the_ruby_gem_takes_the_source_patch_as_its_build() { + let mut offers = offers_from_results( + &[ + patch(SRC_A, RUBY, "2026-01-01T00:00:00Z", &["GHSA-a"]), + patch(SRC_B, RUBY, "2026-02-01T00:00:00Z", &["GHSA-b"]), + patch(A_LINUX, LINUX, "2026-01-02T00:00:00Z", &["GHSA-a"]), + ], + true, + ); + let lock = lock_of( + &["nokogiri (1.19.3)", "nokogiri (1.19.3-x86_64-linux-gnu)"], + &offers, + ) + .await; + assert_eq!( + lock.reference_uuids(&offers, &RecordedIndex::default()), + [SRC_A, A_LINUX, SRC_B] + ); + let references = granted(&[(SRC_A, None), (SRC_B, None), (A_LINUX, Some(SRC_A))]); + assert_eq!(offers.selected[RUBY].uuid, SRC_B, "the newer ruby patch"); + lock.choose(&mut offers, &references, &RecordedIndex::default()); + assert_eq!(offers.selected[RUBY].uuid, SRC_A); + assert_eq!(offers.selected[LINUX].uuid, A_LINUX); + } +} diff --git a/crates/socket-patch-core/src/hosted/gem_index.rs b/crates/socket-patch-core/src/hosted/gem_index.rs new file mode 100644 index 000000000..50254a9dc --- /dev/null +++ b/crates/socket-patch-core/src/hosted/gem_index.rs @@ -0,0 +1,55 @@ +//! What a gem patch registry lists: its compact-index `info/` document. +//! +//! Each platform gem of a fix has a patch of its own, and the registry of +//! any of them lists and serves every one: one +//! `[-] |checksum:` line per gem. A lock +//! of platform builds takes one such registry as the gem's source and pins +//! each build to a sha256, so before it does the run reads the document +//! once per gem ([`engine::gem_index_targets`]) and the gem rewriter holds +//! the lock's builds against it. +//! +//! [`engine::gem_index_targets`]: super::engine::gem_index_targets + +use crate::api::client::ApiClient; + +/// Bound on one document. A gem version's line is a few hundred bytes and +/// a patch registry lists one version: anything near this is not one. +const MAX_GEM_INDEX_BYTES: usize = 1024 * 1024; + +/// The document as text, or why it is not one (too large, not UTF-8). +pub fn decode_gem_index(bytes: Vec) -> Result { + if bytes.len() > MAX_GEM_INDEX_BYTES { + return Err(format!( + "its index document is {} bytes, more than a patch registry's", + bytes.len() + )); + } + String::from_utf8(bytes).map_err(|_| "its index document is not UTF-8 text".to_string()) +} + +/// Read the compact-index document at `url` +/// ([`crate::patch::redirect::gem_index_info_url`]) from the patch server. +/// The error is safe to print: the URL carries a grant token, which is +/// redacted from it. +pub async fn fetch_gem_index(client: &ApiClient, url: &str) -> Result { + let bytes = client + .download_artifact(url) + .await + .map_err(|error| crate::utils::redact::redact_urls_in(&error.to_string()).into_owned())?; + decode_gem_index(bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_document_is_utf8_text_of_a_bounded_size() { + assert_eq!( + decode_gem_index(b"---\n1.0.0 |checksum:abc\n".to_vec()).as_deref(), + Ok("---\n1.0.0 |checksum:abc\n") + ); + assert!(decode_gem_index(vec![0xff, 0xfe]).is_err()); + assert!(decode_gem_index(vec![b'a'; MAX_GEM_INDEX_BYTES + 1]).is_err()); + } +} diff --git a/crates/socket-patch-core/src/hosted/memory/discover.rs b/crates/socket-patch-core/src/hosted/memory/discover.rs index b1581b591..0e7c47420 100644 --- a/crates/socket-patch-core/src/hosted/memory/discover.rs +++ b/crates/socket-patch-core/src/hosted/memory/discover.rs @@ -364,6 +364,33 @@ pub(crate) async fn fetch_wheel_metadata( .collect() } +/// What each gem patch registry lists, once per distinct document URL +/// ([`crate::hosted::engine::gem_index_targets`]): the disk flow's +/// [`crate::hosted::gem_index::fetch_gem_index`] over the provider. +pub(crate) async fn fetch_gem_indexes( + provider: &Provider, + wanted: &BTreeSet, + max_bytes: u64, +) -> BTreeMap> { + let ordered: Vec<&String> = wanted.iter().collect(); + let futures: Vec> = ordered + .iter() + .map(|url| -> BoxFuture<'_, Result> { + Box::pin(async move { + let bytes = provider + .download_artifact(url, max_bytes) + .await + .map_err(|error| { + crate::utils::redact::redact_urls_in(&error.to_string()).into_owned() + })?; + crate::hosted::gem_index::decode_gem_index(bytes) + }) + }) + .collect(); + let results = join_bounded(futures, provider.concurrency).await; + ordered.into_iter().cloned().zip(results).collect() +} + /// Served npm tarballs' own package.json once per distinct `(url, /// sha512)`, for the yarn berry pin's `bin:` map: the disk flow's /// `fetch_hosted_npm_manifest` over the provider. diff --git a/crates/socket-patch-core/src/hosted/memory/mod.rs b/crates/socket-patch-core/src/hosted/memory/mod.rs index 979102f8c..0d96582a4 100644 --- a/crates/socket-patch-core/src/hosted/memory/mod.rs +++ b/crates/socket-patch-core/src/hosted/memory/mod.rs @@ -75,7 +75,7 @@ use crate::policy::{ PolicySource, Root, RootFile, SelectionPolicy, PATCHES_DISABLED, POLICY_FILE_NAMES, }; use crate::rollout::stage::{ - classify, lookup_incomplete, mark_pinned, offers_from_results, Offers, RecordedIndex, Row, + classify_with, lookup_incomplete, mark_pinned, offers_from_results, Offers, RecordedIndex, Row, Stage, ROLLOUT_DEFERRED, }; use crate::utils::purl_key::PurlKey; @@ -1000,6 +1000,10 @@ async fn engine( .is_some_and(|e| e.code == "patch_lookup_failed") }); let roots_by_path: Vec = states.iter().map(|s| s.root.clone()).collect(); + // The package references read to settle the patches of platform-locked + // gems, by uuid. + let mut gem_references: HashMap = + HashMap::new(); for state in states.iter_mut() { if state.error.is_some() { continue; @@ -1009,7 +1013,49 @@ async fn engine( }; let recorded = memory_recorded(project, &state.root, &roots_by_path).await; stage.incomplete |= lookup_incomplete(&recorded, &state.failed_details, batch_failed); - let mut rows = classify(&state.offers, &recorded, &state.root); + // A gem the Bundler lock names as platform builds has one patch per + // build: the patches of platform gems it does not name leave the + // selection, and its builds take the patches of one fix + // (`gem_fixes`), as on disk. That reads the references of the + // patches on offer for those builds; a failed lookup settles + // nothing here and is reported by the run's own. + let lock = crate::hosted::gem_fixes::GemLock::read( + &ProjectView::Memory(project), + state.offers.unfiltered.keys().map(String::as_str), + ) + .await; + lock.narrow(&mut state.offers); + let asked: BTreeSet = lock + .reference_uuids(&state.offers, &recorded) + .into_iter() + .collect(); + let mut gem_builds = HashMap::new(); + if !asked.is_empty() { + let (found, failed) = discover::fetch_references(&provider, &asked).await; + if failed.is_empty() { + gem_builds = lock.choose(&mut state.offers, &found, &recorded); + gem_references.extend(found.into_iter().filter(|(uuid, reference)| { + asked.contains(uuid) + && matches!( + reference.status.as_str(), + "granted" | "reused" | "withdrawn" | "not_found" | "forbidden" + ) + })); + } else { + // Nothing settled: such a gem is left as it is (see + // `GemLock::unsettle`), and the run says so. + let left = lock.unsettle(&mut state.offers); + if !left.is_empty() { + let why = failed.values().next().cloned().unwrap_or_default(); + warnings.push(EngineWarning::new( + crate::hosted::gem_fixes::GEM_FIX_UNSETTLED, + crate::hosted::gem_fixes::unsettled_detail(&left, &why), + Some(state.root.as_str()), + )); + } + } + } + let mut rows = classify_with(&state.offers, &recorded, Some(&gem_builds), &state.root); for row in &mut rows { row.candidate.in_flight = options.in_flight.contains(&row.candidate.base_purl); } @@ -1026,11 +1072,30 @@ async fn engine( .filter(|s| s.error.is_none()) .flat_map(|s| s.selected.iter().map(|(_, u)| u.clone())) .collect(); - let (references, failed_refs) = if uuids.is_empty() { + // The references read above to settle the gems' patches are not asked + // for again. + let unasked: BTreeSet = uuids + .iter() + .filter(|uuid| !gem_references.contains_key(*uuid)) + .cloned() + .collect(); + let (mut references, failed_refs) = if unasked.is_empty() { (HashMap::new(), BTreeMap::new()) } else { - discover::fetch_references(&provider, &uuids).await + discover::fetch_references(&provider, &unasked).await }; + references.extend(gem_references); + // The source patch of a gem fix, where only its platform builds were + // selected: its registry is the gem's source (see + // `engine::missing_gem_sources`). A failed lookup leaves the gem + // alone, with the rewriter's warning. + let sources: BTreeSet = crate::hosted::engine::missing_gem_sources(&references) + .into_iter() + .collect(); + if !sources.is_empty() { + let (found, _) = discover::fetch_references(&provider, &sources).await; + references.extend(found); + } // Roots whose rows' eligibility is unknown: a reference failure that // hit only NEW rows of a capped run defers them instead of failing the // root (§5.2). @@ -1090,7 +1155,11 @@ async fn engine( &origins, ) .await; - mark_pinned(&mut states[*index].rows, &pins); + mark_pinned( + &mut states[*index].rows, + &pins, + &crate::hosted::engine::gem_fixes_of(&plan.candidates), + ); } let wheels: BTreeSet<(String, String)> = planned .iter() @@ -1129,6 +1198,16 @@ async fn engine( ) .await }; + let gem_index_urls: BTreeSet = planned + .iter() + .flat_map(|(_, p)| p.gem_indexes.iter().cloned()) + .collect(); + let gem_indexes = discover::fetch_gem_indexes( + &provider, + &gem_index_urls, + options.limits.max_artifact_bytes, + ) + .await; phases.mark("plan"); let stage_options = StageOptions { @@ -1144,7 +1223,15 @@ async fn engine( if stage.capped() { first_plans.insert(index, plan.clone()); } - match stages::rewrite(plan, &artifact_metadata, &artifact_classic, stage_options).await { + match stages::rewrite( + plan, + &artifact_metadata, + &artifact_classic, + &gem_indexes, + stage_options, + ) + .await + { Ok(done) => rewritten.push((index, done)), Err(RewriteRefused { refusal, skipped }) => { states[index].skipped = skipped; @@ -1227,11 +1314,19 @@ async fn engine( again.push((index, done)); continue; }; - plan.candidates - .retain(|c| !root_deferred.contains(&c.dep.patch_uuid)); + crate::hosted::engine::drop_deferred(&mut plan.candidates, |c| { + root_deferred.contains(&c.dep.patch_uuid) + }); plan.skipped .extend(states[index].deferred.iter().map(deferred_skip)); - match stages::rewrite(plan, &artifact_metadata, &artifact_classic, stage_options).await + match stages::rewrite( + plan, + &artifact_metadata, + &artifact_classic, + &gem_indexes, + stage_options, + ) + .await { Ok(done) => again.push((index, done)), Err(RewriteRefused { refusal, skipped }) => { diff --git a/crates/socket-patch-core/src/hosted/memory/stages.rs b/crates/socket-patch-core/src/hosted/memory/stages.rs index 79a99af09..f39bfb86b 100644 --- a/crates/socket-patch-core/src/hosted/memory/stages.rs +++ b/crates/socket-patch-core/src/hosted/memory/stages.rs @@ -160,6 +160,12 @@ pub(crate) struct Planned { /// `(artifact url, sha512)` of every npm tarball a yarn classic pin /// reads (its sha1, #558, and its package.json, #591). pub(crate) npm_classic: Vec<(String, String)>, + /// The compact-index documents the gem rewriter checks a lock of + /// platform builds against ([`engine::gem_index_targets`]). + pub(crate) gem_indexes: Vec, + /// The uuids the run selected: a candidate outside them was added for + /// its registry alone ([`engine::quiet_candidates`]). + pub(crate) selected: Vec<(String, String)>, } /// Everything up to the wheel-metadata fetch. `unreadable` are the paths @@ -226,6 +232,7 @@ pub(crate) async fn plan( .into_iter() .filter_map(|dep| Some((dep.artifact_url.clone(), dep.integrity.sha512.clone()?))) .collect(); + let gem_indexes = engine::gem_index_targets(&candidates, &read.files); Ok(Planned { project, candidates, @@ -235,6 +242,8 @@ pub(crate) async fn plan( wheels, npm_manifests, npm_classic, + gem_indexes, + selected: selected.to_vec(), }) } @@ -258,12 +267,14 @@ pub(crate) struct RewriteRefused { } /// Wheel metadata, served npm manifests and the served npm tarballs a -/// yarn classic pin reads (each keyed by artifact URL) → the engine's +/// yarn classic pin reads (each keyed by artifact URL), and what the gem +/// patch registries list (`gem_indexes`, by document URL) → the engine's /// rewrite → the guard. pub(crate) async fn rewrite( planned: Planned, artifact_metadata: &BTreeMap, String>>, artifact_classic: &BTreeMap>, + gem_indexes: &BTreeMap>, options: StageOptions, ) -> Result { let Planned { @@ -271,11 +282,24 @@ pub(crate) async fn rewrite( mut candidates, mut skipped, pre_warnings, - read, + mut read, wheels, npm_manifests, npm_classic, + gem_indexes: gem_index_urls, + selected, } = planned; + let listed: Vec<(String, Result)> = gem_index_urls + .into_iter() + .map(|url| { + let document = gem_indexes + .get(&url) + .cloned() + .unwrap_or_else(|| Err("it was not read".to_string())); + (url, document) + }) + .collect(); + engine::record_gem_index(&mut read, &listed); let skipped_before = skipped.clone(); let mut python_metadata: BTreeMap = BTreeMap::new(); let mut unavailable: BTreeSet = BTreeSet::new(); @@ -395,7 +419,9 @@ pub(crate) async fn rewrite( }); } skipped.extend(done.unattributed.iter().cloned()); - let unconfirmed = engine::unconfirmed_candidates(&candidates, &done.confirmed, &skipped); + let quiet = engine::quiet_candidates(&candidates, &selected, &done.rewrite); + let unconfirmed = + engine::unconfirmed_candidates(&candidates, &done.confirmed, &skipped, &quiet); Ok(Rewritten { project, skipped, diff --git a/crates/socket-patch-core/src/hosted/mod.rs b/crates/socket-patch-core/src/hosted/mod.rs index 952280811..f51019f06 100644 --- a/crates/socket-patch-core/src/hosted/mod.rs +++ b/crates/socket-patch-core/src/hosted/mod.rs @@ -5,6 +5,10 @@ //! [`ProjectView`](crate::vendor::lock_inventory::ProjectView), shared by //! the disk flow (`scan`/`get --mode hosted` in the CLI) and the //! in-memory engine. +//! - [`gem_fixes`] — one fix for every build of a gem the Bundler lock +//! names as platform builds, each of which has a patch of its own. +//! - [`gem_index`] — what a gem patch registry lists, read before a lock +//! of platform builds is pinned to it. //! - [`governing_root`] — the workspace-member pre-check (a lock in an //! ancestor directory governs the project). //! - [`guidance`] — the pnpm `trustLockfile` / npm `allow-remote` @@ -17,6 +21,8 @@ //! (`socket-patch-node`) and the CLI's hidden `hosted-bundle` harness. pub mod engine; +pub mod gem_fixes; +pub mod gem_index; pub mod governing_root; pub mod guidance; pub mod memory; diff --git a/crates/socket-patch-core/src/patch/redirect/grant.rs b/crates/socket-patch-core/src/patch/redirect/grant.rs index 695f5152e..17f51fa85 100644 --- a/crates/socket-patch-core/src/patch/redirect/grant.rs +++ b/crates/socket-patch-core/src/patch/redirect/grant.rs @@ -267,12 +267,11 @@ fn check_registry_override(ov: &RegistryOverride, origins: &[String]) -> Result< return Err(bad(what, "64 hex digits")); } } - // A prebuild's platform and sha256 are spelled into `Gemfile.lock` - // (`name (version-) sha256=`) and its platform into the - // gem file name a refresh downloads. One entry per platform: two would - // leave which sha256 the lock pins to their order. - for (at, prebuild) in ids.gem_platforms.iter().enumerate() { - let platform = prebuild.platform.as_str(); + // The platform a gem patch is for is compared with the platforms + // `Gemfile.lock` names and is printed in a skip's detail; the patch it + // was built from is asked for by its uuid and printed there too. The + // ruby-platform gem's patch states no platform. + if let Some(platform) = ids.gem_platform.as_deref() { if !is_plain_gem_token(platform) || platform.len() > MAX_COORDINATE || !platform.starts_with(|c: char| c.is_ascii_alphabetic()) @@ -280,15 +279,9 @@ fn check_registry_override(ov: &RegistryOverride, origins: &[String]) -> Result< { return Err(bad("gem platform", "a plain platform name")); } - if !is_hex(&prebuild.gem_checksum_sha256, 64) { - return Err(bad("gem platform checksum", "64 hex digits")); - } - if ids.gem_platforms[..at] - .iter() - .any(|earlier| earlier.platform == platform) - { - return Err(bad("gem platform list", "one entry per platform")); - } + } + if served(&ids.gem_rebuilt_from_uuid).is_some_and(|s| !is_canonical_uuid(s)) { + return Err(bad("source patch", "a patch UUID")); } for (what, digest) in [ ("Maven pom sha256", &ids.maven_pom_sha256), @@ -603,45 +596,30 @@ mod tests { let reason = malformed(&dep); assert!(reason.starts_with(&format!("its {field} ")), "{reason}"); } - // A gem patch's prebuilds: each platform and sha256 is written - // into the lock. - type Prebuilds = Vec<(&'static str, String)>; - let sha = "c".repeat(64); - let prebuilds: [(Option<&str>, Prebuilds); 6] = [ - ( - None, - vec![("x86_64-linux-gnu", sha.clone()), ("java", sha.clone())], - ), - (Some("gem platform "), vec![("ruby", sha.clone())]), + // A gem patch's platform is matched against the lock's and printed; + // the patch it was built from is asked for by its uuid. + let platforms: [(Option<&str>, Option<&str>, Option<&str>); 7] = [ + (None, None, None), + (None, Some("x86_64-linux-gnu"), Some(UUID)), + (None, Some("java"), None), + (Some("gem platform "), Some("ruby"), None), ( Some("gem platform "), - vec![("arm64-darwin)\n evil (1.0", sha.clone())], - ), - (Some("gem platform "), vec![("21-darwin", sha.clone())]), - ( - Some("gem platform checksum "), - vec![("arm64-darwin", "abc".to_string())], + Some("arm64-darwin)\n evil (1.0"), + None, ), + (Some("gem platform "), Some("21-darwin"), None), ( - Some("gem platform list "), - vec![("arm64-darwin", sha.clone()), ("arm64-darwin", sha.clone())], + Some("source patch "), + Some("arm64-darwin"), + Some("not-a-uuid\n"), ), ]; - for (field, list) in prebuilds { + for (field, platform, source) in platforms { let mut dep = maven(); - dep.registry_override - .as_mut() - .unwrap() - .identifiers - .gem_platforms = list - .iter() - .map( - |(platform, sha)| crate::patch::redirect::GemPlatformChecksum { - platform: platform.to_string(), - gem_checksum_sha256: sha.clone(), - }, - ) - .collect(); + let ids = &mut dep.registry_override.as_mut().unwrap().identifiers; + ids.gem_platform = platform.map(str::to_string); + ids.gem_rebuilt_from_uuid = source.map(str::to_string); match field { None => assert_eq!(check(&dep, &[]), Ok(())), Some(field) => { diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index 7df8fe1b8..27221abb8 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -199,61 +199,51 @@ pub struct RegistryOverrideIdentifiers { /// `gradle/verification-metadata.xml`. #[cfg_attr(test, serde(skip_serializing_if = "Option::is_none"))] pub maven_module_sha256: Option, - /// sha256 hex of the patched ruby-platform gem (`-.gem`), - /// the value Bundler records in the lock's `CHECKSUMS`. + /// sha256 hex of the patched gem this patch's registry serves for it + /// (`-.gem`, or `--.gem` for the + /// patch of a platform gem): the value Bundler records in the lock's + /// `CHECKSUMS`. pub gem_checksum_sha256: Option, - /// The patch's built prebuilds: one entry per platform the patch - /// registry also serves a patched `--.gem` - /// for. Empty (or absent) when it serves the ruby gem alone. The gem - /// rewriter moves a lock's platform entries only when every one of - /// them is listed here. - #[serde(default, deserialize_with = "lenient_gem_platforms")] - #[cfg_attr(test, serde(skip_serializing_if = "Vec::is_empty"))] - pub gem_platforms: Vec, + /// The gem platform this patch is a patch of, as its package URL names + /// it (`?platform=x86_64-linux-gnu`): `None` for the ruby-platform + /// gem. Each platform gem of a fix has a patch of its own, and a lock + /// entry `name (version-)` is only ever pinned to the patch + /// of that platform. + /// + /// Not a field of the patch API's override: the hosted engine sets it + /// from the granted package URL ([`crate::hosted::engine::build_candidates`]), + /// whatever a response carries here. + #[serde(default)] + #[cfg_attr(test, serde(skip_serializing_if = "Option::is_none"))] + pub gem_platform: Option, + /// The uuid of the patch this one was built from (`rebuiltFromUuid` of + /// the package reference): the ruby-platform gem's patch, for the patch + /// of a platform gem. `None` for a patch that is itself a source. The + /// patches of one fix are one family ([`gem_family`]), and any member's + /// registry lists and serves every member. + /// + /// Set by the hosted engine like [`Self::gem_platform`]. + #[serde(default)] + #[cfg_attr(test, serde(skip_serializing_if = "Option::is_none"))] + pub gem_rebuilt_from_uuid: Option, } -/// `gemPlatforms` as the patch API may send it, read so that the field can -/// never fail the response it rides in: one reference response answers for -/// every package of a batch, and a strict reading of this optional list -/// would cost all of them their grant. `null`, or anything that is no list, -/// is no prebuild. An entry without a `platform` or a `gemChecksumSha256` -/// string (missing, `null`, empty, another type) is dropped: that platform -/// has no prebuild, so a lock that names it keeps the skip. What an entry -/// that IS two strings holds is checked later, per grant ([`grant::check`]). -fn lenient_gem_platforms<'de, D>(deserializer: D) -> Result, D::Error> -where - D: serde::Deserializer<'de>, -{ - let value = Value::deserialize(deserializer)?; - let text = |entry: &Value, key: &str| { - let text = entry.get(key)?.as_str()?; - (!text.is_empty()).then(|| text.to_string()) - }; - Ok(value - .as_array() - .into_iter() - .flatten() - .filter_map(|entry| { - Some(GemPlatformChecksum { - platform: text(entry, "platform")?, - gem_checksum_sha256: text(entry, "gemChecksumSha256")?, - }) - }) - .collect()) +/// The family of the gem patch `dep`: the uuid of the patch it was built +/// from, or its own when it is a source. Patches with one family are the +/// builds of one fix, and the registry of any of them serves them all. +pub fn gem_family(dep: &DepOverride) -> &str { + dep.registry_override + .as_ref() + .and_then(|ov| ov.identifiers.gem_rebuilt_from_uuid.as_deref()) + .unwrap_or(&dep.patch_uuid) } -/// One prebuild of a gem patch: a patched platform gem that is a drop-in -/// for the upstream one (same file name, same gemspec metadata, no -/// `extensions`). -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -#[cfg_attr(test, derive(Serialize))] -#[serde(rename_all = "camelCase")] -pub struct GemPlatformChecksum { - /// `Gem::Platform#to_s` as the gem's file name and `Gemfile.lock` spell - /// it (`x86_64-linux-gnu`, `arm64-darwin`, `java`). Never `ruby`. - pub platform: String, - /// sha256 hex of that platform's `.gem`. - pub gem_checksum_sha256: String, +/// The gem platform the patch `dep` is a patch of: `None` for the +/// ruby-platform gem ([`RegistryOverrideIdentifiers::gem_platform`]). +pub fn gem_platform(dep: &DepOverride) -> Option<&str> { + dep.registry_override + .as_ref() + .and_then(|ov| ov.identifiers.gem_platform.as_deref()) } #[derive(Debug, Clone, Deserialize)] @@ -410,6 +400,46 @@ pub struct RewriteResult { serde(skip_serializing_if = "std::collections::BTreeSet::is_empty") )] pub refused_yarn_classic_uuids: std::collections::BTreeSet, + /// Patch uuids of every gem the Bundler lock names as platform builds: + /// each platform gem of a fix has a patch of its own, the lock holds + /// the registry of one of them (the fix's source patch) and pins each + /// build to its own patch by sha256. So the gem rewriter alone decides + /// them: the registry URL in a file proves nothing about one build's + /// patch. + // Unserialized when empty, like the yarn berry sets above. + #[cfg_attr( + test, + serde(skip_serializing_if = "std::collections::BTreeSet::is_empty") + )] + pub gem_family_uuids: std::collections::BTreeSet, + /// The [`Self::gem_family_uuids`] whose build the lock pins to them, + /// written by this run or already in place: one per locked build. + #[cfg_attr( + test, + serde(skip_serializing_if = "std::collections::BTreeSet::is_empty") + )] + pub confirmed_gem_uuids: std::collections::BTreeSet, + /// For each of [`Self::confirmed_gem_uuids`]: the uuid of the patch + /// whose registry the lock names as the gem's one source (the registry + /// of any patch of a fix serves every build of it). That is the fix's + /// source patch, or the patch of one locked build where the source is + /// not available. Lockfile discovery reads that one uuid for the gem. + #[cfg_attr( + test, + serde(skip_serializing_if = "std::collections::BTreeMap::is_empty") + )] + pub gem_anchor_uuids: std::collections::BTreeMap, + /// Gem patch uuids the lock has no build for: a patch of a platform it + /// does not name, the ruby gem's patch beside a lock of platform + /// builds only (its registry may still be the gem's source), a patch + /// of a platform gem beside a lock of the ruby gem only. Nothing in + /// the project is theirs to pin, so they are neither confirmed nor + /// reported as left unpinned. + #[cfg_attr( + test, + serde(skip_serializing_if = "std::collections::BTreeSet::is_empty") + )] + pub gem_idle_uuids: std::collections::BTreeSet, pub python_lock_uuids: std::collections::BTreeSet, pub confirmed_python_lock_uuids: std::collections::BTreeSet, pub refused_python_lock_uuids: std::collections::BTreeSet, @@ -985,6 +1015,10 @@ fn merge_group_delta(result: &mut RewriteResult, delta: RewriteResult) { confirmed_sbt_uuids, refused_sbt_uuids, confirmed_bazel_maven_uuids, + gem_family_uuids, + confirmed_gem_uuids, + gem_anchor_uuids, + gem_idle_uuids, } = delta; result.files.extend(files); result.binary_files.extend(binary_files); @@ -1044,6 +1078,10 @@ fn merge_group_delta(result: &mut RewriteResult, delta: RewriteResult) { result .confirmed_bazel_maven_uuids .extend(confirmed_bazel_maven_uuids); + result.gem_family_uuids.extend(gem_family_uuids); + result.confirmed_gem_uuids.extend(confirmed_gem_uuids); + result.gem_anchor_uuids.extend(gem_anchor_uuids); + result.gem_idle_uuids.extend(gem_idle_uuids); } /// [`rewrite_groups_serial`], with the groups run concurrently under @@ -8086,15 +8124,23 @@ pub fn grant_token_path_segment(url: &str, patch_uuid: &str) -> Option { /// level, so the idempotency guard never silently degrades into the /// nesting-corruption failure mode when a caller forgets the token. pub(crate) fn gem_index_url_pattern(dep: &DepOverride, index_url: &str) -> String { + gem_index_url_pattern_of(dep, index_url, true) +} + +/// [`gem_index_url_pattern`], with the patch uuid a wildcard only when +/// `any_patch`: without it the pattern is the registry of this one patch, +/// under any grant token. +fn gem_index_url_pattern_of(dep: &DepOverride, index_url: &str, any_patch: bool) -> String { let mut url_pat = regex::escape(index_url); let derived_token = grant_token_path_segment(index_url, &dep.patch_uuid); let rotating = [ Some(dep.token.as_str()), derived_token.as_deref(), - Some(dep.patch_uuid.as_str()), + any_patch.then_some(dep.patch_uuid.as_str()), ]; for rotating in rotating.into_iter().flatten() { - if !rotating.is_empty() { + // The uuid itself is no token, whatever the caller put in `token`. + if !rotating.is_empty() && (any_patch || rotating != dep.patch_uuid) { url_pat = url_pat.replace(®ex::escape(&format!("/{rotating}/")), "/[^/\"]+/"); } } @@ -8841,6 +8887,455 @@ pub(crate) fn gem_pair(files: &BTreeMap) -> (&'static str, &'sta } } +/// Engine-supplied input: what the patch registry of each gem fix lists, +/// as the JSON of a map from a compact-index document's URL +/// (`/info/`, see [`gem_index_info_url`]) to +/// `{"body": ""}`, or `{"error": ""}`. A gem locked as platform builds is pinned only to what that +/// document lists ([`gem_family_pins`]). Absent where no engine read the +/// registry (the rewriter on its own): nothing is checked against it then. +pub const GEM_INDEX_KEY: &str = ""; + +/// The compact-index document a patch registry at `index_url` lists the +/// builds of `name` in: one `[-] |checksum:` +/// line per gem it serves. +pub fn gem_index_info_url(index_url: &str, name: &str) -> String { + format!("{}/info/{name}", index_url.trim_end_matches('/')) +} + +/// The documents of [`GEM_INDEX_KEY`], by URL: `Ok` the text, `Err` why it +/// could not be read. `None` when the key is absent: the caller read no +/// registry at all (the rewrite by itself), and nothing is checked against +/// one. A caller that reads them hands the key in every time, and a gem +/// whose registry it holds no document for is then never pinned. +fn gem_index_documents( + files: &BTreeMap, +) -> Option>> { + let text = files.get(GEM_INDEX_KEY)?; + let Some(Value::Object(documents)) = serde_json::from_str::(text).ok() else { + return Some(BTreeMap::new()); + }; + let documents = documents + .into_iter() + .map(|(url, document)| { + let read = match document.get("body").and_then(Value::as_str) { + Some(body) => Ok(body.to_string()), + None => Err(document + .get("error") + .and_then(Value::as_str) + .unwrap_or("it was not read") + .to_string()), + }; + (url, read) + }) + .collect(); + Some(documents) +} + +/// The sha256 of the `.gem` the patch `dep` serves: its registry override's +/// checksum, else its artifact's. +pub fn gem_patch_sha256(dep: &DepOverride) -> Option { + registry_override_of_kind(dep, "rubygems-compact-index") + .and_then(|ov| ov.identifiers.gem_checksum_sha256.clone()) + .or_else(|| dep.integrity.sha256.clone()) +} + +/// Warning code of a gem locked as platform builds that takes the registry +/// of one locked build's patch as its source, because the patch its builds +/// were built from is not available to the run. The gem is moved all the +/// same; the warning says which registry it is on and what follows. +pub const GEM_MEMBER_REGISTRY: &str = "redirect_gem_member_registry"; + +/// The patch whose registry a gem locked as platform builds takes as its +/// one source. The registry of any patch of a fix lists and serves every +/// gem of the fix, so any of them works; the choice only decides which URL +/// the manifest and the lock carry. In order: +/// +/// 1. the patch whose registry `lock` already takes the gem from, when it +/// is the fix's source patch or the patch of a build the lock still +/// names: a pair that works is not rewritten for another URL of the +/// same fix (so a gem that was moved while the source patch was not +/// available stays where it is when that patch turns up later); +/// 2. the fix's source patch (`source`), where the run has it: its +/// registry is the same whichever platforms the lock names; +/// 3. the patch of the first build the lock names (`of_builds`: the +/// lock's order, platforms sorted as Bundler sorts them). +fn gem_anchor<'a>( + lock: &crate::formats::gem::GemfileLock<'_>, + source: Option<&'a DepOverride>, + of_builds: &[&'a DepOverride], +) -> &'a DepOverride { + let eligible = || source.into_iter().chain(of_builds.iter().copied()); + let (name, version) = (of_builds[0].name.as_str(), of_builds[0].version.as_str()); + // The remotes of the `GEM` sections that list the gem at this version. + let remotes: Vec<&str> = lock + .gem_sections() + .filter(|section| { + let mut specs = section.specs.iter().filter_map(|line| line.parsed); + specs.any(|spec| spec.name == name && spec.version == version) + }) + .flat_map(|section| section.remote_bases()) + .collect(); + let in_use = eligible().find(|dep| { + let Some(ov) = registry_override_of_kind(dep, "rubygems-compact-index") else { + return false; + }; + remotes + .iter() + .any(|remote| is_own_gem_registry(dep, &ov.index_url, remote)) + }); + in_use.or(source).unwrap_or(of_builds[0]) +} + +/// Whether `remote` (a lock's `GEM` remote) is the registry of the patch +/// `dep` itself, under any grant token: see [`gem_registry_matcher`]. +fn is_own_gem_registry(dep: &DepOverride, index_url: &str, remote: &str) -> bool { + gem_registry_matcher(dep, index_url, false) + .is_some_and(|registry| registry.is_match(&closed_url(remote))) +} + +/// `url` with one trailing slash: the form in which the rotating segments +/// of a registry URL (`//`, `//`) are whole path segments also +/// where one of them ends the URL. +fn closed_url(url: &str) -> String { + format!("{}/", url.trim_end_matches('/')) +} + +/// A matcher of the registry URL of the patch `dep` (`index_url`), for a +/// URL in the form of [`closed_url`]: the same recognition the manifest +/// wiring uses ([`gem_index_url_pattern`]), which asks nothing of the +/// URL's shape (a registry behind a patch mirror is recognised like any +/// other). The grant token is a wildcard, since it rotates between runs. +/// With `any_patch` the patch uuid is one too (the registry of any patch of +/// the gem at that address); without it the matcher tells the registries +/// of one fix's patches apart. +fn gem_registry_matcher( + dep: &DepOverride, + index_url: &str, + any_patch: bool, +) -> Option { + let index_url = closed_url(index_url); + let pattern = gem_index_url_pattern_of(dep, &index_url, any_patch); + regex::Regex::new(&format!("^{pattern}$")).ok() +} + +/// How a gem locked as platform builds is pinned ([`gem_family_pins`]). +struct GemFamilyPins<'a> { + /// The patch whose registry becomes the gem's one source + /// ([`gem_anchor`]): the fix's source patch where the run has it. Its + /// registry stays the same whichever platforms the lock names, so the + /// manifest's `source:` URL does not change when one is added. + anchor: &'a DepOverride, + /// The platform of the anchor and the fix's uuid, when the anchor is + /// the patch of a locked build because the fix's source patch is not + /// available to the run: said once, as + /// [`GEM_MEMBER_REGISTRY`]. + member_anchor: Option<(&'a str, &'a str)>, + /// `(token, sha256)` per build the lock names, each from the patch of + /// that build. + checksums: Vec<(String, String)>, + /// The uuid of the patch of each of those builds, in the same order. + members: Vec<&'a str>, +} + +/// The pins of a gem the lock names as platform builds (`builds`), from the +/// patches handed in for that gem version (`group`): one patch per locked +/// build, all of one fix ([`gem_family`]), and the patch whose registry +/// the gem takes as its source ([`gem_anchor`]). `Err` is the `redirect_gem_platform_unsupported` warning of a gem +/// that cannot be moved (`redirect_gem_missing_sha256` for a patch that +/// states no sha256 for its gem), with nothing planned for it: +/// +/// * a locked build has no patch here (none is published for it yet, or +/// this run could not use it), or its patch states no sha256; +/// * no one fix has a patch for every locked build. Among several that do, +/// the fix of the ruby-platform gem's patch is taken (the one the +/// selection rules rank first), else the first handed in; +/// * the fix's registry, where the engine read it +/// (`index_documents`, see [`GEM_INDEX_KEY`]), does not list a locked +/// build with the sha256 its patch states, or could not be read; +/// * `merged`: a bundler before 2.2 wrote the lock. +fn gem_family_pins<'a>( + group: &[&'a DepOverride], + lock: &crate::formats::gem::GemfileLock<'_>, + builds: &crate::formats::gem::LockedBuilds<'_>, + merged: bool, + lock_name: &str, + index_documents: Option<&BTreeMap>>, +) -> Result, RewriteWarning> { + let (name, version) = (group[0].name.as_str(), group[0].version.as_str()); + // Every build the lock names, the ruby-platform one first. + let ids = builds.ids(name, version); + let entry = |id: &crate::patch::gem_source::GemId| format!("`{} ({})`", id.name, id.token()); + let entries = |ids: &[&crate::patch::gem_source::GemId]| { + ids.iter() + .map(|id| entry(id)) + .collect::>() + .join(", ") + }; + let skipped = |why: String| RewriteWarning { + code: "redirect_gem_platform_unsupported".into(), + detail: format!( + "{lock_name} locks platform-specific builds of {name} {version} ({}), and {why}; \ + redirect skipped", + entries( + &ids.iter() + .filter(|id| id.platform.is_some()) + .collect::>() + ), + ), + }; + // Bundler < 2.2 lists every source in one GEM section, where only a + // ruby-platform entry has been proven to converge. + if merged { + return Err(skipped( + "its bundler (< 2.2) lists every gem source in one GEM section, where socket-patch \ + redirects only a ruby platform gem" + .to_string(), + )); + } + // The patches of each locked build, in the order handed in. + let of = |id: &crate::patch::gem_source::GemId| -> Vec<&'a DepOverride> { + group + .iter() + .copied() + .filter(|dep| gem_platform(dep) == id.platform.as_deref()) + .collect() + }; + let patched: Vec> = ids.iter().map(of).collect(); + let missing: Vec<&crate::patch::gem_source::GemId> = ids + .iter() + .zip(&patched) + .filter(|(_, patches)| patches.is_empty()) + .map(|(id, _)| id) + .collect(); + if !missing.is_empty() { + let have: Vec<&crate::patch::gem_source::GemId> = ids + .iter() + .zip(&patched) + .filter(|(_, patches)| !patches.is_empty()) + .map(|(id, _)| id) + .collect(); + let has_ruby_patch = group.iter().any(|dep| gem_platform(dep).is_none()); + let available = match (have.is_empty(), has_ruby_patch) { + (false, _) => format!("one is available for {}", entries(&have)), + (true, true) => "one is available for the ruby platform gem only".to_string(), + (true, false) => "none is available for a build this lock names".to_string(), + }; + return Err(skipped(format!( + "no patch is available for {} ({available}); every locked build needs a patch of \ + the same fix, or a machine of that platform could not install the gem", + entries(&missing), + ))); + } + // The fixes that have a patch for every locked build. + let mut families: Vec<&str> = Vec::new(); + for dep in group { + let family = gem_family(dep); + let complete = patched + .iter() + .all(|patches| patches.iter().any(|dep| gem_family(dep) == family)); + if complete && !families.contains(&family) { + families.push(family); + } + } + let preferred = group + .iter() + .find(|dep| gem_platform(dep).is_none()) + .map(|dep| gem_family(dep)) + .filter(|family| families.contains(family)); + let Some(family) = preferred.or(families.first().copied()) else { + // Which builds each fix patches, in the order the fixes come. + let mut by_fix: Vec<(&str, Vec<&crate::patch::gem_source::GemId>)> = Vec::new(); + for (id, patches) in ids.iter().zip(&patched) { + for dep in patches { + let family = gem_family(dep); + match by_fix.iter_mut().find(|(fix, _)| *fix == family) { + Some((_, ids)) => ids.push(id), + None => by_fix.push((family, vec![id])), + } + } + } + let fixes: Vec = by_fix + .iter() + .map(|(fix, ids)| format!("{} by fix {fix}", entries(ids))) + .collect(); + return Err(skipped(format!( + "its builds are patched by different fixes ({}); one fix must have a patch for \ + every locked build, since the gem takes one patch registry as its source", + fixes.join("; "), + ))); + }; + let mut checksums: Vec<(String, String)> = Vec::with_capacity(ids.len()); + let mut members: Vec<&'a str> = Vec::with_capacity(ids.len()); + // The patch of each locked build, in the lock's order. + let mut of_builds: Vec<&'a DepOverride> = Vec::with_capacity(ids.len()); + for (id, patches) in ids.iter().zip(&patched) { + let Some(member) = patches + .iter() + .copied() + .find(|dep| gem_family(dep) == family) + else { + unreachable!("a chosen fix has a patch for every locked build") + }; + let Some(sha256) = gem_patch_sha256(member) else { + return Err(RewriteWarning { + code: "redirect_gem_missing_sha256".into(), + detail: match &id.platform { + None => format!("{name} has no sha256 checksum"), + Some(platform) => { + format!("{name} has no sha256 checksum for its {platform} gem") + } + }, + }); + }; + checksums.push((id.token(), sha256)); + members.push(member.patch_uuid.as_str()); + of_builds.push(member); + } + let source = group.iter().copied().find(|dep| dep.patch_uuid == family); + let anchor = gem_anchor(lock, source, &of_builds); + let member_anchor = match (source, gem_platform(anchor)) { + (None, Some(platform)) => Some((platform, family)), + _ => None, + }; + // What the registry lists, where the engine read it: the lock is about + // to pin each build to a sha256, and a build the registry does not + // serve with exactly that one fails `bundle install` on its platform. + // `None`: the caller reads no registry. A caller that does must hold + // the document of this very registry: one it did not read is no + // evidence, and the gem is left where it is. + // (An anchor with no registry to name is reported where it is wired.) + let registry = registry_override_of_kind(anchor, "rubygems-compact-index"); + let listed = match (index_documents, registry) { + (Some(documents), Some(ov)) => { + match documents.get(&gem_index_info_url(&ov.index_url, name)) { + Some(read) => Some(read), + None => { + return Err(skipped(format!( + "what the patch registry of fix {family} serves was not read, so \ + nothing says it serves every locked build" + ))); + } + } + } + _ => None, + }; + match listed { + None => {} + Some(Err(why)) => { + return Err(skipped(format!( + "what the patch registry of fix {family} serves could not be read ({why}), so \ + nothing says it serves every locked build" + ))); + } + Some(Ok(info)) => { + let unserved: Vec = ids + .iter() + .zip(&checksums) + .filter_map(|(id, (token, sha256))| { + match upstream::compact_index_checksum(info, token) { + Some(listed) if listed.eq_ignore_ascii_case(sha256) => None, + Some(_) => Some(format!("{} with another sha256", entry(id))), + None => Some(format!("no {}", entry(id))), + } + }) + .collect(); + if !unserved.is_empty() { + return Err(skipped(format!( + "the patch registry of fix {family} does not serve what the lock would pin \ + (it lists {}); a build may have been withdrawn or not be published yet", + unserved.join(", "), + ))); + } + } + } + Ok(GemFamilyPins { + anchor, + member_anchor, + checksums, + members, + }) +} + +/// Whether `lock` already resolves a build of the gem `group` patches from +/// a Socket patch registry: a `GEM` section that lists the gem at that +/// version and whose remote is the registry of one of those patches, under +/// any grant token and any patch uuid (both rotate). True for a lock an +/// earlier run moved, whichever patch of the gem it moved it to. +fn gem_already_hosted(lock: &crate::formats::gem::GemfileLock<'_>, group: &[&DepOverride]) -> bool { + let (name, version) = (group[0].name.as_str(), group[0].version.as_str()); + let registries: Vec = group + .iter() + .filter_map(|dep| { + let ov = registry_override_of_kind(dep, "rubygems-compact-index")?; + gem_registry_matcher(dep, &ov.index_url, true) + }) + .collect(); + lock.gem_sections().any(|section| { + let lists = section + .specs + .iter() + .filter_map(|line| line.parsed) + .any(|spec| spec.name == name && spec.version == version); + lists + && section.remote_bases().any(|remote| { + let remote = closed_url(remote); + registries.iter().any(|registry| registry.is_match(&remote)) + }) + }) +} + +/// The gem patches by gem version, in the order they come: the one +/// grouping of the gem rewriter and of the index lookup that precedes it +/// ([`gem_index_urls`]), so that the registry that is read is the registry +/// that is pinned. +fn gem_groups<'a>(gems: impl Iterator) -> Vec> { + let mut groups: Vec> = Vec::new(); + for dep in gems.filter(|dep| dep.ecosystem == "gem") { + let same = |group: &&mut Vec<&'a DepOverride>| { + group[0].name == dep.name && group[0].version == dep.version + }; + match groups.iter_mut().find(same) { + Some(group) => group.push(dep), + None => groups.push(vec![dep]), + } + } + groups +} + +/// The compact-index documents the gem rewriter checks a lock of platform +/// builds against ([`gem_index_documents`]), sorted: `/info/` +/// of the registry each such gem among `overrides` is about to take as its +/// source ([`gem_anchor`]). None for a gem the rewriter will leave alone +/// (a locked build with no patch, builds of different fixes), and none for +/// a gem locked as its ruby-platform gem alone. +pub fn gem_index_urls(files: &BTreeMap, overrides: &[&DepOverride]) -> Vec { + let (_, lock_name) = gem_pair(files); + let Some(lock) = files.get(lock_name) else { + return Vec::new(); + }; + // Read as the rewriter reads it. + let parsed = crate::formats::gem::parse(lock); + let merged = matches!(lock_layout(lock), Some(LockLayout::Merged(_))); + let groups = gem_groups(overrides.iter().copied()); + let mut urls: std::collections::BTreeSet = std::collections::BTreeSet::new(); + for group in &groups { + let (name, version) = (group[0].name.as_str(), group[0].version.as_str()); + let builds = parsed.locked_builds(name, version); + if builds.platforms.is_empty() { + continue; + } + // The rewriter's own choice, before any registry is read. + let Ok(pins) = gem_family_pins(group, &parsed, &builds, merged, lock_name, None) else { + continue; + }; + if let Some(ov) = registry_override_of_kind(pins.anchor, "rubygems-compact-index") { + urls.insert(gem_index_info_url(&ov.index_url, name)); + } + } + urls.into_iter().collect() +} + fn rewrite_gem( files: &BTreeMap, overrides: &[DepOverride], @@ -8925,7 +9420,96 @@ fn rewrite_gem( // What the calls of a rules_ruby hub hold the gems of this lock to, // read once for every gem (`bazel::ruby`). let held = crate::bazel::ruby::handed_over(files); - for dep in &gem { + // The patches by gem version, in the order they were handed in. Each + // platform gem of a fix has a patch of its own, so one gem version can + // come with several: the lock says which of them it has a build for. + let groups = gem_groups(gem.iter().copied()); + let index_documents = gem_index_documents(files); + for group in &groups { + let uuids = || group.iter().map(|dep| dep.patch_uuid.clone()); + let ruby_patch = group + .iter() + .copied() + .find(|dep| gem_platform(dep).is_none()); + let (name, version) = (group[0].name.as_str(), group[0].version.as_str()); + let builds = handed_in + .as_ref() + .map(|parsed| parsed.locked_builds(name, version)); + // Platform-specific builds (`name (version-arm64-darwin)` among the + // specs or the CHECKSUMS entries): bundler installs the build of + // the machine it runs on, so the redirect holds only when ONE fix + // has a patch for EVERY build the lock names. The registry of that + // fix's source patch then becomes the gem's source (it lists and + // serves every build of the fix), and each entry is pinned to the + // sha256 of its own patch. With one build missing, a machine of + // that platform would be sent to a registry that has no gem for + // it: the gem is skipped whole. + let family = match &builds { + Some(builds) if !builds.platforms.is_empty() => { + // Every patch of the gem is decided here: none is confirmed + // by its registry URL standing in a file. + result.gem_family_uuids.extend(uuids()); + // A patch of a gem the lock does not name has nothing to + // pin here, whatever becomes of the others: a platform the + // lock does not list, and the ruby gem where the lock has + // no ruby-platform entry (its patch can only lend the fix + // its registry). + let named = |dep: &&&DepOverride| match gem_platform(dep) { + Some(platform) => builds.platforms.contains(platform), + None => builds.ruby, + }; + let unnamed = group.iter().filter(|dep| !named(dep)); + result + .gem_idle_uuids + .extend(unnamed.map(|dep| dep.patch_uuid.clone())); + let merged = matches!(layout, Some(LockLayout::Merged(_))); + let Some(parsed) = handed_in.as_ref() else { + continue; + }; + let read = index_documents.as_ref(); + match gem_family_pins(group, parsed, builds, merged, lock_name, read) { + Ok(family) => Some(family), + Err(mut warning) => { + // A lock an earlier run moved stays as it is, and + // the reader is told how to take the gem back. + let hosted = handed_in + .as_ref() + .is_some_and(|parsed| gem_already_hosted(parsed, group)); + if hosted && warning.code == "redirect_gem_platform_unsupported" { + warning.detail.push_str(&format!( + ". {lock_name} already takes {name} from a Socket patch \ + registry and is left as it is: run `socket-patch rollback \ + pkg:gem/{name}@{version}` to put the gem back on its \ + upstream registry, or scan again once every locked build \ + has a patch of one fix" + )); + } + result.warnings.push(warning); + continue; + } + } + } + _ => None, + }; + // The patch whose registry becomes the gem's source: the source + // patch of the fix for a gem locked as platform builds, else the + // ruby gem's own patch. A patch of a platform gem never moves the + // ruby-platform entry: its registry serves no such gem. + let dep: &DepOverride = match (&family, ruby_patch) { + (Some(family), _) => family.anchor, + (None, Some(dep)) => dep, + (None, None) if builds.as_ref().is_some_and(|builds| builds.ruby) => { + result.gem_idle_uuids.extend(uuids()); + continue; + } + (None, None) => group[0], + }; + if family.is_none() { + let others = group.iter().filter(|other| !std::ptr::eq(**other, dep)); + result + .gem_idle_uuids + .extend(others.map(|other| other.patch_uuid.clone())); + } let Some(ov) = registry_override_of_kind(dep, "rubygems-compact-index") else { result.warnings.push(RewriteWarning { code: "redirect_gem_missing_override".into(), @@ -8946,24 +9530,22 @@ fn rewrite_gem( }); continue; } - let sha256 = ov - .identifiers - .gem_checksum_sha256 - .clone() - .or_else(|| dep.integrity.sha256.clone()); - // A lock that names only platform builds pins no ruby-platform gem: - // its prebuilds' sha256 (checked below) are all the redirect needs. - let platform_only = handed_in.as_ref().is_some_and(|parsed| { - let builds = parsed.locked_builds(&dep.name, &dep.version); - !builds.platforms.is_empty() && !builds.ruby - }); - if sha256.is_none() && !platform_only { - result.warnings.push(RewriteWarning { - code: "redirect_gem_missing_sha256".into(), - detail: format!("{} has no sha256 checksum", dep.name), - }); - continue; - } + // What `CHECKSUMS` pins for the gem: one `(token, sha256)` per + // build the lock names. The ruby gem's sha256 under + // `name (version)`, unless the lock names platform builds. + let checksums: Vec<(String, String)> = match &family { + Some(family) => family.checksums.clone(), + None => match gem_patch_sha256(dep) { + Some(sha256) => vec![(dep.version.clone(), sha256)], + None => { + result.warnings.push(RewriteWarning { + code: "redirect_gem_missing_sha256".into(), + detail: format!("{} has no sha256 checksum", dep.name), + }); + continue; + } + }, + }; // Neither manifest nor lock in the chosen spelling: nothing to pin. // Say so once (parity with `redirect_npm_no_lockfile`) instead of // silently dropping the dep from the redirected count. A lock-only @@ -9001,94 +9583,6 @@ fn rewrite_gem( continue; }; - // What `CHECKSUMS` pins for the gem: the ruby gem's sha256 under - // `name (version)`, unless the lock names platform builds. - let mut checksums: Vec<(String, String)> = sha256 - .iter() - .map(|sha| (dep.version.clone(), sha.clone())) - .collect(); - // Platform-specific builds (`name (version-arm64-darwin)` among the - // specs or the CHECKSUMS entries): bundler installs the build of - // the machine it runs on, so the redirect holds only when the patch - // registry serves a patched build ("prebuild") for EVERY platform - // the lock names. Each entry is then pinned to its own prebuild. - // With one missing, a machine of that platform would be sent to a - // registry that has no gem for it (or keep the upstream build under - // the ruby gem's sha256): skip the dep entirely. - if let Some(parsed) = &handed_in { - let builds = parsed.locked_builds(&dep.name, &dep.version); - if !builds.platforms.is_empty() { - let prebuilt = |platform: &str| { - ov.identifiers - .gem_platforms - .iter() - .find(|prebuild| prebuild.platform == platform) - }; - // Every build the lock names, the ruby-platform one first. - let ids = builds.ids(&dep.name, &dep.version); - let entry = |id: &crate::patch::gem_source::GemId| { - format!("`{} ({})`", id.name, id.token()) - }; - let platform_builds = || ids.iter().filter(|id| id.platform.is_some()); - let missing: Vec = platform_builds() - .filter(|id| id.platform.as_deref().and_then(prebuilt).is_none()) - .map(entry) - .collect(); - // Bundler < 2.2 lists every source in one GEM section, where - // only a ruby-platform entry has been proven to converge. - let merged = matches!(layout, Some(LockLayout::Merged(_))); - if !missing.is_empty() || merged { - let why = if !missing.is_empty() { - let served: Vec<&str> = ov - .identifiers - .gem_platforms - .iter() - .map(|prebuild| prebuild.platform.as_str()) - .collect(); - format!( - "the patch has no patched build for {} (the patch registry serves \ - the ruby platform gem{})", - missing.join(", "), - if served.is_empty() { - " only".to_string() - } else { - format!(" and patched builds for {}", served.join(", ")) - } - ) - } else { - "its bundler (< 2.2) lists every gem source in one GEM section, where \ - socket-patch redirects only a ruby platform gem" - .to_string() - }; - result.warnings.push(RewriteWarning { - code: "redirect_gem_platform_unsupported".into(), - detail: format!( - "{lock_name} locks platform-specific builds of {} {} ({}), and \ - {why}; redirect skipped", - dep.name, - dep.version, - platform_builds().map(entry).collect::>().join(", "), - ), - }); - continue; - } - // Each build's entry takes its own archive's sha256. The - // ruby gem's is among them only where the lock has that - // entry beside the platform builds (the registry serves it - // too). - checksums = ids - .iter() - .filter_map(|id| { - let sha256 = match id.platform.as_deref() { - Some(platform) => prebuilt(platform)?.gem_checksum_sha256.clone(), - None => sha256.clone()?, - }; - Some((id.token(), sha256)) - }) - .collect(); - } - } - // The lock is what bundler resolves from: a gem it lists under a // `GIT` / `PATH` / `PLUGIN SOURCE` section is served from there // however the Gemfile spells the declaration (a plain `gem` line in @@ -9168,6 +9662,41 @@ fn rewrite_gem( if plan.unchecked { unchecked.push(dep.name.as_str()); } + // Each locked build is pinned to its own patch. On a lock + // that stays MIXED the builds still resolve upstream: none + // of them is pinned. The patches that pin no build (the + // source patch of a lock with no ruby-platform entry, a + // patch of another fix) only lent the fix its registry. + if let Some(family) = family.filter(|_| !plan.mixed) { + let pinned: Vec = + family.members.iter().map(|uuid| uuid.to_string()).collect(); + let lent = uuids().filter(|uuid| !pinned.contains(uuid)); + result.gem_idle_uuids.extend(lent); + for uuid in &pinned { + result + .gem_anchor_uuids + .insert(uuid.clone(), dep.patch_uuid.clone()); + } + result.confirmed_gem_uuids.extend(pinned); + // The source patch is not available: the gem is on the + // registry of one build's patch, and the reader is told. + if let Some((platform, fix)) = family.member_anchor { + result.warnings.push(RewriteWarning { + code: GEM_MEMBER_REGISTRY.into(), + detail: format!( + "{lock_name} takes {name} {version} from the patch registry of \ + its `{platform}` gem's patch ({anchor}): the patch its builds \ + were built from ({fix}) is not available to this run, and every \ + patch registry of a fix serves every build of it. The `source:` \ + in {gemfile_name} names that registry, so the line changes if \ + `{platform}` leaves {lock_name}", + name = dep.name, + version = dep.version, + anchor = dep.patch_uuid, + ), + }); + } + } } Err(warning) => result.warnings.push(warning), } @@ -22925,9 +23454,10 @@ mod tests { } /// Platform-specific CHECKSUMS siblings (`rails (7.0.0-arm64-darwin)`) - /// mean bundler resolves a platform gem the patch registry does not - /// serve — the bare-platform pin would leave the platform line at the - /// upstream sha (or duplicate the bare line). Fail closed: skip the dep. + /// mean bundler resolves a platform gem, and the ruby gem's patch alone + /// has no gem for it: the bare-platform pin would leave the platform + /// line at the upstream sha (or duplicate the bare line). Fail closed: + /// skip the dep. #[test] fn gem_platform_checksums_fail_closed() { let mut files = BTreeMap::new(); @@ -22957,23 +23487,70 @@ mod tests { "skip must warn: {:?}", r.warnings ); + assert!(r.confirmed_gem_uuids.is_empty()); + } + + /// The uuid of [`gem_build_patch`]'s patch of `platform`. + fn build_uuid(platform: &str) -> String { + format!("uuid-{platform}") } - /// [`gem_override`] with a prebuild (`(platform, sha256)`) per platform. - fn gem_override_prebuilt(name: &str, version: &str, prebuilds: &[(&str, &str)]) -> DepOverride { + /// The patch of one platform gem: a patch of its own (uuid, registry + /// and artifact), built from the patch `source` (the fix's source). + fn gem_build_patch( + name: &str, + version: &str, + platform: &str, + sha256: &str, + source: &str, + ) -> DepOverride { + let uuid = build_uuid(platform); let mut dep = gem_override(name, version); - dep.registry_override + dep.patch_uuid = uuid.clone(); + dep.token = format!("tok-{platform}"); + dep.artifact_url = format!("https://patch.test/{name}-{version}-{platform}.gem"); + let ov = dep + .registry_override .as_mut() - .expect("gem_override always carries a registry override") - .identifiers - .gem_platforms = prebuilds + .expect("gem_override always carries a registry override"); + ov.index_url = format!("https://patch.test/gem/tok-{platform}/{uuid}/"); + ov.identifiers.gem_checksum_sha256 = Some(sha256.to_string()); + ov.identifiers.gem_platform = Some(platform.to_string()); + ov.identifiers.gem_rebuilt_from_uuid = Some(source.to_string()); + dep + } + + /// The patches of one fix of a gem: the ruby gem's patch + /// ([`gem_override`], the fix's source, whose registry is + /// [`GEM_TEST_URL`]) and one patch per platform gem + /// (`(platform, sha256)`), each built from it. + fn gem_fix(name: &str, version: &str, builds: &[(&str, &str)]) -> Vec { + let source = gem_override(name, version); + let mut fix: Vec = builds .iter() - .map(|(platform, sha)| GemPlatformChecksum { - platform: platform.to_string(), - gem_checksum_sha256: sha.to_string(), - }) + .map(|(platform, sha)| gem_build_patch(name, version, platform, sha, "uuid")) .collect(); - dep + fix.insert(0, source); + fix + } + + /// [`gem_redirect`] for the patches of one gem. + fn gem_redirect_fix( + gemfile: &str, + lock: &str, + deps: &[DepOverride], + ) -> (String, String, RewriteResult) { + let files = BTreeMap::from([ + ("Gemfile".to_string(), gemfile.to_string()), + ("Gemfile.lock".to_string(), lock.to_string()), + ]); + let r = rewrite_registry_redirect(&files, deps); + let out = |name: &str| r.files.get(name).unwrap_or(&files[name]).clone(); + (out("Gemfile"), out("Gemfile.lock"), r) + } + + fn uuid_set(uuids: &[&str]) -> std::collections::BTreeSet { + uuids.iter().map(|uuid| uuid.to_string()).collect() } const NOKOGIRI_GEMFILE: &str = @@ -23058,25 +23635,27 @@ mod tests { out } - /// A gem bundler locks as precompiled platform builds, with a prebuild - /// for every one of them. - /// Each entry moves, block and sub-lines verbatim, into the patch - /// registry's `GEM` section; `DEPENDENCIES` is pinned; each `CHECKSUMS` - /// entry takes its own prebuild's sha256. The Gemfile edit is the one - /// a ruby gem gets, and a second scan changes nothing. + /// A gem bundler locks as precompiled platform builds, with a patch of + /// one fix for every one of them. Each entry moves, block and sub-lines + /// verbatim, into the `GEM` section of the fix's source patch's + /// registry; `DEPENDENCIES` is pinned; each `CHECKSUMS` entry takes the + /// sha256 of its own patch. The Gemfile edit is the one a ruby gem + /// gets, each build's own patch is confirmed, the source patch (no + /// build of this lock is its gem) is not, and a second scan changes + /// nothing. #[test] - fn gem_platform_builds_move_to_the_patch_registry_with_their_prebuilds() { + fn gem_platform_builds_move_to_the_registry_of_their_fix() { let (arm, linux) = ("a".repeat(64), "b".repeat(64)); let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; - let dep = gem_override_prebuilt( + let fix = gem_fix( "nokogiri", "1.18.10", &[("arm64-darwin", &arm), ("x86_64-linux-gnu", &linux)], ); - let (gemfile, lock, r) = gem_redirect( + let (gemfile, lock, r) = gem_redirect_fix( NOKOGIRI_GEMFILE, &nokogiri_lock(&platforms, false, true), - dep.clone(), + &fix, ); assert!(r.warnings.is_empty(), "{:?}", r.warnings); assert_eq!( @@ -23131,9 +23710,20 @@ mod tests { ), ] ); - - // The pair the scan left is the pair it wants: nothing to do. - let (_, _, again) = gem_redirect(&gemfile, &lock, dep); + let builds = uuid_set(&["uuid-arm64-darwin", "uuid-x86_64-linux-gnu"]); + assert_eq!(r.confirmed_gem_uuids, builds); + assert_eq!( + r.gem_idle_uuids, + uuid_set(&["uuid"]), + "the source lends its registry" + ); + assert_eq!(r.gem_family_uuids.len(), 3); + // No other patch's registry is written anywhere. + assert!(!gemfile.contains("uuid-") && !lock.contains("uuid-")); + + // The pair the scan left is the pair it wants: nothing to do, and + // the same builds are confirmed. + let (_, _, again) = gem_redirect_fix(&gemfile, &lock, &fix); assert!( again.files.is_empty() && again.edits.is_empty() && again.warnings.is_empty(), "a second scan is a no-op: files={:?} edits={:?} warnings={:?}", @@ -23141,6 +23731,7 @@ mod tests { again.edits, again.warnings ); + assert_eq!(again.confirmed_gem_uuids, builds); } /// A lock with no `CHECKSUMS` section (bundler 2.2–2.5, or checksums @@ -23149,7 +23740,7 @@ mod tests { #[test] fn gem_platform_builds_move_in_a_lock_without_checksums() { let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; - let dep = gem_override_prebuilt( + let fix = gem_fix( "nokogiri", "1.18.10", &[ @@ -23157,10 +23748,10 @@ mod tests { ("x86_64-linux-gnu", &"b".repeat(64)), ], ); - let (gemfile, lock, r) = gem_redirect( + let (gemfile, lock, r) = gem_redirect_fix( NOKOGIRI_GEMFILE, &nokogiri_lock(&platforms, false, false), - dep.clone(), + &fix, ); assert_eq!(lock, nokogiri_lock_hosted(&platforms, false, None)); let codes: Vec<&str> = r.warnings.iter().map(|w| w.code.as_str()).collect(); @@ -23170,7 +23761,8 @@ mod tests { "{:?}", r.warnings ); - let (_, _, again) = gem_redirect(&gemfile, &lock, dep); + assert_eq!(r.confirmed_gem_uuids.len(), 2); + let (_, _, again) = gem_redirect_fix(&gemfile, &lock, &fix); assert!( again.files.is_empty() && again.edits.is_empty(), "a second scan changes nothing: {:?}", @@ -23180,15 +23772,16 @@ mod tests { /// A ruby-platform `name (version)` entry beside the platform builds /// (a lock whose PLATFORMS include `ruby`) moves with them, pinned to - /// the ruby gem's own sha256: the registry serves that gem too. + /// the sha256 of the ruby gem's own patch, the fix's source: that + /// patch is then confirmed too. #[test] fn gem_ruby_entry_beside_platform_builds_moves_with_them() { let arm = "a".repeat(64); - let dep = gem_override_prebuilt("nokogiri", "1.18.10", &[("arm64-darwin", &arm)]); - let (gemfile, lock, r) = gem_redirect( + let fix = gem_fix("nokogiri", "1.18.10", &[("arm64-darwin", &arm)]); + let (gemfile, lock, r) = gem_redirect_fix( NOKOGIRI_GEMFILE, &nokogiri_lock(&["arm64-darwin"], true, true), - dep.clone(), + &fix, ); assert!(r.warnings.is_empty(), "{:?}", r.warnings); assert_eq!( @@ -23199,30 +23792,35 @@ mod tests { Some(&[("1.18.10", &"f".repeat(64)), ("1.18.10-arm64-darwin", &arm)]) ) ); - let (_, _, again) = gem_redirect(&gemfile, &lock, dep); + assert_eq!( + r.confirmed_gem_uuids, + uuid_set(&["uuid", "uuid-arm64-darwin"]) + ); + assert!(r.gem_idle_uuids.is_empty()); + let (_, _, again) = gem_redirect_fix(&gemfile, &lock, &fix); assert!(again.files.is_empty() && again.edits.is_empty()); } - /// One locked platform with no prebuild keeps the whole gem where it - /// is: a machine of that platform would be sent to a registry that has - /// no gem for it. The warning names the missing build and what the - /// registry does serve. + /// One locked platform with no patch keeps the whole gem where it is: + /// a machine of that platform would be sent to a registry that has no + /// gem for it. The warning names the locked builds, the one with no + /// patch and the ones that have one, and nothing is confirmed. #[test] - fn gem_platform_without_a_prebuild_skips_the_gem_and_names_it() { + fn gem_platform_without_a_patch_skips_the_gem_and_names_it() { let lock = nokogiri_lock(&["arm64-darwin", "x86_64-linux-gnu"], false, true); - for (prebuilds, served) in [ + for (builds, available) in [ ( vec![("arm64-darwin", "a".repeat(64))], - "the ruby platform gem and patched builds for arm64-darwin", + "(one is available for `nokogiri (1.18.10-arm64-darwin)`)", ), - (vec![], "the ruby platform gem only"), + (vec![], "(one is available for the ruby platform gem only)"), ] { - let prebuilds: Vec<(&str, &str)> = prebuilds + let builds: Vec<(&str, &str)> = builds .iter() .map(|(platform, sha)| (*platform, sha.as_str())) .collect(); - let dep = gem_override_prebuilt("nokogiri", "1.18.10", &prebuilds); - let (gemfile, after, r) = gem_redirect(NOKOGIRI_GEMFILE, &lock, dep); + let fix = gem_fix("nokogiri", "1.18.10", &builds); + let (gemfile, after, r) = gem_redirect_fix(NOKOGIRI_GEMFILE, &lock, &fix); assert!( r.files.is_empty() && r.edits.is_empty(), "nothing is written: {:?}", @@ -23236,41 +23834,58 @@ mod tests { panic!("one warning: {:?}", r.warnings); }; assert_eq!(warning.code, "redirect_gem_platform_unsupported"); - assert!(warning.detail.contains(served), "{}", warning.detail); assert!( - warning - .detail - .contains("no patched build for `nokogiri (1.18.10-x86_64-linux-gnu)`") - == !prebuilds.is_empty(), + warning.detail.starts_with( + "Gemfile.lock locks platform-specific builds of nokogiri 1.18.10 \ + (`nokogiri (1.18.10-arm64-darwin)`, `nokogiri (1.18.10-x86_64-linux-gnu)`), \ + and no patch is available for " + ), "{}", warning.detail ); + assert!(warning.detail.contains(available), "{}", warning.detail); + assert!( + warning.detail.ends_with("; redirect skipped"), + "{}", + warning.detail + ); + let missing_only_linux = warning + .detail + .contains("no patch is available for `nokogiri (1.18.10-x86_64-linux-gnu)` ("); + assert_eq!(missing_only_linux, !builds.is_empty(), "{}", warning.detail); + assert!(r.confirmed_gem_uuids.is_empty()); + // Every patch of the gem was decided here. A patch of a locked + // build is reported as left unpinned; the ruby gem's patch has + // no entry in this lock and nothing to pin, moved or not. + assert_eq!(r.gem_family_uuids.len(), fix.len()); + assert_eq!(r.gem_idle_uuids, uuid_set(&["uuid"])); } } - /// A lock that names only platform builds needs no ruby-platform - /// sha256: a grant whose prebuilds cover every locked platform but that - /// carries no `gemChecksumSha256` (nor a tarball sha256) still moves the - /// builds. A lock with the ruby entry beside them still needs it. + /// A lock that names only platform builds needs no sha256 of the ruby + /// gem: a source patch that states none still lends its registry, and + /// the builds move. A lock with the ruby entry beside them needs it and + /// says so, as does a platform build whose patch states none. #[test] fn gem_platform_only_lock_needs_no_ruby_checksum() { let (arm, linux) = ("a".repeat(64), "b".repeat(64)); let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; - let mut dep = gem_override_prebuilt( + let mut fix = gem_fix( "nokogiri", "1.18.10", &[("arm64-darwin", &arm), ("x86_64-linux-gnu", &linux)], ); - dep.registry_override + fix[0] + .registry_override .as_mut() .expect("gem_override always carries a registry override") .identifiers .gem_checksum_sha256 = None; - dep.integrity.sha256 = None; - let (_, lock, r) = gem_redirect( + fix[0].integrity.sha256 = None; + let (_, lock, r) = gem_redirect_fix( NOKOGIRI_GEMFILE, &nokogiri_lock(&platforms, false, true), - dep.clone(), + &fix, ); assert!(r.warnings.is_empty(), "{:?}", r.warnings); assert_eq!( @@ -23285,17 +23900,34 @@ mod tests { ) ); let with_ruby = nokogiri_lock(&platforms, true, true); - let (_, after, r) = gem_redirect(NOKOGIRI_GEMFILE, &with_ruby, dep); + let (_, after, r) = gem_redirect_fix(NOKOGIRI_GEMFILE, &with_ruby, &fix); assert_eq!(after, with_ruby); assert_eq!(warning_codes(&r), ["redirect_gem_missing_sha256"]); + + let mut fix = gem_fix("nokogiri", "1.18.10", &[("arm64-darwin", &arm)]); + fix[1] + .registry_override + .as_mut() + .unwrap() + .identifiers + .gem_checksum_sha256 = None; + let only_arm = nokogiri_lock(&["arm64-darwin"], false, true); + let (_, after, r) = gem_redirect_fix(NOKOGIRI_GEMFILE, &only_arm, &fix); + assert_eq!(after, only_arm); + assert_eq!(warning_codes(&r), ["redirect_gem_missing_sha256"]); + assert!( + r.warnings[0].detail.contains("arm64-darwin"), + "{}", + r.warnings[0].detail + ); } /// A platform build named only under `CHECKSUMS` counts as locked: with - /// its prebuild, the ruby entry moves and BOTH entries are re-pinned, - /// each to its own archive (never the platform line left on the + /// its patch, the ruby entry moves and BOTH entries are re-pinned, each + /// to its own patch's gem (never the platform line left on the /// upstream sha256). #[test] - fn gem_platform_checksum_entry_is_pinned_to_its_prebuild() { + fn gem_platform_checksum_entry_is_pinned_to_its_patch() { let arm = "a".repeat(64); let files = BTreeMap::from([ ( @@ -23311,8 +23943,8 @@ mod tests { )), ), ]); - let dep = gem_override_prebuilt("rails", "7.0.0", &[("arm64-darwin", &arm)]); - let r = rewrite_registry_redirect(&files, &[dep]); + let fix = gem_fix("rails", "7.0.0", &[("arm64-darwin", &arm)]); + let r = rewrite_registry_redirect(&files, &fix); assert!(r.warnings.is_empty(), "{:?}", r.warnings); let lock = &r.files["Gemfile.lock"]; assert!( @@ -23336,16 +23968,16 @@ mod tests { fn gem_platform_builds_move_in_a_crlf_lock() { let (arm, linux) = ("a".repeat(64), "b".repeat(64)); let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; - let dep = gem_override_prebuilt( + let fix = gem_fix( "nokogiri", "1.18.10", &[("arm64-darwin", &arm), ("x86_64-linux-gnu", &linux)], ); let crlf = |text: &str| text.replace('\n', "\r\n"); - let (gemfile, lock, r) = gem_redirect( + let (gemfile, lock, r) = gem_redirect_fix( &crlf(NOKOGIRI_GEMFILE), &crlf(&nokogiri_lock(&platforms, false, true)), - dep.clone(), + &fix, ); assert!(r.warnings.is_empty(), "{:?}", r.warnings); assert_eq!( @@ -23359,7 +23991,7 @@ mod tests { ]) )) ); - let (_, _, again) = gem_redirect(&gemfile, &lock, dep); + let (_, _, again) = gem_redirect_fix(&gemfile, &lock, &fix); assert!(again.files.is_empty() && again.edits.is_empty()); } @@ -23376,8 +24008,8 @@ mod tests { " specs:\n loofah (2.24.1)\n nokogiri (>= 1.12.0)\n", ) .replace(" nokogiri (= 1.18.10)\n", " loofah\n"); - let dep = gem_override_prebuilt("nokogiri", "1.18.10", &[("arm64-darwin", &arm)]); - let (gemfile_after, lock_after, r) = gem_redirect(gemfile, &lock, dep); + let fix = gem_fix("nokogiri", "1.18.10", &[("arm64-darwin", &arm)]); + let (gemfile_after, lock_after, r) = gem_redirect_fix(gemfile, &lock, &fix); assert!(r.warnings.is_empty(), "{:?}", r.warnings); assert!( gemfile_after.contains(&format!( @@ -23404,7 +24036,7 @@ mod tests { /// Bundler < 2.2 lists every source in ONE `GEM` section. Only a /// ruby-platform entry is proven to converge there, so a platform build - /// keeps the skip even with a prebuild. + /// keeps the skip even with a patch. #[test] fn gem_platform_builds_in_a_merged_lock_are_skipped() { let lock = @@ -23412,8 +24044,8 @@ mod tests { PLATFORMS\n java\n\nDEPENDENCIES\n nokogiri (= 1.10.10)\n\n\ BUNDLED WITH\n 2.1.4\n"; let gemfile = "source \"https://rubygems.org\"\n\ngem \"nokogiri\", \"1.10.10\"\n"; - let dep = gem_override_prebuilt("nokogiri", "1.10.10", &[("java", &"a".repeat(64))]); - let (_, _, r) = gem_redirect(gemfile, lock, dep); + let fix = gem_fix("nokogiri", "1.10.10", &[("java", &"a".repeat(64))]); + let (_, _, r) = gem_redirect_fix(gemfile, lock, &fix); assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.edits); let [warning] = r.warnings.as_slice() else { panic!("one warning: {:?}", r.warnings); @@ -23426,6 +24058,690 @@ mod tests { ); } + /// The patches of two fixes cannot be mixed: the gem takes one patch + /// registry as its source, and a registry serves the builds of one fix. + /// With no fix that has a patch for every locked build, the gem is + /// left alone and the warning says which build belongs to which fix. + #[test] + fn gem_builds_of_two_fixes_are_skipped_and_named() { + let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; + let lock = nokogiri_lock(&platforms, false, true); + let mut fix = gem_fix("nokogiri", "1.18.10", &[("arm64-darwin", &"a".repeat(64))]); + // The linux build is of another fix, whose source is not at hand. + fix.push(gem_build_patch( + "nokogiri", + "1.18.10", + "x86_64-linux-gnu", + &"b".repeat(64), + "other-fix", + )); + let (gemfile, after, r) = gem_redirect_fix(NOKOGIRI_GEMFILE, &lock, &fix); + assert_eq!( + (gemfile.as_str(), after.as_str()), + (NOKOGIRI_GEMFILE, lock.as_str()) + ); + assert!(r.files.is_empty() && r.edits.is_empty()); + let [warning] = r.warnings.as_slice() else { + panic!("one warning: {:?}", r.warnings); + }; + assert_eq!(warning.code, "redirect_gem_platform_unsupported"); + assert!( + warning.detail.contains( + "its builds are patched by different fixes (`nokogiri (1.18.10-arm64-darwin)` \ + by fix uuid; `nokogiri (1.18.10-x86_64-linux-gnu)` by fix other-fix)" + ), + "{}", + warning.detail + ); + assert!(r.confirmed_gem_uuids.is_empty()); + } + + /// Where more than one fix has a patch for every locked build, the fix + /// of the ruby gem's patch is taken: the one the selection rules rank + /// first. Its registry is the source and each build is pinned to its + /// patch of that fix; the other fix's patches pin nothing. + #[test] + fn gem_fix_of_the_ruby_gems_patch_is_preferred() { + let (arm, other_arm) = ("a".repeat(64), "c".repeat(64)); + let lock = nokogiri_lock(&["arm64-darwin"], false, true); + // The other fix comes first, with a patch for the locked build. + let mut other = gem_build_patch("nokogiri", "1.18.10", "arm64-darwin", &other_arm, "z"); + other.patch_uuid = "z-arm64-darwin".into(); + let mut other_source = gem_override("nokogiri", "1.18.10"); + other_source.patch_uuid = "z".into(); + other_source.registry_override.as_mut().unwrap().index_url = + "https://patch.test/gem/tok-z/z/".into(); + let mut patches = vec![other, other_source.clone()]; + patches.extend(gem_fix("nokogiri", "1.18.10", &[("arm64-darwin", &arm)])); + // The ruby gem's patch handed in first is the one that was ranked + // first. + patches.swap(1, 2); + let (gemfile, after, r) = gem_redirect_fix(NOKOGIRI_GEMFILE, &lock, &patches); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!(gemfile.contains(GEM_TEST_URL), "{gemfile}"); + assert!( + after.contains(&format!(" nokogiri (1.18.10-arm64-darwin) sha256={arm}\n")), + "{after}" + ); + assert_eq!(r.confirmed_gem_uuids, uuid_set(&["uuid-arm64-darwin"])); + assert_eq!(r.gem_idle_uuids, uuid_set(&["uuid", "z", "z-arm64-darwin"])); + } + + /// The registry of a build's own patch, as `gem_build_patch` names it. + fn build_registry(platform: &str) -> String { + format!("https://patch.test/gem/tok-{platform}/uuid-{platform}/") + } + + /// Without the fix's source patch (it is not offered to the run) the + /// gem is moved all the same: the registry of any patch of a fix + /// serves every build, so the patch of the first locked build lends + /// its registry, and a warning says so. Each build is still pinned to + /// its own patch's sha256, and the pin they all go by is that patch's. + #[test] + fn gem_builds_without_their_source_patch_take_a_builds_registry() { + let (arm, linux) = ("a".repeat(64), "b".repeat(64)); + let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; + let lock = nokogiri_lock(&platforms, false, true); + let fix = gem_fix( + "nokogiri", + "1.18.10", + &[("arm64-darwin", &arm), ("x86_64-linux-gnu", &linux)], + ); + let on_arm = build_registry("arm64-darwin"); + let (gemfile, moved, r) = gem_redirect_fix(NOKOGIRI_GEMFILE, &lock, &fix[1..]); + assert_eq!(warning_codes(&r), [GEM_MEMBER_REGISTRY]); + assert_eq!( + r.warnings[0].detail, + "Gemfile.lock takes nokogiri 1.18.10 from the patch registry of its `arm64-darwin` \ + gem's patch (uuid-arm64-darwin): the patch its builds were built from (uuid) 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 `arm64-darwin` \ + leaves Gemfile.lock" + ); + assert!( + gemfile.contains(&format!("source: \"{on_arm}\"")), + "{gemfile}" + ); + assert!( + moved.contains(&format!( + "GEM\n remote: {on_arm}\n specs:\n nokogiri (1.18.10-arm64-darwin)\n \ + racc (~> 1.4)\n nokogiri (1.18.10-x86_64-linux-gnu)\n" + )), + "{moved}" + ); + for (platform, sha) in [("arm64-darwin", &arm), ("x86_64-linux-gnu", &linux)] { + assert!( + moved.contains(&format!(" nokogiri (1.18.10-{platform}) sha256={sha}\n")), + "{moved}" + ); + } + let members = ["uuid-arm64-darwin", "uuid-x86_64-linux-gnu"]; + assert_eq!(r.confirmed_gem_uuids, uuid_set(&members)); + assert_eq!( + r.gem_anchor_uuids, + members + .iter() + .map(|uuid| (uuid.to_string(), "uuid-arm64-darwin".to_string())) + .collect() + ); + + // A re-run is a no-op, and says the same. + let (gemfile_again, lock_again, again) = gem_redirect_fix(&gemfile, &moved, &fix[1..]); + assert_eq!( + (gemfile_again, lock_again), + (gemfile.clone(), moved.clone()) + ); + assert!(again.edits.is_empty(), "{:?}", again.edits); + assert_eq!(warning_codes(&again), [GEM_MEMBER_REGISTRY]); + + // The source patch turns up later: the pair works, so it stays on + // the registry it is on. Nothing is written and nothing is said. + let (gemfile_later, lock_later, later) = gem_redirect_fix(&gemfile, &moved, &fix); + assert_eq!( + (gemfile_later, lock_later), + (gemfile.clone(), moved.clone()) + ); + assert!(later.edits.is_empty(), "{:?}", later.edits); + assert!(later.warnings.is_empty(), "{:?}", later.warnings); + assert_eq!(later.confirmed_gem_uuids, uuid_set(&members)); + assert_eq!(later.gem_idle_uuids, uuid_set(&["uuid"])); + assert_eq!( + later.gem_anchor_uuids["uuid-x86_64-linux-gnu"], + "uuid-arm64-darwin" + ); + + // The platform whose patch lends the registry leaves the lock: the + // gem goes to the source patch's registry where the run has it, + // else to the registry of the first build still locked. + let without_arm = moved + .replace( + " nokogiri (1.18.10-arm64-darwin)\n racc (~> 1.4)\n", + "", + ) + .replace("PLATFORMS\n arm64-darwin\n", "PLATFORMS\n") + .replace( + &format!(" nokogiri (1.18.10-arm64-darwin) sha256={arm}\n"), + "", + ); + assert!( + !without_arm.contains("(1.18.10-arm64-darwin)"), + "{without_arm}" + ); + let on_linux = build_registry("x86_64-linux-gnu"); + for (deps, registry, warned) in [ + (&fix[..], GEM_TEST_URL.to_string(), false), + (&fix[2..], on_linux, true), + ] { + let (gemfile_after, lock_after, r) = gem_redirect_fix(&gemfile, &without_arm, deps); + assert_eq!( + gemfile_after, + gemfile.replace(&on_arm, ®istry), + "the `source:` follows the registry" + ); + assert_eq!(lock_after, without_arm.replace(&on_arm, ®istry)); + assert_eq!( + warning_codes(&r), + if warned { + vec![GEM_MEMBER_REGISTRY] + } else { + Vec::<&str>::new() + } + ); + assert_eq!(r.confirmed_gem_uuids, uuid_set(&["uuid-x86_64-linux-gnu"])); + } + } + + /// A registry is recognised as a patch's own by the URL the patch + /// service handed for it, under any grant token and in any shape: with + /// or without the closing slash, behind a patch mirror, and where the + /// patch uuid is not the last path segment. Another patch's registry + /// at the same address is not it. + #[test] + fn a_patchs_own_gem_registry_is_recognised_in_any_url_shape() { + let arm = gem_build_patch( + "nokogiri", + "1.18.10", + "arm64-darwin", + &"a".repeat(64), + "uuid", + ); + let own = |index_url: &str, remote: &str| is_own_gem_registry(&arm, index_url, remote); + let served = build_registry("arm64-darwin"); + assert!(own(&served, &served)); + assert!(own(&served, served.trim_end_matches('/'))); + assert!(own( + &served, + "https://patch.test/gem/an-older-grant/uuid-arm64-darwin" + )); + assert!(!own(&served, &build_registry("x86_64-linux-gnu"))); + assert!(!own(&served, GEM_TEST_URL)); + assert!(!own(&served, "https://rubygems.org")); + // Behind a mirror the path is the served one, under the mirror's base. + let mirrored = + "https://repo.example/artifactory/socket/gem/tok-arm64-darwin/uuid-arm64-darwin/"; + assert!(own( + mirrored, + "https://repo.example/artifactory/socket/gem/rotated/uuid-arm64-darwin" + )); + assert!(!own(mirrored, &served), "another host is another registry"); + // A registry whose address does not end in the patch uuid. + let nested = "https://repo.example/gems/tok-arm64-darwin/uuid-arm64-darwin/index/"; + assert!(own( + nested, + "https://repo.example/gems/rotated/uuid-arm64-darwin/index" + )); + assert!(!own( + nested, + "https://repo.example/gems/rotated/uuid-x86_64-linux-gnu/index" + )); + } + + /// The patches of [`gem_fix`] with every registry at an address that + /// does not end in the patch uuid (`…///index/`). + fn gem_fix_nested(builds: &[(&str, &str)]) -> Vec { + let mut fix = gem_fix("nokogiri", "1.18.10", builds); + for dep in &mut fix { + let (token, uuid) = (dep.token.clone(), dep.patch_uuid.clone()); + let ov = dep.registry_override.as_mut().expect("a gem registry"); + ov.index_url = format!("https://repo.example/gems/{token}/{uuid}/index/"); + } + fix + } + + /// A gem moved to a build's registry stays there when the source patch + /// turns up, whatever the registry's address looks like: the rule reads + /// the patch's own URL, not the position of the uuid in it. + #[test] + fn gem_on_a_builds_registry_stays_whatever_the_url_shape() { + let (arm, linux) = ("a".repeat(64), "b".repeat(64)); + let lock = nokogiri_lock(&["arm64-darwin", "x86_64-linux-gnu"], false, true); + let fix = gem_fix_nested(&[("arm64-darwin", &arm), ("x86_64-linux-gnu", &linux)]); + let (gemfile, moved, first) = gem_redirect_fix(NOKOGIRI_GEMFILE, &lock, &fix[1..]); + assert_eq!(warning_codes(&first), [GEM_MEMBER_REGISTRY]); + let on_arm = "https://repo.example/gems/tok-arm64-darwin/uuid-arm64-darwin/index/"; + assert!(moved.contains(&format!(" remote: {on_arm}\n")), "{moved}"); + + let (gemfile_later, lock_later, later) = gem_redirect_fix(&gemfile, &moved, &fix); + assert_eq!((gemfile_later, lock_later), (gemfile, moved)); + assert!(later.edits.is_empty(), "{:?}", later.edits); + assert!(later.warnings.is_empty(), "{:?}", later.warnings); + assert_eq!( + later.gem_anchor_uuids["uuid-x86_64-linux-gnu"], + "uuid-arm64-darwin" + ); + } + + /// A lock an earlier run moved is recognised as moved also when the + /// patch it was moved to is no longer among the run's patches (an + /// older fix): the registry is a patch registry of this gem under any + /// grant token and any patch uuid, and the skip says the lock is left + /// as it is. + #[test] + fn gem_lock_on_an_older_patchs_registry_is_known_as_hosted() { + let (arm, linux) = ("a".repeat(64), "b".repeat(64)); + let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; + let fix = gem_fix("nokogiri", "1.18.10", &[("arm64-darwin", &arm)]); + let pins = [ + ("1.18.10-arm64-darwin", arm.as_str()), + ("1.18.10-x86_64-linux-gnu", linux.as_str()), + ]; + let older = "https://patch.test/gem/an-older-grant/an-older-patch/"; + let lock = + nokogiri_lock_hosted(&platforms, false, Some(&pins)).replace(GEM_TEST_URL, older); + let gemfile = + NOKOGIRI_GEMFILE.replace("\"1.18.10\"", &format!("\"1.18.10\", source: \"{older}\"")); + let (_, _, r) = gem_redirect_fix(&gemfile, &lock, &fix); + assert_eq!(warning_codes(&r), ["redirect_gem_platform_unsupported"]); + assert!( + r.warnings[0] + .detail + .contains("already takes nokogiri from a Socket patch registry"), + "{}", + r.warnings[0].detail + ); + assert!(r.files.is_empty() && r.edits.is_empty()); + } + + /// The registry that is read is the registry that is pinned: the index + /// lookup and the rewriter decide the gem's registry with one function + /// over one grouping. Where the caller reads registries and holds no + /// document for the one the rewriter is about to pin (it read another, + /// or none), the gem is left alone: an unread registry is no evidence. + #[test] + fn gem_registry_that_was_not_read_is_never_pinned() { + let (arm, linux) = ("a".repeat(64), "b".repeat(64)); + let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; + let fix = gem_fix( + "nokogiri", + "1.18.10", + &[("arm64-darwin", &arm), ("x86_64-linux-gnu", &linux)], + ); + let lock = nokogiri_lock(&platforms, false, true); + let files = |documents: Option| { + let mut files = BTreeMap::from([ + ("Gemfile".to_string(), NOKOGIRI_GEMFILE.to_string()), + ("Gemfile.lock".to_string(), lock.clone()), + ]); + if let Some(documents) = documents { + files.insert(GEM_INDEX_KEY.to_string(), documents.to_string()); + } + files + }; + let body = format!( + "---\n1.18.10-arm64-darwin racc:~> 1.4|checksum:{arm}\n\ + 1.18.10-x86_64-linux-gnu racc:~> 1.4|checksum:{linux}\n" + ); + let of_source = gem_index_info_url(GEM_TEST_URL, "nokogiri"); + let of_arm = gem_index_info_url(&build_registry("arm64-darwin"), "nokogiri"); + + // The lookup names the registry the rewriter takes: the source + // patch's with the whole fix, the first build's without it. + let whole: Vec<&DepOverride> = fix.iter().collect(); + assert_eq!(gem_index_urls(&files(None), &whole), [of_source.clone()]); + assert_eq!(gem_index_urls(&files(None), &whole[1..]), [of_arm.clone()]); + + // Read and pinned agree: the gem moves. + let read_arm = json!({ of_arm.clone(): { "body": body } }); + let moved = rewrite_registry_redirect(&files(Some(read_arm)), &fix[1..]); + assert_eq!(warning_codes(&moved), [GEM_MEMBER_REGISTRY]); + assert_eq!(moved.confirmed_gem_uuids.len(), 2); + + // The document of another registry of the fix, and no document. + for documents in [json!({ of_source.clone(): { "body": body } }), json!({})] { + let r = rewrite_registry_redirect(&files(Some(documents)), &fix[1..]); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.edits); + assert!(r.confirmed_gem_uuids.is_empty()); + assert_eq!(warning_codes(&r), ["redirect_gem_platform_unsupported"]); + assert!( + r.warnings[0].detail.contains( + "what the patch registry of fix uuid serves was not read, so nothing says \ + it serves every locked build; redirect skipped" + ), + "{}", + r.warnings[0].detail + ); + } + + // The rewrite by itself (no caller that reads registries) pins. + let alone = rewrite_registry_redirect(&files(None), &fix[1..]); + assert_eq!(alone.confirmed_gem_uuids.len(), 2); + } + + /// Where the engine read what the fix's registry lists + /// ([`GEM_INDEX_KEY`]), the lock is pinned only to what it lists: every + /// locked build, each with the sha256 its own patch states. A build the + /// registry does not list (not published yet, withdrawn), one listed + /// with another sha256, and a registry that could not be read each + /// leave the gem alone. + #[test] + fn gem_registry_must_list_every_locked_build() { + let (arm, linux) = ("a".repeat(64), "b".repeat(64)); + let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; + let fix = gem_fix( + "nokogiri", + "1.18.10", + &[("arm64-darwin", &arm), ("x86_64-linux-gnu", &linux)], + ); + let lock = nokogiri_lock(&platforms, false, true); + let url = gem_index_info_url(GEM_TEST_URL, "nokogiri"); + assert_eq!(url, "https://patch.test/gem/tok/uuid/info/nokogiri"); + let run = |document: Value| { + let files = BTreeMap::from([ + ("Gemfile".to_string(), NOKOGIRI_GEMFILE.to_string()), + ("Gemfile.lock".to_string(), lock.clone()), + ( + GEM_INDEX_KEY.to_string(), + json!({ url.clone(): document }).to_string(), + ), + ]); + rewrite_registry_redirect(&files, &fix) + }; + let listing = |arm: &str, linux: Option<&str>| { + let mut body = format!( + "---\n1.18.10 mini_portile2:~> 2.8.2,racc:~> 1.4|checksum:{},ruby:>= 3.1.0\n\ + 1.18.10-arm64-darwin racc:~> 1.4|checksum:{arm}\n", + "f".repeat(64) + ); + if let Some(linux) = linux { + body.push_str(&format!( + "1.18.10-x86_64-linux-gnu racc:~> 1.4|checksum:{linux},ruby:< 3.5.dev&>= \ + 3.1,rubygems:>= 3.3.22\n" + )); + } + json!({ "body": body }) + }; + + let moved = run(listing(&arm, Some(&linux))); + assert!(moved.warnings.is_empty(), "{:?}", moved.warnings); + assert_eq!(moved.confirmed_gem_uuids.len(), 2); + assert!( + !moved.files.contains_key(GEM_INDEX_KEY), + "the engine's input is never a written file" + ); + + for (document, why) in [ + ( + listing(&arm, None), + "it lists no `nokogiri (1.18.10-x86_64-linux-gnu)`", + ), + ( + listing(&arm, Some(&"d".repeat(64))), + "it lists `nokogiri (1.18.10-x86_64-linux-gnu)` with another sha256", + ), + ( + json!({ "error": "HTTP 410 Gone" }), + "could not be read (HTTP 410 Gone)", + ), + (json!({}), "could not be read (it was not read)"), + ] { + let r = run(document); + assert!(r.files.is_empty() && r.edits.is_empty(), "{why}"); + assert!(r.confirmed_gem_uuids.is_empty(), "{why}"); + let [warning] = r.warnings.as_slice() else { + panic!("one warning: {:?}", r.warnings); + }; + assert_eq!(warning.code, "redirect_gem_platform_unsupported"); + assert!(warning.detail.contains(why), "{}", warning.detail); + } + } + + /// A lock that gains a platform later moves the new entry into the + /// section the gem already has: the source is the fix's source patch's + /// registry whichever builds the lock names, so the manifest line does + /// not change and the lock gains the one entry. + #[test] + fn gem_lock_gaining_a_platform_keeps_the_manifest_line() { + let (arm, linux) = ("a".repeat(64), "b".repeat(64)); + let fix = gem_fix( + "nokogiri", + "1.18.10", + &[("arm64-darwin", &arm), ("x86_64-linux-gnu", &linux)], + ); + // First, a lock of the linux build alone; the patch of the other + // platform is on offer and has nothing to pin. + let (gemfile, lock, first) = gem_redirect_fix( + NOKOGIRI_GEMFILE, + &nokogiri_lock(&["x86_64-linux-gnu"], false, true), + &fix, + ); + assert!(first.warnings.is_empty(), "{:?}", first.warnings); + assert_eq!( + first.confirmed_gem_uuids, + uuid_set(&["uuid-x86_64-linux-gnu"]) + ); + assert_eq!( + first.gem_idle_uuids, + uuid_set(&["uuid", "uuid-arm64-darwin"]) + ); + // Then the lock gains the darwin build, as `bundle lock + // --add-platform` resolves it from the gem's one source: under the + // patch registry's section, with what the registry lists for it. + let gained = lock + .replace( + " specs:\n nokogiri (1.18.10-x86_64-linux-gnu)\n", + " specs:\n nokogiri (1.18.10-arm64-darwin)\n racc (~> 1.4)\n \ + nokogiri (1.18.10-x86_64-linux-gnu)\n", + ) + .replace("PLATFORMS\n", "PLATFORMS\n arm64-darwin\n") + .replace( + "CHECKSUMS\n", + &format!("CHECKSUMS\n nokogiri (1.18.10-arm64-darwin) sha256={arm}\n"), + ); + assert_ne!(gained, lock); + let (gemfile_again, lock_again, second) = gem_redirect_fix(&gemfile, &gained, &fix); + assert!(second.warnings.is_empty(), "{:?}", second.warnings); + assert_eq!(gemfile_again, gemfile, "the manifest line is the same"); + assert_eq!(lock_again, gained, "the lock already holds the entry"); + assert_eq!( + second.confirmed_gem_uuids, + uuid_set(&["uuid-arm64-darwin", "uuid-x86_64-linux-gnu"]) + ); + } + + /// A pair an earlier development build wired, when one patch listed + /// the patched gem of every platform: every platform entry sits under + /// the registry of the ruby gem's patch, pinned to the sha256 that + /// patch listed for it. That patch is the source patch of today's fix, + /// so the pair is the one a scan writes today but for the checksums. + fn nokogiri_pair_of_an_earlier_build(arm: &str, linux: &str) -> (String, String) { + let gemfile = NOKOGIRI_GEMFILE.replace( + "\"1.18.10\"", + &format!("\"1.18.10\", source: \"{GEM_TEST_URL}\""), + ); + let lock = nokogiri_lock_hosted( + &["arm64-darwin", "x86_64-linux-gnu"], + false, + Some(&[ + ("1.18.10-arm64-darwin", arm), + ("1.18.10-x86_64-linux-gnu", linux), + ]), + ); + (gemfile, lock) + } + + /// Such a pair converges on the next scan: with a patch for every + /// locked build, the manifest line stays, each `CHECKSUMS` entry takes + /// the sha256 of its own patch (unchanged when the patched gem is the + /// same archive), and each build is recorded under its own patch. + #[test] + fn gem_pair_of_an_earlier_build_converges() { + let (old_arm, old_linux) = ("c".repeat(64), "d".repeat(64)); + let (gemfile, lock) = nokogiri_pair_of_an_earlier_build(&old_arm, &old_linux); + // The same archives: nothing is written. + let same = gem_fix( + "nokogiri", + "1.18.10", + &[("arm64-darwin", &old_arm), ("x86_64-linux-gnu", &old_linux)], + ); + let (gemfile_after, lock_after, r) = gem_redirect_fix(&gemfile, &lock, &same); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!(r.edits.is_empty(), "{:?}", r.edits); + assert_eq!((gemfile_after, lock_after), (gemfile.clone(), lock.clone())); + assert_eq!( + r.confirmed_gem_uuids, + uuid_set(&["uuid-arm64-darwin", "uuid-x86_64-linux-gnu"]) + ); + // Rebuilt archives: the checksums follow, and nothing else moves. + let (arm, linux) = ("a".repeat(64), "b".repeat(64)); + let rebuilt = gem_fix( + "nokogiri", + "1.18.10", + &[("arm64-darwin", &arm), ("x86_64-linux-gnu", &linux)], + ); + let (gemfile_after, lock_after, r) = gem_redirect_fix(&gemfile, &lock, &rebuilt); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert_eq!(gemfile_after, gemfile, "the manifest line is the same"); + assert_eq!( + lock_after, + lock.replace(&old_arm, &arm).replace(&old_linux, &linux), + "only the two checksums change" + ); + assert_eq!( + r.confirmed_gem_uuids, + uuid_set(&["uuid-arm64-darwin", "uuid-x86_64-linux-gnu"]) + ); + } + + /// Such a pair is left exactly as it is while a locked build has no + /// patch (the fix lists the ruby gem's patch alone, or one platform's + /// is missing): the warning names the builds and says how to take the + /// gem back to its upstream registry. + #[test] + fn gem_pair_of_an_earlier_build_is_kept_and_the_way_back_named() { + let (old_arm, old_linux) = ("c".repeat(64), "d".repeat(64)); + let (gemfile, lock) = nokogiri_pair_of_an_earlier_build(&old_arm, &old_linux); + let fix = gem_fix("nokogiri", "1.18.10", &[("arm64-darwin", &old_arm)]); + for (deps, missing) in [ + ( + &fix[..1], + "no patch is available for `nokogiri (1.18.10-arm64-darwin)`, `nokogiri \ + (1.18.10-x86_64-linux-gnu)` (one is available for the ruby platform gem only)", + ), + ( + &fix[..], + "no patch is available for `nokogiri (1.18.10-x86_64-linux-gnu)` (one is \ + available for `nokogiri (1.18.10-arm64-darwin)`)", + ), + ] { + let (gemfile_after, lock_after, r) = gem_redirect_fix(&gemfile, &lock, deps); + assert_eq!( + (gemfile_after, lock_after), + (gemfile.clone(), lock.clone()), + "neither file changes" + ); + assert!(r.edits.is_empty(), "{:?}", r.edits); + assert!(r.confirmed_gem_uuids.is_empty(), "no build is attested"); + let [warning] = r.warnings.as_slice() else { + panic!("one warning: {:?}", r.warnings); + }; + assert_eq!(warning.code, "redirect_gem_platform_unsupported"); + assert!(warning.detail.contains(missing), "{}", warning.detail); + assert!( + warning.detail.ends_with( + "redirect skipped. Gemfile.lock already takes nokogiri from a Socket patch \ + registry and is left as it is: run `socket-patch rollback \ + pkg:gem/nokogiri@1.18.10` to put the gem back on its upstream registry, or \ + scan again once every locked build has a patch of one fix" + ), + "{}", + warning.detail + ); + } + // A lock that was never moved gets no such advice. + let upstream = nokogiri_lock(&["arm64-darwin", "x86_64-linux-gnu"], false, true); + let (_, _, r) = gem_redirect_fix(NOKOGIRI_GEMFILE, &upstream, &fix); + assert!( + r.warnings[0].detail.ends_with("redirect skipped"), + "{}", + r.warnings[0].detail + ); + } + + /// A patch only ever pins the gem it is a patch of. Beside a lock of + /// the ruby gem alone, the patches of platform gems have nothing to + /// pin: the ruby gem's patch moves it as before, by its own registry. + /// And a platform gem's patch never moves a ruby-platform entry: its + /// registry serves no such gem. + #[test] + fn gem_patches_of_builds_the_lock_does_not_name_pin_nothing() { + let gemfile = "source \"https://rubygems.org\"\n\ngem \"rails\", \"7.0.0\"\n"; + let lock = gem_lock(&format!(" rails (7.0.0) sha256={}", "2".repeat(64))); + let fix = gem_fix("rails", "7.0.0", &[("java", &"a".repeat(64))]); + let (gemfile_after, lock_after, r) = gem_redirect_fix(gemfile, &lock, &fix); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!(gemfile_after.contains(GEM_TEST_URL), "{gemfile_after}"); + assert!( + lock_after.contains(&format!(" rails (7.0.0) sha256={}\n", "f".repeat(64))), + "{lock_after}" + ); + assert_eq!(r.gem_idle_uuids, uuid_set(&["uuid-java"])); + assert!( + r.gem_family_uuids.is_empty() && r.confirmed_gem_uuids.is_empty(), + "a gem locked as its ruby gem alone is confirmed by its registry URL, as before" + ); + + let (gemfile_after, lock_after, r) = gem_redirect_fix(gemfile, &lock, &fix[1..]); + assert_eq!( + (gemfile_after.as_str(), lock_after.as_str()), + (gemfile, lock.as_str()) + ); + assert!( + r.warnings.is_empty() && r.edits.is_empty(), + "{:?}", + r.warnings + ); + assert_eq!(r.gem_idle_uuids, uuid_set(&["uuid-java"])); + } + + /// A patch reference that still carries the fields the patch service + /// once listed a patch's platform builds in is read as the ruby gem's + /// patch alone: the lock's platform builds have no patch, and the gem + /// is left where it is. + #[test] + fn gem_retired_platform_fields_are_ignored() { + let (arm, linux) = ("a".repeat(64), "b".repeat(64)); + let mut dep = serde_json::to_value(gem_override("nokogiri", "1.18.10")).unwrap(); + dep["registryOverride"]["identifiers"]["gemPlatforms"] = json!([ + { "platform": "arm64-darwin", "gemChecksumSha256": arm }, + { "platform": "x86_64-linux-gnu", "gemChecksumSha256": linux }, + ]); + let dep: DepOverride = serde_json::from_value(dep).expect("the retired field is read past"); + let lock = nokogiri_lock(&["arm64-darwin", "x86_64-linux-gnu"], false, true); + let (gemfile, after, r) = gem_redirect(NOKOGIRI_GEMFILE, &lock, dep); + assert_eq!( + (gemfile.as_str(), after.as_str()), + (NOKOGIRI_GEMFILE, lock.as_str()) + ); + assert_eq!(warning_codes(&r), ["redirect_gem_platform_unsupported"]); + assert!( + r.warnings[0] + .detail + .contains("(one is available for the ruby platform gem only)"), + "{}", + r.warnings[0].detail + ); + } + /// Legal-but-non-canonical declarations (parenthesized call, tab or no /// space after `gem`) are declarations all the same: each takes the /// option where it is — treating one as undeclared would add a second @@ -30215,7 +31531,9 @@ packages: let mut gem_no_override = gem_override("rails", "7.0.0"); gem_no_override.registry_override = None; - let mut gem_no_sha = gem_override("rails", "7.0.0"); + // Another gem: of two patches of one gem version, only the first + // is that gem's. + let mut gem_no_sha = gem_override("rack", "3.1.8"); gem_no_sha .registry_override .as_mut() diff --git a/crates/socket-patch-core/src/policy/mod.rs b/crates/socket-patch-core/src/policy/mod.rs index e79cc569b..7ee33f840 100644 --- a/crates/socket-patch-core/src/policy/mod.rs +++ b/crates/socket-patch-core/src/policy/mod.rs @@ -828,6 +828,12 @@ pub struct Offers { /// them gives way to the selection, whatever it ranks /// ([`crate::rollout::stage::classify`]). pub withheld: BTreeSet<(String, String)>, + /// The offers no filter admits, as `(purl, uuid)`: the withheld ones + /// and the ones below the severity floor. A step that picks another + /// offer of a purl than the winner (a gem fix is taken whole, for + /// every build the lock names) picks among the rest only, so every + /// filter holds for what it picks. Empty without a policy. + pub refused: BTreeSet<(String, String)>, } /// Whether a `--package` spec names the package at `purl`: a purl spec diff --git a/crates/socket-patch-core/src/rollout/stage.rs b/crates/socket-patch-core/src/rollout/stage.rs index 8d09aadba..34774ba77 100644 --- a/crates/socket-patch-core/src/rollout/stage.rs +++ b/crates/socket-patch-core/src/rollout/stage.rs @@ -85,6 +85,7 @@ pub fn offers_from_results(results: &[PatchSearchResult], can_access_paid: bool) unfiltered, selected, withheld: BTreeSet::new(), + refused: BTreeSet::new(), } } @@ -196,6 +197,26 @@ impl RecordedIndex { /// Classify every selected purl of one project root (§5.1). `recorded` is /// the merged view (manifest > hosted pins > vendor ledger). pub fn classify(offers: &Offers, recorded: &RecordedIndex, project: &str) -> Vec { + classify_with(offers, recorded, None, project) +} + +/// [`classify`] for a run that changes what Bundler installs (hosted and +/// vendored mode), which settles the builds of a gem together +/// (`gem_builds`, by patch purl: +/// [`GemLock::choose`](crate::hosted::gem_fixes::GemLock::choose)). Each +/// platform gem of a fix has a patch of its own, and such a project records +/// one uuid for the gem (the registry its lock names, the directory it is +/// vendored under), so only the fix a patch belongs to says whether a +/// build's row is in place or a move to another fix: a row decided there +/// takes that class. Every other row, and every row of a run that settles +/// nothing (`None`: agent mode, a report-only scan), is classified by its +/// own purl, as [`classify`] does. +pub fn classify_with( + offers: &Offers, + recorded: &RecordedIndex, + gem_builds: Option<&HashMap>, + project: &str, +) -> Vec { offers .selected .iter() @@ -206,7 +227,9 @@ pub fn classify(offers: &Offers, recorded: &RecordedIndex, project: &str) -> Vec .get(purl) .map(Vec::as_slice) .unwrap_or(&[]); - let (class, writer) = if uuids.is_empty() { + let (class, writer) = if let Some(class) = gem_builds.and_then(|g| g.get(purl)) { + (class.clone(), selected.clone()) + } else if uuids.is_empty() { (Recorded::None, selected.clone()) } else if uuids.contains(&selected.uuid) { (Recorded::Same, selected.clone()) @@ -283,16 +306,32 @@ pub fn lookup_incomplete( /// /// [`HostedPin::discover`]: crate::patch::redirect::upstream::HostedPin::discover /// [`dep_origins`]: crate::patch::redirect::upstream::dep_origins -pub fn mark_pinned(rows: &mut [Row], pins: &[crate::patch::redirect::upstream::HostedPin]) { +/// +/// `gem_fixes`: for the gem patches the run holds a reference of, the fix +/// each belongs to (the uuid of the patch it was built from). The pin of a +/// gem locked as platform builds names one patch for every build, so a +/// platform build's row is in place exactly when its patch is of the +/// pinned patch's fix, and a move to another fix otherwise. The same goes +/// for the row of the fix's source patch: the pin may name the registry of +/// a build's own patch (a gem moved while the source patch was not +/// available), and the source patch of that fix is then no newer patch. +pub fn mark_pinned( + rows: &mut [Row], + pins: &[crate::patch::redirect::upstream::HostedPin], + gem_fixes: &HashMap, +) { let pairs: Vec<(String, String)> = pins .iter() .map(|p| (p.purl.clone(), p.uuid.to_ascii_lowercase())) .collect(); let index = RecordedIndex::new(None, &pairs); + let fix_of = |uuid: &str| gem_fixes.get(uuid).map_or(uuid, String::as_str).to_string(); for row in rows.iter_mut().filter(|r| r.candidate.recorded.is_new()) { let uuids = index.uuids(&row.candidate.purl); let selected = row.candidate.uuid.to_ascii_lowercase(); - if uuids.contains(&selected) { + let same_fix = Ecosystem::from_purl(&row.candidate.purl) == Some(Ecosystem::Gem) + && uuids.iter().any(|pin| fix_of(pin) == fix_of(&selected)); + if uuids.contains(&selected) || same_fix { row.candidate.recorded = Recorded::Same; } else if let Some(old) = uuids.first() { row.candidate.recorded = Recorded::Superseded { @@ -613,6 +652,106 @@ mod tests { assert_eq!(all.selected["pkg:npm/a@1"].uuid, "p"); } + /// Each platform gem of a fix has a patch of its own, and a hosted or + /// vendored project records one uuid for the gem. Only the fix a patch + /// belongs to says whether a build's row is in place: a run that + /// settles the builds of a gem classifies the row by what was settled, + /// and every other row, like every row of a run that settles nothing, + /// by its own purl. A row is never called in place only because some + /// other build of the gem has a patch recorded. + #[test] + fn a_platform_gems_row_is_classified_by_its_fix_or_by_its_own_purl() { + let ruby = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let darwin = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + let stored = manifest(&[(ruby, "source")]); + let recorded = RecordedIndex::new(Some(&stored), &[]); + let offers = offers_from_results( + &[ + offer(ruby, "source", "2026-01-01T00:00:00Z", &["high"]), + offer(darwin, "darwin", "2026-01-02T00:00:00Z", &["high"]), + ], + false, + ); + let class_of = |rows: &[Row], purl: &str| { + let row = rows.iter().find(|row| row.candidate.purl == purl); + row.expect("row").candidate.recorded.clone() + }; + let moved = Recorded::Superseded { + old_uuid: "source".to_string(), + }; + // Nothing settled for the row: compared with the gem's one record. + for settled in [None, Some(HashMap::new())] { + let rows = classify_with(&offers, &recorded, settled.as_ref(), ""); + assert_eq!(class_of(&rows, ruby), Recorded::Same); + assert_eq!(class_of(&rows, darwin), moved); + } + // Settled: what was decided for the build. + let settled = HashMap::from([(darwin.to_string(), Recorded::Same)]); + let rows = classify_with(&offers, &recorded, Some(&settled), ""); + assert_eq!(class_of(&rows, darwin), Recorded::Same); + } + + /// A pin found by the second discovery pass names one patch for every + /// build of a gem: a platform build's row is in place when its patch is + /// of the pinned patch's fix, and a move to another fix otherwise. + #[test] + fn a_discovered_gem_pin_marks_a_build_by_its_fix() { + let darwin = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + let offers = offers_from_results( + &[offer( + darwin, + "darwin-of-a", + "2026-01-02T00:00:00Z", + &["high"], + )], + true, + ); + let pin = |uuid: &str| HostedPin { + purl: "pkg:gem/nokogiri@1.18.10".into(), + uuid: uuid.into(), + files: vec!["Gemfile.lock".into()], + }; + let fixes = HashMap::from([("darwin-of-a".to_string(), "source-a".to_string())]); + let marked = |pinned: &str, fixes: &HashMap| { + let mut rows = classify(&offers, &RecordedIndex::default(), ""); + mark_pinned(&mut rows, &[pin(pinned)], fixes); + rows[0].candidate.recorded.clone() + }; + // Pinned to the source patch of the build's own fix: in place. + assert_eq!(marked("source-a", &fixes), Recorded::Same); + // Pinned to the build's own patch (a build's registry): in place. + assert_eq!(marked("darwin-of-a", &fixes), Recorded::Same); + // Pinned to another fix: a move, named as one. + assert_eq!( + marked("source-b", &fixes), + Recorded::Superseded { + old_uuid: "source-b".to_string() + } + ); + // The lock names a build's own registry (the source patch was not + // available when the gem was moved): the fix's source patch, which + // only lends its registry, is no newer patch for the project. + let source_row = offers_from_results( + &[offer( + "pkg:gem/nokogiri@1.18.10?platform=ruby", + "source-a", + "2026-01-01T00:00:00Z", + &["high"], + )], + true, + ); + let mut rows = classify(&source_row, &RecordedIndex::default(), ""); + mark_pinned(&mut rows, &[pin("darwin-of-a")], &fixes); + assert_eq!(rows[0].candidate.recorded, Recorded::Same); + // The fix is not known: never called in place on a guess. + assert_eq!( + marked("source-a", &HashMap::new()), + Recorded::Superseded { + old_uuid: "source-a".to_string() + } + ); + } + #[test] fn composer_version_spellings_upgrade_without_spending_the_new_patch_budget() { let stored = manifest(&[("pkg:composer/psr/log@3.0.2.0", "old")]); @@ -680,6 +819,7 @@ mod tests { )]), selected: BTreeMap::from([(purl.to_string(), selected.clone())]), withheld: BTreeSet::new(), + refused: BTreeSet::new(), }; let recorded = manifest(&[(purl, "old")]); let index = RecordedIndex::new(Some(&recorded), &[]); @@ -765,6 +905,7 @@ mod tests { uuid: "aaaaaaaa-1111-4111-8111-00000000000a".into(), files: vec!["package-lock.json".into()], }], + &HashMap::new(), ); assert_eq!(rows[0].candidate.recorded, Recorded::Same); assert_eq!(rows[1].candidate.recorded, Recorded::None); @@ -790,6 +931,7 @@ mod tests { uuid: "AAAAAAAA-2222-4222-8222-00000000000A".into(), files: vec!["package-lock.json".into()], }], + &HashMap::new(), ); assert_eq!( rows[0].candidate.recorded, diff --git a/crates/socket-patch-core/src/utils/purl.rs b/crates/socket-patch-core/src/utils/purl.rs index 777020de0..29841e0ed 100644 --- a/crates/socket-patch-core/src/utils/purl.rs +++ b/crates/socket-patch-core/src/utils/purl.rs @@ -118,6 +118,16 @@ pub fn purl_qualifier<'a>(purl: &'a str, key: &str) -> Option<&'a str> { }) } +/// The platform of the platform gem a purl's `platform` qualifier names: +/// `Some("arm64-darwin")` for `pkg:gem/nokogiri@1.18.10?platform=arm64-darwin`, +/// `None` for the ruby-platform gem (`?platform=ruby`, an empty value, or +/// no qualifier). The one reading of "is this a platform gem's purl"; it +/// does not check the purl's type. +pub fn gem_platform_qualifier(purl: &str) -> Option<&str> { + purl_qualifier(purl, "platform") + .filter(|platform| !platform.is_empty() && !platform.eq_ignore_ascii_case("ruby")) +} + /// The display spelling of a purl's release: `?qualifiers` and `#subpath` /// stripped, then percent-decoded per component ([`normalize_purl`]). /// diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 0151109a7..6e0617ad8 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -59,16 +59,24 @@ //! (`nokogiri (1.18.10-x86_64-linux-gnu)`, `nokogiri (1.18.10-arm64-darwin)`) //! and usually no plain `nokogiri (1.18.10)`. Such a gem cannot be vendored //! as its ruby-platform tree (the extensions would never be built), so it is -//! vendored as the patch service's PREBUILDS — the patched platform gems — -//! one unpacked tree per locked platform, each with the stub gemspec the -//! service serves for it (verified against real bundler 4.0.15): +//! vendored as the PATCHED PLATFORM GEMS: one unpacked tree per locked +//! platform, each with the stub gemspec the service serves for it (verified +//! against real bundler 4.0.15). +//! +//! Each platform gem of a fix has a patch of its own +//! (`pkg:gem/@?platform=`), built from the patch +//! of the ruby gem, the fix's SOURCE patch. The gem is vendored through +//! that source patch: its uuid names the vendored dir, which therefore +//! stays where it is when the lock gains or loses a platform, and the +//! patch of each locked platform ([`GemBuildPatch`]) supplies that +//! platform's tree, its own `tarball` and `gem-stub-gemspec`. //! //! ```text -//! .socket/vendor/gem//-//… # the unpacked prebuild -//! .socket/vendor/gem//-//.gemspec +//! .socket/vendor/gem//-//… # the unpacked patched platform gem +//! .socket/vendor/gem//-//.gemspec //! //! PATH -//! remote: .socket/vendor/gem//- +//! remote: .socket/vendor/gem//- //! specs: //! (-) # every platform block, verbatim //! () @@ -88,18 +96,23 @@ //! `.gitignore` (`!*`) and `.gitattributes` every backend that commits //! binaries writes: they re-include the trees and keep a project filter //! (a Git LFS rule, EOL conversion) off their bytes. A `.gitignore` a -//! prebuild ships inside its own tree would override that, so it is +//! platform gem ships inside its own tree would override that, so it is //! emptied in the copy. A tree git would still not commit in full is //! refused: wired without its binary, the gem would install everywhere //! and fail to load; -//! * every locked platform needs a prebuild. While the service lists none -//! for one of them the gem is left as it is and reported as a skip -//! ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]): a prebuild is listed -//! only once built, so the next run may find it. A plain -//! ` ()` entry beside the platform ones (the ruby platform, -//! which no prebuilt tree serves) is refused with nothing written, and so -//! is a lock written by a bundler older than the layout was run against -//! (`PLATFORM_LAYOUT_MIN_BUNDLER`). +//! * every locked platform needs a patch of the same fix: one built from +//! the source patch the gem is vendored through. While one of them has +//! none (not published yet, withdrawn, or of another fix) the gem is left +//! as it is and reported as a skip +//! ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]): the next run may find +//! it. A plain ` ()` entry beside the platform ones (the +//! ruby platform, whose extensions bundler would never build) is refused +//! with nothing written, and so is a lock written by a bundler older than +//! the layout was run against (`PLATFORM_LAYOUT_MIN_BUNDLER`); +//! * the ledger entry records, per platform, the patch its tree was built +//! from, the sha512 of the platform `.gem` and of the stub gemspec, and +//! that patch's record ([`super::state::GemBuildEntry`]): each tree is +//! verified against its own patch. use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -114,7 +127,7 @@ use crate::patch::path_safety::is_safe_single_segment; use crate::patch::redirect::gem_line_tail_blocks_edit; use crate::utils::fs::{atomic_write_bytes_preserving_mode, read_regular_to_string}; use crate::utils::line_endings::{self, to_lf, LineEndings}; -use crate::utils::purl::{build_gem_purl, parse_gem_purl, purl_qualifier}; +use crate::utils::purl::{build_gem_purl, parse_gem_purl}; use super::common::{ already_patched_result, cleanup_failed_stage, copy_matches_after_hashes, done, failed_result, @@ -126,12 +139,13 @@ use super::registry_fetch::{extract_gem_data, extract_on_blocking_pool}; use super::revert::{self, KeepPolicy}; use super::service_fetch::{ claim_prestaged, downloaded_warning, fetch_served_artifacts, fetch_verified_archive, - fetch_verified_platform_secondary, fetch_verified_secondary, SecondaryArtifactResult, - ServedArtifacts, ServicePolicy, + fetch_verified_secondary, SecondaryArtifactResult, ServedArtifacts, ServiceArtifact, + ServicePolicy, }; use super::source::PackageSource; use super::state::{ - write_marker_or_warn, VendorArtifact, VendorEntry, VendorMarker, WiringAction, WiringRecord, + write_marker_or_warn, GemBuildEntry, VendorArtifact, VendorEntry, VendorMarker, WiringAction, + WiringRecord, }; use super::{RevertOpts, RevertOutcome, VendorOutcome, VendorServiceConfig, VendorWarning}; use crate::formats::gem::{ @@ -210,11 +224,34 @@ struct GemPrelude { copy_ok: bool, /// The platforms the lock pins the gem for, in lock order, when it /// locks it as precompiled platform gems (see the module docs): the - /// copy is then one prebuild tree per platform. Empty for the plain - /// `name (version)` entry, vendored as the gem's own tree. + /// copy is then one patched platform gem's tree per platform. Empty + /// for the plain `name (version)` entry, vendored as the gem's own + /// tree. platforms: Vec, + /// The in-sync copy was judged by what the ledger records for it, not + /// by the patches at hand: no patch of this fix is at hand for some + /// locked platform, and the committed trees still match what they + /// were vendored from ([`BUILDS_KEPT`]). + builds_kept: bool, +} + +/// The patch of one platform gem of a gem the lock pins as platform gems: +/// what [`vendor_gem_builds`] builds that platform's tree from (module +/// docs). `record` is that patch's own record, the patch of +/// `pkg:gem/@?platform=`. +#[derive(Debug, Clone, Copy)] +pub struct GemBuildPatch<'a> { + /// `Gem::Platform#to_s` as `Gemfile.lock` spells it. + pub platform: &'a str, + pub record: &'a PatchRecord, } +/// Advisory of a re-run over a gem vendored as platform gems that finds no +/// patch of the fix for one of the locked platforms any more (or not yet, +/// for a copy an earlier development build vendored): the committed copy +/// still matches what the ledger records for it and stays in force. +pub const BUILDS_KEPT: &str = "vendor_gem_builds_kept"; + /// What `Gemfile.lock` resolves `name`@`version` to, read from every source /// section (`GEM`, `PATH`, `GIT`, `PLUGIN SOURCE`; a lock already vendored /// holds the entries in our `PATH` section): the plain `name (version)` @@ -444,6 +481,7 @@ async fn gem_prelude( installed_path: &Path, project_root: &Path, record: &PatchRecord, + builds: &[GemBuildPatch<'_>], ) -> Result { // ── coordinates ────────────────────────────────────────────────────── let Some((name, version)) = parse_gem_purl(purl) else { @@ -501,8 +539,9 @@ async fn gem_prelude( // key). RubyGems' default portable platform is `ruby`; a bare purl // (no qualifier) is likewise the portable build. A *native* platform // value (`x86_64-linux`, `arm64-darwin`, `java`, `x64-mingw32`, …) - // names a patch of one platform's build and is refused: a patch's - // prebuilds belong to its `ruby` record. + // names the patch of one platform gem and is refused on its own: + // the platform gems of a gem are vendored together, through the + // patch of the ruby gem they were built from ([`GemBuildPatch`]). // 2. The resolved install dir's own name. A locally-installed native // variant is `--` even when the manifest // purl looked portable (the crawler strips the suffix to the base @@ -515,12 +554,16 @@ async fn gem_prelude( // Gating on the platform (not only the staging dir name) lets // `?platform=ruby` and bare purls vendor whatever the staging dir is // called, while still refusing true native builds by either signal. - if let Some(platform) = purl_qualifier(purl, "platform") { - if !platform.is_empty() && !platform.eq_ignore_ascii_case("ruby") { + // The patch of a platform gem is vendored as part of its fix (`builds`: + // the platform patches of a gem the lock pins as platform gems, which + // one of them leads where the ruby gem's patch is not available), and + // never by itself. + if let Some(platform) = crate::utils::purl::gem_platform_qualifier(purl) { + if builds.is_empty() { return Err(refused( "platform_gem_unsupported", format!( - "`{name}@{version}` is a platform-specific gem build (`platform={platform}`); precompiled platform gems cannot be vendored portably. {}", + "`{name}@{version}` `platform={platform}` is the patch of one platform gem; the platform gems of a gem are vendored together, through the patch of the ruby gem they were built from, and only for a gem Gemfile.lock pins as platform gems. {}", platform_gem_remedy(name) ), )); @@ -664,6 +707,7 @@ async fn gem_prelude( let lock_wired = lock_text.split('\n').any(|l| l == remote_line) && gemfile_text.contains(©_rel); let mut copy_ok = false; + let mut builds_kept = false; if lock_wired { if lock_checksum_in_sync(&lock_text, name, version, &locked.platforms) { // Probe the copy only once the lock is known to be wired (the @@ -680,15 +724,52 @@ async fn gem_prelude( && stub_gemspec_valid(©_dir, name).await } platforms => { - let inventory = recorded_inventory(project_root, &record.uuid, ©_rel).await; - platform_copy_intact( - ©_dir, - name, - platforms, - &record.files, - inventory.as_ref(), - ) - .await + let recorded = recorded_copy(project_root, &record.uuid, ©_rel).await; + let inventory = recorded + .as_ref() + .and_then(|entry| entry.artifact.file_inventory.as_ref()); + match locked_builds(platforms, builds) { + // A patch for every locked platform is at hand: + // the copy is in sync when it was built from + // exactly those patches. + Some(patches) => { + let same = recorded.as_ref().is_some_and(|entry| { + entry.gem_builds.len() == patches.len() + && patches.iter().all(|patch| { + entry.gem_builds.iter().any(|built| { + built.platform == patch.platform + && built.uuid == patch.record.uuid + }) + }) + }); + let trees: Vec<(&str, &HashMap)> = patches + .iter() + .map(|patch| (patch.platform, &patch.record.files)) + .collect(); + same && platform_copy_intact(©_dir, name, &trees, inventory).await + } + // Not so: the copy is judged by what the ledger + // records for it (the patch each tree was built + // from; the one patch of an earlier development + // build's entry), and stays in force while it + // still matches. Nothing here could rebuild it. + None => { + let trees: Option)>> = + recorded.as_ref().and_then(|entry| { + platforms + .iter() + .map(|platform| recorded_tree(entry, record, platform)) + .collect() + }); + builds_kept = match trees { + Some(trees) => { + platform_copy_intact(©_dir, name, &trees, inventory).await + } + None => false, + }; + builds_kept + } + } } }; } else { @@ -740,9 +821,44 @@ async fn gem_prelude( lock_wired, copy_ok, platforms: locked.platforms, + builds_kept, }) } +/// The patch at hand for each of `platforms` (the lock's, in lock order), +/// or `None` when one of them has none among `builds`. +fn locked_builds<'b>( + platforms: &[String], + builds: &'b [GemBuildPatch<'b>], +) -> Option>> { + platforms + .iter() + .map(|platform| builds.iter().copied().find(|b| b.platform == platform)) + .collect() +} + +/// The platform `platform`'s tree of the copy `entry` records and the +/// patched files it is held to: the files of the patch the ledger says the +/// tree was built from, or, for an entry an earlier development build +/// wrote (it names platforms and no patch of their own), the files of the +/// one patch `record` the whole copy came with. `None` when the entry +/// records no tree for that platform. +fn recorded_tree<'e>( + entry: &'e VendorEntry, + record: &'e PatchRecord, + platform: &'e str, +) -> Option<(&'e str, &'e HashMap)> { + if entry.gem_builds.is_empty() { + return entry + .gem_platforms + .iter() + .any(|p| p == platform) + .then_some((platform, &record.files)); + } + let built = entry.gem_builds.iter().find(|b| b.platform == platform)?; + Some((platform, &built.record.as_ref()?.files)) +} + /// The oldest bundler whose lock is wired to a directory of prebuilt /// platform gems: the oldest one the layout is run against (the gate of the /// real-bundler capstone in the CLI's `e2e_vendor_gem_build` suite, which @@ -831,18 +947,14 @@ async fn stub_gemspec_valid(tree: &Path, name: &str) -> bool { } } -/// The file inventory the vendor ledger records for the copy at -/// `copy_rel` of the patch `uuid`: what vouches for the bytes of its -/// prebuild trees once they are vendored (see [`verify_platform_tree`]). -/// `None` when the ledger has no entry for that copy, records no inventory -/// for it, or cannot be read. +/// The ledger entry of the copy at `copy_rel` of the patch `uuid`: its +/// file inventory is what vouches for the bytes of its platform trees once +/// they are vendored (see [`verify_platform_tree`]), and its +/// [`VendorEntry::gem_builds`] say which patch each tree was built from. +/// `None` when the ledger has no entry for that copy or cannot be read. /// /// [`verify_platform_tree`]: super::verify::verify_platform_tree -async fn recorded_inventory( - project_root: &Path, - uuid: &str, - copy_rel: &str, -) -> Option> { +async fn recorded_copy(project_root: &Path, uuid: &str, copy_rel: &str) -> Option { let state = super::state::load_state_shared(project_root).await.ok()?; state .entries @@ -850,11 +962,12 @@ async fn recorded_inventory( .find(|e| { e.ecosystem == "gem" && e.uuid == uuid && e.artifact.path.replace('\\', "/") == copy_rel }) - .and_then(|e| e.artifact.file_inventory.clone()) + .cloned() } /// The in-sync test of a copy vendored as platform gems: the tree of every -/// locked platform is there, passes +/// locked platform (`trees`: the platform and the patched files of the +/// patch its tree is of) is there, passes /// [`super::verify::verify_platform_tree`] (every file of it is the one /// the ledger's `inventory` of the copy records; without an inventory it /// must hold a patched file) and has a valid stub gemspec. With an @@ -864,11 +977,10 @@ async fn recorded_inventory( async fn platform_copy_intact( copy_dir: &Path, name: &str, - platforms: &[String], - files: &HashMap, + trees: &[(&str, &HashMap)], inventory: Option<&std::collections::BTreeMap>, ) -> bool { - for platform in platforms { + for (platform, files) in trees { let tree = copy_dir.join(platform); let voucher = super::verify::TreeVoucher::Ledger(inventory); if super::verify::verify_platform_tree(&tree, files, voucher) @@ -977,16 +1089,16 @@ fn gem_edits( /// ([`gem_prelude`], [`gem_edits`]) and not answered by the in-sync hot /// path. The vendor loop's download plan consults this; the `.gem`'s /// `gem-stub-gemspec` secondary rides the same planned download. `None` -/// for a gem the lock pins as platform gems: it is vendored from the -/// prebuilds the service's package reference lists -/// ([`stage_platform_prebuilds`]), and the ruby gem is never downloaded. +/// for a gem the lock pins as platform gems: each platform's tree comes +/// from that platform's own patch ([`stage_platform_builds`]), and the +/// ruby gem of the patch it is vendored through is never downloaded. pub(crate) async fn service_preflight( purl: &str, installed_path: &Path, project_root: &Path, record: &PatchRecord, ) -> Option { - let prelude = gem_prelude(purl, installed_path, project_root, record) + let prelude = gem_prelude(purl, installed_path, project_root, record, &[]) .await .ok()?; let asks = match prelude.lock_wired { @@ -1014,6 +1126,41 @@ pub async fn vendor_gem<'a>( installed_dir: impl Into>, project_root: &Path, record: &PatchRecord, + sources: &PatchSources<'_>, + vendored_at: &str, + dry_run: bool, + force: bool, + service: Option<&VendorServiceConfig>, +) -> VendorOutcome { + vendor_gem_builds( + purl, + installed_dir, + project_root, + record, + &[], + sources, + vendored_at, + dry_run, + force, + service, + ) + .await +} + +/// [`vendor_gem`] with the patches of the gem's platform gems (`builds`): +/// for a gem the lock pins as precompiled platform gems, `record` is the +/// patch of its ruby gem (the fix's source patch, whose uuid names the +/// vendored dir) and each locked platform's tree is built from that +/// platform's own patch in `builds` (module docs). A patch of a platform +/// the lock does not name is not used. For a gem the lock pins as its +/// ruby-platform gem alone, `builds` plays no part. +#[allow(clippy::too_many_arguments)] +pub async fn vendor_gem_builds<'a>( + purl: &str, + installed_dir: impl Into>, + project_root: &Path, + record: &PatchRecord, + builds: &[GemBuildPatch<'_>], _sources: &PatchSources<'_>, vendored_at: &str, dry_run: bool, @@ -1021,7 +1168,8 @@ pub async fn vendor_gem<'a>( service: Option<&VendorServiceConfig>, ) -> VendorOutcome { let installed_dir = installed_dir.into(); - let prelude = match gem_prelude(purl, installed_dir.path(), project_root, record).await { + let prelude = match gem_prelude(purl, installed_dir.path(), project_root, record, builds).await + { Ok(prelude) => prelude, Err(outcome) => return outcome, }; @@ -1039,6 +1187,7 @@ pub async fn vendor_gem<'a>( lock_wired, copy_ok, platforms, + builds_kept, } = &prelude; let (name, version) = (name.as_str(), version.as_str()); let (copy_rel, uuid_dir, copy_dir) = @@ -1068,6 +1217,23 @@ pub async fn vendor_gem<'a>( )); } } + if *builds_kept { + let missing: Vec = platforms + .iter() + .filter(|platform| !builds.iter().any(|b| b.platform == *platform)) + .map(|platform| format!("`{platform}`")) + .collect(); + warnings.push(VendorWarning::new( + BUILDS_KEPT, + format!( + "{name}@{version} stays vendored as it is at {copy_rel}: no patch of \ + this fix is available for {} now, and the committed platform gems \ + still match what they were vendored from. A later run brings the copy \ + up to date once every locked platform has a patch", + missing.join(", ") + ), + )); + } return done( already_patched_result(purl, copy_dir, &record.files), None, @@ -1088,12 +1254,13 @@ pub async fn vendor_gem<'a>( return refusal; } let mut warnings: Vec = Vec::new(); - let result = match materialise_patched_copy( + let (result, built) = match materialise_patched_copy( purl, copy_dir, uuid_dir, name, platforms, + builds, record, false, // live-wired: never unwind the uuid dir on failure service, @@ -1101,7 +1268,7 @@ pub async fn vendor_gem<'a>( ) .await { - Ok(result) => result, + Ok(materialised) => materialised, Err(outcome) => return rebuild_needs_every_prebuild(*outcome), }; if !result.success { @@ -1125,7 +1292,7 @@ pub async fn vendor_gem<'a>( build_gem_purl(name, version), record, copy_rel.to_string(), - platforms, + built, file_inventory, Vec::new(), ); @@ -1145,7 +1312,7 @@ pub async fn vendor_gem<'a>( } let previewed = match platforms.as_slice() { [] => super::service_fetch::preview_service(service, record, extract_gem_data).await, - platforms => preview_platform_prebuilds(service, record, name, platforms).await, + platforms => preview_platform_builds(service, record, name, platforms, builds).await, }; if let Err(outcome) = previewed { return match lock_wired { @@ -1174,12 +1341,13 @@ pub async fn vendor_gem<'a>( if let Some(refusal) = service_offline_conflict(service) { return refusal; } - let mut result = match materialise_patched_copy( + let (mut result, built) = match materialise_patched_copy( purl, copy_dir, uuid_dir, name, platforms, + builds, record, true, // fresh vendor: nothing pre-existing worth keeping service, @@ -1187,7 +1355,7 @@ pub async fn vendor_gem<'a>( ) .await { - Ok(result) => result, + Ok(materialised) => materialised, Err(outcome) => return *outcome, }; if !result.success { @@ -1366,7 +1534,7 @@ pub async fn vendor_gem<'a>( base_purl, record, copy_rel.to_string(), - platforms, + built, file_inventory, wiring, ); @@ -1393,18 +1561,19 @@ fn rebuild_needs_every_prebuild(outcome: VendorOutcome) -> VendorOutcome { /// The ledger entry for a vendored gem copy: `wiring` is the Gemfile + lock /// records on a full vendor, empty on an artifact-only rebuild (see the hot -/// path). `platforms` are the platform trees of a copy vendored as platform -/// gems (empty for the gem's own tree). +/// path). `builds` are the platform trees of a copy vendored as platform +/// gems, each with the patch it was built from (empty for the gem's own +/// tree). fn gem_entry( base_purl: String, record: &PatchRecord, copy_rel: String, - platforms: &[String], + builds: Vec, file_inventory: Option>, wiring: Vec, ) -> VendorEntry { VendorEntry { - gem_platforms: platforms.to_vec(), + gem_builds: builds, ..VendorEntry::new( "gem".to_string(), base_purl, @@ -1576,38 +1745,35 @@ fn refuse_unusable_stub( Ok(()) } -/// The patched platform gem the patch service built for one platform of a -/// gem (a "prebuild": a drop-in for the upstream platform gem, with the -/// patch's files replaced and the extension rebuilt), and the stub gemspec -/// it serves for it — the per-platform twins of the `tarball` and -/// [`GEM_STUB_ARTIFACT_KIND`] artifacts. Each names its platform, and a -/// platform with no prebuild built has neither. -pub(crate) const GEM_PLATFORM_ARTIFACT_KIND: &str = "gem-platform"; -pub(crate) const GEM_PLATFORM_STUB_ARTIFACT_KIND: &str = "gem-platform-stub-gemspec"; - -/// How many platforms' prebuilds (a platform gem and its stub gemspec +/// How many platforms' gems (a patched platform gem and its stub gemspec /// each) are downloaded at once. const PREBUILD_DOWNLOADS_AT_ONCE: usize = 4; -/// Download and verify the prebuild of each of `platforms` and its stub +/// Download and verify the patched gem of each of `platforms` and its stub /// gemspec, and unpack them into `stage`: `//` holds the -/// platform gem's files and `.gemspec` (see the module docs). +/// platform gem's files and `.gemspec` (see the module docs). Each +/// platform's gem is the `tarball` of that platform's own patch (`builds`), +/// and its stub that patch's [`GEM_STUB_ARTIFACT_KIND`]; `record` is the +/// fix's source patch, which every one of them must have been built from. +/// The ruby gem of the source patch is never downloaded (bundler would +/// have to build its extensions). /// -/// Which prebuilds exist is read off the service's package reference -/// alone; the ruby gem that reference also names is never downloaded -/// (bundler would have to build its extensions). While the service lists -/// no prebuild, or no stub, for one of `platforms`, nothing is downloaded -/// and the gem is skipped ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]). A -/// later failure leaves a partial `stage` for the caller to remove. -/// Returns the run's advisories: the download, and the ignore files that -/// were emptied. -async fn stage_platform_prebuilds( +/// Whether every locked platform can be vendored is settled first, from +/// the package references alone: while one of `platforms` has no patch in +/// `builds`, or its patch is not served yet, was built from another patch +/// than `record`, or serves no stub, nothing is downloaded and the gem is +/// skipped ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]). A later failure +/// leaves a partial `stage` for the caller to remove. Returns the run's +/// advisories (the download, and the ignore files that were emptied) and +/// what the ledger records of each tree. +async fn stage_platform_builds( cfg: &VendorServiceConfig, record: &PatchRecord, name: &str, platforms: &[String], + builds: &[GemBuildPatch<'_>], stage: &Path, -) -> Result, Box> { +) -> Result<(Vec, Vec), Box> { use futures_util::StreamExt as _; let policy = ServicePolicy::Refused; // SECURITY: a platform names a directory under the stage, and the @@ -1618,82 +1784,153 @@ async fn stage_platform_prebuilds( format!("unsafe gem platform `{platform}` for `{name}`"), )); } - let listed = fetch_served_artifacts(cfg, &record.uuid).await; - let served = policy.settle(listed, "platform gem", &format!("platform gems for {name}"))?; - - let missing: Vec<&str> = platforms - .iter() - .map(String::as_str) - .filter(|platform| { - served - .platform(GEM_PLATFORM_ARTIFACT_KIND, platform) - .is_none() - || served - .platform(GEM_PLATFORM_STUB_ARTIFACT_KIND, platform) - .is_none() - }) - .collect(); - if !missing.is_empty() { - let quoted = |platforms: &[&str]| { - platforms - .iter() - .map(|platform| format!("`{platform}`")) - .collect::>() - .join(", ") + let quoted = |platforms: &[&str]| { + platforms + .iter() + .map(|platform| format!("`{platform}`")) + .collect::>() + .join(", ") + }; + // Not a failure: a platform's patch is published once it is built, so + // this is as likely "not yet" as "never", and nothing was touched. + let pending = |missing: Vec<(&str, String)>, ready: &[&str]| { + let have = match ready { + [] => "no locked platform has one".to_string(), + [one] => format!("`{one}` has one"), + ready => format!("{} have one", quoted(ready)), }; - let built: Vec<&str> = platforms + let why: Vec = missing .iter() - .map(String::as_str) - .filter(|platform| !missing.contains(platform)) + .map(|(platform, why)| format!("`{platform}`: {why}")) .collect(); - let built = match built.as_slice() { - [] => "it has none of the locked platforms".to_string(), - built => format!("it has {}", quoted(built)), - }; - // Not a failure: a prebuild is listed only once it is built, so - // this is as likely "not yet" as "never", and nothing was touched. - return Err(Box::new(refused( + Box::new(refused( super::VENDOR_PREBUILT_PLATFORM_PENDING, format!( - "the patch service has no prebuilt platform gem of `{name}` for {} yet \ - ({built}); {GEMFILE_LOCK} locks {name} as precompiled platform gems and bundler \ - never builds a `path:` gem's extensions, so the patch is not vendored until \ - every locked platform has one", - quoted(&missing) + "no patch of this fix is available for every platform gem of `{name}` that \ + {GEMFILE_LOCK} locks ({}; {have}); bundler never builds a `path:` gem's \ + extensions, so the patch is not vendored until every locked platform has a \ + patched gem of the same fix", + why.join("; ") ), - ))); + )) + }; + let Some(patches) = locked_builds(platforms, builds) else { + let missing: Vec<(&str, String)> = platforms + .iter() + .filter(|platform| !builds.iter().any(|b| b.platform == *platform)) + .map(|platform| (platform.as_str(), "no patch on offer".to_string())) + .collect(); + let ready: Vec<&str> = platforms + .iter() + .map(String::as_str) + .filter(|platform| builds.iter().any(|b| b.platform == *platform)) + .collect(); + return Err(pending(missing, &ready)); + }; + + // What the service says of each platform's patch, before any download: + // asked together, a few at a time, and read in lock order. + let references: Vec> = futures_util::stream::iter(&patches) + .map(|patch| fetch_served_artifacts(cfg, &patch.record.uuid)) + .buffered(PREBUILD_DOWNLOADS_AT_ONCE) + .collect() + .await; + // The fix the trees must all be of. The gem is vendored through the + // patch of the ruby gem, which every platform's patch names as the one + // it was built from; where that patch is not available, through the + // patch of one locked platform, and the fix is what that one names. + let led_by = patches + .iter() + .position(|patch| patch.record.uuid == record.uuid); + // A lead whose own reference is not ready (its gem is still being + // built, say) is that platform's problem alone: the fix is then what + // the first ready platform names, and each platform is judged by it. + let named = |reference: &ServiceArtifact| match reference { + ServiceArtifact::Ready(served) => served.rebuilt_from_uuid.clone(), + _ => None, + }; + let fix: Option = match led_by { + None => Some(record.uuid.clone()), + Some(lead) => named(&references[lead]).or_else(|| references.iter().find_map(named)), + }; + let mut missing: Vec<(&str, String)> = Vec::new(); + let mut ready: Vec<&str> = Vec::new(); + for (patch, reference) in patches.iter().zip(references) { + let why = match reference { + ServiceArtifact::Ready(served) => match served.rebuilt_from_uuid.as_deref() { + Some(source) if Some(source) == fix.as_deref() => (!served + .has(GEM_STUB_ARTIFACT_KIND)) + .then(|| "its patch serves no stub gemspec".to_string()), + Some(source) => Some(format!( + "its patch {} belongs to another fix (it was built from {source})", + patch.record.uuid + )), + None => Some(format!( + "its patch {} was not built from this fix's patch", + patch.record.uuid + )), + }, + ServiceArtifact::Pending => Some("its patched gem is still being built".to_string()), + ServiceArtifact::Unavailable(reason) => { + Some(format!("its patched gem is not available ({reason})")) + } + failed => { + let subject = format!("platform gem for {name} ({})", patch.platform); + policy.settle(failed, "platform gem", &subject)?; + None + } + }; + match why { + Some(why) => missing.push((patch.platform, why)), + None => ready.push(patch.platform), + } + } + if !missing.is_empty() { + return Err(pending(missing, &ready)); } - // The prebuilds, a few platforms at a time and taken in lock order. - let served = &served; - let mut downloads = std::pin::pin!(futures_util::stream::iter(platforms) - .map(|platform| async move { - let subject = format!("{name} ({platform})"); - let gem = platform_artifact( - cfg, - served, - GEM_PLATFORM_ARTIFACT_KIND, - platform, + // The gems, a few platforms at a time and taken in lock order. + let mut downloads = std::pin::pin!(futures_util::stream::iter(&patches) + .map(|patch| async move { + let subject = format!("{name} ({})", patch.platform); + let fetched = fetch_verified_archive(cfg, &patch.record.uuid).await; + let archive = policy.settle( + fetched, "platform gem", - &subject, - ) - .await?; - let stub = platform_artifact( - cfg, - served, - GEM_PLATFORM_STUB_ARTIFACT_KIND, - platform, - "stub gemspec", - &subject, - ) - .await?; - Ok::<_, Box>((platform, subject, gem, stub)) + &format!("platform gem for {subject}"), + )?; + let stub = match fetch_verified_secondary(cfg, &archive, GEM_STUB_ARTIFACT_KIND).await { + SecondaryArtifactResult::Ready(bytes) => bytes, + SecondaryArtifactResult::Absent => { + return Err(policy.miss(format!( + "the patch service served no stub gemspec for {subject}" + ))) + } + SecondaryArtifactResult::IntegrityMismatch(reason) => { + return Err(policy.hard( + "vendor_prebuilt_integrity_mismatch", + format!( + "prebuilt stub gemspec for {subject} failed integrity verification \ + ({reason}); refusing to vendor tampered bytes" + ), + )) + } + SecondaryArtifactResult::Failed(reason) => { + return Err(policy.miss(format!( + "could not fetch the stub gemspec for {subject} ({reason})" + ))) + } + }; + Ok::<_, Box>((patch, subject, archive, stub)) }) .buffered(PREBUILD_DOWNLOADS_AT_ONCE)); let mut emptied: Vec = Vec::new(); + let mut built: Vec = Vec::with_capacity(patches.len()); + let mut source_url = String::new(); while let Some(downloaded) = downloads.next().await { - let (platform, subject, gem, stub) = downloaded?; + let (patch, subject, archive, stub) = downloaded?; + let platform = patch.platform; refuse_unusable_stub(policy, name, &subject, &String::from_utf8_lossy(&stub))?; let tree = stage.join(platform); @@ -1703,18 +1940,28 @@ async fn stage_platform_prebuilds( format!("cannot create {}: {e}", tree.display()), )); } - if let Err(e) = extract_on_blocking_pool(gem, &tree, extract_gem_data).await { + if source_url.is_empty() { + source_url.clone_from(&archive.source_url); + } + let gemspec_integrity = archive + .secondary + .iter() + .find(|a| a.kind == GEM_STUB_ARTIFACT_KIND) + .map(|a| a.integrity_sri.clone()) + .unwrap_or_default(); + let gem_integrity = archive.integrity_sri.clone(); + if let Err(e) = extract_on_blocking_pool(archive.bytes, &tree, extract_gem_data).await { return Err(policy.hard( "vendor_prebuilt_extract_failed", - format!("cannot extract the prebuilt platform gem for {subject}: {e}"), + format!("cannot extract the patched platform gem for {subject}: {e}"), )); } - match empty_shipped_gitignores(&tree, &record.files).await { + match empty_shipped_gitignores(&tree, &patch.record.files).await { Ok(files) => emptied.extend(files.into_iter().map(|file| format!("{platform}/{file}"))), Err(e) => { return Err(policy.hard( "vendor_prebuilt_write_failed", - format!("cannot empty a `.gitignore` the prebuilt platform gem for {subject} ships: {e}"), + format!("cannot empty a `.gitignore` the patched platform gem for {subject} ships: {e}"), )); } } @@ -1724,46 +1971,45 @@ async fn stage_platform_prebuilds( format!("cannot write the stub gemspec for {subject} into the vendored dir: {e}"), )); } - // `gem` passed the service's digest for this platform above - // (`platform_artifact`), which is what vouches for a tree that - // ships none of the patched files: only one it does ship can - // contradict the patch. + // The gem passed the service's digest for this platform's patch + // above (`fetch_verified_archive`), which is what vouches for a + // tree that ships none of the patched files: only one it does ship + // can contradict the patch. let verified = super::verify::TreeVoucher::VerifiedDownload; - if super::verify::verify_platform_tree(&tree, &record.files, verified) + if super::verify::verify_platform_tree(&tree, &patch.record.files, verified) .await .is_err() { return Err(policy.miss(format!( - "prebuilt platform gem for {subject} does not carry the patch (a patched \ - file it ships is not the patched one)" + "patched platform gem for {subject} does not carry its patch (a patched file \ + it ships is not the patched one)" ))); } + built.push(GemBuildEntry { + platform: platform.to_string(), + uuid: patch.record.uuid.clone(), + gem_integrity, + gemspec_integrity, + record: Some(patch.record.clone()), + }); } - let source_url = platforms - .first() - .and_then(|platform| served.platform(GEM_PLATFORM_ARTIFACT_KIND, platform)) - .map(|artifact| artifact.url.as_str()) - .unwrap_or_default(); let mut warnings = vec![downloaded_warning( - format_args!( - "{name} as prebuilt platform gems ({})", - platforms.join(", ") - ), - source_url, + format_args!("{name} as patched platform gems ({})", platforms.join(", ")), + &source_url, )]; if !emptied.is_empty() { warnings.push(VendorWarning::new( GITIGNORE_NEUTRALIZED, format!( - "{name}: the prebuilt platform gems ship their own `.gitignore` ({}), whose \ + "{name}: the patched platform gems ship their own `.gitignore` ({}), whose \ rules would keep git from committing files of the vendored trees; emptied in \ the vendored copy (commit it)", super::npm_dir::summarize_rules(&emptied) ), )); } - Ok(warnings) + Ok((warnings, built)) } /// The advisory of [`empty_shipped_gitignores`]: the vendored trees differ @@ -1823,68 +2069,38 @@ async fn empty_shipped_gitignores( Ok(emptied) } -/// One per-platform artifact of `kind` (`what`, for messages about -/// `subject`), downloaded and verified against its served integrity like -/// the ruby gem's stub: a mismatch is never vendored. The check is not -/// optional: an artifact the service states no digest for is not listed -/// at all, and for a prebuild that ships none of the patched files it is -/// the only evidence that the tree is the patched build. -async fn platform_artifact( - cfg: &VendorServiceConfig, - served: &ServedArtifacts, - kind: &str, - platform: &str, - what: &str, - subject: &str, -) -> Result, Box> { - let policy = ServicePolicy::Refused; - match fetch_verified_platform_secondary(cfg, served, kind, platform).await { - SecondaryArtifactResult::Ready(bytes) => Ok(bytes), - SecondaryArtifactResult::Absent => { - Err(policy.miss(format!("the patch service served no {what} for {subject}"))) - } - SecondaryArtifactResult::IntegrityMismatch(reason) => Err(policy.hard( - "vendor_prebuilt_integrity_mismatch", - format!( - "prebuilt {what} for {subject} failed integrity verification ({reason}); \ - refusing to vendor tampered bytes" - ), - )), - SecondaryArtifactResult::Failed(reason) => Err(policy.miss(format!( - "could not fetch the {what} for {subject} ({reason})" - ))), - } -} - /// [`gem_service_copy`] for a gem the lock pins as platform gems: the copy -/// is the verified prebuild of each of `platforms`, staged in full and then -/// swapped into place, so a failure leaves any pre-existing (possibly -/// live-wired) copy untouched and no husk behind. The uuid dir's git -/// metadata is the caller's to write ([`restore_uuid_metadata`]): -/// `copy_dir` may itself sit in a stage (`repair`'s restore). +/// is the verified patched gem of each of `platforms`, each from its own +/// patch in `builds`, staged in full and then swapped into place, so a +/// failure leaves any pre-existing (possibly live-wired) copy untouched +/// and no husk behind. The uuid dir's git metadata is the caller's to +/// write ([`restore_uuid_metadata`]): `copy_dir` may itself sit in a stage +/// (`repair`'s restore). Returns what the ledger records of each tree. #[allow(clippy::too_many_arguments)] pub(super) async fn gem_platform_service_copy( service: Option<&VendorServiceConfig>, record: &PatchRecord, name: &str, platforms: &[String], + builds: &[GemBuildPatch<'_>], copy_dir: &Path, uuid_dir: &Path, unwind_uuid_dir: bool, warnings: &mut Vec, -) -> Result<(), Box> { +) -> Result, Box> { let cfg = service .filter(|cfg| cfg.service_enabled()) .ok_or_else(|| Box::new(super::service_fetch::required()))?; let stage = stage_dir_for(copy_dir); let _ = remove_tree(&stage).await; - let staged = match stage_platform_prebuilds(cfg, record, name, platforms, &stage).await { - Ok(staged) => staged, - Err(outcome) => { - cleanup_failed_stage(&stage, uuid_dir, unwind_uuid_dir).await; - return Err(outcome); - } - }; + let (staged, built) = + match stage_platform_builds(cfg, record, name, platforms, builds, &stage).await { + Ok(staged) => staged, + Err(outcome) => { + cleanup_failed_stage(&stage, uuid_dir, unwind_uuid_dir).await; + return Err(outcome); + } + }; if let Err(e) = swap_stage_into_place(&stage, copy_dir).await { cleanup_failed_stage(&stage, uuid_dir, unwind_uuid_dir).await; return Err(ServicePolicy::Refused.hard( @@ -1893,7 +2109,37 @@ pub(super) async fn gem_platform_service_copy( )); } warnings.extend(staged); - Ok(()) + Ok(built) +} + +/// The patches a copy vendored as platform gems is restored from, as the +/// ledger entry `entry` records them: the patch of each tree, with the +/// record it was vendored with. `Err` says why the copy cannot be restored +/// from the ledger alone: an entry an earlier development build wrote +/// names platforms and no patch of their own. +pub(super) fn recorded_builds(entry: &VendorEntry) -> Result>, String> { + if entry.gem_builds.is_empty() { + return Err( + "this copy was vendored by an earlier build, which recorded no patch for its \ + platform gems; run `socket-patch scan --mode vendored` to vendor it again (or \ + restore the committed directory from version control)" + .to_string(), + ); + } + entry + .gem_builds + .iter() + .map(|built| match &built.record { + Some(record) => Ok(GemBuildPatch { + platform: built.platform.as_str(), + record, + }), + None => Err(format!( + "the ledger holds no patch record for the `{}` platform gem", + built.platform + )), + }) + .collect() } /// `/.gitignore` of a gem vendored as platform gems: re-includes @@ -1956,11 +2202,12 @@ async fn keep_platform_trees_committable( /// A dry run's check of a gem the lock pins as platform gems: the whole /// download, verification and unpacking of [`gem_platform_service_copy`], /// into a scratch directory. -async fn preview_platform_prebuilds( +async fn preview_platform_builds( service: Option<&VendorServiceConfig>, record: &PatchRecord, name: &str, platforms: &[String], + builds: &[GemBuildPatch<'_>], ) -> Result<(), Box> { if let Some(outcome) = service_offline_conflict(service) { return Err(Box::new(outcome)); @@ -1970,15 +2217,17 @@ async fn preview_platform_prebuilds( .ok_or_else(|| Box::new(super::service_fetch::required()))?; let scratch = tempfile::tempdir() .map_err(|e| Box::new(refused("vendor_prebuilt_extract_failed", e.to_string())))?; - stage_platform_prebuilds(cfg, record, name, platforms, scratch.path()) + stage_platform_builds(cfg, record, name, platforms, builds, scratch.path()) .await .map(|_| ()) } /// Acquire a verified service copy without replacing the prior copy on -/// failure: the gem's own tree, or one prebuild tree per platform in -/// `platforms` when the lock pins the gem as platform gems (with the uuid -/// dir's git metadata, see [`restore_uuid_metadata`]). +/// failure: the gem's own tree, or one patched platform gem's tree per +/// platform in `platforms` when the lock pins the gem as platform gems, +/// each from its own patch in `builds` (with the uuid dir's git metadata, +/// see [`restore_uuid_metadata`]). Returns what the ledger records of +/// those trees (none for the gem's own tree). #[allow(clippy::too_many_arguments)] async fn materialise_patched_copy( purl: &str, @@ -1986,11 +2235,13 @@ async fn materialise_patched_copy( uuid_dir: &Path, name: &str, platforms: &[String], + builds: &[GemBuildPatch<'_>], record: &PatchRecord, unwind_uuid_dir: bool, service: Option<&VendorServiceConfig>, warnings: &mut Vec, -) -> Result> { +) -> Result<(ApplyResult, Vec), Box> { + let mut built = Vec::new(); match platforms { [] => { gem_service_copy( @@ -2005,11 +2256,12 @@ async fn materialise_patched_copy( .await? } platforms => { - gem_platform_service_copy( + built = gem_platform_service_copy( service, record, name, platforms, + builds, copy_dir, uuid_dir, unwind_uuid_dir, @@ -2031,7 +2283,7 @@ async fn materialise_patched_copy( } } } - Ok(already_patched_result(purl, copy_dir, &record.files)) + Ok((already_patched_result(purl, copy_dir, &record.files), built)) } /// Revert a gem vendor entry: restore the Gemfile line / delete the managed @@ -11673,17 +11925,21 @@ mod tests { .into_bytes() } - /// What the patch service lists for one platform: its prebuild and - /// the stub gemspec (`None` leaves that artifact out of the answer), - /// and the sha512 it advertises for the prebuild when not its own. + /// The patch of one platform gem as the patch service has it: its + /// patched platform gem and the stub gemspec (`None` leaves that + /// artifact out of the answer), and the sha512 it advertises for + /// the gem when not its own. struct Served { platform: &'static str, gem: Option>, stub: Option>, gem_sha512: Option, + /// The patch this one says it was built from, when not the + /// fix's source patch. + built_from: Option<&'static str>, } - /// `platform`'s prebuild: the patched Ruby file and the platform's + /// `platform`'s patch: the patched Ruby file and the platform's /// own binary, with its stub. fn served(platform: &'static str) -> Served { Served { @@ -11691,78 +11947,120 @@ mod tests { gem: Some(make_gem(&[(RB, RB_PATCHED), (SO, platform.as_bytes())])), stub: Some(stub(platform)), gem_sha512: None, + built_from: None, } } - /// A patch service answering for `uuid` with the patched ruby gem - /// and `prebuilds`, in the shape of the wire contract. + /// The uuid of the patch of the platform gem `platform` that was + /// built from the patch `source`: each platform gem of a fix has a + /// patch of its own. + fn build_uuid(source: &str, platform: &str) -> String { + let tail = match platform { + DARWIN => "da0000000001", + LINUX => "110000000002", + _ => "ee0000000003", + }; + format!("{}{tail}", &source[..24]) + } + + /// A patch service answering for the fix whose source patch is + /// `uuid`: that patch (the patched ruby gem) and the patch of each + /// platform gem in `builds`, each a patch of its own in the shape + /// of the wire contract: a `tarball`, a `gem-stub-gemspec`, and + /// `rebuiltFromUuid`. async fn service( uuid: &str, - prebuilds: &[Served], + builds: &[Served], ) -> (wiremock::MockServer, VendorServiceConfig) { use wiremock::matchers::{method, path}; use wiremock::{Mock, ResponseTemplate}; let server = wiremock::MockServer::start().await; - let base = format!("/patch/gem/nokogiri/1.18.10/tok/{uuid}"); - let mut artifacts = Vec::new(); - let mut serve = |artifact: serde_json::Value, route: String, bytes: Vec| { - artifacts.push(artifact); - Mock::given(method("GET")) - .and(path(route)) - .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) - }; + let mut results = serde_json::Map::new(); let mut mocks = Vec::new(); + let mut serve = |route: &str, bytes: Vec| { + mocks.push( + Mock::given(method("GET")) + .and(path(route.to_string())) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)), + ); + }; + let base = format!("/patch/gem/nokogiri/1.18.10/tok/{uuid}"); let ruby_gem = make_gem(&[(RB, RB_PATCHED), (C, &b"patched C\n"[..])]); let route = format!("{base}/nokogiri-1.18.10.gem"); - mocks.push(serve( + results.insert( + uuid.to_string(), serde_json::json!({ - "kind": "tarball", "url": format!("{}{route}", server.uri()), - "integrity": { "sha512": sri_sha512(&ruby_gem) } + "status": "granted", + "purl": NOKO, + "url": format!("{}{route}", server.uri()), + "rebuiltFromUuid": null, + "artifacts": [{ + "kind": "tarball", "url": format!("{}{route}", server.uri()), + "integrity": { "sha512": sri_sha512(&ruby_gem) } + }] }), - route, - ruby_gem, - )); - for prebuild in prebuilds { - let platform = prebuild.platform; + ); + serve(&route, ruby_gem); + for build in builds { + let platform = build.platform; + let member = build_uuid(uuid, platform); + let base = format!("/patch/gem/nokogiri/1.18.10/tok/{member}"); + let mut artifacts = Vec::new(); let files = [ - ("gem-platform", "gem", &prebuild.gem, &prebuild.gem_sha512), - ( - "gem-platform-stub-gemspec", - "gemspec", - &prebuild.stub, - &None, - ), + ("tarball", "gem", &build.gem, &build.gem_sha512), + ("gem-stub-gemspec", "gemspec", &build.stub, &None), ]; for (kind, ext, bytes, sha512) in files { let Some(bytes) = bytes else { continue }; let route = format!("{base}/nokogiri-1.18.10-{platform}.{ext}"); let sha512 = sha512.clone().unwrap_or_else(|| sri_sha512(bytes)); - mocks.push(serve( - serde_json::json!({ - "kind": kind, "platform": platform, - "url": format!("{}{route}", server.uri()), - "contentType": "application/octet-stream", - "sizeBytes": bytes.len(), - "integrity": { "sha512": sha512 } - }), - route, - bytes.clone(), - )); + artifacts.push(serde_json::json!({ + "kind": kind, + "url": format!("{}{route}", server.uri()), + "contentType": "application/octet-stream", + "sizeBytes": bytes.len(), + "integrity": { "sha512": sha512 } + })); + serve(&route, bytes.clone()); } + let gem_url = format!("{}{base}/nokogiri-1.18.10-{platform}.gem", server.uri()); + results.insert( + member, + serde_json::json!({ + "status": if build.gem.is_some() { "granted" } else { "pending_build" }, + "purl": format!("pkg:gem/nokogiri@1.18.10?platform={platform}"), + "url": build.gem.as_ref().map(|_| gem_url), + "rebuiltFromUuid": build.built_from.unwrap_or(uuid), + "artifacts": artifacts + }), + ); } for mock in mocks { mock.mount(&server).await; } + // One answer per patch asked about: `not_found` for a patch + // the service does not have. Mock::given(method("POST")) .and(path("/v0/orgs/acme/patches/package")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "results": { uuid: { - "status": "granted", - "purl": NOKO, - "url": format!("{}{base}/nokogiri-1.18.10.gem", server.uri()), - "artifacts": artifacts - }} - }))) + .respond_with(move |request: &wiremock::Request| { + let body: serde_json::Value = + serde_json::from_slice(&request.body).unwrap_or_default(); + let asked: serde_json::Map = body["uuids"] + .as_array() + .into_iter() + .flatten() + .filter_map(|uuid| uuid.as_str()) + .map(|uuid| { + let answer = results + .get(uuid) + .cloned() + .unwrap_or_else(|| serde_json::json!({ "status": "not_found" })); + (uuid.to_string(), answer) + }) + .collect(); + ResponseTemplate::new(200) + .set_body_json(serde_json::json!({ "results": asked })) + }) .mount(&server) .await; let cfg = gem_service_cfg(&server.uri(), VendorSource::Service, false); @@ -11774,27 +12072,76 @@ mod tests { root.join(".socket/vendor/.uninstalled") } + /// The records of the patches of the two platform gems the fixture + /// lock names, each built from `record`'s patch and patching the + /// same files of its own gem. + fn build_records(record: &PatchRecord) -> Vec<(&'static str, PatchRecord)> { + [DARWIN, LINUX] + .into_iter() + .map(|platform| { + let build = PatchRecord { + uuid: build_uuid(&record.uuid, platform), + ..record.clone() + }; + (platform, build) + }) + .collect() + } + async fn vendor( root: &Path, installed: &Path, record: &PatchRecord, cfg: &VendorServiceConfig, dry_run: bool, + ) -> VendorOutcome { + let records = build_records(record); + let builds: Vec> = records + .iter() + .map(|(platform, record)| GemBuildPatch { platform, record }) + .collect(); + vendor_with(root, installed, record, &builds, cfg, dry_run).await + } + + /// [`vendor`] with the platform patches at hand named (`builds`). + async fn vendor_with( + root: &Path, + installed: &Path, + record: &PatchRecord, + builds: &[GemBuildPatch<'_>], + cfg: &VendorServiceConfig, + dry_run: bool, + ) -> VendorOutcome { + vendor_as(NOKO, root, installed, record, builds, cfg, dry_run).await + } + + /// [`vendor_with`] through the patch record of `purl`. + async fn vendor_as( + purl: &str, + root: &Path, + installed: &Path, + record: &PatchRecord, + builds: &[GemBuildPatch<'_>], + cfg: &VendorServiceConfig, + dry_run: bool, ) -> VendorOutcome { let blobs = root.join("no-blobs"); let sources = PatchSources::blobs_only(&blobs); - ts::vendor_gem( - NOKO, + let outcome = vendor_gem_builds( + purl, installed, root, record, + builds, &sources, "2026-06-09T00:00:00Z", dry_run, false, Some(cfg), ) - .await + .await; + ts::assert_fresh_vendor_in_use(root, &outcome, dry_run).await; + outcome } async fn text(path: PathBuf) -> String { @@ -11864,8 +12211,19 @@ mod tests { vendored(&rel, bare.as_deref()) ); - // The ledger entry. - assert_eq!(entry.gem_platforms, [DARWIN, LINUX]); + // The ledger entry: per platform, the patch its tree was + // built from, the sha512 of that patch's gem and stub, and + // its record. The entry itself is the fix's source patch. + assert_eq!(entry.gem_tree_platforms(), [DARWIN, LINUX]); + assert_eq!(entry.uuid, UUID); + assert!(entry.gem_platforms.is_empty()); + for built in &entry.gem_builds { + assert_eq!(built.uuid, build_uuid(UUID, &built.platform)); + assert!(built.gem_integrity.starts_with("sha512-"), "{built:?}"); + assert!(built.gemspec_integrity.starts_with("sha512-"), "{built:?}"); + let own = built.record.as_ref().expect("the platform patch's record"); + assert_eq!(own.uuid, built.uuid); + } assert_eq!(entry.artifact.path, rel); let inventory = entry.artifact.file_inventory.as_ref().expect("inventory"); let inventoried: Vec<&str> = inventory.keys().map(String::as_str).collect(); @@ -11919,7 +12277,7 @@ mod tests { assert_eq!(saved, entry); assert!(text(root.join(".socket/vendor/state.json")) .await - .contains("\"gemPlatforms\"")); + .contains("\"gemBuilds\"")); // Verification and discovery: one vendored reference. assert_eq!( @@ -11958,39 +12316,69 @@ mod tests { } } - /// Every locked platform needs a prebuild and its stub. While the - /// service lists none for one of them (it lists a prebuild only once - /// built), a dry run and a wet run both leave the gem alone under - /// the benign pending code: they name the gem and the platforms, - /// ask the service for the package reference and nothing else, and - /// write nothing. + /// Every locked platform needs a patch of the fix, with its gem and + /// its stub. While one of them has none (no patch of it at all, one + /// the service does not serve yet, one with no stub, one built from + /// another fix), a dry run and a wet run both leave the gem alone + /// under the benign pending code: they name the gem and what each + /// platform lacks, ask the service for the package references and + /// nothing else, and write nothing. #[tokio::test] - async fn a_locked_platform_without_a_prebuild_is_a_skip_that_downloads_nothing() { - let no_stub = || Served { - stub: None, - ..served(LINUX) - }; - let cases: [(Vec, Vec<&str>); 3] = [ + async fn a_locked_platform_without_a_patch_is_a_skip_that_downloads_nothing() { + let cases: [(Vec, Vec<&str>); 5] = [ ( Vec::new(), vec![ - "of `nokogiri` for `arm64-darwin`, `x86_64-linux-gnu` yet", - "none of the locked platforms", + "`arm64-darwin`: its patched gem is not available (not_found)", + "`x86_64-linux-gnu`: its patched gem is not available (not_found)", + "no locked platform has one", ], ), ( vec![served(DARWIN)], - vec!["for `x86_64-linux-gnu` yet (it has `arm64-darwin`)"], + vec![ + "(`x86_64-linux-gnu`: its patched gem is not available (not_found); \ + `arm64-darwin` has one)", + ], + ), + ( + vec![ + served(DARWIN), + Served { + stub: None, + ..served(LINUX) + }, + ], + vec!["`x86_64-linux-gnu`: its patch serves no stub gemspec"], + ), + ( + vec![ + served(DARWIN), + Served { + gem: None, + ..served(LINUX) + }, + ], + vec!["`x86_64-linux-gnu`: its patched gem is still being built"], ), ( - vec![served(DARWIN), no_stub()], - vec!["for `x86_64-linux-gnu` yet ("], + vec![ + served(DARWIN), + Served { + built_from: Some(UUID_B), + ..served(LINUX) + }, + ], + vec![ + "`x86_64-linux-gnu`: its patch ", + " belongs to another fix (it was built from b0b0b0b0-0000-4000-8000-000000000002)", + ], ), ]; - for (prebuilds, expected) in cases { + for (builds, expected) in cases { let (_tmp, root, record) = project(&lock(Some(&checksums(&sha('a'), "")))).await; let before = ts::tree_snapshot(&root); - let (server, cfg) = service(UUID, &prebuilds).await; + let (server, cfg) = service(UUID, &builds).await; for dry_run in [true, false] { let asked = ts::request_count(&server).await; let (code, detail) = unwrap_refused( @@ -11999,23 +12387,53 @@ mod tests { assert_eq!(code, "vendor_prebuilt_platform_pending", "{detail}"); assert!(crate::vendor::is_unserved(code)); assert!(crate::vendor::refusals::refusal_is_benign(code)); + assert!( + detail.starts_with( + "no patch of this fix is available for every platform gem of \ + `nokogiri` that Gemfile.lock locks (" + ), + "{detail}" + ); for text in &expected { assert!(detail.contains(text), "{detail}"); } assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); assert_eq!( ts::request_count(&server).await, - asked + 1, - "the package reference is the one request: no gem is downloaded" + asked + 2, + "one package reference per platform's patch: no gem is downloaded" ); } } + + // A platform with no patch among the run's records: the service + // is not even asked. + let (_tmp, root, record) = project(&lock(None)).await; + let before = ts::tree_snapshot(&root); + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let records = build_records(&record); + let darwin = GemBuildPatch { + platform: records[0].0, + record: &records[0].1, + }; + for builds in [&[darwin][..], &[][..]] { + let (code, detail) = unwrap_refused( + vendor_with(&root, ¬_installed(&root), &record, builds, &cfg, false).await, + ); + assert_eq!(code, "vendor_prebuilt_platform_pending", "{detail}"); + assert!( + detail.contains("`x86_64-linux-gnu`: no patch on offer"), + "{detail}" + ); + assert_eq!(ts::tree_snapshot(&root), before); + } + assert_eq!(ts::request_count(&server).await, 0); } - /// A copy the lock is ALREADY wired to cannot wait for a prebuild. - /// When one of its trees is lost and the service does not list that - /// platform, the rebuild is the plain miss, a failure, dry run or - /// not, and what is left of the copy stays as it was. + /// A copy the lock is ALREADY wired to cannot wait for a patch. + /// When one of its trees is lost and the service does not serve the + /// patch of that platform, the rebuild is the plain miss, a failure, + /// dry run or not, and what is left of the copy stays as it was. #[tokio::test] async fn a_wired_copy_that_cannot_be_rebuilt_fails_instead_of_skipping() { let (_tmp, root, record) = project(&lock(None)).await; @@ -12031,7 +12449,10 @@ mod tests { vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, ); assert_eq!(code, "vendor_prebuilt_required", "{detail}"); - assert!(detail.contains("for `x86_64-linux-gnu` yet"), "{detail}"); + assert!( + detail.contains("`x86_64-linux-gnu`: its patched gem is not available"), + "{detail}" + ); assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); } } @@ -12183,7 +12604,7 @@ mod tests { let (result, entry, _) = unwrap_done(vendor(&root, &installed, &record, &cfg, false).await); assert!(result.success, "{:?}", result.error); - assert_eq!(entry.unwrap().gem_platforms, [DARWIN, LINUX]); + assert_eq!(entry.unwrap().gem_tree_platforms(), [DARWIN, LINUX]); let asked: Vec = server .received_requests() .await @@ -12199,8 +12620,17 @@ mod tests { ); assert_eq!( asked.len(), - 5, - "the package reference, then a platform gem and its stub per platform: {asked:?}" + 8, + "per platform: its patch's reference (all asked before any download), then \ + that patch's own fetch (its reference, its gem and its stub): {asked:?}" + ); + assert_eq!( + asked[..2], + [ + "/v0/orgs/acme/patches/package", + "/v0/orgs/acme/patches/package" + ], + "every platform is settled before a gem is downloaded: {asked:?}" ); assert_eq!( tokio::fs::read(root.join(rel(UUID)).join(LINUX).join(RB)) @@ -12238,7 +12668,7 @@ mod tests { let (result, entry, _) = unwrap_done(vendor(&root, &installed, &record, &cfg, false).await); assert!(result.success, "{:?}", result.error); - assert_eq!(entry.unwrap().gem_platforms, [DARWIN, LINUX]); + assert_eq!(entry.unwrap().gem_tree_platforms(), [DARWIN, LINUX]); } /// A prebuild is verified against its served integrity like the ruby @@ -12335,7 +12765,7 @@ mod tests { check_vendored_artifact(&root, &bare, &record).await, ArtifactHealth::Healthy ); - bare.gem_platforms.clear(); + bare.gem_builds.clear(); assert_eq!( check_vendored_artifact(&root, &bare, &record).await, ArtifactHealth::Healthy @@ -12395,7 +12825,7 @@ mod tests { // A platform the ledger names must be a plain directory name. let mut poisoned = entry.clone(); - poisoned.gem_platforms = vec!["../x".to_string()]; + poisoned.gem_builds[0].platform = "../x".to_string(); assert_eq!( check_vendored_artifact(&root, &poisoned, &record).await, ArtifactHealth::Unverifiable { @@ -12548,7 +12978,7 @@ mod tests { "{warnings:?}" ); let rebuilt = rebuilt.expect("a refreshed entry"); - assert_eq!(rebuilt.gem_platforms, [DARWIN, LINUX]); + assert_eq!(rebuilt.gem_tree_platforms(), [DARWIN, LINUX]); assert!(rebuilt.wiring.is_empty(), "the first run's records ride on"); assert_eq!(tokio::fs::read(tree.join(RB)).await.unwrap(), RB_PATCHED); assert_eq!( @@ -12663,7 +13093,7 @@ mod tests { let (_server, cfg) = service(UUID_B, &[served(DARWIN), served(LINUX)]).await; let second = vendor_and_persist(&root, &record_b, &cfg).await; assert_eq!(second.uuid, UUID_B); - assert_eq!(second.gem_platforms, [DARWIN, LINUX]); + assert_eq!(second.gem_tree_platforms(), [DARWIN, LINUX]); assert_eq!( text(root.join(GEMFILE_LOCK)).await, vendored(&rel(UUID_B), Some(&checksums("", ""))) @@ -12882,6 +13312,318 @@ mod tests { assert_eq!(ts::request_count(&server).await, 0); } + /// Without the ruby gem's patch (it is not offered to the run) the + /// gem is vendored all the same, through the patch of one locked + /// platform: that patch names the directory and the ledger entry, + /// every tree is still its own platform's, and all of them must + /// name the same fix. A re-run finds the copy in sync and asks + /// nothing. A platform's patch by itself is never vendored. + #[tokio::test] + async fn a_fix_without_its_source_patch_is_vendored_through_a_platforms_patch() { + const LEAD: &str = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + let (_tmp, root, record) = project(&lock(None)).await; + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let records = build_records(&record); + let builds: Vec> = records + .iter() + .map(|(platform, record)| GemBuildPatch { platform, record }) + .collect(); + let lead = &records[0].1; + assert_eq!(records[0].0, DARWIN); + let installed = not_installed(&root); + + // By itself: refused, with nothing asked. + let (code, _) = + unwrap_refused(vendor_as(LEAD, &root, &installed, lead, &[], &cfg, false).await); + assert_eq!(code, "platform_gem_unsupported"); + assert_eq!(ts::request_count(&server).await, 0); + + let (result, entry, _) = + unwrap_done(vendor_as(LEAD, &root, &installed, lead, &builds, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.expect("a ledger entry"); + assert_eq!(entry.uuid, lead.uuid, "named after the leading patch"); + assert_eq!(entry.artifact.path, rel(&lead.uuid)); + assert_eq!(entry.gem_tree_platforms(), [DARWIN, LINUX]); + let built: Vec<&str> = entry.gem_builds.iter().map(|b| b.uuid.as_str()).collect(); + assert_eq!( + built, + [records[0].1.uuid.as_str(), records[1].1.uuid.as_str()] + ); + assert_eq!( + text(root.join(GEMFILE_LOCK)).await, + vendored(&rel(&lead.uuid), None) + ); + for platform in [DARWIN, LINUX] { + assert_eq!( + tokio::fs::read(root.join(rel(&lead.uuid)).join(platform).join(SO)) + .await + .unwrap(), + platform.as_bytes() + ); + } + + // In sync on the next run: nothing is asked or written. + ts::persist(&root, LEAD, entry).await; + let asked = ts::request_count(&server).await; + let before = ts::tree_snapshot(&root); + let again = vendor_as(LEAD, &root, &installed, lead, &builds, &cfg, false).await; + let (result, _, _) = unwrap_done(again); + assert!(result.success, "{:?}", result.error); + assert_eq!(ts::request_count(&server).await, asked); + assert_eq!(ts::tree_snapshot(&root), before); + } + + /// A leading platform patch whose own gem is still being built is + /// that platform's wait alone: the other platforms, whose patches + /// are ready and of one fix, are not called patches of another fix. + #[tokio::test] + async fn a_leading_platform_patch_that_is_not_ready_is_named_alone() { + const LEAD: &str = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + let (_tmp, root, record) = project(&lock(None)).await; + let pending = Served { + gem: None, + ..served(DARWIN) + }; + let (_server, cfg) = service(UUID, &[pending, served(LINUX)]).await; + let records = build_records(&record); + let builds: Vec> = records + .iter() + .map(|(platform, record)| GemBuildPatch { platform, record }) + .collect(); + let before = ts::tree_snapshot(&root); + let outcome = vendor_as( + LEAD, + &root, + ¬_installed(&root), + &records[0].1, + &builds, + &cfg, + false, + ) + .await; + let (code, detail) = unwrap_refused(outcome); + assert_eq!(code, "vendor_prebuilt_platform_pending", "{detail}"); + assert!( + detail.contains( + "(`arm64-darwin`: its patched gem is still being built; `x86_64-linux-gnu` \ + has one)" + ), + "{detail}" + ); + assert!(!detail.contains("another fix"), "{detail}"); + assert_eq!(ts::tree_snapshot(&root), before); + } + + /// A platform's patch that leads its fix still holds every other + /// platform to that fix: a tree of another fix is never mixed in. + #[tokio::test] + async fn a_leading_platform_patch_refuses_a_tree_of_another_fix() { + const LEAD: &str = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + let (_tmp, root, record) = project(&lock(None)).await; + let other = Served { + built_from: Some(UUID_B), + ..served(LINUX) + }; + let (_server, cfg) = service(UUID, &[served(DARWIN), other]).await; + let records = build_records(&record); + let builds: Vec> = records + .iter() + .map(|(platform, record)| GemBuildPatch { platform, record }) + .collect(); + let before = ts::tree_snapshot(&root); + let outcome = vendor_as( + LEAD, + &root, + ¬_installed(&root), + &records[0].1, + &builds, + &cfg, + false, + ) + .await; + let (code, detail) = unwrap_refused(outcome); + assert_eq!(code, "vendor_prebuilt_platform_pending", "{detail}"); + assert!( + detail.contains(&format!( + "`x86_64-linux-gnu`: its patch {} belongs to another fix (it was built from \ + {UUID_B})", + records[1].1.uuid + )), + "{detail}" + ); + assert_eq!(ts::tree_snapshot(&root), before); + } + + /// The vendored dir is named after the fix's source patch, so it + /// stays where it is when the lock gains a platform: the manifest + /// and the lock's `PATH` section are unchanged, the copy gains that + /// platform's tree from that platform's own patch, and the ledger + /// its record. + #[tokio::test] + async fn a_lock_that_gains_a_platform_keeps_its_vendored_dir() { + let darwin_only = |text: String| { + text.replace( + " nokogiri (1.18.10-x86_64-linux-gnu)\n racc (~> 1.4)\n", + "", + ) + .replace(" arm64-darwin\n x86_64-linux-gnu\n", " arm64-darwin\n") + }; + let (_tmp, root, record) = project(&darwin_only(lock(None))).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + // Both platforms' patches are at hand; the lock names one. + let first = vendor_and_persist(&root, &record, &cfg).await; + assert_eq!(first.gem_tree_platforms(), [DARWIN]); + assert!(!root.join(rel(UUID)).join(LINUX).exists()); + let gemfile = text(root.join(GEMFILE)).await; + assert_eq!( + text(root.join(GEMFILE_LOCK)).await, + darwin_only(vendored(&rel(UUID), None)) + ); + + // The lock gains the linux entry under the vendored section. + tokio::fs::write(root.join(GEMFILE_LOCK), vendored(&rel(UUID), None)) + .await + .unwrap(); + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert!( + warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt"), + "{warnings:?}" + ); + let entry = entry.expect("a refreshed entry"); + assert_eq!(entry.gem_tree_platforms(), [DARWIN, LINUX]); + assert_eq!(entry.artifact.path, rel(UUID), "the same directory"); + assert_eq!( + text(root.join(GEMFILE)).await, + gemfile, + "the same manifest line" + ); + assert_eq!( + text(root.join(GEMFILE_LOCK)).await, + vendored(&rel(UUID), None), + "the lock is not edited again" + ); + assert_eq!( + tokio::fs::read(root.join(rel(UUID)).join(LINUX).join(SO)) + .await + .unwrap(), + LINUX.as_bytes() + ); + } + + /// A project an earlier development build vendored: its ledger + /// entry names the platforms and no patch of their own + /// (`gemPlatforms`), and every tree came with the ruby gem's patch. + /// Reading it does not fail, the copy still verifies against that + /// one patch, and revert restores the project byte for byte. A run + /// that has a patch for every locked platform rebuilds the copy from + /// those patches in the same directory and records them; a run that + /// has none leaves the copy in force and says so, with no request. + #[tokio::test] + async fn a_copy_an_earlier_build_vendored_is_kept_converted_and_reverted() { + let original = lock(Some(&checksums(&sha('a'), &sha('b')))); + let (_tmp, root, record) = project(&original).await; + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let entry = vendor_and_persist(&root, &record, &cfg).await; + + // The entry as the earlier build wrote it. + let mut value = serde_json::to_value(&entry).unwrap(); + let object = value.as_object_mut().unwrap(); + assert!(object.remove("gemBuilds").is_some()); + object.insert( + "gemPlatforms".to_string(), + serde_json::json!([DARWIN, LINUX]), + ); + let legacy: VendorEntry = + serde_json::from_value(value).expect("the earlier shape still reads"); + assert!(legacy.gem_builds.is_empty()); + assert_eq!(legacy.gem_tree_platforms(), [DARWIN, LINUX]); + ts::persist(&root, NOKO, legacy.clone()).await; + assert!(text(root.join(".socket/vendor/state.json")) + .await + .contains("\"gemPlatforms\"")); + assert_eq!( + check_vendored_artifact(&root, &legacy, &record).await, + ArtifactHealth::Healthy + ); + // A restore from the ledger alone has no patch to ask for. + let why = recorded_builds(&legacy).unwrap_err(); + assert!( + why.contains("run `socket-patch scan --mode vendored` to vendor it again"), + "{why}" + ); + + // No platform patch at hand: the copy stays, and the run says so. + let snapshot = ts::tree_snapshot(&root); + let requests = ts::request_count(&server).await; + for dry_run in [true, false] { + let (kept, refreshed, warnings) = unwrap_done( + vendor_with(&root, ¬_installed(&root), &record, &[], &cfg, dry_run).await, + ); + assert!(kept.success, "{:?}", kept.error); + assert!(refreshed.is_none(), "the ledger entry is left as it is"); + let said: Vec<&str> = warnings.iter().map(|w| w.code).collect(); + assert_eq!(said, [BUILDS_KEPT], "{warnings:?}"); + assert!( + warnings[0].detail.contains( + "no patch of this fix is available for `arm64-darwin`, \ + `x86_64-linux-gnu` now" + ), + "{}", + warnings[0].detail + ); + assert_eq!(ts::tree_snapshot(&root), snapshot, "dry_run={dry_run}"); + } + assert_eq!( + ts::request_count(&server).await, + requests, + "nothing is asked" + ); + + // A patch for every locked platform: the copy is rebuilt from + // them where it is, and the ledger gains their records. + let pair = ( + text(root.join(GEMFILE)).await, + text(root.join(GEMFILE_LOCK)).await, + ); + let (result, converted, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert!( + warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt"), + "{warnings:?}" + ); + let converted = converted.expect("a refreshed entry"); + assert_eq!(converted.artifact.path, legacy.artifact.path); + assert_eq!(converted.gem_builds.len(), 2); + assert!(converted.gem_platforms.is_empty()); + assert_eq!( + ( + text(root.join(GEMFILE)).await, + text(root.join(GEMFILE_LOCK)).await + ), + pair, + "the pair edit stands" + ); + ts::persist(&root, NOKO, converted).await; + let saved = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); + assert_eq!(saved.gem_builds.len(), 2); + assert!( + !saved.wiring.is_empty(), + "the first run's wiring records are carried forward" + ); + + // Revert from the earlier entry: both files byte for byte. + ts::persist(&root, NOKO, legacy.clone()).await; + let reverted = revert_gem(&legacy, &root, false).await; + assert!(reverted.success, "{:?}", reverted.error); + assert_eq!(text(root.join(GEMFILE)).await, GEMFILE_NOKO); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, original); + assert!(!root.join(rel(UUID)).exists()); + } + /// The lock edit on its own: the blocks move verbatim and in lock /// order (a direct and a transitive gem), revert splices them back, /// and shapes bundler never writes fail closed. diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs b/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs index 63f011009..b187f3854 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/gem.rs @@ -92,6 +92,26 @@ pub async fn gem_locked_builds_in( } } +/// The builds the Bundler lock bundler loads resolves each gem of `purls` +/// to, in whichever source section +/// ([`resolved_gem_builds`](crate::formats::gem::resolved_gem_builds)): a +/// gem vendored as platform gems still names its platforms here. Element +/// `i` answers `purls[i]`; empty for every gem when bundler loads no lock +/// here, or it cannot be read. +pub async fn gem_resolved_builds_in( + view: &ProjectView<'_>, + purls: &[String], +) -> Vec> { + let text = match bundler_loaded_lock_in(view).await { + Some(lock) => view.read_text(lock).await.ok(), + None => None, + }; + match text { + Some(text) => crate::formats::gem::resolved_gem_builds(&text, purls), + None => vec![Vec::new(); purls.len()], + } +} + /// Why the project's Bundler lock was not inventoried, when it holds gem /// files ([`GEM_FILES`]) but bundler loads no lock socket-patch reads /// ([`bundler_loaded_lock_diagnosed_in`]): an unsupported `BUNDLE_GEMFILE` diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs b/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs index 6104bdc1d..759937ece 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/mod.rs @@ -76,7 +76,7 @@ pub(crate) mod vlt; pub(crate) mod yarn; pub use self::bun::{bun_binary_lock_drives, bun_text_lock_drives}; -pub use self::gem::{gem_locked_builds_in, gem_platform_only_purls_in}; +pub use self::gem::{gem_locked_builds_in, gem_platform_only_purls_in, gem_resolved_builds_in}; pub(crate) use self::npm::{ npm_lock_bundled_nodes, npm_lock_entries, npm_lock_legacy_mirror_nodes, npm_lock_located_nodes, NpmLockEntry, NpmLockNode, NpmLockSection, diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 8d38a2ca4..7608eeb08 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -133,9 +133,10 @@ pub(crate) use npm_common::is_safe_npm_name; pub use pnpm_lock::rush::wiring_files as rush_wiring_files; pub use pypi_requirements::requirements_include_names; pub use state::{ - carry_forward_wiring, file_gitignored, ledger_gitignore_refusal, load_state, lookup_entry, - lookup_entry_kv, purl_keys_cover, save_state, save_state_shared, VendorEntry, VendorState, - LEDGER_GITIGNORED, VENDOR_STATE_REL, + carry_forward_wiring, detached_record_at, file_gitignored, ledger_gitignore_refusal, + load_state, lookup_entry, lookup_entry_kv, lookup_gem_build, purl_keys_cover, save_state, + save_state_shared, vendored_uuid, VendorEntry, VendorState, LEDGER_GITIGNORED, + VENDOR_STATE_REL, }; pub use verify::{ artifact_is_file_shaped, check_vendored_artifact, compute_dir_inventory, @@ -721,10 +722,11 @@ pub const VENDOR_PREBUILT_UNAVAILABLE: &str = "vendor_prebuilt_unavailable"; /// no older vendored patch to keep. pub const VENDOR_PREBUILT_REQUIRED: &str = "vendor_prebuilt_required"; -/// gem: `Gemfile.lock` pins the gem as precompiled platform gems and the -/// patch service lists no prebuilt platform gem for at least one of the -/// locked platforms. The service lists a prebuild only once it is built, so -/// "not built yet" and "never built" look the same from here: the package +/// gem: `Gemfile.lock` pins the gem as precompiled platform gems and at +/// least one of the locked platforms has no usable patch of the fix (each +/// platform gem has a patch of its own). A platform's patch is listed only +/// once it is published and built, so "not built yet" and "never built" +/// look the same from here: the package /// is left as it is and the run does not fail because of it, with or /// without an older vendored patch to keep (see [`VENDOR_PREBUILT_PENDING`] /// for the kept one). A re-run vendors it once every platform has one. diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index 569976af4..bbb7061db 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -249,8 +249,13 @@ pub async fn restore( let (name, _) = parse_gem_purl(&entry.base_purl).ok_or("invalid gem coordinates")?; // A gem vendored as platform gems is restored from the - // prebuild of each platform the ledger names. - let copied = match entry.gem_platforms.as_slice() { + // patch of each platform gem the ledger names. + let platforms: Vec = entry + .gem_tree_platforms() + .into_iter() + .map(str::to_string) + .collect(); + let copied = match platforms.as_slice() { [] => { super::gem::gem_service_copy( Some(service), @@ -264,17 +269,20 @@ pub async fn restore( .await } platforms => { + let builds = super::gem::recorded_builds(entry)?; super::gem::gem_platform_service_copy( Some(service), record, &name, platforms, + &builds, &stage, uuid_dir, true, &mut warnings, ) .await + .map(|_| ()) } }; copied.map_err(|outcome| detail(*outcome))?; @@ -419,7 +427,7 @@ pub async fn restore( // Likewise a gem vendored as platform gems: only the artifact dir was // swapped in from the stage, and without the uuid dir's own metadata a // `*.so` / `*.bundle` rule drops the prebuilt binaries from the commit. - if entry.ecosystem == "gem" && !entry.gem_platforms.is_empty() { + if entry.ecosystem == "gem" && !entry.gem_tree_platforms().is_empty() { if let Some(rel) = super::path::vendor_uuid_dir_rel("gem", &entry.uuid) { super::gem::restore_uuid_metadata(&root.join(rel)) .await diff --git a/crates/socket-patch-core/src/vendor/service_fetch.rs b/crates/socket-patch-core/src/vendor/service_fetch.rs index b3c2e2b66..c4e4ade90 100644 --- a/crates/socket-patch-core/src/vendor/service_fetch.rs +++ b/crates/socket-patch-core/src/vendor/service_fetch.rs @@ -112,19 +112,22 @@ pub(crate) fn downloaded_warning( ) } -/// What the patch service lists for a patch besides its archive, learned +/// What the patch service says of a patch without its archive, learned /// from the package reference alone ([`fetch_served_artifacts`]): still /// unverified, and nothing of the patch is downloaded yet. #[derive(Debug)] -pub(crate) struct ServedArtifacts(pub Vec); +pub(crate) struct ServedArtifacts { + /// The uuid of the patch this one was built from; `None` for a patch + /// that is itself a source. + pub rebuilt_from_uuid: Option, + /// The artifacts the service lists besides the archive. + pub artifacts: Vec, +} impl ServedArtifacts { - /// The served artifact of `kind` for the gem platform `platform`, if - /// the service lists one. - pub(crate) fn platform(&self, kind: &str, platform: &str) -> Option<&SecondaryArtifact> { - self.0 - .iter() - .find(|a| a.kind == kind && a.platform.as_deref() == Some(platform)) + /// Whether the service lists an artifact of `kind` for the patch. + pub(crate) fn has(&self, kind: &str) -> bool { + self.artifacts.iter().any(|a| a.kind == kind) } } @@ -202,10 +205,11 @@ pub(crate) async fn fetch_verified_archive( }) } -/// Ask the service which artifacts it serves for `uuid` besides the -/// archive, without downloading the archive: the package reference names -/// them. For a backend that vendors only those (a gem's per-platform -/// prebuilds), so a patch that has none costs one request and no download. +/// Ask the service what it says of the patch `uuid` without downloading +/// its archive: the package reference names the patch it was built from +/// and the artifacts it serves besides the archive. The gem backend asks +/// this of the patch of each platform gem a lock names, so a gem that +/// cannot be vendored on every locked platform costs no download. pub(crate) async fn fetch_served_artifacts( cfg: &VendorServiceConfig, uuid: &str, @@ -222,9 +226,10 @@ pub(crate) async fn fetch_served_artifacts( ) .await; match outcome { - VendorServiceOutcome::Ready(artifacts) => { - ServiceArtifact::Ready(ServedArtifacts(artifacts)) - } + VendorServiceOutcome::Ready(reference) => ServiceArtifact::Ready(ServedArtifacts { + rebuilt_from_uuid: reference.rebuilt_from_uuid, + artifacts: reference.artifacts, + }), VendorServiceOutcome::Pending => ServiceArtifact::Pending, VendorServiceOutcome::Unavailable(reason) => ServiceArtifact::Unavailable(reason), VendorServiceOutcome::Failed(err) => ServiceArtifact::Failed(err.to_string()), @@ -382,19 +387,6 @@ pub(crate) async fn fetch_verified_secondary( fetch_verified_artifact(cfg, archive.secondary.iter().find(|a| a.kind == kind)).await } -/// [`fetch_verified_secondary`] for an artifact served once per gem -/// platform (`gem-platform`, `gem-platform-stub-gemspec`): the one of -/// `kind` whose `platform` is exactly `platform`, the token `Gemfile.lock` -/// spells. -pub(crate) async fn fetch_verified_platform_secondary( - cfg: &VendorServiceConfig, - served: &ServedArtifacts, - kind: &str, - platform: &str, -) -> SecondaryArtifactResult { - fetch_verified_artifact(cfg, served.platform(kind, platform)).await -} - /// Download `artifact` and verify the bytes against its own sha512 SRI; /// `Absent` when the service referenced no such artifact. async fn fetch_verified_artifact( @@ -829,7 +821,6 @@ mod tests { secondary: vec![SecondaryArtifact { prefetched: None, kind: "gem-stub-gemspec".into(), - platform: None, url: format!("{}/stub", server.uri()), integrity_sri: PackedTarball::from_bytes(b"x").integrity, }], diff --git a/crates/socket-patch-core/src/vendor/state.rs b/crates/socket-patch-core/src/vendor/state.rs index 5857af81d..1cc326252 100644 --- a/crates/socket-patch-core/src/vendor/state.rs +++ b/crates/socket-patch-core/src/vendor/state.rs @@ -317,14 +317,25 @@ pub struct VendorEntry { /// pypi/pipenv extras. #[serde(default, skip_serializing_if = "Option::is_none")] pub pipenv: Option, - /// gem: the platforms of a gem vendored as precompiled platform gems, - /// in `Gemfile.lock` order (`arm64-darwin`, `x86_64-linux-gnu`, …). - /// The artifact dir then holds one unpacked prebuild per platform, at + /// gem: the platform gems of a gem vendored as precompiled platform + /// gems, in `Gemfile.lock` order (`arm64-darwin`, `x86_64-linux-gnu`, + /// …), each with the patch its tree was built from. The artifact dir + /// then holds one unpacked patched platform gem per entry, at /// `//`, instead of the gem's own tree: bundler /// never builds a `path:` gem's extensions, so a gem the lock resolves - /// to platform gems is vendored as the patch service's prebuilt ones. + /// to platform gems is vendored as the patched platform gems. Each + /// platform gem of a fix has a patch of its own; the entry's `uuid` + /// (and the artifact dir's) is the fix's source patch, the ruby gem's. /// Empty for a gem vendored as its ruby-platform tree. #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub gem_builds: Vec, + /// gem: the platforms of a gem that an earlier development build + /// vendored as precompiled platform gems, whose trees all came with + /// the ruby gem's patch (`uuid`) and so name no patch of their own. + /// Read only: such an entry still verifies against that one patch, + /// reverts, and is brought to [`Self::gem_builds`] by the next vendor + /// run that finds a patch for every platform. Never written. + #[serde(default, skip_serializing_if = "Vec::is_empty")] pub gem_platforms: Vec, /// True when vendored WITHOUT a manifest record — the posture of every /// `scan` / `get --mode vendored` entry (vendored mode writes no @@ -351,7 +362,46 @@ pub struct VendorEntry { pub record: Option, } +/// One platform gem of a gem vendored as precompiled platform gems +/// ([`VendorEntry::gem_builds`]): the tree `//`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GemBuildEntry { + /// `Gem::Platform#to_s` as `Gemfile.lock` spells it. + pub platform: String, + /// The patch of this platform gem: the one its tree was built from. + pub uuid: String, + /// The sha512 (SRI) of the patched platform `.gem` the tree was + /// unpacked from, as the patch service stated it and the download was + /// verified against. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub gem_integrity: String, + /// The sha512 (SRI) of the stub gemspec the tree holds, likewise. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub gemspec_integrity: String, + /// That patch's record (afterHashes, vulnerabilities), embedded like + /// [`VendorEntry::record`]: what the tree is verified against and what + /// a VEX statement about this platform gem names. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub record: Option, +} + impl VendorEntry { + /// The platforms of a gem vendored as precompiled platform gems, in + /// lock order: [`Self::gem_builds`]', else the ones an earlier + /// development build recorded ([`Self::gem_platforms`]). Empty for + /// every other entry. + pub fn gem_tree_platforms(&self) -> Vec<&str> { + match self.gem_builds.is_empty() { + false => self + .gem_builds + .iter() + .map(|b| b.platform.as_str()) + .collect(), + true => self.gem_platforms.iter().map(String::as_str).collect(), + } + } + /// Create an entry with no ecosystem-specific metadata or embedded record. pub fn new( ecosystem: String, @@ -374,6 +424,7 @@ impl VendorEntry { poetry: None, pdm: None, pipenv: None, + gem_builds: Vec::new(), gem_platforms: Vec::new(), detached: false, record: None, @@ -768,6 +819,62 @@ pub fn lookup_entry_kv<'a>( }) } +/// The tree the ledger records for the platform gem that `purl` is a patch +/// purl of (`pkg:gem/@?platform=`), with the entry +/// that holds it: a gem vendored as platform gems is one entry, filed under +/// the purl of the patch its platform gems were built from, which records +/// the patch of each platform's tree ([`VendorEntry::gem_builds`]). `None` +/// for any other purl, and for a platform the entry holds no tree of. +pub fn lookup_gem_build<'a>( + entries: &'a HashMap, + purl: &str, +) -> Option<(&'a VendorEntry, &'a GemBuildEntry)> { + use crate::crawlers::Ecosystem; + if Ecosystem::from_purl(purl) != Some(Ecosystem::Gem) { + return None; + } + let platform = crate::utils::purl::gem_platform_qualifier(purl)?; + let base = PurlKey::qualified(crate::utils::purl::strip_purl_qualifiers(purl)); + let (_, entry) = entries + .iter() + .filter(|(_, entry)| entry.ecosystem == "gem" && !entry.gem_builds.is_empty()) + .filter(|(_, entry)| PurlKey::qualified(&entry.base_purl) == base) + .min_by(|(a, _), (b, _)| a.cmp(b))?; + let built = entry.gem_builds.iter().find(|b| b.platform == platform)?; + Some((entry, built)) +} + +/// The uuid of the patch the ledger records as vendored for the patch purl +/// `purl`: the patch of that platform's tree for the purl of a platform gem +/// ([`lookup_gem_build`]), else the entry's own ([`lookup_entry`]). +pub fn vendored_uuid<'a>(entries: &'a HashMap, purl: &str) -> Option<&'a str> { + match lookup_gem_build(entries, purl) { + Some((_, built)) => Some(built.uuid.as_str()), + None => lookup_entry(entries, purl).map(|entry| entry.uuid.as_str()), + } +} + +/// The patch record a detached entry (one vendored with no manifest record) +/// carries for the patch purl `purl` at exactly `uuid`: what a re-run reads +/// in place of asking the patch API for the patch again. The record of a +/// platform gem's patch is the one filed with its tree +/// ([`lookup_gem_build`]). +pub fn detached_record_at<'a>( + entries: &'a HashMap, + purl: &str, + uuid: &str, +) -> Option<&'a PatchRecord> { + if let Some((entry, built)) = lookup_gem_build(entries, purl) { + return built + .record + .as_ref() + .filter(|_| entry.detached && built.uuid == uuid); + } + lookup_entry(entries, purl) + .filter(|entry| entry.detached && entry.uuid == uuid) + .and_then(|entry| entry.record.as_ref()) +} + fn state_path(project_root: &Path) -> PathBuf { project_root.join(VENDOR_STATE_REL) } @@ -1365,6 +1472,75 @@ mod tests { ) } + /// A gem vendored as platform gems is one entry, filed under the patch + /// its platform gems were built from, that records the patch of each + /// platform's tree: the purl of a platform gem's patch resolves to that + /// tree's patch, and to nothing for a platform the entry holds no tree + /// of, an entry an earlier build wrote (it names no patch per platform) + /// or another gem. + #[test] + fn a_platform_gem_patch_is_looked_up_in_the_entry_of_its_fix() { + const BUILT: &str = "9f6b2c4e-1d3a-4f6b-8c2d-000000000001"; + let record = |uuid: &str| PatchRecord { + uuid: uuid.to_string(), + exported_at: String::new(), + files: HashMap::new(), + vulnerabilities: HashMap::new(), + description: String::new(), + license: String::new(), + tier: "free".to_string(), + }; + let mut entry = sample_entry(); + entry.ecosystem = "gem".into(); + entry.base_purl = "pkg:gem/nokogiri@1.18.10".into(); + entry.detached = true; + entry.record = Some(record(UUID)); + entry.gem_builds = vec![GemBuildEntry { + platform: "arm64-darwin".into(), + uuid: BUILT.into(), + gem_integrity: String::new(), + gemspec_integrity: String::new(), + record: Some(record(BUILT)), + }]; + let lead = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let built = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + let mut entries = HashMap::from([(lead.to_string(), entry.clone())]); + + let (found, tree) = lookup_gem_build(&entries, built).expect("the tree's patch"); + assert_eq!((found.uuid.as_str(), tree.uuid.as_str()), (UUID, BUILT)); + assert_eq!(vendored_uuid(&entries, built), Some(BUILT)); + assert_eq!(vendored_uuid(&entries, lead), Some(UUID)); + assert_eq!( + detached_record_at(&entries, built, BUILT).map(|r| r.uuid.as_str()), + Some(BUILT) + ); + assert_eq!( + detached_record_at(&entries, lead, UUID).map(|r| r.uuid.as_str()), + Some(UUID) + ); + assert!( + detached_record_at(&entries, built, UUID).is_none(), + "the tree's own patch, not the entry's" + ); + for other in [ + "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", + "pkg:gem/nokogiri@1.18.9?platform=arm64-darwin", + "pkg:gem/racc@1.18.10?platform=arm64-darwin", + "pkg:npm/nokogiri@1.18.10?platform=arm64-darwin", + ] { + assert!(lookup_gem_build(&entries, other).is_none(), "{other}"); + assert_eq!(vendored_uuid(&entries, other), None, "{other}"); + } + assert!(lookup_gem_build(&entries, lead).is_none()); + + // An entry an earlier development build wrote names platforms only. + let legacy = entries.get_mut(lead).expect("entry"); + legacy.gem_builds.clear(); + legacy.gem_platforms = vec!["arm64-darwin".into()]; + assert!(lookup_gem_build(&entries, built).is_none()); + assert_eq!(vendored_uuid(&entries, built), None); + } + /// A cargo entry migrated from the pre-v5 `.cargo/config.toml` wiring to /// `Cargo.toml` must not carry the retired config record forward (one /// `[patch]` surface per entry), while the lock record and originals @@ -2630,6 +2806,7 @@ mod tests { poetry: None, pdm: None, pipenv: None, + gem_builds: Vec::new(), gem_platforms: Vec::new(), }; let built = VendorEntry::npm( diff --git a/crates/socket-patch-core/src/vendor/test_support.rs b/crates/socket-patch-core/src/vendor/test_support.rs index f6a447e88..9b7b66898 100644 --- a/crates/socket-patch-core/src/vendor/test_support.rs +++ b/crates/socket-patch-core/src/vendor/test_support.rs @@ -513,7 +513,11 @@ pub mod service_fixture; /// non-dry-run vendor in the backend suites, so each backend's real output /// (every ecosystem and lock flavor they cover) pins the verdict. `None` /// (no lock yet, so the next install decides) is allowed. -async fn assert_fresh_vendor_in_use(root: &Path, outcome: &VendorOutcome, dry_run: bool) { +pub(crate) async fn assert_fresh_vendor_in_use( + root: &Path, + outcome: &VendorOutcome, + dry_run: bool, +) { let VendorOutcome::Done { result, entry: Some(entry), diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index 7cfaf05cf..3e86a97f2 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -82,7 +82,18 @@ pub(crate) fn checked_artifact_path( // Stale-vendor detection: the path-level uuid IS the staleness signal — // a patch update changes record.uuid, so an artifact still sitting at the // old uuid path must not attest the new patch. - if parts.uuid != record.uuid || entry.uuid != record.uuid { + // + // A gem vendored as platform gems holds one tree per platform, each the + // gem of a patch of its own (`gem_builds`), under the directory named + // after the patch they were built from (the entry's uuid): the record + // of a platform's patch is attested against that directory too. + let own = entry.uuid == record.uuid + || (entry.ecosystem == "gem" + && entry + .gem_builds + .iter() + .any(|built| built.uuid == record.uuid)); + if parts.uuid != entry.uuid || !own { return Err("vendor_uuid_mismatch".to_string()); } Ok(project_root.join(norm)) @@ -153,10 +164,28 @@ pub async fn verify_vendored_patch_record( // A gem vendored as precompiled platform gems: bundler loads // the tree of whichever platform it runs on, so every one of // them must carry the patch. + // Each tree is the platform gem of a patch of its own: it is + // held to the files of that patch, which the ledger embeds + // (`record`'s own when it is that patch). The trees of an entry + // that names no patch per platform (an earlier development + // build's, or one read off a lockfile) all came with the one + // patch `record`. Some(trees) => { let voucher = TreeVoucher::Ledger(entry.artifact.file_inventory.as_ref()); - for tree in &trees { - verify_platform_tree(tree, &record.files, voucher).await?; + for (tree, platform) in &trees { + let built = entry + .gem_builds + .iter() + .find(|built| Some(built.platform.as_str()) == platform.as_deref()); + let files = match built { + Some(built) if built.uuid == record.uuid => &record.files, + Some(built) => match &built.record { + Some(own) => &own.files, + None => &record.files, + }, + None => &record.files, + }; + verify_platform_tree(tree, files, voucher).await?; } } None => verify_dir_members(&artifact, record, cargo_uuid).await?, @@ -276,21 +305,23 @@ async fn verify_dir_members( async fn gem_platform_trees( artifact: &Path, entry: &VendorEntry, -) -> Result>, String> { +) -> Result)>>, String> { if entry.ecosystem != "gem" { return Ok(None); } - if !entry.gem_platforms.is_empty() { + let platforms = entry.gem_tree_platforms(); + if !platforms.is_empty() { // SECURITY: state.json is committed and tamper-able, and each // platform is about to name a directory that gets stat'd and hashed. - if !entry - .gem_platforms + if !platforms .iter() .all(|platform| super::gem::is_platform_dir_name(platform)) { return Err("vendor_path_unsafe".to_string()); } - let trees = entry.gem_platforms.iter().map(|p| artifact.join(p)); + let trees = platforms + .iter() + .map(|p| (artifact.join(p), Some(p.to_string()))); return Ok(Some(trees.collect())); } let Some((name, _)) = crate::utils::purl::parse_gem_purl(&entry.base_purl) else { @@ -314,7 +345,7 @@ async fn gem_platform_trees( if child.file_type().await.is_ok_and(|t| t.is_dir()) && is_file(child.path().join(&stub)).await { - trees.push(child.path()); + trees.push((child.path(), None)); } } trees.sort(); diff --git a/crates/socket-patch-core/src/vex/discover/gem.rs b/crates/socket-patch-core/src/vex/discover/gem.rs index 5d6b838da..2e294da77 100644 --- a/crates/socket-patch-core/src/vex/discover/gem.rs +++ b/crates/socket-patch-core/src/vex/discover/gem.rs @@ -88,8 +88,9 @@ //! resolve ambiguously). //! //! **Platform builds.** A gem bundler locks as precompiled platform gems -//! has one spec per platform, and the rewriter moves all of them (the -//! patch registry serves a patched build, a "prebuild", for each): +//! has one spec per platform, and the rewriter moves all of them to the +//! registry of the fix's source patch (each platform gem has a patch of its +//! own, and that registry serves the patched gem of every one): //! //! ```text //! GEM @@ -111,8 +112,8 @@ //! **Integrity.** `CHECKSUMS` ` name (version) sha256=` becomes //! [`Sha256Hex`](crate::vendor::lock_inventory::LockIntegrity::Sha256Hex). //! A pin of several builds is pinned only when `CHECKSUMS` has a sha256 for -//! every one of them (each `name (version-)` entry holds its own -//! prebuild's); the ref then carries the first build's. +//! every one of them (each `name (version-)` entry holds the +//! sha256 of its own patch's gem); the ref then carries the first build's. //! `integrity_required` is true iff the lock HAS a `CHECKSUMS` section: in //! that era (bundler ≥ 2.6) the rewriter only converges the lock after //! writing the patched gem's sha256, so a pin-less diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-missing/expected-edits.json similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/expected-edits.json rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-missing/expected-edits.json diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-missing/expected-warnings.json similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/expected-warnings.json rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-missing/expected-warnings.json diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/input/Gemfile b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-missing/input/Gemfile similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/input/Gemfile rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-missing/input/Gemfile diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/input/Gemfile.lock b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-missing/input/Gemfile.lock similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/input/Gemfile.lock rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-missing/input/Gemfile.lock diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-missing/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-missing/overrides.json new file mode 100644 index 000000000..4166ee24b --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-build-missing/overrides.json @@ -0,0 +1,44 @@ +[ + { + "ecosystem": "gem", + "name": "nokogiri", + "version": "1.18.10", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/gems/nokogiri-1.18.10.gem", + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + } + }, + "integrity": { + "sha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + } + }, + { + "ecosystem": "gem", + "name": "nokogiri", + "version": "1.18.10", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-77777777777a", + "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-77777777777a/gems/nokogiri-1.18.10-arm64-darwin.gem", + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-77777777777a/", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "gemPlatform": "arm64-darwin", + "gemRebuiltFromUuid": "77777777-7777-7777-7777-777777777777" + } + }, + "integrity": { + "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-rerun/expected-edits.json similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/expected-edits.json rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-rerun/expected-edits.json diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-rerun/expected-warnings.json similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/expected-warnings.json rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-rerun/expected-warnings.json diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/Gemfile b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-rerun/input/Gemfile similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/Gemfile rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-rerun/input/Gemfile diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/Gemfile.lock b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-rerun/input/Gemfile.lock similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/input/Gemfile.lock rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-rerun/input/Gemfile.lock diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-rerun/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-rerun/overrides.json new file mode 100644 index 000000000..9697a5199 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-rerun/overrides.json @@ -0,0 +1,66 @@ +[ + { + "ecosystem": "gem", + "name": "nokogiri", + "version": "1.18.10", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/gems/nokogiri-1.18.10.gem", + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + } + }, + "integrity": { + "sha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + } + }, + { + "ecosystem": "gem", + "name": "nokogiri", + "version": "1.18.10", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-77777777777a", + "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-77777777777a/gems/nokogiri-1.18.10-arm64-darwin.gem", + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-77777777777a/", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "gemPlatform": "arm64-darwin", + "gemRebuiltFromUuid": "77777777-7777-7777-7777-777777777777" + } + }, + "integrity": { + "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } + }, + { + "ecosystem": "gem", + "name": "nokogiri", + "version": "1.18.10", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-77777777777b", + "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-77777777777b/gems/nokogiri-1.18.10-x86_64-linux-gnu.gem", + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-77777777777b/", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "gemPlatform": "x86_64-linux-gnu", + "gemRebuiltFromUuid": "77777777-7777-7777-7777-777777777777" + } + }, + "integrity": { + "sha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-two-fixes/expected-edits.json similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected-warnings.json rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-two-fixes/expected-edits.json diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-two-fixes/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-two-fixes/expected-warnings.json new file mode 100644 index 000000000..57ef0136a --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-two-fixes/expected-warnings.json @@ -0,0 +1 @@ +["redirect_gem_platform_unsupported"] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/input/Gemfile b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-two-fixes/input/Gemfile similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/input/Gemfile rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-two-fixes/input/Gemfile diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/input/Gemfile.lock b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-two-fixes/input/Gemfile.lock similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/input/Gemfile.lock rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-two-fixes/input/Gemfile.lock diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-two-fixes/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-two-fixes/overrides.json new file mode 100644 index 000000000..e57a55248 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds-two-fixes/overrides.json @@ -0,0 +1,66 @@ +[ + { + "ecosystem": "gem", + "name": "nokogiri", + "version": "1.18.10", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/gems/nokogiri-1.18.10.gem", + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + } + }, + "integrity": { + "sha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + } + }, + { + "ecosystem": "gem", + "name": "nokogiri", + "version": "1.18.10", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-77777777777a", + "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-77777777777a/gems/nokogiri-1.18.10-arm64-darwin.gem", + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-77777777777a/", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "gemPlatform": "arm64-darwin", + "gemRebuiltFromUuid": "77777777-7777-7777-7777-777777777777" + } + }, + "integrity": { + "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } + }, + { + "ecosystem": "gem", + "name": "nokogiri", + "version": "1.18.10", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-77777777777b", + "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-77777777777b/gems/nokogiri-1.18.10-x86_64-linux-gnu.gem", + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-77777777777b/", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "gemPlatform": "x86_64-linux-gnu", + "gemRebuiltFromUuid": "88888888-8888-8888-8888-888888888888" + } + }, + "integrity": { + "sha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/expected-edits.json similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected-edits.json rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/expected-edits.json diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/expected-warnings.json new file mode 100644 index 000000000..fe51488c7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/expected-warnings.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected/Gemfile b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/expected/Gemfile similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected/Gemfile rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/expected/Gemfile diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected/Gemfile.lock b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/expected/Gemfile.lock similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/expected/Gemfile.lock rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/expected/Gemfile.lock diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/input/Gemfile b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/input/Gemfile new file mode 100644 index 000000000..bbbe99128 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/input/Gemfile @@ -0,0 +1,4 @@ +source "https://rubygems.org" + +gem "nokogiri", "1.18.10" +gem "puma", "6.0.0" diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/input/Gemfile.lock b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/input/Gemfile.lock new file mode 100644 index 000000000..7064b964b --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/input/Gemfile.lock @@ -0,0 +1,26 @@ +GEM + remote: https://rubygems.org/ + specs: + nokogiri (1.18.10-arm64-darwin) + racc (~> 1.4) + nokogiri (1.18.10-x86_64-linux-gnu) + racc (~> 1.4) + puma (6.0.0) + racc (1.8.1) + +PLATFORMS + arm64-darwin + x86_64-linux-gnu + +DEPENDENCIES + nokogiri (= 1.18.10) + puma (= 6.0.0) + +CHECKSUMS + nokogiri (1.18.10-arm64-darwin) sha256=3333333333333333333333333333333333333333333333333333333333333333 + nokogiri (1.18.10-x86_64-linux-gnu) sha256=4444444444444444444444444444444444444444444444444444444444444444 + puma (6.0.0) sha256=1111111111111111111111111111111111111111111111111111111111111111 + racc (1.8.1) sha256=5555555555555555555555555555555555555555555555555555555555555555 + +BUNDLED WITH + 4.0.15 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/overrides.json new file mode 100644 index 000000000..9697a5199 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-builds/overrides.json @@ -0,0 +1,66 @@ +[ + { + "ecosystem": "gem", + "name": "nokogiri", + "version": "1.18.10", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-777777777777", + "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/gems/nokogiri-1.18.10.gem", + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + } + }, + "integrity": { + "sha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + } + }, + { + "ecosystem": "gem", + "name": "nokogiri", + "version": "1.18.10", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-77777777777a", + "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-77777777777a/gems/nokogiri-1.18.10-arm64-darwin.gem", + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-77777777777a/", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "gemPlatform": "arm64-darwin", + "gemRebuiltFromUuid": "77777777-7777-7777-7777-777777777777" + } + }, + "integrity": { + "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } + }, + { + "ecosystem": "gem", + "name": "nokogiri", + "version": "1.18.10", + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": "77777777-7777-7777-7777-77777777777b", + "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-77777777777b/gems/nokogiri-1.18.10-x86_64-linux-gnu.gem", + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-77777777777b/", + "identifiers": { + "name": "nokogiri", + "version": "1.18.10", + "gemChecksumSha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "gemPlatform": "x86_64-linux-gnu", + "gemRebuiltFromUuid": "77777777-7777-7777-7777-777777777777" + } + }, + "integrity": { + "sha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + } + } +] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/overrides.json deleted file mode 100644 index 293fadc61..000000000 --- a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuild-missing/overrides.json +++ /dev/null @@ -1,28 +0,0 @@ -[ - { - "ecosystem": "gem", - "name": "nokogiri", - "version": "1.18.10", - "token": "11111111-1111-1111-1111-111111111111", - "patchUuid": "77777777-7777-7777-7777-777777777777", - "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/gems/nokogiri-1.18.10.gem", - "registryOverride": { - "kind": "rubygems-compact-index", - "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/", - "identifiers": { - "name": "nokogiri", - "version": "1.18.10", - "gemChecksumSha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", - "gemPlatforms": [ - { - "platform": "arm64-darwin", - "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - } - ] - } - }, - "integrity": { - "sha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" - } - } -] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/overrides.json deleted file mode 100644 index 1d3992b06..000000000 --- a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds/overrides.json +++ /dev/null @@ -1,32 +0,0 @@ -[ - { - "ecosystem": "gem", - "name": "nokogiri", - "version": "1.18.10", - "token": "11111111-1111-1111-1111-111111111111", - "patchUuid": "77777777-7777-7777-7777-777777777777", - "artifactUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/gems/nokogiri-1.18.10.gem", - "registryOverride": { - "kind": "rubygems-compact-index", - "indexUrl": "https://patch.socket.dev/patch-registry/gem/11111111-1111-1111-1111-111111111111/77777777-7777-7777-7777-777777777777/", - "identifiers": { - "name": "nokogiri", - "version": "1.18.10", - "gemChecksumSha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", - "gemPlatforms": [ - { - "platform": "arm64-darwin", - "gemChecksumSha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - { - "platform": "x86_64-linux-gnu", - "gemChecksumSha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" - } - ] - } - }, - "integrity": { - "sha256": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" - } - } -] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-retired-fields/expected-edits.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-retired-fields/expected-edits.json new file mode 100644 index 000000000..fe51488c7 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-retired-fields/expected-edits.json @@ -0,0 +1 @@ +[] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-retired-fields/expected-warnings.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-retired-fields/expected-warnings.json new file mode 100644 index 000000000..57ef0136a --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-retired-fields/expected-warnings.json @@ -0,0 +1 @@ +["redirect_gem_platform_unsupported"] diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-retired-fields/input/Gemfile b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-retired-fields/input/Gemfile new file mode 100644 index 000000000..bbbe99128 --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-retired-fields/input/Gemfile @@ -0,0 +1,4 @@ +source "https://rubygems.org" + +gem "nokogiri", "1.18.10" +gem "puma", "6.0.0" diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-retired-fields/input/Gemfile.lock b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-retired-fields/input/Gemfile.lock new file mode 100644 index 000000000..7064b964b --- /dev/null +++ b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-retired-fields/input/Gemfile.lock @@ -0,0 +1,26 @@ +GEM + remote: https://rubygems.org/ + specs: + nokogiri (1.18.10-arm64-darwin) + racc (~> 1.4) + nokogiri (1.18.10-x86_64-linux-gnu) + racc (~> 1.4) + puma (6.0.0) + racc (1.8.1) + +PLATFORMS + arm64-darwin + x86_64-linux-gnu + +DEPENDENCIES + nokogiri (= 1.18.10) + puma (= 6.0.0) + +CHECKSUMS + nokogiri (1.18.10-arm64-darwin) sha256=3333333333333333333333333333333333333333333333333333333333333333 + nokogiri (1.18.10-x86_64-linux-gnu) sha256=4444444444444444444444444444444444444444444444444444444444444444 + puma (6.0.0) sha256=1111111111111111111111111111111111111111111111111111111111111111 + racc (1.8.1) sha256=5555555555555555555555555555555555555555555555555555555555555555 + +BUNDLED WITH + 4.0.15 diff --git a/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/overrides.json b/crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-retired-fields/overrides.json similarity index 100% rename from crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-prebuilds-rerun/overrides.json rename to crates/socket-patch-core/tests/fixtures/redirect/gem/bundler/platform-retired-fields/overrides.json diff --git a/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json b/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json index c843d7a11..69bed3857 100644 --- a/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json +++ b/crates/socket-patch-core/tests/fixtures/vex-discover-golden/redirect-gem.json @@ -44,7 +44,7 @@ "elsewhere": [], "live_claims": [] }, - "redirect/gem/bundler/platform-prebuild-missing/input": { + "redirect/gem/bundler/platform-build-missing/input": { "refs": [], "diagnostics": [], "recognized": [], @@ -52,7 +52,7 @@ "elsewhere": [], "live_claims": [] }, - "redirect/gem/bundler/platform-prebuilds/expected": { + "redirect/gem/bundler/platform-builds/expected": { "refs": [ { "purl": "pkg:gem/nokogiri@1.18.10", @@ -89,7 +89,7 @@ } ] }, - "redirect/gem/bundler/platform-prebuilds/input": { + "redirect/gem/bundler/platform-builds/input": { "refs": [], "diagnostics": [], "recognized": [], @@ -97,7 +97,7 @@ "elsewhere": [], "live_claims": [] }, - "redirect/gem/bundler/platform-prebuilds-rerun/input": { + "redirect/gem/bundler/platform-builds-rerun/input": { "refs": [ { "purl": "pkg:gem/nokogiri@1.18.10", @@ -133,5 +133,21 @@ "purl": "pkg:gem/nokogiri@1.18.10" } ] + }, + "redirect/gem/bundler/platform-builds-two-fixes/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] + }, + "redirect/gem/bundler/platform-retired-fields/input": { + "refs": [], + "diagnostics": [], + "recognized": [], + "unlocked_pins": [], + "elsewhere": [], + "live_claims": [] } } diff --git a/crates/socket-patch-core/tests/upstream_restore_golden.rs b/crates/socket-patch-core/tests/upstream_restore_golden.rs index 7feddd7e6..678d9ee40 100644 --- a/crates/socket-patch-core/tests/upstream_restore_golden.rs +++ b/crates/socket-patch-core/tests/upstream_restore_golden.rs @@ -609,16 +609,36 @@ async fn gem_edge_shapes_round_trip() { } } -/// [`gem_override`] with a prebuild for each of `platforms`: the patch -/// registry serves a patched platform gem for it too. -fn gem_override_prebuilt(name: &str, version: &str, platforms: &[&str]) -> serde_json::Value { +/// The patches of one fix of a gem: [`gem_override`] (the ruby gem's patch, +/// the fix's source, whose registry [`GEM_INDEX`] serves every gem of the +/// fix) and the patch of each platform gem in `platforms`, built from it, +/// with a uuid, a registry and a sha256 of its own. +fn gem_fix_overrides(name: &str, version: &str, platforms: &[&str]) -> serde_json::Value { let mut overrides = gem_override(name, version); - overrides[0]["registryOverride"]["identifiers"]["gemPlatforms"] = platforms - .iter() - .map(|platform| { - serde_json::json!({"platform": platform, "gemChecksumSha256": "ab".repeat(32)}) - }) - .collect(); + let list = overrides.as_array_mut().unwrap(); + for (n, platform) in platforms.iter().enumerate() { + let uuid = format!("{}{n:02}", &GEM_UUID[..GEM_UUID.len() - 2]); + let index = GEM_INDEX.replace(GEM_UUID, &uuid); + list.push(serde_json::json!({ + "ecosystem": "gem", + "name": name, + "version": version, + "token": "11111111-1111-1111-1111-111111111111", + "patchUuid": uuid, + "artifactUrl": format!("{index}gems/{name}-{version}-{platform}.gem"), + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": index, + "identifiers": { + "name": name, "version": version, + "gemChecksumSha256": "ab".repeat(32), + "gemPlatform": platform, + "gemRebuiltFromUuid": GEM_UUID + } + }, + "integrity": {"sha256": "ab".repeat(32)} + })); + } overrides } @@ -626,14 +646,14 @@ fn gem_override_prebuilt(name: &str, version: &str, platforms: &[&str]) -> serde /// one entry per platform, and no ruby-platform `nokogiri (1.18.10)`. const GEM_PLATFORM_LOCK: &str = "GEM\n remote: https://rubygems.org/\n specs:\n nokogiri (1.18.10-arm64-darwin)\n racc (~> 1.4)\n nokogiri (1.18.10-x86_64-linux-gnu)\n racc (~> 1.4)\n nokogiri-happymapper (0.10.0)\n puma (6.0.0)\n nio4r (~> 2.0)\n racc (1.8.1)\n\nPLATFORMS\n arm64-darwin\n x86_64-linux-gnu\n\nDEPENDENCIES\n nokogiri (= 1.18.10)\n puma\n\nCHECKSUMS\n nokogiri (1.18.10-arm64-darwin) sha256=4444444444444444444444444444444444444444444444444444444444444444\n nokogiri (1.18.10-x86_64-linux-gnu) sha256=5555555555555555555555555555555555555555555555555555555555555555\n nokogiri-happymapper (0.10.0) sha256=6666666666666666666666666666666666666666666666666666666666666666\n puma (6.0.0) sha256=1111111111111111111111111111111111111111111111111111111111111111\n racc (1.8.1) sha256=3333333333333333333333333333333333333333333333333333333333333333\n\nBUNDLED WITH\n 4.0.15\n"; -/// A gem locked as precompiled platform builds, redirected to its -/// prebuilds and restored: every platform entry is back in the upstream +/// A gem locked as precompiled platform builds, redirected to the patches +/// of one fix (each build to its own) and restored: every platform entry is back in the upstream /// section where Bundler sorts it, the `DEPENDENCIES` pin (or added entry) /// is gone, and each `CHECKSUMS` entry is back on its own build's upstream /// sha256 — the pre-scan pair, byte for byte. #[tokio::test] #[serial] -async fn gem_platform_prebuilds_round_trip() { +async fn gem_platform_builds_round_trip() { let platforms = ["arm64-darwin", "x86_64-linux-gnu"]; let gemfile = "source \"https://rubygems.org\"\n\ngem \"nokogiri\", \"1.18.10\"\ngem \"puma\"\n"; @@ -665,13 +685,25 @@ async fn gem_platform_prebuilds_round_trip() { " nio4r (~> 2.0)\n nokogiri (>= 1.18)\n", ) .replace(" nokogiri (= 1.18.10)\n", ""); - let overrides = || gem_override_prebuilt("nokogiri", "1.18.10", &platforms); + let overrides = || gem_fix_overrides("nokogiri", "1.18.10", &platforms); + // The fix without its source patch: the builds go to the registry of + // the first locked build's own patch, and come back the same way. + let without_source = || { + let mut members = overrides(); + members.as_array_mut().unwrap().remove(0); + members + }; let cases = [ synthetic( "platform-builds", &[("Gemfile", gemfile), ("Gemfile.lock", GEM_PLATFORM_LOCK)], overrides(), ), + synthetic( + "platform-builds-no-source", + &[("Gemfile", gemfile), ("Gemfile.lock", GEM_PLATFORM_LOCK)], + without_source(), + ), synthetic( "platform-builds-no-checksums", &[("Gemfile", gemfile), ("Gemfile.lock", &no_checksums)], @@ -705,11 +737,17 @@ async fn gem_platform_prebuilds_round_trip() { } else { "Gemfile.lock" }]; + // The registry of the fix's source patch, or of the first build's + // own patch where the fix comes without its source. + let index = match case.dir.display().to_string().contains("no-source") { + true => GEM_INDEX.replace(GEM_UUID, &format!("{}00", &GEM_UUID[..GEM_UUID.len() - 2])), + false => GEM_INDEX.to_string(), + }; assert!( hosted.contains(&format!( - " remote: {GEM_INDEX}\n specs:\n nokogiri (1.18.10" + " remote: {index}\n specs:\n nokogiri (1.18.10" )) || hosted.contains(&format!( - " remote: {GEM_INDEX}\r\n specs:\r\n nokogiri (1.18.10" + " remote: {index}\r\n specs:\r\n nokogiri (1.18.10" )), "{}: the rewrite moved the builds:\n{hosted}", case.dir.display() @@ -736,9 +774,9 @@ async fn gem_platform_prebuilds_round_trip() { /// that names the gem as platform builds and cannot be converged (here /// `DEPENDENCIES` sits before the `GEM` section): the MIXED state the /// rewriter keeps. The platform entries still resolve from rubygems.org, so -/// a prebuild's sha256 on them would fail every `bundle install` on a +/// a patched gem's sha256 on them would fail every `bundle install` on a /// checksum mismatch. The rewrite writes none, and the unwind hands the -/// lock back byte for byte. A lock that does carry prebuild sha256s on such +/// lock back byte for byte. A lock that does carry patched sha256s on such /// entries is put back on the upstream ones all the same: the restore /// re-pins a platform entry however the lock wires the gem. #[tokio::test] @@ -755,8 +793,7 @@ async fn gem_platform_builds_on_a_mixed_lock_keep_their_upstream_checksums() { let block_gemfile = format!( "source \"https://rubygems.org\"\nsource \"{GEM_INDEX}\" do\n gem \"nokogiri\", \"1.18.10\"\nend\ngem \"puma\"\n" ); - let overrides = - gem_override_prebuilt("nokogiri", "1.18.10", &["arm64-darwin", "x86_64-linux-gnu"]); + let overrides = gem_fix_overrides("nokogiri", "1.18.10", &["arm64-darwin", "x86_64-linux-gnu"]); let pair = |lock: &str| { BTreeMap::from([ ("Gemfile".to_string(), block_gemfile.clone()), @@ -776,12 +813,12 @@ async fn gem_platform_builds_on_a_mixed_lock_keep_their_upstream_checksums() { ); // The unwind, over the pair the rewrite left and over one whose - // platform entries hold prebuild sha256s: the pre-scan lock both times. - let prebuild = "ab".repeat(32); - let pinned_to_prebuilds = lock - .replace(&"4".repeat(64), &prebuild) - .replace(&"5".repeat(64), &prebuild); - assert_ne!(pinned_to_prebuilds, lock); + // platform entries hold patched sha256s: the pre-scan lock both times. + let patched = "ab".repeat(32); + let pinned_to_patches = lock + .replace(&"4".repeat(64), &patched) + .replace(&"5".repeat(64), &patched); + assert_ne!(pinned_to_patches, lock); let pin = HostedPin { purl: "pkg:gem/nokogiri@1.18.10".into(), uuid: GEM_UUID.into(), @@ -789,7 +826,7 @@ async fn gem_platform_builds_on_a_mixed_lock_keep_their_upstream_checksums() { }; for (label, hosted_lock) in [ ("as-rewritten", &lock), - ("prebuild-pins", &pinned_to_prebuilds), + ("patched-pins", &pinned_to_patches), ] { let case = Case { dir: PathBuf::from(format!("synthetic/mixed-platform-builds-{label}")), diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 36d71e2c6..777aeb84c 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -22,7 +22,7 @@ below is about what a package manager installs and builds. | PyPI (`pypi`) — uv / poetry / pdm / pipenv / pip | ✅ in place | ✅ uv project/script locks, PEP 751 `pylock.toml` / `pylock..toml`, poetry, pdm, pipenv (Pipenv 2018 or later — every `Pipfile.lock` category is rewired, lock-only checkouts included; Pipenv 2023+ does not hash-check local wheels — `vendor_integrity_unverified`; Pipenv 2023.7.9+ exports the vendored wheel without a hash, so `pipenv requirements --hash` output fails pip's hash-checking mode — `pypi_pipenv_hash_export_unsupported`; a venv still holding the upstream release is reported as `pypi_pipenv_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)), and requirements.txt. Native uv vendoring requires uv ≥ 0.2.35 (the `[[package]]` lock grammar); hosted mode covers native `uv.lock` from uv 0.1.45 (the first release whose `uv lock` writes one) and requirements from uv 0.0.5; see [uv compatibility](testing/uv-compatibility.md). Declined where a rules_python hub of a Bazel workspace reads the file, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ requirements.txt including hash continuations, uv project/script locks, and PEP 751 locks. Version/source ambiguity is refused; see [uv compatibility](testing/uv-compatibility.md). Poetry 1.x and 2.x locks are supported; Poetry 0.x ignores URL sources and is refused. See [Poetry compatibility](testing/poetry-compatibility.md). Pipenv `Pipfile.lock` (pipfile-spec 6 — Pipenv 7 and later; `path` references for 7–11, `file` from 2018; lock-only checkouts and Pipenv's out-of-tree venv are discovered; a warm venv that Pipenv will not reinstall over warns `redirect_pypi_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)). `pdm.lock` is supported for the lock formats PDM 0.12–1.4 and 2.8.1+ write (`lock_version` 2 / 4.3–4.5.1); the identity-losing 3.1 / 4.0–4.2 formats (PDM 1.8–2.7) are refused. PDM 2.8.0 writes an indistinguishable `4.3` lock but shares that identity-loss bug, so a rewritten 2.8.0 lock crashes `pdm sync` — upgrade to ≥ 2.8.1. See [PDM compatibility](testing/pdm-compatibility.md). | | pixi (`pypi`) — the Python packages of a pixi project, from conda channels or PyPI | ✅ in place, in every environment under `.pixi/envs`: PyPI wheels and pure-Python conda packages (compiled conda packages are not supported yet and are skipped) — see [PyPI: pixi projects](#pypi-pixi-projects) | ❌ refused (`pypi_no_requirements` / `pypi_pyproject_only`, which name agent mode) | ❌ nothing rewritten (`redirect_pypi_pixi_project` names agent mode) | | Cargo (`cargo`) | ✅ in-place + `.cargo-checksum.json` rewrite (shared registry-cache caveat — see [Cargo: shared registry cache](#cargo-shared-registry-cache)) | ✅ `[patch.crates-io]` path entry in the root `Cargo.toml` (v5; per-version Socket keys; pre-v5 `.cargo/config*` wiring migrates on re-run) | ✅ per-patch sparse registry (`[registries.socket-patch-]` + Cargo.lock source/checksum); needs cargo 1.68+ (sparse registries) — a project whose `rust-version` or `rust-toolchain[.toml]` declares an older cargo is refused (`redirect_cargo_old_cargo`), use `--mode vendored`; direct dependencies only — a crate another dependency also pulls in is refused, use `--mode vendored`; a crate the user overrides with `[patch]` (path, git or another registry) is refused too, the override is left alone; a `cargo vendor` or `cargo local-registry` project (crates.io replaced by an on-disk source in the project's, a parent directory's or `$CARGO_HOME`'s `.cargo/config*`) is refused, use agent mode; with no `Cargo.lock` the graph is unknown, so only a project whose sole dependency is the patched crate is redirected; in a Bazel workspace a crate is not pinned while a rules_rust hub reads the project's Cargo files without its cargo config (`redirect_cargo_bazel_config_unread`), see [Bazel workspaces: Cargo](#bazel-workspaces-cargo) | -| RubyGems (`gem`) | ✅ in place | ✅ Gemfile + Gemfile.lock path pair (a CRLF `Gemfile.lock`, as a `core.autocrlf` checkout leaves it, is edited and reverted in its own line ending, and a lock mixing CRLF and LF fails closed; a gem locked as precompiled platform gems is vendored from prebuilt patched platform gems, see [Ruby gems: native extensions](#ruby-gems-native-extensions); `Gemfile` spelling only — a `gems.rb` twin, which bundler ≥ 2 loads instead, or a `BUNDLE_GEMFILE`-configured manifest makes vendoring refuse with `gemfile_not_loaded` before any write); declined where a rules_ruby hub of a Bazel workspace reads the pair, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ a `source:` option on the gem's own declaration, the lock converged to match (see [Ruby gems: hosted mode](#ruby-gems-hosted-mode)) — edits `gems.rb` + `gems.locked` or `Gemfile` + `Gemfile.lock`, whichever the project holds (a `Gemfile` + `gems.rb` twin is refused with `redirect_gem_twin_manifest_ambiguous`: bundler 1.x loads the `Gemfile`, bundler ≥ 2 loads `gems.rb`, and nothing in the project says which bundler installs it; bundler 4's `BUNDLE_LOCKFILE` (environment, app config or global config) naming any other lock is refused with `redirect_gem_bundle_lockfile_unsupported`, as is vendoring with `gemfile_not_loaded`; spellings that diverge beyond Socket's own edits fail closed with `redirect_gem_gemfile_spellings_diverge`; `BUNDLE_GEMFILE` from `.bundle/config` (which outranks the environment, as in bundler), the environment, or the global `~/.bundle/config` / `$BUNDLE_USER_CONFIG` (lowest, as in bundler) is followed when it names the project's `Gemfile` / `gems.rb`, and any other configured manifest is refused with `redirect_gem_bundle_gemfile_unsupported`); a Bundler all-source, exact-source or hostname mirror in app config or the scan environment can capture the patch registry, so the redirect is refused with `redirect_gem_mirror_overrides_source` without printing mirror URLs (scope mirrors to `mirror.https://rubygems.org`; user-global config and mirrors set only in a later install environment are not inspected); the `CHECKSUMS` pin needs bundler ≥ 2.6 (an older lock is still pinned by source and installs frozen; the run says once, with `redirect_gem_no_checksums_section`, that it cannot record the checksums); a stale pre-redirect materialization that `bundle install` would reuse instead of refetching is replaced with the verified patched gem when it is the project's own, else flagged `redirect_gem_stale_install` with the remedy (see "Ruby gems: gems already installed" below and CLI_CONTRACT.md's "Gem stale-install guard"). In a Bazel workspace whose rules_ruby call holds the gem to another sha256 in `gem_checksums`, or has a `gem_checksums` that is not written out in the call, nothing is written for it (`redirect_bazel_gem_checksums_pinned`); see [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems) | +| RubyGems (`gem`) | ✅ in place | ✅ Gemfile + Gemfile.lock path pair (a CRLF `Gemfile.lock`, as a `core.autocrlf` checkout leaves it, is edited and reverted in its own line ending, and a lock mixing CRLF and LF fails closed; a gem locked as precompiled platform gems is vendored from the patched platform gems of its fix, one patch per platform, see [Ruby gems: native extensions](#ruby-gems-native-extensions); `Gemfile` spelling only — a `gems.rb` twin, which bundler ≥ 2 loads instead, or a `BUNDLE_GEMFILE`-configured manifest makes vendoring refuse with `gemfile_not_loaded` before any write); declined where a rules_ruby hub of a Bazel workspace reads the pair, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ a `source:` option on the gem's own declaration, the lock converged to match (see [Ruby gems: hosted mode](#ruby-gems-hosted-mode)) — edits `gems.rb` + `gems.locked` or `Gemfile` + `Gemfile.lock`, whichever the project holds (a `Gemfile` + `gems.rb` twin is refused with `redirect_gem_twin_manifest_ambiguous`: bundler 1.x loads the `Gemfile`, bundler ≥ 2 loads `gems.rb`, and nothing in the project says which bundler installs it; bundler 4's `BUNDLE_LOCKFILE` (environment, app config or global config) naming any other lock is refused with `redirect_gem_bundle_lockfile_unsupported`, as is vendoring with `gemfile_not_loaded`; spellings that diverge beyond Socket's own edits fail closed with `redirect_gem_gemfile_spellings_diverge`; `BUNDLE_GEMFILE` from `.bundle/config` (which outranks the environment, as in bundler), the environment, or the global `~/.bundle/config` / `$BUNDLE_USER_CONFIG` (lowest, as in bundler) is followed when it names the project's `Gemfile` / `gems.rb`, and any other configured manifest is refused with `redirect_gem_bundle_gemfile_unsupported`); a Bundler all-source, exact-source or hostname mirror in app config or the scan environment can capture the patch registry, so the redirect is refused with `redirect_gem_mirror_overrides_source` without printing mirror URLs (scope mirrors to `mirror.https://rubygems.org`; user-global config and mirrors set only in a later install environment are not inspected); the `CHECKSUMS` pin needs bundler ≥ 2.6 (an older lock is still pinned by source and installs frozen; the run says once, with `redirect_gem_no_checksums_section`, that it cannot record the checksums); a stale pre-redirect materialization that `bundle install` would reuse instead of refetching is replaced with the verified patched gem when it is the project's own, else flagged `redirect_gem_stale_install` with the remedy (see "Ruby gems: gems already installed" below and CLI_CONTRACT.md's "Gem stale-install guard"). In a Bazel workspace whose rules_ruby call holds the gem to another sha256 in `gem_checksums`, or has a `gem_checksums` that is not written out in the call, nothing is written for it (`redirect_bazel_gem_checksums_pinned`); see [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems) | | Go (`golang`) | ✅ `go.mod` `replace` → `.socket/go-patches/` — see [Go: directory replaces and go.sum](#go-directory-replaces-and-gosum) | ✅ `replace` → the committed vendor tree | ✅ (free tier) fork-style `replace` → `patch.socket.dev/gopatch/` + committed `go.sum` pin; see [Go notes](#go-directory-replaces-and-gosum). Paid hosted patches are unsupported; `redirect_golang_unsupported` names the vendored remedy | | Maven (`maven`) — Maven and Gradle | ✅ in place in every copy the build consumes: each `~/.m2` copy it reads and each Gradle `files-2.1` copy; `~/.m2` `.sha1`/`.md5` sidecars are rewritten, Gradle copies get advisories; jar-member records swap in the patch service's whole jar — prefer vendored / hosted, see [Maven & NuGet caveats](#maven--nuget-caveats) and [Gradle](#gradle) | ✅ suffixed Maven repository (`-socket.` pin + `.mvn/maven.config` + fallback file repository) for every pom root, single-module or reactor, or Gradle 6.8+ same-GAV repository with settings wiring and SHA-256 checks (a root with both `pom.xml` and a Gradle build wires both); see [JVM vendoring](design/maven-vendoring.md) and [Gradle](#gradle) | ✅ fail-closed by a Socket-only `-socket.` suffix: pom projects get a pinned `` (`${property}` versions are refused); Gradle 6.8+ builds get an owned settings script, lock-entry rewrites and a resolution tripwire — see [Maven & NuGet caveats](#maven--nuget-caveats) and [Gradle](#gradle) | | sbt / Mill / scala-cli (`maven`) | ✅ Coursier caches (sbt 1.3+, sbt 2, Mill, scala-cli) and Ivy caches (sbt 0.13–1.2, `useCoursier := false`) patched in place, Coursier checksum sidecars resynced — see [Scala build tools](#scala-build-tools-sbt-mill-scala-cli) | ✅ sbt 0.13.18+: generated `socket-patch-vendor.sbt` over the committed suffixed `.socket/vendor/maven2` tree; scala-cli directory builds: owned `socket-patch.scala` + same-GAV `.socket/vendor/coursier` tree (Linux / macOS); Mill: not wired (agent or hosted guidance) | ✅ sbt 0.13.18+: one generated `socket-patch.sbt`, gated on sbt's own `sbt update` records; Mill / scala-cli: paste-able snippets only (`redirect_mill_manual_snippet`, `redirect_scala_cli_manual_snippet`) | @@ -4192,7 +4192,7 @@ wire is skipped, neither file changes for it, and the warning says why and what | `redirect_gem_declaration_not_visible` | the lock lists it as a direct dependency, but it is declared where the scan cannot edit: an `eval_gemfile`d file, a loop, a gemspec. Declare it with a literal `gem ""` line in the Gemfile, in place of any other `gem` call that declares it (a gemspec's development dependency stays), or patch it with `--mode agent`. Vendored mode refuses it for the same reason. | | `redirect_gem_dependency_not_locked` | the Gemfile declares it and the lock's `DEPENDENCIES` does not list it. Run `bundle lock` and re-run. | | `redirect_gem_lock_unconvergeable` | the lock cannot be brought in line with the Gemfile: it has no `BUNDLED WITH` section to say which layout its Bundler accepts, or a Bundler < 2.2 lock lists its sources in an order the Gemfile's `source` lines do not explain. Run `bundle lock` with your current Bundler and re-run. Also a Gemfile with more than one top-level `source` line: Bundler 2.2 to 2.7 lock all its gems in one `GEM` section that names every source, which hosted mode does not rewrite, and `bundle lock` writes the same lock again. Keep the source that serves the gem as the one top-level `source` and move each other one into a `source "" do … end` block around the gems that come from it (Bundler's own deprecation warning asks for the same), then run `bundle lock` and re-run; or use `--mode agent`. A Bundler 2.2 release before 2.2.25 keeps the one section even then, so run that `bundle lock` with a later Bundler; the warning says so when the lock was written by one. | -| `redirect_gem_platform_unsupported` | the lock holds a platform-specific build of the gem (`nokogiri (1.18.10-x86_64-linux-gnu)`) that the patch has no patched build for. The warning names the builds the lock holds, the ones that are missing, and what the patch registry serves. See "Precompiled platform gems" below. | +| `redirect_gem_platform_unsupported` | the lock holds platform-specific builds of the gem (`nokogiri (1.18.10-x86_64-linux-gnu)`) and no one fix has a patch for every one of them. The warning names the builds the lock holds and says which of them have no patch, or which fix patches which. See "Precompiled platform gems" below. | `--mode agent` can still patch a gem hosted mode skips. `--mode vendored` can too, unless it refuses the gem itself (see "Ruby gems: gems vendored mode refuses"). @@ -4208,20 +4208,59 @@ gem, and the lock then has one entry per platform the project supports, usually racc (~> 1.4) ``` -For such a gem the patch registry serves a patched platform gem (a "prebuild") per platform: the -upstream platform gem with the patch's files replaced, under the same file name. When the patch -has a prebuild for every platform the lock names, the scan wires the gem like any other. The -Gemfile edit is the same, every platform entry moves to the patch registry's `GEM` section with -its dependency lines (and a plain `nokogiri (1.18.10)` entry beside them moves too), -`DEPENDENCIES` gains the `!`, and each `CHECKSUMS` entry takes the sha256 of its own prebuild. -`bundle install` then fetches the one patched platform gem of the machine it runs on and -compiles nothing, in frozen and deployment mode too. - -When the patch has no prebuild for one of the locked platforms, the gem is skipped with -`redirect_gem_platform_unsupported` and neither file changes: a machine of that platform would -otherwise be sent to a registry that has no gem for it. Remove the platform from the lock if the -project does not need it (`bundle lock --remove-platform `) and re-run, or wait for the -prebuild. +A fix for such a gem is one patch per gem: the patch of the ruby gem, and a patch for each +platform gem that was built from it. Each has its own patch UUID and its own record +(`pkg:gem/nokogiri@1.18.10?platform=arm64-darwin`). A platform gem's patch is the upstream +platform gem with the fix's files replaced, under the same file name. The patch registry of any +of those patches lists and serves every gem of the fix. + +When one fix has a patch for every build the lock names, the scan wires the gem like any other. +The Gemfile edit is the same, and its `source:` is the registry of the ruby gem's patch, whichever +platforms the lock names. Every platform entry moves to that registry's `GEM` section with its +dependency lines (and a plain `nokogiri (1.18.10)` entry beside them moves too), `DEPENDENCIES` +gains the `!`, and each `CHECKSUMS` entry takes the sha256 of its own platform's patched gem. +Before it writes, the scan reads what that registry lists for the gem (one small request per +such gem) and moves the gem only when the registry serves every locked build with the sha256 +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. + +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 +patch registry of a fix serves every gem of it, so the registry of the first locked build's +patch becomes the `source:`. The run says so with `redirect_gem_member_registry`, naming the +platform: that line of the Gemfile changes if that platform leaves the lock. A gem moved this +way stays on that registry when the ruby gem's patch turns up later, since the pair works as it +is. + +Adding a platform later is Bundler's own step: `bundle lock --add-platform ` resolves +the gem from its one source, the patch registry, and adds the entry of that platform's patched +gem with its checksum. The Gemfile does not change, and the next scan reports the new build +under its patch. + +The gem is skipped with `redirect_gem_platform_unsupported`, and neither file changes, when the +scan cannot move every locked build together: + +- a locked build has no usable patch: none is published for it yet, its patched gem is still + being built, or its patch was withdrawn. A machine of that platform would otherwise be sent to + a registry that has no gem for it; +- the locked builds are patched by different fixes and no one fix covers them all. Bundler takes + a gem from one source; +- the patch registry does not serve what the lock would pin, could not be read, or was not read + by the run. A gem is never pinned to a registry the run did not look at. + +The warning names the builds the lock holds and which of these is the case. Remove the platform +from the lock if the project does not need it (`bundle lock --remove-platform `) and +re-run, or wait for the patch. A lock that already takes the gem from a patch registry is left as +it is, and the warning then names the way back: `socket-patch rollback pkg:gem/@` +puts the gem on its upstream registry again. + +`socket-patch get --mode hosted` (or `--mode vendored`) for one patch of such a gem +takes the whole fix: the patch asked for, and the fix's patch for every other build the lock +names. **Undoing it.** `rollback` and `remove` take the option (or the added line) off again and restore the lock: the pair is the pre-scan pair byte for byte, with LF or CRLF line endings. @@ -4390,8 +4429,8 @@ How each mode gets the patched code running: | Mode | What happens | |---|---| -| Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed from the patched platform gem the registry serves for that platform, with nothing to compile; it is skipped with `redirect_gem_platform_unsupported` only while the patch has no patched build for one of the locked platforms. | -| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from prebuilt patched platform gems. The patch service builds one for each platform, and the vendored directory holds each of them unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. Every platform in the lock needs one. While the patch service has none for one of them the gem is skipped with `vendor_prebuilt_platform_pending`, which names the platforms that have none: the run does not fail, nothing is written, a patch that is already vendored stays in place, and a later run vendors the gem once every platform has one. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the prebuilt binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | +| Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed from the patched platform gem the registry serves for that platform, with nothing to compile; it is skipped with `redirect_gem_platform_unsupported` only while no one fix has a patch for every locked platform. | +| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from the patched platform gems of one fix. Each platform gem has a patch of its own, built from the patch of the ruby gem, and the vendored directory (named after that patch, so it does not move when the lock's platforms change; where that patch is not available to the run, after the patch of the first locked platform, and a gem already vendored stays in the directory it has) holds each of them unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The vendor ledger records each platform's tree with its own patch UUID and the checksums of the gem and gemspec it came from, `--json` reports one event per platform gem under its own patch (the summary lines count the gem as one package), and `vex` attests each platform gem by its own patch. Every platform in the lock needs a patch of that fix. While one of them has none the gem is skipped with `vendor_prebuilt_platform_pending`, which names each such platform and why (no patch on offer, a patched gem that is still being built, a patch of another fix): the run does not fail, nothing is written, a patch that is already vendored stays in place, and a later run vendors the gem once every platform has one. A gem that is already vendored this way and whose platforms no longer all have a patch is kept as committed (`vendor_gem_builds_kept`) while its trees still match the ledger. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the prebuilt binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again, which puts the gem back in the same directory. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | | Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, diff --git a/tests/nokogiri/nokogiri_e2e.rb b/tests/nokogiri/nokogiri_e2e.rb index a4340b60c..f53595e04 100644 --- a/tests/nokogiri/nokogiri_e2e.rb +++ b/tests/nokogiri/nokogiri_e2e.rb @@ -584,6 +584,14 @@ def delivered(mode) end + tail(stderr) rewritten = File.read(lock_path) check(rewritten != lock, "it rewires the lock", tail(stdout) + tail(stderr)) + # Each platform gem has a patch of its own: the run reports every + # locked platform under that patch. + reported = events(stdout).select { |e| %w[applied verified].include?(e["action"]) } + .map { |e| [e["purl"].to_s[/[?&]platform=([^&]+)/, 1], e["uuid"]] } + unreported = platforms.reject { |p| reported.include?([p, service.uuid_of(p)]) } + check(unreported.empty?, "it reports each platform gem under that platform's own patch", + "not reported: #{unreported.inspect} +#{reported.inspect}") if mode == "hosted" section = rewritten[/^GEM\n remote: #{Regexp.escape(service.index_url)}\n specs:\n((?: .*\n)+)/, 1].to_s missing = platforms.reject { |p| section.include?(" nokogiri (#{@version}-#{p})\n") } @@ -598,7 +606,13 @@ def delivered(mode) vendored = Dir.glob(File.join(@proj, ".socket", "vendor", "gem", "**", "*.gemspec")) check(vendored.size >= platforms.size, "a patched gem is vendored for each of #{platforms.size} platforms", vendored.inspect) - check(rewritten =~ /^PATH\n remote: \.socket\/vendor\/gem\//, "the lock takes nokogiri from the vendored path", rewritten) + check(rewritten =~ /^PATH\n remote: \.socket\/vendor\/gem\/#{Regexp.escape(service.uuid)}\//, + "the lock takes nokogiri from the vendored path of the fix's source patch", rewritten) + ledger = JSON.parse(File.read(File.join(@proj, ".socket", "vendor", "state.json"))) + built = ledger.fetch("entries", {}).values.flat_map { |entry| entry.fetch("gemBuilds", []) } + .map { |b| [b["platform"], b["uuid"]] } + check(built.sort == platforms.map { |p| [p, service.uuid_of(p)] }.sort, + "the ledger records each platform's tree with its own patch", built.inspect) # From here on nothing may need the patch service. service.take_down service.forget_requests diff --git a/tests/nokogiri/patch_service.rb b/tests/nokogiri/patch_service.rb index e33262d89..b94c3dcbf 100644 --- a/tests/nokogiri/patch_service.rb +++ b/tests/nokogiri/patch_service.rb @@ -12,6 +12,13 @@ # binaries were rebuilt on the service's side), so the client paths under # test are the same. # +# The shape is the service's: a fix is one patch per gem. The ruby gem's +# patch is the fix's source, and each platform gem has a patch of its own +# (its own uuid, its own record under `?platform=`, its own +# `tarball` and `gem-stub-gemspec`) that names the source in +# `rebuiltFromUuid`. The registry of any of those patches lists and serves +# every gem of the fix. +# # No gem dependencies, and nothing newer than Ruby 2.1 syntax: the file is # loaded on every leg, though its scenarios only run where nokogiri has # platform gems (Ruby 2.5 and later). @@ -30,7 +37,8 @@ class PatchService ORG = "nokogiri-e2e" TOKEN = "e2e-grant-token" - Built = Struct.new(:file, :token, :platform, :bytes, :sha256, :sri, :stub, :deps, :ruby, :rubygems) + Built = Struct.new(:file, :token, :platform, :bytes, :sha256, :sri, :stub, :deps, :ruby, :rubygems, + :uuid, :before, :after) attr_reader :uuid, :ghsa @@ -48,7 +56,7 @@ def initialize(name, version, platforms, uuid, ghsa, work, mark) @patch_routes_up = true FileUtils.mkdir_p(@work) @ruby_gem = repack(nil) - @prebuilds = platforms.sort.map { |platform| repack(platform) } + @platform_gems = platforms.sort.map { |platform| repack(platform) } @server = TCPServer.new("127.0.0.1", 0) @thread = Thread.new { loop { serve(@server.accept) } } end @@ -57,8 +65,18 @@ def url "http://127.0.0.1:#{@server.addr[1]}" end + # The registry of the fix's source patch (the ruby gem's): the one source + # a lock of platform gems takes for all of them. def index_url - "#{url}/patch-registry/gem/#{TOKEN}/#{@uuid}/" + registry_url(@uuid) + end + + # The uuid of the patch of the gem of `platform` (nil: the ruby gem's, + # the source). + def uuid_of(platform) + return @uuid if platform.nil? + hex = Digest::SHA256.hexdigest("#{@uuid}/#{platform}") + "#{hex[0, 8]}-#{hex[8, 4]}-4#{hex[13, 3]}-8#{hex[17, 3]}-#{hex[20, 12]}" end def stop @@ -86,7 +104,7 @@ def forget_requests end def sha256_of(platform) - (@prebuilds.find { |b| b.platform == platform } || @ruby_gem).sha256 + (@platform_gems.find { |b| b.platform == platform } || @ruby_gem).sha256 end private @@ -127,7 +145,7 @@ def repack(platform) Gem::Package::TarReader.new(io) { |tar| tar.each { |entry| members[entry.full_name] = entry.read } } end metadata_gz = members.fetch("metadata.gz") - data_gz = patched_data(members.fetch("data.tar.gz"), platform.nil?) + data_gz, before, after = patched_data(members.fetch("data.tar.gz")) sums = { "metadata.gz" => metadata_gz, "data.tar.gz" => data_gz } checksums = { "SHA256" => Hash[sums.map { |name, bytes| [name, Digest::SHA256.hexdigest(bytes)] }], @@ -145,7 +163,7 @@ def repack(platform) Built.new(file, platform ? "#{@version}-#{platform}" : @version, platform, bytes, Digest::SHA256.hexdigest(bytes), "sha512-" + [Digest::SHA512.digest(bytes)].pack("m0"), spec.to_ruby, deps, spec.required_ruby_version.as_list.join("&"), - spec.required_rubygems_version.as_list.join("&")) + spec.required_rubygems_version.as_list.join("&"), uuid_of(platform), before, after) end def gzip(bytes) @@ -158,10 +176,11 @@ def gzip(bytes) end # `data.tar.gz` with the mark appended to `lib/.rb`, every other - # entry as it was. `record`: remember that file's two contents, for the - # patch record the API serves. - def patched_data(data_gz, record) + # entry as it was, and that file's two contents, for the record of this + # gem's patch. + def patched_data(data_gz) target = "lib/#{@name}.rb" + before = after = nil out = StringIO.new("".b) Gem::Package::TarWriter.new(out) do |tar| Zlib::GzipReader.wrap(StringIO.new(data_gz)) do |plain| @@ -175,7 +194,7 @@ def patched_data(data_gz, record) elsif entry.file? bytes = entry.read || "".b if entry.full_name == target - @before, @after = bytes, bytes + @mark if record + before, after = bytes, bytes + @mark bytes += @mark end tar.add_file_simple(entry.full_name, mode, bytes.bytesize) { |io| io.write(bytes) } @@ -184,7 +203,7 @@ def patched_data(data_gz, record) end end end - gzip(out.string) + [gzip(out.string), before, after] end def git_sha256(bytes) @@ -198,9 +217,18 @@ def sri(bytes) # ---- the routes ---------------------------------------------------------- def all_gems - [@ruby_gem] + @prebuilds + [@ruby_gem] + @platform_gems end + def registry_path(uuid) + "/patch-registry/gem/#{TOKEN}/#{uuid}" + end + + def registry_url(uuid) + "#{url}#{registry_path(uuid)}/" + end + + # One line per gem of the fix, whichever patch's registry is asked. def info_body lines = all_gems.map do |g| "#{g.token} #{g.deps}|checksum:#{g.sha256},ruby:#{g.ruby},rubygems:#{g.rubygems}\n" @@ -212,8 +240,9 @@ def base_purl "pkg:gem/#{@name}@#{@version}" end - def patch_purl - "#{base_purl}?platform=ruby" + # The record key of `gem`'s patch: the gem's own purl. + def patch_purl(gem) + "#{base_purl}?platform=#{gem.platform || 'ruby'}" end def vulnerabilities @@ -221,35 +250,30 @@ def vulnerabilities "description" => "nokogiri end-to-end test" } } end - def artifact_url(leaf) - "#{url}/artifacts/#{@uuid}/#{leaf}" + def artifact_url(gem, leaf) + "#{url}/artifacts/#{gem.uuid}/#{leaf}" end - def package_result - artifacts = [{ "kind" => "tarball", "url" => artifact_url(@ruby_gem.file), - "contentType" => "application/octet-stream", "sizeBytes" => @ruby_gem.bytes.bytesize, - "integrity" => { "sha512" => @ruby_gem.sri, "sha256" => @ruby_gem.sha256 } }] - @prebuilds.each do |g| - stub_leaf = g.file.sub(/\.gem\z/, ".gemspec") - artifacts << { "kind" => "gem-platform", "platform" => g.platform, "url" => artifact_url(g.file), - "contentType" => "application/octet-stream", "sizeBytes" => g.bytes.bytesize, - "integrity" => { "sha512" => g.sri, "sha256" => g.sha256 } } - artifacts << { "kind" => "gem-platform-stub-gemspec", "platform" => g.platform, - "url" => artifact_url(stub_leaf), "contentType" => "text/plain", - "sizeBytes" => g.stub.bytesize, "integrity" => { "sha512" => sri(g.stub) } } - end + # The reference of `gem`'s patch: like any gem patch's, with the patch it + # was built from. + def package_result(gem) + stub_leaf = gem.file.sub(/\.gem\z/, ".gemspec") { "status" => "granted", - "url" => "#{url}/patch/gem/#{@name}/#{@version}/#{TOKEN}/#{@uuid}/#{@ruby_gem.file}", - "purl" => patch_purl, - "artifacts" => artifacts, + "url" => "#{url}/patch/gem/#{@name}/#{@version}/#{TOKEN}/#{gem.uuid}/#{gem.file}", + "purl" => patch_purl(gem), + "rebuiltFromUuid" => (gem.platform ? @uuid : nil), + "artifacts" => [ + { "kind" => "tarball", "url" => artifact_url(gem, gem.file), + "contentType" => "application/octet-stream", "sizeBytes" => gem.bytes.bytesize, + "integrity" => { "sha512" => gem.sri, "sha256" => gem.sha256 } }, + { "kind" => "gem-stub-gemspec", "url" => artifact_url(gem, stub_leaf), "contentType" => "text/plain", + "sizeBytes" => gem.stub.bytesize, "integrity" => { "sha512" => sri(gem.stub) } } + ], "registryOverride" => { "kind" => "rubygems-compact-index", - "indexUrl" => index_url, - "identifiers" => { - "name" => @name, "version" => @version, "gemChecksumSha256" => @ruby_gem.sha256, - "gemPlatforms" => @prebuilds.map { |g| { "platform" => g.platform, "gemChecksumSha256" => g.sha256 } } - } + "indexUrl" => registry_url(gem.uuid), + "identifiers" => { "name" => @name, "version" => @version, "gemChecksumSha256" => gem.sha256 } } } end @@ -258,31 +282,45 @@ def json(body) [200, "application/json", JSON.generate(body)] end - # status, content type, body of the answer to `verb path`. - def respond(verb, path) + # status, content type, body of the answer to `verb path` (`body`: the + # request's). + def respond(verb, path, body) api = "/v0/orgs/#{ORG}/patches" - registry = "/patch-registry/gem/#{TOKEN}/#{@uuid}" if verb == "POST" && path == "#{api}/batch" - return json("packages" => [{ "purl" => base_purl, "patches" => [{ - "uuid" => @uuid, "purl" => patch_purl, "tier" => "free", "cveIds" => [], - "ghsaIds" => [@ghsa], "severity" => "high", "title" => "nokogiri end-to-end test" - }] }], "canAccessPaidPatches" => false) + patches = all_gems.map do |g| + { "uuid" => g.uuid, "purl" => patch_purl(g), "tier" => "free", "cveIds" => [], + "ghsaIds" => [@ghsa], "severity" => "high", "title" => "nokogiri end-to-end test" } + end + return json("packages" => [{ "purl" => base_purl, "patches" => patches }], "canAccessPaidPatches" => false) elsif path.start_with?("#{api}/by-package/") - return json("patches" => [{ "uuid" => @uuid, "purl" => patch_purl, - "publishedAt" => "2026-02-01T00:00:00Z", "description" => "nokogiri end-to-end test", - "license" => "MIT", "tier" => "free", "vulnerabilities" => vulnerabilities }], - "canAccessPaidPatches" => false) - elsif path == "#{api}/view/#{@uuid}" - return json("uuid" => @uuid, "purl" => patch_purl, "publishedAt" => "2026-02-01T00:00:00Z", - "files" => { "lib/#{@name}.rb" => { "beforeHash" => git_sha256(@before), - "afterHash" => git_sha256(@after) } }, + patches = all_gems.map do |g| + { "uuid" => g.uuid, "purl" => patch_purl(g), "publishedAt" => "2026-02-01T00:00:00Z", + "description" => "nokogiri end-to-end test", "license" => "MIT", "tier" => "free", + "vulnerabilities" => vulnerabilities } + end + return json("patches" => patches, "canAccessPaidPatches" => false) + elsif path.start_with?("#{api}/view/") + gem = all_gems.find { |g| path == "#{api}/view/#{g.uuid}" } + return [404, "text/plain", ""] unless gem + return json("uuid" => gem.uuid, "purl" => patch_purl(gem), "publishedAt" => "2026-02-01T00:00:00Z", + "files" => { "lib/#{@name}.rb" => { "beforeHash" => git_sha256(gem.before), + "afterHash" => git_sha256(gem.after) } }, "vulnerabilities" => vulnerabilities, "description" => "nokogiri end-to-end test", "license" => "MIT", "tier" => "free") elsif verb == "POST" && path == "#{api}/package" - return json("results" => { @uuid => package_result }) + asked = begin + JSON.parse(body.to_s).fetch("uuids", []) + rescue JSON::ParserError + [] + end + results = {} + all_gems.each { |g| results[g.uuid] = package_result(g) if asked.include?(g.uuid) } + return json("results" => results) end - serves_patch = path.start_with?(registry) || path.start_with?("/artifacts/") || path.start_with?("/patch/") + # Any patch of the fix answers for all of its gems. + registry = all_gems.map { |g| registry_path(g.uuid) }.find { |prefix| path.start_with?(prefix) } + serves_patch = registry || path.start_with?("/artifacts/") || path.start_with?("/patch/") return [404, "text/plain", ""] unless serves_patch return [503, "text/plain", ""] unless @lock.synchronize { @patch_routes_up } @@ -296,7 +334,7 @@ def respond(verb, path) else leaf = File.basename(path) gem = all_gems.find { |g| g.file == leaf } - stub = @prebuilds.find { |g| g.file.sub(/\.gem\z/, ".gemspec") == leaf } + stub = all_gems.find { |g| g.file.sub(/\.gem\z/, ".gemspec") == leaf } if gem then [200, "application/octet-stream", gem.bytes] elsif stub then [200, "text/plain", stub.stub] else [404, "text/plain", ""] @@ -313,9 +351,9 @@ def serve(socket) key, value = header.split(":", 2) length = value.to_i if key.casecmp("content-length").zero? end - socket.read(length) if length > 0 + sent = length > 0 ? socket.read(length) : "" path = target.to_s.split("?").first - status, type, body = respond(verb, path) + status, type, body = respond(verb, path, sent) @lock.synchronize { @requests << [verb, path, status] } reason = { 200 => "OK", 404 => "Not Found", 503 => "Service Unavailable" }.fetch(status) socket.write("HTTP/1.1 #{status} #{reason}\r\nContent-Type: #{type}\r\n" \