diff --git a/.github/workflows/nokogiri-compatibility.yml b/.github/workflows/nokogiri-compatibility.yml index 1aba3f0f90..6bf6256524 100644 --- a/.github/workflows/nokogiri-compatibility.yml +++ b/.github/workflows/nokogiri-compatibility.yml @@ -54,16 +54,24 @@ 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`. +# patch service (tests/nokogiri/patch_service.rb) whose registry lists every +# locked platform gem: a patched build of the real one, under a patch of its +# own, or upstream's own gem behind a redirect while the platform has no +# patched build; then a frozen install from a fresh checkout, `vex` and a +# byte-identical `rollback`. On JRuby the platform is `java`. In the `passed +# through` legs one locked platform has no patched build at first: the +# runner's own, so that the frozen install gets upstream's gem through the +# redirect, or another one. Once the service has that build, the next scan +# moves the lock to the newer registry snapshot. # # 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, which serves a patched build of each real platform gem from that +# platform's own patch; 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`. In the `passed through` leg one locked +# platform has no patched build at first: nothing is vendored and the run +# succeeds, and the scan after the service has that build vendors the gem. # # Every leg downloads gems from rubygems.org, and a rebuild of a precompiled # install downloads the source gem and `mini_portile2` from it too. @@ -184,6 +192,16 @@ jobs: - {os: ubuntu-latest, ruby: '3.1', nokogiri: '1.15.7', install: precompiled, args: '--scenarios hosted', note: hosted} - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, cli: build, args: '--scenarios hosted', note: hosted} - {os: ubuntu-latest, ruby: 'jruby-9.4', nokogiri: '1.18.10', install: java, args: '--scenarios hosted', note: hosted} + # The same with one locked platform that has no patched build at + # first, so that the registry lists upstream's own gem for it and + # answers its file with a redirect. `own` is the runner's + # platform: the frozen install gets upstream's gem through the + # redirect, then the patched gem once the build is there. + # `others` is every other locked platform, which nothing here + # installs (`--add-platform` locks one where Bundler locks the + # runner's alone). + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, args: '--scenarios hosted --add-platform aarch64-linux-gnu --pass-through own', note: 'hosted, own platform passed through'} + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, args: '--scenarios hosted --add-platform aarch64-linux-gnu --pass-through others', note: 'hosted, another platform passed through'} # Vendored mode on a lock that pins nokogiri as platform gems: the # scan commits a patched build of each real platform gem, served # by a stand-in for the patch service, under `.socket/vendor/gem`, @@ -194,6 +212,15 @@ jobs: - {os: ubuntu-latest, ruby: '3.1', nokogiri: '1.15.7', install: precompiled, args: '--scenarios vendored', note: vendored} - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, cli: build, args: '--scenarios vendored', note: vendored} - {os: ubuntu-latest, ruby: 'jruby-9.4', nokogiri: '1.18.10', install: java, args: '--scenarios vendored', note: vendored} + # The same with a locked platform that has no patched build at + # first: the scan commits upstream's own gem for it, which the + # stand-in's registry serves, beside the patched build of the + # other, and the next scan takes the patched build once the + # service has it. `own` is the runner's platform: the frozen + # install loads upstream's nokogiri from the committed tree, then + # the patched one. + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, args: '--scenarios vendored --add-platform aarch64-linux-gnu --pass-through others', note: 'vendored, another platform passed through'} + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, args: '--scenarios vendored --add-platform aarch64-linux-gnu --pass-through own', note: 'vendored, own platform passed through'} needs: static-cli runs-on: ${{ vars.DISABLE_DEPOT_RUNNERS != 'true' && matrix.os == 'ubuntu-latest' && 'depot-ubuntu-24.04-4' || matrix.os }} timeout-minutes: 60 diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 147fed6cc7..eb5af7a2a2 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -468,7 +468,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)`. Its fix is still the one patch of the gem. That patch's package reference lists every gem of the version under `registryOverride.identifiers.gemBuilds`, `{platform, gemChecksumSha256, patchUuid}` each: the ruby gem (`platform: "ruby"`, the patch itself), each patched platform gem with the uuid of its own patch (the upstream platform gem's name, gemspec and file list, with the patch's files replaced), and each platform with no patched build with `patchUuid: null`, for which the patch registry lists upstream's own gem and relays its file from the upstream registry (a redirect to it is followed too). The list is asked for: every package reference request carries `"gemBuilds": true`, and the patch service answers a request without it with the ruby gem's registry alone. A request about a patch whose registry the project's lock takes the gem from, at a snapshot (`/s//`), also presents that key: `"gemSnapshotKeys": { "": "" }`, left out of a request with none to present. The key is the snapshot level of the remote in the one lock a run rewrites, lowercase hexadecimal digits. That lock is the one of the pair Bundler loads, which is the pair the rewriter is given: `gems.locked` for a `gems.rb` project (an orphan `Gemfile.lock` beside it is not read), `Gemfile.lock` otherwise, and the pair `BUNDLE_GEMFILE` names where both spellings are present. A twin that nothing settles presents no key, and neither of its pairs is rewritten. The key is an argument of every reference call (`PatchApi::fetch_registry_references`). The in-memory engine reads it from each root's own lock and asks about a patch once for each snapshot of it that a root names, and once for all the roots that name none: a request names a patch once, the requests of a run are sent together (as many at a time as the host allows), and each root is answered what a checkout of it alone would be. It hands the host's provider the request as the v0 API's body, `{ "uuids": […], "gemBuilds": true, "gemSnapshotKeys": {…} }`, the last left out when there is none. A provider that builds its own body from `uuids` gets references with no list, and a lock of platform builds is then left alone (`redirect_gem_platform_unsupported`). The patch service reads a key only while a gem that patch's registry lists is being built again. The registry lists such a gem with the sha256 it last built, so its key does not change for the length of the rebuild. A request that presents the registry's own key is then answered the registry as it stands. So a lock that is on the patch stays there through the rebuild, byte for byte: a scan reports the gem as already on its patch, and `vex` attests its builds as before. A request that presents another key (the lock is on an earlier snapshot of the patch: since then another build landed with other bytes, or one was withdrawn) is told the patch is not ready (`pending_build`: `the hosted artifact is still being built; re-run later`, the pair untouched, exit 0), and the first run after the rebuild moves the lock once. So a build that is being rebuilt is never taken for a withdrawn one: a locked build goes back to upstream's sha256 only on an answer that lists upstream's gem for it, and the service gives none for a registry it is still building a gem of. A request with no key is answered as a client that asks for no list is, with the registry of the ruby gem alone: a lock that names the gem as its ruby gem alone is left as it is and reported as on its patch, and a project whose lock names platform builds and is not on the patch yet is left on its upstream registry (`redirect_gem_platform_unsupported`) until a run after the rebuild. While the gem's own patch is rebuilt, a request with no key is `pending_build` as well. Outside a rebuild the key changes no answer. With a list, the index URL names the registry as it stood, `/s//` (a key of lowercase hexadecimal digits that the patch service chooses and that changes when what the registry lists changes; it is never read for a meaning); the URL is recognised with any key or none, under any grant token, and written closed by a slash, as Bundler writes a remote. The URL with its snapshot level is written only for a gem the lock names at least one platform build of. For a gem the lock names as its ruby-platform gem alone the registry root WITHOUT that level is written (`/`, which lists the patched gem and nothing else), as release 5.1.0 writes it: the key changes whenever a platform build is published, and under a URL with a key a lock that names only the plain entry could install the local platform's own gem, which may be upstream's. A pair that 5.1.0 pinned is left byte for byte. **The gem moves as soon as ONE build the lock names is patched** (a platform with a `patchUuid`, or the ruby-platform entry): the manifest edit is the same as for any gem, 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 the list gives for its build (for a platform with no patched build that is the upstream gem's, which the entry already had); a lock with no `CHECKSUMS` section gets none. A frozen `bundle install` of that pair fetches the one gem of the machine through the patch registry, compiles nothing and leaves the lock byte-identical (verified on Bundler 4.0.15, frozen, deployment and unfrozen, and a `bundle lock` afterwards changes nothing): a machine of a patched platform installs the patched gem, any other installs what it installed before. No warning is given. Human output has one line per such gem, `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)` (a ruby-platform entry is named `ruby`; a dry run says `would be patched for`; on a terminal a line that does not fit breaks after a clause), and `--json` has one counted `applied` event (`verified` on a dry run) per patched build: `purl` `pkg:gem/@?platform=` (the gem's own purl for the ruby-platform entry), `uuid` that build's patch, `details.gemFix` the gem's patch, `details.platform`, and `details.newlyPatched: true` when this run put the build in place. That is told from the lock's `CHECKSUMS` entry where the build has one. A build with none (a lock with no `CHECKSUMS` section) is told from the registry: a run that moves the lock from one snapshot of the patch to another asks the snapshot the lock names what it lists (ONE request, `/info/`; that snapshot keeps answering as it did), and a build listed there under another sha256 than the patched one the reference gives is newly patched, one under the same sha256 was in place. The request is made only where it can decide something: the lock is on the selected patch's own registry under another snapshot than the reference names, and a locked platform build the reference lists as patched has no `CHECKSUMS` entry. Where the listing cannot be read (the request fails, the document lists no build of the version, it does not list the build, or the build's line names no sha256), the build is not marked new and the run succeeds, with no warning. A build on upstream's gem is an event that is NOT counted in `summary`: `action: "skipped"`, no `uuid`, `errorCode: "gem_upstream_build_kept"`, `details.gemFix`, `details.platform`, and `details.withdrawn: true` where this run put the build back on upstream's gem because its patched build was withdrawn ("Later runs" below). Every count of packages (the human totals, the rollout budget, the severity floor) takes the gem as one package with one patch, and only while one of its locked builds is patched: a gem whose locked builds are all served as upstream's own gem is no package on a hosted patch (no `applied` event, not in the summary line or the telemetry). While a locked build keeps upstream's gem the scan's closing lines say `Not patched yet: nokogiri 1.18.10 for arm64-darwin.` in place of `Nothing left to patch.` (for several gems `Not patched yet: 3 builds of nokogiri 1.18.10, ffi 1.17.2.`, then `Not patched yet: 12 builds of 7 gems.`). **VEX** is per build. The run's own `--vex` attests each patched build under its own patch (`not_affected`, subcomponent `pkg:gem/@?platform=`, impact `Patched via Socket patch (redirected)`; the ruby-platform entry under the gem's patch) and writes an `affected` statement for a build on upstream's gem, whose action statement says that the platform has no patched build yet; it needs no request beyond the run's own, except the record of each patched build that has an installed copy (one request per such build, below). A later `socket-patch vex` on such a lock asks, beyond the record of each hosted patch that has no local record (`view/`, one request per patch, as for a hosted patch of any ecosystem): ONE package reference request for all such gems of the run together (for `gemBuilds`; in batches of at most 500 patches), and, per gem and only for a lock with no `CHECKSUMS` entry for one of its platform builds, one `info/` of the lock's own registry URL. So one such gem costs two requests on a lock with `CHECKSUMS` and three on one without, and N of them N + 1 and at most 2N + 1. Each patched platform build that has an installed copy costs one more, for the record of that build's own patch, which its files are checked against (see `vex_gem_build_unknown`). A build is attested by its patch only when the sha256 the lock installs for it (its `CHECKSUMS` entry, else what the lock's registry lists) is that patch's; it is `affected` when that sha256 is the one listed for upstream's gem; and when neither can be shown (the reference lists another archive than the lock pins, the request failed, or `--offline` with a local record) the build is stated as `affected` too, with an action statement that says why it could not be shown and what settles it (`socket-patch scan --mode hosted` for a lock older than the list, `vex` again, or `vex` without `--offline`), under the warning `vex_gem_build_unknown`; no patch uuid is ever named for it, and the run stays a success (exit 0). A gem locked as its ruby-platform gem alone costs no extra request. `vex` prints the gem's line under its summary (`…: patched for x86_64-linux-gnu; not shown patched for arm64-darwin`), and its `--json` events of builds carry `details.gemFix` and `details.platform` (a build stated as `affected` is an event that `summary` does not count, with `errorCode` `gem_upstream_build_kept` or `vex_gem_build_unknown`). **Later runs**: the same reference changes nothing. A reference with another key (a patched build was published for another platform, or one was withdrawn) refreshes the URL in both files and rewrites the checksums that changed, and the line names what is new: `nokogiri 1.18.10: now also patched for arm64-darwin; already patched for x86_64-linux-gnu`. A platform added with `bundle lock --add-platform` is resolved by Bundler from the registry and reported by the next run. A lock already on the registry follows the reference even when no locked build is patched any more: a withdrawn build's entry goes back to the upstream gem's sha256, and the stale-install guard below replaces a copy a machine installed from the withdrawn build with upstream's gem. The run that puts the entry back says so in the gem's line, `nokogiri 1.18.10: patched for arm64-darwin; upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)` (a dry run says `would be back for`), and in that build's event (`details.withdrawn: true`, `reason` `… its patched build was withdrawn`); a later run finds upstream's sha256 pinned and says `upstream gem kept for …` again. It is told from the lock's `CHECKSUMS` entry (the entry pinned another sha256 than upstream's from a patch registry of the gem). A build with no entry is told from the listing of the registry the lock is on, where the run read it for another reason (to tell which builds are new, above, or for a lock on another patch's registry, below): the listing leaves the build out, or has it under another sha256 than upstream's. That alone causes no request, so a lock with no `CHECKSUMS` section whose run read no listing keeps the `upstream gem kept for …` wording. **Three cases leave the gem as it is, quietly** (one counted `skipped` event with the code, one plain line on stdout, no warning, exit 0). No build the lock names is patched yet (`redirect_gem_no_patched_build`: `nokogiri 1.18.10: no patched build yet for arm64-darwin, x86_64-linux-gnu; left on its upstream registry`). The list leaves out a platform the lock names (`redirect_gem_platform_unlisted`: `nokogiri 1.18.10: the patch registry does not list arm64-darwin, so the gem is left as it is`; for a lock that takes the gem from the registry of another patch, `nokogiri 1.18.10: the newer fix's registry does not list arm64-darwin; the lock stays on the patch it is on`): the patch service lists every platform gem upstream publishes, so a platform the list leaves out is one upstream does not publish (a private build, a yanked platform gem), and the line says only what is known. Known limit: a lock that is already on the patch gets the same outcome when upstream stops publishing a platform gem it names. The gem is reported `redirect_gem_platform_unlisted` on each scan and left as it is, and `vex` states that platform's build `affected` with the remedy (`bundle lock --remove-platform`). It is not handled further: that platform's gem can no longer be installed from upstream either, so the lock is broken there as well. And **a run never turns a build that is patched today into upstream's gem**: a lock that takes the gem from the registry of ANOTHER patch (an earlier fix) is not moved to the selected patch while that patch's list serves upstream's gem for a build the lock's own registry still serves patched (`redirect_gem_newer_fix_waits`: `nokogiri 1.18.10: the newer fix has no patched build for x86_64-linux-gnu yet; the lock stays on the patch it is on`). "Patched today" is what the registry the lock is on serves, not what the lock pins: a patched build that was withdrawn is no longer listed under the snapshot the lock names and its file is refused, so a fresh `bundle install` fails on that platform and staying would keep it failing. So wherever the move would put a build on upstream's gem that the lock does not already pin at upstream's sha256, the run reads the lock's own registry, with a `CHECKSUMS` section or without (ONE request per such gem, `/info/`). A build is patched today when that registry lists it under the sha256 the lock's `CHECKSUMS` pins, or, for a lock with no entry for it, under a sha256 that is not the upstream one the selected list gives. A build the registry does not list, or lists under another sha256 than the lock pins, holds nothing back. **When no build is left to lose the lock moves to the selected patch**, also when that patch has no patched build for any platform the lock names (a lock on a patch registry is never left on one that refuses a build it pins; `redirect_gem_no_patched_build` is for a lock on its upstream registry only): every entry takes the sha256 the selected list gives, the withdrawn build's goes back to upstream's, the line says `upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)` (as under "Later runs"), and the stale-install guard replaces an installed copy of the withdrawn build with upstream's gem. When the registry's answer cannot be read (the request fails, the document lists no build of the version, or the build's line names no sha256) nothing is shown either way, and the lock stays. Under `--patch-mirror-url` that request goes to the patch server, as the run's other registry reads do. **A lock that stays is brought to its own patch's current listing when one of its builds was withdrawn.** In both of these cases the lock stays on the earlier patch, and that patch may have withdrawn a build the lock pins, which then no longer installs. So the run reads what the lock's registry lists in the second case as well as in the third (the same ONE request per gem, `/info/`, made on every run while the lock stays for that reason), and where that listing shows a locked platform build as withdrawn (it does not list the build, or, for a build with a `CHECKSUMS` entry, lists it under another sha256 than the lock pins) the run takes the package reference of the patch the lock is on (its uuid is the patch level of the lock's remote) and follows it as a lock on a patch's own registry follows any later reference of that patch: the URL goes to that patch's current snapshot in both files, the withdrawn build's entry goes back to upstream's sha256, every build that patch still serves patched keeps its entry, and the stale-install guard replaces an installed copy of the withdrawn build with upstream's gem. The selected patch is skipped as before. A `scan` already holds that reference (it asks about every pin the lockfiles hold, to find withdrawn patches) and makes no further request; `get`, and a scan whose check did not cover the pin, make ONE request for it, only when a withdrawal was detected while the lock stays. Human output has the earlier patch's line and the skip's line under it (`nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem back for arm64-darwin (its patched build was withdrawn)`, then `nokogiri 1.18.10: the newer fix has no patched build for x86_64-linux-gnu yet; the lock stays on the patch it is on`); `--json` has the earlier patch's builds (`applied` for each in effect, with `details.gemFix` that patch and no `newlyPatched`; the uncounted `gem_upstream_build_kept` with `details.withdrawn: true` for the one put back) beside the selected patch's counted `skipped` event; `status: "success"`, exit 0, no warning beyond the guard's own. A run over the result changes nothing and asks for no reference. The uuid is read from a file anyone can edit, so it only names which reference to ask for: the answer passes the checks every grant passes, and must be of the same gem and patch, on the registry the lock is on, with a list that names every locked platform. Any other answer (not granted, withdrawn, pending, no list, a list that leaves a locked platform out, another package, a failed request) leaves the pair byte for byte, with the skip alone. A lock written under `--patch-mirror-url` is left as it is too. A lock on the selected patch's own registry follows its list (a withdrawn build goes back to upstream's gem), and a patch that is itself withdrawn is unwound by the withdrawn-patch restore before any of this. The gem is skipped with the warning `redirect_gem_platform_unsupported` only when the reference carries no list of the version's gems, or for a platform build in the merged layout of Bundler < 2.2. A reference carries no list when the patch service has not read the version's platform gems yet, when upstream publishes none, when the request did not ask for one (a host's own request body), and, for a request that presents no snapshot, while a gem of the patch's registry is being built again. In each case the lock is left as it is. A lock that names platform builds is never moved to the registry of the ruby gem alone, which serves none of them; only a lock that names the gem as its ruby gem alone takes that registry. The patch service also has a patch record per patched platform gem (`pkg:gem/@?platform=`), which agent mode applies to an installed copy of that platform; a hosted or a vendored `scan` or `get ` never selects one as a fix of its own. `get ` of such a patch in hosted or vendored mode takes the gem's patch it was built from (`rebuiltFromUuid` on that patch's package reference: one extra reference request, for this case only) and goes on as `get ` does, with one line on stderr (` is the patch of nokogiri 1.18.10's x86_64-linux-gnu build; hosted mode takes the gem's patch , which it was built from`) and, under `--json`, a top-level `platformGemPatch` object (`uuid`, `purl`, `platform`, `gemFix`). Where the reference names no such patch, hosted mode skips the patch with the warning `platform_gem_patch_not_taken` and vendored mode refuses it with `platform_gem_unsupported`, both naming the command to run instead (`socket-patch get pkg:gem/@ --mode `). Agent mode applies the platform gem's own patch to the installed copy of that platform, as before. 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` (locked platform builds of a gem whose reference carries no list of the version's gems, or a platform build in the merged layout of Bundler < 2.2; 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. @@ -489,10 +489,12 @@ 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, or a patched platform gem's sha256 from `gemBuilds`) is already patched and never warns, any other readable archive is stale, and a missing or unreadable one is never evidence by itself. A build the patch registry serves as upstream's own gem (`patchUuid: null`) is judged by its archive too, against the sha256 the list gives for that platform: the upstream gem is what that platform installs, so a copy whose archive is it is current and nothing is said, downloaded or changed. Any other readable archive is a patched build that was withdrawn since (a `bundle install` keeps an installed gem, so it would stay loaded): the installed copy, and a committed cache-dir archive, are replaced with upstream's gem, downloaded through the patch registry (`/gems/.gem`, which the registry relays) and verified against the listed sha256 before any byte is used. It is reported with the guard's own codes, worded for a withdrawn build: `redirect_gem_install_refreshed` (`replaced the withdrawn install at with the upstream gem`; human `Replaced the installed copy of 1 gem with the upstream build (its patched build was withdrawn): .`), `redirect_gem_install_would_refresh` on a dry run, and `redirect_gem_stale_install` where it could not be replaced (`--no-gem-install-refresh`, a shared gem home, a download or checksum failure), whose detail names the files to remove before `bundle install`. A copy whose gem home keeps no archive of it is not judged: a machine that installed a build withdrawn since and no longer has its `.gem` under `/cache/` keeps loading that copy until the gem is reinstalled there, and no request is made to find out. 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. +- A platform build that has a patch of its own (the gem patch's listing names one for it) is a patch of its own: its files carry that patch's header and, for a compiled build, its binaries, so they are never the files of the gem's patch. Its copy is judged by the archive RubyGems installed it from (`/cache/.gem`), by its sha256 alone: the one the lock is pinned to for that build is the patched build, and any other readable archive is another gem than the lock pins. The guard does not compare the installed files with the archive. With no archive (a pruned `cache/`, `gem cleanup`) the record of that build's own patch judges it (`…/patches/view/?include_blobs=false`, asked without the file contents where the API leaves them out, one request per such build). It is never judged by the gem patch's record, the agent-mode one included. With neither an archive nor that record the copy is unjudged: not stale, not replaced, and withheld from the same run's `--vex`. +- One lock has Bundler load a build it does not name. A lock whose `PLATFORMS` section names `ruby` and nothing else names every gem as its ruby-platform gem, and for it Bundler takes, among the installed gems of the locked version, the one that fits the machine best: an installed precompiled build (`--`), which is what an install from the upstream registry left there. So under such a lock each precompiled build of the version that a gem home lists (a `specifications` entry; a gem directory without one is what an install left behind, and nothing loads it) is judged beside the ruby-platform gem, as the gem's own copy. A stale one is reported and never replaced: the patched gem of such a lock is the ruby-platform gem (the lock takes it from the patch's registry without the snapshot level, which lists that gem alone), and installing it means building it. No gem is downloaded for the copy. A lock that names any other platform installs and loads exactly the gems it lists, so there a build the lock does not name stays out, as above. - When several confirmed variant purls resolve to one installed dir, ANY of them judging it patched keeps it quiet. - Staleness needs **positive evidence** — bytes actually read that are not the patched state — so missing or unreadable files never mark a copy stale. - A committed cache-dir archive whose sha256 is readable and differs from the patched artifact's is stale by itself, even with no installed dir at all (a fresh checkout with a committed stale cache). That covers the ruby gem's `-.gem` and each platform build's `--.gem`. @@ -501,8 +503,8 @@ The rewriter reads a fixed set of candidate files from the project root: the npm *The refresh* (default; `--no-gem-install-refresh`, env `SOCKET_NO_GEM_INSTALL_REFRESH`, turns it off). - **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. +- **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. A precompiled build that Bundler loads in place of the ruby-platform gem a ruby-only lock names (see "How a copy is judged") is not refreshed under any flag: its warning gives the reason (`it is a precompiled gem, which Bundler loads in place of the ruby gem the lock names, and the patched gem of this lock is the ruby gem, which \`bundle install\` builds`) and the command (`rm -f && bundle install`), after which Bundler installs the patched ruby-platform gem from the patch registry and builds its extension. No re-run is offered for it, since a re-run does the same. +- **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 (`gemBuilds`); 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. @@ -515,13 +517,14 @@ The rewriter reads a fixed set of candidate files from the project root: the npm - Each refreshed materialization is a `redirect_gem_install_refreshed` note in the JSON `warnings[]`; a human run prints one progress line per kind instead (`Replaced the installed copy of 2 gems with the patched build: …`). A replaced cache-dir archive is listed with the files to commit. - Each materialization that is still stale is a `redirect_gem_stale_install` warning in the JSON `warnings[]`, in three flavors: an installed copy in a SHARED gem home (left alone; the remedy is the project-local bundle path, `bundle config set --local path vendor/bundle && bundle install`, which installs every gem of the project from the lock's sources and leaves the shared home untouched, or `--gem-refresh-shared`; no delete list for a copy that was only left alone); a PROJECT-LOCAL installed copy the refresh did not fix (the reason — the archive could not be downloaded or verified, a native build failed, the path is outside the project, the refresh is turned off — and the files to remove by hand, including the project's stale cache-dir archive when there is one; where `bundle install` would not replace the copy, the list starts with the gem directory itself, holds only the files that are still there, and the human warning's command is `rm -rf … && bundle install`: after a refresh that was tried and failed, a copy whose native extension a Ruby the run asked builds into another gem home (one in the tree of an earlier Ruby, `vendor/bundle/ruby/3.2.0`), for which the re-run named is one "with the Ruby that installed the gem first on `PATH`", and a gem directory whose gemspec is gone, for which no re-run is named; and, after a refresh that was turned off or failed for any other reason, a copy (not a default gem's) whose gem home has another Ruby's beside it (`vendor/bundle/ruby/3.2.0` next to `ruby/3.3.0`), with the re-run that reason has otherwise); and a cache-dir archive alone. An installed copy that agent mode patched in place (stale by its upstream archive only, see above) gets the first two flavors in its own words: the detail names the archive and what a reinstall from it does, the delete list is that archive alone (never the `specifications` entry), and it never calls the install unpatched. Its refresh note reads `replaced the upstream archive of the install patched in place at …`, and the human progress line `Replaced the upstream archive beside 1 gem patched in place with the patched gem: …`; that archive is not a file to commit. The warning re-fires on every re-scan until the stale materialization is gone. - A human run prints ONE warning for all of them: how many gems, which gems in which gem home (or why they were not refreshed), why in one sentence, and the remedy as a command. Its headline is `N gems are still unpatched on disk after the switch to hosted patches` when none of the gems it covers was patched in place; when every one was, `N gems patched in place still have their upstream archives on disk after the switch to hosted patches`; and with both kinds, `N gems still have unpatched files or archives on disk after the switch to hosted patches`. +- While a gem is still stale after the run, the scan's closing lines do not say `Nothing left to patch.`: they say `1 gem is still unpatched on disk: the warning names the command that installs the patched gem.` (`N gems are still unpatched on disk: … the patched gems.`). - A stale-flagged purl is additionally **excluded from the same run's `--vex` `assume_applied` set** — the envelope must never attest a CVE its own warning says is live; the purl falls back to normal installed-tree verification (a patched install still attests, a stale one is omitted). A same-run `--vex` may still fail on "nothing to attest" per the embedded-VEX contract. *The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk; a remote `SOCKET_RUBYGEMS_URL` names is the registry, not another remote). The registry is never asked about a gem the lock resolves from another remote: an archive of such a gem in Bundler's cache dir, under a lock with no `CHECKSUMS` entry for it, is named by `upstream_gem_stale_cache` as one that could not be checked. An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive. Only copies of the builds the restored lock names are judged, each under its own leaf (the ruby-platform gem alone when the lock cannot be read): a platform build the restored lock names (`nokogiri (1.18.10-arm64-darwin)`) is judged and refreshed against that build's own upstream sha256 (its `CHECKSUMS` entry, else the compact index's `-` line) and from `/gems/--.gem`; so is its archive in bundler's cache dir. A copy whose gem home has no readable archive of it (a pruned `cache/`: Bundler 4.1's `prune` setting, a slim image, `gem cleanup`) is judged as the scan direction judges it (#2092): the unwind fetches the record of each patch the gem was pinned to (`…/patches/view/`, for that gem only, through the run's API client) and the copy is stale when every file a record lists hashes to its `afterHash`. Each such copy is judged on its own files, and it is then replaced from the upstream archive like any other; no `cache/` dir is created for it. When no record proves the copy patched and one of them could not judge it (`--offline`, a failed fetch, a patch the API has no record of, record files missing from the copy), nothing tells it from the patched build: it is left as it is and reported under `upstream_gem_stale_install` as one that could not be checked, with that reason and the files to remove. After a request the API does not answer (a network error), no other record is asked for. Such a copy is judged the same way when nothing proves the upstream sha256 (a lock without `CHECKSUMS`, with `--offline` or a registry error): one proven patched is then reported as left on the patched build, since there is no verified archive to replace it with. So is a copy whose gem home does hold an archive, when nothing gives the upstream sha256 to check that archive against (a lock without `CHECKSUMS` that resolves the gem from another remote, or `--offline` or a registry error): the archive says nothing, so the pinned patch records judge the copy's files, a copy proven patched is reported as left on the patched build, and one no record could judge is reported as one that could not be checked ("nothing gives the sha256 of its upstream gem and …"). An unwind with no such copy fetches no patch record. Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. A copy left alone in a SHARED gem home gets no re-run either (#2086): `--gem-refresh-shared` replaces it only on the run that unwinds the gem, so the warning names the project-local bundle path, or, to replace the shared copy, the files to remove (its `specifications` entry and `/cache/.gem`) before `bundle install`, said with its cost: another project that still pins the hosted patch of that gem version then loads the upstream code, which `socket-patch scan` reports there. A path in the warning's `rm -f` command is shell-quoted when it needs to be. A project path outside the project directory that the unwind left alone is named without `--gem-refresh-shared`, for the same reason. Next to an `upstream_gem_stale_install` warning, rollback's "keep their patched bytes" note and its `reinstall_required` detail add " (Bundler: `bundle install` keeps an installed gem; see the gem warning for what to run)". *What never refreshes.* A hosted → vendored takeover (`vendor`, `scan` / `get --mode vendored` over a hosted pin) puts the gem on its upstream entry only on its way to the vendored `path:` source, which is what Bundler loads from then on. The copies Bundler already holds are unused leftovers there, so the takeover changes none of them and downloads no gem for them: resetting the installed copy to the upstream build would cost a registry download in the mode that needs none, and would turn a patched leftover into an unpatched one that `vex` reports against the vendored artifact (`vendored_tree_out_of_sync`, whose gem wording names the copy and how to remove it). Its `upstream_gem_stale_cache` advisory about a patched cache-dir archive is as before. A vendored unwind (`remove`, `rollback`, `vendor --revert`, `scan --prune`, `vendor`'s reconcile of a vendored gem) likewise only names that archive, and never replaces it. -*A vendored unwind after a hosted or an agent scan.* Once a vendored gem is unwound, Bundler loads its installed copy again, so the leftover is in use: if a hosted scan made that copy the patched build before the gem was vendored, the patched code would keep running under the upstream lock, and on bundler ≥ 2.6 `bundle pristine` would fail on the upstream checksum. If agent mode patched that copy in place before the gem was vendored (#2093), the takeover moved its manifest record into the vendor ledger and kept the patched files, so the patched code would keep running with no record left that `rollback` or `apply --check` could act on. A gem `.socket/manifest.json` still has a record for is different: its in-place patch is agent mode's and on record (standalone `vendor` works from the manifest and keeps the record), so the vendored unwind does not judge its installed copy by a record. A wet `rollback`, `remove`, `vendor --revert` or `vendor` reconcile that put a vendored gem back on its upstream entry therefore applies the unwind direction's refresh to the gem's INSTALLED copies (of every build the restored lock names: a gem vendored from prebuilt platform gems is installed as `--`, #2174) when the lock now resolves the gem from rubygems.org (a gem from another remote is not judged: nothing proves its entry is the upstream one), under the same rules (staleness judged by `/cache/.gem` against the upstream sha256, and by the patch record of a detached ledger entry (`scan` / `get --mode vendored`) whose gem the manifest has no record for: a copy whose files all hash to the record's `afterHash` values is stale whatever archive its gem home holds, or when it holds none; a project-local gem home only, unless `--gem-refresh-shared`; `--no-gem-install-refresh`; an archive on disk, else rubygems.org unless `--offline`), with the same `upstream_gem_install_refreshed` note and `upstream_gem_stale_install` warning. `--json` carries them where the command carries a vendored revert's advisories (rollback `warnings[]`; `remove` / `vendor` advisory events); a human run prints the progress line after the gem's own line and one warning for the gems left on the patched build. The upstream sha256 is looked up only for a gem that has an installed copy with its archive, or one holding the record's patched files, so the unwind of a gem that is not installed needs no network. A gem that was only ever vendored has the upstream archive there: nothing is downloaded or changed. Rollback's "keep their patched bytes" note and its `reinstall_required` warning do not count a vendored gem whose installed copies are all proven to be the upstream build (#2214): each has, in its gem home, the archive with the verified upstream sha256, and every file the gem's ledger record lists is in its pre-patch state there (it hashes to its `beforeHash`, or the patch adds it and it is absent). Anything short of that proof keeps the gem in the count: a gem with no installed copy the run can find, a gem from another remote, a pruned `cache/`, no verified sha256, a ledger entry with no record (standalone `vendor` before v5), a file that is patched, edited or unreadable. A `--dry-run`, which does not judge the installed copies, counts every vendored gem it would unwind. A copy agent mode patched is reinstalled from the upstream archive RubyGems kept beside it, so nothing is downloaded for it either unless that archive is gone (a pruned `cache/`); the reinstall also removes what agent mode kept in the gem dir. When nothing proves the upstream sha256 for such a copy (`--offline` under a lock without `CHECKSUMS`), it is left as it is and named by `upstream_gem_stale_install`. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry is refused (a plain-`http` `SOCKET_RUBYGEMS_URL`, see the unwind direction), such an installed copy is reported as one that could not be checked, whichever of the two it is: nothing tells them apart. A `--dry-run` does not preview this (the lock on disk is still the vendored one), and `scan --prune` does not refresh. +*A vendored unwind after a hosted or an agent scan.* Once a vendored gem is unwound, Bundler loads its installed copy again, so the leftover is in use: if a hosted scan made that copy the patched build before the gem was vendored, the patched code would keep running under the upstream lock, and on bundler ≥ 2.6 `bundle pristine` would fail on the upstream checksum. If agent mode patched that copy in place before the gem was vendored (#2093), the takeover moved its manifest record into the vendor ledger and kept the patched files, so the patched code would keep running with no record left that `rollback` or `apply --check` could act on. A gem `.socket/manifest.json` still has a record for is different: its in-place patch is agent mode's and on record (standalone `vendor` works from the manifest and keeps the record), so the vendored unwind does not judge its installed copy by a record. A wet `rollback`, `remove`, `vendor --revert` or `vendor` reconcile that put a vendored gem back on its upstream entry therefore applies the unwind direction's refresh to the gem's INSTALLED copies (of every build the restored lock names: a gem vendored from patched platform gems is installed as `--`, #2174) when the lock now resolves the gem from rubygems.org (a gem from another remote is not judged: nothing proves its entry is the upstream one), under the same rules (staleness judged by `/cache/.gem` against the upstream sha256, and by the patch record of a detached ledger entry (`scan` / `get --mode vendored`) whose gem the manifest has no record for: a copy whose files all hash to the record's `afterHash` values is stale whatever archive its gem home holds, or when it holds none; a project-local gem home only, unless `--gem-refresh-shared`; `--no-gem-install-refresh`; an archive on disk, else rubygems.org unless `--offline`), with the same `upstream_gem_install_refreshed` note and `upstream_gem_stale_install` warning. `--json` carries them where the command carries a vendored revert's advisories (rollback `warnings[]`; `remove` / `vendor` advisory events); a human run prints the progress line after the gem's own line and one warning for the gems left on the patched build. The upstream sha256 is looked up only for a gem that has an installed copy with its archive, or one holding the record's patched files, so the unwind of a gem that is not installed needs no network. A gem that was only ever vendored has the upstream archive there: nothing is downloaded or changed. Rollback's "keep their patched bytes" note and its `reinstall_required` warning do not count a vendored gem whose installed copies are all proven to be the upstream build (#2214): each has, in its gem home, the archive with the verified upstream sha256, and every file the gem's ledger record lists is in its pre-patch state there (it hashes to its `beforeHash`, or the patch adds it and it is absent). Anything short of that proof keeps the gem in the count: a gem with no installed copy the run can find, a gem from another remote, a pruned `cache/`, no verified sha256, a ledger entry with no record (standalone `vendor` before v5), a file that is patched, edited or unreadable. A `--dry-run`, which does not judge the installed copies, counts every vendored gem it would unwind. A copy agent mode patched is reinstalled from the upstream archive RubyGems kept beside it, so nothing is downloaded for it either unless that archive is gone (a pruned `cache/`); the reinstall also removes what agent mode kept in the gem dir. When nothing proves the upstream sha256 for such a copy (`--offline` under a lock without `CHECKSUMS`), it is left as it is and named by `upstream_gem_stale_install`. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry is refused (a plain-`http` `SOCKET_RUBYGEMS_URL`, see the unwind direction), such an installed copy is reported as one that could not be checked, whichever of the two it is: nothing tells them apart. A `--dry-run` does not preview this (the lock on disk is still the vendored one), and `scan --prune` does not refresh. **Pipenv hosted redirect (`Pipfile.lock`, pipfile-spec 6)**: every category other than `_meta` (`default`, `develop`, and Pipenv 2022+ named categories) that pins the package at the patched version is rewritten to the hosted reference — `{"file" | "path": "#sha256=", "hashes": ["sha256:"]}` with `markers`/`extras`/`index` kept exactly as Pipenv wrote them (present or absent: whether Pipenv records `index` depends on its release, the Pipfile spelling and the locking environment, so only the entry itself knows) and `version` dropped; `_meta` (the Pipfile content hash) and the Pipfile itself are never touched, so `pipenv install --deploy`/`sync`/`verify` keep passing. The reference KEY depends on the installing Pipenv: releases 7–11 only install `path` references, 2018 and later `file` ones (0–6 write pipfile-spec < 6 and are refused). The release is probed once per command with `pipenv --version`, resolved on ABSOLUTE `PATH` entries only (a relative entry would run a `pipenv` planted in the scanned repository; `.bat`/`.cmd` shims are found through `PATHEXT` on Windows), only when a pypi patch actually targets an entry of the lock, and `SOCKET_PIPENV_MAJOR=` pins the answer without spawning anything. An unknown installer selects `file` and warns `redirect_pipenv_installer_unknown` only when the lock was rewritten. **Refusal scope**: a pin/source CONFLICT (another version pinned, a foreign `file`/`path` source, a VCS/editable dependency) refuses the whole dependency atomically across categories as `redirect_pipenv_refused` AND vetoes the sibling Python rewriters (requirements.txt / uv.lock / pyproject) for that patch — the project's Pipenv install could not pick the patch up, so a half-redirected checkout is refused; anything else (no entry for the package, an old pipfile-spec, an unparseable lock, a digest-less patch) is `redirect_pipenv_skipped` and leaves the siblings alone (a stale Pipfile.lock in a uv/Poetry/requirements project must not block them). The veto applies to a LIVE lock only: a `Pipfile.lock` with no `Pipfile` beside it is abandoned, so its conflict refuses that file but never the siblings. Hash enforcement at install time is split by era — the `#sha256=` URL fragment is what Pipenv 2023+ verifies, the `hashes` list what 2018–2022 verify, Pipenv 11 either — so both are load-bearing. **Pipenv stale-install guard**: Pipenv never reinstalls a release that is already present (`pipenv install`, `install --deploy` and `sync` all exit 0 and keep the installed bytes — measured on 11.10.4, 2018.11.26 and 2026.8.0, hosted and vendored), so after the rewrite the run probes the Python crawler's site-packages (VIRTUAL_ENV, `./.venv`, `./venv`, Pipenv's out-of-tree `WORKON_HOME` venv; `--global`/`--global-prefix` honoured) for each confirmed Pipfile.lock redirect with the Python stale-install guard's evidence (the pinned patched wheel, else the patch record; STALE needs positive evidence, read-only, skipped on `--dry-run`, stale purls excluded from the same-run `--vex` `assume_applied` set) and the Python stale-install guard (`redirect_pypi_stale_install`, see above) names the site-packages dir and the Pipenv-specific verified remedy: `pipenv run pip uninstall -y && pipenv sync` (or `pipenv --rm && pipenv sync`), with the `sync` arguments following the lock, since plain `pipenv sync` installs only `default`: the targeted form re-syncs the categories that pin the package (`--dev` for `develop`, `--categories ""` for a named category) and the `--rm` form re-syncs every non-empty category — NOT `pipenv uninstall`, which rewrites the Pipfile and re-locks the patch away. The vendored backend emits the twin `pypi_pipenv_stale_install` (`skipped` warning event). **Rollback** (v5.0, upstream restore): each hosted entry gets its registry shape back — `"version": "=="`, the entry's own `index` carried back unchanged (refused unless it — and the Pipfile's explicit `index`, if any — names a PyPI source in `_meta.sources`), and every release file's sha256 from PyPI's JSON API (`SOCKET_PYPI_JSON_API`), sorted by filename as Pipenv records them; an entry that pins another version beside the hosted reference is refused with the `git checkout` remedy (see "Hosted unwind coverage"). A Pipfile names no project, so a same-run `--vex` on a Pipenv project needs `--vex-product` (or a git remote) to detect a product purl. **Discovery**: `Pipfile.lock` is part of the lockfile inventory (every category's `==` pins, with the lock's digest set as `Sha256AnyOf` integrity so a lock-only checkout can be vendored by fetching the pure wheel through PyPI's JSON API — only when `_meta.sources` name the public index; a private-index lock stays discovery-only and never reaches pypi.org), and Socket's own hosted / vendored references stay discoverable as the package they replace, so a re-scan of an already-redirected or already-vendored lock-only checkout re-confirms it (`--vex` attests, vendored reports `already_vendored`) instead of finding nothing. @@ -852,7 +855,7 @@ Human (non-`--json`) output is not a stable interface, but these rules hold: * Hosted and vendored runs that change the project end with one shared `Next steps:` block (commit, reinstall + `socket-patch vex`, then any extra step: `2. Reinstall from the updated lockfile (e.g. \`npm ci\`), then run \`socket-patch vex\` to verify the installed patches.`). A hosted run that rewrote Bundler's files alone words the second step by what it did about the gems Bundler already held (see "Gem stale-install guard"): once it replaced them it is `Run \`socket-patch vex\` to verify the installed patches (the installed gems already hold the patched builds, so there is nothing to reinstall).`, and while a shared gem home still holds unpatched copies it points at the command in that run's warning instead of a reinstall, since a plain `bundle install` keeps the gems it already has. * An agent-mode run that recorded a patch (`scan --mode agent`, agent-mode `get`) ends with its own `Next steps:` block, on stdout: `1. Commit .socket/ to keep the patches.` and `2. Run \`socket-patch apply\` after every \`bundle install\`, locally and in CI. A fresh install removes the patches.` The second step names the install command of each ecosystem the run patched, read from the project's lockfile where several package managers share one (`pnpm install`, `yarn install`, `bun install`, `vlt install`, else `npm install`; `uv sync`, `poetry install`, `pipenv install`, `pdm install`, else `pip install`; `bundle install`; `composer install`; `cargo fetch`; `dotnet restore`), and says `every dependency install` where there is no single command (Maven, Gradle, sbt). After `get --save-only` it reads `Run \`socket-patch apply\` now, and after every …`. A Go patch is a committed copy plus a `replace`, so the first step also names `go.mod (or go.work)` and a run that patched only Go modules has no second step. The block is not printed by a run that recorded nothing new, a dry run, a failed run, a global (`-g` / `--global-prefix`) run, `--silent` or `--json`. With a `--max-new-patches` cap, the lines about deferred patches follow in the same block. * `scan` lists each package it patched once, under the mode's result line (`Switched …`, `Vendored …`, the agent apply's `Applied N patches.`, the `--dry-run` line): ` @ `, worst severity first, then by purl. The name is the package's `name@version` when every row of the project is one ecosystem and its purl otherwise. `` are the first two advisories the patch fixes (a CVE, or the advisory's own id when it has none) and `(+N)` for the rest; `` counts the advisories only the package's other patches fix (paid ones included), since one patch is applied per package version. `--verbose` names every id and lists the unpatched ones under the row by reason, leaving out a line with no ids: `waiting on a merged patch: ` (another patch the account can download fixes them, and the merged patch is not published yet; see [Free and paid patches, and merged patches that are not ready](#free-and-paid-patches-and-merged-patches-that-are-not-ready)), `needs a paid Socket plan: ` (only the paid tier fixes them), and `still unpatched: ` for the rest. On a terminal narrower than a row, the row names fewer ids and then drops the measurements rather than wrap. Only a patch the run applied (or found applied, or on a dry run would apply) gets a row. `--json` carries the same facts on `packages[]` (see [`scan` and `get` JSON](#scan-and-get-json-v50-major)). The other per-package listings a scan used to print (the results table, the `Patches to apply:` blocks, `[add]` / `[fetch]` lines, `Patched packages:`) are gone from the default output; `--verbose` keeps the per-patch blocks. `get` keeps its numbered listing and, like `scan`, no longer names the patches again while it downloads and applies them: its nested apply says `Applied N patches.` (the other buckets only when a patch landed in one: `Applied 4 of 6 patches: 1 already patched, 1 failed.`), and `get --save-only` says `Saved N patches to .` (`(1 updated, 1 skipped)` when so); a recorded patch a `get` replaces still gets its `[update] (replacing )` line. `apply` itself prints as before. -* `scan` closes with the totals of the whole invocation, once, under a blank line: `Patched 22 packages in 3 projects, fixing 39 vulnerabilities (5 critical, 15 high).` (`Would patch …` on a dry run; `in N projects` only past one), then, under the `Verified:` line when there is one, `Saved about 44 hours of engineering time (22 package upgrades at ~2 hours each).` (`Would save …` on a dry run), then `18 vulnerabilities left to patch (32%): 6 await a merged patch, 8 need a package upgrade, 3 need a paid Socket plan, 1 is in packages this run did not patch.` or `Nothing left to patch.` (`No free patches left to apply.` when a lookup of the run went through the public proxy, which answers for free patches only). The reasons, for an advisory left on a patched package: it awaits a merged patch (another patch the account can download fixes it, and no downloadable patch fixes everything those patches fix between them); it needs a paid Socket plan (only a paid patch fixes it, or, for an account without paid access, only a free patch that is not critical; so does every advisory of a package whose every patch is paid); else it needs a package upgrade (a downloadable patch fixes it and the run selected another one, as a selection filter can make it). When any advisory is waiting on a merged patch the next two lines say so: `1 merged patch is not ready yet: Socket is still processing it.` and `Run \`socket-patch scan\` again later to apply it.` (`4 merged patches are not ready yet: Socket is still processing them.` / `… to apply them.`), counting the patched packages that have one, per project directory like the other totals. They are two short lines so that neither wraps an 80-column terminal; where color is on, the count is bold yellow like the count of what is left, and the second line is dim. The counts are occurrences: a package patched in three project directories counts three times, and so does each advisory its patch fixes there; an advisory is one id as the rows show it. "Left to patch" counts the advisories of every package a patch was offered for that this run did not fix, as a share of those it could have. A package a hosted or vendored run finds installed on the machine but absent from a lockfile that lists the whole dependency graph (npm, Cargo, Go, Bundler, Composer) is not the project's and is not counted; a PyPI package always counts, since a requirements file may pin only direct dependencies. A run given a selection filter with reachability findings adds `Reachable: 9 fixed, 2 left to patch (18%).`, the same two counts for the advisories a finding marks `reachable`. The hours are an estimate, and the line says so: each patched package, in every project directory it is patched in, stands for one upgrade that did not have to be made, taken at two hours (finding a release with the fix, moving to it, getting the build and tests through everything else that release changed, and the review). The figure is an assumption, not a measurement of the project. A run that leaves advisories to a paid plan ends with the upsell line below (once per invocation: a project directory whose every patch is paid prints it under its `No downloadable patches` line instead). Nothing is printed when no patch was offered at all. +* `scan` closes with the totals of the whole invocation, once, under a blank line: `Patched 22 packages in 3 projects, fixing 39 vulnerabilities (5 critical, 15 high).` (`Would patch …` on a dry run; `in N projects` only past one), then, under the `Verified:` line when there is one, `Saved about 44 hours of engineering time (22 package upgrades at ~2 hours each).` (`Would save …` on a dry run), then `18 vulnerabilities left to patch (32%): 6 await a merged patch, 8 need a package upgrade, 3 need a paid Socket plan, 1 is in packages this run did not patch.` or `Nothing left to patch.` (`No free patches left to apply.` when a lookup of the run went through the public proxy, which answers for free patches only; and, where a hosted run left a patched gem with its unpatched copy installed, `1 gem is still unpatched on disk: the warning names the command that installs the patched gem.`, see the "Gem stale-install guard" section). The reasons, for an advisory left on a patched package: it awaits a merged patch (another patch the account can download fixes it, and no downloadable patch fixes everything those patches fix between them); it needs a paid Socket plan (only a paid patch fixes it, or, for an account without paid access, only a free patch that is not critical; so does every advisory of a package whose every patch is paid); else it needs a package upgrade (a downloadable patch fixes it and the run selected another one, as a selection filter can make it). When any advisory is waiting on a merged patch the next two lines say so: `1 merged patch is not ready yet: Socket is still processing it.` and `Run \`socket-patch scan\` again later to apply it.` (`4 merged patches are not ready yet: Socket is still processing them.` / `… to apply them.`), counting the patched packages that have one, per project directory like the other totals. They are two short lines so that neither wraps an 80-column terminal; where color is on, the count is bold yellow like the count of what is left, and the second line is dim. The counts are occurrences: a package patched in three project directories counts three times, and so does each advisory its patch fixes there; an advisory is one id as the rows show it. "Left to patch" counts the advisories of every package a patch was offered for that this run did not fix, as a share of those it could have. A package a hosted or vendored run finds installed on the machine but absent from a lockfile that lists the whole dependency graph (npm, Cargo, Go, Bundler, Composer) is not the project's and is not counted; a PyPI package always counts, since a requirements file may pin only direct dependencies. A run given a selection filter with reachability findings adds `Reachable: 9 fixed, 2 left to patch (18%).`, the same two counts for the advisories a finding marks `reachable`. The hours are an estimate, and the line says so: each patched package, in every project directory it is patched in, stands for one upgrade that did not have to be made, taken at two hours (finding a release with the fix, moving to it, getting the build and tests through everything else that release changed, and the review). The figure is an assumption, not a measurement of the project. A run that leaves advisories to a paid plan ends with the upsell line below (once per invocation: a project directory whose every patch is paid prints it under its `No downloadable patches` line instead). Nothing is printed when no patch was offered at all. * **Measurements.** When stdout is a terminal, `scan`, `get` and `show` ask the patch service what it measured about the patches they list (the patch view's `statistics`): the proof-of-concept exploits of the fixed advisories blocked by the patched package, the package's own tests passing on it, the size of the change, and its run-time cost. `scan` shows them in each row (`exploit blocked, 25/25 tests`) and totals them in its closing lines (`Verified: 24 of 24 exploits blocked, 1208 of 1208 package tests passing.`, with `(measured for 18 of 22 patches)` when some were not measured); `get` adds `Verified:` / `Change:` / `Performance:` lines under each listed patch; `show` prints them with the unpatched package's numbers beside them. They are a courtesy to someone reading: a pipe, a log, `--silent` and `--json` make no such request and print no such line, a patch that was never measured shows none, and a failed or slow request costs the output those numbers and nothing else. `scan` asks in the background while it works (for each package's best-ranked patch as soon as the lookup answers, then for any other patch it selected; at most 100 patches a round), waits at most 0.4 s per project directory for answers still out when its rows are due and 1.5 s before its closing lines, and counts an answer that missed its row in the closing lines all the same. * **Marks, bars and color.** Color follows `NO_COLOR` / `CLICOLOR` / `CLICOLOR_FORCE` / `TERM=dumb`. Where color is on, the stream is a terminal and the terminal is known to show UTF-8 (a UTF-8 locale; on Windows: Windows Terminal, an editor's terminal, or an xterm-like one; never `TERM=linux`), `scan` and `rollback` open each done line with a green check mark (the rows of a dry run and of a report-only scan, whose patches are on offer and not in place, leave that column blank), the status line draws its progress bar in line glyphs, and `scan`'s closing lines end with a meter of the share patched. Everywhere else the same lines print in ASCII at the same columns (a space for the mark, `[####----]` for the bar, no meter), so a log or a pipe never carries a glyph. * **Progress.** On a terminal every command shows its waits on one self-rewriting status line that opens with an activity mark (`⠹ Scanning packages`; `|`, `/`, `-`, `\` where glyphs are off). The mark keeps turning for as long as the line shows, whether the command is waiting on the network or busy, so a long step never reads as a hang. `scan` shows `Finding projects` (a hosted or vendored scan looking for its project directories), `Scanning packages`, `Checking 644 packages for patches [####----] 1/2` (lookup batches), `Reading patches [######--] 6/8` (patch records), `Reading patch test results` (the measurements still out when the rows are due), `Looking for other projects` (an agent-mode scan whose search for project directories below outlasts its lookup), then the mode's own steps (`Downloading patches [##------] 2/8` in agent and vendored mode; in hosted mode `Checking 4 hosted patches`, `Resolving hosted artifacts for 3 patches`, `Checking project patches`, `Reading lockfiles`, `Rewriting lockfiles` (`Planning lockfile changes` on a dry run) and `Writing lockfiles`); `rollback` shows `Rolling back packages [###-----] 3/8`. The line is drawn only on a terminal that understands escape sequences, never under `--json`, `--silent`, `TERM=dumb` or `SOCKET_DEBUG`, and it is cleared before anything else prints. A scan leaves one permanent line per project directory, `Found 644 packages (644 npm)`; the count and its per-ecosystem parts are the packages the run goes on to check (after `--ecosystems`, the socket.yml filters and the project's own patches). `Note: N packages from project lockfiles are not yet installed (lockfile-only).` prints only for an agent or report-only scan, which patches installed copies. @@ -1660,7 +1663,7 @@ path. Without hosted pins the no-manifest no-op below is unchanged. **Prebuilt vendor artifacts (`--vendor-source`)**: `service` is the default and `auto` is a compatibility alias. `build` is rejected at argument parsing. There is no local construction or fallback. Package-reference POSTs on the configured API/proxy (`--vendor-url` overrides it) return the download URL and integrity; `--patch-server-url` can override the download origin. The CLI verifies transfer integrity and patched-member afterHashes before writing. Pending builds, missing artifacts, service failures, wrong layouts and integrity mismatches fail closed. Fresh acquisition requires the network; healthy committed artifacts remain reusable offline. -Coverage includes npm (all lock flavors), Python wheels and source distributions, Cargo crates, Go module zips, Composer dist zips, RubyGems, NuGet packages and JVM jars. Directory artifacts are extracted and receive only the existing package-manager layout transformations. RubyGems requires the server's separately verified `gem-stub-gemspec`; a missing or invalid stub is a failure. A gem whose `Gemfile.lock` holds platform-suffixed entries (`nokogiri (1.18.10-x86_64-linux-gnu)`) is taken as the patch's prebuilt platform gems instead: for each locked platform the server's `gem-platform` artifact and its `gem-platform-stub-gemspec` (each carries its `platform`), both verified like the ruby gem and its stub. Which prebuilds exist is read from the package reference alone, and the ruby gem it also names is not downloaded. While the server lists no prebuild for a locked platform nothing is downloaded and the gem is skipped (`vendor_prebuilt_platform_pending`). A prebuild need not ship any of the patch's files (a patch of `patches/**` or `dependencies.yml` lives entirely in the rebuilt binaries): its integrity check against the digest the server states for that platform is mandatory and is what vouches for it, while a patched file it does ship that is not the patched one is a `vendor_prebuilt_required` failure. Yarn Berry checksums come from server metadata. Hosted Berry rollback retrieves upstream checksum metadata from `/upstream/npm/.json` and checks its package identity and upstream integrity against the registry; the CLI does not recreate the Berry zip. +Coverage includes npm (all lock flavors), Python wheels and source distributions, Cargo crates, Go module zips, Composer dist zips, RubyGems, NuGet packages and JVM jars. Directory artifacts are extracted and receive only the existing package-manager layout transformations. RubyGems requires the server's separately verified `gem-stub-gemspec`; a missing or invalid stub is a failure. A gem whose `Gemfile.lock` holds platform-suffixed entries (`nokogiri (1.18.10-x86_64-linux-gnu)`) is taken as its patched platform gems instead. The gem patch's package reference names the patch of each platform (`registryOverride.identifiers.gemBuilds`), which is all that is read to tell which platforms have a patched build; the ruby gem it also names is not downloaded. Each locked platform's tree then comes from that platform's own patch: its `tarball` (the patched platform gem) and its `gem-stub-gemspec`, the references of all of them asked for in ONE request, each download verified against the digest its own reference states, and the gem also against the sha256 the gem patch lists for that platform (a gem that is not the listed one is `vendor_prebuilt_integrity_mismatch`, with any existing copy untouched). While a locked platform has no patched build nothing is downloaded and the gem is not vendored (`vendor_prebuilt_platform_pending`). A patched platform gem need not ship any of the patch's files (a patch of `patches/**` or `dependencies.yml` lives entirely in the rebuilt binaries): its integrity check is mandatory and is what vouches for it, while a patched file it does ship that is not the patched one is a `vendor_prebuilt_required` failure. Yarn Berry checksums come from server metadata. Hosted Berry rollback retrieves upstream checksum metadata from `/upstream/npm/.json` and checks its package identity and upstream integrity against the registry; the CLI does not recreate the Berry zip. Agent runs fetch patch content as per-file blobs (v5.0 removed `--download-mode` and the diff archive path). Vendored runs retain patch records in memory and embed them in the vendor ledger, without staging blobs. N-API and the hosted in-memory engine remain supported for callers such as the future GitHub App. @@ -1742,7 +1745,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 gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the 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 patched 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: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); 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. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way asks the patch service for the reference of its own fix when the run reaches it. That costs ONE small request per vendored platform gem per run, wet or dry: the requests are not batched, and a run over a copy that is in sync makes that one request for it and downloads nothing. The question is advisory, since the copy stands whatever the answer: it is one attempt of at most five seconds, never retried, and outside the circuit breaker the run's other requests share, so a patch service that is down costs such a run one short attempt per vendored platform gem and cannot fail what the run has to vendor. Where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said, a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. Every path that is about to put the trees in place, or that says the ones that are there stay, finishes the copy with one step. It writes the uuid directory's `.gitignore` and `.gitattributes` where one is missing or changed. They are not part of the copy, so a write that fails is the warning `vendor_gem_git_metadata_unwritten`, which names the two files and says to make them writable, and never a failure (a skip that leaves the copy in force carries no warning of its own and ends its line with it: `… stays in force as it is. Also: could not write …`). Git is asked whether it would commit the copy only where trees are about to be placed (a first vendor, a rebuild of a copy the lock is wired to, a restore), before they are moved in and as if nothing were tracked, which does not read the index; a dry run asks the same question and writes nothing. With the uuid directory's own rules in place no rule above them reaches a file of the copy, so the question is whether a rule excludes the directory itself; where those rules could not be written it is asked of every staged file, and the refusal names the files that could not be written as its cause, with that remedy. A refusal (`vendor_artifact_gitignored`) leaves what is on disk as it was: a first vendor writes nothing, an intact copy whose list moved stays in force with the refusal as the reason (the note `vendor_gem_list_not_followed`, exit 0), and a damaged copy is neither restored nor rebuilt (the run fails, as for any copy it cannot put back). A copy that is in step, or that is left in force, asks git nothing: it is already what the project commits. A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it; only a release that contains this support and the platform-gem vendoring it builds on reads such an entry: socket-patch 5.1.0 and earlier have no platform-gem vendoring and do not read such a copy, with or without a tree of upstream's gem (on 5.1.0 `vendor --check` fails, `vendor_check_failed`: a patched file is missing, and `vex` leaves the gem out, `vendor_unwired`, attesting nothing for it), so a project vendored this way is attested, by `vex` or `vendor --check`, with the release that vendored it or a later one), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch scan --mode vendored`, which vendors the copy again from the list. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). A restore hands the list it read to the gem's backend, whether it was refused over that list or restored the copy, so the copy is vendored again, or found in step, by the one answer the restore read, and the fix's reference is asked for once (a list of another fix is never used). Its dry run asks the same question (one request, no download) and previews the copy vendored from that list, one `verified` event per patched build, in place of `wouldRedownload`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A platform removed from the lock after vendoring (`bundle lock --remove-platform `) leaves the copy and its ledger entry as they were: the copy keeps that platform's tree, from which Bundler can lock the platform again, so an in-sync re-run, `vendor --check` and `vex` go on reporting that build as before (a tree of upstream's gem stays `affected`) until the gem is reverted and vendored again. A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (Bundler keeps it for the `ruby` platform and for any other locked platform that none of the gem's builds serves; no platform tree serves it), 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 gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | | 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 | @@ -2522,8 +2525,11 @@ command's integration tests check its output. | `vendor_maven_version_not_selected` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): no module of the build resolves the artifact at the patch's base version; the reason names the versions Maven selects instead (a nearer declaration, the project's own declaration or management, an ``, a version range), or says that no module resolves the artifact. Decided before any download: the patch is not fetched and no file is written, except that a pin an earlier run wrote for that version is taken out of the poms (the reason says so), since it would keep forcing a version the build no longer selects. Human: `[skip] (vendor_maven_version_not_selected): …` in the download phase of `scan` / `get` and in their dry run, `Skipping : …` in `vendor`. The vendored twin of `redirect_maven_version_not_selected`. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). | | `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_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 gem locked as platform gems whose fix is still building is the skip `vendor_prebuilt_platform_pending` instead, vendored or not (below). 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_replaced` | `failed` | repair (gem; a vendor / scan / get `--mode vendored` run that finds a platform gem's tree damaged is refused the exact restore the same way, and then vendors the copy again from the list instead of failing): the list of the gem's fix names another patch for that platform than the vendor ledger records, or no patched build, so the tree cannot be restored as it was vendored. The same for a tree the ledger records as upstream's own gem when the list names a patched build for its platform now, or lists no gem for it (`the copy of upstream's gem for () cannot be restored as it was vendored: …`); a `scan --mode vendored` then vendors what the list names now. Nothing is downloaded or unpacked. Only a list says so: when the fix's reference carries no list, or the service says the patch is not ready (the service has not read the version's gems, or is building one of them again), nothing is said of a replacement and nothing is changed. The restore fails as for any patch the service does not serve, with the detail `vendor_prebuilt_required: the patch service lists no builds for @ right now; run this again later` (under `vendor_artifact_redownload_failed` in `repair` and `vendor_redownload_failed` in a vendor run), and a run that vendors the lock's platforms is the skip `vendor_prebuilt_platform_pending`, whose line says which copy stays in force. The error names both patches and the remedy, the one command that works: run `socket-patch scan --mode vendored`, which vendors what the patch service serves now. | +| `vendor_gem_list_not_followed` | `events[]` (`skipped`, NOT counted in `summary`) | vendor / scan / get `--mode vendored` (gem): an intact copy vendored as platform gems whose fix now lists another build for a locked platform (a patched build published since, or upstream's gem where the patched build was withdrawn) could not be vendored again from that list: a download failed, a build's gem failed its digest or its stub was not served, an upstream gem did not unpack, or git would not commit the new trees (`vendor_artifact_gitignored`, asked before they are moved in). Nothing of the copy was touched and it stays in force, which the run checks before it says so; the run reports the copy as it reports one in step (exit 0) and prints the reason as a note, `Note: @ could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` The next run tries again. | +| `vendor_gem_list_followed` | `events[]` (`skipped`, NOT counted in `summary`) | vendor / scan / get `--mode vendored` (gem): the run vendored an intact copy again because its fix lists another build for a locked platform. JSON only: the gem's line says which platforms changed (`now also patched for …`, `upstream gem back for …`), and the builds' events carry `details.newlyPatched` / `details.withdrawn`. | +| `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 gem cannot be vendored for the locked platforms yet: no locked platform has a patched build (each is served as upstream's gem, `gemBuilds[].patchUuid` is null), or the list leaves a locked platform out, or the patch it names for one is not served; or the fix names no builds right now, which the service says in two ways that are one skip here: a reference that carries no list, or a patch that is not ready (`pending_build`). A lock with a patched build for at least one platform and upstream's gem for the rest is vendored, not skipped (see the gem row of the vendored layouts). Nothing is downloaded or written, the run does not fail (exit 0), and ONE line (stderr, no warning; one counted `skipped` event under the gem's purl) names the platforms without a patched build and the ones that have one (on a terminal it is wrapped like the hosted line of such a gem). With no locked platform patched: `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin and x86_64-linux-gnu.` A platform whose patch is listed but not served yet (still being built) leaves the gem as it is, because the registry then lists neither a patched build that can be vendored nor upstream's gem for it: `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs a gem, patched or upstream's own, for every locked platform; `scan --mode hosted` can patch the others now.` One whose patch the service does not grant (not found, withdrawn, a failed build) reads `no patched build available for ` (mixed: `no patched build yet for and none available for `). A platform the list leaves out is not one to wait for. The patch service lists every platform gem upstream publishes for the version, so it is a platform upstream does not publish, which hosted mode reports as `redirect_gem_platform_unlisted` and leaves alone as well. The line says that the registry does not list it and what settles that, and does not offer hosted mode: `nokogiri@1.19.3 is not vendored: the patch registry does not list java. Vendored mode needs a gem, patched or upstream's own, for every locked platform, and a re-run does not change what the registry lists: this is settled once the lockfile no longer names java (`bundle lock --remove-platform java`), or the registry lists a gem for every locked platform.` (beside a platform with no patched build: `… does not list java, and there is no patched build yet for arm64-darwin. Vendored mode needs …`). A fix that names no builds right now (the service has not read the version's gems, or is building one of them again) names no platform and says what to do, in the same words under `vendor`, `scan` and `get`: `nokogiri@1.19.3 is not vendored: the patch service lists no builds for it right now. Run this again later.` A copy that is already vendored stays in force and the line says so: `… was not brought up to date: no patched build yet for java (… have one). Vendored mode needs a gem, patched or upstream's own, for every locked platform; its vendored copy stays in force as it is.`, or `…; its vendored copy of an earlier patch stays in force as it is.` when the copy is of an older patch; for a fix that names no builds right now, `… was not brought up to date: the patch service lists no builds for it right now. Run this again later; its vendored copy stays in force as it is.` (or `…; its vendored copy of an earlier patch stays in force as it is.`). A gem pinned hosted (a takeover) stays hosted: `…; the gem stays hosted.` A re-run vendors the gem once the registry lists a gem for every locked platform, a patched build for at least one of them, and serves each patch it names. A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is this skip too: `… was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.` Every line of a fix that names no builds says `Run this again later`, the failure below included (`… right now. Run this again later; its vendored copy is missing or damaged and cannot be rebuilt until then.`). 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` (`…; its vendored copy is missing or damaged and cannot be rebuilt until then.`); and an eject of the gem's hosted pin (plain `vendor`), which is all-or-nothing and keeps the pin. | | `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. | @@ -2613,8 +2619,9 @@ 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. A gem vendored as platform gems is asked about wherever its trees are about to be placed (a first vendor, a rebuild of a wired copy, a restore), before they are moved in and without the index, in a dry run too: a refusal leaves what is on disk as it was, and one that comes from the uuid directory's own `.gitignore` and `.gitattributes` not being writable names them and that remedy (see `vendor_gem_git_metadata_unwritten`). A copy that is in step, or left in force, is asked about nothing. | | `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_gem_git_metadata_unwritten` | warning | vendor / scan / get `--mode vendored` and `repair` (a gem vendored as platform gems): the `.gitignore` and `.gitattributes` of the copy's uuid directory could not be written. Those two files keep a project ignore rule or filter (such as `*.so`, or a Git LFS rule) off the vendored binaries; they are not part of the copy, so the trees are in place and correct and the run does not fail. The detail names the two files and the error. Remedy: make them writable and run again. Said by every path that puts the trees in place or leaves them in force, once per run (a skip that leaves the copy in force ends its line with it). Where trees are about to be placed and git would then not commit a file of them, they are not placed: `vendor_artifact_gitignored` names these files as the cause. | | `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. | | `vendor_variant_ambiguous` | `failed` | vendor / scan / get `--mode vendored` (pypi, gem): the package is not installed and the manifest holds several release variants of it (`?artifact_id=` / `?platform=`), none of which the vendor ledger records, so nothing says which distribution to vendor; install the package or keep one release variant. A variant the ledger records (at any patch uuid) is taken as the wired one and its siblings are left out without an event. | @@ -2628,7 +2635,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. Bundler keeps that entry for `ruby` and for every other locked platform that none of the gem's platform builds serves (a gem with no 32-bit ARM build under a lock that names `arm-linux-gnu`). The detail names the plain entry and each such platform under the lock's `PLATFORMS`, with the command that removes them (`bundle lock --remove-platform arm-linux-gnu ruby`); it names `ruby` only when the lock holds it, and `` when the lock shows no such platform. A locked platform of a system other than Linux, macOS, Windows or Java, or one that is not a plain platform name, is not named: the detail then adds that another locked platform may keep the entry; 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. Bundler keeps that entry for `ruby` and for every other locked platform that none of the gem's platform builds serves (a gem with no 32-bit ARM build under a lock that names `arm-linux-gnu`). The detail names the plain entry and each such platform under the lock's `PLATFORMS`, with the command that removes them (`bundle lock --remove-platform arm-linux-gnu ruby`); it names `ruby` only when the lock holds it, and `` when the lock shows no such platform. A locked platform of a system other than Linux, macOS, Windows or Java, or one that is not a plain platform name, is not named: the detail then adds that another locked platform may keep the entry; 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 `get --mode vendored` names the patch of one platform's build (`?platform=`) whose package reference names no gem patch it was built from (the refusal comes before anything is downloaded, with `status: "error"`, and names `socket-patch get pkg:gem/@ --mode vendored`; with such a patch named the run takes that one instead, see `platformGemPatch`). Nothing is written. A locked platform with no patched build 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. | @@ -2663,7 +2670,14 @@ 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_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 gem patch's reference carries no list of the version's gems (`gemBuilds`: the patch service names no platform gem of the version right now, which is also its answer to a project that is not on the patch yet while a gem of the patch is being built again), or the lock is the merged layout of Bundler < 2.2. The detail names the locked builds and which of the two it is. The gem is skipped and the manifest and lock stay byte-identical for it. A platform with no patched build, or one the list does not name, is not this warning: see `gem_upstream_build_kept`, `redirect_gem_no_patched_build` and `redirect_gem_platform_unlisted`. | +| `gem_upstream_build_kept` | `events[]` (`skipped`, NOT counted in `summary`, no `uuid`) | scan/get `--mode hosted` (gem): one platform build the lock names of a gem that was moved to (or is on) the patch registry, which the registry serves as upstream's own gem: that platform has no patched build yet, and installs what it installed before, or its patched build was withdrawn and this run put its lock entry back on upstream's gem. `details.gemFix` is the gem's patch and `details.platform` the platform; `details.withdrawn: true` marks the second case, on the run that puts the entry back (told from the lock's `CHECKSUMS` entry, or, for a build with none, from the listing of the registry the lock is on where the run read it). `details.gemFix` is the patch whose registry the lock is on after the run, which is an earlier patch than the selected one where the lock stays on it (`redirect_gem_newer_fix_waits`, `redirect_gem_platform_unlisted`). The human line of the gem names the build (`upstream gem kept for arm64-darwin (no patched build yet)`, or `upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`). Never a warning, never attested as patched. Also vendor / scan / get `--mode vendored`, `vendor --check` and `vex` (gem): one tree of a gem vendored as platform gems that is upstream's own gem, for a locked platform that had no patched build when the gem was vendored, with the same `details` (`details.withdrawn: true` on the run that puts the tree in place of a patched build that was withdrawn). | +| `platform_gem_patch_not_taken` | `warnings[]` (warning) | get `` `--mode hosted` (gem): the uuid is the patch of one platform gem (`pkg:gem/@?platform=`) and its package reference names no gem patch it was built from, so there is nothing to take in its place: hosted mode patches a gem through the gem's own patch. The patch is skipped, exit 0, and the detail names the command to run (`socket-patch get pkg:gem/@ --mode hosted`). With such a patch named on the reference the run takes that one instead and says so (`platformGemPatch`). | +| `redirect_gem_no_patched_build` | `events[]` (`skipped`) | scan/get `--mode hosted` (gem): the lock holds the gem as precompiled platform builds and none of the builds it names has a patched build yet, so moving the gem would gain nothing: it is left on its upstream registry, byte-identical. Only for a lock that takes the gem from its upstream registry: one that is on a patch registry of the gem already follows the selected patch's list, so that it is never left on a registry that refuses a build it pins (a lock on ANOTHER patch's registry under the rule of `redirect_gem_newer_fix_waits`). One plain line on stdout (`nokogiri 1.18.10: no patched build yet for arm64-darwin, x86_64-linux-gnu; left on its upstream registry`), no warning, exit 0. A later run moves the gem once the patch service lists a patched build for a platform the lock names. | +| `redirect_gem_platform_unlisted` | `events[]` (`skipped`) | scan/get `--mode hosted` (gem): the lock names a platform the gem patch's list (`gemBuilds`) leaves out. The patch service lists every platform gem upstream publishes for the version, whether or not a patched build of it exists or is being made, so a platform it leaves out is one upstream does not publish (a private build, a yanked platform gem), and the run says only that it is not listed. The gem is not moved to that patch. This holds for a lock that is already on the patch too (the known limit above): nothing is written, and no string of the lock reaches the Gemfile. One plain line on stdout (`nokogiri 1.18.10: the patch registry does not list arm64-darwin, so the gem is left as it is`; for a lock on the registry of another patch of the gem, `nokogiri 1.18.10: the newer fix's registry does not list arm64-darwin; the lock stays on the patch it is on`), no warning, exit 0. A lock on its upstream registry is byte-identical. A lock on another patch's registry stays on that patch: byte-identical too, unless that patch has withdrawn a build the lock pins, in which case the run brings the lock to that patch's current listing (one `info/` request to the lock's registry on each such run; see `redirect_gem_newer_fix_waits`). A later run moves the gem once the list has the platform. | +| `redirect_gem_newer_fix_waits` | `events[]` (`skipped`) | scan/get `--mode hosted` (gem): the lock takes the gem from the registry of another patch (an earlier fix), and the selected patch's list serves upstream's own gem for a platform build that the lock's own registry still serves patched. Moving would lose that patched build, so the lock stays on the patch it is on. One plain line on stdout (`nokogiri 1.18.10: the newer fix has no patched build for x86_64-linux-gnu yet; the lock stays on the patch it is on`, naming only the builds that would be lost), no warning, exit 0. Told by one request to the lock's own registry (`/info/`), made with a `CHECKSUMS` section or without wherever the move would put a build on upstream's gem that the lock does not already pin there: a build counts as patched when the registry lists it under the sha256 the lock pins (with no `CHECKSUMS` entry: under a sha256 that is not upstream's), and an answer that cannot be read counts as patched. A build the registry no longer lists, or lists under another sha256, was withdrawn and holds nothing back: when no build is left to lose, the lock moves to the selected patch and the withdrawn build goes back to upstream's gem (`gem_upstream_build_kept` with `details.withdrawn`). While the lock stays it is byte-identical, unless the same listing shows ANOTHER locked build as withdrawn: the run then takes the reference of the patch the lock is on (held from a scan's check of the pins in the lockfiles; one request for `get`) and brings the lock to that patch's current snapshot, with upstream's sha256 back for the withdrawn build, the still-patched builds unchanged and the installed copy replaced by the guard; this event is reported beside that patch's build events. A reference that is not usable, and a lock under `--patch-mirror-url`, leave the pair byte-identical. A later run also moves the gem once the newer fix patches every build the lock has patched. | +| `vex_gem_install_unpatched` | `vex.warnings[]` / `warnings[]` (one per gem) and `events[]` (`skipped`, counted in `summary.skipped`; the `--json` envelope of a standalone `vex` has `status: "partialFailure"`, as for `vex_bazel_not_in_build`) | vex, and the `--vex` of scan / get / apply / vendor (gem): a Bundler lock whose `PLATFORMS` names `ruby` alone takes the gem from its patch registry, and an installed precompiled build of that version, which Bundler loads in place of the ruby-platform gem the lock names, still holds the original content. That is the state of the package, so the gem is not left out as `not_applied`: its statement says `affected`, with an action statement that says so and names `socket-patch scan`, whose warning gives the command that installs the patched gem. A document is written and the process exits 0: `partialFailure` is the envelope's `status` alone, not an exit code. A command run with `--vex` keeps its own exit code and status. | +| `vex_gem_build_unknown` | `vex.warnings[]` / `warnings[]` (one per gem and reason) and `events[]` (`skipped`, NOT counted in `summary`, one per build) | vex, and the `--vex` of scan / get / apply / vendor (gem): a Bundler lock takes the gem from a patch registry as precompiled platform builds, and it could not be shown that a build it names is a patched one, or that the installed copy of a patched build is that build (the record of the build's own patch could not be read, or `--offline` forbids asking). An installed copy of a patched platform build is judged like any installed package, against the record of that build's own patch (asked without file contents, one request per installed patched build, however many gem homes hold it) and never against the gem's: every copy must verify, and a copy that does not leaves the build out with the usual reason (`not_applied`, `hash_mismatch`, …). The archive in the gem home's `cache/` is not evidence for `vex`. For the `--vex` of the run that moved the lock the same check runs: what the run assumes of the gem never stands in for a build that has an installed copy, in whatever gem home, and a record that cannot be read there states the build `affected` under this warning, as `vex` does. For the first: the gem patch's reference lists another archive for that platform than the lock installs (the lock is older than the list: `socket-patch scan --mode hosted` refreshes it), the reference lists no gem for that platform (the list names every platform gem upstream publishes, so a scan changes nothing: the action statement says so, and that the build is settled once the lock no longer names the platform, `bundle lock --remove-platform`), the reference or the registry's `info/` could not be read, or `--offline` forbids asking. The build is stated as `affected`, with an action statement that says why and what to run, and no patch uuid is named for it; the builds that can be shown are attested. Never a failure: the run's status and exit code do not change because of it. | | `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. | @@ -3116,7 +3130,7 @@ socket-patch scan --mode agent --json | jq ' ' ``` -Hosted `scan` and `get` report `details.pinChanged` on each confirmed pin. A wet run reports an `applied` event. A dry run reports the planned result on a `verified` event. The value is `true` when the local dependency files show a new or updated hosted reference for this package and patch UUID. It is `false` when the recorded references stayed the same or the run rewrote nothing. Changes to a sibling package in the same lockfile do not count. A `null` value means the CLI could not determine the change, for example when it could not attribute the final reference to a package version. Older releases omit the field. +Hosted `scan` and `get` report `details.pinChanged` on each confirmed pin. A wet run reports an `applied` event. A dry run reports the planned result on a `verified` event. The value is `true` when the local dependency files show a new or updated hosted reference for this package and patch UUID. It is `false` when the recorded references stayed the same or the run rewrote nothing. Changes to a sibling package in the same lockfile do not count. A `null` value means the CLI could not determine the change, for example when it could not attribute the final reference to a package version. A gem the lock names as platform builds has one pin, the gem patch's, and one event per locked build (see `gem_upstream_build_kept`): each patched build's event carries that pin's value, whatever patch the build itself holds, and the advisory event of a build left on upstream's gem carries no `pinChanged`. Older releases omit the field. To list confirmed pins and the changes the CLI could attribute: @@ -3196,7 +3210,7 @@ A `list` or bare `rollback` that covers patched project directories below `--cwd | Code | Meaning | |---|---| -| `0` | A non-empty OpenVEX document was produced (a statement may say `affected`: see `vex_bazel_not_in_build`) | +| `0` | A non-empty OpenVEX document was produced (a statement may say `affected`: see `vex_bazel_not_in_build`, `vex_gem_build_unknown` and `vex_gem_install_unpatched`) | | `1` | Nothing attested: `no_applicable_patches` (every candidate was omitted — by verification, a wiring gate, or a missing record; the omissions ride `skipped` events) or `no_patches` (an empty manifest file and nothing wired anywhere) | | `2` | Hard error: `manifest_not_found` (no manifest AND no vendor-ledger record / lockfile reference anywhere), `manifest_invalid` / `manifest_unreadable`, `vendor_ledger_corrupt` (v5.0: `redirect_ledger_corrupt` is a warning), `json_requires_output`, `product_undetected`, `serialize_failed`, `write_failed` | @@ -3210,7 +3224,7 @@ The VEX document is JSON-LD, which collides with the standard `--json` envelope |---|---|---|---| | unset | unset | stdout | stderr (one-line summary) | | set to `` | unset | `` | stdout (one-line summary) | -| set to `` | set | `` | stdout (full envelope, with one `verified` event per subcomponent of a `not_affected` statement and one `skipped` event, `errorCode: vex_bazel_not_in_build`, per subcomponent of an `affected` one; `details.status` is the `status` of the statement) | +| set to `` | set | `` | stdout (full envelope, with one `verified` event per subcomponent of a `not_affected` statement and one `skipped` event per subcomponent of an `affected` one, with the `errorCode` of why it is affected (`vex_bazel_not_in_build`, `vex_gem_install_unpatched`, or a gem build's `gem_upstream_build_kept` / `vex_gem_build_unknown`); `details.status` is the `status` of the statement) | | unset | set | (error: `json_requires_output`, exit `2`) | stdout (envelope-only) | `--output -` means stdout (the first row). With `--dry-run`, a document bound for `--output` is built and verified but not written, a previous document at that path is left alone, the one-line summary reads `[dry-run] Would write OpenVEX document with N statements to `, and the envelope's `dryRun` is `true`. In every one-line summary the count reads `N statements (K affected)` when K of the statements say `affected`. A written file ends with a newline, like the stdout form. diff --git a/crates/socket-patch-cli/src/commands/gem_build_lines.rs b/crates/socket-patch-cli/src/commands/gem_build_lines.rs new file mode 100644 index 0000000000..a021ff5bc4 --- /dev/null +++ b/crates/socket-patch-cli/src/commands/gem_build_lines.rs @@ -0,0 +1,148 @@ +//! The line a run prints for a gem a Bundler lock names as precompiled +//! platform builds: which of them are patched. Hosted mode says it of the +//! locked builds of a pin, vendored mode of the trees of a vendored copy. + +use socket_patch_core::hosted::engine::PinReport; +use socket_patch_core::utils::purl::purl_parts; + +/// Which builds are patched of each gem the Bundler lock names as +/// precompiled platform builds, one line per gem. Such a gem takes its +/// patch registry as the one source of every locked build, and the +/// registry serves a patched build for some platforms and upstream's own +/// gem for the rest, so the summary's "1 package" does not say which +/// machines run patched code. Not a warning: nothing here needs doing. +/// +/// - `nokogiri 1.19.3: patched for arm64-darwin, x86_64-linux-gnu` +/// - a platform with no patched build yet: `…: patched for +/// x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched +/// build yet)` +/// - a patched build that this run found for a platform of a lock already +/// on the registry: `…: now also patched for arm64-darwin; already +/// patched for x86_64-linux-gnu` +/// - a build this run put back on upstream's gem, because the patched +/// build its lock entry pinned was withdrawn: `…: patched for +/// arm64-darwin; upstream gem back for x86_64-linux-gnu (its patched +/// build was withdrawn)`, before the builds that never had one +/// - a gem left where it is under one of the quiet skips +/// (`engine::is_quiet_gem_skip`), in the skip's own sentence: `…: no +/// patched build yet for arm64-darwin, x86_64-linux-gnu; left on its +/// upstream registry` +/// +/// The ruby-platform gem, where the lock names it beside the platform +/// builds, is the platform `ruby`. A dry run says `would be patched for` +/// (`would also be patched for`) of the builds a wet run would put in +/// place, and `upstream gem would be back for` of those it would put back. +/// `reports` are the run's pins per locked build (`engine::pin_reports`), +/// `skipped` its skips. Vendored mode says the same of a gem it vendors +/// as platform gems, with a tree in place of a locked build +/// ([`format_vendored_gem_build_lines`]). +pub(crate) fn format_gem_build_lines( + reports: &[socket_patch_core::hosted::engine::PinReport], + skipped: &[socket_patch_core::hosted::engine::SkippedPatch], + dry_run: bool, +) -> Vec { + use socket_patch_core::hosted::engine::{is_quiet_gem_skip, PinReport}; + // Per gem patch, in report order: its locked builds. + let mut gems: Vec<(&str, Vec<&PinReport>)> = Vec::new(); + for report in reports { + let Some(gem_fix) = report.gem_fix.as_deref() else { + continue; + }; + match gems.iter_mut().find(|(fix, _)| *fix == gem_fix) { + Some((_, builds)) => builds.push(report), + None => gems.push((gem_fix, vec![report])), + } + } + let mut lines: Vec = Vec::new(); + for (_, builds) in gems { + let Some((_, name, version)) = builds.first().and_then(|build| purl_parts(&build.purl)) + else { + continue; + }; + let platforms = |keep: &dyn Fn(&PinReport) -> bool| -> String { + let named: Vec<&str> = builds + .iter() + .filter(|build| keep(build)) + .map(|build| build.platform.as_deref().unwrap_or("ruby")) + .collect(); + named.join(", ") + }; + let now = platforms(&|build| build.uuid.is_some() && build.newly_patched); + let before = platforms(&|build| build.uuid.is_some() && !build.newly_patched); + let is_back = |build: &PinReport| build.uuid.is_none() && build.withdrawn; + let back = platforms(&is_back); + let kept = platforms(&|build| build.uuid.is_none() && !build.withdrawn); + let (first, also) = if dry_run { + ("would be patched for", "would also be patched for") + } else { + ("patched for", "now also patched for") + }; + let mut parts: Vec = Vec::new(); + match (now.is_empty(), before.is_empty()) { + (false, true) => parts.push(format!("{first} {now}")), + (false, false) => { + parts.push(format!("{also} {now}")); + parts.push(format!("already patched for {before}")); + } + (true, false) => parts.push(format!("patched for {before}")), + // No locked build is patched: the lock followed a withdrawn + // build back to upstream's gem. + (true, true) => {} + } + if !back.is_empty() { + let is = if dry_run { "would be back" } else { "back" }; + let why = match builds.iter().filter(|build| is_back(build)).count() { + 1 => "its patched build was withdrawn", + _ => "their patched builds were withdrawn", + }; + parts.push(format!("upstream gem {is} for {back} ({why})")); + } + if !kept.is_empty() { + parts.push(format!( + "upstream gem kept for {kept} (no patched build yet)" + )); + } + lines.push(format!("{name} {version}: {}", parts.join("; "))); + } + lines.extend( + skipped + .iter() + .filter(|skip| is_quiet_gem_skip(&skip.reason)) + .filter_map(|skip| skip.detail.clone()), + ); + lines +} + +/// Which trees are patched of each gem vendored as platform gems that +/// holds upstream's own gem for a locked platform, or that this run +/// brought in step with the builds the patch registry lists: hosted +/// mode's line for such a gem, one per gem ([`format_gem_build_lines`]). +/// A gem whose every tree is a patched build says nothing here, as before. +/// `reports` are the run's reports per tree +/// (`crate::commands::vendor::gem_build_reports`). +pub(crate) fn format_vendored_gem_build_lines(reports: &[PinReport], dry_run: bool) -> Vec { + let mut fixes: Vec<&str> = Vec::new(); + for report in reports { + if let Some(fix) = report.gem_fix.as_deref().filter(|fix| !fixes.contains(fix)) { + fixes.push(fix); + } + } + let mut said: Vec = Vec::new(); + for fix in fixes { + let of_gem = |report: &&PinReport| report.gem_fix.as_deref() == Some(fix); + let builds: Vec<&PinReport> = reports.iter().filter(of_gem).collect(); + let patched = |build: &&&PinReport| build.uuid.is_some(); + let gained = builds + .iter() + .filter(patched) + .any(|build| build.newly_patched) + && builds + .iter() + .filter(patched) + .any(|build| !build.newly_patched); + if gained || builds.iter().any(|build| build.uuid.is_none()) { + said.extend(builds.into_iter().cloned()); + } + } + format_gem_build_lines(&said, &[], dry_run) +} diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 5c3f61d959..293aa9abb0 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -20,12 +20,21 @@ use socket_patch_core::patch::gem_refresh::{refresh, Source, Target, Wanted}; use crate::args::{GlobalArgs, RunApiClient}; use crate::ui::plural; -/// What the lock now pins: the hosted patch, or the upstream registry -/// entry an unwind put back. +/// What the lock now pins: the hosted patch, the upstream registry entry +/// an unwind put back, or, for one platform of a gem that stays on its +/// hosted patch, upstream's own gem again. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Direction { Patched, Upstream, + /// A hosted gem locked as platform builds, and a platform the patch + /// registry serves as upstream's own gem while a copy on disk holds + /// another build: the patched build that copy was installed from was + /// withdrawn, and the lock pins upstream's gem for that platform. The + /// hosted scan's guard finds it, so its codes and its retry are the + /// guard's ([`Direction::Patched`]); what replaces the copy is the + /// upstream gem. + Withdrawn, } impl Direction { @@ -33,7 +42,7 @@ impl Direction { fn wanted(self) -> &'static str { match self { Direction::Patched => "patched", - Direction::Upstream => "upstream", + Direction::Upstream | Direction::Withdrawn => "upstream", } } @@ -42,20 +51,43 @@ impl Direction { match self { Direction::Patched => "unpatched", Direction::Upstream => "patched", + Direction::Withdrawn => "withdrawn", } } - fn switched(self) -> &'static str { + /// What became of `gem`, before what is still stale of it. + fn switched(self, gem: &StaleGem) -> String { match self { - Direction::Patched => "was switched to its hosted patch", - Direction::Upstream => "is back on its upstream registry entry", + Direction::Patched => "was switched to its hosted patch".to_string(), + Direction::Upstream => "is back on its upstream registry entry".to_string(), + Direction::Withdrawn => { + let build = GemBuild::of_leaf(&gem.purl, &gem.leaf); + match build.and_then(|build| build.platform) { + Some(platform) => format!( + "is back on upstream's own gem for {platform}, whose patched build was \ + withdrawn" + ), + None => "is back on upstream's own gem, whose patched build was withdrawn" + .to_string(), + } + } + } + } + + /// Whether a re-run of the command can still refresh what this run + /// left: a scan finds the same copy again. An unwind can't be re-run: + /// its first run removed the wiring a second one would look for. + fn rerunnable(self) -> bool { + match self { + Direction::Patched | Direction::Withdrawn => true, + Direction::Upstream => false, } } /// The warning code of a materialization that is still stale. pub(crate) fn stale_code(self) -> &'static str { match self { - Direction::Patched => "redirect_gem_stale_install", + Direction::Patched | Direction::Withdrawn => "redirect_gem_stale_install", Direction::Upstream => "upstream_gem_stale_install", } } @@ -63,7 +95,7 @@ impl Direction { /// The `--json` note of a materialization this run refreshed. pub(crate) fn refreshed_code(self) -> &'static str { match self { - Direction::Patched => "redirect_gem_install_refreshed", + Direction::Patched | Direction::Withdrawn => "redirect_gem_install_refreshed", Direction::Upstream => "upstream_gem_install_refreshed", } } @@ -71,7 +103,7 @@ impl Direction { /// The `--json` note of a materialization a wet run would refresh. pub(crate) fn would_refresh_code(self) -> &'static str { match self { - Direction::Patched => "redirect_gem_install_would_refresh", + Direction::Patched | Direction::Withdrawn => "redirect_gem_install_would_refresh", Direction::Upstream => "upstream_gem_install_would_refresh", } } @@ -161,12 +193,12 @@ impl Policy { } if !self.shared && !resolves_inside(&self.root, path) { return Err(Why::OutOfTree( - match direction { - Direction::Patched => { + match direction.rerunnable() { + true => { "it is outside the project directory; `--gem-refresh-shared` refreshes \ it too" } - Direction::Upstream => "it is outside the project directory", + false => "it is outside the project directory", } .to_string(), )); @@ -201,6 +233,11 @@ pub(crate) enum Why { /// gem could not be had, for this reason. It is not known to be stale, /// and not known not to be. Unverified(String), + /// The copy is a precompiled build of this platform that Bundler loads + /// in place of the ruby-platform gem the lock names. The patched gem + /// of such a lock is the ruby-platform gem, which only an install + /// builds: no refresh was tried. + StandIn(String), } /// What one refresh pass did. @@ -216,6 +253,12 @@ pub(crate) struct Attempt { } impl Attempt { + /// Record that the pass left the materialization at `path` as it was, + /// for `why`, without trying it. + pub(crate) fn leave(&mut self, path: &Path, why: Why) { + self.left.insert(path.to_path_buf(), why); + } + /// Whether the pass changed anything on disk. pub(crate) fn changed(&self, policy: &Policy) -> bool { !policy.dry_run && !self.refreshed.is_empty() @@ -390,7 +433,7 @@ fn files_to_remove(gem: &StaleGem) -> Vec { /// Whether no gem home lists the gem dir `/gems/`: neither /// `specifications/.gemspec` nor the default gem's entry under /// `specifications/default/` is there. Only "not found" says so. -fn gemspec_is_gone(gem_dir: &Path) -> bool { +pub(crate) fn gemspec_is_gone(gem_dir: &Path) -> bool { let Some(spec) = home_spec(gem_dir) else { return false; }; @@ -536,16 +579,14 @@ fn display_list(paths: &[PathBuf]) -> String { /// every one of them does: a gem dir with no gemspec fails a re-run the /// same way, and a copy no Ruby owns needs its Ruby found first. fn retry_hint(direction: Direction, why: Option<&Why>, outlives: Option) -> &'static str { - match (why, direction) { - (Some(Why::Failed(_)), Direction::Patched) if outlives == Some(Outlives::NoGemspec) => "", - (Some(Why::Failed(_)), Direction::Patched) if outlives == Some(Outlives::ForeignRuby) => { + match (why, direction.rerunnable()) { + (Some(Why::Failed(_)), true) if outlives == Some(Outlives::NoGemspec) => "", + (Some(Why::Failed(_)), true) if outlives == Some(Outlives::ForeignRuby) => { "Re-run `socket-patch scan` with the Ruby that installed the gem first on `PATH` \ to retry, or " } - (Some(Why::Disabled), Direction::Patched) => { - "Re-run without `--no-gem-install-refresh`, or " - } - (Some(Why::Failed(_) | Why::OutOfTree(_)), Direction::Patched) => { + (Some(Why::Disabled), true) => "Re-run without `--no-gem-install-refresh`, or ", + (Some(Why::Failed(_) | Why::OutOfTree(_)), true) => { "Re-run `socket-patch scan` to retry, or " } _ => "", @@ -624,6 +665,11 @@ fn reason(why: Option<&Why>) -> String { format!(" ({reason})") } Some(Why::Disabled) => " (`--no-gem-install-refresh` is set)".to_string(), + Some(Why::StandIn(platform)) => format!( + " (it is a precompiled {platform} gem, which Bundler loads in place of the ruby \ + gem the lock names, and the patched gem of this lock is the ruby gem, which \ + `bundle install` builds)" + ), _ => String::new(), } } @@ -631,7 +677,7 @@ fn reason(why: Option<&Why>) -> String { /// The detail of one still-stale materialization (the `--json` warning). /// `why` is `None` where no refresh was attempted yet. pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Why>) -> String { - let (purl, switched) = (&gem.purl, direction.switched()); + let (purl, switched) = (&gem.purl, direction.switched(gem)); let (stale, wanted) = (direction.stale(), direction.wanted()); let reuse = format!("`bundle install` reuses an installed gem instead of fetching the {wanted} one"); @@ -646,7 +692,7 @@ pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Wh return if !project_local && !matches!( why, - Some(Why::Disabled | Why::Failed(_) | Why::OutOfTree(_)) + Some(Why::Disabled | Why::Failed(_) | Why::OutOfTree(_) | Why::StandIn(_)) ) { format!( "{held}. {IN_PLACE_REINSTALL}. Other projects may load that shared gem home, so \ @@ -686,7 +732,7 @@ pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Wh Some((dir, false)) if !matches!( why, - Some(Why::Disabled | Why::Failed(_) | Why::OutOfTree(_)) + Some(Why::Disabled | Why::Failed(_) | Why::OutOfTree(_) | Why::StandIn(_)) ) => { format!( @@ -694,11 +740,11 @@ pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Wh {}, and {reuse}. Other projects may load that gem home, so it was left alone. \ Install the {wanted} gem for this project only with `{LOCAL_PATH_REMEDY}`, or {}", dir.display(), - match direction { - Direction::Patched => { + match direction.rerunnable() { + true => { "re-run with `--gem-refresh-shared` to replace the shared copy".to_string() } - Direction::Upstream => format!( + false => format!( "replace the shared copy: remove {} and run `bundle install` ({})", display_list(&files_to_remove(gem)), other_projects_cost(1) @@ -824,6 +870,11 @@ pub(crate) fn report( } else { (direction.refreshed_code(), "replaced", "Replaced") }; + // Why the upstream gem takes the place of a copy on a hosted scan. + let because = match direction { + Direction::Withdrawn => " (its patched build was withdrawn)", + Direction::Patched | Direction::Upstream => "", + }; let (mut installed, mut archives, mut in_place) = (Vec::new(), Vec::new(), Vec::new()); for (purl, target) in &attempt.refreshed { let what = match target { @@ -850,7 +901,7 @@ pub(crate) fn report( } if !installed.is_empty() { out.progress.push(format!( - "{replaced} the installed copy of {} with the {wanted} build: {}.", + "{replaced} the installed copy of {} with the {wanted} build{because}: {}.", plural(installed.len(), "gem", "gems"), labels(installed.iter().copied()) )); @@ -865,7 +916,7 @@ pub(crate) fn report( } if !archives.is_empty() { out.progress.push(format!( - "{replaced} {} in Bundler's cache dir with the {wanted} gem: {}.", + "{replaced} {} in Bundler's cache dir with the {wanted} gem{because}: {}.", plural(archives.len(), "archive", "archives"), labels(archives.iter().copied()) )); @@ -926,6 +977,7 @@ pub(crate) fn report( let switch = match direction { Direction::Patched => "the switch to hosted patches", Direction::Upstream => "the switch back to the upstream registry", + Direction::Withdrawn => "the withdrawal of a patched build", }; let known = match direction { Direction::Patched if stale.iter().all(|gem| gem.in_place) => format!( @@ -948,6 +1000,10 @@ pub(crate) fn report( "{} the patched build on disk after {switch}", plural(count, "gem still holds", "gems still hold") ), + Direction::Withdrawn => format!( + "{} a patched build on disk that was withdrawn", + plural(count, "gem still holds", "gems still hold") + ), }; let headline = match (count, unchecked.len()) { (_, 0) => known, @@ -988,14 +1044,14 @@ pub(crate) fn report( place from the upstream archive beside it. ", ); } - bullets.push(match direction { - Direction::Patched => format!( + bullets.push(match direction.rerunnable() { + true => format!( "{why}To install {them} for this project only, run `{LOCAL_PATH_REMEDY}`, or \ re-run with `--gem-refresh-shared` to replace the shared {copies}." ), // An unwind can't be re-run (see `retry_hint`), so the shared // copies are replaced by hand (#2086). - Direction::Upstream => format!( + false => format!( "{why}To install {them} for this project only, run `{LOCAL_PATH_REMEDY}`. To \ replace the shared {copies}, run `{}`; {}.", reinstall_command(&shared_files, false), @@ -1299,7 +1355,7 @@ pub(crate) fn view_record( uuid: &str, ) -> Option { view.map(|view| socket_patch_core::manifest::records::record_from_patch_response(&view).1) - .filter(|record| record.uuid == uuid && !record.files.is_empty()) + .filter(|record| record.uuid.eq_ignore_ascii_case(uuid) && !record.files.is_empty()) } /// Why a hosted unwind has no patch record to judge an installed copy by. @@ -1927,6 +1983,76 @@ mod tests { .await } + /// A precompiled build that Bundler loads in place of the ruby gem + /// its lock names is left as it is, in the project's own gem home too: + /// the warning says what the copy is and which gem the lock patches, + /// and offers the command alone. A second scan would do the same, so + /// no retry is offered. + #[tokio::test] + async fn a_precompiled_stand_in_is_left_with_its_reason_and_the_command() { + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let home = proj.join("vendor/bundle/ruby/3.4.0"); + let mut gem = installed("nokogiri", &home, true); + let dir = home.join("gems/nokogiri-1.0.0-arm64-darwin"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + home.join("specifications/nokogiri-1.0.0-arm64-darwin.gemspec"), + "", + ) + .unwrap(); + gem.leaf = "nokogiri-1.0.0-arm64-darwin".to_string(); + gem.installed = Some((dir.clone(), true)); + let policy = policy(&proj, true, false, false); + let mut pass = pass(&[], &policy).await; + pass.leave(&dir, Why::StandIn("arm64-darwin".to_string())); + assert!(!pass.changed(&policy)); + + let out = report( + Direction::Patched, + std::slice::from_ref(&gem), + &pass, + &policy, + ); + let why = "it is a precompiled arm64-darwin gem, which Bundler loads in place of the \ + ruby gem the lock names, and the patched gem of this lock is the ruby gem, \ + which `bundle install` builds"; + // Joined a component at a time, as the code builds them: on Windows + // a `/` inside a component stays a `/`. + let spec = home + .join("specifications") + .join("nokogiri-1.0.0-arm64-darwin.gemspec"); + let archive = home.join("cache").join("nokogiri-1.0.0-arm64-darwin.gem"); + assert_eq!( + out.warnings, + [( + "redirect_gem_stale_install", + format!( + "pkg:gem/nokogiri@1.0.0 was switched to its hosted patch, but its unpatched \ + install at {} was not refreshed ({why}), and `bundle install` reuses an \ + installed gem instead of fetching the patched one. Remove {}, {} and run \ + `bundle install`", + dir.display(), + spec.display(), + archive.display() + ) + )] + ); + let summary = out.summary.expect("a summary"); + assert_eq!( + summary.headline, + "1 gem is still unpatched on disk after the switch to hosted patches" + ); + assert_eq!( + summary.bullets, + [format!( + "Not refreshed ({why}): nokogiri 1.0.0. Run `rm -f {} {} && bundle install`.", + shell_word(&spec), + shell_word(&archive) + )] + ); + } + /// Four gems in a shared home are one warning: the home, the gems, why /// in a sentence, and the remedy as a command. #[tokio::test] @@ -2861,6 +2987,224 @@ mod tests { ); } + /// The copy of a withdrawn build, where the lock pins upstream's gem + /// for the platform: the hosted scan's guard reports it under its own + /// codes and with its own retries (a scan can be re-run), and every + /// line says what the copy is and that the upstream gem takes its + /// place. Nothing calls the result patched. + #[tokio::test] + async fn the_copy_of_a_withdrawn_build_is_replaced_with_the_upstream_gem() { + let withdrawn = Direction::Withdrawn; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let platform_gem = |name: &str, home: &Path, project_local: bool| { + let mut gem = installed(name, home, project_local); + let (dir, _) = gem.installed.take().unwrap(); + let platform_dir = dir.with_file_name(format!("{name}-1.0.0-arm64-darwin")); + std::fs::rename(&dir, &platform_dir).unwrap(); + let specs = home.join("specifications"); + std::fs::rename( + specs.join(format!("{name}-1.0.0.gemspec")), + specs.join(format!("{name}-1.0.0-arm64-darwin.gemspec")), + ) + .unwrap(); + gem.leaf = format!("{name}-1.0.0-arm64-darwin"); + gem.installed = Some((platform_dir, project_local)); + gem + }; + let home = proj.join("vendor/bundle/ruby/3.4.0"); + let local = platform_gem("rexml", &home, true); + let (dir, _) = local.installed.clone().unwrap(); + + // Replaced: the notes and the progress line. + let replaced = Attempt { + refreshed: vec![ + ( + "pkg:gem/rexml@1.0.0".to_string(), + Target::Installed(dir.clone()), + ), + ( + "pkg:gem/rexml@1.0.0".to_string(), + Target::CacheArchive(PathBuf::from( + "vendor/cache/rexml-1.0.0-arm64-darwin.gem", + )), + ), + ], + ..Attempt::default() + }; + let out = report( + withdrawn, + &[], + &replaced, + &policy(&proj, true, false, false), + ); + assert!(out.summary.is_none()); + assert_eq!( + out.progress, + [ + "Replaced the installed copy of 1 gem with the upstream build (its patched build \ + was withdrawn): rexml 1.0.0.", + "Replaced 1 archive in Bundler's cache dir with the upstream gem (its patched \ + build was withdrawn): rexml 1.0.0.", + ] + ); + assert_eq!( + out.warnings, + [ + ( + "redirect_gem_install_refreshed", + format!( + "pkg:gem/rexml@1.0.0: replaced the withdrawn install at {} with the \ + upstream gem", + dir.display() + ) + ), + ( + "redirect_gem_install_refreshed", + "pkg:gem/rexml@1.0.0: replaced the withdrawn archive at \ + vendor/cache/rexml-1.0.0-arm64-darwin.gem with the upstream gem" + .to_string() + ), + ] + ); + let dry = report(withdrawn, &[], &replaced, &policy(&proj, true, false, true)); + assert!( + dry.progress[0].starts_with( + "Would replace the installed copy of 1 gem with the upstream build (its patched \ + build was withdrawn)" + ) && dry + .warnings + .iter() + .all(|(code, _)| *code == "redirect_gem_install_would_refresh"), + "{dry:?}" + ); + + // Left as it is: what it is, why, and how to remove it. A scan can + // be re-run, so the retry is offered. + let off = policy(&proj, false, false, false); + let stale = [local.clone()]; + let out = report(withdrawn, &stale, &pass(&stale, &off).await, &off); + let spec = home + .join("specifications") + .join("rexml-1.0.0-arm64-darwin.gemspec"); + let archive = home.join("cache").join("rexml-1.0.0-arm64-darwin.gem"); + assert_eq!( + out.warnings, + [( + "redirect_gem_stale_install", + format!( + "pkg:gem/rexml@1.0.0 is back on upstream's own gem for arm64-darwin, whose \ + patched build was withdrawn, but its withdrawn install at {} was not \ + refreshed (`--no-gem-install-refresh` is set), and `bundle install` reuses \ + an installed gem instead of fetching the upstream one. Re-run without \ + `--no-gem-install-refresh`, or remove {}, {} and run `bundle install`", + dir.display(), + spec.display(), + archive.display() + ) + )] + ); + let summary = out.summary.expect("a summary"); + assert_eq!( + summary.headline, + "1 gem still holds a patched build on disk that was withdrawn" + ); + assert_eq!( + summary.bullets, + [format!( + "Not refreshed (`--no-gem-install-refresh` is set): rexml 1.0.0. Re-run without \ + `--no-gem-install-refresh`, or run `rm -f {} {} && bundle install`.", + shell_word(&spec), + shell_word(&archive) + )] + ); + + // A run that may not download (`--offline`) and holds no verified + // copy of the upstream gem: the same warning, with that reason. + let on = policy(&proj, true, false, false); + let upstream_gem = |gem: &StaleGem| { + Some(Wanted { + leaf: gem.leaf.clone(), + kind: "upstream", + sha256: BTreeSet::from(["0".repeat(64)]), + urls: vec!["http://127.0.0.1:9/gems/rexml.gem".to_string()], + on_disk: Vec::new(), + }) + }; + let tried = attempt(&stale, upstream_gem, &Source::DiskOnly, &on, withdrawn).await; + let out = report(withdrawn, &stale, &tried, &on); + assert_eq!( + out.summary.expect("a summary").bullets, + [format!( + "Not refreshed (this run is offline and no verified copy of the upstream gem is \ + on disk): rexml 1.0.0. Re-run `socket-patch scan` to retry, or run `rm -f {} {} \ + && bundle install`.", + shell_word(&spec), + shell_word(&archive) + )] + ); + + // The tree of another Ruby beside the gem home (#2242): Bundler + // puts upstream's gem into the gem home of the Ruby that runs it, + // so a withdrawn copy left before any Ruby was asked is removed + // with its gem directory, as any other stale copy is. + let other = home.with_file_name("3.3.0"); + std::fs::create_dir_all(other.join("gems")).unwrap(); + std::fs::create_dir_all(other.join("specifications")).unwrap(); + let out = report(withdrawn, &stale, &tried, &on); + let bullets = out.summary.expect("a summary").bullets; + assert_eq!(bullets.len(), 1, "{bullets:?}"); + let command = format!( + "Re-run `socket-patch scan` to retry, or run `rm -rf {} {} ", + shell_word(&dir), + shell_word(&spec) + ); + assert!( + bullets[0].contains(&command) + && bullets[0].contains("&& bundle install`") + && bullets[0].contains(BESIDE_ANOTHER_RUBY) + && !bullets[0].contains("rm -f "), + "{bullets:?}" + ); + let detail = &out.warnings[0].1; + assert!( + detail.contains(&format!("remove {}, {}", dir.display(), spec.display())) + && detail.contains(BESIDE_ANOTHER_RUBY), + "{detail}" + ); + std::fs::remove_dir_all(&other).unwrap(); + + // In a gem home other projects load: left alone, with the flag + // that covers it. + let shared = platform_gem("rack", &tmp.path().join("gemhome"), false); + let stale = [shared]; + let out = report(withdrawn, &stale, &pass(&stale, &on).await, &on); + let detail = &out.warnings[0].1; + assert!( + detail.contains("but the shared gem home still holds its withdrawn install at") + && detail.ends_with( + "Install the upstream gem for this project only with `bundle config set \ + --local path vendor/bundle && bundle install`, or re-run with \ + `--gem-refresh-shared` to replace the shared copy" + ), + "{detail}" + ); + let summary = out.summary.expect("a summary"); + assert_eq!( + summary.headline, + "1 gem still holds a patched build on disk that was withdrawn" + ); + assert!( + summary.bullets[1].starts_with( + "`bundle install` reuses an installed gem instead of fetching the upstream one. \ + To install it for this project only, run" + ) && summary.bullets[1] + .ends_with("or re-run with `--gem-refresh-shared` to replace the shared copy."), + "{:?}", + summary.bullets + ); + } + /// What a pass may replace: the project's own copies; a shared home, or /// a project path that resolves outside the project, only with /// `--gem-refresh-shared`; nothing with `--no-gem-install-refresh`. diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index c418c32af0..6e1e55e105 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -1,8 +1,7 @@ use clap::Args; use futures_util::StreamExt; use socket_patch_core::api::client::{ - build_proxy_fallback_client, get_api_client_with_overrides, hold_back_debug, - is_fallback_candidate, ApiClient, ApiError, + get_api_client_with_overrides, hold_back_debug, is_fallback_candidate, ApiClient, ApiError, }; use socket_patch_core::api::ranking::{cmp_search_results, severity_order}; use socket_patch_core::api::types::{ @@ -10,12 +9,15 @@ use socket_patch_core::api::types::{ }; use socket_patch_core::crawlers::fuzzy_match::fuzzy_match_packages; use socket_patch_core::formats::pnpm::PnpmLock; +use socket_patch_core::hosted::engine::is_platform_gem_patch; use socket_patch_core::manifest::operations::{read_manifest, write_manifest}; use socket_patch_core::manifest::records::{build_patch_record, files_for_manifest}; use socket_patch_core::manifest::schema::PatchManifest; use socket_patch_core::telemetry::{track_patch_fetch_failed, track_patch_fetched, TelemetryAuth}; use socket_patch_core::utils::concurrent::{api_concurrency_for, ordered_concurrent}; -use socket_patch_core::utils::purl::{canonical_purl, normalize_purl, strip_purl_qualifiers}; +use socket_patch_core::utils::purl::{ + canonical_purl, normalize_purl, purl_parts, purl_qualifier, strip_purl_qualifiers, +}; use socket_patch_core::utils::purl_key::PurlKey; use socket_patch_core::utils::target::{Target, TargetKind}; use socket_patch_core::vendor::load_state; @@ -1226,6 +1228,105 @@ pub(crate) async fn download_patch_records_with( download_patch_records_reusing(selected, params, api_client, prefetched, None).await } +/// Warning code of a hosted `get ` whose UUID names the patch of one +/// platform gem, when no patch of the gem itself could be taken for it +/// ([`PlatformGemPatch`]): the run pins nothing, and the warning names the +/// command that patches the gem. +const PLATFORM_GEM_PATCH_NOT_TAKEN: &str = "platform_gem_patch_not_taken"; + +/// The patch of one platform gem (`pkg:gem/@?platform=…`) +/// that a hosted or a vendored `get` was given by its UUID. Such a run +/// patches a gem through the patch of the gem itself, whose reference +/// names the patched build of every platform: it takes the patch this one +/// was built from ([`Self::gem_patch`]) and goes on as it does for that +/// patch's UUID. +struct PlatformGemPatch { + uuid: String, + purl: String, + /// ` `, as the run's lines name a gem. + gem: String, + platform: String, + /// The gem's patch the run took in its place, once it has one. + gem_fix: Option, +} + +impl PlatformGemPatch { + /// `patch` as the patch of a platform gem; `None` for any other. + fn of(patch: &PatchResponse) -> Option { + if !is_platform_gem_patch(&patch.purl) { + return None; + } + let (_, name, version) = purl_parts(&patch.purl)?; + Some(PlatformGemPatch { + uuid: patch.uuid.clone(), + purl: patch.purl.clone(), + gem: format!("{name} {version}"), + platform: purl_qualifier(&patch.purl, "platform")?.to_string(), + gem_fix: None, + }) + } + + /// The gem's patch: the one this patch's package reference names as + /// what it was built from (`rebuiltFromUuid`). One reference request, + /// then the fetch of that record. `None` when the reference names no + /// patch, a request fails, or the patch named is not the patch of this + /// gem itself. + async fn gem_patch(&self, api_client: &ApiClient) -> Option { + let references = api_client + // The patch of a platform build has no listing to present. + .fetch_registry_references(std::slice::from_ref(&self.uuid), &Default::default()) + .await + .ok()?; + let built_from = references.get(&self.uuid)?.rebuilt_from_uuid.as_deref()?; + // The value goes into a request path: a patch UUID or nothing. + if Target::parse(built_from).kind() != TargetKind::Uuid { + return None; + } + let gem_patch = api_client.fetch_patch(built_from).await.ok()??; + (!is_platform_gem_patch(&gem_patch.purl) + && canonical_purl(&gem_patch.purl) == canonical_purl(&self.purl)) + .then_some(gem_patch) + } + + /// The one line that says which patch the run took (stderr). + fn taken_line(&self, mode: &str) -> Option { + let gem_fix = self.gem_fix.as_deref()?; + Some(format!( + "{} is the patch of {}'s {} build; {mode} mode takes the gem's patch {gem_fix}, \ + which it was built from", + self.uuid, self.gem, self.platform + )) + } + + /// The same fact for the envelope (`platformGemPatch`). + fn taken_json(&self) -> Option { + let gem_fix = self.gem_fix.as_deref()?; + Some(serde_json::json!({ + "uuid": self.uuid, + "purl": self.purl, + "platform": self.platform, + "gemFix": gem_fix, + })) + } + + /// What a run that found no gem's patch to take says of this one: it + /// is no fix of its own in `mode`, and the command that patches the + /// gem there. + fn not_taken(&self, mode: &str) -> String { + let gem = canonical_purl(&self.purl); + // Each command is spelled out whole, as a person would run it. + let run = match mode { + "vendored" => format!("Run `socket-patch get {gem} --mode vendored` instead"), + _ => format!("Run `socket-patch get {gem} --mode hosted` instead"), + }; + format!( + "{} is the patch of {}'s {} build, which {mode} mode does not take by itself: it \ + patches a gem through the gem's own patch. {run}", + self.uuid, self.gem, self.platform, + ) + } +} + pub async fn run(args: GetArgs) -> i32 { // Validate flags let type_flags = [args.id, args.cve, args.ghsa, args.package] @@ -1362,8 +1463,14 @@ pub async fn run(args: GetArgs) -> i32 { eprintln!("Treating \"{}\" as a package name search", args.identifier); } let overrides = args.common.api_client_overrides(); - let (mut api_client, mut use_public_proxy) = - get_api_client_with_overrides(overrides.clone()).await; + let (api_client, mut use_public_proxy) = get_api_client_with_overrides(overrides.clone()).await; + // A hosted or a vendored run patches a gem through the patch of the + // gem itself: the patch of one of its platform gems, which a search + // returns beside it, is no fix of its own there, so the run's client + // answers every search without them. (One named by its UUID stands + // for the gem's patch: see `PlatformGemPatch`.) + let mut api_client = + api_client.offering_platform_gem_patches(mode == super::scan::ScanMode::Agent); let telemetry = TelemetryAuth::for_client(&api_client); // A token whose org could not be resolved put the whole run on the // public proxy (the client already warned on stderr): `--json` @@ -1407,7 +1514,7 @@ pub async fn run(args: GetArgs) -> i32 { // Building the proxy client may print core's proxy // notice straight to stderr: take the line down first. status.finish(); - api_client = build_proxy_fallback_client(&overrides); + api_client = api_client.proxy_fallback(&overrides); use_public_proxy = true; fallback_to_proxy = true; status.set(format!("Fetching patch {}...", args.identifier)); @@ -1416,6 +1523,36 @@ pub async fn run(args: GetArgs) -> i32 { } } status.finish(); + // The patch of one platform gem is no fix of its own in hosted and + // vendored mode: the run takes the gem's patch, which it was built + // from, and goes on below as it does for that patch's UUID. (A + // patch outside the run's ecosystems, or a paid one on the public + // proxy, gets its own answer below and costs no request here.) + let mut platform_gem: Option = None; + if mode != super::scan::ScanMode::Agent { + let named = fetch_result.as_ref().ok().and_then(Option::as_ref); + let asked = named.and_then(PlatformGemPatch::of).filter(|_| { + named.is_some_and(|patch| { + args.common.purl_ecosystem_selected(&patch.purl) + && !(patch.tier == "paid" && use_public_proxy) + }) + }); + if let Some(mut asked) = asked { + status.set(format!("Fetching the patch of {}...", asked.gem)); + let gem_patch = asked.gem_patch(&api_client).await; + status.finish(); + if let Some(gem_patch) = gem_patch { + asked.gem_fix = Some(gem_patch.uuid.clone()); + fetch_result = Ok(Some(gem_patch)); + } + if let Some(line) = asked.taken_line(mode.cli_name()).filter(|_| !quiet) { + let width = crate::ui::attended(crate::ui::Stream::Stderr) + .then(crate::ui::stderr_width); + eprintln!("{}", crate::ui::wrap_line(&line, width)); + } + platform_gem = Some(asked); + } + } match fetch_result { Ok(Some(patch)) => { // The search path's selection rules hold here too: a patch @@ -1492,6 +1629,17 @@ pub async fn run(args: GetArgs) -> i32 { // (`policy_bypassed`). let mut uuid_warnings = super::scan::policy::policy_bypass_warnings(&args.common, &selected); + // A platform gem's patch that no gem's patch was taken for + // reaches the hosted engine, which pins nothing for it: + // say what to run. (The vendored refusal says it itself.) + if let Some(asked) = platform_gem.as_ref().filter(|asked| { + asked.gem_fix.is_none() && mode == super::scan::ScanMode::Hosted + }) { + uuid_warnings.push(( + PLATFORM_GEM_PATCH_NOT_TAKEN.to_string(), + asked.not_taken(mode.cli_name()), + )); + } if !args.common.silent { for (_, detail) in &uuid_warnings { eprintln!("Warning: {detail}"); @@ -1512,7 +1660,15 @@ pub async fn run(args: GetArgs) -> i32 { save_and_apply_patch(&args, &api_client, &patch, &uuid_warnings).await } super::scan::ScanMode::Hosted => { - run_get_hosted(&args, &api_client, &selected, &[], &uuid_warnings).await + run_get_hosted( + &args, + &api_client, + &selected, + platform_gem.as_ref(), + &[], + &uuid_warnings, + ) + .await } super::scan::ScanMode::Vendored => { run_get_vendored( @@ -1521,6 +1677,7 @@ pub async fn run(args: GetArgs) -> i32 { use_public_proxy, &selected, Some(&patch), + platform_gem.as_ref(), &[], &uuid_warnings, &telemetry, @@ -1982,6 +2139,7 @@ pub async fn run(args: GetArgs) -> i32 { &args, &api_client, &selected, + None, &narrow_skips, &narrow_warnings, ) @@ -1994,6 +2152,7 @@ pub async fn run(args: GetArgs) -> i32 { use_public_proxy, &selected, None, + None, &narrow_skips, &narrow_warnings, &telemetry, @@ -2496,11 +2655,14 @@ fn get_download_params(args: &GetArgs, save_only: bool, persist_blobs: bool) -> /// matches `scan --mode hosted` selecting the same patches. The engine owns /// all output (and honors `--dry-run` internally); in JSON mode it records /// its events (`details.mode: "hosted"`) into the get envelope passed as -/// `scan_result` and prints it. +/// `scan_result` and prints it. `platform_gem` is the platform gem's patch +/// the run was given by its UUID, when `selected` is the gem's patch taken +/// for it: the envelope names it (`platformGemPatch`). async fn run_get_hosted( args: &GetArgs, api_client: &ApiClient, selected: &[PatchSearchResult], + platform_gem: Option<&PlatformGemPatch>, narrow_skips: &[PatchEvent], narrow_warnings: &[(String, String)], ) -> i32 { @@ -2513,6 +2675,9 @@ async fn run_get_hosted( let scan_result = args.common.json.then(|| { let mut env = new_envelope(&args.common); fold_narrowing_into_result(&mut env, narrow_skips, narrow_warnings); + if let Some(taken) = platform_gem.and_then(PlatformGemPatch::taken_json) { + env.set_extra("platformGemPatch", taken); + } env }); // Embedded VEX stays a scan/vendor feature (get has no --vex): a @@ -2551,6 +2716,12 @@ async fn run_get_hosted( /// pre-record envelope, so a refused run writes nothing at all; the search /// path lets the download phase record the refusal per patch and still runs /// the vendor step (scan parity). +/// +/// `platform_gem` is the platform gem's patch the uuid path was given. With +/// the gem's patch taken for it (`prefetched`), the envelope names it +/// (`platformGemPatch`). With none taken, `prefetched` is that patch itself +/// and is refused `platform_gem_unsupported` before the engine, with the +/// command that vendors the gem. #[allow(clippy::too_many_arguments)] async fn run_get_vendored( args: &GetArgs, @@ -2558,16 +2729,27 @@ async fn run_get_vendored( use_public_proxy: bool, selected: &[PatchSearchResult], prefetched: Option<&PatchResponse>, + platform_gem: Option<&PlatformGemPatch>, narrow_skips: &[PatchEvent], narrow_warnings: &[(String, String)], telemetry: &TelemetryAuth, ) -> i32 { let mut env = new_envelope(&args.common); fold_narrowing_into_result(&mut env, narrow_skips, narrow_warnings); - // Dry run: ledger-classification preview only (scan's posture) — no - // download, no vendor step, no writes. + if let Some(taken) = platform_gem.and_then(PlatformGemPatch::taken_json) { + env.set_extra("platformGemPatch", taken); + } + // Dry run: scan's preview, with no download, no vendor step and no + // writes. The ledger classification, then what the patch service says + // of the gems the lock names as platform gems, asked through this + // run's client: the route the wet run's vendor step takes, a fallback + // to the public proxy included. `get` plans no rollout, so every row + // is in the run. if args.common.dry_run { - let preview = super::scan::preview_vendor(&args.common, selected).await; + let mut preview = super::scan::classify_vendor(&args.common, selected).await; + preview + .ask_platform_gems(&args.common, api_client, use_public_proxy) + .await; if args.common.json { preview.record_into(&mut env); emit(&env); @@ -2603,13 +2785,23 @@ async fn run_get_vendored( // Human: `Error (): ` on stderr — an error, so it is // exempt from `--silent` like every other `Error (…)` line here. let vendor_state = load_state(&args.common.project_root()).await; - let refusals = Box::pin(vendored_download_refusals( + let mut refusals = Box::pin(vendored_download_refusals( ¶ms, selected, vendor_state.as_ref().map(|s| &s.entries), None, )) .await; + // A platform gem's patch that no gem's patch was taken for: what + // the project's own files refuse it for, if anything, comes first. + if let Some(asked) = platform_gem.filter(|asked| asked.gem_fix.is_none()) { + refusals + .entry(patch.purl.clone()) + .or_insert_with(|| VendorRefusal { + code: "platform_gem_unsupported", + detail: asked.not_taken("vendored"), + }); + } if let Some(VendorRefusal { code, detail }) = refusals.get(&patch.purl) { // An expected skip (a gem version this project doesn't lock) // is not an error: the same `skipped` event and `[skip]` line diff --git a/crates/socket-patch-cli/src/commands/mod.rs b/crates/socket-patch-cli/src/commands/mod.rs index c7975f2ce6..9d096e6603 100644 --- a/crates/socket-patch-cli/src/commands/mod.rs +++ b/crates/socket-patch-cli/src/commands/mod.rs @@ -3,6 +3,7 @@ pub mod apply; pub(crate) mod composer_hints; pub(crate) mod context; pub(crate) mod fetch_stage; +pub(crate) mod gem_build_lines; pub(crate) mod gem_refresh; pub mod get; pub mod hosted_bundle; diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 33f77b8645..573babfbf6 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -13,12 +13,15 @@ use socket_patch_core::patch::redirect::DepOverride; use socket_patch_core::utils::concurrent::api_concurrency; use socket_patch_core::utils::purl::purl_parts; +use crate::commands::gem_build_lines::format_gem_build_lines; + use crate::commands::agent_download::tag_mode; use crate::commands::gem_refresh::{self, StaleGem}; use crate::commands::vex::generate_vex_from_manifest_path; use crate::json_envelope::{ Envelope, EnvelopeError, PatchAction, PatchEvent, RunWarning, VexSummary, }; +use crate::ui::{wrap_line, wrap_words}; use socket_patch_core::formats::gem::GemBuild; use super::{discover_selected, emit_scan, scan_envelope, ScanArgs}; @@ -257,6 +260,24 @@ async fn check_mirror( text.contains(url) || text.contains(encoded.as_str()) || text.contains(escaped.as_str()) }) }; + // A gem the Bundler lock names as its ruby-platform gem alone is pinned + // under its registry without the snapshot level. The registry's URL at + // a snapshot starts with that address, so the pin is one only where no + // snapshot level follows it. + let pinned_without_snapshot = |ov: &socket_patch_core::patch::redirect::RegistryOverride| { + let (root, snapshot) = + socket_patch_core::patch::redirect::split_gem_snapshot(&ov.index_url); + if ov.kind != "rubygems-compact-index" || snapshot.is_none() { + return false; + } + let root = root.trim_end_matches('/'); + files.values().any(|text| { + text.match_indices(root).any(|(at, _)| { + let rest = &text[at + root.len()..]; + !rest.strip_prefix('/').unwrap_or(rest).starts_with("s/") + }) + }) + }; let mut asked = std::collections::BTreeSet::new(); let new_pins: Vec = candidates .iter() @@ -267,7 +288,10 @@ async fn check_mirror( .registry_override .as_ref() .map(|ov| ov.index_url.trim_end_matches('/')); - !already_pinned(&dep.artifact_url) && !index.is_some_and(already_pinned) + let keyless = dep.registry_override.as_ref(); + !already_pinned(&dep.artifact_url) + && !index.is_some_and(already_pinned) + && !keyless.is_some_and(pinned_without_snapshot) }) .filter(|dep| asked.insert(dep.artifact_url.clone())) .map(|dep| dep.artifact_url.clone()) @@ -388,44 +412,140 @@ pub(super) const VEX_HOSTED_UNVERIFIED: &str = "vex_hosted_unverified"; /// uuid: `applied` (`verified` on a dry run) for each confirmed pin, `skipped` /// with the skip's code, and `skipped` / `redirect_unconfirmed` for each /// granted patch no lockfile entry pins. None of them change status or exit. +/// +/// `reports` are the confirmed pins as the run reports them +/// ([`engine::pin_reports`]): a gem the lock names as platform builds has +/// one event per locked build, whose `details` name the gem patch +/// (`gemFix`) and the build's `platform` (none for the ruby-platform gem). +/// A patched build is `applied` under its own patch, with `newlyPatched: +/// true` when this run put it in place. A build the patch registry serves +/// as upstream's own gem is an advisory `skipped` event with no `uuid` +/// ([`engine::GEM_UPSTREAM_BUILD_KEPT`]), which `summary` does not count: +/// nothing was skipped, that platform is as it was. Where this run put +/// the build back on upstream's gem because its patched build was +/// withdrawn, the event says so (`details.withdrawn: true`, and its +/// `reason`). +/// +/// [`engine::pin_reports`]: socket_patch_core::hosted::engine::pin_reports +/// [`engine::GEM_UPSTREAM_BUILD_KEPT`]: socket_patch_core::hosted::engine::GEM_UPSTREAM_BUILD_KEPT pub(super) fn record_hosted_events( env: &mut Envelope, - confirmed: &[(String, String)], + reports: &[socket_patch_core::hosted::engine::PinReport], unconfirmed: &[(String, String)], skipped: &[socket_patch_core::hosted::engine::SkippedPatch], dry_run: bool, changes: &pin_changes::PinChanges<'_>, ) { - for event in hosted_events(confirmed, unconfirmed, skipped, dry_run, Some(changes)) { - env.record(event); + use socket_patch_core::hosted::engine::GEM_UPSTREAM_BUILD_KEPT; + for event in hosted_events(reports, unconfirmed, skipped, dry_run, Some(changes)) { + if event.error_code.as_deref() == Some(GEM_UPSTREAM_BUILD_KEPT) { + env.events.push(event); + } else { + env.record(event); + } } } +/// The pins of `confirmed` that put a patch in effect: all of them but a +/// gem the lock names as platform builds none of which is patched (every +/// one is served as upstream's own gem: a lock that followed a withdrawn +/// build back). Such a gem is on the patch registry and installs nothing +/// patched, so it is no package on a hosted patch: the telemetry, the +/// summary line and the rows under it count what is in effect, as the +/// envelope's events do. +fn pins_in_effect( + confirmed: &[(String, String)], + rewrite: &socket_patch_core::patch::redirect::RewriteResult, +) -> Vec<(String, String)> { + let unpatched = |uuid: &String| { + let builds = rewrite.gem_builds.get(uuid); + builds.is_some_and(|builds| builds.iter().all(|build| build.patch_uuid.is_none())) + }; + let mut pins = confirmed.to_vec(); + pins.retain(|(_, uuid)| !unpatched(uuid)); + pins +} + +/// Each pin of `confirmed` as its own report: what a run's telemetry +/// names, one patch per package, where the envelope reports a gem locked +/// as platform builds per build. +fn pin_reports_by_package( + confirmed: &[(String, String)], +) -> Vec { + confirmed + .iter() + .map( + |(purl, uuid)| socket_patch_core::hosted::engine::PinReport { + purl: purl.clone(), + uuid: Some(uuid.clone()), + gem_fix: None, + platform: None, + newly_patched: false, + withdrawn: false, + }, + ) + .collect() +} + /// A hosted run's per-patch outcomes as events, tagged `mode: "hosted"` /// (see [`record_hosted_events`]): what the envelope records and what the -/// run's telemetry names. +/// run's telemetry names. Only the advisory event of a gem build left on +/// upstream's gem has no `uuid`. fn hosted_events( - confirmed: &[(String, String)], + reports: &[socket_patch_core::hosted::engine::PinReport], unconfirmed: &[(String, String)], skipped: &[socket_patch_core::hosted::engine::SkippedPatch], dry_run: bool, changes: Option<&pin_changes::PinChanges<'_>>, ) -> Vec { + use socket_patch_core::hosted::engine::{ + gem_upstream_build_kept_detail, GEM_UPSTREAM_BUILD_KEPT, + }; let pinned = if dry_run { PatchAction::Verified } else { PatchAction::Applied }; - let mut events: Vec = confirmed + let mut events: Vec = reports .iter() - .map(|(purl, uuid)| { - let event = PatchEvent::new(pinned, purl.as_str()).with_uuid(uuid.as_str()); - match changes { - Some(changes) => event.with_details(serde_json::json!({ - "pinChanged": changes.get(&(purl.as_str(), uuid.as_str())), - })), - None => event, + .map(|report| { + let mut event = match &report.uuid { + Some(uuid) => { + PatchEvent::new(pinned, report.purl.as_str()).with_uuid(uuid.as_str()) + } + None => PatchEvent::new(PatchAction::Skipped, report.purl.as_str()).with_reason( + GEM_UPSTREAM_BUILD_KEPT, + gem_upstream_build_kept_detail( + report.platform.as_deref().unwrap_or_default(), + report.withdrawn, + ), + ), + }; + let mut details = serde_json::Map::new(); + if let Some(gem_fix) = &report.gem_fix { + details.insert("gemFix".to_string(), serde_json::json!(gem_fix)); + if let Some(platform) = &report.platform { + details.insert("platform".to_string(), serde_json::json!(platform)); + } + if report.newly_patched { + details.insert("newlyPatched".to_string(), serde_json::json!(true)); + } + if report.withdrawn { + details.insert("withdrawn".to_string(), serde_json::json!(true)); + } + } + // On a confirmed pin's event alone: the advisory event of a + // build left on upstream's gem names no patch in place. + if let (Some(changes), Some(_)) = (changes, &report.uuid) { + details.insert( + "pinChanged".to_string(), + serde_json::json!(pin_changes::of_report(changes, report)), + ); } + if !details.is_empty() { + event.details = Some(serde_json::Value::Object(details)); + } + event }) .chain(skipped.iter().map(|s| { let mut event = @@ -525,6 +645,18 @@ struct StaleInstallOutcome { /// The gem probe's stale materializations, one per warning, for the /// refresh that follows it ([`refresh_stale_gems`]). gems: Vec, + /// The gem probe's copies of a platform build the patch registry + /// serves as upstream's own gem that are another build: a patched + /// build that was withdrawn. The refresh puts upstream's gem in their + /// place. Not among `stale_purls`: the document says `affected` of + /// such a build whatever is installed, and its copy says nothing of + /// the gem's other builds. + withdrawn: Vec, + /// The stale installed dirs among `gems` that are a precompiled build + /// Bundler loads in place of the ruby-platform gem the lock names, + /// each with its platform. The refresh leaves them: the patched gem + /// of such a lock is the ruby-platform gem, which a reinstall builds. + stand_ins: std::collections::BTreeMap, } /// The gem and Python stale-install probes' fallback: when a confirmed @@ -568,8 +700,10 @@ impl<'a> ViewFallback<'a> { ) -> Option<&socket_patch_core::manifest::schema::PatchRecord> { if !self.fetched.contains_key(uuid) { let record = match self.api { + // The file hashes are all a judgment needs: asked without + // the file contents. Some(api) => api - .fetch_patch(uuid) + .fetch_patch_summary(uuid) .await .ok() .and_then(|view| gem_refresh::view_record(view, uuid)), @@ -611,7 +745,17 @@ fn stale_installed_gem( /// guard" section of CLI_CONTRACT.md). `why` is why the refresh did not fix /// it; `None` describes it before any refresh. fn gem_stale_warning(gem: &StaleGem, why: Option<&gem_refresh::Why>) -> serde_json::Value { - let direction = gem_refresh::Direction::Patched; + gem_stale_warning_of(gem_refresh::Direction::Patched, gem, why) +} + +/// [`gem_stale_warning`] for a materialization that is stale in +/// `direction`: an unpatched copy of a patched build, or the copy of a +/// withdrawn build where the lock pins upstream's gem. +fn gem_stale_warning_of( + direction: gem_refresh::Direction, + gem: &StaleGem, + why: Option<&gem_refresh::Why>, +) -> serde_json::Value { serde_json::json!({ "code": direction.stale_code(), "detail": gem_refresh::stale_detail(direction, gem, why), @@ -656,6 +800,12 @@ fn stale_cache_gem(purl: &str, cache_path: &Path) -> StaleGem { /// with), the patch's view record judges the dir ([`ViewFallback`]). A /// dir that record cannot judge either (the fetch failed, or `--offline`) /// is reported in `unjudged_purls`, never as healthy. +/// * The copy of a platform build that has a patch of its own +/// (`gem_build_patches`, by leaf) is judged by its archive, else by the +/// record of that build's own patch, and never by the gem patch's +/// record, the agent-mode one included: a platform gem's files are not +/// the gem patch's. With neither it is unjudged: not stale, and not +/// replaced. /// * Judgments are grouped by installed dir: platform-variant purls of one /// gem share a dir, and if any variant proves it patched, it is never /// warned. @@ -667,7 +817,17 @@ fn stale_cache_gem(purl: &str, cache_path: &Path) -> StaleGem { /// * 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. +/// include its patched platform builds. +/// * A platform build the patch registry serves as upstream's own gem (no +/// patched build; `gem_upstream` gives the sha256 of that gem by leaf) +/// is pinned to upstream's gem by its lock entry. Its installed copy and +/// its archive in the cache dir are judged by that sha256 alone: an +/// archive that is upstream's gem is the right copy, and nothing is +/// reported, refreshed or downloaded for it. A readable archive with +/// another sha256 is a patched build that was withdrawn (`withdrawn`): +/// the lock does not install it, and `bundle install` keeps it. A copy +/// whose gem home holds no archive of it is not judged: no patch record +/// is fetched for a build that has no 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 @@ -676,6 +836,12 @@ fn stale_cache_gem(purl: &str, cache_path: &Path) -> StaleGem { /// platform build Bundler loads, or replace a build that is not this /// project's. Only where no lock names the gem (a global scan) is the /// first installed copy judged, as before. +/// * A lock whose `PLATFORMS` names `ruby` alone names every gem as its +/// ruby-platform gem, and Bundler loads an installed precompiled build +/// of the locked version in its place. Each such copy is judged beside +/// the ruby-platform gem, as the gem's own: an upstream one is what Ruby +/// runs, and no `bundle install` replaces it (`stand_ins`). +#[allow(clippy::too_many_arguments)] async fn gem_stale_install_warnings( cwd: &Path, global: bool, @@ -689,6 +855,8 @@ async fn gem_stale_install_warnings( (String, String), std::collections::BTreeSet, >, + gem_upstream: &std::collections::BTreeMap, + gem_build_patches: &std::collections::BTreeMap, views: &mut ViewFallback<'_>, ) -> StaleInstallOutcome { use socket_patch_core::crawlers::types::CrawlerOptions; @@ -771,8 +939,27 @@ async fn gem_stale_install_warnings( .filter(|(_, builds)| builds.is_empty()) .map(|(purl, _)| purl.clone()) .collect(); + // The candidates the lock names as their ruby-platform gem alone, where + // Bundler loads an installed precompiled build in its place (module + // docs). + let loads_platform_copies = + socket_patch_core::vendor::lock_inventory::gem_lock_loads_platform_copies_in( + &socket_patch_core::vendor::lock_inventory::ProjectView::Disk(cwd), + ) + .await; + let stood_in = |builds: &[GemBuild]| { + loads_platform_copies && matches!(builds, [ruby] if ruby.platform.is_none()) + }; + let stand_in_purls: Vec = stripped + .iter() + .zip(&named) + .filter(|(_, builds)| stood_in(builds)) + .map(|(purl, _)| purl.clone()) + .collect(); // Per home: each candidate's installed dirs. let mut found_per_home = Vec::with_capacity(homes.len()); + let mut stand_in_dirs: std::collections::BTreeSet = + std::collections::BTreeSet::new(); for home in &homes { let mut by_leaf = crawler .find_builds(&home.gems_dir, &leaves) @@ -782,6 +969,10 @@ async fn gem_stale_install_warnings( .find_each_by_purl(&home.gems_dir, &unnamed) .await .into_iter(); + let mut platform_copies = crawler + .find_platform_builds(&home.gems_dir, &stand_in_purls) + .await + .into_iter(); let dirs: Vec> = named .iter() .map(|builds| { @@ -789,7 +980,17 @@ async fn gem_stale_install_warnings( let pkg = first.next().flatten(); pkg.map(|pkg| pkg.path).into_iter().collect() } else { - by_leaf.by_ref().take(builds.len()).flatten().collect() + let mut dirs: Vec = + by_leaf.by_ref().take(builds.len()).flatten().collect(); + if stood_in(builds) { + // A dir no gemspec lists is what an install left + // behind: neither RubyGems nor Bundler loads it. + let mut copies = platform_copies.next().unwrap_or_default(); + copies.retain(|dir| !gem_refresh::gemspec_is_gone(dir)); + stand_in_dirs.extend(copies.iter().cloned()); + dirs.extend(copies); + } + dirs } }) .collect(); @@ -797,6 +998,11 @@ async fn gem_stale_install_warnings( } let mut dir_state: std::collections::BTreeMap = std::collections::BTreeMap::new(); + // The installed copies of a build on upstream's gem that are another + // build: the candidate, the leaf, and whether the gem home is the + // project's own. + let mut withdrawn_dirs: std::collections::BTreeMap = + std::collections::BTreeMap::new(); // Bundler's configured cache dir (`cache_path`, default vendor/cache). let app_cache = socket_patch_core::crawlers::ruby_crawler::bundler_app_cache_dir(cwd).await; // Copies with no local evidence, judged by the view fallback below. @@ -812,6 +1018,24 @@ async fn gem_stale_install_warnings( let Some(leaf) = dir.file_name().and_then(|n| n.to_str()) else { continue; }; + // Upstream's own gem is what the lock pins for this build: the + // archive RubyGems installed the copy from is that gem, or the + // copy is a build that was withdrawn. Never for a copy that + // stands in for the ruby-platform gem: the lock pins that gem. + let stands_in = stand_in_dirs.contains(dir); + if let Some(upstream_sha) = gem_upstream.get(leaf).filter(|_| !stands_in) { + let archive = gem_refresh::home_cache_archive(dir); + let installed_from = match &archive { + Some(archive) => file_sha256_hex(archive).await, + None => None, + }; + if installed_from.is_some_and(|sha| !sha.eq_ignore_ascii_case(upstream_sha)) { + withdrawn_dirs + .entry(dir.clone()) + .or_insert_with(|| ((*purl).to_string(), leaf.to_string(), *project_local)); + } + continue; + } let entry = dir_state.entry(dir.clone()).or_insert_with(|| DirJudgment { purl: (*purl).to_string(), leaf: leaf.to_string(), @@ -841,7 +1065,12 @@ async fn gem_stale_install_warnings( _ => None, } }; - let judged = match local { + // A platform build with a patch of its own is a patch of its + // own: its files carry that patch's header (and, compiled, its + // binaries), so the gem patch's record says nothing true of it. + // Its archive judges it, else that build's own record (below). + let own_patch = gem_build_patches.get(leaf); + let judged = match local.filter(|_| own_patch.is_none()) { Some(record) => { let judged = judge_installed_record(dir, record).await; if judged.patched @@ -861,7 +1090,10 @@ async fn gem_stale_install_warnings( }; match judged { Some(judged) => entry.record(purl, judged), - None => pending.push((dir.clone(), purl, uuid)), + None => { + let record_of = own_patch.map_or(*uuid, String::as_str); + pending.push((dir.clone(), purl, record_of)); + } } } } @@ -927,10 +1159,48 @@ async fn gem_stale_install_warnings( ); out.warnings.push(gem_stale_warning(&gem, None)); out.gems.push(gem); + if !in_place && stand_in_dirs.contains(dir) { + let platform = GemBuild::of_leaf(&j.purl, &j.leaf).and_then(|build| build.platform); + out.stand_ins + .insert(dir.clone(), platform.unwrap_or_default()); + } // Every variant installed in this dir: VEX matches its exemptions // qualifier-insensitively, so one left out would re-exempt the dir. out.stale_purls.extend(j.purls.iter().cloned()); } + // The copies of a withdrawn build, each with the project's cache-dir + // archive of that build unless it is proven to be upstream's gem: + // bundler installs from it first. + let withdrawn = gem_refresh::Direction::Withdrawn; + for (dir, (purl, leaf, project_local)) in &withdrawn_dirs { + let project_cache = app_cache.join(format!("{leaf}.gem")); + let folded_cache = if *project_local && project_cache.is_file() { + let proven_upstream = match ( + gem_upstream.get(leaf), + file_sha256_hex(&project_cache).await, + ) { + (Some(want), Some(got)) => got.eq_ignore_ascii_case(want), + _ => false, + }; + (!proven_upstream).then_some(project_cache) + } else { + None + }; + if let Some(archive) = &folded_cache { + cache_covered.insert(archive.clone()); + } + let gem = stale_installed_gem( + purl, + dir, + leaf, + *project_local, + folded_cache.as_deref(), + false, + ); + out.warnings + .push(gem_stale_warning_of(withdrawn, &gem, None)); + out.withdrawn.push(gem); + } // Pass 3: standalone vendor/cache staleness — a committed archive whose // sha256 is readable and differs from the patched artifact's, unless a @@ -939,17 +1209,13 @@ async fn gem_stale_install_warnings( // otherwise never warn). One archive per build the lock names: the // ruby gem's alone where no lock names the gem. for (index, (purl, _, _)) in candidates.iter().enumerate() { - let Some(want_shas) = gem_artifact_shas.get(&gem_sha_key(purl)) else { - continue; - }; + let want_shas = gem_artifact_shas.get(&gem_sha_key(purl)); let builds = match named[index].as_slice() { [] => GemBuild::ruby(purl).into_iter().collect(), builds => builds.to_vec(), }; - for cache_path in builds - .iter() - .map(|build| app_cache.join(format!("{}.gem", build.leaf))) - { + for build in &builds { + let cache_path = app_cache.join(format!("{}.gem", build.leaf)); if cache_covered.contains(&cache_path) || !cache_path.is_file() { continue; } @@ -957,6 +1223,20 @@ async fn gem_stale_install_warnings( let Some(got) = file_sha256_hex(&cache_path).await else { continue; }; + // A build on upstream's gem: the archive is that gem, or a + // build that was withdrawn. + if let Some(upstream_sha) = gem_upstream.get(&build.leaf) { + if !got.eq_ignore_ascii_case(upstream_sha) { + let gem = stale_cache_gem(purl, &cache_path); + out.warnings + .push(gem_stale_warning_of(withdrawn, &gem, None)); + out.withdrawn.push(gem); + } + continue; + } + let Some(want_shas) = want_shas else { + continue; + }; if want_shas.contains(&got) { continue; // the PATCHED archive — healthy commit, nothing stale } @@ -980,11 +1260,17 @@ struct GemRefreshed { progress: Vec, /// The one human warning for what is still stale. summary: Option, + /// The one human warning for the copies of a withdrawn build that are + /// still on disk. + withdrawn_summary: Option, /// The cache-dir archives replaced: files the project commits. replaced_archives: Vec, /// An installed copy was replaced with the patched gem, or the upstream /// archive beside one patched in place was. replaced_installs: bool, + /// An installed copy of a withdrawn build was replaced with upstream's + /// gem. + replaced_withdrawn: bool, } /// What became of the copies of the switched gems that Bundler already @@ -998,12 +1284,23 @@ enum GemCopies { Refreshed, /// Some are still stale; the run's warning names the command. Stale, + /// Every stale one was brought in line with what the lock pins, and + /// for one of them that is upstream's gem: its patched build was + /// withdrawn. + Followed, + /// The copy of a withdrawn build is still installed, and nothing else + /// is stale; the run's warning names the command. + Withdrawn, } impl GemRefreshed { fn copies(&self) -> GemCopies { if self.summary.is_some() { GemCopies::Stale + } else if self.withdrawn_summary.is_some() { + GemCopies::Withdrawn + } else if self.replaced_withdrawn { + GemCopies::Followed } else if self.replaced_installs { GemCopies::Refreshed } else { @@ -1019,6 +1316,12 @@ impl GemRefreshed { /// stale says so (the `--vex` exclusions are the second probe's). A /// refresh that fails changes nothing and leaves the warning; it never /// fails the run. `locked` is whether the run holds the apply lock. +/// +/// The copy of a withdrawn build goes the other way under the same +/// policy: it is replaced with upstream's gem, which the patch registry +/// hands on for that platform (`/gems/.gem`), verified +/// against the sha256 the reference lists for it. A build that was +/// withdrawn may be unsafe to keep loading, and `bundle install` keeps it. #[allow(clippy::too_many_arguments)] async fn refresh_stale_gems( common: &crate::args::GlobalArgs, @@ -1033,12 +1336,15 @@ async fn refresh_stale_gems( (String, String), std::collections::BTreeSet, >, + gem_upstream: &std::collections::BTreeMap, + gem_build_patches: &std::collections::BTreeMap, overrides: &[DepOverride], mirror_sources: &socket_patch_core::hosted::engine::MirrorSources, views: &mut ViewFallback<'_>, ) -> GemRefreshed { use socket_patch_core::patch::gem_refresh::{Source, Wanted}; let direction = gem_refresh::Direction::Patched; + let withdrawn = gem_refresh::Direction::Withdrawn; let first = gem_stale_install_warnings( &common.cwd, common.global, @@ -1046,10 +1352,12 @@ async fn refresh_stale_gems( confirmed, local_records, gem_artifact_shas, + gem_upstream, + gem_build_patches, views, ) .await; - if first.gems.is_empty() { + if first.gems.is_empty() && first.withdrawn.is_empty() { return GemRefreshed { outcome: if common.dry_run { StaleInstallOutcome::default() @@ -1064,9 +1372,9 @@ 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 patched build the + // registry serves for that platform, pinned by its own sha256; a + // platform gem declares no extensions, so replacing one builds nothing. let wanted = |gem: &StaleGem| { let (name, version) = gem_sha_key(&gem.purl); let build = GemBuild::of_leaf(&gem.purl, &gem.leaf); @@ -1075,8 +1383,9 @@ async fn refresh_stale_gems( .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) + .flat_map(|ro| ro.identifiers.gem_builds.iter().flatten()) .filter(|prebuild| Some(prebuild.platform.as_str()) == platform) + .filter(|prebuild| prebuild.patch_uuid.is_some()) .map(|prebuild| prebuild.gem_checksum_sha256.to_ascii_lowercase()) .collect(); let sha256 = if prebuilt.is_empty() { @@ -1114,13 +1423,59 @@ async fn refresh_stale_gems( on_disk: Vec::new(), }) }; + // Upstream's gem for the platform of a withdrawn build: what bundler + // itself would download from the patch registry, which hands that + // file on, verified against the sha256 the reference lists for the + // platform before any byte of it is used. + let upstream_wanted = |gem: &StaleGem| { + let (name, version) = gem_sha_key(&gem.purl); + let sha256 = gem_upstream.get(&gem.leaf)?.to_ascii_lowercase(); + let file = format!("{}.gem", gem.leaf); + let mut urls: Vec = overrides + .iter() + .filter(|o| o.ecosystem == "gem" && o.name == name && o.version == version) + .filter_map(|o| o.registry_override.as_ref()) + .map(|ro| format!("{}/gems/{file}", ro.index_url.trim_end_matches('/'))) + .map(|url| mirror_sources.fetch_url(&url).into_owned()) + .collect(); + urls.dedup(); + Some(Wanted { + leaf: gem.leaf.clone(), + kind: "upstream", + sha256: std::collections::BTreeSet::from([sha256]), + urls, + on_disk: Vec::new(), + }) + }; let source = if common.offline { Source::DiskOnly } else { Source::PatchServer(api_client) }; - let pass = gem_refresh::attempt(&first.gems, wanted, &source, &policy, direction).await; - let mut outcome = if pass.changed(&policy) { + // A precompiled build that stands in for the ruby-platform gem the + // lock names is left as it is: the patched gem of that lock is the + // ruby-platform gem, and replacing the copy with it means building it. + let stand_in = |gem: &StaleGem| { + let (dir, _) = gem.installed.as_ref()?; + first.stand_ins.get_key_value(dir) + }; + let replaceable: Vec = (first.gems.iter()) + .filter(|gem| stand_in(gem).is_none()) + .cloned() + .collect(); + let mut pass = gem_refresh::attempt(&replaceable, wanted, &source, &policy, direction).await; + for (dir, platform) in first.gems.iter().filter_map(stand_in) { + pass.leave(dir, gem_refresh::Why::StandIn(platform.clone())); + } + let withdrawn_pass = gem_refresh::attempt( + &first.withdrawn, + upstream_wanted, + &source, + &policy, + withdrawn, + ) + .await; + let mut outcome = if pass.changed(&policy) || withdrawn_pass.changed(&policy) { gem_stale_install_warnings( &common.cwd, common.global, @@ -1128,6 +1483,8 @@ async fn refresh_stale_gems( confirmed, local_records, gem_artifact_shas, + gem_upstream, + gem_build_patches, views, ) .await @@ -1135,25 +1492,126 @@ async fn refresh_stale_gems( first }; let report = gem_refresh::report(direction, &outcome.gems, &pass, &policy); + let withdrawn_report = + gem_refresh::report(withdrawn, &outcome.withdrawn, &withdrawn_pass, &policy); outcome.warnings = report .warnings .iter() + .chain(&withdrawn_report.warnings) .map(|(code, detail)| serde_json::json!({ "code": code, "detail": detail })) .collect(); if common.dry_run { outcome.stale_purls.clear(); outcome.unjudged_purls.clear(); } + let mut progress = report.progress; + progress.extend(withdrawn_report.progress); GemRefreshed { outcome, - progress: report.progress, + progress, summary: report.summary, + withdrawn_summary: withdrawn_report.summary, replaced_archives: if common.dry_run { Vec::new() } else { - pass.replaced_archives().map(Path::to_path_buf).collect() + let replaced = pass.replaced_archives(); + let replaced = replaced.chain(withdrawn_pass.replaced_archives()); + replaced.map(Path::to_path_buf).collect() }, replaced_installs: !common.dry_run && pass.refreshed_an_install(), + replaced_withdrawn: !common.dry_run && withdrawn_pass.refreshed_an_install(), + } +} + +/// The compact-index documents a run has read of the registries a Bundler +/// lock is on, by URL: the text, or why it could not be read. +type GemIndexes = std::collections::BTreeMap>; + +/// Hand the gem rewriter what the registry a Bundler lock is on lists +/// ([`socket_patch_core::hosted::gem_index::read_gem_indexes`]), before +/// each rewrite of `read`. +/// +/// A lock that takes a gem as platform builds from the registry of another +/// patch of the gem is moved to the patch on offer only when no locked +/// build would turn from a patched build that registry still serves into +/// upstream's own gem. Whether it still serves one (a withdrawn build is +/// refused, whatever the lock's `CHECKSUMS` pins) is that registry's to +/// say, so it is asked wherever the move would put a build on upstream's +/// gem that the lock does not pin there already: one small document per +/// such gem, kept in `held` so it is asked for once however often the run +/// rewrites. No other run asks anything, and a document that cannot be +/// read leaves the gem on the patch it is on. +/// +/// Under a patch mirror the lock names its registry on the mirror, and the +/// document is read where the patch server serves it, as every download of +/// the run is (`mirror_sources`). +async fn read_gem_indexes( + common: &crate::args::GlobalArgs, + api_client: &socket_patch_core::api::client::ApiClient, + mirror_sources: &socket_patch_core::hosted::engine::MirrorSources, + candidates: &[socket_patch_core::hosted::engine::Candidate], + read: &mut socket_patch_core::hosted::engine::CandidateFiles, + held: &mut GemIndexes, +) { + use socket_patch_core::hosted::{engine, gem_index}; + // A status line only where a registry is asked. + let asks = engine::gem_index_targets(candidates, &read.files) + .iter() + .any(|url| !held.contains_key(url)); + let reading = gem_index::read_gem_indexes(api_client, mirror_sources, candidates, read, held); + if asks { + crate::ui::busy(common, "Reading gem registries", reading).await; + } else { + reading.await; + } +} + +/// The candidates that bring a Bundler lock which stays on a patch to what +/// that patch serves today +/// ([`socket_patch_core::hosted::gem_index::read_gem_refreshes`]), to +/// rewrite beside `candidates` once `read` holds the documents of +/// [`read_gem_indexes`]. +/// +/// A lock on the registry of another patch of a gem stays there while the +/// patch on offer would take a patched build from it, or does not list a +/// locked platform. Where the registry it stays on has withdrawn a build +/// the lock pins, that platform no longer installs. The reference of the +/// patch the lock is on lists upstream's gem for that build under its +/// current snapshot, and the rewrite follows it there: the patch on offer +/// is skipped as before, and the lock is whole again. The reference is one +/// the run already holds (`references`: the withdrawn-pin sweep of a scan +/// asks about every pin), else one request to the patch service, made only +/// where a withdrawal was detected while a lock stays. One that is not +/// usable changes nothing. +/// +/// Not under a patch mirror: the reference would have to be moved onto the +/// mirror and checked there like a new pin, and such a lock is left as it +/// is. +async fn refresh_gem_patches( + common: &crate::args::GlobalArgs, + api_client: &socket_patch_core::api::client::ApiClient, + candidates: &[socket_patch_core::hosted::engine::Candidate], + read: &socket_patch_core::hosted::engine::CandidateFiles, + references: &std::collections::HashMap< + String, + socket_patch_core::api::types::PackageVendorResult, + >, +) -> Vec { + use socket_patch_core::hosted::{engine, gem_index}; + if common.patch_mirror().is_some() { + return Vec::new(); + } + // A status line only where the patch service is asked. + let asks = engine::gem_refresh_targets(candidates, &read.files) + .iter() + .any(|target| !references.contains_key(&target.uuid)); + let origins = crate::commands::hosted_unwind::patch_server_origins(common); + let refreshing = + gem_index::read_gem_refreshes(api_client, candidates, read, references, &origins); + if asks { + crate::ui::busy(common, "Resolving hosted artifacts", refreshing).await + } else { + refreshing.await } } @@ -1435,6 +1893,22 @@ struct HostedTelemetry { json_error: Option, } +/// The registry snapshots the Bundler lock of the project in `cwd` takes +/// gems from, by patch uuid: what the run's reference requests present +/// ([`ApiClient::fetch_registry_references`]). The lock is the one of the +/// pair the rewriter is given ([`gem_snapshots_presented`]). +/// +/// [`ApiClient::fetch_registry_references`]: socket_patch_core::api::client::ApiClient::fetch_registry_references +/// [`gem_snapshots_presented`]: socket_patch_core::hosted::engine::gem_snapshots_presented +pub(super) async fn gem_lock_snapshots( + cwd: &Path, +) -> socket_patch_core::api::client::GemSnapshotKeys { + use socket_patch_core::vendor::lock_inventory::ProjectView; + let unreadable = std::collections::BTreeSet::new(); + socket_patch_core::hosted::engine::gem_snapshots_presented(&ProjectView::Disk(cwd), &unreadable) + .await +} + #[allow(clippy::too_many_arguments)] async fn run_redirect_selected_untracked( common: &crate::args::GlobalArgs, @@ -1464,6 +1938,12 @@ async fn run_redirect_selected_untracked( // records) would otherwise be silent gaps on a terminal. Inert under // --json/--silent and off a terminal. let mut status = crate::ui::StatusLine::stderr(common.json, common.silent); + // Every reference answer the run holds, by uuid: the selection's, and + // the withdrawn-pin sweep's for the pins the lockfiles already hold. + let mut references: std::collections::HashMap< + String, + socket_patch_core::api::types::PackageVendorResult, + > = std::collections::HashMap::new(); if !selected.is_empty() { let uuids: Vec = selected.iter().map(|(_, uuid)| uuid.clone()).collect(); @@ -1482,7 +1962,8 @@ async fn run_redirect_selected_untracked( "Resolving hosted artifacts for {}", crate::ui::plural(to_fetch.len(), "patch", "patches") )); - let fetched = api_client.fetch_registry_references(&to_fetch).await; + let held = gem_lock_snapshots(&common.cwd).await; + let fetched = api_client.fetch_registry_references(&to_fetch, &held).await; status.finish(); fetched }; @@ -1494,7 +1975,7 @@ async fn run_redirect_selected_untracked( } fetched }); - let references = match fetched { + references = match fetched { Ok(r) => r, // A capped run whose every row is NEW: the failure affects only // rows the incomplete lookup defers anyway (§5.2), so it becomes @@ -1812,7 +2293,7 @@ async fn run_redirect_selected_untracked( // pnpm registry route (the candidate files, read whole), or the files // of a `.mvn/maven.config` to heal, read again now that the lock is // held; everything after the rewrite still runs. - let read = if !candidates.is_empty() || (route_cleanup && may_heal) { + let mut read = if !candidates.is_empty() || (route_cleanup && may_heal) { let mut read = crate::ui::busy( common, "Reading lockfiles", @@ -2041,6 +2522,27 @@ async fn run_redirect_selected_untracked( } status.finish(); candidates.retain(|c| !unavailable_python_artifacts.contains(&c.dep.artifact_url)); + // What the registries a Bundler lock is on list, handed to every + // rewrite of the run and asked for once (see `read_gem_indexes`). + let mut gem_indexes = GemIndexes::new(); + read_gem_indexes( + common, + api_client, + &mirror_sources, + &candidates, + &mut read, + &mut gem_indexes, + ) + .await; + // A gem lock that stays on the patch it is on, while that patch's + // registry no longer serves a build the lock pins, follows that patch's + // reference as it stands (see `refresh_gem_patches`). Only a run that + // may write, or previews: one that holds no lock leaves the lock as it + // is. + if common.dry_run || lock.is_some() { + let refreshed = refresh_gem_patches(common, api_client, &candidates, &read, &references); + candidates.extend(refreshed.await); + } // The Pipfile.lock reference shape depends on the installing Pipenv // (`path` for 7–11, `file` from 2018 on), so the installed release is // probed (`pipenv --version`, up to 10 s) — but only when a pypi patch @@ -2209,12 +2711,21 @@ 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 }; + read_gem_indexes( + common, + api_client, + &mirror_sources, + &candidates, + &mut read, + &mut gem_indexes, + ) + .await; done = engine::rewrite( &view, read, @@ -2227,6 +2738,11 @@ async fn run_redirect_selected_untracked( // Candidates the rewrite left out because discovery would not attribute // their pin (`engine::rewrite`). skipped.extend(done.unattributed.iter().cloned()); + // A gem the lock names as platform builds, left on its upstream + // registry because none of them has a patched build yet: skipped under + // its own code, which is no warning, so it is never reported as a + // granted patch that nothing pins. + skipped.extend(engine::gem_unpatched_skips(&candidates, &done.rewrite)); grant_warnings.extend(mirror_pins_not_moved( &mirror_sources, &candidates, @@ -2378,25 +2894,64 @@ async fn run_redirect_selected_untracked( // // 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 + // variant, and one per patched platform build: the gem a lock that // names platform builds is pinned to) — 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") { + // The platform builds the patch registry serves as upstream's own gem + // (no patched build), by leaf, each with the sha256 of that gem: what + // its lock entry pins, and what a machine of such a platform holds + // unless it installed a patched build that was withdrawn since. + let mut gem_upstream: std::collections::BTreeMap = + std::collections::BTreeMap::new(); + // The platform builds that have a patch of their own, by leaf, each + // with that patch's uuid: a copy of such a build is judged by its + // archive, else by that patch's record, and never by the gem patch's. + let mut gem_build_patches: std::collections::BTreeMap = + std::collections::BTreeMap::new(); + // Of the pins the project's files hold alone: a gem's lock can stay + // on one patch while another patch of the gem is skipped, and what the + // skipped one's registry serves is not what the lock installs. + let pinned_gems: Vec = done + .overrides + .iter() + .filter(|o| o.ecosystem == "gem") + .filter(|o| confirmed.iter().any(|(_, uuid)| *uuid == o.patch_uuid)) + .cloned() + .collect(); + for o in &pinned_gems { 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 + // The reference's list says what each gem of the version is: the + // sha256 of every patched one (the ruby-platform gem's among + // them), the patch of a patched platform build, and upstream's + // sha256 for a platform with none. + let mut patched_builds = Vec::new(); + for build in 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) { + .flat_map(|ro| ro.identifiers.gem_builds.iter().flatten()) + { + let leaf = format!("{}-{}-{}", o.name, o.version, build.platform); + match &build.patch_uuid { + Some(own) => { + patched_builds.push(build.gem_checksum_sha256.clone()); + if build.platform != "ruby" { + gem_build_patches.insert(leaf, own.clone()); + } + } + None => { + gem_upstream.insert(leaf, build.gem_checksum_sha256.clone()); + } + } + } + for sha in sha.into_iter().chain(patched_builds) { gem_artifact_shas .entry((o.name.clone(), o.version.clone())) .or_default() @@ -2412,7 +2967,9 @@ async fn run_redirect_selected_untracked( &confirmed, &local_records, &gem_artifact_shas, - &done.overrides, + &gem_upstream, + &gem_build_patches, + &pinned_gems, &mirror_sources, &mut views, ) @@ -2583,6 +3140,13 @@ 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 pinned as platform builds is one pin, and the registry + // serves upstream's own gem for a platform with no patched build: + // the document names each locked build, as this run reports them. + params.hosted_gem_builds = engine::pin_reports(&confirmed, rewrite) + .into_iter() + .filter(|report| report.gem_fix.is_some()) + .collect(); // 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, @@ -2711,16 +3275,29 @@ async fn run_redirect_selected_untracked( &confirmed, &skipped, ); + // The pins as the run reports them: a gem the lock names as platform + // builds once per locked build. Everything else above and below works + // on the pins themselves, one per package. + let reports = engine::pin_reports(&confirmed, rewrite); + // And the pins that put a patch in effect: what is counted as on a + // hosted patch. + let in_effect = pins_in_effect(&confirmed, rewrite); // Sent before the result prints: a consumer that closes stdout early // (SIGPIPE on the first write) must not lose it. if !selected.is_empty() { socket_patch_core::telemetry::track_patch_hosted( telemetry.command, - confirmed.len(), + in_effect.len(), done.rewritten.len(), common.dry_run, &crate::telemetry_outcomes::patch_outcomes_of( - &hosted_events(&confirmed, &unconfirmed, &skipped, common.dry_run, None), + &hosted_events( + &pin_reports_by_package(&in_effect), + &unconfirmed, + &skipped, + common.dry_run, + None, + ), socket_patch_core::telemetry::MODE_HOSTED, ), &telemetry.auth, @@ -2759,7 +3336,7 @@ async fn run_redirect_selected_untracked( }; record_hosted_events( &mut env, - &confirmed, + &reports, &unconfirmed, &skipped, common.dry_run, @@ -2850,29 +3427,44 @@ async fn run_redirect_selected_untracked( .into_iter() .map(|pin| pin.uuid) .collect(); - confirmed + in_effect .iter() .filter(|(_, uuid)| in_place.contains(uuid)) .count() }); println!( "{}", - format_hosted_summary(confirmed.len(), already, human_files.len(), common.dry_run) + format_hosted_summary(in_effect.len(), 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 // counts the directory into the invocation's closing totals. if let Some(gate) = rollout.as_mut() { let pinned: std::collections::HashSet<&str> = - confirmed.iter().map(|(_, uuid)| uuid.as_str()).collect(); + in_effect.iter().map(|(_, uuid)| uuid.as_str()).collect(); if let Some(report) = gate.report.as_deref_mut() { report.project(&gate.plan, &pinned).await; + report.hosted_builds(&reports); + if !common.dry_run { + let stale: std::collections::BTreeSet<&str> = (gem_refreshed.outcome.gems) + .iter() + .map(|gem| gem.purl.as_str()) + .collect(); + report.stale_gem_installs(stale.len()); + } } } // Then what the run did to the user's Bundler manifest. for line in format_gem_manifest_edits(&rewrite.edits, common.dry_run) { println!("{line}"); } + // And, for a gem the lock names as platform builds, which of + // them are patched. + let stdout_width = + crate::ui::attended(crate::ui::Stream::Stdout).then(crate::ui::stdout_width); + for line in format_gem_build_lines(&reports, &skipped, common.dry_run) { + println!("{}", wrap_line(&line, stdout_width)); + } // And what it took out of a pnpm registry route nothing uses. for line in crate::commands::registry_gc::lines(®istry_removed, common.dry_run) { println!("{line}"); @@ -2906,6 +3498,8 @@ async fn run_redirect_selected_untracked( let skipped_pairs: Vec<(String, String)> = skipped .iter() .filter(|s| s.reason != super::rollout::ROLLOUT_DEFERRED) + // Said above, as one plain line per gem: nothing failed. + .filter(|s| !engine::is_quiet_gem_skip(&s.reason)) .map(|s| (s.purl.clone(), s.reason.clone())) .collect(); let unconfirmed_purls: Vec = @@ -2913,7 +3507,7 @@ async fn run_redirect_selected_untracked( for line in format_unredirected( &skipped_pairs, &unconfirmed_purls, - confirmed.is_empty(), + in_effect.is_empty(), // Only the lockfile rewriters' own warnings explain a // missing lock entry; unrelated guidance (pnpm trust, VEX, // stale installs, Bun default trust) is not what the hint @@ -2950,7 +3544,8 @@ async fn run_redirect_selected_untracked( }; eprintln!("{}", format_warning(code, &detail, width)); } - if let Some(summary) = &gem_refreshed.summary { + let summaries = [&gem_refreshed.summary, &gem_refreshed.withdrawn_summary]; + for summary in summaries.into_iter().flatten() { eprintln!( "{}", render_warning(&format!("{}.", summary.headline), &summary.bullets, width) @@ -3235,54 +3830,6 @@ fn format_error_line(msg: &str) -> String { format!("Error: {}", crate::ui::sentence_case(msg)) } -/// Split `text` into wrap tokens at whitespace, except that a -/// backtick-delimited code span (`` `pnpm install --trust-lockfile` ``) -/// stays one token so a command the user copies is never broken across -/// lines. An unclosed span falls back to plain whitespace splitting. -fn wrap_tokens(text: &str) -> Vec { - let mut tokens: Vec = Vec::new(); - let mut span: Vec<&str> = Vec::new(); - for word in text.split_whitespace() { - span.push(word); - let open = span.iter().map(|w| w.matches('`').count()).sum::() % 2 == 1; - if !open { - tokens.push(span.join(" ")); - span.clear(); - } - } - tokens.extend(span.into_iter().map(str::to_string)); - tokens -} - -/// Greedy word wrap to `width` columns (characters, not bytes). The first -/// line starts with `first_prefix`, later lines with `indent`. A word -/// longer than the line (a URL) gets a line of its own, never split; a -/// backtick code span counts as one word (see [`wrap_tokens`]). -fn wrap_words(text: &str, width: usize, first_prefix: &str, indent: &str) -> Vec { - let mut lines: Vec = Vec::new(); - let mut line = first_prefix.to_string(); - let mut line_len = first_prefix.chars().count(); - let mut empty = true; - for word in wrap_tokens(text) { - let word = word.as_str(); - let wlen = word.chars().count(); - if !empty && line_len + 1 + wlen > width { - lines.push(std::mem::replace(&mut line, indent.to_string())); - line_len = indent.chars().count(); - empty = true; - } - if !empty { - line.push(' '); - line_len += 1; - } - line.push_str(word); - line_len += wlen; - empty = false; - } - lines.push(line); - lines -} - /// Split a long guidance paragraph into its sentences, at every period /// followed by a space (host names and versions such as `patch.socket.dev` /// or `5.4` never contain one). Each sentence keeps its own period; the @@ -3861,6 +4408,18 @@ fn format_next_steps( install` keeps the gems it already has)", &extra, ), + GemCopies::Followed if bundler_only => crate::ui::next_steps_installed( + &commit, + "the installed gems already hold the builds the lockfile pins, so there is nothing \ + to reinstall", + &extra, + ), + GemCopies::Withdrawn if bundler_only => crate::ui::next_steps( + &commit, + "Replace the withdrawn gem build with the command in the warning above (a plain \ + `bundle install` keeps the gems it already has)", + &extra, + ), _ => crate::ui::next_steps( &commit, &format!("Reinstall from the updated lockfile{hint}"), @@ -3979,7 +4538,7 @@ mod tests { describe_skip_reason, format_error_line, format_hosted_summary, format_next_steps, format_redirect_summary, format_takeover_line, format_unredirected, format_warning, join_names, lock_entry_warning_count, pnpm_trust_rerun_reminder, split_sentences, - wrap_tokens, wrap_words, GemCopies, TAKEOVER_INFO_CODES, + GemCopies, TAKEOVER_INFO_CODES, }; use super::{ gem_stale_install_warnings, gem_stale_warning, prune_ignored_warning, record_hosted_events, @@ -4421,9 +4980,13 @@ mod tests { {"purl": "pkg:npm/b@1.0.0", "uuid": "ub", "reason": "not_found"} ])) .unwrap(); + let pinned = super::pin_reports_by_package(&[( + "pkg:npm/minimist@1.2.2".to_string(), + "abc-123".to_string(), + )]); record_hosted_events( &mut env, - &[("pkg:npm/minimist@1.2.2".to_string(), "abc-123".to_string())], + &pinned, &[("pkg:npm/a@1.0.0".to_string(), "ua".to_string())], &skipped, false, @@ -4471,16 +5034,415 @@ mod tests { // A dry run previews the pin as `verified`. let mut env = Envelope::new(Command::Scan); + record_hosted_events(&mut env, &pinned, &[], &[], true, &Default::default()); + assert_eq!(env.summary.verified, 1); + assert_eq!(env.summary.applied, 0); + } + + const BUILD_FIX: &str = "77777777-7777-4777-8777-777777777777"; + const BUILD_LINUX: &str = "77777777-7777-4777-8777-00000000000b"; + + /// One locked build of the gem `pkg:gem/nokogiri@1.19.3` as a run + /// reports it: `patch` is the patch of its patched build (`None`: the + /// registry serves upstream's gem), `newly` whether this run put it in + /// place. + fn build_report( + platform: Option<&str>, + patch: Option<&str>, + newly: bool, + ) -> socket_patch_core::hosted::engine::PinReport { + socket_patch_core::hosted::engine::PinReport { + purl: match platform { + Some(platform) => format!("pkg:gem/nokogiri@1.19.3?platform={platform}"), + None => "pkg:gem/nokogiri@1.19.3".to_string(), + }, + uuid: patch.map(str::to_string), + gem_fix: Some(BUILD_FIX.to_string()), + platform: platform.map(str::to_string), + newly_patched: newly, + withdrawn: false, + } + } + + /// A gem the lock names as platform builds is recorded per locked + /// build. A patched build is a counted `applied` event under its own + /// patch, whose `details` name the gem patch and the platform, and say + /// when this run put the build in place. A build the registry serves as + /// upstream's gem is an event with no `uuid` that no `summary` count + /// moves for. The quiet skip of a gem with no patched build is an + /// ordinary counted skip, and never a warning. + /// + /// `details.pinChanged` is the change of the gem patch's one pin, which + /// every build of the gem goes by: each patched build's event carries + /// it, whatever patch the build itself holds, and the event of a build + /// left on upstream's gem carries none (no patch is in place there). + #[test] + fn hosted_events_report_a_platform_locked_gem_per_build() { + use crate::json_envelope::{Command, Envelope}; + use socket_patch_core::hosted::engine::{ + SkippedPatch, GEM_NO_PATCHED_BUILD, GEM_UPSTREAM_BUILD_KEPT, + }; + let reports = [ + build_report(None, Some(BUILD_FIX), false), + build_report(Some("arm64-darwin"), None, false), + build_report(Some("x86_64-linux-gnu"), Some(BUILD_LINUX), true), + ]; + let skipped = [SkippedPatch { + detail: Some( + "rack 3.1.8: no patched build yet for java; left on its upstream registry".into(), + ), + ..SkippedPatch::new("pkg:gem/rack@3.1.8", "ur", GEM_NO_PATCHED_BUILD) + }]; + let pin = [("pkg:gem/nokogiri@1.19.3".to_string(), BUILD_FIX.to_string())]; + let changed: super::pin_changes::PinChanges<'_> = pin + .iter() + .map(|(purl, uuid)| ((purl.as_str(), uuid.as_str()), true)) + .collect(); + let mut env = Envelope::new(Command::Scan); + record_hosted_events(&mut env, &reports, &[], &skipped, false, &changed); + let v = env.to_value(); + assert_eq!( + v["events"], + serde_json::json!([ + { + "action": "applied", "purl": "pkg:gem/nokogiri@1.19.3", "uuid": BUILD_FIX, + "details": {"gemFix": BUILD_FIX, "mode": "hosted", "pinChanged": true}, + }, + { + "action": "skipped", + "purl": "pkg:gem/nokogiri@1.19.3?platform=arm64-darwin", + "errorCode": GEM_UPSTREAM_BUILD_KEPT, + "reason": "the patch registry serves upstream's own gem for arm64-darwin: \ + no patched build yet", + "details": {"gemFix": BUILD_FIX, "platform": "arm64-darwin", "mode": "hosted"}, + }, + { + "action": "applied", + "purl": "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu", + "uuid": BUILD_LINUX, + "details": { + "gemFix": BUILD_FIX, "platform": "x86_64-linux-gnu", + "newlyPatched": true, "mode": "hosted", "pinChanged": true, + }, + }, + { + "action": "skipped", "purl": "pkg:gem/rack@3.1.8", "uuid": "ur", + "errorCode": GEM_NO_PATCHED_BUILD, + "reason": "rack 3.1.8: no patched build yet for java; left on its upstream \ + registry", + "details": {"mode": "hosted"}, + }, + ]) + ); + assert_eq!(v["summary"]["applied"], 2, "the patched builds"); + assert_eq!( + v["summary"]["skipped"], 1, + "the gem left alone, not the build" + ); + assert_eq!(v["summary"]["failed"], 0); + assert_eq!(v["status"], "success"); + assert!(v["warnings"].as_array().is_none_or(Vec::is_empty), "{v}"); + + // A dry run previews each patched build as `verified`; the build + // left on upstream's gem is reported the same way. A run that + // rewrote nothing says so of every patched build, and one that + // cannot tell says `null`. + for (changes, expected) in [ + ( + super::pin_changes::unchanged(&pin), + serde_json::json!(false), + ), + ( + super::pin_changes::PinChanges::default(), + serde_json::Value::Null, + ), + ] { + let mut env = Envelope::new(Command::Scan); + record_hosted_events(&mut env, &reports, &[], &[], true, &changes); + assert_eq!((env.summary.verified, env.summary.applied), (2, 0)); + assert_eq!(env.summary.skipped, 0); + assert_eq!(env.events.len(), 3); + let v = env.to_value(); + let said: Vec> = v["events"] + .as_array() + .unwrap() + .iter() + .map(|event| event["details"].get("pinChanged")) + .collect(); + assert_eq!(said, [Some(&expected), None, Some(&expected)], "{v}"); + } + + // Telemetry names one patch per package: the pin's. + let pins = [("pkg:gem/nokogiri@1.19.3".to_string(), BUILD_FIX.to_string())]; + let outcomes = crate::telemetry_outcomes::patch_outcomes_of( + &super::hosted_events( + &super::pin_reports_by_package(&pins), + &[], + &skipped, + false, + None, + ), + socket_patch_core::telemetry::MODE_HOSTED, + ); + let named: Vec<(&str, &str, Option<&str>)> = outcomes + .iter() + .map(|o| (o.uuid.as_str(), o.outcome, o.code.as_deref())) + .collect(); + assert_eq!( + named, + [ + (BUILD_FIX, "applied", None), + ("ur", "skipped", Some(GEM_NO_PATCHED_BUILD)), + ] + ); + } + + /// The human line of a gem locked as platform builds: which builds are + /// patched, which keep upstream's gem, which this run found patched on + /// a lock that was already on the registry, and what a dry run would + /// do. A package that is no such gem has no line. A gem left on its + /// upstream registry prints its skip's own sentence. + #[test] + fn gem_build_lines_say_which_builds_are_patched() { + use socket_patch_core::hosted::engine::{SkippedPatch, GEM_NO_PATCHED_BUILD}; + let line = |reports: &[socket_patch_core::hosted::engine::PinReport], dry_run| { + let lines = super::format_gem_build_lines(reports, &[], dry_run); + assert_eq!(lines.len(), 1, "{lines:?}"); + lines.into_iter().next().unwrap() + }; + let arm = |patch, newly| build_report(Some("arm64-darwin"), patch, newly); + let linux = |patch, newly| build_report(Some("x86_64-linux-gnu"), patch, newly); + let (a, b) = (Some("ua"), Some(BUILD_LINUX)); + + // Every locked build patched by this run, then found in place. + assert_eq!( + line(&[arm(a, true), linux(b, true)], false), + "nokogiri 1.19.3: patched for arm64-darwin, x86_64-linux-gnu" + ); + assert_eq!( + line(&[arm(a, false), linux(b, false)], false), + "nokogiri 1.19.3: patched for arm64-darwin, x86_64-linux-gnu" + ); + // One platform has no patched build yet. + assert_eq!( + line(&[arm(None, false), linux(b, true)], false), + "nokogiri 1.19.3: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin \ + (no patched build yet)" + ); + // A later run finds that platform patched. + assert_eq!( + line(&[arm(a, true), linux(b, false)], false), + "nokogiri 1.19.3: now also patched for arm64-darwin; already patched for \ + x86_64-linux-gnu" + ); + // The ruby-platform gem beside the platform builds. + assert_eq!( + line( + &[ + build_report(None, Some(BUILD_FIX), true), + arm(None, false), + linux(b, true) + ], + false + ), + "nokogiri 1.19.3: patched for ruby, x86_64-linux-gnu; upstream gem kept for \ + arm64-darwin (no patched build yet)" + ); + // A dry run says what the wet run would put in place. + assert_eq!( + line(&[arm(None, false), linux(b, true)], true), + "nokogiri 1.19.3: would be patched for x86_64-linux-gnu; upstream gem kept for \ + arm64-darwin (no patched build yet)" + ); + assert_eq!( + line(&[arm(a, true), linux(b, false)], true), + "nokogiri 1.19.3: would also be patched for arm64-darwin; already patched for \ + x86_64-linux-gnu" + ); + + // Any other pin has no line; a gem left alone has its skip's. + let plain = super::pin_reports_by_package(&[ + ("pkg:npm/a@1.0.0".to_string(), "u".to_string()), + ("pkg:gem/rack@3.1.8".to_string(), "v".to_string()), + ]); + assert!(super::format_gem_build_lines(&plain, &[], false).is_empty()); + let left = "rack 3.1.8: no patched build yet for java; left on its upstream registry"; + let skipped = [ + SkippedPatch::new("pkg:npm/b@1.0.0", "ub", "not_found"), + SkippedPatch { + detail: Some(left.to_string()), + ..SkippedPatch::new("pkg:gem/rack@3.1.8", "ur", GEM_NO_PATCHED_BUILD) + }, + ]; + assert_eq!( + super::format_gem_build_lines(&[arm(a, true), linux(b, true)], &skipped, false), + [ + "nokogiri 1.19.3: patched for arm64-darwin, x86_64-linux-gnu", + left + ] + ); + + // On a terminal a line that does not fit breaks after a clause, + // under a hanging indent; one that fits, and any line in a pipe, + // stays whole. + let long = line(&[arm(None, false), linux(b, true)], false); + assert_eq!(super::wrap_line(&long, None), long); + assert_eq!(super::wrap_line(&long, Some(120)), long); + for width in [80, 100] { + assert_eq!( + super::wrap_line(&long, Some(width)), + "nokogiri 1.19.3: patched for x86_64-linux-gnu;\n upstream gem kept for \ + arm64-darwin (no patched build yet)" + ); + } + // A clause wider than the terminal wraps at a word. + let platforms = [ + "aarch64-linux-gnu", + "aarch64-linux-musl", + "arm-linux-gnu", + "arm-linux-musl", + "arm64-darwin", + "x86_64-darwin", + "x86_64-linux-gnu", + "x86_64-linux-musl", + ]; + let many: Vec<_> = platforms + .iter() + .map(|platform| build_report(Some(platform), Some("u"), true)) + .collect(); + let wrapped = super::wrap_line(&line(&many, false), Some(80)); + assert_eq!( + wrapped, + "nokogiri 1.19.3: patched for aarch64-linux-gnu, aarch64-linux-musl,\n \ + arm-linux-gnu, arm-linux-musl, arm64-darwin, x86_64-darwin, x86_64-linux-gnu,\n \ + x86_64-linux-musl" + ); + assert!(wrapped.lines().all(|row| row.chars().count() <= 80)); + } + + /// A build the run put back on upstream's gem, because the patched + /// build its lock entry pinned was withdrawn, is said as such: in the + /// gem's line, before the builds that never had a patched build, and + /// in its uncounted event (`details.withdrawn`, and the reason). A + /// dry run says what the wet run would do. The line wraps after a + /// clause on a terminal and stays whole in a pipe. + #[test] + fn a_withdrawn_build_is_said_to_be_back_on_upstreams_gem() { + use crate::json_envelope::{Command, Envelope}; + use socket_patch_core::hosted::engine::{PinReport, GEM_UPSTREAM_BUILD_KEPT}; + let line = |reports: &[PinReport], dry_run| { + let lines = super::format_gem_build_lines(reports, &[], dry_run); + assert_eq!(lines.len(), 1, "{lines:?}"); + lines.into_iter().next().unwrap() + }; + let back = |platform| PinReport { + withdrawn: true, + ..build_report(Some(platform), None, false) + }; + let arm = |patch, newly| build_report(Some("arm64-darwin"), patch, newly); + let linux = back("x86_64-linux-gnu"); + + // No locked build is patched any more. + let alone = line(std::slice::from_ref(&linux), false); + assert_eq!( + alone, + "nokogiri 1.19.3: upstream gem back for x86_64-linux-gnu (its patched build was \ + withdrawn)" + ); + // Beside a patched build, and one found patched by this run. + let beside = line(&[arm(Some("ua"), false), linux.clone()], false); + assert_eq!( + beside, + "nokogiri 1.19.3: patched for arm64-darwin; upstream gem back for x86_64-linux-gnu \ + (its patched build was withdrawn)" + ); + assert_eq!( + line(&[arm(Some("ua"), true), linux.clone()], false), + "nokogiri 1.19.3: patched for arm64-darwin; upstream gem back for x86_64-linux-gnu \ + (its patched build was withdrawn)" + ); + // Beside a build that never had a patched build, and two of them. + assert_eq!( + line(&[arm(None, false), linux.clone()], false), + "nokogiri 1.19.3: upstream gem back for x86_64-linux-gnu (its patched build was \ + withdrawn); upstream gem kept for arm64-darwin (no patched build yet)" + ); + assert_eq!( + line(&[back("arm64-darwin"), linux.clone()], false), + "nokogiri 1.19.3: upstream gem back for arm64-darwin, x86_64-linux-gnu (their \ + patched builds were withdrawn)" + ); + // A dry run writes nothing. + assert_eq!( + line(&[arm(Some("ua"), false), linux.clone()], true), + "nokogiri 1.19.3: patched for arm64-darwin; upstream gem would be back for \ + x86_64-linux-gnu (its patched build was withdrawn)" + ); + + // One line in a pipe; on a terminal it breaks after the clause. + assert_eq!(super::wrap_line(&beside, None), beside); + assert_eq!(super::wrap_line(&beside, Some(120)), beside); + for width in [80, 100] { + assert_eq!( + super::wrap_line(&beside, Some(width)), + "nokogiri 1.19.3: patched for arm64-darwin;\n upstream gem back for \ + x86_64-linux-gnu (its patched build was withdrawn)" + ); + } + assert_eq!(super::wrap_line(&alone, Some(100)), alone); + assert_eq!( + super::wrap_line(&alone, Some(80)), + "nokogiri 1.19.3: upstream gem back for x86_64-linux-gnu (its patched build was\n \ + withdrawn)" + ); + + // The event: uncounted, with the flag and the reason. + let mut env = Envelope::new(Command::Scan); record_hosted_events( &mut env, - &[("pkg:npm/minimist@1.2.2".to_string(), "abc-123".to_string())], + &[arm(None, false), linux], &[], &[], - true, + false, &Default::default(), ); - assert_eq!(env.summary.verified, 1); - assert_eq!(env.summary.applied, 0); + let v = env.to_value(); + assert_eq!( + v["events"], + serde_json::json!([ + { + "action": "skipped", + "purl": "pkg:gem/nokogiri@1.19.3?platform=arm64-darwin", + "errorCode": GEM_UPSTREAM_BUILD_KEPT, + "reason": "the patch registry serves upstream's own gem for arm64-darwin: \ + no patched build yet", + "details": {"gemFix": BUILD_FIX, "platform": "arm64-darwin", "mode": "hosted"}, + }, + { + "action": "skipped", + "purl": "pkg:gem/nokogiri@1.19.3?platform=x86_64-linux-gnu", + "errorCode": GEM_UPSTREAM_BUILD_KEPT, + "reason": "the patch registry serves upstream's own gem for \ + x86_64-linux-gnu: its patched build was withdrawn", + "details": { + "gemFix": BUILD_FIX, "platform": "x86_64-linux-gnu", + "withdrawn": true, "mode": "hosted", + }, + }, + ]) + ); + let summary = &v["summary"]; + assert_eq!( + (&summary["applied"], &summary["skipped"], &summary["failed"]), + ( + &serde_json::json!(0), + &serde_json::json!(0), + &serde_json::json!(0) + ), + "{v}" + ); + assert_eq!(v["status"], "success"); + assert!(v["warnings"].as_array().is_none_or(Vec::is_empty), "{v}"); } use std::path::PathBuf; @@ -4576,6 +5538,8 @@ mod tests { confirmed, records, &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await @@ -4855,6 +5819,8 @@ mod tests { &one_confirmed, &none, &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -4872,6 +5838,8 @@ mod tests { &one_confirmed, &none, &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -4885,6 +5853,8 @@ mod tests { &one_confirmed, &none, &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -4920,6 +5890,8 @@ mod tests { &confirmed, &std::collections::BTreeMap::new(), &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5015,6 +5987,8 @@ mod tests { &one_confirmed(), &none, &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut views, ) .await; @@ -5035,6 +6009,8 @@ mod tests { &one_confirmed(), &none, &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut views, ) .await; @@ -5065,6 +6041,8 @@ mod tests { &one_confirmed(), &none, &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut views, ) .await; @@ -5102,6 +6080,8 @@ mod tests { &one_confirmed(), &std::collections::BTreeMap::new(), &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut views, ) .await; @@ -5217,6 +6197,8 @@ mod tests { &one_confirmed(), &one_record(), &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5290,6 +6272,8 @@ mod tests { &confirmed, &records, &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await @@ -5335,6 +6319,8 @@ mod tests { &confirmed, &records, &upper, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5381,6 +6367,8 @@ mod tests { &one_confirmed(), &one_record(), &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5424,6 +6412,8 @@ mod tests { &one_confirmed(), &one_record(), &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5452,6 +6442,8 @@ mod tests { &one_confirmed(), &one_record(), &patched_shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5475,6 +6467,8 @@ mod tests { &one_confirmed(), &one_record(), &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5517,6 +6511,8 @@ mod tests { &one_confirmed(), &one_record(), &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5542,6 +6538,8 @@ mod tests { &one_confirmed(), &one_record(), &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5569,6 +6567,8 @@ mod tests { &one_confirmed(), &one_record(), &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5658,6 +6658,8 @@ mod tests { &one_confirmed(), &one_record(), &shas, + &std::collections::BTreeMap::new(), + &std::collections::BTreeMap::new(), &mut super::ViewFallback::offline(), ) .await; @@ -5677,6 +6679,165 @@ mod tests { } } + /// The copies of a platform build the patch registry serves as + /// upstream's own gem are judged by the sha256 of that gem alone: the + /// installed copy by the archive RubyGems installed it from, the + /// committed cache-dir archive by its own. Upstream's gem is the right + /// copy: nothing is stale, nothing is unjudged, and nothing is handed + /// to the refresh. A readable archive with another sha256 is a build + /// that was withdrawn: it is handed to the refresh apart from the + /// unpatched copies, and never withholds the gem from the same run's + /// VEX. A copy with no archive is not judged. The same copies of a + /// platform that has a patched build are stale. + #[tokio::test] + async fn gem_stale_probe_judges_a_build_on_upstreams_gem_by_its_archive() { + let tmp = tempfile::tempdir().unwrap(); + let cwd = tmp.path(); + std::fs::write( + cwd.join("Gemfile"), + "source \"https://rubygems.org\"\ngem \"stale-unit\", \"1.0.0\"\n", + ) + .unwrap(); + std::fs::write( + cwd.join("Gemfile.lock"), + "GEM\n remote: https://rubygems.org/\n specs:\n stale-unit \ + (1.0.0-arm64-darwin)\n stale-unit (1.0.0-x86_64-linux-gnu)\n\nPLATFORMS\n \ + arm64-darwin\n x86_64-linux-gnu\n\nDEPENDENCIES\n stale-unit (= 1.0.0)\n\n\ + BUNDLED WITH\n 2.5.0\n", + ) + .unwrap(); + let leaf = format!("{GEM_LEAF}-arm64-darwin"); + let home = gem_home(cwd); + let gem_dir = home.join("gems").join(&leaf); + std::fs::create_dir_all(gem_dir.join("lib")).unwrap(); + std::fs::write(gem_dir.join("lib").join("stale_unit.rb"), GEM_UPSTREAM).unwrap(); + let archive = home.join("cache").join(format!("{leaf}.gem")); + std::fs::create_dir_all(archive.parent().unwrap()).unwrap(); + std::fs::write(&archive, b"upstream platform .gem").unwrap(); + let committed = cwd.join("vendor").join("cache").join(format!("{leaf}.gem")); + std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); + std::fs::write(&committed, b"upstream platform .gem").unwrap(); + + /// The probe of the one confirmed gem, whose patched artifacts are + /// the ruby gem and the other platform's build. + async fn judge( + cwd: &std::path::Path, + upstream: &std::collections::BTreeMap, + ) -> super::StaleInstallOutcome { + let shas = std::collections::BTreeMap::from([( + ("stale-unit".to_string(), "1.0.0".to_string()), + std::collections::BTreeSet::from(["0".repeat(64), "1".repeat(64)]), + )]); + gem_stale_install_warnings( + cwd, + false, + None, + &one_confirmed(), + &std::collections::BTreeMap::new(), + &shas, + upstream, + &std::collections::BTreeMap::new(), + &mut super::ViewFallback::offline(), + ) + .await + } + let upstream_sha = socket_patch_core::vendor::file_sha256_hex(&archive) + .await + .expect("the archive's sha256"); + let upstream = std::collections::BTreeMap::from([(leaf.clone(), upstream_sha)]); + let patched_platform = std::collections::BTreeMap::new(); + // Nothing of a build on upstream's gem is an unpatched copy, and + // nothing of it keeps the gem out of the run's VEX. + let never_unpatched = |out: &super::StaleInstallOutcome| { + assert!(out.gems.is_empty(), "no unpatched copy"); + assert!(out.stale_purls.is_empty() && out.unjudged_purls.is_empty()); + }; + + let out = judge(cwd, &upstream).await; + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert!(out.withdrawn.is_empty(), "nothing to refresh"); + never_unpatched(&out); + let out = judge(cwd, &patched_platform).await; + assert_eq!(out.warnings.len(), 1, "{:?}", out.warnings); + assert_eq!(out.gems.len(), 1); + assert!(out.withdrawn.is_empty()); + assert_eq!( + out.gems[0].cache_archive.as_deref(), + Some(committed.as_path()), + "the committed archive is stale with it" + ); + + // The copy was installed from another archive than upstream's + // gem: a patched build that was withdrawn since. + std::fs::write(&archive, b"withdrawn platform .gem").unwrap(); + let out = judge(cwd, &upstream).await; + never_unpatched(&out); + let [gem] = out.withdrawn.as_slice() else { + panic!("one withdrawn copy: {:?}", out.withdrawn); + }; + assert_eq!((gem.purl.as_str(), gem.leaf.as_str()), (GEM_PURL, &*leaf)); + assert_eq!(gem.installed, Some((gem_dir.clone(), true))); + assert_eq!( + gem.cache_archive, None, + "the committed archive is upstream's gem" + ); + let [warning] = out.warnings.as_slice() else { + panic!("one warning: {:?}", out.warnings); + }; + assert_eq!(warning["code"], "redirect_gem_stale_install"); + let detail = detail_of(warning); + assert!( + detail.starts_with(&format!( + "{GEM_PURL} is back on upstream's own gem for arm64-darwin, whose patched build \ + was withdrawn, but its withdrawn install at {} was not refreshed, and `bundle \ + install` reuses an installed gem instead of fetching the upstream one.", + gem_dir.display() + )), + "{detail}" + ); + + // So is the committed archive, which goes with the install. + std::fs::write(&committed, b"withdrawn platform .gem").unwrap(); + let out = judge(cwd, &upstream).await; + never_unpatched(&out); + assert_eq!(out.withdrawn.len(), 1, "{:?}", out.withdrawn); + assert_eq!( + out.withdrawn[0].cache_archive.as_deref(), + Some(committed.as_path()) + ); + + // With no archive beside the install there is nothing to judge it + // by, and the committed archive is reported alone. + std::fs::remove_file(&archive).unwrap(); + let out = judge(cwd, &upstream).await; + never_unpatched(&out); + let [gem] = out.withdrawn.as_slice() else { + panic!("the committed archive: {:?}", out.withdrawn); + }; + assert_eq!(gem.installed, None); + assert_eq!(gem.cache_archive.as_deref(), Some(committed.as_path())); + let detail = detail_of(&out.warnings[0]); + assert!( + detail.contains(&format!( + "but Bundler's cache dir still holds its withdrawn archive at {}", + committed.display() + )), + "{detail}" + ); + + // Nothing at all to judge by: unjudged for a patched platform, + // nothing for this one. + std::fs::remove_file(&committed).unwrap(); + let out = judge(cwd, &upstream).await; + assert!(out.warnings.is_empty() && out.withdrawn.is_empty()); + never_unpatched(&out); + let out = judge(cwd, &patched_platform).await; + assert_eq!( + out.unjudged_purls, + std::collections::BTreeSet::from([GEM_PURL.to_string()]) + ); + } + /// The standalone cache-flavor warning's load-bearing wording. #[test] fn gem_stale_cache_warning_names_archive_and_remedy() { @@ -6017,62 +7178,6 @@ mod tests { ); } - #[test] - fn wrap_words_respects_width_prefix_and_long_words() { - assert_eq!( - wrap_words("alpha beta gamma delta", 16, "W: ", " "), - vec!["W: alpha beta", " gamma delta"] - ); - // A word wider than the line sits alone, unsplit. - let url = "https://patch.socket.dev/very/long/path/that/does/not/fit"; - assert_eq!( - wrap_words(&format!("see {url} now"), 20, "", " "), - vec!["see".to_string(), format!(" {url}"), " now".to_string()] - ); - assert_eq!(wrap_words("", 10, "W: ", " "), vec!["W: "]); - // Counts characters, not bytes. - let lines = wrap_words("ééé ééé ééé", 8, "", ""); - assert_eq!(lines, vec!["ééé ééé", "ééé"]); - for line in wrap_words(&"word ".repeat(50), 30, "Warning: ", " ") { - assert!(line.chars().count() <= 30, "{line}"); - } - } - - #[test] - fn wrap_words_keeps_code_spans_whole() { - // The span crosses the wrap column: it moves to the next line whole. - assert_eq!( - wrap_words( - "never rebuild it (`pnpm clean --lockfile`), ever", - 30, - "", - " " - ), - vec!["never rebuild it", " (`pnpm clean --lockfile`),", " ever"] - ); - // A span wider than the line gets a line of its own, unsplit. - assert_eq!( - wrap_words( - "use `pnpm install --frozen-lockfile --store-dir ` now", - 20, - "", - " " - ), - vec![ - "use", - " `pnpm install --frozen-lockfile --store-dir `", - " now" - ] - ); - // Two spans in one word, and a word with a closed span, split normally. - assert_eq!( - wrap_tokens("a `b` c `d e`f g"), - vec!["a", "`b`", "c", "`d e`f", "g"] - ); - // An unclosed span never swallows the rest of the text. - assert_eq!(wrap_tokens("a `b c d"), vec!["a", "`b", "c", "d"]); - } - #[test] fn split_sentences_keeps_hosts_and_versions_whole() { assert_eq!( @@ -6422,6 +7527,19 @@ mod tests { `bundle install` keeps the gems it already has), then run `socket-patch vex` to \ verify the installed patches." ); + // A copy of a withdrawn build went back to upstream's gem: the + // installed gems are what the lock pins, and never called patched. + assert_eq!( + steps(&bundler, GemCopies::Followed)[2], + " 2. Run `socket-patch vex` to verify the installed patches (the installed gems \ + already hold the builds the lockfile pins, so there is nothing to reinstall)." + ); + assert_eq!( + steps(&bundler, GemCopies::Withdrawn)[2], + " 2. Replace the withdrawn gem build with the command in the warning above (a plain \ + `bundle install` keeps the gems it already has), then run `socket-patch vex` to \ + verify the installed patches." + ); // A replaced cache-dir archive is one of Bundler's files too. let with_cache = [ "Gemfile.lock".to_string(), diff --git a/crates/socket-patch-cli/src/commands/scan/hosted/pin_changes.rs b/crates/socket-patch-cli/src/commands/scan/hosted/pin_changes.rs index d1470d2fb6..22a7e986be 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted/pin_changes.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted/pin_changes.rs @@ -1,7 +1,7 @@ use std::borrow::Cow; use std::collections::HashMap; -use socket_patch_core::hosted::engine::Candidate; +use socket_patch_core::hosted::engine::{Candidate, PinReport}; use socket_patch_core::patch::redirect::upstream::foreign_dep_origins; use socket_patch_core::utils::purl_key::PurlKey; use socket_patch_core::vex::discover::{ @@ -40,6 +40,24 @@ pub(super) async fn discover_now(common: &GlobalArgs, candidates: &[Candidate]) before_rewrite(common, candidates, None).await.into_owned() } +/// `details.pinChanged` of one reported pin: the change of the pin it goes +/// by. A build of a gem the lock names as platform builds goes by the gem +/// patch's one pin (`gem_fix`), whatever patch the build itself holds, so +/// every build of the gem reports that pin's change. `None` (`null`) where +/// `changes` has no one answer for the pin. +pub(super) fn of_report(changes: &PinChanges<'_>, report: &PinReport) -> Option { + let Some(gem_fix) = report.gem_fix.as_deref() else { + let uuid = report.uuid.as_deref()?; + return changes.get(&(report.purl.as_str(), uuid)).copied(); + }; + let mut of_pin = changes + .iter() + .filter(|((_, uuid), _)| *uuid == gem_fix) + .map(|(_, changed)| *changed); + let changed = of_pin.next()?; + of_pin.all(|other| other == changed).then_some(changed) +} + pub(super) fn unchanged(confirmed: &[(String, String)]) -> PinChanges<'_> { confirmed .iter() diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 85571f984f..cb2fd7c029 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -9,8 +9,7 @@ use clap::Args; use futures_util::StreamExt; use socket_patch_core::api::client::{ - build_proxy_fallback_client, get_api_client_with_overrides, hold_back_debug, - is_fallback_candidate, ApiClient, ApiError, + get_api_client_with_overrides, hold_back_debug, is_fallback_candidate, ApiClient, ApiError, }; use socket_patch_core::api::types::{BatchPackagePatches, BatchSearchResponse, PatchSearchResult}; use socket_patch_core::crawlers::ruby_crawler::{ @@ -79,7 +78,7 @@ use self::hosted::run_redirect; use self::vendor_flow::{ boxed_vendor_interactive_path, boxed_vendor_json_path, partition_skipped_selected, }; -pub(crate) use self::vendor_flow::{boxed_vendor_step, preview_vendor, VendorStep}; +pub(crate) use self::vendor_flow::{boxed_vendor_step, classify_vendor, VendorStep}; /// Packages per batch request on the authenticated API when `--batch-size` /// is not given: the server's own per-request maximum @@ -788,6 +787,25 @@ fn print_rollout_human(stage: &rollout::Stage, dry_run: bool, silent: bool, own_ } } +/// The invocation's API client as a scan in `mode` asks it. +/// +/// A hosted or a vendored run patches a gem through the patch of the gem +/// itself, whose reference names the patched build of every platform. The +/// patch of a platform gem, which the patch service returns beside it, is +/// no offer there, and the run's client is where that is said, once: it +/// answers every search without those patches +/// ([`ApiClient::offering_platform_gem_patches`]), so nothing after it +/// counts, selects, reports or asks about one. Agent mode's client answers +/// in full: there each is what an installed copy of that platform gem +/// takes. +/// +/// Said for each project directory's run, since the directories of one +/// invocation share a client and can differ in mode. +fn client_for(mode: Option, client: ApiClient) -> ApiClient { + let offered = !matches!(mode, Some(ScanMode::Hosted | ScanMode::Vendored)); + client.offering_platform_gem_patches(offered) +} + /// The tier filter, then the policy's per-package selection (see /// [`ScanPolicy::select`]): scan never prompts, so every package gets its /// top-ranked admitted patch (see `api::ranking`). @@ -2429,9 +2447,10 @@ async fn scan_project( let overrides = args.common.api_client_overrides(); // One client per invocation: the project directories of a run share // its connection (and its org lookup). - let (mut api_client, mut use_public_proxy) = report + let (api_client, mut use_public_proxy) = report .client(get_api_client_with_overrides(overrides.clone())) .await; + let mut api_client = client_for(args.mode, api_client); // Sized for the endpoint the run starts on. A mid-run downgrade to the // proxy keeps these chunk boundaries: every chunk is within the proxy's // body cap by construction (`BATCH_BODY_BYTE_CAP`). @@ -3392,7 +3411,8 @@ async fn scan_project( falling back to public patch API proxy (free patches only)." )); } - api_client = build_proxy_fallback_client(&overrides); + // Made from the run's client: it answers a search alike. + api_client = api_client.proxy_fallback(&overrides); use_public_proxy = true; fallback_to_proxy = true; report.fell_back_to(&api_client); @@ -4172,7 +4192,7 @@ async fn scan_project( let selected = if report_only { selected } else if vendor { - let preview = preview_vendor(&args.common, &selected).await; + let preview = classify_vendor(&args.common, &selected).await; let refused = preview.refused_purls(); vendor_preview = Some(preview); stage.plan(&rows, |r| !refused.contains(&r.writer.purl)); @@ -4385,6 +4405,11 @@ async fn scan_project( .take() .expect("the vendored planning pass computed the preview"); preview.retain_selected(&selected); + // The future embeds the vendor backend's reading of a gem's + // lock and its requests to the patch service, for a vendored + // dry run alone: awaited in line it lay in the poll frame of + // a scan in every mode. `boxed` leaves this frame one pointer. + boxed(|| preview.ask_platform_gems(&args.common, &api_client, use_public_proxy)).await; Some(preview) } else { None diff --git a/crates/socket-patch-cli/src/commands/scan/policy.rs b/crates/socket-patch-cli/src/commands/scan/policy.rs index 616ccac1ae..05448d7994 100644 --- a/crates/socket-patch-cli/src/commands/scan/policy.rs +++ b/crates/socket-patch-cli/src/commands/scan/policy.rs @@ -1158,6 +1158,53 @@ mod tests { .collect() } + /// A package search returns the patches of a gem's platform gems + /// beside the patch of the gem itself, and every one of them is an + /// offer under its own purl: a selection takes what the search answer + /// holds. Agent mode's answer holds them all. The client of a hosted + /// or a vendored run answers without them + /// (`leave_out_platform_gem_patches`), so its selection is the gem's + /// own patch alone, with nothing of the others in any list, withheld + /// or filtered. + #[test] + fn a_selection_takes_a_gem_through_the_patches_its_search_answer_holds() { + use socket_patch_core::api::types::SearchResponse; + use socket_patch_core::hosted::engine::leave_out_platform_gem_patches; + let of = |uuid: &str, purl: &str| { + let mut offer = offer(uuid, &[(HIGH, "high")]); + offer.purl = purl.to_string(); + offer + }; + let source = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let linux = "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu"; + let darwin = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + let answer = || { + let another = "cccccccc-0000-4000-8000-000000000001"; + SearchResponse { + patches: vec![of(A1, linux), of(B1, source), of(another, darwin)], + can_access_paid_patches: true, + } + }; + + let agent = filtered_policy("", r#"{"version": 1}"#, None); + let all = agent.select(answer().patches); + assert_eq!( + all.selected.keys().collect::>(), + [darwin, source, linux], + "agent mode is offered each platform gem's patch" + ); + + let vendored = filtered_policy("", r#"{"version": 1}"#, None); + let mut narrowed = answer(); + leave_out_platform_gem_patches(&mut narrowed); + let own = vendored.select(narrowed.patches); + assert_eq!(own.selected.keys().collect::>(), [source]); + assert_eq!(own.selected[source].uuid, B1); + assert_eq!(own.unfiltered.keys().collect::>(), [source]); + assert!(own.withheld.is_empty()); + assert!(filtered_entries(&vendored).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/report.rs b/crates/socket-patch-cli/src/commands/scan/report.rs index 392f8913bf..aacc4e7560 100644 --- a/crates/socket-patch-cli/src/commands/scan/report.rs +++ b/crates/socket-patch-cli/src/commands/scan/report.rs @@ -20,7 +20,9 @@ use std::time::{Duration, Instant}; use socket_patch_core::api::client::ApiClient; use socket_patch_core::api::ranking::{cmp_batch_infos, severity_order}; use socket_patch_core::api::types::{BatchPackagePatches, PatchSearchResult, PatchStatistics}; +use socket_patch_core::hosted::engine::PinReport; use socket_patch_core::policy::filter::{Reachability, SelectionFilter}; +use socket_patch_core::utils::purl::purl_parts; use socket_patch_core::utils::purl_key::PurlKey; use super::discovery::Access; @@ -51,6 +53,11 @@ const UPGRADE_HOURS: usize = 2; /// The package column is as wide as the longest name, up to this many /// columns; a longer name keeps its `@version` and loses its middle. const MAX_NAME_COL: usize = 44; +/// The widest the closing line about unpatched gem builds +/// ([`unpatched_builds_line`]) lets itself get: one row of an 80-column +/// terminal beside the closing lines' two-column gutter, short of the +/// terminal's last column. +const BUILDS_LINE_COLS: usize = 77; /// One package with a patch on offer, as the report counts and shows it. #[derive(Debug, Clone, Default, PartialEq, Eq)] @@ -280,6 +287,10 @@ pub(crate) struct Counts { /// Some lookup of the run saw free patches only (the public proxy): /// "nothing left" then speaks for the free patches alone. pub(crate) free_only: bool, + /// The gems on a hosted patch whose installed copy is still the + /// unpatched one after the run ([`Run::stale_gem_installs`]): the run + /// then does not say that nothing is left. + pub(crate) stale_installs: usize, } impl Counts { @@ -356,6 +367,91 @@ impl Counts { } } +/// The locked builds of one gem that a hosted run left on upstream's gem: +/// the patch registry has no patched build for their platforms yet, so +/// those platforms install what they installed before. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct UnpatchedBuilds { + /// ` `, as the run's lines name a gem. + pub(crate) gem: String, + pub(crate) platforms: Vec, +} + +/// Add to `builds` the locked builds of `reports` (a hosted run's pins per +/// locked build) that keep upstream's gem. A build is one platform gem of +/// one version, however many project directories lock it: each is listed +/// once, in the order the run met it. +fn note_unpatched_builds(builds: &mut Vec, reports: &[PinReport]) { + let kept = reports + .iter() + .filter(|report| report.gem_fix.is_some() && report.uuid.is_none()); + for report in kept { + let Some((_, name, version)) = purl_parts(&report.purl) else { + continue; + }; + let gem = format!("{name} {version}"); + let platform = report.platform.as_deref().unwrap_or("ruby"); + let at = match builds.iter().position(|known| known.gem == gem) { + Some(at) => at, + None => { + builds.push(UnpatchedBuilds { + gem, + platforms: Vec::new(), + }); + builds.len() - 1 + } + }; + if !builds[at].platforms.iter().any(|known| known == platform) { + builds[at].platforms.push(platform.to_string()); + } + } +} + +/// The closing line about the gem builds a hosted run left on upstream's +/// gem (`builds`), which stands where "Nothing left to patch." would: the +/// run's packages are patched, and these builds of them are not. Not a +/// warning: nothing here needs doing, and a later run patches a build once +/// the patch registry has one. `None` when there is no such build. +/// +/// ```text +/// Not patched yet: nokogiri 1.19.3 for arm64-darwin, x86_64-linux-musl. +/// Not patched yet: 3 builds of nokogiri 1.19.3, ffi 1.17.2. +/// Not patched yet: 12 builds of 7 gems. +/// ``` +/// +/// It names each gem with its platforms while that fits one row of an +/// 80-column terminal ([`BUILDS_LINE_COLS`]), then the gems with how many +/// builds they add up to, then only how many there are of each: the run's +/// own line about each gem names every platform. +fn unpatched_builds_line(builds: &[UnpatchedBuilds], color: bool) -> Option { + const LEAD: &str = "Not patched yet"; + let builds: Vec<&UnpatchedBuilds> = builds + .iter() + .filter(|gem| !gem.platforms.is_empty()) + .collect(); + if builds.is_empty() { + return None; + } + let count = builds.iter().map(|gem| gem.platforms.len()).sum(); + let counted = plural(count, "build", "builds"); + let with_platforms: Vec = builds + .iter() + .map(|gem| format!("{} for {}", gem.gem, gem.platforms.join(", "))) + .collect(); + let gems: Vec<&str> = builds.iter().map(|gem| gem.gem.as_str()).collect(); + // What the row has room for beside the lead, its colon and space, and + // the closing period. + let room = BUILDS_LINE_COLS - LEAD.len() - ": .".len(); + let named = [ + with_platforms.join("; "), + format!("{counted} of {}", gems.join(", ")), + ] + .into_iter() + .find(|named| named.chars().count() <= room) + .unwrap_or_else(|| format!("{counted} of {}", plural(builds.len(), "gem", "gems"))); + Some(format!("{}: {named}.", ui::paint(LEAD, "1;33", color))) +} + /// `left` as a share of `fixed + left`, for the closing lines: a whole /// percentage that never rounds a remainder away (`<1%`) or the fixed /// part to nothing (`>99%`). `None` when nothing was fixed, where the @@ -577,10 +673,16 @@ fn meter(fixed: usize, left: usize, style: Style) -> Option { /// lines under the count say so (how many merged patches, one per patched /// package that waits, and what to do). /// +/// A hosted run can leave a locked build of a patched gem on upstream's +/// gem (`builds`). The lines then name those builds +/// ([`unpatched_builds_line`]) where they would say that nothing is left, +/// or under what is left. +/// /// Where the terminal shows glyphs, the lines of what was done open with a /// check mark (the others are indented to match) and a meter closes them. pub(crate) fn closing( counts: &Counts, + builds: &[UnpatchedBuilds], projects: usize, dry_run: bool, reachability: bool, @@ -588,10 +690,11 @@ pub(crate) fn closing( style: Style, ) -> Vec { let left = counts.left(); - if counts.patched == 0 && left == 0 { + let color = style.color; + let unpatched_builds = unpatched_builds_line(builds, color); + if counts.patched == 0 && left == 0 && unpatched_builds.is_none() { return Vec::new(); } - let color = style.color; let num = |n: usize, one: &str, many: &str| { format!( "{} {}", @@ -703,7 +806,26 @@ pub(crate) fn closing( } else { "Nothing left to patch." }; - lines.push(plain(nothing.to_string())); + // A gem build still on upstream's gem is something left, and so + // is a patched gem whose installed copy is still the unpatched + // one: the run's warning names the command for it. + if counts.stale_installs > 0 { + lines.push(plain(format!( + "{} on disk: the warning names the command that installs the patched {}.", + plural( + counts.stale_installs, + "gem is still unpatched", + "gems are still unpatched" + ), + if counts.stale_installs == 1 { + "gem" + } else { + "gems" + }, + ))); + } else if unpatched_builds.is_none() { + lines.push(plain(nothing.to_string())); + } } else { let mut why = Vec::new(); if counts.left_merge > 0 { @@ -773,6 +895,7 @@ pub(crate) fn closing( ))); } } + lines.extend(unpatched_builds.map(plain)); if reachability { let share = percent_left(counts.fixed_reachable, counts.left_reachable) .map(|p| format!(" ({p})")) @@ -829,6 +952,12 @@ pub(crate) struct Run { shares_lookups: bool, /// Some project directory's lookup ran on the public proxy. free_only: bool, + /// The gem builds the hosted runs left on upstream's gem + /// ([`Self::hosted_builds`]). + unpatched_builds: Vec, + /// The gems the hosted runs left with their unpatched copy installed + /// ([`Self::stale_gem_installs`]). + stale_installs: usize, } impl Run { @@ -851,6 +980,8 @@ impl Run { upsold: false, shares_lookups: false, free_only: false, + unpatched_builds: Vec::new(), + stale_installs: 0, } } @@ -1071,6 +1202,23 @@ impl Run { ); } + /// A project directory's hosted pins per locked build (`reports`, + /// `engine::pin_reports`). The builds among them that keep upstream's + /// gem are named in the closing lines, which then do not say that + /// nothing is left to patch. Once per directory. + pub(crate) fn hosted_builds(&mut self, reports: &[PinReport]) { + note_unpatched_builds(&mut self.unpatched_builds, reports); + } + + /// How many gems a project directory's hosted run left on a hosted + /// patch with the unpatched copy still installed (its + /// `redirect_gem_stale_install` warning names the command). The closing + /// lines then do not say that nothing is left to patch. Once per + /// directory. + pub(crate) fn stale_gem_installs(&mut self, gems: usize) { + self.stale_installs += gems; + } + /// Print the closing lines (stdout), under a blank line. The elapsed /// time is for someone watching: it prints on a terminal only, so a /// log of the same run reads the same every time. @@ -1087,9 +1235,11 @@ impl Run { let mut counts = self.counts; counts.verify(&self.patched, &self.measured); counts.free_only = self.free_only; + counts.stale_installs = self.stale_installs; let elapsed = ui::attended(ui::Stream::Stdout).then(|| self.started.elapsed()); let lines = closing( &counts, + &self.unpatched_builds, self.projects, self.dry_run, self.reachability, @@ -1655,7 +1805,7 @@ mod tests { ..counts(22, 39, 14, 3, 1) }; assert_eq!( - closing(&c, 3, false, false, None, PLAIN), + closing(&c, &[], 3, false, false, None, PLAIN), vec![ "Patched 22 packages in 3 projects, fixing 39 vulnerabilities (5 critical, 21 high).", "Saved about 44 hours of engineering time (22 package upgrades at ~2 hours each).", @@ -1667,6 +1817,7 @@ mod tests { assert_eq!( closing( &counts(1, 1, 0, 0, 0), + &[], 1, false, false, @@ -1679,9 +1830,34 @@ mod tests { "Nothing left to patch.", ] ); + // A patched gem whose installed copy is still the unpatched one is + // something left: the run never says that nothing is. + for (stale, line) in [ + ( + 1, + "1 gem is still unpatched on disk: the warning names the command that installs \ + the patched gem.", + ), + ( + 2, + "2 gems are still unpatched on disk: the warning names the command that installs \ + the patched gems.", + ), + ] { + let c = Counts { + stale_installs: stale, + ..counts(2, 2, 0, 0, 0) + }; + let lines = closing(&c, &[], 1, false, false, None, PLAIN); + assert_eq!(lines.last().map(String::as_str), Some(line)); + assert!( + !lines.iter().any(|l| l.contains("Nothing left")), + "{lines:?}" + ); + } // A patch that names no advisory still patched its package. assert_eq!( - closing(&counts(2, 0, 0, 0, 0), 2, false, false, None, PLAIN), + closing(&counts(2, 0, 0, 0, 0), &[], 2, false, false, None, PLAIN), vec![ "Patched 2 packages in 2 projects.", "Saved about 4 hours of engineering time (2 package upgrades at ~2 hours each).", @@ -1690,14 +1866,14 @@ mod tests { ); // Nothing patched: only what is left, with no share of nothing. assert_eq!( - closing(&counts(0, 0, 0, 4, 1), 0, false, false, None, PLAIN), + closing(&counts(0, 0, 0, 4, 1), &[], 0, false, false, None, PLAIN), vec![ "5 vulnerabilities left to patch: 4 need a paid Socket plan, 1 is in packages \ this run did not patch." ] ); // Nothing found at all: no lines. - assert!(closing(&Counts::default(), 0, false, false, None, PLAIN).is_empty()); + assert!(closing(&Counts::default(), &[], 0, false, false, None, PLAIN).is_empty()); } /// Advisories waiting on a merged patch are counted apart from the @@ -1711,7 +1887,7 @@ mod tests { ..counts(1, 1, 0, 0, 0) }; assert_eq!( - closing(&one, 1, false, false, None, PLAIN)[2..], + closing(&one, &[], 1, false, false, None, PLAIN)[2..], [ "1 vulnerability left to patch (50%): 1 awaits a merged patch.", "1 merged patch is not ready yet: Socket is still processing it.", @@ -1724,7 +1900,7 @@ mod tests { ..counts(22, 39, 8, 3, 1) }; assert_eq!( - closing(&many, 3, true, false, None, PLAIN)[2..], + closing(&many, &[], 3, true, false, None, PLAIN)[2..], [ "18 vulnerabilities would be left to patch (32%): 6 await a merged patch, 8 need a \ package upgrade, 3 need a paid Socket plan, 1 is in packages a run would not \ @@ -1743,7 +1919,7 @@ mod tests { ..counts(22, 39, 1, 0, 2) }; assert_eq!( - closing(&c, 3, true, true, None, PLAIN), + closing(&c, &[], 3, true, true, None, PLAIN), vec![ "Would patch 22 packages in 3 projects, fixing 39 vulnerabilities.", "Would save about 44 hours of engineering time (22 package upgrades at ~2 hours \ @@ -1758,7 +1934,7 @@ mod tests { ..counts(5, 6, 0, 0, 0) }; assert_eq!( - closing(&none_left, 1, false, true, None, PLAIN)[2..], + closing(&none_left, &[], 1, false, true, None, PLAIN)[2..], [ "Nothing left to patch.", "Reachable: 4 fixed, 0 left to patch." @@ -1768,7 +1944,7 @@ mod tests { #[test] fn closing_colors_the_numbers_only() { - let lines = closing(&counts(2, 3, 1, 0, 0), 1, false, false, None, COLOR); + let lines = closing(&counts(2, 3, 1, 0, 0), &[], 1, false, false, None, COLOR); assert_eq!( lines[0], "\x1b[1;32mPatched\x1b[0m \x1b[1m2\x1b[0m packages, fixing \x1b[1m3\x1b[0m vulnerabilities." @@ -1776,7 +1952,7 @@ mod tests { let plain: Vec = lines.iter().map(|l| ui::strip_ansi(l)).collect(); assert_eq!( plain, - closing(&counts(2, 3, 1, 0, 0), 1, false, false, None, PLAIN) + closing(&counts(2, 3, 1, 0, 0), &[], 1, false, false, None, PLAIN) ); } @@ -1841,7 +2017,7 @@ mod tests { tests: 1208, ..counts(22, 39, 23, 0, 0) }; - let plain = closing(&c, 3, false, false, None, PLAIN); + let plain = closing(&c, &[], 3, false, false, None, PLAIN); assert_eq!( plain, vec![ @@ -1853,7 +2029,7 @@ mod tests { ); // With glyphs: a check mark on what was done, the rest indented to // match, and the meter of the share patched. - let fancy: Vec = closing(&c, 3, false, false, None, FANCY) + let fancy: Vec = closing(&c, &[], 3, false, false, None, FANCY) .iter() .map(|l| ui::strip_ansi(l)) .collect(); @@ -1874,7 +2050,7 @@ mod tests { tests_passing: 1200, ..c }; - let lines: Vec = closing(&partly, 3, false, false, None, FANCY) + let lines: Vec = closing(&partly, &[], 3, false, false, None, FANCY) .iter() .map(|l| ui::strip_ansi(l)) .collect(); @@ -1884,7 +2060,7 @@ mod tests { (measured for 18 of 22 patches)." ); // Nothing left: no meter to draw. - let done = closing(&counts(2, 3, 0, 0, 0), 1, false, false, None, FANCY); + let done = closing(&counts(2, 3, 0, 0, 0), &[], 1, false, false, None, FANCY); assert_eq!(done.len(), 3); assert_eq!(ui::strip_ansi(&done[2]), " Nothing left to patch."); // A lookup that saw free patches only speaks for those alone. @@ -1893,11 +2069,238 @@ mod tests { ..counts(2, 3, 0, 0, 0) }; assert_eq!( - closing(&free, 1, false, false, None, PLAIN)[2], + closing(&free, &[], 1, false, false, None, PLAIN)[2], "No free patches left to apply." ); } + fn unpatched(gem: &str, platforms: &[&str]) -> UnpatchedBuilds { + UnpatchedBuilds { + gem: gem.to_string(), + platforms: strs(platforms), + } + } + + /// One locked build of a hosted gem as a run reports it: patched under + /// `patch`, or on upstream's gem with none. + fn build(purl: &str, platform: Option<&str>, patch: Option<&str>) -> PinReport { + PinReport { + purl: match platform { + Some(platform) => format!("{purl}?platform={platform}"), + None => purl.to_string(), + }, + uuid: patch.map(str::to_string), + gem_fix: Some("gem-fix".to_string()), + platform: platform.map(str::to_string), + newly_patched: patch.is_some(), + withdrawn: false, + } + } + + const NOKOGIRI: &str = "pkg:gem/nokogiri@1.19.3"; + const FFI: &str = "pkg:gem/ffi@1.17.2"; + + /// A run whose every package is patched does not say that nothing is + /// left while a locked build of one of them keeps upstream's gem: one + /// line names the build in that place, on a dry run too, with no + /// check mark and no meter. + #[test] + fn closing_names_a_gem_build_that_is_not_patched_yet() { + let one = [unpatched("nokogiri 1.19.3", &["arm64-darwin"])]; + let wet = closing(&counts(1, 1, 0, 0, 0), &one, 1, false, false, None, PLAIN); + assert_eq!( + wet, + vec![ + "Patched 1 package, fixing 1 vulnerability.", + "Saved about 2 hours of engineering time (1 package upgrade at ~2 hours).", + "Not patched yet: nokogiri 1.19.3 for arm64-darwin.", + ] + ); + let dry = closing(&counts(1, 1, 0, 0, 0), &one, 1, true, false, None, PLAIN); + assert_eq!(dry[0], "Would patch 1 package, fixing 1 vulnerability."); + assert_eq!(dry[2..], wet[2..]); + // A lookup that saw free patches only: the build is still what is + // left, so the line about free patches gives way too. + let free = Counts { + free_only: true, + ..counts(1, 1, 0, 0, 0) + }; + assert_eq!( + closing(&free, &one, 1, false, false, None, PLAIN)[2..], + wet[2..] + ); + // With glyphs and color: in the gutter, its lead painted like the + // count of what is left, and nothing after it. + let fancy = closing(&counts(1, 1, 0, 0, 0), &one, 1, false, false, None, FANCY); + assert_eq!( + fancy[2..], + [" \x1b[1;33mNot patched yet\x1b[0m: nokogiri 1.19.3 for arm64-darwin."] + ); + // No build on upstream's gem: nothing is left. + let none = [unpatched("nokogiri 1.19.3", &[])]; + assert_eq!( + closing(&counts(1, 1, 0, 0, 0), &none, 1, false, false, None, PLAIN)[2..], + ["Nothing left to patch."] + ); + } + + /// Beside advisories left to patch the line follows theirs, ahead of + /// the reachable count and the meter. + #[test] + fn closing_names_unpatched_builds_after_what_is_left() { + let one = [unpatched("nokogiri 1.19.3", &["arm64-darwin"])]; + let c = Counts { + left_merge: 1, + merge_packages: 1, + fixed_reachable: 1, + ..counts(2, 3, 0, 0, 1) + }; + let lines: Vec = closing(&c, &one, 1, false, true, None, FANCY) + .iter() + .map(|l| ui::strip_ansi(l)) + .collect(); + assert_eq!( + lines[2..], + [ + " 2 vulnerabilities left to patch (40%): 1 awaits a merged patch, 1 is in \ + packages this run did not patch." + .to_string(), + " 1 merged patch is not ready yet: Socket is still processing it.".to_string(), + " Run `socket-patch scan` again later to apply it.".to_string(), + " Not patched yet: nokogiri 1.19.3 for arm64-darwin.".to_string(), + " Reachable: 1 fixed, 0 left to patch.".to_string(), + format!(" {} 60% patched", "━".repeat(METER_CELLS)), + ] + ); + // The builds alone are worth the closing lines. + assert_eq!( + closing(&Counts::default(), &one, 0, false, false, None, PLAIN), + vec!["Not patched yet: nokogiri 1.19.3 for arm64-darwin."] + ); + } + + /// The line names every gem with its platforms while that fits one row + /// of an 80-column terminal beside the gutter, then the gems and how + /// many builds they add up to, then only how many there are. + #[test] + fn unpatched_builds_line_fits_a_row_and_says_less_when_it_cannot() { + let line = |builds: &[UnpatchedBuilds]| unpatched_builds_line(builds, false); + assert_eq!(line(&[]), None); + assert_eq!( + line(&[unpatched( + "nokogiri 1.19.3", + &["arm64-darwin", "x86_64-linux-musl"] + )]) + .as_deref(), + Some("Not patched yet: nokogiri 1.19.3 for arm64-darwin, x86_64-linux-musl.") + ); + // Two gems, each with its platform. + let two = [ + unpatched("ffi 1.17.2", &["arm64-darwin"]), + unpatched("racc 1.8.1", &["java"]), + ]; + assert_eq!( + line(&two).as_deref(), + Some("Not patched yet: ffi 1.17.2 for arm64-darwin; racc 1.8.1 for java.") + ); + // Too wide with the platforms: the gems, and how many builds. + let wide = [ + unpatched("nokogiri 1.19.3", &["arm64-darwin", "x86_64-linux-musl"]), + unpatched("ffi 1.17.2", &["arm64-darwin"]), + ]; + assert_eq!( + line(&wide).as_deref(), + Some("Not patched yet: 3 builds of nokogiri 1.19.3, ffi 1.17.2.") + ); + // Too wide with the gems: how many there are of each. + let many: Vec = (0..7) + .map(|i| { + unpatched( + &format!("native-gem-{i} 1.0.{i}"), + &["arm64-darwin", "java"], + ) + }) + .collect(); + assert_eq!( + line(&many).as_deref(), + Some("Not patched yet: 14 builds of 7 gems.") + ); + // One gem whose name alone fills the row. + let long = [unpatched(&format!("{} 1.0.0", "g".repeat(70)), &["java"])]; + assert_eq!( + line(&long).as_deref(), + Some("Not patched yet: 1 build of 1 gem.") + ); + // The widest line that still names its platforms: it fills the + // row beside the gutter and no more. One column wider, it does not. + let fits = [unpatched( + "nokogiri 1.19.3", + &["aarch64-linux-musl", "x86_64-darwin", "java"], + )]; + let full = line(&fits).unwrap(); + assert_eq!( + full, + "Not patched yet: nokogiri 1.19.3 for aarch64-linux-musl, x86_64-darwin, java." + ); + assert_eq!(full.chars().count(), BUILDS_LINE_COLS); + assert!(format!(" {full}").chars().count() < 80); + let over = [unpatched( + "nokogiri 1.19.3", + &["aarch64-linux-musl", "x86_64-darwin", "jruby"], + )]; + assert_eq!( + line(&over).as_deref(), + Some("Not patched yet: 3 builds of nokogiri 1.19.3.") + ); + } + + /// The builds on upstream's gem are read off a hosted run's pins per + /// locked build: a patched build and a pin that is no platform gem are + /// not among them, the ruby-platform gem is the platform `ruby`, and a + /// build several project directories lock is one build. + #[test] + fn unpatched_builds_are_the_locked_builds_on_upstream_gems() { + let mut builds = Vec::new(); + let plain_pin = PinReport { + purl: "pkg:npm/undici@8.10.0".to_string(), + uuid: Some("u".to_string()), + gem_fix: None, + platform: None, + newly_patched: false, + withdrawn: false, + }; + note_unpatched_builds( + &mut builds, + &[ + plain_pin.clone(), + build(NOKOGIRI, Some("arm64-darwin"), None), + build(NOKOGIRI, Some("x86_64-linux-gnu"), Some("linux")), + build(NOKOGIRI, None, None), + build(FFI, Some("x86_64-linux-gnu"), Some("ffi-linux")), + ], + ); + assert_eq!( + builds, + [unpatched("nokogiri 1.19.3", &["arm64-darwin", "ruby"])] + ); + // The next project directory locks the same build, and one more. + note_unpatched_builds( + &mut builds, + &[ + build(NOKOGIRI, Some("arm64-darwin"), None), + build(FFI, Some("java"), None), + plain_pin, + ], + ); + assert_eq!( + builds, + [ + unpatched("nokogiri 1.19.3", &["arm64-darwin", "ruby"]), + unpatched("ffi 1.17.2", &["java"]), + ] + ); + } + #[test] fn percent_left_never_rounds_to_all_or_nothing() { assert_eq!(percent_left(39, 18).as_deref(), Some("32%")); 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 ea9c84a1cf..4692e0645f 100644 --- a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs +++ b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs @@ -22,8 +22,12 @@ use socket_patch_core::manifest::operations::{read_manifest, write_manifest}; 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::gem::LockedBuildsPreview; 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, lookup_entry, save_state, GemBuildEntry, VendorOutcome, VendorState, + VENDOR_PREBUILT_PLATFORM_PENDING, +}; use std::collections::{HashMap, HashSet}; use std::path::Path; use std::time::Duration; @@ -107,9 +111,44 @@ pub(crate) struct PreviewRow { /// Symlinked wiring files the wet run's commit refuses to rename over /// (see [`symlinked_wiring_warnings`]); only on vendor/revendor rows. pub(crate) warnings: Vec, + /// gem: the lockfiles pin the package hosted, so the wet run restores + /// its upstream entry before it vendors (a takeover). + pub(crate) hosted: bool, + /// gem: the platform gems the wet run would vendor for a gem + /// `Gemfile.lock` names as precompiled platform gems, each with its + /// own patch, once the patch service was asked + /// ([`VendorPreview::ask_platform_gems`]). Only on vendor/revendor + /// rows, which are then reported once per platform gem, as the wet + /// run reports them. + pub(crate) gem_builds: Vec, + /// gem: the trees the ledger records for the gem, which say which of + /// [`Self::gem_builds`] the wet run would put in place of another. + pub(crate) gem_recorded: Option>, +} + +impl PreviewRow { + /// What the wet run would report of each tree of [`Self::gem_builds`] + /// (`crate::commands::vendor::gem_build_reports`). `gem_recorded` is + /// what the ledger holds for the gem. + fn gem_reports(&self) -> Vec { + // A copy in step holds the trees the ledger records: the wet run + // writes none of them. + let in_step = matches!(self.verdict, PreviewVerdict::AlreadyVendored); + let builds = match (in_step, self.gem_recorded.as_deref()) { + (true, Some(recorded)) => recorded, + _ => self.gem_builds.as_slice(), + }; + crate::commands::vendor::gem_build_reports( + &self.purl, + &self.uuid, + builds, + self.gem_recorded.as_deref(), + !in_step, + ) + } } -/// The vendored dry-run preview, purl-sorted (see [`preview_vendor`]). +/// The vendored dry-run preview, purl-sorted (see [`classify_vendor`]). #[derive(Debug, Clone, Default)] pub(crate) struct VendorPreview { pub(crate) rows: Vec, @@ -161,8 +200,11 @@ impl VendorPreview { /// `details.mode: "vendored"`: `verified` for a patch the wet run would /// vendor (`oldUuid` on a re-vendor), `skipped` / `already_vendored` /// for one in sync, and `skipped` with the preflight's code for one the - /// wet run would refuse (never a status or exit change). Each symlink - /// advisory joins the top-level `warnings`, prefixed with its purl. + /// wet run would refuse (never a status or exit change). A gem the wet + /// run would vendor as platform gems is one `verified` event per + /// platform gem, each under that gem's own patch, as the wet run + /// reports it. Each symlink advisory joins the top-level `warnings`, + /// prefixed with its purl. pub(crate) fn record_into(&self, env: &mut Envelope) { for row in &self.rows { let event = match &row.verdict { @@ -184,10 +226,15 @@ impl VendorPreview { PatchEvent::new(PatchAction::Verified, row.purl.as_str()) } }; - env.record(tag_mode( - event.with_uuid(row.uuid.as_str()), - Some("vendored"), - )); + let event = event.with_uuid(row.uuid.as_str()); + let events = match row.gem_reports().as_slice() { + [] => vec![event], + reports => crate::commands::vendor::gem_build_events(&event, reports), + }; + for event in events { + let event = tag_mode(event, Some("vendored")); + crate::commands::vendor::record_gem_build_event(env, event); + } env.warnings.extend( row.warnings.iter().map(|w| { RunWarning::new(w.code.as_str(), format!("{}: {}", row.purl, w.detail)) @@ -196,6 +243,135 @@ impl VendorPreview { } } + /// Ask the patch service what the wet run would do with each gem of + /// the preview that `Gemfile.lock` names as precompiled platform gems, + /// so a dry run says what the wet run does: vendored mode needs a + /// patched build of every locked platform, which the ledger cannot + /// tell. The requests are the ones the wet run's vendor step makes + /// before it downloads anything, for each such gem the wet run would + /// vendor or re-vendor: the package reference of the gem's patch and, + /// only where that names a patched build for every locked platform, + /// the references of those builds' patches in one request more (see + /// [`socket_patch_core::vendor::gem::preview_locked_builds`]). None is + /// made for any other row, and none under `--offline`. Nothing is + /// downloaded or written. + /// + /// A gem with a patched build of every locked platform keeps its + /// verdict and gains the platform gems it is reported by + /// ([`PreviewRow::gem_builds`]). Any other answer becomes the row's + /// would-refuse verdict, settled as the wet run's vendor step settles + /// the backend's refusal: a locked platform with no patched build is + /// that step's skip, with its one line, and a patch service that + /// could not say is the failure the wet run would end in, never a + /// promise to vendor. + /// + /// `client` is the run's API client, and `use_public_proxy` whether + /// it targets the public proxy: the client the wet run's vendor step + /// asks through, so the preview takes the wet run's route (a fallback + /// to the public proxy included) and resolves no organisation of its + /// own. + pub(crate) async fn ask_platform_gems( + &mut self, + common: &GlobalArgs, + client: &ApiClient, + use_public_proxy: bool, + ) { + let would_vendor = |row: &PreviewRow| { + matches!( + row.verdict, + PreviewVerdict::WouldVendor | PreviewVerdict::WouldRevendor { .. } + ) + }; + // A gem already vendored for its patch is asked about too: its + // copy follows the builds the patch registry lists. + let in_sync = |row: &PreviewRow| matches!(row.verdict, PreviewVerdict::AlreadyVendored); + let candidates: Vec<&str> = self + .rows + .iter() + .filter(|row| would_vendor(row) || in_sync(row)) + .map(|row| row.purl.as_str()) + .collect(); + let platform_gems: HashSet = + socket_patch_core::vendor::gem::gems_locked_as_platform_gems(&common.cwd, &candidates) + .await + .into_iter() + .collect(); + if platform_gems.is_empty() { + return; + } + // Offline, the backend refuses before it would ask. + let service = common.vendor_service_config(Some(client.clone()), use_public_proxy); + let state = load_state(&common.cwd).await.unwrap_or_default(); + for row in &mut self.rows { + let vendored = in_sync(row); + if !(would_vendor(row) || vendored) || !platform_gems.contains(&row.purl) { + continue; + } + row.gem_recorded = lookup_entry(&state.entries, &row.purl) + .filter(|entry| entry.ecosystem == "gem" && !entry.gem_builds.is_empty()) + .map(|entry| entry.gem_builds.clone()); + let asked = socket_patch_core::vendor::gem::preview_locked_builds( + &common.cwd, + &row.purl, + &row.uuid, + row.hosted, + Some(&service), + ) + .await; + let (code, detail) = match asked { + None => continue, + Some(LockedBuildsPreview::Vendor(builds)) => { + // The wet run vendors the copy again with these. + if vendored { + row.verdict = PreviewVerdict::WouldVendor; + } + row.gem_builds = builds; + continue; + } + // A patched build the list names is not served yet: the + // wet run skips the gem and leaves its intact copy in + // force as it is (`wired_copy_failed`). + Some(LockedBuildsPreview::Refused { code, detail }) + if vendored && code == VENDOR_PREBUILT_PLATFORM_PENDING => + { + let detail = format!("{detail}; its vendored copy stays in force as it is."); + (code, detail) + } + // What the wet run leaves a vendored copy with is the + // copy as it is. + Some(LockedBuildsPreview::Refused { .. }) if vendored => continue, + Some(LockedBuildsPreview::Refused { code, detail }) => (code, detail), + }; + // As the vendor loop settles the backend's refusal: an older + // vendored patch still in force keeps an unserved one a skip. + let settled = crate::commands::vendor::keep_older_vendored_patch( + Some(VendorOutcome::Refused { code, detail }), + &state, + &row.purl, + &row.uuid, + common, + ) + .await; + let Some(VendorOutcome::Refused { code, detail }) = settled else { + continue; + }; + row.verdict = PreviewVerdict::WouldRefuse { + code: code.to_string(), + detail, + }; + // The symlink advisories are for rows the wet run writes. + row.warnings.clear(); + } + } + + /// The lines of the gems the wet run would vendor as platform gems + /// with upstream's own gem for a locked platform, as its vendor step + /// prints them (`format_vendored_gem_build_lines`). + fn gem_build_lines(&self) -> Vec { + let reports: Vec<_> = self.rows.iter().flat_map(PreviewRow::gem_reports).collect(); + crate::commands::gem_build_lines::format_vendored_gem_build_lines(&reports, true) + } + /// The uuids of the rows the wet run would vendor or already holds: /// every row it would not refuse. pub(crate) fn landing_uuids(&self) -> HashSet<&str> { @@ -229,12 +405,18 @@ impl VendorPreview { /// (already vendored)` line for each in-sync row (stderr, the wet /// run's line and stream), a `[would-refuse]` line naming what the wet /// run would refuse and why (a `[skip]` line on stderr, as the wet run - /// prints it, when the refusal is an expected skip), and the symlink - /// advisories. Shared by + /// prints it, when the refusal is an expected skip; the one line of a + /// gem with a locked platform that has no patched build, as the wet + /// run's vendor step prints it), and the symlink advisories. Shared by /// `scan --mode vendored --dry-run` and `get … --mode vendored /// --dry-run` so the two cannot drift. Callers gate it on `--silent`. pub(crate) fn print_human(&self) { println!("{}", self.dry_run_line()); + let stdout_width = + crate::ui::attended(crate::ui::Stream::Stdout).then(crate::ui::stdout_width); + for line in self.gem_build_lines() { + println!("{}", crate::ui::wrap_line(&line, stdout_width)); + } for row in &self.rows { if matches!(row.verdict, PreviewVerdict::AlreadyVendored) { eprintln!( @@ -248,7 +430,13 @@ impl VendorPreview { } for row in &self.rows { if let PreviewVerdict::WouldRefuse { code, detail } = &row.verdict { - if row.verdict.would_skip() == Some(true) { + if code == VENDOR_PREBUILT_PLATFORM_PENDING { + // The wet run's line and stream: its vendor step's. + eprintln!( + "{}", + crate::commands::vendor::format_skip(&row.purl, code, detail) + ); + } else if row.verdict.would_skip() == Some(true) { // The wet run's line and stream. eprintln!( "{}", @@ -269,8 +457,9 @@ impl VendorPreview { } } -/// Dry-run preview for `scan --mode vendored` (and `get … --mode vendored -/// --dry-run`): classify each selected patch against the vendor ledger +/// The classification behind the dry-run preview of `scan --mode vendored` +/// (and `get … --mode vendored --dry-run`): classify each selected patch +/// against the vendor ledger /// without writing anything or touching the network beyond discovery /// (see [`PreviewVerdict`]): would-refuse for every purl the wet run /// refuses before any download @@ -294,20 +483,29 @@ impl VendorPreview { /// shows as would-refuse never takes a `--max-new-patches` slot (#1908, /// #1976). Resolves the run's `--patch-server-url` origins and the gem /// takeover refusals itself. -pub(crate) async fn preview_vendor( +/// +/// A dry run then asks the patch service about the gems the lock names as +/// platform gems ([`VendorPreview::ask_platform_gems`]), for the rows the +/// plan left in the run: what the wet run learns in its vendor step, +/// after the plan, is not the planning pass's to know. +pub(crate) async fn classify_vendor( common: &GlobalArgs, selected: &[PatchSearchResult], ) -> VendorPreview { let origins = crate::commands::hosted_unwind::patch_server_origins(common); - let takeover = crate::commands::vendor::gem_takeover_preview_refusals( + let (takeover, hosted) = crate::commands::vendor::gem_takeover_preview_refusals( common, selected.iter().map(|p| p.purl.as_str()), ) .await; - preview_vendor_with(&common.cwd, selected, &origins, &takeover).await + let mut preview = preview_vendor_with(&common.cwd, selected, &origins, &takeover).await; + for row in &mut preview.rows { + row.hosted = hosted.contains(&row.purl); + } + preview } -/// [`preview_vendor`] over caller-resolved `origins` (the run's +/// [`classify_vendor`] over caller-resolved `origins` (the run's /// `--patch-server-url` origins) and `takeover_refusals` (keyed by the /// selected purl, each a would-refuse row); the unit tests seed both. async fn preview_vendor_with( @@ -392,6 +590,9 @@ async fn preview_vendor_with( uuid: p.uuid.clone(), verdict, warnings, + hosted: false, + gem_builds: Vec::new(), + gem_recorded: None, } }) .collect(); @@ -856,7 +1057,7 @@ async fn run_vendor_json_path( // The planning pass: a patch the preflight refuses holds no slot (it // still reaches the engine, which reports the refusal). let writers = writers_of(&rows); - let mut preview = preview_vendor(&args.common, &writers).await; + let mut preview = classify_vendor(&args.common, &writers).await; let refused = preview.refused_purls(); stage.plan(&rows, |r| !refused.contains(&r.writer.purl)); let deferred = stage.deferred_keys(); @@ -867,10 +1068,14 @@ async fn run_vendor_json_path( finish_rollout_json(stage, env); if args.common.dry_run { - // No downloads, no backends: classify against the ledger + // No downloads, no backends: classify against the ledger, ask the + // patch service about the gems the lock names as platform gems, // and preview the GC, exactly like agent mode's dry run (and the // human arm, which previews the same GC through `finish_human`). preview.retain_selected(&selected); + preview + .ask_platform_gems(&args.common, api_client, use_public_proxy) + .await; preview.record_into(env); if prune { gc_into( @@ -1509,6 +1714,7 @@ mod migration_tests { mod preview_tests { use super::{preview_vendor_with, PreviewVerdict}; use crate::json_envelope::{Command, Envelope}; + use socket_patch_core::api::client::{ApiClient, ApiClientOptions, ApiRoute}; use socket_patch_core::api::types::PatchSearchResult; use std::collections::HashMap; use std::path::Path; @@ -1682,6 +1888,78 @@ mod preview_tests { } } + /// A gem `Gemfile.lock` names as precompiled platform gems is vendored + /// only once every locked platform has a patched build, which the + /// ledger cannot tell and the patch service can. Offline the service + /// may not be asked: the row says the failure the wet run ends in, + /// never that the gem would be vendored, and nothing is requested (the + /// API of this run answers nowhere). A gem the lock names for the ruby + /// platform is not asked about, offline or not: its row stands. + #[tokio::test] + async fn an_offline_preview_never_promises_a_platform_locked_gem() { + const NOKO: &str = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + const RACK: &str = "pkg:gem/rack@3.2.6"; + const NOKO_UUID: &str = "9f6b2c4e-1d3a-4f6b-8c2d-7e5a9b1c3d5f"; + const RACK_UUID: &str = "9f6b2c4e-1d3a-4f6b-8c2d-7e5a9b1c3d60"; + let tmp = tempfile::tempdir().unwrap(); + std::fs::write( + tmp.path().join("Gemfile"), + "source \"https://rubygems.org\"\n\ngem \"nokogiri\"\ngem \"rack\"\n", + ) + .unwrap(); + std::fs::write( + tmp.path().join("Gemfile.lock"), + "GEM\n remote: https://rubygems.org/\n specs:\n nokogiri \ + (1.18.10-arm64-darwin)\n nokogiri (1.18.10-x86_64-linux-gnu)\n rack \ + (3.2.6)\n\nPLATFORMS\n arm64-darwin\n x86_64-linux-gnu\n\nDEPENDENCIES\n \ + nokogiri\n rack\n\nBUNDLED WITH\n 2.5.22\n", + ) + .unwrap(); + let common = crate::args::GlobalArgs { + cwd: tmp.path().to_path_buf(), + api_url: Some("http://127.0.0.1:9".to_string()), + proxy_url: Some("http://127.0.0.1:9".to_string()), + offline: true, + dry_run: true, + silent: true, + ..Default::default() + }; + let selected = [sel(NOKO_UUID, NOKO), sel(RACK_UUID, RACK)]; + let mut preview = super::classify_vendor(&common, &selected).await; + assert!( + preview + .rows + .iter() + .all(|row| matches!(row.verdict, PreviewVerdict::WouldVendor)), + "the ledger alone knows neither gem: {:?}", + preview.rows + ); + + // The run's client, which answers nowhere either. + let client = ApiClient::new(ApiClientOptions { + api_url: "http://127.0.0.1:9".to_string(), + api_token: None, + route: ApiRoute::Proxy, + }); + preview.ask_platform_gems(&common, &client, true).await; + let verdict = |purl: &str| { + let row = preview.rows.iter().find(|row| row.purl == purl); + row.unwrap_or_else(|| panic!("{purl}")).verdict.clone() + }; + match verdict(NOKO) { + PreviewVerdict::WouldRefuse { code, detail } => { + assert_eq!(code, "vendor_service_offline_conflict", "{detail}") + } + other => panic!("{other:?}"), + } + assert!(matches!(verdict(RACK), PreviewVerdict::WouldVendor)); + assert_eq!(preview.refused_count(), 1); + assert_eq!( + preview.landing_uuids(), + std::collections::HashSet::from([RACK_UUID]) + ); + } + fn seed_entry(root: &Path, purl: &str, uuid: &str) { let vendor = root.join(".socket/vendor"); std::fs::create_dir_all(&vendor).unwrap(); @@ -2093,14 +2371,14 @@ wheels = [ silent: true, ..Default::default() }; - let refused = super::preview_vendor(&common, &[sel(UUID, SIX)]) + let refused = super::classify_vendor(&common, &[sel(UUID, SIX)]) .await .refused_purls(); assert!(refused.contains(SIX), "{refused:?}"); // Control: without the setting the patch keeps its slot. std::fs::write(tmp.path().join("pyproject.toml"), UV_PYPROJECT).unwrap(); - let refused = super::preview_vendor(&common, &[sel(UUID, SIX)]) + let refused = super::classify_vendor(&common, &[sel(UUID, SIX)]) .await .refused_purls(); assert!(refused.is_empty(), "{refused:?}"); @@ -2471,7 +2749,7 @@ mod npm_lock_entry_refusal_tests { cwd: root.to_path_buf(), ..GlobalArgs::default() }; - let refused = preview_vendor(&common, &[sel(LEFT_PAD), sel(IS_NUMBER)]) + let refused = classify_vendor(&common, &[sel(LEFT_PAD), sel(IS_NUMBER)]) .await .refused_purls(); assert_eq!( diff --git a/crates/socket-patch-cli/src/commands/scan/withdrawn.rs b/crates/socket-patch-cli/src/commands/scan/withdrawn.rs index 6264b93a6d..a5a3f10213 100644 --- a/crates/socket-patch-cli/src/commands/scan/withdrawn.rs +++ b/crates/socket-patch-cli/src/commands/scan/withdrawn.rs @@ -189,6 +189,7 @@ async fn withdrawn( .collect::>() .into_iter() .collect(); + let held = super::hosted::gem_lock_snapshots(&common.cwd).await; // A network round trip between the lookup and the patch records. let asked = crate::ui::busy( common, @@ -196,7 +197,7 @@ async fn withdrawn( "Checking {}", crate::ui::plural(uuids.len(), "hosted patch", "hosted patches") ), - api_client.fetch_registry_references(&uuids), + api_client.fetch_registry_references(&uuids, &held), ) .await; let references = match asked { diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 1c2af7c4fe..bed94134ad 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -25,6 +25,9 @@ use futures_util::StreamExt; use socket_patch_core::api::client::get_api_client_with_overrides; use socket_patch_core::constants::SOCKET_DIR; use socket_patch_core::crawlers::{CrawlerOptions, Ecosystem}; +use socket_patch_core::hosted::engine::{ + gem_upstream_build_kept_detail, PinReport, GEM_UPSTREAM_BUILD_KEPT, +}; use socket_patch_core::manifest::operations::{manifest_exists, read_manifest, write_manifest}; use socket_patch_core::manifest::schema::{PatchManifest, PatchRecord}; use socket_patch_core::patch::apply::{verify_file_patch, PatchSources}; @@ -51,6 +54,7 @@ use std::time::Duration; use crate::args::{apply_env_toggles, GlobalArgs}; use crate::commands::apply::{representative_file, result_to_event, variant_matches_installed}; +use crate::commands::gem_build_lines::format_vendored_gem_build_lines; use crate::commands::lock_cli::acquire_or_emit; use crate::commands::vendor_orphans::{ orphan_label, orphan_removal_failed, orphan_removed_event, orphan_still_wired, @@ -132,14 +136,16 @@ use socket_patch_core::vendor::refusals::refusal_is_benign; /// `vendor_prebuilt_required` failure it always was, a failed `Done` minus /// the unserved marker (its error already says it). /// -/// One unserved refusal is a skip with nothing to keep as well: +/// One unserved refusal is a skip whatever the ledger holds: /// [`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 a locked platform that has no patched build. A patched build +/// is named only once it is published, so the run cannot tell "not yet" +/// from "never", and the project is exactly as it was. The backend's +/// detail is the whole line, and already says which vendored copy, if +/// any, stays in force. /// /// [`Discovery::vendor_entry_live`]: socket_patch_core::vex::discover::Discovery::vendor_entry_live -async fn keep_older_vendored_patch( +pub(crate) async fn keep_older_vendored_patch( outcome: Option, state: &VendorState, purl: &str, @@ -147,6 +153,11 @@ async fn keep_older_vendored_patch( common: &GlobalArgs, ) -> Option { let (code, detail, failed_done) = match outcome { + Some(VendorOutcome::Refused { code, detail }) + if code == vendor::VENDOR_PREBUILT_PLATFORM_PENDING => + { + return Some(VendorOutcome::Refused { code, detail }); + } Some(VendorOutcome::Refused { code, detail }) if vendor::is_unserved(code) => { (code, detail, None) } @@ -197,9 +208,6 @@ async fn keep_older_vendored_patch( entry, warnings, }, - None if code == vendor::VENDOR_PREBUILT_PLATFORM_PENDING => { - VendorOutcome::Refused { code, detail } - } None => VendorOutcome::Refused { code: vendor::VENDOR_PREBUILT_REQUIRED, detail, @@ -399,6 +407,11 @@ async fn takeover_dry_refusal( service, pipenv_version, installed_sites, + // The pin this previews the takeover of stays when the backend + // refuses. + true, + None, + &mut Vec::new(), )) .await; drop(probe); @@ -437,7 +450,15 @@ fn restored_text_previewable( /// Dispatch one purl to its ecosystem backend. `pkg_path` is the crawler's /// installed location (site-packages root for pypi, the package dir /// otherwise), when available. Returns `None` for purls with no vendor -/// backend in this build. +/// backend in this build. Three arguments are the gem backend's alone (see +/// [`vendor::gem::vendor_gem_previewing`]): `hosted` says the lockfile +/// pins the package hosted and the caller keeps that pin when the backend +/// does not vendor it (a takeover or an eject), so the backend words its +/// refusal for a gem that stays hosted; `gem_list` is the list of the +/// gem's fix that an exact restore of its copy was refused over, from +/// which the backend vendors the copy again; `gem_preview` receives the +/// platform gems a dry run found the wet run would vendor for a gem +/// locked as platform gems. #[allow(clippy::too_many_arguments)] pub(crate) async fn dispatch_vendor_one( purl: &str, @@ -451,6 +472,9 @@ pub(crate) async fn dispatch_vendor_one( service: Option<&VendorServiceConfig>, pipenv_version: &tokio::sync::OnceCell>, installed_sites: &vendor::pypi::InstalledSiteListings, + hosted: bool, + gem_list: Option<&vendor::gem::FixList>, + gem_preview: &mut Vec, ) -> Option { let eco = ecosystem_dir_for_purl(purl)?; // Before any backend write: a linked vendor dir is never ours, and the @@ -514,7 +538,23 @@ pub(crate) async fn dispatch_vendor_one( ) .await } - "gem" => vend!(vendor::gem::vendor_gem, pkg_path), + "gem" => { + vendor::gem::vendor_gem_previewing( + purl, + pkg_path, + project_root, + record, + sources, + vendored_at, + dry_run, + force, + service, + hosted, + gem_list, + gem_preview, + ) + .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), @@ -795,6 +835,9 @@ fn advisory_tier(code: &str) -> AdvisoryTier { "vendor_prebuilt_downloaded" | "vendor_artifact_reused" => AdvisoryTier::Verbose, // The run did what was asked; these explain how. "vendor_fetched_missing" + // An intact copy that could not follow its fix's list stays in + // force: nothing is wrong with the project. + | vendor::gem::GEM_LIST_NOT_FOLLOWED | "vendor_would_revert_redirect" | "vendor_takeover_reverted_redirect" | "cargo_wiring_migrated" @@ -813,6 +856,21 @@ pub(crate) fn format_advisory(code: &str, detail: &str, verbose: bool) -> Option } } +/// The human line of a package the run leaves alone as an expected skip: +/// `Skipping : `. The detail of a gem with a locked platform +/// that has no patched build ([`vendor::VENDOR_PREBUILT_PLATFORM_PENDING`]) +/// names the gem itself and is the whole line. +pub(crate) fn format_skip(purl: &str, code: &str, detail: &str) -> String { + if code == vendor::VENDOR_PREBUILT_PLATFORM_PENDING { + // The one line of the gem, on stderr: wrapped for a person at a + // terminal, as the hosted line of such a gem is. + let width = crate::ui::attended(crate::ui::Stream::Stderr).then(crate::ui::stderr_width); + crate::ui::wrap_line(detail, width) + } else { + format!("Skipping {}: {detail}", normalize_purl(purl)) + } +} + /// `Error: Cannot vendor : `. fn format_vendor_failure(purl: &str, detail: &str) -> String { format!("Error: Cannot vendor {}: {detail}", normalize_purl(purl)) @@ -855,6 +913,204 @@ 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 gem's patch, the one its vendored directory and ledger +/// entry are named after. Such a gem is ONE vendored package with one +/// event per platform gem, each under that platform gem's own patch and +/// each counted in `summary`, as hosted mode reports it; the key ties +/// those events together, so a count of packages takes them once. +const GEM_FIX_DETAIL: &str = "gemFix"; +/// `details` key of those events: the platform of the event's gem. +const GEM_PLATFORM_DETAIL: &str = "platform"; + +/// What a run reports of each tree of a gem vendored as platform gems +/// (`builds`, of the gem `base_purl` under the gem's patch `fix`), as +/// hosted mode reports the locked builds of a pin ([`PinReport`]): a +/// patched build under its own patch, a tree of upstream's own gem under +/// none. `wrote`: the run put `builds` in place (or is a dry run of one +/// that would), over the trees the ledger recorded for the gem before +/// (`prior`). A patched build the ledger did not hold is then +/// `newly_patched`, and a tree of upstream's gem where it held a patched +/// build is `withdrawn`. +pub(crate) fn gem_build_reports( + base_purl: &str, + fix: &str, + builds: &[vendor::GemBuildEntry], + prior: Option<&[vendor::GemBuildEntry]>, + wrote: bool, +) -> Vec { + builds + .iter() + .map(|built| { + let before = + prior.and_then(|prior| prior.iter().find(|b| b.platform == built.platform)); + let was_patched = before.is_some_and(|before| !before.is_upstream()); + PinReport { + purl: built.purl(base_purl), + uuid: (!built.is_upstream()).then(|| built.uuid.clone()), + gem_fix: Some(fix.to_string()), + platform: Some(built.platform.clone()), + newly_patched: wrote && !built.is_upstream() && !was_patched, + withdrawn: wrote && built.is_upstream() && was_patched, + } + }) + .collect() +} + +/// `event`, the outcome of a gem vendored as platform gems, once per tree +/// of the gem (`reports`, see [`gem_build_reports`]), as hosted mode +/// reports a pin's locked builds. A patched build is the gem's event under +/// that platform gem (`pkg:gem/@?platform=`) and +/// its own patch, with `newlyPatched: true` where this run put it in place +/// of upstream's gem. A tree of upstream's own gem is the advisory +/// `skipped` event hosted mode records for such a build +/// ([`GEM_UPSTREAM_BUILD_KEPT`]), with no `uuid` and `withdrawn: true` +/// where this run put it in place of a patched build: `summary` does not +/// count it ([`record_gem_build_event`]). Only where the gem's event is a +/// failure (the copy did not verify) does such a tree share it. `details` +/// ties each event to the gem's patch. +pub(crate) fn gem_build_events(event: &PatchEvent, reports: &[PinReport]) -> Vec { + reports + .iter() + .map(|report| { + let platform = report.platform.as_deref().unwrap_or_default(); + let mut built = match &report.uuid { + Some(_) => event.clone(), + None if event.action == PatchAction::Failed => event.clone(), + None => PatchEvent::new(PatchAction::Skipped, report.purl.as_str()).with_reason( + GEM_UPSTREAM_BUILD_KEPT, + gem_upstream_build_kept_detail(platform, report.withdrawn), + ), + }; + built.purl = Some(report.purl.clone()); + built.uuid = report.uuid.clone(); + let mut details = built + .details + .take() + .filter(serde_json::Value::is_object) + .unwrap_or_else(|| serde_json::json!({})); + details[GEM_FIX_DETAIL] = serde_json::json!(report.gem_fix); + details[GEM_PLATFORM_DETAIL] = serde_json::json!(platform); + if report.newly_patched { + details["newlyPatched"] = serde_json::json!(true); + } + if report.withdrawn { + details["withdrawn"] = serde_json::json!(true); + } + built.details = Some(details); + built + }) + .collect() +} + +/// Record one event of [`gem_build_events`]: `summary` counts each but +/// the advisory one of a tree of upstream's gem, where nothing was +/// skipped (as hosted mode records it). +pub(crate) fn record_gem_build_event(env: &mut Envelope, event: PatchEvent) { + if event.error_code.as_deref() == Some(GEM_UPSTREAM_BUILD_KEPT) { + env.events.push(event); + } else { + env.record(event); + } +} + +/// The run's reports of the gems it vendored as platform gems, read back +/// from the events of [`gem_build_events`] in `env`: one per tree a run +/// holds in place (or a dry run would). +fn gem_build_reports_of(env: &Envelope) -> Vec { + let flag = |details: &serde_json::Value, key: &str| details[key].as_bool() == Some(true); + env.events + .iter() + .filter(|event| { + matches!(event.action, PatchAction::Applied | PatchAction::Verified) + || matches!( + event.error_code.as_deref(), + Some("already_vendored" | GEM_UPSTREAM_BUILD_KEPT) + ) + }) + .filter_map(|event| { + let details = event.details.as_ref()?; + Some(PinReport { + purl: event.purl.clone()?, + uuid: event.uuid.clone(), + gem_fix: Some(details.get(GEM_FIX_DETAIL)?.as_str()?.to_string()), + platform: Some(details.get(GEM_PLATFORM_DETAIL)?.as_str()?.to_string()), + newly_patched: flag(details, "newlyPatched"), + withdrawn: flag(details, "withdrawn"), + }) + }) + .collect() +} + +/// 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)) + // The advisory event of a tree of upstream's gem is in no count + // of `summary`, so it is no repeat of one either. + .filter(|event| event.error_code.as_deref() != Some(GEM_UPSTREAM_BUILD_KEPT)) + .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 + })) +} + +/// [`Envelope::retract_applied`] for a vendor run. The advisories of a gem +/// vendored as platform gems name the gem, while its `applied` events name +/// its platform gems, so the advisories of a retracted one are dropped +/// here: the re-tagged events are the gem's one account. +/// +/// `summary.skipped` is left as it is: a vendor advisory is an event the +/// summary never counted ([`push_advisory_event`]), so dropping one takes +/// nothing out of the count. +fn retract_vendored( + env: &mut Envelope, + since: usize, + action: PatchAction, + code: &str, + message: &str, +) -> usize { + let since = since.min(env.events.len()); + let is_build = |event: &PatchEvent| { + event.action == PatchAction::Applied + && event + .details + .as_ref() + .is_some_and(|details| details.get(GEM_FIX_DETAIL).is_some()) + }; + let gems: HashSet = env.events[since..] + .iter() + .filter(|event| is_build(event)) + .filter_map(|event| event.purl.as_deref()) + .map(|purl| strip_purl_qualifiers(purl).to_string()) + .collect(); + let mut index = 0; + env.events.retain(|event| { + let advisory = index >= since + && event.action == PatchAction::Skipped + && event + .purl + .as_deref() + .is_some_and(|purl| gems.contains(strip_purl_qualifiers(purl))); + index += 1; + !advisory + }); + env.retract_applied(since, action, code, message) +} + /// Per-outcome counts behind the human vendor summary line. #[derive(Debug, Default, Clone, PartialEq, Eq)] struct VendorTally { @@ -874,20 +1130,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, @@ -896,8 +1155,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)), } } } @@ -1605,7 +1867,22 @@ 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 reports = gem_build_reports( + &entry.base_purl, + &entry.uuid, + &entry.gem_builds, + None, + false, + ); + for event in gem_build_events(&event, &reports) { + record_gem_build_event(&mut env, event); + } + } else { + env.record(event); + } } let mut unledgered_uuids: HashSet<&str> = HashSet::new(); for (key, record) in manifest @@ -1797,25 +2074,33 @@ async fn gem_takeover_refusal( /// [`gem_takeover_refusal`] for the dry-run preview of `scan` / `get /// --mode vendored`: each selected gem purl the lockfiles still pin hosted -/// whose takeover the wet run would refuse, keyed by the selected purl. -/// Nothing is written (the restore is resolved as a dry run). +/// whose takeover the wet run would refuse, keyed by the selected purl, +/// and with them every selected gem purl the lockfiles pin hosted (the +/// ones the wet run takes over). Nothing is written (the restore is +/// resolved as a dry run). pub(crate) async fn gem_takeover_preview_refusals<'a>( common: &GlobalArgs, purls: impl Iterator, -) -> HashMap { +) -> (HashMap, HashSet) { let gems: Vec<&str> = purls.filter(|p| p.starts_with("pkg:gem/")).collect(); if gems.is_empty() { - return HashMap::new(); + return (HashMap::new(), HashSet::new()); } let pins = HostedPin::all(&crate::commands::discover_wiring(common, &common.cwd).await); - gem_takeover_refusals_for( + let hosted = gems + .iter() + .filter(|purl| pins.iter().any(|pin| PurlKey::same(&pin.purl, purl))) + .map(|purl| purl.to_string()) + .collect(); + let refusals = gem_takeover_refusals_for( &common.cwd, gems.into_iter(), &pins, common.offline, crate::commands::hosted_unwind::patch_server_origins(common), ) - .await + .await; + (refusals, hosted) } /// [`gem_takeover_preview_refusals`] over already-discovered hosted `pins`: @@ -2374,8 +2659,8 @@ async fn run_eject( .await { // An eject has no skip: a pin it cannot vendor stays hosted - // and the eject is refused whole, so a prebuild that is not - // built yet is the plain miss here. + // and the eject is refused whole, so a gem with a locked + // platform that has no patched build is the plain miss here. let code = match vendor::is_unserved(code) { true => vendor::VENDOR_PREBUILT_REQUIRED, false => code, @@ -2658,7 +2943,8 @@ async fn run_eject( restored: the project is still hosted, exactly as before"; // Nothing the vendored apply did survives the rollback: a // package it vendored is still hosted, not applied (#1005). - env.retract_applied( + retract_vendored( + &mut env, events_start, PatchAction::Skipped, "eject_rolled_back", @@ -2859,7 +3145,9 @@ fn vendor_outcomes( crate::telemetry_outcomes::patch_outcomes( env.events .iter() - .filter(|event| event.error_code.as_deref() != Some("vendor_orphan_removed")), + .filter(|event| event.error_code.as_deref() != Some("vendor_orphan_removed")) + // A tree of upstream's own gem is about no patch. + .filter(|event| event.error_code.as_deref() != Some(GEM_UPSTREAM_BUILD_KEPT)), MODE_VENDORED, crate::telemetry_outcomes::uuid_lookup(uuids), ) @@ -2897,7 +3185,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; } } @@ -3391,6 +3686,10 @@ struct CandidateGates<'a> { refusals: &'a VendorRefusals, /// Whether the lockfiles still pin the purl hosted. hosted_pinned: &'a dyn Fn(&str) -> bool, + /// The gem purls the Bundler lock resolves as precompiled platform + /// gems: what is vendored for one is the lock's to say, never the + /// installed copy's. + platform_gems: &'a HashSet, } impl<'a> CandidateGates<'a> { @@ -3414,8 +3713,13 @@ 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. + // So is a gem the lock resolves as platform gems: it is vendored + // as the patched gem of every locked platform, the installed copy + // is one of them at most, and a patch often touches only files no + // platform gem ships. let probe_applicable = group.is_variant_eco - && !matches!(Ecosystem::from_purl(candidate), Some(Ecosystem::Maven)); + && !matches!(Ecosystem::from_purl(candidate), Some(Ecosystem::Maven)) + && !self.platform_gems.contains(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 @@ -3912,6 +4216,16 @@ pub(crate) async fn vendor_records_reusing( }); let hosted_pinned = |purl: &str| hosted_pin_of(purl).is_some(); + let gem_purls: Vec<&str> = vendorable + .iter() + .filter(|purl| Ecosystem::from_purl(purl) == Some(Ecosystem::Gem)) + .map(String::as_str) + .collect(); + let platform_gems: HashSet = + vendor::gem::gems_locked_as_platform_gems(&common.cwd, &gem_purls) + .await + .into_iter() + .collect(); let gates = CandidateGates { cwd: &common.cwd, force, @@ -3919,6 +4233,7 @@ pub(crate) async fn vendor_records_reusing( refused: &fetch_failed, refusals: &refusals, hosted_pinned: &hosted_pinned, + platform_gems: &platform_gems, }; // Candidates the loop refuses as `vendor_variant_ambiguous`, joined to // `fetch_failed` once the loop is done. @@ -3995,7 +4310,7 @@ pub(crate) async fn vendor_records_reusing( // An expected skip, as for the backend's own // benign refusals below. if !common.silent && !common.json { - eprintln!("Skipping {}: {detail}", normalize_purl(candidate)); + eprintln!("{}", format_skip(candidate, code, &detail)); } env.record( PatchEvent::new(PatchAction::Skipped, candidate.clone()) @@ -4212,7 +4527,7 @@ pub(crate) async fn vendor_records_reusing( if refusal_is_benign(code) { // The wet run's skip: nothing is taken over. if !common.silent && !common.json { - eprintln!("Skipping {}: {detail}", normalize_purl(candidate)); + eprintln!("{}", format_skip(candidate, code, &detail)); } env.record( PatchEvent::new(PatchAction::Skipped, candidate.clone()) @@ -4303,6 +4618,14 @@ pub(crate) async fn vendor_records_reusing( } } + // The list of a gem's fix that the exact restore below read, + // whether it restored the copy or was refused over that list: + // handed to the backend, which judges the copy by it and + // vendors it again from it, so the two are decided by one + // answer. And what the restore said of the copy, which the + // backend, finishing the same copy, need not say again. + let mut gem_list: Option = None; + let mut restore_said: Vec = Vec::new(); // A dir-shaped entry with no file inventory (vendored before // inventories were recorded, or past the inventory cap) gives an // exact restore nothing to check a download against: the backend @@ -4330,28 +4653,45 @@ pub(crate) async fn vendor_records_reusing( } _ => true, }; - if redownload { - if common.dry_run { + // A copy vendored as platform gems that cannot be restored + // as it was only because the list of the gem's fix names + // other builds now is not restored: the backend below + // vendors it again from that list, as it does for an intact + // copy. A dry run asks the same question, so that it says + // what the wet run does. + if redownload && common.dry_run { + gem_list = match service { + Some(service) => { + vendor::redownload::restore_refused_over(entry, record, service).await + } + None => None, + }; + if gem_list.is_none() { env.record(PatchEvent::new(PatchAction::Verified, candidate.clone()).with_details(serde_json::json!({"wouldRedownload": true, "path": entry.artifact.path}))); continue; } + } else if redownload { + use vendor::redownload::RestoreError; let restored = match service { Some(service) => { - vendor::redownload::restore(&common.cwd, entry, record, service).await + let cwd = &common.cwd; + vendor::redownload::restore_with_list(cwd, entry, record, service).await } - None => Err( + None => Err(RestoreError::Failed( "vendoring requires a prebuilt artifact from the patch service" .to_string(), - ), + )), }; match restored { - Ok(warnings) => { + Ok((warnings, list)) => { for warning in &warnings { record_warning(env, candidate, warning, common); } env.record(PatchEvent::new(PatchAction::Rebuilt, candidate.clone()).with_details(serde_json::json!({"redownloaded": true, "path": entry.artifact.path}))); + (gem_list, restore_said) = (list, warnings); } - Err(detail) => { + Err(RestoreError::ListMoved(_, list)) => gem_list = Some(list), + Err(RestoreError::Failed(detail)) => { has_errors = true; env.record( PatchEvent::new(PatchAction::Failed, candidate.clone()) @@ -4373,6 +4713,7 @@ pub(crate) async fn vendor_records_reusing( index + 1, total, )); + let mut gem_preview: Vec = Vec::new(); let outcome = dispatch_vendor_one( candidate, candidate_source, @@ -4385,6 +4726,11 @@ pub(crate) async fn vendor_records_reusing( service, &pipenv_version, &installed_sites, + // A takeover the backend does not carry through keeps its + // hosted pin (below). + hosted_pin_of(candidate).is_some(), + gem_list.as_ref(), + &mut gem_preview, ) .await; status.finish(); @@ -4407,6 +4753,51 @@ pub(crate) async fn vendor_records_reusing( let outcome = keep_older_vendored_patch(outcome, &state, candidate, &record.uuid, common).await; + // The trees of a gem vendored as platform gems, for its events + // below: the ones this run wrote, or a dry run found the wet + // run would write, else the ones the ledger records for this + // patch (an in-sync re-run writes none). + // What the ledger held for the gem before this run says which + // of them the run put in place. + let gem_recorded: Option> = + lookup_entry(&state.entries, candidate) + .filter(|entry| entry.ecosystem == "gem" && !entry.gem_builds.is_empty()) + .map(|entry| entry.gem_builds.clone()); + let (gem_builds, gem_wrote): (Vec, bool) = match &outcome { + Some(VendorOutcome::Done { + entry: Some(entry), .. + }) => (entry.gem_builds.clone(), true), + _ if !gem_preview.is_empty() => (gem_preview, true), + _ => { + let recorded = lookup_entry(&state.entries, candidate) + .filter(|entry| entry.ecosystem == "gem" && entry.uuid == record.uuid) + .map(|entry| entry.gem_builds.clone()); + (recorded.unwrap_or_default(), false) + } + }; + let gem_reports = gem_build_reports( + candidate, + &record.uuid, + &gem_builds, + gem_recorded.as_deref(), + gem_wrote, + ); + // The run puts other trees in place than the ledger records: + // the list of the gem's fix names another build for a locked + // platform (a patched build published since, upstream's gem + // where the patched build was withdrawn, or the build of + // another patch). + let gem_moved = gem_wrote + && gem_recorded.as_deref().is_some_and(|recorded| { + let held = |built: &vendor::GemBuildEntry| { + let same = |was: &&vendor::GemBuildEntry| { + was.platform == built.platform + && was.uuid.eq_ignore_ascii_case(&built.uuid) + }; + recorded.iter().any(|was| same(&was)) + }; + gem_builds.len() != recorded.len() || !gem_builds.iter().all(held) + }); match outcome { None => { env.record( @@ -4422,7 +4813,7 @@ pub(crate) async fn vendor_records_reusing( if refusal_is_benign(code) { // An expected skip, not an error: informational. if !common.silent && !common.json { - eprintln!("Skipping {}: {detail}", normalize_purl(candidate)); + eprintln!("{}", format_skip(candidate, code, &detail)); } env.record( PatchEvent::new(PatchAction::Skipped, candidate.clone()) @@ -4493,6 +4884,7 @@ pub(crate) async fn vendor_records_reusing( // ledger recording this exact patch is the tell. let dry_previewed_in_sync = common.dry_run && event.action == PatchAction::Verified + && !gem_moved && lookup_entry(&state.entries, candidate) .is_some_and(|e| e.uuid == record.uuid); if dry_previewed_in_sync { @@ -4507,15 +4899,42 @@ pub(crate) async fn vendor_records_reusing( } else { Vec::new() }; - env.record(event); + // A gem vendored as platform gems is reported per + // platform gem, as hosted mode reports it: where the gem + // is vendored (this run's `applied`, an in-sync + // `already_vendored`, a dry run's `verified` of a copy + // the ledger records) its one event becomes one per + // platform gem, each under that gem's own patch and + // each counted. + let per_build = + matches!(event.action, PatchAction::Applied | PatchAction::Verified) + || in_sync; + if per_build && !gem_reports.is_empty() { + for event in gem_build_events(&event, &gem_reports) { + record_gem_build_event(env, event); + } + } else { + env.record(event); + } for w in &symlinked { record_warning(env, candidate, w, common); } - for w in &warnings { + let said_before = |w: &VendorWarning| { + let same = + |said: &VendorWarning| said.code == w.code && said.detail == w.detail; + restore_said.iter().any(same) + }; + for w in warnings.iter().filter(|w| !said_before(w)) { // "vendored X from the patch service" on a package // this run left untouched would contradict the // "already vendored" count: JSON only. - if in_sync && w.code == "vendor_prebuilt_downloaded" { + // And a copy vendored again because the fix's list + // names other builds is said by the gem's own line + // (`format_vendored_gem_build_lines`), not as a + // warning: nothing was wrong with the copy. + let quiet = (in_sync && w.code == "vendor_prebuilt_downloaded") + || w.code == vendor::gem::GEM_LIST_FOLLOWED; + if quiet { push_advisory_event(env, candidate, w); } else { record_warning(env, candidate, w, common); @@ -4530,7 +4949,10 @@ pub(crate) async fn vendor_records_reusing( // recording it would give `--revert` an entry that // deletes the artifact yet cannot unwire the project — // leave the ledger as is. - let rebuilt = warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt"); + let rebuilt = warnings.iter().any(|w| { + w.code == "vendor_artifact_rebuilt" + || w.code == vendor::gem::GEM_LIST_FOLLOWED + }); let entry = entry.filter(|e| { !rebuilt || state @@ -4667,7 +5089,13 @@ pub(crate) async fn vendor_records_reusing( leftovers.join("; ") ); } - env.retract_applied(events_start, PatchAction::Failed, &refusal.code, &message); + retract_vendored( + env, + events_start, + PatchAction::Failed, + &refusal.code, + &message, + ); if !common.json { eprintln!("Error: {message}"); } @@ -4884,6 +5312,12 @@ fn print_vendor_closing( } let tally = VendorTally::from_envelope(env, common.dry_run, dry_in_sync); println!("{}", format_vendor_summary(common.dry_run, &tally)); + // For a gem vendored as platform gems that holds upstream's own gem + // for a locked platform: which of its platforms are patched. + let stdout_width = crate::ui::attended(crate::ui::Stream::Stdout).then(crate::ui::stdout_width); + for line in format_vendored_gem_build_lines(&gem_build_reports_of(env), common.dry_run) { + println!("{}", crate::ui::wrap_line(&line, stdout_width)); + } if let Some(lines) = closing_lines { let vendored: Vec<&str> = env .events @@ -6006,6 +6440,9 @@ mod dispatch_tests { Some(&service), &tokio::sync::OnceCell::new(), &Default::default(), + false, + None, + &mut Vec::new(), ) .await; // The backend itself may refuse (nothing is installed in the @@ -6137,6 +6574,48 @@ mod plan_gate_tests { } } + /// A gem the Bundler lock resolves as platform gems is vendored as the + /// patched gem of every locked platform, so the installed copy (one + /// platform's gem at most, often shipping none of the patched files) + /// is not put to the variant probe: the candidate goes on to its + /// backend with the installed dir as its source. + #[tokio::test] + async fn judge_does_not_probe_the_install_of_a_gem_locked_as_platform_gems() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let purl = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let dir = root.join("gems/nokogiri-1.18.10-arm64-darwin"); + std::fs::create_dir_all(&dir).unwrap(); + let all_packages = vec![(purl.to_string(), StagedSource::Installed(dir))]; + let records = HashMap::from([(purl.to_string(), record(UUID_B))]); + let none = HashSet::new(); + let variants = HashMap::from([( + "pkg:gem/nokogiri@1.18.10".to_string(), + vec![purl.to_string()], + )]); + let groups = candidate_groups(&all_packages, &variants); + let fresh = VendorState::default(); + // The installed platform gem holds none of the record's files. + assert!(matches!( + gates(root, &records, &none) + .judge(&fresh, &groups[0], purl) + .await, + CandidateVerdict::Skip + )); + let platform_gems = HashSet::from([purl.to_string()]); + let locked = CandidateGates { + platform_gems: &platform_gems, + ..gates(root, &records, &none) + }; + assert!(matches!( + locked.judge(&fresh, &groups[0], purl).await, + CandidateVerdict::Vendor { + superseded: false, + .. + } + )); + } + /// Gates with no vendored refusals, no hosted pins and no `--force`. pub(super) fn gates<'a>( root: &'a Path, @@ -6144,6 +6623,7 @@ mod plan_gate_tests { refused: &'a HashSet, ) -> CandidateGates<'a> { static NONE: VendorRefusals = VendorRefusals::new(); + static NO_PLATFORM_GEMS: std::sync::OnceLock> = std::sync::OnceLock::new(); CandidateGates { cwd: root, force: false, @@ -6151,6 +6631,7 @@ mod plan_gate_tests { refused, refusals: &NONE, hosted_pinned: &|_| false, + platform_gems: NO_PLATFORM_GEMS.get_or_init(HashSet::new), } } @@ -8890,6 +9371,412 @@ mod ui_format_tests { ); } + /// The trees of a gem vendored as platform gems, as the ledger + /// records them. + fn nokogiri_builds() -> Vec { + [("arm64-darwin", "darwin"), ("x86_64-linux-gnu", "linux")] + .into_iter() + .map(|(platform, uuid)| vendor::GemBuildEntry { + platform: platform.to_string(), + uuid: uuid.to_string(), + gem_integrity: String::new(), + gemspec_integrity: String::new(), + files: Default::default(), + }) + .collect() + } + + /// [`gem_build_events`] of trees the ledger records, as a run that + /// wrote none of them reports them. + fn build_events( + event: &PatchEvent, + purl: &str, + fix: &str, + builds: &[vendor::GemBuildEntry], + ) -> Vec { + gem_build_events(event, &gem_build_reports(purl, fix, builds, None, false)) + } + + /// A copy that holds upstream's own gem for a locked platform is + /// reported as hosted mode reports such a pin. The patched build is + /// the gem's event under its own patch, and the only one `summary` + /// counts. The tree of upstream's gem is the advisory event with no + /// patch, which says why it is there. The run's one line names both, + /// and telemetry takes the tree of upstream's gem as about no patch. + #[test] + fn a_tree_of_upstreams_gem_is_an_uncounted_event_and_a_line() { + const GEM: &str = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let mut mixed = nokogiri_builds(); + mixed[1].uuid.clear(); + let record = |event: PatchEvent, reports: &[PinReport]| { + let mut env = Envelope::new(Command::Vendor); + for event in gem_build_events(&event, reports) { + record_gem_build_event(&mut env, event); + } + env + }; + let lines = |env: &Envelope, dry_run: bool| { + format_vendored_gem_build_lines(&gem_build_reports_of(env), dry_run) + }; + + // A first vendor. + let fresh = gem_build_reports(GEM, "source", &mixed, None, true); + let env = record(PatchEvent::new(PatchAction::Applied, GEM), &fresh); + assert_eq!( + serde_json::to_value(&env.events).unwrap(), + serde_json::json!([ + { + "action": "applied", + "purl": "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin", + "uuid": "darwin", + "details": { + "gemFix": "source", "platform": "arm64-darwin", "newlyPatched": true + } + }, + { + "action": "skipped", + "purl": "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", + "reason": "the patch registry serves upstream's own gem for \ + x86_64-linux-gnu: no patched build yet", + "errorCode": "gem_upstream_build_kept", + "details": { "gemFix": "source", "platform": "x86_64-linux-gnu" } + } + ]) + ); + assert_eq!((env.summary.applied, env.summary.skipped), (1, 0)); + assert_eq!(vendored_packages(&env), 1); + const KEPT: &str = "nokogiri 1.18.10: patched for arm64-darwin; upstream gem kept for \ + x86_64-linux-gnu (no patched build yet)"; + assert_eq!(lines(&env, false), [KEPT]); + let uuids = HashMap::from([(GEM.to_string(), "source".to_string())]); + let told: Vec = vendor_outcomes(&env, &uuids) + .into_iter() + .map(|outcome| outcome.uuid) + .collect(); + assert_eq!( + told, + ["darwin"], + "the tree of upstream's gem names no patch" + ); + + // A dry run of it, and a later run that finds the copy in step. + let env = record(PatchEvent::new(PatchAction::Verified, GEM), &fresh); + assert_eq!( + lines(&env, true), + [ + "nokogiri 1.18.10: would be patched for arm64-darwin; upstream gem kept for \ + x86_64-linux-gnu (no patched build yet)" + ] + ); + let in_step = gem_build_reports(GEM, "source", &mixed, Some(&mixed), false); + let already = + PatchEvent::new(PatchAction::Skipped, GEM).with_reason("already_vendored", "in sync"); + let env = record(already.clone(), &in_step); + assert_eq!((env.summary.applied, env.summary.skipped), (0, 1)); + assert_eq!(lines(&env, false), [KEPT]); + + // The linux build is published: the run that takes it says so. + let both = nokogiri_builds(); + let gained = gem_build_reports(GEM, "source", &both, Some(&mixed), true); + let env = record(PatchEvent::new(PatchAction::Applied, GEM), &gained); + assert_eq!(env.summary.applied, 2); + assert_eq!( + env.events[1].details, + Some(serde_json::json!({ + "gemFix": "source", "platform": "x86_64-linux-gnu", "newlyPatched": true + })) + ); + assert_eq!( + env.events[0].details.as_ref().unwrap().get("newlyPatched"), + None + ); + assert_eq!( + lines(&env, false), + [ + "nokogiri 1.18.10: now also patched for x86_64-linux-gnu; already patched for \ + arm64-darwin" + ] + ); + // And it is withdrawn again. + let withdrawn = gem_build_reports(GEM, "source", &mixed, Some(&both), true); + let env = record(PatchEvent::new(PatchAction::Applied, GEM), &withdrawn); + assert_eq!(env.summary.applied, 1); + assert_eq!( + env.events[1].reason.as_deref(), + Some( + "the patch registry serves upstream's own gem for x86_64-linux-gnu: its patched \ + build was withdrawn" + ) + ); + assert_eq!( + lines(&env, false), + [ + "nokogiri 1.18.10: patched for arm64-darwin; upstream gem back for \ + x86_64-linux-gnu (its patched build was withdrawn)" + ] + ); + + // A gem whose every tree is a patched build says no line, as + // before, in step or freshly vendored. + let all = gem_build_reports(GEM, "source", &both, Some(&both), false); + assert!(lines(&record(already, &all), false).is_empty()); + let all = gem_build_reports(GEM, "source", &both, None, true); + let env = record(PatchEvent::new(PatchAction::Applied, GEM), &all); + assert!(lines(&env, false).is_empty()); + + // `vendor --check`: a copy that fails its check fails for every + // tree, the one of upstream's gem included. + let checked = gem_build_reports(GEM, "source", &mixed, None, false); + let failed = + PatchEvent::new(PatchAction::Failed, GEM).with_error("vendor_check_failed", "x"); + let env = record(failed, &checked); + assert_eq!(env.summary.failed, 2); + assert_eq!(env.events[1].uuid, None); + let verified = PatchEvent::new(PatchAction::Verified, GEM); + let env = record(verified, &checked); + assert_eq!((env.summary.verified, env.events.len()), (1, 2)); + } + + /// The advisory event of a tree of upstream's gem is in no count of + /// `summary`, so it takes nothing out of the tally: a package that was + /// skipped beside a gem in step that holds such a tree is still said. + #[test] + fn tally_keeps_a_real_skip_beside_a_gem_with_a_tree_of_upstreams_gem() { + const GEM: &str = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let mut mixed = nokogiri_builds(); + mixed[1].uuid.clear(); + let mut env = Envelope::new(Command::Vendor); + let already = + PatchEvent::new(PatchAction::Skipped, GEM).with_reason("already_vendored", "in sync"); + let in_step = gem_build_reports(GEM, "source", &mixed, Some(&mixed), false); + for event in gem_build_events(&already, &in_step) { + record_gem_build_event(&mut env, event); + } + env.record( + PatchEvent::new(PatchAction::Skipped, "pkg:gem/rack@3.1.8") + .with_reason("vendor_prebuilt_platform_pending", "left as it is"), + ); + assert_eq!(env.summary.skipped, 2, "{:?}", env.events); + let counted = VendorTally::from_envelope(&env, false, 0); + assert_eq!(counted, tally(0, 1, 0, 1, 0)); + assert_eq!( + format_vendor_summary(false, &counted), + "Vendored 0 packages; 1 already vendored; 1 skipped." + ); + } + + /// The outcome of a gem vendored as platform gems becomes one event + /// per platform gem: that gem's purl, its own patch, and details that + /// name the gem's patch and the platform beside whatever the outcome + /// carried. Everything else is the outcome's. + #[test] + fn a_gem_vendored_as_platform_gems_is_one_event_per_platform_gem() { + let outcome = PatchEvent::new( + PatchAction::Skipped, + "pkg:gem/nokogiri@1.18.10?platform=ruby", + ) + .with_reason("already_vendored", "in sync") + .with_details(serde_json::json!({ "kept": true })); + let events = build_events( + &outcome, + "pkg:gem/nokogiri@1.18.10?platform=ruby", + "source", + &nokogiri_builds(), + ); + let json = serde_json::to_value(&events).unwrap(); + assert_eq!( + json, + serde_json::json!([ + { + "action": "skipped", + "purl": "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin", + "uuid": "darwin", + "reason": "in sync", + "errorCode": "already_vendored", + "details": { "kept": true, "gemFix": "source", "platform": "arm64-darwin" } + }, + { + "action": "skipped", + "purl": "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", + "uuid": "linux", + "reason": "in sync", + "errorCode": "already_vendored", + "details": { "kept": true, "gemFix": "source", "platform": "x86_64-linux-gnu" } + } + ]) + ); + } + + /// 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| { + let purl = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + for event in build_events(event, purl, "source", &nokogiri_builds()) { + 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::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}" + ); + } + // Two gems vendored as platform gems are two packages. + let mut two = Envelope::new(Command::Vendor); + builds(&mut two, &event(PatchAction::Applied)); + for event in build_events( + &PatchEvent::new(PatchAction::Applied, "pkg:gem/ffi@1.17.0"), + "pkg:gem/ffi@1.17.0", + "another", + &nokogiri_builds(), + ) { + two.record(event); + } + assert_eq!(vendored_packages(&two), 2); + assert_eq!(two.summary.applied, 4); + assert_eq!( + format_vendor_summary(false, &VendorTally::from_envelope(&two, false, 0)), + "Vendored 2 packages." + ); + // A dry run previews the platform gems of a recorded copy as + // `verified`: one package, already vendored when the ledger + // records this patch. + 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) + ); + } + + /// A gem with a locked platform that has no patched build is one plain + /// line, the backend's own; every other skip names its package first. + /// The line is printed as the backend words it, whatever it says the + /// gem is left with: hosted mode to run, a hosted pin that stays, or a + /// vendored copy that stays in force. + #[test] + fn the_pending_platform_skip_is_one_plain_line() { + let pending = vendor::VENDOR_PREBUILT_PLATFORM_PENDING; + let purl = "pkg:gem/nokogiri@1.19.3?platform=ruby"; + for line in [ + "nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin \ + (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs a gem, patched \ + or upstream's own, for every locked platform; `scan --mode hosted` can patch the \ + others now.", + "nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin \ + (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs a gem, patched \ + or upstream's own, for every locked platform; the gem stays hosted.", + "nokogiri@1.19.3 was not brought up to date: no patched build yet for java. \ + Vendored mode needs a gem, patched or upstream's own, for every locked platform; its \ + vendored copy stays in force as \ + it is.", + "nokogiri@1.19.3 is not vendored: the patch registry does not list java. Vendored mode \ + needs a gem, patched or upstream's own, for every locked platform, and a re-run does \ + not change what the registry \ + lists: this is settled once the lockfile no longer names java (`bundle lock \ + --remove-platform java`), or the registry lists a gem for every locked platform.", + "nokogiri@1.19.3 is not vendored: the patch service lists no builds for it right \ + now. Run this again later.", + ] { + assert_eq!(format_skip(purl, pending, line), line); + } + assert_eq!( + format_skip(purl, "vendor_gem_version_not_locked", "not locked"), + "Skipping pkg:gem/nokogiri@1.19.3?platform=ruby: not locked" + ); + } + + /// A retracted run keeps one account per package: the per-platform + /// `applied` events of a gem are re-tagged, and the advisories that + /// name the gem itself are dropped with them. Another package's + /// events stay as they were. + #[test] + fn retracting_a_gem_vendored_as_platform_gems_drops_its_advisories() { + let gem = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let mut env = Envelope::new(Command::Vendor); + env.record( + PatchEvent::new(PatchAction::Skipped, "pkg:gem/rack@3.1.8") + .with_reason("already_vendored", "in sync"), + ); + let since = env.events.len(); + for event in build_events( + &PatchEvent::new(PatchAction::Applied, gem), + gem, + "source", + &nokogiri_builds(), + ) { + env.record(event); + } + push_advisory_event( + &mut env, + gem, + &VendorWarning::new("vendor_prebuilt_downloaded", "vendored nokogiri"), + ); + let retracted = retract_vendored(&mut env, since, PatchAction::Failed, "refused", "undone"); + assert_eq!(retracted, 2); + let left: Vec<(PatchAction, Option<&str>)> = env + .events + .iter() + .map(|event| (event.action, event.error_code.as_deref())) + .collect(); + assert_eq!( + left, + [ + (PatchAction::Skipped, Some("already_vendored")), + (PatchAction::Failed, Some("refused")), + (PatchAction::Failed, Some("refused")), + ] + ); + assert_eq!((env.summary.applied, env.summary.failed), (0, 2)); + // The dropped advisory was never counted, so the one counted skip + // (the other package's) is still the whole count. + assert_eq!(env.summary.skipped, 1); + let counted = env.events.iter().filter(|event| { + event.action == PatchAction::Skipped + && event.error_code.as_deref() == Some("already_vendored") + }); + assert_eq!(counted.count() as u32, env.summary.skipped); + } + #[test] fn advisories_are_tiered() { assert_eq!( diff --git a/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs b/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs index 5f19fb83fa..7b3b3ccf1e 100644 --- a/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs +++ b/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs @@ -916,7 +916,7 @@ impl VendoredBackend<'_> { common.json, &candidate.purl, "vendor_artifact_redownload_failed", - error, + error.detail().to_string(), ), } } diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 031ab34aaf..edc469f466 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -16,13 +16,13 @@ //! * `--json` (requires `--output`): VEX JSON to file, envelope JSON //! to stdout. This is the CI integration shape. -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::{Path, PathBuf}; use clap::Args; use socket_patch_core::api::client::ApiClient; use socket_patch_core::bazel::built::{unbuilt, Patched, Unbuilt}; -use socket_patch_core::manifest::schema::PatchManifest; +use socket_patch_core::manifest::schema::{PatchManifest, PatchRecord}; use socket_patch_core::telemetry::{track_vex_failed, track_vex_generated, TelemetryAuth}; use socket_patch_core::vex::verify::{npm_manifest_after_hash, DEPENDENCY_NOT_INSTALLED}; use socket_patch_core::vex::{ @@ -33,8 +33,9 @@ use socket_patch_core::vex::{ use crate::args::{apply_env_toggles, parse_bool_flag, GlobalArgs}; use crate::commands::vex_grype; use crate::commands::vex_sources::{ - self, Plan, RunApiClient, Sources, GO_WORKSPACE_OVERRIDE, RECORD_MISMATCH, RECORD_UNAVAILABLE, - REDIRECT_UNWIRED, VENDOR_UNWIRED, WIRING_CONFLICT, + self, GemBuildInfo, HostedGemBuild, Plan, RunApiClient, Sources, GEM_BUILD_UNKNOWN, + GO_WORKSPACE_OVERRIDE, RECORD_MISMATCH, RECORD_UNAVAILABLE, REDIRECT_UNWIRED, VENDOR_UNWIRED, + WIRING_CONFLICT, }; use crate::ecosystem_dispatch::{find_manifest_package_copies_reusing, JvmScope}; use crate::json_envelope::{Command, Envelope, EnvelopeError, PatchAction, PatchEvent, RunWarning}; @@ -226,6 +227,7 @@ impl VexEmbedArgs { flag_prefix: "--vex-", npm_prior: None, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), warnings_printed: Default::default(), } } @@ -296,6 +298,14 @@ pub(crate) struct VexBuildParams { /// standalone `vex` finds them through the lockfiles instead). Empty /// everywhere else. pub hosted_uuids: Vec, + /// Embedded hosted `scan --vex` only: what THIS RUN reports for each + /// locked build of the gems it pinned as platform builds + /// (`engine::pin_reports`, the reports that name a gem patch). The + /// document names those builds one by one, each patched build under + /// its own patch, and the plan asks nothing more to tell them apart + /// (see `vex_sources::Sources::hosted_gem_builds`). Empty everywhere + /// else. + pub hosted_gem_builds: Vec, /// 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. @@ -327,8 +337,26 @@ impl VexBuildParams { /// Successful result of [`generate_vex`]. pub(crate) struct VexWriteSummary { pub statements: usize, - /// How many of them say `affected` ([`unbuilt_by_bazel`]). + /// How many of them say `affected`: of a package Bazel builds without + /// its patch ([`unbuilt_by_bazel`]), or of a gem build the lockfile + /// takes from a patch registry that is not shown patched: upstream's + /// own gem, or a build of which nothing shows what the lock installs + /// ([`GemBuildView::not_patched`]). + /// + /// [`GemBuildView::not_patched`]: crate::commands::vex_sources::GemBuildView::not_patched pub affected: usize, + /// The builds the document names in place of a gem (a gem vendored as + /// platform gems, or taken from its patch registry as platform + /// builds), by purl: the standalone `vex` envelope says of each event + /// which gem patch it goes by. + pub gem_builds: std::collections::BTreeMap, + /// One line per gem whose locked builds this run told apart + /// ([`gem_build_lines`]), for a person. + pub gem_build_lines: Vec, + /// The gems the document says `affected` of because the installed copy + /// Bundler loads is upstream's precompiled build + /// ([`unpatched_gem_stand_ins`]), by purl. + pub gem_stand_ins: std::collections::BTreeSet, pub failed: Vec, /// The built document — returned so the standalone `vex` command can /// emit its per-subcomponent envelope without rebuilding. @@ -362,6 +390,9 @@ pub(crate) struct VexGenError { /// diagnostics say why a lockfile's mention is not live wiring). The /// `--json` error envelopes carry them. pub warnings: Vec, + /// The builds among `failed` that the document would have named in + /// place of a gem, by purl (see [`VexWriteSummary::gem_builds`]). + pub gem_builds: std::collections::BTreeMap, } impl VexGenError { @@ -463,6 +494,7 @@ pub async fn run(args: VexArgs) -> i32 { flag_prefix: "--", npm_prior: None, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), api_client: RunApiClient::new(), warnings_printed: Default::default(), }; @@ -501,6 +533,25 @@ pub async fn run(args: VexArgs) -> i32 { } None => eprintln!("{}", format_vex_emitted(count, summary.affected)), } + // Under it, which builds are attested of a gem the lock + // takes from its patch registry as platform builds. Beside + // the summary: stdout holds the document when it holds no + // summary. On a terminal a long line breaks after a clause. + let on_stdout = output.is_some(); + let width = + match on_stdout { + true => crate::ui::attended(crate::ui::Stream::Stdout) + .then(crate::ui::stdout_width), + false => crate::ui::attended(crate::ui::Stream::Stderr) + .then(crate::ui::stderr_width), + }; + for line in &summary.gem_build_lines { + let line = crate::ui::wrap_line(line, width); + match on_stdout { + true => println!("{line}"), + false => eprintln!("{line}"), + } + } if let Some(line) = grype.as_ref().and_then(|g| g.human_line()) { println!("{line}"); } @@ -591,7 +642,7 @@ pub async fn run(args: VexArgs) -> i32 { &args, e.code, &message, - &e.failed, + (&e.failed, &e.gem_builds), &gems, &run_warnings, grype.as_ref(), @@ -867,7 +918,6 @@ async fn generate_vex( && purl.starts_with("pkg:gem/") && plan.hosted.contains_key(purl)) }; - let redirected: &[String] = &plan.redirected; let product_id = match resolve_product_id( common, params.product.as_deref(), @@ -946,6 +996,14 @@ async fn generate_vex( // applied every gate hashing cannot stand in for (wiring liveness, the // wired-uuid rule, record match), so `--no-verify` skips ONLY the // hashing below — a stale ledger no lockfile wires stays omitted. + // The gems whose installed copies include a precompiled build Bundler + // loads in place of the ruby-platform gem the lock names. + let mut gem_stand_ins: HashSet = HashSet::new(); + // The patched platform builds of which nothing showed what an + // installed copy is ([`JudgedBuildCopies::unknown`]). + let mut unjudged_copies = BTreeMap::new(); + // The patched platform builds that have an installed copy, by purl. + let mut gem_builds_judged = std::collections::BTreeSet::new(); let mut outcome = if params.no_verify { // Trust-the-records mode still needs the vendored classification: // the property-7 exemption and the "(vendored)" phrasing key off @@ -1012,13 +1070,27 @@ async fn generate_vex( // maven's suffixed version; every copy where hosted and registry // bytes share a location) — never by a pristine sibling the // crawler's first match may be. See `vex_consumed`. - let hosted = crate::commands::vex_consumed::hosted_consumed_copies( + let mut hosted = crate::commands::vex_consumed::hosted_consumed_copies( common, &plan.hosted, &copies, params.npm_prior.as_ref(), ) .await; + // A gem the lock takes from its registry as platform builds: the + // copy of a build the lock does not install patched is upstream's + // own gem by the lock, and says nothing of the other builds. + for (purl, gem) in &plan.hosted_gems { + if let Some(consumed) = hosted.get_mut(purl) { + consumed.paths.retain(|path| gem.judges(purl, path)); + } + } + gem_stand_ins = gem_stand_in_copies(common, &plan, &hosted).await; + // A patched platform build is a patch of its own: its installed + // copies are checked against that patch's files under its own + // purl, and never against the gem patch's. + let judged = judge_gem_build_copies(common, params, &plan, &mut hosted).await; + let manifest = judged.view.as_ref().unwrap_or(manifest); let vendor = VendorContext { project_root: common.cwd.clone(), entries: plan.vendor_entries.clone(), @@ -1032,6 +1104,33 @@ async fn generate_vex( ) .await; verifying.finish(); + // A build with an installed copy goes by that copy alone: what the + // run assumes of the gem never stands in for it. + gem_builds_judged = judged.builds; + for note in judged.notes { + let said = + |warning: &RunWarning| warning.code == note.code && warning.detail == note.detail; + if !warnings.iter().any(said) { + note_warning(warnings, common, note.code, note.detail); + } + } + for (purl, why) in judged.unknown { + let gem = plan.hosted_gems.iter().find_map(|(key, gem)| { + let build = gem.builds.iter().find(|build| build.purl == purl)?; + Some((key, gem, build.platform.clone()?)) + }); + let Some((key, gem, platform)) = gem else { + continue; + }; + let note = crate::commands::vex_sources::unjudged_build_note( + key, + &gem.gem_fix, + &platform, + &why, + ); + note_warning(warnings, common, note.code, note.detail); + unjudged_copies.insert(purl, why); + } // Hosted lockfile basis: a DISCOVERED Socket-host reference whose // lock pins the artifact attests from that wiring when no installed // tree exists yet (a lockfile-only CI checkout) — the evidence the @@ -1159,8 +1258,13 @@ async fn generate_vex( .iter() .map(|s| strip_purl_qualifiers(s)) .collect(); - let is_exempt = - |purl: &str| exempt.contains(strip_purl_qualifiers(purl)) && !mirror_refused(purl); + // A platform build with an installed copy is judged by that copy: + // the gem's unqualified purl does not speak for it. + let is_exempt = |purl: &str| { + exempt.contains(strip_purl_qualifiers(purl)) + && !mirror_refused(purl) + && !gem_builds_judged.contains(purl) + }; outcome.failed.retain(|f| !is_exempt(&f.purl)); for key in manifest.patches.keys() { if is_exempt(key) && !outcome.applied.iter().any(|p| p == key) { @@ -1426,6 +1530,9 @@ async fn generate_vex( // through here, `--no-verify` and the in-run ones included. A run told // that the installed tree is what ships (`--no-bazel`) skips the step. let affected = unbuilt_by_bazel(&mut outcome, &plan, common, params, warnings).await; + // A gem whose lock names the patched gem while Ruby runs upstream's + // precompiled build is not left out: the document says `affected`. + let gem_stand_ins = unpatched_gem_stand_ins(&mut outcome, &gem_stand_ins, common, warnings); // The plan's gate omissions (record_unavailable / record_mismatch / // vendor_unwired / redirect_unwired / wiring_conflict) join the omission @@ -1512,6 +1619,34 @@ async fn generate_vex( tooling: Some(format!("socket-patch {}", env!("CARGO_PKG_VERSION"))), }; + // A gem vendored as platform gems, or taken from its patch registry as + // platform builds, was judged above as the one copy or pin it is; the + // document names each of its builds: a patched one under the patch + // that built it, and a hosted one that is not shown patched as + // affected: one the lock installs as upstream's own gem, and one of + // which nothing shows what the lock installs (see `GemBuildView`). + let mut affected = affected; + affected.extend(gem_stand_ins.iter().cloned()); + let mut redirected = plan.redirected.clone(); + let gem_builds = crate::commands::vex_sources::GemBuildView::of_judged(&plan, &unjudged_copies); + if let Some(builds) = &gem_builds { + builds.expand(&mut outcome.applied); + // A build whose own copy did not verify is not one of the gem's + // attested builds, and one that did is named once. + let withheld: HashSet<&str> = outcome.failed.iter().map(|f| f.purl.as_str()).collect(); + let mut named: HashSet = HashSet::new(); + outcome + .applied + .retain(|purl| !withheld.contains(purl.as_str()) && named.insert(purl.clone())); + builds.expand(&mut outcome.vendored); + builds.expand(&mut outcome.code_not_present); + builds.expand(&mut redirected); + builds.expand_noted(&mut affected); + affected.extend(builds.not_patched().iter().cloned()); + } + let manifest = gem_builds.as_ref().map_or(manifest, |builds| builds.view()); + let redirected: &[String] = &redirected; + // `--no-verify` declared these applied with nothing checked on disk. The // purls an in-run hosted redirect confirmed are attested from that run's // own evidence in either mode, so they are not among them. @@ -1564,6 +1699,9 @@ async fn generate_vex( failed: outcome.failed, hosted, warnings: Vec::new(), + gem_builds: gem_builds + .map(|builds| builds.builds().clone()) + .unwrap_or_default(), }); } }; @@ -1655,6 +1793,11 @@ async fn generate_vex( Ok(VexWriteSummary { statements: doc.statements.len(), affected: doc.statements.iter().filter(says_affected).count(), + gem_build_lines: gem_build_lines(&plan, &outcome.applied), + gem_builds: gem_builds + .map(|builds| builds.builds().clone()) + .unwrap_or_default(), + gem_stand_ins: gem_stand_ins.into_iter().map(|(purl, _)| purl).collect(), failed: outcome.failed, doc, warnings: Vec::new(), @@ -2072,6 +2215,86 @@ async fn unbuilt_by_bazel( affected } +/// Run warning: the lock takes the gem from its patch registry, and the +/// installed copy Bundler loads is upstream's precompiled build, so the +/// document says `affected` of it. +const GEM_STAND_IN_UNPATCHED: &str = "vex_gem_install_unpatched"; + +/// The `reason` of the `skipped` event `vex --json` reports for the gem of +/// such a statement. +const GEM_STAND_IN_REASON: &str = "attested as affected, not as patched: Bundler loads an \ + installed precompiled build of this gem, which is upstream's, in place of the patched \ + gem the lock names; the run warning says what to do"; + +/// What to do about such a gem, for its statement and the run warning. +const GEM_STAND_IN_ACTION: &str = "The lock names the patched gem, but an installed copy of \ + this gem is upstream's precompiled build, which Bundler loads in its place and \ + `bundle install` keeps. Run `socket-patch scan`: it names the files to remove before \ + `bundle install` installs the patched gem."; + +/// The hosted gems (by view purl) of which a precompiled build is +/// installed that Bundler loads in place of the ruby-platform gem their +/// lock names: the lock's `PLATFORMS` names `ruby` alone, so it names +/// every gem that way, and Bundler takes the installed gem that fits the +/// machine best. `hosted` is the copies each hosted purl is judged by. The +/// lock is read only when such a copy is installed. +async fn gem_stand_in_copies( + common: &GlobalArgs, + plan: &Plan, + hosted: &HashMap, +) -> HashSet { + use socket_patch_core::formats::gem::GemBuild; + use socket_patch_core::vendor::lock_inventory::{ + gem_lock_loads_platform_copies_in, ProjectView, + }; + let precompiled = |purl: &str, path: &PathBuf| { + let leaf = path.file_name().and_then(|leaf| leaf.to_str()); + leaf.and_then(|leaf| GemBuild::of_leaf(purl, leaf)) + .is_some_and(|build| build.platform.is_some()) + }; + let held: HashSet = hosted + .iter() + .filter(|(purl, _)| purl.starts_with("pkg:gem/") && !plan.hosted_gems.contains_key(*purl)) + .filter(|(purl, copies)| copies.paths.iter().any(|path| precompiled(purl, path))) + .map(|(purl, _)| purl.clone()) + .collect(); + if held.is_empty() + || common.is_global() + || !gem_lock_loads_platform_copies_in(&ProjectView::Disk(&common.cwd)).await + { + return HashSet::new(); + } + held +} + +/// The gems among `stand_ins` ([`gem_stand_in_copies`]) whose installed +/// copy still holds the original content (`not_applied`): the lock pins +/// the patched gem, and what Ruby runs is upstream's precompiled build. +/// That is the state of the package, so it is not left out: each leaves +/// `outcome.failed` and is returned with what to do about it, for a +/// statement that says `affected`. A run warning tells a person the same. +fn unpatched_gem_stand_ins( + outcome: &mut VerifyOutcome, + stand_ins: &HashSet, + common: &GlobalArgs, + warnings: &mut Vec, +) -> Vec<(String, String)> { + let mut affected = Vec::new(); + outcome.failed.retain(|failed| { + if failed.reason != "not_applied" || !stand_ins.contains(&failed.purl) { + return true; + } + affected.push((failed.purl.clone(), GEM_STAND_IN_ACTION.to_string())); + false + }); + affected.sort(); + for (purl, action) in &affected { + let detail = format!("{purl}: the VEX document says affected. {action}"); + note_warning(warnings, common, GEM_STAND_IN_UNPATCHED, detail); + } + affected +} + /// The start of a Maven purl. const MAVEN: &str = "pkg:maven/"; @@ -2162,6 +2385,175 @@ fn vendored_out_of_sync_detail(purl: &str, copies: &[&Path], notes: &str) -> Str ) } +/// What judging the installed copies of the patched platform builds of the +/// hosted gems found ([`judge_gem_build_copies`]). +#[derive(Default)] +struct JudgedBuildCopies { + /// The record view to check the moved copies with: the plan's, plus + /// the own record of each build that has an installed copy. `None` + /// when no copy moved. + view: Option, + /// The builds (by purl) that have an installed copy: every one judged + /// here, whatever came of it. + builds: std::collections::BTreeSet, + /// The builds (by purl) whose own record could not be read, each with + /// why: nothing judged their copies, so they are never attested. + unknown: BTreeMap, + /// What reading the records said of the run (a credential the API + /// refused, answered by the public proxy). + notes: Vec, +} + +/// Moves the installed copies of each patched platform build of a hosted +/// gem out from under the gem's purl, to be judged as that build's own. +/// +/// A platform gem is a patch of its own. Its files are not the gem +/// patch's: a compiled build changes binaries the gem's patch does not +/// name, and the service stamps the files of each patch with that patch's +/// own header, so a copy of the build never matches the gem patch's +/// hashes and is never checked against them. The copies of a build move +/// under the build's purl (`pkg:gem/@?platform=`) +/// with the record of the build's own patch, read once per build without +/// its file contents (the records of a run are read several at a time), +/// and the installed-files check judges them like any +/// other package: every copy must verify (two gem homes can hold the +/// build), and a missing or unreadable file counts as it does elsewhere. +/// Where that record cannot be read, nothing judges the copies. +async fn judge_gem_build_copies( + common: &GlobalArgs, + params: &VexBuildParams, + plan: &Plan, + hosted: &mut HashMap, +) -> JudgedBuildCopies { + use crate::commands::vex_sources::read_build_records; + use socket_patch_core::formats::gem::GemBuild; + use socket_patch_core::vex::gem_builds::GemBuildState; + let mut judged = JudgedBuildCopies::default(); + // Each build that has an installed copy: its purl, its patch, the + // gem's record its own is shaped after, and how its copies are found. + let mut builds = Vec::new(); + for (key, gem) in &plan.hosted_gems { + let (Some(record), Some(consumed)) = (plan.view.patches.get(key), hosted.get_mut(key)) + else { + continue; + }; + // Per build: its patch, and its installed copies. + let mut copies: BTreeMap<&str, (&String, Vec)> = BTreeMap::new(); + let mut kept = Vec::new(); + for path in std::mem::take(&mut consumed.paths) { + let leaf = path.file_name().and_then(|leaf| leaf.to_str()); + let platform = leaf + .and_then(|leaf| GemBuild::of_leaf(key, leaf)) + .and_then(|build| build.platform); + let own = gem.builds.iter().find_map(|build| match &build.state { + GemBuildState::Patched { uuid } + if build.platform.is_some() && build.platform == platform => + { + Some((build, uuid)) + } + _ => None, + }); + match own { + Some((build, uuid)) => { + let of_build = copies + .entry(build.purl.as_str()) + .or_insert((uuid, Vec::new())); + of_build.1.push(path); + } + None => kept.push(path), + } + } + consumed.paths = kept; + let rename = consumed.rename.clone(); + for (purl, (uuid, paths)) in copies { + judged.builds.insert(purl.to_string()); + let copies = socket_patch_core::vex::HostedCopies { + paths, + rename: rename.clone(), + }; + builds.push((purl.to_string(), uuid.clone(), record, copies)); + } + } + let uuids: Vec = builds.iter().map(|(_, uuid, ..)| uuid.clone()).collect(); + let records = read_build_records(common, ¶ms.api_client, &uuids, &mut judged.notes).await; + for ((purl, uuid, record, copies), files) in builds.into_iter().zip(records) { + match files { + Ok(files) => { + let record = PatchRecord { + uuid, + files, + ..record.clone() + }; + judged + .view + .get_or_insert_with(|| plan.view.clone()) + .patches + .insert(purl.clone(), record); + hosted.insert(purl, copies); + } + Err(why) => { + judged.unknown.insert(purl, why); + } + } + } + judged +} + +/// Which builds the document attests of each gem whose locked builds this +/// run told apart (the gems of [`Plan::hosted_gems`] the plan worked out), +/// one line per gem, in the words of the hosted scan's own line: +/// `nokogiri 1.19.3: patched for x86_64-linux-gnu; upstream gem kept for +/// arm64-darwin (no patched build yet)`. A build of which nothing shows +/// what the lock installs is `not shown patched for `: the +/// document says `affected` of it, and the run's warning says why. A +/// build the document leaves out (the lock installs it patched, and the +/// gem's installed copy did not verify) is `not attested for `. +/// The ruby-platform gem, where the lock names it beside the platform +/// builds, is the platform `ruby`. `applied` are the purls the document +/// attests as patched. +fn gem_build_lines(plan: &Plan, applied: &[String]) -> Vec { + use socket_patch_core::vex::gem_builds::GemBuildState; + let patched = |build: &HostedGemBuild| matches!(build.state, GemBuildState::Patched { .. }); + let attested = |build: &HostedGemBuild| patched(build) && applied.contains(&build.purl); + let kept = |build: &HostedGemBuild| build.state == GemBuildState::Upstream; + let unshown = |build: &HostedGemBuild| build.unshown.is_some(); + plan.hosted_gems + .values() + .filter(|gem| gem.resolved) + .map(|gem| { + let platforms = |keep: &dyn Fn(&HostedGemBuild) -> bool| -> String { + let named: Vec<&str> = gem + .builds + .iter() + .filter(|build| keep(build)) + .map(|build| build.platform.as_deref().unwrap_or("ruby")) + .collect(); + named.join(", ") + }; + let parts = [ + ("patched for", platforms(&attested), ""), + ( + "upstream gem kept for", + platforms(&kept), + " (no patched build yet)", + ), + ("not shown patched for", platforms(&unshown), ""), + ( + "not attested for", + platforms(&|build| patched(build) && !attested(build)), + "", + ), + ]; + let parts: Vec = parts + .into_iter() + .filter(|(_, platforms, _)| !platforms.is_empty()) + .map(|(lead, platforms, tail)| format!("{lead} {platforms}{tail}")) + .collect(); + format!("{} {}: {}", gem.name, gem.version, parts.join("; ")) + }) + .collect() +} + /// Record a run-level advisory: into `warnings`, which the `--json` /// envelope carries in `warnings[]`. A human run prints it later, folded /// with the others of its kind ([`flush_warnings`]): nothing prints while @@ -2291,6 +2683,9 @@ pub(crate) async fn generate_vex_from_manifest_path( } /// Outcome of [`generate_vex_without_manifest`]. +// `large_enum_variant`: `Written` carries the document. One value is made +// per run and matched at once, so boxing it would save nothing. +#[allow(clippy::large_enum_variant)] pub(crate) enum ManifestlessVex { /// Nothing references a patch anywhere (no manifest, no ledger record, /// no lockfile reference): the caller keeps its historical calm @@ -2339,13 +2734,20 @@ async fn generate_vex_with_cleanup( calm_when_nothing: bool, ) -> Result { let mut warnings = Vec::new(); - let result = generate_vex_from_manifest_path_inner( - common, - params, - manifest_path, - calm_when_nothing, - &mut warnings, - ) + // The generator's future holds every attestation source it reads, and + // `scan`, `apply` and `vendor` await it for `--vex`: awaited in line + // it lay in the poll frame of each of them, once per place that + // awaits it, in a run without `--vex` too. `boxed` leaves them one + // pointer. + let result = crate::ecosystem_dispatch::boxed(|| { + generate_vex_from_manifest_path_inner( + common, + params, + manifest_path, + calm_when_nothing, + &mut warnings, + ) + }) .await; match result { Ok(mut summary) => { @@ -2498,6 +2900,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_builds: params.hosted_gem_builds.clone(), }; if sources.is_empty() { // A discovery diagnostic (an unparseable lock, a rejected reference) @@ -2517,6 +2920,7 @@ async fn generate_vex_from_manifest_path_inner( failed: Vec::new(), hosted: Vec::new(), warnings: Vec::new(), + gem_builds: Default::default(), } } else { fail(common, params, "manifest_not_found", message).await @@ -2553,6 +2957,7 @@ async fn fail( failed: Vec::new(), hosted: Vec::new(), warnings: Vec::new(), + gem_builds: Default::default(), } } @@ -2744,14 +3149,19 @@ async fn synthesize_go_patches( /// Emit a `vex` error to the active output channel: an error envelope on /// stdout in `--json` mode, a stderr message otherwise. `failures` lists /// patches omitted by verification (populated for `no_applicable_patches`, -/// empty everywhere else), `gems` the hosted gems among them that the hint -/// sends to the scan; `warnings` are the run's advisories, already on -/// stderr in human mode, folded into the envelope's `warnings[]` here. +/// empty everywhere else), with the builds among them that stand for a gem +/// ([`VexGenError::gem_builds`]); `gems` are the hosted gems among them +/// that the hint sends to the scan; `warnings` are the run's advisories, +/// already on stderr in human mode, folded into the envelope's +/// `warnings[]` here. fn emit_envelope_error( args: &VexArgs, code: &str, message: &str, - failures: &[FailedPatch], + (failures, gem_builds): ( + &[FailedPatch], + &std::collections::BTreeMap, + ), gems: &StaleHostedGems, warnings: &[RunWarning], grype: Option<&vex_grype::GrypeConfigOutcome>, @@ -2763,10 +3173,7 @@ fn emit_envelope_error( } env.dry_run = args.common.dry_run; for f in failures { - env.record( - PatchEvent::new(PatchAction::Skipped, f.purl.clone()) - .with_reason(f.reason.clone(), omission_reason_message(&f.reason)), - ); + env.record(omission_event(f, gem_builds)); } env.mark_error(EnvelopeError::new(code, message.to_string())); env.warnings = warnings.to_vec(); @@ -2904,6 +3311,28 @@ fn format_omission_warning(purl: &str, reason: &str) -> String { ) } +/// How a line names the packages `purls` it leaves out +/// ([`crate::ui::package_names`]), a platform gem with its platform: the +/// builds of one gem share its name and version. +fn omitted_names(purls: &[&str]) -> Vec { + use socket_patch_core::crawlers::Ecosystem; + use socket_patch_core::utils::purl::{percent_decode_purl_component, purl_qualifier}; + crate::ui::package_names(purls) + .into_iter() + .zip(purls) + .map(|(name, purl)| { + let platform = purl_qualifier(purl, "platform") + .filter(|_| Ecosystem::from_purl(purl) == Some(Ecosystem::Gem)); + match platform { + Some(platform) => { + format!("{name} ({})", percent_decode_purl_component(platform)) + } + None => name, + } + }) + .collect() +} + /// The stderr lines for the patches left out of the document: one per /// reason, with the count and the first few packages (a project that has /// not installed its patched packages yet leaves every one of them out @@ -2933,7 +3362,7 @@ fn omission_lines(failed: &[FailedPatch], verbose: bool) -> Vec { "Warning: omitting {} packages from VEX: {} ({reason}): {}{}", purls.len(), omission_phrase(reason), - crate::ui::folded(&crate::ui::package_names(&purls), NAMES_SHOWN), + crate::ui::folded(&omitted_names(&purls), NAMES_SHOWN), if purls.len() > NAMES_SHOWN { " (--verbose lists them all)" } else { @@ -3083,39 +3512,106 @@ fn omission_reason_message(reason: &str) -> String { format!("patch omitted from VEX: {}", omission_phrase(reason)) } +/// Say in `details` which gem patch a build named in place of a gem goes +/// by (`gemFix`), and its platform, as the hosted and vendored runs' own +/// events do. +fn gem_build_details(build: &GemBuildInfo, details: &mut serde_json::Value) { + details["gemFix"] = serde_json::json!(build.gem_fix); + if let Some(platform) = &build.platform { + details["platform"] = serde_json::json!(platform); + } +} + +/// The `skipped` event of a patch the document leaves out: its routing +/// tag as `errorCode`, the reason in words, and, for a build among +/// `gem_builds`, the gem patch it goes by ([`gem_build_details`]). +fn omission_event( + f: &FailedPatch, + gem_builds: &std::collections::BTreeMap, +) -> PatchEvent { + let event = PatchEvent::new(PatchAction::Skipped, f.purl.clone()) + .with_reason(f.reason.clone(), omission_reason_message(&f.reason)); + match gem_builds.get(&f.purl) { + Some(build) => { + let mut details = serde_json::json!({}); + gem_build_details(build, &mut details); + event.with_details(details) + } + None => event, + } +} + fn emit_envelope_success( summary: &VexWriteSummary, dry_run: bool, grype: Option<&vex_grype::GrypeConfigOutcome>, ) { + use socket_patch_core::hosted::engine::{ + gem_upstream_build_kept_detail, GEM_UPSTREAM_BUILD_KEPT, + }; let mut env = Envelope::new(Command::Vex); env.dry_run = dry_run; + // Some package is in the document as affected because its patch is not + // in what gets built. + let mut unbuilt = false; for st in &summary.doc.statements { for prod in &st.products { for sub in &prod.subcomponents { + let mut details = serde_json::json!({ + "vulnerability": st.vulnerability.name, + "aliases": st.vulnerability.aliases, + "status": st.status, + }); + let build = summary.gem_builds.get(&sub.id); + if let Some(build) = build { + gem_build_details(build, &mut details); + } + // A gem build that is not shown patched: on upstream's + // gem (reported as the hosted run reports it), or one of + // which nothing shows what the lock installs. Nothing was + // skipped and nothing failed, so its event is counted + // nowhere. + let not_patched = build.and_then(|build| { + let platform = build.platform.as_deref().unwrap_or_default(); + match &build.unshown { + Some(why) => Some((GEM_BUILD_UNKNOWN, why.clone())), + None if build.kept_upstream => Some(( + GEM_UPSTREAM_BUILD_KEPT, + gem_upstream_build_kept_detail(platform, false), + )), + None => None, + } + }); // A package the document says is affected is not reported // as verified, nor counted as such: it is skipped, like a // patch the document leaves out, under its own code. - let event = match st.status { - Status::Affected => PatchEvent::new(PatchAction::Skipped, sub.id.clone()) - .with_reason(BAZEL_NOT_IN_BUILD, AFFECTED_REASON), + let event = match (st.status, not_patched) { + (Status::Affected, Some((code, reason))) => { + let event = PatchEvent::new(PatchAction::Skipped, sub.id.clone()) + .with_reason(code, reason); + env.events.push(event.with_details(details)); + continue; + } + (Status::Affected, None) if summary.gem_stand_ins.contains(&sub.id) => { + unbuilt = true; + PatchEvent::new(PatchAction::Skipped, sub.id.clone()) + .with_reason(GEM_STAND_IN_UNPATCHED, GEM_STAND_IN_REASON) + } + (Status::Affected, None) => { + unbuilt = true; + PatchEvent::new(PatchAction::Skipped, sub.id.clone()) + .with_reason(BAZEL_NOT_IN_BUILD, AFFECTED_REASON) + } _ => PatchEvent::new(PatchAction::Verified, sub.id.clone()), }; - env.record(event.with_details(serde_json::json!({ - "vulnerability": st.vulnerability.name, - "aliases": st.vulnerability.aliases, - "status": st.status, - }))); + env.record(event.with_details(details)); } } } for f in &summary.failed { - env.record( - PatchEvent::new(PatchAction::Skipped, f.purl.clone()) - .with_reason(f.reason.clone(), omission_reason_message(&f.reason)), - ); + env.record(omission_event(f, &summary.gem_builds)); } - if !summary.failed.is_empty() || summary.affected > 0 { + if !summary.failed.is_empty() || unbuilt { env.mark_partial_failure(); } env.warnings = summary.warnings.clone(); @@ -3350,6 +3846,28 @@ mod tests { content (not_applied): pkg:npm/a@1.0.0, pkg:pypi/b@2.0.0" ] ); + // The builds of one gem share its name: each is named with its + // platform. + assert_eq!( + omission_lines( + &[ + failed( + "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin", + "not_applied" + ), + failed( + "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", + "not_applied" + ), + ], + false + ), + [ + "Warning: omitting 2 packages from VEX: the patched files still hold the original \ + content (not_applied): nokogiri@1.18.10 (arm64-darwin), nokogiri@1.18.10 \ + (x86_64-linux-gnu)" + ] + ); } /// Advisories of one kind print once in full, then as one line naming @@ -3942,6 +4460,7 @@ mod npm_prior_tests { flag_prefix: "--vex-", npm_prior: prior, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), api_client: RunApiClient::new(), warnings_printed: Default::default(), }; @@ -4071,6 +4590,7 @@ mod mirror_refusal_tests { redirected: vec![purls[0].to_string(), purls[2].to_string()], lockfile_basis: HashSet::from([purls[0].to_string(), purls[2].to_string()]), hosted, + hosted_gems: Default::default(), gated: Vec::new(), notes: Vec::new(), }; @@ -4193,6 +4713,7 @@ mod mirror_refusal_tests { redirected: vec![gem.to_string(), npm.to_string()], lockfile_basis: HashSet::from([gem.to_string(), npm.to_string()]), hosted, + hosted_gems: Default::default(), gated: Vec::new(), notes: Vec::new(), }; @@ -4372,6 +4893,7 @@ mod unjudged_tests { .into_iter() .collect::>(), hosted, + hosted_gems: Default::default(), gated: Vec::new(), notes: Vec::new(), }; @@ -4499,6 +5021,7 @@ mod bazel_tests { redirected: vec![purls[2].to_string()], lockfile_basis: HashSet::new(), hosted: BTreeMap::from([(purls[2].to_string(), wiring)]), + hosted_gems: Default::default(), gated: Vec::new(), notes: Vec::new(), }; @@ -4560,3 +5083,32 @@ mod bazel_tests { } } } + +#[cfg(test)] +mod embedded_future_tests { + use super::*; + + /// What `--vex` puts on the stack of the commands that can write a + /// document (`scan`, `apply`, `vendor`) stays a pointer to the + /// generator beside what they hand it. A debug build builds every + /// future on the poll frame of the function that awaits it, also in a + /// run without `--vex`, and a scan that applies a patch in place takes + /// most of the 2 MiB a test thread has: what the generator reads and + /// asks about is behind that pointer, whatever it grows to. + #[test] + fn the_generator_costs_the_command_that_embeds_it_a_pointer() { + use std::mem::{size_of, size_of_val}; + let common = GlobalArgs::default(); + let params = VexEmbedArgs::default().to_build_params(None); + let manifest_path = Path::new("manifest.json"); + // The three references, the advisories, the pointer, and the + // result with the removal of a stale document. + let bound = 128 * size_of::(); + let with_manifest = generate_vex_from_manifest_path(&common, ¶ms, manifest_path); + let size = size_of_val(&with_manifest); + assert!(size <= bound, "with a manifest: {size} bytes"); + let without = generate_vex_without_manifest(&common, ¶ms, manifest_path); + let size = size_of_val(&without); + assert!(size <= bound, "without a manifest: {size} bytes"); + } +} diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index f650a8199f..0cecff706e 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -72,24 +72,41 @@ //! DISCOVERED Socket-host reference with a lockfile pin, attests from the //! pinned wiring (the in-run `scan --mode hosted --vex` evidence); //! `Installed` is the agent-mode path. +//! +//! A gem that a Bundler lock takes from its patch registry as platform +//! builds is one hosted pin, but not one answer: the registry serves a +//! patched build for some platforms and upstream's own gem for the others. +//! The plan works out what the lock installs for each build it names +//! ([`Plan::hosted_gems`]): from the hosted run it is part of, or from the +//! lock and at most two requests per gem (the gem patch's reference, and +//! the index of the lock's registry where the lock has no `CHECKSUMS`). +//! The gem is judged as its one pin, and the document then names each +//! build ([`GemBuildView`]): a patched one under its own patch, and one on +//! upstream's gem, or of which neither is shown, as affected. The latter +//! is no failure of the run: the statement says why and what settles it, +//! and one warning names the gem (`vex_gem_build_unknown`). use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use futures_util::StreamExt; use socket_patch_core::api::client::{ - build_proxy_fallback_client, get_api_client_with_overrides, hold_back_debug, - is_fallback_candidate, ApiClient, + build_proxy_fallback_client, hold_back_debug, is_fallback_candidate, ApiClient, }; -use socket_patch_core::manifest::schema::{PatchManifest, PatchRecord}; -use socket_patch_core::patch::redirect::RedirectState; +use socket_patch_core::crawlers::Ecosystem; +use socket_patch_core::hosted::engine::PinReport; +use socket_patch_core::manifest::schema::{PatchFileInfo, PatchManifest, PatchRecord}; +use socket_patch_core::patch::redirect::{GemPlatformChecksum, RedirectState}; use socket_patch_core::utils::concurrent::{api_concurrency, ordered_concurrent}; -use socket_patch_core::utils::purl::strip_purl_qualifiers; +use socket_patch_core::utils::purl::{purl_parts, strip_purl_qualifiers}; use socket_patch_core::utils::purl_key::{canonical_base_purl, PurlKey}; use socket_patch_core::vendor::state::{VendorArtifact, VendorEntry, VendorState}; use socket_patch_core::vex::discover::{ vendor_ref, Discovery, LedgerLiveness, PatchedRef, RecordLiveness, WiringMode, }; +use socket_patch_core::vex::gem_builds::{ + gem_build_states, gem_index_url, locked_gem_pins, GemBuildState, GemBuildUnknown, LockedGemPin, +}; use socket_patch_core::vex::{FailedPatch, Unattested, UnattestedKind}; use crate::args::GlobalArgs; @@ -144,6 +161,13 @@ 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: what that run reports for each + /// locked build of the gems it pinned as platform builds + /// (`engine::pin_reports`, the reports that name a gem patch). The run + /// read the patch service's list of those builds to move the lock, so + /// [`plan`] takes the builds from here and asks nothing. Empty + /// everywhere else. + pub hosted_gem_builds: Vec, } impl Sources { @@ -183,6 +207,12 @@ pub(crate) struct Plan { /// installed copy the build CONSUMES through that wiring /// ([`crate::commands::vex_consumed`]). pub hosted: BTreeMap, + /// The gems of `hosted` that a Bundler lock takes from their patch + /// registry as platform builds, by view purl: what the lock installs + /// for each build it names ([`HostedGem`]). Such a gem is judged as the + /// one pin it is, and the document then names its builds + /// ([`GemBuildView`]). + pub hosted_gems: BTreeMap, /// Candidates omitted by a gate, with their routing tag. pub gated: Vec, /// Run advisories (wiring conflicts, superseded or dead records, record @@ -310,6 +340,14 @@ pub(crate) const GO_WORKSPACE_OVERRIDE: &str = "go_workspace_override"; /// package to the artifact; `vex::Unattested`, /// `UnattestedKind::LockNotRead`). const NOTE_LOCK_NOT_READ: &str = "vex_lock_not_read"; +/// Note, and code of the uncounted event: a platform build of a gem the +/// lockfile takes from a patch registry, of which nothing shows whether the +/// lock installs a patched build or upstream's own gem +/// ([`GemBuildState::Unknown`]). The document says `affected` of the build, +/// with why and what settles it ([`GemBuildUnshown`]): it is never attested +/// on the strength of the gem's one pin, and never left out. Not an +/// omission: the run's status and exit code are what they are without it. +pub(crate) const GEM_BUILD_UNKNOWN: &str = "vex_gem_build_unknown"; /// The omission tag of an [`Unattested`](socket_patch_core::vex::Unattested) /// ref, and the remedy its note ends with. @@ -466,6 +504,292 @@ fn gate_unattested( }); } +/// The builds a document names in place of a gem that is one pin for +/// several platform gems. +/// +/// A gem vendored as platform gems is one vendored copy. What an install +/// loads from it is one platform gem's tree, and each tree was built by a +/// patch of its own, which the ledger entry records with the file hashes +/// of that patch's record ([`VendorEntry::gem_builds`]): each tree is +/// verified against those, never against the record of the gem's patch. +/// So the +/// document names each platform gem +/// (`pkg:gem/@?platform=`) under its own patch, +/// with the vulnerabilities of the gem patch's record: the fix is the same +/// in every one of them. Read from the plan alone, with no request: the +/// ledger is what says which patch built which tree. An entry that names +/// no patch for its trees is attested as the gem itself. A tree the +/// ledger records as upstream's own gem (a locked platform that had no +/// patched build when the gem was vendored) is stated `affected`, like a +/// hosted build on upstream's gem, with what changes that +/// ([`upstream_tree_action`]). +/// +/// A gem a lock takes from its patch registry as platform builds is one +/// hosted pin, judged as one. The registry serves a patched build for some +/// platforms and upstream's own gem for the others, so the pin does not +/// say that every locked build is patched ([`Plan::hosted_gems`]). The +/// document names each locked build: a patched one under its own patch, +/// like a vendored one, and every other one as `affected` +/// ([`Self::not_patched`]). That is a build on upstream's gem, which the +/// lock is known to install without the patch, and a build of which +/// neither is shown ([`GEM_BUILD_UNKNOWN`]): nothing shows that the lock +/// installs a patched build for it, so the document does not say it does, +/// and says why and what settles it. The record of every build stays in +/// the view, so that no statement names a form of the gem that also +/// stands for a build the document does not call patched. +pub(crate) struct GemBuildView { + /// The record view with each such gem's key replaced by its builds' + /// purls. + view: PatchManifest, + /// View purl of the gem → the purls of its builds that are patched. + platform_gems: BTreeMap>, + /// The hosted builds that are not shown patched, each with what to do + /// about it. + not_patched: Vec<(String, String)>, + /// Every build the view names in place of a gem, by purl. + builds: BTreeMap, +} + +/// One build a [`GemBuildView`] names, as the run's events describe it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct GemBuildInfo { + /// The gem patch's uuid: the one pin, or the one vendored copy, all + /// the builds of the gem go by. + pub gem_fix: String, + /// `None` for the ruby-platform gem. + pub platform: Option, + /// A hosted build the patch registry serves as upstream's own gem. + pub kept_upstream: bool, + /// A hosted build of which nothing shows what the lock installs: why, + /// as its event says it ([`GemBuildUnshown::reason`]). + pub unshown: Option, +} + +/// The action statement of a tree of upstream's own gem in a copy +/// vendored as platform gems +/// ([`socket_patch_core::vendor::GemBuildEntry::is_upstream`]): why an +/// install on `platform` is without the gem's patch `gem_fix`, and what +/// changes that. The ledger says what was vendored, not what the patch +/// registry lists today. +fn upstream_tree_action(platform: &str, gem_fix: &str) -> String { + format!( + "The vendored copy holds upstream's own gem for {platform}: the patch registry had no \ + patched build of this gem for it when the copy was vendored, so an install on that \ + platform is without Socket patch {gem_fix}. Run `socket-patch scan --mode vendored` \ + again later: the copy takes the patched build once it is published." + ) +} + +/// The action statement of a hosted gem build on upstream's gem +/// ([`GemBuildState::Upstream`]): why the lock installs it without the +/// gem's patch `gem_fix`, and what changes that. +fn upstream_build_action(platform: &str, gem_fix: &str) -> String { + format!( + "The patch registry has no patched build of this gem for {platform} yet and serves \ + upstream's own gem for it, so an install on that platform is without Socket patch \ + {gem_fix}. Run `socket-patch scan --mode hosted` again later: the lockfile takes the \ + patched build once it is published." + ) +} + +impl GemBuildView { + /// `None` when `plan` attests no gem vendored as platform gems and no + /// gem a lock takes from a patch registry as platform builds. + #[cfg(test)] + pub(crate) fn of(plan: &Plan) -> Option { + Self::of_judged(plan, &BTreeMap::new()) + } + + /// [`Self::of`] once the installed copies were judged: `unknown` names + /// the patched builds (by purl) of which nothing showed that the + /// installed copy is the patched one, each with why. Such a build is + /// stated `affected`, like one of which nothing shows what the lock + /// installs. + pub(crate) fn of_judged( + plan: &Plan, + unknown: &BTreeMap, + ) -> Option { + let vendored: Vec<(&String, &VendorEntry, &PatchRecord)> = plan + .vendor_entries + .iter() + .filter(|(_, entry)| { + entry.ecosystem == "gem" + && !entry.gem_builds.is_empty() + && entry.gem_builds_well_formed() + }) + .filter_map(|(key, entry)| Some((key, entry, plan.view.patches.get(key)?))) + // The entry's trees are the builds of the entry's own patch. + .filter(|(_, entry, record)| record.uuid == entry.uuid) + .collect(); + let hosted: Vec<(&String, &HostedGem, &PatchRecord)> = plan + .hosted_gems + .iter() + .filter_map(|(key, gem)| Some((key, gem, plan.view.patches.get(key)?))) + // The builds are those of the patch the pin attests. + .filter(|(_, gem, record)| record.uuid == gem.gem_fix) + .collect(); + if vendored.is_empty() && hosted.is_empty() { + return None; + } + let mut view = plan.view.clone(); + let mut platform_gems = BTreeMap::new(); + let mut not_patched = Vec::new(); + let mut builds = BTreeMap::new(); + for (key, entry, record) in vendored { + view.patches.remove(key); + let mut patched = Vec::new(); + for built in &entry.gem_builds { + let purl = built.purl(&entry.base_purl); + let upstream = built.is_upstream(); + // A purl the view already attests keeps its own record, + // and the outcome of its own check: no tree of this copy + // says anything of it, as for a hosted build. + if view.patches.contains_key(&purl) { + continue; + } + view.patches.insert( + purl.clone(), + match upstream { + // A tree of upstream's own gem, named for the + // document alone: what it is affected by, as the + // record of the gem's patch states it. No copy is + // checked against this record. + true => record.clone(), + false => PatchRecord { + uuid: built.uuid.clone(), + files: entry.gem_tree_files(&built.platform, &record.files), + ..record.clone() + }, + }, + ); + builds.insert( + purl.clone(), + GemBuildInfo { + gem_fix: entry.uuid.clone(), + platform: Some(built.platform.clone()), + kept_upstream: upstream, + unshown: None, + }, + ); + match upstream { + true => { + not_patched.push((purl, upstream_tree_action(&built.platform, &entry.uuid))) + } + false => patched.push(purl), + } + } + platform_gems.insert(key.clone(), patched); + } + for (key, gem, record) in hosted { + view.patches.remove(key); + let mut patched = Vec::new(); + for build in &gem.builds { + // A purl the view already attests keeps its own record, + // and the outcome of its own check. + if view.patches.contains_key(&build.purl) { + continue; + } + let uuid = match &build.state { + GemBuildState::Patched { uuid } => uuid, + GemBuildState::Upstream | GemBuildState::Unknown(_) => &record.uuid, + }; + view.patches.insert( + build.purl.clone(), + PatchRecord { + uuid: uuid.clone(), + // For the document alone: what it names and fixes. + // No copy is checked against this record. + files: record.files.clone(), + ..record.clone() + }, + ); + let upstream = build.state == GemBuildState::Upstream; + let unread = unknown.get(&build.purl); + let unshown = unread + .or(build.unshown.as_ref()) + .zip(build.platform.as_deref()); + let judged = match unread { + Some(_) => GemBuildState::Unknown(GemBuildUnknown::Unpinned), + None => build.state.clone(), + }; + match (&judged, build.platform.as_deref()) { + (GemBuildState::Patched { .. }, _) => patched.push(build.purl.clone()), + (GemBuildState::Upstream, Some(platform)) => not_patched.push(( + build.purl.clone(), + upstream_build_action(platform, &gem.gem_fix), + )), + (GemBuildState::Unknown(_), Some(_)) => { + let action = unshown.map(|(why, platform)| why.action(platform)); + not_patched.extend(action.map(|action| (build.purl.clone(), action))); + } + // The ruby-platform gem of a patch's registry is the + // gem's patch, never upstream's nor unknown. + (GemBuildState::Upstream | GemBuildState::Unknown(_), None) => {} + } + builds.insert( + build.purl.clone(), + GemBuildInfo { + gem_fix: gem.gem_fix.clone(), + platform: build.platform.clone(), + kept_upstream: upstream, + unshown: unshown.map(|(why, platform)| why.reason(platform)), + }, + ); + } + platform_gems.insert(key.clone(), patched); + } + Some(Self { + view, + platform_gems, + not_patched, + builds, + }) + } + + /// The record view to build the document from. + pub(crate) fn view(&self) -> &PatchManifest { + &self.view + } + + /// The hosted builds that are not shown patched, each with its action + /// statement: what the document says `affected` of. A build the lock + /// installs as upstream's own gem, and one of which nothing shows what + /// the lock installs. + pub(crate) fn not_patched(&self) -> &[(String, String)] { + &self.not_patched + } + + /// Every build the view names in place of a gem, by purl. + pub(crate) fn builds(&self) -> &BTreeMap { + &self.builds + } + + /// Replace each gem of `purls` by its patched builds, in place. + pub(crate) fn expand(&self, purls: &mut Vec) { + *purls = std::mem::take(purls) + .into_iter() + .flat_map(|purl| match self.platform_gems.get(&purl) { + Some(platform_gems) => platform_gems.clone(), + None => vec![purl], + }) + .collect(); + } + + /// [`Self::expand`] for purls that each carry a note. + pub(crate) fn expand_noted(&self, noted: &mut Vec<(String, String)>) { + *noted = std::mem::take(noted) + .into_iter() + .flat_map(|(purl, note)| match self.platform_gems.get(&purl) { + Some(platform_gems) => platform_gems + .iter() + .map(|purl| (purl.clone(), note.clone())) + .collect(), + None => vec![(purl, note)], + }) + .collect(); + } +} + /// One hosted-basis view purl's wiring (see [`Plan::hosted`]). #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct HostedWiring { @@ -477,6 +801,223 @@ pub(crate) struct HostedWiring { pub refs: Vec, } +/// A gem a Bundler lock takes from its patch registry as platform builds +/// (see [`Plan::hosted_gems`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct HostedGem { + /// The gem patch's uuid: the one pin all the builds go by. + pub gem_fix: String, + /// The gem's name and version, as a person reads them. + pub name: String, + pub version: String, + /// The builds the lock names, the ruby-platform gem first. + pub builds: Vec, + /// The plan worked the builds out from the lock and the patch service. + /// Not so for the pins of the run that moved the lock, which says its + /// builds itself. + pub resolved: bool, +} + +/// One build a lock names of a [`HostedGem`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct HostedGemBuild { + /// `None` for the ruby-platform gem. + pub platform: Option, + /// What the document names the build: + /// `pkg:gem/@?platform=`, or the gem's own + /// view purl for the ruby-platform gem. + pub purl: String, + /// What the lock installs for it. + pub state: GemBuildState, + /// For a build in [`GemBuildState::Unknown`]: why nothing shows what + /// the lock installs for it. + pub unshown: Option, +} + +/// Why nothing shows whether a lock installs a patched build or upstream's +/// own gem for a platform build of a hosted gem +/// ([`GemBuildState::Unknown`]), and what settles it. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum GemBuildUnshown { + /// `--offline` forbids asking the patch service for the gem's builds. + Offline, + /// The reference request failed; its error, safe to print. + Request(String), + /// The patch service gave no list of the patch's builds; why. + NoList(String), + /// The lock has no `CHECKSUMS` entry for the build, and the index of + /// its registry could not be read; the error, safe to print. + IndexUnread(String), + /// Neither the lock's `CHECKSUMS` nor the index of its registry names + /// an archive for the build. + Unpinned, + /// The list does not name the build's platform. + Unlisted, + /// The lock installs another archive than the list names: the list is + /// of a later state of the registry than the one the lock names. + Differs, + /// The lock installs the patched build, and nothing shows that the + /// installed copy is it: the record of the build's own patch could + /// not be read; why, safe to print. + RecordUnread(String), +} + +impl From for GemBuildUnshown { + fn from(why: GemBuildUnknown) -> Self { + match why { + GemBuildUnknown::Unpinned => GemBuildUnshown::Unpinned, + GemBuildUnknown::Unlisted => GemBuildUnshown::Unlisted, + GemBuildUnknown::Differs => GemBuildUnshown::Differs, + } + } +} + +impl GemBuildUnshown { + /// The reason in words, said of `them` (`it` for one build, `them` + /// for several). `detail` adds the error of a read that failed: the + /// run's warning carries it, the document and the events do not. + fn why(&self, them: &str, detail: bool) -> String { + let failed = |what: String, error: &str| match detail { + true => format!("{what}: {error}"), + false => what, + }; + match self { + GemBuildUnshown::Offline => "--offline forbids asking the patch API".to_string(), + GemBuildUnshown::Request(error) => { + failed("the patch API request failed".to_string(), error) + } + GemBuildUnshown::NoList(why) => why.clone(), + GemBuildUnshown::IndexUnread(error) => failed( + format!( + "the lockfile has no CHECKSUMS entry for {them}, and its registry's index \ + could not be read" + ), + error, + ), + GemBuildUnshown::Unpinned => format!( + "neither the lockfile's CHECKSUMS nor its registry's index names an archive for \ + {them}" + ), + GemBuildUnshown::Unlisted => { + format!("the patch registry does not list {them} now") + } + GemBuildUnshown::Differs => format!( + "the lockfile installs another archive for {them} than the patch registry lists \ + now" + ), + GemBuildUnshown::RecordUnread(why) => failed( + format!( + "the record of the patch of {them} could not be read, so nothing shows \ + that the installed copy is the patched build" + ), + why, + ), + } + } + + /// What to run to settle it: the request again where one failed, + /// without `--offline` where that forbade it, and the scan that brings + /// the lock up to date where the lock and the patch registry disagree. + fn remedy(&self) -> &'static str { + match self { + GemBuildUnshown::Offline => GEM_BUILD_ONLINE, + GemBuildUnshown::Request(_) + | GemBuildUnshown::IndexUnread(_) + | GemBuildUnshown::RecordUnread(_) => GEM_BUILD_RETRY, + GemBuildUnshown::Unlisted => GEM_BUILD_UNLISTED, + GemBuildUnshown::NoList(_) | GemBuildUnshown::Unpinned | GemBuildUnshown::Differs => { + GEM_BUILD_RESCAN + } + } + } + + /// The action statement of the build for `platform`: what could not be + /// shown, why, and what settles it. It names no patch: none is shown + /// to be in what the lock installs. + fn action(&self, platform: &str) -> String { + if let GemBuildUnshown::RecordUnread(_) = self { + return format!( + "It could not be shown that the installed copy of this gem for {platform} is \ + the patched build the lockfile installs ({}), so it is stated as affected. {}", + self.why("it", false), + self.remedy() + ); + } + format!( + "It could not be shown that the lockfile installs a patched build of this gem for \ + {platform} ({}), so it is stated as affected. {}", + self.why("it", false), + self.remedy() + ) + } + + /// What the uncounted [`GEM_BUILD_UNKNOWN`] event of the build for + /// `platform` says. + fn reason(&self, platform: &str) -> String { + format!( + "not shown patched for {platform}: {}", + self.why("it", false) + ) + } +} + +impl HostedGem { + /// The builds of the gem at the view purl `key`, each named and in + /// the state `state` gives for its platform. + fn of( + key: &str, + gem_fix: &str, + builds: impl IntoIterator, GemBuildState)>, + resolved: bool, + ) -> Option { + let (_, name, version) = purl_parts(key)?; + let base = strip_purl_qualifiers(key); + let builds = builds + .into_iter() + .map(|(platform, state)| HostedGemBuild { + purl: match &platform { + Some(platform) => format!("{base}?platform={platform}"), + None => key.to_string(), + }, + unshown: match (&state, &platform) { + (GemBuildState::Unknown(why), Some(_)) => Some(GemBuildUnshown::from(*why)), + _ => None, + }, + platform, + state, + }) + .collect(); + Some(HostedGem { + gem_fix: gem_fix.to_string(), + name, + version, + builds, + resolved, + }) + } + + /// Whether the installed copy at `path` is evidence about the gem at + /// the view purl `key`. A copy of a platform build the lock does not + /// install as a patched one is not: the document never calls that + /// build patched, and a machine of that platform holds what its lock + /// entry names. Judged as the gem's copy, upstream's own gem there + /// would withhold the builds the lock does install patched. + pub(crate) fn judges(&self, key: &str, path: &std::path::Path) -> bool { + use socket_patch_core::formats::gem::GemBuild; + let leaf = path.file_name().and_then(|leaf| leaf.to_str()); + let Some(platform) = leaf + .and_then(|leaf| GemBuild::of_leaf(key, leaf)) + .and_then(|build| build.platform) + else { + return true; + }; + !self.builds.iter().any(|build| { + build.platform.as_deref() == Some(platform.as_str()) + && !matches!(build.state, GemBuildState::Patched { .. }) + }) + } +} + /// How one view purl is verified. enum Basis { /// The agent-mode path: installed tree / go-patches copy. @@ -557,6 +1098,7 @@ pub(crate) async fn plan( mut redirect, discovery, hosted_uuids, + hosted_gem_builds, } = sources; let mut notes = Vec::new(); // The in-run hosted pins' records, filed under the API's purl like a @@ -880,6 +1422,7 @@ pub(crate) async fn plan( redirected: Vec::new(), lockfile_basis: HashSet::new(), hosted: BTreeMap::new(), + hosted_gems: BTreeMap::new(), gated, notes, }; @@ -944,6 +1487,13 @@ pub(crate) async fn plan( plan.view.patches.insert(cand.key, record); } plan.redirected.sort(); + // The future holds the requests about the builds of the hosted gems: + // awaited in line it is most of this plan's own, in a run with no + // hosted gem too. `boxed` leaves the plan one pointer. + crate::ecosystem_dispatch::boxed(|| { + resolve_hosted_gems(common, root, &mut plan, &hosted_gem_builds, api_client) + }) + .await; // One skip per (purl, reason): a collision gates its key once per // colliding candidate. let mut seen: HashSet<(String, String)> = HashSet::new(); @@ -1273,6 +1823,37 @@ fn local_record_by_uuid( .map(|(k, r)| ((*k).clone(), (*r).clone())) } +/// The run's client: the host's, or built here once (standalone `vex`). +/// Once the authenticated API has refused the credential itself (a 401 +/// to a request of that client, here or earlier in the run), every read +/// is handed the public proxy's client: the read that met the refusal +/// fell back and said so, and none after it presents the credential +/// again. A 403 is about one patch and changes nothing here. +async fn run_client( + common: &GlobalArgs, + api_client: &RunApiClient, + notes: &mut Vec, +) -> ApiClient { + let built_here = !api_client.initialized(); + let client = common.api_client(api_client).await.clone(); + // A client built here whose org could not be resolved put the run on + // the proxy. Its construction already warned on stderr, so only the + // `--json` envelope needs the note (a host that seeded its client + // reports this itself). + if built_here && common.json { + if let Some(reason) = client.org_unresolved() { + notes.push(PlanNote { + code: NOTE_API_AUTH_FALLBACK, + detail: reason.to_string(), + }); + } + } + if client.credential_refused() { + return build_proxy_fallback_client(&common.api_client_overrides()); + } + client +} + /// Fetch the patch view for each of `uuids` (online only; empty under /// `--offline`) with bounded concurrency and `get`'s one-shot 401/403 → /// public-proxy fallback. Returns `uuid → (api purl, record)` for every view @@ -1302,24 +1883,7 @@ async fn fetch_records( return out; } let overrides = common.api_client_overrides(); - // The run's client: the host's, or built here once (standalone `vex`). - let built_here = !api_client.initialized(); - let mut client = api_client - .get_or_init(|| async { get_api_client_with_overrides(overrides.clone()).await.0 }) - .await - .clone(); - // A client built here whose org could not be resolved put the run on - // the proxy. Its construction already warned on stderr, so only the - // `--json` envelope needs the note (a host that seeded its client - // reports this itself). - if built_here && common.json { - if let Some(reason) = client.org_unresolved() { - notes.push(PlanNote { - code: NOTE_API_AUTH_FALLBACK, - detail: reason.to_string(), - }); - } - } + let mut client = run_client(common, api_client, notes).await; let mut use_public_proxy = client.uses_public_proxy(); let mut pending: Vec = uuids.to_vec(); // Each view is a heavy response: say what the run is waiting on (a live @@ -1407,79 +1971,692 @@ async fn fetch_records( out } -#[cfg(test)] -mod tests { - use super::*; - use socket_patch_core::manifest::schema::{PatchFileInfo, VulnerabilityInfo}; - use socket_patch_core::vendor::lock_inventory::LockIntegrity; - use std::path::Path; +/// A hosted gem whose builds the plan works out. +struct PendingGem { + /// Its view purl. + key: String, + /// The gem patch's uuid. + uuid: String, + name: String, + version: String, + /// The registry the lock takes the gem from. + remote: String, + /// The builds the lock names. + pins: Vec, +} - const U1: &str = "7c8d9e0f-1a2b-4a1b-8c2d-3e4f5a6b7c8d"; - const U2: &str = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"; +impl PendingGem { + /// The lock's `CHECKSUMS` does not pin every platform build: what the + /// lock installs for those is what its registry serves. + fn needs_index(&self) -> bool { + self.pins + .iter() + .any(|pin| pin.platform.is_some() && pin.sha256.is_none()) + } +} - fn record(uuid: &str) -> PatchRecord { - PatchRecord { - uuid: uuid.to_string(), - exported_at: String::new(), - files: [( - "package/index.js".to_string(), - PatchFileInfo { - before_hash: String::new(), - after_hash: "a".repeat(64), - }, - )] - .into_iter() - .collect(), - vulnerabilities: [( - "GHSA-x".to_string(), - VulnerabilityInfo { - cves: vec![], - summary: String::new(), - severity: String::new(), - description: String::new(), - }, - )] - .into_iter() - .collect(), - description: String::new(), - license: String::new(), - tier: String::new(), +/// What to run for a build whose state a later run can read. +const GEM_BUILD_RETRY: &str = "Run `socket-patch vex` again to attest each build."; +/// What to run for a build `--offline` kept the run from asking about. +const GEM_BUILD_ONLINE: &str = "Run `socket-patch vex` without --offline to attest each build."; +/// What to run for a build the lock and the patch registry disagree about. +const GEM_BUILD_RESCAN: &str = "Run `socket-patch scan --mode hosted` to bring the lockfile up \ + to date, then `socket-patch vex` again."; + +/// What settles a build of a platform the patch registry does not list. A +/// scan changes nothing for it: the registry lists every platform gem +/// upstream publishes, so the platform is one upstream does not publish. +const GEM_BUILD_UNLISTED: &str = "A scan does not change this: the patch registry lists no gem \ + for that platform. It is settled once the lockfile no longer names the platform \ + (`bundle lock --remove-platform`), or the registry lists a gem for it."; + +/// The [`GEM_BUILD_UNKNOWN`] note of the gem at `key`: nothing shows what +/// the lock installs for the builds of `platforms`, for the reason `why`, +/// so the document says `affected` of them. +fn gem_build_note(key: &str, gem_fix: &str, platforms: &[&str], why: &GemBuildUnshown) -> PlanNote { + let one = platforms.len() == 1; + let them = if one { "it" } else { "them" }; + PlanNote { + code: GEM_BUILD_UNKNOWN, + detail: format!( + "{key}: the lockfile takes its {} for {} from the registry of Socket patch {gem_fix}, \ + which serves a patched build for some platforms and upstream's own gem for the \ + others. Which it is for {} could not be told ({}), so the VEX document states \ + {them} as affected. {}", + if one { "build" } else { "builds" }, + platforms.join(", "), + if one { "this one" } else { "these" }, + why.why(them, true), + why.remedy(), + ), + } +} + +/// Work out [`Plan::hosted_gems`], and why nothing shows what the lock +/// installs for a build where nothing does. +/// +/// A gem `in_run` reports (a pin of the hosted run this plan is part of) +/// takes its builds from there. Any other hosted gem is read from the lock +/// that wires it. One the lock names as its ruby-platform gem alone stays +/// the one pin it is, and nothing is asked for it. For the others the +/// patch service is asked once for the references of all their patches +/// (each lists its patch's builds), and the registry a lock names once per +/// gem, only where that lock's `CHECKSUMS` does not pin every build +/// ([`gem_index`]). +/// +/// Under `--offline`, and where a request fails or the answers do not +/// settle a build, nothing is known of it: the build keeps the reason +/// ([`HostedGemBuild::unshown`]), which the document states it as +/// affected with, and a note names the gem and what to run, once per gem +/// and reason ([`GEM_BUILD_UNKNOWN`]). Nothing is gated: the run is no +/// less a success for it. The ruby-platform gem a lock names beside the +/// platform builds is the gem's patch by the lock's wiring, whatever the +/// requests say. +async fn resolve_hosted_gems( + common: &GlobalArgs, + root: &std::path::Path, + plan: &mut Plan, + in_run: &[PinReport], + api_client: &RunApiClient, +) { + let mut pending: Vec = Vec::new(); + for (key, wiring) in &plan.hosted { + if Ecosystem::from_purl(key) != Some(Ecosystem::Gem) { + continue; + } + let reported: Vec<(Option, GemBuildState)> = in_run + .iter() + .filter(|report| report.gem_fix.as_deref() == Some(wiring.uuid.as_str())) + .map(|report| { + let state = match &report.uuid { + Some(uuid) => GemBuildState::Patched { uuid: uuid.clone() }, + None => GemBuildState::Upstream, + }; + (report.platform.clone(), state) + }) + .collect(); + if !reported.is_empty() { + if let Some(gem) = HostedGem::of(key, &wiring.uuid, reported, false) { + plan.hosted_gems.insert(key.clone(), gem); + } + continue; + } + let Some((_, name, version)) = purl_parts(key) else { + continue; + }; + // The lock that wires the gem, and the registry it names there. + let wired = wiring + .refs + .iter() + .find_map(|r| Some((r.source_file.as_path(), r.url.clone()?))); + let Some((lock, remote)) = wired else { + continue; + }; + let Ok(text) = socket_patch_core::utils::fs::read_regular_to_string(&root.join(lock)).await + else { + continue; + }; + let pins = locked_gem_pins(&text, &name, &version); + if pins.iter().all(|pin| pin.platform.is_none()) { + continue; } + pending.push(PendingGem { + key: key.clone(), + uuid: wiring.uuid.clone(), + name, + version, + remote, + pins, + }); + } + if pending.is_empty() { + return; } - fn hosted_ref(purl: &str, uuid: &str, pinned: bool) -> PatchedRef { - PatchedRef::hosted( - purl.to_string(), - uuid.to_string(), - "package-lock.json", - None, - pinned.then(|| LockIntegrity::Sri("sha512-x".into())), - true, + // What each patch's reference lists, and what each lock's registry + // serves where the lock does not say. + let (lists, indexes) = if common.offline { + let unread = |_: &PendingGem| Err(GemBuildUnshown::Offline); + let lists: Vec<_> = pending.iter().map(unread).collect(); + (lists, pending.iter().map(|_| None).collect()) + } else { + crate::ui::busy( + common, + "Reading gem builds", + read_gem_builds(common, api_client, &pending, &mut plan.notes), ) - } + .await + }; - fn common(root: &Path) -> GlobalArgs { - GlobalArgs { - cwd: root.to_path_buf(), - offline: true, - ..GlobalArgs::default() + for ((gem, list), index) in pending.iter().zip(lists).zip(indexes) { + let (listed, unread) = match list { + Ok(listed) => (listed, None), + Err(unread) => (Vec::new(), Some(unread)), + }; + let served = index.as_ref().and_then(|read| read.as_deref().ok()); + let states = gem_build_states(&gem.version, &gem.pins, &gem.uuid, &listed, served); + let builds = gem.pins.iter().map(|pin| pin.platform.clone()).zip(states); + let Some(mut hosted) = HostedGem::of(&gem.key, &gem.uuid, builds, true) else { + continue; + }; + // What the reads say of a build beyond its state: with no list, + // why there is none; with no index, the error of that read. + for build in &mut hosted.builds { + let Some(why) = build.unshown.take() else { + continue; + }; + build.unshown = Some(match (&unread, why, &index) { + (Some(unread), _, _) => unread.clone(), + (None, GemBuildUnshown::Unpinned, Some(Err(error))) => { + GemBuildUnshown::IndexUnread(error.clone()) + } + (None, why, _) => why, + }); + } + let mut unshown: BTreeMap<&GemBuildUnshown, Vec<&str>> = BTreeMap::new(); + for build in &hosted.builds { + if let (Some(why), Some(platform)) = (&build.unshown, build.platform.as_deref()) { + unshown.entry(why).or_default().push(platform); + } } + for (why, platforms) in unshown { + plan.notes + .push(gem_build_note(&gem.key, &gem.uuid, &platforms, why)); + } + plan.hosted_gems.insert(gem.key.clone(), hosted); } +} + +/// The reads [`resolve_hosted_gems`] makes for `gems`: per gem, the +/// builds its patch's reference lists (ONE request for all of them, with +/// `get`'s one-shot 401/403 → public-proxy fallback), and the index of the +/// registry its lock names, read only for a gem that has a list and whose +/// lock does not pin every build ([`PendingGem::needs_index`]). No patch +/// record is read here: the record of a platform build's own patch is +/// read only for a build that has an installed copy +/// ([`read_build_records`]). +async fn read_gem_builds( + common: &GlobalArgs, + api_client: &RunApiClient, + gems: &[PendingGem], + notes: &mut Vec, +) -> ( + Vec, GemBuildUnshown>>, + Vec>>, +) { + use socket_patch_core::utils::redact::redact_urls_in; + let mut uuids: Vec = gems.iter().map(|gem| gem.uuid.clone()).collect(); + uuids.sort(); + uuids.dedup(); + // Each request presents the registry snapshot the gem's lock is on. + let held: socket_patch_core::api::client::GemSnapshotKeys = gems + .iter() + .filter_map(|gem| { + let (_, key) = socket_patch_core::patch::redirect::split_gem_snapshot(&gem.remote); + Some((gem.uuid.clone(), key?.to_string())) + }) + .collect(); + let mut client = run_client(common, api_client, notes).await; + let mut references = hold_back_debug(client.fetch_registry_references(&uuids, &held)) + .await + .release(); + if let Err(error) = &references { + if !client.uses_public_proxy() && is_fallback_candidate(error) { + // Same stale-credential recovery (and warning text) as the + // record fetch. + notes.push(PlanNote { + code: NOTE_API_AUTH_FALLBACK, + detail: format!( + "authenticated API returned {error}; falling back to public patch API proxy \ + (free patches only)." + ), + }); + client = build_proxy_fallback_client(&common.api_client_overrides()); + references = hold_back_debug(client.fetch_registry_references(&uuids, &held)) + .await + .release(); + } + } + let lists: Vec, GemBuildUnshown>> = gems + .iter() + .map(|gem| match &references { + Err(error) => Err(GemBuildUnshown::Request( + redact_urls_in(&error.to_string()).into_owned(), + )), + Ok(references) => { + let reference = references.get(&gem.uuid); + let granted = reference + .filter(|reference| matches!(reference.status.as_str(), "granted" | "reused")); + granted + .and_then(|reference| reference.registry_override.as_ref()) + .and_then(|registry| registry.identifiers.gem_builds.clone()) + .ok_or_else(|| { + GemBuildUnshown::NoList( + match reference.map(|reference| reference.status.as_str()) { + Some("granted" | "reused") => { + "the patch API lists no builds for that patch" + } + Some("withdrawn") => "the patch API says that patch is withdrawn", + Some("forbidden") => { + "the patch API does not grant that patch to this run" + } + _ => "the patch API has no reference for that patch", + } + .to_string(), + ) + }) + } + }) + .collect(); + let client = &client; + let indexes = ordered_concurrent( + gems.iter().zip(&lists), + fetch_concurrency(client.uses_public_proxy()), + |(gem, list)| async move { + match list.is_ok() && gem.needs_index() { + true => Some(hold_back_debug(gem_index(client, &gem.remote, &gem.name)).await), + false => None, + } + }, + ) + .collect::>() + .await; + let indexes = indexes + .into_iter() + .map(|read| read.map(|held| held.release())) + .collect(); + (lists, indexes) +} + +/// The files each patch among `uuids` (the patches of platform builds) +/// changes, as that patch's own record lists them, in the order asked: +/// what the installed copies of a build are checked against. One request +/// per patch, asked without file contents, several at a time, with the +/// stale-credential fallback of the other reads: a patch the +/// authenticated API refuses (401/403) is asked of the public proxy, and +/// `notes` says so once. A 403 is about one patch, so the next record is +/// still asked of the API first; after a 401 the run's client is the +/// proxy's ([`run_client`]). `Err` says why a record could not be read, +/// safe to print: nothing then judges that build's copies. +pub(crate) async fn read_build_records( + common: &GlobalArgs, + api_client: &RunApiClient, + uuids: &[String], + notes: &mut Vec, +) -> Vec, GemBuildUnshown>> { + use socket_patch_core::utils::redact::redact_urls_in; + if common.offline { + return uuids + .iter() + .map(|_| Err(GemBuildUnshown::Offline)) + .collect(); + } + if uuids.is_empty() { + return Vec::new(); + } + let summaries = |client: ApiClient, uuids: Vec| async move { + let client = &client; + let window = fetch_concurrency(client.uses_public_proxy()); + ordered_concurrent(uuids.iter(), window, |uuid| async move { + hold_back_debug(client.fetch_patch_summary(uuid)).await + }) + .map(|read| read.release()) + .collect::>() + .await + }; + let client = run_client(common, api_client, notes).await; + let on_proxy = client.uses_public_proxy(); + let mut reads = summaries(client, uuids.to_vec()).await; + let refused = |read: &Result<_, socket_patch_core::api::client::ApiError>| matches!(read, Err(e) if is_fallback_candidate(e)); + let again: Vec = (0..reads.len()) + .filter(|at| !on_proxy && refused(&reads[*at])) + .collect(); + if let Some(Err(error)) = again.first().map(|at| &reads[*at]) { + notes.push(PlanNote { + code: NOTE_API_AUTH_FALLBACK, + detail: format!( + "authenticated API returned {error}; falling back to public patch API proxy \ + (free patches only)." + ), + }); + let proxy = build_proxy_fallback_client(&common.api_client_overrides()); + let asked = again.iter().map(|at| uuids[*at].clone()).collect(); + for (at, read) in again.iter().zip(summaries(proxy, asked).await) { + reads[*at] = read; + } + } + let unread = |why: String| GemBuildUnshown::RecordUnread(why); + uuids + .iter() + .zip(reads) + .map(|(uuid, read)| match read { + Ok(Some(view)) if view.uuid.eq_ignore_ascii_case(uuid) => Ok( + socket_patch_core::manifest::records::files_for_manifest(&view), + ), + Ok(_) => Err(unread( + "the patch API has no record of that patch".to_string(), + )), + Err(error) => Err(unread(redact_urls_in(&error.to_string()).into_owned())), + }) + .collect() +} + +/// The [`GEM_BUILD_UNKNOWN`] warning of a patched build of the gem at +/// `key` whose installed copy nothing could judge ([`read_build_records`]). +pub(crate) fn unjudged_build_note( + key: &str, + gem_fix: &str, + platform: &str, + why: &GemBuildUnshown, +) -> PlanNote { + gem_build_note(key, gem_fix, &[platform], why) +} + +/// The compact-index document of the registry a lock names for the gem +/// `name` ([`gem_index_url`]): the sha256 of each gem that registry +/// serves, for a lock whose `CHECKSUMS` does not say what it installs. +/// +/// `remote` is the `remote:` of a lock section that lockfile discovery +/// read as hosted wiring, so it is on a patch server this run was given. +/// The document can only keep a build from being attested: a build is a +/// patched one only on the sha256 the patch service lists beside its +/// patch. The error is safe to print (the URL carries a grant token). +async fn gem_index(client: &ApiClient, remote: &str, name: &str) -> Result { + let url = gem_index_url(remote, name) + .ok_or_else(|| "the lockfile names no registry URL to read it from".to_string())?; + // The read, its size bound and its decoding are the hosted scan's. + socket_patch_core::hosted::gem_index::fetch_gem_index(client, &url).await +} + +#[cfg(test)] +mod tests { + use super::*; + use socket_patch_core::manifest::schema::{PatchFileInfo, VulnerabilityInfo}; + use socket_patch_core::vendor::lock_inventory::LockIntegrity; + use std::path::Path; + + const U1: &str = "7c8d9e0f-1a2b-4a1b-8c2d-3e4f5a6b7c8d"; + const U2: &str = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"; + + fn record(uuid: &str) -> PatchRecord { + PatchRecord { + uuid: uuid.to_string(), + exported_at: String::new(), + files: [( + "package/index.js".to_string(), + PatchFileInfo { + before_hash: String::new(), + after_hash: "a".repeat(64), + }, + )] + .into_iter() + .collect(), + vulnerabilities: [( + "GHSA-x".to_string(), + VulnerabilityInfo { + cves: vec![], + summary: String::new(), + severity: String::new(), + description: String::new(), + }, + )] + .into_iter() + .collect(), + description: String::new(), + license: String::new(), + tier: String::new(), + } + } + + /// A plan attesting the vendored gem `key` at [`U1`], its ledger entry + /// shaped by `shape`. + fn vendored_gem_plan(key: &str, shape: impl FnOnce(&mut VendorEntry)) -> Plan { + let mut entry = VendorEntry::new( + "gem".to_string(), + "pkg:gem/nokogiri@1.18.10".to_string(), + U1.to_string(), + socket_patch_core::vendor::state::VendorArtifact { + yarn_berry10c0: None, + path: format!(".socket/vendor/gem/{U1}/nokogiri-1.18.10"), + sha256: String::new(), + size: None, + platform_locked: None, + file_inventory: None, + }, + Vec::new(), + ); + shape(&mut entry); + Plan { + view: PatchManifest { + patches: HashMap::from([ + (key.to_string(), record(U1)), + ("pkg:npm/left-pad@1.3.0".to_string(), record(U2)), + ]), + setup: None, + }, + vendor_entries: HashMap::from([(key.to_string(), entry)]), + vendor_pins: HashMap::new(), + redirected: Vec::new(), + lockfile_basis: HashSet::new(), + hosted: BTreeMap::new(), + hosted_gems: BTreeMap::new(), + gated: Vec::new(), + notes: Vec::new(), + } + } + + fn gem_build(platform: &str, uuid: &str) -> socket_patch_core::vendor::GemBuildEntry { + socket_patch_core::vendor::GemBuildEntry { + platform: platform.to_string(), + uuid: uuid.to_string(), + gem_integrity: String::new(), + gemspec_integrity: String::new(), + files: Default::default(), + } + } + + /// A gem vendored as platform gems is named per platform gem: each + /// under the patch the ledger records for its tree, with the gem + /// patch's vulnerabilities and files, and the gem's own key gone from + /// the view. Every list of attested purls follows; other packages are + /// as they were. + #[test] + fn a_vendored_gem_is_attested_per_platform_gem_under_its_own_patch() { + const DARWIN: &str = "11111111-1111-4111-8111-111111111111"; + const LINUX: &str = "22222222-2222-4222-8222-222222222222"; + let key = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let plan = vendored_gem_plan(key, |entry| { + entry.gem_builds = vec![ + gem_build("arm64-darwin", DARWIN), + gem_build("x86_64-linux-gnu", LINUX), + ]; + }); + let builds = GemBuildView::of(&plan).expect("a gem vendored as platform gems"); + let view = builds.view(); + let darwin = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + let linux = "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu"; + let mut keys: Vec<&str> = view.patches.keys().map(String::as_str).collect(); + keys.sort_unstable(); + assert_eq!(keys, [darwin, linux, "pkg:npm/left-pad@1.3.0"]); + for (purl, uuid) in [(darwin, DARWIN), (linux, LINUX)] { + let attested = &view.patches[purl]; + assert_eq!(attested.uuid, uuid); + assert_eq!(attested.vulnerabilities, record(U1).vulnerabilities); + assert_eq!(attested.files, record(U1).files); + } + assert_eq!(view.patches["pkg:npm/left-pad@1.3.0"], record(U2)); + + let mut applied = vec!["pkg:npm/left-pad@1.3.0".to_string(), key.to_string()]; + builds.expand(&mut applied); + assert_eq!(applied, ["pkg:npm/left-pad@1.3.0", darwin, linux]); + let mut noted = vec![(key.to_string(), "why".to_string())]; + builds.expand_noted(&mut noted); + assert_eq!( + noted, + [ + (darwin.to_string(), "why".to_string()), + (linux.to_string(), "why".to_string()) + ] + ); + } + + /// A tree of upstream's own gem in a vendored copy is never among the + /// gem's patched builds. The document names it, under the gem's patch + /// and with its vulnerabilities, as a build to state `affected`, with + /// what changes that; the patched tree is attested as before. + #[test] + fn a_vendored_tree_of_upstreams_gem_is_stated_affected() { + const DARWIN: &str = "11111111-1111-4111-8111-111111111111"; + let key = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let darwin = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + let linux = "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu"; + let plan = vendored_gem_plan(key, |entry| { + entry.gem_builds = vec![ + gem_build("arm64-darwin", DARWIN), + gem_build("x86_64-linux-gnu", ""), + ]; + }); + let builds = GemBuildView::of(&plan).expect("a gem vendored as platform gems"); + let view = builds.view(); + assert_eq!(view.patches[darwin].uuid, DARWIN); + assert_eq!( + view.patches[linux], + record(U1), + "named under the gem's patch" + ); + assert!(!view.patches.contains_key(key)); + + let mut vendored = vec![key.to_string()]; + builds.expand(&mut vendored); + assert_eq!(vendored, [darwin], "only the patched tree is attested"); + assert_eq!( + builds.not_patched(), + [( + linux.to_string(), + format!( + "The vendored copy holds upstream's own gem for x86_64-linux-gnu: the patch \ + registry had no patched build of this gem for it when the copy was \ + vendored, so an install on that platform is without Socket patch {U1}. Run \ + `socket-patch scan --mode vendored` again later: the copy takes the patched \ + build once it is published." + ) + )] + ); + let info = &builds.builds()[linux]; + assert!(info.kept_upstream && info.unshown.is_none()); + assert_eq!(info.gem_fix, U1); + assert!(!builds.builds()[darwin].kept_upstream); + + // A copy that holds upstream's gems alone attests no build. + let none = vendored_gem_plan(key, |entry| { + entry.gem_builds = vec![ + gem_build("arm64-darwin", ""), + gem_build("x86_64-linux-gnu", ""), + ]; + }); + let builds = GemBuildView::of(&none).expect("a gem vendored as platform gems"); + let mut vendored = vec![key.to_string()]; + builds.expand(&mut vendored); + assert!(vendored.is_empty()); + assert_eq!(builds.not_patched().len(), 2); + } + + /// A purl the view already attests keeps its own record and the + /// outcome of its own check: a tree of upstream's gem under that purl + /// says nothing of it, so the document never states the one product + /// both ways. As for a hosted build. + #[test] + fn a_vendored_tree_of_upstreams_gem_leaves_an_attested_purl_alone() { + const DARWIN: &str = "11111111-1111-4111-8111-111111111111"; + let key = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let linux = "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu"; + let mut plan = vendored_gem_plan(key, |entry| { + entry.gem_builds = vec![ + gem_build("arm64-darwin", DARWIN), + gem_build("x86_64-linux-gnu", ""), + ]; + }); + plan.view.patches.insert(linux.to_string(), record(U2)); + let builds = GemBuildView::of(&plan).expect("a gem vendored as platform gems"); + assert_eq!(builds.view().patches[linux], record(U2), "its own record"); + assert!( + builds.not_patched().is_empty(), + "{:?}", + builds.not_patched() + ); + assert!(!builds.builds().contains_key(linux)); + + // The same for a patched tree: the purl is not attributed to this + // gem's fix as well, nor attested as one of its builds. + let darwin = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + let mut plan = vendored_gem_plan(key, |entry| { + entry.gem_builds = vec![ + gem_build("arm64-darwin", DARWIN), + gem_build("x86_64-linux-gnu", U2), + ]; + }); + plan.view.patches.insert(darwin.to_string(), record(U2)); + let builds = GemBuildView::of(&plan).expect("a gem vendored as platform gems"); + assert_eq!(builds.view().patches[darwin], record(U2), "its own record"); + assert!(!builds.builds().contains_key(darwin)); + let mut vendored = vec![key.to_string()]; + builds.expand(&mut vendored); + assert_eq!(vendored, [linux], "only the tree the view did not attest"); + } + + /// The gem itself stays the attested package where the ledger does not + /// say which patch built which tree: an entry that names no tree, one + /// whose trees are another patch's than the view's record, and one + /// that names a platform no gem platform token spells. + #[test] + fn a_vendored_gem_with_no_patch_named_for_its_trees_is_attested_as_the_gem() { + let key = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let no_trees = vendored_gem_plan(key, |_| {}); + assert!(GemBuildView::of(&no_trees).is_none()); + let another_patch = vendored_gem_plan(key, |entry| { + entry.uuid = U2.to_string(); + entry.gem_builds = vec![gem_build("arm64-darwin", U2)]; + }); + assert!(GemBuildView::of(&another_patch).is_none()); + let unsafe_platform = vendored_gem_plan(key, |entry| { + entry.gem_builds = vec![gem_build("../x", U2)]; + }); + assert!(GemBuildView::of(&unsafe_platform).is_none()); + } + + fn hosted_ref(purl: &str, uuid: &str, pinned: bool) -> PatchedRef { + PatchedRef::hosted( + purl.to_string(), + uuid.to_string(), + "package-lock.json", + None, + pinned.then(|| LockIntegrity::Sri("sha512-x".into())), + true, + ) + } + + fn common(root: &Path) -> GlobalArgs { + GlobalArgs { + cwd: root.to_path_buf(), + offline: true, + ..GlobalArgs::default() + } + } + + /// `SOCKET_API_CONCURRENCY=1` means one view at a time here as well. + /// Serial: `SOCKET_*` is process-global. + #[test] + #[serial_test::serial] + fn socket_api_concurrency_paces_the_record_fetch() { + use socket_patch_core::utils::concurrent::API_CONCURRENCY_ENV; + let orig = std::env::var(API_CONCURRENCY_ENV).ok(); + std::env::remove_var(API_CONCURRENCY_ENV); + // The authenticated API serves the view without its file contents, + // so the patch API's own window applies there. + assert_eq!(fetch_concurrency(false), api_concurrency(false)); + assert!(fetch_concurrency(false) > FETCH_CONCURRENCY); + assert_eq!(fetch_concurrency(true), 4); - /// `SOCKET_API_CONCURRENCY=1` means one view at a time here as well. - /// Serial: `SOCKET_*` is process-global. - #[test] - #[serial_test::serial] - fn socket_api_concurrency_paces_the_record_fetch() { - use socket_patch_core::utils::concurrent::API_CONCURRENCY_ENV; - let orig = std::env::var(API_CONCURRENCY_ENV).ok(); - std::env::remove_var(API_CONCURRENCY_ENV); - // The authenticated API serves the view without its file contents, - // so the patch API's own window applies there. - assert_eq!(fetch_concurrency(false), api_concurrency(false)); - assert!(fetch_concurrency(false) > FETCH_CONCURRENCY); - assert_eq!(fetch_concurrency(true), 4); - std::env::set_var(API_CONCURRENCY_ENV, "1"); assert_eq!(fetch_concurrency(false), 1); assert_eq!(fetch_concurrency(true), 1); @@ -1571,6 +2748,143 @@ mod tests { assert!(out.contains_key(U1) && out.contains_key(U2), "{out:?}"); } + /// The view of a platform build's patch `uuid`, which changes one file. + fn build_view(uuid: &str, tier: &str) -> serde_json::Value { + serde_json::json!({ + "uuid": uuid, + "purl": "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", + "publishedAt": "2026-01-01T00:00:00Z", + "files": {"lib/nokogiri/version.rb": { + "beforeHash": "a".repeat(64), "afterHash": "b".repeat(64) + }}, + "vulnerabilities": {}, + "description": "", + "license": "MIT", + "tier": tier, + }) + } + + /// `GET` of `route` on `server` answers `status` (with `view` on a + /// 200), `times` times and no more. + async fn mount_view( + server: &wiremock::MockServer, + route: String, + status: u16, + view: Option, + times: u64, + ) { + use wiremock::matchers::{method, path as wm_path}; + use wiremock::{Mock, ResponseTemplate}; + let response = match view { + Some(view) => ResponseTemplate::new(status).set_body_json(view), + None => ResponseTemplate::new(status), + }; + Mock::given(method("GET")) + .and(wm_path(route)) + .respond_with(response) + .expect(times) + .mount(server) + .await; + } + + fn authenticated( + tmp: &Path, + api: &wiremock::MockServer, + proxy: &wiremock::MockServer, + ) -> GlobalArgs { + GlobalArgs { + cwd: tmp.to_path_buf(), + json: true, + api_url: Some(api.uri()), + api_token: Some("sktsec_placeholder_value_for_tests_api".into()), + org: Some("acme".into()), + proxy_url: Some(proxy.uri()), + ..GlobalArgs::default() + } + } + + fn fallback_notes(notes: &[PlanNote]) -> usize { + let fallbacks = notes.iter().filter(|n| n.code == NOTE_API_AUTH_FALLBACK); + fallbacks.count() + } + + /// Each build's record is asked of the authenticated API first, and + /// only one it refuses goes to the public proxy: a paid patch's record, + /// which the proxy does not serve, is read where the API serves it, + /// beside a refused one. The fallback is noted once. + #[tokio::test] + #[serial_test::serial] + async fn a_build_record_goes_to_the_proxy_only_when_the_api_refuses_it() { + let api = wiremock::MockServer::start().await; + let proxy = wiremock::MockServer::start().await; + let org = |uuid: &str| format!("/v0/orgs/acme/patches/view/{uuid}"); + let public = |uuid: &str| format!("/patch/view/{uuid}"); + mount_view(&api, org(U1), 200, Some(build_view(U1, "paid")), 2).await; + mount_view(&api, org(U2), 403, None, 1).await; + mount_view(&proxy, public(U1), 403, None, 0).await; + mount_view(&proxy, public(U2), 200, Some(build_view(U2, "free")), 1).await; + + let tmp = tempfile::tempdir().unwrap(); + let common = authenticated(tmp.path(), &api, &proxy); + let run = RunApiClient::new(); + let mut notes: Vec = Vec::new(); + let uuids = [U1.to_string(), U2.to_string()]; + let records = read_build_records(&common, &run, &uuids, &mut notes).await; + + for (uuid, record) in uuids.iter().zip(&records) { + let files = record + .as_ref() + .unwrap_or_else(|_| panic!("no record of {uuid}")); + let file = files.get("lib/nokogiri/version.rb"); + assert_eq!(file.map(|f| f.after_hash.as_str()), Some(&*"b".repeat(64))); + } + assert_eq!(fallback_notes(¬es), 1, "{notes:?}"); + // A 403 is about one patch: the next read asks the API again. + let again = read_build_records(&common, &run, &uuids[..1], &mut notes).await; + assert!(again[0].is_ok()); + assert_eq!(fallback_notes(¬es), 1, "{notes:?}"); + api.verify().await; + proxy.verify().await; + } + + /// Once the authenticated API has refused the credential itself (a + /// 401), the run's client is handed out as the public proxy's: the + /// reads that follow, of patch records and of build records alike, + /// ask the API nothing, and the fallback is not noted a second time. + #[tokio::test] + #[serial_test::serial] + async fn the_run_stays_on_the_proxy_after_the_credential_is_refused() { + let api = wiremock::MockServer::start().await; + let proxy = wiremock::MockServer::start().await; + let org = |uuid: &str| format!("/v0/orgs/acme/patches/view/{uuid}"); + let public = |uuid: &str| format!("/patch/view/{uuid}"); + mount_view(&api, org(U1), 401, None, 1).await; + mount_view(&api, org(U2), 401, None, 0).await; + mount_view(&proxy, public(U1), 200, Some(build_view(U1, "free")), 1).await; + mount_view(&proxy, public(U2), 200, Some(build_view(U2, "free")), 2).await; + + let tmp = tempfile::tempdir().unwrap(); + let common = authenticated(tmp.path(), &api, &proxy); + let run = RunApiClient::new(); + let mut notes: Vec = Vec::new(); + let before = run_client(&common, &run, &mut notes).await; + assert!(!before.uses_public_proxy()); + let first = read_build_records(&common, &run, &[U1.to_string()], &mut notes).await; + let after = run_client(&common, &run, &mut notes).await; + assert!( + after.uses_public_proxy(), + "the client handed out is the proxy's" + ); + let later = read_build_records(&common, &run, &[U2.to_string()], &mut notes).await; + let records = fetch_records(&common, &run, &[U2.to_string()], &mut notes).await; + + assert!(first[0].is_ok() && later[0].is_ok()); + assert!(records.contains_key(U2), "{records:?}"); + assert_eq!(fallback_notes(¬es), 1, "{notes:?}"); + api.verify().await; + proxy.verify().await; + } + /// Standalone `vex --json` (no host client): a token whose org cannot /// be resolved builds a proxy client here, the records come from the /// proxy, and the envelope gets one `api_auth_fallback` note. A client @@ -1712,6 +3026,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_builds: Vec::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 +3083,7 @@ mod tests { redirect: Some(redirect), discovery: discovery(refs), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert_eq!(plan.redirected, vec![key.to_string()], "{what}"); @@ -1792,6 +3108,7 @@ mod tests { redirect: None, discovery: discovery(vec![hosted_ref("pkg:npm/x@1.0.0", U2, true)]), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert!( @@ -1828,6 +3145,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_builds: Vec::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert!(plan @@ -1871,6 +3189,7 @@ mod tests { hosted_ref("pkg:npm/y@1.0.0", U2, true), ]), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::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 +3239,7 @@ mod tests { redirect: Some(redirect.clone()), discovery: Discovery::default(), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let live = plan( &common(tmp.path()), @@ -2038,6 +3358,7 @@ mod tests { redirect: Some(redirect.clone()), discovery, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; // Control — nothing recognized: the hosted ledger's own recorded @@ -2125,6 +3446,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_builds: Vec::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; let wiring = &plan.hosted["pkg:npm/x@1.0.0"]; @@ -2157,6 +3479,7 @@ mod tests { redirect: Some(redirect.clone()), discovery, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let gated = plan( &common(tmp.path()), @@ -2258,6 +3581,7 @@ mod tests { redirect: Some(redirect.clone()), discovery, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let mut both = discovery(vec![ go_ref(PURL, U1, "go.work"), @@ -2310,6 +3634,7 @@ mod tests { redirect: Some(redirect), discovery: found, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let plan = plan(&common(tmp.path()), sources, &[], &RunApiClient::new()).await; assert_eq!(plan.hosted[PURL].uuid, U1); @@ -2349,6 +3674,7 @@ mod tests { redirect: Some(redirect), discovery: found, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }, &[], &RunApiClient::new(), @@ -2405,6 +3731,7 @@ mod tests { redirect: None, discovery: found, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }, &[], &RunApiClient::new(), @@ -2455,6 +3782,7 @@ mod tests { redirect: None, discovery: found, hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }, &[], &RunApiClient::new(), @@ -2491,6 +3819,7 @@ mod tests { redirect: Some(redirect), discovery: Discovery::default(), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let plan = plan( &common(tmp.path()), @@ -2568,6 +3897,7 @@ mod tests { // not a discovery input: the ledger fallback decides. discovery: Discovery::default(), hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), }; let plan = plan(&common(root), sources, &[], &RunApiClient::new()).await; if gemfile_wired { @@ -2584,4 +3914,787 @@ mod tests { } } } + + // ── A gem a lock takes from its patch registry as platform builds ── + + const GEM: &str = "pkg:gem/nokogiri@1.18.10"; + const GEM_ARM: &str = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + const GEM_LINUX: &str = "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu"; + /// The patches of the gem's patched platform builds. + const ARM_UUID: &str = "11111111-1111-4111-8111-111111111111"; + const LINUX_UUID: &str = "22222222-2222-4222-8222-222222222222"; + /// Upstream's `arm64-darwin` gem, and the patched ones. + const ARM_UPSTREAM: &str = "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0"; + const ARM_PATCHED: &str = "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1"; + const LINUX_PATCHED: &str = "b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1"; + const RUBY_PATCHED: &str = "c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1"; + + /// The registry of the gem's patch on `origin`, at the snapshot `key`. + fn gem_registry(origin: &str, key: &str) -> String { + format!("{origin}/patch-registry/gem/tok/{U1}/s/{key}/") + } + + /// A lock that takes the gem's builds `tokens` (`1.18.10`, + /// `1.18.10-arm64-darwin`, …) from `remote`, pinned as `checksums` + /// say (no `CHECKSUMS` section without any), and the sources that read + /// it: the lock's one hosted pin of the gem's patch [`U1`], whose + /// record a pre-v5 ledger holds, so no record is fetched. + fn hosted_gem_sources( + root: &Path, + remote: &str, + tokens: &[&str], + checksums: &[(&str, &str)], + ) -> Sources { + let mut lock = format!("GEM\n remote: {remote}\n specs:\n"); + for token in tokens { + lock.push_str(&format!(" nokogiri ({token})\n")); + } + lock.push_str("\nDEPENDENCIES\n nokogiri (= 1.18.10)!\n"); + if !checksums.is_empty() { + lock.push_str("\nCHECKSUMS\n"); + for (token, sha256) in checksums { + lock.push_str(&format!(" nokogiri ({token}) sha256={sha256}\n")); + } + } + std::fs::write(root.join("Gemfile.lock"), lock).unwrap(); + let pin = checksums + .first() + .map(|(_, sha256)| LockIntegrity::Sha256Hex(sha256.to_string())); + let wired = PatchedRef::hosted( + GEM.to_string(), + U1.to_string(), + "Gemfile.lock", + Some(remote), + pin, + !checksums.is_empty(), + ); + let mut redirect = RedirectState::new(); + redirect.records.insert(GEM.into(), record(U1)); + redirect + .records + .insert("pkg:npm/x@1.0.0".into(), record(U2)); + Sources { + manifest: PatchManifest::new(), + vendor: VendorState::new(), + redirect: Some(redirect), + discovery: discovery(vec![wired, hosted_ref("pkg:npm/x@1.0.0", U2, true)]), + hosted_uuids: Vec::new(), + hosted_gem_builds: Vec::new(), + } + } + + /// The patch API of the gem's patch on `server`: its reference lists + /// `builds` (platform, sha256, patch) under the snapshot `key`. + async fn mount_gem_reference( + server: &wiremock::MockServer, + key: &str, + builds: &[(&str, &str, Option<&str>)], + ) { + use wiremock::matchers::{method, path as wm_path}; + use wiremock::{Mock, ResponseTemplate}; + let listed: Vec = builds + .iter() + .map(|(platform, sha256, patch)| { + serde_json::json!({ + "platform": platform, "gemChecksumSha256": sha256, "patchUuid": patch, + }) + }) + .collect(); + Mock::given(method("POST")) + .and(wm_path("/v0/orgs/acme/patches/package")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "results": { U1: { + "status": "granted", + "purl": GEM, + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": gem_registry(&server.uri(), key), + "identifiers": { + "name": "nokogiri", "version": "1.18.10", + "gemChecksumSha256": RUBY_PATCHED, "gemBuilds": listed, + }, + }, + }} + }))) + .mount(server) + .await; + } + + /// The index of the registry at the snapshot `key` on `server`. + async fn mount_gem_index(server: &wiremock::MockServer, key: &str, lines: &[(&str, &str)]) { + use wiremock::matchers::{method, path as wm_path}; + use wiremock::{Mock, ResponseTemplate}; + let mut body = "---\n".to_string(); + for (token, sha256) in lines { + body.push_str(&format!("{token} racc:~> 1.4|checksum:{sha256}\n")); + } + Mock::given(method("GET")) + .and(wm_path(format!( + "/patch-registry/gem/tok/{U1}/s/{key}/info/nokogiri" + ))) + .respond_with(ResponseTemplate::new(200).set_body_string(body)) + .mount(server) + .await; + } + + /// A run against the patch API on `server`, authenticated. + fn online(root: &Path, server: &wiremock::MockServer) -> GlobalArgs { + GlobalArgs { + cwd: root.to_path_buf(), + json: true, + silent: true, + api_url: Some(server.uri()), + api_token: Some("sktsec_placeholder_value_for_tests_api".into()), + org: Some("acme".into()), + ..GlobalArgs::default() + } + } + + /// The paths of the requests `server` received, in arrival order. + async fn asked(server: &wiremock::MockServer) -> Vec { + let requests = server.received_requests().await.unwrap_or_default(); + requests + .iter() + .map(|request| request.url.path().to_string()) + .collect() + } + + /// What `plan` says of the gem's builds, by purl. + fn gem_states(plan: &Plan) -> Vec<(&str, &GemBuildState)> { + let gem = &plan.hosted_gems[GEM]; + assert_eq!((gem.gem_fix.as_str(), gem.resolved), (U1, true)); + gem.builds + .iter() + .map(|build| (build.purl.as_str(), &build.state)) + .collect() + } + + fn patched(uuid: &str) -> GemBuildState { + GemBuildState::Patched { + uuid: uuid.to_string(), + } + } + + /// What the document made from `plan` says of the gem: the purls it + /// attests as patched, and each purl it says `affected` of with the + /// action statement. + fn gem_statements(plan: &Plan) -> (Vec, Vec<(String, String)>) { + let builds = GemBuildView::of(plan).expect("a gem locked as platform builds"); + let mut applied = vec![GEM.to_string()]; + builds.expand(&mut applied); + (applied, builds.not_patched().to_vec()) + } + + /// The action statement of a build for `platform` that is not shown + /// patched for the reason `why`, with what to run. + fn unshown_action(platform: &str, why: &str, remedy: &str) -> String { + format!( + "It could not be shown that the lockfile installs a patched build of this gem for \ + {platform} ({why}), so it is stated as affected. {remedy}" + ) + } + + const REFERENCE: &str = "/v0/orgs/acme/patches/package"; + const ONE_PATCHED: [(&str, &str, Option<&str>); 2] = [ + ("arm64-darwin", ARM_UPSTREAM, None), + ("x86_64-linux-gnu", LINUX_PATCHED, Some(LINUX_UUID)), + ]; + const LOCKED: [&str; 2] = ["1.18.10-arm64-darwin", "1.18.10-x86_64-linux-gnu"]; + const PINNED: [(&str, &str); 2] = [ + ("1.18.10-arm64-darwin", ARM_UPSTREAM), + ("1.18.10-x86_64-linux-gnu", LINUX_PATCHED), + ]; + + /// A lock whose `CHECKSUMS` pins every build is settled by ONE + /// request, the gem patch's reference: the build on the sha256 the + /// list gives beside a patch is that patch's, the one on the sha256 it + /// gives beside none is upstream's gem. Nothing is omitted and nothing + /// is noted, and the registry is not asked. No patch record is read + /// for the plan. + #[tokio::test] + #[serial_test::serial] + async fn a_checksummed_lock_tells_its_builds_apart_by_the_reference_alone() { + let server = wiremock::MockServer::start().await; + mount_gem_reference(&server, "4f", &ONE_PATCHED).await; + let tmp = tempfile::tempdir().unwrap(); + let remote = gem_registry(&server.uri(), "4f"); + let sources = hosted_gem_sources(tmp.path(), &remote, &LOCKED, &PINNED); + let plan = plan( + &online(tmp.path(), &server), + sources, + &[], + &RunApiClient::new(), + ) + .await; + assert_eq!( + gem_states(&plan), + [ + (GEM_ARM, &GemBuildState::Upstream), + (GEM_LINUX, &patched(LINUX_UUID)) + ] + ); + assert!(plan.gated.is_empty(), "{:?}", plan.gated); + assert!(plan.notes.is_empty(), "{:?}", plan.notes); + assert_eq!(asked(&server).await, [REFERENCE]); + // The gem is still the one pin the checks judge. + assert_eq!(plan.view.patches[GEM].uuid, U1); + assert!(plan.redirected.contains(&GEM.to_string())); + } + + /// A lock with no `CHECKSUMS` installs what its own registry serves: + /// a second request reads that registry's index, and the builds are + /// told apart by it. Two requests, and no more. + #[tokio::test] + #[serial_test::serial] + async fn a_lock_without_checksums_asks_its_own_registry_too() { + let server = wiremock::MockServer::start().await; + mount_gem_reference(&server, "4f", &ONE_PATCHED).await; + mount_gem_index(&server, "4f", &PINNED).await; + let tmp = tempfile::tempdir().unwrap(); + let remote = gem_registry(&server.uri(), "4f"); + let sources = hosted_gem_sources(tmp.path(), &remote, &LOCKED, &[]); + let plan = plan( + &online(tmp.path(), &server), + sources, + &[], + &RunApiClient::new(), + ) + .await; + assert_eq!( + gem_states(&plan), + [ + (GEM_ARM, &GemBuildState::Upstream), + (GEM_LINUX, &patched(LINUX_UUID)) + ] + ); + assert!(plan.gated.is_empty(), "{:?}", plan.gated); + assert_eq!( + asked(&server).await, + [ + REFERENCE.to_string(), + format!("/patch-registry/gem/tok/{U1}/s/4f/info/nokogiri"), + ] + ); + } + + /// The index of the lock's registry cannot be read: nothing shows what + /// the lock installs, so the document says `affected` of both builds + /// and names no patch for them. Nothing is gated, and one note names + /// the gem, the reason (with the error of the read) and what to run. + #[tokio::test] + #[serial_test::serial] + async fn an_unreadable_index_states_the_builds_of_a_lock_without_checksums_as_affected() { + let server = wiremock::MockServer::start().await; + mount_gem_reference(&server, "4f", &ONE_PATCHED).await; + let tmp = tempfile::tempdir().unwrap(); + let remote = gem_registry(&server.uri(), "4f"); + let sources = hosted_gem_sources(tmp.path(), &remote, &LOCKED, &[]); + let plan = plan( + &online(tmp.path(), &server), + sources, + &[], + &RunApiClient::new(), + ) + .await; + let unpinned = GemBuildState::Unknown(GemBuildUnknown::Unpinned); + assert_eq!( + gem_states(&plan), + [(GEM_ARM, &unpinned), (GEM_LINUX, &unpinned)] + ); + assert!(plan.gated.is_empty(), "{:?}", plan.gated); + let [note] = plan.notes.as_slice() else { + panic!("one note for the gem: {:?}", plan.notes); + }; + assert_eq!(note.code, GEM_BUILD_UNKNOWN); + assert!( + note.detail.starts_with(&format!( + "{GEM}: the lockfile takes its builds for arm64-darwin, x86_64-linux-gnu from \ + the registry of Socket patch {U1}" + )) && note.detail.contains( + "(the lockfile has no CHECKSUMS entry for them, and its registry's index could \ + not be read: " + ) && note.detail.ends_with(&format!( + "), so the VEX document states them as affected. {GEM_BUILD_RETRY}" + )), + "{}", + note.detail + ); + assert!(!note.detail.contains("/tok/"), "the grant token: {note:?}"); + + // The document: both builds as affected, without the error. + let why = "the lockfile has no CHECKSUMS entry for it, and its registry's index could \ + not be read"; + let action = |platform: &str| unshown_action(platform, why, GEM_BUILD_RETRY); + assert_eq!( + gem_statements(&plan), + ( + Vec::new(), + vec![ + (GEM_ARM.to_string(), action("arm64-darwin")), + (GEM_LINUX.to_string(), action("x86_64-linux-gnu")), + ] + ) + ); + } + + /// The reference is of a later registry than the lock names: it lists + /// a patched build for a platform the lock still pins upstream's gem + /// for. That build is not attested as patched, on either way of + /// telling what the lock installs: the document says `affected` of it, + /// and names the patch the list gives for it nowhere. The build the + /// lock does pin patched is attested. Nothing is gated, and the note + /// sends the reader to the scan. + #[tokio::test] + #[serial_test::serial] + async fn a_reference_newer_than_the_lock_attests_no_build_the_lock_pins_otherwise() { + let both = [ + ("arm64-darwin", ARM_PATCHED, Some(ARM_UUID)), + ("x86_64-linux-gnu", LINUX_PATCHED, Some(LINUX_UUID)), + ]; + for checksums in [true, false] { + let server = wiremock::MockServer::start().await; + mount_gem_reference(&server, "5a", &both).await; + mount_gem_index(&server, "4f", &PINNED).await; + let tmp = tempfile::tempdir().unwrap(); + let remote = gem_registry(&server.uri(), "4f"); + let pinned: &[(&str, &str)] = if checksums { &PINNED } else { &[] }; + let sources = hosted_gem_sources(tmp.path(), &remote, &LOCKED, pinned); + let plan = plan( + &online(tmp.path(), &server), + sources, + &[], + &RunApiClient::new(), + ) + .await; + assert_eq!( + gem_states(&plan), + [ + (GEM_ARM, &GemBuildState::Unknown(GemBuildUnknown::Differs)), + (GEM_LINUX, &patched(LINUX_UUID)) + ], + "checksums: {checksums}" + ); + assert!(plan.gated.is_empty(), "{:?}", plan.gated); + let [note] = plan.notes.as_slice() else { + panic!("one note for the gem: {:?}", plan.notes); + }; + assert!( + note.detail.contains("its build for arm64-darwin from") + && note.detail.contains( + "(the lockfile installs another archive for it than the patch registry \ + lists now), so the VEX document states it as affected." + ) + && note.detail.ends_with(GEM_BUILD_RESCAN), + "{}", + note.detail + ); + let (applied, affected) = gem_statements(&plan); + assert_eq!(applied, [GEM_LINUX], "checksums: {checksums}"); + assert_eq!( + affected, + [( + GEM_ARM.to_string(), + unshown_action( + "arm64-darwin", + "the lockfile installs another archive for it than the patch registry \ + lists now", + GEM_BUILD_RESCAN + ) + )], + "checksums: {checksums}" + ); + assert!(!affected[0].1.contains(ARM_UUID) && !affected[0].1.contains(U1)); + // No patch record is read for the plan: a record is read + // only for a build that has an installed copy. + assert_eq!( + asked(&server).await.len(), + if checksums { 1 } else { 2 }, + "checksums: {checksums}" + ); + } + } + + /// `--offline`: nothing is asked, so nothing says which locked build + /// is patched. The document says `affected` of the platform builds, + /// with one note and nothing gated; the ruby-platform gem the lock + /// names beside them is the gem's patch by the lock's wiring alone. + #[tokio::test] + #[serial_test::serial] + async fn offline_states_the_platform_builds_as_affected_and_asks_nothing() { + let server = wiremock::MockServer::start().await; + mount_gem_reference(&server, "4f", &ONE_PATCHED).await; + let tmp = tempfile::tempdir().unwrap(); + let remote = gem_registry(&server.uri(), "4f"); + let sources = hosted_gem_sources( + tmp.path(), + &remote, + &["1.18.10", LOCKED[0], LOCKED[1]], + &[("1.18.10", RUBY_PATCHED), PINNED[0], PINNED[1]], + ); + let common = GlobalArgs { + offline: true, + ..online(tmp.path(), &server) + }; + let plan = plan(&common, sources, &[], &RunApiClient::new()).await; + let unlisted = GemBuildState::Unknown(GemBuildUnknown::Unlisted); + assert_eq!( + gem_states(&plan), + [ + (GEM, &patched(U1)), + (GEM_ARM, &unlisted), + (GEM_LINUX, &unlisted) + ] + ); + assert!(plan.gated.is_empty(), "{:?}", plan.gated); + let [note] = plan.notes.as_slice() else { + panic!("one note for the gem: {:?}", plan.notes); + }; + assert_eq!( + note.detail, + format!( + "{GEM}: the lockfile takes its builds for arm64-darwin, x86_64-linux-gnu from \ + the registry of Socket patch {U1}, which serves a patched build for some \ + platforms and upstream's own gem for the others. Which it is for these could \ + not be told (--offline forbids asking the patch API), so the VEX document \ + states them as affected. Run `socket-patch vex` without --offline to attest \ + each build." + ) + ); + assert_eq!(asked(&server).await, Vec::::new()); + + // The document: the ruby-platform gem under the gem's patch, and + // each platform build as affected. + let action = |platform: &str| { + unshown_action( + platform, + "--offline forbids asking the patch API", + GEM_BUILD_ONLINE, + ) + }; + assert_eq!( + gem_statements(&plan), + ( + vec![GEM.to_string()], + vec![ + (GEM_ARM.to_string(), action("arm64-darwin")), + (GEM_LINUX.to_string(), action("x86_64-linux-gnu")), + ] + ) + ); + } + + /// The reference request fails, or the reference carries no list: no + /// build is attested as patched and the document says `affected` of + /// each, the note says which it was (with the error of a failed + /// request, which the document leaves out), nothing is gated, and the + /// registry is not asked for an index nothing could be held against. + #[tokio::test] + #[serial_test::serial] + async fn a_failed_or_listless_reference_states_the_platform_builds_as_affected() { + use wiremock::matchers::{method, path as wm_path}; + use wiremock::{Mock, ResponseTemplate}; + let no_list = serde_json::json!({ "results": { U1: { + "status": "granted", "purl": GEM, + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": format!("https://patch.example/patch-registry/gem/tok/{U1}/"), + "identifiers": { + "name": "nokogiri", "version": "1.18.10", "gemChecksumSha256": RUBY_PATCHED, + }, + }, + }}}); + for (answer, why, stated, remedy) in [ + ( + ResponseTemplate::new(500), + "(the patch API request failed: ", + "the patch API request failed", + GEM_BUILD_RETRY, + ), + ( + ResponseTemplate::new(200).set_body_json(no_list), + "(the patch API lists no builds for that patch)", + "the patch API lists no builds for that patch", + GEM_BUILD_RESCAN, + ), + ] { + let server = wiremock::MockServer::start().await; + Mock::given(method("POST")) + .and(wm_path(REFERENCE)) + .respond_with(answer) + .mount(&server) + .await; + let tmp = tempfile::tempdir().unwrap(); + let remote = gem_registry(&server.uri(), "4f"); + // No `CHECKSUMS`: with a list, the index would be read. + let sources = hosted_gem_sources(tmp.path(), &remote, &LOCKED, &[]); + let plan = plan( + &online(tmp.path(), &server), + sources, + &[], + &RunApiClient::new(), + ) + .await; + assert!(plan.gated.is_empty(), "{why}: {:?}", plan.gated); + let [note] = plan.notes.as_slice() else { + panic!("one note for the gem: {:?}", plan.notes); + }; + assert!( + note.code == GEM_BUILD_UNKNOWN + && note.detail.contains(why) + && note.detail.ends_with(remedy), + "{}", + note.detail + ); + let asked = asked(&server).await; + assert!( + !asked.is_empty() && asked.iter().all(|path| path == REFERENCE), + "{asked:?}" + ); + // The document: no build as patched, each as affected. + let action = |platform: &str| unshown_action(platform, stated, remedy); + assert_eq!( + gem_statements(&plan), + ( + Vec::new(), + vec![ + (GEM_ARM.to_string(), action("arm64-darwin")), + (GEM_LINUX.to_string(), action("x86_64-linux-gnu")), + ] + ), + "{why}" + ); + } + } + + /// A gem the lock names as its ruby-platform gem alone is the one pin + /// it always was, and so is every other ecosystem's: no request, and + /// nothing for the document to name in its place. + #[tokio::test] + #[serial_test::serial] + async fn a_gem_locked_as_its_ruby_gem_alone_asks_nothing() { + let server = wiremock::MockServer::start().await; + mount_gem_reference(&server, "4f", &ONE_PATCHED).await; + let tmp = tempfile::tempdir().unwrap(); + let remote = format!("{}/patch-registry/gem/tok/{U1}/", server.uri()); + let sources = hosted_gem_sources( + tmp.path(), + &remote, + &["1.18.10"], + &[("1.18.10", RUBY_PATCHED)], + ); + let plan = plan( + &online(tmp.path(), &server), + sources, + &[], + &RunApiClient::new(), + ) + .await; + assert!(plan.hosted_gems.is_empty(), "{:?}", plan.hosted_gems); + assert_eq!(plan.redirected, [GEM, "pkg:npm/x@1.0.0"]); + assert!(plan.gated.is_empty() && plan.notes.is_empty()); + assert!(GemBuildView::of(&plan).is_none()); + assert_eq!(asked(&server).await, Vec::::new()); + } + + /// The pins of the hosted run the plan is part of come with what that + /// run reports for each locked build: the plan takes them as they are + /// and asks nothing, whatever the lock's `CHECKSUMS` hold. + #[tokio::test] + #[serial_test::serial] + async fn the_builds_a_hosted_run_reports_are_taken_without_a_request() { + let server = wiremock::MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let remote = gem_registry(&server.uri(), "4f"); + let report = |platform: Option<&str>, uuid: Option<&str>| PinReport { + purl: match platform { + Some(platform) => format!("{GEM}?platform={platform}"), + None => GEM.to_string(), + }, + uuid: uuid.map(str::to_string), + gem_fix: Some(U1.to_string()), + platform: platform.map(str::to_string), + newly_patched: uuid.is_some(), + withdrawn: false, + }; + let sources = Sources { + hosted_gem_builds: vec![ + report(None, Some(U1)), + report(Some("arm64-darwin"), None), + report(Some("x86_64-linux-gnu"), Some(LINUX_UUID)), + ], + ..hosted_gem_sources(tmp.path(), &remote, &LOCKED, &[]) + }; + let plan = plan( + &online(tmp.path(), &server), + sources, + &[GEM.to_string()], + &RunApiClient::new(), + ) + .await; + let gem = &plan.hosted_gems[GEM]; + assert!(!gem.resolved, "the run says its builds itself"); + let states: Vec<(&str, &GemBuildState)> = gem + .builds + .iter() + .map(|build| (build.purl.as_str(), &build.state)) + .collect(); + assert_eq!( + states, + [ + (GEM, &patched(U1)), + (GEM_ARM, &GemBuildState::Upstream), + (GEM_LINUX, &patched(LINUX_UUID)) + ] + ); + assert!(plan.gated.is_empty() && plan.notes.is_empty()); + assert_eq!(asked(&server).await, Vec::::new()); + } + + /// A plan attesting the hosted gem [`GEM`] at [`U1`], locked as the + /// builds `builds` (platform and state). + fn hosted_gem_plan(builds: Vec<(Option<&str>, GemBuildState)>) -> Plan { + let builds = builds + .into_iter() + .map(|(platform, state)| (platform.map(str::to_string), state)); + let gem = HostedGem::of(GEM, U1, builds, true).unwrap(); + Plan { + view: PatchManifest { + patches: HashMap::from([ + (GEM.to_string(), record(U1)), + ("pkg:npm/left-pad@1.3.0".to_string(), record(U2)), + ]), + setup: None, + }, + vendor_entries: HashMap::new(), + vendor_pins: HashMap::new(), + redirected: vec![GEM.to_string()], + lockfile_basis: HashSet::new(), + hosted: BTreeMap::new(), + hosted_gems: BTreeMap::from([(GEM.to_string(), gem)]), + gated: Vec::new(), + notes: Vec::new(), + } + } + + /// A gem a lock takes from its patch registry as platform builds is + /// named per locked build. A patched build goes under its own patch, + /// with the gem patch's vulnerabilities, wherever the gem was; a build + /// on upstream's gem, and a build nothing is known of, are in no list + /// of attested purls and are handed over as affected, each with what + /// to do. All three keep a record in the view, so no statement names a + /// form of the gem that stands for an unpatched build too. + #[test] + fn a_hosted_gem_is_attested_per_locked_build() { + const JAVA: &str = "pkg:gem/nokogiri@1.18.10?platform=java"; + let plan = hosted_gem_plan(vec![ + (None, patched(U1)), + (Some("arm64-darwin"), GemBuildState::Upstream), + ( + Some("java"), + GemBuildState::Unknown(GemBuildUnknown::Unlisted), + ), + (Some("x86_64-linux-gnu"), patched(LINUX_UUID)), + ]); + let builds = GemBuildView::of(&plan).expect("a gem locked as platform builds"); + let view = builds.view(); + let mut keys: Vec<&str> = view.patches.keys().map(String::as_str).collect(); + keys.sort_unstable(); + assert_eq!( + keys, + [GEM, GEM_ARM, JAVA, GEM_LINUX, "pkg:npm/left-pad@1.3.0"] + ); + assert_eq!(view.patches[GEM].uuid, U1); + assert_eq!(view.patches[GEM_LINUX].uuid, LINUX_UUID); + for purl in [GEM, GEM_ARM, JAVA, GEM_LINUX] { + assert_eq!( + view.patches[purl].vulnerabilities, + record(U1).vulnerabilities + ); + } + + for mut attested in [ + vec!["pkg:npm/left-pad@1.3.0".to_string(), GEM.to_string()], + plan.redirected.clone(), + ] { + let others = attested.len() - 1; + builds.expand(&mut attested); + assert_eq!(attested[others..], [GEM, GEM_LINUX]); + } + assert_eq!( + builds.not_patched(), + [ + ( + GEM_ARM.to_string(), + format!( + "The patch registry has no patched build of this gem for arm64-darwin \ + yet and serves upstream's own gem for it, so an install on that \ + platform is without Socket patch {U1}. Run `socket-patch scan --mode \ + hosted` again later: the lockfile takes the patched build once it is \ + published." + ) + ), + ( + JAVA.to_string(), + // A scan changes nothing for a platform the registry + // does not list, so the remedy names none. + unshown_action( + "java", + "the patch registry does not list it now", + GEM_BUILD_UNLISTED + ) + ), + ] + ); + let described: Vec<(&str, Option<&str>, bool, Option<&str>)> = builds + .builds() + .iter() + .map(|(purl, build)| { + assert_eq!(build.gem_fix, U1); + ( + purl.as_str(), + build.platform.as_deref(), + build.kept_upstream, + build.unshown.as_deref(), + ) + }) + .collect(); + assert_eq!( + described, + [ + (GEM, None, false, None), + (GEM_ARM, Some("arm64-darwin"), true, None), + ( + JAVA, + Some("java"), + false, + Some("not shown patched for java: the patch registry does not list it now") + ), + (GEM_LINUX, Some("x86_64-linux-gnu"), false, None), + ] + ); + } + + /// An installed copy of a platform build the lock does not install + /// patched is no evidence about the gem: it is upstream's own gem by + /// the lock. Every other copy is judged, the ruby-platform one and one + /// of a platform the lock does not name included. + #[test] + fn the_copy_of_a_build_the_lock_installs_unpatched_is_not_judged() { + let plan = hosted_gem_plan(vec![ + (Some("arm64-darwin"), GemBuildState::Upstream), + ( + Some("java"), + GemBuildState::Unknown(GemBuildUnknown::Differs), + ), + (Some("x86_64-linux-gnu"), patched(LINUX_UUID)), + ]); + let gem = &plan.hosted_gems[GEM]; + let judged = |leaf: &str| gem.judges(GEM, &Path::new("/home/gems").join(leaf)); + assert!(!judged("nokogiri-1.18.10-arm64-darwin")); + assert!(!judged("nokogiri-1.18.10-java")); + assert!(judged("nokogiri-1.18.10-x86_64-linux-gnu")); + assert!(judged("nokogiri-1.18.10")); + assert!(judged("nokogiri-1.18.10-aarch64-linux-gnu")); + assert!(judged("nokogiri-1.18.9-arm64-darwin")); + } } diff --git a/crates/socket-patch-cli/src/json_envelope.rs b/crates/socket-patch-cli/src/json_envelope.rs index e399cb2917..a37acd3d86 100644 --- a/crates/socket-patch-cli/src/json_envelope.rs +++ b/crates/socket-patch-cli/src/json_envelope.rs @@ -165,8 +165,11 @@ pub struct VexSummary { pub path: String, /// Number of OpenVEX statements in the document. pub statements: usize, - /// How many of them say `affected` (see `vex_bazel_not_in_build`), not - /// `not_affected`. Omitted from JSON when none does. + /// How many of them say `affected`, not `not_affected`: of a package + /// Bazel builds without its patch (see `vex_bazel_not_in_build`), or of + /// a gem build the lockfile takes from a patch registry as upstream's + /// own gem (`gem_upstream_build_kept`). Omitted from JSON when none + /// does. #[serde(skip_serializing_if = "is_zero")] pub affected: usize, /// Document format tag, e.g. `"openvex-0.2.0"`. diff --git a/crates/socket-patch-cli/src/ui/mod.rs b/crates/socket-patch-cli/src/ui/mod.rs index bb706da3e5..4241282fa6 100644 --- a/crates/socket-patch-cli/src/ui/mod.rs +++ b/crates/socket-patch-cli/src/ui/mod.rs @@ -32,7 +32,7 @@ pub(crate) use status::StatusLine; pub(crate) use text::{ agent_next_steps, folded, manifest_error_message, next_steps, next_steps_installed, package_names, plural, printable, sentence_case, shell_word, short_uuid, sweep_failure, - truncate, worst_and_ids, + truncate, worst_and_ids, wrap_line, wrap_words, }; /// [`text::no_patches_message`] for this run: the manifest path is named diff --git a/crates/socket-patch-cli/src/ui/text.rs b/crates/socket-patch-cli/src/ui/text.rs index eb67e05ec4..5f6f60f162 100644 --- a/crates/socket-patch-cli/src/ui/text.rs +++ b/crates/socket-patch-cli/src/ui/text.rs @@ -1,6 +1,6 @@ //! Pure text helpers for human output: counted nouns, one-line -//! truncation, sentence casing and the "Next steps:" block. No I/O, no -//! terminal state. +//! truncation, word wrap, sentence casing and the "Next steps:" block. No +//! I/O, no terminal state. /// `plural(1, "package", "packages")` → `"1 package"`, /// `plural(2, "package", "packages")` → `"2 packages"` (and `0 packages`). @@ -10,6 +10,117 @@ pub fn plural(n: usize, one: &str, many: &str) -> String { const ELLIPSIS: &str = "..."; +/// Split `text` into wrap tokens at whitespace, except that a +/// backtick-delimited code span (`` `pnpm install --trust-lockfile` ``) +/// stays one token so a command the user copies is never broken across +/// lines. An unclosed span falls back to plain whitespace splitting. +pub(crate) fn wrap_tokens(text: &str) -> Vec { + let mut tokens: Vec = Vec::new(); + let mut span: Vec<&str> = Vec::new(); + for word in text.split_whitespace() { + span.push(word); + let open = span.iter().map(|w| w.matches('`').count()).sum::() % 2 == 1; + if !open { + tokens.push(span.join(" ")); + span.clear(); + } + } + tokens.extend(span.into_iter().map(str::to_string)); + tokens +} + +/// Greedy word wrap to `width` columns (characters, not bytes). The first +/// line starts with `first_prefix`, later lines with `indent`. A word +/// longer than the line (a URL) gets a line of its own, never split; a +/// backtick code span counts as one word (see [`wrap_tokens`]). +pub(crate) fn wrap_words( + text: &str, + width: usize, + first_prefix: &str, + indent: &str, +) -> Vec { + let mut lines: Vec = Vec::new(); + let mut line = first_prefix.to_string(); + let mut line_len = first_prefix.chars().count(); + let mut empty = true; + for word in wrap_tokens(text) { + let word = word.as_str(); + let wlen = word.chars().count(); + if !empty && line_len + 1 + wlen > width { + lines.push(std::mem::replace(&mut line, indent.to_string())); + line_len = indent.chars().count(); + empty = true; + } + if !empty { + line.push(' '); + line_len += 1; + } + line.push_str(word); + line_len += wlen; + empty = false; + } + lines.push(line); + lines +} + +/// `line` as it prints for a person. With `width` (its stream is a +/// terminal with a person at it) a line that does not fit breaks after a +/// clause (`; `) under a two-space hanging indent, so no clause is cut in +/// two unless it is itself wider than the terminal: such a clause wraps at +/// a word from where the row stands, and the clause after it goes on from +/// there. Without `width` the line is as it is, so a pipe or a log keeps +/// one line. +pub(crate) fn wrap_line(line: &str, width: Option) -> String { + const INDENT: &str = " "; + let Some(width) = width else { + return line.to_string(); + }; + let len = |text: &str| text.chars().count(); + // What a row holds beside its indent: every row but the first has one. + let later = width.saturating_sub(INDENT.len()); + let room = |rows: &[String]| if rows.len() > 1 { later } else { width }; + // Put `text` on the row being filled, or on a new one when it is full. + fn place(rows: &mut Vec, text: &str, room: usize) { + let row = rows.last_mut().expect("one row at least"); + if row.is_empty() { + row.push_str(text); + } else if row.chars().count() + 1 + text.chars().count() <= room { + row.push(' '); + row.push_str(text); + } else { + rows.push(text.to_string()); + } + } + let mut rows: Vec = vec![String::new()]; + for clause in line.split_inclusive("; ") { + let clause = clause.trim_end(); + let row = rows.last().expect("one row at least"); + let here = if row.is_empty() { + len(clause) <= room(&rows) + } else { + len(row) + 1 + len(clause) <= room(&rows) + }; + if here || len(clause) <= later { + let room = room(&rows); + place(&mut rows, clause, room); + continue; + } + // Wider than a row: at a word, a code span kept whole. + for word in wrap_tokens(clause) { + let room = room(&rows); + place(&mut rows, &word, room); + } + } + rows.iter() + .enumerate() + .map(|(at, row)| match at { + 0 => row.clone(), + _ => format!("{INDENT}{row}"), + }) + .collect::>() + .join("\n") +} + /// `text` as it may be printed: without its control characters. For /// text that came from a service or a project's files, which is shown /// for reading and must never move the cursor, retitle the terminal or @@ -348,6 +459,121 @@ pub(crate) fn shell_word(word: &str) -> String { mod tests { use super::*; + /// A line breaks after a clause, a clause is cut only when it is + /// wider than the terminal, and the clause after one that wrapped goes + /// on from where it left the row. A pipe keeps one line. + #[test] + fn wrap_line_breaks_after_clauses_and_goes_on_after_one_that_wrapped() { + let kept = + "nokogiri 1.19.3: patched for aarch64-linux-gnu, x86_64-linux-gnu; upstream gem \ + kept for arm64-darwin (no patched build yet)"; + assert_eq!(wrap_line(kept, None), kept); + assert_eq!(wrap_line(kept, Some(200)), kept); + assert_eq!( + wrap_line(kept, Some(80)), + "nokogiri 1.19.3: patched for aarch64-linux-gnu, x86_64-linux-gnu;\n upstream gem kept \ + for arm64-darwin (no patched build yet)" + ); + let waiting = "nokogiri 1.19.3: no patched build yet for aarch64-linux-gnu, arm64-darwin, \ + x86_64-linux-gnu; left on its upstream registry"; + assert_eq!( + wrap_line(waiting, Some(80)), + "nokogiri 1.19.3: no patched build yet for aarch64-linux-gnu, arm64-darwin,\n \ + x86_64-linux-gnu; left on its upstream registry" + ); + let vendored = "nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin \ + (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs a \ + gem, patched or upstream's own, for every locked platform; `scan --mode \ + hosted` can patch the others now."; + assert_eq!( + wrap_line(vendored, Some(80)), + "nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin\n \ + (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs a gem,\n \ + patched or upstream's own, for every locked platform;\n \ + `scan --mode hosted` can patch the others now." + ); + let unlisted = "nokogiri@1.19.3 is not vendored: the patch registry does not list java. \ + Vendored mode needs a gem, patched or upstream's own, for every locked \ + platform, and a re-run does not change what the registry lists: this is \ + settled once the lockfile no longer names java (`bundle lock \ + --remove-platform java`), or the registry lists a gem for every locked \ + platform."; + assert_eq!( + wrap_line(unlisted, Some(80)), + "nokogiri@1.19.3 is not vendored: the patch registry does not list java. Vendored\n \ + mode needs a gem, patched or upstream's own, for every locked platform, and a\n \ + re-run does not change what the registry lists: this is settled once the\n \ + lockfile no longer names java (`bundle lock --remove-platform java`), or the\n \ + registry lists a gem for every locked platform." + ); + for width in [80, 100, 120] { + for line in [kept, waiting, vendored, unlisted] { + let wrapped = wrap_line(line, Some(width)); + assert!( + wrapped.lines().all(|row| row.chars().count() <= width), + "{width}: {wrapped}" + ); + assert_eq!(wrapped.replace("\n ", " "), line, "nothing is lost"); + } + } + } + + #[test] + fn wrap_words_respects_width_prefix_and_long_words() { + assert_eq!( + wrap_words("alpha beta gamma delta", 16, "W: ", " "), + vec!["W: alpha beta", " gamma delta"] + ); + // A word wider than the line sits alone, unsplit. + let url = "https://patch.socket.dev/very/long/path/that/does/not/fit"; + assert_eq!( + wrap_words(&format!("see {url} now"), 20, "", " "), + vec!["see".to_string(), format!(" {url}"), " now".to_string()] + ); + assert_eq!(wrap_words("", 10, "W: ", " "), vec!["W: "]); + // Counts characters, not bytes. + let lines = wrap_words("ééé ééé ééé", 8, "", ""); + assert_eq!(lines, vec!["ééé ééé", "ééé"]); + for line in wrap_words(&"word ".repeat(50), 30, "Warning: ", " ") { + assert!(line.chars().count() <= 30, "{line}"); + } + } + + #[test] + fn wrap_words_keeps_code_spans_whole() { + // The span crosses the wrap column: it moves to the next line whole. + assert_eq!( + wrap_words( + "never rebuild it (`pnpm clean --lockfile`), ever", + 30, + "", + " " + ), + vec!["never rebuild it", " (`pnpm clean --lockfile`),", " ever"] + ); + // A span wider than the line gets a line of its own, unsplit. + assert_eq!( + wrap_words( + "use `pnpm install --frozen-lockfile --store-dir ` now", + 20, + "", + " " + ), + vec![ + "use", + " `pnpm install --frozen-lockfile --store-dir `", + " now" + ] + ); + // Two spans in one word, and a word with a closed span, split normally. + assert_eq!( + wrap_tokens("a `b` c `d e`f g"), + vec!["a", "`b`", "c", "`d e`f", "g"] + ); + // An unclosed span never swallows the rest of the text. + assert_eq!(wrap_tokens("a `b c d"), vec!["a", "`b", "c", "d"]); + } + #[test] fn packages_of_one_ecosystem_are_named_without_it() { assert_eq!( diff --git a/crates/socket-patch-cli/tests/common/pty_io.rs b/crates/socket-patch-cli/tests/common/pty_io.rs index b0674d4db5..57cd52f3e8 100644 --- a/crates/socket-patch-cli/tests/common/pty_io.rs +++ b/crates/socket-patch-cli/tests/common/pty_io.rs @@ -129,6 +129,20 @@ pub fn run(args: &[&str], cwd: &Path, input: &str, timeout: Duration) -> (i32, S /// `TERM` is pinned: `console`/`dialoguer` derive key handling and /// rendering from it, and bare CI shells leave it unset or `dumb`. pub fn run_command( + cmd: portable_pty::CommandBuilder, + args: &[&str], + cwd: &Path, + env: &[(&str, &str)], + answers: &[&[u8]], + timeout: Duration, +) -> PtyRun { + run_command_at(80, cmd, args, cwd, env, answers, timeout) +} + +/// [`run_command`] on a PTY `cols` columns wide, for output that is +/// fitted to the terminal's width. +pub fn run_command_at( + cols: u16, mut cmd: portable_pty::CommandBuilder, args: &[&str], cwd: &Path, @@ -139,7 +153,7 @@ pub fn run_command( let pair = portable_pty::native_pty_system() .openpty(portable_pty::PtySize { rows: 24, - cols: 80, + cols, pixel_width: 0, pixel_height: 0, }) 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 93f020012f..edf4bbbdd4 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -83,15 +83,36 @@ //! real binary: byte-idempotent under the same grant, in-place URL refresh //! (the Gemfile option + the converged lock's remote) under a rotated one. //! -//! MANIFEST-LESS VEX (every installing arm, `manifestless_vex_matrix`): on -//! the fresh checkout the real bundler installed — hosted never writes a -//! `.socket/manifest.json` nor a ledger — `vex` attests `(redirected)` from -//! the lockfile wiring + the patch API (and so does the embedded -//! `apply --vex`); `--offline` is `record_unavailable` with zero requests; -//! the pair reverted to its registry version names the patch nowhere, even -//! under `--no-verify`. The main arm also proves the lock-only revert -//! (the Gemfile's option kept) re-converges on the next unfrozen install, -//! and on the next hosted scan. +//! MANIFEST-LESS VEX (every arm that installs a gem locked as its ruby +//! gem, `manifestless_vex_matrix`): on the fresh checkout the real bundler +//! installed — hosted never writes a `.socket/manifest.json` nor a ledger +//! — `vex` attests `(redirected)` from the lockfile wiring + the patch API +//! (and so does the embedded `apply --vex`); `--offline` is +//! `record_unavailable` with zero requests; the pair reverted to its +//! registry version names the patch nowhere, even under `--no-verify`. The +//! main arm also proves the lock-only revert (the Gemfile's option kept) +//! re-converges on the next unfrozen install, and on the next hosted scan. +//! +//! PLATFORM GEMS (the cases at the end of the file, on a lock the real +//! bundler wrote for a gem published as precompiled platform gems): the +//! gem's fix is one patch, whose reference lists every platform gem of the +//! version under a registry snapshot. Every locked build moves to that +//! registry once one of them is patched. A machine of a patched platform +//! installs the patched gem; a machine of a platform with no patched build +//! yet installs upstream's gem, which the registry answers with a redirect +//! to the upstream registry's file (here a second wiremock). The cases: +//! every locked build patched (with and without `CHECKSUMS`, with the ruby +//! entry beside the builds, and taken over by a vendored run), one build +//! patched (this machine in either role), none patched or one missing +//! from the list (nothing moves, quietly), a newer snapshot, `bundle lock +//! --add-platform` over a hosted lock, and a refresh whose download the +//! registry redirects. VEX names each locked build (`platform_vex_matrix`, +//! over the fresh checkout the real bundler installed): a patched build +//! under its own patch, a build on upstream's gem as affected, whichever of +//! the two this machine holds. A lock that names such a gem as its ruby +//! gem alone (for the `ruby` platform alone, and beside native platforms) +//! takes the registry without the snapshot level: bundler installs the +//! patched ruby gem, never the machine's unpatched platform gem. //! //! VERSION MATRIX: the arms run on bundler 1.17 → 4.x (the CHECKSUMS arm //! from 2.6, the CHECKSUMS-era floor; every other arm from 1.17). Pick the @@ -111,6 +132,7 @@ #[path = "common/mod.rs"] mod common; +use common::envelope::{event_triples, warning_codes}; use common::{binary, hermetic, hermetic_command}; use std::io::Write as _; @@ -2064,8 +2086,7 @@ async fn view_requests(fx: &RedirectFixture) -> usize { /// offline. async fn manifestless_vex_matrix(fx: &RedirectFixture, fresh: &Path) { use vex_e2e_common::{ - assert_absent, assert_attested, assert_not_attested, run_vex, strip_manifest, Marker, - VexVia, + assert_attested, assert_not_attested, run_vex, strip_manifest, Marker, VexVia, }; let bin = binary(); let lock = std::fs::read_to_string(fresh.join(fx.lock_name)).unwrap(); @@ -2112,15 +2133,24 @@ async fn manifestless_vex_matrix(fx: &RedirectFixture, fresh: &Path) { assert_not_attested(&out.envelope, PURL, "record_unavailable"); assert_eq!(request_count(fx).await, before, "--offline made requests"); - // 3. reverted to the registry pair (the patched install kept): no lock - // names the patch, and hosted mode keeps no ledger to remember it. + // 3. reverted to the registry pair (the patched install kept). + assert_reverted_pair_names_no_patch(fx, fresh); +} + +/// `fresh` with its manifest pair put back on the registry version, the +/// installed tree kept: no lock names the patch and hosted mode keeps no +/// ledger to remember it, so `vex` has nothing to attest +/// (`manifest_not_found`), with and without `--no-verify`, online and +/// offline. +fn assert_reverted_pair_names_no_patch(fx: &RedirectFixture, fresh: &Path) { + use vex_e2e_common::{assert_absent, run_vex}; std::fs::write(fresh.join(fx.gemfile_name), &fx.pristine_gemfile).unwrap(); std::fs::write(fresh.join(fx.lock_name), &fx.pristine_lock).unwrap(); for (offline, no_verify) in [(false, false), (false, true), (true, false), (true, true)] { let mut run = vex_run(fx); run.offline = offline; run.no_verify = no_verify; - let out = run_vex(&bin, fresh, &run); + let out = run_vex(&binary(), fresh, &run); let cell = format!("reverted offline={offline} no_verify={no_verify}"); assert_eq!(out.code, Some(2), "{cell}: {out}"); assert_eq!( @@ -6724,7 +6754,39 @@ async fn gem_hosted_scan_says_the_gem_is_held_at_its_version() { ); } -// ── precompiled platform gems ("prebuilds") ─────────────────────────── +// ── precompiled platform gems ───────────────────────────────────────── +// +// The fixture gem as bundler locks a gem that ships precompiled platform +// gems (`vuln-gem (1.0.0-arm64-darwin)`), against a stand-in for the patch +// service that answers as the wire contract has it: +// +// * the gem's fix is ONE patch, [`UUID`], the ruby gem's. Each patched +// platform gem has a patch of its own ([`build_uuid`]), which the search +// routes return beside the gem's and whose reference serves that gem +// (`tarball`) and its stub gemspec; +// * a reference request that carries `"gemBuilds": true` gets the gem +// patch's registry under a snapshot URL (`…//s/`) and the +// list of the version's gems: the ruby gem, each patched platform gem +// with its patch, each platform still on upstream's gem with none. A +// request without it gets the plain URL and no list; +// * the registry under a snapshot lists every gem of that list, serves +// the file of a patched build, and hands on the file of a platform +// with none: it relays upstream's own bytes (a 200). Where a case says +// so ([`PlatformProject::redirects`]) it answers that file with a 302 +// to the upstream registry's own file, which a client must follow too: +// here a second wiremock, the stand-in of that registry's file host, +// so nothing leaves the machine. A platform whose build is still being +// made is in neither. A snapshot answers as it did once a later one +// exists, except for a patched build that is withdrawn +// ([`PlatformProject::withdraw`]): the snapshot then no longer lists +// that build and refuses its file; +// * where a case says so ([`PlatformProject::offer_newer`]) the service +// offers another patch of the gem, [`NEWER_UUID`], with a list and a +// registry of its own, and keeps granting the one it offered before. +// +// "A machine of platform X" is this machine: bundler installs the platform +// gem of the host it runs on, so each case that turns on which platform is +// patched runs with this machine's platform in either role. /// One build a compact index serves: its gem, the token the index lists it /// under (`` for the ruby gem, `-` for a @@ -6735,13 +6797,42 @@ struct IndexBuild { token: String, deps: Vec, gem: Vec, + /// Where the download route sends the client instead of serving `gem`, + /// which the index still lists by its sha256. + redirect: Option, } /// [`mount_compact_index`] for gems published as several builds, the way /// rubygems.org serves a gem with precompiled platform variants: one /// `versions` line per gem listing every token, one `info/` line and -/// one `gems/-.gem` route per build. -async fn mount_build_index(server: &MockServer, base: &str, builds: &[IndexBuild]) { +/// one `gems/-.gem` route per build. `index_headers` go on +/// every index response. +async fn mount_build_index( + server: &MockServer, + base: &str, + builds: &[IndexBuild], + index_headers: &[(&str, &str)], +) { + mount_build_index_at(server, base, builds, index_headers, 5).await; +} + +/// [`mount_build_index`] at a wiremock priority (5 is what a mock has by +/// itself, and a lower number answers first): a listing mounted at a +/// lower number takes the place of one mounted before it under `base`. +async fn mount_build_index_at( + server: &MockServer, + base: &str, + builds: &[IndexBuild], + index_headers: &[(&str, &str)], + priority: u8, +) { + let index = |body: String| { + let mut response = compact_index_body(body); + for (name, value) in index_headers { + response = response.insert_header(*name, *value); + } + response + }; let mut names: Vec<&str> = Vec::new(); for build in builds { if !names.contains(&build.name) { @@ -6761,12 +6852,17 @@ async fn mount_build_index(server: &MockServer, base: &str, builds: &[IndexBuild sha256_hex(&build.gem) )); tokens.push(&build.token); + let file = match &build.redirect { + Some(location) => ResponseTemplate::new(302) + .insert_header("Location", location.as_str()) + .insert_header("Cache-Control", "no-store"), + None => ResponseTemplate::new(200) + .set_body_raw(build.gem.clone(), "application/octet-stream"), + }; Mock::given(method("GET")) .and(path(format!("{base}/gems/{name}-{}.gem", build.token))) - .respond_with( - ResponseTemplate::new(200) - .set_body_raw(build.gem.clone(), "application/octet-stream"), - ) + .respond_with(file) + .with_priority(priority) .mount(server) .await; } @@ -6778,18 +6874,21 @@ async fn mount_build_index(server: &MockServer, base: &str, builds: &[IndexBuild names_body.push_str(&format!("{name}\n")); Mock::given(method("GET")) .and(path(format!("{base}/info/{name}"))) - .respond_with(compact_index_body(info_body)) + .respond_with(index(info_body)) + .with_priority(priority) .mount(server) .await; } Mock::given(method("GET")) .and(path(format!("{base}/versions"))) - .respond_with(compact_index_body(versions_body)) + .respond_with(index(versions_body)) + .with_priority(priority) .mount(server) .await; Mock::given(method("GET")) .and(path(format!("{base}/names"))) - .respond_with(compact_index_body(names_body)) + .respond_with(index(names_body)) + .with_priority(priority) .mount(server) .await; } @@ -6808,7 +6907,7 @@ fn build_marked(lib: String) -> String { /// pure-Ruby gem whose gemspec sets `s.platform` is one. Every build /// carries the same `lib/vuln_gem.rb` (`lib`, the file the patch replaces) /// and its own `lib/vuln_gem/build.rb`, which says which build Ruby loaded: -/// a real prebuild differs from the ruby gem only outside the patched +/// a real platform gem differs from the ruby gem only outside the patched /// files, so one patch record's hashes hold for every build. fn build_gem_build(stage: &Path, tag: &str, platform: Option<&str>, lib: &str) -> Vec { let build = platform.unwrap_or("ruby"); @@ -6827,7 +6926,7 @@ fn build_gem_build(stage: &Path, tag: &str, platform: Option<&str>, lib: &str) - dir.join(format!("{DEP}.gemspec")), format!( "Gem::Specification.new do |s|\n s.name = \"{DEP}\"\n s.version = \"{DEP_VERSION}\"\n{platform_line} \ - s.summary = \"socket-patch hosted-gem prebuild fixture\"\n s.authors = [\"socket-patch e2e\"]\n \ + s.summary = \"socket-patch hosted-gem platform fixture\"\n s.authors = [\"socket-patch e2e\"]\n \ s.files = [\"lib/vuln_gem.rb\", \"lib/vuln_gem/build.rb\"]\n s.require_paths = [\"lib\"]\n \ s.add_dependency \"{TRANSITIVE}\", \">= 0\"\nend\n" ), @@ -6874,180 +6973,282 @@ fn own_and_foreign_platform() -> (String, String) { (own, foreign.to_string()) } -/// A gem bundler locks as precompiled platform builds, with a prebuild for -/// every platform the lock names, against the REAL bundler end to end: -/// -/// 1. upstream publishes the gem as a ruby gem AND as platform gems (this -/// machine's platform, and a foreign one); the real `bundle install` + -/// `bundle lock --add-platform` lock both platform builds and install -/// this machine's platform gem. `ruby_entry` picks the lock's -/// PLATFORMS: without `ruby` the lock holds the platform builds -/// alone, with it bundler keeps the ruby-platform -/// `name (version)` entry beside them (what bundler 4 locks by default -/// for a gem that also ships a ruby gem), and that entry moves too; -/// 2. the hosted scan moves BOTH entries into the patch registry's `GEM` -/// section, pins `DEPENDENCIES`, and (on a `CHECKSUMS` lock) sets each -/// entry to its own prebuild's sha256 — the lock the real `bundle lock` -/// writes for that Gemfile, byte for byte — and replaces the platform -/// copy bundler had installed with the patched platform gem; -/// 3. a fresh checkout's FROZEN `bundle install` fetches exactly this -/// machine's prebuild from the patch registry (never the ruby gem, so -/// nothing is compiled), leaves the lock byte-identical, and Ruby -/// loads the PATCHED file from the platform build; -/// 4. a re-scan is a no-op; -/// 5. `rollback` hands back the pre-scan pair byte for byte and puts the -/// installed copy back on the upstream platform gem; -/// 6. standalone `vex` attests the gem from the lock, hash-verified -/// against the installed platform build. -/// -/// With `takeover` (#2174), a vendored run takes the gem over before step -/// 5, which leaves the patched platform copy the hosted scan installed. -/// Step 5 is then a vendored unwind, and `remove` and `vendor --revert` -/// run over copies of the project as well: each must put the installed -/// platform copy back on the upstream platform gem. -async fn platform_prebuilds_install_frozen_and_roll_back( - tag: &str, - checksums_lock: bool, - ruby_entry: bool, - takeover: bool, -) { - // Bundler locks the specific platform's gem from 2.2; `CHECKSUMS` from - // 2.6. Vendor takes platform gems from a lock bundler 2.3 or newer wrote. - let floor = match (checksums_lock, takeover) { - (true, _) => (2, 6), - (false, true) => (2, 3), - (false, false) => (2, 2), - }; - let Some(bundler) = bundler_e2e::gate("e2e_redirect_gem_build", tag, floor, &|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 sha_of = |builds: &[IndexBuild], token: &str| { - let build = builds.iter().find(|b| b.token == token).expect("build"); - sha256_hex(&build.gem) - }; - let token = |platform: &str| format!("{DEP_VERSION}-{platform}"); +/// Shaped like a Socket API token, so that no run warns about the token +/// itself and a case can hold a run's warnings to an exact list. +const API_TOKEN: &str = "sktsec_00000000000000000000000000000000000000000000_api"; + +/// How the patch service has one platform gem of the fixture gem's version. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Has { + /// A patched build, under a patch of its own. + Patched, + /// No patched build: the registry lists upstream's own gem and hands + /// its file on (it relays the bytes, or redirects to the upstream + /// registry where the case says so). + Upstream, + /// A patched build is being made: no list names the platform yet. + Building, +} - // One wiremock: upstream registry, patch registry, patches API. - 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; - 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 })); +/// A newer patch of the fixture gem, which the service offers in place of +/// [`UUID`] once a case says so ([`PlatformProject::offer_newer`]). +const NEWER_UUID: &str = "8d9e0f1a-2b3c-4b2c-9d3e-4f5a6b7c8d9e"; + +/// The uuid of the patch of `platform`'s patched build. +fn build_uuid(platform: &str) -> String { + build_uuid_of(UUID, platform) +} + +/// [`build_uuid`] for the patched build of the gem patch `fix`. +fn build_uuid_of(fix: &str, platform: &str) -> String { + let hex = sha256_hex(format!("{fix}/{platform}").as_bytes()); + format!( + "{}-{}-4{}-8{}-{}", + &hex[..8], + &hex[8..12], + &hex[13..16], + &hex[17..20], + &hex[20..32] + ) +} + +/// A build's token in the lock, the compact index and its file name: +/// `` for the ruby gem, `-` for a platform gem. +fn build_token(platform: Option<&str>) -> String { + match platform { + Some(platform) => format!("{DEP_VERSION}-{platform}"), + None => DEP_VERSION.to_string(), } - 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: { +} + +/// The purl of a platform gem, as a run reports it and as its own patch's +/// record names it. +fn platform_purl(platform: &str) -> String { + format!("{PURL}?platform={platform}") +} + +/// One gem of the version as the registry lists it. +#[derive(Clone)] +struct ListedGem { + /// `None`: the ruby gem. + platform: Option, + /// The sha256 of the archive the registry serves for it. + sha256: String, + /// The patch of its patched build; `None`: upstream's own gem. + patch: Option, +} + +/// The key of the registry snapshot that lists `listed`: derived from the +/// list, so that the same list is the same URL. +fn snapshot_key(listed: &[ListedGem]) -> String { + let text: String = listed + .iter() + .map(|gem| { + format!( + "{} {} {}\n", + gem.platform.as_deref().unwrap_or("ruby"), + gem.sha256, + gem.patch.as_deref().unwrap_or("-") + ) + }) + .collect(); + sha256_hex(text.as_bytes())[..12].to_string() +} + +/// What the stand-in patch service answers from: the gems, and how it has +/// each platform gem now. +struct PlatformService { + /// The origin of the wiremock that plays the patch service. + api: String, + /// The origin of the stand-in of the upstream registry's file host. + files: String, + /// `lib/vuln_gem.rb` before and after the patch. + orig: String, + patched: String, + /// Upstream's gems, the patched builds and the stub gemspecs of the + /// patched builds, each by [`build_token`]. + upstream: std::collections::BTreeMap>, + builds: std::collections::BTreeMap>, + stubs: std::collections::BTreeMap>, + /// How the service has each platform gem; `None`: it has no list for + /// the gem (a patch of the ruby gem alone). + listing: std::sync::Mutex>>, +} + +impl PlatformService { + /// The sha256 of the gem of `platform`: its patched build, or + /// upstream's own. + fn sha(&self, platform: Option<&str>, patched: bool) -> String { + let gems = if patched { + &self.builds + } else { + &self.upstream + }; + sha256_hex(&gems[&build_token(platform)]) + } + + /// What the registry lists now: the patched ruby gem, then each + /// platform gem that is patched or on upstream's gem. + fn listed(&self) -> Option> { + let listing = self.listing.lock().unwrap().clone()?; + Some(self.listed_as(UUID, &listing)) + } + + /// What the registry of the gem patch `fix` lists when the service has + /// the platform gems as `listing` says: [`Self::listed`] for any patch + /// of the gem. + fn listed_as(&self, fix: &str, listing: &[(String, Has)]) -> Vec { + let mut listed = vec![ListedGem { + platform: None, + sha256: self.sha(None, true), + patch: Some(fix.to_string()), + }]; + for (platform, has) in listing { + let patched = match has { + Has::Patched => true, + Has::Upstream => false, + Has::Building => continue, + }; + listed.push(ListedGem { + sha256: self.sha(Some(platform), patched), + patch: patched.then(|| build_uuid_of(fix, platform)), + platform: Some(platform.clone()), + }); + } + listed + } + + /// The patches a search finds for the gem, as `(uuid, purl)`: the gem's + /// own, and the patch of each patched platform gem. + fn found(&self) -> Vec<(String, String)> { + let mut found = vec![(UUID.to_string(), PURL.to_string())]; + for gem in self.listed().unwrap_or_default() { + if let (Some(platform), Some(patch)) = (gem.platform, gem.patch) { + found.push((patch, platform_purl(&platform))); + } + } + found + } + + /// The path the artifact `leaf` of the patch `uuid` is served at. + fn artifact_path(uuid: &str, leaf: &str) -> String { + format!("/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{uuid}/{leaf}") + } + + /// The artifacts of the patch `uuid` of the gem of `platform`: the + /// patched gem and its stub gemspec. + fn artifacts(&self, uuid: &str, platform: Option<&str>) -> serde_json::Value { + let token = build_token(platform); + let (gem, stub) = (&self.builds[&token], &self.stubs[&token]); + let url = |ext: &str| { + let leaf = format!("{DEP}-{token}.{ext}"); + format!("{}{}", self.api, Self::artifact_path(uuid, &leaf)) + }; + serde_json::json!([ + { "kind": "tarball", "url": url("gem"), + "integrity": { "sha512": sri(gem), "sha256": sha256_hex(gem) } }, + { "kind": "gem-stub-gemspec", "url": url("gemspec"), + "integrity": { "sha512": sri(stub) } }, + ]) + } + + /// The reference of the gem's patch. `with_list`: the request asked for + /// the list of the gem's builds. + fn gem_reference(&self, with_list: bool) -> serde_json::Value { + let listed = self.listed().filter(|_| with_list); + self.reference_listing(UUID, listed.as_deref()) + } + + /// The reference of the gem patch `fix`, whose registry lists `listed` + /// (`None`: no list, and the registry URL without a snapshot). + fn reference_listing(&self, fix: &str, listed: Option<&[ListedGem]>) -> serde_json::Value { + let mut identifiers = serde_json::json!({ + "name": DEP, + "version": DEP_VERSION, + "gemChecksumSha256": self.sha(None, true), + }); + let mut index_url = format!("{}/patch-registry/gem/{TOKEN}/{fix}/", self.api); + if let Some(listed) = listed { + index_url = format!("{index_url}s/{}", snapshot_key(listed)); + let mut builds: Vec = listed + .iter() + .map(|gem| { + serde_json::json!({ + "platform": gem.platform.as_deref().unwrap_or("ruby"), + "gemChecksumSha256": gem.sha256, + "patchUuid": gem.patch, + }) + }) + .collect(); + builds.sort_by_key(|build| build["platform"].as_str().map(str::to_string)); + identifiers["gemBuilds"] = builds.into(); + } + let artifacts = self.artifacts(fix, None); + serde_json::json!({ + "status": "granted", + "url": artifacts[0]["url"], + "purl": PURL, + "artifacts": artifacts, + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": index_url, + "identifiers": identifiers, + } + }) + } + + /// The answer to one package reference request: every uuid it names + /// that is a patch here ([`Self::reference_of`]), and each that + /// `more` answers for. + fn references( + &self, + request: &wiremock::Request, + more: &dyn Fn(&str, bool) -> Option, + ) -> ResponseTemplate { + let asked: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default(); + let with_list = asked["gemBuilds"] == true; + let mut results = serde_json::Map::new(); + for uuid in asked["uuids"].as_array().into_iter().flatten() { + let Some(uuid) = uuid.as_str() else { continue }; + let reference = more(uuid, with_list).or_else(|| self.reference_of(uuid, with_list)); + if let Some(reference) = reference { + results.insert(uuid.to_string(), reference); + } + } + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "results": results })) + } + + /// The reference of the patch `uuid`, where it is the gem's patch or + /// the patch of one of its patched platform gems. `with_list`: the + /// request asked for the list of the gem's builds. + fn reference_of(&self, uuid: &str, with_list: bool) -> Option { + let found = self.found(); + let (_, purl) = found.iter().find(|(patch, _)| patch == uuid)?; + Some(match purl.split_once("?platform=") { + None => self.gem_reference(with_list), + Some((_, platform)) => { + let artifacts = self.artifacts(uuid, Some(platform)); + serde_json::json!({ "status": "granted", - "url": hosted_url, - "purl": PURL, + "url": artifacts[0]["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, + }) + } + + /// The record of the patch `uuid` of `purl`: every build carries the + /// one patched file. + fn view(&self, uuid: &str, purl: &str) -> serde_json::Value { + 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()), + "beforeHash": compute_git_sha256_from_bytes(self.orig.as_bytes()), + "afterHash": compute_git_sha256_from_bytes(self.patched.as_bytes()), } }, "vulnerabilities": { @@ -7059,605 +7260,3286 @@ async fn platform_prebuilds_install_frozen_and_roll_back( } }, "description": "x", "license": "MIT", "tier": "free" - }))) - .mount(&server) - .await; - - // 1. The project, locked and installed by the real bundler. - 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 = |dir: &Path, args: &[&str]| { - let out = bundle(dir, 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(&proj, &config_args); - if !checksums_lock && bundler.at_least(2, 6) { - bundle_ok( - &proj, - &["config", "set", "--local", "lockfile_checksums", "false"], - ); - } - bundle_ok(&proj, &["install"]); - bundle_ok(&proj, &["lock", "--add-platform", &foreign]); - // Bundler adds the `ruby` platform by itself when every locked gem has - // a ruby-platform gem (4.0.15 does); pin the arm's shape either way. - let locks_ruby = |lock: String| lock.contains("\nPLATFORMS\n") && lock.contains("\n ruby\n"); - let locked_ruby = locks_ruby(std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap()); - if ruby_entry && !locked_ruby { - bundle_ok(&proj, &["lock", "--add-platform", "ruby"]); - } else if !ruby_entry && locked_ruby { - bundle_ok(&proj, &["lock", "--remove-platform", "ruby"]); + }) } - if checksums_lock { - bundle_ok(&proj, &["lock", "--add-checksums"]); + + /// Mount the patches API, the artifacts of every patch, and the gem + /// patch's registry under its plain URL, which lists the patched ruby + /// gem alone. + async fn mount(self: &std::sync::Arc, server: &MockServer) { + let api = format!("/v0/orgs/{ORG}/patches"); + let service = self.clone(); + Mock::given(method("POST")) + .and(path(format!("{api}/batch"))) + .respond_with(move |_: &wiremock::Request| { + let patches: Vec = service + .found() + .iter() + .map(|(uuid, purl)| { + serde_json::json!({ + "uuid": uuid, "purl": purl, "tier": "free", + "cveIds": [], "ghsaIds": [], "severity": "high", + "title": "gem platform capstone fixture" + }) + }) + .collect(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [{ "purl": PURL, "patches": patches }], + "canAccessPaidPatches": false, + })) + }) + .mount(server) + .await; + // A platform gem's patch is published after the gem's: a search + // ranks it first. + let service = self.clone(); + Mock::given(method("GET")) + .and(path_regex(format!("^{api}/by-package/.+$"))) + .respond_with(move |_: &wiremock::Request| { + let patches: Vec = service + .found() + .iter() + .rev() + .map(|(uuid, purl)| { + let published = match uuid.as_str() { + UUID => "2026-01-01T00:00:00Z", + _ => "2026-02-01T00:00:00Z", + }; + serde_json::json!({ + "uuid": uuid, "purl": purl, "publishedAt": published, + "description": "x", "license": "MIT", "tier": "free", + "vulnerabilities": {} + }) + }) + .collect(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": patches, + "canAccessPaidPatches": false, + })) + }) + .mount(server) + .await; + let service = self.clone(); + Mock::given(method("POST")) + .and(path(format!("{api}/package"))) + .respond_with(move |request: &wiremock::Request| { + service.references(request, &|_, _| None) + }) + .mount(server) + .await; + for token in self.builds.keys() { + let platform = token.strip_prefix(&format!("{DEP_VERSION}-")); + let (uuid, purl) = match platform { + Some(platform) => (build_uuid(platform), platform_purl(platform)), + None => (UUID.to_string(), PURL.to_string()), + }; + Mock::given(method("GET")) + .and(path(format!("{api}/view/{uuid}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(self.view(&uuid, &purl))) + .mount(server) + .await; + for (ext, bytes) in [ + ("gem", &self.builds[token]), + ("gemspec", &self.stubs[token]), + ] { + let leaf = format!("{DEP}-{token}.{ext}"); + Mock::given(method("GET")) + .and(path(Self::artifact_path(&uuid, &leaf))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes.clone())) + .mount(server) + .await; + } + } + let ruby_gem = IndexBuild { + name: DEP, + token: build_token(None), + deps: vec![format!("{TRANSITIVE}:>= 0")], + gem: self.builds[&build_token(None)].clone(), + redirect: None, + }; + let plain = format!("/patch-registry/gem/{TOKEN}/{UUID}"); + mount_build_index(server, &plain, &[ruby_gem], REGISTRY_INDEX_HEADERS).await; } - let pristine_gemfile = std::fs::read(proj.join("Gemfile")).unwrap(); - let pristine_lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); - for platform in platforms { - assert!( - pristine_lock.contains(&format!(" {DEP} ({})\n", token(platform))), - "the fixture lock must pin the {platform} build:\n{pristine_lock}" - ); +} + +/// What the patch registry sends with every index response. +const REGISTRY_INDEX_HEADERS: &[(&str, &str)] = &[("Cache-Control", "public, no-cache")]; + +/// How the fixture project's lock names the fixture gem, of which upstream +/// publishes a ruby gem and platform gems. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Locked { + /// As the platform gems of this machine's platform and of a foreign + /// one. `ruby_entry` picks the lock's PLATFORMS: without `ruby` the + /// lock holds the platform builds alone, with it bundler keeps the + /// ruby-platform `name (version)` entry beside them (what bundler 4 + /// locks by default for a gem that also ships a ruby gem). + Builds { ruby_entry: bool }, + /// As its ruby-platform gem alone, for the `ruby` platform alone: the + /// lock of a bundler that was told to take ruby gems + /// (`force_ruby_platform`), a setting the checkout does not carry. For + /// such a lock bundler installs the platform gem of the machine where + /// the gem's source lists one. + RubyAlone, + /// As its ruby-platform gem alone, with native platforms in PLATFORMS: + /// the Gemfile declares the gem `force_ruby_platform: true`. + RubyForced, +} + +/// A project the real bundler locked to the fixture gem's platform gems of +/// this machine's platform ([`Self::own`]) and of one it is not +/// ([`Self::foreign`]) and installed, with the stand-in patch service. (Or +/// to its ruby-platform gem alone: [`Locked`].) +struct PlatformProject { + /// The project, its pair before any scan, and the wiremock that plays + /// the upstream registry, the patch registry and the patches API. + /// `index_url` is the registry of the listing served last. + fx: RedirectFixture, + /// The stand-in of the upstream registry's file host: where the patch + /// registry sends a client for a platform it has no patched build of, + /// when it redirects. + files: MockServer, + /// The registry answers the file of a platform with no patched build + /// with a 302 to [`Self::files`], for the snapshots served from now + /// on. Off: it relays upstream's bytes itself. + redirects: bool, + service: std::sync::Arc, + /// The registry snapshots mounted so far, by path, each with what it + /// lists. + snapshots: std::collections::BTreeMap>, + own: String, + foreign: String, + /// The lock has a `CHECKSUMS` section. + checksums: bool, + /// The lock names the ruby-platform gem beside the platform builds. + ruby_entry: bool, +} + +impl PlatformProject { + /// [`Self::start_locked`] with a lock that names the platform gems of + /// this machine's platform and of a foreign one ([`Locked::Builds`]). + async fn start( + tag: &str, + floor: (u32, u32), + checksums: bool, + ruby_entry: bool, + more: &[&str], + ) -> Option { + Self::start_locked(tag, floor, checksums, Locked::Builds { ruby_entry }, more).await } - let ruby_beside = pristine_lock.contains(&format!(" {DEP} ({DEP_VERSION})\n")); - assert_eq!( - ruby_beside, ruby_entry, - "the fixture lock's ruby-platform entry must match the arm:\n{pristine_lock}" - ); - assert_eq!( - pristine_lock.contains("\nCHECKSUMS\n"), - checksums_lock, - "fixture lock CHECKSUMS presence must match the arm:\n{pristine_lock}" - ); - let own_leaf = format!("{DEP}-{DEP_VERSION}-{own}"); - let warm_lib = fresh_installed_lib(&proj, &own_leaf, "vuln_gem.rb"); - assert_eq!( - std::fs::read_to_string(&warm_lib).expect("bundler installed the platform gem"), - orig, - "premise: the upstream platform gem is installed before the scan" - ); - // 2. The hosted scan. - let api = server.uri(); - let proj_str = proj.to_str().expect("utf8 tmp path"); - let scan = || { - run_socket( - &proj, - &[ - "scan", - "--mode", - "hosted", - "--json", - "--yes", - "--cwd", - proj_str, - "--api-url", - &api, - "--org", - ORG, - "--api-token", - "fake", - "--vex", - "out.vex.json", - "--vex-product", - PRODUCT, - ], + /// Build the gems, start both servers, and let the real bundler lock + /// and install the project. Upstream publishes the gem as a ruby gem + /// and as platform gems for this machine's platform, a foreign one and + /// each of `more`; `locked` says which of them the lock names. `None`: + /// the bundler is below `floor` or missing (said on stdout). + async fn start_locked( + tag: &str, + floor: (u32, u32), + checksums: bool, + locked: Locked, + more: &[&str], + ) -> Option { + let ruby_entry = locked == (Locked::Builds { ruby_entry: true }); + let bundler = bundler_e2e::gate("e2e_redirect_gem_build", tag, floor, &|c| { + cache_env::isolate(c); + })?; + let (own, foreign) = own_and_foreign_platform(); + let tmp = tempfile::tempdir().unwrap(); + let stage = tmp.path().join("gem-stage"); + let (orig, patched) = (build_marked(orig_lib()), build_marked(patched_lib())); + let platforms = [own.as_str(), foreign.as_str()]; + let published = std::iter::once(None) + .chain(platforms.into_iter().map(Some)) + .chain(more.iter().copied().map(Some)); + let mut upstream = std::collections::BTreeMap::new(); + let mut builds = std::collections::BTreeMap::new(); + let mut stubs = std::collections::BTreeMap::new(); + for platform in published { + let token = build_token(platform); + upstream.insert( + token.clone(), + build_gem_build(&stage, "orig", platform, &orig), + ); + let build = build_gem_build(&stage, "patched", platform, &patched); + stubs.insert(token.clone(), stub_gemspec(&build)); + builds.insert(token, build); + } + + let server = MockServer::start().await; + let files = MockServer::start().await; + let mut index: Vec = upstream + .iter() + .map(|(token, gem)| IndexBuild { + name: DEP, + token: token.clone(), + deps: vec![format!("{TRANSITIVE}:>= 0")], + gem: gem.clone(), + redirect: None, + }) + .collect(); + index.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, &[]), + redirect: None, + }); + mount_build_index(&server, "/upstream", &index, &[]).await; + for (token, gem) in &upstream { + Mock::given(method("GET")) + .and(path(format!("/gems/{DEP}-{token}.gem"))) + .respond_with( + ResponseTemplate::new(200) + .set_body_raw(gem.clone(), "application/octet-stream"), + ) + .mount(&files) + .await; + } + let service = std::sync::Arc::new(PlatformService { + api: server.uri(), + files: files.uri(), + orig: orig.clone(), + patched: patched.clone(), + upstream, + builds, + stubs, + listing: std::sync::Mutex::new(None), + }); + service.mount(&server).await; + + // The project, locked and installed by the real bundler. + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + let declaration = match locked { + Locked::RubyForced => format!("gem \"{DEP}\", force_ruby_platform: true"), + Locked::Builds { .. } | Locked::RubyAlone => format!("gem \"{DEP}\""), + }; + std::fs::write( + proj.join("Gemfile"), + format!("source \"{}/upstream\"\n\n{declaration}\n", server.uri()), ) + .unwrap(); + 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(&proj, &config_args); + if !checksums && bundler.at_least(2, 6) { + bundle_ok( + &proj, + &["config", "set", "--local", "lockfile_checksums", "false"], + ); + } + let prefers_ruby_gems = ["--local", "force_ruby_platform"]; + if locked == Locked::RubyAlone { + let mut set = vec!["config", "set"]; + set.extend(prefers_ruby_gems); + set.push("true"); + bundle_ok(&proj, &set); + } + bundle_ok(&proj, &["install"]); + // The PLATFORMS section of the lock as it stands. + let locked_platforms = || -> Vec { + let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + let platforms = lock.split("\nPLATFORMS\n").nth(1).unwrap_or_default(); + let platforms = platforms.split("\n\n").next().unwrap_or_default(); + platforms + .lines() + .map(|line| line.trim().to_string()) + .collect() + }; + if let Locked::Builds { .. } = locked { + bundle_ok(&proj, &["lock", "--add-platform", &foreign]); + // Bundler adds platforms by itself to a lock it creates (4.0.15 + // does): `ruby` when every locked gem has a ruby-platform gem, + // and the common platforms every locked gem has a gem for. Pin + // the shape either way. + let locks = |platform: &str| locked_platforms().iter().any(|p| p == platform); + if ruby_entry && !locks("ruby") { + bundle_ok(&proj, &["lock", "--add-platform", "ruby"]); + } else if !ruby_entry && locks("ruby") { + bundle_ok(&proj, &["lock", "--remove-platform", "ruby"]); + } + for platform in more { + if locks(platform) { + bundle_ok(&proj, &["lock", "--remove-platform", platform]); + } + } + } + if checksums { + bundle_ok(&proj, &["lock", "--add-checksums"]); + } + if locked == Locked::RubyAlone { + // The checkout does not carry the setting the lock was made + // under: from here on bundler takes the machine's platform gem + // for the plain entry where the gem's source lists one. + let mut unset = vec!["config", "unset"]; + unset.extend(prefers_ruby_gems); + bundle_ok(&proj, &unset); + } + let pristine_gemfile = std::fs::read(proj.join("Gemfile")).unwrap(); + let pristine_lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + let entries = pristine_lock.matches(&format!(" {DEP} (")).count(); + let ruby_gem_locked = pristine_lock.contains(&format!(" {DEP} ({DEP_VERSION})\n")); + match locked { + Locked::Builds { .. } => { + for platform in platforms { + let token = build_token(Some(platform)); + assert!( + pristine_lock.contains(&format!(" {DEP} ({token})\n")), + "the fixture lock must pin the {platform} build:\n{pristine_lock}" + ); + } + assert_eq!( + ruby_gem_locked, ruby_entry, + "the fixture lock's ruby-platform entry must match the case:\n{pristine_lock}" + ); + assert_eq!( + entries, + 2 + usize::from(ruby_entry), + "the fixture lock must name no other build:\n{pristine_lock}" + ); + } + Locked::RubyAlone | Locked::RubyForced => { + assert!( + ruby_gem_locked && entries == 1, + "the fixture lock must name the ruby-platform gem alone:\n{pristine_lock}" + ); + let native = locked_platforms().iter().any(|p| p != "ruby"); + assert_eq!( + native, + locked == Locked::RubyForced, + "the fixture lock's PLATFORMS must match the case:\n{pristine_lock}" + ); + } + } + assert_eq!( + pristine_lock.contains("\nCHECKSUMS\n"), + checksums, + "fixture lock CHECKSUMS presence must match the case:\n{pristine_lock}" + ); + let project = PlatformProject { + fx: RedirectFixture { + tmp, + proj, + index_url: String::new(), + gemfile_name: "Gemfile", + lock_name: "Gemfile.lock", + patched: patched.into_bytes(), + pristine_gemfile, + pristine_lock: pristine_lock.into_bytes(), + bundler, + _server: server, + }, + files, + redirects: false, + service, + snapshots: std::collections::BTreeMap::new(), + own, + foreign, + checksums, + ruby_entry, + }; + let warm = match locked { + Locked::Builds { .. } => project.installed_lib(&project.fx.proj), + Locked::RubyAlone | Locked::RubyForced => project.installed_ruby_lib(&project.fx.proj), + }; + assert_eq!( + std::fs::read_to_string(warm).expect("bundler installed the gem the lock names"), + orig, + "premise: upstream's gem is installed before the scan" + ); + Some(project) + } + + fn api(&self) -> String { + self.fx._server.uri() + } + + fn pristine_lock(&self) -> String { + String::from_utf8(self.fx.pristine_lock.clone()).unwrap() + } + + fn pristine_gemfile(&self) -> String { + String::from_utf8(self.fx.pristine_gemfile.clone()).unwrap() + } + + fn lock(&self) -> String { + std::fs::read_to_string(self.fx.proj.join("Gemfile.lock")).unwrap() + } + + fn gemfile(&self) -> String { + std::fs::read_to_string(self.fx.proj.join("Gemfile")).unwrap() + } + + /// `--` of this machine's platform gem. + fn own_leaf(&self) -> String { + format!("{DEP}-{}", build_token(Some(&self.own))) + } + + /// `lib/vuln_gem.rb` of this machine's platform gem as bundler + /// installed it under `dir`. + fn installed_lib(&self, dir: &Path) -> PathBuf { + fresh_installed_lib(dir, &self.own_leaf(), "vuln_gem.rb") + } + + /// `lib/vuln_gem.rb` of the ruby-platform gem as bundler installed it + /// under `dir`. + fn installed_ruby_lib(&self, dir: &Path) -> PathBuf { + fresh_installed_lib(dir, &format!("{DEP}-{DEP_VERSION}"), "vuln_gem.rb") + } + + /// `dir` holds the patched ruby-platform gem and no platform gem of + /// this machine, and Ruby loads the patched file from the ruby gem. + fn assert_patched_ruby_gem_installed(&self, dir: &Path) { + assert_eq!( + std::fs::read_to_string(self.installed_ruby_lib(dir)) + .expect("the ruby-platform gem is installed"), + self.service.patched, + "the install holds the file of the patched ruby gem" + ); + assert!( + !self.installed_lib(dir).exists(), + "no platform gem of this machine is installed for the plain entry" + ); + let probe = bundle( + dir, + &[ + "exec", + "ruby", + "-e", + "require \"vuln_gem\"\nputs VulnGem.status\nputs VulnGem::BUILD\nputs TinyDep::VALUE\nputs $LOADED_FEATURES.grep(%r{/vuln_gem\\.rb\\z})", + ], + ); + assert!( + probe.status.success(), + "bundle exec require probe failed.\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&probe.stdout), + String::from_utf8_lossy(&probe.stderr), + ); + let out = String::from_utf8_lossy(&probe.stdout).into_owned(); + let lines: Vec<&str> = out.lines().collect(); + assert_eq!( + lines.len(), + 4, + "status, build, dep and the loaded file:\n{out}" + ); + assert_eq!( + lines[..3], + [patched_marker().as_str(), "ruby", "tiny-ok"], + "Ruby loads the patched file, from the ruby gem:\n{out}" + ); + assert!( + lines[3].contains(&format!("/gems/{DEP}-{DEP_VERSION}/lib/")), + "vuln_gem.rb loads from the installed ruby gem:\n{out}" + ); + } + + /// From now on the service has the platform gems as `listing` says + /// (`None`: it has no list for the gem), and its registry answers under + /// the snapshot of that listing beside every earlier one. Returns the + /// registry URL as a lock names it. + async fn serve(&mut self, listing: Option<&[(&str, Has)]>) -> String { + *self.service.listing.lock().unwrap() = listing.map(|listing| { + listing + .iter() + .map(|(platform, has)| (platform.to_string(), *has)) + .collect() + }); + let mut base = format!("/patch-registry/gem/{TOKEN}/{UUID}"); + if let Some(listed) = self.service.listed() { + base = self.mount_snapshot(UUID, listed).await; + } + self.fx.index_url = format!("{}{base}/", self.api()); + self.fx.index_url.clone() + } + + /// The registry of the gem patch `fix` answers under the snapshot that + /// lists `listed`, from now on. Returns the snapshot's path. + async fn mount_snapshot(&mut self, fix: &str, listed: Vec) -> String { + let base = format!( + "/patch-registry/gem/{TOKEN}/{fix}/s/{}", + snapshot_key(&listed) + ); + if !self.snapshots.contains_key(&base) { + let index = self.index_builds(&listed); + mount_build_index(&self.fx._server, &base, &index, REGISTRY_INDEX_HEADERS).await; + self.snapshots.insert(base.clone(), listed); + } + base + } + + /// What a registry snapshot that lists `listed` serves: the patched + /// build of a gem that has a patch, and upstream's own gem (relayed, + /// or redirected to where [`Self::redirects`] says) of one that has + /// none. + fn index_builds(&self, listed: &[ListedGem]) -> Vec { + listed + .iter() + .map(|gem| { + let token = build_token(gem.platform.as_deref()); + let (gems, redirect) = match gem.patch { + Some(_) => (&self.service.builds, None), + None => ( + &self.service.upstream, + self.redirects + .then(|| format!("{}/gems/{DEP}-{token}.gem", self.service.files)), + ), + }; + IndexBuild { + name: DEP, + deps: vec![format!("{TRANSITIVE}:>= 0")], + gem: gems[&token].clone(), + token, + redirect, + } + }) + .collect() + } + + /// The patched build of `platform` is withdrawn from the registry + /// snapshot `registry` (a URL a lock names): from now on that snapshot + /// lists every other gem it listed and not this one, and refuses its + /// file. A snapshot never changes in any other way. + async fn withdraw(&self, registry: &str, platform: &str) { + let base = registry[self.api().len()..].trim_end_matches('/'); + let listed = self + .snapshots + .get(base) + .unwrap_or_else(|| panic!("no snapshot was served at {registry}")); + let remaining: Vec = listed + .iter() + .filter(|gem| gem.platform.as_deref() != Some(platform)) + .cloned() + .collect(); + assert_eq!( + remaining.len() + 1, + listed.len(), + "the snapshot lists {platform}" + ); + let server = &self.fx._server; + let index = self.index_builds(&remaining); + mount_build_index_at(server, base, &index, REGISTRY_INDEX_HEADERS, 1).await; + let file = format!("{base}/gems/{DEP}-{}.gem", build_token(Some(platform))); + Mock::given(method("GET")) + .and(path(file)) + .respond_with(ResponseTemplate::new(404)) + .with_priority(1) + .mount(server) + .await; + } + + /// From now on the service offers another patch of the gem + /// ([`NEWER_UUID`]) in place of the one it offered: every search finds + /// that patch alone, its reference lists the platform gems as + /// `listing` says (each patched build under a patch of its own), and + /// its registry answers under the snapshot of that listing. The patch + /// offered before stays granted, with the reference [`Self::serve`] + /// last gave it. Returns the newer patch's registry URL as a lock + /// names it. + async fn offer_newer(&mut self, listing: &[(&str, Has)]) -> String { + let listing: Vec<(String, Has)> = listing + .iter() + .map(|(platform, has)| (platform.to_string(), *has)) + .collect(); + let listed = self.service.listed_as(NEWER_UUID, &listing); + let base = self.mount_snapshot(NEWER_UUID, listed.clone()).await; + let server = &self.fx._server; + let api = format!("/v0/orgs/{ORG}/patches"); + Mock::given(method("POST")) + .and(path(format!("{api}/batch"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [{ "purl": PURL, "patches": [{ + "uuid": NEWER_UUID, "purl": PURL, "tier": "free", + "cveIds": [], "ghsaIds": [], "severity": "high", + "title": "gem platform capstone fixture, a newer patch", + }]}], + "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path_regex(format!("^{api}/by-package/.+$"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": [{ + "uuid": NEWER_UUID, "purl": PURL, "publishedAt": "2026-03-01T00:00:00Z", + "description": "x", "license": "MIT", "tier": "free", + "vulnerabilities": {} + }], + "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(server) + .await; + let service = self.service.clone(); + Mock::given(method("POST")) + .and(path(format!("{api}/package"))) + .respond_with(move |request: &wiremock::Request| { + service.references(request, &|uuid, with_list| { + let listed = with_list.then_some(&listed[..]); + (uuid == NEWER_UUID).then(|| service.reference_listing(NEWER_UUID, listed)) + }) + }) + .with_priority(1) + .mount(server) + .await; + let view = self.service.view(NEWER_UUID, PURL); + Mock::given(method("GET")) + .and(path(format!("{api}/view/{NEWER_UUID}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(view)) + .mount(server) + .await; + let token = build_token(None); + for (ext, bytes) in [ + ("gem", &self.service.builds[&token]), + ("gemspec", &self.service.stubs[&token]), + ] { + let leaf = format!("{DEP}-{token}.{ext}"); + Mock::given(method("GET")) + .and(path(PlatformService::artifact_path(NEWER_UUID, &leaf))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes.clone())) + .mount(server) + .await; + } + self.fx.index_url = format!("{}{base}/", self.api()); + self.fx.index_url.clone() + } + + /// `socket-patch --mode hosted` over `dir` against the + /// stand-in service, with `extra` arguments. + fn hosted(&self, dir: &Path, command: &[&str], extra: &[&str]) -> (i32, String, String) { + let api = self.api(); + let mut args: Vec<&str> = command.to_vec(); + args.extend([ + "--mode", + "hosted", + "--yes", + "--cwd", + dir.to_str().expect("utf8 tmp path"), + "--api-url", + &api, + "--org", + ORG, + "--api-token", + API_TOKEN, + ]); + args.extend_from_slice(extra); + run_socket(dir, &args) + } + + /// A `--json` hosted scan of the project, which must exit 0: its + /// envelope. + fn scan(&self, extra: &[&str]) -> serde_json::Value { + let mut args = vec!["--json"]; + args.extend_from_slice(extra); + let (code, stdout, stderr) = self.hosted(&self.fx.proj, &["scan"], &args); + assert_eq!( + code, 0, + "scan failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("scan --json is not JSON: {e}\nstdout:\n{stdout}")) + } + + /// A scan that leaves the gem where it is, quietly: exit 0, both files + /// byte-identical, no warning, and one counted `skipped` event under + /// `code` whose reason is `line`; a person reads that one line on + /// stdout, and nothing on stderr warns or names the gem. The copy + /// bundler installed stays upstream's. + fn assert_left_alone(&self, code: &str, line: &str) { + let untouched = |when: &str| { + assert_eq!(self.lock(), self.pristine_lock(), "{when}: the lock"); + assert_eq!( + self.gemfile(), + self.pristine_gemfile(), + "{when}: the Gemfile" + ); + assert_eq!( + std::fs::read_to_string(self.installed_lib(&self.fx.proj)).unwrap(), + self.service.orig, + "{when}: the installed copy" + ); + }; + let env = self.scan(&[]); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + hosted_events(&env), + [serde_json::json!({ + "action": "skipped", "purl": PURL, "uuid": UUID, + "errorCode": code, "reason": line, + "details": { "mode": "hosted" }, + })], + "{env}" + ); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + let summary = &env["summary"]; + assert_eq!( + (&summary["applied"], &summary["skipped"], &summary["failed"]), + ( + &serde_json::json!(0), + &serde_json::json!(1), + &serde_json::json!(0) + ), + "{env}" + ); + assert_eq!(env["redirect"]["rewrittenFiles"], serde_json::json!([])); + untouched("--json"); + + let (code, stdout, stderr) = self.hosted(&self.fx.proj, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains(&format!("\n{line}\n")), "{stdout}"); + assert!( + !stderr.contains("No patches could be switched") + && !stderr.contains("Warning") + && !stderr.contains(DEP), + "nothing on stderr names it:\n{stderr}" + ); + untouched("for a person"); + } + + /// The project's pair as a hosted scan must leave it for the registry + /// `index_url`, where `pinned` says of each locked platform whether its + /// patched build is what the lock pins: the Gemfile's declaration with + /// the `source:` option, every build of the gem under the registry's + /// `GEM` section and none upstream, each `CHECKSUMS` entry on the sha256 + /// the registry serves for it, and `DEPENDENCIES` source-pinned. + /// Returns the lock. + fn assert_hosted_pair(&self, index_url: &str, pinned: &[(&str, bool)]) -> String { + assert_eq!( + self.gemfile(), + with_source_option( + &self.pristine_gemfile(), + &format!("gem \"{DEP}\""), + index_url + ), + "the Gemfile edit is the one a ruby gem gets" + ); + let lock = self.lock(); + let registry_section = lock + .split("\n\n") + .find(|section| section.contains(&format!("remote: {index_url}\n"))) + .unwrap_or_else(|| panic!("no GEM section of {index_url}:\n{lock}")); + let pristine = self.pristine_lock(); + for (platform, patched) in pinned { + let token = build_token(Some(platform)); + assert!( + registry_section.contains(&format!(" {DEP} ({token})\n {TRANSITIVE}")), + "the {platform} build is under the patch registry with its sub-lines:\n{lock}" + ); + if self.checksums { + let pin = format!( + " {DEP} ({token}) sha256={}\n", + self.service.sha(Some(platform), *patched) + ); + assert!( + lock.contains(&pin), + "CHECKSUMS pins the {platform} build to the sha256 the registry serves for \ + it (patched: {patched}):\n{lock}" + ); + assert_eq!( + pristine.contains(&pin), + !*patched, + "a build on upstream's gem keeps the sha256 it had, a patched one does not" + ); + } + } + let entries = |text: &str| text.matches(&format!(" {DEP} (")).count(); + assert_eq!( + entries(&lock), + entries(&pristine), + "every build, each listed once:\n{lock}" + ); + assert_eq!( + entries(registry_section), + entries(&lock), + "all of them under the patch registry:\n{lock}" + ); + if self.checksums && pristine.contains(&format!(" {DEP} ({DEP_VERSION})\n")) { + let ruby_sha = self.service.sha(None, true); + assert!( + lock.contains(&format!(" {DEP} ({DEP_VERSION}) sha256={ruby_sha}\n")), + "CHECKSUMS pins the ruby-platform entry to the patched ruby gem:\n{lock}" + ); + } + assert!( + lock.contains(&format!("\nDEPENDENCIES\n {DEP}!\n")), + "DEPENDENCIES is source-pinned:\n{lock}" + ); + lock + } + + /// The lock the host bundler itself writes for `gemfile` over the lock + /// `before`, in a scratch dir named `name`. + fn bundler_lock(&self, name: &str, gemfile: &str, before: &str) -> String { + let relock = self.fx.tmp.path().join(name); + std::fs::create_dir_all(&relock).unwrap(); + std::fs::write(relock.join("Gemfile"), gemfile).unwrap(); + std::fs::write(relock.join("Gemfile.lock"), before).unwrap(); + copy_dir_recursive(&self.fx.proj.join(".bundle"), &relock.join(".bundle")); + bundle_ok(&relock, &["lock"]); + std::fs::read_to_string(relock.join("Gemfile.lock")).unwrap() + } + + /// A fresh checkout of the committed pair, named `name`, after the + /// real `bundle install` with `envs` succeeded there and left the lock + /// byte-identical. + fn install_fresh(&self, name: &str, envs: &[(&str, &str)]) -> PathBuf { + let fresh = stage_fresh_checkout(&self.fx, name); + let install = bundle_env(&fresh, &["install"], envs); + assert!( + install.status.success(), + "`bundle install` ({envs:?}) of a fresh checkout must succeed.\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&install.stdout), + String::from_utf8_lossy(&install.stderr), + ); + assert_eq!( + std::fs::read_to_string(fresh.join("Gemfile.lock")).unwrap(), + self.lock(), + "`bundle install` ({envs:?}) must leave the lock byte-identical (bundler {})", + self.fx.bundler.version + ); + fresh + } + + /// `dir` holds this machine's platform gem, the patched build or + /// upstream's own as `patched` says, never the ruby gem, and Ruby loads + /// that file from that platform gem. + fn assert_installed(&self, dir: &Path, patched: bool) { + let (lib, status) = if patched { + (&self.service.patched, patched_marker()) + } else { + (&self.service.orig, "VULNERABLE".to_string()) + }; + assert_eq!( + &std::fs::read_to_string(self.installed_lib(dir)) + .expect("the platform gem is installed"), + lib, + "the install holds the file of the {} platform gem", + if patched { "patched" } else { "upstream" } + ); + assert!( + !fresh_installed_lib(dir, &format!("{DEP}-{DEP_VERSION}"), "vuln_gem.rb").exists(), + "the ruby-platform gem is not what bundler installs" + ); + let probe = bundle( + dir, + &[ + "exec", + "ruby", + "-e", + "require \"vuln_gem\"\nputs VulnGem.status\nputs VulnGem::BUILD\nputs TinyDep::VALUE\nputs $LOADED_FEATURES.grep(%r{/vuln_gem\\.rb\\z})", + ], + ); + assert!( + probe.status.success(), + "bundle exec require probe failed.\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&probe.stdout), + String::from_utf8_lossy(&probe.stderr), + ); + let out = String::from_utf8_lossy(&probe.stdout).into_owned(); + let lines: Vec<&str> = out.lines().collect(); + assert_eq!( + lines.len(), + 4, + "status, build, dep and the loaded file:\n{out}" + ); + assert_eq!( + lines[..3], + [status.as_str(), self.own.as_str(), "tiny-ok"], + "Ruby loads that file, from this machine's platform build:\n{out}" + ); + assert!( + lines[3].contains("/vendor/bundle/") + && lines[3].contains(&format!("/gems/{}/lib/", self.own_leaf())), + "vuln_gem.rb loads from the installed platform gem:\n{out}" + ); + } + + /// The premise of a withdrawn build: a fresh checkout of the project's + /// pair, which is `lock`, can no longer be installed on this machine, + /// frozen or not. The install fails, leaves no build of this machine's + /// platform behind, and leaves the lock as it is. (What bundler says of + /// it, and under which exit code, differs with its release and with + /// which locked build it names first, and is not held to anything.) + fn assert_no_longer_installs(&self, lock: &str) { + for (name, envs) in [ + ("broken-frozen", &[("BUNDLE_FROZEN", "true")][..]), + ("broken", &[]), + ] { + let broken = stage_fresh_checkout(&self.fx, name); + let install = bundle_env(&broken, &["install"], envs); + assert!( + !install.status.success(), + "premise: `bundle install` ({envs:?}) of the unchanged pair fails on this machine \ + (bundler {}):\n{}{}", + self.fx.bundler.version, + String::from_utf8_lossy(&install.stdout), + String::from_utf8_lossy(&install.stderr) + ); + assert!( + !self.installed_lib(&broken).exists(), + "({envs:?}) it installs no build of this platform" + ); + assert_eq!( + std::fs::read_to_string(broken.join("Gemfile.lock")).unwrap(), + lock, + "({envs:?}) and leaves the lock as it is" + ); + } + } + + /// How many requests the patch service and the upstream file host have + /// answered: a mark for [`Self::fetched_since`]. + async fn mark(&self) -> (usize, usize) { + ( + request_paths(&self.fx._server, 0).await.len(), + request_paths(&self.files, 0).await.len(), + ) + } + + /// The gem files asked for since `mark`: of the patch registry (each + /// with the snapshot path it was asked under), and of the upstream file + /// host. + async fn fetched_since(&self, mark: (usize, usize)) -> (Vec, Vec) { + let registry = request_paths(&self.fx._server, mark.0) + .await + .into_iter() + .filter(|path| path.starts_with("/patch-registry/") && path.contains("/gems/")) + .collect(); + let files = request_paths(&self.files, mark.1) + .await + .into_iter() + .filter_map(|path| path.strip_prefix("/gems/").map(str::to_string)) + .collect(); + (registry, files) + } + + /// The index documents (`info/`) of patch registries asked for + /// since `mark`, each with the snapshot path it was asked under. + async fn indexes_since(&self, mark: (usize, usize)) -> Vec { + let asked = request_paths(&self.fx._server, mark.0).await.into_iter(); + asked + .filter(|path| path.starts_with("/patch-registry/") && path.contains("/info/")) + .collect() + } + + /// The body of every package reference request since `mark`, after + /// asserting that each asked for the list of the gem's builds. + async fn references_since(&self, mark: (usize, usize)) -> Vec> { + let requests = self.fx._server.received_requests().await; + let mut asked = Vec::new(); + for request in requests.unwrap_or_default().iter().skip(mark.0) { + if !request.url.path().ends_with("/patches/package") { + continue; + } + let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default(); + assert_eq!( + body["gemBuilds"], true, + "every package reference request asks for the list of the gem's builds: {body}" + ); + let uuids = body["uuids"].as_array().into_iter().flatten(); + asked.push( + uuids + .filter_map(|uuid| uuid.as_str().map(str::to_string)) + .collect(), + ); + } + asked + } + + /// The patch records fetched since `mark`, by uuid. + async fn views_since(&self, mark: (usize, usize)) -> Vec { + let requests = self.fx._server.received_requests().await; + let requests = requests.unwrap_or_default(); + let paths = requests.iter().skip(mark.0).map(|r| r.url.path()); + paths + .filter_map(|path| path.rsplit_once("/patches/view/")) + .map(|(_, uuid)| uuid.to_string()) + .collect() + } + + /// `text` with the mock upstream spelled as rubygems.org on a + /// `CHECKSUMS` lock: an unwind re-derives a `CHECKSUMS` sha256 only for + /// a rubygems.org remote, so there the pair names that registry and the + /// mock serves it (`SOCKET_RUBYGEMS_URL`). + fn as_committed(&self, text: &str) -> String { + let upstream = format!("{}/upstream", self.api()); + if self.checksums { + text.replace(&format!("\"{upstream}\""), "\"https://rubygems.org\"") + .replace(&format!("{upstream}/"), "https://rubygems.org/") + } else { + text.to_string() + } + } + + /// Spell the project's pair as [`Self::as_committed`] does. No bundler + /// runs on a `CHECKSUMS` project after this. + fn commit_pair(&self) { + for file in ["Gemfile", "Gemfile.lock"] { + let path = self.fx.proj.join(file); + let text = std::fs::read_to_string(&path).unwrap(); + std::fs::write(&path, self.as_committed(&text)).unwrap(); + } + } + + /// `socket-patch --json` over `dir` as an unwind runs: against + /// the stand-in service, which is also the patch server, with the mock + /// upstream as the gem registry. Returns the exit code, stdout, stderr. + fn unwind(&self, dir: &Path, argv: &[&str]) -> (i32, String, String) { + let api = self.api(); + let upstream = format!("{api}/upstream"); + let mut args: Vec<&str> = argv.to_vec(); + args.extend([ + "--json", + "--cwd", + dir.to_str().expect("utf8 tmp path"), + "--api-url", + &api, + "--org", + ORG, + "--api-token", + API_TOKEN, + "--patch-server-url", + &api, + ]); + run_socket_env(dir, &args, &[("SOCKET_RUBYGEMS_URL", &upstream)]) + } + + /// `rollback` of the gem: the pair before any scan, byte for byte. + /// Returns the run's stdout. + fn roll_back(&self) -> String { + self.commit_pair(); + let (code, stdout, stderr) = self.unwind(&self.fx.proj, &["rollback", PURL]); + assert_eq!(code, 0, "rollback:\nstdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!( + self.lock(), + self.as_committed(&self.pristine_lock()), + "rollback must hand the lock back byte for byte" + ); + assert_eq!( + self.gemfile(), + self.as_committed(&self.pristine_gemfile()), + "rollback must hand the Gemfile back byte for byte" + ); + stdout + } +} + +/// The path of every request `server` has answered, after the first `skip`. +async fn request_paths(server: &MockServer, skip: usize) -> Vec { + let requests = server.received_requests().await.unwrap_or_default(); + let paths = requests.iter().skip(skip); + paths + .map(|request| request.url.path().to_string()) + .collect() +} + +/// `bundle ` in `dir`, which must succeed. +fn bundle_ok(dir: &Path, args: &[&str]) { + let out = bundle(dir, args); + assert!( + out.status.success(), + "bundle {args:?} failed:\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); +} + +/// The hosted events of a run (`details.mode: "hosted"`), by the platform +/// they name (the ruby gem's, which names none, first), without +/// `details.pinChanged`: the tests compare the rest of each event exactly. +/// The event of every confirmed pin (`applied` / `verified`) carries the +/// key and no other event does. +fn hosted_events(env: &serde_json::Value) -> Vec { + let mut events: Vec = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|event| event["details"]["mode"] == "hosted") + .cloned() + .collect(); + for event in &mut events { + let confirmed = event["action"] == "applied" || event["action"] == "verified"; + let said = event["details"] + .as_object_mut() + .and_then(|details| details.remove("pinChanged")); + assert_eq!( + said.is_some(), + confirmed, + "`pinChanged` is on the event of a confirmed pin alone: {env}" + ); + } + events.sort_by_key(|event| { + let platform = event["details"]["platform"].as_str(); + platform.map(str::to_string) + }); + events +} + +/// The event of a patched build: `applied`, under the build's own patch, +/// with `newlyPatched` when the run put the build in place. +fn patched_event(platform: &str, newly: bool) -> serde_json::Value { + let mut details = serde_json::json!({ "gemFix": UUID, "platform": platform, "mode": "hosted" }); + if newly { + details["newlyPatched"] = serde_json::json!(true); + } + serde_json::json!({ + "action": "applied", "purl": platform_purl(platform), "uuid": build_uuid(platform), + "details": details, + }) +} + +/// The event of the ruby-platform entry a lock keeps beside the platform +/// builds: `applied`, under the gem's own patch. +fn ruby_event(newly: bool) -> serde_json::Value { + let mut details = serde_json::json!({ "gemFix": UUID, "mode": "hosted" }); + if newly { + details["newlyPatched"] = serde_json::json!(true); + } + serde_json::json!({ "action": "applied", "purl": PURL, "uuid": UUID, "details": details }) +} + +/// The uncounted event of a build that stays upstream's gem. +fn upstream_event(platform: &str) -> serde_json::Value { + upstream_event_of(UUID, platform, false) +} + +/// The uncounted event of a build the run put back on upstream's gem: the +/// patched build its lock entry pinned was withdrawn. +fn withdrawn_event(platform: &str) -> serde_json::Value { + upstream_event_of(UUID, platform, true) +} + +/// [`upstream_event`] (or, with `withdrawn`, [`withdrawn_event`]) of a +/// build of the gem patch `fix`. +fn upstream_event_of(fix: &str, platform: &str, withdrawn: bool) -> serde_json::Value { + let mut details = serde_json::json!({ "gemFix": fix, "platform": platform, "mode": "hosted" }); + let why = if withdrawn { + details["withdrawn"] = serde_json::json!(true); + "its patched build was withdrawn" + } else { + "no patched build yet" + }; + serde_json::json!({ + "action": "skipped", + "purl": platform_purl(platform), + "errorCode": "gem_upstream_build_kept", + "reason": format!("the patch registry serves upstream's own gem for {platform}: {why}"), + "details": details, + }) +} + +/// `events`, by platform as [`hosted_events`] orders a run's. +fn by_platform(mut events: Vec) -> Vec { + events.sort_by_key(|event| { + let platform = event["details"]["platform"].as_str(); + platform.map(str::to_string) + }); + events +} + +/// What one statement of a VEX document says of the fixture gem: its +/// status, the packages of the project it is about, the products it names +/// beside the project, and its impact statement (`not_affected`) or action +/// statement (`affected`). +#[derive(Debug, PartialEq)] +struct Said { + status: &'static str, + packages: Vec, + products: Vec, + words: String, +} + +/// Every statement of `doc`, each about the one vulnerability of the gem +/// patch's record ([`VULNS`]) in the project [`PRODUCT`]. +fn said(doc: &serde_json::Value) -> Vec { + let ids = |list: &serde_json::Value| -> Vec { + let items = list.as_array().into_iter().flatten(); + items + .filter_map(|item| item["@id"].as_str().map(str::to_string)) + .collect() + }; + let (vulnerability, aliases) = VULNS[0]; + let statements = doc["statements"].as_array().expect("statements"); + statements + .iter() + .map(|st| { + assert_eq!(st["vulnerability"]["name"], vulnerability, "{st}"); + assert_eq!( + st["vulnerability"]["aliases"], + serde_json::json!(aliases), + "{st}" + ); + assert_eq!(st["products"][0]["@id"], PRODUCT, "{st}"); + let (status, words) = match st["status"].as_str() { + Some("not_affected") => { + assert_eq!( + st["justification"], "inline_mitigations_already_exist", + "{st}" + ); + ("not_affected", &st["impact_statement"]) + } + Some("affected") => ("affected", &st["action_statement"]), + other => panic!("unexpected status {other:?}: {st}"), + }; + Said { + status, + packages: ids(&st["products"][0]["subcomponents"]), + products: ids(&st["products"])[1..].to_vec(), + words: words.as_str().unwrap_or_default().to_string(), + } + }) + .collect() +} + +/// What a document says of the gem where the lock names the platform +/// builds `locked`, each as the registry has it and at least one patched, +/// and with `ruby_entry` the ruby-platform gem beside them. ONE +/// `not_affected` statement names every patched build, each under its own +/// patch, and the ruby-platform gem under the gem's. Its products are the +/// forms a scanner reports a platform gem under, and the gem without a +/// platform only when no locked build is on upstream's gem: a scanner that +/// drops the platform matches every build by that form. Each build on +/// upstream's gem has an `affected` statement of its own. +fn build_statements(locked: &[(&str, Has)], ruby_entry: bool) -> Vec { + let having = |has: Has| -> Vec<&str> { + let builds = locked.iter().filter(|(_, how)| *how == has); + let mut platforms: Vec<&str> = builds.map(|(platform, _)| *platform).collect(); + platforms.sort(); + platforms + }; + let (patched, upstream) = (having(Has::Patched), having(Has::Upstream)); + // The form Grype and Syft report a platform gem under. + let grype_form = |platform: &&str| format!("{PURL}-{platform}"); + let purl = |platform: &&str| platform_purl(platform); + let gem = |named: bool| named.then(|| PURL.to_string()); + let mut patches: Vec = patched + .iter() + .map(|platform| build_uuid(platform)) + .collect(); + patches.extend(ruby_entry.then(|| UUID.to_string())); + patches.sort(); + let parts: Vec = patches + .iter() + .map(|patch| format!("Patched via Socket patch {patch} (redirected)")) + .collect(); + let mut statements = vec![Said { + status: "not_affected", + packages: gem(ruby_entry) + .into_iter() + .chain(patched.iter().map(purl)) + .collect(), + products: gem(upstream.is_empty()) + .into_iter() + .chain(patched.iter().map(grype_form)) + .chain(patched.iter().map(purl)) + .collect(), + words: parts.join("; "), + }]; + statements.extend(upstream.iter().map(|platform| Said { + status: "affected", + packages: vec![purl(platform)], + products: vec![grype_form(platform), purl(platform)], + words: format!( + "The patch registry has no patched build of this gem for {platform} yet and serves \ + upstream's own gem for it, so an install on that platform is without Socket patch \ + {UUID}. Run `socket-patch scan --mode hosted` again later: the lockfile takes the \ + patched build once it is published." + ), + })); + statements +} + +/// Manifest-less VEX over a fresh checkout the REAL bundler installed +/// (`fresh`) of a gem locked as the platform builds `locked`, each as the +/// registry has it ([`manifestless_vex_matrix`] is this for a gem locked as +/// its ruby gem alone, which is one pin under the gem's patch): +/// +/// 1. no `.socket/manifest.json` and no ledger: `vex` names each locked +/// build ([`build_statements`]) and exits 0, a build on upstream's gem +/// included. It asks for the gem patch's record and ONE package +/// reference, the gem patch's, whose list says which sha256 is a +/// patched build's; where the lock has no `CHECKSUMS` to say which +/// sha256 it installs, also for the index of the lock's registry; +/// and for the record of the patch of the build installed on this +/// machine, where that is a patched one, to check its files. It asks +/// nothing else, and nothing of the upstream file host. The +/// embedded `apply --vex` writes the same statements from the same +/// requests; +/// 2. `--offline`: no local record, so nothing is attested +/// (`record_unavailable`, no document), with ZERO requests; +/// 3. the pair reverted to its registry version names the patch nowhere +/// ([`assert_reverted_pair_names_no_patch`]). +async fn platform_vex_matrix(p: &PlatformProject, fresh: &Path, locked: &[(&str, Has)]) { + use vex_e2e_common::{assert_omitted, run_vex, strip_manifest, VexVia}; + let bin = binary(); + let lock = std::fs::read_to_string(fresh.join("Gemfile.lock")).unwrap(); + assert!( + lock.contains(&format!("remote: {}", p.fx.index_url)), + "the installed checkout's lock must name the patch registry (bundler {}):\n{lock}", + p.fx.bundler.version + ); + assert_no_redirect_ledger(fresh); + strip_manifest(fresh); + let statements = build_statements(locked, p.ruby_entry); + let attested = &statements[0].packages; + let affected: Vec<&String> = statements[1..] + .iter() + .flat_map(|said| &said.packages) + .collect(); + let mut asked = vec![ + format!("/v0/orgs/{ORG}/patches/view/{UUID}"), + format!("/v0/orgs/{ORG}/patches/package"), + ]; + if !p.checksums { + asked.push(format!("{}info/{DEP}", &p.fx.index_url[p.api().len()..])); + } + // The machine's own build has an installed copy: where it is a patched + // one, its files are checked against the record of its own patch. + let own_patched = (p.own.as_str(), Has::Patched); + if locked.contains(&own_patched) { + let own = build_uuid(&p.own); + asked.push(format!("/v0/orgs/{ORG}/patches/view/{own}")); + } + + // 1. manifest-less, ledger-less: the lock, the patch API, and the + // lock's registry where the lock has no `CHECKSUMS`. + for via in [VexVia::Vex, VexVia::Apply] { + let mark = p.mark().await; + let out = run_vex(&bin, fresh, &vex_run(&p.fx).via(via)); + assert_eq!( + out.code, + Some(0), + "{via:?}: {out}\n--- Gemfile.lock\n{lock}" + ); + assert_eq!(said(out.doc()), statements, "{via:?}: {out}"); + let env = &out.envelope; + if via == VexVia::Vex { + assert_eq!(env["status"], "success", "{out}"); + let verified = attested.iter().map(|purl| (purl.as_str(), "verified", "")); + let kept = affected + .iter() + .map(|purl| (purl.as_str(), "skipped", "gem_upstream_build_kept")); + let events: Vec<(String, String, String)> = verified + .chain(kept) + .map(|(purl, action, code)| (purl.into(), action.into(), code.into())) + .collect(); + assert_eq!(event_triples(env), events, "{out}"); + assert_eq!( + (&env["summary"]["verified"], &env["summary"]["skipped"]), + (&serde_json::json!(attested.len()), &serde_json::json!(0)), + "a build on upstream's gem is counted nowhere: {out}" + ); + assert_eq!(warning_codes(env), Vec::::new(), "{out}"); + } else { + assert_eq!(env["status"], "noManifest", "{out}"); + assert_eq!(env["vex"]["statements"], statements.len(), "{out}"); + assert_eq!( + env["vex"]["affected"].as_u64().unwrap_or(0), + affected.len() as u64, + "{out}" + ); + } + // The archive Bundler keeps of each gem is no evidence here: an + // installed patched build is held to the record of its own patch. + assert_eq!( + request_paths(&p.fx._server, mark.0).await, + asked, + "{via:?}: the record, one reference, without CHECKSUMS the registry's index, and \ + the record of an installed patched build" + ); + assert_eq!( + p.references_since(mark).await, + [[UUID]], + "{via:?}: the reference of the gem's own patch, with the list of its builds" + ); + assert_eq!( + request_paths(&p.files, mark.1).await, + Vec::::new(), + "{via:?}: nothing of the upstream file host" + ); + } + assert!( + !fresh.join(".socket/manifest.json").exists(), + "vex / apply --vex must never write the manifest" + ); + + // 2. offline: no local record to build a statement from, no network. + let mark = p.mark().await; + let mut offline = vex_run(&p.fx); + offline.offline = true; + let out = run_vex(&bin, fresh, &offline); + assert_omitted(&out, PURL, "record_unavailable", "offline vex"); + assert_eq!( + event_triples(&out.envelope).len(), + 1, + "the gem's one pin is left out, and no build is reported beside it: {out}" + ); + assert_eq!(p.mark().await, mark, "--offline made requests"); + + // 3. reverted to the registry pair (the install kept). + assert_reverted_pair_names_no_patch(&p.fx, fresh); +} + +/// A gem bundler locks as precompiled platform builds, with a patched build +/// for every platform the lock names, against the REAL bundler end to end: +/// +/// 1. upstream publishes the gem as a ruby gem AND as platform gems (this +/// machine's platform, and a foreign one); the real `bundle install` + +/// `bundle lock --add-platform` lock both platform builds and install +/// this machine's platform gem. `ruby_entry` picks the lock's +/// PLATFORMS: without `ruby` the lock holds the platform builds +/// alone, with it bundler keeps the ruby-platform +/// `name (version)` entry beside them (what bundler 4 locks by default +/// for a gem that also ships a ruby gem), and that entry moves too; +/// 2. the hosted scan asks for the gem patch's reference alone, moves +/// EVERY entry into the `GEM` section of the registry snapshot that +/// reference names, pins `DEPENDENCIES`, and (on a `CHECKSUMS` lock) +/// sets each entry to the sha256 the registry serves for it — the lock +/// the real `bundle lock` writes for that Gemfile, byte for byte. It +/// reports one `applied` event per locked build, each under that +/// build's own patch, as its own `--vex` document does, and replaces +/// the platform copy bundler had installed with the patched platform +/// gem; +/// 3. a fresh checkout's FROZEN `bundle install` fetches exactly this +/// machine's patched build from the patch registry (never the ruby +/// gem, so nothing is compiled), leaves the lock byte-identical, and +/// Ruby loads the PATCHED file from the platform build; +/// 4. a re-scan is a no-op, and offers no patch as newer although a +/// search returns the platform gems' own patches beside the gem's; +/// 5. `rollback` hands back the pre-scan pair byte for byte and puts the +/// installed copy back on the upstream platform gem; +/// 6. standalone `vex` over that fresh checkout attests each locked +/// build under its own patch ([`platform_vex_matrix`]). +/// +/// With `takeover`, a vendored run takes the gem over before step 5, each +/// platform's tree from that platform's own patch (asked for in one +/// request), which leaves the patched platform copy the hosted scan +/// installed. Step 5 is then a vendored unwind, and `remove` and +/// `vendor --revert` run over copies of the project as well: each must put +/// the installed platform copy back on the upstream platform gem. +async fn platform_prebuilds_install_frozen_and_roll_back( + tag: &str, + checksums_lock: bool, + ruby_entry: bool, + takeover: bool, +) { + // Bundler locks the specific platform's gem from 2.2; `CHECKSUMS` from + // 2.6. Vendor takes platform gems from a lock bundler 2.3 or newer wrote. + let floor = match (checksums_lock, takeover) { + (true, _) => (2, 6), + (false, true) => (2, 3), + (false, false) => (2, 2), + }; + let Some(mut p) = PlatformProject::start(tag, floor, checksums_lock, ruby_entry, &[]).await + else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let every = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Patched), + ]; + let index_url = p.serve(Some(&every)).await; + let registry = index_url[p.api().len()..].to_string(); + let warm_lib = p.installed_lib(&p.fx.proj); + let (orig, patched) = (p.service.orig.clone(), p.service.patched.clone()); + + // 2. The hosted scan. + let vex = ["--vex", "out.vex.json", "--vex-product", PRODUCT]; + let scanned = p.mark().await; + let env = p.scan(&vex); + assert_eq!(env["status"], "success", "envelope: {env}"); + let reported = |newly: bool| { + let mut events = vec![patched_event(&own, newly), patched_event(&foreign, newly)]; + if ruby_entry { + events.push(ruby_event(newly)); + } + by_platform(events) + }; + assert_eq!( + hosted_events(&env), + reported(true), + "one `applied` event per locked build, each under its own patch: {env}" + ); + assert_eq!( + env["summary"]["applied"], + reported(true).len(), + "every patched build is counted: {env}" + ); + // Nothing warns about platforms, and the platform copy bundler had + // installed is the patched build now. + let codes = warning_codes(&env); + let warned = |code: &str| codes.iter().any(|warned| warned == code); + for code in [ + "redirect_gem_platform_unsupported", + "redirect_gem_stale_install", + "redirect_gem_frozen_install", + ] { + assert!(!warned(code), "no {code}: {env}"); + } + assert_eq!( + warned("redirect_gem_no_checksums_section"), + !checksums_lock, + "{env}" + ); + assert!( + warned("redirect_gem_install_refreshed"), + "the warm platform install is refreshed: {env}" + ); + assert_eq!( + std::fs::read_to_string(&warm_lib).unwrap(), + patched, + "the installed platform copy holds the patched file" + ); + assert_eq!(env["vex"]["statements"], 1, "vex block: {env}"); + let in_run = vex_e2e_common::read_doc(&p.fx.proj.join("out.vex.json")); + assert_eq!( + said(&in_run.expect("the run's document")), + build_statements(&every, ruby_entry), + "the run's own document names each locked build under its own patch" + ); + let asked = p.references_since(scanned).await; + assert!( + !asked.is_empty() && asked.iter().all(|uuids| uuids == &[UUID]), + "the scan asks for the reference of the gem's own patch alone: {asked:?}" + ); + + let lock = p.assert_hosted_pair(&index_url, &[(&own, true), (&foreign, true)]); + let gemfile = p.gemfile(); + // The lock is the one the host bundler writes for that Gemfile over the + // pre-scan lock, byte for byte. + assert_eq!( + lock, + p.bundler_lock("relock", &gemfile, &p.pristine_lock()), + "the scan's lock must be what bundler {} writes for the redirected Gemfile", + p.fx.bundler.version + ); + assert_no_redirect_ledger(&p.fx.proj); + + // 3. A fresh checkout's frozen install: exactly this machine's patched + // build, from the patch registry. + let installing = p.mark().await; + let fresh = p.install_fresh("fresh", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&fresh, true); + let (fetched, redirected) = p.fetched_since(installing).await; + assert_eq!( + fetched, + [format!("{registry}gems/{}.gem", p.own_leaf())], + "the frozen install fetches the one platform gem of this machine" + ); + assert_eq!(redirected, Vec::::new(), "and nothing of upstream"); + + // 4. A re-scan changes nothing. + let env = p.scan(&vex); + assert_eq!(p.lock(), lock, "a re-scan leaves the lock byte-identical"); + assert_eq!(p.gemfile(), gemfile); + assert_eq!(hosted_events(&env), reported(false), "{env}"); + let codes = warning_codes(&env); + for code in [ + "redirect_gem_install_refreshed", + "redirect_gem_stale_install", + "redirect_gem_platform_unsupported", + ] { + assert!( + !codes.iter().any(|said| said == code), + "a re-scan has nothing to refresh, warn about or skip: {env}" + ); + } + assert_eq!( + env["updates"], + serde_json::json!([]), + "a platform gem's own patch is no newer patch of the gem: {env}" + ); + + // 5. Rollback: the pre-scan pair, byte for byte, and the installed + // copy back on the upstream platform gem. + p.commit_pair(); + if takeover { + let taking = p.mark().await; + let (code, stdout, stderr) = + p.unwind(&p.fx.proj, &["get", UUID, "--mode", "vendored", "--yes"]); + assert_eq!(code, 0, "takeover:\nstdout:\n{stdout}\nstderr:\n{stderr}"); + let vendored_lock = p.lock(); + assert!( + vendored_lock.starts_with("PATH\n remote: .socket/vendor/gem/"), + "premise: the gem is vendored:\n{vendored_lock}\nstdout:\n{stdout}" + ); + assert_eq!( + std::fs::read_to_string(&warm_lib).unwrap(), + patched, + "premise: the takeover leaves the patched platform copy installed" + ); + // Each platform's tree comes from that platform's own patch: the + // gem patch's reference, then ONE request for both. + let mut own_patches = [build_uuid(&own), build_uuid(&foreign)]; + own_patches.sort(); + let asked: Vec> = p + .references_since(taking) + .await + .into_iter() + .filter(|uuids| uuids != &[UUID]) + .map(|mut uuids| { + uuids.sort(); + uuids + }) + .collect(); + assert_eq!( + asked, + [own_patches.to_vec()], + "the platform patches are asked for in one request" + ); + // `remove` and `vendor --revert`, each over its own copy of the + // project; `rollback` runs on the project itself below. + for command in ["remove", "vendor --revert"] { + let dir = p.fx.tmp.path().join(format!("unwind-{}", &command[..6])); + copy_dir_recursive(&p.fx.proj, &dir); + // What a `bundle cache` taken under the hosted pin left: this + // machine's patched build in Bundler's cache dir. + let cached = dir + .join("vendor/cache") + .join(format!("{}.gem", p.own_leaf())); + std::fs::create_dir_all(cached.parent().unwrap()).unwrap(); + std::fs::write(&cached, &p.service.builds[&build_token(Some(&own))]).unwrap(); + let argv: &[&str] = match command { + "remove" => &["remove", PURL, "--yes"], + _ => &["vendor", "--revert", "--yes"], + }; + let (code, stdout, stderr) = p.unwind(&dir, argv); + assert_eq!(code, 0, "{command}:\nstdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!( + std::fs::read_to_string(dir.join("Gemfile.lock")).unwrap(), + p.as_committed(&p.pristine_lock()), + "{command} must hand the lock back byte for byte" + ); + assert_eq!( + std::fs::read_to_string(p.installed_lib(&dir)).unwrap(), + orig, + "{command}: the installed platform copy is the upstream build again:\n{stdout}" + ); + assert!( + stdout.contains("upstream_gem_install_refreshed") + && !stdout.contains("upstream_gem_stale_install"), + "{command}: the copy is refreshed, and nothing is left patched:\n{stdout}" + ); + // Both commands report a vendored unwind's advisories as events. + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("{command}: not JSON: {e}\nstdout:\n{stdout}")); + let named: Vec = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["errorCode"] == "upstream_gem_stale_cache") + .map(|e| e.to_string()) + .collect(); + assert_eq!(named.len(), 1, "{command}: one stale-cache warning: {env}"); + assert!( + named[0].contains(&cached.display().to_string()) + && named[0].contains("non-upstream"), + "{command}: the patched platform archive in the cache dir is named: {}", + named[0] + ); + } + } + let stdout = p.roll_back(); + assert_eq!( + std::fs::read_to_string(&warm_lib).unwrap(), + orig, + "the installed platform copy is the upstream build again" + ); + assert!( + !stdout.contains("upstream_gem_stale_install") + && !stdout.contains("upstream_gem_stale_cache"), + "nothing is left on the patched build:\n{stdout}" + ); + // The case whose pair still names the mock upstream: bundler loads the + // upstream code, and a reinstall from the gem home's archive succeeds. + if takeover && !checksums_lock { + let probe = "require \"vuln_gem\"; print VulnGem.status"; + for args in [&["install"][..], &["pristine"]] { + bundle_ok(&p.fx.proj, args); + let run = bundle(&p.fx.proj, &["exec", "ruby", "-e", probe]); + assert_eq!( + String::from_utf8_lossy(&run.stdout), + "VULNERABLE", + "bundle {args:?} leaves the upstream code loaded:\n{}", + String::from_utf8_lossy(&run.stderr) + ); + } + } + + // 6. Standalone VEX over the fresh checkout bundler installed. + platform_vex_matrix(&p, &fresh, &every).await; +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_platform_prebuilds_install_frozen_and_roll_back() { + platform_prebuilds_install_frozen_and_roll_back( + "platform-prebuilds-checksums", + true, + false, + false, + ) + .await; +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_platform_prebuilds_beside_the_ruby_entry_install_frozen_and_roll_back() { + platform_prebuilds_install_frozen_and_roll_back( + "platform-prebuilds-ruby-entry", + true, + true, + false, + ) + .await; +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.2); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_platform_prebuilds_without_checksums_install_frozen_and_roll_back() { + platform_prebuilds_install_frozen_and_roll_back("platform-prebuilds", false, false, false) + .await; +} + +/// A platform gem that went from hosted to vendored, then unwound. +#[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_vendored_unwind_restores_a_platform_install_the_hosted_scan_patched() { + platform_prebuilds_install_frozen_and_roll_back( + "platform-prebuilds-takeover-checksums", + true, + false, + true, + ) + .await; +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.3); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_vendored_unwind_restores_a_platform_install_without_checksums() { + platform_prebuilds_install_frozen_and_roll_back( + "platform-prebuilds-takeover", + false, + false, + true, + ) + .await; +} + +/// A lock with ONE patched platform and one the registry still serves as +/// upstream's own gem, on a `CHECKSUMS` lock, against the REAL bundler. +/// `own_patched` says which of the two this machine is, so the two cases +/// are a machine of the patched platform and a machine of the other: +/// +/// 1. the scan moves BOTH builds to the patch registry (one reference +/// request, for the gem's patch, asking for the list), pins the +/// patched build's sha256 and keeps upstream's for the other, and +/// reports the patched build under its own patch and the other as +/// kept, with no warning. The lock is what the real `bundle lock` +/// writes for that Gemfile, and a later `bundle lock` leaves it alone; +/// 2. `bundle install` of a fresh checkout works frozen, in deployment +/// mode and unfrozen, and leaves the lock byte-identical: a machine of +/// the patched platform gets the PATCHED gem from the registry, a +/// machine of the other gets UPSTREAM's gem, which the registry +/// relays itself or, with `redirects`, answers with a 302 that +/// bundler follows to the upstream file host; +/// 3. the scan itself downloads the patched build to refresh the copy +/// bundler had installed on the patched platform, and nothing at all +/// on the other, whose installed copy is upstream's gem as its lock +/// entry pins it; +/// 4. a re-scan changes nothing, reports no build as newly patched and +/// offers no newer patch; a person reads one plain line; +/// 5. `rollback` hands back the pre-scan pair byte for byte. +async fn one_platform_patched_and_one_on_upstream(tag: &str, own_patched: bool, redirects: bool) { + let Some(mut p) = PlatformProject::start(tag, (2, 6), true, false, &[]).await else { + return; + }; + p.redirects = redirects; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let (patched, upstream) = if own_patched { + (own.as_str(), foreign.as_str()) + } else { + (foreign.as_str(), own.as_str()) + }; + let index_url = p + .serve(Some(&[(patched, Has::Patched), (upstream, Has::Upstream)])) + .await; + let own_file = format!("{}gems/{}.gem", &index_url[p.api().len()..], p.own_leaf()); + let warm_lib = p.installed_lib(&p.fx.proj); + let installed = if own_patched { + p.service.patched.clone() + } else { + p.service.orig.clone() + }; + + // 1. The scan. + let scanned = p.mark().await; + let env = p.scan(&[]); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + hosted_events(&env), + by_platform(vec![patched_event(patched, true), upstream_event(upstream)]), + "{env}" + ); + let summary = &env["summary"]; + assert_eq!( + (&summary["applied"], &summary["skipped"], &summary["failed"]), + ( + &serde_json::json!(1), + &serde_json::json!(0), + &serde_json::json!(0) + ), + "the build on upstream's gem is counted nowhere: {env}" + ); + let refreshed: &[&str] = if own_patched { + &["redirect_gem_install_refreshed"] + } else { + &[] + }; + assert_eq!(warning_codes(&env), refreshed, "{env}"); + assert_eq!( + env["redirect"]["rewrittenFiles"], + serde_json::json!(["Gemfile", "Gemfile.lock"]) + ); + let lock = p.assert_hosted_pair(&index_url, &[(patched, true), (upstream, false)]); + assert_eq!( + lock, + p.bundler_lock("relock", &p.gemfile(), &p.pristine_lock()), + "the scan's lock must be what bundler {} writes for the redirected Gemfile", + p.fx.bundler.version + ); + assert_eq!( + p.references_since(scanned).await, + [[UUID]], + "one reference request, for the gem's own patch" + ); + assert_eq!( + p.views_since(scanned).await, + Vec::::new(), + "no patch record is fetched" + ); + // 3. What the scan itself downloaded. + let (fetched, redirected) = p.fetched_since(scanned).await; + let refresh: &[String] = if own_patched { + std::slice::from_ref(&own_file) + } else { + &[] + }; + assert_eq!( + fetched, refresh, + "the scan downloads the patched build of this machine's platform, when there is one" + ); + assert_eq!(redirected, Vec::::new()); + assert_eq!(std::fs::read_to_string(&warm_lib).unwrap(), installed); + + // A later `bundle lock` has nothing to change. + bundle_ok(&p.fx.proj, &["lock"]); + assert_eq!( + p.lock(), + lock, + "`bundle lock` leaves the lock byte-identical" + ); + + // 2. A machine of this platform installs from a fresh checkout. + let modes: [(&str, &[(&str, &str)]); 3] = [ + ("frozen", &[("BUNDLE_FROZEN", "true")]), + ("deployment", &[("BUNDLE_DEPLOYMENT", "true")]), + ("unfrozen", &[]), + ]; + for (name, envs) in modes { + let installing = p.mark().await; + let fresh = p.install_fresh(name, envs); + p.assert_installed(&fresh, own_patched); + let (fetched, redirected) = p.fetched_since(installing).await; + assert_eq!( + fetched, + std::slice::from_ref(&own_file), + "{name}: bundler asks the patch registry for this machine's platform gem alone" + ); + let handed_on: &[String] = if redirects && !own_patched { + &[format!("{}.gem", p.own_leaf())] + } else { + &[] + }; + assert_eq!( + redirected, handed_on, + "{name}: the registry serves a patched build itself, and relays the gem of a \ + platform with no patched build unless it redirects to the upstream file host" + ); + } + + // 4. A re-scan. + let rescanned = p.mark().await; + let env = p.scan(&[]); + assert_eq!(p.lock(), lock, "a re-scan leaves the lock byte-identical"); + assert_eq!( + hosted_events(&env), + by_platform(vec![ + patched_event(patched, false), + upstream_event(upstream) + ]), + "in place, not newly patched: {env}" + ); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(env["redirect"]["rewrittenFiles"], serde_json::json!([])); + assert_eq!(env["updates"], serde_json::json!([]), "{env}"); + assert_eq!(p.references_since(rescanned).await, [[UUID]]); + let (code, stdout, stderr) = p.hosted(&p.fx.proj, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already on hosted patches; nothing to rewrite.\n"), + "one package, whatever its builds:\n{stdout}" + ); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: patched for {patched}; upstream gem kept for {upstream} (no \ + patched build yet)\n" + )), + "{stdout}" + ); + assert!(!stderr.contains("Warning"), "{stderr}"); + + // 5. Rollback. + let stdout = p.roll_back(); + assert_eq!( + std::fs::read_to_string(&warm_lib).unwrap(), + p.service.orig, + "the installed platform copy is upstream's gem" + ); + assert_eq!( + stdout.contains("upstream_gem_install_refreshed"), + own_patched, + "only a patched copy is put back:\n{stdout}" + ); + assert!( + !stdout.contains("upstream_gem_stale_install") + && !stdout.contains("upstream_gem_stale_cache"), + "nothing is left on the patched build:\n{stdout}" + ); +} + +#[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_machine_of_the_patched_platform_installs_the_patched_gem() { + one_platform_patched_and_one_on_upstream("platform-one-patched-own", true, false).await; +} + +#[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_machine_of_a_platform_with_no_patched_build_installs_upstreams_gem() { + one_platform_patched_and_one_on_upstream("platform-one-patched-other", false, false).await; +} + +/// The same machine against a registry that answers the file of a platform +/// with no patched build with a redirect to the upstream registry: bundler +/// follows it. +#[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_machine_of_a_platform_with_no_patched_build_follows_a_redirect_to_upstream() { + one_platform_patched_and_one_on_upstream("platform-one-patched-other-302", false, true).await; +} + +/// VEX of a lock with ONE patched platform and one the registry still +/// serves as upstream's own gem, which the hosted scan moved and the REAL +/// bundler installed frozen. `own_patched` says which of the two this +/// machine is; `checksums_lock`, whether the lock says which sha256 it +/// installs or the registry's index has to. The patched build is attested +/// under its own patch and the other is said affected, never patched, with +/// exit 0: +/// +/// 1. by the scan's own `--vex`, over the copy bundler had installed; +/// 2. by a later `vex` over a checkout nothing is installed in; +/// 3. by a later `vex` over the checkout the frozen install put this +/// machine's gem in, the patched build or upstream's own: the copy on +/// this machine changes nothing of what is said of either build +/// ([`platform_vex_matrix`]). +async fn one_patched_build_is_attested_and_the_other_said_affected( + tag: &str, + own_patched: bool, + checksums_lock: bool, +) { + let floor = if checksums_lock { (2, 6) } else { (2, 2) }; + let Some(mut p) = PlatformProject::start(tag, floor, checksums_lock, false, &[]).await else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let (patched, upstream) = if own_patched { + (own.as_str(), foreign.as_str()) + } else { + (foreign.as_str(), own.as_str()) + }; + let locked = [(patched, Has::Patched), (upstream, Has::Upstream)]; + let index_url = p.serve(Some(&locked)).await; + let statements = build_statements(&locked, false); + + // 1. The scan, and its own document. + let env = p.scan(&["--vex", "out.vex.json", "--vex-product", PRODUCT]); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + hosted_events(&env), + by_platform(vec![patched_event(patched, true), upstream_event(upstream)]), + "{env}" + ); + p.assert_hosted_pair(&index_url, &[(patched, true), (upstream, false)]); + let in_run = vex_e2e_common::read_doc(&p.fx.proj.join("out.vex.json")); + assert_eq!(said(&in_run.expect("the run's document")), statements); + assert_eq!( + (&env["vex"]["statements"], &env["vex"]["affected"]), + (&serde_json::json!(2), &serde_json::json!(1)), + "{env}" + ); + + // 2. A checkout of the pair, nothing installed. + let checkout = stage_fresh_checkout(&p.fx, "checkout"); + let out = vex_e2e_common::run_vex(&binary(), &checkout, &vex_run(&p.fx)); + assert_eq!(out.code, Some(0), "nothing installed: {out}"); + assert_eq!(said(out.doc()), statements, "nothing installed: {out}"); + + // 3. The checkout a frozen install put this machine's gem in. + let fresh = p.install_fresh("fresh", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&fresh, own_patched); + platform_vex_matrix(&p, &fresh, &locked).await; +} + +#[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_vex_on_a_machine_of_the_patched_platform_says_the_other_build_is_affected() { + one_patched_build_is_attested_and_the_other_said_affected( + "platform-vex-one-patched-own", + true, + true, + ) + .await; +} + +#[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_vex_on_a_machine_of_a_platform_with_no_patched_build_attests_the_patched_one() { + one_patched_build_is_attested_and_the_other_said_affected( + "platform-vex-one-patched-other", + false, + true, + ) + .await; +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.2); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_vex_tells_the_builds_of_a_lock_without_checksums_apart_by_its_registry() { + one_patched_build_is_attested_and_the_other_said_affected( + "platform-vex-one-patched-other-no-checksums", + false, + false, + ) + .await; +} + +/// A gem is moved only once a locked build is patched and every locked +/// platform is listed, and until then a run says so quietly. On the lock +/// the real bundler wrote (with `CHECKSUMS`): +/// +/// 1. no locked build has a patched build: exit 0, both files +/// byte-identical, no warning, one skipped event, one plain line; +/// 2. this machine's platform has one, and the other is missing from the +/// list (the service leaves a platform out while its patched build is +/// being made): the same, under its own code and a line that says only +/// that the registry does not list the platform; +/// 3. the list has it: the run moves the gem, and a fresh checkout +/// installs the patched gem frozen. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_platform_gem_waits_quietly_for_its_patched_builds() { + let Some(mut p) = PlatformProject::start("platform-waits", (2, 6), true, false, &[]).await + else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let mut locked = [own.as_str(), foreign.as_str()]; + locked.sort(); + + // 1. No locked build is patched. + let none = [ + (own.as_str(), Has::Upstream), + (foreign.as_str(), Has::Upstream), + ]; + p.serve(Some(&none)).await; + p.assert_left_alone( + "redirect_gem_no_patched_build", + &format!( + "{DEP} {DEP_VERSION}: no patched build yet for {}, {}; left on its upstream registry", + locked[0], locked[1] + ), + ); + + // 2. A locked platform is missing from the list. + let building = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Building), + ]; + p.serve(Some(&building)).await; + p.assert_left_alone( + "redirect_gem_platform_unlisted", + &format!( + "{DEP} {DEP_VERSION}: the patch registry does not list {foreign}, so the gem is left \ + as it is" + ), + ); + + // 3. The list names every locked platform. + let every = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Patched), + ]; + let index_url = p.serve(Some(&every)).await; + let env = p.scan(&[]); + assert_eq!( + hosted_events(&env), + by_platform(vec![ + patched_event(&own, true), + patched_event(&foreign, true) + ]), + "{env}" + ); + assert_eq!( + warning_codes(&env), + ["redirect_gem_install_refreshed"], + "{env}" + ); + p.assert_hosted_pair(&index_url, &[(&own, true), (&foreign, true)]); + let fresh = p.install_fresh("fresh", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&fresh, true); +} + +/// A gem the lock names as its ruby-platform gem alone, of which upstream +/// also publishes platform gems, under a reference that names the registry +/// at a snapshot and lists the version's gems: this machine's platform on +/// upstream's own gem, the foreign one patched. The registry at a snapshot +/// lists every platform gem, and for a plain entry of a lock for `ruby` +/// alone bundler takes the machine's platform gem where the source lists +/// one, which here is upstream's unpatched gem. So such a gem takes the +/// registry without the snapshot level, which lists the patched gems only: +/// +/// 1. the scan writes the pair a reference with no snapshot gives: the +/// `source:` option and the lock's remote name the registry without +/// the snapshot level, `CHECKSUMS` pins the patched ruby gem, PLATFORMS +/// stays as it was, the run reports one `applied` event under the +/// gem's patch, and the copy bundler had installed is replaced with +/// the patched ruby gem; +/// 2. `bundle lock` leaves that lock byte for byte, and `bundle install` +/// (in the project, and from a fresh checkout, frozen and not) +/// installs the patched ruby gem and no platform gem; +/// 3. a scan under a newer snapshot changes nothing. +async fn ruby_gem_alone_takes_the_registry_without_a_snapshot(tag: &str, locked: Locked) { + let Some(mut p) = PlatformProject::start_locked(tag, (2, 6), true, locked, &[]).await else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + if locked == Locked::RubyAlone && p.fx.bundler.at_least(4, 0) { + // Premise, on the pair before any scan: for the plain entry + // bundler installs this machine's platform gem, which the gem's + // source lists. + let premise = stage_fresh_checkout(&p.fx, "premise"); + let install = bundle_env(&premise, &["install"], &[("BUNDLE_FROZEN", "true")]); + assert!( + install.status.success(), + "premise install failed:\n{}", + String::from_utf8_lossy(&install.stderr) + ); + assert!( + p.installed_lib(&premise).exists() && !p.installed_ruby_lib(&premise).exists(), + "premise: bundler {} takes the machine's platform gem for the plain entry", + p.fx.bundler.version + ); + } + let listing = [ + (own.as_str(), Has::Upstream), + (foreign.as_str(), Has::Patched), + ]; + let snapshot = p.serve(Some(&listing)).await; + let root = format!("{}/patch-registry/gem/{TOKEN}/{UUID}/", p.api()); + assert!( + snapshot.starts_with(&format!("{root}s/")), + "premise: the reference names the registry at a snapshot: {snapshot}" + ); + let pinned = serde_json::json!({ + "action": "applied", "purl": PURL, "uuid": UUID, "details": { "mode": "hosted" }, + }); + let platforms_of = |lock: &str| -> String { + let platforms = lock.split("\nPLATFORMS\n").nth(1).unwrap_or_default(); + platforms + .split("\n\n") + .next() + .unwrap_or_default() + .to_string() + }; + + // 1. The hosted scan. + let env = p.scan(&[]); + assert_eq!(hosted_events(&env), [pinned.clone()], "{env}"); + assert_eq!( + warning_codes(&env), + ["redirect_gem_install_refreshed"], + "{env}" + ); + let last_argument = match locked { + Locked::RubyForced => "force_ruby_platform: true".to_string(), + Locked::Builds { .. } | Locked::RubyAlone => format!("gem \"{DEP}\""), + }; + let gemfile = p.gemfile(); + assert_eq!( + gemfile, + with_source_option(&p.pristine_gemfile(), &last_argument, &root), + "the Gemfile names the registry without the snapshot level" + ); + let lock = p.lock(); + assert!( + lock.contains(&format!( + " remote: {root}\n specs:\n {DEP} ({DEP_VERSION})\n {TRANSITIVE}" + )), + "the gem is under the registry without the snapshot level:\n{lock}" + ); + assert!(!lock.contains(&snapshot), "{lock}"); + assert_eq!( + lock.matches(&format!(" {DEP} (")).count(), + 1, + "the plain entry alone:\n{lock}" + ); + assert!( + lock.contains(&format!( + " {DEP} ({DEP_VERSION}) sha256={}\n", + p.service.sha(None, true) + )), + "CHECKSUMS pins the patched ruby gem:\n{lock}" + ); + assert!( + lock.contains(&format!("\nDEPENDENCIES\n {DEP}!\n")), + "DEPENDENCIES is source-pinned:\n{lock}" + ); + assert_eq!( + platforms_of(&lock), + platforms_of(&p.pristine_lock()), + "PLATFORMS is as bundler wrote it" + ); + assert_eq!( + std::fs::read_to_string(p.installed_ruby_lib(&p.fx.proj)).unwrap(), + p.service.patched, + "the copy bundler had installed is the patched ruby gem" + ); + + // 2. Bundler takes the pair as it is, and installs the patched ruby gem. + assert_eq!( + p.bundler_lock("relock", &gemfile, &lock), + lock, + "`bundle lock` must leave the lock byte-identical (bundler {})", + p.fx.bundler.version + ); + bundle_ok(&p.fx.proj, &["install"]); + assert_eq!(p.lock(), lock, "`bundle install` leaves the lock alone"); + p.assert_patched_ruby_gem_installed(&p.fx.proj); + let frozen = p.install_fresh("frozen", &[("BUNDLE_FROZEN", "true")]); + p.assert_patched_ruby_gem_installed(&frozen); + let unfrozen = p.install_fresh("unfrozen", &[]); + p.assert_patched_ruby_gem_installed(&unfrozen); + + // 3. A newer snapshot, in which this machine's platform has a patched + // build too. Nothing of it concerns a lock that names no platform build. + let every = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Patched), + ]; + let newer = p.serve(Some(&every)).await; + assert_ne!(newer, snapshot, "a newer snapshot is another URL"); + let env = p.scan(&[]); + assert_eq!( + env["redirect"]["rewrittenFiles"], + serde_json::json!([]), + "{env}" + ); + assert_eq!(hosted_events(&env), [pinned], "{env}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(p.lock(), lock); + assert_eq!(p.gemfile(), gemfile); +} + +#[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_ruby_gem_alone_for_the_ruby_platform_installs_the_patched_ruby_gem() { + ruby_gem_alone_takes_the_registry_without_a_snapshot("ruby-alone", Locked::RubyAlone).await; +} + +#[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_ruby_gem_alone_beside_native_platforms_installs_the_patched_ruby_gem() { + ruby_gem_alone_takes_the_registry_without_a_snapshot("ruby-forced", Locked::RubyForced).await; +} + +/// A newer registry snapshot upgrades a hosted lock. This machine's +/// platform has no patched build at first, so the lock pins upstream's +/// gem for it and bundler installs that. Once the build is published the +/// reference names a newer snapshot: +/// +/// 1. the next scan rewrites the registry URL in the Gemfile and the +/// lock and the ONE checksum that changed, reports that build as +/// newly patched and the other as in place, and replaces the copy +/// bundler had installed with the patched gem, downloaded from the +/// newer snapshot; +/// 2. `bundle lock` leaves that lock alone, and `bundle install` (frozen, +/// from a fresh checkout, and in the project) installs the newly +/// patched gem; +/// 3. the earlier snapshot answers as it did: a checkout of the earlier +/// pair still installs upstream's gem frozen; +/// 4. `rollback` hands back the pre-scan pair byte for byte. +/// +/// On a lock with a `CHECKSUMS` section the lock says what each build was, +/// and no registry is asked. On one without, the scan asks the snapshot +/// the lock names what it lists, once, and reports the same. +#[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_newer_registry_snapshot_installs_the_newly_patched_build() { + newer_registry_snapshot_installs_the_newly_patched_build("platform-newer-snapshot", true).await; +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.5); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_newer_registry_snapshot_names_the_newly_patched_build_without_checksums() { + let tag = "platform-newer-snapshot-no-checksums"; + newer_registry_snapshot_installs_the_newly_patched_build(tag, false).await; +} + +async fn newer_registry_snapshot_installs_the_newly_patched_build(tag: &str, checksums: bool) { + let floor = if checksums { (2, 6) } else { (2, 5) }; + let Some(mut p) = PlatformProject::start(tag, floor, checksums, false, &[]).await else { + return; + }; + // The caveat of a lock that cannot record a sha256, on every rewrite. + let caveat: &[&str] = if checksums { + &[] + } else { + &["redirect_gem_no_checksums_section"] + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let warm_lib = p.installed_lib(&p.fx.proj); + let at_first = [ + (own.as_str(), Has::Upstream), + (foreign.as_str(), Has::Patched), + ]; + let first = p.serve(Some(&at_first)).await; + let env = p.scan(&[]); + assert_eq!( + hosted_events(&env), + by_platform(vec![upstream_event(&own), patched_event(&foreign, true)]), + "{env}" + ); + let first_lock = p.assert_hosted_pair(&first, &[(&own, false), (&foreign, true)]); + let first_gemfile = p.gemfile(); + let earlier = p.install_fresh("earlier", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&earlier, false); + // The earlier pair, with nothing installed: for a person's run below. + let committed = stage_fresh_checkout(&p.fx, "committed"); + + // The patched build of this machine's platform is published. + let every = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Patched), + ]; + let second = p.serve(Some(&every)).await; + assert_ne!(first, second, "a newer snapshot is another URL"); + + // 1. The upgrade. + let upgrading = p.mark().await; + let env = p.scan(&[]); + assert_eq!( + hosted_events(&env), + by_platform(vec![ + patched_event(&own, true), + patched_event(&foreign, false) + ]), + "{env}" + ); + assert_eq!( + warning_codes(&env), + [caveat, &["redirect_gem_install_refreshed"]].concat(), + "{env}" + ); + assert_eq!( + env["redirect"]["rewrittenFiles"], + serde_json::json!(["Gemfile", "Gemfile.lock"]) + ); + let lock = p.assert_hosted_pair(&second, &[(&own, true), (&foreign, true)]); + let pin = |patched: bool| { + let token = build_token(Some(&own)); + let sha = p.service.sha(Some(&own), patched); + format!(" {DEP} ({token}) sha256={sha}\n") + }; + assert_eq!( + lock, + first_lock + .replace(&first, &second) + .replace(&pin(false), &pin(true)), + "the URL and the one checksum that changed" + ); + assert_eq!(p.gemfile(), first_gemfile.replace(&first, &second)); + let (fetched, redirected) = p.fetched_since(upgrading).await; + assert_eq!( + fetched, + [format!( + "{}gems/{}.gem", + &second[p.api().len()..], + p.own_leaf() + )], + "the refresh takes the patched build from the newer snapshot" + ); + assert_eq!(redirected, Vec::::new()); + // What the lock does not say, the snapshot it names is asked: once. + let asked: Vec = match checksums { + true => Vec::new(), + false => vec![format!("{}info/{DEP}", &first[p.api().len()..])], }; - let (code, stdout, stderr) = scan(); + assert_eq!(p.indexes_since(upgrading).await, asked); assert_eq!( - code, 0, - "scan failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + std::fs::read_to_string(&warm_lib).unwrap(), + p.service.patched, + "the copy bundler had installed is the patched build" + ); + // For a person: which build this run found patched. + let (code, stdout, stderr) = p.hosted(&committed, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: now also patched for {own}; already patched for {foreign}\n" + )), + "{stdout}" ); - 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}"); - let warning_codes: Vec<&str> = env["warnings"] - .as_array() - .into_iter() - .flatten() - .filter_map(|w| w["code"].as_str()) - .collect(); - for code in [ - "redirect_gem_platform_unsupported", - "redirect_gem_stale_install", - "redirect_gem_frozen_install", - ] { - assert!(!warning_codes.contains(&code), "no {code}: {env}"); - } assert_eq!( - warning_codes.contains(&"redirect_gem_no_checksums_section"), - !checksums_lock, - "{env}" + stderr.matches("Warning").count(), + caveat.len(), + "nothing warns but the lock's own caveat:\n{stderr}" ); - // The platform copy bundler had installed is the prebuild now. + assert_eq!( + std::fs::read_to_string(committed.join("Gemfile.lock")).unwrap(), + lock + ); + + // 2. Bundler agrees with the lock and installs the patched gem. + bundle_ok(&p.fx.proj, &["lock"]); + assert_eq!( + p.lock(), + lock, + "`bundle lock` leaves the lock byte-identical" + ); + let fresh = p.install_fresh("fresh", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&fresh, true); + bundle_ok(&p.fx.proj, &["install"]); + assert_eq!(p.lock(), lock); + p.assert_installed(&p.fx.proj, true); + + // 3. The earlier snapshot answers as it did. + let again = p.fx.tmp.path().join("earlier-again"); + std::fs::create_dir_all(&again).unwrap(); + std::fs::write(again.join("Gemfile"), &first_gemfile).unwrap(); + std::fs::write(again.join("Gemfile.lock"), &first_lock).unwrap(); + copy_dir_recursive(&p.fx.proj.join(".bundle"), &again.join(".bundle")); + let install = bundle_env(&again, &["install"], &[("BUNDLE_FROZEN", "true")]); assert!( - warning_codes.contains(&"redirect_gem_install_refreshed"), - "the warm platform install is refreshed: {env}" + install.status.success(), + "the earlier pair still installs frozen:\n{}", + String::from_utf8_lossy(&install.stderr) ); + p.assert_installed(&again, false); + + // 4. Rollback. + let stdout = p.roll_back(); assert_eq!( std::fs::read_to_string(&warm_lib).unwrap(), - patched, - "the installed platform copy holds the patched file" + p.service.orig, + "the installed platform copy is the upstream build again" ); - assert_eq!(env["vex"]["statements"], 1, "vex block: {env}"); + assert!( + !stdout.contains("upstream_gem_stale_install") + && !stdout.contains("upstream_gem_stale_cache"), + "nothing is left on the patched build:\n{stdout}" + ); +} - let gemfile = std::fs::read_to_string(proj.join("Gemfile")).unwrap(); +/// `bundle lock --add-platform` on a hosted lock: the real bundler resolves +/// the new platform's gem from the patch registry, whose snapshot lists +/// every platform gem of the version, and pins the sha256 listed there: the +/// patched build's for a platform that has one, upstream's for one that +/// has none. Nothing else of the lock changes, and the Gemfile not at all. +/// The next scan reports the new builds with the others and writes nothing. +#[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_bundle_lock_add_platform_resolves_from_the_patch_registry() { + // Two platforms the lock does not name at first, neither this + // machine's nor the foreign one. + const WITH_BUILD: &str = "aarch64-linux"; + const WITHOUT_BUILD: &str = "x64-mingw-ucrt"; + let more = [WITH_BUILD, WITHOUT_BUILD]; + let Some(mut p) = PlatformProject::start("platform-add", (2, 6), true, false, &more).await + else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let listing = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Upstream), + (WITH_BUILD, Has::Patched), + (WITHOUT_BUILD, Has::Upstream), + ]; + let index_url = p.serve(Some(&listing)).await; + let env = p.scan(&[]); assert_eq!( - gemfile, - with_source_option( - &String::from_utf8(pristine_gemfile.clone()).unwrap(), - &format!("gem \"{DEP}\""), - &index_url - ), - "the Gemfile edit is the one a ruby gem gets" + hosted_events(&env), + by_platform(vec![patched_event(&own, true), upstream_event(&foreign)]), + "the builds the lock names: {env}" ); - let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); - // Every platform entry sits in the patch registry's section, none in - // the upstream one. + let hosted_lock = p.assert_hosted_pair(&index_url, &[(&own, true), (&foreign, false)]); + let gemfile = p.gemfile(); + + for platform in more { + bundle_ok(&p.fx.proj, &["lock", "--add-platform", platform]); + } + let lock = p.lock(); + assert_eq!(p.gemfile(), gemfile, "bundler leaves the Gemfile alone"); + // The lock gained exactly the new platforms, their entries and their + // checksums, and lost nothing. + let had: Vec<&str> = hosted_lock.lines().collect(); + let mut gained: Vec<&str> = lock.lines().filter(|line| !had.contains(line)).collect(); + gained.sort(); + let pin = |platform: &str, patched: bool| { + let token = build_token(Some(platform)); + let sha = p.service.sha(Some(platform), patched); + format!(" {DEP} ({token}) sha256={sha}") + }; + let mut want = vec![ + format!(" {WITH_BUILD}"), + format!(" {WITHOUT_BUILD}"), + format!(" {DEP} ({})", build_token(Some(WITH_BUILD))), + format!(" {DEP} ({})", build_token(Some(WITHOUT_BUILD))), + pin(WITH_BUILD, true), + pin(WITHOUT_BUILD, false), + ]; + want.sort(); + assert_eq!( + gained, want, + "the new platforms resolve from the patch registry:\n{lock}" + ); + let lines: Vec<&str> = lock.lines().collect(); + let lost: Vec<&&str> = had.iter().filter(|line| !lines.contains(line)).collect(); + assert_eq!(lost, Vec::<&&str>::new(), "nothing else changes:\n{lock}"); let registry_section = lock .split("\n\n") - .find(|section| section.contains(&format!("remote: {index_url}"))) - .unwrap_or_else(|| panic!("no patch-registry GEM section:\n{lock}")); - for platform in platforms { + .find(|section| section.contains(&format!("remote: {index_url}\n"))) + .unwrap_or_else(|| panic!("no GEM section of {index_url}:\n{lock}")); + for platform in more { assert!( registry_section.contains(&format!( " {DEP} ({})\n {TRANSITIVE}", - token(platform) + build_token(Some(platform)) )), - "the {platform} build moved to the patch registry with its sub-lines:\n{lock}" + "the {platform} build is under the patch registry:\n{lock}" ); - if checksums_lock { - assert!( - lock.contains(&format!( - " {DEP} ({}) sha256={}\n", - token(platform), - sha_of(&patched_builds, &token(platform)) - )), - "CHECKSUMS pins the {platform} prebuild's own sha256:\n{lock}" - ); - } } + + // The next scan reports the new builds and writes nothing. + let env = p.scan(&[]); + assert_eq!(p.lock(), lock, "the scan changes nothing:\n{env}"); + assert_eq!(p.gemfile(), gemfile); + assert_eq!(env["redirect"]["rewrittenFiles"], serde_json::json!([])); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); assert_eq!( - lock.matches(&format!(" {DEP} (")).count(), - 2 + usize::from(ruby_beside), - "every build, each listed once:\n{lock}" + hosted_events(&env), + by_platform(vec![ + patched_event(&own, false), + upstream_event(&foreign), + patched_event(WITH_BUILD, false), + upstream_event(WITHOUT_BUILD), + ]), + "{env}" + ); + let fresh = p.install_fresh("fresh", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&fresh, true); +} + +/// A patched build that was withdrawn must not stay installed, against the +/// REAL bundler, on a `CHECKSUMS` lock: +/// +/// 1. the scan moves the lock while this machine's platform has a +/// patched build and replaces the copy bundler had installed; `bundle +/// install` agrees, and Ruby loads the PATCHED code; +/// 2. the build is withdrawn: the list has upstream's sha256 for this +/// platform, with no patch, and the snapshot the lock names no +/// longer lists the build and refuses its file. A scan that may not +/// refresh puts that sha256 back into the lock, says in its event +/// and in one line that the build is back on upstream's gem, and +/// warns that the withdrawn build is still installed. Bundler does +/// not replace it: `bundle install` succeeds, changes nothing, and +/// Ruby still loads the withdrawn build; +/// 3. the scan replaces the copy with upstream's gem, downloaded once +/// from the patch registry (which relays it; nothing is asked of the +/// upstream file host) and reported as such. `bundle install` leaves +/// it, and `bundle exec ruby` loads UPSTREAM's code; +/// 4. a further scan changes nothing, downloads nothing and warns of +/// nothing; +/// 5. a fresh checkout installs upstream's gem frozen; +/// 6. the run's own document and a later `vex` say `affected` of this +/// machine's build and attest the other platform's under its 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_withdrawn_build_is_replaced_with_upstreams_gem() { + let Some(mut p) = PlatformProject::start("platform-withdrawn", (2, 6), true, false, &[]).await + else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let warm_lib = p.installed_lib(&p.fx.proj); + + // 1. Both platforms patched: this machine holds the patched build. + let every = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Patched), + ]; + let first = p.serve(Some(&every)).await; + let env = p.scan(&[]); + assert_eq!( + warning_codes(&env), + ["redirect_gem_install_refreshed"], + "{env}" ); + let first_lock = p.assert_hosted_pair(&first, &[(&own, true), (&foreign, true)]); + bundle_ok(&p.fx.proj, &["install"]); + assert_eq!(p.lock(), first_lock); + p.assert_installed(&p.fx.proj, true); + // The pair as it is committed, with nothing installed: for a person's + // run below. + let committed = stage_fresh_checkout(&p.fx, "committed"); + + // 2. The build of this machine's platform is withdrawn. + let after = [ + (own.as_str(), Has::Upstream), + (foreign.as_str(), Has::Patched), + ]; + let second = p.serve(Some(&after)).await; + assert_ne!(first, second, "a withdrawal is a newer snapshot"); + p.withdraw(&first, &own).await; + let withdrawing = p.mark().await; + let env = p.scan(&["--no-gem-install-refresh"]); assert_eq!( - registry_section.matches(&format!(" {DEP} (")).count(), - 2 + usize::from(ruby_beside), - "all of them under the patch registry:\n{lock}" + hosted_events(&env), + by_platform(vec![withdrawn_event(&own), patched_event(&foreign, false)]), + "{env}" ); - if ruby_beside && checksums_lock { - assert!( - lock.contains(&format!(" {DEP} ({DEP_VERSION}) sha256={ruby_sha}\n")), - "CHECKSUMS pins the ruby-platform entry to the patched ruby gem:\n{lock}" - ); - } + let lock = p.assert_hosted_pair(&second, &[(&own, false), (&foreign, true)]); + let pin = |patched: bool| { + let token = build_token(Some(&own)); + let sha = p.service.sha(Some(&own), patched); + format!(" {DEP} ({token}) sha256={sha}\n") + }; + assert_eq!( + lock, + first_lock + .replace(&first, &second) + .replace(&pin(true), &pin(false)), + "the URL and the one checksum that changed" + ); + assert_eq!(warning_codes(&env), ["redirect_gem_stale_install"], "{env}"); + let gem_dir = warm_lib.parent().and_then(Path::parent).unwrap(); + let detail = env["warnings"][0]["detail"].as_str().unwrap_or_default(); + assert!( + detail.starts_with(&format!( + "{PURL} is back on upstream's own gem for {own}, whose patched build was withdrawn, \ + but its withdrawn install at {} was not refreshed (`--no-gem-install-refresh` is \ + set), and `bundle install` reuses an installed gem instead of fetching the upstream \ + one. Re-run without `--no-gem-install-refresh`, or remove ", + gem_dir.display() + )), + "{detail}" + ); + let (fetched, redirected) = p.fetched_since(withdrawing).await; + assert_eq!( + (fetched, redirected), + (Vec::new(), Vec::new()), + "nothing is downloaded" + ); + // For a person: the one line, over the pair as it was committed. + let (code, stdout, stderr) = p.hosted(&committed, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); assert!( - lock.contains(&format!("\nDEPENDENCIES\n {DEP}!\n")), - "DEPENDENCIES is source-pinned:\n{lock}" + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: patched for {foreign}; upstream gem back for {own} (its \ + patched build was withdrawn)\n" + )), + "{stdout}" ); - // The lock is the one the host bundler writes for that Gemfile over the - // pre-scan lock, byte for byte. - let relock = tmp.path().join("relock"); - std::fs::create_dir_all(&relock).unwrap(); - std::fs::write(relock.join("Gemfile"), &gemfile).unwrap(); - std::fs::write(relock.join("Gemfile.lock"), &pristine_lock).unwrap(); - copy_dir_recursive(&proj.join(".bundle"), &relock.join(".bundle")); - bundle_ok(&relock, &["lock"]); + assert!(!stderr.contains("Warning"), "{stderr}"); + assert_eq!( + std::fs::read_to_string(committed.join("Gemfile.lock")).unwrap(), + lock + ); + // Bundler keeps the gem it has installed. + bundle_ok(&p.fx.proj, &["install"]); + assert_eq!(p.lock(), lock, "`bundle install` leaves the lock alone"); + p.assert_installed(&p.fx.proj, true); + + // 3. The scan replaces it with upstream's gem, through the registry. + let replacing = p.mark().await; + let env = p.scan(&[]); + assert_eq!( + warning_codes(&env), + ["redirect_gem_install_refreshed"], + "{env}" + ); + assert_eq!( + env["warnings"][0]["detail"], + format!( + "{PURL}: replaced the withdrawn install at {} with the upstream gem", + gem_dir.display() + ), + "{env}" + ); + assert_eq!(env["redirect"]["rewrittenFiles"], serde_json::json!([])); + assert_eq!(p.lock(), lock); + let (fetched, redirected) = p.fetched_since(replacing).await; + assert_eq!( + fetched, + [format!( + "{}gems/{}.gem", + &second[p.api().len()..], + p.own_leaf() + )], + "upstream's gem comes from the patch registry, once" + ); + assert_eq!(redirected, Vec::::new(), "which relays it"); + assert_eq!( + p.views_since(replacing).await, + Vec::::new(), + "no patch record is fetched" + ); + assert_eq!( + std::fs::read_to_string(&warm_lib).unwrap(), + p.service.orig, + "the installed copy is upstream's gem" + ); + bundle_ok(&p.fx.proj, &["install"]); + assert_eq!(p.lock(), lock, "`bundle install` leaves the lock alone"); + p.assert_installed(&p.fx.proj, false); + + // 4. A further scan changes nothing. + let again = p.mark().await; + let env = p.scan(&[]); assert_eq!( + p.lock(), lock, - std::fs::read_to_string(relock.join("Gemfile.lock")).unwrap(), - "the scan's lock must be what bundler {} writes for the redirected Gemfile", - bundler.version + "a further scan leaves the lock byte-identical" ); - assert_no_redirect_ledger(&proj); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(env["redirect"]["rewrittenFiles"], serde_json::json!([])); + assert_eq!( + hosted_events(&env), + by_platform(vec![upstream_event(&own), patched_event(&foreign, false)]), + "{env}" + ); + let (fetched, redirected) = p.fetched_since(again).await; + assert_eq!( + (fetched, redirected), + (Vec::new(), Vec::new()), + "nothing is downloaded" + ); + p.assert_installed(&p.fx.proj, false); - let fx = RedirectFixture { - tmp, - proj: proj.clone(), - index_url: index_url.clone(), - gemfile_name: "Gemfile", - lock_name: "Gemfile.lock", - patched: patched.clone().into_bytes(), - pristine_gemfile, - pristine_lock: pristine_lock.clone().into_bytes(), - bundler, - _server: server, - }; + // 5. A fresh checkout installs upstream's gem. + let fresh = p.install_fresh("fresh", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&fresh, false); - // 3. A fresh checkout's frozen install. - let asked_before = request_count(&fx).await; - let (fresh, install) = fresh_checkout_bundle_install(&fx); - assert!( - install.status.success(), - "fresh-checkout frozen `bundle install` must succeed from the patch registry.\nstdout:\n{}\nstderr:\n{}", - String::from_utf8_lossy(&install.stdout), - String::from_utf8_lossy(&install.stderr), + // 6. VEX: this machine's build is affected, the other attested. + let statements = build_statements(&after, false); + let env = p.scan(&["--vex", "out.vex.json", "--vex-product", PRODUCT]); + let in_run = vex_e2e_common::read_doc(&p.fx.proj.join("out.vex.json")); + assert_eq!(said(&in_run.expect("the run's document")), statements); + assert_eq!( + (&env["vex"]["statements"], &env["vex"]["affected"]), + (&serde_json::json!(2), &serde_json::json!(1)), + "{env}" ); - assert_lock_untouched_by_install(&fx, &fresh); - let installed = fresh_installed_lib(&fresh, &own_leaf, "vuln_gem.rb"); + let out = vex_e2e_common::run_vex(&binary(), &p.fx.proj, &vex_run(&p.fx)); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!(said(out.doc()), statements, "{out}"); + assert_eq!(out.envelope["status"], "success", "{out}"); +} + +/// A patched build that was withdrawn on an earlier patch of the gem, +/// while the patch on offer is a newer one with no patched build for this +/// machine's platform, against the REAL bundler, on a `CHECKSUMS` lock: +/// +/// 1. the scan moves the lock to the earlier patch, which has a patched +/// build for this machine's platform, and replaces the copy bundler +/// had installed; `bundle install` agrees, and Ruby loads the PATCHED +/// code; +/// 2. that build is withdrawn: the earlier patch's registry, under the +/// snapshot the lock names, no longer lists it and refuses its file. +/// A checkout of the unchanged pair cannot be installed on this +/// machine any more; +/// 3. the service offers the newer patch, whose registry serves +/// upstream's gem for this platform. The lock is not held on the +/// earlier patch for a build that is gone: the scan asks the registry +/// the lock is on, once, moves the pair to the newer patch with +/// upstream's sha256 for this platform, says so in one line and one +/// event, and replaces the installed copy with upstream's gem, +/// downloaded once from the newer patch's registry; +/// 4. `bundle lock` leaves that lock alone; a fresh checkout installs +/// upstream's gem, frozen and not; `bundle install` in the project +/// keeps the copy, and `bundle exec ruby` loads UPSTREAM's code; +/// 5. a further scan changes nothing, downloads nothing and asks no +/// registry. +#[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_withdrawn_build_of_an_earlier_patch_moves_to_the_newer_patch() { + let Some(mut p) = + PlatformProject::start("platform-withdrawn-newer", (2, 6), true, false, &[]).await + else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let warm_lib = p.installed_lib(&p.fx.proj); + let api = p.api(); + let known = ["--patch-server-url", api.as_str()]; + + // 1. The earlier patch has a patched build for both platforms. + let every = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Patched), + ]; + let first = p.serve(Some(&every)).await; + let env = p.scan(&known); assert_eq!( - std::fs::read_to_string(&installed).expect("the platform gem is installed"), - patched, - "the fresh install holds the PATCHED file in the platform gem's dir" + warning_codes(&env), + ["redirect_gem_install_refreshed"], + "{env}" + ); + let first_lock = p.assert_hosted_pair(&first, &[(&own, true), (&foreign, true)]); + bundle_ok(&p.fx.proj, &["install"]); + assert_eq!(p.lock(), first_lock); + p.assert_installed(&p.fx.proj, true); + // The pair on the earlier patch, with nothing installed. + let committed = stage_fresh_checkout(&p.fx, "committed"); + + // 2. The build of this machine's platform is withdrawn. + p.withdraw(&first, &own).await; + p.assert_no_longer_installs(&first_lock); + + // 3. The newer patch is on offer: no patched build for this platform. + let after = [ + (own.as_str(), Has::Upstream), + (foreign.as_str(), Has::Patched), + ]; + let earlier_now = p.serve(Some(&after)).await; + assert_ne!(first, earlier_now, "a withdrawal is a newer snapshot"); + let second = p.offer_newer(&after).await; + assert!(second.contains(NEWER_UUID), "{second}"); + let moving = p.mark().await; + let env = p.scan(&known); + let withdrawn_event = upstream_event_of(NEWER_UUID, &own, true); + let foreign_event = serde_json::json!({ + "action": "applied", + "purl": platform_purl(&foreign), + "uuid": build_uuid_of(NEWER_UUID, &foreign), + "details": { "gemFix": NEWER_UUID, "platform": foreign, "mode": "hosted" }, + }); + assert_eq!( + hosted_events(&env), + by_platform(vec![withdrawn_event, foreign_event.clone()]), + "{env}" + ); + assert_eq!(env["status"], "success", "{env}"); + let summary = &env["summary"]; + assert_eq!( + (&summary["applied"], &summary["skipped"], &summary["failed"]), + ( + &serde_json::json!(1), + &serde_json::json!(0), + &serde_json::json!(0) + ), + "{env}" + ); + assert_eq!( + env["redirect"]["rewrittenFiles"], + serde_json::json!(["Gemfile", "Gemfile.lock"]) + ); + let lock = p.assert_hosted_pair(&second, &[(&own, false), (&foreign, true)]); + let pin = |patched: bool| { + let token = build_token(Some(&own)); + let sha = p.service.sha(Some(&own), patched); + format!(" {DEP} ({token}) sha256={sha}\n") + }; + assert_eq!( + lock, + first_lock + .replace(&first, &second) + .replace(&pin(true), &pin(false)), + "the URL and the one checksum that changed" ); assert!( - !fresh_installed_lib(&fresh, &format!("{DEP}-{DEP_VERSION}"), "vuln_gem.rb").exists(), - "the ruby-platform gem is not what bundler installs" + !lock.contains(UUID), + "nothing of the earlier patch:\n{lock}" + ); + // The guard replaced the copy of the withdrawn build. + assert_eq!( + warning_codes(&env), + ["redirect_gem_install_refreshed"], + "{env}" + ); + let gem_dir = warm_lib.parent().and_then(Path::parent).unwrap(); + assert_eq!( + env["warnings"][0]["detail"], + format!( + "{PURL}: replaced the withdrawn install at {} with the upstream gem", + gem_dir.display() + ), + "{env}" ); - // Exactly this machine's prebuild came from the patch registry. - let gems_prefix = format!("{registry_base}/gems/"); - let fetched: Vec = fx - ._server - .received_requests() - .await - .unwrap_or_default() - .iter() - .skip(asked_before) - .filter_map(|r| r.url.path().strip_prefix(&gems_prefix).map(str::to_string)) - .collect(); + assert_eq!( + std::fs::read_to_string(&warm_lib).unwrap(), + p.service.orig, + "the installed copy is upstream's gem" + ); + let (fetched, redirected) = p.fetched_since(moving).await; assert_eq!( fetched, - [format!("{own_leaf}.gem")], - "the frozen install fetches the one platform gem of this machine" + [format!("{}gems/{}.gem", &second[api.len()..], p.own_leaf())], + "upstream's gem comes from the newer patch's registry, once" ); - let probe = bundle( - &fresh, - &[ - "exec", - "ruby", - "-e", - "require \"vuln_gem\"\nputs VulnGem.status\nputs VulnGem::BUILD\nputs TinyDep::VALUE\nputs $LOADED_FEATURES.grep(%r{/vuln_gem\\.rb\\z})", - ], + assert_eq!(redirected, Vec::::new(), "which relays it"); + assert_eq!( + p.indexes_since(moving).await, + [format!("{}info/{DEP}", &first[api.len()..])], + "the registry the lock was on is asked once, and no other" ); + assert_eq!( + p.views_since(moving).await, + Vec::::new(), + "no patch record is fetched" + ); + // For a person, over the pair as it was committed on the earlier patch. + let (code, stdout, stderr) = p.hosted(&committed, &["scan"], &known); + assert_eq!(code, 0, "{stdout}\n{stderr}"); assert!( - probe.status.success(), - "bundle exec require probe failed.\nstdout:\n{}\nstderr:\n{}", - String::from_utf8_lossy(&probe.stdout), - String::from_utf8_lossy(&probe.stderr), + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: patched for {foreign}; upstream gem back for {own} (its \ + patched build was withdrawn)\n" + )), + "{stdout}" + ); + assert!(!stderr.contains("Warning"), "{stderr}"); + assert_eq!( + std::fs::read_to_string(committed.join("Gemfile.lock")).unwrap(), + lock + ); + + // 4. Bundler agrees with the lock and installs upstream's gem. + bundle_ok(&p.fx.proj, &["lock"]); + assert_eq!( + p.lock(), + lock, + "`bundle lock` leaves the lock byte-identical" + ); + let fresh = p.install_fresh("fresh", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&fresh, false); + let unfrozen = p.install_fresh("unfrozen", &[]); + p.assert_installed(&unfrozen, false); + bundle_ok(&p.fx.proj, &["install"]); + assert_eq!(p.lock(), lock, "`bundle install` leaves the lock alone"); + p.assert_installed(&p.fx.proj, false); + + // 5. A further scan changes nothing. + let again = p.mark().await; + let env = p.scan(&known); + assert_eq!( + p.lock(), + lock, + "a further scan leaves the lock byte-identical" + ); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(env["redirect"]["rewrittenFiles"], serde_json::json!([])); + let kept_event = upstream_event_of(NEWER_UUID, &own, false); + assert_eq!( + hosted_events(&env), + by_platform(vec![kept_event, foreign_event]), + "{env}" + ); + let (fetched, redirected) = p.fetched_since(again).await; + assert_eq!( + (fetched, redirected), + (Vec::new(), Vec::new()), + "nothing is downloaded" + ); + assert_eq!( + p.indexes_since(again).await, + Vec::::new(), + "no registry is asked" + ); + p.assert_installed(&p.fx.proj, false); +} + +/// A lock that STAYS on the patch it is on, while that patch has withdrawn +/// this machine's build, against the REAL bundler, on a `CHECKSUMS` lock: +/// +/// 1. the scan moves the lock to a patch with a patched build for both +/// locked platforms and replaces the copy bundler had installed; +/// `bundle install` agrees, and Ruby loads the PATCHED code; +/// 2. the build of this machine's platform is withdrawn: the registry, +/// under the snapshot the lock names, no longer lists it and refuses +/// its file. A checkout of the unchanged pair cannot be installed on +/// this machine any more; +/// 3. a newer patch is on offer that the lock cannot move to: it has no +/// patched build for the other platform, which the lock's patch still +/// serves (`redirect_gem_newer_fix_waits`), or does not list that +/// platform (`redirect_gem_platform_unlisted`). The lock stays on its +/// patch, and the scan brings it to that patch's current listing: it +/// asks the registry the lock is on, once, takes the reference of the +/// lock's patch that its check of the pin already holds, writes that +/// patch's current snapshot with upstream's sha256 for this platform +/// and the other platform's patched sha256 unchanged, says both in +/// two lines and in its events, and replaces the installed copy with +/// upstream's gem from that snapshot; +/// 4. `bundle lock` leaves that lock alone; a fresh checkout installs +/// upstream's gem, frozen and not; `bundle install` in the project +/// keeps the copy, and `bundle exec ruby` loads UPSTREAM's code; +/// 5. a further scan changes nothing and downloads nothing. +async fn lock_that_stays_is_brought_to_its_patchs_current_listing( + tag: &str, + other_on_offer: Has, + code: &str, +) { + let Some(mut p) = PlatformProject::start(tag, (2, 6), true, false, &[]).await else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let warm_lib = p.installed_lib(&p.fx.proj); + let api = p.api(); + let known = ["--patch-server-url", api.as_str()]; + let stays = match other_on_offer { + Has::Building => format!( + "{DEP} {DEP_VERSION}: the newer fix's registry does not list {foreign}; the lock \ + stays on the patch it is on" + ), + _ => format!( + "{DEP} {DEP_VERSION}: the newer fix has no patched build for {foreign} yet; the lock \ + stays on the patch it is on" + ), + }; + let skip_event = serde_json::json!({ + "action": "skipped", "purl": PURL, "uuid": NEWER_UUID, + "errorCode": code, "reason": stays, + "details": { "mode": "hosted" }, + }); + + // 1. Both platforms patched: this machine holds the patched build. + let every = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Patched), + ]; + let first = p.serve(Some(&every)).await; + let env = p.scan(&known); + assert_eq!( + warning_codes(&env), + ["redirect_gem_install_refreshed"], + "{env}" + ); + let first_lock = p.assert_hosted_pair(&first, &[(&own, true), (&foreign, true)]); + bundle_ok(&p.fx.proj, &["install"]); + assert_eq!(p.lock(), first_lock); + p.assert_installed(&p.fx.proj, true); + // The pair as it is committed, with nothing installed. + let committed = stage_fresh_checkout(&p.fx, "committed"); + + // 2. The build of this machine's platform is withdrawn. + p.withdraw(&first, &own).await; + p.assert_no_longer_installs(&first_lock); + + // 3. The lock's patch lists upstream's gem for this platform now, and + // the newer patch on offer is one the lock cannot move to. + let after = [ + (own.as_str(), Has::Upstream), + (foreign.as_str(), Has::Patched), + ]; + let second = p.serve(Some(&after)).await; + assert_ne!(first, second, "a withdrawal is a newer snapshot"); + let on_offer = [ + (own.as_str(), Has::Upstream), + (foreign.as_str(), other_on_offer), + ]; + let newer = p.offer_newer(&on_offer).await; + assert!(newer.contains(NEWER_UUID), "{newer}"); + let refreshing = p.mark().await; + let env = p.scan(&known); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + hosted_events(&env), + by_platform(vec![ + skip_event.clone(), + withdrawn_event(&own), + patched_event(&foreign, false) + ]), + "{env}" + ); + let summary = &env["summary"]; + assert_eq!( + (&summary["applied"], &summary["skipped"], &summary["failed"]), + ( + &serde_json::json!(1), + &serde_json::json!(1), + &serde_json::json!(0) + ), + "{env}" + ); + assert_eq!( + env["redirect"]["rewrittenFiles"], + serde_json::json!(["Gemfile", "Gemfile.lock"]) + ); + let lock = p.assert_hosted_pair(&second, &[(&own, false), (&foreign, true)]); + let pin = |patched: bool| { + let token = build_token(Some(&own)); + let sha = p.service.sha(Some(&own), patched); + format!(" {DEP} ({token}) sha256={sha}\n") + }; + assert_eq!( + lock, + first_lock + .replace(&first, &second) + .replace(&pin(true), &pin(false)), + "the URL and the one checksum that changed" + ); + assert!( + !lock.contains(NEWER_UUID), + "nothing of the patch on offer:\n{lock}" + ); + // The guard replaced the copy of the withdrawn build. + assert_eq!( + warning_codes(&env), + ["redirect_gem_install_refreshed"], + "{env}" + ); + let gem_dir = warm_lib.parent().and_then(Path::parent).unwrap(); + assert_eq!( + env["warnings"][0]["detail"], + format!( + "{PURL}: replaced the withdrawn install at {} with the upstream gem", + gem_dir.display() + ), + "{env}" ); - let out = String::from_utf8_lossy(&probe.stdout).into_owned(); - let lines: Vec<&str> = out.lines().collect(); - let marker = patched_marker(); assert_eq!( - lines.len(), - 4, - "status, build, dep and the loaded file:\n{out}" + std::fs::read_to_string(&warm_lib).unwrap(), + p.service.orig, + "the installed copy is upstream's gem" ); + let (fetched, redirected) = p.fetched_since(refreshing).await; assert_eq!( - lines[..3], - [marker.as_str(), own.as_str(), "tiny-ok"], - "Ruby loads the patched file, from this machine's platform build:\n{out}" - ); - assert!( - lines[3].contains("/vendor/bundle/") - && lines[3].contains(&format!("/gems/{own_leaf}/lib/")), - "vuln_gem.rb loads from the installed platform gem:\n{out}" + fetched, + [format!("{}gems/{}.gem", &second[api.len()..], p.own_leaf())], + "upstream's gem comes from the lock's patch under its current snapshot, once" ); - - // 4. A re-scan changes nothing. - let (code, stdout, stderr) = scan(); + assert_eq!(redirected, Vec::::new(), "which relays it"); assert_eq!( - code, 0, - "re-scan failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + p.indexes_since(refreshing).await, + [format!("{}info/{DEP}", &first[api.len()..])], + "the registry the lock is on is asked once, and no other" ); assert_eq!( - std::fs::read_to_string(fx.proj.join("Gemfile.lock")).unwrap(), - lock, - "a re-scan leaves the lock byte-identical" + p.references_since(refreshing).await, + [vec![UUID.to_string()], vec![NEWER_UUID.to_string()]], + "the check of the pin and the patch on offer: no further reference request" ); assert_eq!( - std::fs::read_to_string(fx.proj.join("Gemfile")).unwrap(), - gemfile - ); - assert!( - !stdout.contains("redirect_gem_install_refreshed") - && !stdout.contains("redirect_gem_stale_install") - && !stdout.contains("redirect_gem_platform_unsupported"), - "a re-scan has nothing to refresh, warn about or skip:\n{stdout}" - ); - - // 5. Rollback: the pre-scan pair, byte for byte, and the installed - // copy back on the upstream platform gem. The restore re-derives a - // `CHECKSUMS` sha256 only for a rubygems.org remote, so that arm - // spells the mock upstream as rubygems.org in the pair and serves - // that registry from the mock (`SOCKET_RUBYGEMS_URL`). No bundler - // runs on that arm's project after this point. - let upstream = format!("{api}/upstream"); - let as_committed = |text: &str| { - if checksums_lock { - text.replace(&format!("\"{upstream}\""), "\"https://rubygems.org\"") - .replace(&format!("{upstream}/"), "https://rubygems.org/") - } else { - text.to_string() - } - }; - for file in ["Gemfile", "Gemfile.lock"] { - let path = fx.proj.join(file); - let text = std::fs::read_to_string(&path).unwrap(); - 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)], - ); - assert_eq!(code, 0, "takeover:\nstdout:\n{stdout}\nstderr:\n{stderr}"); - 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/"), - "premise: the gem is vendored:\n{vendored_lock}\nstdout:\n{stdout}" - ); - assert_eq!( - std::fs::read_to_string(&warm_lib).unwrap(), - patched, - "premise: the takeover leaves the patched platform copy installed" - ); - // `remove` and `vendor --revert`, each over its own copy of the - // project; `rollback` runs on the project itself below. - for command in ["remove", "vendor --revert"] { - let dir = fx.tmp.path().join(format!("unwind-{}", &command[..6])); - copy_dir_recursive(&fx.proj, &dir); - // What a `bundle cache` taken under the hosted pin left: this - // machine's patched prebuild in Bundler's cache dir. - let cached = dir.join("vendor/cache").join(format!("{own_leaf}.gem")); - let prebuild = patched_builds.iter().find(|b| b.token == token(&own)); - std::fs::create_dir_all(cached.parent().unwrap()).unwrap(); - std::fs::write(&cached, &prebuild.expect("own prebuild").gem).unwrap(); - let cwd = dir.to_str().expect("utf8 tmp path"); - let mut argv: Vec<&str> = match command { - "remove" => vec!["remove", PURL, "--yes"], - _ => vec!["vendor", "--revert", "--yes"], - }; - argv.extend([ - "--json", - "--cwd", - cwd, - "--api-url", - &api, - "--org", - ORG, - "--api-token", - "fake", - "--patch-server-url", - &api, - ]); - let (code, stdout, stderr) = - run_socket_env(&dir, &argv, &[("SOCKET_RUBYGEMS_URL", &upstream)]); - assert_eq!(code, 0, "{command}:\nstdout:\n{stdout}\nstderr:\n{stderr}"); - assert_eq!( - std::fs::read_to_string(dir.join("Gemfile.lock")).unwrap(), - as_committed(&pristine_lock), - "{command} must hand the lock back byte for byte" - ); - assert_eq!( - std::fs::read_to_string(fresh_installed_lib(&dir, &own_leaf, "vuln_gem.rb")) - .unwrap(), - orig, - "{command}: the installed platform copy is the upstream build again:\n{stdout}" - ); - assert!( - stdout.contains("upstream_gem_install_refreshed") - && !stdout.contains("upstream_gem_stale_install"), - "{command}: the copy is refreshed, and nothing is left patched:\n{stdout}" - ); - // Both commands report a vendored unwind's advisories as events. - let env: serde_json::Value = serde_json::from_str(&stdout) - .unwrap_or_else(|e| panic!("{command}: not JSON: {e}\nstdout:\n{stdout}")); - let named: Vec = env["events"] - .as_array() - .into_iter() - .flatten() - .filter(|e| e["errorCode"] == "upstream_gem_stale_cache") - .map(|e| e.to_string()) - .collect(); - assert_eq!(named.len(), 1, "{command}: one stale-cache warning: {env}"); - assert!( - named[0].contains(&cached.display().to_string()) - && named[0].contains("non-upstream"), - "{command}: the patched platform archive in the cache dir is named: {}", - named[0] - ); - } + p.views_since(refreshing).await, + Vec::::new(), + "no patch record is fetched" + ); + // For a person, over the pair as it was committed: the two lines. + let (exit, stdout, stderr) = p.hosted(&committed, &["scan"], &known); + assert_eq!(exit, 0, "{stdout}\n{stderr}"); + let back = format!( + "{DEP} {DEP_VERSION}: patched for {foreign}; upstream gem back for {own} (its patched \ + build was withdrawn)" + ); + for line in [&back, &stays] { + assert!(stdout.contains(&format!("\n{line}\n")), "{line}\n{stdout}"); } - let (code, stdout, stderr) = run_socket_env( - &fx.proj, - &[ - "rollback", - PURL, - "--json", - "--cwd", - proj_str, - "--api-url", - &api, - "--org", - ORG, - "--api-token", - "fake", - "--patch-server-url", - &api, - ], - &[("SOCKET_RUBYGEMS_URL", &upstream)], - ); - assert_eq!(code, 0, "rollback:\nstdout:\n{stdout}\nstderr:\n{stderr}"); + assert!(!stderr.contains("Warning"), "{stderr}"); assert_eq!( - std::fs::read_to_string(fx.proj.join("Gemfile.lock")).unwrap(), - as_committed(&pristine_lock), - "rollback must hand the lock back byte for byte" + std::fs::read_to_string(committed.join("Gemfile.lock")).unwrap(), + lock ); + + // 4. Bundler agrees with the lock and installs upstream's gem. + bundle_ok(&p.fx.proj, &["lock"]); + assert_eq!( + p.lock(), + lock, + "`bundle lock` leaves the lock byte-identical" + ); + let fresh = p.install_fresh("fresh", &[("BUNDLE_FROZEN", "true")]); + p.assert_installed(&fresh, false); + let unfrozen = p.install_fresh("unfrozen", &[]); + p.assert_installed(&unfrozen, false); + bundle_ok(&p.fx.proj, &["install"]); + assert_eq!(p.lock(), lock, "`bundle install` leaves the lock alone"); + p.assert_installed(&p.fx.proj, false); + + // 5. A further scan changes nothing. + let again = p.mark().await; + let env = p.scan(&known); assert_eq!( - std::fs::read_to_string(fx.proj.join("Gemfile")).unwrap(), - as_committed(&String::from_utf8_lossy(&fx.pristine_gemfile)), - "rollback must hand the Gemfile back byte for byte" + p.lock(), + lock, + "a further scan leaves the lock byte-identical" ); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(env["redirect"]["rewrittenFiles"], serde_json::json!([])); + assert_eq!(hosted_events(&env), [skip_event], "{env}"); + let (fetched, redirected) = p.fetched_since(again).await; assert_eq!( - std::fs::read_to_string(&warm_lib).unwrap(), - orig, - "the installed platform copy is the upstream build again" + (fetched, redirected), + (Vec::new(), Vec::new()), + "nothing is downloaded" ); - assert!( - !stdout.contains("upstream_gem_stale_install") - && !stdout.contains("upstream_gem_stale_cache"), - "nothing is left on the patched build:\n{stdout}" + assert_eq!( + p.indexes_since(again).await, + [format!("{}info/{DEP}", &second[api.len()..])], + "the registry the lock is on, at the snapshot it names" ); - // The arm whose pair still names the mock upstream: bundler loads the - // upstream code, and a reinstall from the gem home's archive succeeds. - if takeover && !checksums_lock { - let probe = "require \"vuln_gem\"; print VulnGem.status"; - for args in [&["install"][..], &["pristine"]] { - let out = bundle(&fx.proj, args); - assert!( - out.status.success(), - "bundle {args:?} after the unwind:\nstdout:\n{}\nstderr:\n{}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr) - ); - let run = bundle(&fx.proj, &["exec", "ruby", "-e", probe]); - assert_eq!( - String::from_utf8_lossy(&run.stdout), - "VULNERABLE", - "bundle {args:?} leaves the upstream code loaded:\n{}", - String::from_utf8_lossy(&run.stderr) - ); - } - } - - // 6. Standalone VEX over the fresh checkout bundler installed. - 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, - patched_builds: &[IndexBuild], - platforms: &[&str], -) { - 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(); - 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)); - } - 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": fx.index_url, - "identifiers": { - "name": DEP, - "version": DEP_VERSION, - "gemChecksumSha256": ruby_sha, - "gemPlatforms": gem_platforms, - } - } - } - } - }))) - .with_priority(1) - .mount(server) - .await; - for (leaf, bytes) in served { - Mock::given(method("GET")) - .and(path(format!("{stubs}/{leaf}"))) - .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) - .mount(server) - .await; - } + p.assert_installed(&p.fx.proj, false); } #[tokio::test(flavor = "multi_thread")] #[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] -async fn gem_hosted_platform_prebuilds_install_frozen_and_roll_back() { - platform_prebuilds_install_frozen_and_roll_back( - "platform-prebuilds-checksums", - true, - false, - false, +async fn gem_hosted_lock_held_by_another_build_follows_its_patch_past_a_withdrawn_build() { + lock_that_stays_is_brought_to_its_patchs_current_listing( + "platform-withdrawn-held", + Has::Upstream, + "redirect_gem_newer_fix_waits", ) .await; } @@ -7665,47 +10547,70 @@ async fn gem_hosted_platform_prebuilds_install_frozen_and_roll_back() { #[tokio::test(flavor = "multi_thread")] #[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.6 for the CHECKSUMS lock); \ the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] -async fn gem_hosted_platform_prebuilds_beside_the_ruby_entry_install_frozen_and_roll_back() { - platform_prebuilds_install_frozen_and_roll_back( - "platform-prebuilds-ruby-entry", - true, - true, - false, +async fn gem_hosted_lock_left_by_an_unlisted_platform_follows_its_patch_past_a_withdrawn_build() { + lock_that_stays_is_brought_to_its_patchs_current_listing( + "platform-withdrawn-unlisted", + Has::Building, + "redirect_gem_platform_unlisted", ) .await; } -#[tokio::test(flavor = "multi_thread")] -#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.2); \ - the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] -async fn gem_hosted_platform_prebuilds_without_checksums_install_frozen_and_roll_back() { - platform_prebuilds_install_frozen_and_roll_back("platform-prebuilds", false, false, false) - .await; -} - -/// #2174: a platform gem that went from hosted to vendored, then unwound. +/// The stale-install refresh downloads `gems/` from the patch +/// registry, which may answer a file with a redirect (it does for every +/// platform it has no patched build of). The download follows it: here +/// the registry answers the file of this machine's patched build with a +/// 302 to another host, and the copy bundler had installed is replaced +/// with the gem that host serves, verified against the sha256 the list +/// names. #[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_vendored_unwind_restores_a_platform_install_the_hosted_scan_patched() { - platform_prebuilds_install_frozen_and_roll_back( - "platform-prebuilds-takeover-checksums", - true, - false, - true, - ) - .await; -} +async fn gem_hosted_refresh_follows_a_redirect_from_the_patch_registry() { + let Some(mut p) = + PlatformProject::start("platform-refresh-302", (2, 6), true, false, &[]).await + else { + return; + }; + let (own, foreign) = (p.own.clone(), p.foreign.clone()); + let every = [ + (own.as_str(), Has::Patched), + (foreign.as_str(), Has::Patched), + ]; + let index_url = p.serve(Some(&every)).await; + let file = format!("{}.gem", p.own_leaf()); + let elsewhere = format!("/elsewhere/{file}"); + Mock::given(method("GET")) + .and(path(format!("{}gems/{file}", &index_url[p.api().len()..]))) + .respond_with( + ResponseTemplate::new(302) + .insert_header("Location", format!("{}{elsewhere}", p.files.uri()).as_str()) + .insert_header("Cache-Control", "no-store"), + ) + .with_priority(1) + .mount(&p.fx._server) + .await; + Mock::given(method("GET")) + .and(path(elsewhere.clone())) + .respond_with(ResponseTemplate::new(200).set_body_raw( + p.service.builds[&build_token(Some(&own))].clone(), + "application/octet-stream", + )) + .mount(&p.files) + .await; -#[tokio::test(flavor = "multi_thread")] -#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 2.3); \ - the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] -async fn gem_vendored_unwind_restores_a_platform_install_without_checksums() { - platform_prebuilds_install_frozen_and_roll_back( - "platform-prebuilds-takeover", - false, - false, - true, - ) - .await; + let env = p.scan(&[]); + assert_eq!( + warning_codes(&env), + ["redirect_gem_install_refreshed"], + "{env}" + ); + assert_eq!( + std::fs::read_to_string(p.installed_lib(&p.fx.proj)).unwrap(), + p.service.patched, + "the installed copy is the patched build" + ); + let served = p.files.received_requests().await.unwrap_or_default(); + let served: Vec<&str> = served.iter().map(|request| request.url.path()).collect(); + assert_eq!(served, [elsewhere], "the download followed the redirect"); } diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs new file mode 100644 index 0000000000..34ad9fbb53 --- /dev/null +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_platform_builds.rs @@ -0,0 +1,4640 @@ +//! Hosted mode over a gem the Bundler lock names as precompiled platform +//! builds (`nokogiri (1.19.3-x86_64-linux-gnu)`), against a wiremock patch +//! API (real binary, no Ruby or Bundler: nothing is installed here). +//! +//! The gem's fix is one patch, the ruby-platform gem's. Its reference lists +//! every platform gem of the version (`gemBuilds`): the sha256 the patch +//! registry serves and, where there is a patched build, the patch it comes +//! from. A platform with none is served as upstream's own gem. So: +//! +//! * every locked build moves to the registry together as soon as one of +//! them is patched, each pinned to the sha256 listed for it, with no +//! warning; +//! * the run reports the gem per locked build: an `applied` event under +//! the build's own patch, an uncounted `gem_upstream_build_kept` event +//! for a build that stays upstream's gem, and one plain line for people; +//! * a gem with no patched build for any locked platform is left where it +//! is, under a quiet skip; +//! * a later run on the same registry snapshot changes nothing, and one on +//! a newer snapshot refreshes the URL and says which builds it found +//! patched. A lock with `CHECKSUMS` says what each build was; one +//! without is told by the snapshot it names, in one request; +//! * a platform the registry does not list leaves the gem alone under a +//! quiet skip, and a reference with no list at all under the warning +//! `redirect_gem_platform_unsupported`; +//! * a lock whose patched build was withdrawn follows the list back to +//! upstream's gem, and is then counted as no package on a hosted patch; +//! * a lock on the registry of another patch of the gem moves to the patch +//! on offer only when no locked build would turn from a patched build +//! that registry still serves into upstream's gem, which one request to +//! the registry it is on says; otherwise it stays, under a quiet skip. A +//! build that registry withdrew holds nothing back: the lock moves, and +//! the run says that the build is back on upstream's gem; +//! * a lock that stays on another patch of the gem, while that patch has +//! withdrawn a build the lock pins, is brought to that patch's current +//! listing: the run takes that patch's reference (the one its check of +//! the pins holds, else one request), writes its current snapshot with +//! upstream's sha256 back for the withdrawn build, and skips the patch +//! on offer as before; +//! * a gem the lock names as its ruby-platform gem alone takes the +//! registry without its snapshot level, so a pair pinned by a reference +//! with no list is left byte for byte by one with a list. +//! +//! The VEX document is truthful per locked build, in the run's own `--vex` +//! and in a later `socket-patch vex` over the lock the run left: +//! +//! * a patched build is `not_affected` under its own patch, a build on +//! upstream's gem is `affected`, and no statement names a form of the gem +//! that stands for both; +//! * the run's own document costs no request beyond the run's; a later +//! `vex` asks for the gem patch's reference once, and for the index of +//! the lock's registry only when the lock has no `CHECKSUMS`; +//! * a build is attested by its patch only on the sha256 the lock installs +//! for it: one the lock pins otherwise, or that nothing could be read +//! about (`--offline`, a failed request, an unreadable index), is said +//! `affected`, with why and what to run. That is no failure: the run +//! exits 0 as a success, and one warning names the gem +//! (`vex_gem_build_unknown`); +//! * a gem locked as its ruby-platform gem alone is one pin, with no +//! request of its own. + +use std::path::Path; + +use serde_json::{json, Value}; +use wiremock::matchers::{body_partial_json, method, path, path_regex}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +#[path = "common/mod.rs"] +mod common; +use common::envelope::warning_codes; +#[path = "common/pty_io.rs"] +mod pty_io; +#[path = "vex_e2e_common/mod.rs"] +mod vex_e2e_common; + +const ORG: &str = "test-org"; +const DEP: &str = "platform-probe"; +const DEP_VERSION: &str = "1.19.3"; +const PURL: &str = "pkg:gem/platform-probe@1.19.3"; +/// The gem's patch: the one fix, selected as for any gem. +const UUID: &str = "7b1e4f3a-2c5d-4e6f-8a9b-0c1d2e3f4a5b"; +/// The patches of its patched platform builds. +const ARM_UUID: &str = "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d"; +const LINUX_UUID: &str = "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e"; +const TOKEN: &str = "66666666-6666-4666-8666-666666666666"; +const GHSA: &str = "GHSA-plat-form-gems"; +/// Shaped like a Socket API token, so no run warns about the token itself. +const API_TOKEN: &str = "sktsec_00000000000000000000000000000000000000000000_api"; + +const ARM: &str = "arm64-darwin"; +const LINUX: &str = "x86_64-linux-gnu"; + +/// The sha256 a lock pins before any run: upstream's own platform gems. +const ARM_UPSTREAM: &str = "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0"; +const LINUX_UPSTREAM: &str = "b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0"; +/// The sha256 of the patched gems. +const RUBY_PATCHED: &str = "c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1"; +const ARM_PATCHED: &str = "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1"; +const LINUX_PATCHED: &str = "b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1"; +const RACC: &str = "5555555555555555555555555555555555555555555555555555555555555555"; + +/// One platform gem as a reference lists it (`gemBuilds`): its platform, +/// the sha256 the registry serves, and the patch of its patched build +/// (`None`: the registry serves upstream's own gem). +type Listed = (&'static str, &'static str, Option<&'static str>); + +/// `arm64-darwin` on upstream's gem, `x86_64-linux-gnu` patched. +const ONE_PATCHED: [Listed; 2] = [ + (ARM, ARM_UPSTREAM, None), + (LINUX, LINUX_PATCHED, Some(LINUX_UUID)), +]; +const BOTH_PATCHED: [Listed; 2] = [ + (ARM, ARM_PATCHED, Some(ARM_UUID)), + (LINUX, LINUX_PATCHED, Some(LINUX_UUID)), +]; +const NONE_PATCHED: [Listed; 2] = [(ARM, ARM_UPSTREAM, None), (LINUX, LINUX_UPSTREAM, None)]; + +/// The registry URL a reference names: with the snapshot level when it +/// lists platform gems, plain when it does not. +fn index_url(api: &str, snapshot: Option) -> String { + registry_url(api, UUID, snapshot) +} + +/// [`index_url`] of the gem patch `uuid`. +fn registry_url(api: &str, uuid: &str, snapshot: Option) -> String { + let root = format!("{api}/patch-registry/gem/{TOKEN}/{uuid}/"); + match snapshot { + Some(snapshot) => format!("{root}s/{snapshot}"), + None => root, + } +} + +/// The reference of the gem patch `uuid` on `api`. `listing` is its +/// `gemBuilds` and the snapshot its registry URL names; `None` is a +/// reference with no list (a patch of the ruby gem alone). +fn reference(api: &str, uuid: &str, listing: Option<(&[Listed], u32)>) -> Value { + let mut identifiers = json!({ + "name": DEP, "version": DEP_VERSION, "gemChecksumSha256": RUBY_PATCHED, + }); + if let Some((builds, _)) = listing { + identifiers["gemBuilds"] = builds + .iter() + .map(|(platform, sha, patch)| { + json!({ "platform": platform, "gemChecksumSha256": sha, "patchUuid": patch }) + }) + .collect(); + } + let artifact = + format!("{api}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{uuid}/{DEP}-{DEP_VERSION}.gem"); + json!({ + "status": "granted", + "url": artifact, + "purl": PURL, + "artifacts": [{ + "kind": "tarball", "url": artifact, + "integrity": { "sha256": RUBY_PATCHED }, + }], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": registry_url(api, uuid, listing.map(|(_, snapshot)| snapshot)), + "identifiers": identifiers, + }, + }) +} + +/// Mount the patch API of the one gem patch, with [`reference`] of +/// `listing` as its reference. +async fn mount_api(server: &MockServer, listing: Option<(&[Listed], u32)>) { + let api = server.uri(); + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "packages": [{ "purl": PURL, "patches": [{ + "uuid": UUID, "purl": PURL, "tier": "free", "cveIds": [], + "ghsaIds": [GHSA], "severity": "high", "title": "platform gem 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(json!({ + "patches": [{ + "uuid": UUID, "purl": PURL, "publishedAt": "2026-01-01T00:00:00Z", + "description": "x", "license": "MIT", "tier": "free", + "vulnerabilities": { GHSA: { + "cves": ["CVE-2026-5555"], "summary": "s", "severity": "high", + "description": "d", + }}, + }], + "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(json!({ + "results": { UUID: reference(&api, UUID, listing) } + }))) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{UUID}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "uuid": UUID, "purl": PURL, "publishedAt": "2026-01-01T00:00:00Z", + "files": { "lib/platform_probe.rb": { + "beforeHash": "a".repeat(64), "afterHash": "b".repeat(64), + }}, + "vulnerabilities": { GHSA: { + "cves": ["CVE-2026-5555"], "summary": "s", "severity": "high", + "description": "d", + }}, + "description": "x", "license": "MIT", "tier": "free", + }))) + .mount(server) + .await; +} + +/// [`mount_api`] while a gem that the registry `current` lists is being +/// built again: the registry lists what it listed, under its key. A request +/// that presents that key (`gemSnapshotKeys`) is answered it, one that +/// presents another key is told the patch is not ready, and one with no key +/// is answered the registry of the ruby gem alone, with no list. +async fn mount_api_rebuilding(server: &MockServer, current: (&[Listed], u32)) { + let api = server.uri(); + let package = + || Mock::given(method("POST")).and(path(format!("/v0/orgs/{ORG}/patches/package"))); + let holding = json!({ "gemBuilds": true, "gemSnapshotKeys": { UUID: current.1.to_string() } }); + package() + .and(body_partial_json(holding)) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "results": { UUID: reference(&api, UUID, Some(current)) } + }))) + .with_priority(1) + .mount(server) + .await; + package() + .and(|request: &wiremock::Request| { + serde_json::from_slice::(&request.body) + .is_ok_and(|body| body["gemSnapshotKeys"][UUID].is_string()) + }) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "results": { UUID: { + "status": "pending_build", "url": null, "purl": null, "artifacts": [], + "registryOverride": null, + }} + }))) + .with_priority(2) + .mount(server) + .await; + mount_api(server, None).await; +} + +/// The bodies of the package reference requests `server` got. +async fn reference_bodies(server: &MockServer) -> Vec { + let requests = server.received_requests().await.unwrap_or_default(); + requests + .iter() + .filter(|request| request.url.path().ends_with("/patches/package")) + .filter_map(|request| serde_json::from_slice(&request.body).ok()) + .collect() +} + +const GEMFILE: &str = + "source \"https://rubygems.org\"\n\ngem \"platform-probe\", \"1.19.3\"\ngem \"racc\", \"1.8.1\"\n"; + +/// A lock that names the gem as its two platform builds, each pinned to +/// upstream's archive, beside a plain gem. `checksums: false` is the lock +/// of a Bundler that writes no `CHECKSUMS` section. +fn lock(checksums: bool) -> String { + let mut lock = format!( + "GEM\n remote: https://rubygems.org/\n specs:\n {DEP} ({DEP_VERSION}-{ARM})\n {DEP} \ + ({DEP_VERSION}-{LINUX})\n racc (1.8.1)\n\nPLATFORMS\n {ARM}\n {LINUX}\n\nDEPENDENCIES\n \ + {DEP} (= {DEP_VERSION})\n racc (= 1.8.1)\n\n" + ); + if checksums { + lock.push_str(&format!( + "CHECKSUMS\n {DEP} ({DEP_VERSION}-{ARM}) sha256={ARM_UPSTREAM}\n {DEP} \ + ({DEP_VERSION}-{LINUX}) sha256={LINUX_UPSTREAM}\n racc (1.8.1) sha256={RACC}\n\n" + )); + } + lock.push_str("BUNDLED WITH\n 4.0.15\n"); + lock +} + +/// [`lock`] as a hosted run leaves it: the gem's builds under the patch +/// registry `index` (with its closing slash), pinned to `arm` and `linux`. +fn hosted_lock(index: &str, arm: &str, linux: &str) -> String { + format!( + "GEM\n remote: {index}\n specs:\n {DEP} ({DEP_VERSION}-{ARM})\n {DEP} \ + ({DEP_VERSION}-{LINUX})\n\nGEM\n remote: https://rubygems.org/\n specs:\n racc \ + (1.8.1)\n\nPLATFORMS\n {ARM}\n {LINUX}\n\nDEPENDENCIES\n {DEP} (= {DEP_VERSION})!\n racc (= \ + 1.8.1)\n\nCHECKSUMS\n {DEP} ({DEP_VERSION}-{ARM}) sha256={arm}\n {DEP} \ + ({DEP_VERSION}-{LINUX}) sha256={linux}\n racc (1.8.1) sha256={RACC}\n\nBUNDLED WITH\n 4.0.15\n" + ) +} + +/// [`GEMFILE`] as a hosted run leaves it. +fn hosted_gemfile(index: &str) -> String { + GEMFILE.replace( + "gem \"platform-probe\", \"1.19.3\"\n", + &format!("gem \"platform-probe\", \"1.19.3\", source: \"{index}\"\n"), + ) +} + +/// A project with [`GEMFILE`] and `lock`, in a new temp dir. +fn project(lock: &str) -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("Gemfile"), GEMFILE).unwrap(); + std::fs::write(dir.path().join("Gemfile.lock"), lock).unwrap(); + dir +} + +fn read(proj: &Path, rel: &str) -> String { + std::fs::read_to_string(proj.join(rel)).unwrap() +} + +/// `socket-patch --mode hosted` over `proj` against `api`, with +/// `extra` arguments. +fn hosted(proj: &Path, api: &str, command: &[&str], extra: &[&str]) -> (i32, String, String) { + let mut args: Vec<&str> = command.to_vec(); + args.extend_from_slice(&[ + "--mode", + "hosted", + "--yes", + "--cwd", + proj.to_str().expect("utf8 temp path"), + "--api-url", + api, + "--org", + ORG, + "--api-token", + API_TOKEN, + ]); + args.extend_from_slice(extra); + common::run_with_env(proj, &args, &[]) +} + +/// A `--json` hosted scan: exit code and envelope. +fn scan_json(proj: &Path, api: &str, extra: &[&str]) -> (i32, Value) { + let mut args = vec!["--json"]; + args.extend_from_slice(extra); + let (code, stdout, stderr) = hosted(proj, api, &["scan"], &args); + let env: Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON ({e}):\n{stdout}\nstderr:\n{stderr}")); + (code, env) +} + +/// The run's hosted events (`details.mode: "hosted"`), in envelope order, +/// without `details.pinChanged`, which [`pin_changes`] reads: the tests +/// compare the rest of each event exactly. The event of every confirmed +/// pin (`applied`, or `verified` on a dry run) carries the key and no +/// other event does: not a skip, and not the advisory event of a build +/// left on upstream's gem, which names no patch in place. +fn hosted_events(env: &Value) -> Vec { + let mut events: Vec = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|event| event["details"]["mode"] == "hosted") + .cloned() + .collect(); + for event in &mut events { + let confirmed = event["action"] == "applied" || event["action"] == "verified"; + let said = event["details"] + .as_object_mut() + .and_then(|details| details.remove("pinChanged")); + assert_eq!( + said.is_some(), + confirmed, + "`pinChanged` is on the event of a confirmed pin alone: {env}" + ); + } + events +} + +/// `details.pinChanged` of each confirmed pin's event (`applied` / +/// `verified`), in envelope order. A gem the lock names as platform builds +/// has one pin, the gem patch's: every patched build's event says that +/// pin's change, whatever patch the build itself holds. +fn pin_changes(env: &Value) -> Vec> { + env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|event| event["details"]["mode"] == "hosted") + .filter(|event| event["action"] == "applied" || event["action"] == "verified") + .map(|event| event["details"]["pinChanged"].as_bool()) + .collect() +} + +/// The event of a patched build: `applied` (`verified` on a dry run) under +/// the build's own patch. +fn patched_event(action: &str, platform: &str, patch: &str, newly: bool) -> Value { + let mut details = json!({ "gemFix": UUID, "platform": platform, "mode": "hosted" }); + if newly { + details["newlyPatched"] = json!(true); + } + json!({ + "action": action, "purl": format!("{PURL}?platform={platform}"), "uuid": patch, + "details": details, + }) +} + +/// The uncounted event of a build that stays upstream's gem. +fn upstream_event(platform: &str) -> Value { + json!({ + "action": "skipped", + "purl": format!("{PURL}?platform={platform}"), + "errorCode": "gem_upstream_build_kept", + "reason": format!( + "the patch registry serves upstream's own gem for {platform}: no patched build yet" + ), + "details": { "gemFix": UUID, "platform": platform, "mode": "hosted" }, + }) +} + +/// The uuids each reference request of the run asked about, one list per +/// request, and the paths of every request that was no patch API call. +async fn requests(server: &MockServer) -> (Vec>, Vec) { + let mut references = Vec::new(); + let mut other = Vec::new(); + for request in server.received_requests().await.unwrap_or_default() { + let route = request.url.path().to_string(); + if route == format!("/v0/orgs/{ORG}/patches/package") { + let body: Value = serde_json::from_slice(&request.body).unwrap_or_default(); + references.push( + body["uuids"] + .as_array() + .into_iter() + .flatten() + .filter_map(|uuid| uuid.as_str().map(str::to_string)) + .collect(), + ); + } else if !route.starts_with(&format!("/v0/orgs/{ORG}/patches/")) { + other.push(route); + } + } + (references, other) +} + +/// Two locked platforms, one with a patched build and one without: the +/// gem moves, the platform without one keeps the sha256 it had, and the +/// run says so without a warning. One reference request, for the gem's +/// own patch, and no request to the registry. +#[tokio::test(flavor = "multi_thread")] +async fn a_gem_moves_as_soon_as_one_locked_build_is_patched() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&index, ARM_UPSTREAM, LINUX_PATCHED) + ); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&index)); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); + let summary = &env["summary"]; + assert_eq!( + (&summary["applied"], &summary["skipped"], &summary["failed"]), + (&json!(1), &json!(0), &json!(0)), + "the build on upstream's gem is counted nowhere: {env}" + ); + assert_eq!( + env["redirect"]["rewrittenFiles"], + json!(["Gemfile", "Gemfile.lock"]) + ); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, Vec::::new(), "no registry request"); + + // For a person: one plain line on stdout, and nothing that warns. + let proj = project(&lock(true)); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("Switched 1 package to hosted patches; rewrote 2 files.\n"), + "one package, whatever its builds:\n{stdout}" + ); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: patched for {LINUX}; upstream gem kept for {ARM} (no patched \ + build yet)\n" + )), + "{stdout}" + ); + assert!( + !stderr.contains("Warning") + && !stderr.contains("Skipped") + && !stderr.contains("Not hosted"), + "{stderr}" + ); + // `--silent` says nothing of it. + let proj = project(&lock(true)); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &["--silent"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + !stdout.contains(DEP) && !stderr.contains(DEP), + "{stdout}\n{stderr}" + ); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&index, ARM_UPSTREAM, LINUX_PATCHED) + ); + + // A dry run previews the same outcome and writes nothing. + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &["--dry-run"]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("verified", LINUX, LINUX_UUID, true) + ], + "{env}" + ); + assert_eq!(pin_changes(&env), [Some(true)], "the planned move: {env}"); + let (code, stdout, _) = hosted(proj.path(), &api, &["scan"], &["--dry-run"]); + assert_eq!(code, 0, "{stdout}"); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: would be patched for {LINUX}; upstream gem kept for {ARM} (no \ + patched build yet)\n" + )), + "{stdout}" + ); +} + +/// Every locked build has a patched build: one `applied` event per build, +/// each under its own patch, all naming the gem's patch as their fix. +#[tokio::test(flavor = "multi_thread")] +async fn every_patched_build_is_reported_under_its_own_patch() { + let server = MockServer::start().await; + mount_api(&server, Some((&BOTH_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&index, ARM_PATCHED, LINUX_PATCHED) + ); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + patched_event("applied", ARM, ARM_UUID, true), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); + assert_eq!(env["summary"]["applied"], 2, "{env}"); + assert_eq!(env["summary"]["skipped"], 0, "{env}"); + + let proj = project(&lock(true)); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("Switched 1 package to hosted patches; rewrote 2 files.\n"), + "{stdout}" + ); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: patched for {ARM}, {LINUX}\n" + )), + "{stdout}" + ); + assert!(!stderr.contains("Warning"), "{stderr}"); +} + +/// No locked build has a patched build yet: moving the gem would gain +/// nothing, so both files stay as they are. Exit 0, no warning, one +/// skipped event under the quiet code, and one plain line for a person +/// instead of the "No patches could be switched" block. +#[tokio::test(flavor = "multi_thread")] +async fn a_gem_with_no_patched_build_is_left_alone_quietly() { + let server = MockServer::start().await; + mount_api(&server, Some((&NONE_PATCHED[..], 4))).await; + let api = server.uri(); + let left = format!( + "{DEP} {DEP_VERSION}: no patched build yet for {ARM}, {LINUX}; left on its upstream \ + registry" + ); + + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); + assert_eq!(read(proj.path(), "Gemfile"), GEMFILE); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [json!({ + "action": "skipped", "purl": PURL, "uuid": UUID, + "errorCode": "redirect_gem_no_patched_build", "reason": left, + "details": { "mode": "hosted" }, + })], + "{env}" + ); + assert_eq!(env["summary"]["skipped"], 1, "{env}"); + assert_eq!(env["summary"]["applied"], 0, "{env}"); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + assert_eq!(env["redirect"]["rewrittenFiles"], json!([])); + + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains(&format!("\n{left}\n")), "{stdout}"); + assert!( + !stderr.contains("No patches could be switched") + && !stderr.contains("Warning") + && !stderr.contains(DEP), + "nothing on stderr names it:\n{stderr}" + ); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); +} + +/// Later runs. On the same snapshot nothing is written and no build is +/// reported as newly patched. A newer snapshot that lists one more patched +/// build refreshes the registry URL in both files, re-pins that build's +/// sha256 alone, and the run names it. A platform the lock gains afterwards +/// is reported with the others. +#[tokio::test(flavor = "multi_thread")] +async fn later_runs_report_what_changed_since() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + let first_lock = read(proj.path(), "Gemfile.lock"); + assert_eq!(first_lock, hosted_lock(&index, ARM_UPSTREAM, LINUX_PATCHED)); + assert_eq!(pin_changes(&env), [Some(true)], "the gem moved: {env}"); + + // The same snapshot again. + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(pin_changes(&env), [Some(false)], "nothing rewritten: {env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), first_lock); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&index)); + assert_eq!(env["redirect"]["rewrittenFiles"], json!([]), "{env}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, false) + ], + "in place, not newly patched: {env}" + ); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already on hosted patches; nothing to rewrite.\n"), + "{stdout}" + ); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: patched for {LINUX}; upstream gem kept for {ARM} (no patched \ + build yet)\n" + )), + "{stdout}" + ); + + // A newer snapshot: arm64-darwin has a patched build too. + server.reset().await; + mount_api(&server, Some((&BOTH_PATCHED[..], 5))).await; + let newer = format!("{}/", index_url(&api, Some(5))); + let hosted_pair = (first_lock.clone(), hosted_gemfile(&index)); + let human = project(&hosted_pair.0); + std::fs::write(human.path().join("Gemfile"), &hosted_pair.1).unwrap(); + + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&newer, ARM_PATCHED, LINUX_PATCHED), + "the URL and the one checksum that changed" + ); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&newer)); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + patched_event("applied", ARM, ARM_UUID, true), + patched_event("applied", LINUX, LINUX_UUID, false) + ], + "{env}" + ); + // The gem's one pin moved to the newer snapshot: both builds say so, + // the one that was patched before as well. + assert_eq!(pin_changes(&env), [Some(true), Some(true)], "{env}"); + let (code, stdout, stderr) = hosted(human.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: now also patched for {ARM}; already patched for {LINUX}\n" + )), + "{stdout}" + ); + assert!(!stderr.contains("Warning"), "{stderr}"); + assert_eq!( + read(human.path(), "Gemfile.lock"), + hosted_lock(&newer, ARM_PATCHED, LINUX_PATCHED) + ); + + // The lock gains a platform (`bundle lock --add-platform`), which the + // registry serves as upstream's gem: it is reported with the others, + // and nothing is rewritten for it. + const MUSL: &str = "x86_64-linux-musl"; + let musl_sha = "d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0"; + let mut listing: Vec = BOTH_PATCHED.to_vec(); + listing.push((MUSL, musl_sha, None)); + server.reset().await; + mount_api(&server, Some((&listing[..], 5))).await; + let gained = read(proj.path(), "Gemfile.lock") + .replace( + &format!(" {DEP} ({DEP_VERSION}-{LINUX})\n"), + &format!(" {DEP} ({DEP_VERSION}-{LINUX})\n {DEP} ({DEP_VERSION}-{MUSL})\n"), + ) + .replace( + &format!("PLATFORMS\n {ARM}\n {LINUX}\n"), + &format!("PLATFORMS\n {ARM}\n {LINUX}\n {MUSL}\n"), + ) + .replace( + &format!(" {DEP} ({DEP_VERSION}-{LINUX}) sha256={LINUX_PATCHED}\n"), + &format!( + " {DEP} ({DEP_VERSION}-{LINUX}) sha256={LINUX_PATCHED}\n {DEP} \ + ({DEP_VERSION}-{MUSL}) sha256={musl_sha}\n" + ), + ); + std::fs::write(proj.path().join("Gemfile.lock"), &gained).unwrap(); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), gained); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + patched_event("applied", ARM, ARM_UUID, false), + patched_event("applied", LINUX, LINUX_UUID, false), + upstream_event(MUSL), + ], + "{env}" + ); +} + +/// A lock with no `CHECKSUMS` section (Bundler before 2.6): the gem still +/// moves, pinned by source alone, and is reported per build. +#[tokio::test(flavor = "multi_thread")] +async fn a_lock_without_checksums_still_moves() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + + let proj = project(&lock(false)); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + let after = read(proj.path(), "Gemfile.lock"); + assert!( + after.starts_with(&format!( + "GEM\n remote: {index}\n specs:\n {DEP} ({DEP_VERSION}-{ARM})\n {DEP} \ + ({DEP_VERSION}-{LINUX})\n\nGEM\n remote: https://rubygems.org/\n" + )), + "{after}" + ); + assert!(!after.contains("CHECKSUMS"), "{after}"); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&index)); + assert_eq!( + warning_codes(&env), + ["redirect_gem_no_checksums_section"], + "the lock's own caveat, and nothing about platforms: {env}" + ); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); +} + +/// A reference with no list at all is a patch of the ruby gem alone: +/// nothing is written and the run says why. +#[tokio::test(flavor = "multi_thread")] +async fn a_patch_with_no_list_leaves_the_gem_alone_with_a_warning() { + let server = MockServer::start().await; + mount_api(&server, None).await; + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &server.uri(), &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); + assert_eq!(read(proj.path(), "Gemfile"), GEMFILE); + assert_eq!( + warning_codes(&env), + ["redirect_gem_platform_unsupported"], + "{env}" + ); + let detail = env["warnings"][0]["detail"].as_str().unwrap(); + assert!( + detail.contains( + "the patch service names no platform gem of this version right now (its answer is \ + the registry of the ruby platform gem alone)" + ), + "{detail}" + ); + assert_eq!( + hosted_events(&env), + [json!({ + "action": "skipped", "purl": PURL, "uuid": UUID, + "errorCode": "redirect_unconfirmed", + "reason": "no lockfile entry pinning it could be rewritten", + "details": { "mode": "hosted" }, + })], + "{env}" + ); +} + +/// A locked platform the list leaves out: a machine of that platform +/// would be sent to a registry with no gem for it, so the gem is left as +/// it is, with no warning and one plain line that says only that the +/// registry does not list the platform. A later run over a list that has +/// the platform moves it. +#[tokio::test(flavor = "multi_thread")] +async fn a_platform_missing_from_the_list_leaves_the_gem_as_it_is_quietly() { + let linux_only: [Listed; 1] = [(LINUX, LINUX_PATCHED, Some(LINUX_UUID))]; + let server = MockServer::start().await; + mount_api(&server, Some((&linux_only[..], 4))).await; + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &server.uri(), &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); + assert_eq!(read(proj.path(), "Gemfile"), GEMFILE); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + let unlisted = format!( + "{DEP} {DEP_VERSION}: the patch registry does not list {ARM}, so the gem is left as it is" + ); + assert_eq!( + hosted_events(&env), + [json!({ + "action": "skipped", "purl": PURL, "uuid": UUID, + "errorCode": "redirect_gem_platform_unlisted", + "reason": unlisted, + "details": { "mode": "hosted" }, + })], + "{env}" + ); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + + let (code, stdout, stderr) = hosted(proj.path(), &server.uri(), &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains(&format!("\n{unlisted}\n")), "{stdout}"); + assert!(!stderr.contains("Warning"), "{stderr}"); + + // The list names the platform: the gem moves. + let later = MockServer::start().await; + mount_api(&later, Some((&ONE_PATCHED[..], 5))).await; + let (code, env) = scan_json(proj.path(), &later.uri(), &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + assert_ne!(read(proj.path(), "Gemfile.lock"), lock(true)); +} + +/// Mount the searches of the patch API under `routes` (the organisation's +/// `/v0/orgs//patches`, or the public proxy's `/patch`), ahead of +/// [`mount_api`]'s own answers: each finds the gem's patch and the patch +/// record of its linux gem, the latter published later (it would rank +/// first). +async fn mount_searches_with_a_platform_gems_record(server: &MockServer, routes: &str) { + let platform_purl = format!("{PURL}?platform={LINUX}"); + let listed = |uuid: &str, purl: &str| { + json!({ + "uuid": uuid, "purl": purl, "tier": "free", "cveIds": [], + "ghsaIds": [GHSA], "severity": "high", "title": "platform gem fixture", + }) + }; + let found = |uuid: &str, purl: &str| { + json!({ + "uuid": uuid, "purl": purl, "publishedAt": "2026-02-01T00:00:00Z", + "description": "x", "license": "MIT", "tier": "free", + "vulnerabilities": { GHSA: { + "cves": ["CVE-2026-5555"], "summary": "s", "severity": "high", + "description": "d", + }}, + }) + }; + Mock::given(method("POST")) + .and(path(format!("{routes}/batch"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "packages": [{ "purl": PURL, "patches": [ + listed(UUID, PURL), listed(LINUX_UUID, &platform_purl), + ]}], + "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path_regex(format!("^{routes}/by-package/.+$"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "patches": [found(LINUX_UUID, &platform_purl), found(UUID, PURL)], + "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(server) + .await; +} + +/// The patch service also has a patch record per patched platform gem +/// (`pkg:gem/@?platform=`), which a search +/// returns beside the gem's own. Agent mode takes those; a hosted run +/// patches the gem through its own patch alone. The platform gem's record +/// is no selection of its own: one reference request for the one patch, +/// no skip, and a later run offers no "newer patch". +#[tokio::test(flavor = "multi_thread")] +async fn a_platform_gems_own_record_is_no_fix_of_its_own() { + let server = MockServer::start().await; + mount_searches_with_a_platform_gems_record(&server, &format!("/v0/orgs/{ORG}/patches")).await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "the gem is reported per build, and nothing is skipped: {env}" + ); + let selected: Vec<&Value> = env["packages"] + .as_array() + .unwrap() + .iter() + .flat_map(|package| package["selectedUuids"].as_array().unwrap()) + .collect(); + assert_eq!(selected, [&json!(UUID)], "{env}"); + let (references, _) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + + // A later run: in place, and no patch is offered as newer. + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["updates"], json!([]), "{env}"); + assert_eq!(env["rollout"]["counts"]["upgrade"], 0, "{env}"); + assert_eq!(env["redirect"]["rewrittenFiles"], json!([]), "{env}"); + + // `get` for the gem takes the gem's own patch alone, too. + let fresh = project(&lock(true)); + let (code, stdout, stderr) = hosted(fresh.path(), &api, &["get", PURL], &["--json"]); + let env: Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON ({e}):\n{stdout}\nstderr:\n{stderr}")); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); +} + +/// The run's client is where the platform gem's record is left out, so +/// what it remembers and the client it falls back to leave it out too. +/// A scan of two project directories asks the patch service once for both +/// and answers the second from memory: each directory moves through the +/// gem's own patch. And a run the API refuses (401) goes on with the +/// public proxy, whose searches find the same record: the outcome is the +/// one of the organisation's route. +#[tokio::test(flavor = "multi_thread")] +async fn a_platform_gems_own_record_is_no_fix_from_memory_or_on_the_public_proxy() { + // Two project directories, one run. + let server = MockServer::start().await; + mount_searches_with_a_platform_gems_record(&server, &format!("/v0/orgs/{ORG}/patches")).await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let root = tempfile::tempdir().unwrap(); + for dir in ["a", "b"] { + std::fs::create_dir(root.path().join(dir)).unwrap(); + std::fs::write(root.path().join(dir).join("Gemfile"), GEMFILE).unwrap(); + std::fs::write(root.path().join(dir).join("Gemfile.lock"), lock(true)).unwrap(); + } + let (code, stdout, stderr) = hosted(root.path(), &api, &["scan", "a", "b"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + for dir in ["a", "b"] { + assert_eq!( + read(&root.path().join(dir), "Gemfile.lock"), + hosted_lock(&index, ARM_UPSTREAM, LINUX_PATCHED), + "{dir}:\n{stdout}\n{stderr}" + ); + } + assert!(!stderr.contains("Warning"), "{stderr}"); + let (references, _) = requests(&server).await; + assert_eq!( + references, + [[UUID.to_string()], [UUID.to_string()]], + "one reference request a directory, for the gem's patch alone" + ); + let searches = server.received_requests().await.unwrap_or_default(); + let searched = |route: &str| { + let paths = searches.iter().map(|request| request.url.path()); + paths.filter(|path| path.contains(route)).count() + }; + // (Where file descriptors are scarce a run asks directory by directory.) + if !socket_patch_core::crawlers::walk_pool::fd_limit_is_tight() { + assert_eq!( + (searched("/patches/batch"), searched("/patches/by-package/")), + (1, 1), + "premise: the second directory is answered from memory" + ); + } + + // The API refuses the token: the run goes on with the public proxy. + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .respond_with(ResponseTemplate::new(401).set_body_json(json!({ + "error": { "message": "Unauthorized" }, + }))) + .with_priority(1) + .mount(&server) + .await; + mount_searches_with_a_platform_gems_record(&server, "/patch").await; + let api = server.uri(); + Mock::given(method("POST")) + .and(path("/patch/package")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "results": { UUID: reference(&api, UUID, Some((&ONE_PATCHED[..], 4))) } + }))) + .mount(&server) + .await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &["--proxy-url", api.as_str()]); + assert_eq!(code, 0, "{env}"); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); + let selected: Vec<&Value> = env["packages"] + .as_array() + .unwrap() + .iter() + .flat_map(|package| package["selectedUuids"].as_array().unwrap()) + .collect(); + assert_eq!(selected, [&json!(UUID)], "{env}"); + let asked = server.received_requests().await.unwrap_or_default(); + let on_proxy: Vec<&str> = asked + .iter() + .map(|request| request.url.path()) + .filter(|path| path.starts_with("/patch/")) + .collect(); + assert!( + on_proxy.contains(&"/patch/batch") && on_proxy.iter().any(|p| p.contains("/by-package/")), + "premise: the searches ran on the public proxy: {on_proxy:?}" + ); + let referenced: Vec = asked + .iter() + .filter(|request| request.url.path() == "/patch/package") + .map(|request| { + serde_json::from_slice::(&request.body).unwrap_or_default()["uuids"].clone() + }) + .collect(); + assert_eq!(referenced, [json!([UUID])], "one reference request"); +} + +/// The one patched build a lock pins is withdrawn: the list has upstream's +/// gem for every locked platform. The lock follows it (the registry under +/// the earlier snapshot refuses that build from then on), and from there +/// on the gem installs nothing patched. So it is no package on a hosted +/// patch: no `applied` event, the summary line counts none, and no row +/// under it calls the gem patched; the line of the gem says what is true, +/// on the run that follows the withdrawal that the build is back on +/// upstream's gem, and from then on that both builds are upstream's. +#[tokio::test(flavor = "multi_thread")] +async fn a_gem_whose_builds_are_all_upstreams_is_no_package_on_a_hosted_patch() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &server.uri(), &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["summary"]["applied"], 1, "premise: {env}"); + + // The same registry, as it stands after the withdrawal. + server.reset().await; + mount_api(&server, Some((&NONE_PATCHED[..], 5))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(5))); + // The run that follows the withdrawal, over a copy of the pair: the + // build is reported as back on upstream's gem, counted nowhere, and + // the lock's own registry is not asked what it lists. + let before = format!("{}/", index_url(&api, Some(4))); + let copy = hosted_project(&before, ARM_UPSTREAM, LINUX_PATCHED, true); + assert_eq!( + read(copy.path(), "Gemfile.lock"), + read(proj.path(), "Gemfile.lock"), + "premise: the pair the first run left" + ); + let (code, env) = scan_json(copy.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [upstream_event(ARM), withdrawn_event(LINUX)], + "{env}" + ); + let summary = &env["summary"]; + assert_eq!( + (&summary["applied"], &summary["skipped"], &summary["failed"]), + (&json!(0), &json!(0), &json!(0)), + "{env}" + ); + assert_eq!( + read(copy.path(), "Gemfile.lock"), + hosted_lock(&index, ARM_UPSTREAM, LINUX_UPSTREAM) + ); + let (_, other) = requests(&server).await; + assert_eq!(other, Vec::::new(), "no registry request"); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&index, ARM_UPSTREAM, LINUX_UPSTREAM), + "the lock follows the list back to upstream's gem" + ); + assert!( + stdout.contains("Switched 0 packages to hosted patches; rewrote 2 files.\n"), + "{stdout}" + ); + assert!(!stdout.contains("already on hosted patches"), "{stdout}"); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: upstream gem back for {LINUX} (its patched build was \ + withdrawn); upstream gem kept for {ARM} (no patched build yet)\n" + )), + "{stdout}" + ); + assert!( + !stdout.contains(&format!("{DEP}@{DEP_VERSION} {GHSA}")), + "no row calls the gem patched:\n{stdout}" + ); + assert!(!stdout.contains("Nothing left to patch."), "{stdout}"); + + // In place afterwards: still nothing in effect, nothing rewritten. + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["summary"]["applied"], 0, "{env}"); + assert_eq!(env["redirect"]["rewrittenFiles"], json!([]), "{env}"); + assert_eq!( + hosted_events(&env), + [upstream_event(ARM), upstream_event(LINUX)], + "{env}" + ); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(!stdout.contains("already on hosted patches"), "{stdout}"); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: upstream gem kept for {ARM}, {LINUX} (no patched build yet)\n" + )), + "{stdout}" + ); +} + +/// `get --mode hosted` writes what `scan` writes and +/// reports the gem per build the same way. +#[tokio::test(flavor = "multi_thread")] +async fn get_reports_the_gem_as_scan_does() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + + let proj = project(&lock(true)); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["get", UUID], &["--json"]); + let env: Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON ({e}):\n{stdout}\nstderr:\n{stderr}")); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&index, ARM_UPSTREAM, LINUX_PATCHED) + ); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&index)); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, Vec::::new(), "no registry request"); + + let proj = project(&lock(true)); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["get", UUID], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: patched for {LINUX}; upstream gem kept for {ARM} (no patched \ + build yet)\n" + )), + "{stdout}" + ); + assert!(!stderr.contains("Warning"), "{stderr}"); +} + +/// The gem is one package to the rollout budget and to the severity floor, +/// however many of its builds are patched: a budget of one new patch admits +/// it whole, and a floor above its severity leaves it out whole. +#[tokio::test(flavor = "multi_thread")] +async fn rollout_and_the_severity_floor_count_the_gem_once() { + let server = MockServer::start().await; + mount_api(&server, Some((&BOTH_PATCHED[..], 4))).await; + let api = server.uri(); + + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &["--max-new-patches", "1"]); + assert_eq!(code, 0, "{env}"); + assert_eq!( + env["rollout"]["counts"], + json!({ "new": 1, "deferred": 0, "upgrade": 0, "already": 0 }), + "{env}" + ); + assert_eq!(env["rollout"]["deferred"], json!([]), "{env}"); + assert_eq!( + hosted_events(&env), + [ + patched_event("applied", ARM, ARM_UUID, true), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); + + let proj = project(&lock(true)); + let (code, env) = scan_json(proj.path(), &api, &["--min-severity", "critical"]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); + assert_eq!(env["policy"]["counts"]["filtered"], 1, "{env}"); + assert_eq!(hosted_events(&env), Vec::::new(), "{env}"); +} + +// ── A lock on the registry of another patch of the gem ──────────────── + +/// An earlier patch of the gem, which the lock of these tests is on while +/// the patch service offers [`UUID`] for it. +const EARLIER_UUID: &str = "9c8b7a6f-5e4d-4c3b-8a29-1f0e9d8c7b6a"; +/// The patch of the earlier patch's patched `x86_64-linux-gnu` build, and +/// the sha256 of that build. +const EARLIER_LINUX_UUID: &str = "3c4d5e6f-7a8b-4c9d-8e0f-1a2b3c4d5e6f"; +const EARLIER_LINUX_PATCHED: &str = + "b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2"; +/// What the earlier patch's reference lists, at snapshot `3`. +const EARLIER_BUILDS: [Listed; 2] = [ + (ARM, ARM_UPSTREAM, None), + (LINUX, EARLIER_LINUX_PATCHED, Some(EARLIER_LINUX_UUID)), +]; +/// A patch with a patched build for `arm64-darwin` alone. +const ARM_ONLY: [Listed; 2] = [ + (ARM, ARM_PATCHED, Some(ARM_UUID)), + (LINUX, LINUX_UPSTREAM, None), +]; + +/// The registry of the earlier patch on `origin`, as a lock names it. +fn earlier_index(origin: &str) -> String { + format!("{}/", registry_url(origin, EARLIER_UUID, Some(3))) +} + +/// [`mount_api`] for the patch on offer, whose reference lists `offered` +/// at snapshot `4`, with the earlier patch's reference granted beside it: +/// the lock's pin is a patch the service still serves. +async fn mount_api_beside_earlier(server: &MockServer, offered: &[Listed]) { + let api = server.uri(); + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "results": { + UUID: reference(&api, UUID, Some((offered, 4))), + EARLIER_UUID: reference(&api, EARLIER_UUID, Some((&EARLIER_BUILDS[..], 3))), + } + }))) + .with_priority(1) + .mount(server) + .await; + mount_api(server, Some((offered, 4))).await; +} + +/// The compact-index document of the earlier patch's registry, listing +/// `linux` as the sha256 of its `x86_64-linux-gnu` gem. +async fn mount_earlier_index(server: &MockServer, linux: &str) { + mount_earlier_listing(server, Some(linux)).await; +} + +/// The compact-index document of the earlier patch's registry: the patched +/// ruby gem, upstream's `arm64-darwin` gem, and the `x86_64-linux-gnu` gem +/// under the sha256 `linux` (`None`: that build was withdrawn, and the +/// registry does not list it). +async fn mount_earlier_listing(server: &MockServer, linux: Option<&str>) { + let mut listing = format!( + "---\n{DEP_VERSION} racc:~> 1.4|checksum:{RUBY_PATCHED}\n{DEP_VERSION}-{ARM} racc:~> \ + 1.4|checksum:{ARM_UPSTREAM}\n" + ); + if let Some(linux) = linux { + listing.push_str(&format!( + "{DEP_VERSION}-{LINUX} racc:~> 1.4|checksum:{linux}\n" + )); + } + Mock::given(method("GET")) + .and(path(earlier_index_path())) + .respond_with(ResponseTemplate::new(200).set_body_string(listing)) + .mount(server) + .await; +} + +fn earlier_index_path() -> String { + format!("/patch-registry/gem/{TOKEN}/{EARLIER_UUID}/s/3/info/{DEP}") +} + +/// The quiet skip of the patch on offer, left for a later run because the +/// lock would lose its patched `x86_64-linux-gnu` build. +fn newer_fix_waits() -> (String, Value) { + let line = format!( + "{DEP} {DEP_VERSION}: the newer fix has no patched build for {LINUX} yet; the lock stays \ + on the patch it is on" + ); + let event = json!({ + "action": "skipped", "purl": PURL, "uuid": UUID, + "errorCode": "redirect_gem_newer_fix_waits", "reason": line, + "details": { "mode": "hosted" }, + }); + (line, event) +} + +/// The lock is on an earlier patch of the gem, with a patched build for +/// `x86_64-linux-gnu`. The patch on offer has a patched build for +/// `arm64-darwin` alone: moving the lock would turn the linux build into +/// upstream's gem. The lock's `CHECKSUMS` say what it pins, and its +/// registry, asked once a run, that it still serves that build: both files +/// stay byte for byte, with no warning, one skipped event under the quiet +/// code and one plain line. +#[tokio::test(flavor = "multi_thread")] +async fn a_lock_on_an_earlier_patch_keeps_its_patched_build_and_waits_quietly() { + let server = MockServer::start().await; + mount_api_beside_earlier(&server, &ARM_ONLY[..]).await; + mount_earlier_index(&server, EARLIER_LINUX_PATCHED).await; + let api = server.uri(); + let earlier = earlier_index(&api); + let (lock, gemfile) = ( + hosted_lock(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED), + hosted_gemfile(&earlier), + ); + let (line, event) = newer_fix_waits(); + let known = ["--patch-server-url", api.as_str()]; + + for dry_run in [false, true] { + let proj = hosted_project(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED, true); + let mut extra = known.to_vec(); + extra.extend(dry_run.then_some("--dry-run")); + let (code, env) = scan_json(proj.path(), &api, &extra); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock); + assert_eq!(read(proj.path(), "Gemfile"), gemfile); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(hosted_events(&env), [event.clone()], "{env}"); + let summary = &env["summary"]; + assert_eq!( + (&summary["applied"], &summary["skipped"], &summary["failed"]), + (&json!(0), &json!(1), &json!(0)), + "{env}" + ); + assert_eq!(env["redirect"]["rewrittenFiles"], json!([]), "{env}"); + let (_, other) = requests(&server).await; + assert_eq!( + other, + vec![earlier_index_path(); if dry_run { 2 } else { 1 }], + "one request a run, to the registry the lock is on" + ); + } + + // For a person: the one line on stdout, and nothing that warns. + let proj = hosted_project(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED, true); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &known); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains(&format!("\n{line}\n")), "{stdout}"); + assert!( + !stderr.contains("No patches could be switched") + && !stderr.contains("Warning") + && !stderr.contains("Not hosted") + && !stderr.contains(DEP), + "nothing on stderr names it:\n{stderr}" + ); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock); + assert_eq!(read(proj.path(), "Gemfile"), gemfile); + + // `get` of the patch on offer leaves the lock where it is, too. + let (code, stdout, stderr) = hosted(proj.path(), &api, &["get", UUID], &["--json"]); + let env: Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON ({e}):\n{stdout}\nstderr:\n{stderr}")); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert_eq!(hosted_events(&env), [event.clone()], "{env}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock); + let (_, other) = requests(&server).await; + assert_eq!(other, vec![earlier_index_path(); 4], "one request a run"); + + // A registry that does not answer shows nothing either way: the lock + // stays, quietly, after the one request. + let server = MockServer::start().await; + mount_api_beside_earlier(&server, &ARM_ONLY[..]).await; + let api = server.uri(); + let earlier = earlier_index(&api); + let proj = hosted_project(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED, true); + let (code, env) = scan_json(proj.path(), &api, &["--patch-server-url", api.as_str()]); + assert_eq!(code, 0, "{env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED) + ); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(hosted_events(&env), [event], "{env}"); + let (_, other) = requests(&server).await; + assert_eq!(other, [earlier_index_path()], "asked once"); +} + +/// The uncounted event of a build the run put back on upstream's gem: the +/// patched build its lock entry pinned was withdrawn. +fn withdrawn_event(platform: &str) -> Value { + json!({ + "action": "skipped", + "purl": format!("{PURL}?platform={platform}"), + "errorCode": "gem_upstream_build_kept", + "reason": format!( + "the patch registry serves upstream's own gem for {platform}: its patched build was \ + withdrawn" + ), + "details": { "gemFix": UUID, "platform": platform, "withdrawn": true, "mode": "hosted" }, + }) +} + +/// The patched `x86_64-linux-gnu` build the lock pins from an earlier +/// patch was withdrawn: that patch's registry, under the snapshot the lock +/// names, no longer lists the build (or lists another sha256 for it), so +/// an install on that platform fails there. The patch on offer has no +/// patched build for that platform. Staying would keep the install +/// broken, so the lock moves: one request to the registry it is on, both +/// files rewritten for the patch on offer with upstream's sha256 back for +/// that build, exit 0, no warning, and the run says in one line and one +/// uncounted event that the build is back on upstream's gem. A dry run +/// previews the same and writes nothing; a further run changes nothing, +/// asks no registry, and no longer speaks of a withdrawal. +#[tokio::test(flavor = "multi_thread")] +async fn a_withdrawn_build_on_an_earlier_patch_moves_the_lock_to_the_patch_on_offer() { + let line = format!( + "{DEP} {DEP_VERSION}: patched for {ARM}; upstream gem back for {LINUX} (its patched \ + build was withdrawn)" + ); + let other_sha = "b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3"; + for served in [None, Some(other_sha)] { + let server = MockServer::start().await; + mount_api_beside_earlier(&server, &ARM_ONLY[..]).await; + mount_earlier_listing(&server, served).await; + let api = server.uri(); + let (earlier, offered) = ( + earlier_index(&api), + format!("{}/", index_url(&api, Some(4))), + ); + let known = ["--patch-server-url", api.as_str()]; + + // A dry run first: the same outcome, nothing written. + let proj = hosted_project(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED, true); + let before = read(proj.path(), "Gemfile.lock"); + let (code, env) = scan_json(proj.path(), &api, &[known[0], known[1], "--dry-run"]); + assert_eq!(code, 0, "{served:?}: {env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), before, "{served:?}"); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&earlier)); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + patched_event("verified", ARM, ARM_UUID, true), + withdrawn_event(LINUX) + ], + "{served:?}: {env}" + ); + let (code, stdout, stderr) = hosted( + proj.path(), + &api, + &["scan"], + &[known[0], known[1], "--dry-run"], + ); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: would be patched for {ARM}; upstream gem would be back \ + for {LINUX} (its patched build was withdrawn)\n" + )), + "{served:?}:\n{stdout}" + ); + assert_eq!(read(proj.path(), "Gemfile.lock"), before, "{served:?}"); + + // The run. + let asked_before = requests(&server).await.1.len(); + let (code, env) = scan_json(proj.path(), &api, &known); + assert_eq!(code, 0, "{served:?}: {env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&offered, ARM_PATCHED, LINUX_UPSTREAM), + "{served:?}: on the patch on offer, upstream's sha256 back for linux" + ); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&offered)); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + patched_event("applied", ARM, ARM_UUID, true), + withdrawn_event(LINUX) + ], + "{served:?}: {env}" + ); + let summary = &env["summary"]; + assert_eq!( + (&summary["applied"], &summary["skipped"], &summary["failed"]), + (&json!(1), &json!(0), &json!(0)), + "the build back on upstream's gem is counted nowhere: {env}" + ); + assert_eq!( + env["redirect"]["rewrittenFiles"], + json!(["Gemfile", "Gemfile.lock"]) + ); + let (_, other) = requests(&server).await; + assert_eq!( + other[asked_before..], + [earlier_index_path()], + "{served:?}: one request, to the registry the lock was on" + ); + + // A further run: in place, nothing asked, no withdrawal to speak of. + let (code, env) = scan_json(proj.path(), &api, &known); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["redirect"]["rewrittenFiles"], json!([]), "{env}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + patched_event("applied", ARM, ARM_UUID, false), + upstream_event(LINUX) + ], + "{served:?}: {env}" + ); + let (_, other) = requests(&server).await; + assert_eq!(other.len(), asked_before + 1, "no registry request"); + + // For a person: the one line on stdout, and nothing that warns. + let proj = hosted_project(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED, true); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &known); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("Switched 1 package to hosted patches; rewrote 2 files.\n"), + "{stdout}" + ); + assert!(stdout.contains(&format!("\n{line}\n")), "{stdout}"); + assert!( + !stderr.contains("Warning") + && !stderr.contains("Skipped") + && !stderr.contains("Not hosted"), + "{stderr}" + ); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&offered, ARM_PATCHED, LINUX_UPSTREAM) + ); + + // `get` of the patch on offer moves the lock the same way. + let proj = hosted_project(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED, true); + let (code, stdout, stderr) = hosted( + proj.path(), + &api, + &["get", UUID], + &["--json", known[0], known[1]], + ); + let env: Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON ({e}):\n{stdout}\nstderr:\n{stderr}")); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert_eq!( + hosted_events(&env), + [ + patched_event("applied", ARM, ARM_UUID, true), + withdrawn_event(LINUX) + ], + "{served:?}: {env}" + ); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&offered, ARM_PATCHED, LINUX_UPSTREAM) + ); + } +} + +/// On a terminal the line of a build that is back on upstream's gem breaks +/// after its first clause, under a hanging indent, at 80, 100 and 120 +/// columns, and neither row is wider than the terminal. (In a pipe it is +/// one line: the cases above read it there.) +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +async fn the_line_of_a_withdrawn_build_fits_a_terminal_of_80_100_and_120_columns() { + let server = MockServer::start().await; + mount_api_beside_earlier(&server, &ARM_ONLY[..]).await; + mount_earlier_listing(&server, None).await; + let api = server.uri(); + let earlier = earlier_index(&api); + for cols in [80u16, 100, 120] { + let proj = hosted_project(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED, true); + let cwd = proj.path().to_path_buf(); + let api = api.clone(); + let run = tokio::task::spawn_blocking(move || { + let dir = cwd.to_str().expect("utf8 temp path"); + let args = [ + "scan", + "--mode", + "hosted", + "--yes", + "--cwd", + dir, + "--api-url", + api.as_str(), + "--org", + ORG, + "--api-token", + API_TOKEN, + "--patch-server-url", + api.as_str(), + ]; + pty_io::run_command_at( + cols, + common::hermetic::pty_binary_command(), + &args, + &cwd, + &[], + &[], + std::time::Duration::from_secs(60), + ) + }) + .await + .expect("spawn_blocking join"); + let screen = pty_io::render(run.output.as_bytes()); + let shown = screen.join("\n"); + println!("--- {cols} columns\n{shown}"); + assert_eq!(run.code, 0, "{shown}"); + let at = screen + .iter() + .position(|row| row.starts_with(&format!("{DEP} {DEP_VERSION}: "))) + .unwrap_or_else(|| panic!("no line of the gem:\n{shown}")); + assert_eq!( + screen[at..at + 2], + [ + format!("{DEP} {DEP_VERSION}: patched for {ARM};"), + format!(" upstream gem back for {LINUX} (its patched build was withdrawn)"), + ], + "{cols} columns:\n{shown}" + ); + assert!( + screen[at..at + 2] + .iter() + .all(|row| row.chars().count() <= usize::from(cols)), + "wider than {cols} columns:\n{shown}" + ); + } +} + +/// The same withdrawal where the patch on offer has no patched build for +/// any platform the lock names. A lock on its upstream registry would be +/// left there (nothing to gain); a lock on a registry that refuses a build +/// it pins is not: it moves to the patch on offer all the same, every +/// build on upstream's sha256, so that every platform installs again. The +/// gem is then no package on a hosted patch. The run's own VEX and a +/// later `vex` say `affected` of both builds. +#[tokio::test(flavor = "multi_thread")] +async fn a_withdrawn_build_moves_the_lock_to_a_patch_with_no_patched_build_at_all() { + let server = MockServer::start().await; + mount_api_beside_earlier(&server, &NONE_PATCHED[..]).await; + mount_earlier_listing(&server, None).await; + mount_index(&server, ARM_UPSTREAM, LINUX_UPSTREAM).await; + let api = server.uri(); + let (earlier, offered) = ( + earlier_index(&api), + format!("{}/", index_url(&api, Some(4))), + ); + let known = ["--patch-server-url", api.as_str()]; + let line = format!( + "{DEP} {DEP_VERSION}: upstream gem back for {LINUX} (its patched build was withdrawn); \ + upstream gem kept for {ARM} (no patched build yet)" + ); + + let proj = hosted_project(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED, true); + let (code, env, doc) = scan_vex(proj.path(), &api); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&offered, ARM_UPSTREAM, LINUX_UPSTREAM), + "on the patch on offer, every build on upstream's sha256" + ); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&offered)); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [upstream_event(ARM), withdrawn_event(LINUX)], + "{env}" + ); + let summary = &env["summary"]; + assert_eq!( + (&summary["applied"], &summary["skipped"], &summary["failed"]), + (&json!(0), &json!(0), &json!(0)), + "{env}" + ); + assert_eq!( + env["redirect"]["rewrittenFiles"], + json!(["Gemfile", "Gemfile.lock"]) + ); + let (_, other) = requests(&server).await; + assert_eq!(other, [earlier_index_path()], "one registry request"); + // The run's own document: both builds affected. No build is + // attested, so the gem without a platform stands for affected builds + // alone and is named beside each. + let affected = |platform: &str| { + let mut statement = upstream_statement(platform); + statement.products.insert(0, PURL.to_string()); + statement + }; + assert_eq!( + said(&doc.expect("a document")), + [affected(ARM), affected(LINUX)], + "{env}" + ); + assert_eq!(env["vex"]["affected"], 2, "{env}"); + // And a later `vex` over the lock the run left. + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!(said(out.doc()), [affected(ARM), affected(LINUX)], "{out}"); + assert_eq!(out.envelope["status"], "success", "{out}"); + + // For a person. + let proj = hosted_project(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED, true); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &known); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("Switched 0 packages to hosted patches; rewrote 2 files.\n"), + "{stdout}" + ); + assert!(stdout.contains(&format!("\n{line}\n")), "{stdout}"); + assert!( + !stderr.contains("Warning") + && !stderr.contains("No patches could be switched") + && !stderr.contains("Not hosted"), + "{stderr}" + ); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&offered, ARM_UPSTREAM, LINUX_UPSTREAM) + ); +} + +/// The same lock with no `CHECKSUMS` says nothing of what it installs, so +/// the run asks the registry the lock is on, once: its compact-index +/// document for the gem. A registry that lists a patched build for +/// `x86_64-linux-gnu` keeps the lock where it is. One that lists +/// upstream's gem has nothing to lose, and the lock moves to the patch on +/// offer. A registry that does not answer keeps the lock where it is. +#[tokio::test(flavor = "multi_thread")] +async fn a_lock_without_checksums_on_an_earlier_patch_is_judged_by_its_registry() { + let (line, event) = newer_fix_waits(); + + // The registry lists a patched build: the lock stays. + let server = MockServer::start().await; + mount_api_beside_earlier(&server, &ARM_ONLY[..]).await; + mount_earlier_index(&server, EARLIER_LINUX_PATCHED).await; + let api = server.uri(); + let earlier = earlier_index(&api); + let known = ["--patch-server-url", api.as_str()]; + let proj = hosted_project(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED, false); + let lock = read(proj.path(), "Gemfile.lock"); + assert!(!lock.contains("CHECKSUMS"), "premise: {lock}"); + let (code, env) = scan_json(proj.path(), &api, &known); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&earlier)); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(hosted_events(&env), [event.clone()], "{env}"); + let (_, other) = requests(&server).await; + assert_eq!( + other, + [earlier_index_path()], + "one request, to the registry the lock is on" + ); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &known); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains(&format!("\n{line}\n")), "{stdout}"); + assert!(!stderr.contains("Warning"), "{stderr}"); + + // The registry lists upstream's gem: nothing to lose, the lock moves. + let server = MockServer::start().await; + mount_api_beside_earlier(&server, &ARM_ONLY[..]).await; + mount_earlier_index(&server, LINUX_UPSTREAM).await; + let api = server.uri(); + let (earlier, offered) = ( + earlier_index(&api), + format!("{}/", index_url(&api, Some(4))), + ); + let known = ["--patch-server-url", api.as_str()]; + let proj = hosted_project(&earlier, ARM_UPSTREAM, LINUX_UPSTREAM, false); + let (code, env) = scan_json(proj.path(), &api, &known); + assert_eq!(code, 0, "{env}"); + let after = read(proj.path(), "Gemfile.lock"); + assert!( + after.starts_with(&format!( + "GEM\n remote: {offered}\n specs:\n {DEP} ({DEP_VERSION}-{ARM})\n {DEP} \ + ({DEP_VERSION}-{LINUX})\n\nGEM\n remote: https://rubygems.org/\n" + )), + "{after}" + ); + assert!(!after.contains(EARLIER_UUID), "{after}"); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&offered)); + assert_eq!( + warning_codes(&env), + ["redirect_gem_no_checksums_section"], + "the lock's own caveat alone: {env}" + ); + assert_eq!( + hosted_events(&env), + [ + patched_event("applied", ARM, ARM_UUID, true), + upstream_event(LINUX) + ], + "{env}" + ); + let (_, other) = requests(&server).await; + assert_eq!(other, [earlier_index_path()], "one registry request"); + + // The registry does not answer: nothing shows what the lock installs. + let server = MockServer::start().await; + mount_api_beside_earlier(&server, &ARM_ONLY[..]).await; + let api = server.uri(); + let earlier = earlier_index(&api); + let proj = hosted_project(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED, false); + let lock = read(proj.path(), "Gemfile.lock"); + let (code, env) = scan_json(proj.path(), &api, &["--patch-server-url", api.as_str()]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(hosted_events(&env), [event], "{env}"); + let (_, other) = requests(&server).await; + assert_eq!(other, [earlier_index_path()], "asked once"); +} + +/// The patch on offer patches every build the earlier patch does: the +/// lock loses nothing, so it moves to the offered patch's registry, and +/// the run reports each locked build under the patch it then installs. +#[tokio::test(flavor = "multi_thread")] +async fn a_lock_on_an_earlier_patch_moves_to_a_patch_that_patches_as_much() { + let server = MockServer::start().await; + mount_api_beside_earlier(&server, &ONE_PATCHED[..]).await; + let api = server.uri(); + let (earlier, offered) = ( + earlier_index(&api), + format!("{}/", index_url(&api, Some(4))), + ); + let known = ["--patch-server-url", api.as_str()]; + + let proj = hosted_project(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED, true); + let (code, env) = scan_json(proj.path(), &api, &known); + assert_eq!(code, 0, "{env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&offered, ARM_UPSTREAM, LINUX_PATCHED) + ); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&offered)); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); + assert_eq!( + env["redirect"]["rewrittenFiles"], + json!(["Gemfile", "Gemfile.lock"]) + ); + let (_, other) = requests(&server).await; + assert_eq!(other, Vec::::new(), "no registry request"); + + let proj = hosted_project(&earlier, ARM_UPSTREAM, EARLIER_LINUX_PATCHED, true); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &known); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains(&format!( + "\n{DEP} {DEP_VERSION}: patched for {LINUX}; upstream gem kept for {ARM} (no patched \ + build yet)\n" + )), + "{stdout}" + ); + assert!(!stderr.contains("Warning"), "{stderr}"); +} + +/// Under a patch mirror the lock names the earlier patch's registry on +/// the mirror, which may ask for credentials the run was never given. The +/// document is read where the patch server serves it, like every download +/// of the run, and the mirror is asked nothing about it. +#[tokio::test(flavor = "multi_thread")] +async fn the_registry_of_a_lock_on_a_patch_mirror_is_read_from_the_patch_server() { + const PREFIX: &str = "/artifactory/socket-patch"; + let server = MockServer::start().await; + mount_api_beside_earlier(&server, &ARM_ONLY[..]).await; + mount_earlier_index(&server, EARLIER_LINUX_PATCHED).await; + let api = server.uri(); + // The mirror takes the run's check of the pin it would write, and + // wants credentials for anything else. + let mirror = MockServer::start().await; + Mock::given(method("HEAD")) + .and(path(format!( + "{PREFIX}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{UUID}/{DEP}-{DEP_VERSION}.gem" + ))) + .respond_with(ResponseTemplate::new(200)) + .mount(&mirror) + .await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(401)) + .mount(&mirror) + .await; + let base = format!("{}{PREFIX}", mirror.uri()); + + let on_mirror = earlier_index(&base); + let proj = hosted_project(&on_mirror, ARM_UPSTREAM, EARLIER_LINUX_PATCHED, false); + let lock = read(proj.path(), "Gemfile.lock"); + let (code, env) = scan_json(proj.path(), &api, &["--patch-mirror-url", base.as_str()]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&on_mirror)); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(hosted_events(&env), [newer_fix_waits().1], "{env}"); + let (_, other) = requests(&server).await; + assert_eq!( + other, + [earlier_index_path()], + "the patch server is asked, once" + ); + let asked_of_mirror: Vec = mirror + .received_requests() + .await + .unwrap_or_default() + .iter() + .map(|request| format!("{} {}", request.method, request.url.path())) + .filter(|request| request.contains("/info/")) + .collect(); + assert_eq!(asked_of_mirror, Vec::::new()); +} + +// ── A lock that stays on a patch which withdrew a build ─────────────── + +/// The patch of the earlier patch's patched `arm64-darwin` build, and the +/// sha256 of that build. +const EARLIER_ARM_UUID: &str = "4d5e6f7a-8b9c-4d0e-9f1a-2b3c4d5e6f7a"; +const EARLIER_ARM_PATCHED: &str = + "a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2"; +/// The earlier patch with a patched build for both platforms, as the lock +/// of these tests has it (snapshot `3`). +const EARLIER_BOTH: [Listed; 2] = [ + (ARM, EARLIER_ARM_PATCHED, Some(EARLIER_ARM_UUID)), + (LINUX, EARLIER_LINUX_PATCHED, Some(EARLIER_LINUX_UUID)), +]; +/// The snapshot the earlier patch's reference names once a build of it was +/// withdrawn. +const EARLIER_NOW: u32 = 6; + +/// What the patch service answers when it is asked for the reference of +/// the earlier patch. +#[derive(Clone)] +enum EarlierNow { + /// Granted, listing these builds at the snapshot [`EARLIER_NOW`]. + Lists(Vec), + /// Granted, with no list of the version's gems. + NoList, + /// Granted, as the reference of another package. + OtherPackage, + /// Not granted: this status. + Status(&'static str), + /// No answer for that patch. + Absent, + /// The request fails. + Fails, +} + +/// The patch API of the patch on offer ([`UUID`], whose reference lists +/// `offered` at snapshot `4`), which answers a reference request with the +/// patches it was asked for and no other: the one on offer, and the +/// earlier patch as `earlier` says. The earlier patch's record is served +/// too, for a VEX document. +async fn mount_api_refreshing(server: &MockServer, offered: &[Listed], earlier: EarlierNow) { + let api = server.uri(); + let on_offer = reference(&api, UUID, Some((offered, 4))); + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(move |request: &wiremock::Request| { + let asked: Value = serde_json::from_slice(&request.body).unwrap_or_default(); + let asked: Vec<&str> = asked["uuids"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + let mut results = serde_json::Map::new(); + if asked.contains(&UUID) { + results.insert(UUID.to_string(), on_offer.clone()); + } + if asked.contains(&EARLIER_UUID) { + let answer = match &earlier { + EarlierNow::Lists(builds) => Some(reference( + &api, + EARLIER_UUID, + Some((&builds[..], EARLIER_NOW)), + )), + EarlierNow::NoList => Some(reference(&api, EARLIER_UUID, None)), + EarlierNow::OtherPackage => { + let mut other = + reference(&api, EARLIER_UUID, Some((&EARLIER_BOTH[..], EARLIER_NOW))); + other["purl"] = json!("pkg:gem/another-gem@1.19.3"); + Some(other) + } + EarlierNow::Status(status) => Some(json!({ "status": status })), + EarlierNow::Absent => None, + EarlierNow::Fails => return ResponseTemplate::new(500), + }; + results.extend(answer.map(|answer| (EARLIER_UUID.to_string(), answer))); + } + ResponseTemplate::new(200).set_body_json(json!({ "results": results })) + }) + .with_priority(1) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{EARLIER_UUID}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "uuid": EARLIER_UUID, "purl": PURL, "publishedAt": "2025-12-01T00:00:00Z", + "files": { "lib/platform_probe.rb": { + "beforeHash": "a".repeat(64), "afterHash": "c".repeat(64), + }}, + "vulnerabilities": { GHSA: { + "cves": ["CVE-2026-5555"], "summary": "s", "severity": "high", + "description": "d", + }}, + "description": "x", "license": "MIT", "tier": "free", + }))) + .mount(server) + .await; + mount_api(server, Some((offered, 4))).await; +} + +/// The compact-index document of the earlier patch's registry at +/// `snapshot`: the patched ruby gem and `builds` (`(platform, sha256)`). +async fn mount_earlier_snapshot(server: &MockServer, snapshot: u32, builds: &[(&str, &str)]) { + let mut listing = format!("---\n{DEP_VERSION} racc:~> 1.4|checksum:{RUBY_PATCHED}\n"); + for (platform, sha256) in builds { + listing.push_str(&format!( + "{DEP_VERSION}-{platform} racc:~> 1.4|checksum:{sha256}\n" + )); + } + Mock::given(method("GET")) + .and(path(earlier_snapshot_path(snapshot))) + .respond_with(ResponseTemplate::new(200).set_body_string(listing)) + .mount(server) + .await; +} + +fn earlier_snapshot_path(snapshot: u32) -> String { + format!("/patch-registry/gem/{TOKEN}/{EARLIER_UUID}/s/{snapshot}/info/{DEP}") +} + +/// An event of a build of the gem under the earlier patch: `applied` +/// (`verified` on a dry run) under `patch`, or, with none, the uncounted +/// event of a build that is back on upstream's gem. +fn earlier_event(action: &str, platform: &str, patch: Option<&str>) -> Value { + let purl = format!("{PURL}?platform={platform}"); + match patch { + Some(patch) => json!({ + "action": action, "purl": purl, "uuid": patch, + "details": { "gemFix": EARLIER_UUID, "platform": platform, "mode": "hosted" }, + }), + None => json!({ + "action": "skipped", "purl": purl, "errorCode": "gem_upstream_build_kept", + "reason": format!( + "the patch registry serves upstream's own gem for {platform}: its patched \ + build was withdrawn" + ), + "details": { + "gemFix": EARLIER_UUID, "platform": platform, "withdrawn": true, + "mode": "hosted", + }, + }), + } +} + +/// The counted skip of the patch on offer: its code and its line. +fn offer_skip(code: &str, line: &str) -> Value { + json!({ + "action": "skipped", "purl": PURL, "uuid": UUID, + "errorCode": code, "reason": line, + "details": { "mode": "hosted" }, + }) +} + +/// One situation in which a lock stays on the earlier patch: what the +/// patch on offer lists, the build the earlier patch withdrew and the one +/// it still serves (each with the sha256 the lock pins and the patch of +/// that build), the sha256 of upstream's gem for the withdrawn one, and +/// the quiet skip of the patch on offer. +struct Stays { + offered: Vec, + withdrawn: (&'static str, &'static str), + served: (&'static str, &'static str, &'static str), + upstream: &'static str, + skip: (&'static str, String), +} + +impl Stays { + /// The patch on offer serves upstream's gem for both platforms: the + /// lock is held for the linux build, and arm64-darwin was withdrawn. + fn held() -> Stays { + Stays { + offered: NONE_PATCHED.to_vec(), + withdrawn: (ARM, EARLIER_ARM_PATCHED), + served: (LINUX, EARLIER_LINUX_PATCHED, EARLIER_LINUX_UUID), + upstream: ARM_UPSTREAM, + skip: ("redirect_gem_newer_fix_waits", newer_fix_waits().0), + } + } + + /// The patch on offer does not list arm64-darwin, and has a patched + /// build for linux, which the earlier patch withdrew. + fn unlisted() -> Stays { + Stays { + offered: vec![(LINUX, LINUX_PATCHED, Some(LINUX_UUID))], + withdrawn: (LINUX, EARLIER_LINUX_PATCHED), + served: (ARM, EARLIER_ARM_PATCHED, EARLIER_ARM_UUID), + upstream: LINUX_UPSTREAM, + skip: ( + "redirect_gem_platform_unlisted", + format!( + "{DEP} {DEP_VERSION}: the newer fix's registry does not list {ARM}; the lock \ + stays on the patch it is on" + ), + ), + } + } + + /// What the earlier patch's reference lists once the build was + /// withdrawn: upstream's gem for it, the other build as it was. + fn earlier_now(&self) -> Vec { + let mut now = vec![ + (self.withdrawn.0, self.upstream, None), + (self.served.0, self.served.1, Some(self.served.2)), + ]; + now.sort(); + now + } + + /// `(arm64-darwin, x86_64-linux-gnu)` as the lock pins them once it + /// followed the earlier patch's reference. + fn pins_now(&self) -> (&'static str, &'static str) { + if self.withdrawn.0 == ARM { + (self.upstream, self.served.1) + } else { + (self.served.1, self.upstream) + } + } + + /// The stand-in for this situation: the earlier patch's registry at + /// the snapshot the lock names lists the build it still serves and + /// not the withdrawn one, and at its current snapshot what its + /// reference lists. + async fn mount(&self, server: &MockServer, earlier: EarlierNow) { + mount_api_refreshing(server, &self.offered, earlier).await; + mount_earlier_snapshot(server, 3, &[(self.served.0, self.served.1)]).await; + let now: Vec<(&str, &str)> = self + .earlier_now() + .iter() + .map(|(platform, sha256, _)| (*platform, *sha256)) + .collect(); + mount_earlier_snapshot(server, EARLIER_NOW, &now).await; + } + + /// The line of the earlier patch's builds once the lock followed its + /// reference. + fn line(&self, dry_run: bool) -> String { + let back = if dry_run { "would be back" } else { "back" }; + format!( + "{DEP} {DEP_VERSION}: patched for {}; upstream gem {back} for {} (its patched build \ + was withdrawn)", + self.served.0, self.withdrawn.0 + ) + } + + /// The run's hosted events once the lock followed the earlier patch's + /// reference, in envelope order. + fn events(&self, action: &str) -> Vec { + let mut builds = vec![ + earlier_event(action, self.withdrawn.0, None), + earlier_event(action, self.served.0, Some(self.served.2)), + ]; + builds.sort_by_key(|event| event["purl"].as_str().map(str::to_string)); + let mut events = vec![offer_skip(self.skip.0, &self.skip.1)]; + events.extend(builds); + events + } +} + +/// A project whose lock is on the earlier patch at snapshot `3`, with both +/// builds patched there. +fn project_on_earlier(api: &str, checksums: bool) -> tempfile::TempDir { + let earlier = earlier_index(api); + hosted_project( + &earlier, + EARLIER_ARM_PATCHED, + EARLIER_LINUX_PATCHED, + checksums, + ) +} + +/// A lock stays on an earlier patch of the gem (the patch on offer would +/// take a patched build from it, or does not list a locked platform), and +/// that patch has withdrawn another build the lock pins: its registry, +/// asked once, no longer lists it, so that platform no longer installs. +/// The run brings the lock to the earlier patch's current listing: both +/// files name its current snapshot, the withdrawn build is back on +/// upstream's sha256 and the build it still serves is as it was. Exit 0 +/// with no warning: the earlier patch's builds are reported as for a lock +/// that follows a withdrawal on its own patch, the patch on offer is +/// skipped under its quiet code, and a person reads the two lines. A +/// `scan` holds the earlier patch's reference already (it asks about +/// every pin before it rewrites), so it asks for nothing more; a dry run +/// previews the same and writes nothing; a second run changes nothing. +#[tokio::test(flavor = "multi_thread")] +async fn a_lock_that_stays_is_brought_to_the_current_listing_of_the_patch_it_is_on() { + for case in [Stays::held(), Stays::unlisted()] { + let code = case.skip.0; + let server = MockServer::start().await; + case.mount(&server, EarlierNow::Lists(case.earlier_now())) + .await; + let api = server.uri(); + let (before, now) = ( + earlier_index(&api), + format!("{}/", registry_url(&api, EARLIER_UUID, Some(EARLIER_NOW))), + ); + let (arm, linux) = case.pins_now(); + let known = ["--patch-server-url", api.as_str()]; + let pair_before = ( + hosted_lock(&before, EARLIER_ARM_PATCHED, EARLIER_LINUX_PATCHED), + hosted_gemfile(&before), + ); + let pair_now = (hosted_lock(&now, arm, linux), hosted_gemfile(&now)); + let pair = |proj: &Path| (read(proj, "Gemfile.lock"), read(proj, "Gemfile")); + + // A dry run: the same outcome, nothing written. + let proj = project_on_earlier(&api, true); + let (exit, env) = scan_json(proj.path(), &api, &[known[0], known[1], "--dry-run"]); + assert_eq!(exit, 0, "{code}: {env}"); + assert_eq!(pair(proj.path()), pair_before, "{code}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + case.events("verified"), + "{code}: {env}" + ); + let (exit, stdout, stderr) = hosted( + proj.path(), + &api, + &["scan"], + &[known[0], known[1], "--dry-run"], + ); + assert_eq!(exit, 0, "{stdout}\n{stderr}"); + for line in [case.line(true), case.skip.1.clone()] { + assert!(stdout.contains(&format!("\n{line}\n")), "{line}\n{stdout}"); + } + assert_eq!(pair(proj.path()), pair_before, "{code}"); + + // The run. + let asked_before = requests(&server).await; + let (exit, env) = scan_json(proj.path(), &api, &known); + assert_eq!(exit, 0, "{code}: {env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!(pair(proj.path()), pair_now, "{code}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(hosted_events(&env), case.events("applied"), "{code}: {env}"); + let summary = &env["summary"]; + assert_eq!( + (&summary["applied"], &summary["skipped"], &summary["failed"]), + (&json!(1), &json!(1), &json!(0)), + "{code}: {env}" + ); + assert_eq!( + env["redirect"]["rewrittenFiles"], + json!(["Gemfile", "Gemfile.lock"]) + ); + let (references, other) = requests(&server).await; + assert_eq!( + other[asked_before.1.len()..], + [earlier_snapshot_path(3)], + "{code}: one request to the registry the lock is on" + ); + assert_eq!( + references[asked_before.0.len()..], + [vec![EARLIER_UUID.to_string()], vec![UUID.to_string()]], + "{code}: the scan's check of the pin, and the patch on offer: no further request" + ); + + // A second run: the registry lists what the lock pins, so the + // lock is as it is, and the earlier patch's builds are no news. + let asked_before = requests(&server).await; + let (exit, env) = scan_json(proj.path(), &api, &known); + assert_eq!(exit, 0, "{code}: {env}"); + assert_eq!(pair(proj.path()), pair_now, "{code}"); + assert_eq!(env["redirect"]["rewrittenFiles"], json!([]), "{env}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [offer_skip(case.skip.0, &case.skip.1)], + "{code}: {env}" + ); + let (references, other) = requests(&server).await; + assert_eq!( + other[asked_before.1.len()..], + [earlier_snapshot_path(EARLIER_NOW)], + "{code}" + ); + assert_eq!( + references[asked_before.0.len()..], + [vec![EARLIER_UUID.to_string()], vec![UUID.to_string()]], + "{code}" + ); + + // For a person: the two lines on stdout, and nothing that warns. + let proj = project_on_earlier(&api, true); + let (exit, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &known); + assert_eq!(exit, 0, "{stdout}\n{stderr}"); + for line in [case.line(false), case.skip.1.clone()] { + assert!(stdout.contains(&format!("\n{line}\n")), "{line}\n{stdout}"); + } + assert!( + !stderr.contains("Warning") + && !stderr.contains("No patches could be switched") + && !stderr.contains("Not hosted"), + "{code}: {stderr}" + ); + assert_eq!(pair(proj.path()), pair_now, "{code}"); + } +} + +/// `get` of the patch on offer, and a `scan` that does not know the +/// lock's patch server as one, hold no answer for the earlier patch: they +/// ask for its reference, once, after the registry showed the withdrawal, +/// and bring the lock to it as above. Without a withdrawal nothing is +/// asked of the patch service beyond the patch on offer. +#[tokio::test(flavor = "multi_thread")] +async fn a_run_that_holds_no_answer_asks_for_the_reference_of_the_patch_the_lock_stays_on() { + for case in [Stays::held(), Stays::unlisted()] { + let code = case.skip.0; + let server = MockServer::start().await; + case.mount(&server, EarlierNow::Lists(case.earlier_now())) + .await; + let api = server.uri(); + let now = format!("{}/", registry_url(&api, EARLIER_UUID, Some(EARLIER_NOW))); + let (arm, linux) = case.pins_now(); + let known = ["--patch-server-url", api.as_str()]; + let asks = [vec![UUID.to_string()], vec![EARLIER_UUID.to_string()]]; + + // `get`. + let proj = project_on_earlier(&api, true); + let (exit, stdout, stderr) = hosted( + proj.path(), + &api, + &["get", UUID], + &["--json", known[0], known[1]], + ); + let env: Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON ({e}):\n{stdout}\nstderr:\n{stderr}")); + assert_eq!(exit, 0, "{code}: {env}\n{stderr}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&now, arm, linux) + ); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&now)); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(hosted_events(&env), case.events("applied"), "{code}: {env}"); + let (references, other) = requests(&server).await; + assert_eq!( + references, asks, + "{code}: one request for the earlier patch" + ); + assert_eq!(other, [earlier_snapshot_path(3)], "{code}"); + // A second `get` asks for the patch on offer alone. + let (exit, _, stderr) = hosted( + proj.path(), + &api, + &["get", UUID], + &["--json", known[0], known[1]], + ); + assert_eq!(exit, 0, "{stderr}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&now, arm, linux) + ); + let (references, _) = requests(&server).await; + assert_eq!(references[asks.len()..], [vec![UUID.to_string()]], "{code}"); + + // A `scan` that was not told of the patch server (it takes the + // origin from the reference of the patch on offer). + let server = MockServer::start().await; + case.mount(&server, EarlierNow::Lists(case.earlier_now())) + .await; + let api = server.uri(); + let now = format!("{}/", registry_url(&api, EARLIER_UUID, Some(EARLIER_NOW))); + let proj = project_on_earlier(&api, true); + let (exit, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(exit, 0, "{code}: {env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&now, arm, linux) + ); + assert_eq!(hosted_events(&env), case.events("applied"), "{code}: {env}"); + let (references, other) = requests(&server).await; + assert_eq!(references, asks, "{code}"); + assert_eq!(other, [earlier_snapshot_path(3)], "{code}"); + + // No withdrawal: the registry lists both builds as the lock pins + // them. The lock stays byte for byte, and nothing is asked about + // the earlier patch. + let server = MockServer::start().await; + mount_api_refreshing( + &server, + &case.offered, + EarlierNow::Lists(EARLIER_BOTH.to_vec()), + ) + .await; + mount_earlier_snapshot( + &server, + 3, + &[(ARM, EARLIER_ARM_PATCHED), (LINUX, EARLIER_LINUX_PATCHED)], + ) + .await; + let api = server.uri(); + let before = earlier_index(&api); + let proj = project_on_earlier(&api, true); + let (exit, stdout, stderr) = hosted( + proj.path(), + &api, + &["get", UUID], + &["--json", "--patch-server-url", api.as_str()], + ); + let env: Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON ({e}):\n{stdout}\nstderr:\n{stderr}")); + assert_eq!(exit, 0, "{code}: {env}\n{stderr}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&before, EARLIER_ARM_PATCHED, EARLIER_LINUX_PATCHED) + ); + let skip = match code { + "redirect_gem_newer_fix_waits" => format!( + "{DEP} {DEP_VERSION}: the newer fix has no patched build for {ARM}, {LINUX} yet; \ + the lock stays on the patch it is on" + ), + _ => case.skip.1.clone(), + }; + assert_eq!( + hosted_events(&env), + [offer_skip(code, &skip)], + "{code}: {env}" + ); + let (references, other) = requests(&server).await; + assert_eq!(references, [vec![UUID.to_string()]], "{code}"); + assert_eq!( + other, + [earlier_snapshot_path(3)], + "{code}: the one document" + ); + } +} + +/// The reference of the patch the lock stays on is followed only when it +/// is usable. A patch that is not granted or still being built, an answer +/// that is missing, lists no builds, leaves a locked platform out or is +/// of another package, and a request that fails: the lock stays byte for +/// byte, the patch on offer is skipped quietly as before, and the run +/// says nothing more (no warning, no further event, exit 0). +#[tokio::test(flavor = "multi_thread")] +async fn an_unusable_reference_leaves_the_lock_that_stays_as_it_is() { + let case = Stays::held(); + let unusable = [ + (EarlierNow::Status("forbidden"), "not granted"), + (EarlierNow::Status("pending_build"), "still being built"), + (EarlierNow::Status("withdrawn"), "withdrawn"), + (EarlierNow::Absent, "no answer"), + (EarlierNow::NoList, "no list"), + ( + EarlierNow::Lists(vec![( + LINUX, + EARLIER_LINUX_PATCHED, + Some(EARLIER_LINUX_UUID), + )]), + "a list that leaves a locked platform out", + ), + (EarlierNow::OtherPackage, "another package"), + (EarlierNow::Fails, "a request that fails"), + ]; + for (earlier, why) in unusable { + let server = MockServer::start().await; + case.mount(&server, earlier).await; + let api = server.uri(); + let before = earlier_index(&api); + let proj = project_on_earlier(&api, true); + let (exit, stdout, stderr) = hosted( + proj.path(), + &api, + &["get", UUID], + &["--json", "--patch-server-url", api.as_str()], + ); + let env: Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON ({e}):\n{stdout}\nstderr:\n{stderr}")); + assert_eq!(exit, 0, "{why}: {env}\n{stderr}"); + assert_eq!(env["status"], "success", "{why}: {env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&before, EARLIER_ARM_PATCHED, EARLIER_LINUX_PATCHED), + "{why}" + ); + assert_eq!( + read(proj.path(), "Gemfile"), + hosted_gemfile(&before), + "{why}" + ); + assert_eq!(warning_codes(&env), Vec::::new(), "{why}: {env}"); + assert_eq!( + hosted_events(&env), + [offer_skip(case.skip.0, &case.skip.1)], + "{why}: {env}" + ); + assert_eq!(env["redirect"]["rewrittenFiles"], json!([]), "{why}"); + let (references, other) = requests(&server).await; + assert_eq!( + references, + [vec![UUID.to_string()], vec![EARLIER_UUID.to_string()]], + "{why}: asked once" + ); + assert_eq!(other, [earlier_snapshot_path(3)], "{why}"); + } +} + +/// A `scan` checks every pin before it rewrites. Where the earlier patch +/// as a whole was withdrawn, that check restores the gem to its upstream +/// registry first (each build back on the sha256 that registry lists), +/// and the patch on offer is then judged against a lock that is on no +/// patch: here it has no patched build for a locked platform, so the gem +/// is left on its upstream registry. Nothing is asked about the withdrawn +/// patch beyond that check. +#[tokio::test(flavor = "multi_thread")] +async fn a_scan_restores_a_wholly_withdrawn_earlier_patch_before_the_patch_on_offer_is_judged() { + let case = Stays::held(); + let server = MockServer::start().await; + case.mount(&server, EarlierNow::Status("withdrawn")).await; + // The upstream registry, as the restore reads it. + Mock::given(method("GET")) + .and(path(format!("/upstream/info/{DEP}"))) + .respond_with(ResponseTemplate::new(200).set_body_string(format!( + "---\n{DEP_VERSION}-{ARM} racc:~> 1.4|checksum:{ARM_UPSTREAM}\n{DEP_VERSION}-{LINUX} \ + racc:~> 1.4|checksum:{LINUX_UPSTREAM}\n" + ))) + .mount(&server) + .await; + let api = server.uri(); + let upstream = format!("{api}/upstream"); + let proj = project_on_earlier(&api, true); + let args = [ + "scan", + "--mode", + "hosted", + "--yes", + "--json", + "--cwd", + proj.path().to_str().expect("utf8 temp path"), + "--api-url", + api.as_str(), + "--org", + ORG, + "--api-token", + API_TOKEN, + "--patch-server-url", + api.as_str(), + ]; + let env = [("SOCKET_RUBYGEMS_URL", upstream.as_str())]; + let (exit, stdout, stderr) = common::run_with_env(proj.path(), &args, &env); + let env: Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON ({e}):\n{stdout}\nstderr:\n{stderr}")); + assert_eq!(exit, 0, "{env}\n{stderr}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + ( + read(proj.path(), "Gemfile.lock"), + read(proj.path(), "Gemfile") + ), + (lock(true), GEMFILE.to_string()), + "the pair is back on its upstream registry: {env}" + ); + let events: Vec<(String, String, String)> = env["events"] + .as_array() + .into_iter() + .flatten() + .map(|event| { + let text = |key: &str| event[key].as_str().unwrap_or_default().to_string(); + (text("action"), text("uuid"), text("errorCode")) + }) + .collect(); + assert_eq!( + events, + [ + ( + "rolledBack".to_string(), + EARLIER_UUID.to_string(), + "patch_withdrawn".to_string() + ), + ( + "skipped".to_string(), + UUID.to_string(), + "redirect_gem_no_patched_build".to_string() + ), + ], + "{env}" + ); + let (references, other) = requests(&server).await; + assert_eq!( + references, + [vec![EARLIER_UUID.to_string()], vec![UUID.to_string()]], + "the check of the pin and the patch on offer" + ); + assert_eq!( + other, + [format!("/upstream/info/{DEP}")], + "the upstream registry, and no patch registry" + ); +} + +/// The run's own VEX and a later `vex` over the lock a refresh left agree +/// with it: the build the earlier patch still serves is attested under +/// its own patch, and the withdrawn one is stated as affected. +#[tokio::test(flavor = "multi_thread")] +async fn the_vex_of_a_lock_brought_to_its_patchs_current_listing_tells_the_builds_apart() { + let case = Stays::held(); + let server = MockServer::start().await; + case.mount(&server, EarlierNow::Lists(case.earlier_now())) + .await; + let api = server.uri(); + let now = format!("{}/", registry_url(&api, EARLIER_UUID, Some(EARLIER_NOW))); + let (arm, linux) = case.pins_now(); + let statements = || { + let mut affected = upstream_statement(ARM); + affected.words = affected.words.replace(UUID, EARLIER_UUID); + [ + patched_statement(&[(LINUX, EARLIER_LINUX_UUID)], false), + affected, + ] + }; + let proj = project_on_earlier(&api, true); + let (exit, env, doc) = scan_vex(proj.path(), &api); + assert_eq!(exit, 0, "{env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&now, arm, linux) + ); + assert_eq!(said(&doc.expect("a document")), statements(), "{env}"); + assert_eq!( + (&env["vex"]["statements"], &env["vex"]["affected"]), + (&json!(2), &json!(1)), + "{env}" + ); + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!(said(out.doc()), statements(), "{out}"); + assert_eq!(out.envelope["status"], "success", "{out}"); +} + +/// On a terminal the two lines of such a run stand one under the other at +/// 80, 100 and 120 columns, each broken after a clause where it does not +/// fit. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +async fn the_lines_of_a_lock_that_stays_and_is_refreshed_fit_a_terminal() { + for case in [Stays::held(), Stays::unlisted()] { + let server = MockServer::start().await; + case.mount(&server, EarlierNow::Lists(case.earlier_now())) + .await; + let api = server.uri(); + for cols in [80u16, 100, 120] { + let proj = project_on_earlier(&api, true); + let cwd = proj.path().to_path_buf(); + let api = api.clone(); + let run = tokio::task::spawn_blocking(move || { + let dir = cwd.to_str().expect("utf8 temp path"); + let args = [ + "scan", + "--mode", + "hosted", + "--yes", + "--cwd", + dir, + "--api-url", + api.as_str(), + "--org", + ORG, + "--api-token", + API_TOKEN, + "--patch-server-url", + api.as_str(), + ]; + pty_io::run_command_at( + cols, + common::hermetic::pty_binary_command(), + &args, + &cwd, + &[], + &[], + std::time::Duration::from_secs(60), + ) + }) + .await + .expect("spawn_blocking join"); + let screen = pty_io::render(run.output.as_bytes()); + let shown = screen.join("\n"); + println!("--- {} at {cols} columns\n{shown}", case.skip.0); + assert_eq!(run.code, 0, "{shown}"); + let at = screen + .iter() + .position(|row| row.starts_with(&format!("{DEP} {DEP_VERSION}: patched for "))) + .unwrap_or_else(|| panic!("no line of the gem:\n{shown}")); + // The rows of the two lines: each row after a line's first + // hangs under two spaces, up to the next line of the output. + let rows: Vec<&String> = screen[at..] + .iter() + .take_while(|row| row.starts_with(DEP) || row.starts_with(" ")) + .take_while(|row| !row.starts_with(" 1. ")) + .collect(); + let mut lines: Vec = Vec::new(); + for row in &rows { + match (row.strip_prefix(" "), lines.last_mut()) { + (Some(rest), Some(line)) => { + line.push(' '); + line.push_str(rest); + } + _ => lines.push(row.to_string()), + } + } + assert_eq!( + lines, + [case.line(false), case.skip.1.clone()], + "{cols} columns:\n{shown}" + ); + assert!( + rows.iter() + .all(|row| row.chars().count() <= usize::from(cols)), + "wider than {cols} columns:\n{shown}" + ); + // A line that does not fit breaks after a clause where one + // fits the terminal. + let first_clause = |line: &str| line.split_once("; ").map(|(first, _)| first.len() + 1); + for line in [case.line(false), case.skip.1.clone()] { + let whole = line.chars().count() <= usize::from(cols); + let clause = first_clause(&line).filter(|len| *len <= usize::from(cols)); + if let (false, Some(len)) = (whole, clause) { + assert!( + rows.iter().any(|row| **row == line[..len]), + "{cols} columns: {line}\n{shown}" + ); + } + } + } + } +} + +/// Under a patch mirror a lock that stays is left as it is. The reference +/// of the patch it is on names that patch's registry on the patch server, +/// and following it would be a pin on the mirror that the run has not +/// checked there. The registry the lock is on is still read (from the +/// patch server), the patch on offer is skipped as it is without a +/// mirror, and the patch service is asked about no other patch. +#[tokio::test(flavor = "multi_thread")] +async fn a_lock_that_stays_under_a_patch_mirror_is_left_as_it_is() { + const PREFIX: &str = "/artifactory/socket-patch"; + let case = Stays::held(); + let server = MockServer::start().await; + case.mount(&server, EarlierNow::Lists(case.earlier_now())) + .await; + let api = server.uri(); + // The mirror takes the run's check of the pin it would write, and + // wants credentials for anything else. + let mirror = MockServer::start().await; + Mock::given(method("HEAD")) + .and(path(format!( + "{PREFIX}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{UUID}/{DEP}-{DEP_VERSION}.gem" + ))) + .respond_with(ResponseTemplate::new(200)) + .mount(&mirror) + .await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(401)) + .mount(&mirror) + .await; + let base = format!("{}{PREFIX}", mirror.uri()); + + let on_mirror = earlier_index(&base); + let proj = hosted_project(&on_mirror, EARLIER_ARM_PATCHED, EARLIER_LINUX_PATCHED, true); + let lock = read(proj.path(), "Gemfile.lock"); + let (exit, stdout, stderr) = hosted( + proj.path(), + &api, + &["get", UUID], + &["--json", "--patch-mirror-url", base.as_str()], + ); + let env: Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON ({e}):\n{stdout}\nstderr:\n{stderr}")); + assert_eq!(exit, 0, "{env}\n{stderr}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&on_mirror)); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!( + hosted_events(&env), + [offer_skip(case.skip.0, &case.skip.1)], + "{env}" + ); + let (references, other) = requests(&server).await; + assert_eq!( + references, + [vec![UUID.to_string()]], + "the patch on offer alone" + ); + assert_eq!( + other, + [earlier_snapshot_path(3)], + "the registry is read from the patch server, once" + ); +} + +// ── A lock with no `CHECKSUMS` that follows a newer snapshot ────────── + +/// A lock with no `CHECKSUMS` section is on the patch's registry at one +/// snapshot, and the reference names a newer one in which a platform that +/// was on upstream's gem has a patched build. The lock does not say what +/// that build was, so the run asks the snapshot the lock names, once, and +/// reports the build as newly patched: `newlyPatched` on its event, and +/// `now also patched for …` in the line. When that request fails the run +/// reports the builds as it does without it (none is new), and succeeds. +/// A lock with `CHECKSUMS` says what it had, and nothing is asked. +#[tokio::test(flavor = "multi_thread")] +async fn a_lock_without_checksums_on_a_newer_snapshot_says_which_build_is_now_patched() { + let now_also = + format!("{DEP} {DEP_VERSION}: now also patched for {ARM}; already patched for {LINUX}"); + let as_before = format!("{DEP} {DEP_VERSION}: patched for {ARM}, {LINUX}"); + // `(the lock has CHECKSUMS, the snapshot it names answers, arm64-darwin + // is reported as new, the line, the registry requests)`. + let cases = [ + (false, true, true, &now_also, 1), + (false, false, false, &as_before, 1), + (true, true, true, &now_also, 0), + ]; + for (checksums, answers, newly, line, asked) in cases { + let server = MockServer::start().await; + mount_api(&server, Some((&BOTH_PATCHED[..], 5))).await; + if answers { + mount_index(&server, ARM_UPSTREAM, LINUX_PATCHED).await; + } + let api = server.uri(); + let (before, after) = ( + format!("{}/", index_url(&api, Some(4))), + format!("{}/", index_url(&api, Some(5))), + ); + let caveat: &[&str] = if checksums { + &[] + } else { + &["redirect_gem_no_checksums_section"] + }; + let what = format!("checksums {checksums}, answers {answers}"); + + let proj = hosted_project(&before, ARM_UPSTREAM, LINUX_PATCHED, checksums); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{what}: {env}"); + assert_eq!(env["status"], "success", "{what}: {env}"); + let lock = read(proj.path(), "Gemfile.lock"); + assert!( + lock.contains(&format!(" remote: {after}\n")) && !lock.contains(&before), + "{what}: {lock}" + ); + assert_eq!(lock.contains("CHECKSUMS"), checksums, "{what}"); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&after)); + assert_eq!(warning_codes(&env), caveat, "{what}: {env}"); + assert_eq!( + hosted_events(&env), + [ + patched_event("applied", ARM, ARM_UUID, newly), + patched_event("applied", LINUX, LINUX_UUID, false) + ], + "{what}: {env}" + ); + let (_, other) = requests(&server).await; + assert_eq!(other, vec![index_path(); asked], "{what}"); + + // A second run: the lock names the reference's snapshot, so + // nothing is asked and nothing is new. + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{what}: {env}"); + assert_eq!(env["redirect"]["rewrittenFiles"], json!([]), "{what}"); + assert_eq!( + hosted_events(&env), + [ + patched_event("applied", ARM, ARM_UUID, false), + patched_event("applied", LINUX, LINUX_UUID, false) + ], + "{what}: {env}" + ); + let (_, other) = requests(&server).await; + assert_eq!(other.len(), asked, "{what}: no registry request"); + + // For a person, and a dry run. + for dry_run in [true, false] { + let proj = hosted_project(&before, ARM_UPSTREAM, LINUX_PATCHED, checksums); + let extra: &[&str] = if dry_run { &["--dry-run"] } else { &[] }; + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], extra); + assert_eq!(code, 0, "{what}: {stdout}\n{stderr}"); + let line = match (dry_run, newly) { + (true, true) => line.replace("now also patched", "would also be patched"), + _ => line.to_string(), + }; + assert!( + stdout.contains(&format!("\n{line}\n")), + "{what}, dry run {dry_run}:\n{stdout}" + ); + } + } +} + +/// The listing of the snapshot the lock names also says that a build was +/// withdrawn. A lock with no `CHECKSUMS` section has both builds patched +/// at one snapshot, and the reference names a newer one that serves +/// upstream's gem for `arm64-darwin`. The run asks the lock's snapshot +/// once (for the linux build, which the lock does not pin), finds the +/// arm64-darwin build gone from it, or still under the patched sha256, +/// and says that the build is back on upstream's gem, as on a lock with +/// `CHECKSUMS`. When that request fails, nothing says what the build was, +/// and it is reported as upstream's gem alone. +#[tokio::test(flavor = "multi_thread")] +async fn a_lock_without_checksums_on_a_newer_snapshot_says_which_build_was_withdrawn() { + let back = format!( + "{DEP} {DEP_VERSION}: patched for {LINUX}; upstream gem back for {ARM} (its patched \ + build was withdrawn)" + ); + let kept = format!( + "{DEP} {DEP_VERSION}: patched for {LINUX}; upstream gem kept for {ARM} (no patched build \ + yet)" + ); + // `(what the snapshot the lock names lists for arm64-darwin, if it + // answers at all; the event of that build; the line)`. + let cases: [(Option>, Value, &String); 3] = [ + (Some(None), withdrawn_event(ARM), &back), + (Some(Some(ARM_PATCHED)), withdrawn_event(ARM), &back), + (None, upstream_event(ARM), &kept), + ]; + for (listed, arm_event, line) in cases { + let what = format!("the lock's snapshot lists {listed:?}"); + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 5))).await; + if let Some(arm) = listed { + let mut listing = + format!("---\n{DEP_VERSION}-{LINUX} racc:~> 1.4|checksum:{LINUX_PATCHED}\n"); + if let Some(arm) = arm { + listing.push_str(&format!("{DEP_VERSION}-{ARM} racc:~> 1.4|checksum:{arm}\n")); + } + Mock::given(method("GET")) + .and(path(index_path())) + .respond_with(ResponseTemplate::new(200).set_body_string(listing)) + .mount(&server) + .await; + } + let api = server.uri(); + let (before, after) = ( + format!("{}/", index_url(&api, Some(4))), + format!("{}/", index_url(&api, Some(5))), + ); + + let proj = hosted_project(&before, ARM_PATCHED, LINUX_PATCHED, false); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{what}: {env}"); + assert_eq!(env["status"], "success", "{what}: {env}"); + let lock = read(proj.path(), "Gemfile.lock"); + assert!( + lock.contains(&format!(" remote: {after}\n")) && !lock.contains(&before), + "{what}: {lock}" + ); + assert_eq!( + warning_codes(&env), + ["redirect_gem_no_checksums_section"], + "{what}: {env}" + ); + assert_eq!( + hosted_events(&env), + [ + arm_event, + patched_event("applied", LINUX, LINUX_UUID, false) + ], + "{what}: {env}" + ); + let (_, other) = requests(&server).await; + assert_eq!(other, [index_path()], "{what}: asked once"); + + // For a person. + let proj = hosted_project(&before, ARM_PATCHED, LINUX_PATCHED, false); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{what}: {stdout}\n{stderr}"); + assert!(stdout.contains(&format!("\n{line}\n")), "{what}:\n{stdout}"); + } +} + +// ── A gem locked as its ruby-platform gem alone ─────────────────────── + +/// The sha256 a lock pins for upstream's ruby-platform gem. +const RUBY_UPSTREAM: &str = "c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0"; + +/// A lock that names the gem as its ruby-platform gem alone, with +/// `platforms` as its `PLATFORMS` section. +fn ruby_lock(platforms: &[&str]) -> String { + let platforms: String = platforms.iter().map(|p| format!(" {p}\n")).collect(); + format!( + "GEM\n remote: https://rubygems.org/\n specs:\n {DEP} ({DEP_VERSION})\n racc \ + (1.8.1)\n\nPLATFORMS\n{platforms}\nDEPENDENCIES\n {DEP} (= {DEP_VERSION})\n racc (= \ + 1.8.1)\n\nCHECKSUMS\n {DEP} ({DEP_VERSION}) sha256={RUBY_UPSTREAM}\n racc (1.8.1) \ + sha256={RACC}\n\nBUNDLED WITH\n 4.0.15\n" + ) +} + +/// A project that locks the gem as its ruby-platform gem alone was pinned +/// by a reference with no list, whose registry URL has no snapshot level +/// (what release 5.1.0 writes). A scan whose reference names the registry +/// at a snapshot, with the list of the version's gems, leaves that pair +/// byte for byte and confirms the pin: the gem takes the registry without +/// the snapshot level, which lists the patched gems only. A lock that is +/// not pinned yet gets the same pair, whatever its `PLATFORMS` names. +#[tokio::test(flavor = "multi_thread")] +async fn a_gem_locked_as_its_ruby_gem_alone_stays_on_the_registry_without_a_snapshot() { + let listed: [Listed; 3] = [ + (ARM, ARM_PATCHED, Some(ARM_UUID)), + ("ruby", RUBY_PATCHED, Some(UUID)), + (LINUX, LINUX_UPSTREAM, None), + ]; + let pinned_event = json!({ + "action": "applied", "purl": PURL, "uuid": UUID, "details": { "mode": "hosted" }, + }); + for platforms in [&["ruby"][..], &[ARM, "ruby"][..]] { + let server = MockServer::start().await; + mount_api(&server, None).await; + let api = server.uri(); + let root = index_url(&api, None); + + // The pair as a reference with no snapshot pins it. + let proj = project(&ruby_lock(platforms)); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(hosted_events(&env), [pinned_event.clone()], "{env}"); + assert_eq!(pin_changes(&env), [Some(true)], "{env}"); + let (gemfile, lock) = ( + read(proj.path(), "Gemfile"), + read(proj.path(), "Gemfile.lock"), + ); + assert_eq!(gemfile, hosted_gemfile(&root)); + assert!( + lock.starts_with(&format!( + "GEM\n remote: {root}\n specs:\n {DEP} ({DEP_VERSION})\n\nGEM\n" + )), + "{lock}" + ); + assert!( + lock.contains(&format!(" {DEP} ({DEP_VERSION}) sha256={RUBY_PATCHED}\n")), + "{lock}" + ); + + // A reference with a snapshot URL and a list: nothing changes. + server.reset().await; + mount_api(&server, Some((&listed[..], 4))).await; + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!(read(proj.path(), "Gemfile"), gemfile, "{platforms:?}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock, "{platforms:?}"); + assert_eq!(env["redirect"]["rewrittenFiles"], json!([]), "{env}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(hosted_events(&env), [pinned_event.clone()], "{env}"); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, Vec::::new(), "no registry request"); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already on hosted patches; nothing to rewrite.\n"), + "{stdout}" + ); + assert!(!stderr.contains("Warning"), "{stderr}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock); + + // A lock that is not pinned yet takes the same pair. + let fresh = project(&ruby_lock(platforms)); + let (code, env) = scan_json(fresh.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(fresh.path(), "Gemfile"), gemfile, "{platforms:?}"); + assert_eq!(read(fresh.path(), "Gemfile.lock"), lock, "{platforms:?}"); + assert_eq!(hosted_events(&env), [pinned_event.clone()], "{env}"); + } +} + +/// Under a patch mirror a run asks the mirror about each pin it is about +/// to write, and about none the project's files hold already. A gem the +/// lock names as its ruby-platform gem alone is pinned under the registry +/// without its snapshot level, and a run whose reference names the +/// registry at a snapshot knows that pin as its own: the second run asks +/// the mirror nothing and writes nothing. +#[tokio::test(flavor = "multi_thread")] +async fn a_rerun_under_a_patch_mirror_knows_the_pin_without_a_snapshot() { + const PREFIX: &str = "/artifactory/socket-patch"; + let listed: [Listed; 3] = [ + (ARM, ARM_PATCHED, Some(ARM_UUID)), + ("ruby", RUBY_PATCHED, Some(UUID)), + (LINUX, LINUX_UPSTREAM, None), + ]; + let server = MockServer::start().await; + mount_api(&server, Some((&listed[..], 4))).await; + let api = server.uri(); + let mirror = MockServer::start().await; + Mock::given(method("HEAD")) + .and(path(format!( + "{PREFIX}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{UUID}/{DEP}-{DEP_VERSION}.gem" + ))) + .respond_with(ResponseTemplate::new(200)) + .mount(&mirror) + .await; + let base = format!("{}{PREFIX}", mirror.uri()); + let root = registry_url(&base, UUID, None); + let extra = ["--patch-mirror-url", base.as_str()]; + + let proj = project(&ruby_lock(&["ruby"])); + let (code, env) = scan_json(proj.path(), &api, &extra); + assert_eq!(code, 0, "{env}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(read(proj.path(), "Gemfile"), hosted_gemfile(&root)); + let lock = read(proj.path(), "Gemfile.lock"); + assert!( + lock.starts_with(&format!("GEM\n remote: {root}\n specs:\n")), + "{lock}" + ); + assert_eq!( + mirror.received_requests().await.unwrap_or_default().len(), + 1, + "the mirror is asked about the pin the run writes" + ); + + let (code, env) = scan_json(proj.path(), &api, &extra); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["redirect"]["rewrittenFiles"], json!([]), "{env}"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock); + assert_eq!( + mirror.received_requests().await.unwrap_or_default().len(), + 1, + "a pin the project holds is not asked about again" + ); +} + +// ── VEX ─────────────────────────────────────────────────────────────── + +const PRODUCT: &str = "pkg:gem/app@1.0.0"; +const CVE: &str = "CVE-2026-5555"; + +/// The path of the index the gem patch's registry serves at snapshot `4`. +fn index_path() -> String { + format!("/patch-registry/gem/{TOKEN}/{UUID}/s/4/info/{DEP}") +} + +fn build_purl(platform: &str) -> String { + format!("{PURL}?platform={platform}") +} + +/// The form Grype and Syft report a platform gem under. +fn grype_form(platform: &str) -> String { + format!("{PURL}-{platform}") +} + +/// What one statement of a document says: its status, the packages of the +/// project it is about, the products it names beside the project, and its +/// impact statement (`not_affected`) or action statement (`affected`). +#[derive(Debug, PartialEq)] +struct Said { + status: &'static str, + packages: Vec, + products: Vec, + words: String, +} + +/// Every statement of `doc`, each about the one vulnerability of the +/// gem patch's record. +fn said(doc: &Value) -> Vec { + let ids = |list: &Value, key: &str| -> Vec { + let items = list.as_array().into_iter().flatten(); + items + .filter_map(|item| item[key].as_str().map(str::to_string)) + .collect() + }; + let statements = doc["statements"].as_array().expect("statements"); + statements + .iter() + .map(|st| { + assert_eq!(st["vulnerability"]["name"], GHSA, "{st}"); + assert_eq!(st["vulnerability"]["aliases"], json!([CVE]), "{st}"); + assert_eq!(st["products"][0]["@id"], PRODUCT, "{st}"); + let status = match st["status"].as_str() { + Some("not_affected") => "not_affected", + Some("affected") => "affected", + other => panic!("unexpected status {other:?}: {st}"), + }; + let words = match status { + "affected" => &st["action_statement"], + _ => &st["impact_statement"], + }; + Said { + status, + packages: ids(&st["products"][0]["subcomponents"], "@id"), + products: ids(&st["products"], "@id")[1..].to_vec(), + words: words.as_str().unwrap_or_default().to_string(), + } + }) + .collect() +} + +/// The statement of the builds `platforms`, each patched by the patch +/// beside it; `shared` when every locked build is among them, so that the +/// form Trivy reports the gem under stands for patched builds alone. +fn patched_statement(platforms: &[(&str, &str)], shared: bool) -> Said { + let mut products: Vec = Vec::new(); + products.extend(shared.then(|| PURL.to_string())); + products.extend(platforms.iter().map(|(platform, _)| grype_form(platform))); + products.extend(platforms.iter().map(|(platform, _)| build_purl(platform))); + let mut parts: Vec = platforms + .iter() + .map(|(_, patch)| format!("Patched via Socket patch {patch} (redirected)")) + .collect(); + parts.sort(); + Said { + status: "not_affected", + packages: platforms.iter().map(|(p, _)| build_purl(p)).collect(), + products, + words: parts.join("; "), + } +} + +/// The statement of the build for `platform`, which the lock installs as +/// upstream's own gem. +fn upstream_statement(platform: &str) -> Said { + Said { + status: "affected", + packages: vec![build_purl(platform)], + products: vec![grype_form(platform), build_purl(platform)], + words: format!( + "The patch registry has no patched build of this gem for {platform} yet and serves \ + upstream's own gem for it, so an install on that platform is without Socket patch \ + {UUID}. Run `socket-patch scan --mode hosted` again later: the lockfile takes the \ + patched build once it is published." + ), + } +} + +/// The statement of the build for `platform`, of which nothing shows what +/// the lock installs: `why`, and `remedy` is what to run. It names no +/// patch. `shared` when no locked build is attested, so that the form +/// Trivy reports the gem under stands for affected builds alone. +fn unshown_statement(platform: &str, why: &str, remedy: &str, shared: bool) -> Said { + let mut products: Vec = Vec::new(); + products.extend(shared.then(|| PURL.to_string())); + products.extend([grype_form(platform), build_purl(platform)]); + Said { + status: "affected", + packages: vec![build_purl(platform)], + products, + words: format!( + "It could not be shown that the lockfile installs a patched build of this gem for \ + {platform} ({why}), so it is stated as affected. {remedy}" + ), + } +} + +/// What to run for a build the lock and the patch registry disagree about, +/// and for one a later run can read. +const RESCAN: &str = "Run `socket-patch scan --mode hosted` to bring the lockfile up to date, \ + then `socket-patch vex` again."; +const RETRY: &str = "Run `socket-patch vex` again to attest each build."; + +/// The uncounted events of the builds `platforms`, of which nothing shows +/// what the lock installs, after asserting that each says `affected` and +/// that the run counts none of them and is a success. +fn unshown_events(env: &Value, platforms: &[&str]) -> Vec<(String, String, String)> { + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + (&env["summary"]["skipped"], &env["summary"]["failed"]), + (&json!(0), &json!(0)), + "a build that is not shown patched is counted nowhere: {env}" + ); + for event in env["events"].as_array().into_iter().flatten() { + if event["errorCode"] == "vex_gem_build_unknown" { + assert_eq!(event["details"]["status"], "affected", "{event}"); + assert_eq!(event["uuid"], Value::Null, "no patch is named: {event}"); + } + } + platforms + .iter() + .map(|platform| event("skipped", platform, "vex_gem_build_unknown")) + .collect() +} + +/// A `--json` hosted scan with `--vex`: exit code, envelope and document. +fn scan_vex(proj: &Path, api: &str) -> (i32, Value, Option) { + let out = proj.join("out.vex.json"); + let (code, env) = scan_json( + proj, + api, + &[ + "--vex", + out.to_str().expect("utf8 temp path"), + "--vex-product", + PRODUCT, + "--patch-server-url", + api, + ], + ); + (code, env, vex_e2e_common::read_doc(&out)) +} + +/// A later `socket-patch vex` over `proj`, against `api`. +fn vex_run(api: &str) -> vex_e2e_common::VexRun { + vex_e2e_common::VexRun { + api_url: Some(api.to_string()), + api_token: Some(API_TOKEN.to_string()), + org: Some(ORG.to_string()), + // The lock's registry is on the mock origin. + patch_server_url: Some(api.to_string()), + product: Some(PRODUCT.to_string()), + ..vex_e2e_common::VexRun::default() + } +} + +fn vex(proj: &Path, api: &str) -> vex_e2e_common::VexOutcome { + vex_e2e_common::run_vex(&vex_e2e_common::binary(), proj, &vex_run(api)) +} + +/// A project as a hosted run left it: the gem's two builds on the patch +/// registry `index`, pinned to `arm` and `linux`, or by source alone +/// (`checksums: false`, the lock of a Bundler that writes no `CHECKSUMS`). +fn hosted_project(index: &str, arm: &str, linux: &str, checksums: bool) -> tempfile::TempDir { + let mut lock = hosted_lock(index, arm, linux); + if !checksums { + let at = lock.find("CHECKSUMS\n").expect("a CHECKSUMS section"); + let end = lock.find("BUNDLED WITH").expect("a BUNDLED WITH section"); + lock.replace_range(at..end, ""); + } + let dir = project(&lock); + std::fs::write(dir.path().join("Gemfile"), hosted_gemfile(index)).unwrap(); + dir +} + +/// The index the patch registry serves at snapshot `4`: the sha256 of +/// each build it lists. +async fn mount_index(server: &MockServer, arm: &str, linux: &str) { + Mock::given(method("GET")) + .and(path(index_path())) + .respond_with(ResponseTemplate::new(200).set_body_string(format!( + "---\n{DEP_VERSION}-{ARM} racc:~> 1.4|checksum:{arm}\n{DEP_VERSION}-{LINUX} racc:~> \ + 1.4|checksum:{linux}\n" + ))) + .mount(server) + .await; +} + +/// How many times the gem patch's record was asked for. +async fn view_requests(server: &MockServer) -> usize { + let view = format!("/v0/orgs/{ORG}/patches/view/{UUID}"); + let requests = server.received_requests().await.unwrap_or_default(); + requests + .iter() + .filter(|request| request.url.path() == view) + .count() +} + +/// The `vex` events of the gem's builds: `(action, purl, errorCode)`, +/// each naming the gem's patch as its fix and its own platform. +fn build_events(env: &Value) -> Vec<(String, String, String)> { + let events = env["events"].as_array().expect("events"); + events + .iter() + .map(|event| { + let purl = event["purl"].as_str().unwrap_or_default(); + let details = &event["details"]; + assert_eq!(details["gemFix"], UUID, "{event}"); + let platform = details["platform"].as_str().unwrap_or_default(); + assert_eq!(purl, build_purl(platform), "{event}"); + let text = |key: &str| event[key].as_str().unwrap_or_default().to_string(); + (text("action"), text("purl"), text("errorCode")) + }) + .collect() +} + +fn event(action: &str, platform: &str, code: &str) -> (String, String, String) { + (action.to_string(), build_purl(platform), code.to_string()) +} + +/// The run's own `--vex`, one locked build patched and one on upstream's +/// gem: the patched build is attested under its own patch, the other is +/// said affected, and neither statement names the gem without a platform +/// (the form a scanner that drops the platform would match both by). No +/// request beyond the run's own: one reference request, one record, and +/// none to the registry. The same holds on a machine whose platform is +/// the one on upstream's gem, with that gem installed. +#[tokio::test(flavor = "multi_thread")] +async fn the_runs_vex_attests_the_patched_build_and_says_affected_of_the_upstream_one() { + for installed in [false, true] { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let proj = project(&lock(true)); + if installed { + let gem = format!("vendor/bundle/ruby/3.3.0/gems/{DEP}-{DEP_VERSION}-{ARM}/lib"); + std::fs::create_dir_all(proj.path().join(&gem)).unwrap(); + std::fs::write( + proj.path().join(gem).join("platform_probe.rb"), + "upstream\n", + ) + .unwrap(); + } + let (code, env, doc) = scan_vex(proj.path(), &api); + assert_eq!(code, 0, "installed: {installed}: {env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!( + said(&doc.expect("a document")), + [ + patched_statement(&[(LINUX, LINUX_UUID)], false), + upstream_statement(ARM) + ], + "installed: {installed}" + ); + assert_eq!(env["vex"]["statements"], 2, "{env}"); + assert_eq!(env["vex"]["affected"], 1, "{env}"); + assert_eq!( + hosted_events(&env), + [ + upstream_event(ARM), + patched_event("applied", LINUX, LINUX_UUID, true) + ], + "{env}" + ); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, Vec::::new(), "no registry request"); + assert_eq!(view_requests(&server).await, 1, "the gem patch's record"); + } +} + +/// Every locked build patched: one statement names both builds, each under +/// its own patch, and the gem without a platform too. The gem patch's own +/// uuid is in no statement: no locked build is its ruby-platform gem. +#[tokio::test(flavor = "multi_thread")] +async fn the_runs_vex_attests_every_patched_build_under_its_own_patch() { + let server = MockServer::start().await; + mount_api(&server, Some((&BOTH_PATCHED[..], 4))).await; + let api = server.uri(); + let proj = project(&lock(true)); + let (code, env, doc) = scan_vex(proj.path(), &api); + assert_eq!(code, 0, "{env}"); + let doc = doc.expect("a document"); + assert_eq!( + said(&doc), + [patched_statement( + &[(ARM, ARM_UUID), (LINUX, LINUX_UUID)], + true + )] + ); + assert!(!doc.to_string().contains(UUID), "{doc}"); + assert_eq!(env["vex"]["statements"], 1, "{env}"); + assert_eq!(env["vex"]["affected"], Value::Null, "{env}"); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, Vec::::new(), "no registry request"); +} + +/// A lock that names the ruby-platform gem beside the platform builds: +/// that entry is the gem's own patch, attested as the gem itself, beside +/// the patched platform build; the build on upstream's gem is affected. +#[tokio::test(flavor = "multi_thread")] +async fn the_runs_vex_attests_the_ruby_entry_under_the_gems_own_patch() { + let listing: [Listed; 3] = [ + (ARM, ARM_UPSTREAM, None), + ("ruby", RUBY_PATCHED, Some(UUID)), + (LINUX, LINUX_PATCHED, Some(LINUX_UUID)), + ]; + let server = MockServer::start().await; + mount_api(&server, Some((&listing[..], 4))).await; + let api = server.uri(); + let with_ruby = lock(true) + .replace( + &format!(" {DEP} ({DEP_VERSION}-{ARM})\n"), + &format!(" {DEP} ({DEP_VERSION})\n {DEP} ({DEP_VERSION}-{ARM})\n"), + ) + .replace( + &format!(" {DEP} ({DEP_VERSION}-{ARM}) sha256="), + &format!( + " {DEP} ({DEP_VERSION}) sha256={}\n {DEP} ({DEP_VERSION}-{ARM}) sha256=", + "d".repeat(64) + ), + ); + let proj = project(&with_ruby); + let (code, env, doc) = scan_vex(proj.path(), &api); + assert_eq!(code, 0, "{env}"); + let after = read(proj.path(), "Gemfile.lock"); + assert!( + after.contains(&format!(" {DEP} ({DEP_VERSION}) sha256={RUBY_PATCHED}\n")), + "{after}" + ); + let mut patched = patched_statement(&[(LINUX, LINUX_UUID)], false); + patched.packages.insert(0, PURL.to_string()); + patched.words = format!( + "Patched via Socket patch {LINUX_UUID} (redirected); Patched via Socket patch {UUID} \ + (redirected)" + ); + assert_eq!( + said(&doc.expect("a document")), + [patched, upstream_statement(ARM)] + ); + assert_eq!(env["vex"]["affected"], 1, "{env}"); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, Vec::::new(), "no registry request"); +} + +/// A later `vex` over a lock with `CHECKSUMS`: ONE request beyond the +/// record, the gem patch's reference. The document is the run's own, the +/// envelope reports each build with the gem's patch as its fix, and the +/// build on upstream's gem is neither counted nor a failure. A person +/// reads which builds are attested, with no warning. +#[tokio::test(flavor = "multi_thread")] +async fn a_later_vex_tells_the_builds_of_a_checksummed_lock_apart_in_one_request() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, true); + + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!( + said(out.doc()), + [ + patched_statement(&[(LINUX, LINUX_UUID)], false), + upstream_statement(ARM) + ] + ); + let env = &out.envelope; + assert_eq!(env["status"], "success", "{out}"); + assert_eq!( + build_events(env), + [ + event("verified", LINUX, ""), + event("skipped", ARM, "gem_upstream_build_kept") + ], + "{out}" + ); + assert_eq!( + env["events"][1]["reason"], + format!("the patch registry serves upstream's own gem for {ARM}: no patched build yet"), + "{out}" + ); + assert_eq!(env["events"][1]["details"]["status"], "affected", "{out}"); + assert_eq!( + (&env["summary"]["verified"], &env["summary"]["skipped"]), + (&json!(1), &json!(0)), + "the build on upstream's gem is counted nowhere: {out}" + ); + assert_eq!(warning_codes(env), Vec::::new(), "{out}"); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, Vec::::new(), "no registry request"); + assert_eq!(view_requests(&server).await, 1); + + let human = vex_e2e_common::VexRun { + human: true, + ..vex_run(&api) + }; + let out = vex_e2e_common::run_vex(&vex_e2e_common::binary(), proj.path(), &human); + assert_eq!(out.code, Some(0), "{out}"); + assert!( + out.stdout.contains(&format!( + "Wrote OpenVEX document with 2 statements (1 affected) to {}\n{DEP} {DEP_VERSION}: \ + patched for {LINUX}; upstream gem kept for {ARM} (no patched build yet)\n", + out.output.display() + )), + "{out}" + ); + assert!(!out.stderr.contains("Warning"), "{out}"); +} + +/// A later `vex` over a lock with no `CHECKSUMS`: the lock installs what +/// its own registry serves, so a SECOND request reads that registry's +/// index. Two requests, the same document. With the index unreadable +/// nothing shows what the lock installs: both builds are in the document +/// as affected, the run exits 0 as a success, and one warning says why +/// (with the error of the read) and what to run. +#[tokio::test(flavor = "multi_thread")] +async fn a_later_vex_asks_the_registry_of_a_lock_without_checksums() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + mount_index(&server, ARM_UPSTREAM, LINUX_PATCHED).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, false); + assert!(!read(proj.path(), "Gemfile.lock").contains("CHECKSUMS")); + + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!( + said(out.doc()), + [ + patched_statement(&[(LINUX, LINUX_UUID)], false), + upstream_statement(ARM) + ] + ); + assert_eq!(out.envelope["status"], "success", "{out}"); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other, [index_path()], "and the lock's own registry, once"); + + // No index to read: nothing says what the lock installs. + let silent = MockServer::start().await; + mount_api(&silent, Some((&ONE_PATCHED[..], 4))).await; + let api = silent.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, false); + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + let why = "the lockfile has no CHECKSUMS entry for it, and its registry's index could not be \ + read"; + assert_eq!( + said(out.doc()), + [ + unshown_statement(ARM, why, RETRY, true), + unshown_statement(LINUX, why, RETRY, true) + ], + "{out}" + ); + assert!( + !out.doc().to_string().contains(LINUX_UUID) && !out.doc().to_string().contains(UUID), + "no patch is named for a build that is not shown patched: {out}" + ); + assert_eq!( + build_events(&out.envelope), + unshown_events(&out.envelope, &[ARM, LINUX]), + "{out}" + ); + assert_eq!( + out.envelope["events"][0]["reason"], + format!("not shown patched for {ARM}: {why}"), + "{out}" + ); + assert_eq!( + warning_codes(&out.envelope), + ["vex_gem_build_unknown"], + "{out}" + ); + let detail = out.envelope["warnings"][0]["detail"].as_str().unwrap(); + assert!( + detail.contains( + "(the lockfile has no CHECKSUMS entry for them, and its registry's index could not \ + be read: " + ) && detail.ends_with(&format!( + "), so the VEX document states them as affected. {RETRY}" + )) && !detail.contains(TOKEN), + "{detail}" + ); +} + +/// The reference a later `vex` gets is of a newer registry than the lock +/// names: it lists a patched build for the platform the lock still pins +/// upstream's gem for. That build is NOT attested: the lock does not +/// install it. It is in the document as affected, with no patch named for +/// it, beside the build the lock does pin patched; the run exits 0 as a +/// success and sends the reader to the scan that moves the lock. +#[tokio::test(flavor = "multi_thread")] +async fn a_later_vex_says_affected_of_a_build_a_newer_reference_lists_but_the_lock_does_not_pin() { + for checksums in [true, false] { + let server = MockServer::start().await; + mount_api(&server, Some((&BOTH_PATCHED[..], 5))).await; + // The registry the lock names still serves upstream's gem there. + mount_index(&server, ARM_UPSTREAM, LINUX_PATCHED).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, checksums); + + let why = "the lockfile installs another archive for it than the patch registry lists now"; + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "checksums: {checksums}: {out}"); + assert_eq!( + said(out.doc()), + [ + patched_statement(&[(LINUX, LINUX_UUID)], false), + unshown_statement(ARM, why, RESCAN, false) + ], + "checksums: {checksums}" + ); + assert!(!out.doc().to_string().contains(ARM_UUID), "{out}"); + let mut events = vec![event("verified", LINUX, "")]; + events.extend(unshown_events(&out.envelope, &[ARM])); + assert_eq!(build_events(&out.envelope), events, "{out}"); + assert_eq!( + out.envelope["events"][1]["reason"], + format!("not shown patched for {ARM}: {why}"), + "{out}" + ); + assert_eq!(out.envelope["summary"]["verified"], 1, "{out}"); + assert_eq!( + warning_codes(&out.envelope), + ["vex_gem_build_unknown"], + "{out}" + ); + assert_eq!( + out.envelope["warnings"][0]["detail"], + format!( + "{PURL}: the lockfile takes its build for {ARM} from the registry of Socket patch \ + {UUID}, which serves a patched build for some platforms and upstream's own gem \ + for the others. Which it is for this one could not be told (the lockfile \ + installs another archive for it than the patch registry lists now), so the VEX \ + document states it as affected. {RESCAN}" + ), + "{out}" + ); + let (references, other) = requests(&server).await; + assert_eq!(references, [[UUID.to_string()]], "one reference request"); + assert_eq!(other.len(), usize::from(!checksums), "{other:?}"); + + // A person reads the warning and what the document says of each + // build: nothing is left out, and nothing fails. + let human = vex_e2e_common::VexRun { + human: true, + ..vex_run(&api) + }; + let out = vex_e2e_common::run_vex(&vex_e2e_common::binary(), proj.path(), &human); + assert_eq!(out.code, Some(0), "{out}"); + assert!( + out.stdout.ends_with(&format!( + "Wrote OpenVEX document with 2 statements (1 affected) to {}\n{DEP} \ + {DEP_VERSION}: patched for {LINUX}; not shown patched for {ARM}\n", + out.output.display() + )), + "{out}" + ); + assert!( + out.stderr.contains(&format!( + "Warning: {PURL}: the lockfile takes its build for {ARM} from the registry of \ + Socket patch {UUID}" + )), + "{out}" + ); + assert!( + out.stderr.matches("Warning: ").count() == 1 + && !out.stderr.contains("omitting") + && !out.stderr.contains("Error"), + "one warning, and nothing left out: {out}" + ); + + // The scan the note names moves the lock, and the next document + // attests both builds. + let (code, env, doc) = scan_vex(proj.path(), &api); + assert_eq!(code, 0, "{env}"); + assert_eq!( + said(&doc.expect("a document")), + [patched_statement( + &[(ARM, ARM_UUID), (LINUX, LINUX_UUID)], + true + )] + ); + } +} + +/// A hosted run's own `--vex` can meet a build it cannot tell too: a gem +/// an earlier run moved, whose patch this run's search does not return +/// (such a pin is kept, and the run pins nothing), on a lock older than +/// the reference lists. The run's document says `affected` of that build +/// beside the one the lock pins patched, the warning is among the +/// document's, and the run is a success. With every build untold it still +/// is: both are in the document as affected. +#[tokio::test(flavor = "multi_thread")] +async fn the_runs_vex_says_affected_of_a_build_of_a_gem_it_did_not_pin() { + let why = "the lockfile installs another archive for it than the patch registry lists now"; + for (linux_pin, statements, affected) in [ + ( + LINUX_PATCHED, + vec![ + patched_statement(&[(LINUX, LINUX_UUID)], false), + unshown_statement(ARM, why, RESCAN, false), + ], + 1, + ), + ( + LINUX_UPSTREAM, + vec![ + unshown_statement(ARM, why, RESCAN, true), + unshown_statement(LINUX, why, RESCAN, true), + ], + 2, + ), + ] { + let server = MockServer::start().await; + // The search finds no patch for the gem. + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "packages": [], "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(&server) + .await; + mount_api(&server, Some((&BOTH_PATCHED[..], 5))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, linux_pin, true); + let before = read(proj.path(), "Gemfile.lock"); + let (code, env, doc) = scan_vex(proj.path(), &api); + assert_eq!(code, 0, "{env}"); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!(hosted_events(&env), Vec::::new(), "{env}"); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + before, + "nothing is pinned" + ); + assert_eq!(said(&doc.expect("a document")), statements, "{env}"); + assert_eq!(env["vex"]["statements"], 2, "{env}"); + assert_eq!(env["vex"]["affected"], affected, "{env}"); + let vex_warnings: Vec<&str> = env["vex"]["warnings"] + .as_array() + .into_iter() + .flatten() + .filter_map(|warning| warning["code"].as_str()) + .collect(); + assert_eq!( + vex_warnings, + ["vex_hosted_unverified", "vex_gem_build_unknown"], + "the standing note of a hosted run's document, and the one warning for the gem: {env}" + ); + } +} + +/// The record of the gem's patch as a pre-v5 hosted ledger holds it: the +/// one way a hosted pin has a record with no request. +fn write_record_ledger(proj: &Path) { + let view = json!({ + "uuid": UUID, + "files": { "lib/platform_probe.rb": { + "beforeHash": "a".repeat(64), "afterHash": "b".repeat(64), + }}, + "vulnerabilities": { GHSA: { + "cves": [CVE], "summary": "s", "severity": "high", "description": "d", + }}, + "description": "x", "license": "MIT", "tier": "free", + }); + vex_e2e_common::write_legacy_redirect_ledger(proj, PURL, &view); +} + +/// `--offline`, with the record of the gem's patch at hand: no request at +/// all, so nothing says which locked build is patched. The gem's one pin +/// would have attested every build; instead each platform build is in the +/// document as affected, the run exits 0 as a success, and one warning +/// names the gem and what to run. +#[tokio::test(flavor = "multi_thread")] +async fn an_offline_vex_says_affected_of_each_platform_build_and_warns_once() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, true); + write_record_ledger(proj.path()); + let offline = vex_e2e_common::VexRun { + offline: true, + ..vex_run(&api) + }; + + let out = vex_e2e_common::run_vex(&vex_e2e_common::binary(), proj.path(), &offline); + assert_eq!(out.code, Some(0), "{out}"); + let (why, online) = ( + "--offline forbids asking the patch API", + "Run `socket-patch vex` without --offline to attest each build.", + ); + assert_eq!( + said(out.doc()), + [ + unshown_statement(ARM, why, online, true), + unshown_statement(LINUX, why, online, true) + ], + "{out}" + ); + assert!( + !out.doc().to_string().contains(LINUX_UUID) && !out.doc().to_string().contains(UUID), + "no patch is named for a build that is not shown patched: {out}" + ); + assert_eq!( + build_events(&out.envelope), + unshown_events(&out.envelope, &[ARM, LINUX]), + "{out}" + ); + assert_eq!( + out.envelope["warnings"], + json!([{ + "code": "vex_gem_build_unknown", + "detail": format!( + "{PURL}: the lockfile takes its builds for {ARM}, {LINUX} from the registry of \ + Socket patch {UUID}, which serves a patched build for some platforms and \ + upstream's own gem for the others. Which it is for these could not be told \ + (--offline forbids asking the patch API), so the VEX document states them as \ + affected. {online}" + ), + }]), + "{out}" + ); + assert_eq!( + server.received_requests().await.unwrap_or_default().len(), + 0, + "--offline asks nothing" + ); + + // Online, the same project is the document of the run that moved it. + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!( + said(out.doc()), + [ + patched_statement(&[(LINUX, LINUX_UUID)], false), + upstream_statement(ARM) + ] + ); + assert_eq!(view_requests(&server).await, 0, "the ledger has the record"); +} + +/// The reference request fails: the record is there, the list of the +/// gem's builds is not. No build is attested as patched: each is in the +/// document as affected, the run exits 0 as a success, the registry is +/// not asked, and the warning carries the failure (the document does not). +#[tokio::test(flavor = "multi_thread")] +async fn a_failed_reference_request_says_affected_of_each_platform_build() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(ResponseTemplate::new(500)) + .with_priority(1) + .mount(&server) + .await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, true); + + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + let why = "the patch API request failed"; + assert_eq!( + said(out.doc()), + [ + unshown_statement(ARM, why, RETRY, true), + unshown_statement(LINUX, why, RETRY, true) + ], + "{out}" + ); + assert_eq!( + build_events(&out.envelope), + unshown_events(&out.envelope, &[ARM, LINUX]), + "{out}" + ); + assert_eq!( + warning_codes(&out.envelope), + ["vex_gem_build_unknown"], + "{out}" + ); + let detail = out.envelope["warnings"][0]["detail"].as_str().unwrap(); + assert!( + detail.contains("could not be told (the patch API request failed: ") + && detail.ends_with(&format!( + "), so the VEX document states them as affected. {RETRY}" + )), + "{detail}" + ); + let (references, other) = requests(&server).await; + assert!( + !references.is_empty() && references.iter().all(|asked| asked == &[UUID.to_string()]), + "{references:?}" + ); + assert_eq!(other, Vec::::new(), "no registry request"); + + // A person reads one warning for the gem and one line for its builds, + // each named with its platform, and no error. + let human = vex_e2e_common::VexRun { + human: true, + ..vex_run(&api) + }; + let out = vex_e2e_common::run_vex(&vex_e2e_common::binary(), proj.path(), &human); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!(out.stderr.matches("Warning: ").count(), 1, "{out}"); + assert!( + out.stderr.contains(&format!( + "Warning: {PURL}: the lockfile takes its builds for {ARM}, {LINUX} from the \ + registry of Socket patch {UUID}" + )) && !out.stderr.contains("omitting") + && !out.stderr.contains("Error"), + "{out}" + ); + assert!( + out.stdout.ends_with(&format!( + "Wrote OpenVEX document with 2 statements (2 affected) to {}\n{DEP} {DEP_VERSION}: \ + not shown patched for {ARM}, {LINUX}\n", + out.output.display() + )), + "{out}" + ); +} + +/// A gem locked as its ruby-platform gem alone is the one pin it always +/// was: attested as the gem under the gem's patch, with the record as the +/// only request. No reference is asked for and no registry is read. +#[tokio::test(flavor = "multi_thread")] +async fn a_later_vex_of_a_gem_locked_as_its_ruby_gem_alone_asks_nothing_new() { + let server = MockServer::start().await; + mount_api(&server, None).await; + let api = server.uri(); + let index = index_url(&api, None); + let lock = format!( + "GEM\n remote: {index}\n specs:\n {DEP} ({DEP_VERSION})\n\nGEM\n remote: \ + https://rubygems.org/\n specs:\n racc (1.8.1)\n\nPLATFORMS\n ruby\n\nDEPENDENCIES\n \ + {DEP} (= {DEP_VERSION})!\n racc (= 1.8.1)\n\nCHECKSUMS\n {DEP} ({DEP_VERSION}) \ + sha256={RUBY_PATCHED}\n racc (1.8.1) sha256={RACC}\n\nBUNDLED WITH\n 4.0.15\n" + ); + let proj = project(&lock); + std::fs::write(proj.path().join("Gemfile"), hosted_gemfile(&index)).unwrap(); + + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!( + said(out.doc()), + [Said { + status: "not_affected", + packages: vec![PURL.to_string()], + products: vec![PURL.to_string()], + words: format!("Patched via Socket patch {UUID} (redirected)"), + }] + ); + assert_eq!( + out.envelope["events"], + json!([{ + "action": "verified", "purl": PURL, + "details": { "vulnerability": GHSA, "aliases": [CVE], "status": "not_affected" }, + }]), + "{out}" + ); + let (references, other) = requests(&server).await; + assert_eq!( + references, + Vec::>::new(), + "no reference request" + ); + assert_eq!(other, Vec::::new(), "no registry request"); + assert_eq!( + server.received_requests().await.unwrap_or_default().len(), + 1, + "the record, and nothing else" + ); +} + +/// Installed copies are judged per build. A machine of the platform on +/// upstream's gem holds upstream's gem, as its lock entry names it: that +/// copy is no evidence against the build the lock installs patched. A copy +/// of that patched build is: one that does not hold the patch withholds +/// it, and the build on upstream's gem is affected either way. +#[tokio::test(flavor = "multi_thread")] +async fn an_installed_copy_is_evidence_about_its_own_build_alone() { + let patched = b"module PlatformProbe\n FIXED = true\nend\n"; + let upstream = b"module PlatformProbe\n FIXED = false\nend\n"; + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{UUID}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "uuid": UUID, "purl": PURL, "publishedAt": "2026-01-01T00:00:00Z", + "files": { "lib/platform_probe.rb": { + "beforeHash": vex_e2e_common::git_sha256(upstream), + "afterHash": vex_e2e_common::git_sha256(patched), + }}, + "vulnerabilities": { GHSA: { + "cves": [CVE], "summary": "s", "severity": "high", "description": "d", + }}, + "description": "x", "license": "MIT", "tier": "free", + }))) + .with_priority(1) + .mount(&server) + .await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let api = server.uri(); + let index = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&index, ARM_UPSTREAM, LINUX_PATCHED, true); + let install = |platform: &str, content: &[u8]| { + let lib = proj.path().join(format!( + "vendor/bundle/ruby/3.3.0/gems/{DEP}-{DEP_VERSION}-{platform}/lib" + )); + std::fs::create_dir_all(&lib).unwrap(); + std::fs::write(lib.join("platform_probe.rb"), content).unwrap(); + }; + let both = [ + patched_statement(&[(LINUX, LINUX_UUID)], false), + upstream_statement(ARM), + ]; + + // This machine's platform is the one on upstream's gem. + install(ARM, upstream); + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!(said(out.doc()), both, "{out}"); + assert_eq!(out.envelope["status"], "success", "{out}"); + + // The patched build installed beside it, in a gem home that keeps no + // archive of it. A platform gem is a patch of its own, whose files + // carry that patch's header: the gem patch's record says nothing of + // them. While the record of the build's own patch cannot be read, + // nothing judges the copy: the build is stated affected under the + // unknown-build warning, and the run succeeds. + let stamped = [ + format!("# Socket Community Patch: {LINUX_UUID}\n").as_bytes(), + &patched[..], + ] + .concat(); + install(LINUX, &stamped); + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + let statuses: Vec<&str> = out.doc()["statements"] + .as_array() + .into_iter() + .flatten() + .filter_map(|statement| statement["status"].as_str()) + .collect(); + assert_eq!(statuses, ["affected", "affected"], "{out}"); + assert!( + warning_codes(&out.envelope).contains(&"vex_gem_build_unknown".to_string()), + "{out}" + ); + + // With that record served, the copy is checked against it and the + // build is attested. + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{LINUX_UUID}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "uuid": LINUX_UUID, "purl": format!("{PURL}?platform={LINUX}"), + "publishedAt": "2026-01-01T00:00:00Z", + "files": { "lib/platform_probe.rb": { + "beforeHash": vex_e2e_common::git_sha256(upstream), + "afterHash": vex_e2e_common::git_sha256(&stamped), + }}, + "vulnerabilities": {}, + "description": "x", "license": "MIT", "tier": "free", + }))) + .with_priority(1) + .mount(&server) + .await; + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!(said(out.doc()), both, "{out}"); + + // The archive in the gem home is no evidence for `vex`: whatever it + // holds, the copy's files are what the build's record judges. + let cache = proj.path().join("vendor/bundle/ruby/3.3.0/cache"); + std::fs::create_dir_all(&cache).unwrap(); + std::fs::write( + cache.join(format!("{DEP}-{DEP_VERSION}-{LINUX}.gem")), + b"not the listed gem", + ) + .unwrap(); + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!(said(out.doc()), both, "{out}"); + std::fs::remove_dir_all(&cache).unwrap(); + + // That copy still on upstream's files: the build is not attested, and + // no build of the gem is, so the gem without a platform is affected. + install(LINUX, upstream); + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + let mut unpatched = upstream_statement(ARM); + unpatched.products.insert(0, PURL.to_string()); + assert_eq!(said(out.doc()), [unpatched], "{out}"); + vex_e2e_common::assert_not_attested( + &out.envelope, + &format!("{PURL}?platform={LINUX}"), + "not_applied", + ); + assert_eq!(out.envelope["status"], "partialFailure", "{out}"); +} + +/// A lock that already takes its platform builds from this patch's +/// registry, at the snapshot an earlier scan wrote, while the list at hand +/// leaves one of its platforms out: upstream no longer publishes that +/// platform's gem. The gem is reported once, as a gem the registry does +/// not list a platform of, and nothing is written: the pair stays byte for +/// byte, and no string of the lock reaches the Gemfile. `vex` says nothing +/// false of it: the build the lock still installs patched is attested, the +/// one the list no longer names is `affected`, with what settles it. +#[tokio::test(flavor = "multi_thread")] +async fn a_lock_on_its_patch_whose_platform_the_list_no_longer_names_is_reported_and_left() { + let server = MockServer::start().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let proj = project(&lock(true)); + let api = server.uri(); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + let pair = || { + ( + read(proj.path(), "Gemfile.lock"), + read(proj.path(), "Gemfile"), + ) + }; + let pinned = pair(); + assert!(pinned.0.contains(&index_url(&api, Some(4))), "{}", pinned.0); + + // Upstream yanks the arm gem: the list no longer names the platform. + server.reset().await; + let linux_only: [Listed; 1] = [(LINUX, LINUX_PATCHED, Some(LINUX_UUID))]; + mount_api(&server, Some((&linux_only[..], 5))).await; + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(pair(), pinned, "the pair is left as it is"); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + let events = hosted_events(&env); + assert_eq!(events.len(), 1, "reported once: {env}"); + assert_eq!( + (&events[0]["action"], &events[0]["errorCode"]), + (&json!("skipped"), &json!("redirect_gem_platform_unlisted")), + "{env}" + ); + let said = events[0]["reason"].as_str().unwrap_or_default(); + assert!(said.contains(&format!("does not list {ARM}")), "{env}"); + + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + let mut statuses: Vec<(&str, &str)> = out.doc()["statements"] + .as_array() + .into_iter() + .flatten() + .map(|statement| { + let products = statement["products"].to_string(); + let platform = if products.contains(LINUX) { LINUX } else { ARM }; + (platform, statement["status"].as_str().unwrap_or_default()) + }) + .collect(); + statuses.sort(); + assert_eq!( + statuses, + [(ARM, "affected"), (LINUX, "not_affected")], + "{out}" + ); + let warned = out.envelope["warnings"].to_string(); + assert!( + warned.contains("vex_gem_build_unknown") + && warned.contains("bundle lock --remove-platform"), + "the warning names what settles it: {out}" + ); +} + +/// The patch service builds a patched gem again while a lock is pinned to +/// it. Its registry lists what it listed, and answers it to a client that +/// presents its key: the scan of such a lock sends the key its registry +/// URL names. So nothing changes, the gem is reported as on its patch, +/// with nothing left to patch, and `vex` still attests the installed +/// patched build. +#[tokio::test(flavor = "multi_thread")] +async fn a_lock_on_its_patch_presents_its_snapshot_while_a_build_is_rebuilt() { + let patched = b"module PlatformProbe\n FIXED = true\nend\n"; + let upstream = b"module PlatformProbe\n FIXED = false\nend\n"; + let stamped = [ + format!("# Socket Community Patch: {LINUX_UUID}\n").as_bytes(), + &patched[..], + ] + .concat(); + let build_record = || { + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{LINUX_UUID}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "uuid": LINUX_UUID, "purl": format!("{PURL}?platform={LINUX}"), + "publishedAt": "2026-01-01T00:00:00Z", + "files": { "lib/platform_probe.rb": { + "beforeHash": vex_e2e_common::git_sha256(upstream), + "afterHash": vex_e2e_common::git_sha256(&stamped), + }}, + "vulnerabilities": {}, + "description": "x", "license": "MIT", "tier": "free", + }))) + }; + let server = MockServer::start().await; + build_record().mount(&server).await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let proj = project(&lock(true)); + let api = server.uri(); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + // The patched linux build, installed. + let lib = proj.path().join(format!( + "vendor/bundle/ruby/3.3.0/gems/{DEP}-{DEP_VERSION}-{LINUX}/lib" + )); + std::fs::create_dir_all(&lib).unwrap(); + std::fs::write(lib.join("platform_probe.rb"), &stamped).unwrap(); + let pair = || { + ( + read(proj.path(), "Gemfile.lock"), + read(proj.path(), "Gemfile"), + ) + }; + let pinned = pair(); + let (code, settled) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{settled}"); + let attested = vex(proj.path(), &api); + assert_eq!(attested.code, Some(0), "{attested}"); + let build = format!("{PURL}?platform={LINUX}"); + let statuses = |doc: &Value| -> Vec { + vex_e2e_common::statements_for(doc, &build) + .iter() + .filter_map(|statement| statement["status"].as_str().map(str::to_string)) + .collect() + }; + assert_eq!(statuses(attested.doc()), ["not_affected"], "{attested}"); + + // The linux build is being built again. + server.reset().await; + build_record().mount(&server).await; + mount_api_rebuilding(&server, (&ONE_PATCHED[..], 4)).await; + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(pair(), pinned, "the pair is left as it is"); + assert_eq!(warning_codes(&env), warning_codes(&settled), "{env}"); + assert_eq!(hosted_events(&env), hosted_events(&settled), "{env}"); + assert_eq!(env["summary"], settled["summary"], "{env}"); + let bodies = reference_bodies(&server).await; + assert!( + !bodies.is_empty() + && bodies + .iter() + .all(|body| body["gemSnapshotKeys"] == json!({ UUID: "4" })), + "every reference request presents the snapshot the lock is on: {bodies:?}" + ); + let out = vex(proj.path(), &api); + assert_eq!(out.code, Some(0), "{out}"); + assert_eq!(statuses(out.doc()), ["not_affected"], "{out}"); + assert_eq!(warning_codes(&out.envelope), Vec::::new(), "{out}"); + + // For a person: the gem is on its patch, and nothing is left to patch. + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("already on hosted patches") && !stdout.contains("left to patch"), + "{stdout}\n{stderr}" + ); + assert!( + !(stdout + &stderr).contains("still being built"), + "{stderr}" + ); +} + +/// A client that presents no snapshot is answered the registry of the +/// ruby gem alone, with no list, as a client that asks for none is: a +/// project whose lock is not on the patch's registry has no key to present. +/// Its request names none. Its lock names platform builds, which that +/// registry does not serve, so the gem is left on its upstream registry, +/// with the warning that says the service names no platform gem right now, +/// and moves on a run after the rebuild. +#[tokio::test(flavor = "multi_thread")] +async fn a_lock_that_holds_no_snapshot_is_left_alone_while_a_build_is_rebuilt() { + let server = MockServer::start().await; + mount_api_rebuilding(&server, (&ONE_PATCHED[..], 4)).await; + let proj = project(&lock(true)); + let api = server.uri(); + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(read(proj.path(), "Gemfile.lock"), lock(true)); + assert_eq!(read(proj.path(), "Gemfile"), GEMFILE); + assert_eq!( + warning_codes(&env), + ["redirect_gem_platform_unsupported"], + "{env}" + ); + assert!( + env["warnings"].to_string().contains("right now"), + "the warning says it is the state of the service: {env}" + ); + let bodies = reference_bodies(&server).await; + assert!( + !bodies.is_empty() + && bodies + .iter() + .all(|body| body.get("gemSnapshotKeys").is_none()), + "a request with no snapshot to present is the request it always was: {bodies:?}" + ); + + // After the rebuild the gem moves. + server.reset().await; + mount_api(&server, Some((&ONE_PATCHED[..], 4))).await; + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + let index = format!("{}/", index_url(&api, Some(4))); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&index, ARM_UPSTREAM, LINUX_PATCHED) + ); +} + +/// A lock on an earlier snapshot of its patch, in which both builds were +/// patched. Since then the `arm64-darwin` build was withdrawn, and the +/// `x86_64-linux-gnu` build is being built again. The registry as it +/// stands has another key, so the service tells this lock the patch is not +/// ready: nothing is rewritten, and no build is reported as withdrawn or +/// put back on upstream's gem while the service cannot say what the +/// rebuilt one will be. The first run after the rebuild moves the lock +/// once: upstream's gem back for the withdrawn build, the rebuilt one +/// pinned as it was. +#[tokio::test(flavor = "multi_thread")] +async fn a_lock_on_an_earlier_snapshot_waits_out_a_rebuild_and_then_moves_once() { + let server = MockServer::start().await; + let api = server.uri(); + let earlier = format!("{}/", index_url(&api, Some(4))); + let proj = hosted_project(&earlier, ARM_PATCHED, LINUX_PATCHED, true); + let pair = || { + ( + read(proj.path(), "Gemfile.lock"), + read(proj.path(), "Gemfile"), + ) + }; + let pinned = pair(); + + mount_api_rebuilding(&server, (&ONE_PATCHED[..], 6)).await; + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + assert_eq!(pair(), pinned, "the pair is left as it is"); + let said = env.to_string(); + assert!( + said.contains("pending_build") && !said.contains("withdrawn"), + "the patch is still being built, and nothing is called withdrawn: {env}" + ); + assert_eq!(warning_codes(&env), Vec::::new(), "{env}"); + let bodies = reference_bodies(&server).await; + assert!( + !bodies.is_empty() + && bodies + .iter() + .all(|body| body["gemSnapshotKeys"] == json!({ UUID: "4" })), + "every reference request presents the snapshot the lock is on: {bodies:?}" + ); + let (code, stdout, stderr) = hosted(proj.path(), &api, &["scan"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + (stdout + &stderr).contains("still being built"), + "a person is told to run it again later" + ); + assert_eq!(pair(), pinned); + + // The rebuild is over, with the bytes the build had. + server.reset().await; + mount_api(&server, Some((&ONE_PATCHED[..], 6))).await; + let (code, env) = scan_json(proj.path(), &api, &[]); + assert_eq!(code, 0, "{env}"); + let now = format!("{}/", index_url(&api, Some(6))); + assert_eq!( + read(proj.path(), "Gemfile.lock"), + hosted_lock(&now, ARM_UPSTREAM, LINUX_PATCHED), + "{env}" + ); + assert!( + hosted_events(&env).contains(&withdrawn_event(ARM)), + "the withdrawn build is said to be back on upstream's gem: {env}" + ); +} + +/// The files of a Bundler pair as a hosted run leaves them on the snapshot +/// `index` names, written into `proj` under `manifest` and `lock`. +fn write_hosted_pair(proj: &Path, manifest: &str, lock: &str, index: &str) { + std::fs::write(proj.join(manifest), hosted_gemfile(index)).unwrap(); + let pinned = hosted_lock(index, ARM_UPSTREAM, LINUX_PATCHED); + std::fs::write(proj.join(lock), pinned).unwrap(); +} + +/// The snapshot each reference request of the run presented for the patch. +async fn presented_keys(server: &MockServer) -> Vec { + let bodies = reference_bodies(server).await; + bodies + .iter() + .map(|body| body["gemSnapshotKeys"][UUID].clone()) + .collect() +} + +/// A `gems.rb` project with an orphan `Gemfile.lock` beside it, each lock +/// on another snapshot of the patch. Bundler loads `gems.rb`, so the run +/// rewrites `gems.rb` and `gems.locked`, presents the snapshot +/// `gems.locked` names, and leaves the orphan as it is. +#[tokio::test(flavor = "multi_thread")] +async fn a_gems_rb_project_presents_and_rewrites_gems_locked_beside_an_orphan_lock() { + let server = MockServer::start().await; + let api = server.uri(); + mount_api(&server, Some((&BOTH_PATCHED[..], 5))).await; + let index = |snapshot: u32| format!("{}/", index_url(&api, Some(snapshot))); + let dir = tempfile::tempdir().unwrap(); + let proj = dir.path(); + write_hosted_pair(proj, "gems.rb", "gems.locked", &index(4)); + let orphan = hosted_lock(&index(9), ARM_UPSTREAM, LINUX_PATCHED); + std::fs::write(proj.join("Gemfile.lock"), &orphan).unwrap(); + + let (code, env) = scan_json(proj, &api, &[]); + assert_eq!(code, 0, "{env}"); + let keys = presented_keys(&server).await; + assert!( + !keys.is_empty() && keys.iter().all(|key| key == "4"), + "the snapshot of gems.locked is presented: {keys:?}" + ); + assert_eq!( + read(proj, "gems.locked"), + hosted_lock(&index(5), ARM_PATCHED, LINUX_PATCHED), + "{env}" + ); + assert_eq!(read(proj, "gems.rb"), hosted_gemfile(&index(5))); + assert_eq!( + read(proj, "Gemfile.lock"), + orphan, + "the orphan is untouched" + ); + assert!(!proj.join("Gemfile").exists()); +} + +/// Both spellings of the pair side by side, each lock on another snapshot +/// of the patch, with `BUNDLE_GEMFILE` naming the `Gemfile`. Bundler loads +/// that pair, so the run rewrites it and presents the snapshot +/// `Gemfile.lock` names; the `gems.rb` pair is left as it is. Without the +/// setting nothing says which pair Bundler loads: neither is rewritten, +/// and no snapshot is presented. +#[tokio::test(flavor = "multi_thread")] +async fn a_twin_presents_and_rewrites_the_pair_bundle_gemfile_names() { + let server = MockServer::start().await; + let api = server.uri(); + mount_api(&server, Some((&BOTH_PATCHED[..], 5))).await; + let index = |snapshot: u32| format!("{}/", index_url(&api, Some(snapshot))); + let dir = tempfile::tempdir().unwrap(); + let proj = dir.path(); + write_hosted_pair(proj, "Gemfile", "Gemfile.lock", &index(4)); + write_hosted_pair(proj, "gems.rb", "gems.locked", &index(9)); + let other = (read(proj, "gems.rb"), read(proj, "gems.locked")); + std::fs::create_dir(proj.join(".bundle")).unwrap(); + let config = proj.join(".bundle/config"); + std::fs::write(&config, "---\nBUNDLE_GEMFILE: \"Gemfile\"\n").unwrap(); + + let (code, env) = scan_json(proj, &api, &[]); + assert_eq!(code, 0, "{env}"); + let keys = presented_keys(&server).await; + assert!( + !keys.is_empty() && keys.iter().all(|key| key == "4"), + "the snapshot of Gemfile.lock is presented: {keys:?}" + ); + assert_eq!( + read(proj, "Gemfile.lock"), + hosted_lock(&index(5), ARM_PATCHED, LINUX_PATCHED), + "{env}" + ); + assert_eq!(read(proj, "Gemfile"), hosted_gemfile(&index(5))); + assert_eq!((read(proj, "gems.rb"), read(proj, "gems.locked")), other); + + std::fs::remove_file(&config).unwrap(); + server.reset().await; + mount_api(&server, Some((&BOTH_PATCHED[..], 6))).await; + let before = (read(proj, "Gemfile"), read(proj, "Gemfile.lock")); + let (_, env) = scan_json(proj, &api, &[]); + assert_eq!( + (read(proj, "Gemfile"), read(proj, "Gemfile.lock")), + before, + "{env}" + ); + assert_eq!((read(proj, "gems.rb"), read(proj, "gems.locked")), other); + let keys = presented_keys(&server).await; + assert!( + keys.iter().all(Value::is_null), + "a twin nothing settles presents no snapshot: {keys:?}" + ); +} 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 e251ca7e97..a1c673029f 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,14 +101,28 @@ 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). +/// One platform gem of the fixture gem's version as the grant lists it +/// (`gemBuilds`): its platform, the sha256 the patch registry serves for +/// it, and the patch of its patched build (`None`: the registry serves +/// upstream's own gem for that platform). +type ListedBuild<'a> = (&'a str, String, Option<&'a str>); + +/// The snapshot the registry URL of a grant that lists platform gems names. +const SNAPSHOT: u32 = 4; + +/// The patches of the fixture gem's patched platform builds. +const ARM_UUID: &str = "a1b2c3d4-0000-4000-8000-00000000000a"; +const LINUX_UUID: &str = "a1b2c3d4-0000-4000-8000-00000000000b"; + +/// [`mount_api_for`] with the grant also listing `builds`, every platform +/// gem of the version (`gemBuilds`; absent from a grant with none, as the +/// service sends a patch of the ruby gem alone), under a registry URL that +/// names [`SNAPSHOT`]. async fn mount_api_with( server: &MockServer, view_budget: Option, patched_sha: &str, - prebuilds: &[(&str, String)], + builds: &[ListedBuild<'_>], ) { mount_patch_api_with( server, @@ -116,11 +130,18 @@ async fn mount_api_with( PATCHED_LIB, view_budget, patched_sha, - prebuilds, + builds, + SNAPSHOT, ) .await; } +/// The path of the patch registry of the fixture gem's patch as a grant +/// that lists platform gems names it (no trailing slash). +fn snapshot_registry_path() -> String { + format!("/patch-registry/gem/{TOKEN}/{UUID}/s/{SNAPSHOT}") +} + /// [`mount_api_for`] for the patch `uuid`, whose patched lib is /// `patched_lib`. async fn mount_patch_api( @@ -130,37 +151,69 @@ async fn mount_patch_api( view_budget: Option, patched_sha: &str, ) { - mount_patch_api_with(server, uuid, patched_lib, view_budget, patched_sha, &[]).await; + mount_patch_api_with(server, uuid, patched_lib, view_budget, patched_sha, &[], 0).await; } -/// The API of the patch `uuid`, whose patched lib is `patched_lib` and -/// whose grant lists `prebuilds`. -async fn mount_patch_api_with( - server: &MockServer, +/// The grant of the patch `uuid` on `api`, whose patched ruby gem has the +/// sha256 `patched_sha` and which lists `builds` under the registry +/// snapshot `snapshot` (a grant with no list names the registry without +/// one). +fn granted_reference( + api: &str, uuid: &str, - patched_lib: &str, - view_budget: Option, patched_sha: &str, - prebuilds: &[(&str, String)], -) { + builds: &[ListedBuild<'_>], + snapshot: u32, +) -> serde_json::Value { let mut identifiers = serde_json::json!({ "name": DEP, "version": DEP_VERSION, "gemChecksumSha256": patched_sha, }); - if !prebuilds.is_empty() { - identifiers["gemPlatforms"] = prebuilds + let hosted_url = + format!("{api}/patch/gem/{DEP}/{DEP_VERSION}/{TOKEN}/{uuid}/{DEP}-{DEP_VERSION}.gem"); + let mut index_url = format!("{api}/patch-registry/gem/{TOKEN}/{uuid}/"); + if !builds.is_empty() { + identifiers["gemBuilds"] = builds .iter() - .map(|(platform, sha)| { - serde_json::json!({ "platform": platform, "gemChecksumSha256": sha }) + .map(|(platform, sha, patch)| { + serde_json::json!({ + "platform": platform, "gemChecksumSha256": sha, "patchUuid": patch, + }) }) .collect(); + index_url = format!("{index_url}s/{snapshot}"); } - 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()); + serde_json::json!({ + "status": "granted", + "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, + } + }) +} + +/// The API of the patch `uuid`, whose patched lib is `patched_lib` and +/// whose grant lists `builds` under the registry snapshot `snapshot` +/// ([`granted_reference`]). +async fn mount_patch_api_with( + server: &MockServer, + uuid: &str, + patched_lib: &str, + view_budget: Option, + patched_sha: &str, + builds: &[ListedBuild<'_>], + snapshot: u32, +) { + let reference = granted_reference(&server.uri(), uuid, patched_sha, builds, snapshot); Mock::given(method("POST")) .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ @@ -194,23 +247,7 @@ async fn mount_patch_api_with( 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": [{ - "kind": "tarball", - "url": hosted_url, - "integrity": { "sha256": patched_sha } - }], - "registryOverride": { - "kind": "rubygems-compact-index", - "indexUrl": index_url, - "identifiers": identifiers, - } - } - } + "results": { uuid: reference } }))) .mount(server) .await; @@ -351,6 +388,23 @@ fn hosted_pinned(env: &serde_json::Value) -> u64 { .count() as u64 } +/// `(purl, uuid)` of each hosted pin the run reports, in event order. +fn hosted_pins(env: &serde_json::Value) -> 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 text = |key: &str| e[key].as_str().unwrap_or_default().to_string(); + (text("purl"), text("uuid")) + }) + .collect() +} + fn stale_warnings(env: &serde_json::Value) -> Vec { env["warnings"] .as_array() @@ -2647,8 +2701,8 @@ async fn refresh_replaces_a_stale_platform_install_with_its_prebuild() { None, &sha256_of(&real_gem(PATCHED_LIB)), &[ - (PLATFORM, sha256_of(&prebuilt)), - (OTHER_PLATFORM, sha256_of(&other_prebuilt)), + (PLATFORM, sha256_of(&prebuilt), Some(ARM_UUID)), + (OTHER_PLATFORM, sha256_of(&other_prebuilt), Some(LINUX_UUID)), ], ) .await; @@ -2656,7 +2710,8 @@ async fn refresh_replaces_a_stale_platform_install_with_its_prebuild() { // The patch registry serves the prebuild under the platform gem's name. Mock::given(method("GET")) .and(path(format!( - "/patch-registry/gem/{TOKEN}/{UUID}/gems/{leaf}.gem" + "{}/gems/{leaf}.gem", + snapshot_registry_path() ))) .respond_with( ResponseTemplate::new(200).set_body_raw(prebuilt.clone(), "application/octet-stream"), @@ -2718,7 +2773,18 @@ 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}"); + // One pin, reported per locked build, each under its own patch. + assert_eq!( + hosted_pins(&env), + [ + (format!("{PURL}?platform={PLATFORM}"), ARM_UUID.to_string()), + ( + format!("{PURL}?platform={OTHER_PLATFORM}"), + LINUX_UUID.to_string() + ), + ], + "{env}" + ); assert!( !stdout.contains("redirect_gem_platform_unsupported"), "every locked platform has a prebuild: {env}" @@ -2726,7 +2792,7 @@ async fn refresh_replaces_a_stale_platform_install_with_its_prebuild() { // The lock: both builds under the patch registry, each on its own // prebuild's sha256. - let index = format!("{uri}/patch-registry/gem/{TOKEN}/{UUID}/"); + let index = format!("{uri}{}/", snapshot_registry_path()); let hosted_lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); assert!( hosted_lock.contains(&format!( @@ -2871,15 +2937,15 @@ async fn stale_guard_follows_the_builds_the_lock_names_in_a_home_with_both() { None, &sha256_of(&real_gem(PATCHED_LIB)), &[ - (PLATFORM, sha256_of(&prebuilt)), - (OTHER_PLATFORM, sha256_of(&other_prebuilt)), + (PLATFORM, sha256_of(&prebuilt), Some(ARM_UUID)), + (OTHER_PLATFORM, sha256_of(&other_prebuilt), Some(LINUX_UUID)), ], ) .await; let leaf = format!("{DEP}-{DEP_VERSION}-{PLATFORM}"); for (route, body) in [ ( - format!("/patch-registry/gem/{TOKEN}/{UUID}/gems/{leaf}.gem"), + format!("{}/gems/{leaf}.gem", snapshot_registry_path()), prebuilt.clone(), ), (format!("/upstream/gems/{leaf}.gem"), upstream.clone()), @@ -2937,7 +3003,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, "both locked builds: {env}"); let stale = stale_warnings(&env); assert_eq!(stale.len(), 1, "one stale copy, the platform build: {env}"); assert!( @@ -3021,1068 +3087,1628 @@ async fn stale_guard_follows_the_builds_the_lock_names_in_a_home_with_both() { ruby_copy_untouched(); } -/// 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. -#[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)); - let (arm_sha, linux_sha) = ( - sha256_of(&real_gem_for(PATCHED_LIB, PLATFORM)), - sha256_of(&real_gem_for(PATCHED_LIB, OTHER_PLATFORM)), - ); - for complete in [true, false] { - let server = MockServer::start().await; - let mut prebuilds = vec![(PLATFORM, arm_sha.clone())]; - if complete { - prebuilds.push((OTHER_PLATFORM, linux_sha.clone())); - } - mount_api_with(&server, None, &ruby_sha, &prebuilds).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, "{env}\nstderr:\n{stderr}"); - 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}"); - assert!(skipped.is_empty(), "{env}"); - assert!( - after.contains(&format!( - "/patch-registry/gem/{TOKEN}/{UUID}/\n specs:\n {DEP} \ - ({DEP_VERSION}-{PLATFORM})\n {DEP} ({DEP_VERSION}-{OTHER_PLATFORM})\n" - )), - "{after}" - ); - assert!( - after.contains(&format!( - " {DEP} ({DEP_VERSION}-{PLATFORM}) sha256={arm_sha}\n {DEP} \ - ({DEP_VERSION}-{OTHER_PLATFORM}) sha256={linux_sha}\n" - )), - "{after}" - ); - assert!( - stale_warnings(&env).is_empty(), - "nothing is installed: {env}" - ); - } else { - assert_eq!(hosted_pinned(&env), 0, "{env}"); - let [detail] = skipped.as_slice() else { - panic!("one platform skip: {env}"); - }; - assert!( - detail.contains(&format!( - "no patched build for `{DEP} ({DEP_VERSION}-{OTHER_PLATFORM})`" - )) && detail.contains(&format!("patched builds for {PLATFORM}")), - "{detail}" - ); - assert_eq!(after, lock, "the lock is untouched"); - assert_eq!( - std::fs::read_to_string(proj.join("Gemfile")).unwrap(), - gemfile, - "the Gemfile is untouched" - ); - } - } -} - -/// 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: -/// 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 -/// the installed platform copy). +/// A lock of two platform builds where the patch registry has a patched +/// build for the other platform only: this machine's platform is served +/// as upstream's own gem, and its lock entry keeps upstream's sha256. The +/// copy this machine installed and the committed `bundle cache` archive +/// are upstream's gem, which is right. The scan moves the gem, reports no +/// stale install, refreshes nothing and downloads no gem: with the gem +/// home's cached archive beside the install, and with it pruned, where +/// only the patch's file hashes could judge the copy (they would call +/// upstream's files stale). #[tokio::test(flavor = "multi_thread")] -async fn refused_platform_gem_is_counted_as_left_to_patch() { - const LEFT: &str = - "\n1 vulnerability left to patch: 1 is in packages this run did not patch.\n"; - let arm_sha = sha256_of(&real_gem_for(PATCHED_LIB, PLATFORM)); - for mode in ["hosted", "vendored"] { +async fn a_platform_served_as_upstreams_gem_is_no_stale_install() { + let upstream = real_gem_for(UPSTREAM_LIB, PLATFORM); + let other_upstream = real_gem_for(UPSTREAM_LIB, OTHER_PLATFORM); + let other_patched = real_gem_for(PATCHED_LIB, OTHER_PLATFORM); + let leaf = format!("{DEP}-{DEP_VERSION}-{PLATFORM}"); + for cached in [true, false] { let server = MockServer::start().await; - // The lookup names the advisory the patch fixes, as the service - // does (the totals count advisories), and only for a run that - // asks about the gem. - Mock::given(method("POST")) - .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "packages": [], - "canAccessPaidPatches": false, - }))) - .with_priority(2) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) - .and(body_string_contains(DEP)) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "packages": [{ - "purl": PURL, - "patches": [{ - "uuid": UUID, "purl": PURL, "tier": "free", - "cveIds": [], "ghsaIds": [GHSA], "severity": "high", - "title": "gem stale-install fixture" - }] - }], - "canAccessPaidPatches": false, - }))) - .with_priority(1) - .mount(&server) - .await; mount_api_with( &server, None, &sha256_of(&real_gem(PATCHED_LIB)), - &[(PLATFORM, arm_sha.clone())], + &[ + (PLATFORM, sha256_of(&upstream), None), + (OTHER_PLATFORM, sha256_of(&other_patched), Some(LINUX_UUID)), + ], ) .await; + // The registry hands this platform's gem on unchanged: a refresh + // that asked for it would be served, and would show below. + let gem_route = format!("{}/gems/{leaf}.gem", snapshot_registry_path()); + Mock::given(method("GET")) + .and(path(gem_route.clone())) + .respond_with( + ResponseTemplate::new(200) + .set_body_raw(upstream.clone(), "application/octet-stream"), + ) + .mount(&server) + .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}\"\ngem \ - \"plain-probe-gem\", \"1.0.0\"\n" - ); - // The plain gem makes the lock one that lists ruby-platform gems - // too, as every real lock does (nokogiri beside racc). - let lock = platform_lock(&"1".repeat(64), &"2".repeat(64)) - .replace(" specs:\n", " specs:\n plain-probe-gem (1.0.0)\n") - .replace( - "DEPENDENCIES\n", - "DEPENDENCIES\n plain-probe-gem (= 1.0.0)\n", - ); - assert!( - lock.contains(" plain-probe-gem (1.0.0)\n") - && !lock.contains(&format!(" {DEP} ({DEP_VERSION})\n")), - "the lock holds a plain gem, and {DEP} as platform builds only:\n{lock}" - ); - std::fs::write(proj.join("Gemfile"), &gemfile).unwrap(); + std::fs::write( + proj.join("Gemfile"), + format!("source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"), + ) + .unwrap(); + let lock = platform_lock(&sha256_of(&upstream), &sha256_of(&other_upstream)); std::fs::write(proj.join("Gemfile.lock"), &lock).unwrap(); - if mode == "vendored" { - install_real_gem_for(&project_home(&proj), UPSTREAM_LIB, PLATFORM); + let home = project_home(&proj); + let gem_dir = install_real_gem_for(&home, UPSTREAM_LIB, PLATFORM); + let home_archive = home.join("cache").join(format!("{leaf}.gem")); + if !cached { + std::fs::remove_file(&home_archive).unwrap(); } + let committed = proj + .join("vendor") + .join("cache") + .join(format!("{leaf}.gem")); + std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); + std::fs::write(&committed, &upstream).unwrap(); let uri = server.uri(); - let (code, stdout, stderr) = common::run_with_env( - &proj, - &[ - "scan", - "--mode", - mode, - "--yes", - "--cwd", - proj.to_str().unwrap(), - "--api-url", - uri.as_str(), - "--patch-server-url", - uri.as_str(), - "--org", - ORG, - "--api-token", - "fake", - ], - &[], + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "cached={cached}: {env}\nstderr:\n{stderr}"); + // The gem moved: the other platform is patched, this one is not. + assert_eq!( + hosted_pins(&env), + [( + format!("{PURL}?platform={OTHER_PLATFORM}"), + LINUX_UUID.to_string() + )], + "cached={cached}: {env}" ); - 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. - 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}`"), - }; + let hosted_lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + assert!( + hosted_lock.contains(&format!( + "CHECKSUMS\n {DEP} ({DEP_VERSION}-{PLATFORM}) sha256={}\n {DEP} \ + ({DEP_VERSION}-{OTHER_PLATFORM}) sha256={}\n", + sha256_of(&upstream), + sha256_of(&other_patched) + )), + "cached={cached}: this platform keeps upstream's sha256:\n{hosted_lock}" + ); + + // Nothing about this machine's copy: it is the gem the lock pins. assert!( - stderr.contains(&refusal), - "{mode}: the run refuses the gem\nstdout:\n{stdout}\nstderr:\n{stderr}" + stale_warnings(&env).is_empty() + && warnings_with_code(&env, "redirect_gem_install_refreshed").is_empty(), + "cached={cached}: {env}" ); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "cached={cached}"); + assert_eq!(std::fs::read(&committed).unwrap(), upstream); + match cached { + true => assert_eq!(std::fs::read(&home_archive).unwrap(), upstream), + false => assert!(!home_archive.exists(), "no archive is added"), + } + let asked: Vec = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .map(|request| request.url.path().to_string()) + .filter(|route| route.contains("/gems/") || route.contains("/patches/view/")) + .collect(); assert_eq!( - std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), - lock, - "{mode}: the lock is untouched" + asked, + Vec::::new(), + "cached={cached}: no gem is downloaded, no record is fetched to judge the copy" ); + + // For a person: the one line about the gem's builds, and no warning. + let (code, stdout, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &[]), &[]); + assert_eq!(code, 0, "cached={cached}:\n{stdout}\n{stderr}"); assert!( - stdout.ends_with(LEFT), - "{mode}: the refused gem is left to patch\nstdout:\n{stdout}\nstderr:\n{stderr}" + stdout.contains(&format!( + "{DEP} {DEP_VERSION}: patched for {OTHER_PLATFORM}; upstream gem kept for \ + {PLATFORM} (no patched build yet)\n" + )), + "cached={cached}:\n{stdout}" + ); + assert!( + !stderr.contains("stale") && !stderr.contains("unpatched install"), + "cached={cached}:\n{stderr}" ); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "cached={cached}"); + + // The VEX of this machine, from the run itself and from a later + // `vex`: the other platform's build is attested under its own + // patch, and this machine's build is said affected. The installed + // copy is upstream's gem, as its lock entry names it, and is no + // evidence against the build the lock installs patched. + let patched_part = format!("Patched via Socket patch {LINUX_UUID} (redirected)"); + let expected = [ + ( + "not_affected".to_string(), + format!("{PURL}?platform={OTHER_PLATFORM}"), + patched_part, + ), + ( + "affected".to_string(), + format!("{PURL}?platform={PLATFORM}"), + String::new(), + ), + ]; + let said = |doc: &serde_json::Value| -> Vec<(String, String, String)> { + let text = |value: &serde_json::Value| value.as_str().unwrap_or_default().to_string(); + let statements = doc["statements"].as_array().expect("statements"); + statements + .iter() + .map(|st| { + let packages = st["products"][0]["subcomponents"].as_array(); + assert_eq!(packages.map(Vec::len), Some(1), "{st}"); + ( + text(&st["status"]), + text(&st["products"][0]["subcomponents"][0]["@id"]), + text(&st["impact_statement"]), + ) + }) + .collect() + }; + let vex_path = proj.join("run.vex.json"); + let with_vex = [ + "--json", + "--vex", + vex_path.to_str().unwrap(), + "--vex-product", + "pkg:gem/app@1.0.0", + ]; + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &with_vex), &[]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "cached={cached}: {env}\nstderr:\n{stderr}"); + assert_eq!(env["vex"]["affected"], 1, "cached={cached}: {env}"); + let doc = vex_e2e_common::read_doc(&vex_path).expect("the run's document"); + assert_eq!(said(&doc), expected, "cached={cached}: {doc}"); + + let later = vex_e2e_common::VexRun { + api_url: Some(uri.clone()), + api_token: Some("fake".into()), + org: Some(ORG.into()), + patch_server_url: Some(uri.clone()), + product: Some("pkg:gem/app@1.0.0".into()), + ..vex_e2e_common::VexRun::default() + }; + let out = vex_e2e_common::run_vex(&vex_e2e_common::binary(), &proj, &later); + assert_eq!(out.code, Some(0), "cached={cached}: {out}"); + assert_eq!(said(out.doc()), expected, "cached={cached}: {out}"); + assert_eq!(out.envelope["status"], "success", "cached={cached}: {out}"); } } -/// Human output of the run that refreshes: one progress line per kind, -/// no warning, and the committed archive in the files to commit. -#[tokio::test(flavor = "multi_thread")] -async fn refresh_reports_progress_lines_and_the_archive_to_commit() { - let server = MockServer::start().await; - let patched = real_gem(PATCHED_LIB); - mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_patched_gem(&server, patched).await; - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - std::fs::create_dir_all(&proj).unwrap(); - write_manifest_pair(&proj); - install_real_gem(&project_home(&proj), UPSTREAM_LIB); - let leaf = format!("{DEP}-{DEP_VERSION}"); - let committed = proj - .join("vendor") - .join("cache") - .join(format!("{leaf}.gem")); - std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); - std::fs::write(&committed, real_gem(UPSTREAM_LIB)).unwrap(); +/// The snapshot the registry URL names once the patched build of +/// [`PLATFORM`] was withdrawn. +const LATER_SNAPSHOT: u32 = 5; + +/// A machine of the platform [`PLATFORM`] that holds a patched build which +/// was withdrawn since. The lock was moved while both locked platforms had +/// a patched build, and the hosted scan put this machine's patched build +/// in place: the installed copy, the archive RubyGems keeps beside it and +/// the committed `bundle cache` archive are that build. After the +/// withdrawal the reference lists upstream's own gem for this platform (no +/// patch), under a later snapshot, beside the other platform's patched +/// build. +struct WithdrawnBuild { + _tmp: tempfile::TempDir, + proj: PathBuf, + home: PathBuf, + gem_dir: PathBuf, + home_archive: PathBuf, + committed: PathBuf, + /// Upstream's gem for this platform, and the build that was withdrawn. + upstream: Vec, + withdrawn: Vec, + /// The sha256 of the other platform's patched build. + other_patched: String, + /// The path the registry serves this platform's gem at after the + /// withdrawal. + file_route: String, +} - let uri = server.uri(); - let (code, stdout, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &[]), &[]); - assert_eq!(code, 0, "{stderr}"); - assert!( - stderr.contains(&format!( - "Replaced the installed copy of 1 gem with the patched build: {DEP} {DEP_VERSION}." - )) && stderr.contains(&format!( - "Replaced 1 archive in Bundler's cache dir with the patched gem: {DEP} {DEP_VERSION}." - )), - "{stderr}" - ); - assert!(!stderr.contains("still unpatched"), "{stderr}"); - assert!( - stdout.contains(&format!("vendor/cache/{leaf}.gem")), - "the replaced archive is a file to commit:\n{stdout}" - ); +impl WithdrawnBuild { + /// Stage the machine against `server`, which answers as the patch + /// service does after the withdrawal, except for this platform's gem + /// file: each case serves that its own way. + async fn stage(server: &MockServer) -> WithdrawnBuild { + let upstream = real_gem_for(UPSTREAM_LIB, PLATFORM); + let other_upstream = real_gem_for(UPSTREAM_LIB, OTHER_PLATFORM); + let withdrawn = real_gem_for(PATCHED_LIB, PLATFORM); + let other_patched = sha256_of(&real_gem_for(PATCHED_LIB, OTHER_PLATFORM)); + let ruby_sha = sha256_of(&real_gem(PATCHED_LIB)); + let leaf = format!("{DEP}-{DEP_VERSION}-{PLATFORM}"); + + // While both platforms had a patched build. + mount_api_with( + server, + None, + &ruby_sha, + &[ + (PLATFORM, sha256_of(&withdrawn), Some(ARM_UUID)), + (OTHER_PLATFORM, other_patched.clone(), Some(LINUX_UUID)), + ], + ) + .await; + Mock::given(method("GET")) + .and(path(format!( + "{}/gems/{leaf}.gem", + snapshot_registry_path() + ))) + .respond_with( + ResponseTemplate::new(200) + .set_body_raw(withdrawn.clone(), "application/octet-stream"), + ) + .mount(server) + .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(&sha256_of(&upstream), &sha256_of(&other_upstream)), + ) + .unwrap(); + let home = project_home(&proj); + let gem_dir = install_real_gem_for(&home, UPSTREAM_LIB, PLATFORM); + let home_archive = home.join("cache").join(format!("{leaf}.gem")); + let committed = proj + .join("vendor") + .join("cache") + .join(format!("{leaf}.gem")); + std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); + std::fs::write(&committed, &upstream).unwrap(); + let uri = server.uri(); + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "premise: the first scan\n{stdout}\n{stderr}"); + assert_eq!( + installed_lib(&gem_dir), + PATCHED_LIB, + "premise: this machine holds the patched build" + ); + for archive in [&home_archive, &committed] { + assert_eq!(std::fs::read(archive).unwrap(), withdrawn, "premise"); + } + + // The patched build of this platform is withdrawn. + server.reset().await; + mount_patch_api_with( + server, + UUID, + PATCHED_LIB, + None, + &ruby_sha, + &[ + (PLATFORM, sha256_of(&upstream), None), + (OTHER_PLATFORM, other_patched.clone(), Some(LINUX_UUID)), + ], + LATER_SNAPSHOT, + ) + .await; + let file_route = + format!("/patch-registry/gem/{TOKEN}/{UUID}/s/{LATER_SNAPSHOT}/gems/{leaf}.gem"); + WithdrawnBuild { + _tmp: tmp, + proj, + home, + gem_dir, + home_archive, + committed, + upstream, + withdrawn, + other_patched, + file_route, + } + } + + /// The registry hands this platform's gem on as `body`. + async fn relay(&self, server: &MockServer, body: &[u8]) { + Mock::given(method("GET")) + .and(path(self.file_route.clone())) + .respond_with( + ResponseTemplate::new(200).set_body_raw(body.to_vec(), "application/octet-stream"), + ) + .mount(server) + .await; + } + + /// `socket-patch scan --mode hosted` with `extra`: exit code, stdout + /// and stderr. + fn scan(&self, server: &MockServer, extra: &[&str]) -> (i32, String, String) { + let uri = server.uri(); + common::run_with_env(&self.proj, &scan_args(&self.proj, &uri, extra), &[]) + } + + /// A `--json` scan with `extra`, which must exit 0: its envelope. + fn scan_json(&self, server: &MockServer, extra: &[&str]) -> serde_json::Value { + let mut args = vec!["--json"]; + args.extend_from_slice(extra); + let (code, stdout, stderr) = self.scan(server, &args); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + env + } + + /// The lock follows the reference: the registry at the later snapshot, + /// upstream's sha256 for this platform, the other platform's patched + /// build as it was. + fn assert_lock_is_back_on_upstreams_gem(&self, server: &MockServer) { + let lock = std::fs::read_to_string(self.proj.join("Gemfile.lock")).unwrap(); + assert!( + lock.contains(&format!( + " remote: {}/patch-registry/gem/{TOKEN}/{UUID}/s/{LATER_SNAPSHOT}/\n", + server.uri() + )) && lock.contains(&format!( + "CHECKSUMS\n {DEP} ({DEP_VERSION}-{PLATFORM}) sha256={}\n {DEP} \ + ({DEP_VERSION}-{OTHER_PLATFORM}) sha256={}\n", + sha256_of(&self.upstream), + self.other_patched + )), + "{lock}" + ); + } + + /// The copy, the archive beside it and the committed archive are all + /// `gem`, whose `lib` Ruby loads. + fn assert_holds(&self, gem: &[u8], lib: &str) { + assert_eq!(installed_lib(&self.gem_dir), lib); + assert_eq!(std::fs::read(&self.home_archive).unwrap(), gem); + assert_eq!(std::fs::read(&self.committed).unwrap(), gem); + assert!( + !self.home.join(".socket-patch-refresh").exists(), + "no stage left" + ); + } + + /// What a VEX document says of the gem whatever this machine holds: + /// the other platform's build is attested under its own patch, and + /// this platform's build is affected. + fn assert_vex(&self, doc: &serde_json::Value) { + let text = |value: &serde_json::Value| value.as_str().unwrap_or_default().to_string(); + let said: Vec<(String, String, String)> = doc["statements"] + .as_array() + .expect("statements") + .iter() + .map(|st| { + let packages = st["products"][0]["subcomponents"].as_array(); + assert_eq!(packages.map(Vec::len), Some(1), "{st}"); + ( + text(&st["status"]), + text(&st["products"][0]["subcomponents"][0]["@id"]), + text(&st["impact_statement"]), + ) + }) + .collect(); + assert_eq!( + said, + [ + ( + "not_affected".to_string(), + format!("{PURL}?platform={OTHER_PLATFORM}"), + format!("Patched via Socket patch {LINUX_UUID} (redirected)"), + ), + ( + "affected".to_string(), + format!("{PURL}?platform={PLATFORM}"), + String::new(), + ), + ], + "{doc}" + ); + assert!( + !doc.to_string().contains(ARM_UUID), + "the withdrawn build's patch is named nowhere: {doc}" + ); + } + + /// A later `socket-patch vex` over the project: its outcome. + fn later_vex(&self, server: &MockServer) -> vex_e2e_common::VexOutcome { + let later = vex_e2e_common::VexRun { + api_url: Some(server.uri()), + api_token: Some("fake".into()), + org: Some(ORG.into()), + patch_server_url: Some(server.uri()), + product: Some("pkg:gem/app@1.0.0".into()), + ..vex_e2e_common::VexRun::default() + }; + vex_e2e_common::run_vex(&vex_e2e_common::binary(), &self.proj, &later) + } } -/// `--dry-run` writes nothing and says what a wet run would refresh. +/// The paths of the gem files and patch records `server` was asked for +/// after its first `skip` requests. +async fn gems_and_views_since(server: &MockServer, skip: usize) -> Vec { + let requests = server.received_requests().await.unwrap_or_default(); + let routes = requests.iter().skip(skip).map(|r| r.url.path().to_string()); + routes + .filter(|route| route.contains("/gems/") || route.contains("/patches/view/")) + .collect() +} + +/// A patched build that was withdrawn must not stay installed. The next +/// scan puts upstream's sha256 back into the lock, and the guard judges +/// this machine's copy by the archive it was installed from: it is not +/// upstream's gem, so it is replaced, with the committed archive, by the +/// file the patch registry serves for the platform, verified against the +/// sha256 the reference lists. Whether the registry relays that file +/// (200) or redirects to the upstream registry (302), in which case the +/// other host learns nothing of the grant. One download, no patch record. +/// The run's VEX and a later one say `affected` of this platform's build +/// and still attest the other; a further scan changes nothing. #[tokio::test(flavor = "multi_thread")] -async fn refresh_dry_run_only_says_what_it_would_replace() { +async fn a_withdrawn_build_is_replaced_with_upstreams_gem_through_the_registry() { + for redirects in [false, true] { + let server = MockServer::start().await; + let elsewhere = MockServer::start().await; + let w = WithdrawnBuild::stage(&server).await; + let leaf = format!("{DEP}-{DEP_VERSION}-{PLATFORM}"); + if redirects { + let location = format!("{}/gems/{leaf}.gem", elsewhere.uri()); + Mock::given(method("GET")) + .and(path(w.file_route.clone())) + .respond_with( + ResponseTemplate::new(302) + .insert_header("Location", location.as_str()) + .insert_header("Cache-Control", "no-store"), + ) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(format!("/gems/{leaf}.gem"))) + .respond_with( + ResponseTemplate::new(200) + .set_body_raw(w.upstream.clone(), "application/octet-stream"), + ) + .mount(&elsewhere) + .await; + } else { + w.relay(&server, &w.upstream).await; + } + + let env = w.scan_json(&server, &[]); + assert_eq!( + hosted_pins(&env), + [( + format!("{PURL}?platform={OTHER_PLATFORM}"), + LINUX_UUID.to_string() + )], + "redirects={redirects}: {env}" + ); + w.assert_lock_is_back_on_upstreams_gem(&server); + assert!(stale_warnings(&env).is_empty(), "nothing is left: {env}"); + let mut notes = warnings_with_code(&env, "redirect_gem_install_refreshed"); + notes.sort(); + assert_eq!( + notes, + [ + format!( + "{PURL}: replaced the withdrawn archive at {} with the upstream gem", + w.committed.display() + ), + format!( + "{PURL}: replaced the withdrawn install at {} with the upstream gem", + w.gem_dir.display() + ), + ], + "redirects={redirects}: {env}" + ); + w.assert_holds(&w.upstream, UPSTREAM_LIB); + assert_eq!( + gems_and_views_since(&server, 0).await, + [w.file_route.clone()], + "redirects={redirects}: one download for both, and no patch record" + ); + let handed_on = elsewhere.received_requests().await.unwrap_or_default(); + assert_eq!(handed_on.len(), usize::from(redirects)); + for request in &handed_on { + let sent = format!("{:?}", request.headers); + assert!( + request.headers.get("referer").is_none() && !sent.contains(TOKEN), + "the other host learns nothing of the grant: {sent}" + ); + } + + // A further scan changes nothing and downloads nothing. + let lock = std::fs::read(w.proj.join("Gemfile.lock")).unwrap(); + let before = server.received_requests().await.unwrap_or_default().len(); + let vex_path = w.proj.join("run.vex.json"); + let with_vex = [ + "--vex", + vex_path.to_str().unwrap(), + "--vex-product", + "pkg:gem/app@1.0.0", + ]; + let env = w.scan_json(&server, &with_vex); + assert!( + stale_warnings(&env).is_empty() + && warnings_with_code(&env, "redirect_gem_install_refreshed").is_empty(), + "redirects={redirects}: {env}" + ); + assert_eq!(std::fs::read(w.proj.join("Gemfile.lock")).unwrap(), lock); + w.assert_holds(&w.upstream, UPSTREAM_LIB); + let asked = gems_and_views_since(&server, before).await; + assert!( + asked.iter().all(|route| !route.contains("/gems/")), + "redirects={redirects}: {asked:?}" + ); + + // VEX, from that run and from a later `vex`. + assert_eq!(env["vex"]["affected"], 1, "{env}"); + w.assert_vex(&vex_e2e_common::read_doc(&vex_path).expect("the run's document")); + let out = w.later_vex(&server); + assert_eq!(out.code, Some(0), "redirects={redirects}: {out}"); + w.assert_vex(out.doc()); + assert_eq!(out.envelope["status"], "success", "{out}"); + } +} + +/// For a person, the run that replaces the copy of a withdrawn build says +/// so in one line per kind, each naming the upstream gem and why, never a +/// patched one, and has nothing left to reinstall. +#[tokio::test(flavor = "multi_thread")] +async fn a_withdrawn_build_refresh_says_what_took_its_place() { let server = MockServer::start().await; - let patched = real_gem(PATCHED_LIB); - mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_patched_gem(&server, patched).await; - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - std::fs::create_dir_all(&proj).unwrap(); - write_manifest_pair(&proj); - let home = project_home(&proj); - let gem_dir = install_real_gem(&home, UPSTREAM_LIB); - let upstream = real_gem(UPSTREAM_LIB); - let gemfile = std::fs::read(proj.join("Gemfile")).unwrap(); + let w = WithdrawnBuild::stage(&server).await; + w.relay(&server, &w.upstream).await; - let uri = server.uri(); - let (code, stdout, stderr) = common::run_with_env( - &proj, - &scan_args(&proj, &uri, &["--json", "--dry-run"]), - &[], - ); - let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); - let would = warnings_with_code(&env, "redirect_gem_install_would_refresh"); - assert_eq!(would.len(), 1, "{env}"); + let (code, stdout, stderr) = w.scan(&server, &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + for line in [ + format!( + "Replaced the installed copy of 1 gem with the upstream build (its patched build \ + was withdrawn): {DEP} {DEP_VERSION}.\n" + ), + format!( + "Replaced 1 archive in Bundler's cache dir with the upstream gem (its patched build \ + was withdrawn): {DEP} {DEP_VERSION}.\n" + ), + ] { + assert!(stderr.contains(&line), "missing {line:?}:\n{stderr}"); + } assert!( - would[0].contains(&gem_dir.display().to_string()), - "{would:?}" + !stderr.contains("still holds") && !stderr.contains("patched build:"), + "nothing is left to warn about, and nothing is called patched:\n{stderr}" ); - assert!(stale_warnings(&env).is_empty(), "{env}"); - - let (code, _, stderr) = - common::run_with_env(&proj, &scan_args(&proj, &uri, &["--dry-run"]), &[]); - assert_eq!(code, 0, "{stderr}"); assert!( - stderr.contains(&format!( - "Would replace the installed copy of 1 gem with the patched build: {DEP} {DEP_VERSION}." - )), - "{stderr}" - ); - - assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB); - assert_eq!( - std::fs::read(home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem"))).unwrap(), - upstream + stdout.contains( + " 2. Run `socket-patch vex` to verify the installed patches (the installed gems \ + already hold the builds the lockfile pins, so there is nothing to reinstall).\n" + ), + "{stdout}" ); - assert_eq!(std::fs::read(proj.join("Gemfile")).unwrap(), gemfile); assert!( - !server - .received_requests() - .await - .unwrap_or_default() - .iter() - .any(|r| r.url.path().ends_with(".gem")), - "a dry run downloads no archive" + stdout.contains(&format!("vendor/cache/{DEP}-{DEP_VERSION}-{PLATFORM}.gem")), + "the replaced archive is a file to commit:\n{stdout}" ); + w.assert_holds(&w.upstream, UPSTREAM_LIB); } -/// The archive the server sends is not the one the grant pins: nothing of -/// it is used, the install stays as it was, the warning says why, and the -/// run still exits 0. `--no-gem-install-refresh` does not even ask. +/// The withdrawn build is one of an earlier patch of the gem, and the +/// patch on offer is a newer one with no patched build for this machine's +/// platform. The earlier patch's registry, under the snapshot the lock +/// names, no longer lists the build and refuses its file, so the lock is +/// not held there: the scan asks that registry once, moves the pair to +/// the newer patch with upstream's sha256 for this platform, says that +/// the build is back on upstream's gem, and the guard replaces the copy +/// and the committed archive with the file the newer patch's registry +/// serves. One download, no patch record; a further scan changes nothing. #[tokio::test(flavor = "multi_thread")] -async fn refresh_uses_no_byte_of_an_unverified_archive() { +async fn a_withdrawn_build_of_an_earlier_patch_is_replaced_through_the_newer_patchs_registry() { let server = MockServer::start().await; - let patched = real_gem(PATCHED_LIB); - mount_api_for(&server, None, &sha256_of(&patched)).await; - // Same gem, other bytes. - serve_patched_gem( - &server, - real_gem("module StaleProbeGem\n EVIL = true\nend\n"), - ) - .await; - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - std::fs::create_dir_all(&proj).unwrap(); - write_manifest_pair(&proj); - let home = project_home(&proj); - let gem_dir = install_real_gem(&home, UPSTREAM_LIB); - let cache = home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem")); - - let uri = server.uri(); - let (code, stdout, stderr) = - common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); - let env = common::parse_json_envelope(&stdout); - assert_eq!( - code, 0, - "a failed refresh never fails the scan: {env}\n{stderr}" - ); - let details = stale_warnings(&env); - assert_eq!(details.len(), 1, "{env}"); + let w = WithdrawnBuild::stage(&server).await; + let leaf = format!("{DEP}-{DEP_VERSION}-{PLATFORM}"); + let api = server.uri(); + let lock_before = std::fs::read_to_string(w.proj.join("Gemfile.lock")).unwrap(); assert!( - details[0].contains("does not have the pinned sha256"), - "{}", - details[0] + lock_before.contains(&format!(" remote: {api}{}/\n", snapshot_registry_path())), + "premise: the lock is on the earlier patch at its first snapshot:\n{lock_before}" ); - assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB); - assert_eq!(std::fs::read(&cache).unwrap(), real_gem(UPSTREAM_LIB)); - assert!(!home.join(".socket-patch-refresh").exists()); - let before = server.received_requests().await.unwrap_or_default().len(); - let (code, stdout, _) = common::run_with_env( - &proj, - &scan_args(&proj, &uri, &["--json", "--no-gem-install-refresh"]), - &[], + // The service offers the newer patch, with a patched build for the + // other platform alone. The earlier patch is still granted: only its + // build for this platform is gone. + server.reset().await; + let ruby_sha = sha256_of(&real_gem(NEWER_PATCHED_LIB)); + let newer_other = sha256_of(&real_gem_for(NEWER_PATCHED_LIB, OTHER_PLATFORM)); + let newer_other_uuid = "a1b2c3d4-0000-4000-8000-00000000000c"; + let offered = [ + (PLATFORM, sha256_of(&w.upstream), None), + (OTHER_PLATFORM, newer_other.clone(), Some(newer_other_uuid)), + ]; + let earlier_now = [ + (PLATFORM, sha256_of(&w.upstream), None), + (OTHER_PLATFORM, w.other_patched.clone(), Some(LINUX_UUID)), + ]; + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "results": { + NEWER_UUID: granted_reference(&api, NEWER_UUID, &ruby_sha, &offered, LATER_SNAPSHOT), + UUID: granted_reference( + &api, + UUID, + &sha256_of(&real_gem(PATCHED_LIB)), + &earlier_now, + LATER_SNAPSHOT, + ), + } + }))) + .with_priority(1) + .mount(&server) + .await; + mount_patch_api_with( + &server, + NEWER_UUID, + NEWER_PATCHED_LIB, + None, + &ruby_sha, + &offered, + LATER_SNAPSHOT, + ) + .await; + // The earlier patch's registry as the lock names it: the build of + // this platform is not listed, and its file is not served. + let earlier_index = format!("{}/info/{DEP}", snapshot_registry_path()); + Mock::given(method("GET")) + .and(path(earlier_index.clone())) + .respond_with(ResponseTemplate::new(200).set_body_string(format!( + "---\n{DEP_VERSION} |checksum:{}\n{DEP_VERSION}-{OTHER_PLATFORM} |checksum:{}\n", + sha256_of(&real_gem(PATCHED_LIB)), + w.other_patched + ))) + .mount(&server) + .await; + // The newer patch's registry relays upstream's gem for this platform. + let newer_registry = format!("/patch-registry/gem/{TOKEN}/{NEWER_UUID}/s/{LATER_SNAPSHOT}"); + let file_route = format!("{newer_registry}/gems/{leaf}.gem"); + Mock::given(method("GET")) + .and(path(file_route.clone())) + .respond_with( + ResponseTemplate::new(200).set_body_raw(w.upstream.clone(), "application/octet-stream"), + ) + .mount(&server) + .await; + + let known = ["--patch-server-url", api.as_str()]; + let env = w.scan_json(&server, &known); + let lock = std::fs::read_to_string(w.proj.join("Gemfile.lock")).unwrap(); + assert!( + lock.contains(&format!(" remote: {api}{newer_registry}/\n")) + && !lock.contains(UUID) + && lock.contains(&format!( + "CHECKSUMS\n {DEP} ({DEP_VERSION}-{PLATFORM}) sha256={}\n {DEP} \ + ({DEP_VERSION}-{OTHER_PLATFORM}) sha256={newer_other}\n", + sha256_of(&w.upstream), + )), + "the lock is on the newer patch, upstream's sha256 back for this platform:\n{lock}\n{env}" ); - let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{env}"); - let details = stale_warnings(&env); + assert_eq!( + hosted_pins(&env), + [( + format!("{PURL}?platform={OTHER_PLATFORM}"), + newer_other_uuid.to_string() + )], + "{env}" + ); + let back: Vec<&serde_json::Value> = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|event| event["errorCode"] == "gem_upstream_build_kept") + .collect(); + assert_eq!( + back, + [&serde_json::json!({ + "action": "skipped", + "purl": format!("{PURL}?platform={PLATFORM}"), + "errorCode": "gem_upstream_build_kept", + "reason": format!( + "the patch registry serves upstream's own gem for {PLATFORM}: its patched build \ + was withdrawn" + ), + "details": { + "gemFix": NEWER_UUID, "platform": PLATFORM, "withdrawn": true, "mode": "hosted", + }, + })], + "{env}" + ); + assert!(stale_warnings(&env).is_empty(), "nothing is left: {env}"); + let mut notes = warnings_with_code(&env, "redirect_gem_install_refreshed"); + notes.sort(); + assert_eq!( + notes, + [ + format!( + "{PURL}: replaced the withdrawn archive at {} with the upstream gem", + w.committed.display() + ), + format!( + "{PURL}: replaced the withdrawn install at {} with the upstream gem", + w.gem_dir.display() + ), + ], + "{env}" + ); + w.assert_holds(&w.upstream, UPSTREAM_LIB); + let asked = server.received_requests().await.unwrap_or_default(); + let asked: Vec<&str> = asked + .iter() + .map(|request| request.url.path()) + .filter(|route| route.starts_with("/patch-registry/") || route.contains("/patches/view/")) + .collect(); + assert_eq!( + asked, + [earlier_index.as_str(), file_route.as_str()], + "the registry the lock was on is asked once, upstream's gem is downloaded once from the \ + newer patch's registry, and no patch record is fetched" + ); + + // A further scan changes nothing and downloads nothing. + let before = server.received_requests().await.unwrap_or_default().len(); + let env = w.scan_json(&server, &known); assert!( - details.len() == 1 && details[0].contains("`--no-gem-install-refresh` is set"), + stale_warnings(&env).is_empty() + && warnings_with_code(&env, "redirect_gem_install_refreshed").is_empty(), "{env}" ); - let asked_for_gem = server.received_requests().await.unwrap_or_default()[before..] + assert_eq!( + std::fs::read_to_string(w.proj.join("Gemfile.lock")).unwrap(), + lock + ); + w.assert_holds(&w.upstream, UPSTREAM_LIB); + let asked = server.received_requests().await.unwrap_or_default(); + let asked: Vec<&str> = asked .iter() - .any(|r| r.url.path().ends_with(".gem")); - assert!(!asked_for_gem, "an opted-out run downloads no archive"); + .skip(before) + .map(|request| request.url.path()) + .filter(|route| route.starts_with("/patch-registry/")) + .collect(); + assert_eq!(asked, Vec::<&str>::new(), "no registry request"); } -/// A gem home outside the project is left exactly as it was, under ONE -/// human warning that names the gem, the home, and the remedy as a -/// command; `--gem-refresh-shared` refreshes it like a project-local one. -#[cfg(unix)] +/// The lock stays on the patch it is on: the patch on offer serves +/// upstream's gem for the other platform, which the lock's patch still +/// serves patched. That patch withdrew this machine's build, so its +/// registry no longer lists it under the snapshot the lock names. The +/// scan asks that registry once, brings the pair to the same patch's +/// current snapshot with upstream's sha256 for this platform (the other +/// platform's patched sha256 as it was), skips the patch on offer quietly, +/// and the guard replaces the copy and the committed archive with the file +/// that patch's registry serves under its current snapshot. One download, +/// no patch record; a further scan changes nothing and downloads nothing. #[tokio::test(flavor = "multi_thread")] -async fn refresh_leaves_a_shared_gem_home_alone_unless_asked() { +async fn a_withdrawn_build_of_the_patch_a_lock_stays_on_is_replaced_through_its_current_registry() { let server = MockServer::start().await; - let patched = real_gem(PATCHED_LIB); - mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_patched_gem(&server, patched.clone()).await; - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - std::fs::create_dir_all(&proj).unwrap(); - write_manifest_pair(&proj); - let home = tmp.path().join("system-home"); - let bin_dir = tmp.path().join("fake-bin"); - stage_system_home_copy(&home, &bin_dir); - let gem_dir = install_real_gem(&home, UPSTREAM_LIB); - let cache = home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem")); - let path_env = [("PATH", bin_dir.to_str().unwrap())]; + let w = WithdrawnBuild::stage(&server).await; + let api = server.uri(); + let lock_before = std::fs::read_to_string(w.proj.join("Gemfile.lock")).unwrap(); + assert!( + lock_before.contains(&format!(" remote: {api}{}/\n", snapshot_registry_path())), + "premise: the lock is on the patch at its first snapshot:\n{lock_before}" + ); - let uri = server.uri(); - let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &[]), &path_env); - assert_eq!(code, 0, "{stderr}"); + // The service offers a newer patch with no patched build for either + // platform, and answers each reference request with the patches it was + // asked for: the newer one, and the lock's own as it stands. + server.reset().await; + let ruby_sha = sha256_of(&real_gem(PATCHED_LIB)); + let newer_ruby_sha = sha256_of(&real_gem(NEWER_PATCHED_LIB)); + let other_upstream = sha256_of(&real_gem_for(UPSTREAM_LIB, OTHER_PLATFORM)); + let offered = [ + (PLATFORM, sha256_of(&w.upstream), None), + (OTHER_PLATFORM, other_upstream, None), + ]; + let own_now = [ + (PLATFORM, sha256_of(&w.upstream), None), + (OTHER_PLATFORM, w.other_patched.clone(), Some(LINUX_UUID)), + ]; + let on_offer = granted_reference(&api, NEWER_UUID, &newer_ruby_sha, &offered, LATER_SNAPSHOT); + let own = granted_reference(&api, UUID, &ruby_sha, &own_now, LATER_SNAPSHOT); + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(move |request: &wiremock::Request| { + let asked: serde_json::Value = + serde_json::from_slice(&request.body).unwrap_or_default(); + let mut results = serde_json::Map::new(); + for uuid in asked["uuids"].as_array().into_iter().flatten() { + match uuid.as_str() { + Some(NEWER_UUID) => results.insert(NEWER_UUID.to_string(), on_offer.clone()), + Some(UUID) => results.insert(UUID.to_string(), own.clone()), + _ => None, + }; + } + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "results": results })) + }) + .with_priority(1) + .mount(&server) + .await; + mount_patch_api_with( + &server, + NEWER_UUID, + NEWER_PATCHED_LIB, + None, + &newer_ruby_sha, + &offered, + LATER_SNAPSHOT, + ) + .await; + // The lock's registry as the lock names it: the build of this platform + // is not listed. Under its current snapshot it lists upstream's gem + // for it, and relays that file. + let index_before = format!("{}/info/{DEP}", snapshot_registry_path()); + let index_now = format!("/patch-registry/gem/{TOKEN}/{UUID}/s/{LATER_SNAPSHOT}/info/{DEP}"); + for (route, listing) in [ + ( + &index_before, + format!( + "---\n{DEP_VERSION} |checksum:{ruby_sha}\n{DEP_VERSION}-{OTHER_PLATFORM} \ + |checksum:{}\n", + w.other_patched + ), + ), + ( + &index_now, + format!( + "---\n{DEP_VERSION} |checksum:{ruby_sha}\n{DEP_VERSION}-{PLATFORM} \ + |checksum:{}\n{DEP_VERSION}-{OTHER_PLATFORM} |checksum:{}\n", + sha256_of(&w.upstream), + w.other_patched + ), + ), + ] { + Mock::given(method("GET")) + .and(path(route.clone())) + .respond_with(ResponseTemplate::new(200).set_body_string(listing)) + .mount(&server) + .await; + } + w.relay(&server, &w.upstream).await; + + let known = ["--patch-server-url", api.as_str()]; + let env = w.scan_json(&server, &known); + w.assert_lock_is_back_on_upstreams_gem(&server); + assert!( + !std::fs::read_to_string(w.proj.join("Gemfile.lock")) + .unwrap() + .contains(NEWER_UUID), + "the lock stays on its patch" + ); + let events: Vec<(String, String, String)> = env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|event| event["details"]["mode"] == "hosted") + .map(|event| { + let text = |key: &str| event[key].as_str().unwrap_or_default().to_string(); + (text("action"), text("purl"), text("errorCode")) + }) + .collect(); assert_eq!( - installed_lib(&gem_dir), - UPSTREAM_LIB, - "the shared home is not touched" + events, + [ + ( + "skipped".to_string(), + PURL.to_string(), + "redirect_gem_newer_fix_waits".to_string() + ), + ( + "skipped".to_string(), + format!("{PURL}?platform={PLATFORM}"), + "gem_upstream_build_kept".to_string() + ), + ( + "applied".to_string(), + format!("{PURL}?platform={OTHER_PLATFORM}"), + String::new() + ), + ], + "{env}" ); - assert_eq!(std::fs::read(&cache).unwrap(), real_gem(UPSTREAM_LIB)); assert_eq!( - stderr.matches("still unpatched on disk").count(), - 1, - "one stale-install warning:\n{stderr}" + hosted_pins(&env), + [( + format!("{PURL}?platform={OTHER_PLATFORM}"), + LINUX_UUID.to_string() + )], + "{env}" + ); + assert!(stale_warnings(&env).is_empty(), "nothing is left: {env}"); + let mut notes = warnings_with_code(&env, "redirect_gem_install_refreshed"); + notes.sort(); + assert_eq!( + notes, + [ + format!( + "{PURL}: replaced the withdrawn archive at {} with the upstream gem", + w.committed.display() + ), + format!( + "{PURL}: replaced the withdrawn install at {} with the upstream gem", + w.gem_dir.display() + ), + ], + "{env}" + ); + w.assert_holds(&w.upstream, UPSTREAM_LIB); + let asked = server.received_requests().await.unwrap_or_default(); + let routes: Vec<&str> = asked + .iter() + .map(|request| request.url.path()) + .filter(|route| route.starts_with("/patch-registry/") || route.contains("/patches/view/")) + .collect(); + assert_eq!( + routes, + [index_before.as_str(), w.file_route.as_str()], + "the registry the lock is on is asked once, upstream's gem is downloaded once under \ + its current snapshot, and no patch record is fetched" + ); + let references: Vec = asked + .iter() + .filter(|request| request.url.path().ends_with("/patches/package")) + .map(|request| { + serde_json::from_slice::(&request.body).unwrap_or_default()["uuids"] + .clone() + }) + .collect(); + assert_eq!( + references, + [serde_json::json!([UUID]), serde_json::json!([NEWER_UUID])], + "the scan's check of the pin and the patch on offer: no further reference request" ); - for needle in [ - "Warning: 1 gem is still unpatched on disk after the switch to hosted patches.", - &format!( - " - Shared gem home {} (left alone, other projects may load it): {DEP} {DEP_VERSION}.", - home.display() - ), - "run `bundle config set --local path vendor/bundle && bundle install`", - "`--gem-refresh-shared`", - ] { - assert!(stderr.contains(needle), "missing {needle:?}:\n{stderr}"); - } - let (code, stdout, stderr) = common::run_with_env( - &proj, - &scan_args(&proj, &uri, &["--json", "--gem-refresh-shared"]), - &path_env, + // A further scan changes nothing and downloads nothing. + let lock = std::fs::read_to_string(w.proj.join("Gemfile.lock")).unwrap(); + let before = server.received_requests().await.unwrap_or_default().len(); + let env = w.scan_json(&server, &known); + assert!( + stale_warnings(&env).is_empty() + && warnings_with_code(&env, "redirect_gem_install_refreshed").is_empty(), + "{env}" ); - let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{env}\n{stderr}"); - assert!(stale_warnings(&env).is_empty(), "{env}"); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); - assert_eq!(std::fs::read(&cache).unwrap(), patched); + assert_eq!( + std::fs::read_to_string(w.proj.join("Gemfile.lock")).unwrap(), + lock + ); + w.assert_holds(&w.upstream, UPSTREAM_LIB); + let asked = server.received_requests().await.unwrap_or_default(); + let routes: Vec<&str> = asked + .iter() + .skip(before) + .map(|request| request.url.path()) + .filter(|route| route.starts_with("/patch-registry/")) + .collect(); + assert_eq!(routes, [index_now.as_str()], "one listing, no download"); } -/// rubygems.org's stand-in under `/upstream` (`SOCKET_RUBYGEMS_URL`): the -/// compact index entry naming the upstream archive's sha256, and its -/// download. -async fn serve_upstream_gem(server: &MockServer, upstream: &[u8]) { - serve_upstream_gem_indexed_as(server, upstream, &sha256_of(upstream)).await; -} +/// The registry relays bytes that are not the gem the reference lists for +/// the platform: no byte of them is used. The withdrawn build stays, the +/// lock still goes back to upstream's sha256, and the run says, as a +/// warning and never as a failure, that a withdrawn build is still +/// installed and how to remove it. That copy keeps nothing of the gem out +/// of the VEX: the other platform's build is attested, this one affected. +#[tokio::test(flavor = "multi_thread")] +async fn a_withdrawn_build_is_not_replaced_with_a_gem_the_reference_does_not_list() { + let server = MockServer::start().await; + let w = WithdrawnBuild::stage(&server).await; + // The same gem with other bytes. + w.relay( + &server, + &real_gem_for("module StaleProbeGem\n EVIL = true\nend\n", PLATFORM), + ) + .await; + let spec = w + .home + .join("specifications") + .join(format!("{DEP}-{DEP_VERSION}-{PLATFORM}.gemspec")); + let files = [&spec, &w.home_archive, &w.committed]; + + // For a person: one warning, and what to run. + let (code, stdout, stderr) = w.scan(&server, &[]); + assert_eq!(code, 0, "a failed refresh never fails the scan:\n{stderr}"); + w.assert_lock_is_back_on_upstreams_gem(&server); + w.assert_holds(&w.withdrawn, PATCHED_LIB); + let words: Vec = files.iter().map(|path| shell_word(path)).collect(); + let warning = format!( + "Warning: 1 gem still holds a patched build on disk that was withdrawn.\n - Not \ + refreshed (the upstream gem the server sent does not have the pinned sha256): {DEP} \ + {DEP_VERSION}. Re-run `socket-patch scan` to retry, or run `rm -f {} && bundle \ + install`.\n", + words.join(" ") + ); + assert!(stderr.contains(&warning), "missing {warning:?}:\n{stderr}"); + assert_eq!(stderr.matches("still holds").count(), 1, "{stderr}"); + assert!(!stderr.contains("Replaced"), "{stderr}"); + assert!( + stdout.contains( + " 2. Replace the withdrawn gem build with the command in the warning above (a \ + plain `bundle install` keeps the gems it already has), then run `socket-patch vex` \ + to verify the installed patches.\n" + ), + "{stdout}" + ); -/// [`serve_upstream_gem`] with the index's `checksum:` written as -/// `digest`: the gem's sha256 in whichever encoding the server uses. -async fn serve_upstream_gem_indexed_as(server: &MockServer, upstream: &[u8], digest: &str) { - Mock::given(method("GET")) - .and(path(format!("/upstream/info/{DEP}"))) - .respond_with( - ResponseTemplate::new(200) - .set_body_string(format!("---\n{DEP_VERSION} |checksum:{digest}\n")), - ) - .mount(server) - .await; - Mock::given(method("GET")) - .and(path(format!("/upstream/gems/{DEP}-{DEP_VERSION}.gem"))) - .respond_with( - ResponseTemplate::new(200).set_body_raw(upstream.to_vec(), "application/octet-stream"), - ) - .mount(server) - .await; + // The same in `--json`, on every later run, with the run's own VEX. + let vex_path = w.proj.join("run.vex.json"); + let with_vex = [ + "--vex", + vex_path.to_str().unwrap(), + "--vex-product", + "pkg:gem/app@1.0.0", + ]; + let env = w.scan_json(&server, &with_vex); + let listed: Vec = files.iter().map(|p| p.display().to_string()).collect(); + assert_eq!( + stale_warnings(&env), + [format!( + "{PURL} is back on upstream's own gem for {PLATFORM}, whose patched build was \ + withdrawn, but its withdrawn install at {} was not refreshed (the upstream gem the \ + server sent does not have the pinned sha256), and `bundle install` reuses an \ + installed gem instead of fetching the upstream one. Re-run `socket-patch scan` to \ + retry, or remove {} and run `bundle install`", + w.gem_dir.display(), + listed.join(", ") + )], + "{env}" + ); + assert!( + warnings_with_code(&env, "redirect_gem_install_refreshed").is_empty(), + "{env}" + ); + w.assert_holds(&w.withdrawn, PATCHED_LIB); + assert_eq!(env["vex"]["statements"], 2, "{env}"); + assert_eq!(env["vex"]["affected"], 1, "{env}"); + w.assert_vex(&vex_e2e_common::read_doc(&vex_path).expect("the run's document")); + let out = w.later_vex(&server); + assert_eq!(out.code, Some(0), "{out}"); + w.assert_vex(out.doc()); + assert_eq!(out.envelope["status"], "success", "{out}"); } -/// The unwind direction: `rollback` puts the lock back on rubygems.org and -/// the project's installed gem and archives back on the upstream gem, -/// verified against the sha256 the compact index names. +/// The refresh is switched off, or only previewed: nothing is downloaded +/// and nothing replaced. A dry run says what a wet run would replace, and +/// `--no-gem-install-refresh` warns that the withdrawn build is still +/// installed, with the run that replaces it. That run then does. #[tokio::test(flavor = "multi_thread")] -async fn refresh_after_rollback_restores_the_upstream_gem() { +async fn a_withdrawn_build_is_left_with_a_warning_when_the_refresh_is_off() { let server = MockServer::start().await; - let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); - mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_patched_gem(&server, patched.clone()).await; - serve_upstream_gem(&server, &upstream).await; - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - std::fs::create_dir_all(&proj).unwrap(); - write_manifest_pair(&proj); - let home = project_home(&proj); - let gem_dir = install_real_gem(&home, UPSTREAM_LIB); - let leaf = format!("{DEP}-{DEP_VERSION}"); - let cache = home.join("cache").join(format!("{leaf}.gem")); - let committed = proj - .join("vendor") - .join("cache") - .join(format!("{leaf}.gem")); - std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); - std::fs::write(&committed, &upstream).unwrap(); - - let uri = server.uri(); - let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); - assert_eq!(code, 0, "{stderr}"); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "scan refreshed it"); - // The lock as `bundle install` leaves it once the pin is installed. - std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); - - let rubygems = format!("{uri}/upstream"); - let rollback = |extra: &[&'static str]| { - let mut args = vec![ - "rollback", - PURL, - "--cwd", - proj.to_str().unwrap(), - "--api-url", - uri.as_str(), - "--org", - ORG, - "--api-token", - "fake", - "--patch-server-url", - uri.as_str(), - ]; - args.extend_from_slice(extra); - common::run_with_env(&proj, &args, &[("SOCKET_RUBYGEMS_URL", rubygems.as_str())]) - }; + let w = WithdrawnBuild::stage(&server).await; + w.relay(&server, &w.upstream).await; - // A dry run says what it would do and changes nothing. - let (code, stdout, stderr) = rollback(&["--dry-run"]); - assert_eq!(code, 0, "{stdout}\n{stderr}"); - assert!( - stdout.contains(&format!( - "Would replace the installed copy of 1 gem with the upstream build: {DEP} {DEP_VERSION}." - )), - "{stdout}" + let env = w.scan_json(&server, &["--dry-run"]); + let mut would = warnings_with_code(&env, "redirect_gem_install_would_refresh"); + would.sort(); + assert_eq!( + would, + [ + format!( + "{PURL}: would replace the withdrawn archive at {} with the upstream gem", + w.committed.display() + ), + format!( + "{PURL}: would replace the withdrawn install at {} with the upstream gem", + w.gem_dir.display() + ), + ], + "{env}" ); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + assert!(stale_warnings(&env).is_empty(), "{env}"); + w.assert_holds(&w.withdrawn, PATCHED_LIB); - let (code, stdout, stderr) = rollback(&["--json"]); - let env: serde_json::Value = serde_json::from_str(&stdout) - .unwrap_or_else(|e| panic!("not JSON: {e}\n{stdout}\n{stderr}")); - assert_eq!(code, 0, "{env}\n{stderr}"); - let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + let env = w.scan_json(&server, &["--no-gem-install-refresh"]); + w.assert_lock_is_back_on_upstreams_gem(&server); + let stale = stale_warnings(&env); + assert_eq!(stale.len(), 1, "{env}"); assert!( - !lock.contains("/patch-registry/"), - "the lock is back on upstream:\n{lock}" + stale[0].starts_with(&format!( + "{PURL} is back on upstream's own gem for {PLATFORM}, whose patched build was \ + withdrawn, but its withdrawn install at {} was not refreshed \ + (`--no-gem-install-refresh` is set), and `bundle install` reuses an installed gem \ + instead of fetching the upstream one. Re-run without `--no-gem-install-refresh`, \ + or remove ", + w.gem_dir.display() + )) && stale[0].ends_with(" and run `bundle install`"), + "{}", + stale[0] ); - assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB); - assert_eq!(std::fs::read(&cache).unwrap(), upstream); - assert_eq!(std::fs::read(&committed).unwrap(), upstream); + w.assert_holds(&w.withdrawn, PATCHED_LIB); assert_eq!( - warnings_with_code(&env, "upstream_gem_install_refreshed").len(), - 2, - "the install and the committed archive: {env}" + gems_and_views_since(&server, 0).await, + Vec::::new(), + "neither run downloads a gem or fetches a record" ); - assert!( - warnings_with_code(&env, "upstream_gem_stale_cache").is_empty() - && warnings_with_code(&env, "upstream_gem_stale_install").is_empty(), - "nothing is left on the patched build: {env}" + + // The run the warning names. + let env = w.scan_json(&server, &[]); + assert!(stale_warnings(&env).is_empty(), "{env}"); + assert_eq!( + warnings_with_code(&env, "redirect_gem_install_refreshed").len(), + 2, + "{env}" ); + w.assert_holds(&w.upstream, UPSTREAM_LIB); } -/// #2086: `rollback` / `remove` of a hosted gem whose patched copy sits in -/// a shared gem home leave that copy alone and warn about it. The warning -/// names no re-run with `--gem-refresh-shared`: the first run removed the -/// wiring, so a second one has nothing to unwind. It names the -/// project-local path, and the files whose removal makes `bundle install` -/// fetch the upstream gem into the shared home. The generic reinstall note -/// does not claim that the next install replaces the copy. -#[cfg(unix)] +/// 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 patched build. Where the patch registry +/// does not list one locked platform it pins nothing, says which, and +/// leaves both files as they were. #[tokio::test(flavor = "multi_thread")] -async fn hosted_unwind_names_no_rerun_for_a_shared_gem_home() { - const UNWINDS: [&[&str]; 2] = [&["rollback", "--yes"], &["remove", PURL, "--yes"]]; - for (unwind, json) in UNWINDS - .into_iter() - .flat_map(|unwind| [(unwind, false), (unwind, true)]) - { - let case = format!("{unwind:?} json={json}"); +async fn gem_hosted_scan_pins_platform_builds_from_the_lock_alone() { + let ruby_sha = sha256_of(&real_gem(PATCHED_LIB)); + let (arm_sha, linux_sha) = ( + sha256_of(&real_gem_for(PATCHED_LIB, PLATFORM)), + sha256_of(&real_gem_for(PATCHED_LIB, OTHER_PLATFORM)), + ); + for complete in [true, false] { let server = MockServer::start().await; - let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); - mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_patched_gem(&server, patched.clone()).await; - serve_upstream_gem(&server, &upstream).await; + let mut builds = vec![(PLATFORM, arm_sha.clone(), Some(ARM_UUID))]; + if complete { + builds.push((OTHER_PLATFORM, linux_sha.clone(), Some(LINUX_UUID))); + } + 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(); - write_manifest_pair(&proj); - let home = tmp.path().join("system-home"); - let bin_dir = tmp.path().join("fake-bin"); - stage_system_home_copy(&home, &bin_dir); - let gem_dir = install_real_gem(&home, UPSTREAM_LIB); - let leaf = format!("{DEP}-{DEP_VERSION}"); - let cache = home.join("cache").join(format!("{leaf}.gem")); - let spec = home.join("specifications").join(format!("{leaf}.gemspec")); - - // The shared copy becomes the patched build. - let uri = server.uri(); - let rubygems = format!("{uri}/upstream"); - let env = [ - ("PATH", bin_dir.to_str().unwrap()), - ("SOCKET_RUBYGEMS_URL", rubygems.as_str()), - ]; - let (code, _, stderr) = common::run_with_env( - &proj, - &scan_args(&proj, &uri, &["--json", "--gem-refresh-shared"]), - &env, - ); - assert_eq!(code, 0, "{case}: {stderr}"); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{case}: premise"); - std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); - let held_before = snapshot(&home); - - let mut args = unwind.to_vec(); - args.extend([ - "--cwd", - proj.to_str().unwrap(), - "--api-url", - uri.as_str(), - "--org", - ORG, - "--api-token", - "fake", - "--patch-server-url", - uri.as_str(), - ]); - if json { - args.push("--json"); - } - let (code, stdout, stderr) = common::run_with_env(&proj, &args, &env); - assert_eq!(code, 0, "{case}:\n{stdout}\n{stderr}"); - let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); - assert!(!lock.contains("/patch-registry/"), "{case}:\n{lock}"); - assert!( - snapshot(&home) == held_before, - "{case}: the shared gem home is left alone" - ); + 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 remove_files = format!("{} {}", shell_word(&spec), shell_word(&cache)); - let warning = if json { - let env = common::parse_json_envelope(&stdout); - let details = details_with_code(&env, "upstream_gem_stale_install"); - assert_eq!(details.len(), 1, "{case}: {env}"); - // rollback's run-level advisory defers to the gem warning. - if unwind[0] == "rollback" { - let reinstall = details_with_code(&env, "reinstall_required"); - assert_eq!(reinstall.len(), 1, "{case}: {env}"); - assert!( - reinstall[0].contains("`bundle install` keeps an installed gem"), - "{case}: {}", - reinstall[0] - ); - } + 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}"); + 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), 2, "one per locked build: {env}"); + assert!(skipped.is_empty(), "{env}"); assert!( - details[0].contains(&format!( - "remove {}, {} and run `bundle install`", - spec.display(), - cache.display() + after.contains(&format!( + "{}/\n specs:\n {DEP} ({DEP_VERSION}-{PLATFORM})\n {DEP} \ + ({DEP_VERSION}-{OTHER_PLATFORM})\n", + snapshot_registry_path() )), - "{case}: {}", - details[0] + "{after}" + ); + assert!( + after.contains(&format!( + " {DEP} ({DEP_VERSION}-{PLATFORM}) sha256={arm_sha}\n {DEP} \ + ({DEP_VERSION}-{OTHER_PLATFORM}) sha256={linux_sha}\n" + )), + "{after}" + ); + assert!( + stale_warnings(&env).is_empty(), + "nothing is installed: {env}" ); - details[0].clone() } else { + assert_eq!(hosted_pinned(&env), 0, "{env}"); + // A platform the list leaves out: the gem is left as it is, + // and nothing is warned about. + assert!(skipped.is_empty(), "{env}"); + let unlisted: Vec<&str> = env["events"] + .as_array() + .unwrap() + .iter() + .filter(|event| event["errorCode"] == "redirect_gem_platform_unlisted") + .filter_map(|event| event["reason"].as_str()) + .collect(); + let [detail] = unlisted.as_slice() else { + panic!("one quiet skip: {env}"); + }; assert_eq!( - stderr.matches("still holds the patched build").count(), - 1, - "{case}: one warning:\n{stderr}" + *detail, + format!( + "{DEP} {DEP_VERSION}: the patch registry does not list {OTHER_PLATFORM}, so \ + the gem is left as it is" + ) ); - assert!( - stderr.contains(&format!("run `rm -f {remove_files} && bundle install`")), - "{case}: the remedy as a command:\n{stderr}" + assert_eq!(after, lock, "the lock is untouched"); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + gemfile, + "the Gemfile is untouched" ); - if unwind[0] == "rollback" { - assert!( - stdout.contains("1 unwired package keeps its patched bytes") - && stdout.contains("`bundle install` keeps") - && !stdout.contains("package-manager install."), - "{case}: the note defers to the gem warning:\n{stdout}" - ); - } - stderr.clone() - }; - assert!( - warning.contains("bundle config set --local path vendor/bundle && bundle install"), - "{case}: {warning}" - ); - assert!( - !warning.contains("--gem-refresh-shared") && !warning.to_lowercase().contains("re-run"), - "{case}: a second unwind has nothing to unwind: {warning}" - ); - - // Why no re-run is named: the wiring is gone. - let mut again = args.clone(); - again.push("--gem-refresh-shared"); - let (code, stdout, stderr) = common::run_with_env(&proj, &again, &env); - assert_eq!(code, 1, "{case}: premise:\n{stdout}\n{stderr}"); - let nothing = match (json, unwind[0]) { - (true, _) => "\"status\": \"error\"", - (false, "rollback") => "nothing to roll back", - (false, _) => "nothing to remove", - }; - assert!( - format!("{stdout}{stderr}").contains(nothing), - "{case}: premise: a second unwind finds nothing:\n{stdout}\n{stderr}" - ); - assert!(snapshot(&home) == held_before, "{case}"); + } } } -/// A registry that is refused (plain http, and not this machine) is not -/// asked what the upstream gem is. `rollback` still puts the lock back, -/// leaves the installed copy as it is, and says so: the copy is reported as -/// one it could not check, with the reason, not passed over in silence -/// while it still holds the patched build. +/// A lock that names the gem only as platform builds, beside a plain +/// gem, and a patch whose registry does not list 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 +/// the installed platform copy). #[tokio::test(flavor = "multi_thread")] -async fn rollback_reports_the_copy_a_refused_registry_left_unchecked() { - refused_registry_leaves_the_copy_reported(true).await; +async fn refused_platform_gem_is_counted_as_left_to_patch() { + const LEFT: &str = + "\n1 vulnerability left to patch: 1 is in packages this run did not patch.\n"; + let arm_sha = sha256_of(&real_gem_for(PATCHED_LIB, PLATFORM)); + for mode in ["hosted", "vendored"] { + let server = MockServer::start().await; + // The lookup names the advisory the patch fixes, as the service + // does (the totals count advisories), and only for a run that + // asks about the gem. + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [], + "canAccessPaidPatches": false, + }))) + .with_priority(2) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path(format!("/v0/orgs/{ORG}/patches/batch"))) + .and(body_string_contains(DEP)) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "packages": [{ + "purl": PURL, + "patches": [{ + "uuid": UUID, "purl": PURL, "tier": "free", + "cveIds": [], "ghsaIds": [GHSA], "severity": "high", + "title": "gem stale-install fixture" + }] + }], + "canAccessPaidPatches": false, + }))) + .with_priority(1) + .mount(&server) + .await; + mount_api_with( + &server, + None, + &sha256_of(&real_gem(PATCHED_LIB)), + &[(PLATFORM, arm_sha.clone(), Some(ARM_UUID))], + ) + .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}\"\ngem \ + \"plain-probe-gem\", \"1.0.0\"\n" + ); + // The plain gem makes the lock one that lists ruby-platform gems + // too, as every real lock does (nokogiri beside racc). + let lock = platform_lock(&"1".repeat(64), &"2".repeat(64)) + .replace(" specs:\n", " specs:\n plain-probe-gem (1.0.0)\n") + .replace( + "DEPENDENCIES\n", + "DEPENDENCIES\n plain-probe-gem (= 1.0.0)\n", + ); + assert!( + lock.contains(" plain-probe-gem (1.0.0)\n") + && !lock.contains(&format!(" {DEP} ({DEP_VERSION})\n")), + "the lock holds a plain gem, and {DEP} as platform builds only:\n{lock}" + ); + std::fs::write(proj.join("Gemfile"), &gemfile).unwrap(); + std::fs::write(proj.join("Gemfile.lock"), &lock).unwrap(); + if mode == "vendored" { + install_real_gem_for(&project_home(&proj), UPSTREAM_LIB, PLATFORM); + } + + let uri = server.uri(); + let (code, stdout, stderr) = common::run_with_env( + &proj, + &[ + "scan", + "--mode", + mode, + "--yes", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--patch-server-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + ], + &[], + ); + assert_eq!(code, 0, "{mode}\nstdout:\n{stdout}\nstderr:\n{stderr}"); + // The premise: the run left the gem alone for a platform the + // patch registry does not list, which both modes say in the same + // words. + let (refusal, said) = match mode { + "hosted" => ( + format!( + "{DEP} {DEP_VERSION}: the patch registry does not list {OTHER_PLATFORM}, so \ + the gem is left as it is" + ), + &stdout, + ), + _ => ( + format!( + "{DEP}@{DEP_VERSION} is not vendored: the patch registry does not list \ + {OTHER_PLATFORM}. Vendored mode needs a gem, patched or upstream's own, for \ + every locked platform, and a re-run \ + does not change what the registry lists: this is settled once the \ + lockfile no longer names {OTHER_PLATFORM} (`bundle lock --remove-platform \ + {OTHER_PLATFORM}`), or the registry lists a gem for every locked platform." + ), + &stderr, + ), + }; + assert!( + said.contains(&refusal), + "{mode}: the run leaves the gem alone\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + lock, + "{mode}: the lock is untouched" + ); + assert!( + stdout.ends_with(LEFT), + "{mode}: the refused gem is left to patch\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + } } -/// The same with the copy's archive gone from the home's cache (a pruned -/// `cache/`, as slim images have). With nothing to judge the copy by it is -/// still reported, not passed over. +/// Human output of the run that refreshes: one progress line per kind, +/// no warning, and the committed archive in the files to commit. #[tokio::test(flavor = "multi_thread")] -async fn rollback_reports_an_unchecked_copy_whose_cached_archive_is_gone() { - refused_registry_leaves_the_copy_reported(false).await; +async fn refresh_reports_progress_lines_and_the_archive_to_commit() { + let server = MockServer::start().await; + let patched = real_gem(PATCHED_LIB); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + install_real_gem(&project_home(&proj), UPSTREAM_LIB); + let leaf = format!("{DEP}-{DEP_VERSION}"); + let committed = proj + .join("vendor") + .join("cache") + .join(format!("{leaf}.gem")); + std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); + std::fs::write(&committed, real_gem(UPSTREAM_LIB)).unwrap(); + + let uri = server.uri(); + let (code, stdout, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &[]), &[]); + assert_eq!(code, 0, "{stderr}"); + assert!( + stderr.contains(&format!( + "Replaced the installed copy of 1 gem with the patched build: {DEP} {DEP_VERSION}." + )) && stderr.contains(&format!( + "Replaced 1 archive in Bundler's cache dir with the patched gem: {DEP} {DEP_VERSION}." + )), + "{stderr}" + ); + assert!(!stderr.contains("still unpatched"), "{stderr}"); + assert!( + stdout.contains(&format!("vendor/cache/{leaf}.gem")), + "the replaced archive is a file to commit:\n{stdout}" + ); } -async fn refused_registry_leaves_the_copy_reported(cached_archive: bool) { +/// `--dry-run` writes nothing and says what a wet run would refresh. +#[tokio::test(flavor = "multi_thread")] +async fn refresh_dry_run_only_says_what_it_would_replace() { let server = MockServer::start().await; let patched = real_gem(PATCHED_LIB); mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_patched_gem(&server, patched.clone()).await; + serve_patched_gem(&server, patched).await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); std::fs::create_dir_all(&proj).unwrap(); write_manifest_pair(&proj); let home = project_home(&proj); let gem_dir = install_real_gem(&home, UPSTREAM_LIB); - let leaf = format!("{DEP}-{DEP_VERSION}"); - let cache = home.join("cache").join(format!("{leaf}.gem")); + let upstream = real_gem(UPSTREAM_LIB); + let gemfile = std::fs::read(proj.join("Gemfile")).unwrap(); let uri = server.uri(); - let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); - assert_eq!(code, 0, "{stderr}"); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "scan refreshed it"); - std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); - let asked_before = server.received_requests().await.unwrap().len(); - if !cached_archive { - std::fs::remove_file(&cache).unwrap(); - } - - // Refused before any request: nothing is looked up or sent. - const REFUSED: &str = "http://gemstash.example.test:9292"; - let args = [ - "rollback", - PURL, - "--cwd", - proj.to_str().unwrap(), - "--api-url", - uri.as_str(), - "--org", - ORG, - "--api-token", - "fake", - "--patch-server-url", - uri.as_str(), - "--json", - ]; - let (code, stdout, stderr) = - common::run_with_env(&proj, &args, &[("SOCKET_RUBYGEMS_URL", REFUSED)]); - let env: serde_json::Value = serde_json::from_str(&stdout) - .unwrap_or_else(|e| panic!("not JSON: {e}\n{stdout}\n{stderr}")); - assert_eq!(code, 0, "{env}\n{stderr}"); - let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + let (code, stdout, stderr) = common::run_with_env( + &proj, + &scan_args(&proj, &uri, &["--json", "--dry-run"]), + &[], + ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + let would = warnings_with_code(&env, "redirect_gem_install_would_refresh"); + assert_eq!(would.len(), 1, "{env}"); assert!( - !lock.contains("/patch-registry/"), - "the lock is back on upstream:\n{lock}" + would[0].contains(&gem_dir.display().to_string()), + "{would:?}" ); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "left as it is"); - if cached_archive { - assert_eq!(std::fs::read(&cache).unwrap(), patched); - } + assert!(stale_warnings(&env).is_empty(), "{env}"); + + let (code, _, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--dry-run"]), &[]); + assert_eq!(code, 0, "{stderr}"); assert!( - warnings_with_code(&env, "upstream_gem_install_refreshed").is_empty(), - "{env}" + stderr.contains(&format!( + "Would replace the installed copy of 1 gem with the patched build: {DEP} {DEP_VERSION}." + )), + "{stderr}" ); - let unchecked = warnings_with_code(&env, "upstream_gem_stale_install"); - assert_eq!(unchecked.len(), 1, "the copy is reported: {env}"); - for needle in [ - PURL, - "could not be checked against the upstream gem", - "`http://gemstash.example.test:9292` is not an https URL", - "set it to an https URL", - "it still holds the patched build", - "run `bundle install`", - gem_dir.to_str().unwrap(), - ] { - assert!( - unchecked[0].contains(needle), - "missing {needle:?}: {}", - unchecked[0] - ); - } + + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB); assert_eq!( - server.received_requests().await.unwrap().len(), - asked_before, - "the rollback asked a registry" + std::fs::read(home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem"))).unwrap(), + upstream + ); + assert_eq!(std::fs::read(proj.join("Gemfile")).unwrap(), gemfile); + assert!( + !server + .received_requests() + .await + .unwrap_or_default() + .iter() + .any(|r| r.url.path().ends_with(".gem")), + "a dry run downloads no archive" ); } -/// The commands that unwind a hosted gem. -const HOSTED_UNWINDS: [&[&str]; 2] = [&["rollback", "--yes"], &["remove", PURL, "--yes"]]; - -/// A project whose gem a hosted scan pinned, with the lock as `bundle -/// install` leaves it, in a gem home that has no `cache/` dir (Bundler -/// 4.1's `prune` setting, the `rm -rf "${BUNDLE_PATH}"/ruby/*/cache` of the -/// Dockerfile Rails generates, `gem cleanup`). With `refreshed` the scan -/// replaced the installed copy with the patched build; without, it was told -/// not to (`--no-gem-install-refresh`) and the copy is still the upstream -/// one. Returns the installed gem dir and the gem home. -async fn hosted_with_pruned_home_cache( - server: &MockServer, - proj: &Path, - refreshed: bool, -) -> (PathBuf, PathBuf) { - std::fs::create_dir_all(proj).unwrap(); - write_manifest_pair(proj); - let home = project_home(proj); - let gem_dir = install_real_gem(&home, UPSTREAM_LIB); - let uri = server.uri(); - let flags: &[&str] = if refreshed { - &["--json"] - } else { - &["--json", "--no-gem-install-refresh"] - }; - let (code, _, stderr) = common::run_with_env(proj, &scan_args(proj, &uri, flags), &[]); - assert_eq!(code, 0, "{stderr}"); - let expected = if refreshed { PATCHED_LIB } else { UPSTREAM_LIB }; - assert_eq!(installed_lib(&gem_dir), expected, "premise"); - std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); - std::fs::remove_dir_all(home.join("cache")).unwrap(); - (gem_dir, home) -} - -/// Every `detail` (a warning's) or `reason` (an event's) that `--json` -/// output carries under `code`, wherever the command puts it. -fn details_with_code(env: &serde_json::Value, code: &str) -> Vec { - fn walk(value: &serde_json::Value, code: &str, out: &mut Vec) { - match value { - serde_json::Value::Object(map) => { - if map - .get("code") - .or(map.get("errorCode")) - .and_then(|c| c.as_str()) - == Some(code) - { - let detail = map.get("detail").or(map.get("reason")); - out.push( - detail - .and_then(|d| d.as_str()) - .unwrap_or_default() - .to_string(), - ); - } - map.values().for_each(|v| walk(v, code, out)); - } - serde_json::Value::Array(items) => items.iter().for_each(|v| walk(v, code, out)), - _ => {} - } - } - let mut out = Vec::new(); - walk(env, code, &mut out); - out -} - -/// #2092: a gem home with no `cache/` dir has no archive to judge the -/// installed copy by. The hosted unwind judges it by the pin's patch record -/// instead, as the scan does in that home, and puts the upstream gem back: -/// otherwise the app keeps loading the patch under the restored lock, and -/// no later `bundle install` changes that. -#[tokio::test(flavor = "multi_thread")] -async fn hosted_unwind_restores_an_install_whose_home_cache_was_pruned() { - for command in HOSTED_UNWINDS { - let server = MockServer::start().await; - let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); - mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_patched_gem(&server, patched.clone()).await; - serve_upstream_gem(&server, &upstream).await; - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - let (gem_dir, home) = hosted_with_pruned_home_cache(&server, &proj, true).await; - let views_before = view_requests(&server).await; - - let mut args = command.to_vec(); - args.push("--json"); - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); - let env: serde_json::Value = serde_json::from_str(&stdout) - .unwrap_or_else(|e| panic!("{command:?}: not JSON: {e}\n{stdout}\n{stderr}")); - assert_eq!(code, 0, "{command:?}: {env}\n{stderr}"); - let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); - assert!(!lock.contains("/patch-registry/"), "{command:?}:\n{lock}"); - assert_eq!( - installed_lib(&gem_dir), - UPSTREAM_LIB, - "{command:?}: the upstream gem is back: {env}" - ); - assert_eq!( - details_with_code(&env, "upstream_gem_install_refreshed").len(), - 1, - "{command:?}: {env}" - ); - assert!( - details_with_code(&env, "upstream_gem_stale_install").is_empty(), - "{command:?}: nothing is left on the patched build: {env}" - ); - assert!( - !home.join("cache").exists(), - "{command:?}: a pruned cache dir is not created" - ); - assert_eq!( - view_requests(&server).await - views_before, - 1, - "{command:?}: one patch record, for that pin" - ); - } -} - -/// The same in a human run: the refresh is a progress line, and the gem is -/// not counted among the packages that keep their patched bytes. +/// The archive the server sends is not the one the grant pins: nothing of +/// it is used, the install stays as it was, the warning says why, and the +/// run still exits 0. `--no-gem-install-refresh` does not even ask. #[tokio::test(flavor = "multi_thread")] -async fn hosted_unwind_reports_the_pruned_home_refresh_in_a_human_run() { +async fn refresh_uses_no_byte_of_an_unverified_archive() { let server = MockServer::start().await; - let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + let patched = real_gem(PATCHED_LIB); mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_patched_gem(&server, patched.clone()).await; - serve_upstream_gem(&server, &upstream).await; + // Same gem, other bytes. + serve_patched_gem( + &server, + real_gem("module StaleProbeGem\n EVIL = true\nend\n"), + ) + .await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let (gem_dir, _) = hosted_with_pruned_home_cache(&server, &proj, true).await; + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = project_home(&proj); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let cache = home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem")); - // A dry run says what it would do and changes nothing. - let would = format!( - "Would replace the installed copy of 1 gem with the upstream build: {DEP} {DEP_VERSION}." - ); + let uri = server.uri(); let (code, stdout, stderr) = - unwind_run(&proj, &server.uri(), &["rollback", "--yes", "--dry-run"]); - assert_eq!(code, 0, "{stdout}\n{stderr}"); - assert!(stdout.contains(&would), "{stdout}\n{stderr}"); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); - - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes"]); - assert_eq!(code, 0, "{stdout}\n{stderr}"); - assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "{stdout}\n{stderr}"); + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + let env = common::parse_json_envelope(&stdout); + assert_eq!( + code, 0, + "a failed refresh never fails the scan: {env}\n{stderr}" + ); + let details = stale_warnings(&env); + assert_eq!(details.len(), 1, "{env}"); assert!( - stdout.contains(&format!( - "Replaced the installed copy of 1 gem with the upstream build: {DEP} {DEP_VERSION}." - )), - "{stdout}\n{stderr}" + details[0].contains("does not have the pinned sha256"), + "{}", + details[0] + ); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB); + assert_eq!(std::fs::read(&cache).unwrap(), real_gem(UPSTREAM_LIB)); + assert!(!home.join(".socket-patch-refresh").exists()); + + let before = server.received_requests().await.unwrap_or_default().len(); + let (code, stdout, _) = common::run_with_env( + &proj, + &scan_args(&proj, &uri, &["--json", "--no-gem-install-refresh"]), + &[], ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}"); + let details = stale_warnings(&env); assert!( - !stdout.contains("patched bytes") && !stderr.contains("still"), - "nothing is left to reinstall:\n{stdout}\n{stderr}" + details.len() == 1 && details[0].contains("`--no-gem-install-refresh` is set"), + "{env}" ); + let asked_for_gem = server.received_requests().await.unwrap_or_default()[before..] + .iter() + .any(|r| r.url.path().ends_with(".gem")); + assert!(!asked_for_gem, "an opted-out run downloads no archive"); } -/// #2092: when no patch record can be had for such a copy (the API fails), -/// nothing tells it from the patched build. It is left as it is and named -/// as a copy that could not be checked, with the reason and the files to -/// remove: never passed over in silence. +/// A gem home outside the project is left exactly as it was, under ONE +/// human warning that names the gem, the home, and the remedy as a +/// command; `--gem-refresh-shared` refreshes it like a project-local one. +#[cfg(unix)] #[tokio::test(flavor = "multi_thread")] -async fn hosted_unwind_names_a_pruned_home_install_no_record_can_judge() { +async fn refresh_leaves_a_shared_gem_home_alone_unless_asked() { let server = MockServer::start().await; - let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); - // The view answers 500. - mount_api_for(&server, Some(0), &sha256_of(&patched)).await; + let patched = real_gem(PATCHED_LIB); + mount_api_for(&server, None, &sha256_of(&patched)).await; serve_patched_gem(&server, patched.clone()).await; - serve_upstream_gem(&server, &upstream).await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let (gem_dir, home) = hosted_with_pruned_home_cache(&server, &proj, true).await; - let before = snapshot(&home); - let asked_before = server.received_requests().await.unwrap().len(); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = tmp.path().join("system-home"); + let bin_dir = tmp.path().join("fake-bin"); + stage_system_home_copy(&home, &bin_dir); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let cache = home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem")); + let path_env = [("PATH", bin_dir.to_str().unwrap())]; - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes", "--json"]); - let env: serde_json::Value = serde_json::from_str(&stdout) - .unwrap_or_else(|e| panic!("not JSON: {e}\n{stdout}\n{stderr}")); - assert_eq!(code, 0, "{env}\n{stderr}"); - assert_eq!(snapshot(&home), before, "left as it is"); - assert!( - details_with_code(&env, "upstream_gem_install_refreshed").is_empty(), - "{env}" + let uri = server.uri(); + let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &[]), &path_env); + assert_eq!(code, 0, "{stderr}"); + assert_eq!( + installed_lib(&gem_dir), + UPSTREAM_LIB, + "the shared home is not touched" ); - assert!( - gem_downloads_since(&server, asked_before).await.is_empty(), - "no gem was downloaded for a copy nothing judged" + assert_eq!(std::fs::read(&cache).unwrap(), real_gem(UPSTREAM_LIB)); + assert_eq!( + stderr.matches("still unpatched on disk").count(), + 1, + "one stale-install warning:\n{stderr}" ); - let unchecked = details_with_code(&env, "upstream_gem_stale_install"); - assert_eq!(unchecked.len(), 1, "the copy is reported: {env}"); - let spec = home - .join("specifications") - .join(format!("{DEP}-{DEP_VERSION}.gemspec")); for needle in [ - PURL, - "could not be checked against the upstream gem", - "its gem home has no archive of it and its patch record could not be fetched", - "it still holds the patched build", - "run `bundle install`", - gem_dir.to_str().unwrap(), - spec.to_str().unwrap(), - ] { - assert!( - unchecked[0].contains(needle), - "missing {needle:?}: {}", - unchecked[0] - ); + "Warning: 1 gem is still unpatched on disk after the switch to hosted patches.", + &format!( + " - Shared gem home {} (left alone, other projects may load it): {DEP} {DEP_VERSION}.", + home.display() + ), + "run `bundle config set --local path vendor/bundle && bundle install`", + "`--gem-refresh-shared`", + ] { + assert!(stderr.contains(needle), "missing {needle:?}:\n{stderr}"); } - // A human run counts it apart, in one warning. - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - hosted_with_pruned_home_cache(&server, &proj, true).await; - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes"]); - assert_eq!(code, 0, "{stdout}\n{stderr}"); - assert!( - stderr.contains("1 gem on disk could not be checked") - && stderr.contains("its patch record could not be fetched"), - "{stdout}\n{stderr}" + let (code, stdout, stderr) = common::run_with_env( + &proj, + &scan_args(&proj, &uri, &["--json", "--gem-refresh-shared"]), + &path_env, ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert!(stale_warnings(&env).is_empty(), "{env}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + assert_eq!(std::fs::read(&cache).unwrap(), patched); } -/// #2092 where nothing proves the upstream gem's sha256 (a lock without -/// `CHECKSUMS`, with `--offline` or a registry that does not answer): the -/// copy cannot be replaced, but it is not passed over. Offline no record is -/// fetched and the copy is named as one that could not be checked; with the -/// API in reach the record proves it patched and it is named as stale. -#[tokio::test(flavor = "multi_thread")] -async fn hosted_unwind_names_a_pruned_home_install_with_no_upstream_sha256() { - for (offline, needles) in [ - ( - true, - [ - "could not be checked against the upstream gem", - "`--offline` is set, so its patch record was not fetched", - ], - ), - ( - false, - [ - "its patched install at", - "nothing pins the sha256 of the upstream gem", - ], - ), - ] { - let server = MockServer::start().await; - let patched = real_gem(PATCHED_LIB); - mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_patched_gem(&server, patched.clone()).await; - // No rubygems.org stand-in: the compact index is a 404. - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - let (gem_dir, home) = hosted_with_pruned_home_cache(&server, &proj, true).await; - let before = snapshot(&home); - let views_before = view_requests(&server).await; +/// rubygems.org's stand-in under `/upstream` (`SOCKET_RUBYGEMS_URL`): the +/// compact index entry naming the upstream archive's sha256, and its +/// download. +async fn serve_upstream_gem(server: &MockServer, upstream: &[u8]) { + serve_upstream_gem_indexed_as(server, upstream, &sha256_of(upstream)).await; +} - let mut args = vec!["rollback", "--yes", "--json"]; - if offline { - args.push("--offline"); - } - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); - let env: serde_json::Value = serde_json::from_str(&stdout) - .unwrap_or_else(|e| panic!("offline={offline}: not JSON: {e}\n{stdout}\n{stderr}")); - assert_eq!(code, 0, "offline={offline}: {env}\n{stderr}"); - assert_eq!(snapshot(&home), before, "offline={offline}: left as it is"); - let left = details_with_code(&env, "upstream_gem_stale_install"); - assert_eq!(left.len(), 1, "offline={offline}: reported: {env}"); - for needle in - needles - .into_iter() - .chain([PURL, "run `bundle install`", gem_dir.to_str().unwrap()]) - { - assert!( - left[0].contains(needle), - "offline={offline}: missing {needle:?}: {}", - left[0] - ); - } - assert_eq!( - view_requests(&server).await - views_before, - usize::from(!offline), - "offline={offline}: an offline run fetches no record" - ); - } +/// [`serve_upstream_gem`] with the index's `checksum:` written as +/// `digest`: the gem's sha256 in whichever encoding the server uses. +async fn serve_upstream_gem_indexed_as(server: &MockServer, upstream: &[u8], digest: &str) { + Mock::given(method("GET")) + .and(path(format!("/upstream/info/{DEP}"))) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(format!("---\n{DEP_VERSION} |checksum:{digest}\n")), + ) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path(format!("/upstream/gems/{DEP}-{DEP_VERSION}.gem"))) + .respond_with( + ResponseTemplate::new(200).set_body_raw(upstream.to_vec(), "application/octet-stream"), + ) + .mount(server) + .await; } -/// The record judges, it does not assume: an installed copy that is still -/// the upstream gem (the scan was told not to refresh it) is left alone in -/// a home with no `cache/` dir too, with no warning and no gem download. +/// The unwind direction: `rollback` puts the lock back on rubygems.org and +/// the project's installed gem and archives back on the upstream gem, +/// verified against the sha256 the compact index names. #[tokio::test(flavor = "multi_thread")] -async fn hosted_unwind_leaves_an_upstream_install_in_a_pruned_home_alone() { +async fn refresh_after_rollback_restores_the_upstream_gem() { let server = MockServer::start().await; let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); mount_api_for(&server, None, &sha256_of(&patched)).await; @@ -4090,854 +4716,1029 @@ async fn hosted_unwind_leaves_an_upstream_install_in_a_pruned_home_alone() { serve_upstream_gem(&server, &upstream).await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let (_, home) = hosted_with_pruned_home_cache(&server, &proj, false).await; - let before = snapshot(&home); - let asked_before = server.received_requests().await.unwrap().len(); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = project_home(&proj); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let leaf = format!("{DEP}-{DEP_VERSION}"); + let cache = home.join("cache").join(format!("{leaf}.gem")); + let committed = proj + .join("vendor") + .join("cache") + .join(format!("{leaf}.gem")); + std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); + std::fs::write(&committed, &upstream).unwrap(); - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes", "--json"]); + let uri = server.uri(); + let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "scan refreshed it"); + // The lock as `bundle install` leaves it once the pin is installed. + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + + let rubygems = format!("{uri}/upstream"); + let rollback = |extra: &[&'static str]| { + let mut args = vec![ + "rollback", + PURL, + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + uri.as_str(), + ]; + args.extend_from_slice(extra); + common::run_with_env(&proj, &args, &[("SOCKET_RUBYGEMS_URL", rubygems.as_str())]) + }; + + // A dry run says what it would do and changes nothing. + let (code, stdout, stderr) = rollback(&["--dry-run"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains(&format!( + "Would replace the installed copy of 1 gem with the upstream build: {DEP} {DEP_VERSION}." + )), + "{stdout}" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + + let (code, stdout, stderr) = rollback(&["--json"]); let env: serde_json::Value = serde_json::from_str(&stdout) .unwrap_or_else(|e| panic!("not JSON: {e}\n{stdout}\n{stderr}")); assert_eq!(code, 0, "{env}\n{stderr}"); - assert_eq!(snapshot(&home), before, "nothing changed"); + let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); assert!( - details_with_code(&env, "upstream_gem_install_refreshed").is_empty() - && details_with_code(&env, "upstream_gem_stale_install").is_empty(), - "{env}" + !lock.contains("/patch-registry/"), + "the lock is back on upstream:\n{lock}" + ); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB); + assert_eq!(std::fs::read(&cache).unwrap(), upstream); + assert_eq!(std::fs::read(&committed).unwrap(), upstream); + assert_eq!( + warnings_with_code(&env, "upstream_gem_install_refreshed").len(), + 2, + "the install and the committed archive: {env}" ); assert!( - gem_downloads_since(&server, asked_before).await.is_empty(), - "no gem was downloaded" + warnings_with_code(&env, "upstream_gem_stale_cache").is_empty() + && warnings_with_code(&env, "upstream_gem_stale_install").is_empty(), + "nothing is left on the patched build: {env}" ); } -/// A project whose `Gemfile` names a private gem mirror as its source -/// (`source ""`), so the lock resolves the gem from that remote, -/// with the gem installed from it. `checksum` is the sha256 the lock's -/// `CHECKSUMS` section pins for the gem (Bundler 2.6 and later); `None` -/// writes a lock without the section. Returns the installed gem dir. -fn mirror_project(proj: &Path, mirror: &str, checksum: Option<&str>) -> PathBuf { - std::fs::create_dir_all(proj).unwrap(); - std::fs::write( - proj.join("Gemfile"), - format!("source \"{mirror}\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"), - ) - .unwrap(); - let checksums = checksum - .map(|sha| format!("CHECKSUMS\n {DEP} ({DEP_VERSION}) sha256={sha}\n\n")) - .unwrap_or_default(); - std::fs::write( - proj.join("Gemfile.lock"), - format!( - "GEM\n remote: {mirror}/\n specs:\n {DEP} ({DEP_VERSION})\n\n\ - PLATFORMS\n ruby\n\nDEPENDENCIES\n {DEP} (= {DEP_VERSION})\n\n\ - {checksums}BUNDLED WITH\n 2.6.9\n" - ), - ) - .unwrap(); - install_real_gem(&project_home(proj), UPSTREAM_LIB) -} - -/// #2230: a hosted gem the lock resolves from a private mirror, under a -/// lock without `CHECKSUMS`. The unwind restores the pair, and nothing -/// gives the upstream gem's sha256, so the patched archive in the gem home -/// says nothing about the installed copy. The copy is judged by the pin's -/// patch record like one with no archive: the patched build the scan put -/// there is named with the files to remove (`bundle install` and `bundle -/// pristine` keep it otherwise), and offline it is named as a copy that -/// could not be checked. Neither is passed over in silence. +/// #2086: `rollback` / `remove` of a hosted gem whose patched copy sits in +/// a shared gem home leave that copy alone and warn about it. The warning +/// names no re-run with `--gem-refresh-shared`: the first run removed the +/// wiring, so a second one has nothing to unwind. It names the +/// project-local path, and the files whose removal makes `bundle install` +/// fetch the upstream gem into the shared home. The generic reinstall note +/// does not claim that the next install replaces the copy. +#[cfg(unix)] #[tokio::test(flavor = "multi_thread")] -async fn hosted_unwind_names_a_patched_install_from_a_mirror_without_checksums() { - const MIRROR: &str = "https://gems.example.test"; - for (offline, needles) in [ - (false, ["its patched install at", "run `bundle install`"]), - ( - true, - [ - "could not be checked against the upstream gem", - "nothing gives the sha256 of its upstream gem and `--offline` is set, so its \ - patch record was not fetched", - ], - ), - ] { - let server = MockServer::start().await; - let patched = real_gem(PATCHED_LIB); - mount_api_for(&server, None, &sha256_of(&patched)).await; +async fn hosted_unwind_names_no_rerun_for_a_shared_gem_home() { + const UNWINDS: [&[&str]; 2] = [&["rollback", "--yes"], &["remove", PURL, "--yes"]]; + for (unwind, json) in UNWINDS + .into_iter() + .flat_map(|unwind| [(unwind, false), (unwind, true)]) + { + let case = format!("{unwind:?} json={json}"); + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; serve_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let gem_dir = mirror_project(&proj, MIRROR, None); - // The project commits its bundler cache. - let committed = proj - .join("vendor") - .join("cache") - .join(format!("{DEP}-{DEP_VERSION}.gem")); - std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); - std::fs::write(&committed, real_gem(UPSTREAM_LIB)).unwrap(); - let pair = |name: &str| std::fs::read_to_string(proj.join(name)).unwrap(); - let (gemfile, lock) = (pair("Gemfile"), pair("Gemfile.lock")); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = tmp.path().join("system-home"); + let bin_dir = tmp.path().join("fake-bin"); + stage_system_home_copy(&home, &bin_dir); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let leaf = format!("{DEP}-{DEP_VERSION}"); + let cache = home.join("cache").join(format!("{leaf}.gem")); + let spec = home.join("specifications").join(format!("{leaf}.gemspec")); + + // The shared copy becomes the patched build. let uri = server.uri(); - let (code, _, stderr) = - common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); - assert_eq!(code, 0, "{stderr}"); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise: refreshed"); - let home = project_home(&proj); - let before = snapshot(&home); - let asked_before = server.received_requests().await.unwrap().len(); + let rubygems = format!("{uri}/upstream"); + let env = [ + ("PATH", bin_dir.to_str().unwrap()), + ("SOCKET_RUBYGEMS_URL", rubygems.as_str()), + ]; + let (code, _, stderr) = common::run_with_env( + &proj, + &scan_args(&proj, &uri, &["--json", "--gem-refresh-shared"]), + &env, + ); + assert_eq!(code, 0, "{case}: {stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{case}: premise"); + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + let held_before = snapshot(&home); - let mut args = vec!["rollback", "--yes", "--json"]; - if offline { - args.push("--offline"); + let mut args = unwind.to_vec(); + args.extend([ + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + uri.as_str(), + ]); + if json { + args.push("--json"); } - let (code, stdout, stderr) = unwind_run(&proj, &uri, &args); - let env: serde_json::Value = serde_json::from_str(&stdout) - .unwrap_or_else(|e| panic!("offline={offline}: not JSON: {e}\n{stdout}\n{stderr}")); - assert_eq!(code, 0, "offline={offline}: {env}\n{stderr}"); - assert_eq!(pair("Gemfile"), gemfile, "offline={offline}"); - assert_eq!(pair("Gemfile.lock"), lock, "offline={offline}"); - assert_eq!(snapshot(&home), before, "offline={offline}: left as it is"); - let left = details_with_code(&env, "upstream_gem_stale_install"); - assert_eq!(left.len(), 1, "offline={offline}: reported: {env}"); - for needle in needles.into_iter().chain([PURL, gem_dir.to_str().unwrap()]) { + let (code, stdout, stderr) = common::run_with_env(&proj, &args, &env); + assert_eq!(code, 0, "{case}:\n{stdout}\n{stderr}"); + let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + assert!(!lock.contains("/patch-registry/"), "{case}:\n{lock}"); + assert!( + snapshot(&home) == held_before, + "{case}: the shared gem home is left alone" + ); + + let remove_files = format!("{} {}", shell_word(&spec), shell_word(&cache)); + let warning = if json { + let env = common::parse_json_envelope(&stdout); + let details = details_with_code(&env, "upstream_gem_stale_install"); + assert_eq!(details.len(), 1, "{case}: {env}"); + // rollback's run-level advisory defers to the gem warning. + if unwind[0] == "rollback" { + let reinstall = details_with_code(&env, "reinstall_required"); + assert_eq!(reinstall.len(), 1, "{case}: {env}"); + assert!( + reinstall[0].contains("`bundle install` keeps an installed gem"), + "{case}: {}", + reinstall[0] + ); + } assert!( - left[0].contains(needle), - "offline={offline}: missing {needle:?}: {}", - left[0] + details[0].contains(&format!( + "remove {}, {} and run `bundle install`", + spec.display(), + cache.display() + )), + "{case}: {}", + details[0] ); - } - // The archive in Bundler's cache dir is named too, as one nothing - // could check: the registry is not asked about another remote's gem. - let cached = details_with_code(&env, "upstream_gem_stale_cache"); - assert_eq!(cached.len(), 1, "offline={offline}: {env}"); + details[0].clone() + } else { + assert_eq!( + stderr.matches("still holds the patched build").count(), + 1, + "{case}: one warning:\n{stderr}" + ); + assert!( + stderr.contains(&format!("run `rm -f {remove_files} && bundle install`")), + "{case}: the remedy as a command:\n{stderr}" + ); + if unwind[0] == "rollback" { + assert!( + stdout.contains("1 unwired package keeps its patched bytes") + && stdout.contains("`bundle install` keeps") + && !stdout.contains("package-manager install."), + "{case}: the note defers to the gem warning:\n{stdout}" + ); + } + stderr.clone() + }; assert!( - cached[0].contains(committed.to_str().unwrap()) - && cached[0].contains("could not be checked against the upstream sha256"), - "offline={offline}: {}", - cached[0] + warning.contains("bundle config set --local path vendor/bundle && bundle install"), + "{case}: {warning}" ); - let asked_registry = server - .received_requests() - .await - .unwrap() - .iter() - .skip(asked_before) - .any(|request| request.url.path().starts_with("/upstream/")); assert!( - !asked_registry, - "offline={offline}: rubygems.org is not asked about another remote's gem" + !warning.contains("--gem-refresh-shared") && !warning.to_lowercase().contains("re-run"), + "{case}: a second unwind has nothing to unwind: {warning}" + ); + + // Why no re-run is named: the wiring is gone. + let mut again = args.clone(); + again.push("--gem-refresh-shared"); + let (code, stdout, stderr) = common::run_with_env(&proj, &again, &env); + assert_eq!(code, 1, "{case}: premise:\n{stdout}\n{stderr}"); + let nothing = match (json, unwind[0]) { + (true, _) => "\"status\": \"error\"", + (false, "rollback") => "nothing to roll back", + (false, _) => "nothing to remove", + }; + assert!( + format!("{stdout}{stderr}").contains(nothing), + "{case}: premise: a second unwind finds nothing:\n{stdout}\n{stderr}" ); + assert!(snapshot(&home) == held_before, "{case}"); } } -/// The record judges, it does not assume (#2230): an installed copy from a -/// private mirror that is still the upstream gem (the scan was told not to -/// refresh it) gets no warning after the unwind. +/// A registry that is refused (plain http, and not this machine) is not +/// asked what the upstream gem is. `rollback` still puts the lock back, +/// leaves the installed copy as it is, and says so: the copy is reported as +/// one it could not check, with the reason, not passed over in silence +/// while it still holds the patched build. #[tokio::test(flavor = "multi_thread")] -async fn hosted_unwind_leaves_an_upstream_install_from_a_mirror_alone() { +async fn rollback_reports_the_copy_a_refused_registry_left_unchecked() { + refused_registry_leaves_the_copy_reported(true).await; +} + +/// The same with the copy's archive gone from the home's cache (a pruned +/// `cache/`, as slim images have). With nothing to judge the copy by it is +/// still reported, not passed over. +#[tokio::test(flavor = "multi_thread")] +async fn rollback_reports_an_unchecked_copy_whose_cached_archive_is_gone() { + refused_registry_leaves_the_copy_reported(false).await; +} + +async fn refused_registry_leaves_the_copy_reported(cached_archive: bool) { let server = MockServer::start().await; let patched = real_gem(PATCHED_LIB); mount_api_for(&server, None, &sha256_of(&patched)).await; serve_patched_gem(&server, patched.clone()).await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let gem_dir = mirror_project(&proj, "https://gems.example.test", None); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = project_home(&proj); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let leaf = format!("{DEP}-{DEP_VERSION}"); + let cache = home.join("cache").join(format!("{leaf}.gem")); + let uri = server.uri(); - let flags = ["--json", "--no-gem-install-refresh"]; - let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &flags), &[]); + let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); assert_eq!(code, 0, "{stderr}"); - assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "premise"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "scan refreshed it"); + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + let asked_before = server.received_requests().await.unwrap().len(); + if !cached_archive { + std::fs::remove_file(&cache).unwrap(); + } - let (code, stdout, stderr) = unwind_run(&proj, &uri, &["rollback", "--yes", "--json"]); + // Refused before any request: nothing is looked up or sent. + const REFUSED: &str = "http://gemstash.example.test:9292"; + let args = [ + "rollback", + PURL, + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + uri.as_str(), + "--json", + ]; + let (code, stdout, stderr) = + common::run_with_env(&proj, &args, &[("SOCKET_RUBYGEMS_URL", REFUSED)]); let env: serde_json::Value = serde_json::from_str(&stdout) .unwrap_or_else(|e| panic!("not JSON: {e}\n{stdout}\n{stderr}")); assert_eq!(code, 0, "{env}\n{stderr}"); + let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); assert!( - details_with_code(&env, "upstream_gem_stale_install").is_empty(), + !lock.contains("/patch-registry/"), + "the lock is back on upstream:\n{lock}" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "left as it is"); + if cached_archive { + assert_eq!(std::fs::read(&cache).unwrap(), patched); + } + assert!( + warnings_with_code(&env, "upstream_gem_install_refreshed").is_empty(), "{env}" ); -} - -/// #2230: on a lock with `CHECKSUMS`, a hosted gem from a private mirror -/// can be unwound. The restore reads the gem's upstream sha256 from the -/// mirror's own compact index when `SOCKET_RUBYGEMS_URL` names that -/// server: the pair is the pre-scan pair byte for byte and the installed -/// copy is the upstream gem again. Without the setting the unwind refuses, -/// changes nothing and names the setting. -#[tokio::test(flavor = "multi_thread")] -async fn hosted_unwind_restores_a_mirror_gem_when_the_registry_setting_names_the_mirror() { - for command in HOSTED_UNWINDS { - let server = MockServer::start().await; - let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); - mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_patched_gem(&server, patched.clone()).await; - // The mirror: the mock's `/upstream` tree. - serve_upstream_gem(&server, &upstream).await; - let uri = server.uri(); - let mirror = format!("{uri}/upstream"); - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - let gem_dir = mirror_project(&proj, &mirror, Some(&sha256_of(&upstream))); - let pair = |name: &str| std::fs::read_to_string(proj.join(name)).unwrap(); - let (gemfile, lock) = (pair("Gemfile"), pair("Gemfile.lock")); - let (code, _, stderr) = - common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); - assert_eq!(code, 0, "{stderr}"); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise: refreshed"); - let (hosted_gemfile, hosted_lock) = (pair("Gemfile"), pair("Gemfile.lock")); - assert!(hosted_lock.contains("/patch-registry/"), "{hosted_lock}"); - - // rubygems.org (here: another stand-in) is not the lock's remote. - let mut args = command.to_vec(); - args.push("--json"); - let elsewhere = format!("{uri}/elsewhere"); - let (code, stdout, stderr) = unwind_run_with_registry(&proj, &uri, &args, &elsewhere); - assert_ne!(code, 0, "{command:?}: {stdout}\n{stderr}"); - let said = format!("{stdout}\n{stderr}"); - for needle in [ - "is not rubygems.org", - &format!("`SOCKET_RUBYGEMS_URL={mirror}`"), - "git checkout -- Gemfile Gemfile.lock", - ] { - assert!( - said.contains(needle), - "{command:?}: missing {needle:?}: {said}" - ); - } - assert_eq!(pair("Gemfile"), hosted_gemfile, "{command:?}: refused"); - assert_eq!(pair("Gemfile.lock"), hosted_lock, "{command:?}: refused"); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{command:?}: refused"); - - // The setting names the mirror: the remedy the refusal gave. - let (code, stdout, stderr) = unwind_run_with_registry(&proj, &uri, &args, &mirror); - let env: serde_json::Value = serde_json::from_str(&stdout) - .unwrap_or_else(|e| panic!("{command:?}: not JSON: {e}\n{stdout}\n{stderr}")); - assert_eq!(code, 0, "{command:?}: {env}\n{stderr}"); - assert_eq!(pair("Gemfile"), gemfile, "{command:?}"); - assert_eq!(pair("Gemfile.lock"), lock, "{command:?}"); - assert_eq!( - installed_lib(&gem_dir), - UPSTREAM_LIB, - "{command:?}: the upstream gem is back: {env}" - ); + let unchecked = warnings_with_code(&env, "upstream_gem_stale_install"); + assert_eq!(unchecked.len(), 1, "the copy is reported: {env}"); + for needle in [ + PURL, + "could not be checked against the upstream gem", + "`http://gemstash.example.test:9292` is not an https URL", + "set it to an https URL", + "it still holds the patched build", + "run `bundle install`", + gem_dir.to_str().unwrap(), + ] { assert!( - details_with_code(&env, "upstream_gem_stale_install").is_empty(), - "{command:?}: nothing is left on the patched build: {env}" + unchecked[0].contains(needle), + "missing {needle:?}: {}", + unchecked[0] ); } + assert_eq!( + server.received_requests().await.unwrap().len(), + asked_before, + "the rollback asked a registry" + ); } -/// #2285: a mirror built with `gem generate_index` writes the sha256 in -/// its compact index as base64, which Bundler reads and pins as hex in -/// `CHECKSUMS`. With `SOCKET_RUBYGEMS_URL` naming such a mirror the -/// unwind restores the pair byte for byte and puts the upstream gem back. -/// (The URL-safe alphabet Bundler also reads is covered where the digest -/// is parsed, in the core crate's unit tests.) +/// The commands that unwind a hosted gem. +const HOSTED_UNWINDS: [&[&str]; 2] = [&["rollback", "--yes"], &["remove", PURL, "--yes"]]; + +/// A project whose gem a hosted scan pinned, with the lock as `bundle +/// install` leaves it, in a gem home that has no `cache/` dir (Bundler +/// 4.1's `prune` setting, the `rm -rf "${BUNDLE_PATH}"/ruby/*/cache` of the +/// Dockerfile Rails generates, `gem cleanup`). With `refreshed` the scan +/// replaced the installed copy with the patched build; without, it was told +/// not to (`--no-gem-install-refresh`) and the copy is still the upstream +/// one. Returns the installed gem dir and the gem home. +async fn hosted_with_pruned_home_cache( + server: &MockServer, + proj: &Path, + refreshed: bool, +) -> (PathBuf, PathBuf) { + std::fs::create_dir_all(proj).unwrap(); + write_manifest_pair(proj); + let home = project_home(proj); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let uri = server.uri(); + let flags: &[&str] = if refreshed { + &["--json"] + } else { + &["--json", "--no-gem-install-refresh"] + }; + let (code, _, stderr) = common::run_with_env(proj, &scan_args(proj, &uri, flags), &[]); + assert_eq!(code, 0, "{stderr}"); + let expected = if refreshed { PATCHED_LIB } else { UPSTREAM_LIB }; + assert_eq!(installed_lib(&gem_dir), expected, "premise"); + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + std::fs::remove_dir_all(home.join("cache")).unwrap(); + (gem_dir, home) +} + +/// Every `detail` (a warning's) or `reason` (an event's) that `--json` +/// output carries under `code`, wherever the command puts it. +fn details_with_code(env: &serde_json::Value, code: &str) -> Vec { + fn walk(value: &serde_json::Value, code: &str, out: &mut Vec) { + match value { + serde_json::Value::Object(map) => { + if map + .get("code") + .or(map.get("errorCode")) + .and_then(|c| c.as_str()) + == Some(code) + { + let detail = map.get("detail").or(map.get("reason")); + out.push( + detail + .and_then(|d| d.as_str()) + .unwrap_or_default() + .to_string(), + ); + } + map.values().for_each(|v| walk(v, code, out)); + } + serde_json::Value::Array(items) => items.iter().for_each(|v| walk(v, code, out)), + _ => {} + } + } + let mut out = Vec::new(); + walk(env, code, &mut out); + out +} + +/// #2092: a gem home with no `cache/` dir has no archive to judge the +/// installed copy by. The hosted unwind judges it by the pin's patch record +/// instead, as the scan does in that home, and puts the upstream gem back: +/// otherwise the app keeps loading the patch under the restored lock, and +/// no later `bundle install` changes that. #[tokio::test(flavor = "multi_thread")] -async fn hosted_unwind_restores_a_mirror_gem_whose_index_checksum_is_base64() { - use base64::Engine as _; - use sha2::Digest as _; +async fn hosted_unwind_restores_an_install_whose_home_cache_was_pruned() { for command in HOSTED_UNWINDS { let server = MockServer::start().await; let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); mount_api_for(&server, None, &sha256_of(&patched)).await; serve_patched_gem(&server, patched.clone()).await; - let digest = - base64::engine::general_purpose::STANDARD.encode(sha2::Sha256::digest(&upstream)); - assert_eq!(digest.len(), 44, "premise: 43 digits and one `=`"); - serve_upstream_gem_indexed_as(&server, &upstream, &digest).await; - let uri = server.uri(); - let mirror = format!("{uri}/upstream"); + serve_upstream_gem(&server, &upstream).await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let gem_dir = mirror_project(&proj, &mirror, Some(&sha256_of(&upstream))); - let pair = |name: &str| std::fs::read_to_string(proj.join(name)).unwrap(); - let (gemfile, lock) = (pair("Gemfile"), pair("Gemfile.lock")); - let (code, _, stderr) = - common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); - assert_eq!(code, 0, "{command:?}: {stderr}"); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise: refreshed"); - assert!( - pair("Gemfile.lock").contains("/patch-registry/"), - "{command:?}" - ); + let (gem_dir, home) = hosted_with_pruned_home_cache(&server, &proj, true).await; + let views_before = view_requests(&server).await; let mut args = command.to_vec(); args.push("--json"); - let (code, stdout, stderr) = unwind_run_with_registry(&proj, &uri, &args, &mirror); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); let env: serde_json::Value = serde_json::from_str(&stdout) .unwrap_or_else(|e| panic!("{command:?}: not JSON: {e}\n{stdout}\n{stderr}")); assert_eq!(code, 0, "{command:?}: {env}\n{stderr}"); - assert_eq!(pair("Gemfile"), gemfile, "{command:?}"); - assert_eq!(pair("Gemfile.lock"), lock, "{command:?}"); + let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + assert!(!lock.contains("/patch-registry/"), "{command:?}:\n{lock}"); assert_eq!( installed_lib(&gem_dir), UPSTREAM_LIB, "{command:?}: the upstream gem is back: {env}" ); + assert_eq!( + details_with_code(&env, "upstream_gem_install_refreshed").len(), + 1, + "{command:?}: {env}" + ); assert!( details_with_code(&env, "upstream_gem_stale_install").is_empty(), "{command:?}: nothing is left on the patched build: {env}" ); + assert!( + !home.join("cache").exists(), + "{command:?}: a pruned cache dir is not created" + ); + assert_eq!( + view_requests(&server).await - views_before, + 1, + "{command:?}: one patch record, for that pin" + ); } } -/// The vendored half of the patch API for the fixture's patch: the grant -/// names the patched `.gem` and the stub gemspec a path source loads, each -/// with its sha512, beside the hosted registry override. Priority 1, so it -/// answers `patches/package` in place of [`mount_api_for`]'s hosted-only -/// grant. -async fn mount_vendored_grant(server: &MockServer, patched: &[u8]) { - mount_vendored_grant_of(server, UUID, patched).await; +/// The same in a human run: the refresh is a progress line, and the gem is +/// not counted among the packages that keep their patched bytes. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_reports_the_pruned_home_refresh_in_a_human_run() { + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, _) = hosted_with_pruned_home_cache(&server, &proj, true).await; + + // A dry run says what it would do and changes nothing. + let would = format!( + "Would replace the installed copy of 1 gem with the upstream build: {DEP} {DEP_VERSION}." + ); + let (code, stdout, stderr) = + unwind_run(&proj, &server.uri(), &["rollback", "--yes", "--dry-run"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains(&would), "{stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "{stdout}\n{stderr}"); + assert!( + stdout.contains(&format!( + "Replaced the installed copy of 1 gem with the upstream build: {DEP} {DEP_VERSION}." + )), + "{stdout}\n{stderr}" + ); + assert!( + !stdout.contains("patched bytes") && !stderr.contains("still"), + "nothing is left to reinstall:\n{stdout}\n{stderr}" + ); } -/// [`mount_vendored_grant`] for the patch `uuid`. -async fn mount_vendored_grant_of(server: &MockServer, uuid: &str, patched: &[u8]) { - use base64::Engine as _; - use sha2::Digest as _; - let sri = |bytes: &[u8]| { - format!( - "sha512-{}", - base64::engine::general_purpose::STANDARD.encode(sha2::Sha512::digest(bytes)) - ) - }; - let stub = format!( - "Gem::Specification.new do |s|\n s.name = \"{DEP}\".freeze\n s.version = \ - \"{DEP_VERSION}\".freeze\n s.authors = [\"e2e\".freeze]\n s.summary = \ - \"fixture\".freeze\n s.files = [\"lib/stale_probe_gem.rb\".freeze]\n s.require_paths \ - = [\"lib\".freeze]\nend\n" - ) - .into_bytes(); - let leaf = format!("{DEP}-{DEP_VERSION}"); - let base = format!("/artifacts/{uuid}"); - let gem_url = format!("{}{base}/{leaf}.gem", server.uri()); - let stub_url = format!("{}{base}/{leaf}.gemspec", server.uri()); - 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": gem_url, - "purl": PURL, - "artifacts": [ - { "kind": "tarball", "url": gem_url, - "integrity": { "sha512": sri(patched), "sha256": sha256_of(patched) } }, - { "kind": "gem-stub-gemspec", "url": stub_url, - "integrity": { "sha512": sri(&stub) } } - ], - "registryOverride": { - "kind": "rubygems-compact-index", - "indexUrl": format!("{}/patch-registry/gem/{TOKEN}/{uuid}/", server.uri()), - "identifiers": { - "name": DEP, - "version": DEP_VERSION, - "gemChecksumSha256": sha256_of(patched), - } - } - } - } - }))) - .with_priority(1) - .mount(server) - .await; - for (file, bytes) in [ - (format!("{leaf}.gem"), patched.to_vec()), - (format!("{leaf}.gemspec"), stub), +/// #2092: when no patch record can be had for such a copy (the API fails), +/// nothing tells it from the patched build. It is left as it is and named +/// as a copy that could not be checked, with the reason and the files to +/// remove: never passed over in silence. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_names_a_pruned_home_install_no_record_can_judge() { + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + // The view answers 500. + mount_api_for(&server, Some(0), &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, home) = hosted_with_pruned_home_cache(&server, &proj, true).await; + let before = snapshot(&home); + let asked_before = server.received_requests().await.unwrap().len(); + + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes", "--json"]); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert_eq!(snapshot(&home), before, "left as it is"); + assert!( + details_with_code(&env, "upstream_gem_install_refreshed").is_empty(), + "{env}" + ); + assert!( + gem_downloads_since(&server, asked_before).await.is_empty(), + "no gem was downloaded for a copy nothing judged" + ); + let unchecked = details_with_code(&env, "upstream_gem_stale_install"); + assert_eq!(unchecked.len(), 1, "the copy is reported: {env}"); + let spec = home + .join("specifications") + .join(format!("{DEP}-{DEP_VERSION}.gemspec")); + for needle in [ + PURL, + "could not be checked against the upstream gem", + "its gem home has no archive of it and its patch record could not be fetched", + "it still holds the patched build", + "run `bundle install`", + gem_dir.to_str().unwrap(), + spec.to_str().unwrap(), ] { - Mock::given(method("GET")) - .and(path(format!("{base}/{file}"))) - .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) - .mount(server) - .await; + assert!( + unchecked[0].contains(needle), + "missing {needle:?}: {}", + unchecked[0] + ); } -} -/// Every regular file under `dir`, relative, with its bytes. -fn snapshot(dir: &Path) -> std::collections::BTreeMap> { - fn walk(root: &Path, dir: &Path, out: &mut std::collections::BTreeMap>) { - for entry in std::fs::read_dir(dir).unwrap() { - let path = entry.unwrap().path(); - if path.is_dir() { - walk(root, &path, out); - } else { - out.insert( - path.strip_prefix(root).unwrap().to_path_buf(), - std::fs::read(&path).unwrap(), - ); - } - } - } - let mut out = std::collections::BTreeMap::new(); - walk(dir, dir, &mut out); - out + // A human run counts it apart, in one warning. + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + hosted_with_pruned_home_cache(&server, &proj, true).await; + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stderr.contains("1 gem on disk could not be checked") + && stderr.contains("its patch record could not be fetched"), + "{stdout}\n{stderr}" + ); } -/// A hosted → vendored takeover (`get --mode vendored`, `scan --mode -/// vendored`, and plain `vendor`, which ejects the lock's hosted pins) puts -/// the gem back on its upstream entry only on its way to the `path:` -/// source, which is what Bundler loads from then on. The gems -/// Bundler already holds are unused leftovers: the takeover must not -/// refresh them (the patched installed copy would become an unpatched one -/// that `vex` then reports against the vendored artifact) and must download -/// no gem for them (vendored mode needs no registry). The installed gem, -/// its cached archive and the cache-dir archive stay byte-identical, and -/// the takeover's own advisory about the cache-dir archive is unchanged. +/// #2092 where nothing proves the upstream gem's sha256 (a lock without +/// `CHECKSUMS`, with `--offline` or a registry that does not answer): the +/// copy cannot be replaced, but it is not passed over. Offline no record is +/// fetched and the copy is named as one that could not be checked; with the +/// API in reach the record proves it patched and it is named as stale. #[tokio::test(flavor = "multi_thread")] -async fn refresh_is_not_run_by_a_hosted_to_vendored_takeover() { - let takeovers: [&[&str]; 3] = [ - &["get", UUID, "--mode", "vendored"], - &["scan", "--mode", "vendored"], - &["vendor"], - ]; - for takeover in takeovers { +async fn hosted_unwind_names_a_pruned_home_install_with_no_upstream_sha256() { + for (offline, needles) in [ + ( + true, + [ + "could not be checked against the upstream gem", + "`--offline` is set, so its patch record was not fetched", + ], + ), + ( + false, + [ + "its patched install at", + "nothing pins the sha256 of the upstream gem", + ], + ), + ] { let server = MockServer::start().await; - let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + let patched = real_gem(PATCHED_LIB); mount_api_for(&server, None, &sha256_of(&patched)).await; serve_patched_gem(&server, patched.clone()).await; - // Everything a refresh back to upstream would need is there to use. - serve_upstream_gem(&server, &upstream).await; - mount_vendored_grant(&server, &patched).await; + // No rubygems.org stand-in: the compact index is a 404. let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - std::fs::create_dir_all(&proj).unwrap(); - write_manifest_pair(&proj); - let home = project_home(&proj); - let gem_dir = install_real_gem(&home, UPSTREAM_LIB); - let leaf = format!("{DEP}-{DEP_VERSION}"); - let committed = proj - .join("vendor") - .join("cache") - .join(format!("{leaf}.gem")); - std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); - std::fs::write(&committed, &upstream).unwrap(); + let (gem_dir, home) = hosted_with_pruned_home_cache(&server, &proj, true).await; + let before = snapshot(&home); + let views_before = view_requests(&server).await; - // The hosted state: the scan pins the gem and refreshes the - // project's copies; the lock is then as `bundle install` leaves it. - let uri = server.uri(); - let (code, _, stderr) = - common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); - assert_eq!(code, 0, "{takeover:?}: hosted scan:\n{stderr}"); - std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); - assert_eq!( - installed_lib(&gem_dir), - PATCHED_LIB, - "{takeover:?}: premise" - ); + let mut args = vec!["rollback", "--yes", "--json"]; + if offline { + args.push("--offline"); + } + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("offline={offline}: not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "offline={offline}: {env}\n{stderr}"); + assert_eq!(snapshot(&home), before, "offline={offline}: left as it is"); + let left = details_with_code(&env, "upstream_gem_stale_install"); + assert_eq!(left.len(), 1, "offline={offline}: reported: {env}"); + for needle in + needles + .into_iter() + .chain([PURL, "run `bundle install`", gem_dir.to_str().unwrap()]) + { + assert!( + left[0].contains(needle), + "offline={offline}: missing {needle:?}: {}", + left[0] + ); + } assert_eq!( - std::fs::read(&committed).unwrap(), - patched, - "{takeover:?}: premise" - ); - let held_before = (snapshot(&home), snapshot(committed.parent().unwrap())); - let requests_before = server.received_requests().await.unwrap_or_default().len(); - - let rubygems = format!("{uri}/upstream"); - let mut args = takeover.to_vec(); - args.extend([ - "--yes", - "--json", - "--cwd", - proj.to_str().unwrap(), - "--api-url", - uri.as_str(), - "--org", - ORG, - "--api-token", - "fake", - "--patch-server-url", - uri.as_str(), - ]); - let (code, stdout, stderr) = - common::run_with_env(&proj, &args, &[("SOCKET_RUBYGEMS_URL", rubygems.as_str())]); - let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{takeover:?}: {env}\nstderr:\n{stderr}"); - let gemfile = std::fs::read_to_string(proj.join("Gemfile")).unwrap(); - assert!( - gemfile.contains(".socket/vendor/gem/") && !gemfile.contains("/patch-registry/"), - "{takeover:?}: the takeover vendored the gem:\n{gemfile}" + view_requests(&server).await - views_before, + usize::from(!offline), + "offline={offline}: an offline run fetches no record" ); + } +} - assert!( - (snapshot(&home), snapshot(committed.parent().unwrap())) == held_before, - "{takeover:?}: the takeover changed a gem Bundler already held: {env}" - ); - let fetched: Vec = server.received_requests().await.unwrap_or_default() - [requests_before..] - .iter() - .map(|r| r.url.path().to_string()) - .filter(|path| path.contains("/gems/")) - .collect(); - assert!( - fetched.is_empty(), - "{takeover:?}: the takeover downloaded a gem for the installed copies: {fetched:?}" - ); - let text = env.to_string(); - for code in [ - "upstream_gem_install_refreshed", - "upstream_gem_stale_install", - "redirect_gem_install_refreshed", - "redirect_gem_stale_install", - ] { - assert!(!text.contains(code), "{takeover:?}: {code} in {env}"); - } - // The takeover's own advisory about the patched cache-dir archive, - // as it always was: the per-package takeover's event says the - // vendored copy shadows it for now, the eject passes on its - // restore's warning. - let archive = committed.display().to_string(); - if takeover == ["vendor"] { - let details = warnings_with_code(&env, "upstream_gem_stale_cache"); - assert!( - details.len() == 1 && details[0].contains(&archive), - "{takeover:?}: the eject names the archive: {env}" - ); - } else { - let notice = env["events"] - .as_array() - .into_iter() - .flatten() - .find(|e| e["errorCode"] == "upstream_gem_stale_cache") - .unwrap_or_else(|| panic!("{takeover:?}: the takeover names the archive: {env}")); - assert!( - notice["reason"].as_str().is_some_and(|r| { - r.contains("while the gem stays vendored") && r.contains(&archive) - }), - "{takeover:?}: {notice}" - ); - } - } -} - -/// A project whose gem went hosted, then vendored: the hosted scan -/// replaced the project's installed copy and its gem-home archive with the -/// patched build, and the takeover (`scan --mode vendored`) left them -/// alone. Returns the installed gem dir and that archive. -async fn hosted_then_vendored(server: &MockServer, proj: &Path) -> (PathBuf, PathBuf) { +/// The record judges, it does not assume: an installed copy that is still +/// the upstream gem (the scan was told not to refresh it) is left alone in +/// a home with no `cache/` dir too, with no warning and no gem download. +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_leaves_an_upstream_install_in_a_pruned_home_alone() { + let server = MockServer::start().await; let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); - mount_api_for(server, None, &sha256_of(&patched)).await; - serve_patched_gem(server, patched.clone()).await; - serve_upstream_gem(server, &upstream).await; - mount_vendored_grant(server, &patched).await; - std::fs::create_dir_all(proj).unwrap(); - write_manifest_pair(proj); - let home = project_home(proj); - let gem_dir = install_real_gem(&home, UPSTREAM_LIB); - let archive = home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem")); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (_, home) = hosted_with_pruned_home_cache(&server, &proj, false).await; + let before = snapshot(&home); + let asked_before = server.received_requests().await.unwrap().len(); - let uri = server.uri(); - let (code, _, stderr) = common::run_with_env(proj, &scan_args(proj, &uri, &["--json"]), &[]); - assert_eq!(code, 0, "hosted scan:\n{stderr}"); - std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); - let (code, stdout, stderr) = unwind_run( - proj, - &uri, - &["scan", "--mode", "vendored", "--yes", "--json"], + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &["rollback", "--yes", "--json"]); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert_eq!(snapshot(&home), before, "nothing changed"); + assert!( + details_with_code(&env, "upstream_gem_install_refreshed").is_empty() + && details_with_code(&env, "upstream_gem_stale_install").is_empty(), + "{env}" ); - assert_eq!(code, 0, "takeover:\n{stdout}\n{stderr}"); - let gemfile = std::fs::read_to_string(proj.join("Gemfile")).unwrap(); assert!( - gemfile.contains(".socket/vendor/gem/"), - "premise:\n{gemfile}" + gem_downloads_since(&server, asked_before).await.is_empty(), + "no gem was downloaded" ); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise"); - assert_eq!(std::fs::read(&archive).unwrap(), patched, "premise"); - (gem_dir, archive) } -/// Run `args` in `proj` against the mock API, with rubygems.org's stand-in. -fn unwind_run(proj: &Path, uri: &str, args: &[&str]) -> (i32, String, String) { - unwind_run_with_registry(proj, uri, args, &format!("{uri}/upstream")) -} - -/// [`unwind_run`], with `rubygems` as the gem registry (`SOCKET_RUBYGEMS_URL`). -fn unwind_run_with_registry( - proj: &Path, - uri: &str, - args: &[&str], - rubygems: &str, -) -> (i32, String, String) { - let mut args = args.to_vec(); - args.extend([ - "--cwd", - proj.to_str().unwrap(), - "--api-url", - uri, - "--org", - ORG, - "--api-token", - "fake", - "--patch-server-url", - uri, - ]); - common::run_with_env(proj, &args, &[("SOCKET_RUBYGEMS_URL", rubygems)]) +/// A project whose `Gemfile` names a private gem mirror as its source +/// (`source ""`), so the lock resolves the gem from that remote, +/// with the gem installed from it. `checksum` is the sha256 the lock's +/// `CHECKSUMS` section pins for the gem (Bundler 2.6 and later); `None` +/// writes a lock without the section. Returns the installed gem dir. +fn mirror_project(proj: &Path, mirror: &str, checksum: Option<&str>) -> PathBuf { + std::fs::create_dir_all(proj).unwrap(); + std::fs::write( + proj.join("Gemfile"), + format!("source \"{mirror}\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"), + ) + .unwrap(); + let checksums = checksum + .map(|sha| format!("CHECKSUMS\n {DEP} ({DEP_VERSION}) sha256={sha}\n\n")) + .unwrap_or_default(); + std::fs::write( + proj.join("Gemfile.lock"), + format!( + "GEM\n remote: {mirror}/\n specs:\n {DEP} ({DEP_VERSION})\n\n\ + PLATFORMS\n ruby\n\nDEPENDENCIES\n {DEP} (= {DEP_VERSION})\n\n\ + {checksums}BUNDLED WITH\n 2.6.9\n" + ), + ) + .unwrap(); + install_real_gem(&project_home(proj), UPSTREAM_LIB) } -/// The commands that unwind a vendored gem. -const VENDORED_UNWINDS: [&[&str]; 3] = [ - &["rollback", "--yes"], - &["remove", PURL, "--yes"], - &["vendor", "--revert", "--yes"], -]; - -/// #2083: once a vendored gem is unwound, Bundler loads the installed copy -/// again. If a hosted scan made that copy the patched build before the -/// gem was vendored, the unwind puts the upstream gem back, as the hosted -/// unwind does: otherwise the app keeps running the patch under an -/// upstream lock, and `bundle pristine` fails on the upstream checksum. +/// #2230: a hosted gem the lock resolves from a private mirror, under a +/// lock without `CHECKSUMS`. The unwind restores the pair, and nothing +/// gives the upstream gem's sha256, so the patched archive in the gem home +/// says nothing about the installed copy. The copy is judged by the pin's +/// patch record like one with no archive: the patched build the scan put +/// there is named with the files to remove (`bundle install` and `bundle +/// pristine` keep it otherwise), and offline it is named as a copy that +/// could not be checked. Neither is passed over in silence. #[tokio::test(flavor = "multi_thread")] -async fn vendored_unwind_restores_an_install_a_hosted_scan_patched() { - for unwind in VENDORED_UNWINDS { +async fn hosted_unwind_names_a_patched_install_from_a_mirror_without_checksums() { + const MIRROR: &str = "https://gems.example.test"; + for (offline, needles) in [ + (false, ["its patched install at", "run `bundle install`"]), + ( + true, + [ + "could not be checked against the upstream gem", + "nothing gives the sha256 of its upstream gem and `--offline` is set, so its \ + patch record was not fetched", + ], + ), + ] { let server = MockServer::start().await; + let patched = real_gem(PATCHED_LIB); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let (gem_dir, archive) = hosted_then_vendored(&server, &proj).await; + let gem_dir = mirror_project(&proj, MIRROR, None); + // The project commits its bundler cache. + let committed = proj + .join("vendor") + .join("cache") + .join(format!("{DEP}-{DEP_VERSION}.gem")); + std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); + std::fs::write(&committed, real_gem(UPSTREAM_LIB)).unwrap(); + let pair = |name: &str| std::fs::read_to_string(proj.join(name)).unwrap(); + let (gemfile, lock) = (pair("Gemfile"), pair("Gemfile.lock")); + let uri = server.uri(); + let (code, _, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise: refreshed"); + let home = project_home(&proj); + let before = snapshot(&home); + let asked_before = server.received_requests().await.unwrap().len(); - let mut args = unwind.to_vec(); - args.push("--json"); - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); - let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); - let pair = format!( - "{}{}", - std::fs::read_to_string(proj.join("Gemfile")).unwrap(), - std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap() + let mut args = vec!["rollback", "--yes", "--json"]; + if offline { + args.push("--offline"); + } + let (code, stdout, stderr) = unwind_run(&proj, &uri, &args); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("offline={offline}: not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "offline={offline}: {env}\n{stderr}"); + assert_eq!(pair("Gemfile"), gemfile, "offline={offline}"); + assert_eq!(pair("Gemfile.lock"), lock, "offline={offline}"); + assert_eq!(snapshot(&home), before, "offline={offline}: left as it is"); + let left = details_with_code(&env, "upstream_gem_stale_install"); + assert_eq!(left.len(), 1, "offline={offline}: reported: {env}"); + for needle in needles.into_iter().chain([PURL, gem_dir.to_str().unwrap()]) { + assert!( + left[0].contains(needle), + "offline={offline}: missing {needle:?}: {}", + left[0] + ); + } + // The archive in Bundler's cache dir is named too, as one nothing + // could check: the registry is not asked about another remote's gem. + let cached = details_with_code(&env, "upstream_gem_stale_cache"); + assert_eq!(cached.len(), 1, "offline={offline}: {env}"); + assert!( + cached[0].contains(committed.to_str().unwrap()) + && cached[0].contains("could not be checked against the upstream sha256"), + "offline={offline}: {}", + cached[0] ); + let asked_registry = server + .received_requests() + .await + .unwrap() + .iter() + .skip(asked_before) + .any(|request| request.url.path().starts_with("/upstream/")); assert!( - !pair.contains(".socket/vendor/") && !pair.contains("/patch-registry/"), - "{unwind:?}: the gem is back on its upstream entry:\n{pair}" - ); - assert_eq!( - installed_lib(&gem_dir), - UPSTREAM_LIB, - "{unwind:?}: the installed copy is the upstream build again: {env}" - ); - assert_eq!( - std::fs::read(&archive).unwrap(), - real_gem(UPSTREAM_LIB), - "{unwind:?}: so is the archive `bundle pristine` reinstalls from: {env}" - ); - let text = env.to_string(); - assert!( - text.contains("upstream_gem_install_refreshed") - && !text.contains("upstream_gem_stale_install"), - "{unwind:?}: {env}" - ); - // Nothing of the gem is left on its patched build (#2214). - assert!( - details_with_code(&env, "reinstall_required").is_empty(), - "{unwind:?}: {env}" + !asked_registry, + "offline={offline}: rubygems.org is not asked about another remote's gem" ); } } -/// The human run says what it replaced, after its own line for the gem, -/// and rollback's "keeps its patched bytes" note no longer counts the gem. +/// The record judges, it does not assume (#2230): an installed copy from a +/// private mirror that is still the upstream gem (the scan was told not to +/// refresh it) gets no warning after the unwind. #[tokio::test(flavor = "multi_thread")] -async fn vendored_unwind_reports_the_refresh_in_a_human_run() { - let own_lines = [ - format!("Reverted vendoring for {PURL}"), - format!("Reverted vendoring for {PURL}"), - "Reverted 1 vendored package".to_string(), - ]; - for (unwind, own_line) in VENDORED_UNWINDS.into_iter().zip(own_lines) { - let server = MockServer::start().await; - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - let (gem_dir, _) = hosted_then_vendored(&server, &proj).await; +async fn hosted_unwind_leaves_an_upstream_install_from_a_mirror_alone() { + let server = MockServer::start().await; + let patched = real_gem(PATCHED_LIB); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let gem_dir = mirror_project(&proj, "https://gems.example.test", None); + let uri = server.uri(); + let flags = ["--json", "--no-gem-install-refresh"]; + let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &flags), &[]); + assert_eq!(code, 0, "{stderr}"); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "premise"); - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), unwind); - assert_eq!(code, 0, "{unwind:?}: {stdout}\n{stderr}"); - assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "{unwind:?}"); - let replaced = format!( - "Replaced the installed copy of 1 gem with the upstream build: {DEP} {DEP_VERSION}." - ); - assert_eq!(stdout.matches(&replaced).count(), 1, "{unwind:?}: {stdout}"); - assert!(stdout.contains(&own_line), "{unwind:?}: {stdout}"); - if unwind[0] != "vendor" { - assert!( - stdout.find(&own_line) < stdout.find(&replaced), - "{unwind:?}: {stdout}" - ); - } - assert!( - !stdout.contains("patched bytes in installed trees") - && !stderr.contains("upstream_gem") - && !stderr.contains("Warning:"), - "{unwind:?}: nothing is left to warn about:\n{stdout}\n{stderr}" - ); - } + let (code, stdout, stderr) = unwind_run(&proj, &uri, &["rollback", "--yes", "--json"]); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert!( + details_with_code(&env, "upstream_gem_stale_install").is_empty(), + "{env}" + ); } -/// A copy the unwind may not or cannot refresh is left exactly as it was -/// and named with a remedy that works: `--no-gem-install-refresh`, and an -/// upstream gem that cannot be downloaded. +/// #2230: on a lock with `CHECKSUMS`, a hosted gem from a private mirror +/// can be unwound. The restore reads the gem's upstream sha256 from the +/// mirror's own compact index when `SOCKET_RUBYGEMS_URL` names that +/// server: the pair is the pre-scan pair byte for byte and the installed +/// copy is the upstream gem again. Without the setting the unwind refuses, +/// changes nothing and names the setting. #[tokio::test(flavor = "multi_thread")] -async fn vendored_unwind_names_an_install_it_leaves_on_the_patched_build() { - for (unwind, opt_out) in VENDORED_UNWINDS - .into_iter() - .flat_map(|unwind| [(unwind, true), (unwind, false)]) - { +async fn hosted_unwind_restores_a_mirror_gem_when_the_registry_setting_names_the_mirror() { + for command in HOSTED_UNWINDS { let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + // The mirror: the mock's `/upstream` tree. + serve_upstream_gem(&server, &upstream).await; + let uri = server.uri(); + let mirror = format!("{uri}/upstream"); let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let (gem_dir, archive) = hosted_then_vendored(&server, &proj).await; - let home = project_home(&proj); - let held_before = snapshot(&home); - if !opt_out { - // rubygems.org names the upstream sha256 but its download fails. - Mock::given(method("GET")) - .and(path(format!("/upstream/gems/{DEP}-{DEP_VERSION}.gem"))) - .respond_with(ResponseTemplate::new(503)) - .with_priority(1) - .mount(&server) - .await; - } + let gem_dir = mirror_project(&proj, &mirror, Some(&sha256_of(&upstream))); + let pair = |name: &str| std::fs::read_to_string(proj.join(name)).unwrap(); + let (gemfile, lock) = (pair("Gemfile"), pair("Gemfile.lock")); + let (code, _, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise: refreshed"); + let (hosted_gemfile, hosted_lock) = (pair("Gemfile"), pair("Gemfile.lock")); + assert!(hosted_lock.contains("/patch-registry/"), "{hosted_lock}"); - let mut args = unwind.to_vec(); + // rubygems.org (here: another stand-in) is not the lock's remote. + let mut args = command.to_vec(); args.push("--json"); - if opt_out { - args.push("--no-gem-install-refresh"); - } - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); - let env = common::parse_json_envelope(&stdout); - let case = format!("{unwind:?} opt_out={opt_out}"); - assert_eq!(code, 0, "{case}: {env}\nstderr:\n{stderr}"); - assert!( - snapshot(&home) == held_before, - "{case}: the gem home changed: {env}" - ); - let text = env.to_string(); - let spec = home - .join("specifications") - .join(format!("{DEP}-{DEP_VERSION}.gemspec")); + let elsewhere = format!("{uri}/elsewhere"); + let (code, stdout, stderr) = unwind_run_with_registry(&proj, &uri, &args, &elsewhere); + assert_ne!(code, 0, "{command:?}: {stdout}\n{stderr}"); + let said = format!("{stdout}\n{stderr}"); for needle in [ - "upstream_gem_stale_install", - gem_dir.to_str().unwrap(), - spec.to_str().unwrap(), - archive.to_str().unwrap(), - "bundle install", + "is not rubygems.org", + &format!("`SOCKET_RUBYGEMS_URL={mirror}`"), + "git checkout -- Gemfile Gemfile.lock", ] { - // The envelope JSON-escapes a Windows path's backslashes. - let needle = needle.replace('\\', "\\\\"); - assert!(text.contains(&needle), "{case}: no {needle:?} in {env}"); + assert!( + said.contains(needle), + "{command:?}: missing {needle:?}: {said}" + ); } + assert_eq!(pair("Gemfile"), hosted_gemfile, "{command:?}: refused"); + assert_eq!(pair("Gemfile.lock"), hosted_lock, "{command:?}: refused"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{command:?}: refused"); + + // The setting names the mirror: the remedy the refusal gave. + let (code, stdout, stderr) = unwind_run_with_registry(&proj, &uri, &args, &mirror); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("{command:?}: not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "{command:?}: {env}\n{stderr}"); + assert_eq!(pair("Gemfile"), gemfile, "{command:?}"); + assert_eq!(pair("Gemfile.lock"), lock, "{command:?}"); + assert_eq!( + installed_lib(&gem_dir), + UPSTREAM_LIB, + "{command:?}: the upstream gem is back: {env}" + ); assert!( - !text.contains("upstream_gem_install_refreshed"), - "{case}: {env}" + details_with_code(&env, "upstream_gem_stale_install").is_empty(), + "{command:?}: nothing is left on the patched build: {env}" ); } } -/// The human run of the same: one warning with the remedy as a command, -/// and rollback's reinstall note still counts the gem. +/// #2285: a mirror built with `gem generate_index` writes the sha256 in +/// its compact index as base64, which Bundler reads and pins as hex in +/// `CHECKSUMS`. With `SOCKET_RUBYGEMS_URL` naming such a mirror the +/// unwind restores the pair byte for byte and puts the upstream gem back. +/// (The URL-safe alphabet Bundler also reads is covered where the digest +/// is parsed, in the core crate's unit tests.) #[tokio::test(flavor = "multi_thread")] -async fn vendored_unwind_warns_once_in_a_human_run() { - for unwind in VENDORED_UNWINDS { +async fn hosted_unwind_restores_a_mirror_gem_whose_index_checksum_is_base64() { + use base64::Engine as _; + use sha2::Digest as _; + for command in HOSTED_UNWINDS { let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + let digest = + base64::engine::general_purpose::STANDARD.encode(sha2::Sha256::digest(&upstream)); + assert_eq!(digest.len(), 44, "premise: 43 digits and one `=`"); + serve_upstream_gem_indexed_as(&server, &upstream, &digest).await; + let uri = server.uri(); + let mirror = format!("{uri}/upstream"); let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let (gem_dir, archive) = hosted_then_vendored(&server, &proj).await; - - let mut args = unwind.to_vec(); - args.push("--no-gem-install-refresh"); - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); - assert_eq!(code, 0, "{unwind:?}: {stdout}\n{stderr}"); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{unwind:?}"); - let warning = "Warning: 1 gem still holds the patched build on disk after the switch \ - back to the upstream registry"; - assert_eq!(stderr.matches(warning).count(), 1, "{unwind:?}: {stderr}"); + let gem_dir = mirror_project(&proj, &mirror, Some(&sha256_of(&upstream))); + let pair = |name: &str| std::fs::read_to_string(proj.join(name)).unwrap(); + let (gemfile, lock) = (pair("Gemfile"), pair("Gemfile.lock")); + let (code, _, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "{command:?}: {stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise: refreshed"); assert!( - stderr.contains(&format!( - "rm -f {}", - shell_word( - &project_home(&proj) - .join("specifications") - .join(format!("{DEP}-{DEP_VERSION}.gemspec")) - ) - )) && stderr.contains(&format!("{} && bundle install", shell_word(&archive))), - "{unwind:?}: {stderr}" + pair("Gemfile.lock").contains("/patch-registry/"), + "{command:?}" + ); + + let mut args = command.to_vec(); + args.push("--json"); + let (code, stdout, stderr) = unwind_run_with_registry(&proj, &uri, &args, &mirror); + let env: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|e| panic!("{command:?}: not JSON: {e}\n{stdout}\n{stderr}")); + assert_eq!(code, 0, "{command:?}: {env}\n{stderr}"); + assert_eq!(pair("Gemfile"), gemfile, "{command:?}"); + assert_eq!(pair("Gemfile.lock"), lock, "{command:?}"); + assert_eq!( + installed_lib(&gem_dir), + UPSTREAM_LIB, + "{command:?}: the upstream gem is back: {env}" ); assert!( - !stderr.contains("Re-run"), - "{unwind:?}: a second unwind has nothing to unwind: {stderr}" + details_with_code(&env, "upstream_gem_stale_install").is_empty(), + "{command:?}: nothing is left on the patched build: {env}" ); - assert!(!stdout.contains("Replaced the installed copy"), "{stdout}"); - if unwind[0] == "rollback" { - assert!( - stdout.contains("1 unwired package keeps its patched bytes"), - "{stdout}" - ); - } } } -/// A registry that is refused (plain http, and not this machine) is not -/// asked what the upstream gem is, in a vendored unwind as in a hosted one: -/// the installed copy is left exactly as it was and reported as one that -/// could not be checked, with the reason, not passed over while it still -/// holds the patched build. -#[tokio::test(flavor = "multi_thread")] -async fn vendored_unwind_reports_the_copy_a_refused_registry_left_unchecked() { - for unwind in VENDORED_UNWINDS { - let server = MockServer::start().await; - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - let (gem_dir, _) = hosted_then_vendored(&server, &proj).await; - let home = project_home(&proj); - let held_before = snapshot(&home); - let asked_before = server.received_requests().await.unwrap().len(); +/// The vendored half of the patch API for the fixture's patch: the grant +/// names the patched `.gem` and the stub gemspec a path source loads, each +/// with its sha512, beside the hosted registry override. Priority 1, so it +/// answers `patches/package` in place of [`mount_api_for`]'s hosted-only +/// grant. +async fn mount_vendored_grant(server: &MockServer, patched: &[u8]) { + mount_vendored_grant_of(server, UUID, patched).await; +} - let mut args = unwind.to_vec(); - args.push("--json"); - // Refused before any request: nothing is looked up or sent. - let (code, stdout, stderr) = unwind_run_with_registry( - &proj, - &server.uri(), - &args, - "http://gemstash.example.test:9292", - ); - let env = common::parse_json_envelope(&stdout); - let case = format!("{unwind:?}"); - assert_eq!(code, 0, "{case}: {env}\nstderr:\n{stderr}"); - assert!( - snapshot(&home) == held_before, - "{case}: the gem home changed: {env}" - ); - let text = env.to_string(); - for needle in [ - "upstream_gem_stale_install", - "could not be checked against the upstream gem", - "`http://gemstash.example.test:9292` is not an https URL", - "set it to an https URL", - gem_dir.to_str().unwrap(), - ] { - // The envelope JSON-escapes a Windows path's backslashes. - let needle = needle.replace('\\', "\\\\"); - assert!(text.contains(&needle), "{case}: no {needle:?} in {env}"); +/// [`mount_vendored_grant`] for the patch `uuid`. +async fn mount_vendored_grant_of(server: &MockServer, uuid: &str, patched: &[u8]) { + use base64::Engine as _; + use sha2::Digest as _; + let sri = |bytes: &[u8]| { + format!( + "sha512-{}", + base64::engine::general_purpose::STANDARD.encode(sha2::Sha512::digest(bytes)) + ) + }; + let stub = format!( + "Gem::Specification.new do |s|\n s.name = \"{DEP}\".freeze\n s.version = \ + \"{DEP_VERSION}\".freeze\n s.authors = [\"e2e\".freeze]\n s.summary = \ + \"fixture\".freeze\n s.files = [\"lib/stale_probe_gem.rb\".freeze]\n s.require_paths \ + = [\"lib\".freeze]\nend\n" + ) + .into_bytes(); + let leaf = format!("{DEP}-{DEP_VERSION}"); + let base = format!("/artifacts/{uuid}"); + let gem_url = format!("{}{base}/{leaf}.gem", server.uri()); + let stub_url = format!("{}{base}/{leaf}.gemspec", server.uri()); + 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": gem_url, + "purl": PURL, + "artifacts": [ + { "kind": "tarball", "url": gem_url, + "integrity": { "sha512": sri(patched), "sha256": sha256_of(patched) } }, + { "kind": "gem-stub-gemspec", "url": stub_url, + "integrity": { "sha512": sri(&stub) } } + ], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": format!("{}/patch-registry/gem/{TOKEN}/{uuid}/", server.uri()), + "identifiers": { + "name": DEP, + "version": DEP_VERSION, + "gemChecksumSha256": sha256_of(patched), + } + } + } + } + }))) + .with_priority(1) + .mount(server) + .await; + for (file, bytes) in [ + (format!("{leaf}.gem"), patched.to_vec()), + (format!("{leaf}.gemspec"), stub), + ] { + Mock::given(method("GET")) + .and(path(format!("{base}/{file}"))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .mount(server) + .await; + } +} + +/// Every regular file under `dir`, relative, with its bytes. +fn snapshot(dir: &Path) -> std::collections::BTreeMap> { + fn walk(root: &Path, dir: &Path, out: &mut std::collections::BTreeMap>) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + walk(root, &path, out); + } else { + out.insert( + path.strip_prefix(root).unwrap().to_path_buf(), + std::fs::read(&path).unwrap(), + ); + } } - assert!( - !text.contains("upstream_gem_install_refreshed"), - "{case}: {env}" - ); - let upstream_asked = server - .received_requests() - .await - .unwrap() - .iter() - .skip(asked_before) - .any(|request| request.url.path().starts_with("/upstream/")); - assert!(!upstream_asked, "{case}: the unwind asked a registry"); } + let mut out = std::collections::BTreeMap::new(); + walk(dir, dir, &mut out); + out } -/// A gem that was only ever vendored still has the upstream build -/// installed: its unwind changes nothing in the gem home, downloads no -/// gem and raises nothing about it. +/// A hosted → vendored takeover (`get --mode vendored`, `scan --mode +/// vendored`, and plain `vendor`, which ejects the lock's hosted pins) puts +/// the gem back on its upstream entry only on its way to the `path:` +/// source, which is what Bundler loads from then on. The gems +/// Bundler already holds are unused leftovers: the takeover must not +/// refresh them (the patched installed copy would become an unpatched one +/// that `vex` then reports against the vendored artifact) and must download +/// no gem for them (vendored mode needs no registry). The installed gem, +/// its cached archive and the cache-dir archive stay byte-identical, and +/// the takeover's own advisory about the cache-dir archive is unchanged. #[tokio::test(flavor = "multi_thread")] -async fn vendored_unwind_leaves_an_upstream_install_alone() { - for unwind in VENDORED_UNWINDS { +async fn refresh_is_not_run_by_a_hosted_to_vendored_takeover() { + let takeovers: [&[&str]; 3] = [ + &["get", UUID, "--mode", "vendored"], + &["scan", "--mode", "vendored"], + &["vendor"], + ]; + for takeover in takeovers { let server = MockServer::start().await; let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + // Everything a refresh back to upstream would need is there to use. serve_upstream_gem(&server, &upstream).await; mount_vendored_grant(&server, &patched).await; let tmp = tempfile::tempdir().unwrap(); @@ -4945,25 +5746,64 @@ async fn vendored_unwind_leaves_an_upstream_install_alone() { std::fs::create_dir_all(&proj).unwrap(); write_manifest_pair(&proj); let home = project_home(&proj); - install_real_gem(&home, UPSTREAM_LIB); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let leaf = format!("{DEP}-{DEP_VERSION}"); + let committed = proj + .join("vendor") + .join("cache") + .join(format!("{leaf}.gem")); + std::fs::create_dir_all(committed.parent().unwrap()).unwrap(); + std::fs::write(&committed, &upstream).unwrap(); + + // The hosted state: the scan pins the gem and refreshes the + // project's copies; the lock is then as `bundle install` leaves it. let uri = server.uri(); - let (code, stdout, stderr) = unwind_run( - &proj, - &uri, - &["scan", "--mode", "vendored", "--yes", "--json"], + let (code, _, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "{takeover:?}: hosted scan:\n{stderr}"); + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + assert_eq!( + installed_lib(&gem_dir), + PATCHED_LIB, + "{takeover:?}: premise" ); - assert_eq!(code, 0, "vendored scan:\n{stdout}\n{stderr}"); - let held_before = snapshot(&home); + assert_eq!( + std::fs::read(&committed).unwrap(), + patched, + "{takeover:?}: premise" + ); + let held_before = (snapshot(&home), snapshot(committed.parent().unwrap())); let requests_before = server.received_requests().await.unwrap_or_default().len(); - let mut args = unwind.to_vec(); - args.push("--json"); - let (code, stdout, stderr) = unwind_run(&proj, &uri, &args); + let rubygems = format!("{uri}/upstream"); + let mut args = takeover.to_vec(); + args.extend([ + "--yes", + "--json", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + uri.as_str(), + ]); + let (code, stdout, stderr) = + common::run_with_env(&proj, &args, &[("SOCKET_RUBYGEMS_URL", rubygems.as_str())]); let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); + assert_eq!(code, 0, "{takeover:?}: {env}\nstderr:\n{stderr}"); + let gemfile = std::fs::read_to_string(proj.join("Gemfile")).unwrap(); assert!( - snapshot(&home) == held_before, - "{unwind:?}: the gem home changed: {env}" + gemfile.contains(".socket/vendor/gem/") && !gemfile.contains("/patch-registry/"), + "{takeover:?}: the takeover vendored the gem:\n{gemfile}" + ); + + assert!( + (snapshot(&home), snapshot(committed.parent().unwrap())) == held_before, + "{takeover:?}: the takeover changed a gem Bundler already held: {env}" ); let fetched: Vec = server.received_requests().await.unwrap_or_default() [requests_before..] @@ -4971,207 +5811,67 @@ async fn vendored_unwind_leaves_an_upstream_install_alone() { .map(|r| r.url.path().to_string()) .filter(|path| path.contains("/gems/")) .collect(); - assert!(fetched.is_empty(), "{unwind:?}: downloaded {fetched:?}"); + assert!( + fetched.is_empty(), + "{takeover:?}: the takeover downloaded a gem for the installed copies: {fetched:?}" + ); let text = env.to_string(); for code in [ "upstream_gem_install_refreshed", "upstream_gem_stale_install", + "redirect_gem_install_refreshed", + "redirect_gem_stale_install", ] { - assert!(!text.contains(code), "{unwind:?}: {code} in {env}"); + assert!(!text.contains(code), "{takeover:?}: {code} in {env}"); } - } -} - -/// #2214: rollback's "keeps its patched bytes" note, and the -/// `reinstall_required` warning `--json` carries for it, are about the -/// installed trees. Vendored mode never touches a gem home, so a gem that -/// was only ever vendored has nothing patched there once its pair is -/// restored: its installed copy is the upstream build, which its archive -/// in the gem home and the ledger record's pre-patch hashes prove. -#[tokio::test(flavor = "multi_thread")] -async fn rollback_of_an_only_vendored_gem_names_no_reinstall() { - for json in [true, false] { - let case = format!("json={json}"); - let server = MockServer::start().await; - let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); - mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_upstream_gem(&server, &upstream).await; - mount_vendored_grant(&server, &patched).await; - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - std::fs::create_dir_all(&proj).unwrap(); - write_manifest_pair(&proj); - let pair_before = ( - std::fs::read(proj.join("Gemfile")).unwrap(), - std::fs::read(proj.join("Gemfile.lock")).unwrap(), - ); - let home = project_home(&proj); - install_real_gem(&home, UPSTREAM_LIB); - let uri = server.uri(); - let (code, stdout, stderr) = unwind_run( - &proj, - &uri, - &["scan", "--mode", "vendored", "--yes", "--json"], - ); - assert_eq!(code, 0, "{case}: vendored scan:\n{stdout}\n{stderr}"); - assert!( - std::fs::read_to_string(proj.join("Gemfile")) - .unwrap() - .contains(".socket/vendor/gem/"), - "{case}: premise: the gem is vendored" - ); - let held_before = snapshot(&home); - - let mut args = vec!["rollback", "--yes"]; - if json { - args.push("--json"); - } - let (code, stdout, stderr) = unwind_run(&proj, &uri, &args); - assert_eq!(code, 0, "{case}:\n{stdout}\n{stderr}"); - let pair_after = ( - std::fs::read(proj.join("Gemfile")).unwrap(), - std::fs::read(proj.join("Gemfile.lock")).unwrap(), - ); - assert!(pair_after == pair_before, "{case}: the pair is restored"); - assert!( - snapshot(&home) == held_before, - "{case}: the gem home is untouched" - ); - if json { - let env = common::parse_json_envelope(&stdout); - assert_eq!(env["status"], "success", "{case}: {env}"); - assert!( - details_with_code(&env, "reinstall_required").is_empty(), - "{case}: no installed tree holds patched bytes: {env}" - ); - } else { - assert!( - stdout.contains(&format!("Reverted vendoring for {PURL}")), - "{case}:\n{stdout}" - ); + // The takeover's own advisory about the patched cache-dir archive, + // as it always was: the per-package takeover's event says the + // vendored copy shadows it for now, the eject passes on its + // restore's warning. + let archive = committed.display().to_string(); + if takeover == ["vendor"] { + let details = warnings_with_code(&env, "upstream_gem_stale_cache"); assert!( - !stdout.contains("patched bytes in installed trees") - && !stderr.contains("Warning:"), - "{case}: nothing is left to reinstall:\n{stdout}\n{stderr}" - ); - } - } -} - -/// The other side of #2214: an installed copy the unwind could not prove -/// to be the upstream build is still counted. Here agent mode patched the -/// copy before the gem was vendored, and the gem comes from a remote the -/// unwind does not judge, so the patched files stay. -#[tokio::test(flavor = "multi_thread")] -async fn rollback_still_names_a_reinstall_for_an_install_it_could_not_judge() { - for json in [true, false] { - let server = MockServer::start().await; - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - let (gem_dir, _) = - agent_then_vendored_from(&server, &proj, "https://gems.example.test").await; - - let mut args = vec!["rollback", "--yes"]; - if json { - args.push("--json"); - } - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); - assert_eq!(code, 0, "json={json}:\n{stdout}\n{stderr}"); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "json={json}: premise"); - if json { - let env = common::parse_json_envelope(&stdout); - assert_eq!( - details_with_code(&env, "reinstall_required").len(), - 1, - "{env}" + details.len() == 1 && details[0].contains(&archive), + "{takeover:?}: the eject names the archive: {env}" ); } else { + let notice = env["events"] + .as_array() + .into_iter() + .flatten() + .find(|e| e["errorCode"] == "upstream_gem_stale_cache") + .unwrap_or_else(|| panic!("{takeover:?}: the takeover names the archive: {env}")); assert!( - stdout.contains("1 unwired package keeps its patched bytes in installed trees"), - "{stdout}\n{stderr}" + notice["reason"].as_str().is_some_and(|r| { + r.contains("while the gem stays vendored") && r.contains(&archive) + }), + "{takeover:?}: {notice}" ); } } } -/// #2214, a copy the gem home's archive alone would call upstream: agent -/// mode patched it in place, beside the upstream archive, and standalone -/// `vendor` then vendored the gem from the manifest. Rollback may only -/// drop its reinstall warning when the installed copy no longer holds the -/// patched file. -#[tokio::test(flavor = "multi_thread")] -async fn rollback_never_calls_an_agent_patched_install_upstream() { - let server = MockServer::start().await; - let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); - mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_upstream_gem(&server, &upstream).await; - mount_vendored_grant(&server, &patched).await; - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - std::fs::create_dir_all(&proj).unwrap(); - write_manifest_pair(&proj); - let home = project_home(&proj); - let gem_dir = agent_patched_install(&proj, &home); - let uri = server.uri(); - let (code, stdout, stderr) = unwind_run(&proj, &uri, &["vendor", "--yes", "--json"]); - assert_eq!(code, 0, "vendor:\n{stdout}\n{stderr}"); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise"); - assert_eq!( - std::fs::read(home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem"))).unwrap(), - upstream, - "premise: the archive beside it is the upstream one" - ); - - let (code, stdout, stderr) = unwind_run(&proj, &uri, &["rollback", "--yes", "--json"]); - let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); - assert_eq!( - installed_lib(&gem_dir), - PATCHED_LIB, - "premise: this rollback leaves the installed copy patched: {env}" - ); - assert_eq!( - details_with_code(&env, "reinstall_required").len(), - 1, - "the copy is left patched, so the warning stays: {env}" - ); -} - -/// A project whose gem agent mode patched in place and a vendored scan -/// then took over: the takeover moved the manifest record into the vendor -/// ledger and left the installed copy (patched files, upstream archive in -/// the gem home's `cache/`) alone. Returns the installed gem dir and that -/// archive. -async fn agent_then_vendored(server: &MockServer, proj: &Path) -> (PathBuf, PathBuf) { - agent_then_vendored_from(server, proj, "https://rubygems.org").await -} - -/// [`agent_then_vendored`], with `remote` as the pair's gem source. -async fn agent_then_vendored_from( - server: &MockServer, - proj: &Path, - remote: &str, -) -> (PathBuf, PathBuf) { +/// A project whose gem went hosted, then vendored: the hosted scan +/// replaced the project's installed copy and its gem-home archive with the +/// patched build, and the takeover (`scan --mode vendored`) left them +/// alone. Returns the installed gem dir and that archive. +async fn hosted_then_vendored(server: &MockServer, proj: &Path) -> (PathBuf, PathBuf) { let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); mount_api_for(server, None, &sha256_of(&patched)).await; + serve_patched_gem(server, patched.clone()).await; serve_upstream_gem(server, &upstream).await; mount_vendored_grant(server, &patched).await; std::fs::create_dir_all(proj).unwrap(); write_manifest_pair(proj); - for file in ["Gemfile", "Gemfile.lock"] { - let text = std::fs::read_to_string(proj.join(file)).unwrap(); - assert!(text.contains("https://rubygems.org"), "premise: {text}"); - std::fs::write( - proj.join(file), - text.replace("https://rubygems.org", remote), - ) - .unwrap(); - } let home = project_home(proj); - let gem_dir = agent_patched_install(proj, &home); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); let archive = home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem")); let uri = server.uri(); + let (code, _, stderr) = common::run_with_env(proj, &scan_args(proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "hosted scan:\n{stderr}"); + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); let (code, stdout, stderr) = unwind_run( proj, &uri, @@ -5183,45 +5883,58 @@ async fn agent_then_vendored_from( gemfile.contains(".socket/vendor/gem/"), "premise:\n{gemfile}" ); - let manifest = std::fs::read_to_string(proj.join(".socket").join("manifest.json")).unwrap(); - assert!( - stdout.contains("vendor_manifest_record_migrated") && !manifest.contains(PURL), - "premise: the takeover owns the record now:\n{stdout}\n{manifest}" - ); assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise"); - assert_eq!(std::fs::read(&archive).unwrap(), upstream, "premise"); + assert_eq!(std::fs::read(&archive).unwrap(), patched, "premise"); (gem_dir, archive) } -/// The gem downloads (`/gems/.gem`, from any registry) among the -/// requests `server` received after the first `skip`. -async fn gem_downloads_since(server: &MockServer, skip: usize) -> Vec { - server - .received_requests() - .await - .unwrap_or_default() - .iter() - .skip(skip) - .map(|request| request.url.path().to_string()) - .filter(|path| path.contains("/gems/")) - .collect() +/// Run `args` in `proj` against the mock API, with rubygems.org's stand-in. +fn unwind_run(proj: &Path, uri: &str, args: &[&str]) -> (i32, String, String) { + unwind_run_with_registry(proj, uri, args, &format!("{uri}/upstream")) } -/// #2093: a vendored takeover of a gem agent mode patched in place drops -/// the manifest record and keeps the patched files in the installed copy. -/// Once the vendored gem is unwound Bundler loads that copy again, and no -/// record is left that could undo the patch. The unwind therefore puts -/// the upstream gem back, from the upstream archive RubyGems kept in the -/// gem home (nothing is downloaded), and leaves nothing of agent mode's -/// in the gem dir. +/// [`unwind_run`], with `rubygems` as the gem registry (`SOCKET_RUBYGEMS_URL`). +fn unwind_run_with_registry( + proj: &Path, + uri: &str, + args: &[&str], + rubygems: &str, +) -> (i32, String, String) { + let mut args = args.to_vec(); + args.extend([ + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri, + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + uri, + ]); + common::run_with_env(proj, &args, &[("SOCKET_RUBYGEMS_URL", rubygems)]) +} + +/// The commands that unwind a vendored gem. +const VENDORED_UNWINDS: [&[&str]; 3] = [ + &["rollback", "--yes"], + &["remove", PURL, "--yes"], + &["vendor", "--revert", "--yes"], +]; + +/// #2083: once a vendored gem is unwound, Bundler loads the installed copy +/// again. If a hosted scan made that copy the patched build before the +/// gem was vendored, the unwind puts the upstream gem back, as the hosted +/// unwind does: otherwise the app keeps running the patch under an +/// upstream lock, and `bundle pristine` fails on the upstream checksum. #[tokio::test(flavor = "multi_thread")] -async fn vendored_unwind_restores_an_install_agent_mode_patched() { +async fn vendored_unwind_restores_an_install_a_hosted_scan_patched() { for unwind in VENDORED_UNWINDS { let server = MockServer::start().await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let (gem_dir, archive) = agent_then_vendored(&server, &proj).await; - let asked_before = server.received_requests().await.unwrap().len(); + let (gem_dir, archive) = hosted_then_vendored(&server, &proj).await; let mut args = unwind.to_vec(); args.push("--json"); @@ -5234,7 +5947,7 @@ async fn vendored_unwind_restores_an_install_agent_mode_patched() { std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap() ); assert!( - !pair.contains(".socket/vendor/"), + !pair.contains(".socket/vendor/") && !pair.contains("/patch-registry/"), "{unwind:?}: the gem is back on its upstream entry:\n{pair}" ); assert_eq!( @@ -5242,70 +5955,68 @@ async fn vendored_unwind_restores_an_install_agent_mode_patched() { UPSTREAM_LIB, "{unwind:?}: the installed copy is the upstream build again: {env}" ); - assert!( - !gem_dir.join(".socket-patch-kept").exists(), - "{unwind:?}: the copy is a fresh install of the upstream gem: {env}" - ); assert_eq!( std::fs::read(&archive).unwrap(), real_gem(UPSTREAM_LIB), - "{unwind:?}: the upstream archive is untouched: {env}" + "{unwind:?}: so is the archive `bundle pristine` reinstalls from: {env}" ); - let fetched = gem_downloads_since(&server, asked_before).await; - assert!(fetched.is_empty(), "{unwind:?}: downloaded {fetched:?}"); let text = env.to_string(); assert!( text.contains("upstream_gem_install_refreshed") && !text.contains("upstream_gem_stale_install"), "{unwind:?}: {env}" ); + // Nothing of the gem is left on its patched build (#2214). + assert!( + details_with_code(&env, "reinstall_required").is_empty(), + "{unwind:?}: {env}" + ); } } -/// The same with the gem home's `cache/` pruned (Bundler 4.1 `prune`, a -/// Docker image's `rm -rf ruby/*/cache`): the ledger's record still proves -/// the installed files are the patched ones, so the upstream gem is -/// downloaded and installed over them. +/// The human run says what it replaced, after its own line for the gem, +/// and rollback's "keeps its patched bytes" note no longer counts the gem. #[tokio::test(flavor = "multi_thread")] -async fn vendored_unwind_restores_an_agent_patched_install_without_its_archive() { - for unwind in VENDORED_UNWINDS { +async fn vendored_unwind_reports_the_refresh_in_a_human_run() { + let own_lines = [ + format!("Reverted vendoring for {PURL}"), + format!("Reverted vendoring for {PURL}"), + "Reverted 1 vendored package".to_string(), + ]; + for (unwind, own_line) in VENDORED_UNWINDS.into_iter().zip(own_lines) { let server = MockServer::start().await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let (gem_dir, archive) = agent_then_vendored(&server, &proj).await; - std::fs::remove_dir_all(archive.parent().unwrap()).unwrap(); - let asked_before = server.received_requests().await.unwrap().len(); + let (gem_dir, _) = hosted_then_vendored(&server, &proj).await; - let mut args = unwind.to_vec(); - args.push("--json"); - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); - let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); - assert_eq!( - installed_lib(&gem_dir), - UPSTREAM_LIB, - "{unwind:?}: the installed copy is the upstream build again: {env}" - ); - assert_eq!( - gem_downloads_since(&server, asked_before).await, - [format!("/upstream/gems/{DEP}-{DEP_VERSION}.gem")], - "{unwind:?}: one download, of the upstream gem" + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), unwind); + assert_eq!(code, 0, "{unwind:?}: {stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "{unwind:?}"); + let replaced = format!( + "Replaced the installed copy of 1 gem with the upstream build: {DEP} {DEP_VERSION}." ); - let text = env.to_string(); + assert_eq!(stdout.matches(&replaced).count(), 1, "{unwind:?}: {stdout}"); + assert!(stdout.contains(&own_line), "{unwind:?}: {stdout}"); + if unwind[0] != "vendor" { + assert!( + stdout.find(&own_line) < stdout.find(&replaced), + "{unwind:?}: {stdout}" + ); + } assert!( - text.contains("upstream_gem_install_refreshed") - && !text.contains("upstream_gem_stale_install"), - "{unwind:?}: {env}" + !stdout.contains("patched bytes in installed trees") + && !stderr.contains("upstream_gem") + && !stderr.contains("Warning:"), + "{unwind:?}: nothing is left to warn about:\n{stdout}\n{stderr}" ); } } -/// An agent-patched copy the unwind may not replace -/// (`--no-gem-install-refresh`) or cannot (`--offline` with the archive -/// pruned) is left exactly as it was and named with the files to remove, -/// not passed over as if it were the upstream build. +/// A copy the unwind may not or cannot refresh is left exactly as it was +/// and named with a remedy that works: `--no-gem-install-refresh`, and an +/// upstream gem that cannot be downloaded. #[tokio::test(flavor = "multi_thread")] -async fn vendored_unwind_names_an_agent_patched_install_it_leaves() { +async fn vendored_unwind_names_an_install_it_leaves_on_the_patched_build() { for (unwind, opt_out) in VENDORED_UNWINDS .into_iter() .flat_map(|unwind| [(unwind, true), (unwind, false)]) @@ -5313,20 +6024,24 @@ async fn vendored_unwind_names_an_agent_patched_install_it_leaves() { let server = MockServer::start().await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let (gem_dir, archive) = agent_then_vendored(&server, &proj).await; + let (gem_dir, archive) = hosted_then_vendored(&server, &proj).await; let home = project_home(&proj); + let held_before = snapshot(&home); if !opt_out { - std::fs::remove_dir_all(archive.parent().unwrap()).unwrap(); + // rubygems.org names the upstream sha256 but its download fails. + Mock::given(method("GET")) + .and(path(format!("/upstream/gems/{DEP}-{DEP_VERSION}.gem"))) + .respond_with(ResponseTemplate::new(503)) + .with_priority(1) + .mount(&server) + .await; } - let held_before = snapshot(&home); let mut args = unwind.to_vec(); args.push("--json"); - args.push(if opt_out { - "--no-gem-install-refresh" - } else { - "--offline" - }); + if opt_out { + args.push("--no-gem-install-refresh"); + } let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); let env = common::parse_json_envelope(&stdout); let case = format!("{unwind:?} opt_out={opt_out}"); @@ -5343,6 +6058,7 @@ async fn vendored_unwind_names_an_agent_patched_install_it_leaves() { "upstream_gem_stale_install", gem_dir.to_str().unwrap(), spec.to_str().unwrap(), + archive.to_str().unwrap(), "bundle install", ] { // The envelope JSON-escapes a Windows path's backslashes. @@ -5356,591 +6072,1804 @@ async fn vendored_unwind_names_an_agent_patched_install_it_leaves() { } } -/// A manifest record for the gem means its in-place patch is agent mode's -/// and still on record, so a vendored unwind does not end it: -/// `vendor --revert` undoes the vendoring only and leaves the installed -/// copy as it is. Two ways there: standalone `vendor`, which works from -/// the manifest and keeps the record in it, and an agent-mode record -/// written again after a vendored takeover. +/// The human run of the same: one warning with the remedy as a command, +/// and rollback's reinstall note still counts the gem. #[tokio::test(flavor = "multi_thread")] -async fn vendored_unwind_leaves_an_install_the_manifest_still_records() { - for standalone in [true, false] { +async fn vendored_unwind_warns_once_in_a_human_run() { + for unwind in VENDORED_UNWINDS { let server = MockServer::start().await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let home = project_home(&proj); - let uri = server.uri(); - let gem_dir = if standalone { - let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); - mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_upstream_gem(&server, &upstream).await; - mount_vendored_grant(&server, &patched).await; - std::fs::create_dir_all(&proj).unwrap(); - write_manifest_pair(&proj); - let gem_dir = agent_patched_install(&proj, &home); - let (code, stdout, stderr) = unwind_run(&proj, &uri, &["vendor", "--yes", "--json"]); - assert_eq!(code, 0, "vendor:\n{stdout}\n{stderr}"); - gem_dir - } else { - let (gem_dir, _) = agent_then_vendored(&server, &proj).await; - common::write_in_place_patch_record( - &proj.join(".socket"), - PURL, - UUID, - "lib/stale_probe_gem.rb", - UPSTREAM_LIB.as_bytes(), - PATCHED_LIB.as_bytes(), - ); - gem_dir - }; - let case = format!("standalone={standalone}"); - let manifest_path = proj.join(".socket").join("manifest.json"); + let (gem_dir, archive) = hosted_then_vendored(&server, &proj).await; + + let mut args = unwind.to_vec(); + args.push("--no-gem-install-refresh"); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + assert_eq!(code, 0, "{unwind:?}: {stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{unwind:?}"); + let warning = "Warning: 1 gem still holds the patched build on disk after the switch \ + back to the upstream registry"; + assert_eq!(stderr.matches(warning).count(), 1, "{unwind:?}: {stderr}"); assert!( - std::fs::read_to_string(proj.join("Gemfile")) - .unwrap() - .contains(".socket/vendor/gem/") - && std::fs::read_to_string(&manifest_path) - .unwrap() - .contains(PURL), - "{case}: premise: vendored, with the record in the manifest" + stderr.contains(&format!( + "rm -f {}", + shell_word( + &project_home(&proj) + .join("specifications") + .join(format!("{DEP}-{DEP_VERSION}.gemspec")) + ) + )) && stderr.contains(&format!("{} && bundle install", shell_word(&archive))), + "{unwind:?}: {stderr}" + ); + assert!( + !stderr.contains("Re-run"), + "{unwind:?}: a second unwind has nothing to unwind: {stderr}" ); + assert!(!stdout.contains("Replaced the installed copy"), "{stdout}"); + if unwind[0] == "rollback" { + assert!( + stdout.contains("1 unwired package keeps its patched bytes"), + "{stdout}" + ); + } + } +} + +/// A registry that is refused (plain http, and not this machine) is not +/// asked what the upstream gem is, in a vendored unwind as in a hosted one: +/// the installed copy is left exactly as it was and reported as one that +/// could not be checked, with the reason, not passed over while it still +/// holds the patched build. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_reports_the_copy_a_refused_registry_left_unchecked() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, _) = hosted_then_vendored(&server, &proj).await; + let home = project_home(&proj); let held_before = snapshot(&home); + let asked_before = server.received_requests().await.unwrap().len(); - let (code, stdout, stderr) = - unwind_run(&proj, &uri, &["vendor", "--revert", "--yes", "--json"]); + let mut args = unwind.to_vec(); + args.push("--json"); + // Refused before any request: nothing is looked up or sent. + let (code, stdout, stderr) = unwind_run_with_registry( + &proj, + &server.uri(), + &args, + "http://gemstash.example.test:9292", + ); let env = common::parse_json_envelope(&stdout); + let case = format!("{unwind:?}"); assert_eq!(code, 0, "{case}: {env}\nstderr:\n{stderr}"); - assert!( - !std::fs::read_to_string(proj.join("Gemfile")) - .unwrap() - .contains(".socket/vendor/"), - "{case}: the vendoring is undone: {env}" - ); assert!( snapshot(&home) == held_before, "{case}: the gem home changed: {env}" ); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{case}"); - assert!( - std::fs::read_to_string(&manifest_path) - .unwrap() - .contains(PURL), - "{case}: the manifest keeps the record: {env}" - ); let text = env.to_string(); - for code in [ - "upstream_gem_install_refreshed", + for needle in [ "upstream_gem_stale_install", + "could not be checked against the upstream gem", + "`http://gemstash.example.test:9292` is not an https URL", + "set it to an https URL", + gem_dir.to_str().unwrap(), ] { - assert!(!text.contains(code), "{case}: {code} in {env}"); + // The envelope JSON-escapes a Windows path's backslashes. + let needle = needle.replace('\\', "\\\\"); + assert!(text.contains(&needle), "{case}: no {needle:?} in {env}"); } + assert!( + !text.contains("upstream_gem_install_refreshed"), + "{case}: {env}" + ); + let upstream_asked = server + .received_requests() + .await + .unwrap() + .iter() + .skip(asked_before) + .any(|request| request.url.path().starts_with("/upstream/")); + assert!(!upstream_asked, "{case}: the unwind asked a registry"); } } -/// A gem the lock resolves from another remote is not judged, as in every -/// unwind refresh: nothing proves its restored entry is the upstream one, -/// and rubygems.org is not asked about a gem that is not its own. +/// A gem that was only ever vendored still has the upstream build +/// installed: its unwind changes nothing in the gem home, downloads no +/// gem and raises nothing about it. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_leaves_an_upstream_install_alone() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_upstream_gem(&server, &upstream).await; + mount_vendored_grant(&server, &patched).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = project_home(&proj); + install_real_gem(&home, UPSTREAM_LIB); + let uri = server.uri(); + let (code, stdout, stderr) = unwind_run( + &proj, + &uri, + &["scan", "--mode", "vendored", "--yes", "--json"], + ); + assert_eq!(code, 0, "vendored scan:\n{stdout}\n{stderr}"); + let held_before = snapshot(&home); + let requests_before = server.received_requests().await.unwrap_or_default().len(); + + let mut args = unwind.to_vec(); + args.push("--json"); + let (code, stdout, stderr) = unwind_run(&proj, &uri, &args); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); + assert!( + snapshot(&home) == held_before, + "{unwind:?}: the gem home changed: {env}" + ); + let fetched: Vec = server.received_requests().await.unwrap_or_default() + [requests_before..] + .iter() + .map(|r| r.url.path().to_string()) + .filter(|path| path.contains("/gems/")) + .collect(); + assert!(fetched.is_empty(), "{unwind:?}: downloaded {fetched:?}"); + let text = env.to_string(); + for code in [ + "upstream_gem_install_refreshed", + "upstream_gem_stale_install", + ] { + assert!(!text.contains(code), "{unwind:?}: {code} in {env}"); + } + } +} + +/// #2214: rollback's "keeps its patched bytes" note, and the +/// `reinstall_required` warning `--json` carries for it, are about the +/// installed trees. Vendored mode never touches a gem home, so a gem that +/// was only ever vendored has nothing patched there once its pair is +/// restored: its installed copy is the upstream build, which its archive +/// in the gem home and the ledger record's pre-patch hashes prove. +#[tokio::test(flavor = "multi_thread")] +async fn rollback_of_an_only_vendored_gem_names_no_reinstall() { + for json in [true, false] { + let case = format!("json={json}"); + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_upstream_gem(&server, &upstream).await; + mount_vendored_grant(&server, &patched).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let pair_before = ( + std::fs::read(proj.join("Gemfile")).unwrap(), + std::fs::read(proj.join("Gemfile.lock")).unwrap(), + ); + let home = project_home(&proj); + install_real_gem(&home, UPSTREAM_LIB); + let uri = server.uri(); + let (code, stdout, stderr) = unwind_run( + &proj, + &uri, + &["scan", "--mode", "vendored", "--yes", "--json"], + ); + assert_eq!(code, 0, "{case}: vendored scan:\n{stdout}\n{stderr}"); + assert!( + std::fs::read_to_string(proj.join("Gemfile")) + .unwrap() + .contains(".socket/vendor/gem/"), + "{case}: premise: the gem is vendored" + ); + let held_before = snapshot(&home); + + let mut args = vec!["rollback", "--yes"]; + if json { + args.push("--json"); + } + let (code, stdout, stderr) = unwind_run(&proj, &uri, &args); + assert_eq!(code, 0, "{case}:\n{stdout}\n{stderr}"); + let pair_after = ( + std::fs::read(proj.join("Gemfile")).unwrap(), + std::fs::read(proj.join("Gemfile.lock")).unwrap(), + ); + assert!(pair_after == pair_before, "{case}: the pair is restored"); + assert!( + snapshot(&home) == held_before, + "{case}: the gem home is untouched" + ); + if json { + let env = common::parse_json_envelope(&stdout); + assert_eq!(env["status"], "success", "{case}: {env}"); + assert!( + details_with_code(&env, "reinstall_required").is_empty(), + "{case}: no installed tree holds patched bytes: {env}" + ); + } else { + assert!( + stdout.contains(&format!("Reverted vendoring for {PURL}")), + "{case}:\n{stdout}" + ); + assert!( + !stdout.contains("patched bytes in installed trees") + && !stderr.contains("Warning:"), + "{case}: nothing is left to reinstall:\n{stdout}\n{stderr}" + ); + } + } +} + +/// The other side of #2214: an installed copy the unwind could not prove +/// to be the upstream build is still counted. Here agent mode patched the +/// copy before the gem was vendored, and the gem comes from a remote the +/// unwind does not judge, so the patched files stay. +#[tokio::test(flavor = "multi_thread")] +async fn rollback_still_names_a_reinstall_for_an_install_it_could_not_judge() { + for json in [true, false] { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, _) = + agent_then_vendored_from(&server, &proj, "https://gems.example.test").await; + + let mut args = vec!["rollback", "--yes"]; + if json { + args.push("--json"); + } + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + assert_eq!(code, 0, "json={json}:\n{stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "json={json}: premise"); + if json { + let env = common::parse_json_envelope(&stdout); + assert_eq!( + details_with_code(&env, "reinstall_required").len(), + 1, + "{env}" + ); + } else { + assert!( + stdout.contains("1 unwired package keeps its patched bytes in installed trees"), + "{stdout}\n{stderr}" + ); + } + } +} + +/// #2214, a copy the gem home's archive alone would call upstream: agent +/// mode patched it in place, beside the upstream archive, and standalone +/// `vendor` then vendored the gem from the manifest. Rollback may only +/// drop its reinstall warning when the installed copy no longer holds the +/// patched file. +#[tokio::test(flavor = "multi_thread")] +async fn rollback_never_calls_an_agent_patched_install_upstream() { + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_upstream_gem(&server, &upstream).await; + mount_vendored_grant(&server, &patched).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = project_home(&proj); + let gem_dir = agent_patched_install(&proj, &home); + let uri = server.uri(); + let (code, stdout, stderr) = unwind_run(&proj, &uri, &["vendor", "--yes", "--json"]); + assert_eq!(code, 0, "vendor:\n{stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise"); + assert_eq!( + std::fs::read(home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem"))).unwrap(), + upstream, + "premise: the archive beside it is the upstream one" + ); + + let (code, stdout, stderr) = unwind_run(&proj, &uri, &["rollback", "--yes", "--json"]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!( + installed_lib(&gem_dir), + PATCHED_LIB, + "premise: this rollback leaves the installed copy patched: {env}" + ); + assert_eq!( + details_with_code(&env, "reinstall_required").len(), + 1, + "the copy is left patched, so the warning stays: {env}" + ); +} + +/// A project whose gem agent mode patched in place and a vendored scan +/// then took over: the takeover moved the manifest record into the vendor +/// ledger and left the installed copy (patched files, upstream archive in +/// the gem home's `cache/`) alone. Returns the installed gem dir and that +/// archive. +async fn agent_then_vendored(server: &MockServer, proj: &Path) -> (PathBuf, PathBuf) { + agent_then_vendored_from(server, proj, "https://rubygems.org").await +} + +/// [`agent_then_vendored`], with `remote` as the pair's gem source. +async fn agent_then_vendored_from( + server: &MockServer, + proj: &Path, + remote: &str, +) -> (PathBuf, PathBuf) { + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(server, None, &sha256_of(&patched)).await; + serve_upstream_gem(server, &upstream).await; + mount_vendored_grant(server, &patched).await; + std::fs::create_dir_all(proj).unwrap(); + write_manifest_pair(proj); + for file in ["Gemfile", "Gemfile.lock"] { + let text = std::fs::read_to_string(proj.join(file)).unwrap(); + assert!(text.contains("https://rubygems.org"), "premise: {text}"); + std::fs::write( + proj.join(file), + text.replace("https://rubygems.org", remote), + ) + .unwrap(); + } + let home = project_home(proj); + let gem_dir = agent_patched_install(proj, &home); + let archive = home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem")); + + let uri = server.uri(); + let (code, stdout, stderr) = unwind_run( + proj, + &uri, + &["scan", "--mode", "vendored", "--yes", "--json"], + ); + assert_eq!(code, 0, "takeover:\n{stdout}\n{stderr}"); + let gemfile = std::fs::read_to_string(proj.join("Gemfile")).unwrap(); + assert!( + gemfile.contains(".socket/vendor/gem/"), + "premise:\n{gemfile}" + ); + let manifest = std::fs::read_to_string(proj.join(".socket").join("manifest.json")).unwrap(); + assert!( + stdout.contains("vendor_manifest_record_migrated") && !manifest.contains(PURL), + "premise: the takeover owns the record now:\n{stdout}\n{manifest}" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise"); + assert_eq!(std::fs::read(&archive).unwrap(), upstream, "premise"); + (gem_dir, archive) +} + +/// The gem downloads (`/gems/.gem`, from any registry) among the +/// requests `server` received after the first `skip`. +async fn gem_downloads_since(server: &MockServer, skip: usize) -> Vec { + server + .received_requests() + .await + .unwrap_or_default() + .iter() + .skip(skip) + .map(|request| request.url.path().to_string()) + .filter(|path| path.contains("/gems/")) + .collect() +} + +/// #2093: a vendored takeover of a gem agent mode patched in place drops +/// the manifest record and keeps the patched files in the installed copy. +/// Once the vendored gem is unwound Bundler loads that copy again, and no +/// record is left that could undo the patch. The unwind therefore puts +/// the upstream gem back, from the upstream archive RubyGems kept in the +/// gem home (nothing is downloaded), and leaves nothing of agent mode's +/// in the gem dir. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_restores_an_install_agent_mode_patched() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, archive) = agent_then_vendored(&server, &proj).await; + let asked_before = server.received_requests().await.unwrap().len(); + + let mut args = unwind.to_vec(); + args.push("--json"); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); + let pair = format!( + "{}{}", + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap() + ); + assert!( + !pair.contains(".socket/vendor/"), + "{unwind:?}: the gem is back on its upstream entry:\n{pair}" + ); + assert_eq!( + installed_lib(&gem_dir), + UPSTREAM_LIB, + "{unwind:?}: the installed copy is the upstream build again: {env}" + ); + assert!( + !gem_dir.join(".socket-patch-kept").exists(), + "{unwind:?}: the copy is a fresh install of the upstream gem: {env}" + ); + assert_eq!( + std::fs::read(&archive).unwrap(), + real_gem(UPSTREAM_LIB), + "{unwind:?}: the upstream archive is untouched: {env}" + ); + let fetched = gem_downloads_since(&server, asked_before).await; + assert!(fetched.is_empty(), "{unwind:?}: downloaded {fetched:?}"); + let text = env.to_string(); + assert!( + text.contains("upstream_gem_install_refreshed") + && !text.contains("upstream_gem_stale_install"), + "{unwind:?}: {env}" + ); + } +} + +/// The same with the gem home's `cache/` pruned (Bundler 4.1 `prune`, a +/// Docker image's `rm -rf ruby/*/cache`): the ledger's record still proves +/// the installed files are the patched ones, so the upstream gem is +/// downloaded and installed over them. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_restores_an_agent_patched_install_without_its_archive() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, archive) = agent_then_vendored(&server, &proj).await; + std::fs::remove_dir_all(archive.parent().unwrap()).unwrap(); + let asked_before = server.received_requests().await.unwrap().len(); + + let mut args = unwind.to_vec(); + args.push("--json"); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); + assert_eq!( + installed_lib(&gem_dir), + UPSTREAM_LIB, + "{unwind:?}: the installed copy is the upstream build again: {env}" + ); + assert_eq!( + gem_downloads_since(&server, asked_before).await, + [format!("/upstream/gems/{DEP}-{DEP_VERSION}.gem")], + "{unwind:?}: one download, of the upstream gem" + ); + let text = env.to_string(); + assert!( + text.contains("upstream_gem_install_refreshed") + && !text.contains("upstream_gem_stale_install"), + "{unwind:?}: {env}" + ); + } +} + +/// An agent-patched copy the unwind may not replace +/// (`--no-gem-install-refresh`) or cannot (`--offline` with the archive +/// pruned) is left exactly as it was and named with the files to remove, +/// not passed over as if it were the upstream build. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_names_an_agent_patched_install_it_leaves() { + for (unwind, opt_out) in VENDORED_UNWINDS + .into_iter() + .flat_map(|unwind| [(unwind, true), (unwind, false)]) + { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, archive) = agent_then_vendored(&server, &proj).await; + let home = project_home(&proj); + if !opt_out { + std::fs::remove_dir_all(archive.parent().unwrap()).unwrap(); + } + let held_before = snapshot(&home); + + let mut args = unwind.to_vec(); + args.push("--json"); + args.push(if opt_out { + "--no-gem-install-refresh" + } else { + "--offline" + }); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env = common::parse_json_envelope(&stdout); + let case = format!("{unwind:?} opt_out={opt_out}"); + assert_eq!(code, 0, "{case}: {env}\nstderr:\n{stderr}"); + assert!( + snapshot(&home) == held_before, + "{case}: the gem home changed: {env}" + ); + let text = env.to_string(); + let spec = home + .join("specifications") + .join(format!("{DEP}-{DEP_VERSION}.gemspec")); + for needle in [ + "upstream_gem_stale_install", + gem_dir.to_str().unwrap(), + spec.to_str().unwrap(), + "bundle install", + ] { + // The envelope JSON-escapes a Windows path's backslashes. + let needle = needle.replace('\\', "\\\\"); + assert!(text.contains(&needle), "{case}: no {needle:?} in {env}"); + } + assert!( + !text.contains("upstream_gem_install_refreshed"), + "{case}: {env}" + ); + } +} + +/// A manifest record for the gem means its in-place patch is agent mode's +/// and still on record, so a vendored unwind does not end it: +/// `vendor --revert` undoes the vendoring only and leaves the installed +/// copy as it is. Two ways there: standalone `vendor`, which works from +/// the manifest and keeps the record in it, and an agent-mode record +/// written again after a vendored takeover. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_leaves_an_install_the_manifest_still_records() { + for standalone in [true, false] { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let home = project_home(&proj); + let uri = server.uri(); + let gem_dir = if standalone { + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_upstream_gem(&server, &upstream).await; + mount_vendored_grant(&server, &patched).await; + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let gem_dir = agent_patched_install(&proj, &home); + let (code, stdout, stderr) = unwind_run(&proj, &uri, &["vendor", "--yes", "--json"]); + assert_eq!(code, 0, "vendor:\n{stdout}\n{stderr}"); + gem_dir + } else { + let (gem_dir, _) = agent_then_vendored(&server, &proj).await; + common::write_in_place_patch_record( + &proj.join(".socket"), + PURL, + UUID, + "lib/stale_probe_gem.rb", + UPSTREAM_LIB.as_bytes(), + PATCHED_LIB.as_bytes(), + ); + gem_dir + }; + let case = format!("standalone={standalone}"); + let manifest_path = proj.join(".socket").join("manifest.json"); + assert!( + std::fs::read_to_string(proj.join("Gemfile")) + .unwrap() + .contains(".socket/vendor/gem/") + && std::fs::read_to_string(&manifest_path) + .unwrap() + .contains(PURL), + "{case}: premise: vendored, with the record in the manifest" + ); + let held_before = snapshot(&home); + + let (code, stdout, stderr) = + unwind_run(&proj, &uri, &["vendor", "--revert", "--yes", "--json"]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{case}: {env}\nstderr:\n{stderr}"); + assert!( + !std::fs::read_to_string(proj.join("Gemfile")) + .unwrap() + .contains(".socket/vendor/"), + "{case}: the vendoring is undone: {env}" + ); + assert!( + snapshot(&home) == held_before, + "{case}: the gem home changed: {env}" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{case}"); + assert!( + std::fs::read_to_string(&manifest_path) + .unwrap() + .contains(PURL), + "{case}: the manifest keeps the record: {env}" + ); + let text = env.to_string(); + for code in [ + "upstream_gem_install_refreshed", + "upstream_gem_stale_install", + ] { + assert!(!text.contains(code), "{case}: {code} in {env}"); + } + } +} + +/// A gem the lock resolves from another remote is not judged, as in every +/// unwind refresh: nothing proves its restored entry is the upstream one, +/// and rubygems.org is not asked about a gem that is not its own. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_does_not_judge_an_agent_patched_gem_from_another_remote() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, _) = + agent_then_vendored_from(&server, &proj, "https://gems.example.test").await; + let home = project_home(&proj); + let held_before = snapshot(&home); + let asked_before = server.received_requests().await.unwrap().len(); + + let mut args = unwind.to_vec(); + args.push("--json"); + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); + assert!( + std::fs::read_to_string(proj.join("Gemfile.lock")) + .unwrap() + .contains("remote: https://gems.example.test/"), + "{unwind:?}: premise: back on the other remote" + ); + assert!( + snapshot(&home) == held_before, + "{unwind:?}: the gem home changed: {env}" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{unwind:?}"); + let upstream_asked = server + .received_requests() + .await + .unwrap() + .iter() + .skip(asked_before) + .any(|request| request.url.path().starts_with("/upstream/")); + assert!(!upstream_asked, "{unwind:?}: the unwind asked rubygems.org"); + let text = env.to_string(); + for code in [ + "upstream_gem_install_refreshed", + "upstream_gem_stale_install", + ] { + assert!(!text.contains(code), "{unwind:?}: {code} in {env}"); + } + } +} + +/// The human run says what it replaced, and rollback's "keeps its patched +/// bytes" note no longer counts the gem. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_unwind_reports_the_agent_patched_refresh_in_a_human_run() { + for unwind in VENDORED_UNWINDS { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let (gem_dir, _) = agent_then_vendored(&server, &proj).await; + + let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), unwind); + assert_eq!(code, 0, "{unwind:?}: {stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "{unwind:?}"); + assert!( + stdout.contains(&format!( + "Replaced the installed copy of 1 gem with the upstream build: {DEP} \ + {DEP_VERSION}." + )), + "{unwind:?}: {stdout}\n{stderr}" + ); + assert!( + !stdout.contains("keeps its patched bytes") && !stderr.contains("still holds"), + "{unwind:?}: {stdout}\n{stderr}" + ); + } +} + +/// What `scan --mode agent` leaves of the fixture gem under `home`: the +/// upstream install with its lib patched in place, the upstream archive +/// still in the home's `cache/`, and the manifest record (with both blobs) +/// that proves the patch. Returns the gem dir. +fn agent_patched_install(proj: &Path, home: &Path) -> PathBuf { + let gem_dir = install_real_gem(home, UPSTREAM_LIB); + std::fs::write(gem_dir.join("lib").join("stale_probe_gem.rb"), PATCHED_LIB).unwrap(); + common::write_in_place_patch_record( + &proj.join(".socket"), + PURL, + UUID, + "lib/stale_probe_gem.rb", + UPSTREAM_LIB.as_bytes(), + PATCHED_LIB.as_bytes(), + ); + // A file of agent mode's own inside the gem dir (a native gem keeps its + // original build there). + std::fs::write(gem_dir.join(".socket-patch-kept"), "kept").unwrap(); + gem_dir +} + +/// #2089: a gem agent mode patched in place keeps the upstream archive in +/// the gem home's `cache/`. Once the hosted scan pins the patched gem's +/// checksum in the lock, `bundle pristine` and `bundle install +/// --redownload` reinstall from that archive: Bundler 2.6 and later remove +/// the gem and fail on the checksum, older ones bring the unpatched gem +/// back. So the scan replaces that archive with the patched gem and leaves +/// the gem dir, whose files are patched already, exactly as it is; +/// `rollback` still gives the upstream gem back. +#[tokio::test(flavor = "multi_thread")] +async fn refresh_replaces_the_upstream_archive_beside_an_agent_patched_install() { + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = project_home(&proj); + let gem_dir = agent_patched_install(&proj, &home); + let cache = home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem")); + assert_eq!(std::fs::read(&cache).unwrap(), upstream, "fixture"); + + // A dry run says the copy would be replaced and changes nothing. + let uri = server.uri(); + let (code, stdout, stderr) = common::run_with_env( + &proj, + &scan_args(&proj, &uri, &["--json", "--dry-run"]), + &[], + ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!( + warnings_with_code(&env, "redirect_gem_install_would_refresh").len(), + 1, + "{env}" + ); + assert_eq!(std::fs::read(&cache).unwrap(), upstream); + + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!(hosted_pinned(&env), 1, "{env}"); + assert!( + stale_warnings(&env).is_empty(), + "nothing is left stale: {env}" + ); + let notes = warnings_with_code(&env, "redirect_gem_install_refreshed"); + assert!( + notes.len() == 1 + && notes[0].contains(&cache.display().to_string()) + && notes[0].contains("patched in place"), + "the archive, and only it: {env}" + ); + assert!( + gem_dir.join(".socket-patch-kept").is_file(), + "the gem dir is not replaced" + ); + assert_eq!( + std::fs::read(&cache).unwrap(), + patched, + "the archive RubyGems reinstalls from is the one the lock pins" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + assert!( + !home.join(".socket-patch-refresh").exists(), + "no stage left" + ); + + // A re-scan has nothing to refresh and nothing to warn about. + let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &[]), &[]); + assert_eq!(code, 0, "{stderr}"); + assert!( + !stderr.contains("Replaced") + && !stderr.contains("upstream archive") + && !stderr.contains("still unpatched"), + "{stderr}" + ); + + // `rollback` undoes both the hosted pin and the agent record: the + // upstream files and the upstream archive are back. + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + let rubygems = format!("{uri}/upstream"); + let (code, stdout, stderr) = common::run_with_env( + &proj, + &[ + "rollback", + "--yes", + "--json", + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + uri.as_str(), + ], + &[("SOCKET_RUBYGEMS_URL", rubygems.as_str())], + ); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB); + assert_eq!(std::fs::read(&cache).unwrap(), upstream); +} + +/// The same copy where the run may not replace it: it is left byte for +/// byte as it was, and the warning says what is wrong with it (the archive, +/// not the files, which are patched) and how to fix it. A shared gem home +/// gets the project-local path or `--gem-refresh-shared`; +/// `--no-gem-install-refresh` gets the files to remove. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +async fn an_agent_patched_install_the_run_may_not_replace_is_warned_about() { + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + let uri = server.uri(); + let leaf = format!("{DEP}-{DEP_VERSION}"); + + // Project-local, refresh turned off. + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = project_home(&proj); + let gem_dir = agent_patched_install(&proj, &home); + let cache = home.join("cache").join(format!("{leaf}.gem")); + let spec = home.join("specifications").join(format!("{leaf}.gemspec")); + let (code, stdout, stderr) = common::run_with_env( + &proj, + &scan_args(&proj, &uri, &["--json", "--no-gem-install-refresh"]), + &[], + ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\n{stderr}"); + let details = stale_warnings(&env); + assert_eq!(details.len(), 1, "{env}"); + for needle in [ + "patched in place", + "`--no-gem-install-refresh` is set", + &format!("emove {} and run `bundle install`", cache.display()), + ] { + assert!( + details[0].contains(needle), + "missing {needle:?}: {details:?}" + ); + } + assert!( + !details[0].contains("unpatched install") + && !details[0].contains(&spec.display().to_string()), + "the installed files are patched, and stay installed: {details:?}" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + assert_eq!(std::fs::read(&cache).unwrap(), upstream); + + // A shared gem home. + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = tmp.path().join("system-home"); + let bin_dir = tmp.path().join("fake-bin"); + stage_system_home_copy(&home, &bin_dir); + let gem_dir = agent_patched_install(&proj, &home); + let cache = home.join("cache").join(format!("{leaf}.gem")); + let path_env = [("PATH", bin_dir.to_str().unwrap())]; + let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &[]), &path_env); + assert_eq!(code, 0, "{stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + assert_eq!( + std::fs::read(&cache).unwrap(), + upstream, + "the shared home is not touched" + ); + for needle in [ + "Warning: 1 gem patched in place still has its upstream archive on disk after the \ + switch to hosted patches.", + &format!( + " - Shared gem home {} (left alone, other projects may load it): {DEP} {DEP_VERSION}.", + home.display() + ), + "run `bundle config set --local path vendor/bundle && bundle install`", + "`--gem-refresh-shared`", + ] { + assert!(stderr.contains(needle), "missing {needle:?}:\n{stderr}"); + } + assert!(!stderr.contains("still unpatched on disk"), "{stderr}"); + + let (code, stdout, stderr) = common::run_with_env( + &proj, + &scan_args(&proj, &uri, &["--json", "--gem-refresh-shared"]), + &path_env, + ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\n{stderr}"); + assert!(stale_warnings(&env).is_empty(), "{env}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + assert_eq!(std::fs::read(&cache).unwrap(), patched); + assert!(gem_dir.join(".socket-patch-kept").is_file()); +} + +// ── a hosted gem whose patch was superseded, taken over by vendored ─── + +/// The newer patch the service publishes for the fixture gem once the +/// project is hosted on [`UUID`]. +const NEWER_UUID: &str = "9b0c1d2e-3f4a-4b5c-8d7e-8f9a0b1c2d3e"; +const NEWER_PATCHED_LIB: &str = + "module StaleProbeGem\n def self.status\n \"PATCHED AGAIN\"\n end\nend\n"; + +/// The patch API once [`NEWER_UUID`] supersedes [`UUID`] (mount it on a +/// reset server): discovery, selection and the view name only the newer +/// patch, and its grant carries the vendored artifacts beside the hosted +/// override. +async fn mount_newer_patch(server: &MockServer) { + let patched = real_gem(NEWER_PATCHED_LIB); + mount_patch_api( + server, + NEWER_UUID, + NEWER_PATCHED_LIB, + None, + &sha256_of(&patched), + ) + .await; + mount_vendored_grant_of(server, NEWER_UUID, &patched).await; + serve_upstream_gem(server, &real_gem(UPSTREAM_LIB)).await; +} + +/// A project hosted on [`UUID`], with the lock as `bundle install` leaves +/// it and the installed copy holding that patch's bytes, after the service +/// replaced the patch with [`NEWER_UUID`]. Returns the gem home. +async fn hosted_on_a_superseded_patch(server: &MockServer, proj: &Path) -> PathBuf { + let patched = real_gem(PATCHED_LIB); + mount_api_for(server, None, &sha256_of(&patched)).await; + serve_patched_gem(server, patched).await; + std::fs::create_dir_all(proj).unwrap(); + write_manifest_pair(proj); + let home = project_home(proj); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let uri = server.uri(); + let (code, _, stderr) = common::run_with_env(proj, &scan_args(proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "hosted scan:\n{stderr}"); + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise"); + server.reset().await; + mount_newer_patch(server).await; + home +} + +/// The events of `env` that name the fixture gem, as `action/errorCode`. +fn gem_events(env: &serde_json::Value) -> Vec { + env["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["purl"].as_str().is_some_and(|p| p.starts_with(PURL))) + .map(|e| { + format!( + "{}/{}", + e["action"].as_str().unwrap_or_default(), + e["errorCode"].as_str().unwrap_or_default() + ) + }) + .collect() +} + +/// #2129: a gem on a hosted patch whose installed copy holds that patch's +/// bytes, after a newer patch was published for the same version. The +/// installed copy matches neither side of the newer patch, but the gem is +/// installed and its lock entry is ours: `scan --mode vendored` vendors +/// the newer patch, as it does on a checkout with no gems installed, and +/// leaves the installed copy alone. The dry run previews the same, and a +/// second run finds nothing left to do. `get --mode vendored` takes the +/// same path. #[tokio::test(flavor = "multi_thread")] -async fn vendored_unwind_does_not_judge_an_agent_patched_gem_from_another_remote() { - for unwind in VENDORED_UNWINDS { +async fn vendored_takeover_of_a_hosted_gem_whose_patch_was_superseded() { + let takeovers: [&[&str]; 2] = [ + &["scan", "--mode", "vendored"], + &["get", NEWER_UUID, "--mode", "vendored"], + ]; + for takeover in takeovers { let server = MockServer::start().await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let (gem_dir, _) = - agent_then_vendored_from(&server, &proj, "https://gems.example.test").await; - let home = project_home(&proj); + let home = hosted_on_a_superseded_patch(&server, &proj).await; + let uri = server.uri(); let held_before = snapshot(&home); - let asked_before = server.received_requests().await.unwrap().len(); + let read_pair = || { + format!( + "{}{}", + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap() + ) + }; + let pair_before = read_pair(); + let run = |extra: &[&str]| { + let mut args = takeover.to_vec(); + args.extend(["--yes", "--json"]); + args.extend(extra); + let (code, stdout, stderr) = unwind_run(&proj, &uri, &args); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{takeover:?} {extra:?}: {env}\nstderr:\n{stderr}"); + assert!( + !env.to_string().contains("package_not_installed"), + "{takeover:?} {extra:?}: the gem is installed: {env}" + ); + env + }; - let mut args = unwind.to_vec(); - args.push("--json"); - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), &args); - let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{unwind:?}: {env}\nstderr:\n{stderr}"); + run(&["--dry-run"]); + assert_eq!( + read_pair(), + pair_before, + "{takeover:?}: the dry run wrote nothing" + ); assert!( - std::fs::read_to_string(proj.join("Gemfile.lock")) - .unwrap() - .contains("remote: https://gems.example.test/"), - "{unwind:?}: premise: back on the other remote" + !proj.join(".socket").join("vendor").exists(), + "{takeover:?}" + ); + + let env = run(&[]); + let copy_rel = format!(".socket/vendor/gem/{NEWER_UUID}/{DEP}-{DEP_VERSION}"); + let pair = read_pair(); + assert!( + pair.matches(©_rel).count() >= 2 && !pair.contains("/patch-registry/"), + "{takeover:?}: the pair names the newer patch's copy and no hosted pin:\n{pair}\n{env}" + ); + assert_eq!( + installed_lib(&proj.join(©_rel)), + NEWER_PATCHED_LIB, + "{takeover:?}: the vendored copy is the newer patch" ); assert!( snapshot(&home) == held_before, - "{unwind:?}: the gem home changed: {env}" + "{takeover:?}: the takeover left the installed copy alone: {env}" ); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{unwind:?}"); - let upstream_asked = server - .received_requests() - .await - .unwrap() - .iter() - .skip(asked_before) - .any(|request| request.url.path().starts_with("/upstream/")); - assert!(!upstream_asked, "{unwind:?}: the unwind asked rubygems.org"); - let text = env.to_string(); - for code in [ - "upstream_gem_install_refreshed", - "upstream_gem_stale_install", - ] { - assert!(!text.contains(code), "{unwind:?}: {code} in {env}"); - } - } -} - -/// The human run says what it replaced, and rollback's "keeps its patched -/// bytes" note no longer counts the gem. -#[tokio::test(flavor = "multi_thread")] -async fn vendored_unwind_reports_the_agent_patched_refresh_in_a_human_run() { - for unwind in VENDORED_UNWINDS { - let server = MockServer::start().await; - let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - let (gem_dir, _) = agent_then_vendored(&server, &proj).await; - let (code, stdout, stderr) = unwind_run(&proj, &server.uri(), unwind); - assert_eq!(code, 0, "{unwind:?}: {stdout}\n{stderr}"); - assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "{unwind:?}"); - assert!( - stdout.contains(&format!( - "Replaced the installed copy of 1 gem with the upstream build: {DEP} \ - {DEP_VERSION}." - )), - "{unwind:?}: {stdout}\n{stderr}" + let env = run(&[]); + assert_eq!( + read_pair(), + pair, + "{takeover:?}: the re-run changed the pair: {env}" ); assert!( - !stdout.contains("keeps its patched bytes") && !stderr.contains("still holds"), - "{unwind:?}: {stdout}\n{stderr}" + snapshot(&home) == held_before, + "{takeover:?}: the re-run changed the installed copy: {env}" ); } } -/// What `scan --mode agent` leaves of the fixture gem under `home`: the -/// upstream install with its lib patched in place, the upstream archive -/// still in the home's `cache/`, and the manifest record (with both blobs) -/// that proves the patch. Returns the gem dir. -fn agent_patched_install(proj: &Path, home: &Path) -> PathBuf { - let gem_dir = install_real_gem(home, UPSTREAM_LIB); - std::fs::write(gem_dir.join("lib").join("stale_probe_gem.rb"), PATCHED_LIB).unwrap(); - common::write_in_place_patch_record( - &proj.join(".socket"), - PURL, - UUID, - "lib/stale_probe_gem.rb", - UPSTREAM_LIB.as_bytes(), - PATCHED_LIB.as_bytes(), - ); - // A file of agent mode's own inside the gem dir (a native gem keeps its - // original build there). - std::fs::write(gem_dir.join(".socket-patch-kept"), "kept").unwrap(); - gem_dir -} - -/// #2089: a gem agent mode patched in place keeps the upstream archive in -/// the gem home's `cache/`. Once the hosted scan pins the patched gem's -/// checksum in the lock, `bundle pristine` and `bundle install -/// --redownload` reinstall from that archive: Bundler 2.6 and later remove -/// the gem and fail on the checksum, older ones bring the unpatched gem -/// back. So the scan replaces that archive with the patched gem and leaves -/// the gem dir, whose files are patched already, exactly as it is; -/// `rollback` still gives the upstream gem back. +/// #2129, the native-extension half: a hosted gem that builds an +/// extension cannot be vendored, superseded patch or not. The refusal +/// names that (`native_extensions_unsupported`), not a gem that is "not +/// installed", and the hosted pin stays. (A dry run of the scan previews +/// no native-extension refusal for any hosted gem, so only the real run is +/// held to this.) #[tokio::test(flavor = "multi_thread")] -async fn refresh_replaces_the_upstream_archive_beside_an_agent_patched_install() { +async fn vendored_takeover_of_a_superseded_native_gem_names_the_extension() { let server = MockServer::start().await; - let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); - mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_patched_gem(&server, patched.clone()).await; - serve_upstream_gem(&server, &upstream).await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - std::fs::create_dir_all(&proj).unwrap(); - write_manifest_pair(&proj); - let home = project_home(&proj); - let gem_dir = agent_patched_install(&proj, &home); - let cache = home.join("cache").join(format!("{DEP}-{DEP_VERSION}.gem")); - assert_eq!(std::fs::read(&cache).unwrap(), upstream, "fixture"); - - // A dry run says the copy would be replaced and changes nothing. - let uri = server.uri(); - let (code, stdout, stderr) = common::run_with_env( - &proj, - &scan_args(&proj, &uri, &["--json", "--dry-run"]), - &[], - ); - let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); - assert_eq!( - warnings_with_code(&env, "redirect_gem_install_would_refresh").len(), - 1, - "{env}" - ); - assert_eq!(std::fs::read(&cache).unwrap(), upstream); - - let (code, stdout, stderr) = - common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); - let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); - assert_eq!(hosted_pinned(&env), 1, "{env}"); - assert!( - stale_warnings(&env).is_empty(), - "nothing is left stale: {env}" - ); - let notes = warnings_with_code(&env, "redirect_gem_install_refreshed"); - assert!( - notes.len() == 1 - && notes[0].contains(&cache.display().to_string()) - && notes[0].contains("patched in place"), - "the archive, and only it: {env}" - ); - assert!( - gem_dir.join(".socket-patch-kept").is_file(), - "the gem dir is not replaced" - ); - assert_eq!( - std::fs::read(&cache).unwrap(), - patched, - "the archive RubyGems reinstalls from is the one the lock pins" - ); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); - assert!( - !home.join(".socket-patch-refresh").exists(), - "no stage left" - ); - - // A re-scan has nothing to refresh and nothing to warn about. - let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &[]), &[]); - assert_eq!(code, 0, "{stderr}"); - assert!( - !stderr.contains("Replaced") - && !stderr.contains("upstream archive") - && !stderr.contains("still unpatched"), - "{stderr}" + let home = hosted_on_a_superseded_patch(&server, &proj).await; + let spec = home + .join("specifications") + .join(format!("{DEP}-{DEP_VERSION}.gemspec")); + let text = std::fs::read_to_string(&spec).unwrap(); + std::fs::write( + &spec, + text.replace( + " s.require_paths", + " s.extensions = [\"ext/probe/extconf.rb\".freeze]\n s.require_paths", + ), + ) + .unwrap(); + let pair_before = ( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), ); - - // `rollback` undoes both the hosted pin and the agent record: the - // upstream files and the upstream archive are back. - std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); - let rubygems = format!("{uri}/upstream"); - let (code, stdout, stderr) = common::run_with_env( - &proj, - &[ - "rollback", - "--yes", - "--json", - "--cwd", - proj.to_str().unwrap(), - "--api-url", - uri.as_str(), - "--org", - ORG, - "--api-token", - "fake", - "--patch-server-url", - uri.as_str(), - ], - &[("SOCKET_RUBYGEMS_URL", rubygems.as_str())], + + let (code, stdout, stderr) = unwind_run( + &proj, + &server.uri(), + &["scan", "--mode", "vendored", "--yes", "--json"], ); - assert_eq!(code, 0, "{stdout}\n{stderr}"); - assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB); - assert_eq!(std::fs::read(&cache).unwrap(), upstream); + let env = common::parse_json_envelope(&stdout); + let events = gem_events(&env); + assert!( + events + .iter() + .any(|e| e.ends_with("/native_extensions_unsupported")), + "{events:?}\n{env}\nstderr:\n{stderr}" + ); + assert!(!env.to_string().contains("package_not_installed"), "{env}"); + assert_ne!(code, 0, "{env}"); + assert_eq!( + ( + std::fs::read_to_string(proj.join("Gemfile")).unwrap(), + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + ), + pair_before, + "the hosted pin stays" + ); + assert!(!proj.join(".socket").join("vendor").exists()); } -/// The same copy where the run may not replace it: it is left byte for -/// byte as it was, and the warning says what is wrong with it (the archive, -/// not the files, which are patched) and how to fix it. A shared gem home -/// gets the project-local path or `--gem-refresh-shared`; -/// `--no-gem-install-refresh` gets the files to remove. -#[cfg(unix)] +/// A lock whose `PLATFORMS` names `ruby` alone names every gem as its +/// ruby-platform gem, and for such a lock Bundler loads an installed +/// precompiled build of the locked version in its place: the copy an +/// install from the upstream registry left behind. After the switch that +/// copy is what Ruby runs, and `bundle install` keeps it. +/// +/// * The scan reports it and does not replace it: the patched gem of this +/// lock is the ruby-platform gem, which only an install builds. It asks +/// the patch registry for no gem, names the command, offers no retry +/// that would do the same, and does not say that nothing is left. +/// * `vex` exits 0 and says `affected` of the gem, with what to do. +/// * A lock that names another platform as well loads the gems it lists, +/// so the copy is not this project's, and a gem dir no gemspec lists is +/// no gem: neither is reported. #[tokio::test(flavor = "multi_thread")] -async fn an_agent_patched_install_the_run_may_not_replace_is_warned_about() { +async fn a_precompiled_copy_under_a_ruby_only_lock_is_reported_and_attested_affected() { + use vex_e2e_common::{run_vex, statements_for, VexRun}; let server = MockServer::start().await; - let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + let patched = real_gem(PATCHED_LIB); mount_api_for(&server, None, &sha256_of(&patched)).await; - serve_patched_gem(&server, patched.clone()).await; + serve_patched_gem(&server, patched).await; let uri = server.uri(); - let leaf = format!("{DEP}-{DEP_VERSION}"); - - // Project-local, refresh turned off. let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); std::fs::create_dir_all(&proj).unwrap(); write_manifest_pair(&proj); let home = project_home(&proj); - let gem_dir = agent_patched_install(&proj, &home); - let cache = home.join("cache").join(format!("{leaf}.gem")); + let gem_dir = install_real_gem_for(&home, UPSTREAM_LIB, PLATFORM); + let leaf = format!("{DEP}-{DEP_VERSION}-{PLATFORM}"); let spec = home.join("specifications").join(format!("{leaf}.gemspec")); - let (code, stdout, stderr) = common::run_with_env( - &proj, - &scan_args(&proj, &uri, &["--json", "--no-gem-install-refresh"]), - &[], + + let (code, stdout, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &[]), &[]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!( + stderr.contains("1 gem is still unpatched on disk after the switch to hosted patches") + && stderr.contains(&format!( + "Not refreshed (it is a precompiled {PLATFORM} gem, which Bundler loads in \ + place of the ruby gem the lock names" + )), + "the copy Bundler loads is reported with what it is:\n{stderr}" + ); + assert!( + stderr.contains("Run `rm -f ") + && stderr.contains(&format!("{leaf}.gemspec")) + && stderr.contains(&format!("{leaf}.gem && bundle install`")), + "the command names the copy's gemspec and archive:\n{stderr}" + ); + assert!(!stderr.contains("to retry"), "{stderr}"); + assert!( + stdout.contains( + "1 gem is still unpatched on disk: the warning names the command that installs the \ + patched gem." + ) && !stdout.contains("Nothing left to patch"), + "the closing lines do not say that nothing is left:\n{stdout}" + ); + assert_eq!(installed_lib(&gem_dir), UPSTREAM_LIB, "the copy is left"); + let gems: Vec = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .map(|request| request.url.path().to_string()) + .filter(|path| path.contains("/gems/")) + .collect(); + assert!(gems.is_empty(), "no gem is asked for: {gems:?}"); + + // `vex`: a document, exit 0, and the gem's actual state. + let run = VexRun { + api_url: Some(uri.clone()), + api_token: Some("fake".into()), + org: Some(ORG.into()), + patch_server_url: Some(uri.clone()), + product: Some("pkg:gem/app@1.0.0".into()), + ..VexRun::default() + }; + let out = run_vex(&vex_e2e_common::binary(), &proj, &run); + assert_eq!(out.code, Some(0), "{out}"); + let statements = statements_for(out.doc(), PURL); + assert_eq!(statements.len(), 1, "{out}"); + assert_eq!(statements[0]["status"], "affected", "{out}"); + let action = statements[0]["action_statement"] + .as_str() + .unwrap_or_default(); + assert!(action.contains("Run `socket-patch scan`"), "{action}"); + let skipped: Vec<&serde_json::Value> = out.envelope["events"] + .as_array() + .into_iter() + .flatten() + .filter(|event| event["action"] == "skipped") + .collect(); + assert_eq!(skipped.len(), 1, "{out}"); + assert_eq!( + skipped[0]["errorCode"], "vex_gem_install_unpatched", + "{out}" + ); + assert!( + warnings_with_code(&out.envelope, "vex_gem_install_unpatched") + .iter() + .any(|detail| detail.contains("the VEX document says affected")), + "{out}" ); + + // A lock that names another platform too loads exactly what it lists. + let lock_path = proj.join("Gemfile.lock"); + let hosted_lock = std::fs::read_to_string(&lock_path).unwrap(); + let both = hosted_lock.replace("PLATFORMS\n ruby\n", "PLATFORMS\n ruby\n x86_64-linux\n"); + assert_ne!(both, hosted_lock); + std::fs::write(&lock_path, &both).unwrap(); + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{env}\n{stderr}"); - let details = stale_warnings(&env); - assert_eq!(details.len(), 1, "{env}"); - for needle in [ - "patched in place", - "`--no-gem-install-refresh` is set", - &format!("emove {} and run `bundle install`", cache.display()), + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert!(stale_warnings(&env).is_empty(), "{env}"); + + // Back on the ruby-only lock, with the copy's gemspec removed: the dir + // is what an install left behind, and nothing loads it. + std::fs::write(&lock_path, &hosted_lock).unwrap(); + std::fs::remove_file(&spec).unwrap(); + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert!(stale_warnings(&env).is_empty(), "{env}"); +} + +/// A patched platform build in a gem home whose `cache/` was pruned (a +/// slim image, `gem cleanup`): no archive says which gem the copy was +/// installed from. A platform gem is a patch of its own, whose files carry +/// that patch's header, so they never hash to what the gem patch's record +/// lists. +/// +/// * The copy is judged by the record of its own patch: the healthy one is +/// left alone and nothing is said, run after run. Judged by the gem +/// patch's record it was called stale and replaced, or warned about, +/// every time. +/// * Where that build's record cannot be read, nothing judges the copy: it +/// is not called stale and is not replaced. +/// * An upstream copy in the same place is still stale, by the build's +/// record. +#[tokio::test(flavor = "multi_thread")] +async fn a_patched_platform_copy_with_a_pruned_cache_is_judged_by_its_own_patch() { + // What the platform build's own patch makes of the file. + let stamped = format!("# Socket Community Patch: {ARM_UUID}\n{PATCHED_LIB}"); + let build_record = |served: bool| { + let template = match served { + true => ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "uuid": ARM_UUID, + "purl": format!("{PURL}?platform={PLATFORM}"), + "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(stamped.as_bytes()), + } }, + "vulnerabilities": {}, + "description": "x", "license": "MIT", "tier": "free" + })), + false => ResponseTemplate::new(404), + }; + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{ARM_UUID}"))) + .respond_with(template) + }; + for (served, installed, stale) in [ + (true, stamped.as_str(), false), + (false, stamped.as_str(), false), + (true, UPSTREAM_LIB, true), ] { + let server = MockServer::start().await; + let prebuilt = real_gem_for(&stamped, PLATFORM); + let other = real_gem_for(PATCHED_LIB, OTHER_PLATFORM); + mount_api_with( + &server, + None, + &sha256_of(&real_gem(PATCHED_LIB)), + &[ + (PLATFORM, sha256_of(&prebuilt), Some(ARM_UUID)), + (OTHER_PLATFORM, sha256_of(&other), Some(LINUX_UUID)), + ], + ) + .await; + build_record(served).mount(&server).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(); + let upstream = |platform: &str| sha256_of(&real_gem_for(UPSTREAM_LIB, platform)); + std::fs::write( + proj.join("Gemfile.lock"), + platform_lock(&upstream(PLATFORM), &upstream(OTHER_PLATFORM)), + ) + .unwrap(); + let home = project_home(&proj); + let gem_dir = install_real_gem_for(&home, installed, PLATFORM); + std::fs::remove_dir_all(home.join("cache")).unwrap(); + + let uri = server.uri(); + let label = format!("record served: {served}, stale: {stale}"); + for run in ["first", "second"] { + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{label}, {run} scan: {env}\nstderr:\n{stderr}"); + assert_eq!( + stale_warnings(&env).len(), + usize::from(stale), + "{label}, {run} scan: {env}" + ); + assert!( + warnings_with_code(&env, "redirect_gem_install_refreshed").is_empty(), + "{label}, {run} scan: nothing is replaced without the archive: {env}" + ); + assert_eq!(installed_lib(&gem_dir), installed, "{label}, {run} scan"); + } + let fix_records = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|request| { + request + .url + .path() + .ends_with(&format!("/patches/view/{UUID}")) + }) + .count(); + assert_eq!( + fix_records, 0, + "{label}: the gem patch's record is not what judges it" + ); + // The build's own record is asked for without its file contents. + let own: Vec> = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|request| { + request + .url + .path() + .ends_with(&format!("/patches/view/{ARM_UUID}")) + }) + .map(|request| request.url.query().map(str::to_string)) + .collect(); assert!( - details[0].contains(needle), - "missing {needle:?}: {details:?}" + !own.is_empty() + && own + .iter() + .all(|query| query.as_deref() == Some("include_blobs=false")), + "{label}: {own:?}" ); } - assert!( - !details[0].contains("unpatched install") - && !details[0].contains(&spec.display().to_string()), - "the installed files are patched, and stay installed: {details:?}" - ); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); - assert_eq!(std::fs::read(&cache).unwrap(), upstream); +} - // A shared gem home. +/// The record of the [`PLATFORM`] build's own patch, whose patched lib is +/// `stamped`, as the patch API serves it. +async fn mount_build_record(server: &MockServer, stamped: &str) { + let api = format!("/v0/orgs/{ORG}/patches/view/{ARM_UUID}"); + mount_build_record_at(server, &api, stamped).await; +} + +/// [`mount_build_record`] under `route`. +async fn mount_build_record_at(server: &MockServer, route: &str, stamped: &str) { + let record = serde_json::json!({ + "uuid": ARM_UUID, + "purl": format!("{PURL}?platform={PLATFORM}"), + "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(stamped.as_bytes()), + } }, + "vulnerabilities": {}, + "description": "x", "license": "MIT", "tier": "free" + }); + Mock::given(method("GET")) + .and(path(route)) + .respond_with(ResponseTemplate::new(200).set_body_json(record)) + .mount(server) + .await; +} + +/// `vex` judges an installed platform copy as it judges any installed +/// package: its files against the record of that build's own patch, one +/// request per build, asked without file contents. The archive in the gem +/// home is no evidence for it. +/// +/// * The healthy copy is attested. +/// * A file of the gem with other bytes, or a file that is gone, leaves +/// the build out, with the patched archive still in `cache/`. +/// * The scan's guard goes by that archive's sha256 alone: it does not +/// compare the installed files with it, so it says nothing. +#[tokio::test(flavor = "multi_thread")] +async fn a_platform_copy_is_attested_by_the_record_of_its_own_patch() { + use vex_e2e_common::{assert_not_attested, run_vex, statements_for, VexRun}; + let stamped = format!("# Socket Community Patch: {ARM_UUID}\n{PATCHED_LIB}"); + let server = MockServer::start().await; let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - std::fs::create_dir_all(&proj).unwrap(); - write_manifest_pair(&proj); - let home = tmp.path().join("system-home"); - let bin_dir = tmp.path().join("fake-bin"); - stage_system_home_copy(&home, &bin_dir); - let gem_dir = agent_patched_install(&proj, &home); - let cache = home.join("cache").join(format!("{leaf}.gem")); - let path_env = [("PATH", bin_dir.to_str().unwrap())]; - let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &[]), &path_env); - assert_eq!(code, 0, "{stderr}"); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); + let proj = platform_project(&server, tmp.path(), &real_gem_for(&stamped, PLATFORM)).await; + mount_build_record(&server, &stamped).await; + let home = project_home(&proj); + let gem_dir = install_real_gem_for(&home, &stamped, PLATFORM); + let uri = server.uri(); + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert!(stale_warnings(&env).is_empty(), "{env}"); assert_eq!( - std::fs::read(&cache).unwrap(), - upstream, - "the shared home is not touched" + build_record_requests(&server).await, + 0, + "the guard goes by the archive, with no record read" ); - for needle in [ - "Warning: 1 gem patched in place still has its upstream archive on disk after the \ - switch to hosted patches.", - &format!( - " - Shared gem home {} (left alone, other projects may load it): {DEP} {DEP_VERSION}.", - home.display() - ), - "run `bundle config set --local path vendor/bundle && bundle install`", - "`--gem-refresh-shared`", - ] { - assert!(stderr.contains(needle), "missing {needle:?}:\n{stderr}"); - } - assert!(!stderr.contains("still unpatched on disk"), "{stderr}"); - let (code, stdout, stderr) = common::run_with_env( - &proj, - &scan_args(&proj, &uri, &["--json", "--gem-refresh-shared"]), - &path_env, + let run = VexRun { + api_url: Some(uri.clone()), + api_token: Some("fake".into()), + org: Some(ORG.into()), + patch_server_url: Some(uri.clone()), + product: Some("pkg:gem/app@1.0.0".into()), + ..VexRun::default() + }; + let build = format!("{PURL}?platform={PLATFORM}"); + let out = run_vex(&vex_e2e_common::binary(), &proj, &run); + assert_eq!(out.code, Some(0), "{out}"); + let attested = statements_for(out.doc(), &build); + assert!( + attested + .iter() + .any(|statement| statement["status"] == "not_affected"), + "the build is attested by its own record: {out}" ); + assert_eq!(build_record_requests(&server).await, 1, "one request"); + let requests = server.received_requests().await.unwrap_or_default(); + let record = format!("/patches/view/{ARM_UUID}"); + let asked = requests + .iter() + .find(|request| request.url.path().ends_with(&record)) + .and_then(|request| request.url.query().map(str::to_string)); + assert_eq!(asked.as_deref(), Some("include_blobs=false")); + + // The patched archive is still in `cache/`; a file of the gem is not + // what the build's patch makes of it. + let lib = gem_dir.join("lib").join("stale_probe_gem.rb"); + std::fs::write(&lib, "module StaleProbeGem; end # edited\n").unwrap(); + let out = run_vex(&vex_e2e_common::binary(), &proj, &run); + assert_not_attested(&out.envelope, &build, "hash_mismatch"); + std::fs::remove_file(&lib).unwrap(); + let out = run_vex(&vex_e2e_common::binary(), &proj, &run); + assert!( + statements_for(out.doc(), &build) + .iter() + .all(|statement| statement["status"] != "not_affected"), + "a build with a file gone is not attested: {out}" + ); + + // The guard does not hold the tree to the archive: nothing is said. + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{env}\n{stderr}"); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); assert!(stale_warnings(&env).is_empty(), "{env}"); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB); - assert_eq!(std::fs::read(&cache).unwrap(), patched); - assert!(gem_dir.join(".socket-patch-kept").is_file()); -} - -// ── a hosted gem whose patch was superseded, taken over by vendored ─── - -/// The newer patch the service publishes for the fixture gem once the -/// project is hosted on [`UUID`]. -const NEWER_UUID: &str = "9b0c1d2e-3f4a-4b5c-8d7e-8f9a0b1c2d3e"; -const NEWER_PATCHED_LIB: &str = - "module StaleProbeGem\n def self.status\n \"PATCHED AGAIN\"\n end\nend\n"; - -/// The patch API once [`NEWER_UUID`] supersedes [`UUID`] (mount it on a -/// reset server): discovery, selection and the view name only the newer -/// patch, and its grant carries the vendored artifacts beside the hosted -/// override. -async fn mount_newer_patch(server: &MockServer) { - let patched = real_gem(NEWER_PATCHED_LIB); - mount_patch_api( + assert!( + warnings_with_code(&env, "redirect_gem_install_refreshed").is_empty(), + "{env}" + ); +} + +/// A project locked on the two platform builds of the fixture gem, against +/// a service that lists a patched build for both, the one for [`PLATFORM`] +/// being `prebuilt`. Returns the project dir. +async fn platform_project(server: &MockServer, tmp: &Path, prebuilt: &[u8]) -> PathBuf { + let other = real_gem_for(PATCHED_LIB, OTHER_PLATFORM); + mount_api_with( server, - NEWER_UUID, - NEWER_PATCHED_LIB, None, - &sha256_of(&patched), + &sha256_of(&real_gem(PATCHED_LIB)), + &[ + (PLATFORM, sha256_of(prebuilt), Some(ARM_UUID)), + (OTHER_PLATFORM, sha256_of(&other), Some(LINUX_UUID)), + ], ) .await; - mount_vendored_grant_of(server, NEWER_UUID, &patched).await; - serve_upstream_gem(server, &real_gem(UPSTREAM_LIB)).await; + let proj = tmp.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(); + let upstream = |platform: &str| sha256_of(&real_gem_for(UPSTREAM_LIB, platform)); + std::fs::write( + proj.join("Gemfile.lock"), + platform_lock(&upstream(PLATFORM), &upstream(OTHER_PLATFORM)), + ) + .unwrap(); + proj } -/// A project hosted on [`UUID`], with the lock as `bundle install` leaves -/// it and the installed copy holding that patch's bytes, after the service -/// replaced the patch with [`NEWER_UUID`]. Returns the gem home. -async fn hosted_on_a_superseded_patch(server: &MockServer, proj: &Path) -> PathBuf { - let patched = real_gem(PATCHED_LIB); - mount_api_for(server, None, &sha256_of(&patched)).await; - serve_patched_gem(server, patched).await; - std::fs::create_dir_all(proj).unwrap(); - write_manifest_pair(proj); - let home = project_home(proj); - let gem_dir = install_real_gem(&home, UPSTREAM_LIB); - let uri = server.uri(); - let (code, _, stderr) = common::run_with_env(proj, &scan_args(proj, &uri, &["--json"]), &[]); - assert_eq!(code, 0, "hosted scan:\n{stderr}"); - std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); - assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise"); - server.reset().await; - mount_newer_patch(server).await; - home +/// How many requests `server` got for the record of the [`PLATFORM`] +/// build's own patch. +async fn build_record_requests(server: &MockServer) -> usize { + let requests = server.received_requests().await.unwrap_or_default(); + let record = format!("/patches/view/{ARM_UUID}"); + requests + .iter() + .filter(|request| request.url.path().ends_with(&record)) + .count() } -/// The events of `env` that name the fixture gem, as `action/errorCode`. -fn gem_events(env: &serde_json::Value) -> Vec { - env["events"] - .as_array() - .into_iter() - .flatten() - .filter(|e| e["purl"].as_str().is_some_and(|p| p.starts_with(PURL))) - .map(|e| { - format!( - "{}/{}", - e["action"].as_str().unwrap_or_default(), - e["errorCode"].as_str().unwrap_or_default() - ) - }) - .collect() +/// The `--vex` of the run that moved the lock judges an installed platform +/// copy as `vex` does: against the record of the build's own patch, with +/// one request. Where that record cannot be read nothing judges the copy, +/// and the build is stated `affected` under the unknown-build warning, as +/// `vex` states it: what the run assumes of the gem does not attest it. +#[tokio::test(flavor = "multi_thread")] +async fn the_vex_of_the_run_that_moved_the_lock_checks_a_build_by_its_own_record() { + let stamped = format!("# Socket Community Patch: {ARM_UUID}\n{PATCHED_LIB}"); + let build = format!("{PURL}?platform={PLATFORM}"); + for record_served in [true, false] { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = platform_project(&server, tmp.path(), &real_gem_for(&stamped, PLATFORM)).await; + if record_served { + mount_build_record(&server, &stamped).await; + } + install_real_gem_for(&project_home(&proj), &stamped, PLATFORM); + let (code, env, doc) = scan_with_vex(&proj, &server.uri()); + let label = format!("record served: {record_served}: {env}\n{doc}"); + assert_eq!(code, 0, "{label}"); + let statuses: Vec<&str> = vex_e2e_common::statements_for(&doc, &build) + .iter() + .filter_map(|statement| statement["status"].as_str()) + .collect(); + assert_eq!(build_record_requests(&server).await, 1, "{label}"); + match record_served { + true => assert_eq!(statuses, ["not_affected"], "{label}"), + false => { + assert_eq!(statuses, ["affected"], "{label}"); + let warned = env["vex"]["warnings"].to_string(); + assert!(warned.contains("vex_gem_build_unknown"), "{label}"); + } + } + } } -/// #2129: a gem on a hosted patch whose installed copy holds that patch's -/// bytes, after a newer patch was published for the same version. The -/// installed copy matches neither side of the newer patch, but the gem is -/// installed and its lock entry is ours: `scan --mode vendored` vendors -/// the newer patch, as it does on a checkout with no gems installed, and -/// leaves the installed copy alone. The dry run previews the same, and a -/// second run finds nothing left to do. `get --mode vendored` takes the -/// same path. +/// `scan --mode hosted --json --vex` in `proj`: the exit code, the +/// envelope and the document it wrote (null where it wrote none). +fn scan_with_vex(proj: &Path, uri: &str) -> (i32, serde_json::Value, serde_json::Value) { + let vex_path = proj.join("out.vex.json"); + let _ = std::fs::remove_file(&vex_path); + let vex = ["--json", "--vex", vex_path.to_str().unwrap()]; + let product = ["--vex-product", "pkg:gem/app@1.0.0"]; + let args = scan_args(proj, uri, &[vex.as_slice(), product.as_slice()].concat()); + let (code, stdout, _stderr) = common::run_with_env(proj, &args, &[]); + let doc = serde_json::from_slice(&std::fs::read(&vex_path).unwrap_or_default()); + ( + code, + common::parse_json_envelope(&stdout), + doc.unwrap_or_default(), + ) +} + +/// A platform build has one `vex` outcome, from all of its installed +/// copies, and is attested only when every copy is the patched build by +/// the record of its own patch. +/// +/// * The same build installed from upstream's gem in two gem homes is +/// left out once, not once per home. +/// * One patched copy beside one that is upstream's gem is left out. +/// * Where the build's record cannot be read nothing judges the copies: +/// the build is stated `affected` once, under the unknown-build +/// warning, and is in no other list. +/// * The run that moves the lock holds the build to the same: what it +/// assumes of the gem does not speak for a copy in a gem home its guard +/// left as it was. #[tokio::test(flavor = "multi_thread")] -async fn vendored_takeover_of_a_hosted_gem_whose_patch_was_superseded() { - let takeovers: [&[&str]; 2] = [ - &["scan", "--mode", "vendored"], - &["get", NEWER_UUID, "--mode", "vendored"], - ]; - for takeover in takeovers { +async fn a_platform_build_in_two_gem_homes_has_one_vex_outcome() { + use vex_e2e_common::{run_vex, statements_for, VexRun}; + let stamped = format!("# Socket Community Patch: {ARM_UUID}\n{PATCHED_LIB}"); + let build = format!("{PURL}?platform={PLATFORM}"); + let outcome = |envelope: &serde_json::Value, doc: &serde_json::Value| { + let events: Vec<(String, String)> = envelope["events"] + .as_array() + .into_iter() + .flatten() + .filter(|event| event["purl"] == build.as_str()) + .map(|event| { + let text = |key: &str| event[key].as_str().unwrap_or_default().to_string(); + (text("action"), text("errorCode")) + }) + .collect(); + let statuses: Vec = statements_for(doc, &build) + .iter() + .filter_map(|statement| statement["status"].as_str().map(str::to_string)) + .collect(); + (events, statuses) + }; + let skipped = |code: &str| vec![("skipped".to_string(), code.to_string())]; + for (first_lib, second_lib, record_served, expected) in [ + (UPSTREAM_LIB, UPSTREAM_LIB, true, "not_applied"), + (stamped.as_str(), UPSTREAM_LIB, true, "not_applied"), + ( + stamped.as_str(), + stamped.as_str(), + false, + "vex_gem_build_unknown", + ), + ] { let server = MockServer::start().await; let tmp = tempfile::tempdir().unwrap(); - let proj = tmp.path().join("proj"); - let home = hosted_on_a_superseded_patch(&server, &proj).await; + let proj = platform_project(&server, tmp.path(), &real_gem_for(&stamped, PLATFORM)).await; + if record_served { + mount_build_record(&server, &stamped).await; + } let uri = server.uri(); - let held_before = snapshot(&home); - let read_pair = || { - format!( - "{}{}", - std::fs::read_to_string(proj.join("Gemfile")).unwrap(), - std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap() - ) + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + // Two gem homes of the project: the trees of two Rubies. + let first = project_home(&proj); + let second = first.with_file_name("3.4.0"); + install_real_gem_for(&first, first_lib, PLATFORM); + install_real_gem_for(&second, second_lib, PLATFORM); + let run = VexRun { + api_url: Some(uri.clone()), + api_token: Some("fake".into()), + org: Some(ORG.into()), + patch_server_url: Some(uri.clone()), + product: Some("pkg:gem/app@1.0.0".into()), + ..VexRun::default() }; - let pair_before = read_pair(); - let run = |extra: &[&str]| { - let mut args = takeover.to_vec(); - args.extend(["--yes", "--json"]); - args.extend(extra); - let (code, stdout, stderr) = unwind_run(&proj, &uri, &args); - let env = common::parse_json_envelope(&stdout); - assert_eq!(code, 0, "{takeover:?} {extra:?}: {env}\nstderr:\n{stderr}"); - assert!( - !env.to_string().contains("package_not_installed"), - "{takeover:?} {extra:?}: the gem is installed: {env}" - ); - env + let out = run_vex(&vex_e2e_common::binary(), &proj, &run); + let label = format!("{expected}: {out}"); + let (events, statuses) = outcome(&out.envelope, out.doc()); + assert_eq!(events, skipped(expected), "{label}"); + let affected = match record_served { + true => Vec::new(), + false => vec!["affected".to_string()], }; + assert_eq!(statuses, affected, "{label}"); + assert_eq!(build_record_requests(&server).await, 1, "one per build"); + } - run(&["--dry-run"]); - assert_eq!( - read_pair(), - pair_before, - "{takeover:?}: the dry run wrote nothing" - ); - assert!( - !proj.join(".socket").join("vendor").exists(), - "{takeover:?}" - ); + // The run that moves the lock, with a copy its guard passes (the + // archive in `cache/` is the patched gem) whose files are not the + // patched build's: the guard says nothing, and the run's own document + // does not attest the build on the strength of the gem's pin. + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = platform_project(&server, tmp.path(), &real_gem_for(&stamped, PLATFORM)).await; + mount_build_record(&server, &stamped).await; + let first = project_home(&proj); + install_real_gem_for(&first, &stamped, PLATFORM); + let other = install_real_gem_for(&first.with_file_name("3.4.0"), &stamped, PLATFORM); + std::fs::write(other.join("lib").join("stale_probe_gem.rb"), UPSTREAM_LIB).unwrap(); + let (code, env, doc) = scan_with_vex(&proj, &server.uri()); + assert_eq!(code, 0, "{env}"); + assert!(stale_warnings(&env).is_empty(), "{env}"); + let (_, statuses) = outcome(&env, &doc); + assert!( + !statuses.iter().any(|status| status == "not_affected"), + "a build with an unpatched copy is not attested by the run: {env}\n{doc}" + ); +} - let env = run(&[]); - let copy_rel = format!(".socket/vendor/gem/{NEWER_UUID}/{DEP}-{DEP_VERSION}"); - let pair = read_pair(); - assert!( - pair.matches(©_rel).count() >= 2 && !pair.contains("/patch-registry/"), - "{takeover:?}: the pair names the newer patch's copy and no hosted pin:\n{pair}\n{env}" - ); - assert_eq!( - installed_lib(&proj.join(©_rel)), - NEWER_PATCHED_LIB, - "{takeover:?}: the vendored copy is the newer patch" - ); - assert!( - snapshot(&home) == held_before, - "{takeover:?}: the takeover left the installed copy alone: {env}" - ); +/// A credential the patch API refuses for the record of a build's own +/// patch is answered by the public proxy, as for every other read of +/// `vex`: the build is attested, and the run says which API answered. +#[tokio::test(flavor = "multi_thread")] +async fn a_build_record_the_api_refuses_is_read_from_the_public_proxy() { + use vex_e2e_common::{run_vex, statements_for, VexRun}; + let stamped = format!("# Socket Community Patch: {ARM_UUID}\n{PATCHED_LIB}"); + let build = format!("{PURL}?platform={PLATFORM}"); + let server = MockServer::start().await; + let proxy = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = platform_project(&server, tmp.path(), &real_gem_for(&stamped, PLATFORM)).await; + Mock::given(method("GET")) + .and(path(format!("/v0/orgs/{ORG}/patches/view/{ARM_UUID}"))) + .respond_with(ResponseTemplate::new(401)) + .mount(&server) + .await; + let on_proxy = format!("/patch/view/{ARM_UUID}"); + mount_build_record_at(&proxy, &on_proxy, &stamped).await; + install_real_gem_for(&project_home(&proj), &stamped, PLATFORM); + let uri = server.uri(); + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); - let env = run(&[]); - assert_eq!( - read_pair(), - pair, - "{takeover:?}: the re-run changed the pair: {env}" - ); - assert!( - snapshot(&home) == held_before, - "{takeover:?}: the re-run changed the installed copy: {env}" - ); - } + let run = VexRun { + api_url: Some(uri.clone()), + api_token: Some("fake".into()), + org: Some(ORG.into()), + patch_server_url: Some(uri.clone()), + proxy_url: Some(proxy.uri()), + product: Some("pkg:gem/app@1.0.0".into()), + ..VexRun::default() + }; + let out = run_vex(&vex_e2e_common::binary(), &proj, &run); + assert_eq!(out.code, Some(0), "{out}"); + let attested = statements_for(out.doc(), &build); + assert!( + attested + .iter() + .any(|statement| statement["status"] == "not_affected"), + "the build is attested by the record the proxy served: {out}" + ); + let warned = out.envelope["warnings"].to_string(); + assert!(warned.contains("api_auth_fallback"), "{out}"); + assert!(!warned.contains("vex_gem_build_unknown"), "{out}"); + let asked = proxy.received_requests().await.unwrap_or_default(); + let records: Vec<&str> = asked + .iter() + .map(|request| request.url.path()) + .filter(|route| *route == on_proxy) + .collect(); + assert_eq!(records.len(), 1, "one request to the proxy: {asked:?}"); } -/// #2129, the native-extension half: a hosted gem that builds an -/// extension cannot be vendored, superseded patch or not. The refusal -/// names that (`native_extensions_unsupported`), not a gem that is "not -/// installed", and the hosted pin stays. (A dry run of the scan previews -/// no native-extension refusal for any hosted gem, so only the real run is -/// held to this.) +/// The guard knows the ruby-platform gem by the sha256 the reference's +/// list gives for it, whatever the reference's own checksum says: a lock +/// that names the ruby-platform gem beside a platform build, with the +/// patched ruby gem installed from its archive, has no stale install. #[tokio::test(flavor = "multi_thread")] -async fn vendored_takeover_of_a_superseded_native_gem_names_the_extension() { +async fn the_ruby_gem_of_a_platform_lock_is_judged_by_its_list_entry() { + let stamped = format!("# Socket Community Patch: {ARM_UUID}\n{PATCHED_LIB}"); + let ruby_sha = sha256_of(&real_gem(PATCHED_LIB)); + let arm_sha = sha256_of(&real_gem_for(&stamped, PLATFORM)); let server = MockServer::start().await; + // The reference's own checksum is not the list's entry for the gem. + mount_api_with( + &server, + None, + &"f".repeat(64), + &[ + ("ruby", ruby_sha.clone(), Some(UUID)), + (PLATFORM, arm_sha, Some(ARM_UUID)), + ], + ) + .await; let tmp = tempfile::tempdir().unwrap(); let proj = tmp.path().join("proj"); - let home = hosted_on_a_superseded_patch(&server, &proj).await; - let spec = home - .join("specifications") - .join(format!("{DEP}-{DEP_VERSION}.gemspec")); - let text = std::fs::read_to_string(&spec).unwrap(); + std::fs::create_dir_all(&proj).unwrap(); std::fs::write( - &spec, - text.replace( - " s.require_paths", - " s.extensions = [\"ext/probe/extconf.rb\".freeze]\n s.require_paths", - ), + proj.join("Gemfile"), + format!("source \"https://rubygems.org\"\ngem \"{DEP}\", \"{DEP_VERSION}\"\n"), ) .unwrap(); - let pair_before = ( - std::fs::read_to_string(proj.join("Gemfile")).unwrap(), - std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), - ); + let upstream = |platform: &str| sha256_of(&real_gem_for(UPSTREAM_LIB, platform)); + let lock = format!( + "GEM\n remote: https://rubygems.org/\n specs:\n {DEP} ({DEP_VERSION})\n {DEP} \ + ({DEP_VERSION}-{PLATFORM})\n\nPLATFORMS\n {PLATFORM}\n ruby\n\nDEPENDENCIES\n {DEP} (= \ + {DEP_VERSION})\n\nCHECKSUMS\n {DEP} ({DEP_VERSION}) sha256={}\n {DEP} \ + ({DEP_VERSION}-{PLATFORM}) sha256={}\n\nBUNDLED WITH\n 4.0.15\n", + sha256_of(&real_gem(UPSTREAM_LIB)), + upstream(PLATFORM), + ); + std::fs::write(proj.join("Gemfile.lock"), lock).unwrap(); + let home = project_home(&proj); + let ruby_dir = install_real_gem(&home, PATCHED_LIB); + install_real_gem_for(&home, &stamped, PLATFORM); - let (code, stdout, stderr) = unwind_run( - &proj, - &server.uri(), - &["scan", "--mode", "vendored", "--yes", "--json"], - ); + let uri = server.uri(); + let (code, stdout, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); let env = common::parse_json_envelope(&stdout); - let events = gem_events(&env); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + let after = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); assert!( - events - .iter() - .any(|e| e.ends_with("/native_extensions_unsupported")), - "{events:?}\n{env}\nstderr:\n{stderr}" + after.contains(&format!(" {DEP} ({DEP_VERSION}) sha256={ruby_sha}\n")), + "the lock pins the ruby gem to the list's entry: {after}" ); - assert!(!env.to_string().contains("package_not_installed"), "{env}"); - assert_ne!(code, 0, "{env}"); - assert_eq!( - ( - std::fs::read_to_string(proj.join("Gemfile")).unwrap(), - std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), - ), - pair_before, - "the hosted pin stays" + assert!(stale_warnings(&env).is_empty(), "{env}"); + assert!( + warnings_with_code(&env, "redirect_gem_install_refreshed").is_empty(), + "{env}" ); - assert!(!proj.join(".socket").join("vendor").exists()); + assert_eq!(installed_lib(&ruby_dir), PATCHED_LIB); } // ── a gem vendored mode refuses, patched in the mode its refusal names ── 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 0c654c0f70..5c11370da0 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -52,9 +52,11 @@ //! PLATFORM GEMS (`gem_vendor_platform_gems_fresh_checkout_bundle_install_and_revert`, //! bundler >= 2.3): a gem the real bundler locks as precompiled platform //! gems, from a local source that publishes it that way, is vendored as the -//! patch service's prebuilt platform gem of every locked platform; the -//! fresh checkout loads the patched file from the tree of the platform it -//! runs on, with no request to the service. +//! patched platform gem of every locked platform, each from that platform's +//! own patch, which the gem patch's reference names; the fresh checkout +//! loads the patched file from the tree of the platform it runs on, with no +//! request to the service. While a locked platform has no patched build +//! the gem is not vendored, and the run says so in one line. //! //! VERSION MATRIX: every capstone runs on bundler 1.17 → 4.x (verified //! 1.17.3, 2.0.2 … 2.7.2, 4.0.15, 4.0.21 — the pair edit's PATH + @@ -2767,12 +2769,14 @@ const PLAT_PRISTINE: &str = "module Sockplat\n VERSION = \"1.0.0\"\nend\n"; /// sets `platform` is one. /// * `service/`: what the patch service serves for the patch of /// `sockplat` — the patched ruby gem, the patched platform gem of each -/// platform (a "prebuild") and the stub gemspec of each +/// platform and the stub gemspec of each /// (`Gem::Specification#to_ruby`). /// * `platforms`: the platforms, this machine's first. /// /// `pristine.rb` / `patched.rb` (the caller's) are `lib/sockplat.rb` -/// before and after the patch. +/// before and after the patch. Beside it every gem carries +/// `lib//build`, which names the build it is: the one file that +/// tells one platform's gem from another's. const PLATFORM_GEMS_RB: &str = r##" require "rubygems/package" require "zlib" @@ -2786,15 +2790,16 @@ bodies = { "upstream" => File.read("pristine.rb"), "patched" => File.read("patch build = lambda do |dir, name, platform, body, deps| work = File.join(out, dir, "#{name}-#{platform || "ruby"}") - FileUtils.mkdir_p(File.join(work, "lib")) + FileUtils.mkdir_p(File.join(work, "lib", name)) File.write(File.join(work, "lib/#{name}.rb"), body) + File.write(File.join(work, "lib/#{name}/build"), platform || "ruby") spec = Gem::Specification.new do |s| s.name = name s.version = "1.0.0" s.platform = platform if platform s.summary = "fixture" s.authors = ["fixture"] - s.files = ["lib/#{name}.rb"] + s.files = ["lib/#{name}.rb", "lib/#{name}/build"] deps.each { |dep| s.add_runtime_dependency(dep, ">= 1.0") } end [spec, Dir.chdir(work) { File.join(work, Gem::Package.build(spec)) }] @@ -2824,74 +2829,239 @@ 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 +/// The `sha512-` SRI string of `bytes`. +fn sri(bytes: &[u8]) -> String { + use sha2::{Digest as _, Sha512}; + format!("sha512-{}", b64(&Sha512::digest(bytes))) +} + +fn sha256_hex(bytes: &[u8]) -> String { + use sha2::{Digest as _, Sha256}; + hex::encode(Sha256::digest(bytes)) +} + +/// The uuid of the patch of `platform`'s patched build, for the gem patch +/// `uuid`: each patched platform gem has a patch of its own. +fn build_uuid(uuid: &str, platform: &str) -> String { + let hex = sha256_hex(format!("{uuid}/{platform}").as_bytes()); + format!( + "{}-{}-4{}-8{}-{}", + &hex[..8], + &hex[8..12], + &hex[13..16], + &hex[17..20], + &hex[20..32] + ) +} + +/// The purl of the fixture gem's platform gem of `platform`. +fn platform_purl(platform: &str) -> String { + format!("pkg:gem/{PLAT}@{PLAT_VERSION}?platform={platform}") +} + +/// A patch service answering for the gem patch `uuid` the way the wire +/// contract has it. The gem's fix is that one patch, the ruby gem's +/// (`purl`). Its reference serves the ruby gem (`tarball`) with its stub +/// and, for a request that asks (`"gemBuilds": true`), names its registry +/// under a snapshot URL and lists every gem of the version +/// (`registryOverride.identifiers.gemBuilds`): the ruby gem, each platform +/// of `patched` with the patch of its patched build ([`build_uuid`]), and +/// each of `upstream` with none (the registry hands on upstream's own gem +/// for it, and serves its file); a platform in neither is one the list +/// leaves out, as for a +/// platform upstream does not publish. Each of those patches serves that +/// platform's gem (`tarball`) +/// and stub gemspec, and one request answers for every uuid it names. A +/// platform of `building` is listed with the patch of its patched build +/// too, and the reference of that patch answers `pending_build`: the +/// build is named before it is served. The +/// URLs name the production host, so the run reaches them only through /// `--patch-server-url`. async fn platform_patch_service( - service: &Path, + fixture: &Path, purl: &str, uuid: &str, - prebuilds: &[String], + patched: &[String], + upstream: &[String], + building: &[String], ) -> MockServer { - use base64::Engine as _; - use sha2::{Digest as _, Sha512}; + // Hand the test's task back to the runtime once, which renews its tokio + // cooperative budget. A `MockServer` verifies its mocks when it is + // dropped, on a blocking executor of its own, and a task that has used + // up its budget never gets through that. Every mount, every read of + // the received requests and every server start spends some of it, and + // a test that only runs child processes in between never yields by + // itself. + tokio::task::yield_now().await; 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 file_of = |platform: Option<&str>| match platform { + Some(platform) => format!("{leaf}-{platform}"), + None => leaf.clone(), + }; + let read = |dir: &str, file: String| std::fs::read(fixture.join(dir).join(file)).unwrap(); + // The artifacts of the patch `own` of the gem of `platform`, each + // mounted where its URL says. + let mut mounts = Vec::new(); + let mut artifacts = |own: &str, platform: Option<&str>| { + let mut out = Vec::new(); + for (kind, ext) in [("tarball", "gem"), ("gem-stub-gemspec", "gemspec")] { + let bytes = read("service", format!("{}.{ext}", file_of(platform))); + let route = format!( + "/patch/gem/{PLAT}/{PLAT_VERSION}/grant-token/{own}/{}.{ext}", + file_of(platform) + ); + out.push(serde_json::json!({ + "kind": kind, + "url": format!("https://patch.socket.dev{route}"), + "contentType": "application/octet-stream", + "sizeBytes": bytes.len(), + "integrity": { "sha512": sri(&bytes) }, + })); + mounts.push((route, bytes)); + } + serde_json::Value::Array(out) + }; + + let ruby_sha = sha256_hex(&read("service", format!("{leaf}.gem"))); + let mut builds = vec![serde_json::json!({ + "platform": "ruby", "gemChecksumSha256": ruby_sha, "patchUuid": uuid, + })]; + let mut references = serde_json::Map::new(); + // The record of a platform gem's own patch, which a client checks that + // gem's tree against. (This fixture builds every patched gem from one + // `patched.rb`, so the records of the builds list the same hashes; the + // patch service stamps each patch's files, and theirs differ.) + let (pristine, patched_rb) = ( + read("", "pristine.rb".into()), + read("", "patched.rb".into()), + ); + let mut records = Vec::new(); + for platform in patched { + let own = build_uuid(uuid, platform); + let gem = read("service", format!("{}.gem", file_of(Some(platform)))); + builds.push(serde_json::json!({ + "platform": platform, "gemChecksumSha256": sha256_hex(&gem), "patchUuid": own, + })); + records.push(( + own.clone(), + serde_json::json!({ + "uuid": own, + "purl": platform_purl(platform), + "publishedAt": "2026-01-01T00:00:00Z", + "files": { "lib/sockplat.rb": { + "beforeHash": git_sha256(&pristine), + "afterHash": git_sha256(&patched_rb), + } }, + "vulnerabilities": {}, + "description": "fixture platform gem patch", + "license": "MIT", + "tier": "free", + }), )); + let artifacts = artifacts(&own, Some(platform)); + references.insert( + own, + serde_json::json!({ + "status": "granted", + "purl": platform_purl(platform), + "url": artifacts[0]["url"], + "artifacts": artifacts, + }), + ); + } + let mut upstream_gems = Vec::new(); + for platform in upstream { + let gem = read("repo/gems", format!("{}.gem", file_of(Some(platform)))); + builds.push(serde_json::json!({ + "platform": platform, "gemChecksumSha256": sha256_hex(&gem), "patchUuid": null, + })); + upstream_gems.push((format!("{}.gem", file_of(Some(platform))), gem)); + } + for platform in building { + let own = build_uuid(uuid, platform); + let gem = read("service", format!("{}.gem", file_of(Some(platform)))); + builds.push(serde_json::json!({ + "platform": platform, "gemChecksumSha256": sha256_hex(&gem), "patchUuid": own, + })); + let unserved = + serde_json::json!({ "status": "pending_build", "url": null, "artifacts": [] }); + references.insert(own, unserved); } - 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)) - ) }, + builds.sort_by_key(|build| build["platform"].as_str().map(str::to_string)); + let key = &sha256_hex( + serde_json::Value::from(builds.clone()) + .to_string() + .as_bytes(), + )[..12]; + let registry = format!("https://patch.socket.dev/patch-registry/gem/grant-token/{uuid}/"); + let artifacts = artifacts(uuid, None); + // The registry serves upstream's own gem of a platform it lists with + // no patched build, under the snapshot the list goes by. + for (file, gem) in upstream_gems { + let route = format!("/patch-registry/gem/grant-token/{uuid}/s/{key}/gems/{file}"); + mounts.push((route, gem)); + } + let reference = |listed: bool| { + let mut identifiers = serde_json::json!({ + "name": PLAT, "version": PLAT_VERSION, "gemChecksumSha256": ruby_sha, }); - if let Some(platform) = platform { - artifact["platform"] = serde_json::json!(platform); + let mut index_url = registry.clone(); + if listed { + identifiers["gemBuilds"] = builds.clone().into(); + index_url = format!("{registry}s/{key}"); } - artifacts.push(artifact); + serde_json::json!({ + "status": "granted", + "purl": purl, + "url": artifacts[0]["url"], + "artifacts": artifacts, + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": index_url, + "identifiers": identifiers, + }, + }) + }; + let (with_list, plain) = (reference(true), reference(false)); + let gem_patch = uuid.to_string(); + Mock::given(method("POST")) + .and(path_regex(r"/(patch|patches)/package$")) + .respond_with(move |request: &wiremock::Request| { + let asked: serde_json::Value = + serde_json::from_slice(&request.body).unwrap_or_default(); + let mut results = serde_json::Map::new(); + for asked_uuid in asked["uuids"].as_array().into_iter().flatten() { + let Some(asked_uuid) = asked_uuid.as_str() else { + continue; + }; + let reference = match asked_uuid == gem_patch { + true if asked["gemBuilds"] == true => Some(&with_list), + true => Some(&plain), + false => references.get(asked_uuid), + }; + if let Some(reference) = reference { + results.insert(asked_uuid.to_string(), reference.clone()); + } + } + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "results": results })) + }) + .mount(&server) + .await; + for (route, bytes) in mounts { 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: { - "status": "granted", - "purl": purl, - "url": artifacts[0]["url"], - "artifacts": artifacts, - }} - }))) - .mount(&server) - .await; + for (own, record) in records { + Mock::given(method("GET")) + .and(path_regex(format!("/(patch|patches)/view/{own}$"))) + .respond_with(ResponseTemplate::new(200).set_body_json(record)) + .mount(&server) + .await; + } server } @@ -2917,35 +3087,123 @@ async fn service_requests(server: &MockServer) -> usize { .await .unwrap_or_default() .iter() - .filter(|r| r.url.path().ends_with("/package") || r.url.path().starts_with("/patch/gem/")) + .filter(|r| { + let path = r.url.path(); + path.ends_with("/package") + || path.starts_with("/patch/gem/") + || path.starts_with("/patch-registry/") + }) .count() } +/// The uuids each package reference request to `server` named, in arrival +/// order, each list sorted. Every request must have asked for the list of +/// the gem's builds. +async fn reference_requests(server: &MockServer) -> Vec> { + let requests = server.received_requests().await.unwrap_or_default(); + let mut asked = Vec::new(); + for request in requests + .iter() + .filter(|request| request.url.path().ends_with("/package")) + { + let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default(); + assert_eq!( + body["gemBuilds"], true, + "every package reference request asks for the list of the gem's builds: {body}" + ); + let uuids = body["uuids"].as_array().into_iter().flatten(); + let mut uuids: Vec = uuids + .filter_map(|uuid| uuid.as_str().map(str::to_string)) + .collect(); + uuids.sort(); + asked.push(uuids); + } + asked +} + +/// The events of `env` with `action` that are a platform gem's +/// (`details.gemFix`), as `(purl, uuid, gemFix, platform, errorCode)`, in +/// envelope order. +fn platform_gem_events( + env: &serde_json::Value, + action: &str, +) -> Vec<(String, String, String, String, String)> { + let text = |value: &serde_json::Value| value.as_str().unwrap_or_default().to_string(); + let events = env["events"].as_array().into_iter().flatten(); + events + .filter(|event| event["action"] == action && event["details"]["gemFix"].is_string()) + .map(|event| { + ( + text(&event["purl"]), + text(&event["uuid"]), + text(&event["details"]["gemFix"]), + text(&event["details"]["platform"]), + text(&event["errorCode"]), + ) + }) + .collect() +} + +/// One event per platform gem of `platforms` (in lock order), each under +/// that platform's own patch and naming the gem's patch as its fix. +fn per_platform_gem( + platforms: &[String], + code: &str, +) -> Vec<(String, String, String, String, String)> { + platforms + .iter() + .map(|platform| { + ( + platform_purl(platform), + build_uuid(UUID, platform), + UUID.to_string(), + platform.clone(), + code.to_string(), + ) + }) + .collect() +} + /// 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. Vendor takes the patched platform gem of +/// EVERY locked platform instead, each from that platform's own patch: /// /// 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 patched build (the service lists +/// upstream's own gem for it, or names a patch for it that is still +/// being built), or is one the service's list leaves out (a platform +/// upstream does not publish, which the line says with what settles +/// it), the gem is not vendored: the run +/// exits 0, says so in ONE line that names the platform, asks for the +/// gem patch's reference (and, where every platform is named a patch, +/// for the platform patches' in one request more), downloads no gem +/// and writes nothing, and a dry run says the same; +/// 3. with a patched build of every platform, a dry run names each +/// platform gem and writes nothing, and `vendor` asks for the gem +/// patch's reference and then for the platform patches in ONE +/// request, unpacks one tree per platform from that platform's own +/// gem (each with its stub gemspec), moves every platform block into +/// one `PATH` section, wires the Gemfile, records each tree's patch +/// and digests in the ledger, and reports one event per platform gem; +/// 4. `vex` attests each platform gem `(vendored)` under its own patch, +/// 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 -/// keeps the vendored one; -/// 7. `vendor --revert` restores the Gemfile and the lock byte for byte +/// and a newer patch that lacks one platform's patched build leaves +/// the vendored one in force; +/// 7. a ledger whose entry has the key `gemPlatforms` in place of +/// `gemBuilds` (as a development build recorded the platforms of the +/// copy) reads with the key ignored, and `vendor --revert` and +/// `rollback` each restore the Gemfile and the lock byte for byte; +/// 8. `vendor --revert` restores the Gemfile and the lock byte for byte /// (the registry CHECKSUMS tokens included) and removes the trees. /// /// Before the revert, a copy of the vendored project drops one platform @@ -3003,6 +3261,7 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) .collect(); let (own, foreign) = platforms.split_first().expect("platforms"); assert_eq!(foreign.len(), 2, "two foreign platforms: {platforms:?}"); + let none: &[String] = &[]; let proj = base.join("proj"); std::fs::create_dir_all(&proj).unwrap(); @@ -3080,61 +3339,353 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) PLAT_PRISTINE.as_bytes(), patched.as_bytes(), ); - let vendor = |server: &MockServer| { + let vendor_in = |root: &Path, server: &MockServer, json: bool| { let uri = server.uri(); - run_socket( - &proj, - &[ - "vendor", - "--json", - "--cwd", - proj.to_str().unwrap(), - "--patch-server-url", - &uri, - ], - ) + let mut args = vec!["vendor"]; + if json { + args.push("--json"); + } + args.extend(["--cwd", root.to_str().unwrap(), "--patch-server-url", &uri]); + run_socket(root, &args) }; + let vendor = |server: &MockServer| vendor_in(&proj, server, true); + let vendor_dry_run = |server: &MockServer| { + let uri = server.uri(); + let root = proj.to_str().unwrap(); + let flags = ["vendor", "--json", "--dry-run", "--cwd", root]; + run_socket(&proj, &[&flags[..], &["--patch-server-url", &uri]].concat()) + }; + // The project as it is before anything is vendored, for a person's run. + let unvendored = base.join("unvendored"); + common::fs_tree::copy_tree(&proj, &unvendored); + + // 2. One locked platform has no gem to vendor: the gem is not + // vendored, in one line, the run does not fail, no gem is + // downloaded and nothing is written. Either the service names a + // patch for that platform whose own reference says it is still + // being built (which a run learns from its second request, for the + // platform patches), or the list leaves the platform out, which is + // not one to wait for: the line says that the registry does not + // list it, and what settles that. A dry run says what the wet run + // says. (A platform the registry lists as upstream's own gem is + // vendored as that gem: step 2b.) + let mut own_patches: Vec = platforms.iter().map(|p| build_uuid(UUID, p)).collect(); + own_patches.sort(); + let (with_build, without_build) = platforms.split_at(2); + let mut have = with_build.to_vec(); + have.sort(); + let not_vendored = format!( + "{PLAT}@{PLAT_VERSION} is not vendored: no patched build yet for {} ({} and {} have \ + one). Vendored mode needs a gem, patched or upstream's own, for every locked platform; \ + `scan --mode hosted` can patch the \ + others now.", + without_build[0], have[0], have[1] + ); + let not_listed = format!( + "{PLAT}@{PLAT_VERSION} is not vendored: the patch registry does not list {0}. Vendored \ + mode needs a gem, patched or upstream's own, for every locked platform, and a re-run does \ + not change what the registry \ + lists: this is settled once the lockfile no longer names {0} (`bundle lock \ + --remove-platform {0}`), or the registry lists a gem for every locked platform.", + without_build[0] + ); + for building in [none, without_build] { + let not_vendored = match building.is_empty() { + true => ¬_listed, + false => ¬_vendored, + }; + let partial = + platform_patch_service(&fixture, &purl, UUID, with_build, none, building).await; + let mut asked = vec![vec![UUID.to_string()]]; + if !building.is_empty() { + asked.push(own_patches.clone()); + } + let (code, stdout, stderr) = vendor_dry_run(&partial); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let dry = parse_json_envelope(&stdout); + let previewed: Vec<&serde_json::Value> = dry["events"] + .as_array() + .unwrap() + .iter() + .filter(|e| e["action"] != "skipped" || e["reason"] != not_vendored.as_str()) + .collect(); + assert_eq!( + (dry["summary"]["skipped"].as_u64(), previewed.len()), + (Some(1), 0), + "a dry run says what the wet run says: {dry}" + ); + assert_eq!(reference_requests(&partial).await, asked); + let (code, stdout, stderr) = vendor(&partial); + assert_eq!( + code, 0, + "a platform with no patched build is no failure.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env = parse_json_envelope(&stdout); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!(env["summary"]["applied"], 0, "nothing vendored: {env}"); + assert_eq!(env["summary"]["failed"], 0, "and nothing failed: {env}"); + assert_eq!(env["summary"]["skipped"], 1, "one counted skip: {env}"); + let skipped = env["events"] + .as_array() + .unwrap() + .iter() + .find(|e| e["errorCode"] == "vendor_prebuilt_platform_pending") + .unwrap_or_else(|| panic!("a vendor_prebuilt_platform_pending event: {env}")); + assert_eq!(skipped["action"], "skipped", "{skipped}"); + assert_eq!(skipped["reason"], not_vendored.as_str(), "{skipped}"); + assert_eq!( + artifact_downloads(&partial).await, + Vec::::new(), + "the package reference says what is built: nothing is downloaded" + ); + assert_eq!( + reference_requests(&partial).await, + [asked.clone(), asked].concat(), + "the reference of the gem's own patch and, where it names a patch for every \ + platform, those of the platform patches: nothing else" + ); + assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_before); + assert_eq!(std::fs::read(&lock_path).unwrap(), lock_before); + assert!(!proj.join(".socket/vendor").exists(), "nothing is written"); + // For a person: that one line, and no warning. (The other line of + // stderr is the note that this run names no API token.) + let (code, stdout, stderr) = vendor_in(&unvendored, &partial, false); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let said: Vec<&str> = stderr + .lines() + .filter(|line| !line.contains("SOCKET_API_TOKEN")) + .collect(); + assert_eq!( + said, + [not_vendored.as_str()], + "one line on stderr:\n{stderr}" + ); + assert!( + stdout.contains("Vendored 0 packages; 1 skipped."), + "{stdout}" + ); + assert!(!unvendored.join(".socket/vendor").exists()); + } - // 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. - let partial = - platform_patch_service(&fixture.join("service"), &purl, 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}" - ); - let env = parse_json_envelope(&stdout); - assert_eq!(env["summary"]["applied"], 0, "nothing vendored: {env}"); - assert_eq!(env["summary"]["failed"], 0, "and nothing failed: {env}"); - let skipped = env["events"] - .as_array() - .unwrap() - .iter() - .find(|e| e["errorCode"] == "vendor_prebuilt_platform_pending") - .unwrap_or_else(|| panic!("a vendor_prebuilt_platform_pending event: {env}")); - 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}" - ); + // 2b. One locked platform has no patched build, and the registry + // serves upstream's own gem for it: the gem is vendored, with the + // patched build's tree for the platforms that have one (this + // machine's among them) and upstream's gem for the other. A fresh + // checkout installs frozen with no request to the patch service, + // Ruby loads the patched build, and revert restores both files. + { + let mixed = base.join("mixed"); + common::fs_tree::copy_tree(&proj, &mixed); + let server = + platform_patch_service(&fixture, &purl, UUID, with_build, without_build, none).await; + let unpatched = &without_build[0]; + let (code, stdout, stderr) = vendor_in(&mixed, &server, true); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let env = parse_json_envelope(&stdout); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!(env["summary"]["applied"], 2, "the patched builds: {env}"); + assert_eq!(env["summary"]["skipped"], 0, "{env}"); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + assert_eq!( + platform_gem_events(&env, "applied"), + per_platform_gem(&have, ""), + "{env}" + ); + let kept: Vec<_> = platform_gem_events(&env, "skipped") + .into_iter() + .filter(|event| event.4 == "gem_upstream_build_kept") + .collect(); + assert_eq!( + kept, + [( + platform_purl(unpatched), + String::new(), + UUID.to_string(), + unpatched.clone(), + "gem_upstream_build_kept".to_string() + )], + "the tree of upstream's gem is reported with no patch: {env}" + ); + assert!( + env["warnings"].as_array().is_none_or(Vec::is_empty), + "no warning: {env}" + ); + // The requests: the gem patch's list, the patched builds' + // references in one request, their gems and stubs, and upstream's + // gem from the gem patch's registry. + let mut patched_patches: Vec = + with_build.iter().map(|p| build_uuid(UUID, p)).collect(); + patched_patches.sort(); + assert_eq!( + reference_requests(&server).await, + [vec![UUID.to_string()], patched_patches] + ); + let registry_gems: Vec = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|r| r.url.path().starts_with("/patch-registry/")) + .filter_map(|r| r.url.path().rsplit('/').next().map(str::to_string)) + .collect(); + assert_eq!( + registry_gems, + [format!("{PLAT}-{PLAT_VERSION}-{unpatched}.gem")], + "upstream's gem comes from the patch server" + ); + assert_eq!(artifact_downloads(&server).await.len(), 4); + + let copy_rel = format!(".socket/vendor/gem/{UUID}/{PLAT}-{PLAT_VERSION}"); + for platform in &platforms { + let tree = mixed.join(©_rel).join(platform); + let expected = match platform == unpatched { + true => PLAT_PRISTINE, + false => patched.as_str(), + }; + assert_eq!( + std::fs::read_to_string(tree.join("lib/sockplat.rb")).unwrap(), + expected, + "{platform}" + ); + assert_eq!( + &std::fs::read_to_string(tree.join("lib/sockplat/build")).unwrap(), + platform, + "{platform}: the tree is that platform's own gem" + ); + } + let gemspec = mixed + .join(©_rel) + .join(unpatched) + .join(format!("{PLAT}.gemspec")); + let gemspec = std::fs::read_to_string(gemspec).unwrap(); + assert!( + gemspec.starts_with("--- !ruby/object:Gem::Specification"), + "the gemspec upstream's gem carries:\n{gemspec}" + ); + let lock = std::fs::read_to_string(mixed.join("Gemfile.lock")).unwrap(); + assert!( + lock.starts_with(&format!( + "PATH\n remote: {copy_rel}\n specs:\n{blocks}\nGEM\n" + )), + "every platform block sits in the one PATH section:\n{lock}" + ); + // For a person: one package, and the line that says which + // platforms are patched. + let person = base.join("mixed-person"); + common::fs_tree::copy_tree(&unvendored, &person); + let (code, stdout, stderr) = vendor_in(&person, &server, false); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!(stdout.contains("Vendored 1 package."), "{stdout}"); + let line = format!( + "{PLAT} {PLAT_VERSION}: patched for {}, {}; upstream gem kept for {unpatched} (no \ + patched build yet)", + have[0], have[1] + ); + let flat = stdout.replace("\n ", " "); + assert!(flat.contains(&line), "{line}\n{stdout}"); + let said: Vec<&str> = stderr + .lines() + .filter(|line| !line.contains("SOCKET_API_TOKEN")) + .collect(); + assert_eq!(said, Vec::<&str>::new(), "no warning:\n{stderr}"); + + // A fresh checkout: only the committable files. + let fresh = base.join("mixed-fresh"); + std::fs::create_dir_all(&fresh).unwrap(); + std::fs::copy(mixed.join("Gemfile"), fresh.join("Gemfile")).unwrap(); + std::fs::copy(mixed.join("Gemfile.lock"), fresh.join("Gemfile.lock")).unwrap(); + common::fs_tree::copy_tree(&mixed.join(".socket"), &fresh.join(".socket")); + common::fs_tree::copy_tree(&mixed.join(".bundle"), &fresh.join(".bundle")); + let lock_wired = std::fs::read(mixed.join("Gemfile.lock")).unwrap(); + let served_before = service_requests(&server).await; + let ci = bundle(&fresh, &["install"], true); + assert!( + ci.status.success(), + "a frozen `bundle install` over a copy with upstream's gem for a platform.\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&ci.stdout), + String::from_utf8_lossy(&ci.stderr), + ); + assert_eq!( + std::fs::read(fresh.join("Gemfile.lock")).unwrap(), + lock_wired + ); + let script = format!( + "require \"{declared}\"\n\ + abort \"probe constant missing after require\" unless defined?(Sockplat::SOCKET_PATCH_VENDOR_E2E)\n\ + loaded = $LOADED_FEATURES.grep(%r{{/sockplat\\.rb\\z}})\n\ + puts loaded\n\ + puts \"build=\" + File.read(File.join(File.dirname(loaded.first), \"sockplat/build\"))" + ); + let probe = bundle(&fresh, &["exec", "ruby", "-e", script.as_str()], false); + let probe_out = String::from_utf8_lossy(&probe.stdout).into_owned(); + assert!( + probe.status.success(), + "the runtime probe failed.\nstdout:\n{probe_out}\nstderr:\n{}", + String::from_utf8_lossy(&probe.stderr), + ); + assert!( + probe_out.contains(&format!("{copy_rel}/{own}/lib/sockplat.rb")) + && probe_out.contains(&format!("build={own}")), + "Ruby loads the patched build of the running platform:\n{probe_out}" + ); + for args in [&["install"][..], &["lock"][..]] { + let regen = bundle(&fresh, args, false); + assert!( + regen.status.success(), + "`bundle {}` over the vendored pair failed:\n{}", + args.join(" "), + String::from_utf8_lossy(®en.stderr) + ); + assert_eq!( + std::fs::read(fresh.join("Gemfile.lock")).unwrap(), + lock_wired, + "`bundle {}` regenerates the committed lock byte for byte", + args.join(" ") + ); + } + assert_eq!( + service_requests(&server).await, + served_before, + "the fresh checkout installs with no request to the patch service" + ); + + // `vendor --check` verifies the copy, and revert restores both + // files byte for byte. + let root = mixed.to_str().unwrap(); + let (code, stdout, stderr) = + run_socket(&mixed, &["vendor", "--check", "--json", "--cwd", root]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let (code, stdout, stderr) = + run_socket(&mixed, &["vendor", "--revert", "--json", "--cwd", root]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!( + std::fs::read(mixed.join("Gemfile")).unwrap(), + gemfile_before + ); + assert_eq!( + std::fs::read(mixed.join("Gemfile.lock")).unwrap(), + lock_before + ); + assert!(!mixed.join(".socket/vendor").exists()); + } + + // 3. A patched build of every platform: a dry run names the platform + // gems the wet run vendors and writes nothing; then vendor. + let preview = platform_patch_service(&fixture, &purl, UUID, &platforms, none, none).await; + let (code, stdout, stderr) = vendor_dry_run(&preview); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let dry = parse_json_envelope(&stdout); assert_eq!( - artifact_downloads(&partial).await, - Vec::::new(), - "the package reference says what is built: nothing is downloaded" + platform_gem_events(&dry, "verified"), + per_platform_gem(&sorted, ""), + "a dry run reports one `verified` event per platform gem: {dry}" ); + assert_eq!(dry["summary"]["verified"], 3, "each is counted: {dry}"); assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_before); assert_eq!(std::fs::read(&lock_path).unwrap(), lock_before); - assert!( - !proj.join(".socket/vendor/gem").exists(), - "no vendored copy is written" - ); - drop(partial); + assert!(!proj.join(".socket/vendor").exists(), "nothing is written"); - // 3. Every prebuild served: vendor. - let server = platform_patch_service(&fixture.join("service"), &purl, UUID, &platforms).await; + let server = platform_patch_service(&fixture, &purl, UUID, &platforms, none, none).await; let (code, stdout, stderr) = vendor(&server); assert_eq!( code, 0, @@ -3142,20 +3693,32 @@ 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}"); 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. + assert_eq!( + platform_gem_events(&env, "applied"), + per_platform_gem(&sorted, ""), + "one `applied` event per platform gem, each under its own patch: {env}" + ); + assert_eq!(env["summary"]["applied"], 3, "each is counted: {env}"); + // The gem patch's reference, then ONE request for the platform patches. + assert_eq!( + reference_requests(&server).await, + [vec![UUID.to_string()], own_patches.clone()], + "one batched reference request for the platform patches" + ); + // The platform gems and their stubs are all that is downloaded: the + // ruby gem the gem patch's reference names is not. let mut downloaded = artifact_downloads(&server).await; downloaded.sort(); - let mut prebuilds: Vec = platforms + let mut platform_files: Vec = platforms .iter() .flat_map(|p| ["gem", "gemspec"].map(|ext| format!("{PLAT}-{PLAT_VERSION}-{p}.{ext}"))) .collect(); - prebuilds.sort(); - assert_eq!(downloaded, prebuilds); + platform_files.sort(); + assert_eq!(downloaded, platform_files); - // One prebuild tree per platform, each with its own stub gemspec. + // One tree per platform, each that platform's own patched gem with its + // own stub gemspec. let copy_rel = format!(".socket/vendor/gem/{UUID}/{PLAT}-{PLAT_VERSION}"); for platform in &platforms { let tree = proj.join(©_rel).join(platform); @@ -3164,6 +3727,11 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) patched, "{platform}: the vendored tree must hold the patched bytes" ); + assert_eq!( + &std::fs::read_to_string(tree.join("lib/sockplat/build")).unwrap(), + platform, + "{platform}: the tree is that platform's own gem" + ); let stub = std::fs::read_to_string(tree.join(format!("{PLAT}.gemspec"))) .unwrap_or_else(|e| panic!("{platform}: stub gemspec not materialized: {e}")); assert!( @@ -3208,20 +3776,58 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) !lock.contains(&format!("\n {PLAT} ({PLAT_VERSION}-{own}) sha256=")), "a path gem's CHECKSUMS entry is bare:\n{lock}" ); - let state = std::fs::read_to_string(proj.join(".socket/vendor/state.json")).unwrap(); - let state: serde_json::Value = serde_json::from_str(&state).unwrap(); - let entry = state["entries"] - .as_object() - .and_then(|entries| entries.values().next()) - .unwrap_or_else(|| panic!("a ledger entry: {state}")); + // The ledger records which patch built which tree, and the digests its + // downloads passed. + let state_path = proj.join(".socket/vendor/state.json"); + let ledger_entry = || { + let state = std::fs::read_to_string(&state_path).unwrap(); + let state: serde_json::Value = serde_json::from_str(&state).unwrap(); + let entries = state["entries"].as_object().cloned(); + entries + .and_then(|entries| entries.values().next().cloned()) + .unwrap_or_else(|| panic!("a ledger entry: {state}")) + }; + let entry = ledger_entry(); + let recorded: Vec = sorted + .iter() + .map(|platform| { + let file = |ext: &str| { + let leaf = format!("{PLAT}-{PLAT_VERSION}-{platform}.{ext}"); + std::fs::read(fixture.join("service").join(leaf)).unwrap() + }; + serde_json::json!({ + "platform": platform, + "uuid": build_uuid(UUID, platform), + "gemIntegrity": sri(&file("gem")), + "gemspecIntegrity": sri(&file("gemspec")), + // The files of that build's own record, which the tree + // was checked against. + "files": { "lib/sockplat.rb": { + "beforeHash": git_sha256(PLAT_PRISTINE.as_bytes()), + "afterHash": git_sha256(patched.as_bytes()), + } }, + }) + }) + .collect(); + assert_eq!(entry["uuid"], UUID, "the entry is the gem patch's: {entry}"); assert_eq!( - entry["gemPlatforms"], - serde_json::json!(sorted), - "the ledger records the platform trees: {entry}" + entry["gemBuilds"], + serde_json::Value::from(recorded), + "the ledger records each tree's patch: {entry}" + ); + // For a person: one package, then nothing to do. + let (code, stdout, stderr) = vendor_in(&unvendored, &server, false); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!(stdout.contains("Vendored 1 package."), "{stdout}"); + let (code, stdout, stderr) = vendor_in(&unvendored, &server, false); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!( + stdout.contains("1 package is already vendored; nothing to do."), + "{stdout}" ); - // 4. VEX attests the patch against the committed trees, and `--check` - // covers every one of them. + // 4. VEX attests each platform gem against the committed trees, under + // the patch of its tree, and `--check` covers every one of them. let vex_path = proj.join("out.vex.json"); let (code, stdout, stderr) = run_socket( &proj, @@ -3242,13 +3848,17 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) assert_eq!(stmts.len(), 1, "the vendored patch must be attested: {doc}"); assert_eq!(stmts[0]["vulnerability"]["name"], GHSA); assert_eq!(stmts[0]["status"], "not_affected"); - assert!( - stmts[0]["impact_statement"] - .as_str() - .unwrap() - .contains("(vendored)"), - "vendored attestation must carry the (vendored) marker: {doc}" - ); + let impact = stmts[0]["impact_statement"].as_str().unwrap(); + for platform in &platforms { + let part = format!( + "Patched via Socket patch {} (vendored)", + build_uuid(UUID, platform) + ); + assert!( + impact.split("; ").any(|said| said == part), + "{platform}: attested under the patch of its tree: {doc}" + ); + } let check = |root: &Path| { let uri = server.uri(); run_socket( @@ -3269,6 +3879,11 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) code, 0, "vendor --check failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" ); + assert_eq!( + platform_gem_events(&parse_json_envelope(&stdout), "verified"), + per_platform_gem(&sorted, "vendor_check_ok"), + "one verdict per platform gem:\n{stdout}" + ); let tampered = base.join("tampered"); common::fs_tree::copy_tree(&proj, &tampered); std::fs::write( @@ -3310,7 +3925,9 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) "require \"{declared}\"\n\ abort \"probe constant missing after require\" unless defined?(Sockplat::SOCKET_PATCH_VENDOR_E2E)\n\ puts Sockplat::SOCKET_PATCH_VENDOR_E2E\n\ - puts $LOADED_FEATURES.grep(%r{{/sockplat\\.rb\\z}})" + loaded = $LOADED_FEATURES.grep(%r{{/sockplat\\.rb\\z}})\n\ + puts loaded\n\ + puts \"build=\" + File.read(File.join(File.dirname(loaded.first), \"sockplat/build\"))" ); let probe = bundle(&fresh, &["exec", "ruby", "-e", script.as_str()], false); assert!( @@ -3328,6 +3945,10 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) probe_out.contains(&format!("{copy_rel}/{own}/lib/sockplat.rb")), "the patched file must load from the tree of the running platform:\n{probe_out}" ); + assert!( + probe_out.contains(&format!("build={own}")), + "that tree is this machine's own platform gem:\n{probe_out}" + ); // The lock is the one bundler itself writes for this Gemfile: an // unfrozen install and a re-lock leave it byte-identical. for args in [&["install"][..], &["lock"][..]] { @@ -3352,12 +3973,14 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) "the fresh checkout installs with no request to the patch service" ); - // 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 - // its own runtime, which cannot be started (or dropped) from inside - // this test's async context. + // Manifest-less VEX over the fresh checkout: each platform gem is + // attested under the patch of its tree from the lock's PATH wiring and + // the vendor ledger, which records those patches. With the ledgers + // gone too nothing says which patch built which tree, and the gem is + // attested as itself from the lock and the patch API alone (the + // platform trees are then read off the committed directory). 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| { scope.spawn(|| { use vex_e2e_common::{ @@ -3377,11 +4000,19 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) product: Some(PRODUCT.into()), ..base }; - let base_purl = format!("pkg:gem/{PLAT}@{PLAT_VERSION}"); 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 { + assert_attested( + out.doc(), + &platform_purl(platform), + &build_uuid(UUID, platform), + Marker::Vendored, + VULNS, + ); + } + let base_purl = format!("pkg:gem/{PLAT}@{PLAT_VERSION}"); strip_ledgers(&fresh); let out = run_vex(&binary(), &fresh, &run(VexRun::online(&api))); assert_eq!(out.code, Some(0), "ledger-less vex: {out}"); @@ -3389,9 +4020,10 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) }); }); - // 6. A second run changes nothing and asks the service nothing. + // 6. A second run changes nothing. It asks the service for the gem + // patch's list, which names the builds the copy holds. let gemfile_wired = std::fs::read(&gemfile_path).unwrap(); - let state_wired = std::fs::read(proj.join(".socket/vendor/state.json")).unwrap(); + let state_wired = std::fs::read(&state_path).unwrap(); let (code, stdout, stderr) = vendor(&server); assert_eq!( code, 0, @@ -3399,30 +4031,32 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) ); let env2 = parse_json_envelope(&stdout); assert_eq!(env2["summary"]["failed"], 0, "re-run must not fail: {env2}"); - assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_wired); - assert_eq!(std::fs::read(&lock_path).unwrap(), lock_wired); assert_eq!( - std::fs::read(proj.join(".socket/vendor/state.json")).unwrap(), - state_wired + platform_gem_events(&env2, "skipped"), + per_platform_gem(&sorted, "already_vendored"), + "{env2}" ); + assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_wired); + assert_eq!(std::fs::read(&lock_path).unwrap(), lock_wired); + assert_eq!(std::fs::read(&state_path).unwrap(), state_wired); assert_eq!( service_requests(&server).await, - served_before, - "an in-sync re-run downloads nothing" + served_before + 1, + "an in-sync re-run asks for the gem patch's list and 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 patch of the gem that lacks the patched build of a platform + // the vendored copy holds one for: the vendored patch stays in force, + // and the run says so in one line 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; + platform_patch_service(&fixture, &purl, UUID_NEXT, with_build, without_build, none).await; let (code, stdout, stderr) = vendor(&update); assert_eq!( code, 0, - "an update that is not built yet is no failure.\nstdout:\n{stdout}\nstderr:\n{stderr}" + "an update that lacks a platform is no failure.\nstdout:\n{stdout}\nstderr:\n{stderr}" ); let env3 = parse_json_envelope(&stdout); assert_eq!(env3["summary"]["failed"], 0, "nothing failed: {env3}"); @@ -3433,29 +4067,81 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) .find(|e| e["errorCode"] == "vendor_prebuilt_platform_pending") .unwrap_or_else(|| panic!("a vendor_prebuilt_platform_pending event: {env3}")); assert_eq!(kept["action"], "skipped", "{kept}"); - let said = kept.to_string(); - assert!( - said.contains(&format!("kept the vendored patch {UUID}")) - && said.contains(&format!("`{}`", platforms[2])) - && said.contains(UUID_NEXT), - "the skip names the kept patch, the new one and the platform: {kept}" + assert_eq!( + kept["reason"], + format!( + "{PLAT}@{PLAT_VERSION} was not brought up to date: the newer fix has no patched \ + build for {} yet; its vendored copy of an earlier patch stays in force as it is.", + without_build[0] + ) + .as_str(), + "{kept}" ); assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_wired); assert_eq!(std::fs::read(&lock_path).unwrap(), lock_wired); - assert_eq!( - std::fs::read(proj.join(".socket/vendor/state.json")).unwrap(), - state_wired - ); + assert_eq!(std::fs::read(&state_path).unwrap(), state_wired); assert!( !proj .join(format!(".socket/vendor/gem/{UUID_NEXT}")) .exists(), - "nothing of the unbuilt patch is written" + "nothing of the newer patch is written" ); assert_eq!(artifact_downloads(&update).await, Vec::::new()); drop(update); std::fs::write(&manifest_path, manifest).unwrap(); + // 7. A ledger whose entry has the key `gemPlatforms` in place of + // `gemBuilds`, as a development build recorded the platforms of the + // copy. It reads with the key ignored: a check says of it what it + // says of the same ledger without the key. `vendor --revert` and + // `rollback` need nothing the key held: each restores the Gemfile + // and the lock Bundler wrote, byte for byte, and removes the trees. + let mut without_key: serde_json::Value = serde_json::from_slice(&state_wired).unwrap(); + for entry in without_key["entries"].as_object_mut().unwrap().values_mut() { + let removed = entry.as_object_mut().unwrap().remove("gemBuilds"); + assert!(removed.is_some(), "the entry names its trees: {entry}"); + } + let mut with_key = without_key.clone(); + for entry in with_key["entries"].as_object_mut().unwrap().values_mut() { + let entry = entry.as_object_mut().unwrap(); + entry.insert("gemPlatforms".into(), serde_json::json!(sorted)); + } + let check_over = |state: &serde_json::Value| { + std::fs::write(&state_path, serde_json::to_vec_pretty(state).unwrap()).unwrap(); + let (code, stdout, stderr) = check(&proj); + (code, parse_json_envelope(&stdout), stderr) + }; + let (plain_code, plain, _) = check_over(&without_key); + let (code, checked, stderr) = check_over(&with_key); + assert!( + checked["error"].is_null(), + "the ledger reads: {checked}\n{stderr}" + ); + assert_eq!((code, &checked), (plain_code, &plain), "the key is ignored"); + let unvendor: [&[&str]; 2] = [&["vendor", "--revert", "--json"], &["rollback", "--json"]]; + for command in unvendor { + let copy = base.join(format!("unvendored-by-{}", command[0])); + common::fs_tree::copy_tree(&proj, ©); + let args = [command, &["--cwd", copy.to_str().unwrap()]].concat(); + let (code, stdout, stderr) = run_socket(©, &args); + assert_eq!( + code, 0, + "{command:?} over an entry with the key.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_eq!( + std::fs::read(copy.join("Gemfile")).unwrap(), + gemfile_before, + "{command:?}" + ); + assert_eq!( + std::fs::read(copy.join("Gemfile.lock")).unwrap(), + lock_before, + "{command:?}" + ); + assert!(!copy.join(".socket/vendor/gem").exists(), "{command:?}"); + } + std::fs::write(&state_path, &state_wired).unwrap(); + // A platform the project drops after the gem is vendored (#2283): // `bundle lock --remove-platform` takes it out of the wired lock, // which still installs frozen, and `rollback` then gives back the lock @@ -3523,7 +4209,7 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) ); assert!(!removed.join(".socket/vendor").exists()); - // 7. Revert: both files byte for byte, every tree gone. + // 8. Revert: both files byte for byte, every tree gone. let (code, stdout, stderr) = run_socket( &proj, &[ diff --git a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs index f981d445c1..4e22dd43a5 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs @@ -2816,7 +2816,9 @@ fn gem_hosted_ref_is_verified_under_an_out_of_tree_config_bundle_path() { /// x86_64-linux/` dir with no gemspec. Nothing loads that dir, so `vex` /// attests the gem, in the project's bundle path and in an out-of-tree /// one alike. With its gemspec back the platform build is installed and -/// unpatched, and `vex` refuses again (#1092). +/// unpatched (#1092), and under this lock, whose `PLATFORMS` names `ruby` +/// alone, Bundler loads it in place of the ruby gem: `vex` exits 0 and +/// says `affected` of the gem, which is its state. #[test] fn gem_hosted_ref_is_attested_beside_a_leftover_platform_dir_with_no_gemspec() { const U: &str = "77777777-7777-7777-7777-777777777777"; @@ -2869,13 +2871,23 @@ fn gem_hosted_ref_is_attested_beside_a_leftover_platform_dir_with_no_gemspec() { let (code, env) = vex_json(&cwd, &args); assert_eq!( code, - Some(1), + Some(0), "an installed unpatched platform build (out of tree: {out_of_tree}): {env}" ); - let reason = skipped_reason(&env, purl); - assert!( - reason == "not_applied" || reason == "hash_mismatch", - "the platform build was read and failed verification, got {reason}: {env}" + assert_eq!( + skipped_reason(&env, purl), + "vex_gem_install_unpatched", + "the platform build was read, and the gem is stated as it is: {env}" ); + let doc: serde_json::Value = + serde_json::from_slice(&std::fs::read(cwd.join("out.vex.json")).unwrap_or_default()) + .unwrap_or_default(); + let statuses: Vec<&str> = doc["statements"] + .as_array() + .into_iter() + .flatten() + .filter_map(|statement| statement["status"].as_str()) + .collect(); + assert_eq!(statuses, ["affected"], "{doc}"); } } diff --git a/crates/socket-patch-cli/tests/get/get_platform_gem_uuid.rs b/crates/socket-patch-cli/tests/get/get_platform_gem_uuid.rs new file mode 100644 index 0000000000..c3d3a42959 --- /dev/null +++ b/crates/socket-patch-cli/tests/get/get_platform_gem_uuid.rs @@ -0,0 +1,772 @@ +//! `get ` where the uuid names the patch of ONE PLATFORM GEM (its +//! record's purl is `pkg:gem/@?platform=`), +//! against a stand-in patch service (the real binary; no Ruby or Bundler +//! runs here). +//! +//! In hosted and vendored mode a gem is patched through the patch of the +//! gem itself, whose reference names the patched build of every platform. +//! The patch of one platform gem is no fix of its own there, so the run +//! takes the patch it was built from, which that patch's package reference +//! names (`rebuiltFromUuid`), and goes on as `get ` does: +//! +//! * the project is left file for file as `get ` +//! leaves it, in both modes; +//! * one plain line says which patch was taken (stderr, once, fitted to a +//! terminal's width; nothing under `--silent`), and the `--json` +//! envelope names the patch that was asked for under `platformGemPatch`; +//! * it costs one reference request more, for the platform gem's patch; +//! * with no patch named for the build to come from, nothing is written +//! and the run names the command to run instead: hosted mode pins +//! nothing under a warning, vendored mode refuses +//! `platform_gem_unsupported`; +//! * agent mode applies the platform gem's own record to the installed +//! copy of that platform, with no reference request; +//! * the uuid of a patch of the gem itself, and of a patch of another +//! ecosystem, cost no request of this kind. + +use std::collections::BTreeMap; +use std::path::Path; + +use base64::Engine as _; +use serde_json::{json, Value}; +use sha2::{Digest, Sha512}; +use wiremock::matchers::{method, path as wm_path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +use crate::common::envelope::{ + envelope_error_code, envelope_error_message, event_triples, parse_json_envelope, +}; +use crate::common::{self, git_sha256, sha256_hex}; + +const ORG: &str = "test-org"; +/// A name nothing on the developer's machine can have installed. +const NAME: &str = "sockplatget"; +const VERSION: &str = "1.0.0"; +const PURL: &str = "pkg:gem/sockplatget@1.0.0"; +/// The gem's patch: the patch of its ruby gem, the one fix of the gem. +const UUID: &str = "6e7f0000-0000-4000-8000-000000000001"; +const DARWIN: &str = "arm64-darwin"; +const LINUX: &str = "x86_64-linux-gnu"; +/// The patches of its two patched platform gems. +const DARWIN_UUID: &str = "6e7f0000-0000-4000-8000-0000000000da"; +const LINUX_UUID: &str = "6e7f0000-0000-4000-8000-0000000000f1"; +const TOKEN: &str = "66666666-6666-4666-8666-666666666666"; +const LIB: &str = "lib/sockplatget.rb"; +const SO: &str = "lib/sockplatget/ext.so"; +const PRISTINE: &[u8] = b"module SockPlatGet; VERSION = '1.0.0'; end\n"; +const PATCHED: &[u8] = b"module SockPlatGet; VERSION = '1.0.0'; SAFE = true; end\n"; +const GHSA: &str = "GHSA-plat-form-gems"; +/// Shaped like a Socket API token, so no run warns about the token itself. +const API_TOKEN: &str = "sktsec_00000000000000000000000000000000000000000000_api"; + +const GEMFILE: &str = "source \"https://rubygems.org\"\n\ngem \"sockplatget\", \"~> 1.0\"\n"; + +/// Bundler's lock of a project that takes the gem as its two precompiled +/// platform gems. +fn lock() -> String { + format!( + "GEM\n remote: https://rubygems.org/\n specs:\n {NAME} ({VERSION}-{DARWIN})\n \ + {NAME} ({VERSION}-{LINUX})\n\nPLATFORMS\n {DARWIN}\n {LINUX}\n\nDEPENDENCIES\n \ + {NAME} (~> 1.0)\n\nBUNDLED WITH\n 2.5.22\n" + ) +} + +/// A minimal `.gem`: an uncompressed tar whose `data.tar.gz` holds `files`. +fn make_gem(files: &[(&str, &[u8])]) -> Vec { + let mut data = tar::Builder::new(Vec::new()); + for (path, bytes) in files { + let mut header = tar::Header::new_gnu(); + header.set_size(bytes.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + data.append_data(&mut header, path, *bytes).unwrap(); + } + let data_tar = data.into_inner().unwrap(); + let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut gz, &data_tar).unwrap(); + let data_tar_gz = gz.finish().unwrap(); + let mut gem = tar::Builder::new(Vec::new()); + let mut header = tar::Header::new_gnu(); + header.set_size(data_tar_gz.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + gem.append_data(&mut header, "data.tar.gz", data_tar_gz.as_slice()) + .unwrap(); + gem.into_inner().unwrap() +} + +/// The patched gem of `platform`: the patched Ruby file and the platform's +/// own binary. +fn platform_gem(platform: &str) -> Vec { + make_gem(&[(LIB, PATCHED), (SO, platform.as_bytes())]) +} + +fn stub(platform: &str) -> Vec { + format!( + "Gem::Specification.new do |s|\n s.name = \"{NAME}\"\n s.version = \"{VERSION}\"\n \ + s.platform = \"{platform}\"\n s.summary = \"a synthetic fixture gem\"\n \ + s.authors = [\"Socket\"]\n s.require_paths = [\"lib\"]\nend\n" + ) + .into_bytes() +} + +fn sri(bytes: &[u8]) -> String { + format!( + "sha512-{}", + base64::engine::general_purpose::STANDARD.encode(Sha512::digest(bytes)) + ) +} + +fn build_uuid(platform: &str) -> &'static str { + match platform { + DARWIN => DARWIN_UUID, + _ => LINUX_UUID, + } +} + +/// A patch record as the patch API's view serves it. +fn patch_view(uuid: &str, purl: &str) -> Value { + json!({ + "uuid": uuid, + "purl": purl, + "publishedAt": "2026-01-01T00:00:00Z", + "files": { + LIB: { + "beforeHash": git_sha256(PRISTINE), + "afterHash": git_sha256(PATCHED), + "blobContent": base64::engine::general_purpose::STANDARD.encode(PATCHED), + } + }, + "vulnerabilities": { + GHSA: { + "cves": ["CVE-2026-31337"], + "summary": "a synthetic vulnerability", + "severity": "high", + "description": "details" + } + }, + "description": "synthetic platform gem patch", + "license": "MIT", + "tier": "free" + }) +} + +/// What the reference of a platform gem's patch says of the patch it was +/// built from. +#[derive(Clone, Copy, Debug)] +enum BuiltFrom { + /// `rebuiltFromUuid`: the gem's patch. + Gem, + /// No such field. + Absent, + /// `rebuiltFromUuid: null`. + Null, + /// A value that is no patch uuid. + Malformed, + /// The uuid of a patch the service has no record of. + Unknown, + /// The patch of the gem's other platform gem. + PlatformPatch, + /// The reference request answers nothing for the patch. + NoResult, +} + +/// A uuid the stand-in has no record of. +const UNKNOWN_UUID: &str = "6e7f0000-0000-4000-8000-00000000dead"; +/// A second patch of the gem itself, whose record spells its purl with +/// `?platform=ruby`, and a patch of an npm package. The stand-in grants +/// neither a reference. +const RUBY_UUID: &str = "6e7f0000-0000-4000-8000-0000000000b1"; +const NPM_UUID: &str = "6e7f0000-0000-4000-8000-0000000000c2"; +const NPM_PURL: &str = "pkg:npm/sockplatget-js@1.0.0"; + +/// The patch service of the one gem: the gem's patch, whose reference +/// lists the version's gems (`gemBuilds`) under a registry snapshot, and +/// the patch of each platform gem, whose reference serves that gem and +/// its stub gemspec and names the gem's patch as `built_from` says. +async fn service(built_from: BuiltFrom) -> MockServer { + let server = MockServer::start().await; + let api = server.uri(); + let mut results = serde_json::Map::new(); + let ruby_gem = make_gem(&[(LIB, PATCHED)]); + let mut gem_builds = vec![json!({ + "platform": "ruby", "gemChecksumSha256": sha256_hex(&ruby_gem), "patchUuid": UUID + })]; + for platform in [DARWIN, LINUX] { + let own = build_uuid(platform); + let (gem, gemspec) = (platform_gem(platform), stub(platform)); + let base = format!("/patch/gem/{NAME}/{VERSION}/{TOKEN}/{own}/{NAME}-{VERSION}-{platform}"); + let mut artifacts = Vec::new(); + for (kind, ext, bytes) in [ + ("tarball", "gem", &gem), + ("gem-stub-gemspec", "gemspec", &gemspec), + ] { + let route = format!("{base}.{ext}"); + artifacts.push(json!({ + "kind": kind, + "url": format!("{api}{route}"), + "integrity": { "sha512": sri(bytes) } + })); + Mock::given(method("GET")) + .and(wm_path(route)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes.clone())) + .mount(&server) + .await; + } + gem_builds.push(json!({ + "platform": platform, "gemChecksumSha256": sha256_hex(&gem), "patchUuid": own + })); + let purl = format!("{PURL}?platform={platform}"); + let mut reference = json!({ + "status": "granted", + "purl": purl, + "url": format!("{api}{base}.gem"), + "artifacts": artifacts, + }); + match built_from { + BuiltFrom::Gem => reference["rebuiltFromUuid"] = json!(UUID), + BuiltFrom::Absent | BuiltFrom::NoResult => {} + BuiltFrom::Null => reference["rebuiltFromUuid"] = Value::Null, + BuiltFrom::Malformed => reference["rebuiltFromUuid"] = json!("../view/elsewhere"), + BuiltFrom::Unknown => reference["rebuiltFromUuid"] = json!(UNKNOWN_UUID), + BuiltFrom::PlatformPatch => reference["rebuiltFromUuid"] = json!(DARWIN_UUID), + } + if !matches!(built_from, BuiltFrom::NoResult) { + results.insert(own.to_string(), reference); + } + mount_view(&server, own, &purl).await; + } + gem_builds.sort_by_key(|build| build["platform"].as_str().map(str::to_string)); + let ruby_url = format!("{api}/patch/gem/{NAME}/{VERSION}/{TOKEN}/{UUID}/{NAME}-{VERSION}.gem"); + results.insert( + UUID.to_string(), + json!({ + "status": "granted", + "purl": PURL, + "url": ruby_url, + "artifacts": [{ "kind": "tarball", "url": ruby_url, + "integrity": { "sha512": sri(&ruby_gem), + "sha256": sha256_hex(&ruby_gem) } }], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": format!("{api}/patch-registry/gem/{TOKEN}/{UUID}/s/4f0a/"), + "identifiers": { + "name": NAME, "version": VERSION, + "gemChecksumSha256": sha256_hex(&ruby_gem), + "gemBuilds": gem_builds + } + } + }), + ); + Mock::given(method("POST")) + .and(wm_path(format!("/v0/orgs/{ORG}/patches/package"))) + .respond_with(move |request: &wiremock::Request| { + let asked: Value = serde_json::from_slice(&request.body).unwrap_or_default(); + let answered: serde_json::Map = asked["uuids"] + .as_array() + .into_iter() + .flatten() + .filter_map(|uuid| { + let uuid = uuid.as_str()?; + Some((uuid.to_string(), results.get(uuid)?.clone())) + }) + .collect(); + ResponseTemplate::new(200).set_body_json(json!({ "results": answered })) + }) + .mount(&server) + .await; + mount_view(&server, UUID, PURL).await; + mount_view(&server, RUBY_UUID, &format!("{PURL}?platform=ruby")).await; + mount_view(&server, NPM_UUID, NPM_PURL).await; + server +} + +async fn mount_view(server: &MockServer, uuid: &str, purl: &str) { + Mock::given(method("GET")) + .and(wm_path(format!("/v0/orgs/{ORG}/patches/view/{uuid}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(patch_view(uuid, purl))) + .mount(server) + .await; +} + +/// The patch API calls `server` has seen since its first `skip` requests: +/// the uuids each reference request named, and the uuid of each record +/// that was fetched, in arrival order. +async fn api_calls(server: &MockServer, skip: usize) -> (Vec>, Vec) { + let requests = server.received_requests().await.unwrap_or_default(); + let mut references = Vec::new(); + let mut views = Vec::new(); + for request in requests.iter().skip(skip) { + let route = request.url.path(); + if route.ends_with("/patches/package") { + let asked: Value = serde_json::from_slice(&request.body).unwrap_or_default(); + let uuids = asked["uuids"].as_array().into_iter().flatten(); + references.push( + uuids + .filter_map(|uuid| Some(uuid.as_str()?.to_string())) + .collect(), + ); + } else if let Some((_, uuid)) = route.rsplit_once("/patches/view/") { + views.push(uuid.to_string()); + } + } + (references, views) +} + +async fn request_count(server: &MockServer) -> usize { + server.received_requests().await.unwrap_or_default().len() +} + +/// A Bundler project that locks the gem as its two platform gems, in a +/// new temp dir. +fn project() -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("Gemfile"), GEMFILE).unwrap(); + std::fs::write(dir.path().join("Gemfile.lock"), lock()).unwrap(); + dir +} + +/// The arguments of `socket-patch get [--mode ]` against +/// `api`, with `extra` ones. +fn get_args<'a>( + api: &'a str, + uuid: &'a str, + mode: Option<&'a str>, + extra: &[&'a str], +) -> Vec<&'a str> { + let mut args = vec!["get", uuid, "--yes", "--api-url", api, "--proxy-url", api]; + args.extend_from_slice(&["--org", ORG, "--api-token", API_TOKEN]); + if let Some(mode) = mode { + args.extend_from_slice(&["--mode", mode]); + } + args.extend_from_slice(extra); + args +} + +/// `socket-patch get [--mode ]` at `root` against `api`, +/// with `extra` arguments. +fn get( + root: &Path, + api: &str, + uuid: &str, + mode: Option<&str>, + extra: &[&str], +) -> (i32, String, String) { + common::run_with_env(root, &get_args(api, uuid, mode, extra), &[]) +} + +/// [`get`] under `--json`: the exit code, the envelope and stderr. +fn get_json(root: &Path, api: &str, uuid: &str, mode: &str) -> (i32, Value, String) { + let (code, stdout, stderr) = get(root, api, uuid, Some(mode), &["--json"]); + (code, parse_json_envelope(&stdout), stderr) +} + +/// Every file under `root` with its content, by `/`-joined relative path. +/// A file reads as text (every file these runs write is text) with the +/// one thing that differs from run to run, the time a copy was vendored, +/// blanked. +fn tree(root: &Path) -> BTreeMap { + fn walk(dir: &Path, root: &Path, out: &mut BTreeMap) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + walk(&path, root, out); + continue; + } + let rel: Vec = path + .strip_prefix(root) + .unwrap() + .components() + .map(|part| part.as_os_str().to_string_lossy().into_owned()) + .collect(); + let text = String::from_utf8(std::fs::read(&path).unwrap()) + .unwrap_or_else(|_| panic!("{} is not text", path.display())); + let lines: Vec<&str> = text + .split_inclusive('\n') + .map( + |line| match line.trim_start().starts_with("\"vendoredAt\":") { + true => " \"vendoredAt\":