diff --git a/.github/workflows/nokogiri-compatibility.yml b/.github/workflows/nokogiri-compatibility.yml index 17659d19c..7a09c2536 100644 --- a/.github/workflows/nokogiri-compatibility.yml +++ b/.github/workflows/nokogiri-compatibility.yml @@ -49,6 +49,13 @@ name: nokogiri patch compatibility # of each real platform gem; then a frozen install from a fresh checkout, # `vex` and a byte-identical `rollback`. On JRuby the platform is `java`. # +# The `vendored` legs run the script's vendored scenario instead: a vendored +# scan of a lock that pins nokogiri as platform gems, against a stand-in for +# the patch service (tests/nokogiri/patch_service.rb) that serves a patched +# build of each real platform gem; then a frozen install from a fresh +# checkout with the service unreachable, `vex` and a `rollback` to the lock +# as it was. On JRuby the platform is `java`. +# # Every leg downloads gems from rubygems.org, and a rebuild of a precompiled # install downloads the source gem and `mini_portile2` from it too. # @@ -74,6 +81,11 @@ on: - 'crates/socket-patch-core/src/patch/redirect/grant.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/gem.rs' - 'crates/socket-patch-cli/src/commands/gem_refresh.rs' + # Vendored mode's gem backend. + - 'crates/socket-patch-core/src/vendor/gem.rs' + - 'crates/socket-patch-core/src/vendor/verify.rs' + - 'crates/socket-patch-core/src/vendor/redownload.rs' + - 'crates/socket-patch-core/src/vendor/service_fetch.rs' push: branches: [main] paths: @@ -161,6 +173,16 @@ jobs: - {os: ubuntu-latest, ruby: '3.1', nokogiri: '1.15.7', install: precompiled, args: '--scenarios hosted', note: hosted} - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, cli: build, args: '--scenarios hosted', note: hosted} - {os: ubuntu-latest, ruby: 'jruby-9.4', nokogiri: '1.18.10', install: java, args: '--scenarios hosted', note: hosted} + # Vendored mode on a lock that pins nokogiri as platform gems: the + # scan commits a patched build of each real platform gem, served + # by a stand-in for the patch service, under `.socket/vendor/gem`, + # and a fresh checkout installs from that tree with the lock + # frozen and the service unreachable. On JRuby the platform is + # `java`. + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, args: '--scenarios vendored', note: vendored} + - {os: ubuntu-latest, ruby: '3.1', nokogiri: '1.15.7', install: precompiled, args: '--scenarios vendored', note: vendored} + - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, cli: build, args: '--scenarios vendored', note: vendored} + - {os: ubuntu-latest, ruby: 'jruby-9.4', nokogiri: '1.18.10', install: java, args: '--scenarios vendored', note: vendored} 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 c34e774f7..0fdbc134d 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1385,7 +1385,7 @@ path. Without hosted pins the no-manifest no-op below is unchanged. **Prebuilt vendor artifacts (`--vendor-source`)**: `service` is the default and `auto` is a compatibility alias. `build` is rejected at argument parsing. There is no local construction or fallback. Package-reference POSTs on the configured API/proxy (`--vendor-url` overrides it) return the download URL and integrity; `--patch-server-url` can override the download origin. The CLI verifies transfer integrity and patched-member afterHashes before writing. Pending builds, missing artifacts, service failures, wrong layouts and integrity mismatches fail closed. Fresh acquisition requires the network; healthy committed artifacts remain reusable offline. -Coverage includes npm (all lock flavors), Python wheels and source distributions, Cargo crates, Go module zips, Composer dist zips, RubyGems, NuGet packages and JVM jars. Directory artifacts are extracted and receive only the existing package-manager layout transformations. RubyGems requires the server's separately verified `gem-stub-gemspec`; a missing or invalid stub is a failure. Yarn Berry checksums come from server metadata. Hosted Berry rollback retrieves upstream checksum metadata from `/upstream/npm/.json` and checks its package identity and upstream integrity against the registry; the CLI does not recreate the Berry zip. +Coverage includes npm (all lock flavors), Python wheels and source distributions, Cargo crates, Go module zips, Composer dist zips, RubyGems, NuGet packages and JVM jars. Directory artifacts are extracted and receive only the existing package-manager layout transformations. RubyGems requires the server's separately verified `gem-stub-gemspec`; a missing or invalid stub is a failure. A gem whose `Gemfile.lock` holds platform-suffixed entries (`nokogiri (1.18.10-x86_64-linux-gnu)`) is taken as the patch's prebuilt platform gems instead: for each locked platform the server's `gem-platform` artifact and its `gem-platform-stub-gemspec` (each carries its `platform`), both verified like the ruby gem and its stub. Which prebuilds exist is read from the package reference alone, and the ruby gem it also names is not downloaded. While the server lists no prebuild for a locked platform nothing is downloaded and the gem is skipped (`vendor_prebuilt_platform_pending`). A prebuild need not ship any of the patch's files (a patch of `patches/**` or `dependencies.yml` lives entirely in the rebuilt binaries): its integrity check against the digest the server states for that platform is mandatory and is what vouches for it, while a patched file it does ship that is not the patched one is a `vendor_prebuilt_required` failure. Yarn Berry checksums come from server metadata. Hosted Berry rollback retrieves upstream checksum metadata from `/upstream/npm/.json` and checks its package identity and upstream integrity against the registry; the CLI does not recreate the Berry zip. Agent runs fetch patch content as per-file blobs (v5.0 removed `--download-mode` and the diff archive path). Vendored runs retain patch records in memory and embed them in the vendor ledger, without staging blobs. N-API and the hosted in-memory engine remain supported for callers such as the future GitHub App. @@ -1453,7 +1453,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md` | -| gem | gem dir `-/` + gemspec materialized from `specifications/` | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked prebuilt platform gem per locked platform, `-//`, each with its gemspec, plus `/.gitignore` (`!*`: re-includes the prebuilt binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a prebuilt platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patch's prebuilt platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform; EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. Every locked platform needs a prebuild: while the patch service lists none for one of them the gem is skipped (`vendor_prebuilt_platform_pending`, no failure) with nothing written. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no prebuilt tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock) | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | @@ -1488,7 +1488,7 @@ worse, lets a warm cache silently serve unpatched bytes): | npm / pnpm | `packages[].resolution.integrity` (sha512) | recomputed from the tarball; the versioned `pnpm.overrides` selector pins exactly the patched version | | npm / bun | the packages-entry trailing `sha512-…` | recomputed from the tarball; tamper fails the frozen install on Bun ≥ 1.3.10 (URL/local tarball tuples are verified from 1.3.10, registry 4-tuples from 1.2.0 — so on 1.1.39–1.3.9 a hosted or vendored rewrite removes digest enforcement for the patched package; see `docs/testing/bun-compatibility.md`) | | npm / vlt | node slot [2] (sha512), slot [3] (resolved) | a `file` node carries none: the committed directory is the artifact, verified against the ledger's file inventory (`vendor_inventory_mismatch` on a planted, removed or changed file); integrity-less by vlt's design, like every `file:` directory dependency | -| gem | `CHECKSUMS` section (bundler ≥ 2.6 opt-in) | the vendored gem's entry rewritten to bundler's own path-gem form (bare `name (ver)`, sha256 token stripped) so re-locks stay byte-stable; original line in the ledger | +| gem | `CHECKSUMS` section (bundler ≥ 2.6 opt-in) | the vendored gem's entry rewritten to bundler's own path-gem form (bare `name (ver)`, sha256 token stripped) so re-locks stay byte-stable; original line in the ledger. A gem vendored as platform gems has one entry per platform (`name (ver-platform)`): each is made bare, and each original line is in the ledger | | pypi / uv | `wheels[].hash`, `sdist.hash`, requires-dist specifiers | single `{filename, hash: sha256-of-our-wheel}`; sdist dropped; dropped specifiers ledgered for revert | | pypi / poetry | `files = [{file, hash}]` (2.x) / `[metadata.files]` entry (1.0/1.1) / `[metadata.hashes]` entry (0.12) | replaced with a single `{file, hash: sha256-of-our-wheel}` (or the bare hash for 0.12) in the generation's own table (Poetry ≥ 1.4 verifies the artifact against one listed hash; older writers are flagged `pypi_poetry_integrity_unverified`; stale registry hashes removed) | | pypi / pdm | `[[package]].files[]` hashes | replaced with our wheel's sha256; hash-less locks refused (`pypi_pdm_lock_no_hashes`) | @@ -2208,6 +2208,7 @@ command's integration tests check its output. | `vendor_maven_selection_undetermined` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): what the build selects for the artifact cannot be read (the reason says why: typically a pom the local repository does not hold, because the project was never resolved) and no declaration names the patch's base version, so nothing is pinned on a guess and no file is written. The reason carries the remedy that fits its cause (resolve the project once and re-run when a pom is missing from the local repository; otherwise declare the artifact at the base version). The vendored twin of `redirect_maven_selection_undetermined`. | | `vendor_maven_pin_would_move_module` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven reactor): the only poms that resolve the artifact at the patch's base version are parent poms above a module that resolves another version. A `` pin in the parent is inherited by that module and would move it, and Maven has no management that reaches a parent and not its children, so nothing is pinned and no file is written; the reason names the parent, the module and its version. When a sibling module does select the base version it is pinned and the same sentence is the `vendor_jvm_degraded` reason `pin_would_move_module`. | | `vendor_prebuilt_pending` / `vendor_prebuilt_unavailable` | `skipped` | vendor / scan / get `--mode vendored` (every ecosystem, #954, #1235): the package is already vendored at another patch uuid, and the patch service has no prebuilt artifact for the selected (superseding) uuid — still building (`pending_build`) / not served (`build_failed`, `not_found`, `withdrawn`, no usable artifact). Nothing is touched: the older patch's artifact, wiring and ledger entry stay in force, the detail names both uuids (`kept the vendored patch : prebuilt is still building for patch `, where `` is the backend's artifact kind: `artifact` for the npm family, `.gem`, `crate`, `module zip`, `dist zip`, `wheel`, `.jar`, `.nupkg`, …), and the run does not fail (exit 0), the way hosted mode keeps its pin and lists the upgrade in `redirect.skipped[]`. A re-run picks the new patch up once the service serves it. A package with no vendored patch to keep still fails (`failed`, error `prebuilt is still building` / `prebuilt unavailable: `; outside the npm family under `vendor_prebuilt_required`), as does a request/transport failure. | +| `vendor_prebuilt_platform_pending` | `skipped` | vendor / scan / get `--mode vendored` (gem): `Gemfile.lock` pins the gem as precompiled platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the patch service lists no prebuilt platform gem (or no stub gemspec) for at least one locked platform. The service lists a prebuild only once it is built, so "not built yet" and "never built" look the same: the detail names the gem, the platforms with no prebuild and the ones that have one, nothing is downloaded or written, and the run does not fail (exit 0), with or without an older vendored patch. With one, it stays in force and the detail names both uuids (`kept the vendored patch : … for patch `). A re-run vendors the gem once every locked platform has a prebuild. Two cases stay failures (`vendor_prebuilt_required`): a copy the lock is already wired to that is missing or damaged and cannot be rebuilt, by a re-run or by `repair`; and an eject of the gem's hosted pin (plain `vendor`), which is all-or-nothing and keeps the pin. | | `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. | @@ -2289,7 +2290,7 @@ command's integration tests check its output. | `vendor_dep_manifest_unlocked` | refused | vendor (yarn classic): the patch rewrites the package's own `package.json` to depend on a descriptor (`name@range`) no `yarn.lock` block is keyed by — an added dependency, or an existing one moved to a new range. A descriptor every wired block's sub-map already names is not counted: yarn keys those blocks by the registry packument's ranges, which can differ from the tarball's `package.json` (#1578). yarn 1 builds its install graph from the lock, so the rewired block would name a dependency it never resolves: online frozen installs fetch it unpinned, `--offline` installs fail and every plain `yarn install` re-saves the lock (#591). Refused after staging and before any wiring is written (the staged uuid dir is removed); the detail names the descriptors. Remedy: lock them first (for example `yarn add `), then re-run. A dry run, which stages nothing, does not foresee it. Also `failed` on `repair` (and `vendor_check_failed` on `vendor --check`) for a lock an older release already vendored that way, with a block wired to the entry naming a descriptor no block locks and the recorded pre-vendor block did not (#1379); the lock is left as it is. Remedy: `yarn install` (without `--frozen-lockfile`) to lock them, then commit `yarn.lock`. | | `redirect_yarn_classic_dep_manifest_unlocked` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` depends on a descriptor no `yarn.lock` block is keyed by and that the sub-maps of the registry blocks being pinned don't already name (yarn keys those by the packument's ranges, #1578). yarn 1 installs only what the lock names, so a pin would install the patched package without that dependency (#591). The dep is not pinned and never confirmed; the lock is left as it was. The served tarball is read on every run, so a pin an earlier release wrote without this check (#1462) gets the same warning and is never confirmed either; it stays in the lock until the dependency is locked or the pin is rolled back. Same remedy as `vendor_dep_manifest_unlocked`. | | `redirect_yarn_classic_dep_manifest_rewritten` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` declares other dependencies than the pinned block's sub-maps, every descriptor already locked; the block's `dependencies:` / `optionalDependencies:` sub-maps are rewritten to match, in the shape yarn 1 writes for that manifest (#591, #1558). | -| `vendor_artifact_gitignored` | `failed` | vendor (vlt, the npm-family tarball flavors — npm, pnpm, bun, yarn classic, yarn berry — NuGet, every PyPI flavor, 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 prebuilt platform gems, and the JVM trees of Maven, Gradle, sbt and scala-cli): inside a git work tree, `git check-ignore --no-index` reports the new artifact's uuid directory (JVM: its tree root, such as `.socket/vendor/maven2`) as ignored by a rule its own `.gitignore` cannot override (such as a root `.socket/` or `vendor/` rule; the detail names the rule). Remedy: drop that rule for `.socket/vendor/`. Refused before any write, dry run included. A file rule such as `*.tgz`, `*.nupkg`, `*.whl` or `*.jar` is overridden by the `!*` `.gitignore` vendoring writes into the uuid dir or tree root (PyPI's uuid dir also gets the `.gitattributes` that unsets a `*.whl filter=lfs` rule); if a written tarball, directory payload, nupkg or wheel still reads as ignored, the run refuses and removes the uuid dir it created. | | `vendor_artifact_gitignore_unchecked` | warning | vendor (vlt, the npm-family tarball flavors, NuGet and every PyPI flavor): git is installed but could not answer the ignore check for the written vendored directory (it failed to start, ran past 30 s, or `rev-parse` / `check-ignore` exited with an error); the package is vendored and the detail names what failed. Remedy: make sure no ignore rule covers `.socket/` before committing. Git absent, or a project outside any work tree, raises nothing. | | `vendor_ledger_gitignored` | top-level error (exit 1) | vendor / scan / get `--mode vendored` (every backend) and the hosted→vendored eject: inside a git work tree, `git check-ignore` reports the vendor ledger `.socket/vendor/state.json` as ignored by a file rule (such as `state.json`, `*.json` or `**/state.json`; the message names it), so the commit the run asks for would leave it out and no other checkout could `rollback`, `list` or `vendor --revert` the patches (#1638). A ledger git already tracks is never refused. Refused before any write, dry run included. Remedy: drop the rule or add `!.socket/vendor/state.json`. A rule that ignores `.socket/` or `.socket/vendor/` as a directory is `vendor_artifact_gitignored`: per package from the backends that check it themselves (the npm family, NuGet, PyPI, the JVM trees), and as this same run-level refusal when the run includes any other ecosystem. | | `vendor_ledger_entry_missing` | `failed` | vendor (vlt): the only installed copy is vlt's link to a committed vendored directory, but the vendor ledger has no entry for the package; restore `.socket/vendor/state.json` from version control (v5.0: `repair` no longer re-synthesizes it). Replaces the `package_not_installed` skip. | @@ -2304,6 +2305,7 @@ command's integration tests check its output. | `vendor_uuid_mismatch` | `skipped` | repair: the manifest's patch uuid moved past the vendored artifact — a re-vendor (`vendor` / `scan --mode vendored`) is pending; repair does not cross patch generations. | | `content_mismatch_overwritten` | `skipped` (warning) | apply (explicit `--allow-patch-conflicts` / `--force`): a file matched NEITHER beforeHash nor afterHash and was overwritten with the full verified patched content. This includes a file the patch adds (empty beforeHash) that already exists with other content. `--strict` turns this case into a `failed` event instead. Agent-mode `get` / `scan --json` carry it as a `(content_mismatch_overwritten) …` `warnings[]` entry (#1004). | | `vendor_lock_checksums_unsupported` / `vendor_stale_lock_checksum` | `failed` | vendor (gem): an ambiguous/platform CHECKSUMS entry, or a v1-wired lock whose stale token blocks the hot path (run `vendor --revert` + re-vendor). | +| `platform_gem_unsupported` | `failed` | vendor / scan / get `--mode vendored` (gem): a precompiled platform gem that cannot be vendored. `Gemfile.lock` pins the gem as platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and also holds the plain ` ()` entry of the `ruby` platform, which no prebuilt tree serves (the detail names it; `bundle lock --remove-platform ruby` drops it); or it pins the gem as platform gems and its `BUNDLED WITH` is absent or names a Bundler older than 2.3, the oldest the vendored layout is verified on (the detail names the version needed; `bundle update --bundler` re-locks); or the installed copy is a platform gem and the lock names no platform for the gem; or the patch record is for one platform's build (`?platform=`). Nothing is written. A locked platform the patch service has no prebuild for is not this failure: see `vendor_prebuilt_platform_pending`. | | `redirect_unattributable` | `skipped` (hosted event) | scan/get `--mode hosted`: the rewriters would pin the patch, but lockfile discovery over the result reads that pin as contested (another lock or requirements file resolves the same version elsewhere, or the pin is not one the package manager consumes), so `vex`, `rollback`, `remove` and `vendor` would refuse it. The candidate is left out of the rewrite, so nothing is written for it; the detail carries discovery's findings. Exit code unchanged. | | `redirect_grant_malformed` / `redirect_grant_insecure_url` | `skipped` (hosted event) + `warnings[]` | scan/get `--mode hosted` and the in-memory engine: the patch API's reference for the package has a field that is not in the shape the project's files take verbatim (`redirect_grant_malformed`; the detail names the field), or names a plain-`http` artifact or registry index URL on an origin that is neither `--patch-server-url` nor a loopback address (`redirect_grant_insecure_url`; the detail names the host). Refused before anything is planned: nothing is written for the package and it stays unpatched. Exit code unchanged. See the grant gate under "Scan modes (v5.0)". | | `redirect_copy_unpatched` | `warnings[]` (warning) | scan/get `--mode hosted` (pnpm, yarn): the pin was written, but its own lock also installs an unpatched copy of the same `name@version`, which no rewrite reaches: a pnpm `file:` directory or tarball dependency (#935), or a yarn `file:` tarball / directory, URL tarball or berry `portal:` / `link:` dependency declared under another name (`lp2@file:…`, #939, #1236; not repeated for a copy a yarn classic skip warning already names), or a yarn classic copy installed from a parent's `bundleDependencies` (#758). The detail names the lock entry (for a bundled copy, the parent's entry and the copy's directory). Neither the run's own `--vex` nor a later `vex` attests the package (`vex` warns `patched_ref_unattributable`), but discovery still manages the pin, so `rollback` / `remove` undo it. | diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 982fc4d71..a5a84cbb6 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -132,6 +132,12 @@ use socket_patch_core::vendor::refusals::refusal_is_benign; /// `vendor_prebuilt_required` failure it always was, a failed `Done` minus /// the unserved marker (its error already says it). /// +/// One unserved refusal is a skip with nothing to keep as well: +/// [`vendor::VENDOR_PREBUILT_PLATFORM_PENDING`], a gem locked as platform +/// gems whose prebuild for one of the locked platforms the service does +/// not list. A prebuild is listed only once built, so the run cannot tell +/// "not yet" from "never", and the project is exactly as it was. +/// /// [`Discovery::vendor_entry_live`]: socket_patch_core::vex::discover::Discovery::vendor_entry_live async fn keep_older_vendored_patch( outcome: Option, @@ -191,6 +197,9 @@ async fn keep_older_vendored_patch( entry, warnings, }, + None if code == vendor::VENDOR_PREBUILT_PLATFORM_PENDING => { + VendorOutcome::Refused { code, detail } + } None => VendorOutcome::Refused { code: vendor::VENDOR_PREBUILT_REQUIRED, detail, @@ -302,6 +311,14 @@ async fn takeover_dry_refusal( .await; drop(probe); match outcome { + // A skip, not a failure, for a takeover in the vendor loop: the + // wet run rolls the restore back, so the hosted pin stays (see + // `keep_older_vendored_patch`). The eject plan refuses it. + Some(VendorOutcome::Refused { code, detail }) + if code == vendor::VENDOR_PREBUILT_PLATFORM_PENDING => + { + Some((code, detail)) + } // A takeover has no older vendored patch to keep in force. Some(VendorOutcome::Refused { code, detail }) if vendor::is_unserved(code) => { Some((vendor::VENDOR_PREBUILT_REQUIRED, detail)) @@ -2097,6 +2114,13 @@ async fn run_eject( ) .await { + // An eject has no skip: a pin it cannot vendor stays hosted + // and the eject is refused whole, so a prebuild that is not + // built yet is the plain miss here. + let code = match vendor::is_unserved(code) { + true => vendor::VENDOR_PREBUILT_REQUIRED, + false => code, + }; refused.push((pin.purl.clone(), code, detail)); } // sbt / scala-cli also require build evidence. The backend treats @@ -3795,6 +3819,17 @@ pub(crate) async fn vendor_records_reusing( ) .await { + if refusal_is_benign(code) { + // The wet run's skip: nothing is taken over. + if !common.silent && !common.json { + eprintln!("Skipping {}: {detail}", normalize_purl(candidate)); + } + env.record( + PatchEvent::new(PatchAction::Skipped, candidate.clone()) + .with_reason(code, detail), + ); + continue; + } has_errors = true; env.record( PatchEvent::new(PatchAction::Failed, candidate.clone()) 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 dff961856..4a143fdfe 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -49,6 +49,13 @@ //! attested again; full registry revert (ledgers + artifact kept) → //! `vendor_unwired`, also under `--no-verify`. //! +//! PLATFORM GEMS (`gem_vendor_platform_gems_fresh_checkout_bundle_install_and_revert`, +//! bundler >= 2.3): a gem the real bundler locks as precompiled platform +//! gems, from a local source that publishes it that way, is vendored as the +//! patch service's prebuilt platform gem of every locked platform; the +//! fresh checkout loads the patched file from the tree of the platform it +//! runs on, with no request to the service. +//! //! VERSION MATRIX: every capstone runs on bundler 1.17 → 4.x (verified //! 1.17.3, 2.0.2 … 2.7.2, 4.0.15, 4.0.21 — the pair edit's PATH + //! `(= v)!` shape installs frozen on all of them). Select with `PATH` and @@ -69,7 +76,7 @@ mod prebuilt_common; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; -use wiremock::matchers::{method, path}; +use wiremock::matchers::{method, path, path_regex}; use wiremock::{Mock, MockServer, ResponseTemplate}; #[path = "common/bundler_e2e.rs"] @@ -2682,3 +2689,735 @@ fn gem_vendor_crlf_lock_fresh_checkout_and_revert() { "revert restores the CRLF lock byte for byte" ); } + +// ── a gem locked as precompiled platform gems ────────────────────────── + +/// The fixture gem of the platform-gem capstone: published as platform +/// gems only, with a pure-Ruby dependency. +const PLAT: &str = "sockplat"; +const PLAT_VERSION: &str = "1.0.0"; +const PLAT_PRISTINE: &str = "module Sockplat\n VERSION = \"1.0.0\"\nend\n"; + +/// Builds, with RubyGems itself, in the current directory: +/// +/// * `repo/`: a static `file://` rubygems source (see +/// [`private_gem_source`]) serving `sockplat 1.0.0` as PLATFORM gems +/// only — one for this machine's platform and two foreign ones — its +/// dependency `sockdep 1.0.0`, and `sockparent 1.0.0`, which depends on +/// it. A platform gem needs no binary: a pure-Ruby gem whose gemspec +/// sets `platform` is one. +/// * `service/`: what the patch service serves for the patch of +/// `sockplat` — the patched ruby gem, the patched platform gem of each +/// platform (a "prebuild") and the stub gemspec of each +/// (`Gem::Specification#to_ruby`). +/// * `platforms`: the platforms, this machine's first. +/// +/// `pristine.rb` / `patched.rb` (the caller's) are `lib/sockplat.rb` +/// before and after the patch. +const PLATFORM_GEMS_RB: &str = r##" +require "rubygems/package" +require "zlib" +require "fileutils" + +out = Dir.pwd +local = Gem::Platform.local +own = Gem::Platform.new([local.cpu, local.os, nil]).to_s +platforms = ([own] + %w[x86_64-linux arm64-darwin x64-mingw-ucrt]).uniq.first(3) +bodies = { "upstream" => File.read("pristine.rb"), "patched" => File.read("patched.rb") } + +build = lambda do |dir, name, platform, body, deps| + work = File.join(out, dir, "#{name}-#{platform || "ruby"}") + FileUtils.mkdir_p(File.join(work, "lib")) + File.write(File.join(work, "lib/#{name}.rb"), body) + spec = Gem::Specification.new do |s| + s.name = name + s.version = "1.0.0" + s.platform = platform if platform + s.summary = "fixture" + s.authors = ["fixture"] + s.files = ["lib/#{name}.rb"] + deps.each { |dep| s.add_runtime_dependency(dep, ">= 1.0") } + end + [spec, Dir.chdir(work) { File.join(work, Gem::Package.build(spec)) }] +end + +FileUtils.mkdir_p(["repo/gems", "repo/quick/Marshal.4.8", "service"]) +tuples = [] +publish = lambda do |spec, file| + FileUtils.cp(file, "repo/gems") + tuples << [spec.name, spec.version, spec.platform.to_s] + File.binwrite("repo/quick/Marshal.4.8/#{spec.full_name}.gemspec.rz", + Zlib::Deflate.deflate(Marshal.dump(spec))) +end +publish.call(*build.call("upstream", "sockdep", nil, "module Sockdep; end\n", [])) +publish.call(*build.call("upstream", "sockparent", nil, "require \"sockplat\"\n", ["sockplat"])) +platforms.each do |platform| + publish.call(*build.call("upstream", "sockplat", platform, bodies["upstream"], ["sockdep"])) +end +{ "specs.4.8.gz" => tuples, "latest_specs.4.8.gz" => tuples, "prerelease_specs.4.8.gz" => [] }.each do |f, v| + Zlib::GzipWriter.open("repo/#{f}") { |gz| gz.write(Marshal.dump(v)) } +end +([nil] + platforms).each do |platform| + spec, file = build.call("patched", "sockplat", platform, bodies["patched"], ["sockdep"]) + FileUtils.cp(file, "service") + File.write("service/#{spec.full_name}.gemspec", spec.to_ruby) +end +File.write("platforms", platforms.join("\n")) +"##; + +/// A patch service answering for the patch `uuid` the way the wire +/// contract of gem prebuilds has it: the ruby gem as the `tarball` (with +/// its stub), and a `gem-platform` gem + `gem-platform-stub-gemspec` for +/// each of `prebuilds`, each naming its `platform`. The URLs name the +/// production host, so the run reaches them only through +/// `--patch-server-url`. +async fn platform_patch_service( + service: &Path, + purl: &str, + uuid: &str, + prebuilds: &[String], +) -> MockServer { + use base64::Engine as _; + use sha2::{Digest as _, Sha512}; + let server = MockServer::start().await; + let leaf = format!("{PLAT}-{PLAT_VERSION}"); + let mut served: Vec<(&str, Option<&str>, String)> = vec![ + ("tarball", None, format!("{leaf}.gem")), + ("gem-stub-gemspec", None, format!("{leaf}.gemspec")), + ]; + for platform in prebuilds { + served.push(( + "gem-platform", + Some(platform.as_str()), + format!("{leaf}-{platform}.gem"), + )); + served.push(( + "gem-platform-stub-gemspec", + Some(platform.as_str()), + format!("{leaf}-{platform}.gemspec"), + )); + } + let mut artifacts = Vec::new(); + for (kind, platform, file) in served { + let bytes = std::fs::read(service.join(&file)).unwrap(); + let route = format!("/patch/gem/{PLAT}/{PLAT_VERSION}/grant-token/{uuid}/{file}"); + let mut artifact = serde_json::json!({ + "kind": kind, + "url": format!("https://patch.socket.dev{route}"), + "contentType": "application/octet-stream", + "sizeBytes": bytes.len(), + "integrity": { "sha512": format!( + "sha512-{}", + base64::engine::general_purpose::STANDARD.encode(Sha512::digest(&bytes)) + ) }, + }); + if let Some(platform) = platform { + artifact["platform"] = serde_json::json!(platform); + } + artifacts.push(artifact); + Mock::given(method("GET")) + .and(path(route)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .mount(&server) + .await; + } + Mock::given(method("POST")) + .and(path_regex(r"/(patch|patches)/package$")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "results": { uuid: { + "status": "granted", + "purl": purl, + "url": artifacts[0]["url"], + "artifacts": artifacts, + }} + }))) + .mount(&server) + .await; + server +} + +/// A second patch of the fixture gem, published after [`UUID`]. +const UUID_NEXT: &str = "4d5e6f7a-8b9c-4b2c-9d3e-123456789abc"; + +/// The artifacts `server` has been asked to serve, by file name. +async fn artifact_downloads(server: &MockServer) -> Vec { + server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|r| r.url.path().starts_with("/patch/gem/")) + .filter_map(|r| r.url.path().rsplit('/').next().map(str::to_string)) + .collect() +} + +/// How many grants and artifact downloads `server` has answered. +async fn service_requests(server: &MockServer) -> usize { + server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|r| r.url.path().ends_with("/package") || r.url.path().starts_with("/patch/gem/")) + .count() +} + +/// A gem bundler locks as PRECOMPILED PLATFORM gems (the shape of +/// nokogiri: one lock entry per platform, no plain `name (version)`), which +/// cannot be vendored as its own tree because bundler never builds a +/// `path:` gem's extensions. Vendor takes the patch service's prebuild of +/// EVERY locked platform instead: +/// +/// 1. the REAL bundler resolves the fixture gem from a local source that +/// publishes it as platform gems only, and locks this machine's +/// platform and two foreign ones; +/// 2. while the service lacks one platform's prebuild the gem is +/// skipped, by that platform's name: the run does not fail, downloads +/// no gem and writes nothing; +/// 3. with every prebuild served, `vendor` unpacks one tree per platform +/// (each with its stub gemspec), moves every platform block into one +/// `PATH` section and wires the Gemfile; +/// 4. `vex` attests the patch `(vendored)`, and `vendor --check` covers +/// every platform's tree (a tampered FOREIGN tree fails it); +/// 5. a fresh checkout — the committable files only, and no request to +/// the patch service — installs frozen with a byte-stable lock, loads +/// the PATCHED file from the tree of the running platform, and an +/// unfrozen install and `bundle lock` regenerate the same lock; +/// 6. a second `vendor` run changes nothing and asks the service nothing, +/// and a newer patch whose prebuild for one platform is not built yet +/// keeps the vendored one; +/// 7. `vendor --revert` restores the Gemfile and the lock byte for byte +/// (the registry CHECKSUMS tokens included) and removes the trees. +/// +/// Run for a gem the Gemfile declares, and for one it only reaches through +/// another gem (wired by the managed block). +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real bundler >= 2.3; the unpinned `test` job \ + skips it, the e2e job runs it with a pinned toolchain via --ignored"] +async fn gem_vendor_platform_gems_fresh_checkout_bundle_install_and_revert() { + // Floor 2.3: the oldest bundler this layout was run against (it locks + // one entry per platform and reads a path source's per-platform + // gemspecs the same way up to 4.x). + let Some(bundler) = bundler_e2e::gate("e2e_vendor_gem_build", "platform gems", (2, 3), &|c| { + cache_env::isolate(c); + }) else { + return; + }; + for declared in ["sockplat", "sockparent"] { + platform_gems_capstone(&bundler, declared).await; + } +} + +/// The platform-gem capstone for a project whose Gemfile declares +/// `declared`: the platform gem itself, or `sockparent`, which makes the +/// platform gem a transitive dependency. +async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) { + let tmp = tempfile::tempdir().unwrap(); + // Bundler spells the lock's `file://` remote with the real path. + let base = tmp.path().canonicalize().unwrap(); + + // 1. The fixture source and service artifacts. + let marker = format!("module Sockplat\n SOCKET_PATCH_VENDOR_E2E = \"{UUID}\"\nend\n"); + let patched = format!("{PLAT_PRISTINE}{marker}"); + let fixture = base.join("fixture"); + std::fs::create_dir_all(&fixture).unwrap(); + std::fs::write(fixture.join("pristine.rb"), PLAT_PRISTINE).unwrap(); + std::fs::write(fixture.join("patched.rb"), &patched).unwrap(); + let mut ruby = Command::new("ruby"); + ruby.args(["-e", PLATFORM_GEMS_RB]).current_dir(&fixture); + cache_env::isolate(&mut ruby); + let built = ruby.output().expect("failed to run ruby"); + assert!( + built.status.success(), + "building the platform gem fixture failed:\n{}", + String::from_utf8_lossy(&built.stderr) + ); + let platforms: Vec = std::fs::read_to_string(fixture.join("platforms")) + .unwrap() + .lines() + .map(str::to_string) + .collect(); + let (own, foreign) = platforms.split_first().expect("platforms"); + assert_eq!(foreign.len(), 2, "two foreign platforms: {platforms:?}"); + + let proj = base.join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write( + proj.join("Gemfile"), + format!( + "source \"file://{}\"\n\ngem \"{declared}\"\n", + fixture.join("repo").display() + ), + ) + .unwrap(); + let config = bundle( + &proj, + &argv(&bundler.config_local_args("path", "vendor/bundle")), + false, + ); + assert!(config.status.success(), "bundle config failed"); + let install = bundle(&proj, &["install"], false); + assert!( + install.status.success(), + "fixture `bundle install` failed:\n{}", + String::from_utf8_lossy(&install.stderr) + ); + for platform in &platforms { + let add = bundle(&proj, &["lock", "--add-platform", platform.as_str()], false); + assert!( + add.status.success(), + "`bundle lock --add-platform {platform}` failed:\n{}", + String::from_utf8_lossy(&add.stderr) + ); + } + let lock_path = proj.join("Gemfile.lock"); + let gemfile_path = proj.join("Gemfile"); + let lock_before = std::fs::read(&lock_path).unwrap(); + let gemfile_before = std::fs::read(&gemfile_path).unwrap(); + let lock_text = String::from_utf8(lock_before.clone()).unwrap(); + // The premise: bundler locked one entry per platform, each with its + // dependency line, and no plain `sockplat (1.0.0)`. Bundler sorts a + // section's specs by full name. + let mut sorted = platforms.clone(); + sorted.sort(); + let blocks: String = sorted + .iter() + .map(|p| format!(" {PLAT} ({PLAT_VERSION}-{p})\n sockdep (>= 1.0)\n")) + .collect(); + assert!( + lock_text.contains(&blocks) + && !lock_text.contains(&format!(" {PLAT} ({PLAT_VERSION})\n")), + "bundler must lock {PLAT} as platform gems only (test premise):\n{lock_text}" + ); + + let mut ruby = Command::new("ruby"); + ruby.args(["-e", "puts Gem.ruby_api_version"]); + cache_env::isolate(&mut ruby); + let api = ruby.output().expect("failed to run ruby"); + let api = String::from_utf8_lossy(&api.stdout).trim().to_string(); + let installed_rb = proj + .join("vendor/bundle/ruby") + .join(&api) + .join("gems") + .join(format!("{PLAT}-{PLAT_VERSION}-{own}")) + .join("lib/sockplat.rb"); + assert_eq!( + std::fs::read_to_string(&installed_rb).expect("the installed platform gem"), + PLAT_PRISTINE, + "bundler installs this machine's platform gem into a platform-suffixed dir" + ); + + // The patch record is the ruby gem's, as the patch service publishes it. + let purl = format!("pkg:gem/{PLAT}@{PLAT_VERSION}?platform=ruby"); + stage_patch_with_vuln( + &proj, + &purl, + "lib/sockplat.rb", + PLAT_PRISTINE.as_bytes(), + patched.as_bytes(), + ); + let vendor = |server: &MockServer| { + let uri = server.uri(); + run_socket( + &proj, + &[ + "vendor", + "--json", + "--cwd", + proj.to_str().unwrap(), + "--patch-server-url", + &uri, + ], + ) + }; + + // 2. One locked platform without a prebuild (the service lists one + // only once it is built): the gem is skipped, by name, the run does + // not fail, no gem is downloaded and nothing is written. + let partial = + platform_patch_service(&fixture.join("service"), &purl, UUID, &platforms[..2]).await; + let (code, stdout, stderr) = vendor(&partial); + assert_eq!( + code, 0, + "a prebuild that is not built yet is no failure.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env = parse_json_envelope(&stdout); + assert_eq!(env["summary"]["applied"], 0, "nothing vendored: {env}"); + assert_eq!(env["summary"]["failed"], 0, "and nothing failed: {env}"); + let skipped = env["events"] + .as_array() + .unwrap() + .iter() + .find(|e| e["errorCode"] == "vendor_prebuilt_platform_pending") + .unwrap_or_else(|| panic!("a vendor_prebuilt_platform_pending event: {env}")); + assert_eq!(skipped["action"], "skipped", "{skipped}"); + let said = skipped.to_string(); + assert!( + said.contains(&format!("`{PLAT}`")) && said.contains(&format!("`{}`", platforms[2])), + "the skip names the gem and the platform with no prebuild: {skipped}" + ); + assert_eq!( + artifact_downloads(&partial).await, + Vec::::new(), + "the package reference says what is built: nothing is downloaded" + ); + assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_before); + assert_eq!(std::fs::read(&lock_path).unwrap(), lock_before); + assert!( + !proj.join(".socket/vendor/gem").exists(), + "no vendored copy is written" + ); + drop(partial); + + // 3. Every prebuild served: vendor. + let server = platform_patch_service(&fixture.join("service"), &purl, UUID, &platforms).await; + let (code, stdout, stderr) = vendor(&server); + assert_eq!( + code, 0, + "vendor failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env = parse_json_envelope(&stdout); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert_eq!(env["summary"]["applied"], 1, "one package vendored: {env}"); + assert_eq!(env["summary"]["failed"], 0, "no failures: {env}"); + // The prebuilds and their stubs are all that is downloaded: the ruby + // gem the same reference names is not. + let mut downloaded = artifact_downloads(&server).await; + downloaded.sort(); + let mut prebuilds: Vec = platforms + .iter() + .flat_map(|p| ["gem", "gemspec"].map(|ext| format!("{PLAT}-{PLAT_VERSION}-{p}.{ext}"))) + .collect(); + prebuilds.sort(); + assert_eq!(downloaded, prebuilds); + + // One prebuild tree per platform, each with its own stub gemspec. + let copy_rel = format!(".socket/vendor/gem/{UUID}/{PLAT}-{PLAT_VERSION}"); + for platform in &platforms { + let tree = proj.join(©_rel).join(platform); + assert_eq!( + std::fs::read_to_string(tree.join("lib/sockplat.rb")).unwrap(), + patched, + "{platform}: the vendored tree must hold the patched bytes" + ); + let stub = std::fs::read_to_string(tree.join(format!("{PLAT}.gemspec"))) + .unwrap_or_else(|e| panic!("{platform}: stub gemspec not materialized: {e}")); + assert!( + stub.contains(&format!("s.platform = \"{platform}\"")), + "{platform}: the stub is the platform gem's:\n{stub}" + ); + } + assert!( + !proj + .join(©_rel) + .join(format!("{PLAT}.gemspec")) + .exists(), + "no ruby-platform gemspec at the vendored dir's root" + ); + + // The pair edit: `path:` on the declaration, every platform block in + // one PATH section ahead of GEM, the `(= v)!` pin, bare CHECKSUMS. + let gemfile = std::fs::read_to_string(&gemfile_path).unwrap(); + assert!( + gemfile.contains(&format!( + "gem \"{PLAT}\", \"{PLAT_VERSION}\", path: \"{copy_rel}\"" + )), + "Gemfile line not rewritten to the exact-pin + path: form:\n{gemfile}" + ); + assert_eq!( + gemfile.contains("# >>> socket-patch vendor (managed) >>>"), + declared != PLAT, + "only a gem the Gemfile did not declare is wired by the managed block:\n{gemfile}" + ); + let lock = std::fs::read_to_string(&lock_path).unwrap(); + assert!( + lock.starts_with(&format!( + "PATH\n remote: {copy_rel}\n specs:\n{blocks}\nGEM\n" + )), + "every platform block must sit in one PATH section ahead of GEM:\n{lock}" + ); + assert!( + lock.contains(&format!("\n {PLAT} (= {PLAT_VERSION})!\n")), + "DEPENDENCIES pin missing:\n{lock}" + ); + assert!( + !lock.contains(&format!("\n {PLAT} ({PLAT_VERSION}-{own}) sha256=")), + "a path gem's CHECKSUMS entry is bare:\n{lock}" + ); + let state = std::fs::read_to_string(proj.join(".socket/vendor/state.json")).unwrap(); + let state: serde_json::Value = serde_json::from_str(&state).unwrap(); + let entry = state["entries"] + .as_object() + .and_then(|entries| entries.values().next()) + .unwrap_or_else(|| panic!("a ledger entry: {state}")); + assert_eq!( + entry["gemPlatforms"], + serde_json::json!(sorted), + "the ledger records the platform trees: {entry}" + ); + + // 4. VEX attests the patch against the committed trees, and `--check` + // covers every one of them. + let vex_path = proj.join("out.vex.json"); + let (code, stdout, stderr) = run_socket( + &proj, + &[ + "vex", + "--cwd", + proj.to_str().unwrap(), + "--output", + vex_path.to_str().unwrap(), + "--product", + PRODUCT, + ], + ); + assert_eq!(code, 0, "vex failed.\nstdout:\n{stdout}\nstderr:\n{stderr}"); + let doc: serde_json::Value = + serde_json::from_slice(&std::fs::read(&vex_path).unwrap()).unwrap(); + let stmts = doc["statements"].as_array().unwrap(); + assert_eq!(stmts.len(), 1, "the vendored patch must be attested: {doc}"); + assert_eq!(stmts[0]["vulnerability"]["name"], GHSA); + assert_eq!(stmts[0]["status"], "not_affected"); + assert!( + stmts[0]["impact_statement"] + .as_str() + .unwrap() + .contains("(vendored)"), + "vendored attestation must carry the (vendored) marker: {doc}" + ); + let check = |root: &Path| { + let uri = server.uri(); + run_socket( + root, + &[ + "vendor", + "--check", + "--json", + "--cwd", + root.to_str().unwrap(), + "--patch-server-url", + &uri, + ], + ) + }; + let (code, stdout, stderr) = check(&proj); + assert_eq!( + code, 0, + "vendor --check failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let tampered = base.join("tampered"); + common::fs_tree::copy_tree(&proj, &tampered); + std::fs::write( + tampered + .join(©_rel) + .join(&foreign[0]) + .join("lib/sockplat.rb"), + PLAT_PRISTINE, + ) + .unwrap(); + let (code, stdout, stderr) = check(&tampered); + assert_ne!( + code, 0, + "an unpatched tree of a FOREIGN platform must fail the check.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + + // 5. FRESH CHECKOUT: only the committable files, and no patch service. + let fresh = base.join("fresh"); + std::fs::create_dir_all(&fresh).unwrap(); + std::fs::copy(&gemfile_path, fresh.join("Gemfile")).unwrap(); + std::fs::copy(&lock_path, fresh.join("Gemfile.lock")).unwrap(); + common::fs_tree::copy_tree(&proj.join(".socket"), &fresh.join(".socket")); + common::fs_tree::copy_tree(&proj.join(".bundle"), &fresh.join(".bundle")); + let lock_wired = std::fs::read(&lock_path).unwrap(); + let served_before = service_requests(&server).await; + let ci = bundle(&fresh, &["install"], true); + assert!( + ci.status.success(), + "fresh-checkout frozen `bundle install` must succeed from the vendored trees.\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, + "frozen install must leave the committed Gemfile.lock byte-identical" + ); + let script = format!( + "require \"{declared}\"\n\ + abort \"probe constant missing after require\" unless defined?(Sockplat::SOCKET_PATCH_VENDOR_E2E)\n\ + puts Sockplat::SOCKET_PATCH_VENDOR_E2E\n\ + puts $LOADED_FEATURES.grep(%r{{/sockplat\\.rb\\z}})" + ); + let probe = bundle(&fresh, &["exec", "ruby", "-e", script.as_str()], false); + assert!( + probe.status.success(), + "bundle exec runtime probe failed.\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&probe.stdout), + String::from_utf8_lossy(&probe.stderr), + ); + let probe_out = String::from_utf8_lossy(&probe.stdout).into_owned(); + assert!( + probe_out.contains(UUID), + "probe constant must carry the patch uuid:\n{probe_out}" + ); + assert!( + probe_out.contains(&format!("{copy_rel}/{own}/lib/sockplat.rb")), + "the patched file must load from the tree of the running platform:\n{probe_out}" + ); + // The lock is the one bundler itself writes for this Gemfile: an + // unfrozen install and a re-lock leave it byte-identical. + for args in [&["install"][..], &["lock"][..]] { + 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 {}` must regenerate the committed lock byte for byte (bundler {})", + args.join(" "), + bundler.version + ); + } + assert_eq!( + service_requests(&server).await, + served_before, + "the fresh checkout installs with no request to the patch service" + ); + + // Manifest-less VEX over the fresh checkout: attested from the lock's + // PATH wiring and the vendor ledger, and, with the ledgers gone too, + // from the lock and the patch API alone (the platform trees are then + // read off the committed directory). On a plain thread: PatchApi runs + // its own runtime, which cannot be started (or dropped) from inside + // this test's async context. + std::thread::scope(|scope| { + scope.spawn(|| { + use vex_e2e_common::{ + assert_attested, patch_view, run_vex, strip_ledgers, strip_manifest, Marker, + PatchApi, VexRun, + }; + let api = PatchApi::start(vec![( + UUID.into(), + patch_view( + UUID, + &purl, + &[("lib/sockplat.rb", &git_sha256(patched.as_bytes()))], + VULNS, + ), + )]); + let run = |base: VexRun| VexRun { + product: Some(PRODUCT.into()), + ..base + }; + let base_purl = format!("pkg:gem/{PLAT}@{PLAT_VERSION}"); + strip_manifest(&fresh); + let out = run_vex(&binary(), &fresh, &run(VexRun::offline())); + assert_eq!(out.code, Some(0), "manifest-less vex: {out}"); + assert_attested(out.doc(), &base_purl, UUID, Marker::Vendored, VULNS); + strip_ledgers(&fresh); + let out = run_vex(&binary(), &fresh, &run(VexRun::online(&api))); + assert_eq!(out.code, Some(0), "ledger-less vex: {out}"); + assert_attested(out.doc(), &base_purl, UUID, Marker::Vendored, VULNS); + }); + }); + + // 6. A second run changes nothing and asks the service nothing. + let gemfile_wired = std::fs::read(&gemfile_path).unwrap(); + let state_wired = std::fs::read(proj.join(".socket/vendor/state.json")).unwrap(); + let (code, stdout, stderr) = vendor(&server); + assert_eq!( + code, 0, + "re-vendor failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env2 = parse_json_envelope(&stdout); + assert_eq!(env2["summary"]["failed"], 0, "re-run must not fail: {env2}"); + assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_wired); + assert_eq!(std::fs::read(&lock_path).unwrap(), lock_wired); + assert_eq!( + std::fs::read(proj.join(".socket/vendor/state.json")).unwrap(), + state_wired + ); + assert_eq!( + service_requests(&server).await, + served_before, + "an in-sync re-run downloads nothing" + ); + + // A newer patch of the gem whose prebuild for one platform is not + // built yet: the vendored patch stays in force, and the run says so + // and does not fail. + let manifest_path = proj.join(".socket/manifest.json"); + let manifest = std::fs::read_to_string(&manifest_path).unwrap(); + std::fs::write(&manifest_path, manifest.replace(UUID, UUID_NEXT)).unwrap(); + let update = + platform_patch_service(&fixture.join("service"), &purl, UUID_NEXT, &platforms[..2]).await; + let (code, stdout, stderr) = vendor(&update); + assert_eq!( + code, 0, + "an update that is not built yet is no failure.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env3 = parse_json_envelope(&stdout); + assert_eq!(env3["summary"]["failed"], 0, "nothing failed: {env3}"); + let kept = env3["events"] + .as_array() + .unwrap() + .iter() + .find(|e| e["errorCode"] == "vendor_prebuilt_platform_pending") + .unwrap_or_else(|| panic!("a vendor_prebuilt_platform_pending event: {env3}")); + assert_eq!(kept["action"], "skipped", "{kept}"); + let said = kept.to_string(); + assert!( + said.contains(&format!("kept the vendored patch {UUID}")) + && said.contains(&format!("`{}`", platforms[2])) + && said.contains(UUID_NEXT), + "the skip names the kept patch, the new one and the platform: {kept}" + ); + assert_eq!(std::fs::read(&gemfile_path).unwrap(), gemfile_wired); + assert_eq!(std::fs::read(&lock_path).unwrap(), lock_wired); + assert_eq!( + std::fs::read(proj.join(".socket/vendor/state.json")).unwrap(), + state_wired + ); + assert!( + !proj + .join(format!(".socket/vendor/gem/{UUID_NEXT}")) + .exists(), + "nothing of the unbuilt patch is written" + ); + assert_eq!(artifact_downloads(&update).await, Vec::::new()); + drop(update); + std::fs::write(&manifest_path, manifest).unwrap(); + + // 7. Revert: both files byte for byte, every tree gone. + let (code, stdout, stderr) = run_socket( + &proj, + &[ + "vendor", + "--revert", + "--json", + "--cwd", + proj.to_str().unwrap(), + ], + ); + assert_eq!( + code, 0, + "revert failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let renv = parse_json_envelope(&stdout); + assert_eq!(renv["summary"]["removed"], 1, "one entry reverted: {renv}"); + assert_eq!( + std::fs::read(&gemfile_path).unwrap(), + gemfile_before, + "revert must restore the Gemfile byte for byte" + ); + assert_eq!( + String::from_utf8(std::fs::read(&lock_path).unwrap()).unwrap(), + lock_text, + "revert must restore Gemfile.lock byte for byte" + ); + assert!(!proj.join(".socket/vendor").exists()); +} diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index ad50a715d..fc2401f1f 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -1445,23 +1445,8 @@ impl ApiClient { vendor_url: Option<&str>, patch_server_url: Option<&str>, ) -> VendorServiceOutcome { - if !is_uuid_shaped(uuid) { - return VendorServiceOutcome::Failed(ApiError::InvalidHash(format!( - "Invalid patch UUID: {uuid}" - ))); - } - // Circuit breaker: after consecutive retryable failures the service - // is down for this run — skip it without any I/O instead of paying - // every package's retries (and mixing sources package by package). - let failures = self.vendor_outage.load(Ordering::Relaxed); - if failures >= VENDOR_BREAKER_THRESHOLD { - // Worded to read inside the callers' "patch service request - // failed (...)" wrapper: no request was made, and the skip is - // scoped to this run. - return VendorServiceOutcome::Failed(ApiError::Other(format!( - "not attempted: the service failed for the previous {failures} packages in \ - this run" - ))); + if let Some(refused) = self.vendor_request_refused(uuid) { + return VendorServiceOutcome::Failed(refused); } // A download the attached plan already fetched stands in for the // live requests; everything around it (the breaker check above, the @@ -1485,7 +1470,35 @@ impl ApiClient { .await } }; - match &outcome { + self.note_vendor_outcome(&outcome, retryable_failure); + outcome + } + + /// Why a vendor-service call for `uuid` is answered without any I/O, if + /// it is: a malformed uuid, or the run-level circuit breaker — after + /// consecutive retryable failures the service is down for this run, so + /// it is skipped instead of paying every package's retries (and mixing + /// sources package by package). + fn vendor_request_refused(&self, uuid: &str) -> Option { + if !is_uuid_shaped(uuid) { + return Some(ApiError::InvalidHash(format!("Invalid patch UUID: {uuid}"))); + } + let failures = self.vendor_outage.load(Ordering::Relaxed); + // Worded to read inside the callers' "patch service request failed + // (...)" wrapper: no request was made, and the skip is scoped to + // this run. + (failures >= VENDOR_BREAKER_THRESHOLD).then(|| { + ApiError::Other(format!( + "not attempted: the service failed for the previous {failures} packages in \ + this run" + )) + }) + } + + /// Fold one vendor-service outcome into the circuit breaker's count of + /// consecutive retryable failures. + fn note_vendor_outcome(&self, outcome: &VendorServiceOutcome, retryable_failure: bool) { + match outcome { VendorServiceOutcome::Failed(_) if retryable_failure => { self.vendor_outage.fetch_add(1, Ordering::Relaxed); } @@ -1494,6 +1507,41 @@ impl ApiClient { VendorServiceOutcome::Failed(_) => {} _ => self.vendor_outage.store(0, Ordering::Relaxed), } + } + + /// Step 1 of [`Self::fetch_vendor_package`] on its own: what the + /// service lists for the patch besides its archive (the per-platform + /// gem prebuilds and their stub gemspecs), each with its host-rewritten + /// URL and sha512, and NO archive download. A backend that takes only + /// those artifacts learns here which exist. Same grant, statuses, retry + /// ladder and circuit breaker as the full fetch; a uuid the attached + /// plan names is answered from its reference batch. + pub(crate) async fn fetch_vendor_reference( + &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 (outcome, retryable_failure) = match self + .request_vendor_package(uuid, free_only, vendor_url) + .await + { + Ok(result) => ( + reference_miss(&result.status).unwrap_or_else(|| { + VendorServiceOutcome::Ready(served_secondary_artifacts( + &result, + patch_server_url, + )) + }), + false, + ), + Err((e, retryable)) => (VendorServiceOutcome::Failed(e), retryable), + }; + self.note_vendor_outcome(&outcome, retryable_failure); outcome } @@ -1583,22 +1631,8 @@ impl ApiClient { Err((e, retryable)) => return (VendorServiceOutcome::Failed(e), retryable), }; // Classify the build/grant status before attempting any download. - match result.status.as_str() { - "granted" | "reused" => {} - "pending_build" => return done(VendorServiceOutcome::Pending), - "build_failed" | "withdrawn" | "not_found" => { - return done(VendorServiceOutcome::Unavailable(result.status.clone())) - } - "forbidden" => { - return done(VendorServiceOutcome::Failed(ApiError::Forbidden( - "Forbidden: not entitled to this patch (paid tier or no org access).".into(), - ))) - } - other => { - return done(VendorServiceOutcome::Unavailable(format!( - "unknown status `{other}`" - ))) - } + if let Some(miss) = reference_miss(&result.status) { + return done(miss); } // Select the native tarball artifact and its sha512 (the universal @@ -1642,35 +1676,7 @@ impl ApiClient { return done(VendorServiceOutcome::Unavailable(PYPI_NOT_A_WHEEL.into())); } - // Surface the OTHER served artifacts (e.g. the gem path-source stub - // gemspec) — their host-rewritten URL + normalized sha512 — so a - // backend that needs one can download + verify it lazily. Each is - // skipped unless it carries both a url and a sha512. - let mut secondary_artifacts: Vec = Vec::new(); - if let Some(arts) = result.artifacts.as_ref() { - for a in arts { - if a.kind == "tarball" { - continue; - } - let (Some(url), Some(sha512)) = (a.url.as_deref(), a.integrity.sha512.as_deref()) - else { - continue; - }; - let url = match patch_server_url { - Some(base) => match rewrite_url_host(url, base) { - Ok(u) => u, - Err(_) => continue, - }, - None => url.to_string(), - }; - secondary_artifacts.push(SecondaryArtifact { - kind: a.kind.clone(), - url, - integrity_sri: normalize_sha512_sri(sha512), - prefetched: None, - }); - } - } + let secondary_artifacts = served_secondary_artifacts(&result, patch_server_url); // ── Step 2: download the prebuilt archive ────────────────────────── let downloaded = self.download_vendor_archive(&download_url, None).await; @@ -2127,6 +2133,9 @@ pub(crate) struct FetchedVendorPackage { #[derive(Debug, Clone)] pub(crate) struct SecondaryArtifact { pub kind: String, + /// The gem platform a `gem-platform` / `gem-platform-stub-gemspec` + /// artifact is for; `None` on every other kind. + pub platform: Option, pub url: String, /// Normalized `sha512-` of the artifact bytes. pub integrity_sri: String, @@ -2191,15 +2200,17 @@ impl std::fmt::Debug for PrefetchedSecondary { } } -/// Outcome of [`ApiClient::fetch_vendor_package`]. +/// Outcome of [`ApiClient::fetch_vendor_package`], and, with the served +/// artifact list in place of the archive, of +/// [`ApiClient::fetch_vendor_reference`]. /// /// The vendor backends map these onto the `auto`/`service`/`build` policy: /// `Ready` → use the service archive; `Pending`/`Unavailable`/`Failed` → fall /// back to a local build under `auto`, or hard-fail under `service`. #[derive(Debug)] -pub(crate) enum VendorServiceOutcome { +pub(crate) enum VendorServiceOutcome { /// Archive downloaded; integrity carried for the caller to verify. - Ready(FetchedVendorPackage), + Ready(T), /// The archive is still building (`pending_build` status or serve 408) — /// retryable. Pending, @@ -2210,6 +2221,59 @@ pub(crate) enum VendorServiceOutcome { Failed(ApiError), } +/// What a package reference's build/grant `status` settles on its own, +/// before any download: `None` for a granted one. +fn reference_miss(status: &str) -> Option> { + match status { + "granted" | "reused" => None, + "pending_build" => Some(VendorServiceOutcome::Pending), + "build_failed" | "withdrawn" | "not_found" => { + Some(VendorServiceOutcome::Unavailable(status.to_string())) + } + "forbidden" => Some(VendorServiceOutcome::Failed(ApiError::Forbidden( + "Forbidden: not entitled to this patch (paid tier or no org access).".into(), + ))), + other => Some(VendorServiceOutcome::Unavailable(format!( + "unknown status `{other}`" + ))), + } +} + +/// The served artifacts of a granted reference OTHER than the archive (the +/// gem path-source stub gemspec, the per-platform gem prebuilds, …) — their +/// host-rewritten URL + normalized sha512 — so a backend that needs one can +/// download + verify it lazily. Each is skipped unless it carries both a +/// url and a sha512. +fn served_secondary_artifacts( + result: &PackageVendorResult, + patch_server_url: Option<&str>, +) -> Vec { + let mut secondary_artifacts: Vec = Vec::new(); + for a in result.artifacts.iter().flatten() { + if a.kind == "tarball" { + continue; + } + let (Some(url), Some(sha512)) = (a.url.as_deref(), a.integrity.sha512.as_deref()) else { + continue; + }; + let url = match patch_server_url { + Some(base) => match rewrite_url_host(url, base) { + Ok(u) => u, + Err(_) => continue, + }, + None => url.to_string(), + }; + secondary_artifacts.push(SecondaryArtifact { + kind: a.kind.clone(), + platform: a.platform.clone(), + url, + integrity_sri: normalize_sha512_sri(sha512), + prefetched: None, + }); + } + secondary_artifacts +} + /// A serve GET's answer short of a failure. enum ServeDownload { Bytes(Vec), diff --git a/crates/socket-patch-core/src/api/types.rs b/crates/socket-patch-core/src/api/types.rs index bba41bcde..3ee1cb5cc 100644 --- a/crates/socket-patch-core/src/api/types.rs +++ b/crates/socket-patch-core/src/api/types.rs @@ -184,20 +184,22 @@ pub struct PackageVendorResult { /// One served artifact: the native tarball (`kind: "tarball"`), or a /// second artifact — npm's yarn-berry cache zip (`kind: "yarn-berry-zip"`), /// gem's path-source stub gemspec (`kind: "gem-stub-gemspec"`), or, per -/// built prebuild of a gem patch, the patched platform gem (`kind: -/// "gem-platform"`) and its stub gemspec (`kind: -/// "gem-platform-stub-gemspec"`). `url` is null only when the artifact isn't -/// stored yet (e.g. an unbuilt berry zip). +/// platform a gem patch has a prebuild for, the patched platform gem +/// (`kind: "gem-platform"`) and its stub gemspec +/// (`kind: "gem-platform-stub-gemspec"`). `url` is null only when the +/// artifact isn't stored yet (e.g. an unbuilt berry zip). #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PackageVendorArtifact { pub kind: String, #[serde(default)] pub url: Option, - /// The gem platform (`x86_64-linux-gnu`, `arm64-darwin`) the artifact - /// is built for: present exactly on the two per-prebuild kinds. Nothing - /// is decided by it, so a value that is no string reads as absent - /// instead of failing the whole response. + /// The gem platform the artifact is for (`x86_64-linux-gnu`, + /// `arm64-darwin`, `java`: `Gem::Platform#to_s` as `Gemfile.lock` + /// spells it, never `ruby`). Present exactly on the two `gem-platform*` + /// kinds; a patch with no prebuild serves neither. A value that is no + /// string reads as absent instead of failing the whole response: that + /// artifact is then the prebuild of no platform. #[serde(default, deserialize_with = "lenient_string")] pub platform: Option, /// Every ecosystem's tarball populates `sha512` (npm SRI form @@ -369,6 +371,47 @@ mod tests { ); } + /// A gem patch with prebuilds serves, beside the ruby gem's `tarball` + /// and stub, one `gem-platform` gem and stub per built platform; the + /// artifacts every patch served before carry no `platform`. + #[test] + fn package_vendor_result_reads_the_gem_platform_artifacts() { + let json = r#"{ + "status": "granted", + "purl": "pkg:gem/nokogiri@1.18.10?platform=ruby", + "url": "https://patch.example/nokogiri-1.18.10.gem", + "artifacts": [ + { "kind": "tarball", "url": "https://patch.example/nokogiri-1.18.10.gem", + "integrity": { "sha512": "sha512-ruby" } }, + { "kind": "gem-platform", "platform": "x86_64-linux-gnu", + "url": "https://patch.example/nokogiri-1.18.10-x86_64-linux-gnu.gem", + "contentType": "application/octet-stream", "sizeBytes": 4000000, + "integrity": { "sha512": "sha512-prebuild" } }, + { "kind": "gem-platform-stub-gemspec", "platform": "x86_64-linux-gnu", + "url": "https://patch.example/nokogiri-1.18.10-x86_64-linux-gnu.gemspec", + "integrity": { "sha512": "sha512-stub" } } + ] + }"#; + let result: PackageVendorResult = serde_json::from_str(json).unwrap(); + let artifacts = result.artifacts.unwrap(); + let seen: Vec<(&str, Option<&str>)> = artifacts + .iter() + .map(|a| (a.kind.as_str(), a.platform.as_deref())) + .collect(); + assert_eq!( + seen, + [ + ("tarball", None), + ("gem-platform", Some("x86_64-linux-gnu")), + ("gem-platform-stub-gemspec", Some("x86_64-linux-gnu")), + ] + ); + assert_eq!( + artifacts[1].integrity.sha512.as_deref(), + Some("sha512-prebuild") + ); + } + #[test] fn test_organizations_response_deserialize() { // Mirrors GET /v0/organizations: an object keyed by org id. `name` diff --git a/crates/socket-patch-core/src/formats/gem/hosted.rs b/crates/socket-patch-core/src/formats/gem/hosted.rs index 2d484bf91..7f7a9d87b 100644 --- a/crates/socket-patch-core/src/formats/gem/hosted.rs +++ b/crates/socket-patch-core/src/formats/gem/hosted.rs @@ -477,7 +477,7 @@ pub(crate) fn bundled_before_2_2(lock: &str) -> bool { /// The `major.minor` of the bundler the lock's `BUNDLED WITH` names, and /// the version as written. -fn bundled_with_version(lock: &str) -> Option<((u32, u32), &str)> { +pub(crate) fn bundled_with_version(lock: &str) -> Option<((u32, u32), &str)> { let mut lines = lock.lines().map(|l| l.trim_end_matches('\r')); let version = lines .by_ref() diff --git a/crates/socket-patch-core/src/formats/gem/mod.rs b/crates/socket-patch-core/src/formats/gem/mod.rs index 62915e9a2..9cd230b25 100644 --- a/crates/socket-patch-core/src/formats/gem/mod.rs +++ b/crates/socket-patch-core/src/formats/gem/mod.rs @@ -417,8 +417,10 @@ impl<'t> GemfileLock<'t> { /// The registry inventory: `GEM`-section `specs:` entries plus the /// bundler >= 2.6 `CHECKSUMS` sha256 pins when present (older locks stay - /// discovery-only). Platform-suffixed specs are skipped (platform gems - /// are unsupported for vendoring). Each spec resolves against its OWN + /// discovery-only). Platform-suffixed specs are skipped (the inventory + /// names the ruby-platform gem a registry serves; a gem locked as + /// platform gems is vendored from the patch service's prebuilt ones, + /// never from a registry). Each spec resolves against its OWN /// section's remote (bundler >= 2 emits one GEM section per source); a /// section with several distinct remotes (a legacy bundler 1.x /// multisource lock) leaves its specs without a resolved URL, fail diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 525dcc91a..2948d5da0 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -51,14 +51,64 @@ //! extensions are refused: bundler silently skips extension builds for path //! sources and the missing `.so` only fails at `require` time with a //! confusing error — refusing up front is the honest failure. - +//! +//! ## A gem locked as precompiled platform gems +//! +//! Bundler installs a native gem such as nokogiri as PRECOMPILED PLATFORM +//! gems: the lock holds one entry per platform +//! (`nokogiri (1.18.10-x86_64-linux-gnu)`, `nokogiri (1.18.10-arm64-darwin)`) +//! and usually no plain `nokogiri (1.18.10)`. Such a gem cannot be vendored +//! as its ruby-platform tree (the extensions would never be built), so it is +//! vendored as the patch service's PREBUILDS — the patched platform gems — +//! one unpacked tree per locked platform, each with the stub gemspec the +//! service serves for it (verified against real bundler 4.0.15): +//! +//! ```text +//! .socket/vendor/gem//-//… # the unpacked prebuild +//! .socket/vendor/gem//-//.gemspec +//! +//! PATH +//! remote: .socket/vendor/gem//- +//! specs: +//! (-) # every platform block, verbatim +//! () +//! (-) +//! () +//! ``` +//! +//! * the vendored dir, the Gemfile `path:` and the `PATH` `remote:` are the +//! ones of a ruby-platform gem: bundler's path glob (`{,*,*/*}.gemspec`) +//! finds the gemspec of every platform tree, locks one spec per platform +//! under the one section, and loads the tree of the running platform with +//! no build step; +//! * EVERY platform block of the gem moves into the section, and every +//! `CHECKSUMS` line of the gem becomes bare; +//! * the trees hold compiled extensions (`*.so`, `*.bundle`, a JRuby gem's +//! `*.jar`), which stock ignore templates name, so the uuid dir gets the +//! `.gitignore` (`!*`) and `.gitattributes` every backend that commits +//! binaries writes: they re-include the trees and keep a project filter +//! (a Git LFS rule, EOL conversion) off their bytes. A `.gitignore` a +//! prebuild ships inside its own tree would override that, so it is +//! emptied in the copy. A tree git would still not commit in full is +//! refused: wired without its binary, the gem would install everywhere +//! and fail to load; +//! * every locked platform needs a prebuild. While the service lists none +//! for one of them the gem is left as it is and reported as a skip +//! ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]): a prebuild is listed +//! only once built, so the next run may find it. A plain +//! ` ()` entry beside the platform ones (the ruby platform, +//! which no prebuilt tree serves) is refused with nothing written, and so +//! is a lock written by a bundler older than the layout was run against +//! (`PLATFORM_LAYOUT_MIN_BUNDLER`). + +use std::collections::HashMap; use std::path::{Path, PathBuf}; use serde_json::Value; use crate::formats::gem::gemfile; -use crate::manifest::schema::PatchRecord; -use crate::patch::apply::{ApplyResult, PatchSources}; +use crate::manifest::schema::{PatchFileInfo, PatchRecord}; +use crate::patch::apply::{normalize_file_path, ApplyResult, PatchSources}; use crate::patch::copy_tree::remove_tree; use crate::patch::path_safety::is_safe_single_segment; use crate::patch::redirect::gem_line_tail_blocks_edit; @@ -75,15 +125,18 @@ 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, fetch_verified_archive, fetch_verified_secondary, SecondaryArtifactResult, - ServicePolicy, + claim_prestaged, downloaded_warning, fetch_served_artifacts, fetch_verified_archive, + fetch_verified_platform_secondary, fetch_verified_secondary, SecondaryArtifactResult, + ServedArtifacts, ServicePolicy, }; use super::source::PackageSource; use super::state::{ write_marker_or_warn, VendorArtifact, VendorEntry, VendorMarker, WiringAction, WiringRecord, }; use super::{RevertOpts, RevertOutcome, VendorOutcome, VendorServiceConfig, VendorWarning}; -use crate::formats::gem::{is_plain_gem_token, listed_specs, split_checksum_entry, split_entry}; +use crate::formats::gem::{ + is_plain_gem_token, listed_specs, split_checksum_entry, split_entry, GemfileLock, +}; const GEMFILE: &str = "Gemfile"; const GEMFILE_LOCK: &str = "Gemfile.lock"; @@ -94,7 +147,8 @@ const GEMFILE_LOCK: &str = "Gemfile.lock"; /// /// `gemfile_lock_spec`: `original` and `new` are arrays of verbatim lock /// lines. In `original`, lines indented 4+ spaces are the gem's GEM spec -/// block and the single 2-space line (if any) other than a ` remote: ` line +/// block (one block per platform, in lock order, for a gem vendored as +/// platform gems) and the single 2-space line (if any) other than a ` remote: ` line /// is the pre-vendor DEPENDENCIES entry — its absence means the gem was /// transitive and revert deletes the added entry. A ` remote: ` line names /// the GEM section the block came from, and revert restores into it. It is @@ -107,7 +161,10 @@ const GEMFILE_LOCK: &str = "Gemfile.lock"; /// `gemfile_lock_checksum`: `original`/`new` are the verbatim CHECKSUMS line /// strings (the registry ` () sha256=` form vs the bare /// ` ()` path form). A SEPARATE record — never appended into -/// `gemfile_lock_spec`'s arrays, whose revert parses them positionally. +/// `gemfile_lock_spec`'s arrays, whose revert parses them positionally. For +/// a gem vendored as platform gems each is an ARRAY of such lines, one per +/// platform entry the edit made bare (`new`) and the registry line each +/// replaced (`original`); revert pairs them by their ` ()`. const GEMFILE_WIRING_KIND: &str = "gemfile_line"; const LOCK_WIRING_KIND: &str = "gemfile_lock_spec"; const LOCK_CHECKSUM_WIRING_KIND: &str = "gemfile_lock_checksum"; @@ -151,6 +208,52 @@ struct GemPrelude { /// ...and the committed copy is intact (the in-sync hot path, which /// never asks the service). copy_ok: bool, + /// The platforms the lock pins the gem for, in lock order, when it + /// locks it as precompiled platform gems (see the module docs): the + /// copy is then one prebuild tree per platform. Empty for the plain + /// `name (version)` entry, vendored as the gem's own tree. + platforms: Vec, +} + +/// What `Gemfile.lock` resolves `name`@`version` to, read from every source +/// section (`GEM`, `PATH`, `GIT`, `PLUGIN SOURCE`; a lock already vendored +/// holds the entries in our `PATH` section): the plain `name (version)` +/// entry of the ruby platform, and the platforms of its platform-suffixed +/// entries (`name (version-arm64-darwin)`), in lock order. +struct LockedGem { + plain: bool, + platforms: Vec, +} + +impl LockedGem { + /// No section resolves the gem at this version (#2075): there is no + /// entry to move into a `PATH` section. What [`listed_specs`] says of + /// the same lock. + fn absent(&self) -> bool { + !self.plain && self.platforms.is_empty() + } +} + +fn locked_gem(lock: &GemfileLock<'_>, name: &str, version: &str) -> LockedGem { + let mut locked = LockedGem { + plain: false, + platforms: Vec::new(), + }; + let specs = lock + .sections + .iter() + .flat_map(|s| s.specs.iter().filter_map(|l| l.parsed)) + .filter(|spec| spec.name == name && spec.version == version); + for spec in specs { + match spec.platform { + None => locked.plain = true, + Some(platform) if !locked.platforms.iter().any(|p| p == platform) => { + locked.platforms.push(platform.to_string()); + } + Some(_) => {} + } + } + locked } /// Why vendored mode must not wire this project's Gemfile, if it must not: @@ -209,19 +312,28 @@ fn version_not_locked_detail(name: &str, version: &str) -> String { ) } -/// The gem purls of `purls` whose version the project's `Gemfile.lock` -/// doesn't resolve, each with the [`GEM_VERSION_NOT_LOCKED`] refusal the -/// backend raises for it. A project that installs to a shared gem home -/// (the Bundler default) is crawled together with the versions Ruby ships -/// and the ones other projects installed; vendoring is a `Gemfile.lock` -/// edit, and for those versions there is no entry to edit (#2075, the -/// vendored twin of hosted mode's `redirect_gem_version_not_locked`). -/// A spec entry in any source section counts as resolved -/// ([`listed_specs`]). +/// The refusals the backend raises for the gem purls of `purls` from +/// `Gemfile.lock` alone, each with its purl, decided before the patch +/// service is asked for anything: /// -/// Read-only. Nothing is returned when bundler loads another manifest or -/// the lock can't be read: the backend reports those itself. -pub async fn gem_version_not_locked_refusals( +/// * [`GEM_VERSION_NOT_LOCKED`] for a version the lock doesn't resolve. A +/// project that installs to a shared gem home (the Bundler default) is +/// crawled together with the versions Ruby ships and the ones other +/// projects installed; vendoring is a `Gemfile.lock` edit, and for those +/// versions there is no entry to edit (#2075, the vendored twin of hosted +/// mode's `redirect_gem_version_not_locked`). A spec entry in any source +/// section counts as resolved. +/// * [`platform_lock_refusal`] for a gem the lock pins as platform gems in +/// a way that cannot be vendored (the ruby platform locked beside them, a +/// lock written by an older bundler). The CLI raises it with its other +/// pre-download refusals, so a gem under a hosted pin is refused BEFORE +/// the hosted→vendored takeover restores its upstream entry; refused by +/// the backend afterwards, it would end up unpatched in both modes. +/// +/// Read-only: the lock is read and parsed once for every purl. Nothing is +/// returned when bundler loads another manifest or the lock can't be read: +/// the backend reports those itself. +pub async fn gem_lock_refusals( project_root: &Path, purls: &[&str], ) -> Vec<(String, (&'static str, String))> { @@ -238,21 +350,32 @@ pub async fn gem_version_not_locked_refusals( let Ok(lock_text) = read_regular_to_string(&project_root.join(GEMFILE_LOCK)).await else { return Vec::new(); }; - let listed = listed_specs(&lock_text); + let lock = crate::formats::gem::parse(&lock_text); gems.into_iter() - .filter(|(_, name, version)| !listed.contains(&(name.as_str(), version.as_str()))) - .map(|(purl, name, version)| { - ( - purl.to_string(), - ( + .filter_map(|(purl, name, version)| { + let locked = locked_gem(&lock, &name, &version); + let refusal = match locked.absent() { + true => ( GEM_VERSION_NOT_LOCKED, version_not_locked_detail(&name, &version), ), - ) + false => platform_lock_refusal(&name, &version, &locked, &lock_text)?, + }; + Some((purl.to_string(), refusal)) }) .collect() } +/// The [`GEM_VERSION_NOT_LOCKED`] refusals of [`gem_lock_refusals`]. +pub async fn gem_version_not_locked_refusals( + project_root: &Path, + purls: &[&str], +) -> Vec<(String, (&'static str, String))> { + let mut refusals = gem_lock_refusals(project_root, purls).await; + refusals.retain(|(_, (code, _))| *code == GEM_VERSION_NOT_LOCKED); + refusals +} + /// The per-gem twin of [`gem_manifest_refusal`] for the hosted→vendored /// takeover: the backend's Gemfile declaration gate ([`plan_gemfile_edit`] /// and [`refuse_append_of_direct_dependency`], refused as @@ -369,20 +492,25 @@ async fn gem_prelude( )); } - // Platform-specific (precompiled) gem builds ship machine-specific - // artifacts — committing one would break every other platform — so they - // are refused, not guessed at. Two independent signals decide this: + // A platform-specific (precompiled) gem build ships machine-specific + // artifacts — committing ONE would break every other platform — so the + // installed build is never what gets vendored. Two independent signals + // say the copy is such a build: // // 1. The purl's own `?platform=` qualifier (the AUTHORITATIVE production // key). RubyGems' default portable platform is `ruby`; a bare purl - // (no qualifier) is likewise the portable build. Only a *native* - // platform value (`x86_64-linux`, `arm64-darwin`, `java`, - // `x64-mingw32`, …) is refused. - // 2. Defense in depth: the resolved install dir's own name. A - // locally-installed native variant is `--` - // even when the manifest purl looked portable (the crawler strips the - // suffix to the base purl, so a `?platform=ruby` lookup can still land - // on a native install dir). + // (no qualifier) is likewise the portable build. A *native* platform + // value (`x86_64-linux`, `arm64-darwin`, `java`, `x64-mingw32`, …) + // names a patch of one platform's build and is refused: a patch's + // prebuilds belong to its `ruby` record. + // 2. The resolved install dir's own name. A locally-installed native + // variant is `--` even when the manifest + // purl looked portable (the crawler strips the suffix to the base + // purl, so a `?platform=ruby` lookup can still land on a native + // install dir). Whether that is vendorable is the lock's to say, + // below: a lock that pins the gem as platform gems is vendored from + // the patch service's prebuilds for EVERY platform it pins (the + // installed dir is one of them, and is not read). // // Gating on the platform (not only the staging dir name) lets // `?platform=ruby` and bare purls vendor whatever the staging dir is @@ -402,21 +530,31 @@ async fn gem_prelude( .file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(); - // Fail closed: only two dir names are legitimate here — the gem's own + // Fail closed: only three dir names are legitimate here — the gem's own // `-` leaf (installed, or staged by - // a server download), and a literal `gem` staging dir, still - // admitted for compatibility though fetch_gem no longer produces it. - // Everything else is refused, including a `--` - // precompiled build; an allowlist (not a suffix match) means an unexpected - // install dir name can never slip through into a vendored copy. - if installed_path.is_dir() && dir_name != leaf && dir_name != "gem" { - return Err(refused( + // a server download), a literal `gem` staging dir, still + // admitted for compatibility though fetch_gem no longer produces it, and + // a `--` precompiled build, which is judged + // against the lock once it is read (below). Everything else is refused; + // an allowlist (not a suffix match) means an unexpected install dir + // name can never slip through into a vendored copy. + let installed_as_dir = installed_path.is_dir(); + let platform_install = installed_as_dir + && dir_name + .strip_prefix(leaf.as_str()) + .and_then(|rest| rest.strip_prefix('-')) + .is_some_and(|platform| !platform.is_empty()); + let not_portable = || { + refused( "platform_gem_unsupported", format!( "installed dir `{dir_name}` is not the portable `{leaf}` gem (platform-specific or unexpected gem builds cannot be vendored portably). {}", platform_gem_remedy(name) ), - )); + ) + }; + if installed_as_dir && dir_name != leaf && dir_name != "gem" && !platform_install { + return Err(not_portable()); } // ── project files ──────────────────────────────────────────────────── @@ -460,8 +598,8 @@ async fn gem_prelude( }; let (lock_eol, lock_text) = lock_lf_form(lock_text); // A version the lock doesn't resolve has no entry to move into a PATH - // section: an expected skip (see [`gem_version_not_locked_refusals`]), - // decided before the patch service is asked for anything. + // section: an expected skip (see [`gem_lock_refusals`]), decided before + // the patch service is asked for anything. if !listed_specs(&lock_text).contains(&(name, version)) { return Err(refused( GEM_VERSION_NOT_LOCKED, @@ -469,6 +607,23 @@ async fn gem_prelude( )); } + // ── a gem the lock pins as precompiled platform gems ───────────────── + // The lock decides what is vendored: the gem's own tree for the plain + // `name (version)` entry, the patch service's prebuilds for + // platform-suffixed ones (see the module docs). Decided here, before + // the patch service is asked for anything. + let locked = locked_gem(&crate::formats::gem::parse(&lock_text), name, version); + if locked.platforms.is_empty() { + // Locked for the ruby platform alone: the copy to vendor is the + // ruby gem's tree, which a precompiled install is not (and whose + // extensions bundler would never build from a `path:`). + if platform_install { + return Err(not_portable()); + } + } else if let Some((code, detail)) = platform_lock_refusal(name, version, &locked, &lock_text) { + return Err(refused(code, detail)); + } + let local_stub = { let spec_src = installed_path .parent() @@ -486,7 +641,10 @@ async fn gem_prelude( // Only the local stub is checked here (when present); the service stub is // re-checked in `gem_service_copy`, and a native gem emits no service stub // at all (the converter refuses it), so the service path also misses. - if let Some(text) = &local_stub { + // A gem locked as platform gems is vendored from prebuilds, which have + // nothing to build: an installed ruby-platform copy of it (compiled on + // this machine, beside the lock's platform gems) says nothing of them. + if let Some(text) = local_stub.as_ref().filter(|_| locked.platforms.is_empty()) { if gemspec_declares_extensions(text) { return Err(refused( "native_extensions_unsupported", @@ -507,7 +665,7 @@ async fn gem_prelude( lock_text.split('\n').any(|l| l == remote_line) && gemfile_text.contains(©_rel); let mut copy_ok = false; if lock_wired { - if lock_checksum_in_sync(&lock_text, name, version) { + if lock_checksum_in_sync(&lock_text, name, version, &locked.platforms) { // Probe the copy only once the lock is known to be wired (the // common fresh vendor has no copy to hash). Invalid-stub heal: a // project vendored before the stub check carries a defective @@ -516,11 +674,23 @@ async fn gem_prelude( // the artifact rebuild (which re-materialises a valid stub) // instead of the silent `already_vendored` no-op. The stub read // runs second so a hash mismatch short-circuits it. - copy_ok = copy_matches_after_hashes(©_dir, &record.files).await - && match read_regular_to_string(©_dir.join(format!("{name}.gemspec"))).await { - Ok(text) => gemspec_missing_required_attrs(&text).is_empty(), - Err(_) => false, - }; + copy_ok = match locked.platforms.as_slice() { + [] => { + copy_matches_after_hashes(©_dir, &record.files).await + && stub_gemspec_valid(©_dir, name).await + } + platforms => { + let inventory = recorded_inventory(project_root, &record.uuid, ©_rel).await; + platform_copy_intact( + ©_dir, + name, + platforms, + &record.files, + inventory.as_ref(), + ) + .await + } + }; } else { // Wired everywhere EXCEPT the lock's CHECKSUMS entry, which still // carries the registry form — a lock wired by a pre-CHECKSUMS-aware @@ -540,6 +710,22 @@ async fn gem_prelude( )); } } + // ── prebuilt trees git would not commit ────────────────────────────── + // Short of the in-sync no-op, this run (or the wet run a dry run + // previews) writes prebuilt binaries under the uuid dir. A rule that + // 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. + let in_sync = lock_wired && copy_ok; + if !locked.platforms.is_empty() && !in_sync { + if let Some((code, detail)) = + super::npm_dir::ignored_root_refusal(project_root, &uuid_dir_rel).await + { + return Err(refused(code, detail)); + } + } Ok(GemPrelude { name: name.to_string(), version: version.to_string(), @@ -553,9 +739,154 @@ async fn gem_prelude( lock_eol, lock_wired, copy_ok, + platforms: locked.platforms, }) } +/// The oldest bundler whose lock is wired to a directory of prebuilt +/// platform gems: the oldest one the layout is run against (the gate of the +/// real-bundler capstone in the CLI's `e2e_vendor_gem_build` suite, which +/// frozen-installs it on 2.3 up to 4.x). Whether an older bundler locks +/// one spec per platform for such a directory and loads the tree of the +/// running platform is not known, so its lock is left alone. +const PLATFORM_LAYOUT_MIN_BUNDLER: (u32, u32) = (2, 3); + +/// Why a gem the lock pins as platform gems cannot be vendored from +/// prebuilds, when the lock alone says so: it also locks the plain +/// `name (version)` entry — the ruby platform, which no prebuilt tree +/// serves and whose extensions bundler never builds for a `path:` gem — +/// one of its platforms is no directory name, or the bundler that wrote +/// the lock (`BUNDLED WITH`) is unknown or older than +/// [`PLATFORM_LAYOUT_MIN_BUNDLER`]. `None` for a gem the lock does not pin +/// as platform gems. +fn platform_lock_refusal( + name: &str, + version: &str, + locked: &LockedGem, + lock_text: &str, +) -> Option<(&'static str, String)> { + if locked.platforms.is_empty() { + return None; + } + if locked.plain { + let entries: Vec = locked + .platforms + .iter() + .map(|platform| format!("`{name} ({version}-{platform})`")) + .collect(); + return Some(( + "platform_gem_unsupported", + format!( + "{GEMFILE_LOCK} locks `{name} ({version})` (the ruby platform) beside the platform gems {}: a vendored directory of prebuilt platform gems has nothing for the ruby platform, and bundler never builds a `path:` gem's extensions. Remove the ruby platform from the lock (`bundle lock --remove-platform ruby`) to vendor {name}", + entries.join(", ") + ), + )); + } + // SECURITY: each platform names a directory under the copy dir. + if let Some(unsafe_platform) = locked.platforms.iter().find(|p| !is_platform_dir_name(p)) { + return Some(( + "unsafe_coordinates", + format!("unsafe gem platform `{unsafe_platform}` for `{name}` @ `{version}`"), + )); + } + let (major, minor) = PLATFORM_LAYOUT_MIN_BUNDLER; + let written_by = match crate::formats::gem::hosted::bundled_with_version(lock_text) { + Some((bundler, _)) if bundler >= PLATFORM_LAYOUT_MIN_BUNDLER => return None, + Some((_, written)) => format!("was written by Bundler {written}"), + None => "does not say which Bundler wrote it (no `BUNDLED WITH`)".to_string(), + }; + Some(( + "platform_gem_unsupported", + format!( + "{GEMFILE_LOCK} locks `{name}` as precompiled platform gems and {written_by}: a vendored directory of prebuilt platform gems needs Bundler {major}.{minor} or later, the oldest it is verified on. Re-lock with Bundler {major}.{minor} or later (`bundle update --bundler`) to vendor {name}" + ), + )) +} + +/// The [`platform_lock_refusal`]s of [`gem_lock_refusals`]. +pub async fn gem_platform_lock_refusals( + project_root: &Path, + purls: &[&str], +) -> Vec<(String, (&'static str, String))> { + let mut refusals = gem_lock_refusals(project_root, purls).await; + refusals.retain(|(_, (code, _))| *code != GEM_VERSION_NOT_LOCKED); + refusals +} + +/// Whether a gem platform may name a directory under the vendored dir: one +/// safe path segment in the plain gem-token charset. The platforms of a +/// lock entry and of a ledger entry both come from committed, tamper-able +/// files. +pub(super) fn is_platform_dir_name(platform: &str) -> bool { + is_safe_single_segment(platform) && is_plain_gem_token(platform) +} + +/// Whether `tree` holds the stub gemspec of the gem `name` +/// (`.gemspec`, which a path source needs) with the attributes +/// 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 { + Ok(text) => gemspec_missing_required_attrs(&text).is_empty(), + Err(_) => false, + } +} + +/// The file inventory the vendor ledger records for the copy at +/// `copy_rel` of the patch `uuid`: what vouches for the bytes of its +/// prebuild trees once they are vendored (see [`verify_platform_tree`]). +/// `None` when the ledger has no entry for that copy, records no inventory +/// for it, or cannot be read. +/// +/// [`verify_platform_tree`]: super::verify::verify_platform_tree +async fn recorded_inventory( + project_root: &Path, + uuid: &str, + copy_rel: &str, +) -> Option> { + let state = super::state::load_state_shared(project_root).await.ok()?; + state + .entries + .values() + .find(|e| { + e.ecosystem == "gem" && e.uuid == uuid && e.artifact.path.replace('\\', "/") == copy_rel + }) + .and_then(|e| e.artifact.file_inventory.clone()) +} + +/// The in-sync test of a copy vendored as platform gems: the tree of every +/// locked platform is there, passes +/// [`super::verify::verify_platform_tree`] (every file of it is the one +/// the ledger's `inventory` of the copy records; without an inventory it +/// must hold a patched file) and has a valid stub gemspec. With an +/// inventory, the copy as a whole must also match it, as `vendor --check` +/// requires: a file outside every locked tree (at the copy root, or the +/// tree of a platform the lock does not name) is not in sync. +async fn platform_copy_intact( + copy_dir: &Path, + name: &str, + platforms: &[String], + files: &HashMap, + inventory: Option<&std::collections::BTreeMap>, +) -> bool { + for platform in platforms { + let tree = copy_dir.join(platform); + let voucher = super::verify::TreeVoucher::Ledger(inventory); + if super::verify::verify_platform_tree(&tree, files, voucher) + .await + .is_err() + || !stub_gemspec_valid(&tree, name).await + { + return false; + } + } + match inventory { + Some(inventory) => super::verify::verify_dir_inventory(copy_dir, inventory, None) + .await + .is_ok(), + None => true, + } +} + /// A fresh wet vendor's pure edits, computed before any download or write: /// the Gemfile declaration plan (refused when not editable) and the /// Gemfile.lock surgery (a failed `Done` when the lock's shape defeats it). @@ -612,7 +943,19 @@ fn gem_edits( // ── Gemfile.lock edit (pure text surgery, computed before any write) ── // A lock-shape failure therefore costs no download / copy / patch and no // Gemfile write. - let lock_edit = match edit_lock(&prelude.lock_text, name, version, &prelude.copy_rel) { + let lock_edit = edit_lock(&prelude.lock_text, name, version, &prelude.copy_rel).and_then( + |edit| match edit.platforms == prelude.platforms { + true => Ok(edit), + // The copy holds one prebuild per platform the lock resolves + // the gem for, and the edit moves the entries of one section: + // an entry it leaves behind (in a GIT or foreign PATH section) + // would have a tree and no spec in the vendored section. + false => Err(format!( + "Gemfile.lock lists platform entries of `{name} ({version})` outside the one section the edit moves" + )), + }, + ); + let lock_edit = match lock_edit { Ok(edit) => edit, Err(e) => { return Err(Box::new(done( @@ -629,11 +972,14 @@ fn gem_edits( Ok((plan, lock_edit)) } -/// Whether [`vendor_gem`] — a wet run with the service enabled — asks the -/// patch service for `record`: past every refusal it raises first +/// The archive download [`vendor_gem`] — a wet run with the service +/// enabled — makes for `record`: past every refusal it raises first /// ([`gem_prelude`], [`gem_edits`]) and not answered by the in-sync hot /// path. The vendor loop's download plan consults this; the `.gem`'s -/// `gem-stub-gemspec` secondary rides the same planned download. +/// `gem-stub-gemspec` secondary rides the same planned download. `None` +/// for a gem the lock pins as platform gems: it is vendored from the +/// prebuilds the service's package reference lists +/// ([`stage_platform_prebuilds`]), and the ruby gem is never downloaded. pub(crate) async fn service_preflight( purl: &str, installed_path: &Path, @@ -647,16 +993,18 @@ pub(crate) async fn service_preflight( true => !prelude.copy_ok, false => gem_edits(purl, &prelude).is_ok(), }; - // `gem_service_copy` fetches the stub gemspec right after the `.gem`, - // and extracts the `.gem`'s data.tar.gz into the copy dir's stage. - asks.then(|| crate::api::client::PlannedDownload { - secondary: Some(GEM_STUB_ARTIFACT_KIND.to_string()), - stage: Some(super::prestage::PrestageRecipe::extract( - project_root, - &prelude.copy_dir, - extract_gem_data, - )), - ..crate::api::client::PlannedDownload::archive(record.uuid.clone()) + (asks && prelude.platforms.is_empty()).then(|| { + // `gem_service_copy` fetches the stub gemspec right after the `.gem`, + // and extracts the `.gem`'s data.tar.gz into the copy dir's stage. + crate::api::client::PlannedDownload { + secondary: Some(GEM_STUB_ARTIFACT_KIND.to_string()), + stage: Some(super::prestage::PrestageRecipe::extract( + project_root, + &prelude.copy_dir, + extract_gem_data, + )), + ..crate::api::client::PlannedDownload::archive(record.uuid.clone()) + } }) } @@ -690,6 +1038,7 @@ pub async fn vendor_gem<'a>( lock_eol, lock_wired, copy_ok, + platforms, } = &prelude; let (name, version) = (name.as_str(), version.as_str()); let (copy_rel, uuid_dir, copy_dir) = @@ -703,10 +1052,26 @@ pub async fn vendor_gem<'a>( // 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}"), + ), + )); + } + } return done( already_patched_result(purl, copy_dir, &record.files), None, - Vec::new(), + warnings, ); } // Wired (Gemfile + lock + CHECKSUMS) but the committed copy is @@ -728,6 +1093,7 @@ pub async fn vendor_gem<'a>( copy_dir, uuid_dir, name, + platforms, record, false, // live-wired: never unwind the uuid dir on failure service, @@ -736,7 +1102,7 @@ pub async fn vendor_gem<'a>( .await { Ok(result) => result, - Err(outcome) => return *outcome, + Err(outcome) => return rebuild_needs_every_prebuild(*outcome), }; if !result.success { return done(result, None, warnings); @@ -759,6 +1125,7 @@ pub async fn vendor_gem<'a>( build_gem_purl(name, version), record, copy_rel.to_string(), + platforms, file_inventory, Vec::new(), ); @@ -776,10 +1143,15 @@ pub async fn vendor_gem<'a>( return *outcome; } } - if let Err(outcome) = - super::service_fetch::preview_service(service, record, extract_gem_data).await - { - return *outcome; + let previewed = match platforms.as_slice() { + [] => super::service_fetch::preview_service(service, record, extract_gem_data).await, + platforms => preview_platform_prebuilds(service, record, name, platforms).await, + }; + if let Err(outcome) = previewed { + return match lock_wired { + true => rebuild_needs_every_prebuild(*outcome), + false => *outcome, + }; } return done( super::common::preview_result(purl, copy_dir, &record.files), @@ -807,6 +1179,7 @@ pub async fn vendor_gem<'a>( copy_dir, uuid_dir, name, + platforms, record, true, // fresh vendor: nothing pre-existing worth keeping service, @@ -824,6 +1197,29 @@ pub async fn vendor_gem<'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. + 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); + } + // ── Gemfile edit ───────────────────────────────────────────────────── // Both project files are user-owned: preserve their permission bits. let new_gemfile = apply_gemfile_plan(gemfile_text, &plan); @@ -926,42 +1322,51 @@ pub async fn vendor_gem<'a>( // rides in its OWN record: revert must restore the registry `sha256=` // line verbatim — it is not recomputable offline, and a bare entry on a // registry-sourced gem hard-fails frozen installs (spike, exit 16). - if let Some((orig_line, new_line)) = &lock_edit.checksum_rewrite { + // One line for the plain entry, one per rewritten platform entry for a + // gem vendored as platform gems (see [`LOCK_CHECKSUM_WIRING_KIND`]). + let checksum_lines = |lines: Vec| match platforms.is_empty() { + true => lines.into_iter().next().map(Value::String), + false => Some(to_array(lines)), + }; + let (originals, bares): (Vec, Vec) = + lock_edit.checksum_rewrites.iter().cloned().unzip(); + if !bares.is_empty() { wiring.push(WiringRecord { file: GEMFILE_LOCK.to_string(), kind: LOCK_CHECKSUM_WIRING_KIND.to_string(), action: WiringAction::Rewritten, key: Some(name.to_string()), - original: Some(Value::String(orig_line.clone())), - new: Some(Value::String(new_line.clone())), + original: checksum_lines(originals), + new: checksum_lines(bares), }); - } else if lock_edit.rewired_ours { + } else if lock_edit.rewired_ours && !lock_edit.checksum_bare.is_empty() { // Re-vendor with the bare path-form line already in place (our // previous run stripped the registry token): the record must ride // again with `original: None` — dropped, the first run's registry // `sha256=` line would vanish from the ledger with the entry being // replaced, and a later --revert could no longer restore it (a bare // leftover on a registry gem hard-fails frozen installs, exit 16). - if let Some(bare) = &lock_edit.checksum_bare { - wiring.push(WiringRecord { - file: GEMFILE_LOCK.to_string(), - kind: LOCK_CHECKSUM_WIRING_KIND.to_string(), - action: WiringAction::Rewritten, - key: Some(name.to_string()), - original: None, - new: Some(Value::String(bare.clone())), - }); - } + wiring.push(WiringRecord { + file: GEMFILE_LOCK.to_string(), + kind: LOCK_CHECKSUM_WIRING_KIND.to_string(), + action: WiringAction::Rewritten, + key: Some(name.to_string()), + original: None, + new: checksum_lines(lock_edit.checksum_bare.clone()), + }); } // The whole tree, stub gemspec included: no lockfile integrity covers a // path source's bytes. - let file_inventory = - inventory_or_warn(copy_dir, &format!("{name}@{version}"), &mut warnings).await; + let file_inventory = match platform_inventory { + Some(inventory) => inventory, + None => inventory_or_warn(copy_dir, &format!("{name}@{version}"), &mut warnings).await, + }; let entry = gem_entry( base_purl, record, copy_rel.to_string(), + platforms, file_inventory, wiring, ); @@ -969,30 +1374,52 @@ pub async fn vendor_gem<'a>( done(result, Some(entry), warnings) } +/// The outcome of rebuilding a copy the lock is ALREADY wired to when the +/// service lists no prebuild for one of its platforms. For a gem that is +/// not vendored yet that is a skip +/// ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]): nothing depends on the +/// copy. Here the lock names a tree that is missing or damaged, and no +/// older patch stands in for it, so it is the plain miss, a failure. +fn rebuild_needs_every_prebuild(outcome: VendorOutcome) -> VendorOutcome { + match outcome { + VendorOutcome::Refused { code, detail } + if code == super::VENDOR_PREBUILT_PLATFORM_PENDING => + { + refused(super::VENDOR_PREBUILT_REQUIRED, detail) + } + other => other, + } +} + /// The ledger entry for a vendored gem copy: `wiring` is the Gemfile + lock /// records on a full vendor, empty on an artifact-only rebuild (see the hot -/// path). +/// path). `platforms` are the platform trees of a copy vendored as platform +/// gems (empty for the gem's own tree). fn gem_entry( base_purl: String, record: &PatchRecord, copy_rel: String, + platforms: &[String], file_inventory: Option>, wiring: Vec, ) -> VendorEntry { - VendorEntry::new( - "gem".to_string(), - base_purl, - record.uuid.clone(), - VendorArtifact { - yarn_berry10c0: None, - path: copy_rel, - sha256: String::new(), // dir-shaped: whole-tree integrity is the inventory - size: None, - platform_locked: None, - file_inventory, - }, - wiring, - ) + VendorEntry { + gem_platforms: platforms.to_vec(), + ..VendorEntry::new( + "gem".to_string(), + base_purl, + record.uuid.clone(), + VendorArtifact { + yarn_berry10c0: None, + path: copy_rel, + sha256: String::new(), // dir-shaped: whole-tree integrity is the inventory + size: None, + platform_locked: None, + file_inventory, + }, + wiring, + ) + } } /// The path-source stub gemspec served as the gem's SECOND artifact, alongside @@ -1044,48 +1471,7 @@ pub(super) async fn gem_service_copy( return Err(policy.miss(format!("could not fetch the stub gemspec ({reason})"))); } }; - let stub_text = String::from_utf8_lossy(&stub); - - // Defense in depth: the converter does not emit a stub for native gems, but - // refuse one here too — bundler silently skips extension builds for path - // sources, so a native gem would install and then fail at `require` time. - if gemspec_declares_extensions(&stub_text) { - return Err(policy.hard( - "native_extensions_unsupported", - format!( - "the served stub gemspec for {name} declares native extensions; bundler does \ - not build extensions for path-sourced gems. {}", - // The Gemfile plan passed before the service was asked, so - // the declaration is one hosted mode can edit too. - native_extensions_remedy(name, true) - ), - )); - } - - // Bundler rejects path-source gemspecs without summary/authors. Refuse - // before writing anything, so invalid stubs leave no partial artifact. - let missing_attrs = gemspec_missing_required_attrs(&stub_text); - if !missing_attrs.is_empty() { - let licenses_note = if gemspec_assigns_attr(&stub_text, &["licenses", "license"]) { - "" - } else { - " (it also omits `licenses`, a rubygems warning)" - }; - let reason = format!( - "the served stub gemspec for {name} is invalid: it does not assign the \ - rubygems-required attribute(s) {}{licenses_note}; bundler validates \ - path-source gemspecs, so vendoring it would make every later \ - `bundle install` fail", - missing_attrs.join(", "), - ); - return Err(policy.hard( - "vendor_prebuilt_stub_invalid", - format!( - "{}. Retry after the patch service publishes a corrected artifact", - reason - ), - )); - } + refuse_unusable_stub(policy, name, name, &String::from_utf8_lossy(&stub))?; // Extract the patched `.gem`'s data.tar.gz into a STAGE sibling, add the // stub as `.gemspec` (a `.gem`'s data.tar.gz never carries one — @@ -1139,52 +1525,536 @@ pub(super) async fn gem_service_copy( Ok(()) } -/// Acquire a verified service copy without replacing the prior copy on failure. -#[allow(clippy::too_many_arguments)] -async fn materialise_patched_copy( - purl: &str, - copy_dir: &Path, - uuid_dir: &Path, +/// Why the stub gemspec the service served for `subject` (the gem `name`, +/// or one platform's prebuild of it) cannot be vendored, checked before +/// anything is written so an unusable stub leaves no partial artifact. +fn refuse_unusable_stub( + policy: ServicePolicy<'_>, name: &str, - record: &PatchRecord, - unwind_uuid_dir: bool, - service: Option<&VendorServiceConfig>, - warnings: &mut Vec, -) -> Result> { - gem_service_copy( - service, - record, - name, - copy_dir, - uuid_dir, - unwind_uuid_dir, - warnings, - ) - .await?; - Ok(already_patched_result(purl, copy_dir, &record.files)) -} + subject: &str, + stub_text: &str, +) -> Result<(), Box> { + // Defense in depth: the converter does not emit a stub for native gems, but + // refuse one here too — bundler silently skips extension builds for path + // sources, so a native gem would install and then fail at `require` time. + if gemspec_declares_extensions(stub_text) { + return Err(policy.hard( + "native_extensions_unsupported", + format!( + "the served stub gemspec for {subject} declares native extensions; bundler does \ + not build extensions for path-sourced gems. {}", + // The Gemfile plan passed before the service was asked, so + // the declaration is one hosted mode can edit too. + native_extensions_remedy(name, true) + ), + )); + } -/// Revert a gem vendor entry: restore the Gemfile line / delete the managed -/// block, splice the lock's spec block back into GEM specs (sorted), the -/// original DEPENDENCIES entry back in and the registry CHECKSUMS line back -/// over the bare path form, then remove the validated uuid dir. -/// A fragment that no longer looks like what vendor wrote — a hand edit, a -/// `bundle update`, a newer vendor run — gets a `vendor_lock_entry_drifted` -/// warning, and then neither file is written: the Gemfile and the lock are -/// reverted together or not at all (#988). -pub async fn revert_gem(entry: &VendorEntry, project_root: &Path, dry_run: bool) -> RevertOutcome { - revert_gem_opts(entry, project_root, RevertOpts::new(dry_run)).await + // Bundler rejects path-source gemspecs without summary/authors. + let missing_attrs = gemspec_missing_required_attrs(stub_text); + if !missing_attrs.is_empty() { + let licenses_note = if gemspec_assigns_attr(stub_text, &["licenses", "license"]) { + "" + } else { + " (it also omits `licenses`, a rubygems warning)" + }; + let reason = format!( + "the served stub gemspec for {subject} is invalid: it does not assign the \ + rubygems-required attribute(s) {}{licenses_note}; bundler validates \ + path-source gemspecs, so vendoring it would make every later \ + `bundle install` fail", + missing_attrs.join(", "), + ); + return Err(policy.hard( + "vendor_prebuilt_stub_invalid", + format!( + "{}. Retry after the patch service publishes a corrected artifact", + reason + ), + )); + } + Ok(()) } -/// [`revert_gem`] with full [`RevertOpts`]: `keep_artifact` skips ONLY the -/// artifact deletion; the wiring restore — and the empty-wiring refusal, -/// which applies under `keep_artifact` too — runs unchanged. +/// The patched platform gem the patch service built for one platform of a +/// gem (a "prebuild": a drop-in for the upstream platform gem, with the +/// patch's files replaced and the extension rebuilt), and the stub gemspec +/// it serves for it — the per-platform twins of the `tarball` and +/// [`GEM_STUB_ARTIFACT_KIND`] artifacts. Each names its platform, and a +/// platform with no prebuild built has neither. +pub(crate) const GEM_PLATFORM_ARTIFACT_KIND: &str = "gem-platform"; +pub(crate) const GEM_PLATFORM_STUB_ARTIFACT_KIND: &str = "gem-platform-stub-gemspec"; + +/// How many platforms' prebuilds (a platform gem and its stub gemspec +/// each) are downloaded at once. +const PREBUILD_DOWNLOADS_AT_ONCE: usize = 4; + +/// Download and verify the prebuild of each of `platforms` and its stub +/// gemspec, and unpack them into `stage`: `//` holds the +/// platform gem's files and `.gemspec` (see the module docs). /// -/// LOSSINESS GUARD (the [`RevertOutcome`] contract every backend honors): a -/// record left alone as genuine drift keeps the artifact dir (and the caller -/// keeps the ledger entry) — the Gemfile `path:` or the lock's PATH section -/// may still route through it, and the entry holds the only pre-vendor -/// originals. A record whose live state already equals its reverted state +/// Which prebuilds exist is read off the service's package reference +/// alone; the ruby gem that reference also names is never downloaded +/// (bundler would have to build its extensions). While the service lists +/// no prebuild, or no stub, for one of `platforms`, nothing is downloaded +/// and the gem is skipped ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]). A +/// later failure leaves a partial `stage` for the caller to remove. +/// Returns the run's advisories: the download, and the ignore files that +/// were emptied. +async fn stage_platform_prebuilds( + cfg: &VendorServiceConfig, + record: &PatchRecord, + name: &str, + platforms: &[String], + stage: &Path, +) -> Result, Box> { + use futures_util::StreamExt as _; + let policy = ServicePolicy::Refused; + // SECURITY: a platform names a directory under the stage, and the + // ledger a restore reads them from is committed, tamper-able data. + if let Some(platform) = platforms.iter().find(|p| !is_platform_dir_name(p)) { + return Err(policy.hard( + "unsafe_coordinates", + format!("unsafe gem platform `{platform}` for `{name}`"), + )); + } + let listed = fetch_served_artifacts(cfg, &record.uuid).await; + let served = policy.settle(listed, "platform gem", &format!("platform gems for {name}"))?; + + let missing: Vec<&str> = platforms + .iter() + .map(String::as_str) + .filter(|platform| { + served + .platform(GEM_PLATFORM_ARTIFACT_KIND, platform) + .is_none() + || served + .platform(GEM_PLATFORM_STUB_ARTIFACT_KIND, platform) + .is_none() + }) + .collect(); + if !missing.is_empty() { + let quoted = |platforms: &[&str]| { + platforms + .iter() + .map(|platform| format!("`{platform}`")) + .collect::>() + .join(", ") + }; + let built: Vec<&str> = platforms + .iter() + .map(String::as_str) + .filter(|platform| !missing.contains(platform)) + .collect(); + let built = match built.as_slice() { + [] => "it has none of the locked platforms".to_string(), + built => format!("it has {}", quoted(built)), + }; + // Not a failure: a prebuild is listed only once it is built, so + // this is as likely "not yet" as "never", and nothing was touched. + return Err(Box::new(refused( + super::VENDOR_PREBUILT_PLATFORM_PENDING, + format!( + "the patch service has no prebuilt platform gem of `{name}` for {} yet \ + ({built}); {GEMFILE_LOCK} locks {name} as precompiled platform gems and bundler \ + never builds a `path:` gem's extensions, so the patch is not vendored until \ + every locked platform has one", + quoted(&missing) + ), + ))); + } + + // The prebuilds, a few platforms at a time and taken in lock order. + let served = &served; + let mut downloads = std::pin::pin!(futures_util::stream::iter(platforms) + .map(|platform| async move { + let subject = format!("{name} ({platform})"); + let gem = platform_artifact( + cfg, + served, + GEM_PLATFORM_ARTIFACT_KIND, + platform, + "platform gem", + &subject, + ) + .await?; + let stub = platform_artifact( + cfg, + served, + GEM_PLATFORM_STUB_ARTIFACT_KIND, + platform, + "stub gemspec", + &subject, + ) + .await?; + Ok::<_, Box>((platform, subject, gem, stub)) + }) + .buffered(PREBUILD_DOWNLOADS_AT_ONCE)); + + let mut emptied: Vec = Vec::new(); + while let Some(downloaded) = downloads.next().await { + let (platform, subject, gem, stub) = downloaded?; + refuse_unusable_stub(policy, name, &subject, &String::from_utf8_lossy(&stub))?; + + let tree = stage.join(platform); + if let Err(e) = tokio::fs::create_dir_all(&tree).await { + return Err(policy.hard( + "vendor_prebuilt_write_failed", + format!("cannot create {}: {e}", tree.display()), + )); + } + if let Err(e) = extract_on_blocking_pool(gem, &tree, extract_gem_data).await { + return Err(policy.hard( + "vendor_prebuilt_extract_failed", + format!("cannot extract the prebuilt platform gem for {subject}: {e}"), + )); + } + match empty_shipped_gitignores(&tree, &record.files).await { + Ok(files) => emptied.extend(files.into_iter().map(|file| format!("{platform}/{file}"))), + Err(e) => { + return Err(policy.hard( + "vendor_prebuilt_write_failed", + format!("cannot empty a `.gitignore` the prebuilt platform gem for {subject} ships: {e}"), + )); + } + } + if let Err(e) = tokio::fs::write(tree.join(format!("{name}.gemspec")), &stub).await { + return Err(policy.hard( + "vendor_prebuilt_write_failed", + format!("cannot write the stub gemspec for {subject} into the vendored dir: {e}"), + )); + } + // `gem` passed the service's digest for this platform above + // (`platform_artifact`), which is what vouches for a tree that + // ships none of the patched files: only one it does ship can + // contradict the patch. + let verified = super::verify::TreeVoucher::VerifiedDownload; + if super::verify::verify_platform_tree(&tree, &record.files, verified) + .await + .is_err() + { + return Err(policy.miss(format!( + "prebuilt platform gem for {subject} does not carry the patch (a patched \ + file it ships is not the patched one)" + ))); + } + } + + let source_url = platforms + .first() + .and_then(|platform| served.platform(GEM_PLATFORM_ARTIFACT_KIND, platform)) + .map(|artifact| artifact.url.as_str()) + .unwrap_or_default(); + let mut warnings = vec![downloaded_warning( + format_args!( + "{name} as prebuilt platform gems ({})", + platforms.join(", ") + ), + source_url, + )]; + if !emptied.is_empty() { + warnings.push(VendorWarning::new( + GITIGNORE_NEUTRALIZED, + format!( + "{name}: the prebuilt platform gems ship their own `.gitignore` ({}), whose \ + rules would keep git from committing files of the vendored trees; emptied in \ + the vendored copy (commit it)", + super::npm_dir::summarize_rules(&emptied) + ), + )); + } + Ok(warnings) +} + +/// The advisory of [`empty_shipped_gitignores`]: the vendored trees differ +/// from the prebuilds in the ignore files named. +const GITIGNORE_NEUTRALIZED: &str = "vendor_gem_gitignore_neutralized"; + +/// Empty every `.gitignore` a prebuild ships inside `tree`. Git reads one +/// at any depth, and for the files below it its rules win over the uuid +/// dir's `!*`: a `*.so` rule the gem's own repository used would leave the +/// binary out of the commit, with no rule of the project's to remove. The +/// file stays, empty, so the tree keeps the gem's file list — the way the +/// Composer backend neutralises the filters of a mirrored copy. Done while +/// the tree is staged, so the ledger's inventory and `repair`'s restore +/// 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 +/// emptied, relative to `tree`. +async fn empty_shipped_gitignores( + tree: &Path, + files: &HashMap, +) -> std::io::Result> { + let root = tree.to_path_buf(); + let shipped = tokio::task::spawn_blocking(move || { + let mut shipped: Vec<(PathBuf, String)> = Vec::new(); + // Links are not followed (and none is extracted): only the + // regular files of the tree itself. + for entry in walkdir::WalkDir::new(&root).sort_by_file_name() { + let entry = entry?; + if entry.file_name() != ".gitignore" + || !entry.file_type().is_file() + || entry.metadata()?.len() == 0 + { + continue; + } + let rel = entry + .path() + .strip_prefix(&root) + .map_err(std::io::Error::other)? + .to_string_lossy() + .replace('\\', "/"); + shipped.push((entry.into_path(), rel)); + } + Ok::<_, std::io::Error>(shipped) + }) + .await + .map_err(std::io::Error::other)??; + let mut emptied = Vec::new(); + for (path, rel) in shipped { + if files.keys().any(|key| normalize_file_path(key) == rel) { + continue; + } + atomic_write_bytes_preserving_mode(&path, b"").await?; + emptied.push(rel); + } + Ok(emptied) +} + +/// One per-platform artifact of `kind` (`what`, for messages about +/// `subject`), downloaded and verified against its served integrity like +/// the ruby gem's stub: a mismatch is never vendored. The check is not +/// optional: an artifact the service states no digest for is not listed +/// at all, and for a prebuild that ships none of the patched files it is +/// the only evidence that the tree is the patched build. +async fn platform_artifact( + cfg: &VendorServiceConfig, + served: &ServedArtifacts, + kind: &str, + platform: &str, + what: &str, + subject: &str, +) -> Result, Box> { + let policy = ServicePolicy::Refused; + match fetch_verified_platform_secondary(cfg, served, kind, platform).await { + SecondaryArtifactResult::Ready(bytes) => Ok(bytes), + SecondaryArtifactResult::Absent => { + Err(policy.miss(format!("the patch service served no {what} for {subject}"))) + } + SecondaryArtifactResult::IntegrityMismatch(reason) => Err(policy.hard( + "vendor_prebuilt_integrity_mismatch", + format!( + "prebuilt {what} for {subject} failed integrity verification ({reason}); \ + refusing to vendor tampered bytes" + ), + )), + SecondaryArtifactResult::Failed(reason) => Err(policy.miss(format!( + "could not fetch the {what} for {subject} ({reason})" + ))), + } +} + +/// [`gem_service_copy`] for a gem the lock pins as platform gems: the copy +/// is the verified prebuild of each of `platforms`, staged in full and then +/// swapped into place, so a failure leaves any pre-existing (possibly +/// live-wired) copy untouched and no husk behind. The uuid dir's git +/// metadata is the caller's to write ([`restore_uuid_metadata`]): +/// `copy_dir` may itself sit in a stage (`repair`'s restore). +#[allow(clippy::too_many_arguments)] +pub(super) async fn gem_platform_service_copy( + service: Option<&VendorServiceConfig>, + record: &PatchRecord, + name: &str, + platforms: &[String], + copy_dir: &Path, + uuid_dir: &Path, + unwind_uuid_dir: bool, + warnings: &mut Vec, +) -> Result<(), Box> { + let cfg = service + .filter(|cfg| cfg.service_enabled()) + .ok_or_else(|| Box::new(super::service_fetch::required()))?; + let stage = stage_dir_for(copy_dir); + let _ = remove_tree(&stage).await; + let staged = match stage_platform_prebuilds(cfg, record, name, platforms, &stage).await { + Ok(staged) => staged, + Err(outcome) => { + cleanup_failed_stage(&stage, uuid_dir, unwind_uuid_dir).await; + return Err(outcome); + } + }; + if let Err(e) = swap_stage_into_place(&stage, copy_dir).await { + cleanup_failed_stage(&stage, uuid_dir, unwind_uuid_dir).await; + return Err(ServicePolicy::Refused.hard( + "vendor_prebuilt_write_failed", + format!("cannot move the extracted platform gems into place: {e}"), + )); + } + warnings.extend(staged); + Ok(()) +} + +/// `/.gitignore` of a gem vendored as platform gems: re-includes +/// everything under the uuid dir against the project's own ignore rules. +/// A prebuild's tree holds the compiled extension (`*.so`, `*.bundle`, +/// `*.dll`, a JRuby gem's `*.jar`), which stock ignore templates name; a +/// gem vendored as its own tree is source files and gets none. +const UUID_GITIGNORE: &str = "!*\n"; + +/// Rewrite `/.gitignore` ([`UUID_GITIGNORE`]) and +/// `/.gitattributes` of a gem vendored as platform gems when absent +/// or different, with the writer every backend that commits binaries +/// shares: the attributes keep a project rule such as `*.so filter=lfs`, +/// or an EOL conversion, from changing the bytes git commits. Neither file +/// is part of the copy, so writing them is no rebuild. `true` when either +/// was rewritten. +pub(crate) async fn restore_uuid_metadata(uuid_dir: &Path) -> std::io::Result { + super::npm_dir::write_uuid_metadata(uuid_dir, UUID_GITIGNORE).await +} + +/// Ask git whether it would commit every file of the platform trees just +/// written (`inventory`: the copy's files) and the uuid dir's `.gitignore` +/// and `.gitattributes`. A rule the `.gitignore` cannot override refuses +/// `vendor_artifact_gitignored`, and the caller unwinds; git failing to +/// answer is only a warning. Nothing is asked without an inventory, whose +/// absence is already reported. +async fn keep_platform_trees_committable( + project_root: &Path, + copy_rel: &str, + inventory: Option<&std::collections::BTreeMap>, + 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. +async fn preview_platform_prebuilds( + service: Option<&VendorServiceConfig>, + record: &PatchRecord, + name: &str, + platforms: &[String], +) -> Result<(), Box> { + if let Some(outcome) = service_offline_conflict(service) { + return Err(Box::new(outcome)); + } + let cfg = service + .filter(|cfg| cfg.service_enabled()) + .ok_or_else(|| Box::new(super::service_fetch::required()))?; + let scratch = tempfile::tempdir() + .map_err(|e| Box::new(refused("vendor_prebuilt_extract_failed", e.to_string())))?; + stage_platform_prebuilds(cfg, record, name, platforms, scratch.path()) + .await + .map(|_| ()) +} + +/// Acquire a verified service copy without replacing the prior copy on +/// failure: the gem's own tree, or one prebuild tree per platform in +/// `platforms` when the lock pins the gem as platform gems (with the uuid +/// dir's git metadata, see [`restore_uuid_metadata`]). +#[allow(clippy::too_many_arguments)] +async fn materialise_patched_copy( + purl: &str, + copy_dir: &Path, + uuid_dir: &Path, + name: &str, + platforms: &[String], + record: &PatchRecord, + unwind_uuid_dir: bool, + service: Option<&VendorServiceConfig>, + warnings: &mut Vec, +) -> Result> { + match platforms { + [] => { + gem_service_copy( + service, + record, + name, + copy_dir, + uuid_dir, + unwind_uuid_dir, + warnings, + ) + .await? + } + platforms => { + gem_platform_service_copy( + service, + record, + name, + platforms, + 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(already_patched_result(purl, copy_dir, &record.files)) +} + +/// Revert a gem vendor entry: restore the Gemfile line / delete the managed +/// block, splice the lock's spec block back into GEM specs (sorted), the +/// original DEPENDENCIES entry back in and the registry CHECKSUMS line back +/// over the bare path form, then remove the validated uuid dir. +/// A fragment that no longer looks like what vendor wrote — a hand edit, a +/// `bundle update`, a newer vendor run — gets a `vendor_lock_entry_drifted` +/// warning, and then neither file is written: the Gemfile and the lock are +/// reverted together or not at all (#988). +pub async fn revert_gem(entry: &VendorEntry, project_root: &Path, dry_run: bool) -> RevertOutcome { + revert_gem_opts(entry, project_root, RevertOpts::new(dry_run)).await +} + +/// [`revert_gem`] with full [`RevertOpts`]: `keep_artifact` skips ONLY the +/// artifact deletion; the wiring restore — and the empty-wiring refusal, +/// which applies under `keep_artifact` too — runs unchanged. +/// +/// LOSSINESS GUARD (the [`RevertOutcome`] contract every backend honors): a +/// record left alone as genuine drift keeps the artifact dir (and the caller +/// keeps the ledger entry) — the Gemfile `path:` or the lock's PATH section +/// may still route through it, and the entry holds the only pre-vendor +/// originals. A record whose live state already equals its reverted state /// is convergence, not drift, and stays silent (LIVENESS CONTRACT), so an /// earlier partial revert or a `bundle update` regeneration never wedges /// the entry forever. @@ -1963,8 +2833,13 @@ fn apply_gemfile_plan(text: &str, plan: &GemfilePlan) -> String { /// The applied lock edit plus the verbatim fragments the ledger records. struct LockEdit { text: String, - /// The gem's GEM spec block as removed (4-space line + 6-space sublines). + /// The gem's GEM spec block as removed (4-space line + 6-space sublines); + /// for a gem locked as platform gems, every platform's block in lock + /// order. removed_spec_block: Vec, + /// The platform of each removed block, in lock order; empty when the + /// one block is the plain `name (version)` entry. + platforms: Vec, /// The pre-vendor DEPENDENCIES entry (`None` = the gem was transitive and /// the entry was added; revert deletes it). old_dep_line: Option, @@ -1972,23 +2847,24 @@ struct LockEdit { path_section: Vec, /// The DEPENDENCIES entry we wrote (` (= )!`). new_dep_line: String, - /// CHECKSUMS rewrite `(original line, bare replacement)`; `None` when the - /// lock has no CHECKSUMS section, no entry for the gem, or the entry was - /// already bare (idempotency: our own edit is never recorded as an - /// "original" — reverting it onto a registry-sourced lock would break - /// frozen installs). - checksum_rewrite: Option<(String, String)>, + /// CHECKSUMS rewrites `(original line, bare replacement)`, one per + /// removed block that had a registry line; empty when the lock has no + /// CHECKSUMS section, no entry for the gem, or every entry was already + /// bare (idempotency: our own edit is never recorded as an "original" — + /// reverting it onto a registry-sourced lock would break frozen + /// installs). + checksum_rewrites: Vec<(String, String)>, /// The spec block was lifted from OUR OWN previous PATH section (a /// re-vendor to a newer patch uuid), not from GEM/specs: the lifted /// fragments are this backend's own prior wiring, so the caller records /// `original: None` and the true pre-vendor originals ride forward from /// the ledger entry being replaced (`persist_vendor_entry`). rewired_ours: bool, - /// The already-bare CHECKSUMS line for the gem, when one is present. + /// The already-bare CHECKSUMS lines of the gem's removed blocks. /// Only consulted on a re-vendor (`rewired_ours`): the checksum record - /// must ride again or the first run's registry `sha256=` restore line - /// drops out of the ledger with the entry being replaced. - checksum_bare: Option, + /// must ride again or the first run's registry `sha256=` restore lines + /// drop out of the ledger with the entry being replaced. + checksum_bare: Vec, /// The ` remote: ` line of the GEM section the spec block was lifted /// from, unless that is the lock's first GEM section (#779) and not a /// hosted gem's own (#2090). Revert puts the block back into that @@ -2102,36 +2978,31 @@ fn edit_lock(text: &str, name: &str, version: &str, rel: &str) -> Result)> = gem_sections .iter() .enumerate() - .filter_map(|(k, &(gs, ge))| { - (gs..ge) - .find(|&i| lines[i] == target) - .map(|i| (k, gs, ge, i)) - }); - let hit = hits.next(); - if hits.next().is_some() { + .map(|(k, &span)| (k, span, gem_spec_blocks(&lines, span, name, version))) + .filter(|(_, _, blocks)| !blocks.is_empty()) + .collect(); + // SECURITY/fail-closed: a plain entry beside platform-suffixed ones is + // a gem locked for the ruby platform too, which no vendored prebuild + // serves (`gem_prelude` refuses it as `platform_gem_unsupported` before + // this point) — and lifting only one kind would leave the other behind + // as a stale registry spec. The CHECKSUMS branch below refuses a + // platform-suffixed sibling of a plain entry as well, but only bundler + // ≥ 2.6 locks have a CHECKSUMS section to catch it in. + let blocks_of = || found.iter().flat_map(|(_, _, blocks)| blocks.iter()); + if blocks_of().any(|b| b.platform.is_none()) { + if let Some(platform) = blocks_of().find_map(|b| b.platform.as_deref()) { + return Err(format!( + "Gemfile.lock GEM specs has a platform-suffixed entry `{name} ({version}-{platform})` beside the plain `{name} ({version})`; a gem locked both for the ruby platform and as a platform-specific gem cannot be vendored (re-resolve the lock before vendoring)" + )); + } + } + if found.len() > 1 { // SECURITY/fail-closed: bundler locks one spec per gem; the same // entry under two sources is a lock this backend does not // understand, and lifting either copy would be a guess. @@ -2141,8 +3012,9 @@ fn edit_lock(text: &str, name: &str, version: &str, rel: &str) -> Result = None; let mut rewired_ours = false; - let removed_spec_block: Vec = match hit { - Some((k, gem_start, gem_end, block_start)) => { + let (removed_spec_block, platforms): (Vec, Vec) = match found.into_iter().next() + { + Some((k, (gem_start, gem_end), blocks)) => { if k > 0 || hosted_gem_section(&lines[gem_start..gem_end]) { // Revert must find this section again; without a remote // line there is nothing to find it by. @@ -2156,16 +3028,14 @@ fn edit_lock(text: &str, name: &str, version: &str, rel: &str) -> Result { // Re-vendor: the entry lives in the PATH section our previous // run emitted (remote parses as our vendored dir for exactly - // this gem). Lift the block and drop the old section — step 3 + // this gem). Lift the blocks and drop the old section — step 3 // re-emits it at the NEW uuid's sorted position. The lifted // lines are our own wiring, not pre-vendor originals: flagged // via `rewired_ours` (see the `LockEdit` field docs). @@ -2174,25 +3044,27 @@ fn edit_lock(text: &str, name: &str, version: &str, rel: &str) -> Result = (ps..pe) - .filter(|i| !(block_start..block_end).contains(i)) + .filter(|i| !in_block(i)) .map(|i| lines[i].as_str()) .filter(|l| !l.is_empty()) .collect(); - if non_block.len() != 3 + let mixed = blocks.iter().any(|b| b.platform.is_none()) + && blocks.iter().any(|b| b.platform.is_some()); + if mixed + || non_block.len() != 3 || non_block[0] != "PATH" || !non_block[1].starts_with(" remote: ") || non_block[2] != " specs:" @@ -2201,10 +3073,11 @@ fn edit_lock(text: &str, name: &str, version: &str, rel: &str) -> Result = lines[block_start..block_end].to_vec(); + let block: Vec = lines[spec_blocks_span(&blocks, name, version)?].to_vec(); + let platforms = blocks.into_iter().filter_map(|b| b.platform).collect(); lines.drain(ps..pe); rewired_ours = true; - block + (block, platforms) } }; @@ -2289,32 +3162,44 @@ fn edit_lock(text: &str, name: &str, version: &str, rel: &str) -> Result = None; - let mut checksum_bare: Option = None; + let mut checksum_rewrites: Vec<(String, String)> = Vec::new(); + let mut checksum_bare: Vec = Vec::new(); if let Some((ck_start, ck_end)) = section_span(&lines, "CHECKSUMS") { - let bare = format!(" {name} ({version})"); - let mut plain_at: Option = None; + // The tokens of the entries that moved: ``, or one + // `-` per platform block (spike G5: a native gem + // gets one CHECKSUMS line per platform spec). + let moved: Vec = match platforms.as_slice() { + [] => vec![version.to_string()], + platforms => platforms + .iter() + .map(|platform| format!("{version}-{platform}")) + .collect(), + }; + let platform_prefix = format!("{version}-"); + // (line index, token) of each moved entry's line. + let mut ours: Vec<(usize, String)> = Vec::new(); for (i, line) in lines.iter().enumerate().take(ck_end).skip(ck_start + 1) { match checksum_entry(line) { - Some((n, v)) if n == name && v == version => { - if plain_at.is_some() { + Some((n, v)) if n == name && moved.iter().any(|token| token == v) => { + if ours.iter().any(|(_, token)| token == v) { // SECURITY/fail-closed: duplicate entries mean the // grammar assumption is wrong for this lock — editing // one of them would be a guess. return Err(format!( - "Gemfile.lock CHECKSUMS has more than one entry for `{name} ({version})`" + "Gemfile.lock CHECKSUMS has more than one entry for `{name} ({v})`" )); } - plain_at = Some(i); + ours.push((i, v.to_string())); } - Some((n, v)) if n == name && v.starts_with(&platform_prefix) => { - // SECURITY/fail-closed: platform-suffixed installs were - // refused (`platform_gem_unsupported`) before this point, - // so a platform sibling here means the lock disagrees - // with the installed tree — never guess which entries + Some((n, v)) if n == name && (v == version || v.starts_with(&platform_prefix)) => { + // SECURITY/fail-closed: an entry for a build of this gem + // version that GEM specs does not lock (a + // platform-suffixed sibling of the plain entry, or the + // plain entry beside platform gems) means the lock + // disagrees with itself — never guess which entries // bundler would collapse for a PATH spec. return Err(format!( - "Gemfile.lock CHECKSUMS has a platform-suffixed entry `{n} ({v})` but the installed gem is not platform-specific; the lock disagrees with the install (re-resolve it before vendoring)" + "Gemfile.lock CHECKSUMS has an entry `{n} ({v})` for a build of the gem that its specs do not lock (a platform-specific or platform-suffixed sibling); the lock disagrees with itself (re-resolve it before vendoring)" )); } Some(_) => {} @@ -2329,12 +3214,13 @@ fn edit_lock(text: &str, name: &str, version: &str, rel: &str) -> Result {} } } - if let Some(i) = plain_at { + for (i, token) in ours { + let bare = format!(" {name} ({token})"); if lines[i] != bare { - checksum_rewrite = Some((lines[i].clone(), bare.clone())); + checksum_rewrites.push((lines[i].clone(), bare.clone())); lines[i] = bare; } else { - checksum_bare = Some(bare); + checksum_bare.push(bare); } } } @@ -2342,16 +3228,95 @@ fn edit_lock(text: &str, name: &str, version: &str, rel: &str) -> Result, +} + +/// The spec blocks of `name`@`version` in the section `[start, end)`, in +/// lock order: its plain `name (version)` entry (the ruby platform) and its +/// platform-suffixed ones (`name (version-arm64-darwin)`). RubyGems +/// versions never contain `-`, so `version-` opens the platform. +fn gem_spec_blocks( + lines: &[String], + (start, end): (usize, usize), + name: &str, + version: &str, +) -> Vec { + let platform_prefix = format!("{version}-"); + let mut blocks = Vec::new(); + let mut i = start + 1; + while i < end { + let platform = match spec_entry(&lines[i]) { + Some((n, v)) if n == name && v == version => Some(None), + Some((n, v)) if n == name => v + .strip_prefix(&platform_prefix) + .map(|platform| Some(platform.to_string())), + _ => None, + }; + let Some(platform) = platform else { + i += 1; + continue; + }; + let mut block_end = i + 1; + while block_end < end && lines[block_end].starts_with(" ") { + block_end += 1; + } + blocks.push(SpecBlock { + start: i, + end: block_end, + platform, + }); + i = block_end; + } + blocks +} + +/// The one line span `blocks` (a gem's spec blocks in one section, +/// non-empty) cover, which the lock edit moves as a whole. Fail-closed on +/// what bundler never writes: an entry listed twice, or the platform +/// entries apart from each other (bundler sorts a section's specs by full +/// name, so they are adjacent; revert puts the recorded blocks back as one +/// run, which would not be where separated ones came from). +fn spec_blocks_span( + blocks: &[SpecBlock], + name: &str, + version: &str, +) -> Result, String> { + for (i, block) in blocks.iter().enumerate() { + if blocks[..i].iter().any(|b| b.platform == block.platform) { + let token = match &block.platform { + Some(platform) => format!("{version}-{platform}"), + None => version.to_string(), + }; + return Err(format!( + "Gemfile.lock lists `{name} ({token})` more than once in one section" + )); + } + } + if blocks.windows(2).any(|pair| pair[0].end != pair[1].start) { + return Err(format!( + "Gemfile.lock lists the platform entries of `{name} ({version})` apart from each other, which is not the order bundler writes (re-resolve the lock before vendoring)" + )); + } + Ok(blocks[0].start..blocks[blocks.len() - 1].end) +} + /// `[start, end)` of a lock section: the column-0 `header` line through (not /// including) the next column-0 line. Blank separator lines belong to the /// section they follow. @@ -2518,21 +3483,30 @@ fn checksum_line_names_gem(line: &str, name: &str) -> bool { /// True when the lock's CHECKSUMS section is coherent with a path-sourced /// gem: no section, no entry for the gem, or exactly the bare -/// ` ()` form. A leftover registry `sha256=` token (a lock -/// wired by a pre-CHECKSUMS-aware socket-patch) is NOT in sync — bundler -/// silently preserves it forever (spike G4), so the hot path must not declare -/// such a lock done; only revert + re-vendor can repair it. -fn lock_checksum_in_sync(lock_text: &str, name: &str, version: &str) -> bool { +/// ` ()` form — for a gem wired as platform gems, the bare +/// ` (-)` form of each of `platforms`. A leftover +/// registry `sha256=` token (a lock wired by a pre-CHECKSUMS-aware +/// socket-patch) is NOT in sync — bundler silently preserves it forever +/// (spike G4), so the hot path must not declare such a lock done; only +/// revert + re-vendor can repair it. Nor is an entry for a build of the gem +/// the wired `PATH` section does not hold. +fn lock_checksum_in_sync(lock_text: &str, name: &str, version: &str, platforms: &[String]) -> bool { let lines: Vec = lock_text.split('\n').map(str::to_string).collect(); let Some((ck_start, ck_end)) = section_span(&lines, "CHECKSUMS") else { return true; }; - let bare = format!(" {name} ({version})"); + let wired = |token: &str| match platforms { + [] => token == version, + platforms => token + .strip_prefix(version) + .and_then(|rest| rest.strip_prefix('-')) + .is_some_and(|platform| platforms.iter().any(|p| p == platform)), + }; let platform_prefix = format!("{version}-"); for line in &lines[ck_start + 1..ck_end] { match checksum_entry(line) { Some((n, v)) if n == name && (v == version || v.starts_with(&platform_prefix)) => { - if line.as_str() != bare { + if !wired(v) || *line != format!(" {n} ({v})") { return false; } } @@ -3068,8 +4042,34 @@ async fn revert_lock_checksum_record( w: &WiringRecord, own: &OwnGem<'_>, ) -> Result { - let Some(written) = w.new.as_ref().and_then(Value::as_str) else { - return Ok(RecordRevert::Drifted); + // Each line vendor wrote, with the registry line it replaced: the one + // pair of a ruby-platform gem, or (arrays) one pair per platform entry + // of a gem vendored as platform gems, matched by their `name (token)`. + let pairs: Vec<(String, Option)> = match (w.new.as_ref(), w.original.as_ref()) { + (Some(Value::String(written)), original) => vec![( + written.clone(), + original.and_then(Value::as_str).map(str::to_string), + )], + (Some(written @ Value::Array(_)), original) => { + let (Some(written), Some(originals)) = ( + wiring_string_array(Some(written)), + original.map_or(Some(Vec::new()), |o| wiring_string_array(Some(o))), + ) else { + return Ok(RecordRevert::Drifted); + }; + written + .into_iter() + .map(|line| { + let entry = checksum_entry(&line); + let original = originals + .iter() + .find(|o| entry.is_some() && checksum_entry(o) == entry) + .cloned(); + (line, original) + }) + .collect() + } + _ => return Ok(RecordRevert::Drifted), }; let Some(file) = files.text(GEMFILE_LOCK).await? else { return Ok(RecordRevert::FileMissing); @@ -3080,31 +4080,36 @@ async fn revert_lock_checksum_record( // checksum for the gem at all, so there is no line left to restore. return Ok(RecordRevert::Done); }; - let original = w.original.as_ref().and_then(Value::as_str); - let Some(i) = (ck_start + 1..ck_end).find(|&i| lines[i] == written) else { - // ALREADY CONVERGED: the registry line vendor replaced is back. - let converged = - original.is_some_and(|orig| (ck_start + 1..ck_end).any(|i| lines[i] == orig)); - return Ok(if converged { - RecordRevert::Done - } else { - RecordRevert::Drifted - }); - }; - let Some(original) = original else { - // A re-vendor rides the checksum record forward with `original: None` - // for the caller's carry-forward to fill. When the chain has no - // registry line to fill FROM — the pre-vendor entry was ALREADY the - // bare path form (vendor then recorded no checksum wiring at all) — - // there is nothing to restore: the bare line still standing IS the - // pre-vendor state, not drift. - return Ok(RecordRevert::Done); - }; - if !own.is_checksum(written) || !own.is_checksum(original) { - return Err(own.refused(w, NOT_OUR_CHECKSUM)); + // Every pair is judged before the lock text is replaced, so one drifted + // line leaves the others as found. + let mut restored = false; + for (written, original) in &pairs { + let original = original.as_deref(); + let Some(i) = (ck_start + 1..ck_end).find(|&i| lines[i] == *written) else { + // ALREADY CONVERGED: the registry line vendor replaced is back. + if original.is_some_and(|orig| (ck_start + 1..ck_end).any(|i| lines[i] == orig)) { + continue; + } + return Ok(RecordRevert::Drifted); + }; + let Some(original) = original else { + // A re-vendor rides the checksum record forward with `original: None` + // for the caller's carry-forward to fill. When the chain has no + // registry line to fill FROM — the pre-vendor entry was ALREADY the + // bare path form (vendor then recorded no checksum wiring at all) — + // there is nothing to restore: the bare line still standing IS the + // pre-vendor state, not drift. + continue; + }; + if !own.is_checksum(written) || !own.is_checksum(original) { + return Err(own.refused(w, NOT_OUR_CHECKSUM)); + } + lines[i] = original.to_string(); + restored = true; + } + if restored { + file.set(lines.join("\n")); } - lines[i] = original.to_string(); - file.set(lines.join("\n")); Ok(RecordRevert::Done) } @@ -5771,7 +6776,7 @@ mod tests { // A lock WITHOUT a CHECKSUMS section must keep producing // the exact pre-CHECKSUMS output and no checksum record. let edit = edit_lock(LOCK_DIRECT, "rack", "3.2.6", ©_rel()).unwrap(); - assert!(edit.checksum_rewrite.is_none()); + assert!(edit.checksum_rewrites.is_empty()); assert_eq!(edit.text, expected_lock_direct()); } @@ -10560,4 +11565,1456 @@ mod tests { Some(lock.as_str()) ); } + + /// A gem bundler locked as precompiled platform gems (see the module + /// docs): vendored from the patch service's prebuilds, one tree per + /// locked platform. + mod platform_gems { + use super::*; + use crate::vendor::test_support as ts; + use crate::vendor::{check_vendored_artifact, ArtifactHealth}; + + const NOKO: &str = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + const UUID_B: &str = "b0b0b0b0-0000-4000-8000-000000000002"; + const DARWIN: &str = "arm64-darwin"; + const LINUX: &str = "x86_64-linux-gnu"; + const RB: &str = "lib/nokogiri/version.rb"; + const SO: &str = "lib/nokogiri/nokogiri.so"; + const C: &str = "ext/nokogiri/xml_node.c"; + const RB_PRISTINE: &[u8] = b"module Nokogiri\n VERSION = \"1.18.10\"\nend\n"; + const RB_PATCHED: &[u8] = + b"module Nokogiri\n VERSION = \"1.18.10\"\n SOCKET_PATCHED = true\nend\n"; + const GEMFILE_NOKO: &str = + "source \"https://rubygems.org\"\n\ngem \"nokogiri\", \"~> 1.18\"\ngem \"puma\"\n"; + const BLOCKS: &str = " nokogiri (1.18.10-arm64-darwin)\n racc (~> 1.4)\n nokogiri (1.18.10-x86_64-linux-gnu)\n racc (~> 1.4)\n"; + const TAIL: &str = "PLATFORMS\n arm64-darwin\n x86_64-linux-gnu\n\n"; + + fn rel(uuid: &str) -> String { + format!(".socket/vendor/gem/{uuid}/nokogiri-1.18.10") + } + + /// A registry CHECKSUMS token (`ch` repeated to a sha256's length). + fn sha(ch: char) -> String { + format!(" sha256={}", ch.to_string().repeat(64)) + } + + /// A CHECKSUMS section whose two nokogiri entries end in `darwin` and + /// `linux` (a registry token from [`sha`], or nothing for the bare + /// form of a path gem). + fn checksums(darwin: &str, linux: &str) -> String { + format!( + "CHECKSUMS\n nokogiri (1.18.10-arm64-darwin){darwin}\n nokogiri (1.18.10-x86_64-linux-gnu){linux}\n puma (6.4.2){}\n racc (1.8.1){}\n\n", + sha('c'), + sha('d') + ) + } + + /// Bundler's lock of a project that takes nokogiri as precompiled + /// platform gems, with the CHECKSUMS section of a bundler >= 2.6 + /// lock when `checksums` is one. + fn lock(checksums: Option<&str>) -> String { + format!( + "GEM\n remote: https://rubygems.org/\n specs:\n{BLOCKS} puma (6.4.2)\n nio4r (~> 2.0)\n racc (1.8.1)\n\n{TAIL}DEPENDENCIES\n nokogiri (~> 1.18)\n puma\n\n{}BUNDLED WITH\n 2.5.22\n", + checksums.unwrap_or_default() + ) + } + + /// [`lock`] as vendoring leaves it for the copy at `rel`. + fn vendored(rel: &str, checksums: Option<&str>) -> String { + format!( + "PATH\n remote: {rel}\n specs:\n{BLOCKS}\nGEM\n remote: https://rubygems.org/\n specs:\n puma (6.4.2)\n nio4r (~> 2.0)\n racc (1.8.1)\n\n{TAIL}DEPENDENCIES\n nokogiri (= 1.18.10)!\n puma\n\n{}BUNDLED WITH\n 2.5.22\n", + checksums.unwrap_or_default() + ) + } + + fn record(uuid: &str, files: &[(&str, &[u8], &[u8])]) -> PatchRecord { + PatchRecord { + uuid: uuid.to_string(), + exported_at: "2026-06-09T00:00:00Z".to_string(), + files: files + .iter() + .map(|(path, before, after)| { + ( + path.to_string(), + PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(before), + after_hash: compute_git_sha256_from_bytes(after), + }, + ) + }) + .collect(), + vulnerabilities: HashMap::new(), + description: String::new(), + license: String::new(), + tier: String::new(), + } + } + + /// A bundler project locking nokogiri with `lock`, and the patch of + /// its `lib/nokogiri/version.rb`. + async fn project(lock: &str) -> (tempfile::TempDir, PathBuf, PatchRecord) { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("project"); + tokio::fs::create_dir_all(&root).await.unwrap(); + tokio::fs::write(root.join(GEMFILE), GEMFILE_NOKO) + .await + .unwrap(); + tokio::fs::write(root.join(GEMFILE_LOCK), lock) + .await + .unwrap(); + (dir, root, record(UUID, &[(RB, RB_PRISTINE, RB_PATCHED)])) + } + + /// The stub gemspec the service serves for `platform`'s prebuild. + fn stub(platform: &str) -> Vec { + format!( + "# -*- encoding: utf-8 -*-\n# stub: nokogiri 1.18.10 {platform} lib\n\nGem::Specification.new do |s|\n s.name = \"nokogiri\".freeze\n s.version = \"1.18.10\".freeze\n s.platform = \"{platform}\".freeze\n s.summary = \"fixture\".freeze\n s.authors = [\"fixture\".freeze]\n s.require_paths = [\"lib\".freeze]\n s.add_runtime_dependency(%q.freeze, [\"~> 1.4\".freeze])\nend\n" + ) + .into_bytes() + } + + /// What the patch service lists for one platform: its prebuild and + /// the stub gemspec (`None` leaves that artifact out of the answer), + /// and the sha512 it advertises for the prebuild when not its own. + struct Served { + platform: &'static str, + gem: Option>, + stub: Option>, + gem_sha512: Option, + } + + /// `platform`'s prebuild: the patched Ruby file and the platform's + /// own binary, with its stub. + fn served(platform: &'static str) -> Served { + Served { + platform, + gem: Some(make_gem(&[(RB, RB_PATCHED), (SO, platform.as_bytes())])), + stub: Some(stub(platform)), + gem_sha512: None, + } + } + + /// A patch service answering for `uuid` with the patched ruby gem + /// and `prebuilds`, in the shape of the wire contract. + async fn service( + uuid: &str, + prebuilds: &[Served], + ) -> (wiremock::MockServer, VendorServiceConfig) { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, ResponseTemplate}; + let server = wiremock::MockServer::start().await; + let base = format!("/patch/gem/nokogiri/1.18.10/tok/{uuid}"); + let mut artifacts = Vec::new(); + let mut serve = |artifact: serde_json::Value, route: String, bytes: Vec| { + artifacts.push(artifact); + Mock::given(method("GET")) + .and(path(route)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + }; + let mut mocks = Vec::new(); + let ruby_gem = make_gem(&[(RB, RB_PATCHED), (C, &b"patched C\n"[..])]); + let route = format!("{base}/nokogiri-1.18.10.gem"); + mocks.push(serve( + serde_json::json!({ + "kind": "tarball", "url": format!("{}{route}", server.uri()), + "integrity": { "sha512": sri_sha512(&ruby_gem) } + }), + route, + ruby_gem, + )); + for prebuild in prebuilds { + let platform = prebuild.platform; + let files = [ + ("gem-platform", "gem", &prebuild.gem, &prebuild.gem_sha512), + ( + "gem-platform-stub-gemspec", + "gemspec", + &prebuild.stub, + &None, + ), + ]; + for (kind, ext, bytes, sha512) in files { + let Some(bytes) = bytes else { continue }; + let route = format!("{base}/nokogiri-1.18.10-{platform}.{ext}"); + let sha512 = sha512.clone().unwrap_or_else(|| sri_sha512(bytes)); + mocks.push(serve( + serde_json::json!({ + "kind": kind, "platform": platform, + "url": format!("{}{route}", server.uri()), + "contentType": "application/octet-stream", + "sizeBytes": bytes.len(), + "integrity": { "sha512": sha512 } + }), + route, + bytes.clone(), + )); + } + } + for mock in mocks { + mock.mount(&server).await; + } + Mock::given(method("POST")) + .and(path("/v0/orgs/acme/patches/package")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "results": { uuid: { + "status": "granted", + "purl": NOKO, + "url": format!("{}{base}/nokogiri-1.18.10.gem", server.uri()), + "artifacts": artifacts + }} + }))) + .mount(&server) + .await; + let cfg = gem_service_cfg(&server.uri(), VendorSource::Service, false); + (server, cfg) + } + + /// A source that is not installed (a lock-only checkout). + fn not_installed(root: &Path) -> PathBuf { + root.join(".socket/vendor/.uninstalled") + } + + async fn vendor( + root: &Path, + installed: &Path, + record: &PatchRecord, + cfg: &VendorServiceConfig, + dry_run: bool, + ) -> VendorOutcome { + let blobs = root.join("no-blobs"); + let sources = PatchSources::blobs_only(&blobs); + ts::vendor_gem( + NOKO, + installed, + root, + record, + &sources, + "2026-06-09T00:00:00Z", + dry_run, + false, + Some(cfg), + ) + .await + } + + async fn text(path: PathBuf) -> String { + tokio::fs::read_to_string(path).await.unwrap() + } + + /// Vendor the project at `root` from `cfg`'s service and persist the + /// ledger entry the way the CLI does (carry-forward included). + async fn vendor_and_persist( + root: &Path, + record: &PatchRecord, + cfg: &VendorServiceConfig, + ) -> VendorEntry { + let (result, entry, _) = + unwrap_done(vendor(root, ¬_installed(root), record, cfg, false).await); + assert!(result.success, "{:?}", result.error); + ts::persist(root, NOKO, entry.expect("a ledger entry")).await; + crate::vendor::load_state(root).await.unwrap().entries[NOKO].clone() + } + + /// The capability: every platform block moves into one PATH section, + /// each platform gets its prebuild tree and stub, the ledger records + /// the platforms and (when the lock had them) every registry + /// CHECKSUMS line, a second run is a no-op, the copy verifies, and + /// revert restores the Gemfile and the lock byte for byte. + #[tokio::test] + async fn vendors_from_prebuilds_and_reverts_byte_for_byte() { + let registry = checksums(&sha('a'), &sha('b')); + for before in [None, Some(registry.as_str())] { + let lock_before = lock(before); + let (_tmp, root, record) = project(&lock_before).await; + 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 entry = entry.expect("a ledger entry"); + + // One prebuild tree per platform, each with its own stub. + let rel = rel(UUID); + for platform in [DARWIN, LINUX] { + let tree = root.join(&rel).join(platform); + assert_eq!(tokio::fs::read(tree.join(RB)).await.unwrap(), RB_PATCHED); + assert_eq!( + tokio::fs::read(tree.join(SO)).await.unwrap(), + platform.as_bytes() + ); + assert_eq!( + tokio::fs::read(tree.join("nokogiri.gemspec")) + .await + .unwrap(), + stub(platform) + ); + } + 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 ledger entry. + assert_eq!(entry.gem_platforms, [DARWIN, LINUX]); + 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); + assert!(text(root.join(".socket/vendor/state.json")) + .await + .contains("\"gemPlatforms\"")); + + // 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 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()); + } + } + + /// Every locked platform needs a prebuild and its stub. While the + /// service lists none for one of them (it lists a prebuild only once + /// built), a dry run and a wet run both leave the gem alone under + /// the benign pending code: they name the gem and the platforms, + /// ask the service for the package reference and nothing else, and + /// write nothing. + #[tokio::test] + async fn a_locked_platform_without_a_prebuild_is_a_skip_that_downloads_nothing() { + let no_stub = || Served { + stub: None, + ..served(LINUX) + }; + let cases: [(Vec, Vec<&str>); 3] = [ + ( + Vec::new(), + vec![ + "of `nokogiri` for `arm64-darwin`, `x86_64-linux-gnu` yet", + "none of the locked platforms", + ], + ), + ( + vec![served(DARWIN)], + vec!["for `x86_64-linux-gnu` yet (it has `arm64-darwin`)"], + ), + ( + vec![served(DARWIN), no_stub()], + vec!["for `x86_64-linux-gnu` yet ("], + ), + ]; + for (prebuilds, expected) in cases { + let (_tmp, root, record) = project(&lock(Some(&checksums(&sha('a'), "")))).await; + let before = ts::tree_snapshot(&root); + let (server, cfg) = service(UUID, &prebuilds).await; + for dry_run in [true, false] { + let asked = ts::request_count(&server).await; + let (code, detail) = unwrap_refused( + vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, + ); + assert_eq!(code, "vendor_prebuilt_platform_pending", "{detail}"); + assert!(crate::vendor::is_unserved(code)); + assert!(crate::vendor::refusals::refusal_is_benign(code)); + for text in &expected { + assert!(detail.contains(text), "{detail}"); + } + assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); + assert_eq!( + ts::request_count(&server).await, + asked + 1, + "the package reference is the one request: no gem is downloaded" + ); + } + } + } + + /// A copy the lock is ALREADY wired to cannot wait for a prebuild. + /// When one of its trees is lost and the service does not list that + /// platform, the rebuild is the plain miss, a failure, dry run or + /// not, and what is left of the copy stays as it was. + #[tokio::test] + async fn a_wired_copy_that_cannot_be_rebuilt_fails_instead_of_skipping() { + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + tokio::fs::remove_dir_all(root.join(rel(UUID)).join(LINUX)) + .await + .unwrap(); + let before = ts::tree_snapshot(&root); + let (_server, cfg) = service(UUID, &[served(DARWIN)]).await; + for dry_run in [true, false] { + let (code, detail) = unwrap_refused( + vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, + ); + assert_eq!(code, "vendor_prebuilt_required", "{detail}"); + assert!(detail.contains("for `x86_64-linux-gnu` yet"), "{detail}"); + assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); + } + } + + /// The layout is wired only for a lock written by a bundler it was + /// run against: a lock that names an older one, or none, is refused + /// by the version it needs, from the lock alone (so before a + /// takeover too), with the service not asked and nothing written. + #[tokio::test] + async fn a_lock_from_a_bundler_older_than_the_layout_is_verified_on_is_refused() { + for (bundled_with, says) in [ + ("BUNDLED WITH\n 2.2.33\n", "was written by Bundler 2.2.33"), + ("BUNDLED WITH\n 1.17.3\n", "was written by Bundler 1.17.3"), + ("", "does not say which Bundler wrote it"), + ] { + let old = lock(None).replace("BUNDLED WITH\n 2.5.22\n", bundled_with); + let (_tmp, root, record) = project(&old).await; + let before = ts::tree_snapshot(&root); + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + for dry_run in [true, false] { + let (code, detail) = unwrap_refused( + vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, + ); + assert_eq!(code, "platform_gem_unsupported", "{detail}"); + assert!(detail.contains(says), "{detail}"); + assert!(detail.contains("needs Bundler 2.3 or later"), "{detail}"); + } + assert_eq!(ts::tree_snapshot(&root), before); + assert_eq!(ts::request_count(&server).await, 0); + let early = gem_platform_lock_refusals(&root, &[NOKO]).await; + assert_eq!(early.len(), 1, "{early:?}"); + assert_eq!(early[0].1 .0, "platform_gem_unsupported"); + } + // The floor itself, and a gem the lock does not pin as platform + // gems, whatever bundler wrote it. + let floor = lock(None).replace(" 2.5.22\n", " 2.3.0\n"); + let (_tmp, root, record) = project(&floor).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let (result, ..) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + let locked = LockedGem { + plain: true, + platforms: Vec::new(), + }; + assert!(platform_lock_refusal("rack", "3.2.6", &locked, "").is_none()); + } + + /// A plain `name (version)` entry beside the platform ones is the + /// ruby platform, which no prebuilt tree serves: refused by name + /// before the service is asked, with nothing written. + #[tokio::test] + async fn a_plain_entry_beside_the_platform_gems_is_refused() { + let with_plain = lock(None) + .replace( + " specs:\n", + " specs:\n nokogiri (1.18.10)\n mini_portile2 (~> 2.8.2)\n racc (~> 1.4)\n", + ) + .replace(" arm64-darwin\n", " arm64-darwin\n ruby\n"); + let (_tmp, root, record) = project(&with_plain).await; + let before = ts::tree_snapshot(&root); + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + for dry_run in [true, false] { + let (code, detail) = unwrap_refused( + vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, + ); + assert_eq!(code, "platform_gem_unsupported"); + assert!( + detail.contains("`nokogiri (1.18.10)` (the ruby platform)"), + "{detail}" + ); + assert!( + detail.contains("`nokogiri (1.18.10-arm64-darwin)`"), + "{detail}" + ); + } + assert_eq!(ts::tree_snapshot(&root), before); + assert_eq!(ts::request_count(&server).await, 0); + assert!( + service_preflight(NOKO, ¬_installed(&root), &root, &record) + .await + .is_none(), + "no download is planned for a gem the backend refuses first" + ); + // The same refusal is the CLI's to raise before a takeover, and + // a lock that pins platform gems alone has none. + let early = gem_platform_lock_refusals(&root, &[NOKO, PURL]).await; + assert_eq!(early.len(), 1, "{early:?}"); + assert_eq!(early[0].0, NOKO); + assert_eq!(early[0].1 .0, "platform_gem_unsupported"); + assert!(early[0].1 .1.contains("(the ruby platform)"), "{early:?}"); + tokio::fs::write(root.join(GEMFILE_LOCK), lock(None)) + .await + .unwrap(); + assert!(gem_platform_lock_refusals(&root, &[NOKO]).await.is_empty()); + // The lock edit refuses the shape on its own too. + let err = edit_lock(&with_plain, "nokogiri", "1.18.10", &rel(UUID)) + .err() + .expect("a plain entry beside platform ones must fail closed"); + assert!(err.contains("platform-suffixed"), "{err}"); + } + + /// A native gem locked for the ruby platform alone is still refused, + /// whatever the service has: bundler would build it from source, and + /// never does for a `path:` gem. The service is not asked. + #[tokio::test] + async fn a_native_gem_locked_only_for_the_ruby_platform_stays_refused() { + let plain = lock(None).replace( + BLOCKS, + " nokogiri (1.18.10)\n mini_portile2 (~> 2.8.2)\n racc (~> 1.4)\n", + ); + let (tmp, root, record) = project(&plain).await; + let installed = tmp + .path() + .join("gem_home/gems/nokogiri-1.18.10-arm64-darwin"); + tokio::fs::create_dir_all(&installed).await.unwrap(); + let before = ts::tree_snapshot(&root); + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let (code, detail) = + unwrap_refused(vendor(&root, &installed, &record, &cfg, false).await); + assert_eq!(code, "platform_gem_unsupported"); + assert!(detail.contains("nokogiri-1.18.10-arm64-darwin"), "{detail}"); + assert_eq!(ts::tree_snapshot(&root), before); + assert_eq!(ts::request_count(&server).await, 0); + } + + /// The installed copy of a platform-locked gem is a platform gem dir + /// (`gems/nokogiri-1.18.10-arm64-darwin`): it vendors, from the + /// prebuilds and not from that dir. No archive download is planned + /// and the ruby gem is never downloaded: the package reference + /// names the prebuilds, and they are all that is fetched. + #[tokio::test] + async fn an_installed_platform_gem_dir_vendors_from_the_prebuilds() { + let (tmp, root, record) = project(&lock(None)).await; + let installed = tmp + .path() + .join("gem_home/gems/nokogiri-1.18.10-arm64-darwin"); + tokio::fs::create_dir_all(installed.join("lib/nokogiri")) + .await + .unwrap(); + tokio::fs::write(installed.join(RB), RB_PRISTINE) + .await + .unwrap(); + assert_eq!( + service_preflight(NOKO, &installed, &root, &record).await, + None + ); + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let (result, entry, _) = + unwrap_done(vendor(&root, &installed, &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert_eq!(entry.unwrap().gem_platforms, [DARWIN, LINUX]); + let asked: Vec = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .map(|request| request.url.path().to_string()) + .collect(); + assert!( + !asked + .iter() + .any(|path| path.ends_with("/nokogiri-1.18.10.gem")), + "the ruby gem is not downloaded: {asked:?}" + ); + assert_eq!( + asked.len(), + 5, + "the package reference, then a platform gem and its stub per platform: {asked:?}" + ); + assert_eq!( + tokio::fs::read(root.join(rel(UUID)).join(LINUX).join(RB)) + .await + .unwrap(), + RB_PATCHED + ); + assert_eq!( + tokio::fs::read(installed.join(RB)).await.unwrap(), + RB_PRISTINE, + "the installed copy is not touched" + ); + } + + /// An installed ruby-platform copy of the gem (compiled on this + /// machine) beside a lock that pins platform gems: the extensions + /// its gemspec declares are not the prebuilt trees', so they are no + /// refusal. + #[tokio::test] + async fn a_compiled_ruby_install_beside_a_platform_lock_still_vendors() { + let (tmp, root, record) = project(&lock(None)).await; + let home = tmp.path().join("gem_home"); + let installed = home.join("gems/nokogiri-1.18.10"); + tokio::fs::create_dir_all(&installed).await.unwrap(); + tokio::fs::create_dir_all(home.join("specifications")) + .await + .unwrap(); + tokio::fs::write( + home.join("specifications/nokogiri-1.18.10.gemspec"), + "Gem::Specification.new do |s|\n s.name = \"nokogiri\"\n s.extensions = [\"ext/nokogiri/extconf.rb\"]\nend\n", + ) + .await + .unwrap(); + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let (result, entry, _) = + unwrap_done(vendor(&root, &installed, &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert_eq!(entry.unwrap().gem_platforms, [DARWIN, LINUX]); + } + + /// A prebuild is verified against its served integrity like the ruby + /// gem, and a patched file it ships must be the patched one: either + /// failure refuses with nothing written. + #[tokio::test] + async fn a_tampered_or_unpatched_prebuild_is_refused_with_nothing_written() { + let tampered = Served { + gem_sha512: Some(sri_sha512(b"some other bytes")), + ..served(LINUX) + }; + let unpatched = Served { + gem: Some(make_gem(&[(RB, RB_PRISTINE), (SO, &b"so"[..])])), + ..served(LINUX) + }; + let native_stub = Served { + stub: Some( + String::from_utf8(stub(LINUX)) + .unwrap() + .replace( + " s.require_paths", + " s.extensions = [\"ext/nokogiri/extconf.rb\".freeze]\n s.require_paths", + ) + .into_bytes(), + ), + ..served(LINUX) + }; + for (bad, code) in [ + (tampered, "vendor_prebuilt_integrity_mismatch"), + (unpatched, "vendor_prebuilt_required"), + (native_stub, "native_extensions_unsupported"), + ] { + let (_tmp, root, record) = project(&lock(None)).await; + let before = ts::tree_snapshot(&root); + let (_server, cfg) = service(UUID, &[served(DARWIN), bad]).await; + for dry_run in [true, false] { + let (refused, detail) = unwrap_refused( + vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, + ); + assert_eq!(refused, code, "{detail}"); + assert!(detail.contains(LINUX), "{detail}"); + assert_eq!(ts::tree_snapshot(&root), before, "{code} dry_run={dry_run}"); + } + } + } + + /// A patch of a source the platform gem never shipped (it ships the + /// compiled extension) vendors: the prebuild carries the patched + /// files it does ship. One rule then judges a tree wherever it is + /// judged (the download, a re-run's in-sync test, the check): a + /// patched file it holds is the patched one, and one it lacks is no + /// mismatch; the ledger's inventory vouches for every byte of the + /// tree; and with no inventory the tree must hold a patched file. + #[tokio::test] + async fn a_patch_of_unshipped_sources_vendors_and_verifies_by_inventory() { + const EXTRA: &str = "lib/nokogiri/extra.rb"; + const EXTRA_PATCHED: &[u8] = b"# extra, patched\n"; + let with_extra = |platform: &'static str| Served { + gem: Some(make_gem(&[ + (RB, RB_PATCHED), + (EXTRA, EXTRA_PATCHED), + (SO, platform.as_bytes()), + ])), + ..served(platform) + }; + let (_tmp, root, _) = project(&lock(None)).await; + let record = record( + UUID, + &[ + (RB, RB_PRISTINE, RB_PATCHED), + (EXTRA, &b"# extra\n"[..], EXTRA_PATCHED), + (C, &b"pristine C\n"[..], &b"patched C\n"[..]), + ], + ); + let (_server, cfg) = service(UUID, &[with_extra(DARWIN), with_extra(LINUX)]).await; + let entry = vendor_and_persist(&root, &record, &cfg).await; + let tree = root.join(rel(UUID)).join(LINUX); + assert!(!tree.join(C).exists()); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + let corrupt = |reason: &str| ArtifactHealth::Corrupt { + reason: reason.to_string(), + }; + + // No inventory says which files were vendored: the unshipped + // source is accepted, also for an entry synthesized from the + // lock (no platforms either), which reads the trees off the + // artifact. + let mut bare = entry.clone(); + bare.artifact.file_inventory = None; + assert_eq!( + check_vendored_artifact(&root, &bare, &record).await, + ArtifactHealth::Healthy + ); + bare.gem_platforms.clear(); + assert_eq!( + check_vendored_artifact(&root, &bare, &record).await, + ArtifactHealth::Healthy + ); + // A tree holding none of the patched files is vouched for by + // the inventory; with none, nothing vouches for it. + let unshipped = record_of(&record, &[C]); + assert_eq!( + check_vendored_artifact(&root, &entry, &unshipped).await, + ArtifactHealth::Healthy + ); + assert_eq!( + check_vendored_artifact(&root, &bare, &unshipped).await, + corrupt("file_not_found") + ); + + // A patched file the inventory lists and the tree no longer + // holds was vendored and then lost. The check says so, and the + // next run rebuilds the copy instead of calling it in sync. + tokio::fs::remove_file(tree.join(EXTRA)).await.unwrap(); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + corrupt("vendor_inventory_mismatch") + ); + let (result, rebuilt, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert!( + warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt"), + "{warnings:?}" + ); + assert!(rebuilt.is_some(), "a refreshed entry"); + assert_eq!( + tokio::fs::read(tree.join(EXTRA)).await.unwrap(), + EXTRA_PATCHED + ); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + + // Drift in ONE platform's tree fails the whole copy. + tokio::fs::write(tree.join(SO), b"another binary") + .await + .unwrap(); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + corrupt("vendor_inventory_mismatch") + ); + tokio::fs::write(tree.join(RB), RB_PRISTINE).await.unwrap(); + for entry in [&entry, &bare] { + assert_eq!( + check_vendored_artifact(&root, entry, &record).await, + corrupt("vendor_hash_mismatch") + ); + } + + // A platform the ledger names must be a plain directory name. + let mut poisoned = entry.clone(); + poisoned.gem_platforms = vec!["../x".to_string()]; + assert_eq!( + check_vendored_artifact(&root, &poisoned, &record).await, + ArtifactHealth::Unverifiable { + reason: "vendor_path_unsafe".to_string() + } + ); + } + + /// The usual nokogiri patch touches only files no precompiled gem + /// ships (`patches/…`, `dependencies.yml`): it lives entirely in the + /// binaries the prebuild was rebuilt with. Such a prebuild vendors, + /// on the strength of its download's integrity check, and is then + /// vouched for by the ledger's inventory: the in-sync test of a + /// re-run and the check both pass, and both catch a tampered binary. + #[tokio::test] + async fn a_prebuild_holding_none_of_the_patched_files_vendors_and_verifies_by_inventory() { + let (_tmp, root, _) = project(&lock(None)).await; + let record = record(UUID, &[(C, &b"pristine C\n"[..], &b"patched C\n"[..])]); + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let before = ts::tree_snapshot(&root); + let (preview, ..) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, true).await); + assert!(preview.success, "{:?}", preview.error); + assert_eq!(ts::tree_snapshot(&root), before, "a dry run writes nothing"); + + let entry = vendor_and_persist(&root, &record, &cfg).await; + let tree = root.join(rel(UUID)).join(LINUX); + assert!(!tree.join(C).exists(), "the prebuild ships no patched file"); + let inventory = entry.artifact.file_inventory.as_ref().expect("inventory"); + assert!(inventory.contains_key(&format!("{LINUX}/{SO}"))); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + // A second run is in sync and asks the service nothing. + 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); + + // Without the inventory nothing vouches for such a tree. + let mut bare = entry.clone(); + bare.artifact.file_inventory = None; + assert_eq!( + check_vendored_artifact(&root, &bare, &record).await, + ArtifactHealth::Corrupt { + reason: "file_not_found".to_string() + } + ); + + // A tampered binary: the check reports it, and the next run + // rebuilds the copy instead of calling it in sync. + tokio::fs::write(tree.join(SO), b"another binary") + .await + .unwrap(); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Corrupt { + reason: "vendor_inventory_mismatch".to_string() + } + ); + let (result, rebuilt, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert!( + warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt"), + "{warnings:?}" + ); + assert!(rebuilt.is_some(), "a refreshed entry"); + assert_eq!( + tokio::fs::read(tree.join(SO)).await.unwrap(), + LINUX.as_bytes() + ); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + } + + /// A file planted outside every locked platform's tree (at the copy + /// root, or as the tree of a platform the lock does not name, which + /// bundler's glob would load once that platform is added) is one + /// the ledger's inventory does not list. The check rejects it, and + /// so does the in-sync test of a re-run, which rebuilds the copy. + #[tokio::test] + async fn a_file_planted_outside_the_locked_trees_is_not_in_sync() { + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let entry = vendor_and_persist(&root, &record, &cfg).await; + let copy = root.join(rel(UUID)); + for planted in [ + copy.join("planted.rb"), + copy.join("x64-mingw-ucrt").join(SO), + ] { + tokio::fs::create_dir_all(planted.parent().unwrap()) + .await + .unwrap(); + tokio::fs::write(&planted, b"unpatched").await.unwrap(); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Corrupt { + reason: "vendor_inventory_mismatch".to_string() + } + ); + let (result, rebuilt, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert!( + warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt"), + "{warnings:?}" + ); + assert!(rebuilt.is_some(), "a refreshed entry"); + assert!(!planted.exists(), "the rebuild drops {planted:?}"); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + } + } + + /// `record` with only `files`. + fn record_of(record: &PatchRecord, files: &[&str]) -> PatchRecord { + let mut only = record.clone(); + only.files.retain(|file, _| files.contains(&file.as_str())); + only + } + + /// A wired copy that lost one platform's tree is rebuilt in full by + /// the next run (Gemfile and lock untouched), and `repair`'s restore + /// rebuilds it from the ledger's platforms and inventory. + #[tokio::test] + async fn a_lost_platform_tree_is_rebuilt_by_a_rerun_and_by_restore() { + let (_tmp, root, record) = project(&lock(Some(&checksums(&sha('a'), &sha('b'))))).await; + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let entry = vendor_and_persist(&root, &record, &cfg).await; + let tree = root.join(rel(UUID)).join(LINUX); + let wired = ( + text(root.join(GEMFILE)).await, + text(root.join(GEMFILE_LOCK)).await, + ); + + tokio::fs::remove_dir_all(&tree).await.unwrap(); + let (result, rebuilt, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert!( + warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt"), + "{warnings:?}" + ); + let rebuilt = rebuilt.expect("a refreshed entry"); + assert_eq!(rebuilt.gem_platforms, [DARWIN, LINUX]); + assert!(rebuilt.wiring.is_empty(), "the first run's records ride on"); + assert_eq!(tokio::fs::read(tree.join(RB)).await.unwrap(), RB_PATCHED); + assert_eq!( + ( + text(root.join(GEMFILE)).await, + text(root.join(GEMFILE_LOCK)).await + ), + wired + ); + + // The uuid dir's git metadata is not part of the copy: restore + // swaps the copy in from a stage of its own and writes the + // metadata where the project keeps it. + let uuid_dir = root.join(format!(".socket/vendor/gem/{UUID}")); + let metadata = [ + (".gitignore", "!*\n"), + (".gitattributes", crate::vendor::npm_dir::UUID_GITATTRIBUTES), + ]; + for (file, text_of) in metadata { + assert_eq!(text(uuid_dir.join(file)).await, text_of, "{file}"); + tokio::fs::remove_file(uuid_dir.join(file)).await.unwrap(); + } + 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() + } + ); + crate::vendor::redownload::restore(&root, &entry, &record, &cfg) + .await + .expect("restore"); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + for (file, text_of) in metadata { + assert_eq!(text(uuid_dir.join(file)).await, text_of, "restore: {file}"); + } + + // An in-sync re-run puts back metadata that went missing, asks + // the service nothing, 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(); + } + let lost = ts::tree_snapshot(&root); + let (preview, ..) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, true).await); + assert!(preview.success, "{:?}", preview.error); + assert_eq!(ts::tree_snapshot(&root), lost, "a dry run writes nothing"); + let (again, entry_again, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success, "{:?}", again.error); + assert!(entry_again.is_none() && warnings.is_empty(), "{warnings:?}"); + 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); + } + + /// A lock wired to the copy whose CHECKSUMS entry of one platform + /// still carries a registry token is not in sync: refused with the + /// repair path, like the plain entry's. + #[tokio::test] + async fn a_stale_platform_checksum_token_is_refused_on_a_rerun() { + let (_tmp, root, record) = project(&lock(Some(&checksums(&sha('a'), &sha('b'))))).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + // (`\n` + two spaces: the CHECKSUMS entry, not the PATH spec.) + let wired = text(root.join(GEMFILE_LOCK)).await; + let stale = wired.replace( + "\n nokogiri (1.18.10-x86_64-linux-gnu)\n", + &format!("\n nokogiri (1.18.10-x86_64-linux-gnu){}\n", sha('b')), + ); + assert_ne!(stale, wired); + tokio::fs::write(root.join(GEMFILE_LOCK), &stale) + .await + .unwrap(); + let (code, _) = + unwrap_refused(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert_eq!(code, "vendor_stale_lock_checksum"); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, stale); + } + + /// A patch update (new uuid, same gem) over a lock real bundler + /// wrote, where only the platform it downloaded has a registry + /// CHECKSUMS token: the blocks move to the new uuid's section, and + /// the first run's originals — carried forward by the ledger — still + /// restore both files byte for byte. + #[tokio::test] + async fn a_patch_update_rewires_the_platform_blocks_and_still_reverts() { + let lock_before = lock(Some(&checksums(&sha('a'), ""))); + let (_tmp, root, record_a) = project(&lock_before).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let first = vendor_and_persist(&root, &record_a, &cfg).await; + let rec = first + .wiring + .iter() + .find(|w| w.kind == LOCK_CHECKSUM_WIRING_KIND) + .expect("a checksum record"); + assert_eq!( + rec.new, + Some(serde_json::json!([" nokogiri (1.18.10-arm64-darwin)"])), + "only the rewritten entry is recorded" + ); + + let record_b = PatchRecord { + uuid: UUID_B.to_string(), + ..record_a.clone() + }; + let (_server, cfg) = service(UUID_B, &[served(DARWIN), served(LINUX)]).await; + let second = vendor_and_persist(&root, &record_b, &cfg).await; + assert_eq!(second.uuid, UUID_B); + assert_eq!(second.gem_platforms, [DARWIN, LINUX]); + assert_eq!( + text(root.join(GEMFILE_LOCK)).await, + vendored(&rel(UUID_B), Some(&checksums("", ""))) + ); + assert!(text(root.join(GEMFILE)).await.contains(&rel(UUID_B))); + + let reverted = revert_gem(&second, &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(format!(".socket/vendor/gem/{UUID_B}")).exists()); + } + + /// What git says of `path` (project-relative) in the work tree at + /// `root`: `git -- `, trimmed. + fn git(root: &Path, args: &[&str], path: &str) -> String { + let git = crate::utils::process::resolve_tool("git").expect("git"); + let out = std::process::Command::new(git) + .arg("-C") + .arg(root) + .args(args) + .arg("--") + .arg(path) + .output() + .expect("git runs"); + String::from_utf8_lossy(&out.stdout).trim().to_string() + } + + /// The prebuilt binaries are committable, byte for byte: a project + /// rule that ignores them by pattern (`*.so`) is overridden by the + /// uuid dir's own `.gitignore`, and a project filter on them (a Git + /// LFS rule) by its `.gitattributes`, the pair every backend that + /// commits binaries writes. A rule nothing under the uuid dir can + /// override (one that ignores a directory above it) refuses the gem + /// before anything is downloaded, in a dry run as in a wet one. + #[tokio::test] + async fn prebuilt_binaries_git_would_not_commit_are_re_included_or_refused() { + for (rules, refused_code) in [ + ("*.so\n*.bundle\n", None), + ("/.socket/vendor/gem/\n", Some("vendor_artifact_gitignored")), + ] { + let (_tmp, root, record) = project(&lock(None)).await; + if ts::git_project(&root, rules).is_none() { + return; // no git, nothing to commit + } + tokio::fs::write( + root.join(".gitattributes"), + "*.so filter=lfs diff=lfs merge=lfs -text\n", + ) + .await + .unwrap(); + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let uuid_dir = root.join(format!(".socket/vendor/gem/{UUID}")); + match refused_code { + None => { + let outcome = + vendor(&root, ¬_installed(&root), &record, &cfg, false).await; + let (result, entry, warnings) = unwrap_done(outcome); + assert!(result.success, "{:?}", result.error); + assert!(entry.is_some()); + assert!( + !warnings.iter().any(|w| w.code.contains("gitignore")), + "{warnings:?}" + ); + assert_eq!(text(uuid_dir.join(".gitignore")).await, "!*\n"); + assert_eq!( + text(uuid_dir.join(".gitattributes")).await, + crate::vendor::npm_dir::UUID_GITATTRIBUTES + ); + let binary = format!("{}/{DARWIN}/{SO}", rel(UUID)); + assert_eq!( + crate::vendor::npm_dir::gitignored(&root, &[binary.clone()]).await, + None, + "git commits the prebuilt binary" + ); + assert_eq!( + git(&root, &["check-attr", "filter"], &binary), + format!("{binary}: filter: unset"), + "and commits its bytes, not what the project's LFS filter makes of them" + ); + } + Some(code) => { + let before = ts::tree_snapshot(&root); + for dry_run in [true, false] { + let (refused, detail) = unwrap_refused( + vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, + ); + assert_eq!(refused, code, "dry_run={dry_run}: {detail}"); + assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); + } + assert_eq!( + ts::request_count(&server).await, + 0, + "refused before the service is asked for anything" + ); + assert!(!root.join(".socket/vendor").exists()); + } + } + } + } + + /// A prebuild that ships a `.gitignore` of its own (its repository's, + /// swept into the gem) would hide files from git below the uuid + /// dir's `!*`, where no rule of the project's reaches. Each is + /// emptied in the copy, at any depth, and reported; the ledger's + /// inventory is of the tree as vendored, so the check passes and + /// `repair`'s restore reproduces it. One the patch itself rewrites + /// keeps the patch's bytes. + #[tokio::test] + async fn a_gitignore_a_prebuild_ships_is_emptied_in_the_copy() { + const NESTED: &str = "lib/nokogiri/.gitignore"; + const PATCHED_IGNORE: &str = "ext/.gitignore"; + let shipping = |platform: &'static str| Served { + gem: Some(make_gem(&[ + (RB, RB_PATCHED), + (SO, platform.as_bytes()), + (".gitignore", &b"*.so\n*.bundle\n"[..]), + (NESTED, &b"nokogiri.so\n"[..]), + (PATCHED_IGNORE, &b"# the patch's own\n"[..]), + ])), + ..served(platform) + }; + let (_tmp, root, _) = project(&lock(None)).await; + let record = record( + UUID, + &[ + (RB, RB_PRISTINE, RB_PATCHED), + (PATCHED_IGNORE, &b"*.o\n"[..], &b"# the patch's own\n"[..]), + ], + ); + if ts::git_project(&root, "*.so\n").is_none() { + return; // no git, nothing to commit + } + let (_server, cfg) = service(UUID, &[shipping(DARWIN), shipping(LINUX)]).await; + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + let neutralized: Vec<_> = warnings + .iter() + .filter(|w| w.code == "vendor_gem_gitignore_neutralized") + .collect(); + assert_eq!(neutralized.len(), 1, "{warnings:?}"); + for file in [ + format!("{DARWIN}/.gitignore"), + format!("{DARWIN}/{NESTED}"), + format!("{LINUX}/.gitignore"), + ] { + assert!(neutralized[0].detail.contains(&file), "{neutralized:?}"); + } + assert!( + !neutralized[0].detail.contains(PATCHED_IGNORE), + "{neutralized:?}" + ); + ts::persist(&root, NOKO, entry.expect("a ledger entry")).await; + let entry = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); + + let copy = root.join(rel(UUID)); + let emptied = |copy: &Path| { + for platform in [DARWIN, LINUX] { + let tree = copy.join(platform); + for file in [".gitignore", NESTED] { + assert_eq!(std::fs::read(tree.join(file)).unwrap(), b"", "{file}"); + } + assert_eq!( + std::fs::read(tree.join(PATCHED_IGNORE)).unwrap(), + b"# the patch's own\n" + ); + } + }; + emptied(©); + let binary = format!("{}/{LINUX}/{SO}", rel(UUID)); + assert_eq!( + crate::vendor::npm_dir::gitignored(&root, &[binary]).await, + None, + "git commits the prebuilt binary" + ); + // The inventory is of the tree as vendored: it lists the + // emptied files, the check passes, and a second run is in sync. + let inventory = entry.artifact.file_inventory.as_ref().expect("inventory"); + assert!(inventory.contains_key(&format!("{LINUX}/{NESTED}"))); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + let (again, rerun_entry, _) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success && rerun_entry.is_none(), "{:?}", again.error); + + // `repair`'s restore reproduces the same tree from the service. + tokio::fs::remove_dir_all(copy.join(LINUX)).await.unwrap(); + crate::vendor::redownload::restore(&root, &entry, &record, &cfg) + .await + .expect("restore"); + emptied(©); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + } + + /// A platform names a directory under the vendored dir, and the lock + /// it is read from is committed data: one that is no plain directory + /// name is refused before anything is asked or written. + #[tokio::test] + async fn an_unsafe_platform_token_is_refused() { + let poisoned = lock(None).replace("1.18.10-x86_64-linux-gnu", "1.18.10-.."); + let (_tmp, root, record) = project(&poisoned).await; + let before = ts::tree_snapshot(&root); + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let (code, detail) = + unwrap_refused(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert_eq!(code, "unsafe_coordinates"); + assert!(detail.contains("`..`"), "{detail}"); + assert_eq!(ts::tree_snapshot(&root), before); + assert_eq!(ts::request_count(&server).await, 0); + } + + /// The lock edit on its own: the blocks move verbatim and in lock + /// order (a direct and a transitive gem), revert splices them back, + /// and shapes bundler never writes fail closed. + #[test] + fn the_lock_edit_moves_every_platform_block_and_fails_closed() { + let registry = checksums(&sha('a'), &sha('b')); + let transitive = lock(None).replace(" nokogiri (~> 1.18)\n", ""); + for before in [lock(None), lock(Some(®istry)), transitive] { + let edit = edit_lock(&before, "nokogiri", "1.18.10", &rel(UUID)).unwrap(); + assert_eq!(edit.platforms, [DARWIN, LINUX]); + assert_eq!(edit.removed_spec_block.join("\n") + "\n", BLOCKS); + assert!(!edit.rewired_ours); + let (original, new) = lock_record_lines(&edit); + let reverted = revert_lock_text(&edit.text, &original, &new).unwrap(); + // The checksum record restores the registry tokens. + let reverted = match reverted.split_once("CHECKSUMS\n") { + Some((head, entries)) => { + let entries = edit.checksum_rewrites.iter().fold( + entries.to_string(), + |text, (orig, bare)| { + text.replace(&format!("{bare}\n"), &format!("{orig}\n")) + }, + ); + format!("{head}CHECKSUMS\n{entries}") + } + None => reverted, + }; + assert_eq!(reverted, before); + + // A patch update lifts the same blocks out of our section. + let again = edit_lock(&edit.text, "nokogiri", "1.18.10", &rel(UUID_B)).unwrap(); + assert!(again.rewired_ours); + assert_eq!(again.platforms, [DARWIN, LINUX]); + assert_eq!(again.text, edit.text.replace(UUID, UUID_B)); + } + + let fails = |lock: String, why: &str| { + let err = edit_lock(&lock, "nokogiri", "1.18.10", &rel(UUID)) + .err() + .unwrap_or_else(|| panic!("must fail closed: {why}")); + assert!(err.contains(why), "{err}"); + }; + // The platform entries apart from each other. + fails( + lock(None).replace( + " nokogiri (1.18.10-x86_64-linux-gnu)\n racc (~> 1.4)\n puma (6.4.2)\n nio4r (~> 2.0)\n", + " puma (6.4.2)\n nio4r (~> 2.0)\n nokogiri (1.18.10-x86_64-linux-gnu)\n racc (~> 1.4)\n", + ), + "apart from each other", + ); + // One platform listed twice. + fails( + lock(None).replace( + " puma (6.4.2)\n", + " nokogiri (1.18.10-arm64-darwin)\n puma (6.4.2)\n", + ), + "more than once", + ); + // CHECKSUMS entries for builds the specs do not lock. + fails( + lock(Some(®istry)).replace( + "CHECKSUMS\n", + &format!("CHECKSUMS\n nokogiri (1.18.10){}\n", sha('e')), + ), + "its specs do not lock", + ); + fails( + lock(Some(®istry)).replace( + "CHECKSUMS\n", + &format!( + "CHECKSUMS\n nokogiri (1.18.10-aarch64-linux-musl){}\n", + sha('e') + ), + ), + "its specs do not lock", + ); + // Our own section holding more than vendor wrote. + let edit = edit_lock(&lock(None), "nokogiri", "1.18.10", &rel(UUID)).unwrap(); + fails( + edit.text.replace( + " nokogiri (1.18.10-arm64-darwin)\n", + " nokogiri (1.18.10)\n nokogiri (1.18.10-arm64-darwin)\n", + ), + "not the shape vendor wrote", + ); + } + + /// The checksum record of a gem vendored as platform gems pairs each + /// bare line with the registry line of the same entry: an entry that + /// was bare before vendoring is left alone, a restored one has + /// converged, and a missing one is drift that writes nothing. + #[tokio::test] + async fn the_checksum_record_restores_each_platform_line_or_none() { + let lock_before = lock(Some(&checksums(&sha('a'), &sha('b')))); + let (_tmp, root, record) = project(&lock_before).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let entry = vendor_and_persist(&root, &record, &cfg).await; + let wired = text(root.join(GEMFILE_LOCK)).await; + + // One registry line already back (a partial hand restore). + let partly = wired.replace( + " nokogiri (1.18.10-arm64-darwin)\n nokogiri", + &format!(" nokogiri (1.18.10-arm64-darwin){}\n nokogiri", sha('a')), + ); + assert_ne!(partly, wired); + // One entry gone altogether: drift, and neither file is written. + let drifted = wired.replace(" nokogiri (1.18.10-x86_64-linux-gnu)\n puma", " puma"); + assert_ne!(drifted, wired); + let gemfile = text(root.join(GEMFILE)).await; + tokio::fs::write(root.join(GEMFILE_LOCK), &drifted) + .await + .unwrap(); + let outcome = revert_gem(&entry, &root, false).await; + assert!( + outcome + .warnings + .iter() + .any(|w| w.code == "vendor_lock_entry_drifted"), + "{:?}", + outcome.warnings + ); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, drifted); + assert_eq!(text(root.join(GEMFILE)).await, gemfile); + assert!(root.join(rel(UUID)).is_dir(), "the copy is kept on drift"); + + tokio::fs::write(root.join(GEMFILE_LOCK), &partly) + .await + .unwrap(); + let outcome = revert_gem(&entry, &root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(outcome.warnings.is_empty(), "{:?}", outcome.warnings); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, lock_before); + assert_eq!(text(root.join(GEMFILE)).await, GEMFILE_NOKO); + } + } } diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/recover.rs b/crates/socket-patch-core/src/vendor/lock_inventory/recover.rs index 5376b46d5..f998bea4f 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/recover.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/recover.rs @@ -95,20 +95,34 @@ pub async fn recover_lock_entry( }) } "gem" => { - let line = wiring_original(entry, &["gemfile_lock_checksum"]) - .and_then(|v| v.as_str().map(str::to_string)) - .ok_or_else(|| "no pre-vendor Gemfile.lock checksum recorded".to_string())?; - let sha = line - .split("sha256=") - .nth(1) - .map(|rest| { - rest.trim_end_matches(',') - .trim() - .chars() - .take_while(|c| c.is_ascii_hexdigit()) - .collect::() + // One CHECKSUMS line for a gem vendored as its own tree; an + // array of them, one per platform entry the edit made bare, + // for a gem vendored as precompiled platform gems. + let lines: Vec<&str> = match wiring_original(entry, &["gemfile_lock_checksum"]) { + Some(Value::String(line)) => vec![line.as_str()], + Some(Value::Array(lines)) => lines.iter().filter_map(Value::as_str).collect(), + _ => Vec::new(), + }; + if lines.is_empty() { + return Err("no pre-vendor Gemfile.lock checksum recorded".to_string()); + } + // The first line with a sha256, and the `.gem` it pins: the + // ruby gem for the plain `name (version)` entry, the platform + // gem for a `name (version-platform)` one. + let (gem_version, sha) = lines + .iter() + .find_map(|line| { + let sha = checksum_line_sha256(line)?; + let gem_version = match crate::formats::gem::split_checksum_entry(line.trim()) { + Some((gem, token, _)) + if gem == name && token.starts_with(&format!("{version}-")) => + { + token.to_string() + } + _ => version.clone(), + }; + Some((gem_version, sha)) }) - .filter(|s| is_hex(s, 64)) .ok_or_else(|| { "the pre-vendor checksum line has no sha256; refusing an unverifiable fetch" .to_string() @@ -143,7 +157,7 @@ pub async fn recover_lock_entry( source_kind: SourceKind::Unspecified, pnpm_env: false, purl: format!("pkg:gem/{name}@{version}"), - resolved: gem_download_url(&base, &name, &version), + resolved: gem_download_url(&base, &name, &gem_version), name, version, integrity: LockIntegrity::Sha256Hex(sha.to_ascii_lowercase()), @@ -298,6 +312,21 @@ fn parse_base_purl_coords(base_purl: &str) -> Option<(String, String)> { Some((name, version)) } +/// The 64-hex sha256 a recorded `Gemfile.lock` CHECKSUMS line +/// (` () sha256=`) pins, if it pins one. +fn checksum_line_sha256(line: &str) -> Option { + line.split("sha256=") + .nth(1) + .map(|rest| { + rest.trim_end_matches(',') + .trim() + .chars() + .take_while(|c| c.is_ascii_hexdigit()) + .collect::() + }) + .filter(|s| is_hex(s, 64)) +} + /// First wiring record of one of `kinds` carrying an `original` payload. fn wiring_original<'a>( entry: &'a crate::vendor::state::VendorEntry, diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/recover_tests.rs b/crates/socket-patch-core/src/vendor/lock_inventory/recover_tests.rs index b1129b73d..a9daab3b9 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/recover_tests.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/recover_tests.rs @@ -305,6 +305,41 @@ async fn composer_gem_uv_fragments_recover() { Some("https://rubygems.org/downloads/rack-3.0.0.gem") ); + // gem vendored as precompiled platform gems: the record holds an ARRAY + // of lines, one per platform entry that carried a registry checksum. + // The first line with a sha256 is recovered, for the platform gem it + // pins. + let platform_sha = "f".repeat(64); + let platform_gem = entry( + "gem", + "pkg:gem/nokogiri@1.18.10", + vec![rec( + "gemfile_lock_checksum", + serde_json::json!([ + " nokogiri (1.18.10-arm64-darwin)", + format!(" nokogiri (1.18.10-x86_64-linux-gnu) sha256={platform_sha}"), + ]), + )], + ); + let got = recover_lock_entry(tmp.path(), &platform_gem).await.unwrap(); + assert_eq!(got.version, "1.18.10"); + assert_eq!(got.integrity, LockIntegrity::Sha256Hex(platform_sha)); + assert_eq!( + got.resolved.as_deref(), + Some("https://rubygems.org/downloads/nokogiri-1.18.10-x86_64-linux-gnu.gem") + ); + // An array with no checksum at all is as unverifiable as a bare line. + let bare = entry( + "gem", + "pkg:gem/nokogiri@1.18.10", + vec![rec( + "gemfile_lock_checksum", + serde_json::json!([" nokogiri (1.18.10-arm64-darwin)"]), + )], + ); + let err = recover_lock_entry(tmp.path(), &bare).await.unwrap_err(); + assert!(err.contains("no sha256"), "{err}"); + // uv: the original [[package]] unit lists wheels; only the PURE one // is recoverable. let wheel_sha = "e".repeat(64); diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index dd6c03c94..2243aa74d 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -720,10 +720,23 @@ pub const VENDOR_PREBUILT_UNAVAILABLE: &str = "vendor_prebuilt_unavailable"; /// no older vendored patch to keep. pub const VENDOR_PREBUILT_REQUIRED: &str = "vendor_prebuilt_required"; +/// gem: `Gemfile.lock` pins the gem as precompiled platform gems and the +/// patch service lists no prebuilt platform gem for at least one of the +/// locked platforms. The service lists a prebuild only once it is built, so +/// "not built yet" and "never built" look the same from here: the package +/// is left as it is and the run does not fail because of it, with or +/// without an older vendored patch to keep (see [`VENDOR_PREBUILT_PENDING`] +/// for the kept one). A re-run vendors it once every platform has one. +pub const VENDOR_PREBUILT_PLATFORM_PENDING: &str = "vendor_prebuilt_platform_pending"; + /// Whether `code` marks a patch the service does not serve (yet): -/// [`VENDOR_PREBUILT_PENDING`] or [`VENDOR_PREBUILT_UNAVAILABLE`]. +/// [`VENDOR_PREBUILT_PENDING`], [`VENDOR_PREBUILT_UNAVAILABLE`] or +/// [`VENDOR_PREBUILT_PLATFORM_PENDING`]. pub fn is_unserved(code: &str) -> bool { - matches!(code, VENDOR_PREBUILT_PENDING | VENDOR_PREBUILT_UNAVAILABLE) + matches!( + code, + VENDOR_PREBUILT_PENDING | VENDOR_PREBUILT_UNAVAILABLE | VENDOR_PREBUILT_PLATFORM_PENDING + ) } /// The result of one backend `vendor_*` call. diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index e6bc9195b..a6c0df6af 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -231,17 +231,36 @@ pub async fn restore( "gem" => { let (name, _) = parse_gem_purl(&entry.base_purl).ok_or("invalid gem coordinates")?; - super::gem::gem_service_copy( - Some(service), - record, - &name, - &stage, - uuid_dir, - true, - &mut warnings, - ) - .await - .map_err(|outcome| detail(*outcome))?; + // A gem vendored as platform gems is restored from the + // prebuild of each platform the ledger names. + let copied = match entry.gem_platforms.as_slice() { + [] => { + super::gem::gem_service_copy( + Some(service), + record, + &name, + &stage, + uuid_dir, + true, + &mut warnings, + ) + .await + } + platforms => { + super::gem::gem_platform_service_copy( + Some(service), + record, + &name, + platforms, + &stage, + uuid_dir, + true, + &mut warnings, + ) + .await + } + }; + copied.map_err(|outcome| detail(*outcome))?; } "npm" => { let (name, version) = super::npm_common::parse_npm_purl(&entry.base_purl) @@ -380,6 +399,16 @@ 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 prebuilt binaries from the commit. + if entry.ecosystem == "gem" && !entry.gem_platforms.is_empty() { + if let Some(rel) = super::path::vendor_uuid_dir_rel("gem", &entry.uuid) { + super::gem::restore_uuid_metadata(&root.join(rel)) + .await + .map_err(|e| format!("cannot restore the vendored dir's git metadata: {e}"))?; + } + } Ok(warnings) } diff --git a/crates/socket-patch-core/src/vendor/refusals.rs b/crates/socket-patch-core/src/vendor/refusals.rs index 74ac3883c..6d91c065e 100644 --- a/crates/socket-patch-core/src/vendor/refusals.rs +++ b/crates/socket-patch-core/src/vendor/refusals.rs @@ -198,9 +198,11 @@ async fn maven_refusals( .unwrap_or_default() } -/// The gem candidates whose version `Gemfile.lock` doesn't resolve -/// ([`gem::gem_version_not_locked_refusals`]), installed or not: the -/// backend refuses either before it asks the patch service for anything. +/// The gem candidates the backend refuses from `Gemfile.lock` alone +/// ([`gem::gem_lock_refusals`]), installed or not: a version the lock +/// doesn't resolve, and a gem it locks as platform gems in a way that +/// cannot be vendored. The backend refuses either before it asks the patch +/// service for anything. async fn gem_refusals( project_root: &Path, candidates: &[(&str, &str)], @@ -213,7 +215,7 @@ async fn gem_refusals( if gems.is_empty() { return Vec::new(); } - gem::gem_version_not_locked_refusals(project_root, &gems).await + gem::gem_lock_refusals(project_root, &gems).await } fn refuse(out: &mut VendorRefusals, purl: &str, code: &'static str, detail: &str) { diff --git a/crates/socket-patch-core/src/vendor/service_fetch.rs b/crates/socket-patch-core/src/vendor/service_fetch.rs index fca75828d..b3c2e2b66 100644 --- a/crates/socket-patch-core/src/vendor/service_fetch.rs +++ b/crates/socket-patch-core/src/vendor/service_fetch.rs @@ -90,13 +90,7 @@ impl VerifiedArchive { /// it has used these bytes for `subject`. The source URL carries the /// org's grant token; [`VendorWarning::new`] quotes it redacted. pub(crate) fn downloaded_warning(&self, subject: impl std::fmt::Display) -> VendorWarning { - VendorWarning::new( - "vendor_prebuilt_downloaded", - format!( - "vendored {subject} from the patch service ({})", - self.source_url - ), - ) + downloaded_warning(subject, &self.source_url) } /// Hex sha256 of [`Self::bytes`], digested once on first ask. @@ -106,9 +100,40 @@ impl VerifiedArchive { } } +/// The `vendor_prebuilt_downloaded` advisory for `subject`, vendored from +/// `source_url` (see [`VerifiedArchive::downloaded_warning`]). +pub(crate) fn downloaded_warning( + subject: impl std::fmt::Display, + source_url: &str, +) -> VendorWarning { + VendorWarning::new( + "vendor_prebuilt_downloaded", + format!("vendored {subject} from the patch service ({source_url})"), + ) +} + +/// What the patch service lists for a patch besides its archive, learned +/// from the package reference alone ([`fetch_served_artifacts`]): still +/// unverified, and nothing of the patch is downloaded yet. +#[derive(Debug)] +pub(crate) struct ServedArtifacts(pub Vec); + +impl ServedArtifacts { + /// The served artifact of `kind` for the gem platform `platform`, if + /// the service lists one. + pub(crate) fn platform(&self, kind: &str, platform: &str) -> Option<&SecondaryArtifact> { + self.0 + .iter() + .find(|a| a.kind == kind && a.platform.as_deref() == Some(platform)) + } +} + +/// What the service has for a patch: its verified archive +/// ([`fetch_verified_archive`]), or the list of its other artifacts +/// ([`fetch_served_artifacts`]). #[derive(Debug)] -pub(crate) enum ServiceArtifact { - Ready(VerifiedArchive), +pub(crate) enum ServiceArtifact { + Ready(T), /// Archive still building (retryable). Pending, /// Terminal miss for this input (not built / withdrawn / not found / no @@ -177,6 +202,35 @@ pub(crate) async fn fetch_verified_archive( }) } +/// Ask the service which artifacts it serves for `uuid` besides the +/// archive, without downloading the archive: the package reference names +/// them. For a backend that vendors only those (a gem's per-platform +/// prebuilds), so a patch that has none costs one request and no download. +pub(crate) async fn fetch_served_artifacts( + 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( + uuid, + cfg.use_public_proxy, + cfg.vendor_url.as_deref(), + cfg.patch_server_url.as_deref(), + ) + .await; + match outcome { + VendorServiceOutcome::Ready(artifacts) => { + ServiceArtifact::Ready(ServedArtifacts(artifacts)) + } + VendorServiceOutcome::Pending => ServiceArtifact::Pending, + VendorServiceOutcome::Unavailable(reason) => ServiceArtifact::Unavailable(reason), + VendorServiceOutcome::Failed(err) => ServiceArtifact::Failed(err.to_string()), + } +} + /// Move the tree the download plan pre-staged from `archive`'s bytes (see /// [`crate::vendor::prestage`]) into `stage`, the backend's stage for /// `copy_dir`, where the backend would otherwise extract them. `false` — @@ -232,12 +286,12 @@ impl ServicePolicy<'_> { } /// `noun` names the artifact kind; `subject` identifies it in error messages. - pub(crate) fn settle( + pub(crate) fn settle( &self, - artifact: ServiceArtifact, + artifact: ServiceArtifact, noun: &str, subject: &str, - ) -> Result> { + ) -> Result> { match artifact { ServiceArtifact::Ready(archive) => Ok(archive), ServiceArtifact::IntegrityMismatch(reason) => Err(self.hard( @@ -324,11 +378,33 @@ pub(crate) async fn fetch_verified_secondary( cfg: &VendorServiceConfig, archive: &VerifiedArchive, kind: &str, +) -> SecondaryArtifactResult { + fetch_verified_artifact(cfg, archive.secondary.iter().find(|a| a.kind == kind)).await +} + +/// [`fetch_verified_secondary`] for an artifact served once per gem +/// platform (`gem-platform`, `gem-platform-stub-gemspec`): the one of +/// `kind` whose `platform` is exactly `platform`, the token `Gemfile.lock` +/// spells. +pub(crate) async fn fetch_verified_platform_secondary( + cfg: &VendorServiceConfig, + served: &ServedArtifacts, + kind: &str, + platform: &str, +) -> SecondaryArtifactResult { + fetch_verified_artifact(cfg, served.platform(kind, platform)).await +} + +/// Download `artifact` and verify the bytes against its own sha512 SRI; +/// `Absent` when the service referenced no such artifact. +async fn fetch_verified_artifact( + cfg: &VendorServiceConfig, + artifact: Option<&SecondaryArtifact>, ) -> SecondaryArtifactResult { let Some(client) = cfg.client.as_ref() else { return SecondaryArtifactResult::Failed("vendor service not configured".to_string()); }; - let Some(artifact) = archive.secondary.iter().find(|a| a.kind == kind) else { + let Some(artifact) = artifact else { return SecondaryArtifactResult::Absent; }; @@ -753,6 +829,7 @@ mod tests { secondary: vec![SecondaryArtifact { prefetched: None, kind: "gem-stub-gemspec".into(), + platform: None, url: format!("{}/stub", server.uri()), integrity_sri: PackedTarball::from_bytes(b"x").integrity, }], diff --git a/crates/socket-patch-core/src/vendor/state.rs b/crates/socket-patch-core/src/vendor/state.rs index 079fac06d..5857af81d 100644 --- a/crates/socket-patch-core/src/vendor/state.rs +++ b/crates/socket-patch-core/src/vendor/state.rs @@ -317,6 +317,15 @@ pub struct VendorEntry { /// pypi/pipenv extras. #[serde(default, skip_serializing_if = "Option::is_none")] pub pipenv: Option, + /// gem: the platforms of a gem vendored as precompiled platform gems, + /// in `Gemfile.lock` order (`arm64-darwin`, `x86_64-linux-gnu`, …). + /// The artifact dir then holds one unpacked prebuild per platform, at + /// `//`, instead of the gem's own tree: bundler + /// never builds a `path:` gem's extensions, so a gem the lock resolves + /// to platform gems is vendored as the patch service's prebuilt ones. + /// Empty for a gem vendored as its ruby-platform tree. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub gem_platforms: Vec, /// True when vendored WITHOUT a manifest record — the posture of every /// `scan` / `get --mode vendored` entry (vendored mode writes no /// `.socket/manifest.json`); only the manifest-driven standalone @@ -365,6 +374,7 @@ impl VendorEntry { poetry: None, pdm: None, pipenv: None, + gem_platforms: Vec::new(), detached: false, record: None, } @@ -2620,6 +2630,7 @@ mod tests { poetry: None, pdm: None, pipenv: None, + gem_platforms: Vec::new(), }; let built = VendorEntry::npm( "pkg:npm/left-pad@1.3.0".to_string(), diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index 038b4d8da..fb4f2083e 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -26,7 +26,10 @@ use std::path::{Path, PathBuf}; use crate::hash::git_sha256::compute_git_sha256_from_bytes; use crate::manifest::schema::{PatchFileInfo, PatchRecord}; -use crate::patch::apply::{normalize_file_path, verify_file_patch, VerifyStatus}; +use crate::patch::apply::{ + is_missing_path, is_safe_relative_subpath, normalize_file_path, verify_file_patch, VerifyStatus, +}; +use crate::patch::file_hash::compute_file_git_sha256; use crate::patch::package::read_archive_to_map; use super::path::parse_vendor_path; @@ -131,7 +134,18 @@ pub async fn verify_vendored_patch_record( path_str.ends_with(".whl") || path_str.ends_with(".nupkg") || path_str.ends_with(".jar"); if !is_tarball && !is_zip { let cargo_uuid = (entry.ecosystem == "cargo").then_some(entry.uuid.as_str()); - verify_dir_members(&artifact, record, cargo_uuid).await?; + match gem_platform_trees(&artifact, entry).await? { + // A gem vendored as precompiled platform gems: bundler loads + // the tree of whichever platform it runs on, so every one of + // them must carry the patch. + Some(trees) => { + let voucher = TreeVoucher::Ledger(entry.artifact.file_inventory.as_ref()); + for tree in &trees { + verify_platform_tree(tree, &record.files, voucher).await?; + } + } + None => verify_dir_members(&artifact, record, cargo_uuid).await?, + } // Whole-tree cross-check: a dir-shaped artifact's bytes are covered // by NO lockfile integrity (bundler path sources, cargo path deps, // …), so the members above are the only thing the record can vouch @@ -226,6 +240,161 @@ async fn verify_dir_members( Ok(()) } +/// The prebuild trees of a gem vendored as precompiled platform gems +/// (`//`, see [`super::gem`]'s module docs); `None` +/// for every other dir-shaped artifact, whose files sit in the artifact dir +/// itself. The ledger entry names the trees. An entry synthesized from a +/// lockfile reference names none, so the layout is then read off the +/// artifact: no `.gemspec` at its root (every gem vendored as its own +/// tree has one there) and one in each platform's subdirectory. +async fn gem_platform_trees( + artifact: &Path, + entry: &VendorEntry, +) -> Result>, String> { + if entry.ecosystem != "gem" { + return Ok(None); + } + if !entry.gem_platforms.is_empty() { + // SECURITY: state.json is committed and tamper-able, and each + // platform is about to name a directory that gets stat'd and hashed. + if !entry + .gem_platforms + .iter() + .all(|platform| super::gem::is_platform_dir_name(platform)) + { + return Err("vendor_path_unsafe".to_string()); + } + let trees = entry.gem_platforms.iter().map(|p| artifact.join(p)); + return Ok(Some(trees.collect())); + } + let Some((name, _)) = crate::utils::purl::parse_gem_purl(&entry.base_purl) else { + return Ok(None); + }; + let stub = format!("{name}.gemspec"); + let is_file = |path: PathBuf| async move { + tokio::fs::symlink_metadata(path) + .await + .is_ok_and(|m| m.is_file()) + }; + if is_file(artifact.join(&stub)).await { + return Ok(None); + } + let mut trees = Vec::new(); + let Ok(mut entries) = tokio::fs::read_dir(artifact).await else { + return Ok(None); + }; + while let Ok(Some(child)) = entries.next_entry().await { + // `file_type` does not follow links: a linked tree is no tree. + if child.file_type().await.is_ok_and(|t| t.is_dir()) + && is_file(child.path().join(&stub)).await + { + trees.push(child.path()); + } + } + trees.sort(); + Ok((!trees.is_empty()).then_some(trees)) +} + +/// What vouches for the bytes of a prebuild tree beyond the patched files +/// it holds (see [`verify_platform_tree`]). +#[derive(Clone, Copy)] +pub(crate) enum TreeVoucher<'a> { + /// The tree was just unpacked from a prebuild archive whose bytes + /// passed the integrity digest the patch service states for that + /// platform. No unverified archive is ever unpacked. + VerifiedDownload, + /// The ledger's file inventory of the vendored copy (keyed + /// `/`), taken when the copy was vendored; `None` for + /// an entry that records none. + Ledger(Option<&'a BTreeMap>), +} + +/// The rule one prebuild tree of a gem vendored as precompiled platform +/// gems must meet (`tree` is `//`, `files` the patch +/// record's). One rule for every place that judges such a tree: the +/// download gate, the in-sync test of a re-run, and `vendor --check` / +/// `vex` / `repair`. +/// +/// * A patched file the tree holds hashes to its `afterHash`. +/// * A patched file the tree does NOT hold is no mismatch, even when it +/// holds none of them. A platform gem ships the compiled extension and +/// often not what it was built from: the usual nokogiri patch adds a +/// file under `patches/` or edits `dependencies.yml`, which no +/// precompiled gem ships, so the patch lives entirely in the binaries +/// the patch service rebuilt. What stands for those bytes is `voucher`: +/// the integrity check of the download while the tree is staged, and +/// afterwards the ledger's inventory, which every file of the tree must +/// match (a file it lists that is gone or changed is a mismatch, and so +/// is one it does not list). +/// * With neither — an entry with no inventory — the tree must hold at +/// least one patched file: otherwise nothing vouches for it. +/// +/// The error is a stable routing tag (see the module docs). +pub(crate) async fn verify_platform_tree( + tree: &Path, + files: &HashMap, + voucher: TreeVoucher<'_>, +) -> Result<(), String> { + if !tokio::fs::symlink_metadata(tree) + .await + .is_ok_and(|m| m.is_dir()) + { + return Err("file_not_found".to_string()); + } + let mut holds_patched_file = false; + for (file_name, info) in files { + let normalized = normalize_file_path(file_name); + // SECURITY: never hash through a record key that escapes the tree. + if !is_safe_relative_subpath(normalized) { + return Err("file_not_found".to_string()); + } + match compute_file_git_sha256(&tree.join(normalized)).await { + Ok(hash) if hash == info.after_hash => holds_patched_file = true, + Ok(_) => return Err("vendor_hash_mismatch".to_string()), + Err(e) if is_missing_path(&e) => {} + Err(_) => return Err("file_not_found".to_string()), + } + } + match voucher { + TreeVoucher::VerifiedDownload => Ok(()), + TreeVoucher::Ledger(Some(inventory)) => verify_tree_inventory(tree, inventory).await, + TreeVoucher::Ledger(None) if holds_patched_file => Ok(()), + TreeVoucher::Ledger(None) => Err("file_not_found".to_string()), + } +} + +/// [`verify_dir_inventory`] for one prebuild tree: the files under `tree` +/// are exactly the ones the copy's `inventory` lists below +/// `/`, with the recorded bytes. +async fn verify_tree_inventory( + tree: &Path, + inventory: &BTreeMap, +) -> Result<(), String> { + let mismatch = || "vendor_inventory_mismatch".to_string(); + let platform = tree + .file_name() + .and_then(|name| name.to_str()) + .ok_or_else(mismatch)?; + let prefix = format!("{platform}/"); + let recorded: BTreeMap<&str, &str> = inventory + .iter() + .filter_map(|(file, hash)| Some((file.strip_prefix(&prefix)?, hash.as_str()))) + .collect(); + let actual = compute_dir_inventory(tree) + .await + .map_err(|_| "vendor_artifact_unreadable".to_string())?; + if actual.len() != recorded.len() { + return Err(mismatch()); + } + for (file, hash) in recorded { + match actual.get(file) { + Some(live) if live.eq_ignore_ascii_case(hash) => {} + _ => return Err(mismatch()), + } + } + Ok(()) +} + /// A vlt package-dir entry: npm, flavor `vlt`, not a tarball. The vendored /// dir layout decides before the suffix does: the path ends in the package /// name, which may itself end in one (`lodash.zip`). diff --git a/crates/socket-patch-core/src/vex/discover/gem.rs b/crates/socket-patch-core/src/vex/discover/gem.rs index 7518f2762..5d6b838da 100644 --- a/crates/socket-patch-core/src/vex/discover/gem.rs +++ b/crates/socket-patch-core/src/vex/discover/gem.rs @@ -178,7 +178,11 @@ //! root-anchored `.socket/vendor/gem//-` dir //! ([`vendor_ref`]; `./` and a trailing `/` tolerated), and each spec under //! it must be exactly the gem that leaf names (the vendor backend names the -//! dir after the gem it replaces; [`vendored_leaf_purl`] must agree). An +//! dir after the gem it replaces; [`vendored_leaf_purl`] must agree). A gem +//! bundler locked as precompiled platform gems is vendored as one prebuilt +//! tree per platform in that one dir, so its section holds a spec per +//! platform (`nokogiri (1.18.10-arm64-darwin)`, …): together they are ONE +//! vendored reference of the gem. An //! escaping (`../`, absolute), leaf-less, non-gem, or mismatched remote is //! [`DIAG_REF_INVALID`]. Path gems carry no sha256 (bundler writes a BARE //! `CHECKSUMS` entry for them), so vendored refs never set @@ -938,8 +942,13 @@ fn spec_ref( }; // A platform build is hosted wiring only in a Socket section of the // gem's own, where the rewriter moves every build of the version. + // A vendored `PATH` section holds one spec per platform of a gem + // vendored as precompiled platform gems (`vendor::gem`): its dir has a + // prebuild tree for each, so every one of them is the same reference + // to the one artifact ([`Discovery::push`] keeps one). + let hosted = matches!(wiring, Wiring::Hosted { .. }); let own_hosted = matches!(wiring, Wiring::Hosted { only: None, .. }); - if let Some(platform) = spec.platform.filter(|_| !own_hosted) { + if let Some(platform) = spec.platform.filter(|_| hosted && !own_hosted) { out.diag( DIAG_REF_INVALID, file, @@ -1401,6 +1410,76 @@ mod tests { assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); } + /// A gem `vendor::gem` vendored as precompiled platform gems: the one + /// PATH section holds a spec per platform (each with its dependency + /// sublines) and CHECKSUMS a bare entry per platform. Together they are + /// ONE vendored reference of the gem, with or without a CHECKSUMS + /// section. + #[tokio::test] + async fn vendored_platform_gems_are_one_reference() { + let rel = vendored_rel(UUID_A, "nokogiri-1.18.10"); + let checksums = format!( + "CHECKSUMS\n nokogiri (1.18.10-arm64-darwin)\n nokogiri (1.18.10-x86_64-linux-gnu)\n \ + racc (1.8.1) sha256={SHA_UP}\n\n" + ); + for checksums in [checksums.as_str(), ""] { + let lock = format!( + "PATH\n remote: {rel}\n specs:\n nokogiri (1.18.10-arm64-darwin)\n \ + racc (~> 1.4)\n nokogiri (1.18.10-x86_64-linux-gnu)\n racc (~> 1.4)\n\n\ + GEM\n remote: https://rubygems.org/\n specs:\n racc (1.8.1)\n\n\ + PLATFORMS\n arm64-darwin\n x86_64-linux-gnu\n\n\ + DEPENDENCIES\n nokogiri (= 1.18.10)!\n\n{checksums}BUNDLED WITH\n 4.0.15\n" + ); + let p = Project::new(); + p.write( + "Gemfile", + manifest(&[vendored_decl("nokogiri", "1.18.10", &rel)]), + ); + p.write("Gemfile.lock", lock); + let out = run(&p).await; + assert_refs( + &out, + &[("pkg:gem/nokogiri@1.18.10", UUID_A, WiringMode::Vendored)], + ); + let r = only(&out); + assert_eq!(r.artifact_rel.as_deref(), Some(rel.as_str())); + assert_eq!(r.locked_integrity, None); + assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); + } + } + + /// Platform specs under a vendored PATH section keep the section's + /// other rules: the dir must be the gem's own, and the manifest must + /// name it. Each failing spec is diagnosed, and none is a reference. + #[tokio::test] + async fn vendored_platform_specs_keep_the_leaf_and_manifest_rules() { + let platform_specs = + " nokogiri (1.18.10-arm64-darwin)\n nokogiri (1.18.10-x86_64-linux-gnu)\n"; + let tail = "GEM\n remote: https://rubygems.org/\n specs:\n\nDEPENDENCIES\n \ + nokogiri (= 1.18.10)!\n"; + let own = vendored_rel(UUID_A, "nokogiri-1.18.10"); + let other = vendored_rel(UUID_A, "rack-3.2.6"); + for (remote, declared, code) in [ + // Another gem's vendored dir. + (&other, &other, DIAG_REF_INVALID), + // The gem's own dir, which the Gemfile does not name. + (&own, &other, DIAG_REF_UNATTRIBUTABLE), + ] { + let p = Project::new(); + p.write( + "Gemfile", + manifest(&[vendored_decl("nokogiri", "1.18.10", declared)]), + ); + p.write( + "Gemfile.lock", + format!("PATH\n remote: {remote}\n specs:\n{platform_specs}\n{tail}"), + ); + let out = run(&p).await; + assert!(out.refs.is_empty(), "{remote}: {:#?}", out.refs); + assert_eq!(diag_codes(&out), vec![code; 2], "{:#?}", out.diagnostics); + } + } + /// Several vendored gems (bundler sorts PATH sections by remote), a /// hyphenated gem name, a hosted section, and a CRLF checkout — all in /// one lock. diff --git a/docs/ecosystems.md b/docs/ecosystems.md index d7ce43d90..c9a5f34b9 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -17,7 +17,7 @@ The backticked slug in each row is the value `-e`/`--ecosystems` accepts (e.g. | npm (`npm`) — pnpm / yarn / berry / bun / vlt | ✅ any install layout, vlt's `node_modules/.vlt` store included (every store copy, copy-on-write) | ✅ seven lockfile flavors: package-lock, yarn classic, yarn berry (node-modules linker; PnP refused), pnpm v9, pnpm legacy v5.4/v6.0 (`pnpm 7/8` — frozen installs are path-bound because those majors absolutize `file:` override specifiers; moved checkouts run one `pnpm install --offline --no-frozen-lockfile`, surfaced as `vendor_pnpm_legacy_absolute_specifier`), bun text `bun.lock` lockfileVersion 0/1/2/3 and native binary `bun.lockb` revisions 1/2/3 (binary locks stay binary; text workspace vendoring requires lockfileVersion 2 — see [Bun compatibility](testing/bun-compatibility.md)), vlt `vlt-lock.json` lockfileVersion 0/1 (patched package directories for direct dependencies of the root or a workspace member; transitive targets refused — see [vlt notes](#npm-vlt-notes)). Rush monorepos on pnpm 9 and newer are wired through `pnpm-config.json` and each directly-depending project's `package.json` — see [Rush notes](#npm-rush-monorepos) | ✅ package-lock / npm-shrinkwrap, pnpm-lock.yaml and legacy shrinkwrap.yaml (pnpm majors 1–12; block and flow resolutions), yarn classic, yarn berry, bun, vlt (`vlt-lock.json` without `lockfileVersion`, 0 or 1) — pnpm, berry, bun and vlt carry constraints, see [npm hosted-mode notes](#npm-hosted-mode-notes) and [vlt notes](#npm-vlt-notes) | | 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). | ✅ 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). | | 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 | -| 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; `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) | ✅ 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") | +| RubyGems (`gem`) | ✅ in place | ✅ Gemfile + Gemfile.lock path pair (a CRLF `Gemfile.lock`, as a `core.autocrlf` checkout leaves it, is edited and reverted in its own line ending, and a lock mixing CRLF and LF fails closed; a gem locked as precompiled platform gems is vendored from prebuilt patched platform gems, see [Ruby gems: native extensions](#ruby-gems-native-extensions); `Gemfile` spelling only — a `gems.rb` twin, which bundler ≥ 2 loads instead, or a `BUNDLE_GEMFILE`-configured manifest makes vendoring refuse with `gemfile_not_loaded` before any write) | ✅ 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") | | 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`) | @@ -2274,7 +2274,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 from the patched platform gem the registry serves for that platform, with nothing to compile; it is skipped with `redirect_gem_platform_unsupported` only while the patch has no patched build for one of the locked platforms. | -| Vendored | Refused with `native_extensions_unsupported`: Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for the 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 prebuilt patched platform gems. The patch service builds one for each platform, and the vendored directory holds each of them unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. Every platform in the lock needs one. While the patch service has none for one of them the gem is skipped with `vendor_prebuilt_platform_pending`, which names the platforms that have none: the run does not fail, nothing is written, a patch that is already vendored stays in place, and a later run vendors the gem once every platform has one. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the prebuilt binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | | 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,