diff --git a/.github/workflows/nokogiri-compatibility.yml b/.github/workflows/nokogiri-compatibility.yml index 90f2c56bd4..6bf6256524 100644 --- a/.github/workflows/nokogiri-compatibility.yml +++ b/.github/workflows/nokogiri-compatibility.yml @@ -213,8 +213,14 @@ jobs: - {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: nothing is vendored until the service has it. - - {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, a platform passed through'} + # 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 965edb1d37..7d1e5ef96a 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1743,7 +1743,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 patched platform gem per locked platform, `-//`, each 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, 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. Every locked platform needs a patched build: while one has none the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. 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 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). socket-patch 5.1.0 and earlier have no platform-gem vendoring and do not read such a copy (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 checked and attested with the release that vendored it or a later one. 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): the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch rollback ` and then `socket-patch scan --mode vendored`. 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 each (`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`; human lines and totals count the gem as one package. `vex` attests each vendored platform gem under its own patch, from the committed ledger alone. 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 platform gem and a gem with a platform that has no patched build as the same one line and `skipped` event as the wet run, never as "would vendor". A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform 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 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 (the `ruby` platform, which no platform 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 | | 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 +2522,10 @@ command's integration tests check its output. | `vendor_maven_selection_undetermined` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): what the build selects for the artifact cannot be read (the reason says why: typically a pom the local repository does not hold, because the project was never resolved) and no declaration names the patch's base version, so nothing is pinned on a guess and no file is written. The reason carries the remedy that fits its cause (resolve the project once and re-run when a pom is missing from the local repository; otherwise declare the artifact at the base version). The vendored twin of `redirect_maven_selection_undetermined`. | | `vendor_maven_pin_would_move_module` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven reactor): the only poms that resolve the artifact at the patch's base version are parent poms above a module that resolves another version. A `` pin in the parent is inherited by that module and would move it, and Maven has no management that reaches a parent and not its children, so nothing is pinned and no file is written; the reason names the parent, the module and its version. When a sibling module does select the base version it is pinned and the same sentence is the `vendor_jvm_degraded` reason `pin_would_move_module`. | | `vendor_prebuilt_pending` / `vendor_prebuilt_unavailable` | `skipped` | vendor / scan / get `--mode vendored` (every ecosystem, #954, #1235): the package is already vendored at another patch uuid, and the patch service has no prebuilt artifact for the selected (superseding) uuid — still building (`pending_build`) / not served (`build_failed`, `not_found`, `withdrawn`, no usable artifact). Nothing is touched: the older patch's artifact, wiring and ledger entry stay in force, the detail names both uuids (`kept the vendored patch : prebuilt is still building for patch `, where `` is the backend's artifact kind: `artifact` for the npm family, `.gem`, `crate`, `module zip`, `dist zip`, `wheel`, `.jar`, `.nupkg`, …), and the run does not fail (exit 0), the way hosted mode keeps its pin and lists the upgrade in `redirect.skipped[]`. A re-run picks the new patch up once the service serves it. A 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, and a vendor / scan / get `--mode vendored` run that finds a platform gem's tree damaged (gem): 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. 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: `socket-patch rollback `, then `socket-patch scan --mode vendored`. | -| `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 patch's reference has no patched build for at least one locked platform: the platform is served as upstream's gem (`gemBuilds[].patchUuid` is null), or the list leaves it out; 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`). Vendored mode is all-or-nothing for such a gem. 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): `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 every locked platform; `scan --mode hosted` can patch the others now.` (with no platform patched: `… no patched build yet for arm64-darwin and x86_64-linux-gnu. Vendored mode needs every locked platform.`). A platform whose patch is listed but not served yet (still being built) counts the same way, and 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 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 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 every locked platform has a patched build. 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. | +| `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. | @@ -2612,8 +2614,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 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. | @@ -2663,7 +2666,7 @@ command's integration tests check its output. | `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 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. | +| `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. | 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/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 d384e69b6c..5cced1283d 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -13,6 +13,8 @@ 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; @@ -3917,112 +3919,6 @@ fn format_gem_manifest_edits( .collect() } -/// 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. -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 -} - /// What wiring a gem to its patch source costs the project's update /// workflow, said once per run under [`format_gem_manifest_edits`]' lines. /// 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 83ba3ded8b..4692e0645f 100644 --- a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs +++ b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs @@ -121,6 +121,31 @@ pub(crate) struct PreviewRow { /// 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 [`classify_vendor`]). @@ -202,14 +227,13 @@ impl VendorPreview { } }; let event = event.with_uuid(row.uuid.as_str()); - let events = match row.gem_builds.as_slice() { + let events = match row.gem_reports().as_slice() { [] => vec![event], - builds => { - crate::commands::vendor::gem_build_events(&event, &row.purl, &row.uuid, builds) - } + reports => crate::commands::vendor::gem_build_events(&event, reports), }; for event in events { - env.record(tag_mode(event, Some("vendored"))); + let event = tag_mode(event, Some("vendored")); + crate::commands::vendor::record_gem_build_event(env, event); } env.warnings.extend( row.warnings.iter().map(|w| { @@ -258,10 +282,13 @@ impl VendorPreview { 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)) + .filter(|row| would_vendor(row) || in_sync(row)) .map(|row| row.purl.as_str()) .collect(); let platform_gems: HashSet = @@ -276,9 +303,13 @@ impl VendorPreview { 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 { - if !would_vendor(row) || !platform_gems.contains(&row.purl) { + 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, @@ -290,9 +321,25 @@ impl VendorPreview { 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 @@ -317,6 +364,14 @@ impl VendorPreview { } } + /// 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> { @@ -357,6 +412,11 @@ impl VendorPreview { /// --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!( @@ -532,6 +592,7 @@ async fn preview_vendor_with( warnings, hosted: false, gem_builds: Vec::new(), + gem_recorded: None, } }) .collect(); diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index f643abb22d..ea4b33a5aa 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, @@ -314,6 +318,7 @@ async fn takeover_dry_refusal( // The pin this previews the takeover of stays when the backend // refuses. true, + None, &mut Vec::new(), )) .await; @@ -353,11 +358,13 @@ 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. Two arguments are the gem backend's alone (see +/// 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_preview` receives the +/// 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)] @@ -374,6 +381,7 @@ pub(crate) async fn dispatch_vendor_one( 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)?; @@ -450,6 +458,7 @@ pub(crate) async fn dispatch_vendor_one( force, service, hosted, + gem_list, gem_preview, ) .await @@ -734,6 +743,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" @@ -819,31 +831,121 @@ const GEM_FIX_DETAIL: &str = "gemFix"; /// `details` key of those events: the platform of the event's gem. const GEM_PLATFORM_DETAIL: &str = "platform"; -/// `event`, the outcome of a gem vendored as platform gems, once per tree -/// of `builds`: each names that platform gem -/// (`pkg:gem/@?platform=`) and its own patch, -/// and `details` ties it to the gem's patch `fix`. -pub(crate) fn gem_build_events( - event: &PatchEvent, +/// 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], -) -> Vec { + prior: Option<&[vendor::GemBuildEntry]>, + wrote: bool, +) -> Vec { builds .iter() .map(|built| { - let mut event = event.clone(); - event.purl = Some(built.purl(base_purl)); - event.uuid = Some(built.uuid.clone()); - let mut details = event + 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!(fix); - details[GEM_PLATFORM_DETAIL] = serde_json::json!(built.platform); - event.details = Some(details); - event + 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() } @@ -856,6 +958,9 @@ fn gem_fix_repeats(env: &Envelope, counted: impl Fn(&PatchEvent) -> bool) -> u32 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 @@ -1664,9 +1769,15 @@ async fn run_check(args: &VendorArgs) -> i32 { // 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() { - for event in gem_build_events(&event, &entry.base_purl, &entry.uuid, &entry.gem_builds) - { - env.record(event); + 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); @@ -2918,7 +3029,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), ) @@ -4385,6 +4498,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 @@ -4412,28 +4533,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()) @@ -4471,6 +4609,7 @@ pub(crate) async fn vendor_records_reusing( // 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; @@ -4497,16 +4636,47 @@ pub(crate) async fn vendor_records_reusing( // 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). - let gem_builds: Vec = match &outcome { + // 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(), - _ if !gem_preview.is_empty() => gem_preview, - _ => lookup_entry(&state.entries, candidate) - .filter(|entry| entry.ecosystem == "gem" && entry.uuid == record.uuid) - .map(|entry| entry.gem_builds.clone()) - .unwrap_or_default(), + }) => (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( @@ -4591,6 +4761,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 { @@ -4615,10 +4786,9 @@ pub(crate) async fn vendor_records_reusing( let per_build = matches!(event.action, PatchAction::Applied | PatchAction::Verified) || in_sync; - if per_build && !gem_builds.is_empty() { - for event in gem_build_events(&event, candidate, &record.uuid, &gem_builds) - { - env.record(event); + 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); @@ -4626,11 +4796,22 @@ pub(crate) async fn vendor_records_reusing( 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); @@ -4645,7 +4826,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 @@ -5005,6 +5189,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 @@ -6062,6 +6252,7 @@ mod dispatch_tests { &tokio::sync::OnceCell::new(), &Default::default(), false, + None, &mut Vec::new(), ) .await; @@ -8925,6 +9116,185 @@ mod ui_format_tests { .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 @@ -8937,7 +9307,7 @@ mod ui_format_tests { ) .with_reason("already_vendored", "in sync") .with_details(serde_json::json!({ "kept": true })); - let events = gem_build_events( + let events = build_events( &outcome, "pkg:gem/nokogiri@1.18.10?platform=ruby", "source", @@ -8975,7 +9345,7 @@ mod ui_format_tests { 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 gem_build_events(event, purl, "source", &nokogiri_builds()) { + for event in build_events(event, purl, "source", &nokogiri_builds()) { env.record(event); } }; @@ -9019,7 +9389,7 @@ mod ui_format_tests { // 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 gem_build_events( + for event in build_events( &PatchEvent::new(PatchAction::Applied, "pkg:gem/ffi@1.17.0"), "pkg:gem/ffi@1.17.0", "another", @@ -9059,16 +9429,19 @@ mod ui_format_tests { 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 every \ - locked platform; `scan --mode hosted` can patch the others now.", + (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 every \ - locked platform; the gem stays hosted.", + (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 every locked platform; its vendored copy stays in force as \ + 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 every locked platform, and a re-run does not change what the registry \ + "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 \ @@ -9095,7 +9468,7 @@ mod ui_format_tests { .with_reason("already_vendored", "in sync"), ); let since = env.events.len(); - for event in gem_build_events( + for event in build_events( &PatchEvent::new(PatchAction::Applied, gem), gem, "source", 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_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index a8d392eb6a..0cecff706e 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -518,7 +518,11 @@ fn gate_unattested( /// 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. +/// 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 @@ -561,6 +565,21 @@ pub(crate) struct GemBuildInfo { 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. @@ -618,32 +637,48 @@ impl GemBuildView { let mut builds = BTreeMap::new(); for (key, entry, record) in vendored { view.patches.remove(key); - let purls: Vec = entry - .gem_builds - .iter() - .map(|built| { - let purl = built.purl(&entry.base_purl); - // A purl the view already attests keeps its own record. - view.patches - .entry(purl.clone()) - .or_insert_with(|| PatchRecord { + 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: false, - unshown: None, }, - ); - purl - }) - .collect(); - platform_gems.insert(key.clone(), purls); + }, + ); + 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); @@ -2465,6 +2500,110 @@ mod tests { ); } + /// 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 diff --git a/crates/socket-patch-cli/src/ui/text.rs b/crates/socket-patch-cli/src/ui/text.rs index 96be986c97..5f6f60f162 100644 --- a/crates/socket-patch-cli/src/ui/text.rs +++ b/crates/socket-patch-cli/src/ui/text.rs @@ -482,16 +482,32 @@ mod tests { 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 \ - every locked platform; `scan --mode hosted` can patch the others now."; + (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 every\n \ - locked platform; `scan --mode hosted` can patch the others now." + (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] { + for line in [kept, waiting, vendored, unlisted] { let wrapped = wrap_line(line, Some(width)); assert!( wrapped.lines().all(|row| row.chars().count() <= width), 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 5e28de5d68..d9d39decc8 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 @@ -4364,7 +4364,8 @@ async fn refused_platform_gem_is_counted_as_left_to_patch() { _ => ( format!( "{DEP}@{DEP_VERSION} is not vendored: the patch registry does not list \ - {OTHER_PLATFORM}. Vendored mode needs every locked platform, and a re-run \ + {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." 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 9bbf8a1ee1..cd9b1adfa2 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -2867,7 +2867,8 @@ fn platform_purl(platform: &str) -> String { /// (`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); a platform in neither is one the list leaves out, as for a +/// 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 @@ -2969,11 +2970,13 @@ async fn platform_patch_service( }), ); } + 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); @@ -2993,6 +2996,12 @@ async fn platform_patch_service( )[..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, @@ -3078,7 +3087,12 @@ 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() } @@ -3340,15 +3354,16 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) let unvendored = base.join("unvendored"); common::fs_tree::copy_tree(&proj, &unvendored); - // 2. One locked platform has no patched build yet: the gem is not + // 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. The same whether the service - // lists upstream's own gem for that platform or names a patch for - // it whose own reference says it is still being built (which a run - // learns from its second request, for the platform patches). A - // platform the list leaves out 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. + // 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); @@ -3356,24 +3371,26 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) have.sort(); let not_vendored = format!( "{PLAT}@{PLAT_VERSION} is not vendored: no patched build yet for {} ({} and {} have \ - one). Vendored mode needs every locked platform; `scan --mode hosted` can patch the \ + 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 every locked platform, and a re-run does not change what the registry \ + 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 (listed, building) in [(without_build, none), (none, none), (none, without_build)] { - let not_vendored = match listed.is_empty() && building.is_empty() { + 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, listed, building).await; + 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()); @@ -3445,6 +3462,208 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) assert!(!unvendored.join(".socket/vendor").exists()); } + // 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; @@ -3796,7 +4015,8 @@ 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(&state_path).unwrap(); let (code, stdout, stderr) = vendor(&server); @@ -3816,13 +4036,13 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) 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 that lacks one platform's patched build: - // the vendored patch stays in force, and the run says so in one line - // 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(); @@ -3845,10 +4065,9 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) assert_eq!( kept["reason"], format!( - "{PLAT}@{PLAT_VERSION} was not brought up to date: no patched build yet for {} ({} \ - and {} have one). Vendored mode needs every locked platform; its vendored copy of \ - an earlier patch stays in force as it is.", - without_build[0], have[0], have[1] + "{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}" diff --git a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs index 36a5b646a2..e70cd45a43 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs @@ -94,6 +94,52 @@ fn platform_gem(platform: &str) -> Vec { ]) } +/// The gemspec upstream's gem for `platform` carries (its `metadata.gz`, +/// as YAML). +fn upstream_gemspec(platform: &str) -> String { + format!( + "--- !ruby/object:Gem::Specification\nname: {NAME}\nversion: \ + !ruby/object:Gem::Version\n version: {VERSION}\nplatform: {platform}\nauthors:\n- \ + Socket\nextensions: []\nrequire_paths:\n- lib\nsummary: a synthetic fixture gem\n" + ) +} + +/// Upstream's own gem of `platform`, which has no patched build: the +/// pristine Ruby file, upstream's binary, and its gemspec. +fn upstream_gem(platform: &str) -> Vec { + let gz = |bytes: &[u8]| { + let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut gz, bytes).unwrap(); + gz.finish().unwrap() + }; + let binary = format!("upstream's {platform}"); + let data = make_gem(&[(LIB, PRISTINE), (SO, binary.as_bytes())]); + // `make_gem` wraps the data archive alone: take it out and put the + // gemspec beside it, as a gem holds them. + let mut inner = tar::Archive::new(data.as_slice()); + let mut data_tar_gz = Vec::new(); + for entry in inner.entries().unwrap() { + std::io::Read::read_to_end(&mut entry.unwrap(), &mut data_tar_gz).unwrap(); + } + let mut gem = tar::Builder::new(Vec::new()); + let metadata = gz(upstream_gemspec(platform).as_bytes()); + for (name, bytes) in [("metadata.gz", &metadata), ("data.tar.gz", &data_tar_gz)] { + let mut header = tar::Header::new_gnu(); + header.set_size(bytes.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + gem.append_data(&mut header, name, bytes.as_slice()) + .unwrap(); + } + gem.into_inner().unwrap() +} + +/// Where the registry of the gem patch `uuid` serves upstream's gem of +/// `platform`. +fn upstream_route(uuid: &str, platform: &str) -> String { + format!("/patch-registry/gem/tok/{uuid}/s/4/gems/{NAME}-{VERSION}-{platform}.gem") +} + fn stub(platform: &str) -> Vec { format!( "Gem::Specification.new do |s|\n s.name = \"{NAME}\"\n s.version = \"{VERSION}\"\n \ @@ -168,8 +214,15 @@ fn build_files(platform: &str) -> serde_json::Value { }) } +/// A patch service where `linux` has a patched build and the patch of +/// darwin's build, which the gem patch's list names, is still being built. +async fn service_still_building_darwin() -> MockServer { + service_of(UUID, &[(DARWIN, Some("pending_build")), (LINUX, None)], &[]).await +} + /// A patch service where the platforms of `patched` have a patched build -/// and those of `pass_through` are listed as upstream's own gem. +/// and those of `pass_through` are listed as upstream's own gem, which the +/// gem patch's registry serves. async fn service(patched: &[&'static str], pass_through: &[&'static str]) -> MockServer { let granted: Vec<(&'static str, Option<&'static str>)> = patched.iter().map(|platform| (*platform, None)).collect(); @@ -250,9 +303,15 @@ async fn service_of( } } for platform in pass_through { + let gem = upstream_gem(platform); gem_builds.push(serde_json::json!({ - "platform": platform, "gemChecksumSha256": "ab".repeat(32), "patchUuid": null + "platform": platform, "gemChecksumSha256": sha256_hex(&gem), "patchUuid": null })); + Mock::given(method("GET")) + .and(wm_path(upstream_route(uuid, platform))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(gem)) + .mount(&server) + .await; } gem_builds.sort_by_key(|build| build["platform"].as_str().map(str::to_string)); let ruby_gem = make_gem(&[(LIB, &stamped(uuid))]); @@ -345,7 +404,7 @@ async fn downloads(server: &MockServer) -> Vec { let mut paths: Vec = requests .iter() .map(|request| request.url.path().to_string()) - .filter(|path| path.starts_with("/patch/gem/")) + .filter(|path| path.starts_with("/patch/gem/") || path.contains("/gems/")) .collect(); paths.sort(); paths @@ -404,10 +463,38 @@ fn run(root: &Path, args: &[&str], api: &str) -> (i32, String, String) { ) } +/// [`run`] with the failure points `failing` (`SOCKET_PATCH_FAILPOINT`): +/// each named step fails once, as a real fault there would. +fn run_failing(root: &Path, args: &[&str], api: &str, failing: &str) -> (i32, String, String) { + run_in(root, args, api, &[("SOCKET_PATCH_FAILPOINT", failing)]) +} + +/// [`run`] with `env` set for the process. +fn run_in(root: &Path, args: &[&str], api: &str, env: &[(&str, &str)]) -> (i32, String, String) { + run_with( + root, + args, + api, + &["--api-token", "fake-token", "--org", ORG], + env, + ) +} + /// [`run`] with the `credentials` flags in place of a token and its /// organisation. fn run_as(root: &Path, args: &[&str], api: &str, credentials: &[&str]) -> (i32, String, String) { + run_with(root, args, api, credentials, &[]) +} + +fn run_with( + root: &Path, + args: &[&str], + api: &str, + credentials: &[&str], + env: &[(&str, &str)], +) -> (i32, String, String) { let mut cmd = hermetic::command(&binary()); + cmd.envs(env.iter().copied()); hermetic::scrub_extra(&mut cmd, &[hermetic::Extra::Bundle]); cmd.env_remove("GEM_HOME").env_remove("GEM_PATH"); crate::common::jvm_env::isolate_cli(&mut cmd); @@ -591,7 +678,11 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { stdout.contains("1 package is already vendored; nothing to do."), "the gem is one package:\n{stdout}\n{stderr}" ); - assert_eq!(server.received_requests().await.unwrap().len(), asked); + assert_eq!( + server.received_requests().await.unwrap().len(), + asked + 2, + "each run asks for the gem patch's list, which names the builds the copy holds" + ); // 3. `vendor --check`: one verdict per platform gem. let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); @@ -670,109 +761,1393 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { ); assert_eq!( server.received_requests().await.unwrap().len(), - asked, - "offline" + asked + 2, + "`vendor --check` and an offline `vex` ask nothing" + ); + + // 5. A damaged tree: the check fails per platform gem, and the next + // run rebuilds the copy. The gem patch's reference says which patch + // each platform's gem is (the ledger must name the same ones), then + // those patches are asked for in one request. The run then finds + // the restored copy in step by the list the restore read, which + // hands it on: the gem patch's reference is asked for once. + std::fs::write(tree(root, LINUX).join(SO), b"another binary").unwrap(); + let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["failed"], 2, "{env:#}"); + assert_per_platform_gem(&env, "failed", "vendor_check_failed"); + let before = reference_requests(&server).await.len(); + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["rebuilt"], 1, "{env:#}"); + assert_per_platform_gem(&env, "skipped", "already_vendored"); + assert_eq!( + reference_requests(&server).await[before..], + [ + vec![UUID.to_string()], + vec![DARWIN_UUID.to_string(), LINUX_UUID.to_string()], + ] + ); + assert_eq!( + std::fs::read(tree(root, LINUX).join(SO)).unwrap(), + LINUX.as_bytes() + ); + + // 5b. The ledger is committed data, and it does not choose what is + // unpacked: with the patch of the linux tree edited to another + // served patch, the damaged tree is not restored from it. `repair`, + // which restores a copy as it was vendored, refuses, downloads + // nothing and names the command that vendors the current build. + // That command does: a vendor run takes the copy from the list of + // the gem's fix, as for a list that moved, so the tree is the + // build the list names and the ledger names its patch again. + let state_path = root.join(".socket/vendor/state.json"); + let honest = std::fs::read_to_string(&state_path).unwrap(); + std::fs::write(&state_path, honest.replace(LINUX_UUID, DARWIN_UUID)).unwrap(); + std::fs::write(tree(root, LINUX).join(SO), b"another binary").unwrap(); + // A dry run says what the wet run does. Both trees are patched in + // the ledger and in the list, under another patch for one of them: the + // copy is not in step, it would be vendored again. + let dry = with(VENDOR_IT, &["--dry-run"]); + let (code, stdout, stderr) = run(root, &dry, &server.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("Would vendor 1 package.") && !stdout.contains("already vendored"), + "{stdout}\n{stderr}" + ); + let fetched = downloads(&server).await.len(); + let repair = ["repair", "--download-only", "--json"]; + let (code, env, stderr) = run_json(root, &repair, &server.uri()); + assert_ne!(code, 0, "{env:#}\n{stderr}"); + // Said as what it is, a build that is no longer the one the fix + // names, under its own code and with the commands that vendor the + // current one: not as tampering, and not as a first vendoring. + let said = env.to_string(); + assert!( + said.contains("vendor_prebuilt_replaced") + && said.contains("cannot be restored as it was vendored") + && said.contains("the gem's fix now names patch") + && said.contains( + "Nothing was restored. Run `socket-patch scan --mode vendored`, which vendors \ + what the patch service serves now" + ) + && said.matches("`socket-patch ").count() == 1 + && !said.contains("rollback"), + "{env:#}" + ); + assert!( + !said.contains("vendor_prebuilt_integrity_mismatch"), + "{env:#}" + ); + assert_eq!( + downloads(&server).await.len(), + fetched, + "nothing is downloaded" + ); + assert_eq!( + std::fs::read(tree(root, LINUX).join(SO)).unwrap(), + b"another binary", + "nothing is unpacked" + ); + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["failed"], 0, "{env:#}"); + assert_eq!( + std::fs::read(tree(root, LINUX).join(SO)).unwrap(), + LINUX.as_bytes(), + "the build the list names" + ); + let ledger: serde_json::Value = + serde_json::from_slice(&std::fs::read(&state_path).unwrap()).unwrap(); + assert_eq!( + ledger["entries"][PURL]["gemBuilds"][1]["uuid"], LINUX_UUID, + "the ledger names the patch the tree came from: {ledger:#}" + ); + let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + + // 6. Revert. + let (code, env, stderr) = run_json(root, &["vendor", "--revert", "--json"], &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile")).unwrap(), + GEMFILE + ); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock() + ); + assert!(!root.join(".socket/vendor").exists()); +} + +/// A locked platform with no patched build, beside one that has one: the +/// gem is vendored. The patched platform gets its patched build's tree, +/// the other the tree of upstream's own gem, which the gem patch's +/// registry serves, with the gemspec that gem carries. The run counts the +/// patched build alone, reports the other as hosted mode does (the +/// advisory `gem_upstream_build_kept`, with no patch), and says which is +/// which in one line. A later run finds the copy in step, `vendor --check` +/// verifies it and finds a change to the upstream tree, `vex` attests the +/// patched build and states the other `affected`, and revert restores +/// both files byte for byte. +#[tokio::test] +async fn a_locked_platform_without_a_patched_build_gets_upstreams_gem() { + let server = service(&[LINUX], &[DARWIN]).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let line = format!( + "{NAME} {VERSION}: patched for {LINUX}; upstream gem kept for {DARWIN} (no patched build \ + yet)" + ); + let kept = + format!("the patch registry serves upstream's own gem for {DARWIN}: no patched build yet"); + let darwin_purl = format!("{PURL}?platform={DARWIN}"); + let linux_purl = format!("{PURL}?platform={LINUX}"); + // The events of the gem's trees: the patched build, counted, and the + // advisory one of upstream's gem, which `summary` leaves out. + let assert_trees = |env: &serde_json::Value, action: &str, code: &str| { + let trees: Vec<&serde_json::Value> = env["events"] + .as_array() + .unwrap() + .iter() + .filter(|event| event["details"]["gemFix"] == UUID) + .filter(|event| event["errorCode"] != "vendor_prebuilt_downloaded") + .collect(); + assert_eq!(trees.len(), 2, "{env:#}"); + let (upstream, patched) = (trees[0], trees[1]); + assert_eq!(upstream["action"], "skipped", "{env:#}"); + assert_eq!(upstream["purl"], darwin_purl.as_str(), "{env:#}"); + assert_eq!(upstream["errorCode"], "gem_upstream_build_kept", "{env:#}"); + assert_eq!(upstream["reason"], kept.as_str(), "{env:#}"); + assert!(upstream.get("uuid").is_none(), "no patch: {upstream:#}"); + assert_eq!(upstream["details"]["platform"], DARWIN, "{env:#}"); + assert_eq!(patched["action"], action, "{env:#}"); + assert_eq!(patched["purl"], linux_purl.as_str(), "{env:#}"); + assert_eq!(patched["uuid"], LINUX_UUID, "{env:#}"); + let coded = patched["errorCode"].as_str().unwrap_or_default(); + assert_eq!(coded, code, "{env:#}"); + }; + + // 1. A dry run says what the wet run does and writes nothing. + let dry = with(VENDOR_IT, &["--dry-run"]); + let (code, stdout, stderr) = run(root, &dry, &server.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains("Would vendor 1 package."), "{stdout}"); + assert!( + stdout.contains(&line.replace("patched for", "would be patched for")), + "{stdout}" + ); + assert_eq!(said_of_the_gem(&stderr), Vec::<&str>::new(), "{stderr}"); + assert_nothing_vendored(root); + + // 2. The wet run. + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["status"], "success", "{env:#}"); + assert_eq!(env["summary"]["applied"], 1, "{env:#}"); + assert_eq!(env["summary"]["skipped"], 0, "{env:#}"); + assert_eq!(env["summary"]["failed"], 0, "{env:#}"); + assert_trees(&env, "applied", ""); + assert!( + env["warnings"].as_array().is_none_or(Vec::is_empty), + "{env:#}" + ); + assert_eq!( + std::fs::read(tree(root, LINUX).join(LIB)).unwrap(), + stamped(LINUX_UUID) + ); + assert_eq!( + std::fs::read(tree(root, DARWIN).join(LIB)).unwrap(), + PRISTINE + ); + assert_eq!( + std::fs::read(tree(root, DARWIN).join(SO)).unwrap(), + format!("upstream's {DARWIN}").as_bytes() + ); + assert_eq!( + std::fs::read_to_string(tree(root, DARWIN).join(format!("{NAME}.gemspec"))).unwrap(), + upstream_gemspec(DARWIN), + "the gemspec upstream's gem carries" + ); + let lock_wired = std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(); + for platform in [DARWIN, LINUX] { + let block = format!("PATH\n remote: .socket/vendor/gem/{UUID}/{NAME}-{VERSION}\n"); + assert!(lock_wired.contains(&block), "{lock_wired}"); + assert!( + lock_wired.contains(&format!(" {NAME} ({VERSION}-{platform})\n")), + "{lock_wired}" + ); + } + // The requests: the gem patch's list, the reference of the one + // patched build, its gem and stub, and upstream's gem from the gem + // patch's registry. Nothing else is downloaded. + assert_eq!( + reference_requests(&server).await[2..], + [vec![UUID.to_string()], vec![LINUX_UUID.to_string()]] + ); + let base = format!("/patch/gem/{NAME}/{VERSION}/tok-{LINUX}/{LINUX_UUID}/{NAME}-{VERSION}"); + let wet = [ + format!("{base}.gem"), + format!("{base}.gemspec"), + upstream_route(UUID, DARWIN), + ]; + // (The dry run of `vendor` downloads and verifies the same three.) + let mut expected = [wet.clone(), wet].concat(); + expected.sort(); + assert_eq!(downloads(&server).await, expected); + // The ledger: the tree of upstream's gem names no patch. + let ledger: serde_json::Value = + serde_json::from_slice(&std::fs::read(root.join(".socket/vendor/state.json")).unwrap()) + .unwrap(); + let builds = &ledger["entries"][PURL]["gemBuilds"]; + assert_eq!(builds[0]["platform"], DARWIN, "{builds:#}"); + assert!(builds[0].get("uuid").is_none(), "{builds:#}"); + assert!(builds[0].get("files").is_none(), "{builds:#}"); + let sha256 = base64::engine::general_purpose::STANDARD + .encode(sha2::Sha256::digest(upstream_gem(DARWIN))); + assert_eq!( + builds[0]["gemIntegrity"], + format!("sha256-{sha256}").as_str() + ); + assert_eq!(builds[1]["uuid"], LINUX_UUID, "{builds:#}"); + + // 3. A later run: in step, one request (the list), the same line. + let asked = server.received_requests().await.unwrap().len(); + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 0, "{env:#}"); + assert_eq!(env["summary"]["skipped"], 1, "{env:#}"); + assert_trees(&env, "skipped", "already_vendored"); + assert_eq!(server.received_requests().await.unwrap().len(), asked + 1); + let (code, stdout, stderr) = run(root, VENDOR_IT, &server.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already vendored; nothing to do."), + "{stdout}" + ); + assert!(stdout.contains(&line), "{stdout}"); + assert_eq!(said_of_the_gem(&stderr), Vec::<&str>::new(), "{stderr}"); + + // 4. `vendor --check`: the patched tree verifies, the tree of + // upstream's gem is reported as such, and a change to it is found. + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["verified"], 1, "{env:#}"); + assert_trees(&env, "verified", "vendor_check_ok"); + let binary = tree(root, DARWIN).join(SO); + std::fs::write(&binary, b"not upstream's").unwrap(); + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); + assert_eq!( + env["summary"]["failed"], 2, + "every tree of the copy: {env:#}" + ); + std::fs::write(&binary, format!("upstream's {DARWIN}")).unwrap(); + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + + // 5. `vex`, offline from the ledger: the patched build is attested + // under its own patch, and the build on upstream's gem is stated + // affected, with what changes that. + let out = root.join("vex.json"); + let vex = [ + "vex", + "--offline", + "--json", + "--product", + "pkg:gem/app@1.0.0", + "--output", + out.to_str().unwrap(), + ]; + let (code, env, stderr) = run_json(root, &vex, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(&out).unwrap()).unwrap(); + let status_of = |purl: &str| -> Vec<(String, String)> { + let statements = doc["statements"].as_array().unwrap().iter(); + statements + .filter(|statement| statement.to_string().contains(purl)) + .map(|statement| { + let text = |key: &str| statement[key].as_str().unwrap_or_default().to_string(); + (text("status"), text("action_statement")) + }) + .collect() + }; + assert_eq!( + status_of(&linux_purl), + [("not_affected".to_string(), String::new())], + "{doc:#}" + ); + let affected = status_of(&darwin_purl); + assert_eq!(affected.len(), 1, "{doc:#}"); + assert_eq!(affected[0].0, "affected", "{doc:#}"); + assert_eq!( + affected[0].1, + format!( + "The vendored copy holds upstream's own gem for {DARWIN}: 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 {UUID}. Run `socket-patch scan --mode vendored` \ + again later: the copy takes the patched build once it is published." + ), + "{doc:#}" + ); + let kept_events: Vec<&serde_json::Value> = env["events"] + .as_array() + .unwrap() + .iter() + .filter(|event| event["errorCode"] == "gem_upstream_build_kept") + .collect(); + assert_eq!(kept_events.len(), 1, "{env:#}"); + assert_eq!(kept_events[0]["purl"], darwin_purl.as_str(), "{env:#}"); + + // 6. Revert. + let (code, env, stderr) = run_json(root, &["vendor", "--revert", "--json"], &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile")).unwrap(), + GEMFILE + ); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock() + ); + assert!(!root.join(".socket/vendor").exists()); +} + +/// The copy follows the builds the gem patch's registry lists. A later +/// run takes a patched build that was published since in place of +/// upstream's gem, and puts upstream's gem back where a patched build was +/// withdrawn: one line each, counted as hosted mode counts them, with no +/// warning, and a dry run says the same first. The Gemfile and the lock +/// stay as the first run left them. +#[tokio::test] +async fn a_later_run_follows_a_published_and_a_withdrawn_build() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + let lock_wired = std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(); + let darwin_lib = tree(root, DARWIN).join(LIB); + let linux_lib = tree(root, LINUX).join(LIB); + + let steps: [(&[&'static str], &[&'static str], String); 2] = [ + // The darwin build is published. + ( + &[DARWIN, LINUX], + &[], + format!("{NAME} {VERSION}: now also patched for {DARWIN}; already patched for {LINUX}"), + ), + // The linux build is withdrawn. + ( + &[DARWIN], + &[LINUX], + format!( + "{NAME} {VERSION}: patched for {DARWIN}; upstream gem back for {LINUX} (its \ + patched build was withdrawn)" + ), + ), + ]; + for (patched, pass_through, line) in steps { + let server = service(patched, pass_through).await; + let before = std::fs::read(&linux_lib).unwrap(); + let dry = with(VENDOR_IT, &["--dry-run"]); + let (code, stdout, stderr) = run(root, &dry, &server.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + let would = line + .replace("now also patched", "would also be patched") + .replace("gem back for", "gem would be back for"); + assert!(stdout.contains(&would), "{would}\n{stdout}"); + assert!(stdout.contains("Would vendor 1 package."), "{stdout}"); + assert_eq!( + std::fs::read(&linux_lib).unwrap(), + before, + "a dry run writes nothing" + ); + + let (code, stdout, stderr) = run(root, VENDOR_IT, &server.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains(&line), "{line}\n{stdout}"); + assert!(stdout.contains("Vendored 1 package."), "{stdout}"); + // Nothing on stderr but the note about this test's stand-in token. + let said: Vec<&str> = stderr + .lines() + .filter(|l| !l.contains("--api-token") && !l.contains("fake-token")) + .filter(|l| !l.trim().is_empty()) + .collect(); + assert_eq!(said, Vec::<&str>::new(), "no warning: {stderr}"); + let is_patched = |platform: &str| patched.contains(&platform); + for (lib, platform) in [(&darwin_lib, DARWIN), (&linux_lib, LINUX)] { + let expected = match is_patched(platform) { + true => stamped(build_uuid(platform)), + false => PRISTINE.to_vec(), + }; + assert_eq!(std::fs::read(lib).unwrap(), expected, "{platform}"); + } + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock_wired + ); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + + // In step again: each patched build the copy holds, already + // vendored. + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 0, "{env:#}"); + assert_eq!(env["summary"]["skipped"], patched.len(), "{env:#}"); + } + + // The JSON of a run that takes a published build: `applied` per + // patched build, `newlyPatched` on the one it put in place. + let server = service(&[DARWIN, LINUX], &[]).await; + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 2, "{env:#}"); + assert_per_platform_gem(&env, "applied", ""); + let newly: Vec<&str> = env["events"] + .as_array() + .unwrap() + .iter() + .filter(|event| event["details"]["newlyPatched"] == true) + .filter_map(|event| event["details"]["platform"].as_str()) + .collect(); + assert_eq!(newly, [LINUX], "{env:#}"); + assert!( + env["warnings"].as_array().is_none_or(Vec::is_empty), + "{env:#}" + ); + + // Revert: both files as they were before the first run. + let (code, env, stderr) = run_json(root, &["vendor", "--revert", "--json"], &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock() + ); + assert!(!root.join(".socket/vendor").exists()); +} + +/// Every regular file under `root`, by relative path. +fn snapshot(root: &Path) -> std::collections::BTreeMap> { + fn walk(base: &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(base, &path, out); + } else { + let rel = path + .strip_prefix(base) + .unwrap() + .to_string_lossy() + .into_owned(); + out.insert(rel, std::fs::read(&path).unwrap()); + } + } + } + let mut out = std::collections::BTreeMap::new(); + walk(root, root, &mut out); + out +} + +/// A copy that is damaged after the list of its fix moved is vendored +/// again from that list. The exact restore of the copy as it was vendored +/// is refused (the list names another build for a platform), and the run +/// goes on to what it does for an intact copy whose list moved, instead of +/// failing on every re-run until a rollback. Whichever tree is damaged: +/// the one of upstream's gem, or the patched one. +#[tokio::test] +async fn a_damaged_copy_is_vendored_from_the_list_once_the_list_moved() { + for damaged in [DARWIN, LINUX] { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + let lock_wired = std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(); + + // The darwin build is published, and a tree of the copy is damaged. + let server = service(&[DARWIN, LINUX], &[]).await; + std::fs::write(tree(root, damaged).join(SO), b"damaged").unwrap(); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 1, "{damaged}: {env:#}\n{stderr}"); + + // A dry run says what the wet run does: it would vendor the copy + // from the list, not download it again as it was. The refused + // restore hands the list it read to the backend, so either run + // asks for the fix's list once, and then for the patches it names. + let one_list = [ + vec![UUID.to_string()], + vec![DARWIN_UUID.to_string(), LINUX_UUID.to_string()], + ]; + let before = snapshot(root); + let asked = reference_requests(&server).await.len(); + let dry = with(VENDOR, &["--dry-run"]); + let (code, env, stderr) = run_json(root, &dry, &server.uri()); + assert_eq!(code, 0, "{damaged}: {env:#}\n{stderr}"); + assert_eq!( + reference_requests(&server).await[asked..], + one_list, + "{damaged}: the dry run" + ); + assert_per_platform_gem(&env, "verified", ""); + assert_eq!(env["summary"]["verified"], 2, "{damaged}: {env:#}"); + assert!( + !env.to_string().contains("wouldRedownload"), + "{damaged}: {env:#}" + ); + let newly: Vec<&str> = env["events"] + .as_array() + .unwrap() + .iter() + .filter(|event| event["details"]["newlyPatched"] == true) + .filter_map(|event| event["details"]["platform"].as_str()) + .collect(); + assert_eq!(newly, [DARWIN], "{damaged}: {env:#}"); + assert_eq!( + snapshot(root), + before, + "{damaged}: a dry run writes nothing" + ); + + let asked = reference_requests(&server).await.len(); + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{damaged}: {env:#}\n{stderr}"); + assert_eq!( + reference_requests(&server).await[asked..], + one_list, + "{damaged}: the wet run" + ); + assert_eq!(env["status"], "success", "{damaged}: {env:#}"); + assert_eq!(env["summary"]["failed"], 0, "{damaged}: {env:#}"); + assert_eq!(env["summary"]["applied"], 2, "{damaged}: {env:#}"); + assert_per_platform_gem(&env, "applied", ""); + for platform in [DARWIN, LINUX] { + assert_eq!( + std::fs::read(tree(root, platform).join(LIB)).unwrap(), + stamped(build_uuid(platform)), + "{damaged}: {platform} is the build the list names" + ); + assert_eq!( + std::fs::read(tree(root, platform).join(SO)).unwrap(), + platform.as_bytes(), + "{damaged}: {platform}" + ); + } + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock_wired, + "{damaged}" + ); + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{damaged}: {env:#}\n{stderr}"); + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{damaged}: {env:#}\n{stderr}"); + assert_per_platform_gem(&env, "skipped", "already_vendored"); + } +} + +/// An intact copy is never made worse, and a run never fails because of +/// something it could have left alone. The list of the gem's fix names a +/// patched build for a platform the copy holds upstream's gem for, and +/// that build cannot be vendored (its gem is not the one its patch +/// states). Every file of the project stays byte for byte what it was, the +/// run exits 0 and counts the copy as it counts one in step, and one line +/// says that the copy could not be brought in step and stays in force. A +/// dry run says the same. +#[tokio::test] +async fn an_intact_copy_stays_in_force_when_its_list_cannot_be_followed() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + let before = snapshot(root); + + let server = service(&[DARWIN, LINUX], &[]).await; + let gem = + format!("/patch/gem/{NAME}/{VERSION}/tok-{DARWIN}/{DARWIN_UUID}/{NAME}-{VERSION}.gem"); + Mock::given(method("GET")) + .and(wm_path(gem)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"not the gem".to_vec())) + .with_priority(1) + .mount(&server) + .await; + let note = format!( + "{NAME}@{VERSION} could not be brought in step with the builds the patch registry lists (" + ); + // The git metadata of the uuid dir is not part of the copy: the wet + // run puts back a file of it that is gone, the dry run writes nothing. + let gitattributes = root.join(format!(".socket/vendor/gem/{UUID}/.gitattributes")); + for flags in [&["--dry-run"][..], &[]] { + let dry_run = !flags.is_empty(); + // (Gone since the dry run, which wrote nothing, for the wet one.) + let _ = std::fs::remove_file(&gitattributes); + let mut before = before.clone(); + if dry_run { + let rel = gitattributes.strip_prefix(root).unwrap(); + before + .remove(&rel.to_string_lossy().into_owned()) + .expect("the file"); + } + let args = with(VENDOR, flags); + let (code, env, stderr) = run_json(root, &args, &server.uri()); + assert_eq!(code, 0, "{args:?}\n{env:#}\n{stderr}"); + assert_eq!(env["status"], "success", "{args:?}\n{env:#}"); + for (count, n) in [ + ("failed", 0), + ("applied", 0), + ("verified", 0), + ("skipped", 1), + ] { + assert_eq!( + env["summary"][count], n, + "{args:?} summary.{count}: {env:#}" + ); + } + let events = env["events"].as_array().unwrap(); + let of = |code: &str| -> Vec<&serde_json::Value> { + let coded = events.iter().filter(|event| event["errorCode"] == code); + coded.collect() + }; + let notes = of("vendor_gem_list_not_followed"); + let [said] = notes.as_slice() else { + panic!("{args:?}: one line: {env:#}"); + }; + let reason = said["reason"].as_str().unwrap_or_default(); + assert!( + reason.starts_with(¬e) + && reason.ends_with("); its vendored copy stays in force as it is."), + "{args:?}: {reason}" + ); + assert_eq!(of("already_vendored").len(), 1, "{args:?}: {env:#}"); + assert_eq!(of("gem_upstream_build_kept").len(), 1, "{args:?}: {env:#}"); + assert_eq!( + snapshot(root), + before, + "{args:?}: every file, byte for byte" + ); + assert_eq!(gitattributes.exists(), !dry_run, "{args:?}"); + } + + // For a person: the copy is already vendored, the line of the gem as + // the copy holds it, and the note. No error and no warning. + let (code, stdout, stderr) = run(root, VENDOR_IT, &server.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already vendored; nothing to do."), + "{stdout}" + ); + assert!( + stdout.contains(&format!( + "{NAME} {VERSION}: patched for {LINUX}; upstream gem kept for {DARWIN} (no patched \ + build yet)" + )), + "{stdout}" + ); + let said: Vec<&str> = stderr + .lines() + .filter(|l| !l.contains("--api-token") && !l.contains("fake-token")) + .filter(|l| !l.trim().is_empty()) + .collect(); + assert!( + matches!(said.as_slice(), [line] if line.starts_with(&format!("Note: {note}"))), + "one note, no error and no warning:\n{stderr}" + ); + assert_eq!(snapshot(root), before); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); +} + +/// A run that could not vendor an intact copy again says that the copy +/// stays in force only when it still stands. One failure happens after +/// the copy was changed, and is a failure the user sees (exit 1, the +/// error, no word of a copy in force): the stage cannot be moved into +/// place and the copy that was moved aside cannot be moved back, so the +/// lock names a path that holds nothing (the old copy is kept beside it). +/// The next run vendors the copy again from the list, as for any damaged +/// copy. +#[tokio::test] +async fn a_copy_changed_by_a_failed_rebuild_is_not_said_to_stay_in_force() { + let copy = format!(".socket/vendor/gem/{UUID}/{NAME}-{VERSION}"); + let failing = "vendor_swap_stage~fail,vendor_swap_restore~fail"; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + let ledger = std::fs::read(root.join(".socket/vendor/state.json")).unwrap(); + + // The darwin build is published: the list moved. + let server = service(&[DARWIN, LINUX], &[]).await; + let (code, stdout, stderr) = run_failing(root, VENDOR_IT, &server.uri(), failing); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!( + stderr.contains("Error:") + && stderr.contains("failpoint `vendor_swap_stage` injected an error"), + "{stderr}" + ); + let said = format!("{stdout}\n{stderr}"); + assert!( + !said.contains("stays in force") && !said.contains("already vendored"), + "the copy is not in force as it was:\n{said}" + ); + assert!(stdout.contains("1 failed"), "{stdout}"); + assert_eq!( + std::fs::read(root.join(".socket/vendor/state.json")).unwrap(), + ledger, + "the ledger is as it was" ); + // The path the lock names holds nothing; the old copy is beside it. + assert!(!root.join(©).exists()); + assert!(root.join(format!("{copy}.socket-old")).exists()); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); + + // The next run: vendored again from the list. + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["failed"], 0, "{env:#}"); + for platform in [DARWIN, LINUX] { + assert_eq!( + std::fs::read(tree(root, platform).join(LIB)).unwrap(), + stamped(build_uuid(platform)), + "{platform}" + ); + } + assert!(!root.join(format!("{copy}.socket-old")).exists()); + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); +} + +/// The git metadata of the uuid directory is not part of the copy: it is +/// written once the new trees are in place, and a write that fails (a +/// directory stands where the file belongs) is a warning, never a +/// failure. The run exits 0 with the trees the list names in place and +/// the ledger recording them, says the warning every backend gives for +/// ignore rules it could not vouch for, and says nothing of a copy that +/// stays as it was. +#[tokio::test] +async fn metadata_that_cannot_be_written_is_a_warning_and_the_copy_is_vendored() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + let gitattributes = root.join(format!(".socket/vendor/gem/{UUID}/.gitattributes")); + std::fs::remove_file(&gitattributes).unwrap(); + std::fs::create_dir(&gitattributes).unwrap(); + std::fs::write(gitattributes.join("in the way"), b"").unwrap(); + + // The darwin build is published: the list moved. + let server = service(&[DARWIN, LINUX], &[]).await; + let (code, stdout, stderr) = run(root, VENDOR_IT, &server.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("Vendored 1 package.") + && stdout.contains(&format!( + "{NAME} {VERSION}: now also patched for {DARWIN}; already patched for {LINUX}" + )), + "{stdout}" + ); + assert!( + stderr.contains(&format!( + "Warning: could not write `.socket/vendor/gem/{UUID}/.gitignore` and \ + `.socket/vendor/gem/{UUID}/.gitattributes` (" + )) && stderr.contains("make those two files writable and run this again"), + "{stderr}" + ); + let said = format!("{stdout}\n{stderr}"); + assert!( + !said.contains("Error:") && !said.contains("stays in force") && !said.contains("failed"), + "{said}" + ); + for platform in [DARWIN, LINUX] { + assert_eq!( + std::fs::read(tree(root, platform).join(LIB)).unwrap(), + stamped(build_uuid(platform)), + "{platform}" + ); + } + let recorded = &ledger(root)["entries"][PURL]["gemBuilds"]; + let patches: Vec<&str> = recorded + .as_array() + .into_iter() + .flatten() + .filter_map(|built| built["uuid"].as_str()) + .collect(); + assert_eq!(patches, [DARWIN_UUID, LINUX_UUID], "{recorded:#}"); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); +} + +/// `git ` in `root`, which must succeed. +fn git(root: &Path, args: &[&str]) { + let status = std::process::Command::new("git") + .arg("-C") + .arg(root) + .args(args) + .status() + .expect("run git"); + assert!(status.success(), "git {args:?}"); +} + +/// A project that is a git work tree whose own rules ignore compiled +/// binaries (`*.so`), as stock templates do. `None` without git. +fn git_project_ignoring_binaries() -> Option { + let tmp = tempfile::tempdir().unwrap(); + let init = std::process::Command::new("git") + .arg("-C") + .arg(tmp.path()) + .args(["init", "-q"]) + .status(); + if !init.is_ok_and(|status| status.success()) { + return None; + } + write_project(tmp.path()); + std::fs::write(tmp.path().join(".gitignore"), "*.so\n").unwrap(); + Some(tmp) +} + +/// Put a directory where the uuid directory's `.gitignore` belongs, so +/// that no run can write that file. +fn obstruct_gitignore(root: &Path) { + let gitignore = root.join(format!(".socket/vendor/gem/{UUID}/.gitignore")); + let _ = std::fs::remove_file(&gitignore); + std::fs::create_dir_all(gitignore.join("in the way")).unwrap(); +} + +/// Whether a run's summary says it vendored the gem, or would. +fn says_it_vendors(stdout: &str) -> bool { + stdout.contains("Vendored 1 package.") || stdout.contains("Would vendor 1 package.") +} + +/// What a run says of a copy git would not commit because the uuid +/// directory's own ignore rules could not be written. +fn assert_refused_for_unwritten_metadata(said: &str) { + let cause = format!( + "`.socket/vendor/gem/{UUID}/.gitignore` and `.socket/vendor/gem/{UUID}/.gitattributes`, \ + which keep such a rule off it, could not be written (" + ); + assert!( + said.contains("git would not commit the vendored artifact at") + && said.contains(&cause) + && said.contains("make those two files writable and vendor again"), + "{said}" + ); +} + +/// Git is asked whether it would commit a copy only where trees are about +/// to be placed, before they are moved in, and a dry run asks the same. A +/// refusal 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, and a damaged copy is not restored. A copy that +/// is already there asks git nothing. Here a project rule ignores the +/// binaries (`*.so`) and the uuid directory's `.gitignore`, which keeps +/// such a rule off them, cannot be written. +#[tokio::test] +async fn a_copy_git_would_not_commit_is_refused_before_its_trees_are_placed() { + let check = ["vendor", "--check", "--json"]; + let failed_with = |env: &serde_json::Value, code: &str| -> String { + let failed = env["events"] + .as_array() + .into_iter() + .flatten() + .find(|event| event["action"] == "failed" && event["errorCode"] == code); + let failed = failed.unwrap_or_else(|| panic!("a failed `{code}` event: {env:#}")); + failed["error"].as_str().unwrap_or_default().to_string() + }; + let dry = with(VENDOR, &["--dry-run"]); + + // 1. A first vendor, dry and wet: refused, and nothing is written. + let Some(project) = git_project_ignoring_binaries() else { + return; // no git, nothing to commit + }; + let root = project.path(); + let lock_before = std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(); + let first = service(&[LINUX], &[DARWIN]).await; + obstruct_gitignore(root); + let before = snapshot(root); + let (code, env, stderr) = run_json(root, &dry, &first.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); + assert_refused_for_unwritten_metadata(&failed_with(&env, "vendor_artifact_gitignored")); + assert_eq!(snapshot(root), before, "a dry run writes nothing"); + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); + assert_refused_for_unwritten_metadata(&failed_with(&env, "vendor_artifact_gitignored")); + assert!(!root.join(format!(".socket/vendor/gem/{UUID}")).exists()); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock_before + ); + // (The refused copy was removed whole, with what stood in its way.) + obstruct_gitignore(root); + let (code, _stdout, stderr) = run(root, VENDOR_IT, &first.uri()); + assert_eq!(code, 1, "{stderr}"); + assert!(stderr.contains("Error:"), "{stderr}"); + assert_refused_for_unwritten_metadata(&stderr); + + // The copy vendored, then its `.gitignore` made unwritable. + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + obstruct_gitignore(root); + let vendored = snapshot(root); + let warning = format!("Warning: could not write `.socket/vendor/gem/{UUID}/.gitignore` and"); + + // 2. In step: git is asked nothing. The copy stands, and the run says + // what it could not write. + let (code, stdout, stderr) = run(root, VENDOR_IT, &first.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already vendored; nothing to do."), + "{stdout}" + ); + assert!( + stderr.contains(&warning) && !stderr.contains("Error:"), + "{stderr}" + ); + assert_eq!(snapshot(root), vendored, "in step"); + + // 3. A build the list names is not served yet: the copy stays in + // force, and the skip's line ends with the same. + let building = service_still_building_darwin().await; + let (code, stdout, stderr) = run(root, VENDOR_IT, &building.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stderr.contains("its vendored copy stays in force as it is. Also: could not write `"), + "{stderr}" + ); + assert_eq!(snapshot(root), vendored, "a pending build"); + + // 4. The list moved: the intact copy stays in force, byte for byte, + // dry and wet, and the note names the rule and the cause. + let moved = service(&[DARWIN, LINUX], &[]).await; + for args in [with(VENDOR_IT, &["--dry-run"]), VENDOR_IT.to_vec()] { + let (code, stdout, stderr) = run(root, &args, &moved.uri()); + assert_eq!(code, 0, "{args:?}: {stdout}\n{stderr}"); + let notes: Vec<&str> = stderr.lines().filter(|l| l.starts_with("Note:")).collect(); + assert!( + matches!(notes.as_slice(), [note] if note.starts_with(&format!( + "Note: {NAME}@{VERSION} could not be brought in step with the builds the patch \ + registry lists (git would not commit the vendored artifact at" + )) && note.contains(".gitignore:1:*.so") + && note.ends_with("its vendored copy stays in force as it is.")), + "{args:?}: {stderr}" + ); + assert_refused_for_unwritten_metadata(&stderr); + assert!( + !stderr.contains("Error:") && !says_it_vendors(&stdout), + "{args:?}: {stdout}\n{stderr}" + ); + assert_eq!(snapshot(root), vendored, "{args:?}"); + } + let (code, env, stderr) = run_json(root, &check, &moved.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + + // 5. A damaged tree: neither `repair` nor a vendor run moves in trees + // git would not commit, and the copy is as it was. + std::fs::write(tree(root, LINUX).join(SO), b"damaged").unwrap(); + let damaged = snapshot(root); + for restore in [&["repair", "--download-only", "--json"][..], VENDOR] { + let (code, env, stderr) = run_json(root, restore, &first.uri()); + assert_ne!(code, 0, "{restore:?}: {env:#}\n{stderr}"); + assert_refused_for_unwritten_metadata(&env.to_string()); + assert!( + env.to_string().contains("vendor_artifact_gitignored"), + "{restore:?}: {env:#}" + ); + assert_eq!( + snapshot(root), + damaged, + "{restore:?}: the copy is as it was" + ); + } +} + +/// An intact copy that is committed, whose list moves while a project +/// rule would keep a new file out of the commit (one that excludes the +/// vendored directory, added since): the copy is byte for byte what it +/// was, the run ends as it does for an intact copy, and one note names +/// the rule. A dry run says the same. +#[tokio::test] +async fn a_committed_copy_stays_as_it_is_when_a_rule_would_ignore_what_its_list_names() { + let Some(project) = git_project_ignoring_binaries() else { + return; // no git, nothing to commit + }; + let root = project.path(); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + git(root, &["add", "-f", "."]); + git( + root, + &[ + "-c", + "user.name=test", + "-c", + "user.email=test@example.invalid", + "-c", + "commit.gpgsign=false", + "commit", + "-q", + "-m", + "vendor", + ], + ); + std::fs::write(root.join(".gitignore"), "*.so\n/.socket/vendor/gem/\n").unwrap(); + let committed = snapshot(root); + + let moved = service(&[DARWIN, LINUX], &[]).await; + for args in [with(VENDOR_IT, &["--dry-run"]), VENDOR_IT.to_vec()] { + let (code, stdout, stderr) = run(root, &args, &moved.uri()); + assert_eq!(code, 0, "{args:?}: {stdout}\n{stderr}"); + let notes: Vec<&str> = stderr.lines().filter(|l| l.starts_with("Note:")).collect(); + assert!( + matches!(notes.as_slice(), [note] if note.starts_with(&format!( + "Note: {NAME}@{VERSION} could not be brought in step with the builds the patch \ + registry lists (git would not commit the vendored artifact at" + )) && note.contains(".gitignore:2:/.socket/vendor/gem/") + && note.ends_with("its vendored copy stays in force as it is.")), + "{args:?}: {stderr}" + ); + let warned = stderr + .lines() + .any(|l| l.starts_with("Warning:") && !l.contains("--api-token")); + assert!( + !stderr.contains("Error:") && !warned && !says_it_vendors(&stdout), + "{args:?}: {stdout}\n{stderr}" + ); + assert_eq!(snapshot(root), committed, "{args:?}: byte for byte"); + } + let (code, env, stderr) = run_json(root, VENDOR, &moved.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["failed"], 0, "{env:#}"); + assert_eq!(env["summary"]["applied"], 0, "{env:#}"); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &moved.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); +} + +/// A project that was exported without its `.git` into a directory an +/// outer repository ignores (an artifact in `build/` of a CI workspace). +/// The gem's backend asks git nothing about a copy in step, so it adds +/// no refusal there: a scan's dry run finds the copy `already_vendored` +/// and exits 0. A wet scan still refuses such a project before it looks +/// at any package, as it does on the base branch and in 5.1.0, by the +/// run's own ledger check (`vendor_artifact_gitignored` for +/// `.socket/vendor`, by the outer rule): git would commit neither the +/// ledger nor the copy from there. What is pinned here is that the +/// refusal is that one, and not one of the gem's. +#[tokio::test] +async fn a_project_in_an_ignored_directory_of_an_outer_repository_is_refused_by_the_run_alone() { + fn copy_tree(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap() { + let entry = entry.unwrap(); + let target = to.join(entry.file_name()); + if entry.path().is_dir() { + copy_tree(&entry.path(), &target); + } else { + std::fs::copy(entry.path(), &target).unwrap(); + } + } + } + let scan = with(SCAN_IT, &["--json"]); + let server = service(&[DARWIN, LINUX], &[]).await; + mount_search(&server).await; + let made = fresh_project(SCAN_IT); + let (code, env, stderr) = run_json(made.path(), &scan, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_per_platform_gem(&env, "applied", ""); - // 5. A damaged tree: the check fails per platform gem, and the next - // run rebuilds the copy. The gem patch's reference says which patch - // each platform's gem is (the ledger must name the same ones), then - // those patches are asked for in one request. - std::fs::write(tree(root, LINUX).join(SO), b"another binary").unwrap(); - let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); - assert_eq!(code, 1, "{env:#}\n{stderr}"); - assert_eq!(env["summary"]["failed"], 2, "{env:#}"); - assert_per_platform_gem(&env, "failed", "vendor_check_failed"); - let before = reference_requests(&server).await.len(); - let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + let outer = tempfile::tempdir().unwrap(); + let init = std::process::Command::new("git") + .arg("-C") + .arg(outer.path()) + .args(["init", "-q"]) + .status(); + if !init.is_ok_and(|status| status.success()) { + return; // no git, nothing to ask + } + std::fs::write(outer.path().join(".gitignore"), "build/\n").unwrap(); + let root = outer.path().join("build/app"); + copy_tree(made.path(), &root); + let exported = snapshot(&root); + + let dry = with(SCAN_IT, &["--json", "--dry-run"]); + let (code, env, stderr) = run_json(&root, &dry, &server.uri()); assert_eq!(code, 0, "{env:#}\n{stderr}"); - assert_eq!(env["summary"]["rebuilt"], 1, "{env:#}"); assert_per_platform_gem(&env, "skipped", "already_vendored"); - assert_eq!( - reference_requests(&server).await[before..], - [ - vec![UUID.to_string()], - vec![DARWIN_UUID.to_string(), LINUX_UUID.to_string()] - ] + assert!( + !env.to_string().contains("vendor_artifact_gitignored"), + "{env:#}" ); + assert_eq!(snapshot(&root), exported, "the dry run"); + + let (code, env, stderr) = run_json(&root, &scan, &server.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); + assert_eq!(env["status"], "error", "{env:#}"); assert_eq!( - std::fs::read(tree(root, LINUX).join(SO)).unwrap(), - LINUX.as_bytes() + env["error"]["code"], "vendor_artifact_gitignored", + "{env:#}" ); - - // 5b. The ledger is committed data, and it does not choose what is - // unpacked: with the patch of the linux tree edited to another - // served patch, the damaged tree is not rebuilt from it. The run - // fails, downloads nothing and leaves the tree as it was. - let state_path = root.join(".socket/vendor/state.json"); - let honest = std::fs::read_to_string(&state_path).unwrap(); - std::fs::write(&state_path, honest.replace(LINUX_UUID, DARWIN_UUID)).unwrap(); - std::fs::write(tree(root, LINUX).join(SO), b"another binary").unwrap(); - let fetched = downloads(&server).await.len(); - let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); - assert_ne!(code, 0, "{env:#}\n{stderr}"); - // Said as what it is, a build that is no longer the one the fix - // names, under its own code and with the commands that vendor the - // current one: not as tampering, and not as a first vendoring. - let said = env.to_string(); + let message = env["error"]["message"].as_str().unwrap_or_default(); assert!( - said.contains("vendor_prebuilt_replaced") - && said.contains("cannot be restored as it was vendored") - && said.contains("the gem's fix now names patch") - && said.contains("socket-patch scan --mode vendored"), - "{env:#}" + message.starts_with( + "git would not commit the vendored artifact at .socket/vendor (.gitignore:1:build/" + ), + "the run's own check, of the vendor directory: {message}" ); assert!( - !said.contains("vendor_prebuilt_integrity_mismatch"), - "{env:#}" + env["events"].as_array().is_some_and(Vec::is_empty), + "no package was looked at: {env:#}" ); - assert_eq!( - downloads(&server).await.len(), - fetched, - "nothing is downloaded" + assert_eq!(snapshot(&root), exported); +} + +/// A run that finds a copy in step starts git for its own ledger check +/// and for nothing else: the copy asks git nothing. A run that is about +/// to place trees asks, and never with the index. Counted with a `git` +/// first on `PATH` that logs each call and hands it on. +#[cfg(unix)] +#[tokio::test] +async fn a_copy_in_step_asks_git_nothing() { + use std::os::unix::fs::PermissionsExt as _; + let Some(project) = git_project_ignoring_binaries() else { + return; // no git, nothing to count + }; + let root = project.path(); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + + let path = std::env::var("PATH").unwrap_or_default(); + let real = std::env::split_paths(&path) + .map(|dir| dir.join("git")) + .find(|git| git.is_file()) + .expect("git on PATH"); + let shim = tempfile::tempdir().unwrap(); + let log = shim.path().join("calls.log"); + let script = format!( + "#!/bin/sh\necho \"$@\" >> '{}'\nexec '{}' \"$@\"\n", + log.display(), + real.display() ); + let git_shim = shim.path().join("git"); + std::fs::write(&git_shim, script).unwrap(); + std::fs::set_permissions(&git_shim, std::fs::Permissions::from_mode(0o755)).unwrap(); + let shimmed = format!("{}:{path}", shim.path().display()); + let calls = || std::fs::read_to_string(&log).unwrap_or_default(); + // What every vendored run asks of git, whatever it finds: whether the + // vendor directory and its ledger would be committed. + let ledger_check = "-C . rev-parse --is-inside-work-tree\n-C . check-ignore -v -z --stdin\n"; + + // In step, wet and dry. + for args in [VENDOR_IT.to_vec(), with(VENDOR_IT, &["--dry-run"])] { + let _ = std::fs::remove_file(&log); + let (code, stdout, stderr) = run_in(root, &args, &first.uri(), &[("PATH", &shimmed)]); + assert_eq!(code, 0, "{args:?}: {stdout}\n{stderr}"); + assert!(stdout.contains("already vendored"), "{args:?}: {stdout}"); + assert_eq!( + calls(), + ledger_check, + "{args:?}: the run's ledger check, and nothing for the copy" + ); + } + + // The list moved: trees are about to be placed, so git is asked about + // them, dry and wet alike and never with its index. + let moved = service(&[DARWIN, LINUX], &[]).await; + let mut asked_each = Vec::new(); + for args in [with(VENDOR_IT, &["--dry-run"]), VENDOR_IT.to_vec()] { + let _ = std::fs::remove_file(&log); + let (code, stdout, stderr) = run_in(root, &args, &moved.uri(), &[("PATH", &shimmed)]); + assert_eq!(code, 0, "{args:?}: {stdout}\n{stderr}"); + assert!(says_it_vendors(&stdout), "{args:?}: {stdout}"); + let asked = calls(); + let about_the_copy = asked.strip_prefix(ledger_check).unwrap_or_default(); + assert_eq!( + about_the_copy, + "-C . rev-parse --is-inside-work-tree\n-C . check-ignore -v -z --stdin --no-index\n", + "{args:?}: one question about the trees, without the index: {asked}" + ); + asked_each.push(asked); + } assert_eq!( - std::fs::read(tree(root, LINUX).join(SO)).unwrap(), - b"another binary", - "nothing is unpacked" + asked_each[0], asked_each[1], + "a dry run asks what the wet run asks" ); - std::fs::write(&state_path, honest).unwrap(); - let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); +} + +/// The same paths with no rule that ignores the copy: the files that +/// could not be written are a warning, never a failure, on each of them, +/// said once per run. A skip, which carries no warning, ends its line +/// with it. +#[tokio::test] +async fn unwritable_metadata_is_a_warning_on_every_path() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let warning = format!( + "Warning: could not write `.socket/vendor/gem/{UUID}/.gitignore` and \ + `.socket/vendor/gem/{UUID}/.gitattributes` (" + ); + let warned_once = |stderr: &str| stderr.matches(warning.as_str()).count() == 1; + let first = service(&[LINUX], &[DARWIN]).await; + + // A first vendor. + obstruct_gitignore(root); + let (code, stdout, stderr) = run(root, VENDOR_IT, &first.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains("Vendored 1 package."), "{stdout}"); + assert!( + warned_once(&stderr) && !stderr.contains("Error:"), + "{stderr}" + ); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &first.uri()); assert_eq!(code, 0, "{env:#}\n{stderr}"); + + // In step. + let (code, stdout, stderr) = run(root, VENDOR_IT, &first.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already vendored; nothing to do."), + "{stdout}" + ); + assert!(warned_once(&stderr), "{stderr}"); + + // A build the list names is not served yet: the skip's line ends + // with it. + let building = service_still_building_darwin().await; + let (code, stdout, stderr) = run(root, VENDOR_IT, &building.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stderr.contains("its vendored copy stays in force as it is. Also: could not write `") + && stderr.contains("make those two files writable and run this again."), + "{stderr}" + ); + + // A damaged tree, restored by a vendor run and by `repair`: the + // warning is said once, though the run finishes the copy twice. + std::fs::write(tree(root, LINUX).join(SO), b"damaged").unwrap(); + let (code, stdout, stderr) = run(root, VENDOR_IT, &first.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(warned_once(&stderr), "{stderr}"); assert_eq!( std::fs::read(tree(root, LINUX).join(SO)).unwrap(), LINUX.as_bytes() ); - let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); - assert_eq!(code, 0, "{env:#}\n{stderr}"); + std::fs::write(tree(root, LINUX).join(SO), b"damaged").unwrap(); + let (code, stdout, stderr) = run(root, &["repair", "--download-only"], &first.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(warned_once(&stderr), "{stdout}\n{stderr}"); - // 6. Revert. - let (code, env, stderr) = run_json(root, &["vendor", "--revert", "--json"], &server.uri()); + // The list moved. + let moved = service(&[DARWIN, LINUX], &[]).await; + let (code, stdout, stderr) = run(root, VENDOR_IT, &moved.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains("Vendored 1 package."), "{stdout}"); + assert!(warned_once(&stderr), "{stderr}"); +} + +/// A manifest record for the purl of a platform gem at that build's own +/// patch, beside the vendored entry (what a record of the build fetched +/// by its uuid leaves): `vex` attests that build from the committed tree +/// all the same, online and offline, and names the vendored copy as what +/// patches it. +#[tokio::test] +async fn a_manifest_record_of_a_builds_own_patch_leaves_the_build_attested_from_the_tree() { + let server = service(&[DARWIN, LINUX], &[]).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); assert_eq!(code, 0, "{env:#}\n{stderr}"); - assert_eq!( - std::fs::read_to_string(root.join("Gemfile")).unwrap(), - GEMFILE - ); - assert_eq!( - std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), - lock() - ); - assert!(!root.join(".socket/vendor").exists()); + + let manifest_path = root.join(".socket/manifest.json"); + let mut manifest: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap(); + let view = build_view(LINUX); + manifest["patches"][format!("{PURL}?platform={LINUX}")] = serde_json::json!({ + "uuid": LINUX_UUID, + "exportedAt": "2026-01-01T00:00:00Z", + "files": build_files(LINUX), + "vulnerabilities": view["vulnerabilities"], + "description": view["description"], + "license": "MIT", + "tier": "free" + }); + std::fs::write( + &manifest_path, + serde_json::to_vec_pretty(&manifest).unwrap(), + ) + .unwrap(); + + let out = root.join("vex.json"); + for offline in [true, false] { + let _ = std::fs::remove_file(&out); + let mut args = vec!["vex", "--product", "pkg:gem/app@1.0.0", "--output"]; + args.push(out.to_str().unwrap()); + if offline { + args.push("--offline"); + } + let (code, stdout, stderr) = run(root, &args, &server.uri()); + assert_eq!(code, 0, "offline {offline}: {stdout}\n{stderr}"); + let doc: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&out).unwrap()).unwrap(); + let statements = doc["statements"].as_array().expect("statements"); + assert_eq!(statements.len(), 1, "offline {offline}: {doc:#}"); + let statement = &statements[0]; + assert_eq!(statement["status"], "not_affected", "{doc:#}"); + let attested: Vec<&str> = statement["products"] + .as_array() + .into_iter() + .flatten() + .flat_map(|product| product["subcomponents"].as_array().into_iter().flatten()) + .filter_map(|component| component["@id"].as_str()) + .collect(); + for platform in [DARWIN, LINUX] { + let purl = format!("{PURL}?platform={platform}"); + assert!( + attested.contains(&purl.as_str()), + "offline {offline}: {platform}: {attested:?}" + ); + } + let impact = statement["impact_statement"].as_str().unwrap_or_default(); + for own in [DARWIN_UUID, LINUX_UUID] { + let part = format!("Patched via Socket patch {own} (vendored)"); + assert!( + impact.split("; ").any(|p| p == part), + "offline {offline}: {impact}" + ); + } + } } -/// A locked platform with no patched build: the gem is not vendored, the +/// No locked platform has a patched build: the gem is not vendored, the /// run exits 0 with nothing written and nothing downloaded, and says so in /// one plain line (a counted benign skip in `--json`). #[tokio::test] -async fn a_locked_platform_without_a_patched_build_is_one_line_and_no_failure() { - let server = service(&[LINUX], &[DARWIN]).await; +async fn a_gem_with_no_patched_build_for_any_locked_platform_is_one_line_and_no_failure() { + let server = service(&[], &[DARWIN, LINUX]).await; let tmp = tempfile::tempdir().unwrap(); let root = tmp.path(); write_project(root); - let line = format!( - "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has one). \ - Vendored mode needs every locked platform; `scan --mode hosted` can patch the others now." - ); + let line = + format!("{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} and {LINUX}."); let (code, stdout, stderr) = run( root, @@ -918,13 +2293,13 @@ fn write_hosted_project(root: &Path) -> (String, String) { (gemfile, lock) } -/// An eject (`vendor` over a hosted lock) of a gem whose registry serves -/// upstream's own gem for one locked platform cannot vendor it: the eject -/// is refused whole, the reason names the platform, and the lock stays -/// hosted, byte for byte. +/// An eject (`vendor` over a hosted lock) of a gem while the patch of one +/// locked platform's build is still being built cannot vendor it: the +/// eject is refused whole, the reason names the platform, and the lock +/// stays hosted, byte for byte. #[tokio::test] -async fn an_eject_of_a_gem_with_a_pass_through_platform_is_refused_whole() { - let server = service(&[LINUX], &[DARWIN]).await; +async fn an_eject_of_a_gem_with_a_build_still_being_built_is_refused_whole() { + let server = service_still_building_darwin().await; let tmp = tempfile::tempdir().unwrap(); let root = tmp.path(); let (gemfile, lock) = write_hosted_project(root); @@ -946,7 +2321,8 @@ async fn an_eject_of_a_gem_with_a_pass_through_platform_is_refused_whole() { failed["error"], format!( "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has \ - one). Vendored mode needs every locked platform; the gem stays hosted." + one). Vendored mode needs a gem, patched or upstream's own, for every locked \ + platform; the gem stays hosted." ) .as_str(), "{failed:#}" @@ -1148,11 +2524,72 @@ async fn a_vendored_scan_takes_over_a_hosted_platform_gem() { } /// The same takeover while the registry serves upstream's own gem for one -/// locked platform: the gem is not vendored and stays hosted, byte for +/// locked platform: the gem is vendored all the same, with the patched +/// build's tree for the one platform and upstream's gem for the other, as +/// the hosted lock installed them. The scan's dry run says so first, and +/// an eject (`vendor` over the hosted lock) vendors the same. +#[tokio::test] +async fn a_takeover_of_a_hosted_gem_with_upstreams_gem_for_a_platform_vendors_both() { + for command in [SCAN_IT, VENDOR_IT] { + let server = service(&[LINUX], &[DARWIN]).await; + mount_search(&server).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let (_, hosted_lock) = write_hosted_project(root); + if command[0] == "scan" { + install_darwin_gem(root); + } + let line = format!( + "{NAME} {VERSION}: patched for {LINUX}; upstream gem kept for {DARWIN} (no patched \ + build yet)" + ); + + let dry = with(command, &["--dry-run"]); + let (code, stdout, stderr) = run(root, &dry, &server.uri()); + assert_eq!(code, 0, "{dry:?}\n{stdout}\n{stderr}"); + // (An eject's dry run names the packages it would eject and asks + // the patch service nothing.) + if command[0] == "scan" { + let would = line.replace("patched for", "would be patched for"); + assert!(stdout.contains(&would), "{dry:?}\n{stdout}\n{stderr}"); + } + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + hosted_lock + ); + assert!(!root.join(".socket/vendor/gem").exists()); + + let (code, stdout, stderr) = run(root, command, &server.uri()); + assert_eq!(code, 0, "{command:?}\n{stdout}\n{stderr}"); + assert!(stdout.contains(&line), "{command:?}\n{stdout}\n{stderr}"); + let lock = std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(); + assert!( + lock.starts_with(&format!( + "PATH\n remote: .socket/vendor/gem/{UUID}/{NAME}-{VERSION}\n" + )), + "{lock}" + ); + assert!(!lock.contains("patch-registry"), "{lock}"); + assert_eq!( + std::fs::read(tree(root, LINUX).join(LIB)).unwrap(), + stamped(LINUX_UUID) + ); + assert_eq!( + std::fs::read(tree(root, DARWIN).join(LIB)).unwrap(), + PRISTINE + ); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + } +} + +/// The same takeover while the patch of one locked platform's build is +/// still being built: the gem is not vendored and stays hosted, byte for /// byte, the run does not fail, and its one line says the pin stays. #[tokio::test] -async fn a_vendored_scan_leaves_a_hosted_gem_with_a_pass_through_platform_hosted() { - let server = service(&[LINUX], &[DARWIN]).await; +async fn a_vendored_scan_leaves_a_hosted_gem_with_a_build_still_being_built_hosted() { + let server = service_still_building_darwin().await; mount_search(&server).await; let tmp = tempfile::tempdir().unwrap(); let root = tmp.path(); @@ -1174,7 +2611,8 @@ async fn a_vendored_scan_leaves_a_hosted_gem_with_a_pass_through_platform_hosted skipped["reason"], format!( "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has \ - one). Vendored mode needs every locked platform; the gem stays hosted." + one). Vendored mode needs a gem, patched or upstream's own, for every locked \ + platform; the gem stays hosted." ) .as_str(), "{skipped:#}" @@ -1530,21 +2968,142 @@ async fn a_vendored_get_dry_run_follows_the_runs_fallback_to_the_public_proxy() } } -/// Every dry run of a gem with a locked platform that has no patched build -/// says what the wet run says, and neither claims to vendor it: the gem -/// patch's reference lists upstream's own gem for the platform, so that -/// one request is all a run makes. +/// Every dry run of a gem none of whose locked platforms has a patched +/// build says what the wet run says, and neither claims to vendor it: the +/// gem patch's reference lists upstream's own gem for each platform, so +/// that one request is all a run makes. +#[tokio::test] +async fn every_dry_run_says_the_wet_runs_line_for_a_gem_with_no_patched_build() { + let line = + format!("{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} and {LINUX}."); + for command in [VENDOR_IT, SCAN_IT, GET_IT] { + let server = service(&[], &[DARWIN, LINUX]).await; + mount_search(&server).await; + assert_dry_and_wet_runs_skip_alike(&server, command, &line, &[vec![UUID.to_string()]]) + .await; + } +} + +/// Every dry run of a gem with a patched build for one locked platform and +/// upstream's own gem for the other says what the wet run does: it would +/// vendor the gem, with the one line that says which platform is patched, +/// the patched build `verified` where the wet run reports `applied`, and +/// the advisory event of the build on upstream's gem in both. `scan` and +/// `get` ask for the references the wet run asks for and download nothing. #[tokio::test] -async fn every_dry_run_says_the_wet_runs_line_for_a_platform_with_no_patched_build() { +async fn every_dry_run_previews_a_gem_with_upstreams_gem_for_a_platform() { let line = format!( - "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has one). \ - Vendored mode needs every locked platform; `scan --mode hosted` can patch the others now." + "{NAME} {VERSION}: would be patched for {LINUX}; upstream gem kept for {DARWIN} (no \ + patched build yet)" ); for command in [VENDOR_IT, SCAN_IT, GET_IT] { let server = service(&[LINUX], &[DARWIN]).await; mount_search(&server).await; - assert_dry_and_wet_runs_skip_alike(&server, command, &line, &[vec![UUID.to_string()]]) - .await; + let project = fresh_project(command); + let root = project.path(); + let trees = |env: &serde_json::Value| -> Vec<(String, String, String)> { + let events = env["events"].as_array().unwrap().iter(); + events + .filter(|event| event["details"]["gemFix"] == UUID) + .filter(|event| event["errorCode"] != "vendor_prebuilt_downloaded") + .map(|event| { + let text = |key: &str| event[key].as_str().unwrap_or_default().to_string(); + (text("purl"), text("uuid"), text("errorCode")) + }) + .collect() + }; + let expected = [ + ( + format!("{PURL}?platform={DARWIN}"), + String::new(), + "gem_upstream_build_kept".to_string(), + ), + ( + format!("{PURL}?platform={LINUX}"), + LINUX_UUID.to_string(), + String::new(), + ), + ]; + + let args = with(command, &["--dry-run", "--json"]); + let (code, dry, stderr) = run_json(root, &args, &server.uri()); + assert_eq!(code, 0, "{args:?}\n{dry:#}\n{stderr}"); + assert_eq!(dry["status"], "success", "{dry:#}"); + assert_eq!(trees(&dry), expected, "{args:?}\n{dry:#}"); + for (count, n) in [ + ("verified", 1), + ("applied", 0), + ("skipped", 0), + ("failed", 0), + ] { + assert_eq!(dry["summary"][count], n, "summary.{count}: {dry:#}"); + } + assert_eq!( + reference_requests(&server).await, + [vec![UUID.to_string()], vec![LINUX_UUID.to_string()]], + "{command:?}: the wet run's reference requests" + ); + let downloaded = downloads(&server).await.len(); + match command[0] { + "vendor" => assert_eq!(downloaded, 3, "the gems and the stub, verified"), + _ => assert_eq!(downloaded, 0, "{command:?} downloads nothing"), + } + assert_nothing_vendored(root); + + let args = with(command, &["--dry-run"]); + let (code, stdout, stderr) = run(root, &args, &server.uri()); + assert_eq!(code, 0, "{args:?}\n{stdout}\n{stderr}"); + assert!(stdout.contains(&line), "{args:?}\n{stdout}"); + assert_eq!(said_of_the_gem(&stderr), Vec::<&str>::new(), "{stderr}"); + assert_nothing_vendored(root); + + let args = with(command, &["--json"]); + let (code, wet, stderr) = run_json(root, &args, &server.uri()); + assert_eq!(code, 0, "{args:?}\n{wet:#}\n{stderr}"); + assert_eq!(wet["summary"]["applied"], 1, "{wet:#}"); + assert_eq!(trees(&wet), expected, "{args:?}\n{wet:#}"); + assert_eq!( + std::fs::read(tree(root, LINUX).join(LIB)).unwrap(), + stamped(LINUX_UUID) + ); + assert_eq!( + std::fs::read(tree(root, DARWIN).join(LIB)).unwrap(), + PRISTINE + ); + + // Vendored: a dry run of a later scan asks for the gem patch's + // list, as the wet run does, and says what that run says: each + // tree as the copy holds it, and the gem's line. + let asked = reference_requests(&server).await.len(); + let args = with(command, &["--dry-run", "--json"]); + let (code, dry, stderr) = run_json(root, &args, &server.uri()); + assert_eq!(code, 0, "{args:?}\n{dry:#}\n{stderr}"); + assert_eq!(dry["summary"]["verified"], 0, "{args:?}\n{dry:#}"); + assert_eq!( + reference_requests(&server).await[asked..], + [vec![UUID.to_string()]], + "{args:?}" + ); + let in_step = [ + expected[0].clone(), + ( + expected[1].0.clone(), + expected[1].1.clone(), + "already_vendored".to_string(), + ), + ]; + assert_eq!(trees(&dry), in_step, "{args:?}\n{dry:#}"); + let args = with(command, &["--json"]); + let (code, wet, stderr) = run_json(root, &args, &server.uri()); + assert_eq!(code, 0, "{args:?}\n{wet:#}\n{stderr}"); + assert_eq!(trees(&wet), in_step, "{args:?}: the real run\n{wet:#}"); + for flags in [&["--dry-run"][..], &[]] { + let args = with(command, flags); + let (code, stdout, stderr) = run(root, &args, &server.uri()); + assert_eq!(code, 0, "{args:?}\n{stdout}\n{stderr}"); + let kept = line.replace("would be patched for", "patched for"); + assert!(stdout.contains(&kept), "{args:?}\n{stdout}\n{stderr}"); + } } } @@ -1562,7 +3121,8 @@ async fn a_platform_patch_that_is_not_served_is_the_same_skip_in_every_dry_and_w ] { let line = format!( "{NAME}@{VERSION} is not vendored: {none} {DARWIN} ({LINUX} has one). Vendored mode \ - needs every locked platform; `scan --mode hosted` can patch the others now." + needs a gem, patched or upstream's own, for every locked platform; `scan --mode \ + hosted` can patch the others now." ); for command in [VENDOR_IT, SCAN_IT, GET_IT] { let server = service_of(UUID, &[(DARWIN, Some(status)), (LINUX, None)], &[]).await; @@ -1596,7 +3156,8 @@ async fn an_unserved_platform_patch_keeps_the_vendored_copy_of_an_earlier_patch( let newer = service_of(UUID_B, &[(DARWIN, Some(status)), (LINUX, None)], &[]).await; let line = format!( "{NAME}@{VERSION} was not brought up to date: {none} {DARWIN} ({LINUX} has one). \ - Vendored mode needs every locked platform; its vendored copy of an earlier patch \ + Vendored mode needs a gem, patched or upstream's own, for every locked platform; its \ + vendored copy of an earlier patch \ stays in force as it is." ); for flags in [&["--dry-run"][..], &[]] { @@ -1671,7 +3232,8 @@ async fn an_unserved_platform_patch_still_fails_a_damaged_wired_copy_and_an_ejec failed["error"], format!( "{NAME}@{VERSION} is not vendored: {none} {DARWIN} ({LINUX} has one). Vendored \ - mode needs every locked platform; the gem stays hosted." + mode needs a gem, patched or upstream's own, for every locked platform; the gem \ + stays hosted." ) .as_str(), "{failed:#}" @@ -1689,20 +3251,18 @@ async fn an_unserved_platform_patch_still_fails_a_damaged_wired_copy_and_an_ejec } } -/// `scan --mode vendored` over a lock that pins the gem hosted, while a -/// locked platform has no patched build (the registry serves upstream's -/// own gem for it, or the patch of its build is still being built): the -/// dry run and the wet run both say the gem stays hosted, and it does, -/// byte for byte. +/// `scan --mode vendored` over a lock that pins the gem hosted, while the +/// patch of one locked platform's build is still being built: the dry run +/// and the wet run both say the gem stays hosted, and it does, byte for +/// byte. #[tokio::test] -async fn a_takeover_of_a_hosted_gem_with_an_unpatched_platform_stays_hosted_dry_or_wet() { +async fn a_takeover_of_a_hosted_gem_with_a_build_still_being_built_stays_hosted_dry_or_wet() { let line = format!( "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has one). \ - Vendored mode needs every locked platform; the gem stays hosted." + Vendored mode needs a gem, patched or upstream's own, for every locked platform; the gem \ + stays hosted." ); - let pass_through = service(&[LINUX], &[DARWIN]).await; - let building = service_of(UUID, &[(DARWIN, Some("pending_build")), (LINUX, None)], &[]).await; - for server in [pass_through, building] { + for server in [service_still_building_darwin().await] { mount_search(&server).await; let tmp = tempfile::tempdir().unwrap(); let root = tmp.path(); @@ -1732,7 +3292,7 @@ async fn a_takeover_of_a_hosted_gem_with_an_unpatched_platform_stays_hosted_dry_ } /// No run tells a gem that stays hosted to run hosted mode. A hosted gem -/// with a locked platform that has no patched build reaches the vendored +/// with a locked platform whose patched build is still being built reaches the vendored /// backend three ways: `scan` and `get` take it over (their dry runs ask /// the patch service with no record of the patch), and `vendor` ejects it, /// which is all or nothing and so fails. Each of them, dry or wet, for a @@ -1743,10 +3303,11 @@ async fn a_takeover_of_a_hosted_gem_with_an_unpatched_platform_stays_hosted_dry_ async fn no_run_tells_a_gem_that_stays_hosted_to_run_hosted_mode() { let stays = format!( "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has one). \ - Vendored mode needs every locked platform; the gem stays hosted." + Vendored mode needs a gem, patched or upstream's own, for every locked platform; the gem \ + stays hosted." ); for command in [SCAN_IT, GET_IT, VENDOR_IT] { - let server = service(&[LINUX], &[DARWIN]).await; + let server = service_still_building_darwin().await; mount_search(&server).await; let tmp = tempfile::tempdir().unwrap(); let root = tmp.path(); @@ -1782,7 +3343,7 @@ async fn no_run_tells_a_gem_that_stays_hosted_to_run_hosted_mode() { // The same platforms for a gem with no hosted pin: hosted mode is what // patches the others. - let server = service(&[LINUX], &[DARWIN]).await; + let server = service_still_building_darwin().await; let project = fresh_project(VENDOR_IT); let (code, stdout, stderr) = run(project.path(), VENDOR_IT, &server.uri()); assert_eq!(code, 0, "{stdout}\n{stderr}"); @@ -1833,6 +3394,54 @@ async fn an_offline_dry_run_asks_nothing_and_promises_nothing() { ); } +/// The contract and the guide say what the CLI says. The remedy of a build +/// that was replaced is the vendored scan alone, in the row of its code as +/// in the message. What vendored mode needs of a gem locked as platform +/// gems is a gem for every locked platform, patched or upstream's. And both +/// say which releases read a copy with a tree of upstream's gem. +#[test] +fn the_contract_and_the_guide_say_what_the_cli_says() { + let cli = Path::new(env!("CARGO_MANIFEST_DIR")); + let read = |path: std::path::PathBuf| { + std::fs::read_to_string(&path) + .unwrap_or_else(|e| panic!("{}: {e}", path.display())) + .replace("\r\n", "\n") + }; + let contract = read(cli.join("CLI_CONTRACT.md")); + let guide = read(cli.join("../../docs/ecosystems.md")); + + let row = contract + .lines() + .find(|line| line.starts_with("| `vendor_prebuilt_replaced` |")) + .expect("the row of vendor_prebuilt_replaced"); + assert!( + row.ends_with( + "the one command that works: run `socket-patch scan --mode vendored`, which vendors \ + what the patch service serves now. |" + ), + "{row}" + ); + assert!(!row.contains("socket-patch rollback"), "{row}"); + + assert!( + contract.contains( + "Vendored mode needs a gem, patched or upstream's own, for every locked platform" + ), + "the contract quotes the line" + ); + for (name, text) in [("contract", &contract), ("guide", &guide)] { + assert!(!text.contains("needs every locked platform"), "{name}"); + // What released 5.1.0 does on such a copy was run, not assumed: + // it fails the check and attests nothing for the gem. + assert!( + text.contains( + "5.1.0 and earlier have no platform-gem vendoring and do not read such a copy" + ) && !text.contains("can attest the gem as patched for every platform"), + "{name}" + ); + } +} + /// The contract and the guide say which releases read a gem vendored as /// platform gems. Released 5.1.0 was run on such a copy: it has no /// platform-gem vendoring, its `vendor --check` fails and its `vex` leaves diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index 2216a04e83..3e966d2405 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -336,6 +336,9 @@ pub struct ApiClient { /// here so every blob/tarball download shares one connection pool /// instead of paying a fresh TLS-config build + handshake per request. plain: reqwest::Client, + /// `plain` that follows no redirect: for a download that must come + /// from the host it is asked of ([`Self::download_registry_gem`]). + plain_no_redirect: reqwest::Client, api_url: String, /// Bearer token; always `None` on an [`ApiRoute::Proxy`] client. api_token: Option, @@ -555,6 +558,12 @@ impl VendorRetryPolicy { /// `service` fails closed — the existing miss policy). pub(crate) const VENDOR_BREAKER_THRESHOLD: u32 = 2; +/// Bound on an advisory reference read +/// ([`ApiClient::fetch_vendor_reference_once`]): a service that answers +/// does so well inside it, and one that does not costs the run this much +/// and no retry. +pub(crate) const ADVISORY_REFERENCE_TIMEOUT: Duration = Duration::from_secs(5); + /// The jitter key of the package-reference POST's retries (archive and /// artifact downloads are keyed by their URL). const VENDOR_REFERENCES_KEY: &str = "POST vendor package references"; @@ -629,7 +638,8 @@ impl ApiClient { }; Self { client: api_client(api_token.as_deref(), &timeouts), - plain: plain_client(&timeouts), + plain: plain_client(&timeouts, true), + plain_no_redirect: plain_client(&timeouts, false), api_url, api_token, route: options.route, @@ -715,7 +725,8 @@ impl ApiClient { /// cloning the client. pub fn with_api_timeouts(mut self, timeouts: ApiTimeouts) -> Self { self.client = api_client(self.api_token.as_deref(), &timeouts); - self.plain = plain_client(&timeouts); + self.plain = plain_client(&timeouts, true); + self.plain_no_redirect = plain_client(&timeouts, false); self } @@ -1821,6 +1832,45 @@ impl ApiClient { outcome } + /// [`Self::fetch_vendor_reference`] as an advisory question, one whose + /// caller goes on as it was when it gets no answer: ONE attempt, bounded + /// by [`ADVISORY_REFERENCE_TIMEOUT`], never retried, and outside the + /// circuit breaker, which neither counts its failure nor is reset by + /// its answer. So a service that is down costs such a caller one short + /// attempt, and cannot make the run's real requests fail unasked. While + /// the breaker is open the service is down for this run and nothing is + /// asked. Always a request of its own: no plan answers it. + pub(crate) async fn fetch_vendor_reference_once( + &self, + uuid: &str, + free_only: bool, + vendor_url: Option<&str>, + patch_server_url: Option<&str>, + ) -> VendorServiceOutcome { + if let Some(refused) = self.vendor_request_refused(uuid) { + return VendorServiceOutcome::Failed(refused); + } + let uuids = [uuid.to_string()]; + let asked = tokio::time::timeout( + ADVISORY_REFERENCE_TIMEOUT, + self.request_vendor_references_once(&uuids, free_only, vendor_url), + ) + .await; + match asked { + Ok(Ok(results)) => match results.get(uuid) { + Some(result) => vendor_reference(result, patch_server_url), + None => VendorServiceOutcome::Failed(ApiError::Other(format!( + "package response missing a result for {uuid}" + ))), + }, + Ok(Err((e, _))) => VendorServiceOutcome::Failed(e), + Err(_) => VendorServiceOutcome::Failed(ApiError::Network(format!( + "no answer within {}s", + ADVISORY_REFERENCE_TIMEOUT.as_secs() + ))), + } + } + /// [`Self::fetch_vendor_reference`] for several patches in ONE request /// (per [`MAX_REFERENCE_BATCH`] uuids): the outcome of each of `uuids`, /// in their order. `Err` when no answer was had at all (a refused or @@ -2279,6 +2329,24 @@ impl ApiClient { max_bytes: u64, noun: &str, ) -> Result { + self.serve_get_once_with(true, url, max_bytes, noun).await + } + + /// [`Self::serve_get_once`] with the plain client (`follow_redirects`) + /// or its twin that follows no redirect. Only for that twin is a + /// redirect an answer of its own: a terminal miss, like a 404. The + /// client that follows redirects answers as it always did. + async fn serve_get_once_with( + &self, + follow_redirects: bool, + url: &str, + max_bytes: u64, + noun: &str, + ) -> Result { + let client = match follow_redirects { + true => &self.plain, + false => &self.plain_no_redirect, + }; if !(url.starts_with("https://") || url.starts_with("http://")) { return Err(( ApiError::Other(format!( @@ -2293,7 +2361,7 @@ impl ApiClient { // below gets its own (larger) bound — archives can be big. let sent = tokio::time::timeout( self.vendor_retry.attempt_timeout, - self.plain + client .get(url) .header(header::ACCEPT, "application/octet-stream") .send(), @@ -2327,6 +2395,11 @@ impl ApiClient { // 404 (build_failed / not stored) and 410 (withdrawn) are terminal // misses; the caller decides build-fallback vs hard-fail. StatusCode::NOT_FOUND | StatusCode::GONE => return Ok(ServeDownload::NotFound), + // The gem's registry answered a redirect to the client that + // follows none: the gem is not served here. + status if !follow_redirects && status.is_redirection() => { + return Ok(ServeDownload::NotFound) + } // 408 = the archive is still building (Retry-After) — the // caller's pending policy, never retried here. StatusCode::REQUEST_TIMEOUT => return Ok(ServeDownload::Pending), @@ -2382,6 +2455,20 @@ impl ApiClient { artifact_download_result(self.download_vendor_archive(url, None).await, url) } + /// [`Self::download_artifact`] for a gem file a patch registry lists + /// as upstream's own (`/gems/`), which a vendored copy + /// takes from the patch service and from nowhere else: no redirect is + /// followed, and one the registry answers is the gem not being served + /// ("artifact not found"). + pub(crate) async fn download_registry_gem(&self, url: &str) -> Result, ApiError> { + let outcome = self + .retry_vendor(url, "vendor package download", None, || { + self.serve_get_once_with(false, url, MAX_VENDOR_PACKAGE_BYTES, "vendor package") + }) + .await; + artifact_download_result(outcome, url) + } + /// The first attempt of [`Self::download_artifact`] alone: `Ok` with /// exactly the result `download_artifact` would return when that attempt /// settles it (success, or a failure it would not retry), `Err` with the @@ -2632,6 +2719,10 @@ pub(crate) struct VendorReference { /// serves them (`registryOverride.identifiers.gemBuilds`); `None` when /// the reference carries no list. pub gem_builds: Option>, + /// gem: the index URL of that registry (`registryOverride.indexUrl`, + /// its host rewritten like every artifact URL): where the registry + /// serves the gem file of each platform it lists, `gems/`. + pub gem_index_url: Option, } /// Outcome of [`ApiClient::fetch_vendor_package`], and, with the @@ -2682,14 +2773,19 @@ fn vendor_reference( if let Some(miss) = reference_miss(&result.status) { return miss; } - let gem_builds = result - .registry_override - .as_ref() - .and_then(|registry| registry.identifiers.gem_builds.clone()); + let registry = result.registry_override.as_ref(); + let gem_builds = registry.and_then(|registry| registry.identifiers.gem_builds.clone()); + let gem_index_url = registry + .filter(|registry| registry.kind == "rubygems-compact-index") + .and_then(|registry| match patch_server_url { + Some(base) => rewrite_url_host(®istry.index_url, base).ok(), + None => Some(registry.index_url.clone()), + }); VendorServiceOutcome::Ready(VendorReference { archive: served_artifacts(result, patch_server_url, true).pop(), secondary: served_secondary_artifacts(result, patch_server_url), gem_builds, + gem_index_url, }) } @@ -2785,18 +2881,21 @@ fn api_client(api_token: Option<&str>, timeouts: &ApiTimeouts) -> reqwest::Clien /// A serve URL holds its grant token in the path, and a serve route can /// answer with a redirect to another host, which the client follows. No /// `Referer` is set on the way: it would hand that URL to the next host. -fn plain_client(timeouts: &ApiTimeouts) -> reqwest::Client { +fn plain_client(timeouts: &ApiTimeouts, follow_redirects: bool) -> reqwest::Client { let mut headers = HeaderMap::new(); headers.insert( header::USER_AGENT, HeaderValue::from_static(USER_AGENT_VALUE), ); + let builder = crate::utils::http::client_builder() + .default_headers(headers) + .referer(false); + let builder = match follow_redirects { + true => builder, + false => builder.redirect(reqwest::redirect::Policy::none()), + }; timeouts - .apply( - crate::utils::http::client_builder() - .default_headers(headers) - .referer(false), - ) + .apply(builder) .build() .expect("failed to build plain reqwest client") } @@ -6227,6 +6326,66 @@ mod vendor_package_tests { assert!(!sent.contains(GRANT), "the grant token: {sent}"); } + /// Upstream's own gem of a patch registry is taken from that registry + /// alone: a redirect it answers is not followed, and is the gem not + /// being served. The file itself downloads as any artifact does. + #[tokio::test] + async fn download_registry_gem_follows_no_redirect() { + let registry = MockServer::start().await; + let elsewhere = MockServer::start().await; + let redirected = "/patch-registry/gem/tok/u/s/4f/gems/a-1.0.0-java.gem"; + let relayed = "/patch-registry/gem/tok/u/s/4f/gems/a-1.0.0-x86_64-linux.gem"; + Mock::given(method("GET")) + .and(path(redirected)) + .respond_with(ResponseTemplate::new(302).insert_header( + "Location", + format!("{}/gems/a.gem", elsewhere.uri()).as_str(), + )) + .mount(®istry) + .await; + Mock::given(method("GET")) + .and(path(relayed)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"upstream".to_vec())) + .mount(®istry) + .await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"elsewhere".to_vec())) + .mount(&elsewhere) + .await; + let client = auth_client(registry.uri()); + let err = client + .download_registry_gem(&format!("{}{redirected}", registry.uri())) + .await + .expect_err("a redirect is the gem not being served"); + assert!(err.to_string().contains("artifact not found"), "{err}"); + let asked = elsewhere.received_requests().await.unwrap_or_default(); + assert!(asked.is_empty(), "the redirect was followed: {asked:?}"); + let bytes = client + .download_registry_gem(&format!("{}{relayed}", registry.uri())) + .await + .expect("the registry's own file"); + assert_eq!(bytes, b"upstream"); + + // The client that follows redirects answers a redirect it cannot + // follow (no `Location`) as it always did: a failed download, with + // its status, and not a file that is not served. + let odd = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(302)) + .mount(&odd) + .await; + let client = auth_client(odd.uri()).with_vendor_retry(VendorRetryPolicy::none()); + let err = client + .download_artifact(&format!("{}/patch/gem/a.gem", odd.uri())) + .await + .expect_err("a redirect with nowhere to go"); + let said = err.to_string(); + assert!( + said.contains("download failed with status") && !said.contains("artifact not found"), + "{said}" + ); + } + /// A promised secondary that 404s must ERROR ("artifact not found"), /// and a still-building 408 maps to "artifact still building" — the /// arms encoding the no-soft-skip policy for promised artifacts. @@ -7034,6 +7193,82 @@ mod vendor_retry_tests { assert_eq!(c.vendor_outage.load(Ordering::Relaxed), 0); } + /// An advisory reference read is ONE request, whatever the retry + /// policy, and stands outside the breaker: its failures are not + /// counted and cannot open it, so the run's real requests are still + /// made after any number of them, and its answer resets nothing. With + /// the breaker already open it asks nothing. A service that accepts + /// the request and never answers costs the bound of the read, not the + /// ladder's attempts. + #[tokio::test] + async fn an_advisory_reference_read_is_one_attempt_outside_the_breaker() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path(POST_PATH)) + .respond_with(ResponseTemplate::new(503)) + .mount(&server) + .await; + let c = client(&server.uri(), fast()); + for uuid in [UUID_A, UUID_B, UUID_C] { + let o = c.fetch_vendor_reference_once(uuid, false, None, None).await; + assert!(matches!(o, VendorServiceOutcome::Failed(_)), "{o:?}"); + } + assert_eq!(posts(&server).await, 3, "one request each, never retried"); + assert_eq!(c.vendor_outage_count(), 0, "not counted"); + // The run's real request is made, with its ladder, and counted. + let o = c.fetch_vendor_reference(UUID_A, false, None, None).await; + assert!( + matches!(&o, VendorServiceOutcome::Failed(e) if !e.to_string().contains("not attempted")), + "{o:?}" + ); + assert_eq!(posts(&server).await, 6); + assert_eq!(c.vendor_outage_count(), 1); + // An open breaker: the service is down for this run. + c.vendor_outage + .store(VENDOR_BREAKER_THRESHOLD, Ordering::Relaxed); + let o = c + .fetch_vendor_reference_once(UUID_B, false, None, None) + .await; + assert!(matches!(o, VendorServiceOutcome::Failed(_)), "{o:?}"); + assert_eq!(posts(&server).await, 6, "nothing is asked"); + + // An answer changes the count no more than a failure does. + c.vendor_outage.store(1, Ordering::Relaxed); + server.reset().await; + Mock::given(method("POST")) + .and(path(POST_PATH)) + .respond_with(granted(&server, UUID_A)) + .mount(&server) + .await; + let o = c + .fetch_vendor_reference_once(UUID_A, false, None, None) + .await; + assert!(matches!(o, VendorServiceOutcome::Ready(_)), "{o:?}"); + assert_eq!(c.vendor_outage_count(), 1); + + // No answer at all: the read gives up at its own bound. + server.reset().await; + Mock::given(method("POST")) + .and(path(POST_PATH)) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(120))) + .mount(&server) + .await; + let started = std::time::Instant::now(); + let o = c + .fetch_vendor_reference_once(UUID_A, false, None, None) + .await; + let took = started.elapsed(); + assert!( + matches!(&o, VendorServiceOutcome::Failed(e) if e.to_string().contains("no answer within")), + "{o:?}" + ); + assert!( + took >= ADVISORY_REFERENCE_TIMEOUT && took < ADVISORY_REFERENCE_TIMEOUT * 3, + "{took:?}" + ); + assert_eq!(c.vendor_outage_count(), 1); + } + /// Pending / Unavailable answers prove the service is up: they reset /// the count, so an isolated failure never opens the breaker. #[tokio::test] diff --git a/crates/socket-patch-core/src/patch/gem_refresh.rs b/crates/socket-patch-core/src/patch/gem_refresh.rs index fb70463a44..20a15de886 100644 --- a/crates/socket-patch-core/src/patch/gem_refresh.rs +++ b/crates/socket-patch-core/src/patch/gem_refresh.rs @@ -213,7 +213,7 @@ fn inspect(bytes: Vec, wanted: &Wanted) -> Result { } /// A `.gem`'s `metadata.gz` member, gunzipped: the gemspec as YAML. -fn gem_metadata(gem_bytes: &[u8]) -> Option> { +pub(crate) fn gem_metadata(gem_bytes: &[u8]) -> Option> { use std::io::Read as _; let mut archive = tar::Archive::new(gem_bytes); for entry in archive.entries().ok()? { @@ -233,11 +233,11 @@ fn gem_metadata(gem_bytes: &[u8]) -> Option> { /// What a gemspec's YAML says that the refresh acts on. #[derive(Debug, PartialEq, Eq)] -struct SpecFacts { +pub(crate) struct SpecFacts { /// `-`, plus `-` for a platform gem. - full_name: String, + pub(crate) full_name: String, /// `extensions` lists at least one build script. - native: bool, + pub(crate) native: bool, } /// A top-level `key:` line of a gemspec's YAML and the rest of that line. @@ -265,7 +265,7 @@ fn unquote(value: &str) -> &str { /// top-level keys of one mapping, each followed by its indented block or /// its sequence items. `None` when the name or version cannot be read, or /// the platform is not a plain string. -fn parse_metadata(yaml: &str) -> Option { +pub(crate) fn parse_metadata(yaml: &str) -> Option { let lines: Vec<&str> = yaml.lines().collect(); let (mut name, mut version, mut platform, mut native) = (None, None, None, false); let mut i = 0; diff --git a/crates/socket-patch-core/src/vendor/common.rs b/crates/socket-patch-core/src/vendor/common.rs index 8f1cce2275..2fbbba64db 100644 --- a/crates/socket-patch-core/src/vendor/common.rs +++ b/crates/socket-patch-core/src/vendor/common.rs @@ -375,7 +375,11 @@ pub(crate) async fn swap_stage_into_place(stage: &Path, copy_dir: &Path) -> std: Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, Err(e) => return Err(e), }; - match tokio::fs::rename(stage, copy_dir).await { + let renamed = match crate::utils::failpoint::hit_or_error("vendor_swap_stage") { + Ok(()) => tokio::fs::rename(stage, copy_dir).await, + Err(e) => Err(e), + }; + match renamed { Ok(()) => { crate::utils::durability::moved(stage, copy_dir); if had_old { @@ -384,7 +388,7 @@ pub(crate) async fn swap_stage_into_place(stage: &Path, copy_dir: &Path) -> std: Ok(()) } Err(e) => { - if had_old { + if had_old && !crate::utils::failpoint::fails("vendor_swap_restore") { let _ = tokio::fs::rename(&backup, copy_dir).await; } Err(e) diff --git a/crates/socket-patch-core/src/vendor/composer_lock.rs b/crates/socket-patch-core/src/vendor/composer_lock.rs index 46b33ee717..ac4dc25f26 100644 --- a/crates/socket-patch-core/src/vendor/composer_lock.rs +++ b/crates/socket-patch-core/src/vendor/composer_lock.rs @@ -4252,7 +4252,7 @@ mod tests { let err = super::super::redownload::restore(root, &entry, &record, &cfg) .await .unwrap_err(); - assert!(err.contains("no complete file inventory"), "{err}"); + assert!(err.detail().contains("no complete file inventory"), "{err}"); } #[tokio::test] diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index d44df1cc7b..f182fd3ad6 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -61,7 +61,8 @@ //! as its ruby-platform tree (the extensions would never be built), so it is //! vendored as the patch service's PATCHED PLATFORM GEMS, one unpacked tree //! per locked platform, each with the stub gemspec the service serves for -//! it (verified against real bundler 4.0.15). The gem's fix is the patch +//! it (verified against real bundler 4.0.15), and upstream's own gem for a +//! platform that has no patched build yet. The gem's fix is the patch //! of its ruby gem (`` below, whatever the platforms); each patched //! platform gem has a patch of its own, which the fix's package reference //! names (`gemBuilds[].patchUuid`) and whose `tarball` and stub gemspec @@ -96,12 +97,21 @@ //! emptied in the copy. A tree git would still not commit in full is //! refused: wired without its binary, the gem would install everywhere //! and fail to load; -//! * every locked platform needs a patched build. While the fix's -//! reference names none for one of them (the patch registry serves -//! upstream's own gem for it, does not list it, or lists no platform gem -//! at all), or the patch it names for one is not served (it is still -//! being built, or the service does not grant it), the gem is left as it -//! is and reported as a skip +//! * every locked platform gets a tree, and at least one of them a +//! patched build. A platform the fix's reference names no patched build +//! for (`patchUuid: null`: the patch registry serves upstream's own gem +//! for it) gets that gem's tree, unchanged: the `.gem` the registry +//! serves for the platform, downloaded from the patch server and checked +//! against the sha256 the reference lists, with the gemspec the gem +//! itself carries (its `metadata.gz`, which bundler reads as it reads a +//! Ruby gemspec). Hosted mode installs the same gem for such a platform. +//! A later run follows the list: the tree becomes the patched build's +//! once one is published, and a tree whose patched build was withdrawn +//! goes back to upstream's gem ([`moved_sources`]). While no locked +//! platform has a patched build, the registry does not list one of them +//! or lists no platform gem at all, or the patch it names for one is not +//! served (it is still being built, or the service does not grant it), +//! the gem is left as it is and reported as a skip //! ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]): a build is named and //! served only once published, so the next run may find it. A plain //! ` ()` entry beside the platform ones (the ruby platform, @@ -143,9 +153,9 @@ use super::path::{parse_vendor_path, vendor_uuid_dir_rel}; use super::registry_fetch::{extract_gem_data, extract_on_blocking_pool}; use super::revert::{self, KeepPolicy}; use super::service_fetch::{ - claim_prestaged, downloaded_warning, fetch_served_reference, fetch_served_references, - fetch_verified_archive, fetch_verified_artifact, fetch_verified_secondary, - SecondaryArtifactResult, ServiceArtifact, ServicePolicy, Unserved, + ask_served_reference, claim_prestaged, downloaded_warning, fetch_served_reference, + fetch_served_references, fetch_verified_archive, fetch_verified_artifact, + fetch_verified_secondary, SecondaryArtifactResult, ServiceArtifact, ServicePolicy, Unserved, }; use super::source::PackageSource; use super::state::{ @@ -785,8 +795,8 @@ async fn gem_prelude_of( // ignores the dir itself (`.socket/`) cannot be overridden from inside // it, so the commit would drop the trees the lock names: refused here, // dry run or not, before anything is downloaded. Rules that ignore - // single files are for [`keep_platform_trees_committable`], once the - // trees are known. + // single files are for [`finish_platform_copy`], once the trees are + // staged. let in_sync = lock_wired && copy_ok; if !locked.platforms.is_empty() && !in_sync { if let Some((code, detail)) = @@ -895,11 +905,112 @@ pub(super) fn is_platform_dir_name(platform: &str) -> bool { /// bundler requires of one. async fn stub_gemspec_valid(tree: &Path, name: &str) -> bool { match read_regular_to_string(&tree.join(format!("{name}.gemspec"))).await { + // The gemspec a gem carries (a tree of upstream's own gem): it has + // to be the one of the gem this tree is named after. + Ok(text) if text.starts_with("---") => { + let dir = |path: Option<&Path>| { + let name = path.and_then(Path::file_name); + name.and_then(|name| name.to_str()).map(str::to_string) + }; + let leaf = dir(tree.parent()) + .zip(dir(Some(tree))) + .map(|(gem, platform)| format!("{gem}-{platform}")); + let facts = crate::patch::gem_refresh::parse_metadata(&text); + facts.is_some_and(|facts| !facts.native && Some(facts.full_name) == leaf) + } Ok(text) => gemspec_missing_required_attrs(&text).is_empty(), Err(_) => false, } } +/// Whether a ledger entry is one that follows the list of its gem's fix: +/// a gem copy of the patch `uuid` vendored as platform gems, whose entry +/// names the build of each tree. The one rule for the copies a run asks +/// the patch service about: an entry that names no build of its trees (a +/// development build's ledger) cannot say that the list names another +/// one, and is left alone. +pub fn follows_list(entry: &VendorEntry, uuid: &str) -> bool { + entry.ecosystem == "gem" && entry.uuid == uuid && !entry.gem_builds.is_empty() +} + +/// What the list of the gem's fix `uuid` names for each locked platform +/// now, where that is not what the ledger records for the copy: a patched +/// build where the copy holds upstream's gem (the build was published +/// since), upstream's gem where it holds a patched one (the build was +/// withdrawn), or the build of another patch. `None` while the list names +/// what the copy holds. Only a list that names a gem for every locked +/// platform says that it moved: with no list (the service has not read +/// the version's gems, or is building one again), a platform the list +/// leaves out, no answer or no service to ask, the copy stands as it is +/// and nothing is said. +/// +/// The list is `handed`, where a restore of the copy has just read it, +/// and else asked for: ONE request for this gem alone, and an advisory +/// one ([`ask_served_reference`]: a single short attempt, outside the +/// retry ladder and the circuit breaker), since the copy stands either +/// way. A service that is down costs a run that attempt per such gem, +/// and cannot fail what the run really has to vendor. +async fn moved_sources( + project_root: &Path, + service: Option<&VendorServiceConfig>, + uuid: &str, + name: &str, + copy_rel: &str, + trees: &PlatformTrees<'_>, + handed: Option<&FixList>, +) -> Option> { + let BuildsFrom::Locked(platforms) = &trees.from else { + return None; + }; + let entry = recorded_copy(project_root, uuid, copy_rel).await?; + if !follows_list(&entry, uuid) { + return None; + } + let asked; + let list = match handed { + Some(list) => list, + None => { + let cfg = service.filter(|cfg| cfg.service_enabled())?; + if service_offline_conflict(service).is_some() { + return None; + } + asked = fix_list_of(uuid, name, ask_served_reference(cfg, uuid).await).ok()??; + &asked + } + }; + let sources = listed_sources(list, name, trees, platforms).ok()?; + let moved = sources.iter().any(|source| { + let recorded = entry + .gem_builds + .iter() + .find(|b| b.platform == source.platform); + !recorded.is_some_and(|built| built.uuid.eq_ignore_ascii_case(&source.uuid)) + }); + moved.then_some(sources) +} + +/// The platforms whose patched build the vendored copy of ANOTHER patch +/// of the gem `name`@`version` holds, as the ledger records it. +async fn held_patched_platforms( + project_root: &Path, + name: &str, + version: &str, + uuid: &str, +) -> Vec { + let Ok(state) = super::state::load_state_shared(project_root).await else { + return Vec::new(); + }; + let base_purl = build_gem_purl(name, version); + let earlier = state.entries.values().filter(|entry| { + entry.ecosystem == "gem" && entry.base_purl == base_purl && entry.uuid != uuid + }); + earlier + .flat_map(|entry| entry.gem_builds.iter()) + .filter(|built| !built.is_upstream()) + .map(|built| built.platform.clone()) + .collect() +} + /// The vendor ledger's entry for the copy at `copy_rel` of the patch /// `uuid`: its file inventory is what vouches for the bytes of the /// platform trees once they are vendored (see [`verify_platform_tree`]), @@ -1129,6 +1240,7 @@ pub async fn vendor_gem<'a>( force, service, false, + None, &mut Vec::new(), ) .await @@ -1146,6 +1258,13 @@ pub async fn vendor_gem<'a>( /// which restores the gem's upstream entry before it calls and puts the /// pin back after a refusal). The skip of a gem with a locked platform /// that has no patched build then says that the gem stays hosted. +/// +/// `list`: the list of the gem's fix that a restore of the copy has just +/// read ([`restore_with_list`](super::redownload::restore_with_list)), +/// whether it restored the copy or was refused over that list. This call +/// judges the copy by it, and vendors a damaged copy again from it, so +/// the two are decided by one answer and the fix's reference is not asked +/// for again. A list of another fix than `record`'s is ignored. #[allow(clippy::too_many_arguments)] pub async fn vendor_gem_previewing<'a>( purl: &str, @@ -1158,6 +1277,7 @@ pub async fn vendor_gem_previewing<'a>( _force: bool, service: Option<&VendorServiceConfig>, hosted: bool, + list: Option<&FixList>, previewed: &mut Vec, ) -> VendorOutcome { let installed_dir = installed_dir.into(); @@ -1199,10 +1319,19 @@ pub async fn vendor_gem_previewing<'a>( let (lock_wired, copy_ok) = (*lock_wired, *copy_ok); // What is vendored for each locked platform, once the service names it. let label = format!("{name}@{version}"); + // The patched builds a copy of another patch of the gem holds. + let held = match platforms.is_empty() { + true => Vec::new(), + false => held_patched_platforms(project_root, name, version, &record.uuid).await, + }; let locked = |standing: Standing| PlatformTrees { gem: &label, from: BuildsFrom::Locked(platforms), standing, + held: match standing { + Standing::EarlierPatch => held.clone(), + _ => Vec::new(), + }, }; // ── idempotent hot path ────────────────────────────────────────────── @@ -1210,24 +1339,49 @@ pub async fn vendor_gem_previewing<'a>( // already reference the uuid path → touch nothing. `entry` stays `None`: // the first run's ledger entry holds the only copy of the pre-vendor // originals. - if lock_wired { - if copy_ok { - // The uuid dir's `.gitignore` / `.gitattributes` are not part - // of the copy: one that was deleted (or never written) is put - // back, or a project `*.so` rule drops the binaries from the - // next commit. - let mut warnings: Vec = Vec::new(); - if !platforms.is_empty() && !dry_run { - if let Err(e) = restore_uuid_metadata(uuid_dir).await { - warnings.push(VendorWarning::new( - super::npm_dir::GITIGNORE_UNCHECKED, - super::npm_dir::gitignore_unchecked_detail( - copy_rel, - &format!("cannot write the vendored dir's git metadata: {e}"), - ), - )); - } + // An intact copy vendored as platform gems still follows the fix's + // list: a locked platform that gained a patched build, or lost one to + // a withdrawal, is vendored again as the list has it now. + let list = list.filter(|list| list.is_of(&record.uuid) && lock_wired && !platforms.is_empty()); + let moved = match lock_wired && copy_ok && !platforms.is_empty() { + true => { + let wired = locked(Standing::Wired); + let (uuid, root) = (record.uuid.as_str(), project_root); + moved_sources(root, service, uuid, name, copy_rel, &wired, list).await + } + false => None, + }; + // A damaged copy whose exact restore was refused because the list + // names other builds is vendored again from the list that restore + // read: the gems it names, which settle the copy as the rebuild's own + // read of them would. + let handed = match list.filter(|_| !copy_ok) { + Some(list) => match listed_sources(list, name, &locked(Standing::Wired), platforms) { + Ok(sources) => Some(sources), + Err(unlisted) => { + let prelude = &prelude; + return wired_copy_failed(*unlisted, false, project_root, record, prelude, dry_run) + .await; } + }, + None => None, + }; + // The trees of the wired copy: the ones the list was already read to + // name (it is not read again), else the locked ones. + let wired = match moved.as_ref().or(handed.as_ref()) { + Some(sources) => PlatformTrees { + gem: &label, + from: BuildsFrom::Listed(sources), + standing: Standing::Wired, + held: Vec::new(), + }, + None => locked(Standing::Wired), + }; + if lock_wired { + if copy_ok && moved.is_none() { + let warnings = copy_in_force(project_root, record, &prelude, true, dry_run) + .await + .unwrap_or_default(); return done( already_patched_result(purl, copy_dir, &record.files), None, @@ -1248,34 +1402,54 @@ pub async fn vendor_gem_previewing<'a>( return refusal; } let mut warnings: Vec = Vec::new(); - let (result, builds) = match materialise_patched_copy( + let materialised = materialise_patched_copy( purl, + (project_root, copy_rel), copy_dir, uuid_dir, name, - &locked(Standing::Wired), + &wired, record, false, // live-wired: never unwind the uuid dir on failure service, &mut warnings, ) - .await - { - Ok(materialised) => materialised, - Err(outcome) => { - return wired_copy_not_rebuilt(*outcome, project_root, record, &prelude).await + .await; + let (result, builds) = match materialised { + Ok((result, builds)) if result.success => (result, builds), + failed => { + let failure = match failed { + Ok((result, _)) => done(result, None, warnings), + Err(outcome) => *outcome, + }; + return wired_copy_failed( + failure, + moved.is_some(), + project_root, + record, + &prelude, + dry_run, + ) + .await; } }; - if !result.success { - return done(result, None, warnings); - } - warnings.push(VendorWarning::new( - "vendor_artifact_rebuilt", - format!( - "the committed vendored copy for {name}@{version} was missing or stale; \ - rebuilt at {copy_rel} (Gemfile and Gemfile.lock untouched)" + warnings.push(match moved.is_some() { + true => VendorWarning::new( + GEM_LIST_FOLLOWED, + format!( + "the patch registry lists other builds for {name}@{version} than the \ + vendored copy held; vendored again at {copy_rel} (Gemfile and \ + Gemfile.lock untouched)" + ), ), - )); + false => VendorWarning::new( + "vendor_artifact_rebuilt", + format!( + "the committed vendored copy for {name}@{version} was missing or \ + stale; rebuilt at {copy_rel} (Gemfile and Gemfile.lock untouched)" + ), + ), + }); // The rebuilt tree may differ from the one the ledger // inventoried (a service ↔ local flip swaps the stub gemspec): // hand back a refreshed entry. Its wiring is empty ON PURPOSE — @@ -1311,16 +1485,30 @@ pub async fn vendor_gem_previewing<'a>( [] => super::service_fetch::preview_service(service, record, extract_gem_data) .await .map(|()| Vec::new()), - _ => preview_platform_builds(service, record, name, &locked(standing)).await, + _ => { + let trees = match lock_wired { + true => wired, + false => locked(standing), + }; + let place = (project_root, copy_rel); + preview_platform_builds(service, record, name, &trees, place).await + } }; match checked { Ok(builds) => *previewed = builds, - Err(outcome) => { - return match lock_wired { - true => wired_copy_not_rebuilt(*outcome, project_root, record, &prelude).await, - false => *outcome, - }; + // As the wet run settles it. + Err(outcome) if lock_wired => { + return wired_copy_failed( + *outcome, + moved.is_some(), + project_root, + record, + &prelude, + dry_run, + ) + .await } + Err(outcome) => return *outcome, } return done( super::common::preview_result(purl, copy_dir, &record.files), @@ -1345,6 +1533,7 @@ pub async fn vendor_gem_previewing<'a>( } let (mut result, builds) = match materialise_patched_copy( purl, + (project_root, copy_rel), copy_dir, uuid_dir, name, @@ -1366,26 +1555,13 @@ pub async fn vendor_gem_previewing<'a>( } result.package_path = copy_dir.display().to_string(); - // ── prebuilt trees git would not commit ────────────────────────────── - // Asked before either project file is written (see - // `keep_platform_trees_committable`). The inventory taken for it is - // the entry's, below. + // The inventory of the platform trees, which the entry records below. + // (Whether git would commit them was asked before they were moved into + // place: `finish_platform_copy`.) let mut platform_inventory = None; if !platforms.is_empty() { let inventory = inventory_or_warn(copy_dir, &format!("{name}@{version}"), &mut warnings).await; - if let Err(refusal) = keep_platform_trees_committable( - project_root, - copy_rel, - inventory.as_ref(), - &mut warnings, - ) - .await - { - let _ = remove_tree(uuid_dir).await; - prune_empty_vendor_levels(uuid_dir).await; - return refusal; - } platform_inventory = Some(inventory); } @@ -1543,46 +1719,288 @@ pub async fn vendor_gem_previewing<'a>( done(result, Some(entry), warnings) } +/// Advisory of a run that vendored an intact copy again because the list +/// of the gem's fix names another build for a locked platform than the +/// copy held: a patched build published since, or upstream's gem where +/// the patched build was withdrawn. The entry it comes with replaces the +/// copy's own, as an artifact rebuild's does. +pub const GEM_LIST_FOLLOWED: &str = "vendor_gem_list_followed"; + +/// Advisory of a run that found the same and could not vendor the copy +/// again (a request that failed, a build that is not served or fails its +/// digest, a gem that does not unpack): the copy is intact and stays in +/// force as it is, and the run ends as it does for a copy in step. +pub const GEM_LIST_NOT_FOLLOWED: &str = "vendor_gem_list_not_followed"; + +/// Whether the copy the ledger records for `record` stands, with the git +/// metadata of its uuid dir in place: the one answer behind every "the +/// vendored copy stays in force". `verified`: this run's prelude found +/// the copy intact and nothing has written to it since, so its trees are +/// not read again; otherwise every tree the entry names is checked +/// ([`recorded_copy_stands`]), as after an attempt to vendor the copy +/// again, which can fail once the copy was already changed. A copy +/// vendored as platform gems that stands is then confirmed +/// ([`CopyStep::Confirming`], never by a dry run): the uuid dir's +/// `.gitignore` and `.gitattributes` are put back where one is missing, +/// and git is asked nothing, since the copy is already what the project +/// commits. `None` when the copy does not stand; else what there is to +/// say of it. +async fn copy_in_force( + project_root: &Path, + record: &PatchRecord, + prelude: &GemPrelude, + verified: bool, + dry_run: bool, +) -> Option> { + let (copy_rel, copy_dir) = (prelude.copy_rel.as_str(), prelude.copy_dir.as_path()); + let stands = verified + || recorded_copy_stands(project_root, record, copy_rel, copy_dir, &prelude.name).await; + if !stands { + return None; + } + let mut warnings: Vec = Vec::new(); + if !prelude.platforms.is_empty() && !dry_run { + // Confirming a copy refuses nothing. + let _ = finish_platform_copy( + project_root, + copy_rel, + CopyStep::Confirming, + false, + &mut warnings, + ) + .await; + } + Some(warnings) +} + +/// Advisory of a copy vendored as platform gems whose uuid dir's +/// `.gitignore` and `.gitattributes` could not be written. The trees are +/// in place and correct, but those two files are what keeps a project +/// ignore rule or filter (such as `*.so`) off them: the detail names the +/// files and says to make them writable. +pub const GEM_GIT_METADATA_UNWRITTEN: &str = "vendor_gem_git_metadata_unwritten"; + +/// What a run is doing with the copy it finishes ([`finish_platform_copy`]). +pub(super) enum CopyStep<'a> { + /// Trees are about to be moved into place: a first vendor, a rebuild of + /// a copy the lock is wired to, a restore, or a dry run's preview of + /// one. They are staged at this directory. + Placing(&'a Path), + /// The copy that is there stands: one found in step, or one left in + /// force. + Confirming, +} + +/// Finish a copy vendored as platform gems: the one step of every path +/// that is about to put such trees in place, or that says the ones that +/// are there stay. +/// +/// 1. The uuid dir's `.gitignore` and `.gitattributes` are written where +/// absent or different ([`restore_uuid_metadata`]). They are not part +/// of the copy, so a write that fails is never a failure: it is the +/// warning [`GEM_GIT_METADATA_UNWRITTEN`]. A dry run writes nothing, +/// and says what it can tell of that write. +/// 2. Where trees are about to be placed ([`CopyStep::Placing`]), git is +/// asked whether it would commit them, BEFORE they are moved in, so a +/// refusal leaves what is on disk as it was. The question needs only +/// path names, and is asked as if nothing were tracked, which does not +/// read the index. With the uuid dir's own rules in place no rule +/// above them reaches a file of the copy, so what can keep the copy out +/// of a commit is a rule that excludes the directory itself. Without +/// them every rule of the project applies to every staged file, and +/// the refusal (`vendor_artifact_gitignored`) gives the files that +/// could not be written as its cause, with what to do about them. Git +/// failing to answer is only a warning. A dry run asks the same. +/// +/// A copy that is already there ([`CopyStep::Confirming`]) is what the +/// project commits, and git is asked nothing about it. +pub(super) async fn finish_platform_copy( + project_root: &Path, + copy_rel: &str, + step: CopyStep<'_>, + dry_run: bool, + warnings: &mut Vec, +) -> Result<(), VendorOutcome> { + let Some((uuid_dir_rel, _)) = copy_rel.rsplit_once('/') else { + return Ok(()); + }; + let uuid_dir = project_root.join(uuid_dir_rel); + let metadata = format!("`{uuid_dir_rel}/.gitignore` and `{uuid_dir_rel}/.gitattributes`"); + let unwritten: Option = match dry_run { + true => metadata_write_would_fail(&uuid_dir).await, + false => match restore_uuid_metadata(&uuid_dir).await { + Ok(_) => None, + Err(e) => Some(e.to_string()), + }, + }; + let ignoring = match (&step, &unwritten) { + (CopyStep::Confirming, _) => Ok(None), + (CopyStep::Placing(_), None) => { + super::npm_dir::gitignore_probe(project_root, &[format!("{uuid_dir_rel}/")]).await + } + (CopyStep::Placing(staged), Some(_)) => { + match super::verify::compute_dir_inventory(staged).await { + Ok(inventory) => { + let paths: Vec = inventory + .keys() + .map(|file| format!("{copy_rel}/{file}")) + .collect(); + super::npm_dir::gitignore_probe(project_root, &paths).await + } + // What could not be listed is already said of the copy. + Err(_) => Ok(None), + } + } + }; + match (ignoring, unwritten) { + (Ok(Some(rules)), None) => Err(refused( + super::npm_dir::GITIGNORED, + super::npm_dir::gitignored_detail(copy_rel, &rules), + )), + (Ok(Some(rules)), Some(e)) => Err(refused( + super::npm_dir::GITIGNORED, + format!( + "git would not commit the vendored artifact at {copy_rel} ({rules}): {metadata}, \ + which keep such a rule off it, could not be written ({e}); make those two files \ + writable and vendor again" + ), + )), + (unanswered, unwritten) => { + if let Some(e) = unwritten { + warnings.push(VendorWarning::new( + GEM_GIT_METADATA_UNWRITTEN, + format!( + "could not write {metadata} ({e}): they keep a project ignore rule or \ + filter (such as `*.so`) off the vendored copy at {copy_rel}; make those \ + two files writable and run this again" + ), + )); + } + if let Err(why) = unanswered { + warnings.push(VendorWarning::new( + super::npm_dir::GITIGNORE_UNCHECKED, + super::npm_dir::gitignore_unchecked_detail(copy_rel, &why), + )); + } + Ok(()) + } + } +} + +/// What a wet run's write of the uuid dir's `.gitignore` and +/// `.gitattributes` would fail on, as far as a dry run can tell without +/// writing: something that is not a regular file stands where one of them +/// belongs. +async fn metadata_write_would_fail(uuid_dir: &Path) -> Option { + for name in [".gitignore", ".gitattributes"] { + let there = tokio::fs::symlink_metadata(uuid_dir.join(name)).await; + if there.is_ok_and(|file| !file.is_file()) { + return Some(format!("{name} is not a regular file")); + } + } + None +} + +/// Remove a uuid dir that holds nothing but its git metadata, and the +/// vendor levels that leaves empty: a run that did not put its trees in +/// place leaves no such directory behind. +pub(super) async fn remove_metadata_alone(uuid_dir: &Path) { + let Ok(mut entries) = tokio::fs::read_dir(uuid_dir).await else { + return; + }; + let mut names = Vec::new(); + while let Ok(Some(entry)) = entries.next_entry().await { + names.push(entry.file_name()); + } + if names + .iter() + .all(|name| name == ".gitignore" || name == ".gitattributes") + { + for name in &names { + let _ = tokio::fs::remove_file(uuid_dir.join(name)).await; + } + prune_empty_vendor_levels(uuid_dir).await; + } +} + /// The outcome of a copy the lock is ALREADY wired to that this run could -/// not rebuild because a locked platform has no patched build -/// ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]). While the copy the -/// ledger records is intact (the lock gained a platform since) it stays -/// in force as it is, and the outcome stays that skip. Otherwise the lock -/// names a tree that is missing or damaged and no older patch stands in -/// for it: the plain miss, a failure. -async fn wired_copy_not_rebuilt( - outcome: VendorOutcome, +/// not vendor again (`failure`: the refusal, or the result that did not +/// succeed). What is said depends on whether the copy the ledger records +/// still stands ([`copy_in_force`]), which is asked here and never +/// assumed: an attempt can fail after the copy was changed (the swap of +/// the stage fails and cannot be undone). +/// +/// * A locked platform has no patched build to vendor +/// ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]): while the copy stands +/// it stays in force as it is, and the outcome stays that skip. +/// * `moved`: the copy was intact and only the list of its fix, which +/// names another build for a locked platform, said to vendor it again. +/// While it still stands, an intact copy is never made worse and the +/// run never fails over it: it stays in force, the run reports it as it +/// reports a copy in step, and one line says why it was not brought in +/// step ([`GEM_LIST_NOT_FOLLOWED`]). +/// * Otherwise the lock names a copy that is missing or damaged: the +/// failure, as for any damaged copy. +async fn wired_copy_failed( + failure: VendorOutcome, + moved: bool, project_root: &Path, record: &PatchRecord, prelude: &GemPrelude, + dry_run: bool, ) -> VendorOutcome { - match outcome { - VendorOutcome::Refused { code, detail } - if code == super::VENDOR_PREBUILT_PLATFORM_PENDING => - { - let stands = recorded_copy_stands( - project_root, - record, - &prelude.copy_rel, - &prelude.copy_dir, - &prelude.name, + let pending = matches!(&failure, VendorOutcome::Refused { code, .. } + if *code == super::VENDOR_PREBUILT_PLATFORM_PENDING); + if !pending && !moved { + return failure; + } + let in_force = copy_in_force(project_root, record, prelude, false, dry_run).await; + match (failure, in_force) { + // A skip carries no advisory of its own: what there is to say of + // the copy ends its line. + (VendorOutcome::Refused { code, detail }, Some(warnings)) if pending => { + let also: String = warnings + .iter() + .map(|warning| format!(" Also: {}.", warning.detail.trim_end_matches('.'))) + .collect(); + refused( + code, + format!("{detail}; its vendored copy stays in force as it is.{also}"), ) - .await; - match stands { - true => refused( - code, - format!("{detail}; its vendored copy stays in force as it is."), - ), - false => refused( - super::VENDOR_PREBUILT_REQUIRED, - format!( - "{detail}; its vendored copy is missing or damaged and cannot be \ - rebuilt until then." - ), + } + (VendorOutcome::Refused { detail, .. }, None) if pending => refused( + super::VENDOR_PREBUILT_REQUIRED, + format!( + "{detail}; its vendored copy is missing or damaged and cannot be rebuilt until \ + then." + ), + ), + (failure, Some(mut warnings)) => { + let why = match &failure { + VendorOutcome::Refused { detail, .. } => detail.clone(), + VendorOutcome::Done { result, .. } => result.error.clone().unwrap_or_default(), + }; + let why = match why.trim().trim_end_matches('.') { + "" => String::new(), + why => format!(" ({why})"), + }; + warnings.push(VendorWarning::new( + GEM_LIST_NOT_FOLLOWED, + format!( + "{}@{} could not be brought in step with the builds the patch registry \ + lists{why}; its vendored copy stays in force as it is.", + prelude.name, prelude.version ), - } + )); + let purl = build_gem_purl(&prelude.name, &prelude.version); + done( + already_patched_result(&purl, &prelude.copy_dir, &record.files), + None, + warnings, + ) } - other => other, + // The copy the lock names no longer stands. + (failure, None) => failure, } } @@ -1794,8 +2212,66 @@ pub(super) enum BuildsFrom<'a> { /// (`gemBuilds[].patchUuid`). Locked(&'a [String]), /// The trees a ledger entry records, each from its recorded patch: a - /// restore of that copy. - Recorded(&'a [GemBuildEntry]), + /// restore of that copy, held to the list of the fix as it was read + /// for it ([`restore_list`]). + Recorded(&'a [GemBuildEntry], &'a FixList), + /// [`Self::Locked`] where the list was already read: the gem it names + /// for each locked platform ([`moved_sources`], or a restore that was + /// refused over it), so the fix's reference is asked for once. + Listed(&'a [BuildSource]), +} + +/// The list of a gem's fix as ONE request read it: the gem its registry +/// lists for each platform (a patched build with its patch, or upstream's +/// own), and where that registry serves the gem files. What reads it +/// hands it on, so a copy is judged and vendored by one answer. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FixList { + /// The fix whose list this is. A list is only ever used for that fix. + fix: String, + builds: Vec, + index_url: Option, +} + +impl FixList { + /// Whether this is the list of the fix `uuid`. + fn is_of(&self, uuid: &str) -> bool { + self.fix.eq_ignore_ascii_case(uuid) + } +} + +/// The list of the gem's fix `uuid`: ONE request, the fix's package +/// reference, and nothing downloaded. `None` when the reference carries +/// no list right now (the service has not read the version's gems, or is +/// building one again). +async fn read_fix_list( + cfg: &VendorServiceConfig, + uuid: &str, + name: &str, +) -> Result, Box> { + fix_list_of(uuid, name, fetch_served_reference(cfg, uuid).await) +} + +/// The list in the `reference` the service answered for the fix `uuid`. +fn fix_list_of( + uuid: &str, + name: &str, + reference: ServiceArtifact, +) -> Result, Box> { + let served = match reference { + ServiceArtifact::Pending => return Ok(None), + reference => ServicePolicy::Refused.settle( + reference, + "platform gem", + &format!("platform gems for {name}"), + )?, + }; + let (fix, index_url) = (uuid.to_string(), served.gem_index_url); + Ok(served.gem_builds.map(|builds| FixList { + fix, + builds, + index_url, + })) } /// What a gem has in place of the patch being vendored, should a locked @@ -1819,18 +2295,30 @@ pub(super) struct PlatformTrees<'a> { pub(super) gem: &'a str, pub(super) from: BuildsFrom<'a>, pub(super) standing: Standing, + /// The platforms whose patched build the copy in force of another + /// patch of the gem holds ([`Standing::EarlierPatch`]): the gem does + /// not move to a fix whose list patches fewer of them, as a hosted + /// lock does not. Empty where no such copy stands. + pub(super) held: Vec, } /// One platform tree to stage: the patch it is unpacked from, and what its /// downloads must match beyond the digests that patch's own reference -/// states for them. -struct BuildSource { +/// states for them. Or, for a platform the fix's list names no patched +/// build for, upstream's own gem as the patch registry serves it. +#[derive(Clone)] +pub(super) struct BuildSource { platform: String, + /// The patch of the platform's patched build; empty for upstream's gem. uuid: String, + /// Upstream's gem for the platform: the file the fix's registry serves + /// for it (`gems/`), with the sha256 its list names. + upstream: Option, pinned: BuildPin, } -enum BuildPin { +#[derive(Clone)] +pub(super) enum BuildPin { /// sha256 (hex) of the `.gem` the gem patch's registry lists for the /// platform (`gemBuilds[].gemChecksumSha256`). Registry(String), @@ -1879,6 +2367,18 @@ impl NoPatchedBuild<'_> { } } +/// What vendored mode needs of the patch registry for a gem locked as +/// platform gems, in the lines of a gem it leaves as it is: a tree for +/// each locked platform, of the patched build or of upstream's own gem. +const NEEDS_A_GEM: &str = + "Vendored mode needs a gem, patched or upstream's own, for every locked platform"; + +/// The remedy of a copy that cannot be restored as it was vendored because +/// the list of its fix moved ([`VENDOR_PREBUILT_REPLACED`]): the run that +/// vendors the copy again from that list. +const VENDOR_FROM_THE_LIST: &str = + "Run `socket-patch scan --mode vendored`, which vendors what the patch service serves now"; + /// The one line for a gem left as it is because the locked platforms of /// `missing` have no patched build, while `patched` (the other locked /// platforms) have one. Its last clause says what the gem's `standing` @@ -1889,7 +2389,7 @@ impl NoPatchedBuild<'_> { /// it, as `vex` does of such a build. For a lock already wired to this /// patch's copy /// ([`Standing::Wired`]) the caller ends the line with what became of -/// that copy ([`wired_copy_not_rebuilt`]); otherwise it is the whole +/// that copy ([`wired_copy_failed`]); otherwise it is the whole /// line. fn no_patched_build_detail( gem: &str, @@ -1926,11 +2426,10 @@ fn no_patched_build_detail( Standing::Hosted => "; the gem stays hosted.", }; return format!( - "{gem} {lead}: the patch registry does not list {names}{also}. Vendored mode needs \ - every locked platform, and a re-run does not change what the registry lists: this \ - is settled once the lockfile no longer names {names} (`bundle lock \ - --remove-platform {args}`), or the registry lists a gem for every locked \ - platform{tail}", + "{gem} {lead}: the patch registry does not list {names}{also}. {NEEDS_A_GEM}, and a \ + re-run does not change what the registry lists: this is settled once the \ + lockfile no longer names {names} (`bundle lock --remove-platform {args}`), or the \ + registry lists a gem for every locked platform{tail}", names = listed(unlisted), args = unlisted.join(" "), ); @@ -1949,7 +2448,57 @@ fn no_patched_build_detail( (Standing::NotVendored, false) => "; `scan --mode hosted` can patch the others now.", (Standing::Hosted, false) => "; the gem stays hosted.", }; - format!("{gem} {lead}: {none}{have}. Vendored mode needs every locked platform{tail}") + format!("{gem} {lead}: {none}{have}. {NEEDS_A_GEM}{tail}") +} + +/// The skip of a gem none of whose locked platforms (`upstream`) has a +/// patched build in the fix's list: there is nothing to vendor it for, +/// and the registry would serve upstream's own gem for each. The gem +/// moves on a later run, once a build of one of them is published. +fn none_patched_skip(trees: &PlatformTrees<'_>, upstream: &[&str]) -> Box { + let (lead, tail) = match trees.standing { + Standing::NotVendored | Standing::Hosted => ("is not vendored", "."), + Standing::Wired => ("was not brought up to date", ""), + Standing::EarlierPatch => ( + "was not brought up to date", + "; its vendored copy of an earlier patch stays in force as it is.", + ), + }; + Box::new(refused( + super::VENDOR_PREBUILT_PLATFORM_PENDING, + format!( + "{} {lead}: no patched build yet for {}{tail}", + trees.gem, + listed(upstream) + ), + )) +} + +/// The skip of a gem whose copy of an earlier patch holds the patched +/// build of platforms (`lost`) that the newer fix has none for: the copy +/// stays in force, as a hosted lock stays on the patch it is on +/// ([`GEM_NEWER_FIX_WAITS`](crate::hosted::engine::GEM_NEWER_FIX_WAITS)). +fn newer_fix_waits(trees: &PlatformTrees<'_>, lost: &[&str]) -> Box { + Box::new(refused( + super::VENDOR_PREBUILT_PLATFORM_PENDING, + format!( + "{} 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.", + trees.gem, + listed(lost) + ), + )) +} + +/// `sha256-` of a sha256 given in hex, as the patch registry +/// lists a gem's; `None` for anything else. +fn sha256_sri(hex_digest: &str) -> Option { + use base64::Engine as _; + let bytes = hex::decode(hex_digest).ok().filter(|b| b.len() == 32)?; + Some(format!( + "sha256-{}", + base64::engine::general_purpose::STANDARD.encode(bytes) + )) } /// What a gem's fix says when it names no builds to vendor from right @@ -2017,45 +2566,168 @@ async fn locked_build_sources( name: &str, trees: &PlatformTrees<'_>, platforms: &[String], +) -> Result, Box> { + match read_fix_list(cfg, uuid, name).await? { + Some(list) => listed_sources(&list, name, trees, platforms), + None => Err(no_builds_listed_skip(trees)), + } +} + +/// [`locked_build_sources`] of a list that was already read: no request. +fn listed_sources( + list: &FixList, + name: &str, + trees: &PlatformTrees<'_>, + platforms: &[String], ) -> Result, Box> { let policy = ServicePolicy::Refused; - let served = match fetch_served_reference(cfg, uuid).await { - ServiceArtifact::Pending => return Err(no_builds_listed_skip(trees)), - reference => policy.settle( - reference, - "platform gem", - &format!("platform gems for {name}"), - )?, - }; - let Some(builds) = served.gem_builds.as_deref() else { - return Err(no_builds_listed_skip(trees)); - }; - let mut sources: Vec = Vec::with_capacity(platforms.len()); + let builds = list.builds.as_slice(); + let mut listed = Vec::with_capacity(platforms.len()); let mut missing = NoPatchedBuild::default(); for platform in platforms { - let Some(build) = builds.iter().find(|build| build.platform == *platform) else { - missing.unlisted.push(platform); - continue; - }; - match build.patch_uuid.as_deref() { - Some(uuid) => sources.push(BuildSource { - platform: platform.clone(), - uuid: uuid.to_string(), - pinned: BuildPin::Registry(build.gem_checksum_sha256.clone()), - }), - None => missing.yet.push(platform), + match builds.iter().find(|build| build.platform == *platform) { + Some(build) => listed.push((platform, build)), + None => missing.unlisted.push(platform), } } - if missing.is_empty() { - return Ok(sources); + // The skips first: a gem that is left as it is whatever its gems are + // is never failed over one of them. A platform the list leaves out + // has no gem to vendor at all. + if !missing.is_empty() { + return Err(no_patched_build(trees, &missing, &[])); + } + let of = |patched: bool| -> Vec<&str> { + let kept = listed + .iter() + .filter(|(_, build)| build.patch_uuid.is_some() == patched); + kept.map(|(platform, _)| platform.as_str()).collect() + }; + let patched = of(true); + // With no patched build among the locked platforms there is nothing + // to vendor the gem for. A copy the lock is already wired to follows + // the list all the same, as a hosted lock does: its builds were + // withdrawn, and its trees go back to upstream's gems. + if patched.is_empty() && trees.standing != Standing::Wired { + return Err(none_patched_skip(trees, &of(false))); + } + let lost: Vec<&str> = trees + .held + .iter() + .map(String::as_str) + .filter(|held| platforms.iter().any(|p| p == held) && !patched.contains(held)) + .collect(); + if !lost.is_empty() { + return Err(newer_fix_waits(trees, &lost)); + } + let mut sources: Vec = Vec::with_capacity(listed.len()); + for (platform, build) in listed { + let upstream = match build.patch_uuid { + Some(_) => None, + // Upstream's own gem, from the registry that lists it. + None => { + let index = list.index_url.as_deref(); + let gem = upstream_gem_artifact(index, trees.gem, platform, build); + Some(gem.ok_or_else(|| { + policy.miss(format!( + "the patch service names no registry or no sha256 for upstream's \ + gem of {name} ({platform})" + )) + })?) + } + }; + sources.push(BuildSource { + platform: platform.clone(), + uuid: build.patch_uuid.clone().unwrap_or_default(), + upstream, + pinned: BuildPin::Registry(build.gem_checksum_sha256.clone()), + }); } - let patched: Vec<&str> = sources.iter().map(|s| s.platform.as_str()).collect(); - Err(no_patched_build(trees, &missing, &patched)) + Ok(sources) } -/// A restore found that the build a ledger entry records for a platform is -/// no longer the one the list of the gem's fix names for it: it was rebuilt -/// under another patch or with other bytes, or withdrawn. A fix that +/// The version of `gem` (`@`, as [`PlatformTrees::gem`] +/// names it). +fn gem_version(gem: &str) -> &str { + gem.rsplit_once('@').map_or("", |(_, version)| version) +} + +/// Upstream's own gem of `platform` as the registry at `index` (the +/// gem patch's `indexUrl`) serves it and `listed` pins it: the file +/// `/gems/--.gem`, with the sha256 of the +/// list. `None` when the reference names no registry, or no sha256 that +/// is one. `gem` is `@`. +fn upstream_gem_artifact( + index: Option<&str>, + gem: &str, + platform: &str, + listed: &crate::patch::redirect::GemPlatformChecksum, +) -> Option { + let (name, version) = gem.rsplit_once('@')?; + Some(crate::api::client::SecondaryArtifact { + kind: "gem".to_string(), + url: format!( + "{}/gems/{name}-{version}-{platform}.gem", + index?.trim_end_matches('/') + ), + integrity_sri: sha256_sri(&listed.gem_checksum_sha256)?, + prefetched: None, + }) +} + +/// The list a restore of a copy of the fix `fix` (the gem +/// `name`@`version`) is held to: ONE request. A restore has no copy to +/// leave in force: with no list it fails, and says when to run it again. +pub(super) async fn restore_list( + cfg: &VendorServiceConfig, + fix: &str, + name: &str, + version: &str, +) -> Result> { + if !cfg.service_enabled() { + return Err(Box::new(super::service_fetch::required())); + } + read_fix_list(cfg, fix, name).await?.ok_or_else(|| { + let gem = format!("{name}@{version}"); + ServicePolicy::Refused.unserved( + super::VENDOR_PREBUILT_PENDING, + format!("{}; run this again later", no_builds_listed(&gem)), + ) + }) +} + +/// The list of the fix `fix` (the gem `name`@`version`) where a restore +/// of the trees `builds` would be refused because it names another build +/// for one of them ([`VENDOR_PREBUILT_REPLACED`]): what a dry run asks in +/// place of the restore. ONE request, nothing downloaded. +pub(super) async fn recorded_list_moved( + cfg: &VendorServiceConfig, + fix: &str, + name: &str, + version: &str, + builds: &[GemBuildEntry], +) -> Option { + let gem = format!("{name}@{version}"); + let list = restore_list(cfg, fix, name, version).await.ok()?; + let trees = PlatformTrees { + gem: &gem, + from: BuildsFrom::Recorded(builds, &list), + standing: Standing::Wired, + held: Vec::new(), + }; + let moved = recorded_build_sources(name, &trees, builds, &list) + .is_err_and(|outcome| is_list_moved(&outcome)); + moved.then_some(list) +} + +/// Whether `outcome` is a restore's refusal of a copy whose list moved +/// ([`VENDOR_PREBUILT_REPLACED`]). +pub(super) fn is_list_moved(outcome: &VendorOutcome) -> bool { + matches!(outcome, VendorOutcome::Refused { code, .. } if *code == VENDOR_PREBUILT_REPLACED) +} + +/// A restore found that the build a ledger entry records for a platform is +/// no longer the one the list of the gem's fix names for it: it was rebuilt +/// under another patch or with other bytes, or withdrawn. A fix that /// carries no list says neither ([`no_builds_listed`]). /// Nothing is unpacked. Not an integrity failure: the same state follows /// an edited ledger, and neither is told from the other here. @@ -2078,34 +2750,15 @@ pub(crate) const VENDOR_PREBUILT_REPLACED: &str = "vendor_prebuilt_replaced"; /// or none, is not worded as tampering nor as a first vendoring: the copy /// cannot be restored as it was ([`VENDOR_PREBUILT_REPLACED`]), and the /// message names the commands that vendor the current build. -async fn recorded_build_sources( - cfg: &VendorServiceConfig, - fix: &str, +fn recorded_build_sources( name: &str, trees: &PlatformTrees<'_>, builds: &[GemBuildEntry], + list: &FixList, ) -> Result, Box> { let policy = ServicePolicy::Refused; - // A restore has no copy to leave in force: it fails, and says when to - // run it again. - let not_listed = || { - policy.unserved( - super::VENDOR_PREBUILT_PENDING, - format!("{}; run this again later", no_builds_listed(trees.gem)), - ) - }; - let served = match fetch_served_reference(cfg, fix).await { - ServiceArtifact::Pending => return Err(not_listed()), - reference => policy.settle( - reference, - "platform gem", - &format!("platform gems for {name}"), - )?, - }; // Only a list says a build was replaced or withdrawn. - let Some(listed) = served.gem_builds.as_deref() else { - return Err(not_listed()); - }; + let listed = list.builds.as_slice(); let mut sources = Vec::with_capacity(builds.len()); for built in builds { let subject = format!("{name} ({})", built.platform); @@ -2115,14 +2768,62 @@ async fn recorded_build_sources( format!( "the copy of the platform gem for {subject} cannot be restored as it was \ vendored: the vendor ledger records patch {} for it, and the gem's fix \ - {now}. Nothing was restored. To vendor what the patch service serves \ - now, run `socket-patch rollback pkg:gem/{}` and then \ - `socket-patch scan --mode vendored`", - built.uuid, trees.gem + {now}. Nothing was restored. {VENDOR_FROM_THE_LIST}", + built.uuid ), ) }; let now = listed.iter().find(|gem| gem.platform == built.platform); + // A tree of upstream's own gem is restored from the gem the + // registry lists for the platform today, which must be the one the + // entry pins. + if built.is_upstream() { + let Some(gem) = now.filter(|gem| gem.patch_uuid.is_none()) else { + return Err(policy.hard( + VENDOR_PREBUILT_REPLACED, + format!( + "the copy of upstream's gem for {subject} cannot be restored as it \ + was vendored: the gem's fix {} for that platform now. Nothing was \ + restored. {VENDOR_FROM_THE_LIST}", + match now.and_then(|gem| gem.patch_uuid.as_deref()) { + Some(uuid) => format!("names the patched build of patch {uuid}"), + None => "lists no gem".to_string(), + } + ), + )); + }; + // The list still names upstream's gem for the platform: a + // reference that does not say where it is, or pins no sha256 + // that is one, is a miss and not a list that moved. + let index = list.index_url.as_deref(); + let Some(artifact) = upstream_gem_artifact(index, trees.gem, &built.platform, gem) + else { + return Err(policy.miss(format!( + "the patch service names no registry or no sha256 for upstream's gem of \ + {subject}" + ))); + }; + if built.gem_integrity.is_empty() { + return Err(policy.hard( + "vendor_prebuilt_integrity_mismatch", + format!( + "the vendor ledger's entry for upstream's gem for {subject} pins no \ + digest for the gem it was vendored from; refusing to restore it" + ), + )); + } + sources.push(BuildSource { + platform: built.platform.clone(), + uuid: String::new(), + upstream: Some(artifact), + pinned: BuildPin::Restored { + sha256: gem.gem_checksum_sha256.clone(), + gem: built.gem_integrity.clone(), + gemspec: String::new(), + }, + }); + continue; + } let Some((gem, uuid)) = now.and_then(|gem| Some((gem, gem.patch_uuid.as_deref()?))) else { return Err(replaced( "names no patched build for that platform now (it was withdrawn)", @@ -2147,6 +2848,7 @@ async fn recorded_build_sources( sources.push(BuildSource { platform: built.platform.clone(), uuid: uuid.to_string(), + upstream: None, pinned: BuildPin::Restored { sha256: gem.gem_checksum_sha256.clone(), gem: built.gem_integrity.clone(), @@ -2193,14 +2895,15 @@ fn refuse_foreign_stub( } } -/// One platform tree whose patch the service serves: its source, how -/// messages name it (` ()`), and the gem and the stub -/// gemspec that patch's reference lists. +/// One platform tree to download: its source, how messages name it +/// (` ()`), its gem, and the stub gemspec its patch's +/// reference lists. A tree of upstream's own gem has no stub: its gemspec +/// is the one the gem carries. type ServedBuild<'a> = ( &'a BuildSource, String, crate::api::client::SecondaryArtifact, - crate::api::client::SecondaryArtifact, + Option, ); /// What the patch of each of `sources` serves, asked for in ONE request @@ -2221,14 +2924,29 @@ async fn served_builds<'a>( sources: &'a [BuildSource], ) -> Result>, Box> { let policy = ServicePolicy::Refused; - let uuids: Vec = sources.iter().map(|source| source.uuid.clone()).collect(); - let references = fetch_served_references(cfg, &uuids) + // Only a patched build has a patch to ask about. + let patched = sources.iter().filter(|source| source.upstream.is_none()); + let uuids: Vec = patched.map(|source| source.uuid.clone()).collect(); + let mut references = fetch_served_references(cfg, &uuids) .await - .map_err(|reason| policy.miss(format!("patch service request failed ({reason})")))?; + .map_err(|reason| policy.miss(format!("patch service request failed ({reason})")))? + .into_iter(); let mut builds = Vec::with_capacity(sources.len()); let mut missing = NoPatchedBuild::default(); - for (source, (reference, unserved)) in sources.iter().zip(references) { - if let (BuildsFrom::Locked(_), Some(unserved)) = (&trees.from, unserved) { + for source in sources { + if let Some(gem) = &source.upstream { + let subject = format!("{name} ({})", source.platform); + builds.push((source, subject, gem.clone(), None)); + continue; + } + let Some((reference, unserved)) = references.next() else { + return Err(policy.miss(format!( + "the patch service did not answer for the patch of {name} ({})", + source.platform + ))); + }; + let from_list = !matches!(trees.from, BuildsFrom::Recorded(..)); + if let (true, Some(unserved)) = (from_list, unserved) { match unserved { Unserved::Building => missing.yet.push(&source.platform), Unserved::NotGranted => missing.unavailable.push(&source.platform), @@ -2251,11 +2969,12 @@ async fn served_builds<'a>( "the patch service served no stub gemspec for {subject}" ))); }; - builds.push((source, subject, gem, stub)); + builds.push((source, subject, gem, Some(stub))); } if !missing.is_empty() { let patched: Vec<&str> = builds .iter() + .filter(|(source, ..)| source.upstream.is_none()) .map(|(source, ..)| source.platform.as_str()) .collect(); return Err(no_patched_build(trees, &missing, &patched)); @@ -2324,7 +3043,8 @@ async fn stage_platform_builds( let policy = ServicePolicy::Refused; let platforms: Vec<&str> = match &trees.from { BuildsFrom::Locked(platforms) => platforms.iter().map(String::as_str).collect(), - BuildsFrom::Recorded(builds) => builds.iter().map(|b| b.platform.as_str()).collect(), + BuildsFrom::Recorded(builds, _) => builds.iter().map(|b| b.platform.as_str()).collect(), + BuildsFrom::Listed(sources) => sources.iter().map(|s| s.platform.as_str()).collect(), }; // SECURITY: a platform names a directory under the stage, and the // ledger a restore reads them from is committed, tamper-able data. @@ -2338,19 +3058,30 @@ async fn stage_platform_builds( BuildsFrom::Locked(platforms) => { locked_build_sources(cfg, &record.uuid, name, trees, platforms).await? } - BuildsFrom::Recorded(builds) => { - recorded_build_sources(cfg, &record.uuid, name, trees, builds).await? - } + BuildsFrom::Recorded(builds, list) => recorded_build_sources(name, trees, builds, list)?, + BuildsFrom::Listed(sources) => sources.to_vec(), }; let builds = served_builds(cfg, name, trees, &sources).await?; + let version = gem_version(trees.gem); // The gems, a few platforms at a time and taken in lock order. let mut downloads = std::pin::pin!(futures_util::stream::iter(&builds) .map(|(source, subject, gem, stub)| async move { - let gem_bytes = build_artifact(cfg, gem, "patched platform gem", subject).await?; - source.pinned.check_gem(&gem_bytes, subject)?; - let stub_bytes = build_artifact(cfg, stub, "stub gemspec", subject).await?; + let what = gem_noun(source); + // Upstream's own gem comes from the patch registry and from + // nowhere it might point to. + let from_registry = source.upstream.is_some(); + let gem_bytes = build_artifact(cfg, gem, what, subject, from_registry).await?; + source.pinned.check_gem(&gem_bytes, what, subject)?; + let Some(stub) = stub else { + // Upstream's own gem: its gemspec is the one it carries, + // and no patch names files of it. + let leaf = format!("{name}-{version}-{}", source.platform); + let gemspec = upstream_gemspec(&gem_bytes, &leaf, subject)?; + return Ok((gem_bytes, gemspec, BTreeMap::new())); + }; + let stub_bytes = build_artifact(cfg, stub, "stub gemspec", subject, false).await?; source.pinned.check_stub(&stub_bytes, subject)?; let files = build_files(cfg, source, subject).await?; Ok::<_, Box>((gem_bytes, stub_bytes, files)) @@ -2366,10 +3097,13 @@ async fn stage_platform_builds( let (gem_bytes, stub_bytes, files) = downloaded?; let own: HashMap = files.clone().into_iter().collect(); let platform = source.platform.as_str(); - let stub_text = String::from_utf8_lossy(&stub_bytes); - refuse_unusable_stub(policy, name, subject, &stub_text)?; - if matches!(trees.from, BuildsFrom::Recorded(_)) { - refuse_foreign_stub(policy, trees.gem, platform, subject, &stub_text)?; + let what = gem_noun(source); + if stub.is_some() { + let stub_text = String::from_utf8_lossy(&stub_bytes); + refuse_unusable_stub(policy, name, subject, &stub_text)?; + if matches!(trees.from, BuildsFrom::Recorded(..)) { + refuse_foreign_stub(policy, trees.gem, platform, subject, &stub_text)?; + } } let tree = stage.join(platform); @@ -2382,7 +3116,7 @@ async fn stage_platform_builds( if let Err(e) = extract_on_blocking_pool(gem_bytes, &tree, extract_gem_data).await { return Err(policy.hard( "vendor_prebuilt_extract_failed", - format!("cannot extract the patched platform gem for {subject}: {e}"), + format!("cannot extract the {what} for {subject}: {e}"), )); } match empty_shipped_gitignores(&tree, &own).await { @@ -2390,14 +3124,14 @@ async fn stage_platform_builds( Err(e) => { return Err(policy.hard( "vendor_prebuilt_write_failed", - format!("cannot empty a `.gitignore` the patched platform gem for {subject} ships: {e}"), + format!("cannot empty a `.gitignore` the {what} for {subject} ships: {e}"), )); } } if let Err(e) = tokio::fs::write(tree.join(format!("{name}.gemspec")), &stub_bytes).await { return Err(policy.hard( "vendor_prebuilt_write_failed", - format!("cannot write the stub gemspec for {subject} into the vendored dir: {e}"), + format!("cannot write the gemspec for {subject} into the vendored dir: {e}"), )); } // The gem passed the digests stated for this platform above, which @@ -2417,24 +3151,51 @@ async fn stage_platform_builds( platform: platform.to_string(), uuid: source.uuid.clone(), gem_integrity: gem.integrity_sri.clone(), - gemspec_integrity: stub.integrity_sri.clone(), + gemspec_integrity: stub + .as_ref() + .map_or_else(String::new, |s| s.integrity_sri.clone()), files, }); } + // Where the copy came from: a patched build's gem, else (a copy of + // upstream's gems alone, after a withdrawal) the first gem of it. let source_url = builds - .first() + .iter() + .find(|(source, ..)| source.upstream.is_none()) + .or(builds.first()) .map(|(_, _, gem, _)| gem.url.as_str()) .unwrap_or_default(); - let mut warnings = vec![downloaded_warning( - format_args!("{name} as patched platform gems ({})", platforms.join(", ")), - source_url, - )]; + let of = |upstream: bool| -> Vec<&str> { + let kept = builds + .iter() + .filter(|(source, ..)| source.upstream.is_some() == upstream); + kept.map(|(source, ..)| source.platform.as_str()).collect() + }; + let (patched, upstream) = (of(false), of(true)); + let subject = match (patched.as_slice(), upstream.as_slice()) { + (_, []) => format!("{name} as patched platform gems ({})", platforms.join(", ")), + ([], upstream) => format!( + "{name} as upstream's own platform gems ({})", + upstream.join(", ") + ), + (patched, upstream) => format!( + "{name} as platform gems (patched: {}; upstream's own: {})", + patched.join(", "), + upstream.join(", ") + ), + }; + let mut warnings = vec![downloaded_warning(subject, source_url)]; if !emptied.is_empty() { + // Whose `.gitignore` it is: the gems of the copy, patched or not. + let gems = match upstream.is_empty() { + true => "the patched platform gems", + false => "the platform gems", + }; warnings.push(VendorWarning::new( GITIGNORE_NEUTRALIZED, format!( - "{name}: the patched platform gems ship their own `.gitignore` ({}), whose \ + "{name}: {gems} ship their own `.gitignore` ({}), whose \ rules would keep git from committing files of the vendored trees; emptied in \ the vendored copy (commit it)", super::npm_dir::summarize_rules(&emptied) @@ -2444,14 +3205,66 @@ async fn stage_platform_builds( Ok((warnings, built)) } +/// How messages name the gem of `source`. +fn gem_noun(source: &BuildSource) -> &'static str { + match source.upstream { + Some(_) => "upstream platform gem", + None => "patched platform gem", + } +} + +/// The gemspec of a tree of upstream's own gem: the one the gem carries +/// (`metadata.gz`, a gemspec as YAML, which Bundler reads from a +/// `.gemspec` file as it reads the Ruby form). It must be the gemspec of +/// the gem `leaf` (`--`) and declare no +/// extension: Bundler builds none for a path gem. +fn upstream_gemspec( + gem_bytes: &[u8], + leaf: &str, + subject: &str, +) -> Result, Box> { + use crate::patch::gem_refresh::{gem_metadata, parse_metadata}; + let policy = ServicePolicy::Refused; + let metadata = gem_metadata(gem_bytes); + let facts = metadata + .as_deref() + .and_then(|yaml| std::str::from_utf8(yaml).ok()) + .and_then(parse_metadata); + let (Some(metadata), Some(facts)) = (metadata, facts) else { + return Err(policy.hard( + "vendor_prebuilt_extract_failed", + format!("upstream's gem for {subject} carries no gemspec that can be read"), + )); + }; + if facts.full_name != leaf { + return Err(policy.hard( + "vendor_prebuilt_integrity_mismatch", + format!( + "upstream's gem for {subject} is {}, not {leaf}; refusing to vendor it", + facts.full_name + ), + )); + } + if facts.native { + return Err(policy.hard( + "native_extensions_unsupported", + format!( + "upstream's gem for {subject} builds a native extension; bundler does not \ + build extensions for path-sourced gems" + ), + )); + } + Ok(metadata) +} + impl BuildPin { /// Whether the downloaded platform gem is the one this tree is pinned /// to; a mismatch is never vendored. - fn check_gem(&self, gem: &[u8], subject: &str) -> Result<(), Box> { + fn check_gem(&self, gem: &[u8], what: &str, subject: &str) -> Result<(), Box> { let mismatch = |why: String| { ServicePolicy::Refused.hard( "vendor_prebuilt_integrity_mismatch", - format!("patched platform gem for {subject} {why}; refusing to vendor it"), + format!("{what} for {subject} {why}; refusing to vendor it"), ) }; let (Self::Registry(listed) | Self::Restored { sha256: listed, .. }) = self; @@ -2510,8 +3323,9 @@ const GITIGNORE_NEUTRALIZED: &str = "vendor_gem_gitignore_neutralized"; /// see the same bytes. /// /// A `.gitignore` the patch itself rewrites is left as the patch has it -/// (its hash is the record's); what it ignores is then for -/// [`keep_platform_trees_committable`] to refuse. Returns the paths +/// (its hash is the record's), with what it ignores: git is asked about +/// the copy before its trees are in place, where it reads no such file. +/// Returns the paths /// emptied, relative to `tree`. async fn empty_shipped_gitignores( tree: &Path, @@ -2564,9 +3378,14 @@ async fn build_artifact( artifact: &crate::api::client::SecondaryArtifact, what: &str, subject: &str, + from_registry: bool, ) -> Result, Box> { let policy = ServicePolicy::Refused; - match fetch_verified_artifact(cfg, Some(artifact)).await { + let fetched = match from_registry { + true => super::service_fetch::fetch_verified_registry_gem(cfg, artifact).await, + false => fetch_verified_artifact(cfg, Some(artifact)).await, + }; + match fetched { SecondaryArtifactResult::Ready(bytes) => Ok(bytes), SecondaryArtifactResult::Absent => { Err(policy.miss(format!("the patch service served no {what} for {subject}"))) @@ -2588,15 +3407,19 @@ async fn build_artifact( /// is the verified patched gem of each platform of `trees`, each from its /// own patch, staged in full and then swapped into place, so a failure /// leaves any pre-existing (possibly live-wired) copy untouched and no -/// husk behind. The uuid dir's git metadata is the caller's to write -/// ([`restore_uuid_metadata`]): `copy_dir` may itself sit in a stage -/// (`repair`'s restore). Returns what the ledger records of each tree. +/// husk behind. `place` is the project and the copy's path in it, where +/// `copy_dir` is that place: the copy is then finished between the stage +/// and the swap ([`CopyStep::Placing`]), so one git would not commit is +/// refused with nothing moved. Without it `copy_dir` itself sits in a +/// stage (`repair`'s restore), and the copy is the caller's to finish +/// before it moves that in. Returns what the ledger records of each tree. #[allow(clippy::too_many_arguments)] pub(super) async fn gem_platform_service_copy( service: Option<&VendorServiceConfig>, record: &PatchRecord, name: &str, trees: &PlatformTrees<'_>, + place: Option<(&Path, &str)>, copy_dir: &Path, uuid_dir: &Path, unwind_uuid_dir: bool, @@ -2614,8 +3437,24 @@ pub(super) async fn gem_platform_service_copy( return Err(outcome); } }; - if let Err(e) = swap_stage_into_place(&stage, copy_dir).await { + // Nothing was moved in: neither the stage nor a uuid dir that would + // hold its git metadata alone is left behind. + let abandon = || async { cleanup_failed_stage(&stage, uuid_dir, unwind_uuid_dir).await; + if place.is_some() && !unwind_uuid_dir { + remove_metadata_alone(uuid_dir).await; + } + }; + if let Some((project_root, copy_rel)) = place { + let placing = CopyStep::Placing(&stage); + let finished = finish_platform_copy(project_root, copy_rel, placing, false, warnings); + if let Err(refusal) = finished.await { + abandon().await; + return Err(Box::new(refusal)); + } + } + if let Err(e) = swap_stage_into_place(&stage, copy_dir).await { + abandon().await; return Err(ServicePolicy::Refused.hard( "vendor_prebuilt_write_failed", format!("cannot move the extracted platform gems into place: {e}"), @@ -2643,45 +3482,6 @@ pub(crate) async fn restore_uuid_metadata(uuid_dir: &Path) -> std::io::Result>, - warnings: &mut Vec, -) -> Result<(), VendorOutcome> { - let Some(inventory) = inventory else { - return Ok(()); - }; - let mut paths: Vec = inventory - .keys() - .map(|file| format!("{copy_rel}/{file}")) - .collect(); - if let Some((uuid_dir_rel, _)) = copy_rel.rsplit_once('/') { - paths.push(format!("{uuid_dir_rel}/.gitignore")); - paths.push(format!("{uuid_dir_rel}/.gitattributes")); - } - match super::npm_dir::gitignore_probe(project_root, &paths).await { - Ok(Some(rules)) => Err(refused( - super::npm_dir::GITIGNORED, - super::npm_dir::gitignored_detail(copy_rel, &rules), - )), - Ok(None) => Ok(()), - Err(why) => { - warnings.push(VendorWarning::new( - super::npm_dir::GITIGNORE_UNCHECKED, - super::npm_dir::gitignore_unchecked_detail(copy_rel, &why), - )); - Ok(()) - } - } -} - /// A dry run's check of a gem the lock pins as platform gems: the whole /// download, verification and unpacking of [`gem_platform_service_copy`], /// into a scratch directory. Returns what the wet run's ledger entry @@ -2691,6 +3491,7 @@ async fn preview_platform_builds( record: &PatchRecord, name: &str, trees: &PlatformTrees<'_>, + (project_root, copy_rel): (&Path, &str), ) -> Result, Box> { if let Some(outcome) = service_offline_conflict(service) { return Err(Box::new(outcome)); @@ -2700,9 +3501,14 @@ async fn preview_platform_builds( .ok_or_else(|| Box::new(super::service_fetch::required()))?; let scratch = tempfile::tempdir() .map_err(|e| Box::new(refused("vendor_prebuilt_extract_failed", e.to_string())))?; - stage_platform_builds(cfg, record, name, trees, scratch.path()) + let (_, built) = stage_platform_builds(cfg, record, name, trees, scratch.path()).await?; + // What the wet run asks before it moves the trees in, with nothing + // written: the dry run says what that run does. + let placing = CopyStep::Placing(scratch.path()); + finish_platform_copy(project_root, copy_rel, placing, true, &mut Vec::new()) .await - .map(|(_, built)| built) + .map_err(Box::new)?; + Ok(built) } /// What a run would do with a gem `Gemfile.lock` names as precompiled @@ -2710,10 +3516,11 @@ async fn preview_platform_builds( /// ([`preview_locked_builds`]). #[derive(Debug)] pub enum LockedBuildsPreview { - /// Every locked platform has a patched build, and the service serves - /// the patch of each: the tree of each, in lock order, with the patch - /// it is vendored from. Nothing was downloaded, so the entries carry - /// no digest. + /// The registry lists a gem for every locked platform and a patched + /// build for at least one, and the service serves the patch of each + /// patched build: the tree of each platform, in lock order, with the + /// patch it is vendored from (none for a tree of upstream's own gem). + /// Nothing was downloaded, so the entries carry no digest. Vendor(Vec), /// What the backend refuses the gem with before it downloads /// anything: the skip of a gem with a locked platform that has no @@ -2739,11 +3546,18 @@ pub enum LockedBuildsPreview { /// the skip of a locked platform with no patched build says that the gem /// stays hosted, as the wet run's does ([`vendor_gem_previewing`]). /// +/// A lock already wired to this patch's copy is judged by the list +/// alone: where it names another build for a locked platform than the +/// tree the ledger records (a patched build published since, upstream's +/// gem where the patched build was withdrawn), and serves each patched +/// build it names, the wet run vendors the copy again with those +/// ([`moved_sources`]). +/// /// `None` for a gem this does not judge, so the caller's own verdict /// stands: one the lock does not name as platform gems, one whose lock is -/// already wired to this patch's copy (only the copy tells what a run -/// does with it), one a hub of a Bazel workspace takes, and a lock the -/// edit fails on. +/// already wired to this patch's copy and holds what the list names (only +/// the copy tells what a run does with it), one a hub of a Bazel +/// workspace takes, and a lock the edit fails on. pub async fn preview_locked_builds( project_root: &Path, purl: &str, @@ -2763,12 +3577,46 @@ pub async fn preview_locked_builds( Ok(prelude) => prelude, Err(outcome) => return refusal(outcome), }; - if prelude.platforms.is_empty() - || prelude.lock_wired - || bazel::takes(&prelude, project_root, uuid).await - { + if prelude.platforms.is_empty() || bazel::takes(&prelude, project_root, uuid).await { return None; } + let builds_of = |sources: Vec| { + let build = |source: BuildSource| GemBuildEntry { + platform: source.platform, + uuid: source.uuid, + gem_integrity: String::new(), + gemspec_integrity: String::new(), + files: BTreeMap::new(), + }; + LockedBuildsPreview::Vendor(sources.into_iter().map(build).collect()) + }; + if prelude.lock_wired { + let label = format!("{}@{}", prelude.name, prelude.version); + let trees = PlatformTrees { + gem: &label, + from: BuildsFrom::Locked(&prelude.platforms), + standing: Standing::Wired, + held: Vec::new(), + }; + let (name, copy_rel) = (prelude.name.as_str(), prelude.copy_rel.as_str()); + let moved = moved_sources(project_root, service, uuid, name, copy_rel, &trees, None); + let sources = moved.await?; + let cfg = service.filter(|cfg| cfg.service_enabled())?; + // A patched build the list names that is not served yet is the + // wet run's skip, with the copy left in force + // ([`wired_copy_failed`]): the caller says so of an intact copy. + return match served_builds(cfg, name, &trees, &sources).await { + Ok(_) => Some(builds_of(sources)), + Err(outcome) => match *outcome { + VendorOutcome::Refused { code, detail } + if code == super::VENDOR_PREBUILT_PLATFORM_PENDING => + { + Some(LockedBuildsPreview::Refused { code, detail }) + } + _ => None, + }, + }; + } let standing = match hosted { true => Standing::Hosted, false => match gem_edits(purl, &prelude) { @@ -2783,10 +3631,17 @@ pub async fn preview_locked_builds( return refusal(super::service_fetch::required()); }; let label = format!("{}@{}", prelude.name, prelude.version); + let held = match standing { + Standing::EarlierPatch => { + held_patched_platforms(project_root, &prelude.name, &prelude.version, uuid).await + } + _ => Vec::new(), + }; let trees = PlatformTrees { gem: &label, from: BuildsFrom::Locked(&prelude.platforms), standing, + held, }; let named = locked_build_sources(cfg, uuid, &prelude.name, &trees, &prelude.platforms).await; let sources = match named { @@ -2797,28 +3652,19 @@ pub async fn preview_locked_builds( if let Err(outcome) = served_builds(cfg, &prelude.name, &trees, &sources).await { return refusal(*outcome); } - Some(LockedBuildsPreview::Vendor( - sources - .into_iter() - .map(|source| GemBuildEntry { - platform: source.platform, - uuid: source.uuid, - gem_integrity: String::new(), - gemspec_integrity: String::new(), - files: BTreeMap::new(), - }) - .collect(), - )) + Some(builds_of(sources)) } /// Acquire a verified service copy without replacing the prior copy on /// failure: the gem's own tree, or one patched platform gem's tree per -/// platform of `trees` when the lock pins the gem as platform gems (with -/// the uuid dir's git metadata, see [`restore_uuid_metadata`]). Returns -/// what the ledger records of each such tree, with the result. +/// platform of `trees` when the lock pins the gem as platform gems. +/// Those trees are finished before they are moved into `place`, the +/// project and the copy's path in it ([`gem_platform_service_copy`]). +/// Returns what the ledger records of each such tree, with the result. #[allow(clippy::too_many_arguments)] async fn materialise_patched_copy( purl: &str, + place: (&Path, &str), copy_dir: &Path, uuid_dir: &Path, name: &str, @@ -2848,25 +3694,13 @@ async fn materialise_patched_copy( record, name, trees, + Some(place), copy_dir, uuid_dir, unwind_uuid_dir, warnings, ) .await?; - if let Err(e) = restore_uuid_metadata(uuid_dir).await { - if unwind_uuid_dir { - let _ = remove_tree(uuid_dir).await; - prune_empty_vendor_levels(uuid_dir).await; - } - return Err(ServicePolicy::Refused.hard( - "vendor_prebuilt_write_failed", - format!( - "cannot write the git metadata of {}: {e}", - uuid_dir.display() - ), - )); - } } } Ok(( @@ -8535,6 +9369,16 @@ mod tests { /// `metadata.gz`). `data_files` are the inner data.tar.gz entries at the /// root (no prefix dir), as a real `.gem` carries them. pub(super) fn make_gem(data_files: &[(&str, &[u8])]) -> Vec { + // A token metadata.gz: the CLI service path never reads it (it uses the + // served stub), but a real `.gem` always carries one. + make_gem_with_metadata( + b"--- !ruby/object:Gem::Specification\nname: rack\n", + data_files, + ) + } + + /// [`make_gem`] with the gemspec `metadata` (YAML) the gem carries. + pub(super) fn make_gem_with_metadata(metadata: &[u8], data_files: &[(&str, &[u8])]) -> Vec { use std::io::Write as _; let mut data_tar = tar::Builder::new(Vec::new()); for (rel, content) in data_files { @@ -8548,11 +9392,8 @@ mod tests { let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); enc.write_all(&data_tar).unwrap(); let data_gz = enc.finish().unwrap(); - // A token metadata.gz: the CLI service path never reads it (it uses the - // served stub), but a real `.gem` always carries one. let mut menc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); - menc.write_all(b"--- !ruby/object:Gem::Specification\nname: rack\n") - .unwrap(); + menc.write_all(metadata).unwrap(); let metadata_gz = menc.finish().unwrap(); let mut outer = tar::Builder::new(Vec::new()); for (name, bytes) in [ @@ -12807,6 +13648,53 @@ mod tests { } } + /// The gemspec upstream's gem for `platform` carries, as YAML. + fn upstream_gemspec_yaml(platform: &str) -> String { + format!( + "--- !ruby/object:Gem::Specification\nname: nokogiri\nversion: \ + !ruby/object:Gem::Version\n version: 1.18.10\nplatform: {platform}\nauthors:\n- \ + Nokogiri\nextensions: []\nsummary: upstream\n" + ) + } + + /// Upstream's own gem for `platform`, which has no patched build: + /// the registry lists it as it is (`patchUuid: null`) and serves + /// its file. + fn upstream(platform: &'static str) -> Served { + Served { + platform, + listed: Listed::PassThrough, + own: Own::Granted, + gem: Some(make_gem_with_metadata( + upstream_gemspec_yaml(platform).as_bytes(), + &[(RB, RB_PRISTINE), (SO, b"upstream's binary")], + )), + stub: None, + gem_sha512: None, + listed_sha256: None, + files: BTreeMap::new(), + } + } + + /// What the ledger records of `platform`'s tree of [`upstream`]'s + /// gem. + fn kept(platform: &'static str) -> GemBuildEntry { + use base64::Engine as _; + use sha2::Digest as _; + let gem = upstream(platform).gem.unwrap_or_default(); + let digest = sha2::Sha256::digest(&gem); + GemBuildEntry { + platform: platform.to_string(), + uuid: String::new(), + gem_integrity: format!( + "sha256-{}", + base64::engine::general_purpose::STANDARD.encode(digest) + ), + gemspec_integrity: String::new(), + files: BTreeMap::new(), + } + } + /// The patch of `platform`'s patched build of the fix `uuid`. fn build_uuid(uuid: &str, platform: &str) -> String { let tag = &crate::utils::digest::sha256_hex_of(platform.as_bytes())[..8]; @@ -12858,6 +13746,13 @@ mod tests { "platform": platform, "gemChecksumSha256": listed_sha256, "patchUuid": null })); + // The registry serves the file of a gem it lists. + if let Some(gem) = build.gem.as_deref().filter(|_| list) { + let route = format!( + "/patch-registry/gem/tok/{uuid}/s/4/gems/nokogiri-1.18.10-{platform}.gem" + ); + artifact("gem", route, gem, None); + } continue; } Listed::Patched => gem_builds.push(serde_json::json!({ @@ -13122,151 +14017,1414 @@ mod tests { } assert!(!root.join(&rel).join("nokogiri.gemspec").exists()); - // The pair edit. - assert_eq!( - text(root.join(GEMFILE)).await, - GEMFILE_NOKO.replace( - "gem \"nokogiri\", \"~> 1.18\"", - &format!("gem \"nokogiri\", \"1.18.10\", path: \"{rel}\"") - ) - ); - let bare = before.map(|_| checksums("", "")); - assert_eq!( - text(root.join(GEMFILE_LOCK)).await, - vendored(&rel, bare.as_deref()) - ); + // The pair edit. + assert_eq!( + text(root.join(GEMFILE)).await, + GEMFILE_NOKO.replace( + "gem \"nokogiri\", \"~> 1.18\"", + &format!("gem \"nokogiri\", \"1.18.10\", path: \"{rel}\"") + ) + ); + let bare = before.map(|_| checksums("", "")); + assert_eq!( + text(root.join(GEMFILE_LOCK)).await, + vendored(&rel, bare.as_deref()) + ); + + // The requests: the gem patch's reference says which + // patch each locked platform's build is, the platform + // patches' references come in ONE request, and only the + // platform gems and their stubs are downloaded. + assert_eq!( + reference_requests(&server).await, + [ + vec![UUID.to_string()], + vec![build_uuid(UUID, DARWIN), build_uuid(UUID, LINUX)], + ] + ); + let mut fetched = downloads(&server).await; + fetched.sort(); + let file = |platform: &str, ext: &str| { + let own = build_uuid(UUID, platform); + format!( + "/patch/gem/nokogiri/1.18.10/tok/{own}/nokogiri-1.18.10-{platform}.{ext}" + ) + }; + let mut expected = vec![ + file(DARWIN, "gem"), + file(DARWIN, "gemspec"), + file(LINUX, "gem"), + file(LINUX, "gemspec"), + ]; + expected.sort(); + assert_eq!(fetched, expected); + + // The ledger entry: each tree's platform, patch and digests, + // in lock order. + assert_eq!(entry.gem_builds, [built(UUID, DARWIN), built(UUID, LINUX)]); + assert_eq!(entry.uuid, UUID); + assert_eq!(entry.artifact.path, rel); + let inventory = entry.artifact.file_inventory.as_ref().expect("inventory"); + let inventoried: Vec<&str> = inventory.keys().map(String::as_str).collect(); + assert_eq!( + inventoried, + [ + "arm64-darwin/lib/nokogiri/nokogiri.so", + "arm64-darwin/lib/nokogiri/version.rb", + "arm64-darwin/nokogiri.gemspec", + "x86_64-linux-gnu/lib/nokogiri/nokogiri.so", + "x86_64-linux-gnu/lib/nokogiri/version.rb", + "x86_64-linux-gnu/nokogiri.gemspec", + ] + ); + let checksum_record = entry + .wiring + .iter() + .find(|w| w.kind == LOCK_CHECKSUM_WIRING_KIND); + match before { + None => assert!(checksum_record.is_none(), "{checksum_record:?}"), + Some(_) => { + let rec = checksum_record.expect("a checksum record"); + assert_eq!( + rec.original, + Some(serde_json::json!([ + format!(" nokogiri (1.18.10-arm64-darwin){}", sha('a')), + format!(" nokogiri (1.18.10-x86_64-linux-gnu){}", sha('b')), + ])) + ); + assert_eq!( + rec.new, + Some(serde_json::json!([ + " nokogiri (1.18.10-arm64-darwin)", + " nokogiri (1.18.10-x86_64-linux-gnu)", + ])) + ); + } + } + assert!( + warnings + .iter() + .any(|w| w.code == "vendor_prebuilt_downloaded" + && w.detail.contains(DARWIN) + && w.detail.contains(LINUX)), + "{warnings:?}" + ); + + // The ledger round trip through state.json. + ts::persist(&root, NOKO, entry.clone()).await; + let saved = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); + assert_eq!(saved, entry); + let ledger = text(root.join(".socket/vendor/state.json")).await; + assert!(ledger.contains("\"gemBuilds\""), "{ledger}"); + assert!(ledger.contains("\"gemIntegrity\""), "{ledger}"); + assert!(ledger.contains("\"gemspecIntegrity\""), "{ledger}"); + + // Verification and discovery: one vendored reference. + assert_eq!( + check_vendored_artifact(&root, &saved, &record).await, + ArtifactHealth::Healthy + ); + let found = crate::vex::discover::discover_patched_refs(&root).await; + let refs: Vec<_> = found + .refs + .iter() + .map(|r| (r.purl.as_str(), r.uuid.as_str(), r.artifact_rel.as_deref())) + .collect(); + assert_eq!( + refs, + [("pkg:gem/nokogiri@1.18.10", UUID, Some(rel.as_str()))] + ); + assert!(found.diagnostics.is_empty(), "{:?}", found.diagnostics); + + // A second run changes nothing. It asks the service one + // thing, the list of the gem's fix, which names the builds + // the copy holds. + let requests = ts::request_count(&server).await; + let snapshot = ts::tree_snapshot(&root); + let (again, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success, "{:?}", again.error); + assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); + assert_eq!(ts::tree_snapshot(&root), snapshot); + assert_eq!(ts::request_count(&server).await, requests + 1); + + // Revert: both files byte for byte, the trees gone. + let reverted = revert_gem(&saved, &root, false).await; + assert!(reverted.success, "{:?}", reverted.error); + assert!(reverted.warnings.is_empty(), "{:?}", reverted.warnings); + assert_eq!(text(root.join(GEMFILE)).await, GEMFILE_NOKO); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, lock_before); + assert!(!root.join(".socket/vendor/gem").exists()); + } + } + + /// A lock whose platforms are not all patched is vendored when the + /// fix's list names a patched build for at least one of them. The + /// patched platform gets the tree of its patched build, the other + /// the gem the patch registry lists for it: upstream's own, + /// unchanged, with the gemspec that gem carries. That gem comes + /// from the patch server and is checked against the sha256 of the + /// list. The ledger records the tree with no patch, the copy + /// verifies and a change to the tree is found, a second run asks + /// for the fix's list alone, and revert restores both files byte + /// for byte. + #[tokio::test] + async fn a_platform_without_a_patched_build_is_vendored_as_upstreams_gem() { + let lock_before = lock(None); + let (_tmp, root, record) = project(&lock_before).await; + let (server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.expect("a ledger entry"); + + let rel = rel(UUID); + let read = |platform: &str, file: &str| { + std::fs::read(root.join(&rel).join(platform).join(file)).unwrap() + }; + assert_eq!(read(DARWIN, RB), stamped(DARWIN)); + assert_eq!(read(DARWIN, "nokogiri.gemspec"), stub(DARWIN)); + assert_eq!(read(LINUX, RB), RB_PRISTINE, "upstream's file, unchanged"); + assert_eq!(read(LINUX, SO), b"upstream's binary"); + assert_eq!( + read(LINUX, "nokogiri.gemspec"), + upstream_gemspec_yaml(LINUX).as_bytes(), + "the gemspec upstream's gem carries, as it is" + ); + // Both platforms are in the one PATH section, as when both are + // patched. + assert_eq!(text(root.join(GEMFILE_LOCK)).await, vendored(&rel, None)); + + // The requests: the fix's list, the reference of the one + // patched build, that build's gem and stub, and upstream's gem + // from the fix's registry on the patch server. + assert_eq!( + reference_requests(&server).await, + [vec![UUID.to_string()], vec![build_uuid(UUID, DARWIN)]] + ); + let own = build_uuid(UUID, DARWIN); + let mut fetched = downloads(&server).await; + fetched.sort(); + let mut expected = vec![ + format!("/patch/gem/nokogiri/1.18.10/tok/{own}/nokogiri-1.18.10-{DARWIN}.gem"), + format!("/patch/gem/nokogiri/1.18.10/tok/{own}/nokogiri-1.18.10-{DARWIN}.gemspec"), + format!("/patch-registry/gem/tok/{UUID}/s/4/gems/nokogiri-1.18.10-{LINUX}.gem"), + ]; + expected.sort(); + assert_eq!(fetched, expected); + let downloaded: Vec<&str> = warnings + .iter() + .filter(|w| w.code == "vendor_prebuilt_downloaded") + .map(|w| w.detail.as_str()) + .collect(); + assert!( + matches!(downloaded.as_slice(), [said] if said.contains( + "nokogiri as platform gems (patched: arm64-darwin; upstream's own: \ + x86_64-linux-gnu)" + )), + "{warnings:?}" + ); + + // The ledger: the tree of upstream's gem names no patch, no + // gemspec digest and no files, only the gem it is. + assert_eq!(entry.gem_builds, [built(UUID, DARWIN), kept(LINUX)]); + ts::persist(&root, NOKO, entry.clone()).await; + let saved = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); + assert_eq!(saved, entry); + let ledger: Value = + serde_json::from_str(&text(root.join(".socket/vendor/state.json")).await).unwrap(); + assert_eq!( + ledger["entries"][NOKO]["gemBuilds"][1], + serde_json::json!({ + "platform": LINUX, + "gemIntegrity": kept(LINUX).gem_integrity, + }) + ); + assert!(saved.gem_builds[1].is_upstream() && !saved.gem_builds[0].is_upstream()); + assert!(saved.gem_tree_files(LINUX, &record.files).is_empty()); + + // The copy verifies, and its inventory vouches for every file + // of the tree no patch names a file of. + assert_eq!( + check_vendored_artifact(&root, &saved, &record).await, + ArtifactHealth::Healthy + ); + let binary = root.join(&rel).join(LINUX).join(SO); + tokio::fs::write(&binary, b"another binary").await.unwrap(); + assert!(matches!( + check_vendored_artifact(&root, &saved, &record).await, + ArtifactHealth::Corrupt { .. } + )); + tokio::fs::write(&binary, b"upstream's binary") + .await + .unwrap(); + + // A second run changes nothing: one request, the fix's list. + let requests = ts::request_count(&server).await; + let snapshot = ts::tree_snapshot(&root); + let (again, rerun_entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success, "{:?}", again.error); + assert!(rerun_entry.is_none() && warnings.is_empty(), "{warnings:?}"); + assert_eq!(ts::tree_snapshot(&root), snapshot); + assert_eq!(ts::request_count(&server).await, requests + 1); + + let reverted = revert_gem(&saved, &root, false).await; + assert!(reverted.success, "{:?}", reverted.error); + assert!(reverted.warnings.is_empty(), "{:?}", reverted.warnings); + assert_eq!(text(root.join(GEMFILE)).await, GEMFILE_NOKO); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, lock_before); + assert!(!root.join(".socket/vendor/gem").exists()); + } + + /// The copy follows the fix's list. A locked platform that gains a + /// patched build gets that build's tree in place of upstream's + /// gem; one whose patched build is withdrawn goes back to + /// upstream's gem, the last one included. The Gemfile and the lock + /// are not touched, and the copy verifies after each step. + #[tokio::test] + async fn a_vendored_copy_follows_a_gained_and_a_withdrawn_build() { + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + let lock_wired = text(root.join(GEMFILE_LOCK)).await; + let gemfile_wired = text(root.join(GEMFILE)).await; + let rel = rel(UUID); + let linux_rb = root.join(&rel).join(LINUX).join(RB); + let darwin_rb = root.join(&rel).join(DARWIN).join(RB); + + let steps: [(Vec, Vec); 3] = [ + // The linux build is published. + ( + vec![served(DARWIN), served(LINUX)], + vec![built(UUID, DARWIN), built(UUID, LINUX)], + ), + // The darwin build is withdrawn. + ( + vec![upstream(DARWIN), served(LINUX)], + vec![kept(DARWIN), built(UUID, LINUX)], + ), + // And the linux one: the copy holds upstream's gems alone. + ( + vec![upstream(DARWIN), upstream(LINUX)], + vec![kept(DARWIN), kept(LINUX)], + ), + ]; + for (list, expected) in steps { + let (server, cfg) = service(UUID, &list).await; + // A dry run says the same and writes nothing. + let snapshot = ts::tree_snapshot(&root); + let mut previewed = Vec::new(); + let preview = vendor_gem_previewing( + NOKO, + not_installed(&root).as_path(), + &root, + &record, + &PatchSources::blobs_only(&root.join("no-blobs")), + "2026-06-09T00:00:00Z", + true, + false, + Some(&cfg), + false, + None, + &mut previewed, + ) + .await; + let (preview, ..) = unwrap_done(preview); + assert!(preview.success, "{:?}", preview.error); + let named = |builds: &[GemBuildEntry]| -> Vec<(String, String)> { + let pair = |b: &GemBuildEntry| (b.platform.clone(), b.uuid.clone()); + builds.iter().map(pair).collect() + }; + assert_eq!(named(&previewed), named(&expected)); + assert_eq!( + ts::tree_snapshot(&root), + snapshot, + "a dry run writes nothing" + ); + + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.expect("the copy's new ledger entry"); + assert_eq!(entry.gem_builds, expected); + assert!( + warnings.iter().any(|w| w.code == GEM_LIST_FOLLOWED + && w.detail.contains("lists other builds for nokogiri@1.18.10")), + "{warnings:?}" + ); + // The download advisory names the gems as they are: the + // patched ones, upstream's, or both, and where they came + // from. + let all_upstream = expected.iter().all(GemBuildEntry::is_upstream); + let downloaded: Vec<&str> = warnings + .iter() + .filter(|w| w.code == "vendor_prebuilt_downloaded") + .map(|w| w.detail.as_str()) + .collect(); + let [downloaded] = downloaded.as_slice() else { + panic!("one download advisory: {warnings:?}"); + }; + assert!( + !downloaded.contains("patched: ;") && downloaded.contains(" (http"), + "{downloaded}" + ); + assert_eq!( + downloaded.contains( + "vendored nokogiri as upstream's own platform gems (arm64-darwin, \ + x86_64-linux-gnu) from the patch service (http" + ), + all_upstream, + "{downloaded}" + ); + ts::persist(&root, NOKO, entry).await; + let saved = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); + assert_eq!( + check_vendored_artifact(&root, &saved, &record).await, + ArtifactHealth::Healthy + ); + for (path, platform) in [(&darwin_rb, DARWIN), (&linux_rb, LINUX)] { + let patched = !saved + .gem_builds + .iter() + .any(|b| b.platform == platform && b.is_upstream()); + let expected = if patched { + stamped(platform) + } else { + RB_PRISTINE.to_vec() + }; + assert_eq!(tokio::fs::read(path).await.unwrap(), expected, "{platform}"); + } + assert_eq!(text(root.join(GEMFILE_LOCK)).await, lock_wired); + assert_eq!(text(root.join(GEMFILE)).await, gemfile_wired); + + // In step with the list again: the fix's list, nothing else. + let requests = ts::request_count(&server).await; + let (again, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success, "{:?}", again.error); + assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); + assert_eq!(ts::request_count(&server).await, requests + 1); + } + } + + /// An intact copy is never made worse, and a run never fails over + /// something it could have left alone. When the list names another + /// build for a locked platform and that build cannot be vendored + /// (its gem fails the digest, its stub is not served, upstream's + /// gem does not unpack), nothing of the copy is touched: the run + /// ends as it does for a copy in step, with the one line that says + /// the copy stays in force. A build the list names that is not + /// served yet keeps its skip. A dry run says the same. An entry + /// that names no build of its trees says nothing of the list: no + /// request is made for it. + #[tokio::test] + async fn an_intact_copy_stays_in_force_when_the_list_cannot_be_followed() { + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + let before = ts::tree_snapshot(&root); + let another = make_gem(&[(RB, &stamped(LINUX)), (SO, &b"another"[..])]); + let failing: [(Vec, &str); 3] = [ + ( + vec![ + served(DARWIN), + Served { + gem_sha512: Some(sri_sha512(&another)), + ..served(LINUX) + }, + ], + "failed integrity verification", + ), + ( + vec![ + served(DARWIN), + Served { + stub: None, + ..served(LINUX) + }, + ], + "stub gemspec", + ), + ( + vec![ + Served { + gem: Some(b"not a gem".to_vec()), + ..upstream(DARWIN) + }, + upstream(LINUX), + ], + "arm64-darwin", + ), + ]; + // The git metadata of the uuid dir is no part of the copy: a + // run that leaves the copy in force puts back one that is gone, + // as a run that finds the copy in step does (a dry run writes + // nothing). + let metadata = format!(".socket/vendor/gem/{UUID}/.gitattributes"); + for (list, why) in failing { + let (_server, cfg) = service(UUID, &list).await; + for dry_run in [true, false] { + tokio::fs::remove_file(root.join(&metadata)).await.unwrap(); + let mut before = before.clone(); + if dry_run { + before.remove(&metadata).expect("the metadata file"); + } + let (result, rerun_entry, warnings) = unwrap_done( + vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, + ); + assert!(result.success, "{why}: {:?}", result.error); + assert!(rerun_entry.is_none(), "{why}: the ledger entry stands"); + let [said] = warnings.as_slice() else { + panic!("{why}: one line: {warnings:?}"); + }; + assert_eq!(said.code, GEM_LIST_NOT_FOLLOWED, "{why}"); + assert!( + said.detail.starts_with( + "nokogiri@1.18.10 could not be brought in step with the builds the \ + patch registry lists (" + ) && said + .detail + .ends_with("); its vendored copy stays in force as it is.") + && said.detail.contains(why), + "{why}: {}", + said.detail + ); + assert_eq!(ts::tree_snapshot(&root), before, "{why}: byte for byte"); + let gitattributes = crate::vendor::npm_dir::UUID_GITATTRIBUTES; + tokio::fs::write(root.join(&metadata), gitattributes) + .await + .unwrap(); + } + } + + // A build the list names that is not served yet: the skip. + let (_server, cfg) = + service(UUID, &[served(DARWIN), unserved(LINUX, "pending_build")]).await; + let (code, detail) = + unwrap_refused(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert_eq!(code, crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING); + assert!( + detail.ends_with("; its vendored copy stays in force as it is."), + "{detail}" + ); + assert_eq!(ts::tree_snapshot(&root), before); + // A scan's preview says the same skip, not a copy in step. + match preview_locked_builds(&root, NOKO, UUID, false, Some(&cfg)).await { + Some(LockedBuildsPreview::Refused { code, detail: said }) => { + assert_eq!(code, crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING); + assert!(detail.starts_with(&said), "{said} / {detail}"); + } + previewed => panic!("{previewed:?}"), + } + assert_eq!(ts::tree_snapshot(&root), before); + + // An entry that names no build of its trees (a development + // build's ledger), over trees that hold the files of the gem's + // own patch, which is what such an entry is checked against. + let plain = |platform: &'static str| Served { + gem: Some(make_gem(&[(RB, RB_PATCHED), (SO, platform.as_bytes())])), + files: BTreeMap::from([( + RB.to_string(), + PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(RB_PRISTINE), + after_hash: compute_git_sha256_from_bytes(RB_PATCHED), + }, + )]), + ..served(platform) + }; + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[plain(DARWIN), plain(LINUX)]).await; + let mut no_builds = vendor_and_persist(&root, &record, &cfg).await; + no_builds.gem_builds.clear(); + ts::persist(&root, NOKO, no_builds).await; + let ledgered = ts::tree_snapshot(&root); + let (server, cfg) = service(UUID, &[plain(DARWIN), upstream(LINUX)]).await; + let (result, rerun_entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert!(rerun_entry.is_none() && warnings.is_empty(), "{warnings:?}"); + assert_eq!(ts::request_count(&server).await, 0); + assert_eq!(ts::tree_snapshot(&root), ledgered); + } + + /// The git metadata of the uuid dir is not part of the copy. Every + /// path that puts the trees in place, or says they stay in force, + /// finishes the copy the same way: a write of it that fails is a + /// warning, never a failure, that names the two files and says to + /// make them writable. The trees are in place and correct, and the + /// entry handed back records them. A skip, which carries no + /// advisory, ends its line with it. + #[tokio::test] + async fn metadata_that_cannot_be_written_is_a_warning_on_every_path() { + let (_tmp, root, record) = project(&lock(None)).await; + // A directory where the file belongs: every write of it fails. + let uuid_rel = format!(".socket/vendor/gem/{UUID}"); + let gitattributes = root.join(&uuid_rel).join(".gitattributes"); + tokio::fs::create_dir_all(gitattributes.join("in the way")) + .await + .unwrap(); + let linux = root.join(rel(UUID)).join(LINUX); + let said = format!( + "could not write `{uuid_rel}/.gitignore` and `{uuid_rel}/.gitattributes` (" + ); + let remedy = "make those two files writable and run this again"; + let warned = |warnings: &[VendorWarning]| -> bool { + let of_it: Vec<&VendorWarning> = warnings + .iter() + .filter(|w| w.code == GEM_GIT_METADATA_UNWRITTEN) + .collect(); + let gitignore = warnings.iter().filter(|w| w.code.contains("gitignore")); + matches!(of_it.as_slice(), [w] if w.detail.starts_with(&said) + && w.detail.ends_with(remedy)) + && gitignore.count() == 0 + }; + + // A first vendor: vendored, wired and recorded, with the warning. + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert!(warned(&warnings), "{warnings:?}"); + let entry = entry.expect("the first vendor's entry"); + assert_eq!(entry.gem_builds, [built(UUID, DARWIN), kept(LINUX)]); + assert!(text(root.join(GEMFILE_LOCK)).await.contains("PATH\n")); + ts::persist(&root, NOKO, entry).await; + + // The copy in step: left as it is, with the warning alone. + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success && entry.is_none(), "{:?}", result.error); + assert!(warned(&warnings) && warnings.len() == 1, "{warnings:?}"); + + // A skip while the copy stays in force ends its line with it. + let prelude = gem_prelude(NOKO, ¬_installed(&root), &root, &record) + .await + .unwrap_or_else(|_| panic!("the prelude of a wired gem")); + let pending = refused( + crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING, + "nokogiri@1.18.10 was not brought up to date: no patched build yet for java" + .to_string(), + ); + let settled = wired_copy_failed(pending, false, &root, &record, &prelude, false).await; + let (code, detail) = unwrap_refused(settled); + assert_eq!(code, crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING); + assert!( + detail.starts_with(&format!( + "nokogiri@1.18.10 was not brought up to date: no patched build yet for java; \ + its vendored copy stays in force as it is. Also: {said}" + )) && detail.ends_with(&format!("{remedy}.")), + "{detail}" + ); + + // The list moved: the copy takes the build that was published. + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + let codes: Vec<&str> = warnings.iter().map(|w| w.code).collect(); + assert!( + warned(&warnings) + && codes.contains(&GEM_LIST_FOLLOWED) + && !codes.contains(&GEM_LIST_NOT_FOLLOWED), + "{warnings:?}" + ); + let entry = entry.expect("the entry of the trees that are in place"); + assert_eq!( + entry.gem_builds, + [built(UUID, DARWIN), built(UUID, LINUX)], + "the ledger is handed what is on disk" + ); + let patched = tokio::fs::read(linux.join(RB)).await.unwrap(); + assert_eq!(patched, stamped(LINUX), "the patched build"); + ts::persist(&root, NOKO, entry).await; + let entry = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); + + // A damaged copy is restored, and rebuilt, while the metadata + // stays unwritable. + tokio::fs::remove_dir_all(&linux).await.unwrap(); + let restored = crate::vendor::redownload::restore(&root, &entry, &record, &cfg).await; + let warnings = restored.expect("a restore never fails over the metadata"); + assert!(warned(&warnings), "{warnings:?}"); + assert_eq!( + tokio::fs::read(linux.join(RB)).await.unwrap(), + stamped(LINUX) + ); + tokio::fs::remove_dir_all(&linux).await.unwrap(); + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert!( + warned(&warnings) && warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt"), + "{warnings:?}" + ); + assert!(entry.is_some(), "the rebuilt copy's entry"); + let rebuilt = tokio::fs::read(linux.join(RB)).await.unwrap(); + assert_eq!(rebuilt, stamped(LINUX), "rebuilt"); + } + + /// Git is asked whether it would commit a copy only where trees are + /// about to be placed, before they are moved in and as if nothing + /// were tracked, and a dry run asks the same. So a refusal 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, and a damaged copy is neither restored nor rebuilt. + /// A copy that is already there asks git nothing. Here a project + /// rule ignores the binaries (`*.so`) and the uuid dir's own + /// `.gitignore`, which keeps such a rule off them, cannot be + /// written: the refusal names that as its cause. + #[tokio::test] + async fn a_copy_git_would_not_commit_is_refused_before_its_trees_are_placed() { + let uuid_rel = format!(".socket/vendor/gem/{UUID}"); + let cause = format!( + "`{uuid_rel}/.gitignore` and `{uuid_rel}/.gitattributes`, which keep such a rule \ + off it, could not be written (" + ); + let names_the_cause = |detail: &str| { + detail.contains("git would not commit the vendored artifact at") + && detail.contains(".gitignore:1:*.so") + && detail.contains(&cause) + && detail.contains("make those two files writable and vendor again") + }; + let refused_for_it = |outcome: VendorOutcome| { + let (code, detail) = unwrap_refused(outcome); + assert_eq!(code, "vendor_artifact_gitignored", "{detail}"); + assert!(names_the_cause(&detail), "{detail}"); + }; + let obstruct = |root: &Path| { + let gitignore = root.join(&uuid_rel).join(".gitignore"); + let _ = std::fs::remove_file(&gitignore); + std::fs::create_dir_all(gitignore.join("in the way")).unwrap(); + }; + + // A first vendor, dry and wet: refused, and nothing is written. + let (_tmp, root, record) = project(&lock(None)).await; + if ts::git_project(&root, "*.so\n").is_none() { + return; // no git, nothing to commit + } + obstruct(&root); + let before = ts::tree_snapshot(&root); + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + refused_for_it(vendor(&root, ¬_installed(&root), &record, &cfg, true).await); + assert_eq!(ts::tree_snapshot(&root), before, "a dry run"); + refused_for_it(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!( + !root.join(&uuid_rel).exists(), + "nothing of the copy is left" + ); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, lock(None)); + + // A copy the lock names, with its `.gitignore` unwritable. + let entry = vendor_and_persist(&root, &record, &cfg).await; + obstruct(&root); + let before = ts::tree_snapshot(&root); + + // In step: git is asked nothing. The copy stands, with the + // warning of the file that could not be written. + let (result, _, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + let codes: Vec<&str> = warnings.iter().map(|w| w.code).collect(); + assert_eq!(codes, [GEM_GIT_METADATA_UNWRITTEN], "{warnings:?}"); + + // The list moved: the intact copy stays in force, byte for + // byte, dry and wet, and the note names the rule and the cause. + let (_server, moved) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + for dry_run in [true, false] { + let outcome = vendor(&root, ¬_installed(&root), &record, &moved, dry_run).await; + let (result, entry, warnings) = unwrap_done(outcome); + assert!(result.success && entry.is_none(), "dry run {dry_run}"); + let note = warnings.iter().find(|w| w.code == GEM_LIST_NOT_FOLLOWED); + let note = note.unwrap_or_else(|| panic!("dry run {dry_run}: {warnings:?}")); + assert!( + names_the_cause(¬e.detail) + && note + .detail + .ends_with("its vendored copy stays in force as it is."), + "dry run {dry_run}: {note:?}" + ); + assert_eq!(ts::tree_snapshot(&root), before, "dry run {dry_run}"); + } + + // A damaged copy: neither a restore nor the rebuild moves trees + // git would not commit, and the copy is as it was. + let linux = root.join(rel(UUID)).join(LINUX); + tokio::fs::remove_dir_all(&linux).await.unwrap(); + let damaged = ts::tree_snapshot(&root); + let failed = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) + .await + .expect_err("a restore git would not commit"); + assert!( + failed.detail().starts_with("vendor_artifact_gitignored: ") + && names_the_cause(failed.detail()), + "{failed}" + ); + assert_eq!(ts::tree_snapshot(&root), damaged, "the restore"); + for dry_run in [true, false] { + refused_for_it(vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await); + assert_eq!(ts::tree_snapshot(&root), damaged, "dry run {dry_run}"); + } + } + + /// With the uuid dir's own rules in place no rule above them + /// reaches a file of the copy, and what git can still refuse is a + /// rule that excludes the directory itself. Added after the copy + /// was vendored, such a rule keeps a moved list from being + /// followed: the copy stays in force, dry and wet, and the note + /// names the rule. In step, the same copy is asked about nothing. + #[tokio::test] + async fn a_rule_that_excludes_the_directory_keeps_a_wired_copy_as_it_is() { + let (_tmp, root, record) = project(&lock(None)).await; + if ts::git_project(&root, "*.so\n").is_none() { + return; // no git, nothing to commit + } + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + // (Without the rule, a scan's preview says the wet run vendors.) + let (_server, published) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let previewed = preview_locked_builds(&root, NOKO, UUID, false, Some(&published)).await; + assert!( + matches!(previewed, Some(LockedBuildsPreview::Vendor(_))), + "{previewed:?}" + ); + tokio::fs::write(root.join(".gitignore"), "*.so\n/.socket/vendor/gem/\n") + .await + .unwrap(); + let before = ts::tree_snapshot(&root); + + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success && entry.is_none(), "{:?}", result.error); + assert!(warnings.is_empty(), "in step: {warnings:?}"); + + let (_server, moved) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + // The preview of a scan, which downloads nothing, does not say + // that the copy would be vendored either. + let previewed = preview_locked_builds(&root, NOKO, UUID, false, Some(&moved)).await; + assert!( + !matches!(previewed, Some(LockedBuildsPreview::Vendor(_))), + "{previewed:?}" + ); + for dry_run in [true, false] { + let outcome = vendor(&root, ¬_installed(&root), &record, &moved, dry_run).await; + let (result, entry, warnings) = unwrap_done(outcome); + assert!(result.success && entry.is_none(), "dry run {dry_run}"); + let codes: Vec<&str> = warnings.iter().map(|w| w.code).collect(); + assert_eq!( + codes, + [GEM_LIST_NOT_FOLLOWED], + "dry run {dry_run}: {warnings:?}" + ); + assert!( + warnings[0] + .detail + .contains(".gitignore:2:/.socket/vendor/gem/") + && warnings[0] + .detail + .ends_with("its vendored copy stays in force as it is."), + "dry run {dry_run}: {warnings:?}" + ); + assert_eq!(ts::tree_snapshot(&root), before, "dry run {dry_run}"); + } + } + + /// A copy that is already there asks git nothing, wherever the + /// project sits: one exported without its `.git` into a directory + /// an outer repository ignores is found in step like any other, + /// with nothing said, though git would call every path of it + /// ignored. + #[tokio::test] + async fn a_copy_in_step_in_an_ignored_directory_of_an_outer_repository_stands() { + fn copy_tree(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap() { + let entry = entry.unwrap(); + let target = to.join(entry.file_name()); + if entry.path().is_dir() { + copy_tree(&entry.path(), &target); + } else { + std::fs::copy(entry.path(), &target).unwrap(); + } + } + } + let (_tmp, made, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + vendor_and_persist(&made, &record, &cfg).await; + + let outer = tempfile::tempdir().unwrap(); + if ts::git_project(outer.path(), "build/\n").is_none() { + return; // no git, nothing to ask + } + let root = outer.path().join("build/app"); + copy_tree(&made, &root); + let binary = format!("build/app/{}/{DARWIN}/{SO}", rel(UUID)); + assert!( + crate::vendor::npm_dir::gitignored(outer.path(), &[binary]) + .await + .is_some(), + "git calls the copy ignored there" + ); + let before = ts::tree_snapshot(&root); + for dry_run in [true, false] { + let outcome = vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await; + let (result, entry, warnings) = unwrap_done(outcome); + assert!(result.success, "dry run {dry_run}: {:?}", result.error); + assert!( + entry.is_none() && warnings.is_empty(), + "dry run {dry_run}: {warnings:?}" + ); + assert_eq!(ts::tree_snapshot(&root), before, "dry run {dry_run}"); + } + } + + /// A rebuild that fails leaves no uuid dir behind where there was + /// none: the metadata is written after the trees are in place, + /// never before them. + #[tokio::test] + async fn a_failed_rebuild_leaves_no_uuid_dir_of_metadata_alone() { + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + let uuid_dir = root.join(format!(".socket/vendor/gem/{UUID}")); + tokio::fs::remove_dir_all(&uuid_dir).await.unwrap(); + // Upstream's gem for linux does not unpack. + let broken = Served { + gem: Some(b"not a gem".to_vec()), + ..upstream(LINUX) + }; + let (_server, cfg) = service(UUID, &[served(DARWIN), broken]).await; + let outcome = vendor(&root, ¬_installed(&root), &record, &cfg, false).await; + assert!( + !matches!(&outcome, VendorOutcome::Done { result, .. } if result.success), + "the rebuild fails" + ); + assert!(!uuid_dir.exists(), "no directory of metadata alone"); + } + + /// A gem the lock names as platform gems is no position of the + /// download plan, and each such gem a run finds vendored asks for + /// the list of its own fix, live: ONE request, which names that + /// fix alone, and nothing downloaded for a copy in step. The + /// question is advisory: with no answer the copy stands, nothing + /// is said, and the circuit breaker is not touched, so a service + /// that is down for these reads cannot fail what the run really + /// has to vendor. A copy whose list moved is vendored from the + /// list that was read to find that out, so the fix's reference is + /// asked for once. + #[tokio::test] + async fn each_vendored_gem_asks_for_the_list_of_its_own_fix() { + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + assert_eq!( + service_preflight(NOKO, ¬_installed(&root), &root, &record).await, + None, + "nothing of the gem's own patch is downloaded, so nothing is planned" + ); + + let (server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + let (again, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success, "{:?}", again.error); + assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); + assert_eq!( + reference_requests(&server).await, + [vec![UUID.to_string()]], + "one request, for this gem's fix alone" + ); + assert_eq!(ts::request_count(&server).await, 1, "nothing is downloaded"); + + // No answer (the service is unavailable): the copy stands with + // nothing said, each read is one request, and after any number + // of them the breaker is closed. + let down = wiremock::MockServer::start().await; + wiremock::Mock::given(wiremock::matchers::method("POST")) + .respond_with(wiremock::ResponseTemplate::new(503)) + .mount(&down) + .await; + let cfg = ts::service_cfg(&down.uri(), crate::vendor::VendorSource::Service, false); + let before = ts::tree_snapshot(&root); + for asked in 1..=3 { + let (again, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success, "{:?}", again.error); + assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); + assert_eq!(ts::request_count(&down).await, asked); + } + let client = cfg.client.as_ref().expect("the service's client"); + assert_eq!( + client.vendor_outage_count(), + 0, + "the breaker is not touched" + ); + assert_eq!(ts::tree_snapshot(&root), before); + + // The list moved: the rebuild takes the gems the list was read + // to name. + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let (result, entry, _) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + ts::persist(&root, NOKO, entry.expect("the copy's new entry")).await; + let asked = reference_requests(&server).await; + let fixes = asked + .iter() + .filter(|uuids| uuids.contains(&UUID.to_string())); + assert_eq!(fixes.count(), 1, "{asked:?}"); + } + + /// A restore reads the list of the gem's fix once and hands it on, + /// whether it is refused over that list or restores the copy, and + /// the backend does not ask for the fix's reference again, wet or + /// dry: a damaged copy whose list moved is vendored again from the + /// list the restore read, and a restored copy is judged in step by + /// it. A list of another fix is not used: the backend asks. + #[tokio::test] + async fn a_restore_hands_the_list_it_read_to_the_backend() { + use crate::vendor::redownload::{ + restore_refused_over, restore_with_list, RestoreError, + }; + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + let entry = vendor_and_persist(&root, &record, &cfg).await; + let linux = root.join(rel(UUID)).join(LINUX); + tokio::fs::remove_dir_all(&linux).await.unwrap(); + let blobs = root.join("no-blobs"); + let sources = PatchSources::blobs_only(&blobs); + let fix_requests = |asked: Vec>| { + let of_fix = asked + .iter() + .filter(|uuids| uuids.contains(&UUID.to_string())); + of_fix.count() + }; + + for dry_run in [true, false] { + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let list = match dry_run { + true => restore_refused_over(&entry, &record, &cfg).await, + false => match restore_with_list(&root, &entry, &record, &cfg).await { + Err(RestoreError::ListMoved(_, list)) => Some(list), + other => panic!("the restore is refused over the list: {other:?}"), + }, + }; + let list = list.expect("the list that moved"); + assert_eq!(fix_requests(reference_requests(&server).await), 1); + assert!(!linux.exists(), "the restore unpacked nothing"); + let mut previewed = Vec::new(); + let outcome = vendor_gem_previewing( + NOKO, + not_installed(&root).as_path(), + &root, + &record, + &sources, + "2026-06-09T00:00:00Z", + dry_run, + false, + Some(&cfg), + false, + Some(&list), + &mut previewed, + ) + .await; + let (result, rebuilt_entry, _) = unwrap_done(outcome); + let rebuilt = rebuilt_entry.clone(); + assert!(result.success, "dry run {dry_run}: {:?}", result.error); + assert_eq!( + fix_requests(reference_requests(&server).await), + 1, + "dry run {dry_run}: the backend does not ask for the fix's list again" + ); + let builds = match dry_run { + true => previewed, + false => rebuilt.expect("the rebuilt copy's entry").gem_builds, + }; + let named: Vec<(&str, &str)> = builds + .iter() + .map(|b| (b.platform.as_str(), b.uuid.as_str())) + .collect(); + assert_eq!( + named, + [ + (DARWIN, build_uuid(UUID, DARWIN).as_str()), + (LINUX, build_uuid(UUID, LINUX).as_str()) + ], + "dry run {dry_run}: vendored from the list that was handed over" + ); + assert_eq!(linux.exists(), !dry_run, "dry run {dry_run}"); + if !dry_run { + ts::persist(&root, NOKO, rebuilt_entry.expect("the wet run's entry")).await; + } + } + + // A restore that succeeds hands its list on too: the copy it + // put back is found in step by that list, with no request. + let entry = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); + tokio::fs::remove_dir_all(&linux).await.unwrap(); + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let (_, list) = restore_with_list(&root, &entry, &record, &cfg) + .await + .expect("the list did not move: the copy is restored"); + let list = list.expect("the list the restore read"); + assert!(linux.exists(), "restored"); + let asked = ts::request_count(&server).await; + let in_step = |list: Option| { + let (root, record, cfg) = (root.clone(), record.clone(), cfg.clone()); + async move { + let blobs = root.join("no-blobs"); + let outcome = vendor_gem_previewing( + NOKO, + not_installed(&root).as_path(), + &root, + &record, + &PatchSources::blobs_only(&blobs), + "2026-06-09T00:00:00Z", + false, + false, + Some(&cfg), + false, + list.as_ref(), + &mut Vec::new(), + ) + .await; + let (result, entry, warnings) = unwrap_done(outcome); + assert!(result.success, "{:?}", result.error); + assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); + } + }; + in_step(Some(list.clone())).await; + assert_eq!( + ts::request_count(&server).await, + asked, + "judged by the list the restore read" + ); + // The list of another fix says nothing of this gem. + let foreign = FixList { + fix: UUID_B.to_string(), + ..list + }; + in_step(Some(foreign)).await; + assert_eq!( + reference_requests(&server).await.last(), + Some(&vec![UUID.to_string()]), + "the backend asks for its own fix's list" + ); + assert_eq!(ts::request_count(&server).await, asked + 1); + } + + /// A gem that is left as it is whatever its gems are is never + /// failed over one of them: the skips are judged before an + /// upstream gem the list does not pin. Beside a patched build that + /// gem is the miss it was. Upstream's gem is taken from the patch + /// registry alone: a redirect it answers is the gem not being + /// served, and is not followed. + #[tokio::test] + async fn a_skip_is_judged_before_an_upstream_gem_that_cannot_be_fetched() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, ResponseTemplate}; + let unpinned = |platform| Served { + listed_sha256: Some("not a sha256".to_string()), + ..upstream(platform) + }; + let unlisted = Served { + listed: Listed::Unlisted, + ..served(LINUX) + }; + let skips = [ + ( + vec![unpinned(DARWIN), unlisted], + "the patch registry does not list x86_64-linux-gnu", + ), + ( + vec![unpinned(DARWIN), upstream(LINUX)], + "is not vendored: no patched build yet for arm64-darwin and \ + x86_64-linux-gnu.", + ), + ]; + for (list, says) in skips { + let (_tmp, root, record) = project(&lock(None)).await; + let (server, cfg) = service(UUID, &list).await; + let (code, detail) = unwrap_refused( + vendor(&root, ¬_installed(&root), &record, &cfg, false).await, + ); + assert_eq!( + code, + crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING, + "{detail}" + ); + assert!(detail.contains(says), "{detail}"); + assert_eq!(downloads(&server).await, Vec::::new()); + } + + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[unpinned(DARWIN), served(LINUX)]).await; + let (code, detail) = + unwrap_refused(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert_eq!(code, crate::vendor::VENDOR_PREBUILT_REQUIRED, "{detail}"); + assert!( + detail.contains("no sha256 for upstream's gem of nokogiri (arm64-darwin)"), + "{detail}" + ); + assert!(!root.join(".socket/vendor/gem").exists()); + + // The registry answers the gem's file with a redirect. + let elsewhere = wiremock::MockServer::start().await; + let (server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + let file = + format!("/patch-registry/gem/tok/{UUID}/s/4/gems/nokogiri-1.18.10-{LINUX}.gem"); + Mock::given(method("GET")) + .and(path(file.as_str())) + .respond_with(ResponseTemplate::new(302).insert_header( + "Location", + format!("{}/gems/nokogiri-1.18.10-{LINUX}.gem", elsewhere.uri()).as_str(), + )) + .with_priority(1) + .mount(&server) + .await; + let (code, detail) = + unwrap_refused(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert_eq!(code, crate::vendor::VENDOR_PREBUILT_REQUIRED, "{detail}"); + assert!( + detail.contains( + "could not fetch the upstream platform gem for nokogiri (x86_64-linux-gnu) \ + (artifact not found" + ), + "{detail}" + ); + assert_eq!( + ts::request_count(&elsewhere).await, + 0, + "no redirect is followed" + ); + assert!(!root.join(".socket/vendor/gem").exists()); + } + + /// A `.gitignore` a gem of the copy ships is emptied whichever gem + /// it is, and the advisory names the gems as they are. + #[tokio::test] + async fn a_gitignore_upstreams_gem_ships_is_emptied_and_named_as_such() { + let (_tmp, root, record) = project(&lock(None)).await; + let shipping = Served { + gem: Some(make_gem_with_metadata( + upstream_gemspec_yaml(LINUX).as_bytes(), + &[(RB, RB_PRISTINE), (".gitignore", &b"*.so\n"[..])], + )), + ..upstream(LINUX) + }; + let (_server, cfg) = service(UUID, &[served(DARWIN), shipping]).await; + let (result, _, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + let said: Vec<&str> = warnings + .iter() + .filter(|w| w.code == GITIGNORE_NEUTRALIZED) + .map(|w| w.detail.as_str()) + .collect(); + assert!( + matches!(said.as_slice(), [said] if said.starts_with( + "nokogiri: the platform gems ship their own `.gitignore` (" + )), + "{warnings:?}" + ); + let emptied = root.join(rel(UUID)).join(LINUX).join(".gitignore"); + assert_eq!(tokio::fs::read(emptied).await.unwrap(), b""); + } - // The requests: the gem patch's reference says which - // patch each locked platform's build is, the platform - // patches' references come in ONE request, and only the - // platform gems and their stubs are downloaded. - assert_eq!( - reference_requests(&server).await, - [ - vec![UUID.to_string()], - vec![build_uuid(UUID, DARWIN), build_uuid(UUID, LINUX)], - ] - ); - let mut fetched = downloads(&server).await; - fetched.sort(); - let file = |platform: &str, ext: &str| { - let own = build_uuid(UUID, platform); - format!( - "/patch/gem/nokogiri/1.18.10/tok/{own}/nokogiri-1.18.10-{platform}.{ext}" - ) + /// A fresh vendor of a gem none of whose locked platforms has a + /// patched build is the skip it was, whatever the list names for + /// them, and an upstream gem that is not the one the list names + /// (another sha256, another gem's gemspec, one with extensions to + /// build) is refused with nothing left behind. + #[tokio::test] + async fn an_upstream_gem_that_is_not_the_listed_one_is_refused() { + let another = |metadata: String| Served { + gem: Some(make_gem_with_metadata( + metadata.as_bytes(), + &[(RB, RB_PRISTINE)], + )), + ..upstream(LINUX) + }; + let cases = [ + ( + Served { + listed_sha256: Some("0".repeat(64)), + ..upstream(LINUX) + }, + "integrity", + ), + ( + another(upstream_gemspec_yaml(DARWIN)), + "vendor_prebuilt_integrity_mismatch", + ), + ( + another( + upstream_gemspec_yaml(LINUX) + .replace("extensions: []", "extensions:\n- ext/nokogiri/extconf.rb"), + ), + "native_extensions_unsupported", + ), + ]; + for (linux, says) in cases { + let lock_before = lock(None); + let (_tmp, root, record) = project(&lock_before).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), linux]).await; + let outcome = vendor(&root, ¬_installed(&root), &record, &cfg, false).await; + let said = match outcome { + VendorOutcome::Refused { code, detail } => format!("{code}: {detail}"), + VendorOutcome::Done { result, .. } => { + assert!(!result.success, "{says}: vendored"); + result.error.unwrap_or_default() + } }; - let mut expected = vec![ - file(DARWIN, "gem"), - file(DARWIN, "gemspec"), - file(LINUX, "gem"), - file(LINUX, "gemspec"), - ]; - expected.sort(); - assert_eq!(fetched, expected); + assert!(said.contains(says), "{says}: {said}"); + assert!(said.contains("x86_64-linux-gnu"), "{said}"); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, lock_before, "{says}"); + assert!(!root.join(".socket/vendor/gem").exists(), "{says}"); + } + } - // The ledger entry: each tree's platform, patch and digests, - // in lock order. - assert_eq!(entry.gem_builds, [built(UUID, DARWIN), built(UUID, LINUX)]); - assert_eq!(entry.uuid, UUID); - assert_eq!(entry.artifact.path, rel); - let inventory = entry.artifact.file_inventory.as_ref().expect("inventory"); - let inventoried: Vec<&str> = inventory.keys().map(String::as_str).collect(); - assert_eq!( - inventoried, - [ - "arm64-darwin/lib/nokogiri/nokogiri.so", - "arm64-darwin/lib/nokogiri/version.rb", - "arm64-darwin/nokogiri.gemspec", - "x86_64-linux-gnu/lib/nokogiri/nokogiri.so", - "x86_64-linux-gnu/lib/nokogiri/version.rb", - "x86_64-linux-gnu/nokogiri.gemspec", - ] - ); - let checksum_record = entry - .wiring - .iter() - .find(|w| w.kind == LOCK_CHECKSUM_WIRING_KIND); - match before { - None => assert!(checksum_record.is_none(), "{checksum_record:?}"), - Some(_) => { - let rec = checksum_record.expect("a checksum record"); - assert_eq!( - rec.original, - Some(serde_json::json!([ - format!(" nokogiri (1.18.10-arm64-darwin){}", sha('a')), - format!(" nokogiri (1.18.10-x86_64-linux-gnu){}", sha('b')), - ])) - ); - assert_eq!( - rec.new, - Some(serde_json::json!([ - " nokogiri (1.18.10-arm64-darwin)", - " nokogiri (1.18.10-x86_64-linux-gnu)", - ])) - ); - } + /// `repair` (a restore) of a copy with a tree of upstream's gem + /// fetches that gem again from the fix's registry, by the digest + /// the ledger recorded with the tree, and refuses, with nothing + /// unpacked, when the list names a patched build for the platform + /// now, when it lists another gem, and when the ledger entry pins + /// no digest for the tree. + #[tokio::test] + async fn a_lost_tree_of_upstreams_gem_is_restored_from_the_fixs_registry() { + let (_tmp, root, record) = project(&lock(None)).await; + let (server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + let entry = vendor_and_persist(&root, &record, &cfg).await; + let tree = root.join(rel(UUID)).join(LINUX); + tokio::fs::remove_dir_all(&tree).await.unwrap(); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Corrupt { + reason: "file_not_found".to_string() } + ); + + // The refusals. + let before = ts::tree_snapshot(&root); + let mut no_pin = entry.clone(); + no_pin.gem_builds[1].gem_integrity.clear(); + let refused = crate::vendor::redownload::restore(&root, &no_pin, &record, &cfg) + .await + .expect_err("an entry with no digest for the tree"); + assert!(refused.detail().contains("pins no digest"), "{refused}"); + let another_gem = Served { + gem: Some(make_gem_with_metadata( + upstream_gemspec_yaml(LINUX).as_bytes(), + &[(RB, RB_PRISTINE), (SO, b"another release")], + )), + ..upstream(LINUX) + }; + for (now, code, says) in [ + ( + served(LINUX), + VENDOR_PREBUILT_REPLACED, + "names the patched build of patch", + ), + ( + another_gem, + "vendor_prebuilt_integrity_mismatch", + "is not the gem this copy was vendored from", + ), + ] { + let (_server, cfg) = service(UUID, &[served(DARWIN), now]).await; + let refused = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) + .await + .expect_err("a list that moved"); + assert!(refused.detail().starts_with(code), "{refused}"); + assert!(refused.detail().contains(says), "{refused}"); assert!( - warnings - .iter() - .any(|w| w.code == "vendor_prebuilt_downloaded" - && w.detail.contains(DARWIN) - && w.detail.contains(LINUX)), - "{warnings:?}" + refused.detail().contains("nokogiri (x86_64-linux-gnu)"), + "{refused}" ); - - // The ledger round trip through state.json. - ts::persist(&root, NOKO, entry.clone()).await; - let saved = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); - assert_eq!(saved, entry); - let ledger = text(root.join(".socket/vendor/state.json")).await; - assert!(ledger.contains("\"gemBuilds\""), "{ledger}"); - assert!(ledger.contains("\"gemIntegrity\""), "{ledger}"); - assert!(ledger.contains("\"gemspecIntegrity\""), "{ledger}"); - - // Verification and discovery: one vendored reference. + assert_eq!(ts::tree_snapshot(&root), before, "{says}"); + // Only the list that names another build is a list that + // moved, which a dry run is told without a download. + let moved = code == VENDOR_PREBUILT_REPLACED; + let list_moved = matches!( + refused, + crate::vendor::redownload::RestoreError::ListMoved(..) + ); + assert_eq!(list_moved, moved, "{refused}"); + // A list that moved names the one command that works, once: + // the scan that vendors the copy again from that list. assert_eq!( - check_vendored_artifact(&root, &saved, &record).await, - ArtifactHealth::Healthy + refused.detail().ends_with( + "Nothing was restored. Run `socket-patch scan --mode vendored`, which \ + vendors what the patch service serves now" + ), + moved, + "{refused}" ); - let found = crate::vex::discover::discover_patched_refs(&root).await; - let refs: Vec<_> = found - .refs - .iter() - .map(|r| (r.purl.as_str(), r.uuid.as_str(), r.artifact_rel.as_deref())) - .collect(); assert_eq!( - refs, - [("pkg:gem/nokogiri@1.18.10", UUID, Some(rel.as_str()))] + refused.detail().matches("`socket-patch ").count(), + usize::from(moved), + "{refused}" ); - assert!(found.diagnostics.is_empty(), "{:?}", found.diagnostics); - - // A second run changes nothing and asks the service nothing. - let requests = ts::request_count(&server).await; - let snapshot = ts::tree_snapshot(&root); - let (again, entry, warnings) = - unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); - assert!(again.success, "{:?}", again.error); - assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); - assert_eq!(ts::tree_snapshot(&root), snapshot); - assert_eq!(ts::request_count(&server).await, requests); - - // Revert: both files byte for byte, the trees gone. - let reverted = revert_gem(&saved, &root, false).await; - assert!(reverted.success, "{:?}", reverted.error); - assert!(reverted.warnings.is_empty(), "{:?}", reverted.warnings); - assert_eq!(text(root.join(GEMFILE)).await, GEMFILE_NOKO); - assert_eq!(text(root.join(GEMFILE_LOCK)).await, lock_before); - assert!(!root.join(".socket/vendor/gem").exists()); + let asked = crate::vendor::redownload::restore_refused_over(&entry, &record, &cfg); + assert_eq!(asked.await.is_some(), moved, "{says}"); } + // A list that still names upstream's gem and does not pin it + // is a miss, not a list that moved. + let unpinned = Served { + listed_sha256: Some("not a sha256".to_string()), + ..upstream(LINUX) + }; + let (_server, loose) = service(UUID, &[served(DARWIN), unpinned]).await; + let refused = crate::vendor::redownload::restore(&root, &entry, &record, &loose) + .await + .expect_err("an upstream gem the list does not pin"); + assert!( + refused + .detail() + .contains("no sha256 for upstream's gem of nokogiri (x86_64-linux-gnu)") + && !refused.detail().contains(VENDOR_PREBUILT_REPLACED), + "{refused}" + ); + assert!( + matches!(refused, crate::vendor::redownload::RestoreError::Failed(_)), + "{refused}" + ); + assert_eq!(ts::tree_snapshot(&root), before); + + // The restore: the fix's list, the patched build's reference, + // and both gems again. + let asked = reference_requests(&server).await.len(); + let fetched = downloads(&server).await.len(); + crate::vendor::redownload::restore(&root, &entry, &record, &cfg) + .await + .expect("restore"); + assert_eq!( + reference_requests(&server).await[asked..], + [vec![UUID.to_string()], vec![build_uuid(UUID, DARWIN)]] + ); + let again = downloads(&server).await[fetched..].to_vec(); + assert!( + again.contains(&format!( + "/patch-registry/gem/tok/{UUID}/s/4/gems/nokogiri-1.18.10-{LINUX}.gem" + )), + "{again:?}" + ); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + assert_eq!( + tokio::fs::read(tree.join("nokogiri.gemspec")) + .await + .unwrap(), + upstream_gemspec_yaml(LINUX).as_bytes() + ); } - /// Every locked platform needs a patched build. While the gem - /// patch's reference names none for one of them (the registry - /// serves upstream's own gem for it, does not list it, or lists no - /// platform gem at all), a dry run and a wet run both leave the gem - /// alone under the benign pending code: one line that names the gem - /// and the platforms, one request (the gem patch's reference), no + /// The gem needs a gem for every locked platform and a patched + /// build of one at least. While the list of the gem's fix leaves a + /// locked platform out, names a patched build for none, or is not + /// there at all, a dry run and a wet run both leave the gem alone + /// under the benign pending code: one line that names the gem and + /// the platforms, one request (the gem patch's reference), no /// download and nothing written. #[tokio::test] async fn a_locked_platform_without_a_patched_build_is_a_skip_that_downloads_nothing() { @@ -13274,14 +15432,7 @@ mod tests { listed, ..served(platform) }; - let cases: [(Vec, bool, &str); 6] = [ - ( - vec![served(DARWIN), listed(LINUX, Listed::PassThrough)], - true, - "nokogiri@1.18.10 is not vendored: no patched build yet for x86_64-linux-gnu \ - (arm64-darwin has one). Vendored mode needs every locked platform; `scan \ - --mode hosted` can patch the others now.", - ), + let cases: [(Vec, bool, &str); 5] = [ // A platform the list leaves out is one upstream does not // publish: not one to wait for, and hosted mode leaves // such a gem alone too. @@ -13289,7 +15440,8 @@ mod tests { vec![listed(DARWIN, Listed::Unlisted), served(LINUX)], true, "nokogiri@1.18.10 is not vendored: the patch registry does not list \ - arm64-darwin. Vendored mode needs every locked platform, and a re-run does \ + arm64-darwin. 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 arm64-darwin (`bundle lock --remove-platform arm64-darwin`), \ or the registry lists a gem for every locked platform.", @@ -13301,11 +15453,11 @@ mod tests { ], true, "nokogiri@1.18.10 is not vendored: the patch registry does not list \ - arm64-darwin, and there is no patched build yet for x86_64-linux-gnu. \ - Vendored mode needs every locked platform, and a re-run does not change \ - what the registry lists: this is settled once the lockfile no longer names \ - arm64-darwin (`bundle lock --remove-platform arm64-darwin`), or the \ - registry lists a gem for every locked platform.", + arm64-darwin. 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 arm64-darwin (`bundle lock --remove-platform arm64-darwin`), \ + or the registry lists a gem for every locked platform.", ), ( vec![ @@ -13314,14 +15466,15 @@ mod tests { ], true, "nokogiri@1.18.10 is not vendored: no patched build yet for arm64-darwin and \ - x86_64-linux-gnu. Vendored mode needs every locked platform.", + x86_64-linux-gnu.", ), ( Vec::new(), true, "nokogiri@1.18.10 is not vendored: the patch registry does not list \ - arm64-darwin and x86_64-linux-gnu. Vendored mode needs every locked \ - platform, and a re-run does not change what the registry lists: this is \ + arm64-darwin and x86_64-linux-gnu. 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 arm64-darwin and \ x86_64-linux-gnu (`bundle lock --remove-platform arm64-darwin \ x86_64-linux-gnu`), or the registry lists a gem for every locked platform.", @@ -13415,10 +15568,11 @@ mod tests { ); } - /// A platform the lock gains after the gem was vendored, with no - /// patched build: the vendored copy stays in force exactly as it - /// is, dry run or not, under the same benign code and one line - /// that says why it was not brought up to date. + /// A platform the lock gains after the gem was vendored, whose + /// patched build is named and not served yet: the vendored copy + /// stays in force exactly as it is, dry run or not, under the same + /// benign code and one line that says why it was not brought up to + /// date. #[tokio::test] async fn a_vendored_gem_whose_lock_gains_an_unpatched_platform_stays_as_it_is() { const JAVA: &str = "java"; @@ -13433,11 +15587,8 @@ mod tests { ); tokio::fs::write(&lock_path, &gained).await.unwrap(); let before = ts::tree_snapshot(&root); - let pass_through = Served { - listed: Listed::PassThrough, - ..served(JAVA) - }; - let (server, cfg) = service(UUID, &[served(DARWIN), pass_through, served(LINUX)]).await; + let building = unserved(JAVA, "pending_build"); + let (server, cfg) = service(UUID, &[served(DARWIN), building, served(LINUX)]).await; for dry_run in [true, false] { let (code, detail) = unwrap_refused( vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, @@ -13446,8 +15597,9 @@ mod tests { assert_eq!( detail, "nokogiri@1.18.10 was not brought up to date: no patched build yet for java \ - (arm64-darwin and x86_64-linux-gnu have one). Vendored mode needs every \ - locked platform; its vendored copy stays in force as it is." + (arm64-darwin and x86_64-linux-gnu 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." ); assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); } @@ -13479,7 +15631,8 @@ mod tests { assert_eq!( detail, "nokogiri@1.18.10 was not brought up to date: the patch registry does not \ - list x86_64-linux-gnu. Vendored mode needs every locked platform, and a \ + list x86_64-linux-gnu. 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 x86_64-linux-gnu (`bundle lock --remove-platform \ x86_64-linux-gnu`), or the registry lists a gem for every locked platform; \ @@ -13518,7 +15671,8 @@ mod tests { /// download and nothing written. #[tokio::test] async fn a_platform_patch_that_is_not_served_is_a_skip_that_downloads_nothing() { - const NEEDS: &str = "Vendored mode needs every locked platform"; + const NEEDS: &str = + "Vendored mode needs a gem, patched or upstream's own, for every locked platform"; const HOSTED: &str = "`scan --mode hosted` can patch the others now."; let mut cases: Vec<(Vec, String)> = vec![ ( @@ -13610,8 +15764,9 @@ mod tests { detail, format!( "nokogiri@1.18.10 was not brought up to date: {none} \ - x86_64-linux-gnu (arm64-darwin has one). Vendored mode needs every \ - locked platform; its vendored copy of an earlier patch stays in \ + x86_64-linux-gnu (arm64-darwin has one). Vendored mode needs a gem, \ + patched or upstream's own, for every locked platform; its vendored \ + copy of an earlier patch stays in \ force as it is." ) ); @@ -13638,8 +15793,9 @@ mod tests { detail, format!( "nokogiri@1.18.10 was not brought up to date: {none} java \ - (arm64-darwin and x86_64-linux-gnu have one). Vendored mode needs \ - every locked platform; its vendored copy stays in force as it is." + (arm64-darwin and x86_64-linux-gnu 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." ) ); assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); @@ -13679,7 +15835,8 @@ mod tests { format!( "nokogiri@1.18.10 was not brought up to date: no patched build \ {none} for x86_64-linux-gnu (arm64-darwin has one). Vendored mode \ - needs every locked platform; its vendored copy is missing or \ + needs a gem, patched or upstream's own, for every locked platform; \ + its vendored copy is missing or \ damaged and cannot be rebuilt until then." ) ); @@ -13688,8 +15845,11 @@ mod tests { let failed = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) .await .expect_err("a recorded tree whose patch is not served cannot be restored"); - assert!(failed.starts_with("vendor_prebuilt_required: "), "{failed}"); - assert!(failed.contains(restore_says), "{failed}"); + assert!( + failed.detail().starts_with("vendor_prebuilt_required: "), + "{failed}" + ); + assert!(failed.detail().contains(restore_says), "{failed}"); assert_eq!(ts::tree_snapshot(&root), before, "restore"); } } @@ -13734,7 +15894,7 @@ mod tests { let failed = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) .await .expect_err("a fix that lists no builds restores nothing"); - assert_eq!(failed, RESTORE); + assert_eq!(failed.detail(), RESTORE); assert_eq!(ts::tree_snapshot(&root), before, "restore"); // The same from a fix that is not ready, in the same words. @@ -13749,7 +15909,7 @@ mod tests { let failed = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) .await .expect_err("a fix that is not ready restores nothing"); - assert_eq!(failed, RESTORE); + assert_eq!(failed.detail(), RESTORE); assert_eq!(ts::tree_snapshot(&root), before, "restore"); let pass_through = Served { @@ -13761,8 +15921,8 @@ mod tests { .await .expect_err("a list with no patched build for the platform restores nothing"); assert!( - failed.starts_with("vendor_prebuilt_replaced: ") - && failed.contains("(it was withdrawn)"), + failed.detail().starts_with("vendor_prebuilt_replaced: ") + && failed.detail().contains("(it was withdrawn)"), "{failed}" ); assert_eq!(ts::tree_snapshot(&root), before, "restore"); @@ -13847,6 +16007,7 @@ mod tests { false, Some(cfg), false, + None, previewed, ) .await @@ -13854,11 +16015,7 @@ mod tests { let (_tmp, root, record) = project(&lock(None)).await; let before = ts::tree_snapshot(&root); - let pass_through = Served { - listed: Listed::PassThrough, - ..served(LINUX) - }; - for not_vendorable in [pass_through, unserved(LINUX, "pending_build")] { + for not_vendorable in [unserved(LINUX, "pending_build")] { let (_server, cfg) = service(UUID, &[served(DARWIN), not_vendorable]).await; let mut previewed = Vec::new(); let outcome = run(&root, &record, &cfg, true, &mut previewed).await; @@ -13922,16 +16079,10 @@ mod tests { assert_eq!(reference_requests(&server).await, both_requests(UUID)); assert_eq!(downloads(&server).await, Vec::::new()); - // A locked platform with no patched build, which the gem - // patch's reference says (one request), or whose patch is not - // served, which that patch's own reference says (the second): - // the wet run's skip, word for word. - let pass_through = Served { - listed: Listed::PassThrough, - ..served(LINUX) - }; + // A locked platform whose patch is not served, which that + // patch's own reference says (the second request): the wet + // run's skip, word for word. for (not_vendorable, requests) in [ - (pass_through, vec![vec![UUID.to_string()]]), ( unserved(LINUX, "pending_build"), both_requests(UUID).to_vec(), @@ -14006,7 +16157,9 @@ mod tests { assert_eq!(ts::tree_snapshot(&root), before); // Not judged: a gem the lock names for the ruby platform, and - // a lock already wired to the patch's copy. + // a lock already wired to the patch's copy while that copy + // holds the builds the list names. The list is all the latter + // asks for: one request. let ruby_gem = "pkg:gem/puma@6.4.2"; assert!( preview_locked_builds(&root, ruby_gem, UUID, false, Some(&cfg)) @@ -14016,7 +16169,41 @@ mod tests { vendor_and_persist(&root, &record, &cfg).await; let asked = ts::request_count(&server).await; assert!(preview(&root, &cfg).await.is_none()); - assert_eq!(ts::request_count(&server).await, asked); + assert_eq!(ts::request_count(&server).await, asked + 1); + + // A wired lock whose copy holds another build than the list + // names now is judged by the list: the trees the wet run puts + // in place, for a published build and for a withdrawn one. + // Each patched build must be served, as for a fresh vendor. + let (withdrawn, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + match preview(&root, &cfg).await { + Some(LockedBuildsPreview::Vendor(builds)) => assert_eq!( + builds, + [ + named(DARWIN), + GemBuildEntry { + uuid: String::new(), + ..named(LINUX) + } + ] + ), + other => panic!("{other:?}"), + } + assert_eq!( + reference_requests(&withdrawn).await, + [vec![UUID.to_string()], vec![build_uuid(UUID, DARWIN)]] + ); + assert_eq!(downloads(&withdrawn).await, Vec::::new()); + let (_unserved, cfg) = + service(UUID, &[unserved(DARWIN, "pending_build"), upstream(LINUX)]).await; + // The wet run skips the gem and leaves the copy as it is; the + // preview says that skip rather than a copy in step. + match preview(&root, &cfg).await { + Some(LockedBuildsPreview::Refused { code, .. }) => { + assert_eq!(code, crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING) + } + other => panic!("the wet run's pending skip: {other:?}"), + } } /// The preview words a skip as the wet run does when the Gemfile @@ -14062,7 +16249,8 @@ mod tests { fn the_line_of_an_unpatched_platform_ends_with_what_the_gem_is_left_with() { const GEM: &str = "nokogiri@1.18.10"; const NONE_YET: &str = "no patched build yet for arm64-darwin"; - const NEEDS: &str = "Vendored mode needs every locked platform"; + const NEEDS: &str = + "Vendored mode needs a gem, patched or upstream's own, for every locked platform"; let yet = NoPatchedBuild { yet: vec![DARWIN], ..NoPatchedBuild::default() @@ -14091,7 +16279,7 @@ mod tests { {NEEDS}; its vendored copy of an earlier patch stays in force as it is." ) ); - // Left open for `wired_copy_not_rebuilt`, which knows whether + // Left open for `wired_copy_failed`, which knows whether // this patch's copy still stands. assert_eq!( line(Standing::Wired, &[LINUX]), @@ -14155,6 +16343,7 @@ mod tests { gem: "nokogiri@1.18.10", from: BuildsFrom::Locked(&platforms), standing, + held: Vec::new(), }; let (code, detail) = unwrap_refused(*no_builds_listed_skip(&trees)); assert_eq!(code, "vendor_prebuilt_platform_pending"); @@ -14209,19 +16398,17 @@ mod tests { false, Some(cfg), hosted, + None, &mut Vec::new(), ) .await; unwrap_refused(outcome) } - const NEEDS: &str = "Vendored mode needs every locked platform"; - let pass_through = Served { - listed: Listed::PassThrough, - ..served(LINUX) - }; + const NEEDS: &str = + "Vendored mode needs a gem, patched or upstream's own, for every locked platform"; let cases: [(Vec, String); 3] = [ ( - vec![served(DARWIN), pass_through], + vec![served(DARWIN), unserved(LINUX, "pending_build")], format!( "nokogiri@1.18.10 is not vendored: no patched build yet for \ x86_64-linux-gnu (arm64-darwin has one). {NEEDS}; the gem stays hosted." @@ -14774,13 +16961,13 @@ mod tests { check_vendored_artifact(&root, &entry, &record).await, ArtifactHealth::Healthy ); - // A second run is in sync and asks the service nothing. + // A second run is in sync and asks for the fix's list alone. let requests = ts::request_count(&server).await; let (again, rerun_entry, warnings) = unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); assert!(again.success, "{:?}", again.error); assert!(rerun_entry.is_none() && warnings.is_empty(), "{warnings:?}"); - assert_eq!(ts::request_count(&server).await, requests); + assert_eq!(ts::request_count(&server).await, requests + 1); // Without the inventory the files of each tree's own patch // vouch for it: the binary that patch built is in the tree. @@ -14957,6 +17144,23 @@ mod tests { .await .expect_err("an edited ledger entry is refused"); assert!(format!("{refused:?}").contains(why), "{refused:?}"); + // Only the list that names another patch has a remedy, the + // scan that vendors the copy again from it, named once and + // with no rollback before it. + let replaced = why.starts_with("the gem's fix"); + assert_eq!( + refused.detail().ends_with( + "Nothing was restored. Run `socket-patch scan --mode vendored`, which \ + vendors what the patch service serves now" + ), + replaced, + "{refused}" + ); + assert_eq!( + refused.detail().matches("`socket-patch ").count(), + usize::from(replaced), + "{refused}" + ); assert!(!tree.exists(), "nothing is unpacked: {why}"); assert_eq!(downloads(&server).await.len(), fetched, "{why}"); } @@ -14983,7 +17187,8 @@ mod tests { } // An in-sync re-run puts back metadata that went missing, asks - // the service nothing, and leaves a dry run's tree alone. + // the service for the fix's list alone (the dry run and the + // wet run once each), and leaves a dry run's tree alone. let requests = ts::request_count(&server).await; for (file, _) in metadata { tokio::fs::remove_file(uuid_dir.join(file)).await.unwrap(); @@ -15000,7 +17205,7 @@ mod tests { for (file, text_of) in metadata { assert_eq!(text(uuid_dir.join(file)).await, text_of, "re-run: {file}"); } - assert_eq!(ts::request_count(&server).await, requests); + assert_eq!(ts::request_count(&server).await, requests + 2); } /// A restore checks each download against the digest the ledger @@ -15041,11 +17246,15 @@ mod tests { .await .expect_err("a download that is not the recorded one"); assert!( - err.starts_with("vendor_prebuilt_integrity_mismatch"), + err.detail() + .starts_with("vendor_prebuilt_integrity_mismatch"), + "{err}" + ); + assert!(err.detail().contains(says), "{err}"); + assert!( + err.detail().contains("nokogiri (x86_64-linux-gnu)"), "{err}" ); - assert!(err.contains(says), "{err}"); - assert!(err.contains("nokogiri (x86_64-linux-gnu)"), "{err}"); assert_eq!(ts::tree_snapshot(&root), before); } } @@ -15158,9 +17367,11 @@ mod tests { assert!(!root.join(format!(".socket/vendor/gem/{UUID_B}")).exists()); } - /// A newer patch of a gem already vendored, with a locked platform - /// that has no patched build yet: the copy of the earlier patch - /// stays wired and untouched, and the skip's one line says so. + /// A newer patch of a gem already vendored, which has no patched + /// build yet for a platform the vendored copy holds one for: the + /// gem does not move to a fix that patches fewer of its locked + /// builds. The copy of the earlier patch stays wired and + /// untouched, and the skip's one line says so. #[tokio::test] async fn a_newer_patch_with_an_unpatched_platform_keeps_the_earlier_copy() { let (_tmp, root, record_a) = project(&lock(None)).await; @@ -15183,9 +17394,9 @@ mod tests { assert_eq!(code, "vendor_prebuilt_platform_pending", "{detail}"); assert_eq!( detail, - "nokogiri@1.18.10 was not brought up to date: no patched build yet for \ - x86_64-linux-gnu (arm64-darwin has one). Vendored mode needs every locked \ - platform; its vendored copy of an earlier patch stays in force as it is." + "nokogiri@1.18.10 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." ); assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); } diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 29e3026531..d3c3ec8f2b 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -728,16 +728,19 @@ pub const VENDOR_PREBUILT_UNAVAILABLE: &str = "vendor_prebuilt_unavailable"; /// no older vendored patch to keep. pub const VENDOR_PREBUILT_REQUIRED: &str = "vendor_prebuilt_required"; -/// gem: `Gemfile.lock` pins the gem as precompiled platform gems and at -/// least one of the locked platforms has no patched build: the gem -/// patch's registry serves upstream's own gem for it or does not list it, -/// or the patch it names for that build is not served (still being built, -/// or not granted). A patched build is named and served only once it is +/// gem: `Gemfile.lock` pins the gem as precompiled platform gems and the +/// gem cannot be vendored for them yet: no locked platform has a patched +/// build (the gem patch's registry serves upstream's own gem for each), +/// the registry does not list one of them, the patch it names for a build +/// is not served (still being built, or not granted), or a newer fix has +/// no patched build for a platform the vendored copy of an earlier patch +/// holds one for. A patched build is named and served only once it is /// published, so "not yet" and "never" look the same from here: the /// package is left as it is and the /// run does not fail because of it, whether or not an earlier vendored /// copy stays in force (the detail says which). A re-run vendors it once -/// every locked platform has one. +/// the registry lists a gem for every locked platform, a patched build +/// for at least one of them, and serves each build it names. pub const VENDOR_PREBUILT_PLATFORM_PENDING: &str = "vendor_prebuilt_platform_pending"; /// Whether `code` marks a patch the service does not serve (yet): diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index f35b366e5b..64ba1fce9c 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -70,13 +70,89 @@ pub(super) fn ledger_blocks_restore(entry: &VendorEntry) -> Option { None } +/// Why [`restore`] did not restore an entry's artifact, each with what to +/// say of it (`: ` where the backend names a code). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RestoreError { + /// gem: the copy cannot be restored AS IT WAS VENDORED because the + /// list of the gem's fix names another build for a platform than the + /// entry records (`vendor_prebuilt_replaced`). Nothing is wrong with + /// the service or the download: a run that vendors takes the copy + /// from the list as it is now, which comes with the refusal so that + /// the run does not ask for it again. + ListMoved(String, super::gem::FixList), + /// Every other reason. + Failed(String), +} + +impl RestoreError { + /// What to say of it. + pub fn detail(&self) -> &str { + match self { + RestoreError::ListMoved(detail, _) | RestoreError::Failed(detail) => detail, + } + } +} + +impl std::fmt::Display for RestoreError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.detail()) + } +} + +impl From for RestoreError { + fn from(detail: String) -> Self { + RestoreError::Failed(detail) + } +} + +impl From<&str> for RestoreError { + fn from(detail: &str) -> Self { + RestoreError::Failed(detail.to_string()) + } +} + +/// The list of its gem's fix that [`restore`] of `entry` would be refused +/// over because it moved ([`RestoreError::ListMoved`]): what a dry run +/// asks in place of the restore. ONE request, nothing downloaded or +/// written. `None` when the restore would not be refused for that, for +/// every entry that is not a gem vendored as platform gems, and offline. +pub async fn restore_refused_over( + entry: &VendorEntry, + record: &PatchRecord, + service: &VendorServiceConfig, +) -> Option { + if !super::gem::follows_list(entry, &record.uuid) + || super::common::service_offline_conflict(Some(service)).is_some() + { + return None; + } + let (name, version) = parse_gem_purl(&entry.base_purl)?; + super::gem::recorded_list_moved(service, &record.uuid, &name, &version, &entry.gem_builds).await +} + /// Restore only the recorded artifact. Project wiring and ledger are never written. pub async fn restore( root: &Path, entry: &VendorEntry, record: &PatchRecord, service: &VendorServiceConfig, -) -> Result, String> { +) -> Result, RestoreError> { + let restored = restore_with_list(root, entry, record, service).await; + restored.map(|(warnings, _)| warnings) +} + +/// [`restore`], which also hands back the list of the gem's fix it read +/// for a gem vendored as platform gems (`None` for every other entry). A +/// run that goes on to the gem's backend hands it that list, so the copy +/// is restored and then judged by one answer. +pub async fn restore_with_list( + root: &Path, + entry: &VendorEntry, + record: &PatchRecord, + service: &VendorServiceConfig, +) -> Result<(Vec, Option), RestoreError> { + let mut gem_list = None; let ecosystem = super::ecosystem_dir_for_purl(&entry.base_purl); if ecosystem != Some(layout::ledger_ecosystem(&entry.ecosystem)) { return Err("ledger package identity does not match its artifact ecosystem".into()); @@ -87,16 +163,17 @@ pub async fn restore( return Err(format!( "vendor_dir_symlink_unsupported: {}", super::path::vendor_dir_symlink_detail(&link) - )); + ) + .into()); } if let Some(outcome) = super::common::service_offline_conflict(Some(service)) { - return Err(detail(outcome)); + return Err(detail(outcome).into()); } // A JVM tree belongs to its build root: repairing from a subproject // would restore it where the real build never looks (#428). if entry.ecosystem == layout::LEDGER_ECOSYSTEM { if let Some(detail) = super::maven_repo::not_build_root(root) { - return Err(format!("vendor_jvm_shape_unsupported: {detail}")); + return Err(format!("vendor_jvm_shape_unsupported: {detail}").into()); } } let artifact = match super::verify::checked_artifact_path(root, entry, record) { @@ -114,13 +191,13 @@ pub async fn restore( &record.uuid, )?) } - Err(reason) => return Err(reason), + Err(reason) => return Err(reason.into()), }; if crate::utils::containment::linked_level(root, &root.join(&entry.artifact.path)).is_some() { return Err("vendor_path_unsafe: artifact path contains a symlink".into()); } if let Some(detail) = ledger_blocks_restore(entry) { - return Err(detail); + return Err(detail.into()); } let file_shaped = !super::verify::is_vlt_dir_entry(entry) && super::verify::artifact_is_file_shaped(&entry.artifact.path); @@ -255,41 +332,54 @@ pub async fn restore( // A gem vendored as platform gems is restored tree by tree, // each from the patch the gem's fix names for its platform // today, which must be the one the ledger records, and - // against the digests recorded with it. - let copied = match entry.gem_builds.as_slice() { - [] => { - super::gem::gem_service_copy( - Some(service), - record, - &name, - &stage, - uuid_dir, - true, - &mut warnings, - ) - .await - } + // against the digests recorded with it. The fix's list is + // read once, here: a refusal over it hands it on. + match entry.gem_builds.as_slice() { + [] => super::gem::gem_service_copy( + Some(service), + record, + &name, + &stage, + uuid_dir, + true, + &mut warnings, + ) + .await + .map_err(|outcome| detail(*outcome))?, builds => { + let fix = record.uuid.as_str(); + let list = super::gem::restore_list(service, fix, &name, &version) + .await + .map_err(|outcome| detail(*outcome))?; let trees = super::gem::PlatformTrees { gem: &format!("{name}@{version}"), - from: super::gem::BuildsFrom::Recorded(builds), + from: super::gem::BuildsFrom::Recorded(builds, &list), standing: super::gem::Standing::Wired, + held: Vec::new(), }; - super::gem::gem_platform_service_copy( + let copied = super::gem::gem_platform_service_copy( Some(service), record, &name, &trees, + None, &stage, uuid_dir, true, &mut warnings, ) - .await - .map(|_| ()) + .await; + if let Err(outcome) = copied { + let moved = super::gem::is_list_moved(&outcome); + let detail = detail(*outcome); + return Err(match moved { + true => RestoreError::ListMoved(detail, list), + false => RestoreError::Failed(detail), + }); + } + gem_list = Some(list); } - }; - copied.map_err(|outcome| detail(*outcome))?; + } } "npm" => { let (name, version) = super::npm_common::parse_npm_purl(&entry.base_purl) @@ -338,12 +428,7 @@ pub async fn restore( return Err("server module does not carry the patched files".into()); } } - _ => { - return Err(format!( - "unsupported artifact ecosystem {}", - entry.ecosystem - )) - } + _ => return Err(format!("unsupported artifact ecosystem {}", entry.ecosystem).into()), } { let inventory = entry @@ -399,6 +484,22 @@ pub async fn restore( warnings.push(warning); } } + // A gem vendored as platform gems is finished as on every path + // that places its trees, before they are moved in: the uuid dir's + // metadata (a write that fails is a warning), then git's word on + // the commit. Refused, the copy is as it was. + if entry.ecosystem == "gem" && !file_shaped && !entry.gem_tree_platforms().is_empty() { + let copy_rel = entry.artifact.path.replace('\\', "/"); + let placing = super::gem::CopyStep::Placing(&stage); + let finished = + super::gem::finish_platform_copy(root, ©_rel, placing, false, &mut warnings); + if let Err(refusal) = finished.await { + if let Some(real_uuid_dir) = artifact.parent() { + super::gem::remove_metadata_alone(real_uuid_dir).await; + } + return Err(detail(refusal).into()); + } + } let swapped = if file_shaped { let result = tokio::fs::rename(&stage, &artifact).await; if result.is_ok() { @@ -413,7 +514,7 @@ pub async fn restore( let _ = super::vlt_lock::keep_vlt_links(entry, &temporary.path().join(rel), root).await; } - return Err(error.to_string()); + return Err(error.to_string().into()); } } restore_npm_uuid_metadata(entry, root) @@ -428,11 +529,9 @@ pub async fn restore( .map_err(|e| e.to_string())?; } } - // Likewise a gem vendored as platform gems: only the artifact dir was - // swapped in from the stage, and without the uuid dir's own metadata a - // `*.so` / `*.bundle` rule drops the compiled binaries from the commit. - let archive = super::gem::bazel::is_archive(entry); - if entry.ecosystem == "gem" && (archive || !entry.gem_tree_platforms().is_empty()) { + // Likewise a gem committed as its archive: only the artifact was + // swapped in from the stage. + if entry.ecosystem == "gem" && super::gem::bazel::is_archive(entry) { if let Some(rel) = super::path::vendor_uuid_dir_rel("gem", &entry.uuid) { super::gem::restore_uuid_metadata(&root.join(rel)) .await @@ -445,7 +544,7 @@ pub async fn restore( if entry.flavor.as_deref() == Some(super::maven_repo::HUB_FLAVOR) { super::maven_repo::restore_hub_files(root, entry).await?; } - Ok(warnings) + Ok((warnings, gem_list)) } /// Rewrite an npm-family entry's `/.gitignore` and @@ -1057,7 +1156,7 @@ mod tests { .await .unwrap_err(); assert!( - error.starts_with("vendor_dir_symlink_unsupported"), + error.detail().starts_with("vendor_dir_symlink_unsupported"), "{error}" ); assert!(server.received_requests().await.unwrap().is_empty()); @@ -1082,9 +1181,11 @@ mod tests { let error = restore(root.path(), &entry, &record(), &cfg) .await .unwrap_err(); - assert!(error.contains("no archive SHA-256"), "{error}"); + assert!(error.detail().contains("no archive SHA-256"), "{error}"); assert!( - error.contains(super::super::common::REVERT_ALL_AND_REVENDOR), + error + .detail() + .contains(super::super::common::REVERT_ALL_AND_REVENDOR), "the refusal names the remedy that records a new fingerprint: {error}" ); assert!(server.received_requests().await.unwrap().is_empty()); @@ -1116,6 +1217,7 @@ mod tests { assert!(restore(root.path(), &entry, &record(), &cfg) .await .unwrap_err() + .detail() .contains("recorded SHA-256")); assert_eq!(tree_snapshot(root.path()), before); server.reset().await; @@ -1149,6 +1251,7 @@ mod tests { ) .await .unwrap_err() + .detail() .contains("hash_mismatch")); assert!(!root.path().join(&entry.artifact.path).exists()); } @@ -1214,13 +1317,16 @@ mod tests { ) .await .unwrap_err(); - assert!(error.contains("no complete file inventory"), "{error}"); assert!( - error.contains("re-run the vendoring command"), + error.detail().contains("no complete file inventory"), + "{error}" + ); + assert!( + error.detail().contains("re-run the vendoring command"), "the refusal names the remedy that rebuilds the copy: {error}" ); assert!( - !error.contains("--revert"), + !error.detail().contains("--revert"), "no revert is needed for a dir copy: {error}" ); assert!(server.received_requests().await.unwrap().is_empty()); @@ -1234,6 +1340,7 @@ mod tests { ) .await .unwrap_err() + .detail() .contains("identity")); assert_eq!(tree_snapshot(root.path()), before); } @@ -1301,7 +1408,7 @@ mod tests { let error = restore(root.path(), &entry, &record(), &cfg) .await .unwrap_err(); - assert!(error.contains(expected), "{status}: {error}"); + assert!(error.detail().contains(expected), "{status}: {error}"); assert_eq!(tree_snapshot(root.path()), before, "{status}"); } } diff --git a/crates/socket-patch-core/src/vendor/service_fetch.rs b/crates/socket-patch-core/src/vendor/service_fetch.rs index 0a72fe5464..033f3270ef 100644 --- a/crates/socket-patch-core/src/vendor/service_fetch.rs +++ b/crates/socket-patch-core/src/vendor/service_fetch.rs @@ -126,6 +126,9 @@ pub(crate) struct ServedReference { /// serves them, each with the patch of its patched build if it has /// one; `None` when the reference carries no list. pub gem_builds: Option>, + /// gem: the index URL of that registry, which serves the gem file of + /// each platform it lists at `gems/`. + pub gem_index_url: Option, } impl ServedReference { @@ -141,6 +144,7 @@ impl From for ServedReference { archive: reference.archive, secondary: reference.secondary, gem_builds: reference.gem_builds, + gem_index_url: reference.gem_index_url, } } } @@ -243,6 +247,28 @@ pub(crate) async fn fetch_served_reference( served_reference(outcome) } +/// [`fetch_served_reference`] as an advisory question, for a caller that +/// leaves things as they are when it gets no answer: one short attempt, +/// outside the retry ladder and the circuit breaker +/// ([`crate::api::client::ApiClient::fetch_vendor_reference_once`]). +pub(crate) async fn ask_served_reference( + cfg: &VendorServiceConfig, + uuid: &str, +) -> ServiceArtifact { + let Some(client) = cfg.client.as_ref() else { + return ServiceArtifact::Unavailable("vendor service not configured".to_string()); + }; + let outcome = client + .fetch_vendor_reference_once( + uuid, + cfg.use_public_proxy, + cfg.vendor_url.as_deref(), + cfg.patch_server_url.as_deref(), + ) + .await; + served_reference(outcome) +} + /// Why the service does not serve one patch of a /// [`fetch_served_references`] batch, when it answered for that patch: the /// status of the patch's own reference, which says nothing of the request. @@ -458,6 +484,25 @@ pub(crate) async fn fetch_verified_secondary( pub(crate) async fn fetch_verified_artifact( cfg: &VendorServiceConfig, artifact: Option<&SecondaryArtifact>, +) -> SecondaryArtifactResult { + fetch_verified(cfg, artifact, false).await +} + +/// [`fetch_verified_artifact`] for a gem file a patch registry lists as +/// upstream's own: it is taken from the patch service alone, so no +/// redirect is followed +/// ([`crate::api::client::ApiClient::download_registry_gem`]). +pub(crate) async fn fetch_verified_registry_gem( + cfg: &VendorServiceConfig, + artifact: &SecondaryArtifact, +) -> SecondaryArtifactResult { + fetch_verified(cfg, Some(artifact), true).await +} + +async fn fetch_verified( + cfg: &VendorServiceConfig, + artifact: Option<&SecondaryArtifact>, + registry_gem: bool, ) -> SecondaryArtifactResult { let Some(client) = cfg.client.as_ref() else { return SecondaryArtifactResult::Failed("vendor service not configured".to_string()); @@ -470,6 +515,7 @@ pub(crate) async fn fetch_verified_artifact( // live request (its debug lines print here, where this call's would). let downloaded = match artifact.prefetched.as_ref().and_then(|p| p.take()) { Some(held) => held.release(), + None if registry_gem => client.download_registry_gem(&artifact.url).await, None => client.download_artifact(&artifact.url).await, }; let bytes = match downloaded { diff --git a/crates/socket-patch-core/src/vendor/state.rs b/crates/socket-patch-core/src/vendor/state.rs index d0a237202f..1c946c8642 100644 --- a/crates/socket-patch-core/src/vendor/state.rs +++ b/crates/socket-patch-core/src/vendor/state.rs @@ -360,10 +360,29 @@ pub struct GemBuildEntry { /// `Gem::Platform#to_s` as `Gemfile.lock` spells it. pub platform: String, /// The patch of this platform gem: the one the tree was unpacked from. + /// Absent for a tree of upstream's own gem ([`Self::is_upstream`]): a + /// locked platform that had no patched build when the gem was + /// vendored. Such a tree is the gem the patch registry lists for the + /// platform, unchanged, with the gemspec that gem carries. It records + /// no patch, no gemspec digest and no files: nothing in it is patched, + /// the copy's file inventory vouches for every byte of it as it does + /// for a patched tree, and its gem digest is what a restore fetches + /// it again by. + /// + /// Older readers: one that requires a patch of every tree (the first + /// to record `gemBuilds`) fails on the entry. One that knows no + /// `gemBuilds` ignores the key and judges the trees it finds on disk + /// by the files of the gem's patch and the copy's inventory, under + /// which a tree that ships none of the patched files passes: it + /// would take a tree of upstream's gem for a patched one whenever that + /// gem ships none of them. A project vendored this way must not be + /// attested by a CLI that does not read this entry. + #[serde(default, skip_serializing_if = "String::is_empty")] pub uuid: String, - /// The sha512 (SRI) of the patched platform `.gem` the tree was - /// unpacked from, as the patch service stated it and the download was - /// verified against. + /// The digest (SRI) of the platform `.gem` the tree was unpacked + /// from, which the download was verified against: the sha512 the + /// patch service states for a patched build, the sha256 the patch + /// registry lists for upstream's gem. #[serde(default, skip_serializing_if = "String::is_empty")] pub gem_integrity: String, /// The sha512 (SRI) of the stub gemspec the tree holds, likewise. @@ -381,6 +400,12 @@ pub struct GemBuildEntry { } impl GemBuildEntry { + /// Whether this is a tree of upstream's own gem, which no patch + /// stands behind ([`Self::uuid`]). + pub fn is_upstream(&self) -> bool { + self.uuid.is_empty() + } + /// The purl of this platform gem of the gem `base_purl`: /// `pkg:gem/@?platform=`. pub fn purl(&self, base_purl: &str) -> String { @@ -404,19 +429,18 @@ impl VendorEntry { /// gem: the files the tree of `platform` is verified against: those of /// that platform's own patch where the ledger records them - /// ([`GemBuildEntry::files`]), else `fallback`, the gem patch's. + /// ([`GemBuildEntry::files`]), else `fallback`, the gem patch's. None + /// for a tree of upstream's own gem, which holds no patched file. pub fn gem_tree_files( &self, platform: &str, fallback: &HashMap, ) -> HashMap { - self.gem_builds - .iter() - .find(|built| built.platform == platform && !built.files.is_empty()) - .map_or_else( - || fallback.clone(), - |built| built.files.clone().into_iter().collect(), - ) + match self.gem_builds.iter().find(|b| b.platform == platform) { + Some(built) if built.is_upstream() => HashMap::new(), + Some(built) if !built.files.is_empty() => built.files.clone().into_iter().collect(), + _ => fallback.clone(), + } } /// gem: the platforms of a copy vendored as precompiled platform gems diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 6f432cdc86..0cfa8de7e6 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -22,7 +22,7 @@ below is about what a package manager installs and builds. | PyPI (`pypi`) — uv / poetry / pdm / pipenv / pip | ✅ in place | ✅ uv project/script locks, PEP 751 `pylock.toml` / `pylock..toml`, poetry, pdm, pipenv (Pipenv 2018 or later — every `Pipfile.lock` category is rewired, lock-only checkouts included; Pipenv 2023+ does not hash-check local wheels — `vendor_integrity_unverified`; Pipenv 2023.7.9+ exports the vendored wheel without a hash, so `pipenv requirements --hash` output fails pip's hash-checking mode — `pypi_pipenv_hash_export_unsupported`; a venv still holding the upstream release is reported as `pypi_pipenv_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)), and requirements.txt. Native uv vendoring requires uv ≥ 0.2.35 (the `[[package]]` lock grammar); hosted mode covers native `uv.lock` from uv 0.1.45 (the first release whose `uv lock` writes one) and requirements from uv 0.0.5; see [uv compatibility](testing/uv-compatibility.md). Declined where a rules_python hub of a Bazel workspace reads the file, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ requirements.txt including hash continuations, uv project/script locks, and PEP 751 locks. Version/source ambiguity is refused; see [uv compatibility](testing/uv-compatibility.md). Poetry 1.x and 2.x locks are supported; Poetry 0.x ignores URL sources and is refused. See [Poetry compatibility](testing/poetry-compatibility.md). Pipenv `Pipfile.lock` (pipfile-spec 6 — Pipenv 7 and later; `path` references for 7–11, `file` from 2018; lock-only checkouts and Pipenv's out-of-tree venv are discovered; a warm venv that Pipenv will not reinstall over warns `redirect_pypi_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)). `pdm.lock` is supported for the lock formats PDM 0.12–1.4 and 2.8.1+ write (`lock_version` 2 / 4.3–4.5.1); the identity-losing 3.1 / 4.0–4.2 formats (PDM 1.8–2.7) are refused. PDM 2.8.0 writes an indistinguishable `4.3` lock but shares that identity-loss bug, so a rewritten 2.8.0 lock crashes `pdm sync` — upgrade to ≥ 2.8.1. See [PDM compatibility](testing/pdm-compatibility.md). | | pixi (`pypi`) — the Python packages of a pixi project, from conda channels or PyPI | ✅ in place, in every environment under `.pixi/envs`: PyPI wheels and pure-Python conda packages (compiled conda packages are not supported yet and are skipped) — see [PyPI: pixi projects](#pypi-pixi-projects) | ❌ refused (`pypi_no_requirements` / `pypi_pyproject_only`, which name agent mode) | ❌ nothing rewritten (`redirect_pypi_pixi_project` names agent mode) | | Cargo (`cargo`) | ✅ in-place + `.cargo-checksum.json` rewrite (shared registry-cache caveat — see [Cargo: shared registry cache](#cargo-shared-registry-cache)) | ✅ `[patch.crates-io]` path entry in the root `Cargo.toml` (v5; per-version Socket keys; pre-v5 `.cargo/config*` wiring migrates on re-run) | ✅ per-patch sparse registry (`[registries.socket-patch-]` + Cargo.lock source/checksum); needs cargo 1.68+ (sparse registries) — a project whose `rust-version` or `rust-toolchain[.toml]` declares an older cargo is refused (`redirect_cargo_old_cargo`), use `--mode vendored`; direct dependencies only — a crate another dependency also pulls in is refused, use `--mode vendored`; a crate the user overrides with `[patch]` (path, git or another registry) is refused too, the override is left alone; a `cargo vendor` or `cargo local-registry` project (crates.io replaced by an on-disk source in the project's, a parent directory's or `$CARGO_HOME`'s `.cargo/config*`) is refused, use agent mode; with no `Cargo.lock` the graph is unknown, so only a project whose sole dependency is the patched crate is redirected; in a Bazel workspace a crate is not pinned while a rules_rust hub reads the project's Cargo files without its cargo config (`redirect_cargo_bazel_config_unread`), see [Bazel workspaces: Cargo](#bazel-workspaces-cargo) | -| RubyGems (`gem`) | ✅ in place | ✅ Gemfile + Gemfile.lock path pair (a CRLF `Gemfile.lock`, as a `core.autocrlf` checkout leaves it, is edited and reverted in its own line ending, and a lock mixing CRLF and LF fails closed; a gem locked as precompiled platform gems is vendored from the patched platform gems, see [Ruby gems: native extensions](#ruby-gems-native-extensions); `Gemfile` spelling only — a `gems.rb` twin, which bundler ≥ 2 loads instead, or a `BUNDLE_GEMFILE`-configured manifest makes vendoring refuse with `gemfile_not_loaded` before any write); declined where a rules_ruby hub of a Bazel workspace reads the pair, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ a `source:` option on the gem's own declaration, the lock converged to match (see [Ruby gems: hosted mode](#ruby-gems-hosted-mode)) — edits `gems.rb` + `gems.locked` or `Gemfile` + `Gemfile.lock`, whichever the project holds (a `Gemfile` + `gems.rb` twin is refused with `redirect_gem_twin_manifest_ambiguous`: bundler 1.x loads the `Gemfile`, bundler ≥ 2 loads `gems.rb`, and nothing in the project says which bundler installs it; bundler 4's `BUNDLE_LOCKFILE` (environment, app config or global config) naming any other lock is refused with `redirect_gem_bundle_lockfile_unsupported`, as is vendoring with `gemfile_not_loaded`; spellings that diverge beyond Socket's own edits fail closed with `redirect_gem_gemfile_spellings_diverge`; `BUNDLE_GEMFILE` from `.bundle/config` (which outranks the environment, as in bundler), the environment, or the global `~/.bundle/config` / `$BUNDLE_USER_CONFIG` (lowest, as in bundler) is followed when it names the project's `Gemfile` / `gems.rb`, and any other configured manifest is refused with `redirect_gem_bundle_gemfile_unsupported`); a Bundler all-source, exact-source or hostname mirror in app config or the scan environment can capture the patch registry, so the redirect is refused with `redirect_gem_mirror_overrides_source` without printing mirror URLs (scope mirrors to `mirror.https://rubygems.org`; user-global config and mirrors set only in a later install environment are not inspected); the `CHECKSUMS` pin needs bundler ≥ 2.6 (an older lock is still pinned by source and installs frozen; the run says once, with `redirect_gem_no_checksums_section`, that it cannot record the checksums); a stale pre-redirect materialization that `bundle install` would reuse instead of refetching is replaced with the verified patched gem when it is the project's own, else flagged `redirect_gem_stale_install` with the remedy (see "Ruby gems: gems already installed" below and CLI_CONTRACT.md's "Gem stale-install guard"). In a Bazel workspace whose rules_ruby call holds the gem to another sha256 in `gem_checksums`, or has a `gem_checksums` that is not written out in the call, nothing is written for it (`redirect_bazel_gem_checksums_pinned`); see [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems) | +| RubyGems (`gem`) | ✅ in place | ✅ Gemfile + Gemfile.lock path pair (a CRLF `Gemfile.lock`, as a `core.autocrlf` checkout leaves it, is edited and reverted in its own line ending, and a lock mixing CRLF and LF fails closed; a gem locked as precompiled platform gems is vendored from the patched platform gems, with upstream's own gem for a platform that has no patched build yet, see [Ruby gems: native extensions](#ruby-gems-native-extensions); `Gemfile` spelling only — a `gems.rb` twin, which bundler ≥ 2 loads instead, or a `BUNDLE_GEMFILE`-configured manifest makes vendoring refuse with `gemfile_not_loaded` before any write); declined where a rules_ruby hub of a Bazel workspace reads the pair, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ a `source:` option on the gem's own declaration, the lock converged to match (see [Ruby gems: hosted mode](#ruby-gems-hosted-mode)) — edits `gems.rb` + `gems.locked` or `Gemfile` + `Gemfile.lock`, whichever the project holds (a `Gemfile` + `gems.rb` twin is refused with `redirect_gem_twin_manifest_ambiguous`: bundler 1.x loads the `Gemfile`, bundler ≥ 2 loads `gems.rb`, and nothing in the project says which bundler installs it; bundler 4's `BUNDLE_LOCKFILE` (environment, app config or global config) naming any other lock is refused with `redirect_gem_bundle_lockfile_unsupported`, as is vendoring with `gemfile_not_loaded`; spellings that diverge beyond Socket's own edits fail closed with `redirect_gem_gemfile_spellings_diverge`; `BUNDLE_GEMFILE` from `.bundle/config` (which outranks the environment, as in bundler), the environment, or the global `~/.bundle/config` / `$BUNDLE_USER_CONFIG` (lowest, as in bundler) is followed when it names the project's `Gemfile` / `gems.rb`, and any other configured manifest is refused with `redirect_gem_bundle_gemfile_unsupported`); a Bundler all-source, exact-source or hostname mirror in app config or the scan environment can capture the patch registry, so the redirect is refused with `redirect_gem_mirror_overrides_source` without printing mirror URLs (scope mirrors to `mirror.https://rubygems.org`; user-global config and mirrors set only in a later install environment are not inspected); the `CHECKSUMS` pin needs bundler ≥ 2.6 (an older lock is still pinned by source and installs frozen; the run says once, with `redirect_gem_no_checksums_section`, that it cannot record the checksums); a stale pre-redirect materialization that `bundle install` would reuse instead of refetching is replaced with the verified patched gem when it is the project's own, else flagged `redirect_gem_stale_install` with the remedy (see "Ruby gems: gems already installed" below and CLI_CONTRACT.md's "Gem stale-install guard"). In a Bazel workspace whose rules_ruby call holds the gem to another sha256 in `gem_checksums`, or has a `gem_checksums` that is not written out in the call, nothing is written for it (`redirect_bazel_gem_checksums_pinned`); see [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems) | | Go (`golang`) | ✅ `go.mod` `replace` → `.socket/go-patches/` — see [Go: directory replaces and go.sum](#go-directory-replaces-and-gosum) | ✅ `replace` → the committed vendor tree | ✅ (free tier) fork-style `replace` → `patch.socket.dev/gopatch/` + committed `go.sum` pin; see [Go notes](#go-directory-replaces-and-gosum). Paid hosted patches are unsupported; `redirect_golang_unsupported` names the vendored remedy | | Maven (`maven`) — Maven and Gradle | ✅ in place in every copy the build consumes: each `~/.m2` copy it reads and each Gradle `files-2.1` copy; `~/.m2` `.sha1`/`.md5` sidecars are rewritten, Gradle copies get advisories; jar-member records swap in the patch service's whole jar — prefer vendored / hosted, see [Maven & NuGet caveats](#maven--nuget-caveats) and [Gradle](#gradle) | ✅ suffixed Maven repository (`-socket.` pin + `.mvn/maven.config` + fallback file repository) for every pom root, single-module or reactor, or Gradle 6.8+ same-GAV repository with settings wiring and SHA-256 checks (a root with both `pom.xml` and a Gradle build wires both); see [JVM vendoring](design/maven-vendoring.md) and [Gradle](#gradle) | ✅ fail-closed by a Socket-only `-socket.` suffix: pom projects get a pinned `` (`${property}` versions are refused); Gradle 6.8+ builds get an owned settings script, lock-entry rewrites and a resolution tripwire — see [Maven & NuGet caveats](#maven--nuget-caveats) and [Gradle](#gradle) | | sbt / Mill / scala-cli (`maven`) | ✅ Coursier caches (sbt 1.3+, sbt 2, Mill, scala-cli) and Ivy caches (sbt 0.13–1.2, `useCoursier := false`) patched in place, Coursier checksum sidecars resynced — see [Scala build tools](#scala-build-tools-sbt-mill-scala-cli) | ✅ sbt 0.13.18+: generated `socket-patch-vendor.sbt` over the committed suffixed `.socket/vendor/maven2` tree; scala-cli directory builds: owned `socket-patch.scala` + same-GAV `.socket/vendor/coursier` tree (Linux / macOS); Mill: not wired (agent or hosted guidance) | ✅ sbt 0.13.18+: one generated `socket-patch.sbt`, gated on sbt's own `sbt update` records; Mill / scala-cli: paste-able snippets only (`redirect_mill_manual_snippet`, `redirect_scala_cli_manual_snippet`) | @@ -5234,7 +5234,7 @@ How each mode gets the patched code running: | Mode | What happens | |---|---| | Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed through the patch registry with nothing to compile: the patched platform gem where the platform has one, upstream's own gem where it has none yet. The gem moves as soon as one locked platform has a patched build, and the run names the platforms that are patched and the ones that keep upstream's gem. | -| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. Every platform in the lock needs a patched build. While one has none the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) names the platforms without a patched build and says that hosted mode can patch the others now. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once every platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. socket-patch 5.1.0 and earlier have no platform-gem vendoring and do not read such a copy: on 5.1.0 `vendor --check` fails on it and `vex` leaves the gem out of the document. Check and attest a project vendored this way (`vendor --check`, `vex`) with the release that vendored it or a later one. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | +| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org, and without following a redirect), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. Only a socket-patch release that contains this support and the platform-gem vendoring it builds on reads such a copy. 5.1.0 and earlier have no platform-gem vendoring and do not read such a copy: on 5.1.0 `vendor --check` fails on it and `vex` leaves the gem out of the document. Attest a project vendored this way (`vex`, `vendor --check`) with the release that vendored it or a later one. A later scan asks the patch registry which builds it lists (one small request per gem vendored this way: a single short attempt, which a patch service that is down cannot turn into a failure) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. A vendored copy that is intact is never made worse by this: when the registry cannot be asked the copy is left as it is, and when a newly listed build cannot be vendored (a failed download, a digest that does not match) the copy stays in force, the run exits 0 and one note says so (`vendor_gem_list_not_followed`). The run checks that the copy still stands before it says that; a rebuild that fails after it changed the copy is reported as a failure, and the next scan vendors the copy again. A copy that is damaged after the registry's list changed is vendored again from the current list by the next scan. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. A run that cannot write those two files says so and goes on (`vendor_gem_git_metadata_unwritten`: make them writable and run again); where git would then leave a binary out of the commit, the new files are not put in place and the run names the two files. Git is asked only when files are about to be placed, never about a copy that is already there. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | | Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, diff --git a/tests/nokogiri/nokogiri_e2e.rb b/tests/nokogiri/nokogiri_e2e.rb index f2d9ca1b2b..2269797183 100644 --- a/tests/nokogiri/nokogiri_e2e.rb +++ b/tests/nokogiri/nokogiri_e2e.rb @@ -533,11 +533,17 @@ def scenario(name) # patched nothing moves. Once the service has the builds that # were missing, the next scan moves the lock to the newer # registry snapshot and the install is the patched gem. - # vendored The scan commits the patched platform gem of every locked - # platform, each from its own patch, and a fresh checkout - # installs from that tree with the service unreachable. While - # a locked platform has no patched build nothing is vendored: - # the run says so and exits 0. + # vendored The scan commits one tree per locked platform: the patched + # platform gem, from its own patch, where the platform has a + # patched build, and upstream's own gem, which the patch + # registry serves, where it has none yet. A fresh checkout + # installs from those trees with the service unreachable, and + # Ruby there loads the patched gem where this machine's + # platform has one and upstream's own where it has none. Once + # the service has the builds that were missing, the next scan + # puts their trees in place. While no locked platform has a + # patched build nothing is vendored: the run says so and + # exits 0. # # Either way the scenario ends with `vex` and a `rollback` to the lock as # it was. @@ -797,8 +803,15 @@ def redirect_warnings(stdout) # The vendored scans, up to the lock that takes nokogiri from the # committed tree. Returns that lock. def vendored(service, platforms, waiting, lock, gemfile) - unless waiting.empty? - # A locked platform with no patched build: nothing is vendored. + have = platforms - waiting + if !waiting.empty? && !have.empty? && @opts[:redirect] + vendored_redirect_not_followed(service, lock, gemfile) + waiting.each { |platform| service.publish(platform) } + elsif !waiting.empty? && !have.empty? + vendored_with_upstream(service, platforms, waiting, have) + waiting.each { |platform| service.publish(platform) } + elsif !waiting.empty? + # No locked platform has a patched build: nothing is vendored. code, stdout, stderr, secs = sp_service("scan", "--mode", "vendored", "--yes", "--json") pending = events(stdout).find { |e| e["errorCode"] == "vendor_prebuilt_platform_pending" } || {} check(code.zero? && pending["action"] == "skipped", @@ -818,6 +831,14 @@ def vendored(service, platforms, waiting, lock, gemfile) code, stdout, stderr, secs = sp_service("scan", "--mode", "vendored", "--yes", "--json") said = tail(stdout) + tail(stderr) check(code.zero?, "`scan --mode vendored` succeeds (#{secs.round}s)", "exit #{code}\n#{said}") + unless waiting.empty? || have.empty? || @opts[:redirect] + # The copy held upstream's gem for these: the scan puts the patched + # builds in their place, and says so with no warning. + gained = events(stdout).select { |e| e["details"].is_a?(Hash) && e["details"]["newlyPatched"] } + .map { |e| e["details"]["platform"] } + check(gained.sort == waiting.sort && warning_codes(stdout).empty?, + "it takes the builds published since in place of upstream's gem", "#{gained.inspect}\n#{said}") + end rewritten = File.read(lock_path) check(rewritten != lock, "it rewires the lock", said) vendored = Dir.glob(File.join(@proj, ".socket", "vendor", "gem", "**", "*.gemspec")) @@ -843,9 +864,91 @@ def vendored(service, platforms, waiting, lock, gemfile) rewritten end + # The same lock against a registry that answers the file of upstream's + # gem with a redirect to the upstream registry (`--pass-through-redirect`). + # Vendored mode takes that gem from the patch service alone: the + # redirect is not followed, the gem is not served as far as the scan is + # concerned, and nothing is vendored or written. + def vendored_redirect_not_followed(service, lock, gemfile) + service.forget_requests + code, stdout, stderr, secs = sp_service("scan", "--mode", "vendored", "--yes", "--json") + said = stdout + stderr + check(!code.zero? && said.include?("could not fetch the upstream platform gem"), + "`scan --mode vendored` does not vendor the gem while the registry redirects upstream's gem (#{secs.round}s)", + "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + answers = service.requests.select { |_, path, _| path.include?("/gems/") }.map(&:last).uniq + check(answers == [302] && service.upstream_requests.empty?, + "the redirect is not followed: nothing is asked of the upstream registry", + (service.requests + service.upstream_requests).inspect) + check(File.read(lock_path) == lock && File.read(File.join(@proj, "Gemfile")) == gemfile && + !File.exist?(File.join(@proj, ".socket", "vendor", "gem")), "nothing is written") + end + + # A lock with a patched build for some platforms (`have`) and none yet for + # the others (`waiting`): the scan vendors the gem, with upstream's own + # gem for the latter, and a fresh checkout installs from the trees with + # the service unreachable. + def vendored_with_upstream(service, platforms, waiting, have) + service.forget_requests + code, stdout, stderr, secs = sp_service("scan", "--mode", "vendored", "--yes", "--json") + said = tail(stdout) + tail(stderr) + builds = events(stdout).select { |e| e["details"].is_a?(Hash) && e["details"]["gemFix"] == UUID } + kept = builds.select { |e| e["errorCode"] == "gem_upstream_build_kept" } + applied = builds.select { |e| e["action"] == "applied" } + platforms_of = lambda { |list| list.map { |e| e["details"]["platform"] }.sort } + check(code.zero? && platforms_of.call(applied) == have.sort && platforms_of.call(kept) == waiting.sort, + "`scan --mode vendored` vendors the gem: patched for #{have.join(', ')}, upstream's own gem for " \ + "#{waiting.join(', ')} (#{secs.round}s)", "exit #{code}\n#{said}") + check(kept.all? { |e| e["uuid"].nil? } && applied.all? { |e| e["uuid"] == service.uuid_of(e["details"]["platform"]) }, + "each patched build under its own patch, the others under none", builds.inspect) + check(warning_codes(stdout).empty?, "with no warning", said) + mixed = File.read(lock_path) + check(mixed =~ /^PATH\n remote: \.socket\/vendor\/gem\//, "the lock takes nokogiri from the vendored path", mixed) + gemspec = lambda do |platform| + Dir.glob(File.join(@proj, ".socket", "vendor", "gem", "*", "nokogiri-#{@version}", platform, "nokogiri.gemspec")).first + end + check(platforms.all? { |p| gemspec.call(p) }, "with a tree for each of #{platforms.size} platforms") + check(waiting.all? { |p| File.read(gemspec.call(p).to_s).start_with?("---") } && + have.none? { |p| File.read(gemspec.call(p).to_s).start_with?("---") }, + "a tree of upstream's gem carries the gemspec that gem holds") + # Upstream's gem comes from the patch registry, as its list names it. + files = waiting.map { |p| "nokogiri-#{@version}-#{p}.gem" }.sort + fetched = service.requests.select { |_, path, _| path.include?("/gems/") } + .map { |_, path, status| [File.basename(path), status] }.sort + check(fetched == files.map { |f| [f, 200] }, "upstream's gem is asked of the patch registry", fetched.inspect) + check(service.upstream_requests.empty?, "and of nothing else", service.upstream_requests.inspect) + # A later scan finds the copy in step and says which platforms are + # patched. + code, stdout, stderr, = sp_service("scan", "--mode", "vendored", "--yes") + line = stdout.gsub(/\n\s+/, " ") + check(code.zero? && line.include?("nokogiri #{@version}: patched for") && line.include?("upstream gem kept for") && + waiting.all? { |p| line.include?(p) } && File.read(lock_path) == mixed, + "a later scan changes nothing and says which platforms are patched", "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + # `vex`: a patched build is attested, a build on upstream's gem is not. + code, stdout, stderr, = sp_service("vex", "--offline", "--product", PRODUCT, "--output", File.join(@proj, "vex.json")) + statements = begin + JSON.parse(File.read(File.join(@proj, "vex.json"))).fetch("statements", []) + rescue StandardError + [] + end + status_of = lambda do |platform| + purl = "pkg:gem/nokogiri@#{@version}?platform=#{platform}" + statements.select { |st| st.to_s.include?(purl) }.map { |st| st["status"] }.uniq + end + check(code.zero? && have.all? { |p| status_of.call(p) == ["not_affected"] } && + waiting.all? { |p| status_of.call(p) == ["affected"] }, + "`vex` attests the patched builds and states the builds on upstream's gem affected", + "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + # A fresh checkout, with the patch service unreachable. + service.take_down + installs_frozen(service, "vendored", mixed, have.include?(own_platform)) + service.bring_up + end + # A fresh checkout of what the scan left to commit installs with the lock # frozen, and Ruby there loads nokogiri: the patched gem when `patched`, - # else upstream's own, which the patch registry hands on. + # else upstream's own, which the patch registry hands on (hosted) or the + # vendored tree holds (vendored). def installs_frozen(service, mode, rewritten, patched) checkout = fresh_checkout(mode == "vendored" ? [".socket"] : []) service.forget_requests @@ -861,7 +964,9 @@ def installs_frozen(service, mode, rewritten, patched) JSON.pretty_generate(now)) file = "nokogiri-#{@version}-#{own_platform}.gem" answers = service.requests.select { |_, path, _| path.end_with?("/gems/#{file}") }.map(&:last).uniq - if @opts[:redirect] + if mode == "vendored" + check(answers.empty?, "from the tree of upstream's gem the scan committed", answers.inspect) + elsif @opts[:redirect] check(answers == [302] && service.upstream_requests.include?(["GET", "/gems/#{file}", 200]), "which the patch registry answers with a redirect to the upstream registry", (service.requests + service.upstream_requests).inspect)