diff --git a/.github/workflows/bazel-ruby.yml b/.github/workflows/bazel-ruby.yml index bf0b2ffde..322a1fd35 100644 --- a/.github/workflows/bazel-ruby.yml +++ b/.github/workflows/bazel-ruby.yml @@ -33,9 +33,10 @@ on: # discovery, the lock inventory, the Ruby crawler (it says which lock # Bundler loads), the upstream restore of `rollback`, the stale-install # guard that those commands end with, the vendored backend - # (vendor/gem.rs), and the refusal of vendored mode beside a hub that - # reads the lock (vendor/bazel_hub.rs), which vendor/refusals.rs hands - # to every command. + # (vendor/gem.rs, and vendor/gem/ for the gem it commits for a hub), + # and the refusal of vendored mode beside a hub that reads the lock + # (vendor/bazel_hub.rs), which vendor/refusals.rs hands to every + # command. # Last, the VEX code: `vex/` of the core, the files of the `vex` # command, and `bazel/` of the core, which reads the workspace files and # decides whether Bazel builds what was patched. Every flow holds the @@ -73,6 +74,7 @@ on: - 'crates/socket-patch-core/src/patch/redirect/upstream/gem.rs' - 'crates/*/src/**/gem_refresh.rs' - 'crates/socket-patch-core/src/vendor/gem.rs' + - 'crates/socket-patch-core/src/vendor/gem/**' - 'crates/socket-patch-core/src/vendor/bazel_hub.rs' - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/bazel/**' @@ -101,6 +103,7 @@ on: - 'crates/socket-patch-core/src/patch/redirect/upstream/gem.rs' - 'crates/*/src/**/gem_refresh.rs' - 'crates/socket-patch-core/src/vendor/gem.rs' + - 'crates/socket-patch-core/src/vendor/gem/**' - 'crates/socket-patch-core/src/vendor/bazel_hub.rs' - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/bazel/**' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 45aed9c43..d329e9a1f 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -122,7 +122,7 @@ Every subcommand accepts the same set of "global" flags via a single shared `Glo | `--no-vlt-install-cleanup` | — | `SOCKET_NO_VLT_INSTALL_CLEANUP` | `false` | bool | Opt out of hosted mode's warm-tree heal for vlt: stale installed copies (`node_modules/.vlt-lock.json` and the stale `node_modules/.vlt/` entries) are left in place after `vlt-lock.json` is repointed (`scan`/`get --mode hosted`) or restored (`rollback`/`remove`), and the `redirect_vlt_reinstall_required` advisory tells you to run `vlt ci` instead. Stale copies of optional dependencies are always left in place (see `redirect_vlt_reinstall_required`). Other subcommands accept it silently | | `--no-gem-install-refresh` | — | `SOCKET_NO_GEM_INSTALL_REFRESH` | `false` | bool | Opt out of hosted mode's gem stale-install refresh: the gems Bundler already holds for the project (an installed gem under the project and its cached `.gem`, an archive in `vendor/cache`) are left as they are after `Gemfile.lock` is repointed (`scan`/`get --mode hosted`) or restored (`rollback`/`remove`, of a hosted pin or of a vendored gem; `vendor --revert`), and the `redirect_gem_stale_install` / `upstream_gem_stale_install` warning names the files to remove by hand instead (see the "Gem stale-install guard" section). Other subcommands accept it silently | | `--gem-refresh-shared` | — | `SOCKET_GEM_REFRESH_SHARED` | `false` | bool | Extend the gem stale-install refresh to gem homes OUTSIDE the project (the system gems, `~/.gem`, an rbenv or asdf home) and to project bundle or cache paths that resolve outside the project directory. Off by default: another project on the machine may pin the other build of the same gem version, and its `bundle pristine` then fails on the replaced archive's checksum (see the "Gem stale-install guard" section). Other subcommands accept it silently | -| `--allow-vendored-in-bazel` | — | `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `false` | bool | Let vendored mode write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. Vendored mode declines such a package by default, and the switch lifts each of those refusals. `vendor_composer_bazel_workspace`: the lock then names the patched copy by a path relative to the directory Composer runs in, and a Bazel rule that runs `composer install` anywhere else fails on it. `vendor_pypi_bazel_hub` and `vendor_gem_bazel_hub`: a rules_python or rules_ruby hub of the workspace reads the lock, which then names the patched copy by a path under `.socket/vendor`, and neither ruleset builds from that. For a project whose build does find the copy, or does not take its packages from that lock. Read by `vendor`, `scan --mode vendored` and `get --mode vendored`; other subcommands accept it silently. See docs/ecosystems.md "Bazel workspaces: Composer" and "Bazel workspaces: PyPI and RubyGems vendored mode" | +| `--allow-vendored-in-bazel` | — | `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `false` | bool | Let vendored mode write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. Vendored mode declines such a package by default, and the switch lifts each of those refusals. `vendor_composer_bazel_workspace`: the lock then names the patched copy by a path relative to the directory Composer runs in, and a Bazel rule that runs `composer install` anywhere else fails on it. `vendor_pypi_bazel_hub` and `vendor_gem_bazel_hub`: a rules_python or rules_ruby hub of the workspace reads the lock, which then names the patched copy by a path under `.socket/vendor`, and neither ruleset builds from that. For a project whose build does find the copy, or does not take its packages from that lock. A gem that vendored mode commits for a rules_ruby hub as an archive without the switch (`vendor_gem_bazel_file_source`) is vendored by its path with it, like every other gem. Read by `vendor`, `scan --mode vendored` and `get --mode vendored`; other subcommands accept it silently. See docs/ecosystems.md "Bazel workspaces: Composer" and "Bazel workspaces: PyPI and RubyGems vendored mode" | **`--download-mode` removed (v5.0, MAJOR).** The global `--download-mode` flag and its `SOCKET_DOWNLOAD_MODE` binding are gone, with no alias: passing the flag is a usage error (exit 2) and the env var is ignored. Patch content is always fetched as per-file blobs (`.socket/blobs/`); `.socket/diffs/` archives are obsolete, never read, and removed by the cleanup sweeps. @@ -1728,7 +1728,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` unless the run has `--allow-vendored-in-bazel` | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked prebuilt platform gem per locked platform, `-//`, each with its gemspec, plus `/.gitignore` (`!*`: re-includes the prebuilt binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a prebuilt platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patch's prebuilt platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform; EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. Every locked platform needs a prebuild: while the patch service lists none for one of them the gem is skipped (`vendor_prebuilt_platform_pending`, no failure) with nothing written. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no prebuilt tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the project is refused `vendor_gem_bazel_hub` unless the run has `--allow-vendored-in-bazel` | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked prebuilt platform gem per locked platform, `-//`, each with its gemspec, plus `/.gitignore` (`!*`: re-includes the prebuilt binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a prebuilt platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patch's prebuilt platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform; EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. Every locked platform needs a prebuild: while the patch service lists none for one of them the gem is skipped (`vendor_prebuilt_platform_pending`, no failure) with nothing written. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no prebuilt tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub`, and with `--allow-vendored-in-bazel` it is vendored by its path as above | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | @@ -2537,7 +2537,9 @@ command's integration tests check its output. | `vendor_bun_lockb_invalid` | `failed` | vendor / scan / get `--mode vendored`: the binary lock is malformed, unreadable, unsupported or cannot be rewritten safely. The detail names the parser, hash or filesystem error. Refused before patch downloads and before hosted takeover; the package's `failed` event carries `errorCode` and `error`, while `get ` also carries top-level `error.code`. Dry-run predicts the same refusal. | | `vendor_bun_workspace_unsupported` | `failed` | vendor / scan / get `--mode vendored` (bun): the text lock holds `workspace:` packages and its `lockfileVersion` is below 2 — Bun 1.2–1.3 resolve a workspace member's local-tarball path relative to the member; a committed version-2 lock is the proof every consumer runs Bun ≥ 1.4 (deliberate over-approximation: root-only declared packages would install on version 1 too). Detail names the version integer and a version-specific remedy: delete `bun.lock` and re-lock with Bun ≥ 1.4 (an in-place `bun install` keeps the existing version) — then, for a version-1 lock, "or use `--mode hosted`, which accepts version-1 workspace locks"; for a version-0 lock, "or delete `bun.lock`, re-lock with Bun ≥ 1.2 (which writes lockfileVersion 1) and use `--mode hosted`" (hosted refuses version-0 workspace locks, so a bare hosted pointer would send the user into a second refusal). Refused before any write — in the pre-download preflight on `get`/`scan` (see `vendor_bun_lockb_invalid` for the placements); in the shared preflight that `vendor` and the vendor step run BEFORE a hosted → vendored takeover's revert (a hosted-redirected purl stays hosted-wired, ledger and lock untouched; `vendor --dry-run` previews the same `failed` code); and in the engine when the run would write a NEW local tuple. Exempt: purls the vendor ledger wires at the selected uuid, purls whose every `bun.lock` instance is already a `.socket/vendor/npm/` tuple (any uuid), in-sync re-runs and `repair` redownloads. | | `vendor_composer_bazel_workspace` | `failed` | vendor / scan / get `--mode vendored` (composer): the project is in a Bazel workspace (its directory, or one above it up to the root of its git checkout, holds `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel`). Vendored mode makes `composer.lock` name the patched copy by a path relative to the directory Composer runs in; a Bazel repository rule or build action that runs `composer install` from the lock anywhere else fails with Composer's `Source path "…" is not found for package …`, and the build with it (Bazel 9.3.2, 8.8.2, 7.7.2). Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the Bazel root and the mode that writes no such path, `--mode hosted`. Not refused: a run with `--allow-vendored-in-bazel`, `vendor --revert`, and a package whose `composer.lock` entry already names the copy of the same patch (the run leaves the lock as it is, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included; a new patch for it is refused). A project that commits its `vendor/` tree is refused like any other: the tree shows that Composer has run in the project's directory, not that no rule of the workspace runs it elsewhere as well. See docs/ecosystems.md "Bazel workspaces: Composer". | -| `vendor_pypi_bazel_hub` / `vendor_gem_bazel_hub` | `failed` | vendor / scan / get `--mode vendored` (pypi, gem): a hub of the project's Bazel workspace reads a file of the project that the run would point at the copy under `.socket/vendor`. That is a rules_python `pip.parse` whose `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows` or `uv_lock` names a requirements file of the project that the run may write (`requirements.txt` or a file it includes with `-r`, as one set: in a project with no tool lock, for a package they name beside a uv, Pipenv or PEP 751 lock, and for a package they hold by a URL, which is a hosted pin, beside a Poetry or PDM lock) or the `uv.lock` of a uv project; a rules_ruby `ruby.bundle_fetch` whose `gemfile` or `gemfile_lock` names the project's `Gemfile` or `Gemfile.lock`; and a call of a `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`), where `@//` is the main repository when the file says `workspace(name = "")`. Neither ruleset builds from such a file: rules_python 2.5.0-rc4 fails with `invalid user-provided repo name '___/_socket/vendor/pypi/…'`, and the `bundle install` action of rules_ruby 1.0.0-rc2 with `The path … does not exist.`, after a command that exited 0 (Bazel 9.3.2, 8.8.2, 7.7.2). Also refused, for every package whose run would write such a file: a workspace whose files cannot be read with certainty where a call of the hub may be behind that (a call of the hub whose file is not a plain string label or that passes `*` or `**`; a hub proxy handed on; a module file or a statement of one that cannot be read, while the workspace calls the hub or a file that was read names its ruleset; a root `MODULE.bazel` or a `WORKSPACE` file that cannot be read at all, for which one byte that is not UTF-8 is enough), because a call may then read the project's lock. Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the call with its file and line, the lock (or the place and the reason of the doubt), the Bazel root, and the mode whose pin both rulesets build, `--mode hosted` (rules_ruby where its call passes no `gem_checksums`, which the detail for a gem says). Not refused: a package whose run writes no file that such a call names, in a Bazel workspace or outside one (a Poetry or PDM project, whose lock is wired alone, beside a hub that reads its exported `requirements.txt`, unless that file holds the package by a URL); a workspace whose files were read and neither call the hub nor name its ruleset; a run with `--allow-vendored-in-bazel`; `vendor --revert`; and a package that the file the call names already names by the copy of the same patch (`.socket/vendor/pypi//`, `.socket/vendor/gem//`): the run adds nothing to what the hub reads, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included, while a new patch for the package is refused; where the calls name more than one file of the project, each of them that holds the package has to name the copy. Where the reading is in doubt no file is known to be the hub's, and every run without the switch is refused. See docs/ecosystems.md "Bazel workspaces: PyPI and RubyGems vendored mode" | +| `vendor_pypi_bazel_hub` / `vendor_gem_bazel_hub` | `failed` | vendor / scan / get `--mode vendored` (pypi, gem): a hub of the project's Bazel workspace reads a file of the project that the run would point at the copy under `.socket/vendor`. That is a rules_python `pip.parse` whose `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows` or `uv_lock` names a requirements file of the project that the run may write (`requirements.txt` or a file it includes with `-r`, as one set: in a project with no tool lock, for a package they name beside a uv, Pipenv or PEP 751 lock, and for a package they hold by a URL, which is a hosted pin, beside a Poetry or PDM lock) or the `uv.lock` of a uv project; a rules_ruby `ruby.bundle_fetch` whose `gemfile` or `gemfile_lock` names the project's `Gemfile` or `Gemfile.lock`; and a call of a `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`), where `@//` is the main repository when the file says `workspace(name = "")`. Neither ruleset builds from such a file: rules_python 2.5.0-rc4 fails with `invalid user-provided repo name '___/_socket/vendor/pypi/…'`, and the `bundle install` action of rules_ruby 1.0.0-rc2 with `The path … does not exist.`, after a command that exited 0 (Bazel 9.3.2, 8.8.2, 7.7.2). Also refused, for every package whose run would write such a file: a workspace whose files cannot be read with certainty where a call of the hub may be behind that (a call of the hub whose file is not a plain string label or that passes `*` or `**`; a hub proxy handed on; a module file or a statement of one that cannot be read, while the workspace calls the hub or a file that was read names its ruleset; a root `MODULE.bazel` or a `WORKSPACE` file that cannot be read at all, for which one byte that is not UTF-8 is enough), because a call may then read the project's lock. Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the call with its file and line, the lock (or the place and the reason of the doubt), the Bazel root, and the mode whose pin both rulesets build, `--mode hosted` (rules_ruby where its call passes no `gem_checksums`, which the detail for a gem says). Not refused: a package whose run writes no file that such a call names, in a Bazel workspace or outside one (a Poetry or PDM project, whose lock is wired alone, beside a hub that reads its exported `requirements.txt`, unless that file holds the package by a URL); a workspace whose files were read and neither call the hub nor name its ruleset; a run with `--allow-vendored-in-bazel`; `vendor --revert`; and a package that the file the call names already names by the copy of the same patch (`.socket/vendor/pypi//`, `.socket/vendor/gem//`): the run adds nothing to what the hub reads, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included, while a new patch for the package is refused; where the calls name more than one file of the project, each of them that holds the package has to name the copy. Where the reading is in doubt no file is known to be the hub's, and every run without the switch is refused. For a gem the refusal is narrower: where a `ruby.bundle_fetch` call names the project's `Gemfile` or lock and the reading is certain, the gem is vendored as its committed archive (`vendor_gem_bazel_file_source`) and is refused only where that form is not known to build, which the detail names in the place of the path sentence: the checkout names no Bazel release as three numbers in `.bazelversion` or `.bazeliskrc` (none at all, or `latest` or a release candidate), or names 9.1.0 or one outside 7, 8 and 9; the project is not the root of the Bazel workspace; a `WORKSPACE` file defines repositories; a call of the hub does not write out the files it reads, or reads one of the two files alone; its `gem_checksums` are not written out; the lock has no `CHECKSUMS` section and a call that reads the two files has no `gem_checksums` entry for the gem (the detail names that call); the lock's `BUNDLED WITH` names no Bundler, or one that is neither 2.6 or later of the 2 line nor of the 4 line (the hub runs the lock's Bundler, and was built with 2.6.9 and 4.0.15); or the lock holds the gem as platform gems. One more condition is known only once the patched gem is downloaded, so it is refused by the backend, after the download and before any write, with the same code, and a dry run of `scan` or `get`, which downloads nothing, does not show it: a `gem_checksums` entry of any call that reads the two files that holds the gem to another sha256 than the patched gem's (the detail names the call, the entry and both sums, and says that no undo puts the old value back; no file is edited). See docs/ecosystems.md "Bazel workspaces: PyPI and RubyGems vendored mode" and "Bazel workspaces: RubyGems vendored mode" | +| `vendor_gem_bazel_file_source` | `skipped` (advisory; human: `Warning: …`) | vendor / scan / get `--mode vendored` (gem; additive): the gem was committed for a rules_ruby hub of the project's Bazel workspace as its archive, `.socket/vendor/gem//gems/-.gem`, which `Gemfile` and `Gemfile.lock` name by the relative URL `file:.socket/vendor/gem//`. The detail says what that form costs: Bundler by itself does not install from such a source (`bundle install` on a machine without the gem and `bundle lock --update` fail; on a machine that installed the gem before the patch, `bundle install` passes and keeps that unpatched copy), so the checkout builds its gems through Bazel only, and hosted mode serves both; and Bazel does not watch the gem, so an output base that fetched the hub before keeps what it fetched. A human run that vendored only such gems words the second of its `Next steps:` as ``Build with Bazel, which installs the committed gems, then run `socket-patch vex` to verify the installed patches.`` in the place of the reinstall; one that vendored other packages too keeps its reinstall step and adds the line `Build with Bazel as well: it alone installs the gems committed for its hub.` One event per gem vendored this way by the run; none on an in-sync run, and none with `--allow-vendored-in-bazel`. The ledger entry's artifact is the archive (`artifact.path` is `.socket/vendor/gem//gems/-.gem`, with its `sha256` and `size`), and its wiring records are `gemfile_file_source` and `gemfile_lock_file_source`. See docs/ecosystems.md "Bazel workspaces: RubyGems vendored mode" | +| `vendor_gem_bazel_checksum_left` | warning of the undo (human: `Warning: …`) | `vendor --revert` / `rollback` / `remove` (gem; additive): the undo put `Gemfile` and `Gemfile.lock` back for a gem that was committed for a rules_ruby hub (`vendor_gem_bazel_file_source`), and the `gem_checksums` of a `ruby.bundle_fetch` call of the workspace still hold the gem to the sha256 of the patched gem, which the vendoring run asked the user to write there. socket-patch does not edit the call, so the Bazel build fails on that entry (`Checksum was … but wanted …`) until it holds the upstream gem's sha256 again or is removed. The detail names the call with its file and line, the entry and the sha256. The undo itself is complete and its exit code is unchanged; also reported by its dry run. See docs/ecosystems.md "Bazel workspaces: RubyGems vendored mode" | | `vendor_lockfile_missing` / `vendor_lockfile_version_unsupported` (bun preflight placement) | `failed` | scan / get `--mode vendored` (bun): the pre-download preflight found `bun.lock` unreadable / at a `lockfileVersion` other than 0 to 3 (a newer version: update socket-patch; no integer: re-lock with Bun ≥ 1.2 — the same text as hosted's `redirect_bun_lock_unsupported`) or outside bun's single-line `packages` grammar. Same placements as `vendor_bun_lockb_invalid`; nothing fetched, no patch record. An unreadable `.socket/vendor/state.json` met by the same preflight is `vendor_state_unreadable` (see that row), never one of these. | | `bun_lockb_invalid` | scan `warnings[]` (run-level) | scan (every mode): the native binary inventory could not parse or read `bun.lockb`; detail names the format or filesystem error. Also printed as `Warning: …` on stderr. Exit and status remain unchanged. The warning is retained on empty and non-empty scans; valid binary locks are inventoried normally without a runtime or install. | | `bun_lock_unsupported` | scan `warnings[]` (run-level) | scan (every mode): the text `bun.lock` is there but the lock reader refuses it — a `lockfileVersion` newer than 3, no integer version, or a `packages` section outside bun's single-line grammar (a comment line, a re-indent) — so the packages it lists were not read from the lockfile. Detail is the shared version gate's text or `bun.lock: line : …`, followed by `, so the packages it lists were NOT read from the lockfile: a package that is locked but not installed was not scanned`. Also printed as `Warning: …` on stderr, and a scan that then finds no package at all ends `No packages found (see the warning).` instead of advising an install. Status and exit are unchanged (0): before, a checkout without `node_modules` scanned as an empty project and the lock was not mentioned. Installed packages are still crawled, and hosted / vendored runs keep their own refusal (`redirect_bun_lock_unsupported` / `vendor_lockfile_version_unsupported`). The hosted in-memory engine reports the same code among its warnings. | @@ -4179,7 +4181,7 @@ match it, withholds the statement: | `gradle_unpatched_copy` | `failed[].reason` | The purl the warning above (or `vex_gradle_derived_cache_check_failed`) withheld. | | `vex_gradle_derived_cache_check_failed` | run warning | The derived-cache check of an attested Gradle copy did not finish (it crashed), so a copy derived from the unpatched jar cannot be ruled out; no statement for that purl. | | `vex_gradle_lock_above_base` | run warning and `failed[].reason` | A hosted pin is wired, but a lock file records a release above its base, which that build resolves instead of the patch; no statement until it is re-locked or the patch is rolled back. | -| `vex_bazel_not_in_build` | run warning and `skipped` event of `vex` | In a Bazel workspace, `MODULE.bazel` or a file it includes hands the package to a hub that builds it from a lock (aspect_rules_js `npm.npm_translate_lock`, rules_python `pip.parse`, rules_ruby `ruby.bundle_fetch`), and the patch is not in what the hub builds: it is in the installed copy while the project's own lock, which the call names, lists the package at that version without naming the patch (the lock in the project's directory, or the lock of a pnpm workspace above it that names that directory among its importers), or it is a PyPI copy under `.socket/vendor` and the call names the file that points at it. The package is not omitted: each advisory of its patch gets a statement of the package's own with `status: "affected"`, the package as the one subcomponent of the product, and an `action_statement` that says what Bazel builds the package from and what to run (`scan --mode hosted` in the directory of that lock; for a vendored copy `vendor --revert` first), and for an installed copy ends with the way out of a repository that ships the installed tree (``If what you ship is the installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).``), with no `justification` and no `impact_statement`; they come after the `not_affected` statement of an advisory that a patched package shares. The warning, one per package, starts `: the VEX document says affected.` and goes on with the action statement; no `vendored_tree_out_of_sync` warning is given for such a package. The document is always written for it, and the exit code is the one of a run without it: standalone `vex` exits 0 with the document, also when every statement is `affected`. It does not report the package as verified: each such statement is a `skipped` event with this `errorCode` and `details.status: "affected"`, counted in `summary.skipped` and not in `summary.verified`, and the envelope's `status` is `partialFailure`. A command run with `--vex` writes the document, keeps its exit code and status, and carries the warning in `vex.warnings` and the number of such statements in `vex.affected`. The one-line summary counts them: `Wrote OpenVEX document with 2 statements (1 affected) to `. `--no-verify` changes none of it. Not raised in a run with `--no-bazel` / `--vex-no-bazel` / `SOCKET_VEX_NO_BAZEL`, which reads no Bazel file (see "The installed tree" under "VEX provenance markers"), for a hosted pin, for a vendored gem (no build has shown what rules_ruby does with one), in a `--global` run, for a patch whose record names no advisory (no run attests it), for the lock of another project (beside the project, below it, or above it without naming it), for a package that only the env document of a pnpm 11 lock lists, for a call that is not a statement of its own (in a comprehension, behind `and`, in a conditional, in the arguments of another call: it may never run), for a call that passes `*` or `**` or a `pip.parse` with `uv_lock` (it may take its packages from a file that is not read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, a label that is not a plain string, a lock that cannot be read, is over 64 MiB or is a link out of the Bazel root): the statement is then the `not_affected` one of a project without Bazel. See "Bazel workspaces: VEX" in `docs/ecosystems.md`. | +| `vex_bazel_not_in_build` | run warning and `skipped` event of `vex` | In a Bazel workspace, `MODULE.bazel` or a file it includes hands the package to a hub that builds it from a lock (aspect_rules_js `npm.npm_translate_lock`, rules_python `pip.parse`, rules_ruby `ruby.bundle_fetch`), and the patch is not in what the hub builds: it is in the installed copy while the project's own lock, which the call names, lists the package at that version without naming the patch (the lock in the project's directory, or the lock of a pnpm workspace above it that names that directory among its importers), or it is a PyPI copy under `.socket/vendor` and the call names the file that points at it. The package is not omitted: each advisory of its patch gets a statement of the package's own with `status: "affected"`, the package as the one subcomponent of the product, and an `action_statement` that says what Bazel builds the package from and what to run (`scan --mode hosted` in the directory of that lock; for a vendored copy `vendor --revert` first), and for an installed copy ends with the way out of a repository that ships the installed tree (``If what you ship is the installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).``), with no `justification` and no `impact_statement`; they come after the `not_affected` statement of an advisory that a patched package shares. The warning, one per package, starts `: the VEX document says affected.` and goes on with the action statement; no `vendored_tree_out_of_sync` warning is given for such a package. The document is always written for it, and the exit code is the one of a run without it: standalone `vex` exits 0 with the document, also when every statement is `affected`. It does not report the package as verified: each such statement is a `skipped` event with this `errorCode` and `details.status: "affected"`, counted in `summary.skipped` and not in `summary.verified`, and the envelope's `status` is `partialFailure`. A command run with `--vex` writes the document, keeps its exit code and status, and carries the warning in `vex.warnings` and the number of such statements in `vex.affected`. The one-line summary counts them: `Wrote OpenVEX document with 2 statements (1 affected) to `. `--no-verify` changes none of it. Not raised in a run with `--no-bazel` / `--vex-no-bazel` / `SOCKET_VEX_NO_BAZEL`, which reads no Bazel file (see "The installed tree" under "VEX provenance markers"), for a hosted pin, for a vendored gem (rules_ruby builds one that is committed as its archive, `vendor_gem_bazel_file_source`, and one vendored by its path only when the call lists the copy's files, which is not read), in a `--global` run, for a patch whose record names no advisory (no run attests it), for the lock of another project (beside the project, below it, or above it without naming it), for a package that only the env document of a pnpm 11 lock lists, for a call that is not a statement of its own (in a comprehension, behind `and`, in a conditional, in the arguments of another call: it may never run), for a call that passes `*` or `**` or a `pip.parse` with `uv_lock` (it may take its packages from a file that is not read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, a label that is not a plain string, a lock that cannot be read, is over 64 MiB or is a link out of the Bazel root): the statement is then the `not_affected` one of a project without Bazel. See "Bazel workspaces: VEX" in `docs/ecosystems.md`. | | `vex_pnpm_bundled_copy` | run warning and `failed[].reason` | An npm pin is wired, but its pnpm lock names a package whose `bundledDependencies` may ship an unpatched copy of it (the lock does not record that copy's version); no statement while that package bundles it. `vendor --check` and `scan` still treat the wiring as live. | | `vex_deno_lock_copy` | run warning and `failed[].reason` | An npm pin is wired, but `deno.lock` locks the same `name@version`, which `deno install` installs without the wiring; no statement while it does. `vendor --check` and `scan` still treat the wiring as live. | | `vex_maven_reactor_root` | run warning and `failed[].reason` | A hosted Maven patch is wired in a reactor (`` / ``, a profile's included, or Maven 4 subproject discovery) one of whose modules may build the unpatched version: it resolves the patched version, or its selection cannot be told on the machine that runs `vex`, and no pin or declaration of the patch reaches it; or a declaration may still build the base version; or a pom of the reactor cannot be read. No statement; the note names the module (#261). `list`, `rollback` and `remove` still find the wiring. | diff --git a/crates/socket-patch-cli/src/args.rs b/crates/socket-patch-cli/src/args.rs index 2f1354fcd..1b9e7b6b8 100644 --- a/crates/socket-patch-cli/src/args.rs +++ b/crates/socket-patch-cli/src/args.rs @@ -435,8 +435,10 @@ pub struct GlobalArgs { /// (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`), which builds /// nothing from a lock that names a copy under `.socket/vendor`. Pass /// it when the build does find the copy, or does not take the - /// project's packages from that lock. Other subcommands accept it - /// silently. + /// project's packages from that lock. Without it a gem is committed + /// for a rules_ruby hub as an archive that the hub builds, where + /// that is known to build; with it every gem is vendored by its + /// path. Other subcommands accept it silently. #[arg( help_heading = GLOBAL_OPTIONS, long = "allow-vendored-in-bazel", diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index f0a5b1c86..e44c159a7 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -4797,7 +4797,16 @@ fn print_vendor_closing( .iter() .filter(|f| flavor_install_command(f).is_some()) .all(|f| JVM_TOOLS.contains(&f.as_str())); - let reinstall = if jvm_only { + // A gem committed for a rules_ruby hub is installed by the Bazel + // build alone: Bundler by itself fails on its source, which the + // warning of the run says. + let advisory = socket_patch_core::vendor::gem::BAZEL_FILE_SOURCE; + let for_bazel = |e: &&PatchEvent| e.error_code.as_deref() == Some(advisory); + let for_bazel = env.events.iter().filter(for_bazel).count(); + let only_for_bazel = for_bazel > 0 && for_bazel == env.summary.applied as usize; + let reinstall = if only_for_bazel { + "Build with Bazel, which installs the committed gems".to_string() + } else if jvm_only { let cmds: Vec = installs.iter().map(|c| format!("`{c}`")).collect(); // The block of a hub is in a file of the checkout's own. let how = match installs == [HUB_BUILD] { @@ -4815,6 +4824,12 @@ fn print_vendor_closing( format!("Run {} to update the installed tree", cmds.join(" and ")) }; let mut extra = Vec::new(); + if for_bazel > 0 && !only_for_bazel { + extra.push( + "Build with Bazel as well: it alone installs the gems committed for its hub." + .to_string(), + ); + } if wired_flavors.contains("bun") && common.cwd.join("bun.lockb").exists() { extra.push( "For binary Bun workspaces, also commit the workspace members' \ diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs index adcae9388..b24a64133 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs @@ -34,16 +34,35 @@ //! without a Bazel hold the command to the same in the fixture's checkout, //! with what a person reads and the calls that stand against nothing. //! -//! Vendored mode would commit the unpacked patched gem under -//! `.socket/vendor/gem` and make `Gemfile` and `Gemfile.lock` name it by -//! its path from the project, and rules_ruby runs `bundle install` in a -//! repository of Bazel's that holds the two files and not the copy. So in -//! this checkout, where the hub reads both files, the command declines the -//! gem and writes nothing ([`vendored_bundle_fetch`]): the build stays the -//! unpatched one. With `--allow-vendored-in-bazel` it does what it did -//! before it declined, and the build fails until `vendor --revert` has put -//! the two files back. Hosted mode, which the refusal names, then patches -//! the build. +//! Outside a Bazel workspace vendored mode commits the unpacked patched gem +//! under `.socket/vendor/gem` and makes `Gemfile` and `Gemfile.lock` name +//! it by its path from the project. rules_ruby runs `bundle install` in a +//! repository of Bazel's that holds the two files and not the copy, so that +//! form fails the build of this checkout, where the hub reads both files. +//! +//! A vendored gem that this hub does build is one the lock names as hosted +//! mode names it, with the patch registry's URL replaced by a relative +//! `file:` URL of a directory of the checkout that holds the patched gem at +//! `gems/-.gem`. rules_ruby asks Bazel for that URL, Bazel +//! reads it from the root of the workspace, and Bundler holds the file to +//! the lock's `CHECKSUMS` line. [`file_source_by_hand`] writes those three +//! files by hand ([`by_hand`]) and builds them on a second machine that +//! reaches no patch host, and on a third one where one byte of the gem is +//! another. The hub runs the Bundler its lock names, so the flow does both +//! again with a lock that names Bundler 2.6.9 ([`OLDER_BUNDLER`]). +//! +//! [`vendored_bundle_fetch`] holds `scan --mode vendored` to writing those +//! files, byte for byte, where the checkout names the Bazel release it is +//! built with, and to declining the gem where it names none: Bazel 9.1.0 +//! fails on such a URL, and nothing in the checkout says that another +//! release builds it. The tests without a Bazel hold it to every other +//! condition under which it declines +//! ([`a_gem_is_declined_where_the_committed_gem_is_not_known_to_build`]): +//! a Bundler in the lock that no hub here was built with, a second call +//! that reads the pair and holds the gem to other bytes or to none, and +//! the rest. +//! With `--allow-vendored-in-bazel` the command writes the copy of every +//! other project, as it did. //! //! Both markers are read from what Bazel built, and each holds an id made //! for the run, so no cache of an earlier run can supply either gem. The @@ -84,6 +103,7 @@ //! that host (`SOCKET_PATCH_SERVER_URL`). use std::io::Write as _; +use std::path::PathBuf; use std::time::Instant; use base64::Engine as _; @@ -92,10 +112,10 @@ use sha2::{Digest, Sha256, Sha512}; use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; -use crate::envelope::{codes_in, event_for}; +use crate::envelope::{codes_in, event_for, events}; use crate::harness::{ cell_without_bazel, changed, fixture_path, rewrite, with_vex, Cell, Claim, Declined, Fixture, - How, Ran, StandIn, Tree, ALLOW, CONSUMER, NOTHING, VENDORED, + How, Ran, StandIn, Tree, ALLOW, CONSUMER, NOTHING, REPO_CACHE, VENDORED, }; use crate::hosted_memory_common::{read_tree, Patch, ORG}; @@ -358,13 +378,7 @@ impl Served { let record_route = format!("/v0/orgs/{ORG}/patches/view/{uuid}"); standin.serve(1, &record_route, record.to_string().as_bytes()); - let gems = |name: &str| rewrite(&format!("{RUBYGEMS}/gems/{name}-"), &origin); - cell.route_downloads(&[ - gems(NAME), - gems(NEIGHBOUR), - rewrite(&format!("{PATCH_HOST}/"), &origin), - format!("block {PATCH_HOST}"), - ]); + cell.route_downloads(&routes(&origin, true)); cell.write("Gemfile.lock", lock_pinning(&neighbour_gem, &upstream_gem)); Served { standin, @@ -382,6 +396,20 @@ impl Served { } } +/// The downloader config of a flow whose stand-in is at `origin`: the +/// fixture's two gems on rubygems.org go there, and so does everything on +/// the patch host where the machine reaches one (`patch_host`). A URL of the +/// patch host that no rule rewrote is refused, so on a machine that reaches +/// none a build that asks for it fails, and no download of Bazel's goes to +/// the real one. +fn routes(origin: &str, patch_host: bool) -> Vec { + let gems = |name: &str| rewrite(&format!("{RUBYGEMS}/gems/{name}-"), origin); + let mut rules = vec![gems(NAME), gems(NEIGHBOUR)]; + rules.extend(patch_host.then(|| rewrite(&format!("{PATCH_HOST}/"), origin))); + rules.push(format!("block {PATCH_HOST}")); + rules +} + /// `socket-patch ` in `cell`, with `standin` as the Socket API and as /// rubygems.org, and with the variables `env` as well. fn run(standin: &StandIn, cell: &Cell, args: &[&str], env: &[(&str, &str)]) -> Ran { @@ -723,48 +751,299 @@ fn hosted_bundle_fetch_gem_checksums() { ); } +/// Where the patched gem of the patch `uuid` is committed for a hub: the +/// directory of the patch under `.socket/vendor`, which the lock names as +/// the gem's source, and in it the path rules_ruby asks a source for. +fn committed_gem(uuid: &str) -> String { + format!(".socket/vendor/gem/{uuid}/gems/{NAME}-{VERSION}.gem") +} + +/// The fixture's checkout with the patched gem `patched` of the patch +/// `uuid` vendored for the hub, written by hand: the files that differ from +/// the fixture's, each whole, by its path from the checkout. `Gemfile` and +/// `Gemfile.lock` are what hosted mode writes with the patch registry's URL +/// replaced by `file:.socket/vendor/gem//`, and the gem is committed +/// where rules_ruby asks that source for it. +fn by_hand(uuid: &str, patched: &[u8]) -> Tree { + let source = format!("file:.socket/vendor/gem/{uuid}/"); + let gemfile = format!( + "source \"https://rubygems.org/\"\n\n\ + gem \"{NAME}\", \"{VERSION}\", source: \"{source}\"\n\ + gem \"{NEIGHBOUR}\", \"{VERSION}\"\n" + ); + let lock = format!( + "GEM\n remote: {source}\n specs:\n {NAME} ({VERSION})\n\n\ + GEM\n remote: https://rubygems.org/\n specs:\n {NEIGHBOUR} ({VERSION})\n\n\ + PLATFORMS\n ruby\n\n\ + DEPENDENCIES\n {NEIGHBOUR} (= {VERSION})\n {NAME} (= {VERSION})!\n\n\ + CHECKSUMS\n{}{}\n\ + BUNDLED WITH\n 4.0.15\n", + checksum(NEIGHBOUR, &sha256_hex(&neighbour())), + checksum(NAME, &sha256_hex(patched)), + ); + Tree::from([ + (committed_gem(uuid), patched.to_vec()), + ("Gemfile".to_string(), gemfile.into_bytes()), + ("Gemfile.lock".to_string(), lock.into_bytes()), + ]) +} + +/// Whether the repository cache of `cell`, which its twins share, holds a +/// download of `gem`: Bazel keeps a file there under its sha256. +fn cached(cell: &Cell, gem: &[u8]) -> bool { + let cache = match std::env::var_os(REPO_CACHE) { + Some(shared) => PathBuf::from(shared), + None => cell.path("../cache"), + }; + let files = cache.join("content_addressable/sha256"); + assert!(files.is_dir(), "no repository cache at {}", cache.display()); + files.join(sha256_hex(gem)).join("file").exists() +} + +/// A second machine with the files of `cell` that reaches no patch host: a +/// new output base, and a downloader config that sends nothing there. +fn without_patch_host(cell: &Cell, origin: &str) -> Cell { + let mut twin = cell.twin(); + twin.route_downloads(&routes(origin, false)); + twin +} + +/// The build of `cell`, where one byte of the committed gem is not the one +/// the lock pins (`patched`), fails on the lock's checksum: Bundler names +/// the sha256 of the lock and the one of the file. +fn fails_on_the_checksum(cell: &Cell, patched: &[u8], changed: &[u8]) { + let build = cell.bazel("build", &[CONSUMER]); + let stderr = squeezed(&build.stderr()); + let sums = [patched, changed].map(|gem| format!("sha256={}", sha256_hex(gem))); + assert!( + !build.ok() + && stderr.contains("mismatchedchecksums") + && sums.iter().all(|sum| stderr.contains(sum)), + "{}: the build did not fail on the checksum of the committed gem:\n{}", + cell.test, + build.dump() + ); +} + +/// A Bundler of the 2 line, which most locks name today, in the place of +/// the fixture's 4.0.15: rules_ruby installs the Bundler of the lock's +/// `BUNDLED WITH` in the hub, and the hub's `bundle install` is that one's. +const OLDER_BUNDLER: &str = "2.6.9"; + +/// Makes the lock of `cell` name Bundler `version`. +fn names_bundler(cell: &Cell, version: &str) { + let lock = String::from_utf8(cell.tree()["Gemfile.lock"].clone()).expect("a text file"); + let named = "\nBUNDLED WITH\n 4.0.15\n"; + assert!(lock.ends_with(named), "{}: {lock}", cell.test); + let other = format!("\nBUNDLED WITH\n {version}\n"); + cell.write("Gemfile.lock", lock.replace(named, &other)); +} + +/// `gem` with its last byte changed: one of the padding a tar ends with, so +/// the file is still a gem RubyGems reads, with another sha256. +fn one_byte_changed(gem: &[u8]) -> Vec { + let mut changed = gem.to_vec(); + *changed.last_mut().expect("a gem has bytes") ^= 1; + changed +} + +/// A vendored gem that the hub builds, written by hand. +/// +/// - (a) `bazel build` and `bazel run //:consumer` print the unpatched +/// marker. +/// - (b) By hand ([`by_hand`]): `Gemfile` gives the gem the source +/// `file:.socket/vendor/gem//`, `Gemfile.lock` resolves it from a +/// `GEM` section of that remote with the sha256 of the patched gem in +/// `CHECKSUMS`, and the patched gem is committed at +/// `.socket/vendor/gem//gems/-.gem`. No file of +/// Bazel's is touched. +/// - (c) On a second machine with those files (a new output base and, on +/// Bazel 9, a new contents cache), which reaches no patch host and whose +/// repository cache holds no copy of the patched gem, the same two Bazel +/// commands print the patched marker. Bazel changed no file, and a +/// `--lockfile_mode=error` build passes. The stand-in was asked for no +/// patched gem and for no further upstream one. +/// - (d) On a third machine, with one byte of the committed gem changed, +/// the build fails on the lock's checksum. +/// - (e) On a fourth machine, whose lock names Bundler 2.6.9, the hub holds +/// that Bundler and the same two Bazel commands print the patched marker; +/// on a fifth one, with the changed byte, the build fails on the lock's +/// checksum. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn file_source_by_hand() { + let test = "ruby::file_source_by_hand"; + let started = Instant::now(); + let Some(mut cell) = Cell::open(test, &FIXTURE) else { + return; + }; + let release = cell.release().to_string(); + let served = Served::to(&mut cell); + let (standin, uuid) = (&served.standin, served.uuid.as_str()); + let origin = standin.origin(); + + // (a) The unpatched build. + let before = cell.builds_unpatched(&served.unpatched); + let upstream_fetches = standin.asked(&served.upstream_route); + + // (b) The three files, by hand. + let files = by_hand(uuid, &served.patched_gem); + for (rel, bytes) in &files { + cell.write(rel, bytes); + } + let wired = cell.tree(); + let written: Vec = files.keys().cloned().collect(); + assert_eq!(changed(&before, &wired), written, "{test}"); + + // (c) A second machine: patched, from the committed gem and nothing + // else. + assert!(!cached(&cell, &served.patched_gem), "{test}"); + let second = without_patch_host(&cell, &origin); + second.builds_patched(&wired, &served.patched); + let patch_host = |path: &String| path.starts_with(&format!("/{PATCH_HOST}/")); + let asked: Vec = standin.requests().into_iter().filter(patch_host).collect(); + assert_eq!(asked, NOTHING, "{test}: the patch host was asked"); + assert_eq!( + standin.asked(&served.upstream_route), + upstream_fetches, + "{test}: the patched build fetched the upstream gem" + ); + + // (d) A third machine, where one byte of the committed gem is another. + let third = without_patch_host(&second, &origin); + let other = one_byte_changed(&served.patched_gem); + third.write(&committed_gem(uuid), &other); + fails_on_the_checksum(&third, &served.patched_gem, &other); + + // (e) The same two machines with the Bundler of most locks. + let fourth = without_patch_host(&third, &origin); + fourth.write(&committed_gem(uuid), &served.patched_gem); + names_bundler(&fourth, OLDER_BUNDLER); + fourth.builds_patched(&fourth.tree(), &served.patched); + let bundler = format!("@bundle//:bundler-{OLDER_BUNDLER}"); + let held = fourth.bazel("query", &[&bundler]); + assert!(held.ok(), "{test}: no {bundler}:\n{}", held.dump()); + let fifth = without_patch_host(&fourth, &origin); + fifth.write(&committed_gem(uuid), &other); + fails_on_the_checksum(&fifth, &served.patched_gem, &other); + assert_eq!( + standin.asked(&served.upstream_route), + upstream_fetches, + "{test}: the build went to the upstream gem" + ); + let asked: Vec = standin.requests().into_iter().filter(patch_host).collect(); + assert_eq!(asked, NOTHING, "{test}: the patch host was asked"); + + println!( + "{test}: Bazel {release} built {:?} on a second machine that reaches no patch host, \ + from {} and a `file:` source in Gemfile and Gemfile.lock written by hand; one changed \ + byte of that gem failed a third machine's build (Bundler: mismatched checksums); the \ + same with Bundler {OLDER_BUNDLER} in the lock and the hub, on a fourth and a fifth; {:?}", + served.patched, + committed_gem(uuid), + started.elapsed() + ); +} + /// The code under which vendored mode declines a gem whose Gemfile or lock /// a hub of the workspace reads, and what a refusal has to name in the -/// fixture's checkout: the hub's call with its line in `MODULE.bazel`, and -/// the file it reads. +/// fixture's checkout: the hub's call with its line in `MODULE.bazel`, the +/// file it reads, and why the committed gem is not known to build there. +/// The fixture names no Bazel release. const DECLINED: Declined = Declined { purl: PURL, code: "vendor_gem_bazel_hub", names: &[ "`ruby.bundle_fetch` (MODULE.bazel:15)", "names Gemfile.lock; ", + "the checkout names no Bazel release as three numbers (`.bazelversion`", ], }; +/// The advisory of a run that committed a gem for a hub. +const ADVISORY: &str = "vendor_gem_bazel_file_source"; +/// The warning of an undo that leaves a `gem_checksums` entry of the call +/// holding the gem to the patched one. +const ENTRY_LEFT: &str = "vendor_gem_bazel_checksum_left"; + /// The variables of a command of vendored mode, which downloads the /// patched gem from the patch host: the stand-in at `origin` is that host. fn patch_host(origin: &str) -> [(&str, &str); 1] { [("SOCKET_PATCH_SERVER_URL", origin)] } -/// Vendored mode beside a hub that reads the Gemfile and its lock. +/// For a finished `scan --mode vendored --yes` in the fixture's checkout +/// with the files `before`, where the hub reads the lock and the checkout +/// names its Bazel release: the command vendored the one gem and says what +/// that form costs. It wrote the three files of [`by_hand`], byte for +/// byte, and beside them only its own: the ledger, the marker of the +/// patch's directory, and the two files that keep git from ignoring or +/// converting the gem. Gives the files of the checkout. +fn committed_for_the_hub(cell: &Cell, scan: &Ran, served: &Served, before: &Tree) -> Tree { + let (test, said) = (&cell.test, &scan.dump); + assert_eq!(scan.code, 0, "{test}: {said}"); + assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{test}: {said}"); + let advised = |event: &&serde_json::Value| event["errorCode"] == ADVISORY; + let advisory = events(&scan.envelope).iter().find(advised); + let advisory = advisory.and_then(|event| event["reason"].as_str()); + let advisory = advisory.unwrap_or_default(); + let costs = [ + "through Bazel only", + "keeps that unpatched copy", + "`--mode hosted`", + "does not watch", + ]; + for cost in costs { + assert!(advisory.contains(cost), "{test}: no {cost:?} in {said}"); + } + let by_hand = by_hand(&served.uuid, &served.patched_gem); + let dir = format!(".socket/vendor/gem/{}", served.uuid); + let own = [".gitattributes", ".gitignore", "socket-patch.vendor.json"]; + let own = own.map(|file| format!("{dir}/{file}")); + let ledger = ".socket/vendor/state.json".to_string(); + let mut written: Vec = by_hand.keys().cloned().chain(own).chain([ledger]).collect(); + written.sort(); + let vendored = cell.tree(); + assert_eq!(changed(before, &vendored), written, "{test}: {said}"); + for (rel, bytes) in &by_hand { + let same = vendored[rel] == *bytes; + assert!(same, "{test}: {rel} is not the file written by hand"); + } + vendored +} + +/// Vendored mode beside a hub that reads the Gemfile and its lock, on a +/// machine whose Bazel reaches no patch host. /// /// - (a) `bazel build` and `bazel run //:consumer` print the unpatched /// marker. -/// - (b) `socket-patch scan --mode vendored --yes` declines the gem: it -/// exits 1, names the call of `MODULE.bazel` that reads the lock, hosted -/// mode and the switch, writes nothing and downloads no gem. The same -/// two Bazel commands print the unpatched marker, and change no file. -/// - (c) With `--allow-vendored-in-bazel` the command does what it did -/// before it declined: it passes and reports the gem vendored. It -/// commits the unpacked patched gem, with its specification and its -/// ledger, under `.socket/vendor`, and makes the declaration of -/// `Gemfile` and a `PATH` section of `Gemfile.lock` name that copy by -/// its path from the project. The same `bazel build` fails: rules_ruby -/// copies `Gemfile` and `Gemfile.lock` into a repository of Bazel's and -/// runs `bundle install` there, where the path names nothing. `vex` -/// attests the gem as patched all the same: it reads the committed -/// copy, and what rules_ruby builds from one is not judged. -/// - (d) `socket-patch vendor --revert`, which takes no switch: every file -/// of the checkout is the one of before, and the build prints the -/// unpatched marker again. -/// - (e) Hosted mode, which the refusal names: the same two Bazel commands -/// print the patched marker. +/// - (b) The checkout names no Bazel release, so `socket-patch scan --mode +/// vendored --yes` declines the gem: it exits 1, names the call of +/// `MODULE.bazel` that reads the lock, the missing release, hosted mode +/// and the switch, writes nothing and downloads no gem. The same two +/// Bazel commands print the unpatched marker, and change no file. With +/// `--allow-vendored-in-bazel` the command writes the unpacked copy named +/// by its path, as in every other project, and the same build fails in +/// `bundle install`, where the path names nothing: the failure the +/// decline is for. `vendor --revert` puts every file and the build back. +/// - (c) With the release of this Bazel in `.bazelversion`, the same +/// command vendors the gem: it writes the three files of +/// [`file_source_by_hand`], byte for byte, with its ledger, and says +/// what the form costs. +/// - (d) The same two Bazel commands, with no step in between, print the +/// patched marker. Bazel asked for no patched gem and no upstream one, +/// changed no file, and a `--lockfile_mode=error` build passes. +/// `vendor --check` passes. +/// - (e) On a second machine with those files, where one byte of the +/// committed gem is another, `vendor --check` fails on the sha256 of the +/// ledger and the build fails on the lock's checksum. +/// - (f) `socket-patch vendor --revert`: every file of the checkout is the +/// one of before, and the build prints the unpatched marker again. +/// - (g) Hosted mode, which the refusal names, on a machine that reaches +/// the patch host: the same two Bazel commands print the patched marker. +/// +/// The flow asserts the VEX document of its patch as `main.rs` says. #[test] #[ignore = "real Bazel; run with --ignored"] fn vendored_bundle_fetch() { @@ -777,82 +1056,109 @@ fn vendored_bundle_fetch() { let served = Served::to(&mut cell); let (standin, uuid) = (&served.standin, served.uuid.as_str()); let origin = standin.origin(); - let vendoring = |args: &[&str]| run(standin, &cell, args, &patch_host(&origin)); + cell.route_downloads(&routes(&origin, false)); + let run = |cell: &Cell, args: &[&str]| run(standin, cell, args, &patch_host(&origin)); // (a) The unpatched build. let before = cell.builds_unpatched(&served.unpatched); - // (b) The one command of vendored mode: declined, with nothing written - // and nothing of the patch fetched. The same build passes, on the - // upstream gem. - cell.declined(&vendoring(&VENDORED), &DECLINED, 1, "failed", &before); + // (b) No release is named: declined, with nothing written and nothing + // of the patch fetched. The same build passes, on the upstream gem. + cell.declined(&run(&cell, &VENDORED), &DECLINED, 1, "failed", &before); assert_eq!(standin.asked(&served.artifact_route), 0, "{test}"); cell.builds_patched(&before, &served.unpatched); - // (c) On the user's word: the copy, its ledger, and the two files that - // name it. - let scan = vendoring(&[&VENDORED[..], &[ALLOW]].concat()); - let said = &scan.dump; - assert_eq!(scan.code, 0, "{test}: {said}"); - assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); - assert_eq!(scan.envelope["summary"]["applied"], 1, "{test}: {said}"); - let vendored = cell.tree(); - let kept = format!(".socket/vendor/gem/{uuid}"); - let copy = format!("{kept}/{NAME}-{VERSION}"); - let mut written = vec![ - format!("{kept}/socket-patch.vendor.json"), - format!("{copy}/{LIB}"), - format!("{copy}/{NAME}.gemspec"), - ".socket/vendor/state.json".to_string(), - "Gemfile".to_string(), - "Gemfile.lock".to_string(), - ]; - written.sort(); - assert_eq!(changed(&before, &vendored), written, "{test}: {said}"); - let patched_source = source(&format!("PATCHED {uuid}")); - let lib = &vendored[&format!("{copy}/{LIB}")]; - assert_eq!(*lib, patched_source.as_bytes(), "{test}"); - let text = |rel: &str| String::from_utf8(vendored[rel].clone()).expect("a text file"); - let (gemfile, lock) = (text("Gemfile"), text("Gemfile.lock")); - let declaration = format!("gem \"{NAME}\", \"{VERSION}\", path: \"{copy}\""); - let declared = gemfile.lines().filter(|line| *line == declaration).count(); - assert_eq!(declared, 1, "{test}: Gemfile:\n{gemfile}"); - let section = format!("PATH\n remote: {copy}\n specs:\n {NAME} ({VERSION})\n\n"); - assert!(lock.starts_with(§ion), "{test}: Gemfile.lock:\n{lock}"); + // What the decline is for: on the user's word the command writes the + // copy of every other project, named by its path, and the same build + // fails where rules_ruby runs Bundler, in a repository of Bazel's that + // does not hold that path. Bundler breaks its message at the width of + // its console, so it is compared without white space. The undo, which + // takes no switch, puts every file and the build back. + { + let scan = run(&cell, &[&VENDORED[..], &[ALLOW]].concat()); + assert_eq!(scan.code, 0, "{test}: {}", scan.dump); + let copy = format!(".socket/vendor/gem/{uuid}/{NAME}-{VERSION}"); + let lock = String::from_utf8(cell.tree()["Gemfile.lock"].clone()).expect("a text file"); + let section = format!("PATH\n remote: {copy}\n specs:\n {NAME} ({VERSION})\n\n"); + assert!(lock.starts_with(§ion), "{test}: Gemfile.lock:\n{lock}"); + let build = cell.bazel("build", &[CONSUMER]); + let stderr = squeezed(&build.stderr()); + let missing = squeezed(&format!("{copy}` does not exist.")); + assert!( + !build.ok() && stderr.contains("Runningbundleinstall") && stderr.contains(&missing), + "{test}: the build did not fail on the path of the copy ({missing:?}):\n{}", + build.dump() + ); + let undo = run(&cell, &["vendor", "--revert", "--yes"]); + cell.undone(&undo, "removed", &before, &served.unpatched); + } + // The build after the undo fetched the upstream gem once more. + let upstream_fetches = standin.asked(&served.upstream_route); - // The same build fails where rules_ruby runs Bundler, on the path of - // the copy, and changes no file of the checkout. Bundler breaks the - // message at the width of its console, so it is compared without white - // space. - let build = cell.bazel("build", &[CONSUMER]); - let stderr = squeezed(&build.stderr()); - let missing = squeezed(&format!("{copy}` does not exist.")); - assert!( - !build.ok() && stderr.contains("Runningbundleinstall") && stderr.contains(&missing), - "{test}: the build did not fail on the path of the copy ({missing:?}):\n{}", - build.dump() + // (c) The release is named: the gem, its ledger, and the two files + // that name it. The document of that run and the one of `vex` say so, + // before the patched build. + cell.write(".bazelversion", format!("{release}\n")); + let before = cell.tree(); + let claim = Claim::new(PURL, uuid, How::Vendored); + let in_run = cell.document("in-run"); + let scan = run(&cell, &[&VENDORED[..], &with_vex(&in_run)].concat()); + let vendored = committed_for_the_hub(&cell, &scan, &served, &before); + cell.wrote_in_run(&scan, &in_run, &claim); + cell.stands_alone(run, &claim, true); + + // (d) The same build, no step in between: patched, from the committed + // gem. + cell.builds_patched(&vendored, &served.patched); + assert_eq!(standin.asked(&served.patched_route), 0, "{test}"); + assert_eq!( + standin.asked(&served.upstream_route), + upstream_fetches, + "{test}: the patched build fetched the upstream gem" ); - assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{test}"); - let socket_patch = |cell: &Cell, args: &[&str]| run(standin, cell, args, &[]); - cell.stands_alone(socket_patch, &Claim::new(PURL, uuid, How::Vendored), true); + cell.stands_alone(run, &claim, true); + cell.stands_alone(run, &claim, false); + cell.detects_product(run, None); + let check = run(&cell, &["vendor", "--check"]); + assert_eq!(check.code, 0, "{test}: {}", check.dump); + + // (e) A second machine, where one byte of the committed gem is another. + { + let second = cell.twin(); + let other = one_byte_changed(&served.patched_gem); + second.write(&committed_gem(uuid), &other); + let check = run(&second, &["vendor", "--check"]); + let caught = check.dump.contains("vendor_sha256_mismatch"); + assert!(check.code == 1 && caught, "{test}: {}", check.dump); + fails_on_the_checksum(&second, &served.patched_gem, &other); + } - // (d) The undo: every file is the one of before, and so is the build. - let undo = socket_patch(&cell, &["vendor", "--revert", "--yes"]); + // (f) The undo: every file is the one of before, and so is the build, + // and `vex` has no document for it. The same two documents where no + // Bazel has built. + let undo = run(&cell, &["vendor", "--revert", "--yes"]); cell.undone(&undo, "removed", &before, &served.unpatched); + cell.attests_nothing(run, 2, "manifest_not_found"); + cell.attests_unbuilt(run, &VENDORED, &before, &vendored, &claim); - // (e) The remedy the refusal names: hosted mode patches the build. - let scan = socket_patch(&cell, &["scan", "--mode", "hosted", "--yes"]); + // (g) The remedy the refusal names, where Bazel reaches the patch host: + // hosted mode patches the build. + cell.route_downloads(&routes(&origin, true)); + let scan = run(&cell, &["scan", "--mode", "hosted", "--yes"]); let pinned = cell.pinned_by(&scan, PURL, uuid, &before, &["Gemfile", "Gemfile.lock"]); cell.builds_patched(&pinned, &served.patched); println!( - "{test}: Bazel {release} built {:?}; `scan --mode vendored` declined ({}), wrote \ - nothing, and the build stayed the same; with {ALLOW} it wrote {copy} and pointed \ - Gemfile and Gemfile.lock at it, and the next build failed (Bundler: The path ... does \ - not exist) while `vex` attested the gem; `vendor --revert` restored all {} files and \ - the build; `scan --mode hosted` built {:?}; {:?}", + "{test}: Bazel {release} built {:?}; `scan --mode vendored` declined ({}) in a checkout \ + that names no Bazel release, and the build stayed the same; with the release named it \ + wrote {} and a `file:` source in Gemfile and Gemfile.lock, the files written by hand, \ + and the next build printed {:?} with no patch host; one changed byte failed `vendor \ + --check` and a second machine's build (Bundler: mismatched checksums); `vendor \ + --revert` restored all {} files and the build; `scan --mode hosted` built {:?}; {:?}", served.unpatched, DECLINED.code, + committed_gem(uuid), + served.patched, before.len(), served.patched, started.elapsed() @@ -892,10 +1198,11 @@ fn checkout() -> (Cell, Served) { } /// Without a Bazel: in the fixture's checkout, where the hub reads the -/// Gemfile and its lock, every command that would vendor the gem declines -/// it, writes nothing and fetches no gem. On the user's word vendored mode -/// goes on, and a later run without it passes and writes nothing: the lock -/// the hub reads already names the copy. +/// Gemfile and its lock and no file names a Bazel release, every command +/// that would vendor the gem declines it, writes nothing and fetches no +/// gem. On the user's word vendored mode goes on, with the copy of every +/// other project, and a later run without it passes and writes nothing: +/// the lock the hub reads already names the copy. #[test] fn every_command_that_would_vendor_declines_beside_a_hub_that_reads_the_lock() { let (cell, served) = checkout(); @@ -920,6 +1227,306 @@ fn every_command_that_would_vendor_declines_beside_a_hub_that_reads_the_lock() { cell.vendors_on_the_users_word(run, &DECLINED); } +/// Without a Bazel: in the fixture's checkout with its Bazel release named +/// in `.bazelversion`, vendored mode commits the gem for the hub. +/// +/// - A dry run names no refusal and writes nothing. +/// - The run writes the three files of [`by_hand`], byte for byte, and +/// says what the form costs. +/// - A later run passes and writes nothing, also a scan that names no mode +/// and one with the switch: the pair names the committed gem. +/// - A hosted scan leaves the pair alone and names the undo. +/// - `vendor --check` passes, and fails on one changed byte of the gem, +/// which `repair` puts right. +/// - `vendor --revert`, `rollback` and `remove` each put every file back, +/// byte for byte, and the gem is vendored the same again after each. +/// - Run as a person runs it, the command names the Bazel build as the +/// next step, and no reinstall: Bundler by itself fails on the source. +/// - With Bundler 2.6.9 in the lock the gem is vendored the same way. +/// - With the switch the run writes the copy of every other project. +/// - A vendored scan takes over a hosted pin of the gem, and writes the +/// same three files. +#[test] +fn a_gem_is_committed_for_the_hub_and_put_back() { + let (cell, served) = checkout(); + cell.write(".bazelversion", "9.3.2\n"); + let (standin, uuid) = (&served.standin, served.uuid.as_str()); + let origin = standin.origin(); + let go = |args: &[&str]| run(standin, &cell, args, &patch_host(&origin)); + let before = cell.tree(); + let same = |ran: &Ran, tree: &Tree| { + assert_eq!(ran.code, 0, "{}", ran.dump); + assert_eq!(changed(tree, &cell.tree()), NOTHING, "{}", ran.dump); + }; + + let dry = go(&[&VENDORED[..], &["--dry-run"]].concat()); + same(&dry, &before); + assert!(!dry.dump.contains(DECLINED.code), "{}", dry.dump); + let vendored = committed_for_the_hub(&cell, &go(&VENDORED), &served, &before); + for in_sync in [ + &VENDORED[..], + &["scan", "--yes"], + &[&VENDORED[..], &[ALLOW]].concat(), + ] { + let again = go(in_sync); + same(&again, &vendored); + assert_eq!(again.envelope["status"], "success", "{}", again.dump); + assert!(!again.dump.contains(DECLINED.code), "{}", again.dump); + } + + // Hosted mode leaves a gem vendored this way alone, and says how to + // hand it over. + let hosted = go(&["scan", "--mode", "hosted", "--yes"]); + same(&hosted, &vendored); + let handed_over = hosted.dump.contains("socket-patch's own vendored wiring"); + assert!(handed_over, "{}", hosted.dump); + + same(&go(&["vendor", "--check"]), &vendored); + cell.write(&committed_gem(uuid), one_byte_changed(&served.patched_gem)); + let check = go(&["vendor", "--check"]); + let caught = check.dump.contains("vendor_sha256_mismatch"); + assert!(check.code == 1 && caught, "{}", check.dump); + same(&go(&["repair"]), &vendored); + + for undo in [ + &["vendor", "--revert", "--yes"][..], + &["rollback", "--yes"], + &["remove", PURL, "--yes"], + ] { + same(&go(undo), &before); + committed_for_the_hub(&cell, &go(&VENDORED), &served, &before); + } + same(&go(&["vendor", "--revert", "--yes"]), &before); + + // As a person runs it: the next step is the build, and no reinstall. + let rubygems = format!("{origin}/{RUBYGEMS}"); + let env = [ + ("SOCKET_RUBYGEMS_URL", rubygems.as_str()), + patch_host(&origin)[0], + ]; + let [stdout, stderr] = cell.socket_patch_person(&origin, &VENDORED, &env); + let said = format!("--- stdout\n{stdout}\n--- stderr\n{stderr}"); + let step = + "2. Build with Bazel, which installs the committed gems, then run `socket-patch vex`"; + let stepped = squeezed(&stdout).contains(&squeezed(step)); + assert!(stepped && !stdout.contains("Reinstall"), "{said}"); + assert!( + stderr.contains("Warning: ") && stderr.contains("through Bazel only"), + "{said}" + ); + same(&go(&["vendor", "--revert", "--yes"]), &before); + + // The Bundler of most locks, which a hub was built with too. + names_bundler(&cell, OLDER_BUNDLER); + let older = cell.tree(); + let ran = go(&VENDORED); + assert_eq!(ran.envelope["summary"]["applied"], 1, "{}", ran.dump); + assert!(ran.dump.contains(ADVISORY), "{}", ran.dump); + same(&go(&["vendor", "--revert", "--yes"]), &older); + cell.write("Gemfile.lock", &before["Gemfile.lock"]); + + // On the user's word: the copy of every other project, named by its + // path. + let allowed = go(&[&VENDORED[..], &[ALLOW]].concat()); + assert_eq!( + allowed.envelope["summary"]["applied"], 1, + "{}", + allowed.dump + ); + let lock = String::from_utf8(cell.tree()["Gemfile.lock"].clone()).expect("a text file"); + let copy = format!("PATH\n remote: .socket/vendor/gem/{uuid}/{NAME}-{VERSION}\n"); + assert!(lock.starts_with(©), "{lock}"); + same(&go(&["vendor", "--revert", "--yes"]), &before); + + let hosted = go(&["scan", "--mode", "hosted", "--yes"]); + assert_eq!(hosted.envelope["summary"]["applied"], 1, "{}", hosted.dump); + let taken_over = go(&VENDORED); + assert_eq!(taken_over.code, 0, "{}", taken_over.dump); + let tree = cell.tree(); + for (rel, bytes) in by_hand(uuid, &served.patched_gem) { + assert!(tree[&rel] == bytes, "{rel}: {}", taken_over.dump); + } + same(&go(&["vendor", "--revert", "--yes"]), &before); +} + +/// Without a Bazel: each condition under which the committed gem is not +/// known to build declines the gem, with nothing written and no gem +/// fetched, and names the call, the lock and the condition. The lock's +/// `CHECKSUMS` line or the `gem_checksums` entry of every call that reads +/// the pair is what holds the committed gem to its bytes: an entry that +/// holds the gem to other bytes declines it once the patched gem is known, +/// naming the call, the entry and both sums, also where it is a second +/// call's. With the sum of the patched gem written there the gem is +/// vendored, also in a lock with no `CHECKSUMS` section, and each undo +/// then puts every file back and says that the entry it leaves in the call +/// fails the build. +#[test] +fn a_gem_is_declined_where_the_committed_gem_is_not_known_to_build() { + let scan = |cell: &Cell, served: &Served| { + let origin = served.standin.origin(); + run(&served.standin, cell, &VENDORED, &patch_host(&origin)) + }; + let text = + |cell: &Cell, rel: &str| String::from_utf8(cell.tree()[rel].clone()).expect("a text file"); + // The lock without its `CHECKSUMS` section. + let unchecked = |cell: &Cell| { + let lock = text(cell, "Gemfile.lock"); + let (head, sums) = lock.split_once("CHECKSUMS\n").expect("a CHECKSUMS section"); + let (_, tail) = sums.split_once("\n\n").expect("a section after it"); + cell.write("Gemfile.lock", format!("{head}{tail}")); + }; + // The call with `gem_checksums = `. + let pins = |cell: &Cell, sums: &str| { + let lock = " gemfile_lock = \"//:Gemfile.lock\",\n"; + let module = text(cell, "MODULE.bazel"); + assert!(module.contains(lock), "{module}"); + let pinned = format!("{lock} gem_checksums = {sums},\n"); + cell.write("MODULE.bazel", module.replace(lock, &pinned)); + }; + // A second call that reads the same pair, for a hub of its own, with + // the arguments `more`: the line of `MODULE.bazel` it is on. + let second = |cell: &Cell, more: &str| { + let module = text(cell, "MODULE.bazel"); + let call = format!( + "ruby.bundle_fetch(name = \"tools\", gemfile = \"//:Gemfile\", gemfile_lock = \ + \"//:Gemfile.lock\"{more})\n" + ); + cell.write("MODULE.bazel", format!("{module}{call}")); + module.lines().count() + 1 + }; + let entry = |sum: &str| format!("{{\"{NAME}-{VERSION}\": \"{sum}\"}}"); + let unheld = |line: usize| { + format!( + "has no CHECKSUMS section and `ruby.bundle_fetch` (MODULE.bazel:{line}) has no \ + `gem_checksums` entry for {NAME}-{VERSION}" + ) + }; + let (first_unheld, second_unheld) = (unheld(15), unheld(28)); + type Edit<'a> = &'a dyn Fn(&Cell); + let cases: [(Edit, &str); 10] = [ + ( + &|cell| cell.write(".bazelversion", "9.1.0\n"), + "Bazel 9.1.0 fails on such a URL", + ), + ( + &|cell| cell.write(".bazelversion", "10.0.0\n"), + "not known to build on Bazel 10.0.0", + ), + ( + &|cell| cell.write(".bazelversion", "latest\n"), + DECLINED.names[2], + ), + (&unchecked, &first_unheld), + ( + // The first call holds the gem, and the second one does not. + &|cell| { + unchecked(cell); + pins(cell, &entry(PLACEHOLDER)); + assert_eq!(second(cell, ""), 28); + }, + &second_unheld, + ), + ( + &|cell| names_bundler(cell, "2.5.23"), + "not known to build with Bundler 2.5.23, which Gemfile.lock names", + ), + ( + &|cell| names_bundler(cell, "5.0.0"), + "not known to build with Bundler 5.0.0, which Gemfile.lock names", + ), + ( + &|cell| pins(cell, "SUMS"), + "the `gem_checksums` of `ruby.bundle_fetch` (MODULE.bazel:15) are not written out", + ), + ( + &|cell| { + cell.write( + "WORKSPACE", + "local_repository(name = \"x\", path = \"x\")\n", + ) + }, + "a `WORKSPACE` file of the workspace defines repositories", + ), + ( + &|cell| cell.write(".bazelrc", "build --repository_disable_download\n"), + ".bazelrc:1 names `--repository_disable_download`, under which Bazel may not read the \ + committed gem", + ), + ]; + for (edit, why) in cases { + let (cell, served) = checkout(); + cell.write(".bazelversion", "9.3.2\n"); + edit(&cell); + let package = Declined { + names: &[DECLINED.names[0], DECLINED.names[1], why], + ..DECLINED + }; + let before = cell.tree(); + cell.declined(&scan(&cell, &served), &package, 1, "failed", &before); + assert_eq!(served.standin.asked(&served.artifact_route), 0, "{why}"); + } + + // An entry that holds the gem to the upstream bytes. + let (cell, served) = checkout(); + cell.write(".bazelversion", "9.3.2\n"); + let sums = [&served.upstream_gem, &served.patched_gem].map(|gem| sha256_hex(gem)); + let unpinned = text(&cell, "MODULE.bazel"); + pins(&cell, &entry(&sums[0])); + let before = cell.tree(); + let ran = scan(&cell, &served); + let said = squeezed(&ran.dump); + let named = [ + format!("hold {NAME}-{VERSION} to sha256 {}", sums[0]), + format!("the patched gem has {}", sums[1]), + DECLINED.code.to_string(), + ]; + let named = named.iter().all(|part| said.contains(&squeezed(part))); + assert!(ran.code == 1 && named, "{}", ran.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", ran.dump); + + // The sum of the patched gem there, and a second call that reads the + // pair and holds the gem to the upstream bytes: its hub would fail. + cell.write("MODULE.bazel", &unpinned); + pins(&cell, &entry(&sums[1])); + let pinned = text(&cell, "MODULE.bazel"); + let line = second(&cell, &format!(", gem_checksums = {}", entry(&sums[0]))); + let before = cell.tree(); + let ran = scan(&cell, &served); + let said = squeezed(&ran.dump); + let named = format!( + "`ruby.bundle_fetch` (MODULE.bazel:{line}) hold {NAME}-{VERSION} to sha256 {}", + sums[0] + ); + let named = said.contains(&squeezed(&named)) && said.contains(DECLINED.code); + assert!(ran.code == 1 && named, "{}", ran.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", ran.dump); + + // The one call, with the sum of the patched gem: vendored, with and + // without a `CHECKSUMS` section in the lock. Each undo puts every file + // back and names the entry it leaves in the call. + cell.write("MODULE.bazel", &pinned); + for (with_section, undo) in [ + (true, &["vendor", "--revert", "--yes"][..]), + (true, &["rollback", "--yes"]), + (false, &["remove", PURL, "--yes"]), + ] { + if !with_section { + unchecked(&cell); + } + let before = cell.tree(); + let ran = scan(&cell, &served); + assert_eq!(ran.envelope["summary"]["applied"], 1, "{}", ran.dump); + let pinned = text(&cell, "Gemfile.lock").contains(&checksum(NAME, &sums[1])); + assert_eq!(pinned, with_section, "{}", ran.dump); + let undo = run(&served.standin, &cell, undo, &[]); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", undo.dump); + let said = squeezed(&undo.dump); + let left = format!("`ruby.bundle_fetch` (MODULE.bazel:15) still hold {NAME}-{VERSION}"); + let left = said.contains(ENTRY_LEFT) && said.contains(&squeezed(&left)); + assert!(undo.code == 0 && left, "{}", undo.dump); + } +} + /// Without a Bazel: the refusal is the project's whose files a hub reads, /// and no other's. In a workspace whose hub reads the files of another /// project, and in no workspace at all, vendored mode vendors the gem as diff --git a/crates/socket-patch-core/src/bazel/built.rs b/crates/socket-patch-core/src/bazel/built.rs index 60cefae56..956806815 100644 --- a/crates/socket-patch-core/src/bazel/built.rs +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -13,10 +13,12 @@ //! points at a copy committed under `.socket/vendor`: 2.5.0-rc4 takes the //! path for the name of a project and fails the build of everything the //! hub serves (Bazel 9.3.2, 8.8.2 and 7.7.2). rules_js does build a -//! vendored tarball. rules_ruby 1.0.0-rc2 fails the build on a vendored -//! gem (same three releases) unless the call lists every file of the copy -//! among its `srcs`, which it copies beside the Gemfile: `srcs` is not -//! read here, so a vendored gem is not judged. +//! vendored tarball. rules_ruby 1.0.0-rc2 builds a gem that is committed +//! as its archive and named by a `file:` source +//! ([`crate::vendor::gem::bazel`]), and fails the build on one vendored by +//! its path (same three releases) unless the call lists every file of the +//! copy among its `srcs`, which it copies beside the Gemfile: `srcs` is +//! not read here, so a vendored gem is not judged. //! //! [`unbuilt`] names, for a patched package, the call that builds it from a //! file without its patch. It says so only when the files of the workspace @@ -79,7 +81,7 @@ use std::path::{Component, Path}; use aho_corasick::AhoCorasick; use super::starlark::{Call, File, Value}; -use super::workspace::{disk, Doubt, Extension, Repo, Workspace}; +use super::workspace::{disk, Doubt, Extension, Repo, Tag, Workspace}; use super::BazelRoot; use crate::formats::gem::locked_specs; use crate::formats::pnpm::grammar::documents; @@ -138,7 +140,8 @@ struct Hub { members: fn(&str) -> Vec, /// Whether a call of the tag may build a package from a line that /// points at a copy under `.socket/vendor`: rules_js does, and - /// rules_ruby does when the call lists the files of the copy. + /// rules_ruby does for a gem committed as its archive, or when the + /// call lists the files of the copy. builds_vendored: bool, } @@ -368,6 +371,25 @@ fn reads( doubt.or_else(|| hidden().or_else(unread).cloned()).map(Err) } +/// The calls of the hub of `ecosystem` in the module files of `workspace`, +/// each with the files of the main repository it names by a label that is +/// written out (their paths from the Bazel root), and what leaves open +/// whether these are all of them ([`Tags::doubts`]). No call of a +/// `WORKSPACE` file is among them. +/// +/// [`Tags::doubts`]: super::workspace::Tags::doubts +pub(crate) fn hub_calls<'w>( + workspace: &'w Workspace, + ecosystem: &str, +) -> (Vec<(Tag<'w>, Vec)>, Vec) { + let Some(hub) = HUBS.iter().find(|hub| hub.ecosystem == ecosystem) else { + return Default::default(); + }; + let tags = workspace.tags(&hub.extension, hub.tag); + let named = |tag: Tag<'w>| (tag, files(workspace, tag.call, hub.files, None)); + (tags.calls.into_iter().map(named).collect(), tags.doubts) +} + /// Whether the requirements file `start` (a path from the Bazel root) /// brings in a file for which `own` holds, through its `-r` includes and /// theirs, each read with `read`. An include that cannot be read brings in diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index 7df8fe1b8..830fc7930 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -8199,7 +8199,7 @@ fn gem_dependency_entry(lock: &str, line_no: usize) -> &str { /// and the lock resolves it from a `GEM` section naming that remote, with a /// source-pinned `DEPENDENCIES` entry. Bundler refuses any other pair under /// frozen / deployment mode, so a plan that fails this is never committed. -fn gem_pair_agrees( +pub(crate) fn gem_pair_agrees( manifest: &str, lock: &str, dep: &DepOverride, @@ -8386,12 +8386,14 @@ fn plan_gem_redirect( } // Bundler allows ONE source per gem: an option that already // picks one (`git:`, `path:`, another `source:`) cannot take - // the Socket source beside it. When the blocking `path:` is + // the Socket source beside it. When the blocking `path:` (or + // the `source:` of a gem committed for a Bazel hub) is // socket-patch's OWN vendored wiring, prescribe the eject path // instead of leaving the user to puzzle over their own Gemfile. if let Some(spelling) = decl.source_selecting() { let socket_vendored = decl.args.iter().any(|arg| { - matches!(&arg.kind, ArgKind::Option { key, .. } if key == "path") + let ours = |key: &str| key == "path" || key == "source"; + matches!(&arg.kind, ArgKind::Option { key, .. } if ours(key)) && gf[arg.start..arg.end].contains(".socket/vendor/") }); return Err(refuse( @@ -8832,6 +8834,27 @@ fn plan_gem_redirect( }) } +/// The pair edit of hosted mode for the gem `dep` with `source` in the place +/// of the patch registry's URL and `sha256` as the sum of the gem's archive: +/// `Gemfile` and `Gemfile.lock` as the edit leaves them, and its edits. +/// Vendored mode writes it for a gem whose lock a Bazel hub reads +/// ([`crate::vendor::gem::bazel`]), with a relative `file:` URL of the +/// checkout as `source`. +pub(crate) fn plan_gem_source( + gemfile: &str, + lock: &str, + dep: &DepOverride, + source: &str, + sha256: &str, +) -> Result<(String, String, Vec), RewriteWarning> { + let sums = [(dep.version.clone(), sha256.to_string())]; + let (files, names) = (BTreeMap::new(), ("Gemfile", "Gemfile.lock")); + let (gemfile, layout) = (Some(gemfile), lock_layout(lock)); + let layout = layout.as_ref(); + let plan = plan_gem_redirect(&files, dep, source, &sums, gemfile, lock, names, layout)?; + Ok((plan.gemfile, plan.lock, plan.staged.edits)) +} + /// The Bundler manifest and lock that the gem rewriter edits among `files`: /// `gems.rb` and `gems.locked` where the project has a `gems.rb`. pub(crate) fn gem_pair(files: &BTreeMap) -> (&'static str, &'static str) { diff --git a/crates/socket-patch-core/src/vendor/bazel_hub.rs b/crates/socket-patch-core/src/vendor/bazel_hub.rs index cde62bcc7..0a7b8a850 100644 --- a/crates/socket-patch-core/src/vendor/bazel_hub.rs +++ b/crates/socket-patch-core/src/vendor/bazel_hub.rs @@ -1,5 +1,6 @@ //! PyPI and RubyGems vendored mode for a project whose lock a Bazel hub -//! reads: declined unless the user allows it. +//! reads: declined unless the user allows it, or the package is a gem that +//! can be committed for the hub as its archive ([`super::gem::bazel`]). //! //! rules_python's `pip.parse` and rules_ruby's `ruby.bundle_fetch` build //! the packages of a lock in repositories of Bazel's own. Vendored mode @@ -42,6 +43,8 @@ use crate::crawlers::Ecosystem; use crate::utils::env_compat::env_flag; use crate::utils::fs::run_blocking; use crate::utils::pnpm_workspace::without_verbatim_prefix; +use crate::utils::purl::parse_gem_purl; +use crate::vendor::gem::bazel as gem_hub; use crate::vendor::path::vendor_uuid_dir_rel; use crate::vendor::refusals::ALLOW_IN_BAZEL_ENV; @@ -65,9 +68,11 @@ pub async fn refusals<'a>( } /// What stands between vendored mode and a list of files of a project -/// ([`standing`]): the words of the refusal, and the text of the lock the -/// hub reads where a call names one. `None` where nothing does. -type Standing = Option<(String, Option)>; +/// ([`standing`]): what was read of the workspace, the text of the lock the +/// hub reads where a call names one, and for a call that names a gem's +/// files whether a gem can be committed for it as its archive +/// ([`gem_hub::gate`]). `None` where nothing stands in the way. +type Standing = Option<(String, Option, Option>)>; /// What rules_ruby builds of a hosted pin: the `sha256` of a gem that the /// call lists holds the build to the registry's gem. @@ -116,12 +121,12 @@ async fn refusals_unless<'a>( let at = match asked.iter().position(|(of, _)| *of == list) { Some(at) => at, None => { - let stands = standing(&root, purls, ruleset, hosted, list.1.clone()).await; + let stands = standing(&root, purls, ruleset, list.1.clone()).await; asked.push((list, stands)); asked.len() - 1 } }; - let Some((detail, lock)) = &asked[at].1 else { + let Some((reads, lock, gem)) = &asked[at].1 else { continue; }; // A lock names the copy of a patch by the copy's directory, outside @@ -163,28 +168,50 @@ async fn refusals_unless<'a>( wired = names(&text) || !holds(&text); } } - if !wired { - refused.push((*purl, code, detail.clone())); + if wired { + continue; } + // A gem is committed as its archive where the hub is known to + // build that: only where it is not is the gem declined. + let committed = gem.as_ref().map(|hub| { + let (name, version) = parse_gem_purl(purl).unwrap_or_default(); + let hub = hub.as_ref().map_err(String::clone)?; + hub.declines(&name, &version).map_or(Ok(()), Err) + }); + let fails = match committed { + Some(Ok(())) => continue, + Some(Err(why)) => format!( + "vendored mode commits the patched gem for such a call and names it by a \ + relative `file:` URL, which is not known to build here: {why}" + ), + None => format!( + "vendored mode makes the lock name the patched copy by a path under \ + .socket/vendor, and {ruleset} fails the build on such a lock" + ), + }; + let detail = format!( + "{reads}; {fails}; use `--mode hosted`, which names the patched package by a URL \ + that {ruleset} fetches{hosted}, or pass `--allow-vendored-in-bazel` if no build \ + takes the packages of this project from {ruleset}" + ); + refused.push((*purl, code, detail)); } refused } /// The [`Standing`] of the files `locks` of the project of `root`, for the -/// packages of `ruleset` (purls of the type `purls`), whose hosted pin is -/// built `hosted`. +/// packages of `ruleset` (purls of the type `purls`). async fn standing( root: &BazelRoot, purls: &'static str, ruleset: &str, - hosted: &str, locks: Vec, ) -> Standing { // The root is canonical: on Windows that spelling has a prefix no user // types and no tool prints. let at = without_verbatim_prefix(root.dir.clone()); let at = at.display(); - let (reads, lock) = match reader(root, purls, locks).await? { + let (reads, lock, gem) = match reader(root, purls, locks).await? { Ok(Unbuilt { call, file, @@ -196,7 +223,12 @@ async fn standing( // Read as a lock of the workspace is: within its bound, and // not through a link that leads out of the Bazel root. let dir = root.dir.clone(); - (reads, run_blocking(move || lock_text(&dir, &lock)).await) + let lock = run_blocking(move || lock_text(&dir, &lock)).await; + let gem = match purls { + "gem" => Some(gem_hub::gate(root).await), + _ => None, + }; + (reads, lock, gem) } Err(Doubt { file, line, why }) => { let line = match line { @@ -207,17 +239,10 @@ async fn standing( "the files of the Bazel workspace at {at} cannot be read with certainty, so a \ call of {ruleset} may name a lock of this project ({file}{line}: {why})" ); - (reads, None) + (reads, None, None) } }; - let detail = format!( - "{reads}; vendored mode makes the lock name the patched copy by a path under \ - .socket/vendor, and {ruleset} fails the build on such a lock; use `--mode hosted`, \ - which names the patched package by a URL that {ruleset} fetches{hosted}, or pass \ - `--allow-vendored-in-bazel` if no build takes the packages of this project from \ - {ruleset}" - ); - Some((detail, lock)) + Some((reads, lock, gem)) } #[cfg(test)] @@ -292,7 +317,7 @@ ruby.bundle_fetch(name = "bundle", gemfile = "//api:Gemfile", gemfile_lock = "// [ "`ruby.bundle_fetch` (MODULE.bazel:4)", "names api/Gemfile.lock; ", - "and rules_ruby fails the build", + "which is not known to build here: the project is not the root", ], ), ] { diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 0151109a7..3e3e2ddc7 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -138,6 +138,12 @@ use crate::formats::gem::{ is_plain_gem_token, listed_specs, split_checksum_entry, split_entry, GemfileLock, }; +pub(crate) mod bazel; + +/// The code of the advisory a run gives for a gem it vendored for a Bazel +/// hub, whose build alone installs it. +pub const BAZEL_FILE_SOURCE: &str = bazel::ADVISORY; + pub(super) const GEMFILE: &str = "Gemfile"; pub(super) const GEMFILE_LOCK: &str = "Gemfile.lock"; @@ -989,6 +995,9 @@ pub(crate) async fn service_preflight( let prelude = gem_prelude(purl, installed_path, project_root, record) .await .ok()?; + if let Some(planned) = bazel::preflight(purl, &prelude, project_root, record).await { + return planned; + } let asks = match prelude.lock_wired { true => !prelude.copy_ok, false => gem_edits(purl, &prelude).is_ok(), @@ -1025,6 +1034,19 @@ pub async fn vendor_gem<'a>( Ok(prelude) => prelude, Err(outcome) => return outcome, }; + // A gem whose lock a Bazel hub reads is committed as its archive. + let for_hub = bazel::vendor( + purl, + &prelude, + project_root, + record, + vendored_at, + dry_run, + service, + ); + if let Some(outcome) = for_hub.await { + return outcome; + } let GemPrelude { name, version, @@ -1428,17 +1450,13 @@ fn gem_entry( /// eval-able Ruby form a bundler path source loads. pub(crate) const GEM_STUB_ARTIFACT_KIND: &str = "gem-stub-gemspec"; -/// Download and verify the `.gem` and its stub gemspec, then atomically -/// replace the copy. Missing, invalid, or native-extension stubs are refused. -pub(super) async fn gem_service_copy( +/// Download and verify the `.gem` and its stub gemspec. Missing, invalid, or +/// native-extension stubs are refused. +async fn gem_service_archive( service: Option<&VendorServiceConfig>, record: &PatchRecord, name: &str, - copy_dir: &Path, - uuid_dir: &Path, - unwind_uuid_dir: bool, - warnings: &mut Vec, -) -> Result<(), Box> { +) -> Result<(super::service_fetch::VerifiedArchive, Vec), Box> { let cfg = service .filter(|cfg| cfg.service_enabled()) .ok_or_else(|| Box::new(super::service_fetch::required()))?; @@ -1446,7 +1464,7 @@ pub(super) async fn gem_service_copy( let fetched = fetch_verified_archive(cfg, &record.uuid).await; let subject = format!(".gem for {name}"); let policy = ServicePolicy::Refused; - let mut archive = policy.settle(fetched, ".gem", &subject)?; + let archive = policy.settle(fetched, ".gem", &subject)?; // Step 2: the stub gemspec the converter generated alongside the `.gem`. let stub = match fetch_verified_secondary(cfg, &archive, GEM_STUB_ARTIFACT_KIND).await { @@ -1472,6 +1490,22 @@ pub(super) async fn gem_service_copy( } }; refuse_unusable_stub(policy, name, name, &String::from_utf8_lossy(&stub))?; + Ok((archive, stub)) +} + +/// [`gem_service_archive`], then atomically replace the copy with the +/// unpacked gem and its stub gemspec. +pub(super) async fn gem_service_copy( + service: Option<&VendorServiceConfig>, + record: &PatchRecord, + name: &str, + copy_dir: &Path, + uuid_dir: &Path, + unwind_uuid_dir: bool, + warnings: &mut Vec, +) -> Result<(), Box> { + let (mut archive, stub) = gem_service_archive(service, record, name).await?; + let policy = ServicePolicy::Refused; // 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 — @@ -2100,6 +2134,11 @@ pub async fn revert_gem_opts( )); } + // A gem committed as its archive, for a Bazel hub. + if bazel::is_archive(entry) { + return bazel::revert(entry, project_root, &uuid_dir_rel, opts).await; + } + // Wiring is restored in reverse application order: lock first, Gemfile // last (the mirror image of vendor's Gemfile-then-lock). Every record is // planned against in-memory text first and nothing is written unless @@ -7672,7 +7711,7 @@ mod tests { /// Build a `.gem` (uncompressed outer tar holding `data.tar.gz` + /// `metadata.gz`). `data_files` are the inner data.tar.gz entries at the /// root (no prefix dir), as a real `.gem` carries them. - fn make_gem(data_files: &[(&str, &[u8])]) -> Vec { + pub(super) fn make_gem(data_files: &[(&str, &[u8])]) -> Vec { use std::io::Write as _; let mut data_tar = tar::Builder::new(Vec::new()); for (rel, content) in data_files { @@ -7715,16 +7754,27 @@ mod tests { gem_bytes: &[u8], gem_sha512: &str, stub: Option<(&[u8], &str)>, + ) { + mount_gem_granted_as(server, UUID, gem_bytes, gem_sha512, stub).await; + } + + /// [`mount_gem_granted`] for the patch `uuid`. + async fn mount_gem_granted_as( + server: &wiremock::MockServer, + uuid: &str, + gem_bytes: &[u8], + gem_sha512: &str, + stub: Option<(&[u8], &str)>, ) { use wiremock::matchers::{method, path}; use wiremock::{Mock, ResponseTemplate}; - let gem_path = format!("/patch/gem/rack/3.2.6/tok/{UUID}/rack-3.2.6.gem"); + let gem_path = format!("/patch/gem/rack/3.2.6/tok/{uuid}/rack-3.2.6.gem"); let gem_url = format!("{}{gem_path}", server.uri()); let mut artifacts = vec![serde_json::json!({ "kind": "tarball", "url": gem_url, "integrity": { "sha512": gem_sha512 } })]; - let stub_path = format!("/patch/gem/rack/3.2.6/tok/{UUID}/rack-3.2.6.gemspec"); + let stub_path = format!("/patch/gem/rack/3.2.6/tok/{uuid}/rack-3.2.6.gemspec"); if let Some((stub_bytes, stub_sha512)) = stub { let stub_url = format!("{}{stub_path}", server.uri()); artifacts.push(serde_json::json!({ @@ -7740,7 +7790,7 @@ mod tests { Mock::given(method("POST")) .and(path("/v0/orgs/acme/patches/package")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "results": { UUID: { + "results": { uuid: { "status": "granted", "url": gem_url, "purl": PURL, @@ -7833,6 +7883,177 @@ mod tests { .any(|w| w.code == "vendor_prebuilt_downloaded")); } + /// A gem whose `Gemfile` and lock a Bazel hub reads is committed as its + /// archive ([`bazel`]): the pair names it by a `file:` source, a later + /// run is in sync, a gem that went missing is written again and held + /// to the lock, a newer patch takes the source over, and the revert + /// puts the pair back. A `gem_checksums` entry for other bytes declines + /// the gem once its bytes are known, with nothing written. + #[tokio::test] + #[serial_test::serial] + async fn a_gem_of_a_lock_a_bazel_hub_reads_is_committed_as_its_archive() { + let _unset = crate::test_env::EnvGuard::unset(super::super::refusals::ALLOW_IN_BAZEL_ENV); + let sums = "CHECKSUMS\n puma (6.4.2) sha256=aa\n rack (3.2.6) sha256=bb\n\nBUNDLED WITH"; + // A Bundler that a hub was built with. + let lock = LOCK_DIRECT.replace("BUNDLED WITH", sums); + let lock = lock.replace(" 2.5.22\n", " 2.6.9\n"); + assert!(lock.ends_with("BUNDLED WITH\n 2.6.9\n"), "{lock}"); + let (_tmp, root, _installed, blobs, record) = fixture(GEMFILE_DIRECT, &lock).await; + let module = "ruby = use_extension(\"@rules_ruby//ruby:extensions.bzl\", \"ruby\")\n\ + ruby.bundle_fetch(name = \"b\", gemfile = \"//:Gemfile\", gemfile_lock = \ + \"//:Gemfile.lock\"SUMS)\n"; + let write = |file: &str, text: &str| std::fs::write(root.join(file), text).unwrap(); + let read = |file: &str| std::fs::read_to_string(root.join(file)).unwrap(); + write("MODULE.bazel", &module.replace("SUMS", "")); + write(".bazelversion", "8.8.2\n"); + let gem = make_gem(&[("lib/rack.rb", PATCHED)]); + let sum = crate::utils::digest::sha256_hex_of(&gem); + let server = wiremock::MockServer::start().await; + let stub = Some((SERVICE_STUB, sri_sha512(SERVICE_STUB))); + let stub = stub.as_ref().map(|(bytes, sri)| (*bytes, sri.as_str())); + mount_gem_granted(&server, &gem, &sri_sha512(&gem), stub).await; + let sources = PatchSources::blobs_only(&blobs); + let cfg = gem_service_cfg(&server.uri(), VendorSource::Service, false); + let run = |record: &PatchRecord, dry_run: bool, cfg: &VendorServiceConfig| { + let (record, cfg) = (record.clone(), cfg.clone()); + let (root, sources) = (root.clone(), sources.clone()); + async move { + let at = "2026-06-09T00:00:00Z"; + let install = missing_install(&root); + crate::vendor::test_support::vendor_gem( + PURL, + &install, + &root, + &record, + &sources, + at, + dry_run, + false, + Some(&cfg), + ) + .await + } + }; + let archive = + |uuid: &str| root.join(format!(".socket/vendor/gem/{uuid}/gems/rack-3.2.6.gem")); + let source = |uuid: &str| format!("file:.socket/vendor/gem/{uuid}/"); + + // An entry of the call for the upstream gem: declined, nothing + // written. A dry run says the same. + let pinned = format!( + ", gem_checksums = {{\"rack-3.2.6\": \"{}\"}}", + "c".repeat(64) + ); + write("MODULE.bazel", &module.replace("SUMS", &pinned)); + for dry_run in [true, false] { + let (code, detail) = unwrap_refused(run(&record, dry_run, &cfg).await); + assert_eq!(code, "vendor_gem_bazel_hub"); + assert!( + detail.contains(&sum) && detail.contains("rack-3.2.6"), + "{detail}" + ); + assert_eq!([read(GEMFILE), read(GEMFILE_LOCK)], [GEMFILE_DIRECT, &lock]); + assert!(!root.join(".socket").exists()); + } + write("MODULE.bazel", &module.replace("SUMS", "")); + + // A gem that does not hold the patched file is not committed. + let other = wiremock::MockServer::start().await; + let unpatched = make_gem(&[("lib/rack.rb", PRISTINE)]); + mount_gem_granted(&other, &unpatched, &sri_sha512(&unpatched), stub).await; + let unpatched = gem_service_cfg(&other.uri(), VendorSource::Service, false); + let (code, _) = unwrap_refused(run(&record, false, &unpatched).await); + assert_eq!(code, "vendor_prebuilt_required"); + assert!(!root.join(".socket").exists() && read(GEMFILE_LOCK) == lock); + + // A dry run writes nothing; the run commits the gem and names it. + let (result, entry, _) = unwrap_done(run(&record, true, &cfg).await); + assert!(result.success && entry.is_none() && !root.join(".socket").exists()); + let (result, entry, warnings) = unwrap_done(run(&record, false, &cfg).await); + let first = entry.expect("an entry"); + assert!(result.success, "{:?}", result.error); + assert_eq!(std::fs::read(archive(UUID)).unwrap(), gem); + let rel = format!(".socket/vendor/gem/{UUID}/gems/rack-3.2.6.gem"); + assert_eq!( + (first.artifact.path.as_str(), first.artifact.sha256.as_str()), + (rel.as_str(), sum.as_str()) + ); + let declared = format!("gem \"rack\", \"~> 3.1\", source: \"{}\"\n", source(UUID)); + assert!(read(GEMFILE).ends_with(&declared), "{}", read(GEMFILE)); + let section = format!( + "GEM\n remote: {}\n specs:\n rack (3.2.6)\n base64 (>= 0.1.0)\n\n", + source(UUID) + ); + let wired = read(GEMFILE_LOCK); + assert!(wired.starts_with(§ion), "{wired}"); + assert!(wired.contains(&format!(" rack (~> 3.1)!\n\nCHECKSUMS\n puma (6.4.2) sha256=aa\n rack (3.2.6) sha256={sum}\n")), "{wired}"); + assert!( + warnings.iter().any(|w| w.code == bazel::ADVISORY), + "{warnings:?}" + ); + assert!(root + .join(format!(".socket/vendor/gem/{UUID}/.gitignore")) + .exists()); + + // In sync: nothing to record, nothing to say. + let (result, entry, warnings) = unwrap_done(run(&record, false, &cfg).await); + assert!( + result.success && entry.is_none() && warnings.is_empty(), + "{warnings:?}" + ); + + // The gem is gone: written again, with the pair as it is. One the + // lock does not pin is not written. + std::fs::remove_file(archive(UUID)).unwrap(); + let (_, entry, warnings) = unwrap_done(run(&record, false, &cfg).await); + assert!(entry.is_some_and(|entry| entry.wiring.is_empty())); + assert!( + warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt"), + "{warnings:?}" + ); + assert_eq!(std::fs::read(archive(UUID)).unwrap(), gem); + assert_eq!(read(GEMFILE_LOCK), wired); + std::fs::remove_file(archive(UUID)).unwrap(); + write(GEMFILE_LOCK, &wired.replace(&sum, &"d".repeat(64))); + let (code, detail) = unwrap_refused(run(&record, false, &cfg).await); + assert_eq!(code, "vendor_gem_bazel_hub"); + assert!( + detail.contains("Gemfile.lock holds rack 3.2.6 to sha256"), + "{detail}" + ); + assert!(!archive(UUID).exists()); + write(GEMFILE_LOCK, &wired); + unwrap_done(run(&record, false, &cfg).await); + + // A newer patch of the gem takes the source over, and its entry, + // with what the caller carries forward, reverts to the first pair. + let newer_gem = make_gem(&[("lib/rack.rb", PATCHED), ("lib/more.rb", b"more\n")]); + let newer = PatchRecord { + uuid: UUID2.to_string(), + ..record.clone() + }; + let second = wiremock::MockServer::start().await; + mount_gem_granted_as(&second, UUID2, &newer_gem, &sri_sha512(&newer_gem), stub).await; + let cfg2 = gem_service_cfg(&second.uri(), VendorSource::Service, false); + let (result, entry, _) = unwrap_done(run(&newer, false, &cfg2).await); + assert!(result.success, "{:?}", result.error); + let mut entry = entry.expect("an entry"); + assert_eq!(std::fs::read(archive(UUID2)).unwrap(), newer_gem); + let pair = read(GEMFILE) + &read(GEMFILE_LOCK); + assert!( + pair.contains(&source(UUID2)) && !pair.contains(&source(UUID)), + "{pair}" + ); + crate::vendor::state::carry_forward_wiring(&first, &mut entry); + let outcome = revert_gem(&entry, &root, false).await; + assert!( + outcome.success && outcome.warnings.is_empty(), + "{outcome:?}" + ); + assert_eq!([read(GEMFILE), read(GEMFILE_LOCK)], [GEMFILE_DIRECT, &lock]); + assert!(!archive(UUID2).exists()); + } + /// `service` mode + a `.gem` integrity mismatch hard-fails; nothing wired. #[tokio::test] async fn service_gem_integrity_mismatch_hard_fails() { diff --git a/crates/socket-patch-core/src/vendor/gem/bazel.rs b/crates/socket-patch-core/src/vendor/gem/bazel.rs new file mode 100644 index 000000000..eac33508e --- /dev/null +++ b/crates/socket-patch-core/src/vendor/gem/bazel.rs @@ -0,0 +1,1514 @@ +//! RubyGems vendored mode for a gem whose `Gemfile` and lock a Bazel hub +//! reads. +//! +//! rules_ruby's `ruby.bundle_fetch` copies the two files into a repository +//! of Bazel's, has Bazel download `gems/-.gem` for +//! every gem of a `GEM` section, and runs `bundle install --local` there. +//! The unpacked copy that vendored mode commits everywhere else +//! ([`super`]: named by a `path:`) is not in that repository, and the build +//! fails on it. What the hub does build is the pair hosted mode writes, +//! with a relative `file:` URL of the checkout in the place of the patch +//! registry's, and the patched gem committed where the ruleset asks that +//! source for it: +//! +//! ```text +//! gem "", …, source: "file:.socket/vendor/gem//" # Gemfile +//! +//! GEM # Gemfile.lock +//! remote: file:.socket/vendor/gem// +//! specs: +//! () +//! DEPENDENCIES +//! (…)! +//! CHECKSUMS +//! () sha256= +//! +//! .socket/vendor/gem//gems/-.gem # the patched gem +//! ``` +//! +//! Bazel's server runs in the root of the workspace and opens the URL from +//! there, and Bundler holds the file to the lock's `CHECKSUMS` line. Built +//! on Bazel 9.3.2, 8.8.2 and 7.7.2 with rules_ruby 1.0.0-rc2 on a machine +//! that reaches no patch host; one changed byte of the gem fails the build +//! of a machine that fetches the hub anew (`ruby::` in the CLI's +//! `e2e_bazel_build`). No file of Bazel's is written. +//! +//! The pair is the hosted planner's own ([`plan_gem_source`]), and its undo +//! is that edit in reverse ([`revert`]). It is written only where [`gate`] +//! shows that it builds, and never on the user's word +//! ([`ALLOW_IN_BAZEL_ENV`]), which asks for the copy of every other +//! project. Anywhere else the gem is declined +//! ([`crate::vendor::bazel_hub`]). +//! +//! What the form costs, which the run says ([`ADVISORY`]): Bundler by +//! itself does not install from such a source (`bundle install` on a +//! machine without the gem and `bundle lock --update` fail, and on a +//! machine that installed the gem before the patch it passes and keeps +//! that unpatched copy), so the checkout builds its gems through Bazel +//! only; and Bazel does not watch the gem, so an output base that fetched +//! the hub before keeps what it fetched. + +use std::path::Path; + +use serde_json::{json, Value}; + +use super::{ + checksum_entry, dep_entry_name, gem_edits, gem_service_archive, is_one_line, + restore_uuid_metadata, GemPrelude, RevertFiles, GEMFILE, GEMFILE_LOCK, GEM_STUB_ARTIFACT_KIND, +}; +use crate::api::client::PlannedDownload; +use crate::bazel::built::{hub_calls, lock_text, reader}; +use crate::bazel::rc::{declared_release, mentions, Release}; +use crate::bazel::starlark::Value as Starlark; +use crate::bazel::workspace::{disk, Doubt, Tag, Workspace}; +use crate::bazel::BazelRoot; +use crate::formats::gem::declarations; +use crate::formats::gem::hosted::bundled_with_version; +use crate::formats::gem::{parse, parse_spec}; +use crate::manifest::schema::{PatchFileInfo, PatchRecord}; +use crate::patch::copy_tree::remove_tree; +use crate::patch::redirect::{gem_pair_agrees, plan_gem_source, DepOverride, FileEdit}; +use crate::utils::digest::sha256_hex_of; +use crate::utils::env_compat::env_flag; +use crate::utils::fs::{ + atomic_write_artifact, atomic_write_bytes_preserving_mode, read_regular_to_bytes, run_blocking, +}; +use crate::utils::purl::{build_gem_purl, parse_gem_purl}; +use crate::vendor::bazel_hub::GEM_CODE; +use crate::vendor::common::{ + already_patched_result, copy_matches_after_hashes, done, failed_result, preview_result, + prune_empty_vendor_levels, refused, service_offline_conflict, +}; +use crate::vendor::npm_dir::ignored_root_refusal; +use crate::vendor::path::vendor_uuid_dir_rel; +use crate::vendor::refusals::ALLOW_IN_BAZEL_ENV; +use crate::vendor::registry_fetch::{extract_gem_data, extract_on_blocking_pool}; +use crate::vendor::revert::{self, KeepPolicy}; +use crate::vendor::service_fetch::ServicePolicy; +use crate::vendor::state::{ + write_marker_or_warn, VendorArtifact, VendorEntry, VendorMarker, WiringAction, WiringRecord, +}; +use crate::vendor::{RevertOpts, RevertOutcome, VendorOutcome, VendorServiceConfig, VendorWarning}; + +/// The advisory of a run that vendored a gem this way: what the form costs +/// (see the module docs). +pub(crate) const ADVISORY: &str = "vendor_gem_bazel_file_source"; + +/// The warning of an undo ([`revert`]) after which a `gem_checksums` entry +/// still holds the gem to the patched one's sha256: the entry is the +/// user's own edit, which the run asked for and no undo takes back, and +/// Bazel fails the download of the upstream gem on it. +const ENTRY_LEFT: &str = "vendor_gem_bazel_checksum_left"; + +/// The wiring records of an entry: the source `Gemfile` gives the gem, and +/// what `Gemfile.lock` held before it followed (`original`: the `remote` of +/// the section the gem came from, its `dependency` entry and its `checksum` +/// line, each as the lock spelled it, the last two only where it had one). +pub(crate) const GEMFILE_KIND: &str = "gemfile_file_source"; +pub(crate) const LOCK_KIND: &str = "gemfile_lock_file_source"; + +/// The calls of the hub that read the `Gemfile` and the lock of a project +/// for which a gem committed as its archive is known to build ([`gate`]). +pub(crate) struct Hub { + /// The lock, as Bazel reads it. + lock: String, + /// Those calls, each as a message names it ([`named`]). Every one of + /// them fetches the gem for a hub of its own. + calls: Vec, + /// What the `gem_checksums` of those calls hold a gem to: its + /// `-`, the sha256, and the call, by its place among + /// them. + pins: Vec<(String, String, usize)>, +} + +/// A call of the hub, as a message names it. +fn named(tag: &Tag<'_>) -> String { + format!("`ruby.bundle_fetch` ({}:{})", tag.file, tag.call.line) +} + +/// Whether a gem of the project at the Bazel root `root`, whose `Gemfile` +/// or lock a call of the hub names, can be committed as its archive: the +/// calls that read the two files, or why that is not known to build here. +/// Read from the files of the checkout alone: +/// +/// - The workspace is read with certainty, and no `WORKSPACE` file defines +/// a repository: every call that reads the two files is among the ones +/// seen. +/// - The project is the root of the workspace, where Bazel opens the URL +/// from. +/// - Each call of the hub writes out the files it reads, and one that reads +/// the `Gemfile` or the lock of the project reads both, with +/// `gem_checksums` that are written out. +/// - The checkout names a Bazel release whose downloader opens such a URL +/// ([`opens_file_urls`]), and no rc file of it takes the download from +/// that downloader ([`reads_the_checkout`]). +/// - The lock names a Bundler that the hub is known to build such a source +/// with ([`bundler_builds`]). +pub(crate) async fn gate(root: &BazelRoot) -> Result { + let (dir, project) = (root.dir.clone(), root.project.clone()); + run_blocking(move || read(&dir, &project)).await +} + +fn read(dir: &Path, project: &Path) -> Result { + let view = disk(dir); + let workspace = Workspace::read(&view); + let (calls, doubts) = hub_calls(&workspace, "gem"); + if let Some(doubt) = workspace.doubts.first().or(doubts.first()) { + return Err(uncertain(doubt)); + } + if workspace.legacy.is_some() { + return Err( + "a `WORKSPACE` file of the workspace defines repositories, which are not read".into(), + ); + } + if !project.as_os_str().is_empty() { + return Err( + "the project is not the root of the Bazel workspace, where Bazel opens such a URL \ + from" + .into(), + ); + } + let (mut reading, mut pins) = (Vec::new(), Vec::new()); + for (tag, files) in &calls { + let call = named(tag); + let plain = |name| matches!(tag.call.arg(name), None | Some(Starlark::Str(_))); + if tag.call.unpacks() || !plain("gemfile") || !plain("gemfile_lock") { + return Err(format!("{call} does not write out the files it reads")); + } + let reads = |file| files.iter().any(|path| path == file); + match (reads(GEMFILE), reads(GEMFILE_LOCK)) { + (false, false) => continue, + (true, true) => {} + _ => { + return Err(format!( + "{call} reads one of Gemfile and Gemfile.lock alone" + )) + } + } + let unwritten = || format!("the `gem_checksums` of {call} are not written out"); + match tag.call.arg("gem_checksums") { + None => {} + Some(Starlark::Dict(sums)) => { + for (gem, sum) in sums { + let Starlark::Str(sum) = sum else { + return Err(unwritten()); + }; + pins.push((gem.clone(), sum.clone(), reading.len())); + } + } + Some(_) => return Err(unwritten()), + } + reading.push(call); + } + if reading.is_empty() { + return Err("no `ruby.bundle_fetch` call is seen to read Gemfile and Gemfile.lock".into()); + } + opens_file_urls(declared_release(&view))?; + reads_the_checkout(mentions(&view, &KEEPS_BAZEL_OFF))?; + let unread = || "Gemfile.lock cannot be read".to_string(); + let lock = lock_text(dir, GEMFILE_LOCK).ok_or_else(unread)?; + bundler_builds(&lock)?; + let calls = reading; + Ok(Hub { lock, calls, pins }) +} + +/// Whether the hub is known to build a gem of such a source with the +/// Bundler the lock names (`BUNDLED WITH`), which rules_ruby installs in +/// the hub and runs there. Built with 2.6.9 and 4.0.15, which also hold +/// the gem to the lock's `CHECKSUMS` line; the later releases of the 2 +/// line and the ones of the 4 line are taken to do the same. Every such +/// lock has one `GEM` section per source, which the pair is written for. +fn bundler_builds(lock: &str) -> Result<(), String> { + match bundled_with_version(lock) { + Some(((2, 6..) | (4, _), _)) => Ok(()), + Some((_, version)) => Err(format!( + "it is not known to build with Bundler {version}, which Gemfile.lock names \ + (`BUNDLED WITH`) and the hub runs (it does with 2.6.9 and 4.0.15)" + )), + None => Err( + "Gemfile.lock names no Bundler (`BUNDLED WITH`) for the hub to run, and not every \ + Bundler is known to build such a source" + .into(), + ), + } +} + +/// The options of an rc file under which Bazel may not read the committed +/// gem: a remote downloader is handed the URL in the place of Bazel's own +/// (read in Bazel's source: 9.3.2 keeps a `file:` URL to itself, 7.7.2 does +/// not), a build that may not download fetches nothing, and a hub pinned in +/// a vendor directory keeps the gems it has. None was built. +const KEEPS_BAZEL_OFF: [&str; 3] = [ + "experimental_remote_downloader", + "repository_disable_download", + "vendor_dir", +]; + +/// Whether the rc files of the checkout leave the download of the gem to +/// Bazel's own downloader, by what [`mentions`] found of +/// [`KEEPS_BAZEL_OFF`] in them. An option that is named counts however it +/// is set, and so does an rc file that cannot be read. +fn reads_the_checkout(found: Result, String>) -> Result<(), String> { + match found.map(|found| found.into_iter().next()) { + Ok(None) => Ok(()), + Ok(Some((file, line, word))) => Err(format!( + "{file}:{line} names `{word}`, under which Bazel may not read the committed gem" + )), + Err(file) => Err(format!( + "the rc file {file} cannot be read, and may keep Bazel from reading the committed gem" + )), + } +} + +/// What a doubt of the reader of the workspace's files says of them. +fn uncertain(Doubt { file, line, why }: &Doubt) -> String { + let line = match line { + 0 => String::new(), + line => format!(":{line}"), + }; + format!("the files of the Bazel workspace are not read with certainty ({file}{line}: {why})") +} + +/// Whether the downloader of the Bazel `release` a checkout names opens a +/// relative `file:` URL from the root of the workspace. Built on 7.7.2, +/// 8.8.2 and 9.3.2, and the other releases of those three lines are taken +/// to do the same but for 9.1.0: Bazel's own history says that +/// `repository_ctx.download` fails on such a URL there, and that 9.1.1 and +/// 9.2.0 fixed it. A checkout that names no release, or one that is not +/// three numbers (`latest`, a release candidate), may be built by that one, +/// and by any release to come. +fn opens_file_urls(release: Option) -> Result<(), String> { + match release { + None => Err( + "the checkout names no Bazel release as three numbers (`.bazelversion`, or \ + `USE_BAZEL_VERSION` in `.bazeliskrc`), and not every release opens such a URL" + .into(), + ), + Some((9, 1, 0)) => Err("Bazel 9.1.0 fails on such a URL (9.1.1 and later open it)".into()), + Some((7..=9, _, _)) => Ok(()), + Some((major, minor, patch)) => Err(format!( + "it is not known to build on Bazel {major}.{minor}.{patch} (it does on 7.7.2, 8.8.2 \ + and 9.3.2)" + )), + } +} + +impl Hub { + /// Why version `version` of the gem `name` is not committed for these + /// calls, before its bytes are known: the lock holds it as platform + /// gems, which no build has been run with, or in the hub of one of the + /// calls nothing would hold the committed gem to its bytes. Bundler + /// holds it to the lock's `CHECKSUMS` line and Bazel to the + /// `gem_checksums` entry of the call that fetches it, and to nothing + /// else. + pub(crate) fn declines(&self, name: &str, version: &str) -> Option { + let lock = parse(&self.lock); + if !lock.locked_builds(name, version).platforms.is_empty() { + return Some(format!( + "Gemfile.lock holds {name} {version} as platform gems" + )); + } + if lock.has_checksums() { + return None; + } + let key = format!("{name}-{version}"); + let held = |call: &usize| self.entries(&key).any(|(_, of)| of == *call); + let call = &self.calls[(0..self.calls.len()).find(|call| !held(call))?]; + Some(format!( + "Gemfile.lock has no CHECKSUMS section and {call} has no `gem_checksums` entry for \ + {key}, so nothing would hold the committed gem to its bytes there (`bundle lock \ + --add-checksums` writes the section)" + )) + } + + /// The `gem_checksums` entries of the gem `key` (`-`): + /// the sha256 and the call of each. + fn entries<'a>(&'a self, key: &'a str) -> impl Iterator { + let of = move |(gem, sum, call): &'a (String, String, usize)| { + (gem == key).then_some((sum.as_str(), *call)) + }; + self.pins.iter().filter_map(of) + } + + /// Why the patched gem, whose bytes hash to `sha256`, is not committed + /// for these calls: a `gem_checksums` entry of one of them holds the + /// gem to other bytes, and Bazel would fail that hub's download of the + /// committed ones. The call is the user's to edit. + fn pinned_to_other_bytes(&self, name: &str, version: &str, sha256: &str) -> Option { + let key = format!("{name}-{version}"); + let other = |(sum, _): &(&str, usize)| !sum.eq_ignore_ascii_case(sha256); + let (sum, call) = self.entries(&key).find(other)?; + let call = &self.calls[call]; + Some(format!( + "the `gem_checksums` of {call} hold {key} to sha256 {sum}, and the patched gem has \ + {sha256}: write that value there and run again (socket-patch does not edit the \ + call, and no undo puts the old value back)" + )) + } +} + +/// Where the gem of one patch is committed for a hub, and the lock it is +/// named in. +struct Site { + /// The directory of the patch, from the project. + dir: String, + /// The source the pair names: `file:.socket/vendor/gem//`. + source: String, + /// The patched gem, from the project: where rules_ruby asks that + /// source for it. + archive: String, + /// `Gemfile.lock`, as it was read. + lock: String, + /// The gem, as the hosted planner takes it. + dep: DepOverride, +} + +impl Site { + fn of(prelude: &GemPrelude, uuid: &str) -> Option { + let dir = vendor_uuid_dir_rel("gem", uuid)?; + let (name, version) = (&prelude.name, &prelude.version); + Some(Site { + source: format!("file:{dir}/"), + archive: format!("{dir}/gems/{name}-{version}.gem"), + dir, + lock: prelude.lock_eol.restore(&prelude.lock_text).into_owned(), + dep: DepOverride { + ecosystem: "gem".into(), + name: name.clone(), + namespace: None, + version: version.clone(), + token: String::new(), + patch_uuid: uuid.to_string(), + artifact_url: String::new(), + npm_registry_url: None, + registry_override: None, + integrity: Default::default(), + }, + }) + } + + /// How the gem of `prelude` is vendored in the project at `project`. + /// `None`: as it is without Bazel. `Ok(None)`: the pair names the + /// source already. `Ok(Some)`: for these calls. `Err`: not at all, and + /// this is why. + async fn lane( + &self, + prelude: &GemPrelude, + project: &Path, + ) -> Option, String>> { + if prelude.lock_wired { + return None; + } + let gemfile = &prelude.gemfile_text; + if gemfile.contains(&self.source) + && gem_pair_agrees(gemfile, &self.lock, &self.dep, &self.source).is_ok() + { + return Some(Ok(None)); + } + if env_flag(ALLOW_IN_BAZEL_ENV) { + return None; + } + let dir = project.to_path_buf(); + let root = run_blocking(move || crate::bazel::bazel_root(&dir)).await?; + let files = [GEMFILE, GEMFILE_LOCK].map(String::from).to_vec(); + Some(match reader(&root, "gem", files).await? { + Err(doubt) => Err(uncertain(&doubt)), + Ok(_) => gate(&root).await.and_then(|hub| { + let declined = hub.declines(&prelude.name, &prelude.version); + declined.map_or(Ok(Some(hub)), Err) + }), + }) + } + + /// Whether the committed gem is the one the pair names: it holds every + /// file of `record` as patched, and hashes to what the lock pins. + async fn intact(&self, project: &Path, record: &PatchRecord) -> bool { + let Ok(bytes) = read_regular_to_bytes(&project.join(&self.archive)).await else { + return false; + }; + self.pinned().is_none_or(|sum| sum == sha256_hex_of(&bytes)) + && carries(bytes, &record.files).await + } + + /// The sha256 the lock's `CHECKSUMS` holds the gem to. + fn pinned(&self) -> Option { + let lock = parse(&self.lock); + let sum = lock.checksum(&self.dep.name, &self.dep.version)?; + Some(sum.to_ascii_lowercase()) + } + + /// Whether the `Gemfile` gives the gem the source of an earlier patch: + /// the new one takes its place, as the hosted planner follows a patch + /// that supersedes one. + fn follows(&self, gemfile: &str) -> bool { + let decls = declarations::declarations(gemfile); + let ours = |url: &str| crate::origin::vendor_uuid_dir(url).is_some(); + let mut sources = decls.of(&self.dep.name).filter_map(|decl| decl.source()?.1); + sources.any(ours) + } +} + +/// Whether the gem archive `bytes` holds every file of a patch as patched. +pub(crate) async fn carries( + bytes: Vec, + files: &std::collections::HashMap, +) -> bool { + let Ok(stage) = tempfile::tempdir() else { + return false; + }; + let unpacked = extract_on_blocking_pool(bytes, stage.path(), extract_gem_data).await; + unpacked.is_ok() && copy_matches_after_hashes(stage.path(), files).await +} + +/// Whether the artifact of a ledger entry is a gem committed as its +/// archive. +pub(crate) fn is_archive(entry: &VendorEntry) -> bool { + entry.ecosystem == "gem" && archive_path(&entry.artifact.path) +} + +/// Whether `path` (with `/` between its parts) is where this form commits +/// a gem: `/gems/.gem`, the path rules_ruby asks a source +/// for. A copy that is vendored by its path is a directory named for its +/// gem and version, and a version may end in `.gem`. +pub(crate) fn archive_path(path: &str) -> bool { + let dir = path.rsplit_once('/').map(|(dir, _)| dir); + path.ends_with(".gem") && dir.is_some_and(|dir| dir.ends_with("/gems")) +} + +/// Hold the committed gem `archive` to `record`: every file of the patch +/// is in it as patched. The error is the routing tag of +/// [`crate::vendor::verify::verify_vendored_patch_record`]. +pub(crate) async fn verify(archive: &Path, record: &PatchRecord) -> Result<(), String> { + let unreadable = |_| "vendor_artifact_unreadable".to_string(); + let bytes = read_regular_to_bytes(archive).await.map_err(unreadable)?; + match carries(bytes, &record.files).await { + true => Ok(()), + false => Err("vendor_hash_mismatch".to_string()), + } +} + +/// The download [`vendor`] makes for the gem of `prelude`: the archive and +/// its stub gemspec, which says whether the gem is one the lane takes. +/// `None` where the gem is vendored as it is without Bazel; `Some(None)` +/// where it is declined, or in place. +pub(super) async fn preflight( + purl: &str, + prelude: &GemPrelude, + project: &Path, + record: &PatchRecord, +) -> Option> { + let site = Site::of(prelude, &record.uuid)?; + let asks = match site.lane(prelude, project).await? { + Err(_) => false, + Ok(None) => !site.intact(project, record).await, + Ok(Some(_)) => site.follows(&prelude.gemfile_text) || gem_edits(purl, prelude).is_ok(), + }; + Some(asks.then(|| PlannedDownload { + secondary: Some(GEM_STUB_ARTIFACT_KIND.to_string()), + ..PlannedDownload::archive(record.uuid.clone()) + })) +} + +/// Vendor the gem of `prelude` as its archive, for a hub that reads the +/// `Gemfile` and the lock of the project (see the module docs). `None` +/// where no hub reads them, or the user asked for the copy of every other +/// project: the caller goes on. +pub(super) async fn vendor( + purl: &str, + prelude: &GemPrelude, + project: &Path, + record: &PatchRecord, + vendored_at: &str, + dry_run: bool, + service: Option<&VendorServiceConfig>, +) -> Option { + let site = Site::of(prelude, &record.uuid)?; + let hub = match site.lane(prelude, project).await? { + Ok(hub) => hub, + Err(why) => { + let detail = format!( + "a call of rules_ruby in the Bazel workspace reads the lock of this project, \ + and the patched gem cannot be committed for it: {why}" + ); + return Some(refused(GEM_CODE, detail)); + } + }; + let (name, version) = (prelude.name.as_str(), prelude.version.as_str()); + let archive = project.join(&site.archive); + if hub.is_none() && site.intact(project, record).await { + let result = already_patched_result(purl, &archive, &record.files); + return Some(done(result, None, Vec::new())); + } + // The gem meets the refusals of every vendored gem first. A + // declaration that carries the source of an earlier patch passed them + // when that patch was vendored. + if hub.is_some() && !site.follows(&prelude.gemfile_text) { + if let Err(outcome) = gem_edits(purl, prelude) { + return Some(*outcome); + } + } + // Dry run or not, before anything is downloaded: a directory that git + // ignores holds no gem a clone would have. + if let Some((code, detail)) = ignored_root_refusal(project, &site.dir).await { + return Some(refused(code, detail)); + } + if let Some(refusal) = service_offline_conflict(service) { + return Some(refusal); + } + let fetched = match gem_service_archive(service, record, name).await { + Ok((fetched, _)) => fetched, + Err(outcome) => return Some(*outcome), + }; + let sha256 = fetched.sha256_hex().to_string(); + if !carries(fetched.bytes.clone(), &record.files).await { + return Some(*ServicePolicy::Refused.miss(format!( + "prebuilt .gem for {name} extracted to an unexpected layout (patched files absent \ + at their recorded paths)" + ))); + } + let declined = |why: String| Some(refused(GEM_CODE, why)); + let plan = match &hub { + // The pair is in place and the gem is not: only the gem is + // written, and it has to be the one the lock pins. + None => match site.pinned().filter(|sum| *sum != sha256) { + Some(sum) => { + return declined(format!( + "Gemfile.lock holds {name} {version} to sha256 {sum}, and the patch \ + service's gem has {sha256}; {}", + crate::vendor::common::REVERT_ALL_AND_REVENDOR + )) + } + None => None, + }, + Some(hub) => { + if let Some(why) = hub.pinned_to_other_bytes(name, version, &sha256) { + return declined(why); + } + let (gemfile, lock) = (&prelude.gemfile_text, &site.lock); + match plan_gem_source(gemfile, lock, &site.dep, &site.source, &sha256) { + Ok(plan) => Some(plan), + Err(warning) => { + return declined(format!( + "Gemfile and Gemfile.lock cannot name the committed gem as hosted mode \ + names a patch registry, and for the reason a hosted run gives ({}: {}); \ + the way on that reason names is the one of a hosted run", + warning.code, warning.detail + )) + } + } + } + }; + if dry_run { + let result = preview_result(purl, &archive, &record.files); + return Some(done(result, None, Vec::new())); + } + + // ── the gem, where rules_ruby asks the source for it ───────────────── + let uuid_dir = prelude.uuid_dir.as_path(); + // A gem whose pair was in place keeps what it has. + let fresh = plan.is_some(); + let unwind = || async { + if fresh { + let _ = remove_tree(uuid_dir).await; + prune_empty_vendor_levels(uuid_dir).await; + } + }; + let failed = |what: &str, e: std::io::Error| { + let error = format!("failed to write {what}: {e}"); + Some(done(failed_result(purl, &archive, error), None, Vec::new())) + }; + let written = async { + tokio::fs::create_dir_all(archive.parent().unwrap_or(uuid_dir)).await?; + atomic_write_artifact(&archive, &fetched.bytes).await?; + // Stock ignore templates name `*.gem`. + restore_uuid_metadata(uuid_dir).await + }; + if let Err(e) = written.await { + unwind().await; + return failed(&site.archive, e); + } + let mut warnings = vec![fetched.downloaded_warning(name)]; + let artifact = VendorArtifact { + yarn_berry10c0: None, + path: site.archive.clone(), + sha256, + size: Some(fetched.bytes.len() as u64), + platform_locked: None, + file_inventory: None, + }; + let entry = |wiring| { + let purl = build_gem_purl(name, version); + VendorEntry::new("gem".into(), purl, record.uuid.clone(), artifact, wiring) + }; + let result = already_patched_result(purl, &archive, &record.files); + let Some((gemfile, lock, edits)) = plan else { + warnings.push(VendorWarning::new( + "vendor_artifact_rebuilt", + format!( + "the committed gem for {name}@{version} was missing or not the patched one; \ + written again at {} (Gemfile and Gemfile.lock untouched)", + site.archive + ), + )); + // The wiring is the first run's, which the caller carries forward. + return Some(done(result, Some(entry(Vec::new())), warnings)); + }; + + // ── Gemfile, then Gemfile.lock (a failure unwinds the Gemfile) ─────── + if let Err(e) = + atomic_write_bytes_preserving_mode(&prelude.gemfile_path, gemfile.as_bytes()).await + { + unwind().await; + return failed(GEMFILE, e); + } + if let Err(e) = atomic_write_bytes_preserving_mode(&prelude.lock_path, lock.as_bytes()).await { + let before = prelude.gemfile_text.as_bytes(); + let _ = atomic_write_bytes_preserving_mode(&prelude.gemfile_path, before).await; + unwind().await; + return failed(GEMFILE_LOCK, e); + } + let marker = VendorMarker::new("gem", &build_gem_purl(name, version), record, vendored_at); + write_marker_or_warn(uuid_dir, &marker, &mut warnings).await; + warnings.push(VendorWarning::new( + ADVISORY, + format!( + "{name} {version} is vendored for the Bazel hub that reads Gemfile.lock: Gemfile and \ + Gemfile.lock name {} by a relative `file:` URL, which Bazel builds. Bundler by \ + itself does not install from such a source (`bundle install` on a machine without \ + the gem and `bundle lock --update` fail; on a machine that installed the gem before, \ + `bundle install` passes and keeps that unpatched copy), so this checkout builds its \ + gems through Bazel only; `--mode hosted` serves both. Bazel does not watch the gem: \ + an output base that fetched the hub before keeps what it fetched", + site.archive + ), + )); + Some(done( + result, + Some(entry(records(name, &site.source, &edits))), + warnings, + )) +} + +/// The wiring records of the pair edit `edits` made for the gem `name` +/// ([`GEMFILE_KIND`], [`LOCK_KIND`]). An edit that followed an earlier +/// patch moved no entry of the lock: its record has no `original`, and the +/// caller carries the one of the entry it replaces forward. +fn records(name: &str, source: &str, edits: &[FileEdit]) -> Vec { + let before = |kind: &str| { + let edit = edits.iter().find(|edit| edit.kind == kind)?; + edit.original.clone() + }; + let original = before("redirect_gemfile_lock_gem_source").map(|remote| { + json!({ + "remote": remote, + "dependency": before("redirect_gemfile_lock_dependency_pin"), + "checksum": before("redirect_gemfile_lock_checksum"), + }) + }); + let record = |file: &str, kind: &str, action, original| WiringRecord { + file: file.to_string(), + kind: kind.to_string(), + action, + key: Some(name.to_string()), + original, + new: Some(Value::String(source.to_string())), + }; + vec![ + record(GEMFILE, GEMFILE_KIND, WiringAction::Added, None), + record(GEMFILE_LOCK, LOCK_KIND, WiringAction::Rewritten, original), + ] +} + +/// Revert the entry of a gem committed as its archive: the `Gemfile` loses +/// the source, the lock's entry goes back to the section it came from with +/// its `DEPENDENCIES` entry and its `CHECKSUMS` line, and the directory of +/// the patch is removed. A file that names the source nowhere has been put +/// back already, and the other goes back by itself; a file that names it +/// and no longer holds what [`vendor`] wrote leaves both alone +/// (`vendor_lock_entry_drifted`) with the gem. +pub(super) async fn revert( + entry: &VendorEntry, + project: &Path, + uuid_dir_rel: &str, + opts: RevertOpts, +) -> RevertOutcome { + let Some((name, version)) = parse_gem_purl(&entry.base_purl) else { + return RevertOutcome::failed(format!("not a gem purl: {}", entry.base_purl)); + }; + let source = format!("file:{uuid_dir_rel}/"); + let mut files = RevertFiles::new(project); + let mut texts = Vec::new(); + for file in [GEMFILE_LOCK, GEMFILE] { + match files.text(file).await { + Ok(text) => texts.push(text.map(|text| text.text().to_string())), + Err(e) => return RevertOutcome::failed(e), + } + } + let mut outcome = RevertOutcome::ok(); + let before = entry.wiring.iter().find(|w| w.kind == LOCK_KIND); + let before = before.and_then(|w| w.original.as_ref()); + match (&texts[0], &texts[1]) { + (Some(lock), Some(gemfile)) if lock.contains(&source) || gemfile.contains(&source) => { + // A file that names the source nowhere has been put back + // already: the other one goes back by itself. + let lock = match lock.contains(&source) { + true => before.and_then(|b| unwire_lock(lock, &name, &version, &source, b)), + false => Some(lock.clone()), + }; + let gemfile = match gemfile.contains(&source) { + true => unwire_gemfile(gemfile, &name, &source), + false => Some(gemfile.clone()), + }; + match (lock, gemfile) { + (Some(lock), Some(gemfile)) => { + for (file, text) in [(GEMFILE_LOCK, lock), (GEMFILE, gemfile)] { + if let Ok(Some(file)) = files.text(file).await { + file.set(text); + } + } + let key = format!("{name}-{version}"); + let (dir, sum) = (project.to_path_buf(), entry.artifact.sha256.clone()); + let left = run_blocking(move || entry_left(&dir, &key, &sum)).await; + outcome.warnings.extend(left); + } + _ => outcome.warnings.push(VendorWarning::new( + "vendor_lock_entry_drifted", + format!( + "{GEMFILE} and {GEMFILE_LOCK} no longer carry what vendor wrote for \ + {name}; left alone, and neither was changed" + ), + )), + } + } + (Some(_), Some(_)) => {} + _ => outcome.warnings.push(VendorWarning::new( + "vendor_lockfile_missing", + format!("{GEMFILE} or {GEMFILE_LOCK} is missing; the {name} entry cannot be restored"), + )), + } + if !opts.dry_run { + if let Err(e) = files.write_changed().await { + return RevertOutcome::failed(e); + } + } + revert::finish(outcome, project, uuid_dir_rel, opts, KeepPolicy::OnDrift).await +} + +/// What an undo in the project at `project` says of a call of the hub +/// whose `gem_checksums` still hold the gem `key` (`-`) to +/// `sha256`, the one of the committed gem ([`ENTRY_LEFT`]). Read apart from +/// [`gate`]: the entry fails the build whatever else the checkout says. +fn entry_left(project: &Path, key: &str, sha256: &str) -> Option { + let root = crate::bazel::bazel_root(project)?; + let workspace = Workspace::read(&disk(&root.dir)); + let holds = |tag: &Tag<'_>| match tag.call.arg("gem_checksums") { + Some(Starlark::Dict(sums)) => sums.iter().any(|(gem, sum)| { + gem == key && matches!(sum, Starlark::Str(sum) if sum.eq_ignore_ascii_case(sha256)) + }), + _ => false, + }; + let (calls, _) = hub_calls(&workspace, "gem"); + let call = calls + .iter() + .find(|(tag, _)| holds(tag)) + .map(|(tag, _)| named(tag))?; + Some(VendorWarning::new( + ENTRY_LEFT, + format!( + "the `gem_checksums` of {call} still hold {key} to the sha256 of the patched gem \ + ({sha256}), and the lock names the upstream gem again: the Bazel build fails on \ + that entry until it holds the upstream gem's sha256, or is removed (socket-patch \ + does not edit the call)" + ), + )) +} + +/// `gemfile` without the source `source` of the gem `name`: the option +/// goes from the one declaration that carries it, or the whole line where +/// the pair added it. `None` unless exactly one declaration carries it. +fn unwire_gemfile(gemfile: &str, name: &str, source: &str) -> Option { + let decls = declarations::declarations(gemfile); + let ours = |decl: &&declarations::Declaration| { + decl.source().is_some_and(|(_, url)| url == Some(source)) + }; + let mut ours = decls.of(name).filter(ours); + let (decl, None) = (ours.next()?, ours.next()) else { + return None; + }; + Some(match declarations::is_added_line(gemfile, decl) { + true => declarations::without_added_line(gemfile, decl), + false => declarations::without_arg(gemfile, decl.source()?.0), + }) +} + +/// `lock` (with `\n` line endings) with version `version` of the gem +/// `name` back where it was before the pair named `source`, as `before` +/// records it ([`LOCK_KIND`]): the entry in the section of that remote, +/// where Bundler sorts it; its `DEPENDENCIES` entry as it was, or gone +/// where the pair added it; and its `CHECKSUMS` line likewise. `None` for a +/// lock that does not hold exactly what the pair wrote, and for a record +/// that would put back a line that is not this gem's. +fn unwire_lock( + lock: &str, + name: &str, + version: &str, + source: &str, + before: &Value, +) -> Option { + let mut lines: Vec = lock.split('\n').map(str::to_string).collect(); + // The `GEM` section whose one remote is `remote`: the line of its + // first entry. + let entries = |lines: &[String], remote: &str| { + let remote = format!(" remote: {remote}"); + let head = ["GEM", remote.as_str(), " specs:"]; + let heads = |at: &usize| lines.get(*at..at + 3).is_some_and(|l| l[..] == head[..]); + (0..lines.len()).find(heads).map(|at| at + 3) + }; + // The entry of a line that is this gem's own, as the lock spells it. + let own = |key: &str, names: &dyn Fn(&str) -> bool| match before.get(key) { + None | Some(Value::Null) => Some(None), + Some(Value::String(entry)) => { + let line = format!(" {entry}"); + (is_one_line(&line, false) && names(&line)).then_some(Some(line)) + } + Some(_) => None, + }; + let dependency = own("dependency", &|line| dep_entry_name(line) == Some(name))?; + let checksum = own("checksum", &|line| { + checksum_entry(line).is_some_and(|(gem, _)| gem == name) + })?; + + // The section of the patch: the gem's entry with its dependencies, and + // the blank line after it. + let first = entries(&lines, source)?; + if lines.get(first) != Some(&format!(" {name} ({version})")) { + return None; + } + let deps = lines[first + 1..] + .iter() + .take_while(|l| l.starts_with(" ")); + let end = first + 1 + deps.count(); + if lines.get(end).is_none_or(|line| !line.is_empty()) { + return None; + } + let block: Vec = lines.drain(first - 3..=end).skip(3).collect(); + let block = &block[..block.len() - 1]; + + // Back into the section it came from, by its full name. + let full = |line: &str| { + let spec = parse_spec(line.strip_prefix(" ")?)?; + let platform = spec.platform.map(|platform| format!("-{platform}")); + let platform = platform.unwrap_or_default(); + Some(format!("{}-{}{platform}", spec.name, spec.version)) + }; + let ours = format!("{name}-{version}"); + let mut at = entries(&lines, before.get("remote")?.as_str()?)?; + while lines.get(at).is_some_and(|line| line.starts_with(" ")) { + if full(&lines[at]).is_some_and(|other| other > ours) { + break; + } + at += 1; + } + lines.splice(at..at, block.iter().cloned()); + + // The lines of a section that is all two-space entries. + let section = |lines: &[String], header: &str| { + let start = lines.iter().position(|line| line == header)? + 1; + let len = lines[start..].iter().take_while(|l| l.starts_with(" ")); + Some(start..start + len.count()) + }; + let pinned = |line: &String| line.ends_with('!') && dep_entry_name(line) == Some(name); + let at = section(&lines, "DEPENDENCIES")?.find(|at| pinned(&lines[*at]))?; + match dependency { + Some(entry) => lines[at] = entry, + None => drop(lines.remove(at)), + } + let sums = section(&lines, "CHECKSUMS").unwrap_or(0..0); + let pins = |line: &String| checksum_entry(line) == Some((name, version)); + match (sums.clone().find(|at| pins(&lines[*at])), checksum) { + (Some(at), Some(line)) => lines[at] = line, + (Some(at), None) => drop(lines.remove(at)), + (None, None) => {} + (None, Some(_)) => return None, + } + Some(lines.join("\n")) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::path::PathBuf; + + const UUID: &str = "11111111-1111-4111-8111-111111111111"; + const NEWER: &str = "33333333-3333-4333-8333-333333333333"; + const MODULE: &str = r#"ruby = use_extension("@rules_ruby//ruby:extensions.bzl", "ruby") +ruby.bundle_fetch(name = "bundle", gemfile = "//:Gemfile", gemfile_lock = "//:Gemfile.lock") +"#; + const GEMFILE_TEXT: &str = "source \"https://rubygems.org/\"\n\ngem \"rack\", \"~> 2.2\"\n"; + + fn sum(of: char) -> String { + of.to_string().repeat(64) + } + + /// A lock that resolves `rack 2.2.3`, which depends on `zeitwerk`, + /// between two other gems, with a `CHECKSUMS` section. + fn lock() -> String { + format!( + "GEM\n remote: https://rubygems.org/\n specs:\n ast (1.0.0)\n rack (2.2.3)\n \ + zeitwerk (~> 2.6)\n zeitwerk (2.6.0)\n\nPLATFORMS\n ruby\n\nDEPENDENCIES\n rack \ + (~> 2.2)\n\nCHECKSUMS\n ast (1.0.0) sha256={}\n rack (2.2.3) sha256={}\n zeitwerk \ + (2.6.0) sha256={}\n\nBUNDLED WITH\n 2.6.9\n", + sum('a'), + sum('b'), + sum('c') + ) + } + + /// A checkout whose root `MODULE.bazel` is `module`, canonical, with + /// the files `files` and Bazel 9.3.2 in `.bazelversion`. + fn checkout(module: &str, files: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) { + let tmp = tempfile::tempdir().unwrap(); + let root = fs::canonicalize(tmp.path()).unwrap(); + let (lock, head) = (lock(), "ref: refs/heads/main\n"); + let all = [ + (".git/HEAD", head), + ("MODULE.bazel", module), + (".bazelversion", "9.3.2\n"), + (GEMFILE, GEMFILE_TEXT), + (GEMFILE_LOCK, lock.as_str()), + ]; + for (path, text) in all.iter().chain(files) { + let path = root.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + (tmp, root) + } + + /// Why [`gate`] declines the project at `project`, or `None`. + async fn declined(project: &Path) -> Option { + let root = crate::bazel::bazel_root(project).expect("a Bazel workspace"); + gate(&root).await.err() + } + + #[tokio::test] + async fn the_gate_holds_where_each_condition_is_read_from_the_checkout() { + let (_tmp, root) = checkout(MODULE, &[]); + assert_eq!(declined(&root).await, None); + // Each edit of that checkout, and what the gate then names. + let call = "ruby.bundle_fetch(name = \"bundle\", gemfile = \"//:Gemfile\", "; + let lock_arg = "gemfile_lock = \"//:Gemfile.lock\""; + let pinned = |sums: &str| MODULE.replace(lock_arg, &format!("{lock_arg}, {sums}")); + let bundler = |version: &str| lock().replace(" 2.6.9", &format!(" {version}")); + let unnamed = "names no Bazel release as three numbers"; + let cases: [(&str, String, &str); 18] = [ + (".bazelversion", String::new(), unnamed), + (".bazelversion", "latest\n".into(), unnamed), + (".bazelversion", "9.3.2rc1\n".into(), unnamed), + ( + ".bazelversion", + "9.1.0\n".into(), + "Bazel 9.1.0 fails on such a URL", + ), + ( + ".bazelversion", + "6.5.0\n".into(), + "not known to build on Bazel 6.5.0", + ), + ( + "WORKSPACE", + "local_repository(name = \"x\", path = \"x\")\n".into(), + "a `WORKSPACE` file of the workspace defines repositories", + ), + ( + "MODULE.bazel", + format!("{MODULE}include(\"//:more.MODULE.bazel\")\n"), + "not read with certainty (more.MODULE.bazel: it does not exist", + ), + ( + "MODULE.bazel", + MODULE.replace(lock_arg, "**LOCK"), + "`ruby.bundle_fetch` (MODULE.bazel:2) does not write out the files it reads", + ), + ( + "MODULE.bazel", + format!("{MODULE}{call}gemfile_lock = \"//svc:Gemfile.lock\")\n"), + "`ruby.bundle_fetch` (MODULE.bazel:3) reads one of Gemfile and Gemfile.lock alone", + ), + ( + "MODULE.bazel", + pinned("gem_checksums = SUMS"), + "the `gem_checksums` of `ruby.bundle_fetch` (MODULE.bazel:2) are not written out", + ), + ( + "MODULE.bazel", + pinned("gem_checksums = {\"rack-2.2.3\": SUM}"), + "the `gem_checksums` of `ruby.bundle_fetch` (MODULE.bazel:2) are not written out", + ), + ( + "MODULE.bazel", + MODULE.replace("//:", "//svc:"), + "no `ruby.bundle_fetch` call is seen to read Gemfile and Gemfile.lock", + ), + ( + GEMFILE_LOCK, + bundler("1.17.3"), + "not known to build with Bundler 1.17.3, which Gemfile.lock names", + ), + ( + GEMFILE_LOCK, + bundler("2.5.23"), + "not known to build with Bundler 2.5.23, which Gemfile.lock names", + ), + ( + GEMFILE_LOCK, + String::new(), + "Gemfile.lock names no Bundler (`BUNDLED WITH`)", + ), + ( + ".bazelrc", + "build --experimental_remote_downloader=grpcs://cache.example\n".into(), + ".bazelrc:1 names `--experimental_remote_downloader=grpcs://cache.example`, under \ + which Bazel may not read the committed gem", + ), + ( + ".bazelrc", + "build \"--copt\n".into(), + "the rc file .bazelrc:1 cannot be read", + ), + ( + ".bazelrc", + "common --vendor_dir=third_party/bazel\n".into(), + ".bazelrc:1 names `--vendor_dir=third_party/bazel`", + ), + ]; + for (file, text, why) in cases { + let (_tmp, root) = checkout(MODULE, &[(file, &text)]); + let said = declined(&root).await.unwrap_or_default(); + assert!( + said.contains(why), + "{file} = {text:?}: {said:?}, not {why:?}" + ); + } + // A call that reads the files of another project is none of this + // one's, whatever it holds its gems to. + let other = MODULE + .replace("//:", "//svc:") + .replace(lock_arg, "gem_checksums = SUMS"); + let (_tmp, root) = checkout(&format!("{MODULE}{}", other.lines().nth(1).unwrap()), &[]); + assert_eq!(declined(&root).await, None); + // A project below the root: Bazel opens the URL from the root. + let below = MODULE.replace("//:", "//api:"); + let files = [("api/Gemfile", GEMFILE_TEXT), ("api/Gemfile.lock", "")]; + let (_tmp, root) = checkout(&below, &files); + let said = declined(&root.join("api")).await.unwrap_or_default(); + assert!( + said.contains("is not the root of the Bazel workspace"), + "{said}" + ); + } + + #[test] + fn a_release_opens_the_url_where_one_of_its_line_was_built() { + for known in [ + (7, 0, 0), + (7, 7, 2), + (8, 8, 2), + (9, 0, 2), + (9, 1, 1), + (9, 3, 2), + ] { + assert_eq!(opens_file_urls(Some(known)), Ok(()), "{known:?}"); + } + for unknown in [None, Some((9, 1, 0)), Some((6, 5, 0)), Some((10, 0, 0))] { + assert!(opens_file_urls(unknown).is_err(), "{unknown:?}"); + } + } + + #[test] + fn the_hub_builds_with_a_bundler_of_a_line_that_was_built() { + let named = |version: &str| format!("GEM\n specs:\n\nBUNDLED WITH\n {version}\n"); + for known in ["2.6.0", "2.6.9", "2.7.2", "4.0.15"] { + assert_eq!(bundler_builds(&named(known)), Ok(()), "{known}"); + } + for unknown in ["2.2.19", "2.5.23", "3.0.0", "5.0.0", "two"] { + assert!(bundler_builds(&named(unknown)).is_err(), "{unknown}"); + } + } + + /// The artifact of the form is known by its place, so a copy vendored + /// by its path, a directory, keeps the checks of one whatever its + /// version ends in. + #[test] + fn a_committed_gem_is_known_by_its_place() { + use crate::vendor::verify::artifact_is_file_shaped; + let committed = ".socket/vendor/gem/u/gems/rack-2.2.3.gem"; + assert!(archive_path(committed) && artifact_is_file_shaped(committed)); + assert!(artifact_is_file_shaped(&committed.replace('/', "\\"))); + for copy in [".socket/vendor/gem/u/rack-1.0.0.gem", "rack.gem"] { + assert!( + !archive_path(copy) && !artifact_is_file_shaped(copy), + "{copy}" + ); + } + } + + /// The committed gem is held to its bytes by the lock's `CHECKSUMS` + /// line or by the `gem_checksums` entry of every call that reads the + /// pair, and an entry of any of them that holds the gem to other bytes + /// declines it. + #[tokio::test] + async fn a_gem_is_committed_only_where_its_bytes_are_held() { + let entry = format!("gem_checksums = {{\"rack-2.2.3\": \"{}\"}}", sum('B')); + let lock_arg = "gemfile_lock = \"//:Gemfile.lock\""; + let pinned = MODULE.replace(lock_arg, &format!("{lock_arg}, {entry}")); + let unchecked = + lock().split("CHECKSUMS").next().unwrap().to_string() + "BUNDLED WITH\n 2.6.2\n"; + let hub = |module: &str, lock: &str| { + let (module, lock) = (module.to_string(), lock.to_string()); + async move { + let (_tmp, root) = checkout(&module, &[(GEMFILE_LOCK, &lock)]); + let root = crate::bazel::bazel_root(&root).unwrap(); + gate(&root).await.expect("the gate holds") + } + }; + let (rack, version) = ("rack", "2.2.3"); + assert_eq!(hub(MODULE, &lock()).await.declines(rack, version), None); + let declined = hub(MODULE, &unchecked).await.declines(rack, version); + let unheld = |line: u32| { + format!( + "has no CHECKSUMS section and `ruby.bundle_fetch` (MODULE.bazel:{line}) has no \ + `gem_checksums` entry for rack-2.2.3" + ) + }; + assert!(declined.is_some_and(|said| said.contains(&unheld(2)))); + assert_eq!(hub(&pinned, &unchecked).await.declines(rack, version), None); + // The entry is of the gem alone, and is read without regard to case. + let held = hub(&pinned, &lock()).await; + assert_eq!(held.pinned_to_other_bytes(rack, version, &sum('b')), None); + assert_eq!(held.pinned_to_other_bytes("ast", "1.0.0", &sum('d')), None); + let other = held.pinned_to_other_bytes(rack, version, &sum('d')); + let other = other.unwrap_or_default(); + let named = [ + "the `gem_checksums` of `ruby.bundle_fetch` (MODULE.bazel:2) hold rack-2.2.3 to sha256", + &sum('B'), + &sum('d'), + "socket-patch does not edit the call", + ]; + assert!(named.iter().all(|part| other.contains(part)), "{other}"); + // A second call that reads the pair fetches the gem for a hub of + // its own: its entry holds the gem too, and where the lock has no + // section it needs one. + let second = |sums: &str| { + let call = MODULE.lines().nth(1).unwrap(); + let call = call.replace("\"bundle\"", "\"tools\""); + format!( + "{pinned}{}\n", + call.replace(lock_arg, &format!("{lock_arg}{sums}")) + ) + }; + let upstream = format!(", gem_checksums = {{\"rack-2.2.3\": \"{}\"}}", sum('d')); + let held = hub(&second(&upstream), &lock()).await; + let other = held.pinned_to_other_bytes(rack, version, &sum('b')); + let other = other.unwrap_or_default(); + let named = [ + "`ruby.bundle_fetch` (MODULE.bazel:3) hold rack-2.2.3", + &sum('d'), + ]; + assert!(named.iter().all(|part| other.contains(part)), "{other}"); + assert_eq!( + held.pinned_to_other_bytes(rack, version, &sum('d')) + .is_some(), + true + ); + let declined = hub(&second(""), &unchecked).await.declines(rack, version); + assert!(declined.is_some_and(|said| said.contains(&unheld(3)))); + let both = second(&upstream.replace(&sum('d'), &sum('b'))); + let held = hub(&both, &unchecked).await; + assert_eq!(held.declines(rack, version), None); + assert_eq!(held.pinned_to_other_bytes(rack, version, &sum('b')), None); + // A gem the lock holds as platform gems. + let platform = lock().replace(" rack (2.2.3)\n", " rack (2.2.3-java)\n"); + let declined = hub(MODULE, &platform).await.declines(rack, version); + assert!(declined.is_some_and(|said| said.contains("as platform gems"))); + } + + /// The pair the planner writes for the gem `name` of patch `uuid` in + /// the project at `dir`, on disk, with its gem committed: the ledger + /// entry of it. + fn wire(dir: &Path, name: &str, version: &str, uuid: &str) -> VendorEntry { + let rel = vendor_uuid_dir_rel("gem", uuid).unwrap(); + let (source, archive) = ( + format!("file:{rel}/"), + format!("{rel}/gems/{name}-{version}.gem"), + ); + let dep = DepOverride { + ecosystem: "gem".into(), + name: name.into(), + namespace: None, + version: version.into(), + token: String::new(), + patch_uuid: uuid.into(), + artifact_url: String::new(), + npm_registry_url: None, + registry_override: None, + integrity: Default::default(), + }; + let read = |file: &str| fs::read_to_string(dir.join(file)).unwrap(); + let (gemfile, lock) = (read(GEMFILE), read(GEMFILE_LOCK)); + let planned = plan_gem_source(&gemfile, &lock, &dep, &source, &sum('f')); + let (gemfile, lock, edits) = planned.expect("a plan"); + assert_eq!(gem_pair_agrees(&gemfile, &lock, &dep, &source), Ok(())); + fs::write(dir.join(GEMFILE), gemfile).unwrap(); + fs::write(dir.join(GEMFILE_LOCK), lock).unwrap(); + fs::create_dir_all(dir.join(&archive).parent().unwrap()).unwrap(); + fs::write(dir.join(&archive), "a gem").unwrap(); + let artifact = VendorArtifact { + yarn_berry10c0: None, + path: archive, + sha256: sum('f'), + size: None, + platform_locked: None, + file_inventory: None, + }; + let purl = build_gem_purl(name, version); + VendorEntry::new( + "gem".into(), + purl, + uuid.into(), + artifact, + records(name, &source, &edits), + ) + } + + async fn reverted(entry: &VendorEntry, dir: &Path) -> RevertOutcome { + let rel = vendor_uuid_dir_rel("gem", &entry.uuid).unwrap(); + revert(entry, dir, &rel, RevertOpts::new(false)).await + } + + /// Every pair the planner writes goes back byte for byte, with the + /// directory of the patch: a declared gem with its own requirement, + /// options and comment, an undeclared one, a pair with CRLF line + /// endings, and a lock with no `CHECKSUMS` section. + #[tokio::test] + async fn the_revert_puts_the_pair_back_byte_for_byte() { + let decorated = "source \"https://rubygems.org/\"\n\ngem 'ast'\ngem \"rack\", \"~> 2.2\", \ + require: false # the web server\n"; + let unchecked = + lock().split("CHECKSUMS").next().unwrap().to_string() + "BUNDLED WITH\n 2.5.0"; + let crlf = |text: &str| text.replace('\n', "\r\n"); + let cases = [ + ("rack", "2.2.3", GEMFILE_TEXT.to_string(), lock()), + ("rack", "2.2.3", decorated.to_string(), lock()), + ( + "zeitwerk", + "2.6.0", + GEMFILE_TEXT.trim_end().to_string(), + lock(), + ), + ("rack", "2.2.3", crlf(GEMFILE_TEXT), crlf(&lock())), + ("zeitwerk", "2.6.0", crlf(decorated), crlf(&lock())), + ("rack", "2.2.3", GEMFILE_TEXT.to_string(), unchecked), + ]; + for (name, version, gemfile, lock) in cases { + let files = [(GEMFILE, gemfile.as_str()), (GEMFILE_LOCK, lock.as_str())]; + let (_tmp, root) = checkout(MODULE, &files); + let entry = wire(&root, name, version, UUID); + let wired = fs::read_to_string(root.join(GEMFILE_LOCK)).unwrap(); + assert!(wired.contains(&format!(" remote: file:.socket/vendor/gem/{UUID}/"))); + let outcome = reverted(&entry, &root).await; + assert!( + outcome.success && outcome.warnings.is_empty(), + "{outcome:?}" + ); + let read = |file: &str| fs::read_to_string(root.join(file)).unwrap(); + assert_eq!( + [read(GEMFILE), read(GEMFILE_LOCK)], + [gemfile, lock], + "{name}" + ); + assert!( + !root.join(".socket/vendor").exists(), + "{name}: the gem is left" + ); + } + } + + /// An undo leaves the call as the user wrote it: where its + /// `gem_checksums` still hold the gem to the committed gem's sha256, + /// which fails the build of the lock the undo puts back, it says so. + #[tokio::test] + async fn an_undo_names_the_entry_it_leaves_in_the_call() { + let lock_arg = "gemfile_lock = \"//:Gemfile.lock\""; + let pinned = |sum: &str| { + let entry = format!("{lock_arg}, gem_checksums = {{\"rack-2.2.3\": \"{sum}\"}}"); + MODULE.replace(lock_arg, &entry) + }; + // `wire` commits a gem whose sha256 is all `f`. + for (module, left) in [ + (pinned(&sum('F')), true), + (pinned(&sum('a')), false), + (MODULE.to_string(), false), + ] { + let (_tmp, root) = checkout(&module, &[]); + let entry = wire(&root, "rack", "2.2.3", UUID); + let outcome = reverted(&entry, &root).await; + let read = |file: &str| fs::read_to_string(root.join(file)).unwrap(); + assert!(outcome.success, "{outcome:?}"); + assert_eq!( + [read(GEMFILE), read(GEMFILE_LOCK)], + [GEMFILE_TEXT.to_string(), lock()] + ); + let said: Vec<&str> = outcome.warnings.iter().map(|w| w.code).collect(); + assert_eq!(said, [ENTRY_LEFT][..usize::from(left)], "{module}"); + let named = [ + "`ruby.bundle_fetch` (MODULE.bazel:2) still hold rack-2.2.3", + &sum('f'), + ]; + let detail = outcome.warnings.first().map(|w| w.detail.as_str()); + let detail = detail.unwrap_or_default(); + assert!( + !left || named.iter().all(|part| detail.contains(part)), + "{detail}" + ); + } + } + + /// A newer patch of the gem takes the source over in place, and its + /// entry, with what the caller carries forward from the one it + /// replaces, puts back the pair of before the first. + #[tokio::test] + async fn a_patch_that_follows_another_reverts_to_the_pair_of_before_both() { + let (_tmp, root) = checkout(MODULE, &[]); + let first = wire(&root, "rack", "2.2.3", UUID); + let mut second = wire(&root, "rack", "2.2.3", NEWER); + let read = |file: &str| fs::read_to_string(root.join(file)).unwrap(); + assert!(!read(GEMFILE_LOCK).contains(UUID) && !read(GEMFILE).contains(UUID)); + // The second edit moved no entry: its record holds no original. + assert_eq!(second.wiring[1].original, None); + assert!(!reverted(&second, &root).await.warnings.is_empty()); + crate::vendor::state::carry_forward_wiring(&first, &mut second); + let outcome = reverted(&second, &root).await; + assert!( + outcome.success && outcome.warnings.is_empty(), + "{outcome:?}" + ); + assert_eq!( + [read(GEMFILE), read(GEMFILE_LOCK)], + [GEMFILE_TEXT.to_string(), lock()] + ); + } + + /// A pair that no longer holds what the run wrote is left alone with + /// the gem, and so is one whose record would put back a line that is + /// not this gem's; a pair that names the source nowhere has been put + /// back, and the gem goes. + #[tokio::test] + async fn a_pair_that_drifted_is_left_alone_and_one_put_back_by_hand_is_done() { + let (_tmp, root) = checkout(MODULE, &[]); + let entry = wire(&root, "rack", "2.2.3", UUID); + let read = |file: &str| fs::read_to_string(root.join(file)).unwrap(); + let (gemfile, wired) = (read(GEMFILE), read(GEMFILE_LOCK)); + let kept = |outcome: &RevertOutcome| { + let drifted = |w: &VendorWarning| w.code == "vendor_lock_entry_drifted"; + let pair = [read(GEMFILE), read(GEMFILE_LOCK)]; + outcome.success + && outcome.warnings.iter().any(drifted) + && root.join(".socket/vendor").exists() + && pair[0] == gemfile + }; + // Another gem moved into the section of the patch. + let drifted = wired.replacen( + " rack (2.2.3)\n", + " rack (2.2.3)\n ast (1.0.0)\n", + 1, + ); + fs::write(root.join(GEMFILE_LOCK), &drifted).unwrap(); + assert!(kept(&reverted(&entry, &root).await)); + assert_eq!(read(GEMFILE_LOCK), drifted); + fs::write(root.join(GEMFILE_LOCK), &wired).unwrap(); + // A record that names another gem's line, or more than one line. + for (key, line) in [ + ("checksum", format!("ast (1.0.0) sha256={}", sum('e'))), + ( + "checksum", + format!("rack (2.2.3) sha256={}\n evil (1.0.0)", sum('e')), + ), + ("dependency", "ast".to_string()), + ] { + let mut tampered = entry.clone(); + tampered.wiring[1].original.as_mut().unwrap()[key] = json!(line); + assert!(kept(&reverted(&tampered, &root).await), "{key}: {line}"); + assert_eq!(read(GEMFILE_LOCK), wired, "{key}: {line}"); + } + // Put back by hand: nothing is left to do but to remove the gem. + fs::write(root.join(GEMFILE), GEMFILE_TEXT).unwrap(); + fs::write(root.join(GEMFILE_LOCK), lock()).unwrap(); + let outcome = reverted(&entry, &root).await; + assert!( + outcome.success && outcome.warnings.is_empty(), + "{outcome:?}" + ); + assert!(!root.join(".socket/vendor").exists()); + // One of the two put back by hand: the other goes back by itself, + // and the gem goes. + for by_hand in [GEMFILE, GEMFILE_LOCK] { + let (_tmp, root) = checkout(MODULE, &[]); + let entry = wire(&root, "rack", "2.2.3", UUID); + let before = match by_hand { + GEMFILE => GEMFILE_TEXT.to_string(), + _ => lock(), + }; + fs::write(root.join(by_hand), before).unwrap(); + let outcome = reverted(&entry, &root).await; + assert!( + outcome.success && outcome.warnings.is_empty(), + "{by_hand}: {outcome:?}" + ); + let read = |file: &str| fs::read_to_string(root.join(file)).unwrap(); + assert_eq!( + [read(GEMFILE), read(GEMFILE_LOCK)], + [GEMFILE_TEXT.to_string(), lock()], + "{by_hand}" + ); + assert!(!root.join(".socket/vendor").exists(), "{by_hand}"); + } + } + + /// A committed gem is held to the patch by the files in it. + #[tokio::test] + async fn a_committed_gem_is_held_to_the_files_of_the_patch() { + let patched = b"module Rack\nend\n"; + let record: PatchRecord = serde_json::from_value(json!({ + "uuid": UUID, + "exportedAt": "2026-01-01T00:00:00Z", + "files": { "lib/rack.rb": { + "beforeHash": sum('0'), + "afterHash": crate::hash::git_sha256::compute_git_sha256_from_bytes(patched), + }}, + "vulnerabilities": {}, "description": "", "license": "MIT", "tier": "free", + })) + .unwrap(); + let tmp = tempfile::tempdir().unwrap(); + let archive = tmp.path().join("rack-2.2.3.gem"); + let gem = |source: &[u8]| super::super::tests::make_gem(&[("lib/rack.rb", source)]); + fs::write(&archive, gem(patched)).unwrap(); + assert_eq!(verify(&archive, &record).await, Ok(())); + fs::write(&archive, gem(b"module Rack\n # unpatched\nend\n")).unwrap(); + assert_eq!( + verify(&archive, &record).await, + Err("vendor_hash_mismatch".into()) + ); + fs::write(&archive, b"no gem").unwrap(); + assert_eq!( + verify(&archive, &record).await, + Err("vendor_hash_mismatch".into()) + ); + fs::remove_file(&archive).unwrap(); + assert_eq!( + verify(&archive, &record).await, + Err("vendor_artifact_unreadable".into()) + ); + } +} diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index 569976af4..71ba3784f 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -163,7 +163,11 @@ pub async fn restore( { return Err("the downloaded artifact does not match the recorded size".into()); } - if entry.artifact.path.ends_with(".jar") { + if super::gem::bazel::is_archive(entry) { + if !super::gem::bazel::carries(archive.bytes.clone(), &record.files).await { + return Err("the downloaded gem does not carry the patched files".into()); + } + } else if entry.artifact.path.ends_with(".jar") { // A jar is read by name, case and all, by the JVM: the // installer-shaped strictness of the wheel reader (ASCII names, // no case-colliding pair) refuses obfuscated jars that hold @@ -419,7 +423,8 @@ pub async fn restore( // Likewise a gem vendored as platform gems: only the artifact dir was // swapped in from the stage, and without the uuid dir's own metadata a // `*.so` / `*.bundle` rule drops the prebuilt binaries from the commit. - if entry.ecosystem == "gem" && !entry.gem_platforms.is_empty() { + let archive = super::gem::bazel::is_archive(entry); + if entry.ecosystem == "gem" && (archive || !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 diff --git a/crates/socket-patch-core/src/vendor/refusals.rs b/crates/socket-patch-core/src/vendor/refusals.rs index 59feaff0a..d621e12d0 100644 --- a/crates/socket-patch-core/src/vendor/refusals.rs +++ b/crates/socket-patch-core/src/vendor/refusals.rs @@ -28,7 +28,8 @@ //! it ([`ALLOW_IN_BAZEL_ENV`]) or the lock already names the patch's //! copy: any Composer project (`vendor_composer_bazel_workspace`), and a //! PyPI or RubyGems project whose lock a hub of the workspace reads -//! (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`); +//! (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`), but a gem that +//! can be committed for the hub as its archive ([`gem::bazel`]); //! 8. a Maven jar that only a rules_jvm_external hub of a Bazel workspace //! builds and whose entry cannot be written there (the `maven_bazel_*` //! codes of [`crate::bazel::maven`]), from the same dispatch. diff --git a/crates/socket-patch-core/src/vendor/state.rs b/crates/socket-patch-core/src/vendor/state.rs index 5857af81d..af5c61432 100644 --- a/crates/socket-patch-core/src/vendor/state.rs +++ b/crates/socket-patch-core/src/vendor/state.rs @@ -1283,8 +1283,10 @@ async fn wiring_file_refusal(rec: &WiringRecord, project_root: &Path) -> Option< super::pypi_requirements::ledger_file_refusal(project_root, file).await } // The rest. - "gemfile_line" => one_of(&["Gemfile"]), - "gemfile_lock_spec" | "gemfile_lock_checksum" => one_of(&["Gemfile.lock"]), + "gemfile_line" | super::gem::bazel::GEMFILE_KIND => one_of(&["Gemfile"]), + "gemfile_lock_spec" | "gemfile_lock_checksum" | super::gem::bazel::LOCK_KIND => { + one_of(&["Gemfile.lock"]) + } "cargo_patch_entry" => one_of(&[ super::cargo_manifest::CARGO_TOML, super::cargo_config::CONFIG_TOML, @@ -2801,6 +2803,8 @@ mod tests { ("pypi", "requirements_line", "requirements/dev.txt"), ("gem", "gemfile_line", "Gemfile"), ("gem", "gemfile_lock_spec", "Gemfile.lock"), + ("gem", "gemfile_file_source", "Gemfile"), + ("gem", "gemfile_lock_file_source", "Gemfile.lock"), ("cargo", "cargo_patch_entry", "Cargo.toml"), ("cargo", "cargo_patch_entry", ".cargo/config.toml"), ("cargo", "cargo_lock_entry", "Cargo.lock"), @@ -2838,6 +2842,8 @@ mod tests { ("pypi", "requirements_line", ".socket/vendor/notes.txt"), ("gem", "gemfile_line", "Rakefile"), ("gem", "gemfile_lock_spec", "Gemfile"), + ("gem", "gemfile_file_source", "Gemfile.lock"), + ("gem", "gemfile_lock_file_source", "MODULE.bazel"), ("cargo", "cargo_patch_entry", "build.rs"), ("golang", "go_replace", "main.go"), ("composer", "composer_lock_package", "composer.json"), diff --git a/crates/socket-patch-core/src/vendor/verify.rs b/crates/socket-patch-core/src/vendor/verify.rs index 7cfaf05cf..0e9785611 100644 --- a/crates/socket-patch-core/src/vendor/verify.rs +++ b/crates/socket-patch-core/src/vendor/verify.rs @@ -137,6 +137,10 @@ pub async fn verify_vendored_patch_record( .map_err(|e| e.to_string())??; return super::pypi_distribution::verify_members(&members, &entry.artifact.path, record); } + // A gem committed as its archive, for a Bazel hub. + if super::gem::bazel::is_archive(entry) { + return super::gem::bazel::verify(&artifact, record).await; + } let path_str = artifact.to_string_lossy(); if path_str.ends_with(".jar") { let files = record.files.clone(); @@ -816,7 +820,7 @@ pub(crate) const MAX_HEALTH_HASH_BYTES: u64 = 512 * 1024 * 1024; /// audit with a million planted files. const MAX_INVENTORY_ENTRIES: usize = 10_000; -/// Is this artifact path a single committed FILE (tarball/wheel/nupkg/jar) +/// Is this artifact path a single committed FILE (tarball/wheel/nupkg/jar/gem) /// — whose whole-file drift check is the ledger `sha256` — as opposed to a /// dir-shaped copy whose counterpart is the `fileInventory`? One suffix /// rule shared by the health check, repair's fingerprint fill, and the @@ -829,6 +833,7 @@ pub fn artifact_is_file_shaped(path: &str) -> bool { || norm.ends_with(".zip") || norm.ends_with(".nupkg") || norm.ends_with(".jar") + || super::gem::bazel::archive_path(&norm) } /// Full-file inventory of a dir-shaped artifact: every regular file under diff --git a/crates/socket-patch-core/src/vex/discover/gem.rs b/crates/socket-patch-core/src/vex/discover/gem.rs index 5d6b838da..2f68ef949 100644 --- a/crates/socket-patch-core/src/vex/discover/gem.rs +++ b/crates/socket-patch-core/src/vex/discover/gem.rs @@ -188,13 +188,29 @@ //! `CHECKSUMS` entry for them), so vendored refs never set //! `locked_integrity` — the committed artifact is hashed instead. //! +//! ## Vendored for a Bazel hub (`vendor::gem::bazel`) +//! +//! ```text +//! GEM +//! remote: file:.socket/vendor/gem// +//! specs: +//! () +//! ``` +//! +//! A `GEM` section whose one remote is the directory of a patch under +//! `.socket/vendor/gem`, spelled as that relative `file:` URL, is a +//! vendored reference of the ruby-platform gem under it to the archive +//! committed at `/gems/-.gem`, which is +//! where rules_ruby asks the source for it. The manifest has to give the +//! gem that source, as for a hosted one, and `CHECKSUMS` pins the archive. +//! //! `GIT` / `PLUGIN SOURCE` sections are never Socket wiring and are ignored. use std::collections::{BTreeSet, HashMap}; use super::{ - names_vendor_dir, simple_purl, vendor_ref, vendored_leaf_purl, DiscoverCtx, Discovery, - PatchedRef, DIAG_LOCKFILE_UNPARSEABLE, DIAG_REF_INVALID, DIAG_REF_UNATTRIBUTABLE, + names_vendor_dir, simple_purl, vendor_ref, vendor_uuid_dir, vendored_leaf_purl, DiscoverCtx, + Discovery, PatchedRef, DIAG_LOCKFILE_UNPARSEABLE, DIAG_REF_INVALID, DIAG_REF_UNATTRIBUTABLE, }; use crate::crawlers::ruby_crawler::bundler_loaded_lock_in; use crate::formats::gem::{ @@ -255,7 +271,10 @@ async fn extract_file(ctx: &DiscoverCtx<'_>, file: &str, confirm: bool, out: &mu // One with a section that reads as Socket wiring. let wired = readable && lock.sections.iter().any(|sec| match sec.header { - "GEM" => sec.remotes.iter().any(|r| ctx.hosted_uuid(r).is_some()), + "GEM" => { + let wires = |r: &&str| ctx.hosted_uuid(r).is_some() || names_vendor_dir(r); + sec.remotes.iter().any(wires) + } "PATH" => sec.remotes.iter().any(|r| names_vendor_dir(r)), _ => false, }); @@ -386,7 +405,9 @@ impl ManifestSources { return Err(format!("there is no readable {rel} beside it")); }; let want = match wiring { - Wiring::Hosted { remote, .. } => format!("`source: \"{remote}\"`"), + Wiring::Hosted { remote, .. } | Wiring::Archive { remote, .. } => { + format!("`source: \"{remote}\"`") + } Wiring::Vendored(vref) => format!("`path: \"{}\"`", vref.artifact_rel), }; let mut declared = false; @@ -394,7 +415,8 @@ impl ManifestSources { declared = true; let given = Self::given(text, decl); let ours = match (&given, wiring) { - (Given::Source(url), Wiring::Hosted { remote, .. }) => same_remote(url, remote), + (Given::Source(url), Wiring::Hosted { remote, .. }) + | (Given::Source(url), Wiring::Archive { remote, .. }) => same_remote(url, remote), (Given::Path(dir), Wiring::Vendored(vref)) => { vendor_ref(dir).is_some_and(|v| v.artifact_rel == vref.artifact_rel) } @@ -760,12 +782,19 @@ enum Wiring<'t> { only: Option>, }, Vendored(super::VendorRef), + /// The directory of a patch as a `GEM` section's one remote: the gem + /// is committed there as its archive (module docs, "Vendored for a + /// Bazel hub"). + Archive { + remote: &'t str, + uuid: String, + }, } impl Wiring<'_> { fn uuid(&self) -> &str { match self { - Wiring::Hosted { uuid, .. } => uuid, + Wiring::Hosted { uuid, .. } | Wiring::Archive { uuid, .. } => uuid, Wiring::Vendored(vref) => &vref.uuid, } } @@ -783,6 +812,13 @@ fn hosted_wirings<'t>( blocks: &[(String, String)], out: &mut Discovery, ) -> Vec> { + if let [remote] = sec.remotes.as_slice() { + let uuid = vendor_uuid_dir(remote).filter(|(eco, _)| eco == "gem"); + let uuid = uuid.filter(|(_, uuid)| *remote == format!("file:.socket/vendor/gem/{uuid}/")); + if let Some((_, uuid)) = uuid { + return vec![Wiring::Archive { remote, uuid }]; + } + } for remote in sec.remotes.iter().filter(|r| names_vendor_dir(r)) { out.diag( DIAG_REF_INVALID, @@ -1007,6 +1043,21 @@ fn spec_ref( out.shadow(pin); } } + Wiring::Archive { remote, .. } => { + let archive = format!("{remote}gems/{}-{}.gem", spec.name, spec.version); + let Some(vref) = vendor_ref(&archive).filter(|_| spec.platform.is_none()) else { + out.diag( + DIAG_REF_INVALID, + file, + format!("{at}: {purl} is locked from {remote:?}, which holds no such gem"), + ); + return; + }; + if manifest_confirms(file, &at, coords, wiring, manifest, out) { + let pin = lock.integrity(spec.name, spec.version); + out.push(PatchedRef::vendored(purl, &vref, file, pin)); + } + } Wiring::Vendored(vref) => { let leaf = format!("{}-{}", spec.name, spec.version); if vref.leaf != leaf @@ -1048,7 +1099,7 @@ fn manifest_confirms( // source-pinned, so the lock has to follow the manifest first. let rewire = match wiring { Wiring::Hosted { .. } => "socket-patch scan", - Wiring::Vendored(_) => "socket-patch vendor", + Wiring::Vendored(_) | Wiring::Archive { .. } => "socket-patch vendor", }; let rel = manifest.rel; out.diag( @@ -1376,6 +1427,78 @@ mod tests { assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); } + /// `vendor::gem::bazel`'s pair for a Bazel hub: a `GEM` section whose one + /// remote is the patch's directory as a relative `file:` URL is a + /// vendored reference to the gem committed under it, pinned by + /// `CHECKSUMS`, where the manifest gives the gem that source. Any other + /// spelling of such a remote is none, nor is a platform entry there. + #[tokio::test] + async fn a_gem_section_of_the_patch_s_directory_is_a_vendored_archive() { + let source = format!("file:.socket/vendor/gem/{UUID_A}/"); + let lock = |remote: &str, spec: &str| { + format!( + "GEM\n remote: {remote}\n specs:\n {spec}\n\n\ + GEM\n remote: https://rubygems.org/\n specs:\n puma (6.4.2)\n\n\ + PLATFORMS\n ruby\n\nDEPENDENCIES\n puma\n rack (~> 3.2)!\n\n\ + CHECKSUMS\n rack (3.2.6) sha256={SHA_A}\n\nBUNDLED WITH\n 2.6.9\n" + ) + }; + let declared = |source: &str| { + manifest(&[ + "gem \"puma\"".to_string(), + format!("gem \"rack\", \"~> 3.2\", source: \"{source}\""), + ]) + }; + let p = Project::new(); + p.write("Gemfile", declared(&source)); + p.write("Gemfile.lock", lock(&source, "rack (3.2.6)")); + let out = run(&p).await; + assert_refs( + &out, + &[("pkg:gem/rack@3.2.6", UUID_A, WiringMode::Vendored)], + ); + let r = only(&out); + let archive = vendored_rel(UUID_A, "gems/rack-3.2.6.gem"); + assert_eq!(r.artifact_rel.as_deref(), Some(archive.as_str())); + let pinned = crate::vendor::lock_inventory::LockIntegrity::Sha256Hex(SHA_A.into()); + assert_eq!(r.locked_integrity, Some(pinned)); + assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); + + // A manifest that does not give the gem that source, a platform + // entry, and the directory spelled any other way. + let other = format!("file:.socket/vendor/gem/{UUID_B}/"); + for (gemfile, lock, code) in [ + ( + declared(&other), + lock(&source, "rack (3.2.6)"), + DIAG_REF_UNATTRIBUTABLE, + ), + ( + declared(&source), + lock(&source, "rack (3.2.6-java)"), + DIAG_REF_INVALID, + ), + ( + declared(&source), + lock(&source.replace("file:", "file:./"), "rack (3.2.6)"), + DIAG_REF_INVALID, + ), + ( + declared(&source), + lock(source.trim_end_matches('/'), "rack (3.2.6)"), + DIAG_REF_INVALID, + ), + ] { + let p = Project::new(); + p.write("Gemfile", gemfile); + p.write("Gemfile.lock", &lock); + let out = run(&p).await; + assert!(out.refs.is_empty(), "{lock}: {:#?}", out.refs); + let codes: Vec<&str> = out.diagnostics.iter().map(|d| d.code).collect(); + assert_eq!(codes, [code], "{lock}: {:?}", out.diagnostics); + } + } + /// bundler 2.7 with `lockfile_checksums`: the path gem keeps a BARE /// CHECKSUMS entry; the transitive-gem shape leaves an empty GEM specs /// stanza behind. `./` and a trailing `/` on the remote are tolerated. diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 949a0d26b..dcb0afc47 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2153,7 +2153,7 @@ workspace and that Bazel does not build keeps the matrix at the top. | npm: aspect_rules_js `npm.npm_translate_lock` over a pnpm lock | Supported with `pnpm-workspace.yaml` in the `data` of a hub that runs pnpm 11 or later | Supported | Not supported | Supported | | PyPI: rules_python `pip.parse` over a requirements file | Supported | Not supported | Not supported | Supported | | Go: gazelle `go_deps.from_file` over `go.mod` | Supported | Supported | Not supported | Supported with a hosted or vendored patch | -| RubyGems: rules_ruby `ruby.bundle_fetch` over `Gemfile.lock` | Supported with no `gem_checksums` on the call, or with one written out in the call that does not name the gem or holds it to the patched gem's sha256 | Not supported | Not supported | Supported | +| RubyGems: rules_ruby `ruby.bundle_fetch` over `Gemfile.lock` | Supported with no `gem_checksums` on the call, or with one written out in the call that does not name the gem or holds it to the patched gem's sha256 | Supported with the Bazel release named in `.bazelversion` | Not supported | Supported | | Cargo: rules_rust `crate.from_cargo` over `Cargo.lock` | Supported with `cargo_config` on the hub | Supported | Not supported | Supported with a hosted or vendored patch | | NuGet: rules_csharp `nuget.from_lock` over `packages.lock.json` | Supported with `nuget_config` on the tag | Not supported | Not supported | Supported with no restored copy on the machine | | Composer: a rule of your own that runs `composer install` from `composer.lock` | Supported | Not supported | Not supported | Supported with a hosted patch | @@ -2173,15 +2173,19 @@ exits 0 and leaves a build that fails (the known problems below). What a cell sa - **Not supported**: socket-patch promises nothing about what a Bazel build holds after the mode ran, so do not use it for a package that Bazel builds. In most of these cells the patch does not reach the build, or the build breaks (see the known problems below). - Vendored mode for PyPI, RubyGems and Composer declines instead: the command exits 1 and - writes nothing. For PyPI and RubyGems that is where the call of the row reads a file the + Vendored mode for PyPI and Composer declines instead: the command exits 1 and + writes nothing. For PyPI that is where the call of the row reads a file the run would rewrite ([Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode)), for Composer in every Bazel workspace ([Bazel workspaces: Composer](#bazel-workspaces-composer)). + Vendored mode for RubyGems declines the same way wherever the condition of its cell, or + another one of + [Bazel workspaces: RubyGems vendored mode](#bazel-workspaces-rubygems-vendored-mode), does + not hold. - **Supported**, for VEX: `socket-patch vex` and `--vex` say `not_affected` of a package the Bazel build takes patched, and `affected` of one whose patch Bazel does not build. - [Bazel workspaces: VEX](#bazel-workspaces-vex) has the cases and the limits; a vendored gem - is one of the limits. + [Bazel workspaces: VEX](#bazel-workspaces-vex) has the cases and the limits; a gem vendored + with `--allow-vendored-in-bazel` is one of the limits. - **Supported with a condition**, for VEX: under the condition the cell names, the document says `not_affected` of a package the Bazel build takes patched, and a test holds it to that (for a hosted Maven patch a test without Bazel). It does not say `affected` of a @@ -2223,7 +2227,12 @@ What the table was tested with: the build: with a lock that has none the build takes whatever the patch registry serves. A gem that `gem_checksums` names is left as it is until its entry holds the sha256 of the patched gem, and so is every gem beside a `gem_checksums` that is not written out in the - call: see [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems). + call: see [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems). Vendored mode: + that call with no `gem_checksums` and that lock, with the project at the Bazel root and + the Bazel release in `.bazelversion`; the files it writes were built with Bundler 2.6.9 in + the lock as well, written by hand; + [Bazel workspaces: RubyGems vendored mode](#bazel-workspaces-rubygems-vendored-mode) has + every condition. - **Cargo**: rules_rust 0.75.0 (Bazel 9 and 8) and 0.56.0 (Bazel 7), `crate.from_cargo` with `cargo_lockfile = "//:Cargo.lock"`, `manifests = ["//:Cargo.toml"]` and `cargo_config = "//:.cargo/config.toml"`, and no cargo-bazel lock (`lockfile`). @@ -2295,6 +2304,12 @@ Known problems. In each of these a command exits 0 today and the next Bazel buil `CHECKSUMS` section, keeps the upstream gem. Change the entry by hand to the sha256 of the patched gem (the scan wrote it for the gem in the lock's `CHECKSUMS` section, where the lock has one), or run `socket-patch rollback`. +- **A vendored gem that `gem_checksums` pins, after an undo.** Vendored mode declines such a + gem until the entry holds the sha256 of the patched gem, which you write. No undo puts the + old value back: after `vendor --revert`, `rollback` or `remove` the lock names the upstream + gem again and the build fails on the entry (`Checksum was ... but wanted ...`) until it + holds the upstream sha256 again or is deleted. The undo says so in a warning + (`vendor_gem_bazel_checksum_left`). - **Vendored npm on a hub with `update_pnpm_lock = True`** (measured with pnpm 9 and 10): the pnpm that Bazel runs does not see `.socket/vendor`. Use hosted mode there. - **Hosted npm on such a hub with a pnpm of 11 or later, when hosted mode is told not to @@ -2324,10 +2339,14 @@ In these a command exits 0 and the Bazel build passes on the unpatched package: - **Hosted PyPI, when `pip.parse` takes the requirements of the build's platform from another file** than the one socket-patch rewrote (`requirements_by_platform`, `requirements_linux` and its siblings). +- **RubyGems, where Bazel does not fetch the hub again**: a hub pinned in a vendor directory + (`VENDOR.bazel`) that was made before the patch, and a build with `--nofetch` after an + earlier fetch, keep the gems they have, in every mode. Measured by hand on Bazel 9.3.2; + no test here runs it, and `vex` does not see it. [Bazel workspaces: VEX](#bazel-workspaces-vex) lists what the document says in such cases. -And three that concern neither: +And five that concern neither: - **Vendored Cargo under rules_rust 0.75.0**: a build writes a `BUILD.bazel` into the committed copy, and right after it `vendor --check` exits 1 (`vendor_inventory_mismatch`) @@ -2340,6 +2359,20 @@ And three that concern neither: - **Hosted NuGet prints the access token of the patch in the build's output.** rules_csharp asks the Socket source for every package of the lock, and Bazel prints a warning with that source's URL, the token in it, for each package the source does not hold. +- **Vendored RubyGems and Bundler outside Bazel.** The lock names the committed gem by a + relative `file:` URL, which Bundler by itself does not install from: `bundle install` on a + machine that has not installed the gem fails, and so does every `bundle lock --update`, + until `vendor --revert`. On a machine that installed the gem before the patch, Bundler + keeps that installed copy: `bundle install` passes there and the program runs the + unpatched gem, with no error. The run says both in a warning. Hosted mode serves both + builds. +- **Vendored RubyGems in an output base that fetched the gems before.** Bazel does not watch + the committed gem. When the gem alone changes afterwards (another commit with the same + `Gemfile.lock`, a damaged file), such an output base keeps building what it fetched, never + the changed bytes, until it fetches the hub again: after a change of `Gemfile.lock`, or + after `bazel clean --expunge`. The same holds the other way: an output base that fetched a + damaged gem keeps failing after `repair` put the gem right, until it fetches the hub + again. ## Bazel workspaces: npm @@ -3778,7 +3811,9 @@ and neither ruleset builds from such a file: Both were measured on Bazel 9.3.2, 8.8.2 and 7.7.2, after a `scan --mode vendored` that exited 0 and reported the package vendored. So vendored mode now declines such a package, where the -files of the workspace show that a hub reads the file it would rewrite. +files of the workspace show that a hub reads the file it would rewrite. For a gem it writes +another form there, which rules_ruby builds, and declines only where that form is not known +to build: [Bazel workspaces: RubyGems vendored mode](#bazel-workspaces-rubygems-vendored-mode). **What is read.** The project is in a Bazel workspace by the lookup of [Bazel workspaces: `.bazelignore`](#bazel-workspaces-bazelignore). There socket-patch reads @@ -3869,7 +3904,9 @@ file that your Bazel no longer reads (Bazel 9 never reads it, Bazel 8 only with `--enable_workspace`), or for a `ruby.bundle_fetch` to which you add every file of the vendored gem as `srcs`, which rules_ruby copies beside the Gemfile (no test here builds that). socket-patch checks none of these. It is the switch of -[Bazel workspaces: Composer](#bazel-workspaces-composer). +[Bazel workspaces: Composer](#bazel-workspaces-composer). With it a gem is vendored by its +path, as in every other project, also where the form of the next section would be written +without it. `vendor --revert` is never declined. Neither is a package that is already vendored: where the file that the call names already names the copy of the same patch @@ -3921,6 +3958,132 @@ Limits: [`ruby.rs`](../crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs) run the refusal, the switch and hosted mode on a real Bazel. +## Bazel workspaces: RubyGems vendored mode + +For a gem whose `Gemfile` and lock a `ruby.bundle_fetch` call reads, vendored mode commits +the patched gem as the archive the patch service serves, and names it in the two files as +hosted mode names a patch registry, with a relative `file:` URL in the registry's place: + +``` +gem "rack", "~> 2.2", source: "file:.socket/vendor/gem//" # Gemfile + +GEM # Gemfile.lock + remote: file:.socket/vendor/gem// + specs: + rack (2.2.3) + +DEPENDENCIES + rack (~> 2.2)! + +CHECKSUMS + rack (2.2.3) sha256= + +.socket/vendor/gem//gems/rack-2.2.3.gem # the patched gem +``` + +rules_ruby asks Bazel for `gems/-.gem`. Bazel's server runs in the +root of the workspace and opens the relative URL from there, which Bazel documents nowhere, +and Bundler, in the `bundle install` step of the build, holds the file to the lock's +`CHECKSUMS` line. No file of Bazel's is written, and `MODULE.bazel.lock` stays as it is. The +directory of the patch also holds the marker of the patch and a `.gitignore` (`!*`) and +`.gitattributes` of its own: stock ignore templates name `*.gem`. + +Built on Bazel 9.3.2, 8.8.2 and 7.7.2 with rules_ruby 1.0.0-rc2, and with Bundler 4.0.15 +and 2.6.9 in the lock, which is the Bundler the hub installs and runs: the build is the +patched one on a machine that reaches no patch host, and one changed byte of the committed +gem fails the build of a machine that fetches the hub anew (`Bundler found mismatched +checksums`). By hand, and by no test here: a gem that the `Gemfile` does not declare builds +patched (9.3.2), and a build without the committed gem fails. + +**Where it is written.** Only for a gem whose `Gemfile` or `Gemfile.lock` a call of the hub +names, read as +[Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) +says, and only where each of these holds. All are read from the files of the checkout; no +Bazel is run. Where one does not hold the gem is declined with `vendor_gem_bazel_hub`, +nothing is written, and the message names it: + +- **The checkout names a Bazel release that opens such a URL.** `.bazelversion`, or + `USE_BAZEL_VERSION` in `.bazeliskrc`, names a release of Bazel 7, 8 or 9 other than 9.1.0. + Bazel's own history says that the downloader of 9.1.0 fails on such a URL and that 9.1.1 + and 9.2.0 fixed it (read, not run). A checkout that names no release, or one that is not + three numbers (`latest`, `8.x`), is declined: 9.1.0 may build it, or a release to come. + What the environment of a machine names (`USE_BAZEL_VERSION` in a shell) is not seen. +- **No rc file of the checkout takes the download from Bazel's own downloader.** `.bazelrc` + and the files it imports name none of `--experimental_remote_downloader` (a remote + downloader is handed the URL in the place of Bazel's own), `--repository_disable_download` + and `--vendor_dir` (a hub pinned in a vendor directory keeps the gems it has), however the + option is set, and each of those files can be read. An rc file of the machine or of the + home directory, and the command line, are not seen. +- **The project is the root of the Bazel workspace.** Bazel opens the URL from the root, and + the committed gem lies under the project. +- **The workspace is read with certainty**: its module files are, no `WORKSPACE` file + defines a repository, every `ruby.bundle_fetch` call writes out the files it reads, and a + call that reads the `Gemfile` or the lock of the project reads both. +- **Something holds the gem to its bytes, in the hub of every call that reads the two + files**: the lock has a `CHECKSUMS` section, or the `gem_checksums` of each such call + have an entry for the gem. With neither, any bytes at that path would build in that hub. + `bundle lock --add-checksums` writes the section (Bundler 2.6 or later). `gem_checksums` + have to be written out as a dict of strings. +- **Every `gem_checksums` entry for the gem holds it to the patched gem.** rules_ruby hands + that sha256 to Bazel, which fails the download of any other bytes. An entry for the + upstream gem, in any call that reads the two files, declines the gem once the patched + one is downloaded, and the message names the call, the entry and the sha256 to write + there. socket-patch does not edit the call: write the value, and run the command again. + A dry run downloads no gem, so it cannot see this condition and lists the gem as one the + run would vendor. No undo puts the old value back: after `vendor --revert`, `rollback` or + `remove` the build fails on the entry (`Checksum was ... but wanted ...`) until it holds + the upstream sha256 again or is deleted, and the undo says so in a warning + (`vendor_gem_bazel_checksum_left`). +- **The lock names a Bundler that a hub was built with** (`BUNDLED WITH`): 2.6 or later of + the 2 line, or one of the 4 line. rules_ruby installs the Bundler of the lock in the hub + and runs it there. Built with 2.6.9 and 4.0.15, which both hold the gem to the lock's + `CHECKSUMS` line; an older one, and a lock that names none, is declined. +- **The lock holds the gem as its ruby-platform entry** and not as platform gems. + +Before any of these, the gem meets what vendored mode refuses for every gem +([Ruby gems: gems vendored mode refuses](#ruby-gems-gems-vendored-mode-refuses)): a native +extension, a declaration that cannot be edited and the rest answer as they do outside Bazel. + +**What it costs.** The run says both in a warning (`vendor_gem_bazel_file_source`): + +- **Bundler by itself does not install from that source.** `bundle install` on a machine + that has not installed the gem fails, and so does every `bundle lock --update` (measured + with Bundler 4.0.15). On a machine that installed the gem before the patch, Bundler keeps + that installed copy: `bundle install` passes there and the program runs the unpatched + gem, with no error. The checkout then builds its gems through Bazel only. Hosted mode + serves both builds. A run that vendored nothing but such gems names the Bazel build as + its next step, and no reinstall. +- **Bazel does not watch the committed gem.** An output base that fetched the hub before + keeps building what it fetched when the gem alone changes afterwards, never the changed + bytes. A change of `Gemfile.lock` fetches the hub again, and so does a new output base. + An output base that fetched a damaged gem likewise keeps failing after `repair`, until + it fetches the hub again (`bazel clean --expunge`). + +**The other commands.** A later run passes and writes nothing. `vendor --check` holds the +committed gem to the patch, by its patched files, and to the sha256 of the ledger, and +`repair` downloads it again. `vendor --revert`, `rollback` and `remove` take the source off +the `Gemfile`, put the lock's entry back into its section where Bundler sorts it, with its +`DEPENDENCIES` entry and its `CHECKSUMS` line as they were, and delete the directory of the +patch: byte for byte for a lock whose entries are in Bundler's own order. A file of the two +that names the source nowhere has been put back already, by hand or by git, and the other +goes back by itself. A file that still names it and whose `source:` or `GEM` section is no +longer what the run wrote leaves both alone with the gem (`vendor_lock_entry_drifted`); the +gem's `CHECKSUMS` line is put back as it was whatever it holds by then. A newer patch of the gem takes the source over in place, and a vendored +scan takes over a hosted pin of the gem. `list` and `vex` show the gem as vendored; `vex` +says `not_affected` of it, and the flow below holds that document to the patched build. +`vex` holds the committed gem to its patched files; only `vendor --check` holds it to its +bytes as well, which a fresh build does too. + +With `--allow-vendored-in-bazel` vendored mode writes what it writes in every other project, +the unpacked copy named by its path, which this hub does not build. + +Not covered: `rb_bundle_fetch` in a `WORKSPACE` file, a project below the Bazel root, a gem +locked as platform gems and a lock of a Bundler older than 2.6, which are declined; Windows, +releases of rules_ruby other than 1.0.0-rc2, and a Bundler inside the hub other than 4.0.15 +and 2.6.9, which were not run. +[`ruby.rs`](../crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs) builds the form on a +real Bazel, written by hand and written by the command. + ## Ruby gems: hosted mode `scan --mode hosted` makes Bundler install a patched gem from that patch's own gem source on @@ -4468,12 +4631,14 @@ is patched: the file that points at the copy. rules_python 2.5.0-rc4 takes the path of the line for the name of a project, and the build of everything the hub serves fails (same three releases). A vendored npm tarball is built by rules_js and keeps its statement. So does a - vendored gem, for another reason: rules_ruby builds one only when the call lists every + vendored gem. One committed as its archive for the hub + ([Bazel workspaces: RubyGems vendored mode](#bazel-workspaces-rubygems-vendored-mode)) is + built by rules_ruby. One vendored by its path is built only when the call lists every file of the copy among its `srcs`, which is not read, so nothing is said of it. - Vendored mode declines both by default where the hub reads the file - ([Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode)), - so this is the state of a project vendored with `--allow-vendored-in-bazel` or by an - earlier release. + Vendored mode declines a PyPI package by default where the hub reads the file + ([Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode)) + and writes the path of a gem only with `--allow-vendored-in-bazel`, so these are the + states of a project vendored with that switch or by an earlier release. Each advisory of such a patch gets a statement of the package's own with the status `affected`. It names that package alone under the product, and its `action_statement` says @@ -4571,7 +4736,8 @@ The document and the build are tested to agree on real Bazel 9.3.2, 8.8.2 and aspect_rules_js's `npm.npm_translate_lock(pnpm_lock = "//:pnpm-lock.yaml")` (hosted and vendored), PyPI through rules_python's `pip.parse(requirements_lock = "//:requirements.txt")` (hosted), and RubyGems through rules_ruby's -`ruby.bundle_fetch(gemfile_lock = "//:Gemfile.lock")` without `gem_checksums` (hosted). There +`ruby.bundle_fetch(gemfile_lock = "//:Gemfile.lock")` without `gem_checksums` (hosted, and +vendored as the gem's committed archive). There the build prints the patched package, and the document of the run (`--vex`), of `vex` and of `vex --no-verify` is one `not_affected` statement that names the package and the patch; the first two are the same in a checkout with the same files that Bazel has not built in, and @@ -4607,12 +4773,13 @@ the build is broken): of its own, a file that is not given as a plain string label. And where the line that points at the copy is in a requirements file that the file the call names brings in with `-r`. Measured for PyPI, where the build fails. -- **Vendored mode for RubyGems** beside `ruby.bundle_fetch`. rules_ruby 1.0.0-rc2 runs +- **A gem vendored by its path** beside `ruby.bundle_fetch`. rules_ruby 1.0.0-rc2 runs `bundle install` in a repository that holds the Gemfile, its lock and the files the call lists as `srcs`, so the path of the copy does not exist there unless every file of the copy is listed. Measured on the three releases: the build fails, and the statement still says - `not_affected`. Vendored mode declines such a gem by default, so this is the state of a - project vendored with `--allow-vendored-in-bazel` or by an earlier release. + `not_affected`. Vendored mode writes that form beside such a hub only with + `--allow-vendored-in-bazel`, so this is the state of a project vendored with the switch or + by an earlier release. - **A vendored package whose own files the hub does not read**, while the lock the hub does read still lists the registry's package: a uv or Poetry project vendored through `pyproject.toml` and its lock while `pip.parse` reads a requirements file exported before; diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 01494161d..b97fe7870 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 4042 + "max": 4053 }, "lock-readers": { "paths": [