diff --git a/.github/workflows/bazel-pypi.yml b/.github/workflows/bazel-pypi.yml index cd5198576..381838cab 100644 --- a/.github/workflows/bazel-pypi.yml +++ b/.github/workflows/bazel-pypi.yml @@ -41,7 +41,10 @@ on: # files and decides whether Bazel builds what was patched. Every flow # holds the exact document socket-patch writes about its build, patched # or not, so a change to how a document is built or worded - # starts the legs of every ecosystem. Nothing else that + # starts the legs of every ecosystem. `bazel/` also says which lock a + # hub reads, for the refusal of vendored mode beside such a hub + # (vendor/bazel_hub.rs), which vendor/refusals.rs hands to every + # command. Nothing else that # another ecosystem's flow owns is here, so any other change to one # ecosystem starts that ecosystem's legs only. # @@ -71,9 +74,12 @@ on: - 'crates/socket-patch-core/src/utils/python_lock.rs' - 'crates/socket-patch-core/src/utils/requirements.rs' - 'crates/socket-patch-core/src/vendor/lock_inventory/pypi.rs' + - 'crates/socket-patch-core/src/vendor/pypi.rs' - 'crates/socket-patch-core/src/vendor/pypi_distribution.rs' - 'crates/socket-patch-core/src/vendor/pypi_requirements.rs' - 'crates/socket-patch-core/src/vendor/pypi_wheel.rs' + - 'crates/socket-patch-core/src/vendor/bazel_hub.rs' + - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/vex/discover/pypi_other.rs' - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-core/src/vex/**' @@ -105,9 +111,12 @@ on: - 'crates/socket-patch-core/src/utils/python_lock.rs' - 'crates/socket-patch-core/src/utils/requirements.rs' - 'crates/socket-patch-core/src/vendor/lock_inventory/pypi.rs' + - 'crates/socket-patch-core/src/vendor/pypi.rs' - 'crates/socket-patch-core/src/vendor/pypi_distribution.rs' - 'crates/socket-patch-core/src/vendor/pypi_requirements.rs' - 'crates/socket-patch-core/src/vendor/pypi_wheel.rs' + - 'crates/socket-patch-core/src/vendor/bazel_hub.rs' + - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/vex/discover/pypi_other.rs' - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-core/src/vex/**' diff --git a/.github/workflows/bazel-ruby.yml b/.github/workflows/bazel-ruby.yml index 9ed16999c..bf0b2ffde 100644 --- a/.github/workflows/bazel-ruby.yml +++ b/.github/workflows/bazel-ruby.yml @@ -1,8 +1,8 @@ name: Bazel patch compatibility (RubyGems) -# The RubyGems flow of the real-Bazel tests (`ruby::` in `e2e_bazel_build`): -# hosted mode for a gem that rules_ruby's `ruby.bundle_fetch` reads from -# `Gemfile` and `Gemfile.lock`, on each Bazel release below. +# The RubyGems flows of the real-Bazel tests (`ruby::` in `e2e_bazel_build`): +# hosted and vendored mode for a gem that rules_ruby's `ruby.bundle_fetch` +# reads from `Gemfile` and `Gemfile.lock`, on each Bazel release below. # bazel-compatibility.yml holds the legs and what every ecosystem shares; # this file says when the Ruby legs run and on which releases. # @@ -24,14 +24,18 @@ name: Bazel patch compatibility (RubyGems) on: pull_request: types: [opened, synchronize, reopened, ready_for_review] - # What a pull request run covers: the RubyGems flow and its fixture, the - # harness and the workflows that run it, the Bazel installer and its - # pins, and the RubyGems files that `scan --mode hosted` and `rollback` - # run through in the fixture, each by its own path: the readers of a - # Bundler lock and a Gemfile with the lock half of the hosted rewrite - # (formats/gem), lock discovery, the lock inventory, the Ruby crawler - # (it says which lock Bundler loads), the upstream restore of - # `rollback`, and the stale-install guard that both commands end with. + # What a pull request run covers: the RubyGems flows and their fixture, + # the harness and the workflows that run it, the Bazel installer and its + # pins, and the RubyGems files that `scan --mode hosted`, `rollback`, + # `scan --mode vendored` and `vendor --revert` run through in the + # fixture, each by its own path: the readers of a Bundler lock and a + # Gemfile with the lock half of the hosted rewrite (formats/gem), lock + # 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. # 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 @@ -45,13 +49,13 @@ on: # hosted rewrite is there (`rewrite_gem` and its planner in # patch/redirect/mod.rs, the file of every ecosystem's rewriter), and # so are patch/redirect/grant.rs, hosted/engine.rs and - # commands/scan/hosted.rs, the shared test helpers and the toolchain - # files. vendor/gem.rs is the vendored backend, which the flow only - # borrows two readers of a `gem` line from. A change to one of those + # commands/scan/hosted.rs, the rest of vendored mode (the download from + # the patch service, the ledger, the `vendor` command), the shared test + # helpers and the toolchain files. A change to one of those # gets its run on the push to main (when the file is in the list below) # or in the nightly run, not on the pull request: that is the price of - # not running every ecosystem's legs on every shared change. The flow - # does not run the native extension rebuild of agent mode + # not running every ecosystem's legs on every shared change. No flow + # runs the native extension rebuild of agent mode # (patch/gem_ext.rs, patch/gem_source.rs), which is in neither list. On # demand, workflow_dispatch runs the legs on any branch. paths: @@ -68,6 +72,9 @@ on: - 'crates/socket-patch-core/src/crawlers/ruby_crawler.rs' - '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/bazel_hub.rs' + - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/src/commands/vex*.rs' @@ -76,9 +83,9 @@ on: # The pull request paths, and what only a push to main covers: the # root of the test target (it changes when an ecosystem's module is # added; ci.yml builds the target and runs its hermetic tests on every - # pull request), the vendored backend, the shared engine code and test - # helpers the flow runs through, and the toolchain files. A main push - # outside this list waits for the nightly run below. + # pull request), the shared engine code and test helpers the flows run + # through, and the toolchain files. A main push outside this list waits + # for the nightly run below. paths: - '.github/workflows/bazel-ruby.yml' - '.github/workflows/bazel-compatibility.yml' @@ -93,11 +100,13 @@ on: - 'crates/socket-patch-core/src/crawlers/ruby_crawler.rs' - '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/bazel_hub.rs' + - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/src/commands/vex*.rs' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - - 'crates/socket-patch-core/src/vendor/gem.rs' - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/hosted/**' - 'crates/socket-patch-cli/src/commands/**' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index bc390b2e6..45aed9c43 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; the one refusal it lifts today is `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. The switch is not specific to Composer: any refusal of vendored mode that rests on the Bazel workspace reads this one. For a project whose build does find the copy. Read by `vendor`, `scan --mode vendored` and `get --mode vendored`; other subcommands accept it silently. See docs/ecosystems.md "Bazel workspaces: Composer" | +| `--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" | **`--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,12 +1728,12 @@ 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 | -| 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) | +| 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` | +| 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 | | pypi / pipenv (Pipfile.lock) | (rebuilt wheel) | lock-only: the `default`/`develop` entry → `{file, hashes:[sha256-of-our-wheel]}`. Pipfile + `_meta.hash` untouched. Emits `vendor_integrity_unverified` — pipenv does not hash-check file entries; the committed wheel bytes are the protection — and, when another entry is hashed, `pypi_pipenv_hash_export_unsupported` (`pipenv requirements --hash` drops the vendored wheel's hash) | `pipenv install --deploy` (+ `pipenv verify`), cold cache | -| pypi / requirements.txt (pip / `uv pip`) | (rebuilt wheel) | pin line → `./` (markers carried over; transitive deps appended), plus `--hash=sha256:` only when the requirements tree is already in pip's hash-checking mode (any `--hash` or `--require-hashes`) | `pip install -r` / `uv pip install -r` **run from the project root** (both resolve bare paths against the CWD) | +| pypi / requirements.txt (pip / `uv pip`) | (rebuilt wheel) | pin line → `./` (markers carried over; transitive deps appended), plus `--hash=sha256:` only when the requirements tree is already in pip's hash-checking mode (any `--hash` or `--require-hashes`) | `pip install -r` / `uv pip install -r` **run from the project root** (both resolve bare paths against the CWD). Where a rules_python hub of the project's Bazel workspace reads `requirements.txt` or a file it includes with `-r`, the project is refused `vendor_pypi_bazel_hub` unless the run has `--allow-vendored-in-bazel` | | nuget | deterministically rebuilt `.nupkg` at `..nupkg` (the uuid dir IS a NuGet folder feed; the stale embedded signature is dropped — unsigned is accepted under NuGet's default validation), plus `/.gitignore` (`!*`: re-includes the nupkg against the project's ignores, such as VisualStudio.gitignore's `*.nupkg`); refuses `vendor_artifact_gitignored` when git would still drop it | `nuget.config` source + `packageSourceMapping` for the id (creating the mapping from scratch ALSO fans a `` out to every pre-existing source, including the ones NuGet inherits from the user config and parent directories' configs (v5.0 #354), none at all when an inherited config already maps packages — mapping is exclusive, NU1100 otherwise; another source's exact pattern for the id is set aside in a comment while vendored, `vendor_nuget_mapping_set_aside`, #462) **+** `packages.lock.json` `contentHash` → `base64(sha512(nupkg))` for the entries at the patched version in every lock a project under the root restores into — the root `packages.lock.json`, member projects' locks, `packages..lock.json`, a literal `NuGetLockFilePath` (v5.0 #353/#514; an unevaluable `NuGetLockFilePath` is refused with `vendor_nuget_lock_path_unresolved`) — (`vendor_nuget_no_lockfile` warning when there is none; a lock that also resolves the id at another version is refused with `vendor_nuget_lock_other_version`, nothing written) | `dotnet restore --locked-mode`, cold cache, `--network none` (tampered nupkg fails NU1403) | | maven | the patched `.jar` + the upstream pom (its `` suffixed, and what it inherits from its parents through `${project.version}` declared at the base version between `socket-patch:inherited` markers, so it resolves what the upstream pom does; transitives survive) + `.sha1` sidecars + an ownership marker under `.socket/vendor/maven2///-socket./`; every JVM tree root (`.socket/vendor/maven2`, Gradle's `.socket/vendor/gradle`, Coursier's `.socket/vendor/coursier`) owns a `.gitignore` (`!*`) that re-includes the jars against the project's ignores, such as Java.gitignore's `*.jar`, plus a `.gitattributes` (`-text`); a tree root git ignores itself refuses `vendor_artifact_gitignored` | every pom root, single-module (a reactor of one) or multi-module: the pinned `` + `` pin, `.mvn/maven.config` (`maven.repo.local.tail`) and the `socket-patch-vendor` fallback file repository (`checksumPolicy=fail`); Gradle, sbt and scala-cli roots go to the same JVM backend (ledger ecosystem `jvm`). Pre-v5 `maven_pom_repository` entries (`` to `.socket/vendor/maven/`) are revert-only: vendoring their root is refused (`vendor_jvm_shape_unsupported`, `legacy_maven_root`) | `mvn` build on a fresh checkout with a warm local repository and behind `mirrorOf external:*` (host capstone `e2e_vendor_maven_build` across the Maven matrix) | @@ -2537,6 +2537,7 @@ 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_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. | diff --git a/crates/socket-patch-cli/src/args.rs b/crates/socket-patch-cli/src/args.rs index 2184c23ef..2f1354fcd 100644 --- a/crates/socket-patch-cli/src/args.rs +++ b/crates/socket-patch-cli/src/args.rs @@ -427,11 +427,16 @@ pub struct GlobalArgs { /// Vendored mode (`vendor`, `scan`/`get --mode vendored`): 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; today that is a Composer package + /// a package by default: a Composer package /// (`vendor_composer_bazel_workspace`), whose lock names the copy by a /// path that a Bazel rule running `composer install` in another - /// directory does not find. Pass it when the build does find the - /// copy. Other subcommands accept it silently. + /// directory does not find, and a PyPI or RubyGems package whose lock + /// a rules_python or rules_ruby hub of the workspace reads + /// (`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. #[arg( help_heading = GLOBAL_OPTIONS, long = "allow-vendored-in-bazel", diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs index d77fb6975..a8f49e0a5 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs @@ -172,10 +172,12 @@ //! the same. //! - Bazel would read that file as a package of the user's workspace. The //! crate has a dependency ([`DEP`]), so the file names a repository of -//! the hub, which the main repository does not see, and the commands -//! that analyse every target fail on it: `bazel cquery //...` and -//! `bazel query 'deps(//...)'` ([`analyses`]). The line that the scan -//! wrote into `.bazelignore` keeps the copies out of Bazel's packages: +//! the hub, which the main repository does not see, as it does not see +//! `platforms`, which the file names too. The commands that analyse +//! every target fail on the first of the two that Bazel meets: +//! `bazel cquery //...` and `bazel query 'deps(//...)'` ([`analyses`]). +//! The line that the scan wrote into `.bazelignore` keeps the copies out +//! of Bazel's packages: //! `//...` is the user's own target ([`every_target`]), both commands //! pass, and the build is the patched one, because the hub reads the //! copy by its path, not as a package. A user who comments the line out @@ -872,15 +874,42 @@ fn every_target(cell: &Cell) -> Vec { targets } +/// Whether `stderr` says that the main repository does not see a +/// repository that the build file in the copy names: one of the hub, or +/// `platforms`. Bazel names the first one it meets, and which one that is +/// differs from run to run. The same words about another repository's view +/// are another failure. +fn unseen(stderr: &str) -> bool { + (stderr.split("No repository visible as '@").skip(1)) + .filter_map(|rest| rest.split_once("' from main repository")) + .any(|(repo, _)| { + !repo.contains('\'') && (repo == "platforms" || repo.starts_with("crates__")) + }) +} + +/// [`unseen`] takes the two messages Bazel was seen to print, and neither +/// another repository's name nor another repository's view. +#[test] +fn an_unseen_repository_is_one_the_copy_names_and_the_main_repository_misses() { + let said = |repo: &str, from: &str| { + format!("ERROR: no such package: No repository visible as '@{repo}' from {from}\n") + }; + assert!(unseen(&said("platforms", "main repository"))); + assert!(unseen(&said("crates__dep-1.0.0", "main repository"))); + assert!(!unseen(&said("rules_cc", "main repository"))); + assert!(!unseen(&said("platforms", "repository '@@rules_rust+'"))); + assert!(!unseen("Loading: 0 packages loaded\n")); +} + /// Whether the commands that analyse every target of the checkout of /// `cell` pass: `bazel cquery //...` and `bazel query 'deps(//...)'`, which -/// agree. One that fails has met a repository of the hub, which the main -/// repository does not see. +/// agree. One that fails has met a repository that the build file in the +/// copy names and the main repository does not see ([`unseen`]). fn analyses(cell: &Cell) -> bool { let runs = [("cquery", "//..."), ("query", "deps(//...)")]; let runs = runs.map(|(command, targets)| cell.bazel(command, &[targets])); for run in &runs { - let unseen = run.stderr().contains("No repository visible as '@crates__"); + let unseen = unseen(&run.stderr()); assert_ne!(run.ok(), unseen, "{}: {}", cell.test, run.dump()); } assert_eq!(runs[0].ok(), runs[1].ok(), "{}", cell.test); @@ -1194,8 +1223,9 @@ fn vendored_from_cargo_with_config() { // package: `//...` is the consumer alone, and the commands that analyse // every target pass. A user who comments the line out has the package // back, where the ruleset writes the build file: `//...` names targets - // there, those commands fail on the repository of the dependency, and - // the file Bazel now reads is a change of the copy again. + // there, those commands fail on a repository that the file names and + // the main repository does not see, and the file Bazel now reads is a + // change of the copy again. assert_eq!(every_target(&cell), [CONSUMER], "{test}"); assert!(analyses(&cell), "{test}: under the line of the scan"); cell.write(".bazelignore", DECLINED); diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs index dea1f4b94..758f68df2 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -158,6 +158,26 @@ const ADVISORY: &str = "GHSA-test-aaaa-bbbb"; /// package is affected. pub const NOT_IN_BUILD: &str = "vex_bazel_not_in_build"; +/// The one command of vendored mode. +pub const VENDORED: [&str; 4] = ["scan", "--mode", "vendored", "--yes"]; + +/// The switch that lets vendored mode write for a package it declines +/// because of the project's Bazel workspace, and the variable of the same +/// meaning. +pub const ALLOW: &str = "--allow-vendored-in-bazel"; +pub const ALLOW_ENV: &str = "SOCKET_ALLOW_VENDORED_IN_BAZEL"; + +/// A package that vendored mode declines in a checkout, because a hub of +/// the workspace reads a lock the run would rewrite. +pub struct Declined<'a> { + pub purl: &'a str, + /// The error code of the refusal. + pub code: &'a str, + /// What the refusal has to name beside hosted mode and the switch: the + /// call with its file and line, and the lock. + pub names: &'a [&'a str], +} + /// The mode a flow patched its package in, which a document says after the /// patch id. Or [`How::Unbuilt`]: the patch is in a copy that Bazel does /// not build, and a document says the package is affected. @@ -1111,6 +1131,120 @@ impl Cell { assert_eq!(changed(before, &self.tree()), NOTHING, "{test}"); } + /// For a finished command of vendored mode where it declines + /// `package`: it ended with `exit` and reports the package as its one + /// event, `action` under the code of the refusal, in words that name + /// the call, the lock, hosted mode and the switch. No file of the + /// checkout differs from `before`. + pub fn declined(&self, ran: &Ran, package: &Declined, exit: i32, action: &str, before: &Tree) { + let (test, said) = (&self.test, &ran.dump); + assert_eq!(ran.code, exit, "{test}: {said}"); + let [event] = events(&ran.envelope) else { + panic!("{test}: not one event: {said}"); + }; + let reported = [&event["purl"], &event["action"], &event["errorCode"]]; + let expected = [package.purl, action, package.code]; + assert_eq!(reported, expected, "{test}: {said}"); + let why = event["error"].as_str().or(event["reason"].as_str()); + let why = why.unwrap_or_default(); + let switch = format!("`{ALLOW}`"); + for name in package.names.iter().chain(&["`--mode hosted`", &switch]) { + assert!(why.contains(name), "{test}: no {name:?} in {why:?}"); + } + assert_eq!(changed(before, &self.tree()), NOTHING, "{test}: {said}"); + } + + /// Without a Bazel, in this checkout where a hub reads the lock of + /// `package`: every command that would vendor the package declines it + /// and writes nothing. That is the scan, `get`, `vendor` for a patch + /// the manifest records and, where the package is pinned hosted, the + /// scan that would take the pin over and the `vendor` that would eject + /// it, so the pin stays. A dry run of the scan names the refusal and + /// passes; one of `vendor` fails as its run does. `run` runs + /// `socket-patch` here, with the variables it is given. + pub fn declines_every_vendoring( + &self, + run: impl Fn(&Cell, &[&str], &[(&str, &str)]) -> Ran, + package: &Declined, + ) { + let declines = |args: &[&str], exit: i32, action: &str, before: &Tree| { + let ran = run(self, args, &[]); + self.declined(&ran, package, exit, action, before); + ran + }; + let before = self.tree(); + let get = ["get", package.purl, "--mode", "vendored", "--yes"]; + declines(&VENDORED, 1, "failed", &before); + declines(&get, 1, "failed", &before); + declines( + &[&VENDORED[..], &["--dry-run"]].concat(), + 0, + "skipped", + &before, + ); + + let saved = run(self, &["get", package.purl, "--save-only", "--yes"], &[]); + assert_eq!(saved.code, 0, "{}", saved.dump); + let vendor = [["vendor", "--yes"], ["vendor", "--dry-run"]]; + for vendor in &vendor { + declines(vendor, 1, "failed", &self.tree()); + } + std::fs::remove_dir_all(self.path(".socket")).expect("remove .socket"); + + // The eject is refused whole, before it restores a pin, and so is + // its dry run. + let hosted = run(self, &["scan", "--mode", "hosted", "--yes"], &[]); + assert_eq!(hosted.envelope["summary"]["applied"], 1, "{}", hosted.dump); + let pinned = self.tree(); + assert_ne!(changed(&before, &pinned), NOTHING, "{}", hosted.dump); + declines(&VENDORED, 1, "failed", &pinned); + for eject in &vendor { + let eject = declines(eject, 1, "failed", &pinned); + let refused = &eject.envelope["error"]["code"]; + assert_eq!(*refused, "eject_refused", "{}", eject.dump); + let why = event_for(&eject.envelope, package.purl)["error"].as_str(); + let kept = why.is_some_and(|why| why.starts_with("kept hosted: ")); + assert!(kept, "{}", eject.dump); + } + } + + /// Without a Bazel, in such a checkout: vendored mode goes on when the + /// user says so, with the switch or its variable. A later run without + /// either passes and writes nothing: the lock the hub reads already + /// names the copy of that patch, so the run is in sync, and so is a + /// scan that names no mode, which runs in vendored mode in a vendored + /// project. `vendor --revert` takes no switch: it puts every file back. + pub fn vendors_on_the_users_word( + &self, + run: impl Fn(&Cell, &[&str], &[(&str, &str)]) -> Ran, + package: &Declined, + ) { + let before = self.tree(); + let reverts = |why: &str| { + let undo = run(self, &["vendor", "--revert", "--yes"], &[]); + assert_eq!(undo.code, 0, "{why}: {}", undo.dump); + assert_eq!(changed(&before, &self.tree()), NOTHING, "{why}"); + }; + let vendors = |args: &[&str], env: &[(&str, &str)]| { + let ran = run(self, args, env); + assert_eq!(ran.code, 0, "{}", ran.dump); + assert_eq!(ran.envelope["summary"]["applied"], 1, "{}", ran.dump); + }; + vendors(&VENDORED, &[(ALLOW_ENV, "1")]); + reverts(ALLOW_ENV); + vendors(&[&VENDORED[..], &[ALLOW]].concat(), &[]); + let vendored = self.tree(); + for in_sync in [&VENDORED[..], &["scan", "--yes"]] { + let again = run(self, in_sync, &[]); + let said = &again.dump; + assert_eq!(again.code, 0, "{in_sync:?}: {said}"); + assert_eq!(again.envelope["status"], "success", "{in_sync:?}: {said}"); + assert!(!said.contains(package.code), "{in_sync:?}: {said}"); + assert_eq!(changed(&vendored, &self.tree()), NOTHING, "{in_sync:?}"); + } + reverts(ALLOW); + } + /// `socket-patch ` in the workspace copy, as a user in that /// directory runs it, against the Socket API at `api`. Its home and /// temp directory are the cell's, and every proxy is a closed port, so diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs index 336469dea..357c8e54d 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs @@ -42,14 +42,18 @@ //! id made for the run, so no cache of an earlier run can supply it. The //! flow asserts the VEX document of its patch as `main.rs` says. //! -//! The vendored flow ([`vendored_pip_parse`]) commits the patched wheel and -//! points the package's line of `requirements.txt` at it. rules_python -//! builds no wheel from such a line: the build fails until -//! `vendor --revert` has put the pin back. The flow asserts that; that -//! every form of `vex` meanwhile writes a document that says the package -//! is affected, and names the call of `MODULE.bazel` that reads the file; -//! and that the revert and hosted mode, which the document names, end in -//! the patched build and in a document that says not affected. +//! Vendored mode would commit the patched wheel and point the package's +//! line of `requirements.txt` at it, and rules_python builds no wheel from +//! such a line. So in this checkout, where the hub reads that file, the +//! command declines the package and writes nothing +//! ([`vendored_pip_parse`]): 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 pin back. The flow +//! asserts that; that every form of `vex` meanwhile writes a document that +//! says the package is affected, and names the call of `MODULE.bazel` that +//! reads the file; that the revert brings the unpatched build back; and +//! that hosted mode, which the refusal and the document name, ends in the +//! patched build and in a document that says not affected. //! //! One loopback server stands in for four hosts. The Socket API and the //! patch host answer at their own paths; `pypi.org` (the project pages of @@ -94,8 +98,8 @@ use sha2::{Digest, Sha512}; use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; use crate::harness::{ - cell_without_bazel, changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, - StandIn, Tree, CONSUMER, NOTHING, + cell_without_bazel, changed, fixture_path, rewrite, with_vex, Cell, Claim, Declined, Fixture, + How, Ran, StandIn, Tree, ALLOW, CONSUMER, NOTHING, VENDORED, }; use crate::hosted_memory_common::{read_tree, Patch, ORG}; @@ -571,6 +575,8 @@ struct Vendoring { uuid: String, wheels: [Wheel; 2], patched: Wheel, + /// The route of the patched wheel on the stand-in's patch host. + route: String, /// The record of the patch, as the API serves it. record: Value, } @@ -622,6 +628,7 @@ impl Vendoring { uuid, wheels, patched, + route, record, } } @@ -629,34 +636,56 @@ impl Vendoring { /// `socket-patch ` in `cell`, with the stand-in as the Socket /// API, the patch server and the index's JSON API. fn run(&self, cell: &Cell, args: &[&str]) -> Ran { + self.run_with(cell, args, &[]) + } + + /// [`Vendoring::run`] with the variables `more` as well. + fn run_with(&self, cell: &Cell, args: &[&str], more: &[(&str, &str)]) -> Ran { let origin = self.standin.origin(); let json_api = format!("{origin}/{INDEX}/pypi"); let env = [ ("SOCKET_PATCH_SERVER_URL", origin.as_str()), ("SOCKET_PYPI_JSON_API", json_api.as_str()), ]; - cell.socket_patch(&origin, args, &env) + cell.socket_patch(&origin, args, &[&env[..], more].concat()) } } +/// The code under which vendored mode declines a package whose +/// requirements a hub of the workspace reads. +const DECLINED: &str = "vendor_pypi_bazel_hub"; + +/// The line of the `MODULE.bazel` of `cell` that calls the hub. +fn hub_line(cell: &Cell) -> usize { + let module = String::from_utf8(cell.tree()["MODULE.bazel"].clone()).expect("a text file"); + let above = module.lines().take_while(|line| *line != "pip.parse("); + above.count() + 1 +} + +/// What a refusal of vendored mode has to name in the checkout of `cell`: +/// the hub's call with its line in `MODULE.bazel`, and the file it reads. +fn refusal_names(cell: &Cell) -> [String; 2] { + let call = format!("`pip.parse` (MODULE.bazel:{})", hub_line(cell)); + [call, format!("names {REQUIREMENTS}; ")] +} + /// What `socket-patch` has to name when it says that the package is /// affected: the file that points at the committed wheel, the hub's call /// with its line in the `MODULE.bazel` of `cell`, and the two commands /// that patch what Bazel builds. fn names(cell: &Cell) -> Vec { - let module = String::from_utf8(cell.tree()["MODULE.bazel"].clone()).expect("a text file"); - let above = module.lines().take_while(|line| *line != "pip.parse("); vec![ format!("the line of {REQUIREMENTS} that points at"), - format!("(`pip.parse`, MODULE.bazel:{})", above.count() + 1), + format!("(`pip.parse`, MODULE.bazel:{})", hub_line(cell)), "`socket-patch vendor --revert`, then `socket-patch scan --mode hosted`".to_string(), ] } -/// Vendored mode in the checkout of `cell`, whose `requirements.txt` pins -/// the wheels of `with`: `scan --mode vendored --yes` commits the patched -/// wheel under `.socket/vendor/pypi` and points the package's line of -/// `requirements.txt` at it. The command passes, and with `--vex` it +/// Vendored mode on the user's word in the checkout of `cell`, whose +/// `requirements.txt` pins the wheels of `with` and is read by the hub: +/// `scan --mode vendored --yes --allow-vendored-in-bazel` commits the +/// patched wheel under `.socket/vendor/pypi` and points the package's line +/// of `requirements.txt` at it. The command passes, and with `--vex` it /// writes a document that says the package is affected; so do /// `apply --vex` and `vendor --vex`, and `vex` and `vex --no-verify`. Each /// names the call of `MODULE.bazel` that hands `requirements.txt` to @@ -667,8 +696,10 @@ fn vendors_the_wheel(cell: &Cell, with: &Vendoring) -> Tree { let run = |cell: &Cell, args: &[&str]| with.run(cell, args); let in_run = cell.document("in-run"); - let vendoring = ["scan", "--mode", "vendored", "--yes"]; - let scan = run(cell, &[&vendoring[..], &with_vex(&in_run)].concat()); + let scan = run( + cell, + &[&VENDORED[..], &[ALLOW], &with_vex(&in_run)].concat(), + ); let said = &scan.dump; assert_eq!(scan.code, 0, "{test}: {said}"); assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); @@ -710,20 +741,13 @@ fn vendors_the_wheel(cell: &Cell, with: &Vendoring) -> Tree { vendored } -/// What the document of an affected package tells the user to do, in the -/// checkout of `cell` that vendored mode patched: `vendor --revert` puts -/// every file back as it was in `before`, and `scan --mode hosted --yes` -/// then pins the patch of `with` in `requirements.txt`. Its document and -/// the one of `vex` attest the package, through the pin. -fn reverts_and_pins(cell: &Cell, with: &Vendoring, before: &Tree) { - let test = &cell.test; +/// The second thing the document of an affected package tells the user to +/// do, in the checkout of `cell` whose files `vendor --revert` has put back +/// as they were in `before`: `scan --mode hosted --yes` pins the patch of +/// `with` in `requirements.txt`. Its document and the one of `vex` attest +/// the package, through the pin. +fn pins(cell: &Cell, with: &Vendoring, before: &Tree) { let run = |cell: &Cell, args: &[&str]| with.run(cell, args); - let undo = run(cell, &["vendor", "--revert", "--yes"]); - let said = &undo.dump; - assert_eq!(undo.code, 0, "{test}: {said}"); - assert_eq!(undo.envelope["summary"]["removed"], 1, "{test}: {said}"); - assert_eq!(changed(before, &cell.tree()), NOTHING, "{test}: {said}"); - let claim = Claim::new(PURL, &with.uuid, How::Hosted); let document = cell.document("hosted"); let hosted = ["scan", "--mode", "hosted", "--yes"]; @@ -733,25 +757,43 @@ fn reverts_and_pins(cell: &Cell, with: &Vendoring, before: &Tree) { cell.stands_alone(run, &claim, true); } +/// Vendored mode where it declines: `socket-patch ` in `cell` ends +/// with `exit` and reports the package under [`DECLINED`], as the one event +/// `action`, in words that name the hub's call, the file it reads, hosted +/// mode and the switch. No file of the checkout differs from `before`. +fn declines(cell: &Cell, with: &Vendoring, args: &[&str], exit: i32, action: &str, before: &Tree) { + let names = refusal_names(cell); + let package = Declined { + purl: PURL, + code: DECLINED, + names: &names.each_ref().map(String::as_str), + }; + cell.declined(&with.run(cell, args), &package, exit, action, before); +} + /// Vendored mode beside a hub that reads `requirements.txt`. /// /// - (a) `bazel build` and `bazel run //:consumer` print the unpatched /// marker. -/// - (b) `scan --mode vendored --yes` commits the patched wheel and points -/// the package's line of `requirements.txt` at it -/// ([`vendors_the_wheel`]). The command passes, and it and every other -/// form of `vex` write a document that says the package is affected: -/// each names the call of `MODULE.bazel` that reads the file, and the -/// way out. -/// - (c) The same `bazel build` fails, as the document said it may: -/// rules_python takes the path of that line for the name of a project -/// and leaves the hub without a repository it can name. No build holds -/// the patched wheel, and `vex` says affected again. -/// - (d) What the document says to do ([`reverts_and_pins`]): -/// `vendor --revert` puts every file back, `scan --mode hosted --yes` -/// pins the patch in `requirements.txt`, the same two Bazel commands -/// print the patched marker, and `vex` attests the package as not -/// affected. +/// - (b) `scan --mode vendored --yes` declines the package: it exits 1, +/// names the call of `MODULE.bazel` that reads the file, hosted mode and +/// the switch, writes nothing and downloads no wheel. 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 ([`vendors_the_wheel`]): it commits the patched +/// wheel and points the package's line of `requirements.txt` at it. It +/// passes, and it and every other form of `vex` write a document that +/// says the package is affected: each names the call of `MODULE.bazel` +/// that reads the file, and the way out. The same `bazel build` fails, +/// as the document said it may: rules_python takes the path of that +/// line for the name of a project and leaves the hub without a +/// repository it can name. No build holds the patched wheel, and `vex` +/// says affected again. +/// - (d) What the document says to do: `vendor --revert` puts every file +/// back, and the same two Bazel commands print the unpatched marker +/// again. `scan --mode hosted --yes` then pins the patch in +/// `requirements.txt` ([`pins`]), the two commands print the patched +/// marker, and `vex` attests the package as not affected. #[test] #[ignore = "real Bazel; run with --ignored"] fn vendored_pip_parse() { @@ -768,15 +810,28 @@ fn vendored_pip_parse() { // (a) The unpatched build. let before = cell.builds_unpatched(UNPATCHED); - // (b) Vendored mode commits the wheel, and says it is affected. - let vendored = vendors_the_wheel(&cell, &with); + // (b) The one command of vendored mode: declined, with nothing written + // and nothing of the patch fetched. The same build passes, on the + // upstream package. + declines(&cell, &with, &VENDORED, 1, "failed", &before); + assert_eq!(with.standin.asked(&with.route), 0, "{test}"); + cell.builds_patched(&before, UNPATCHED); - // (c) The build fails on the line that names the committed wheel, and - // changes no file of the checkout. + // (c) On the user's word vendored mode commits the wheel, and says it + // is affected. The build fails on the line that names the committed + // wheel, and changes no file of the checkout: rules_python makes the + // name of a repository from the path, and Bazel takes no such name. A + // console may break the message, so it is compared without white space. + let vendored = vendors_the_wheel(&cell, &with); let build = cell.bazel("build", &[CONSUMER]); - let named = with.patched.filename().replace(['-', '.'], "_"); + let named = format!( + "invalid user-provided repo name 'pip_311__/_socket/vendor/pypi/{}/{}'", + with.uuid.replace('-', "_"), + with.patched.filename().replace(['-', '.'], "_") + ); + let squeezed = |text: &str| text.split_whitespace().collect::(); assert!( - !build.ok() && build.stderr().contains(&named), + !build.ok() && squeezed(&build.stderr()).contains(&squeezed(&named)), "{test}: the build did not fail on the vendored line ({named}):\n{}", build.dump() ); @@ -785,18 +840,22 @@ fn vendored_pip_parse() { let names = names(&cell); cell.stands_alone(run, &Claim::unbuilt(PURL, &with.uuid, &names), true); - // (d) The way out: the undo, then hosted mode, whose pin Bazel builds. - reverts_and_pins(&cell, &with, &before); + // (d) The way out: the undo, which brings the files and the build + // back, then hosted mode, whose pin Bazel builds. + let undo = run(&cell, &["vendor", "--revert", "--yes"]); + cell.undone(&undo, "removed", &before, UNPATCHED); + pins(&cell, &with, &before); let marker = format!("OUT: PATCHED {}", with.uuid); cell.builds(&marker); let claim = Claim::new(PURL, &with.uuid, How::Hosted); cell.stands_alone(run, &claim, true); println!( - "{test}: Bazel {release} built {UNPATCHED:?}, and failed to build after `scan --mode \ - vendored`, while every form of `vex` said the package is affected; after `vendor \ - --revert` and `scan --mode hosted` it built {marker:?}, and `vex` said it is not \ - affected; {:?}", + "{test}: Bazel {release} built {UNPATCHED:?}; `scan --mode vendored` declined \ + ({DECLINED}), wrote nothing, and the build stayed {UNPATCHED:?}; with {ALLOW} it \ + vendored the wheel and the build failed ({named}), while every form of `vex` said the \ + package is affected; after `vendor --revert` it built {UNPATCHED:?} again, and after \ + `scan --mode hosted` {marker:?}, and `vex` said it is not affected; {:?}", started.elapsed() ); } @@ -815,14 +874,16 @@ fn checkout(with: &Vendoring) -> Cell { cell } -/// Without a Bazel: steps (b) and (d) of [`vendored_pip_parse`] in the +/// Without a Bazel: steps (c) and (d) of [`vendored_pip_parse`] in the /// fixture's checkout, where `MODULE.bazel` hands `requirements.txt` to -/// rules_python. Between them, `scan --mode vendored --vex`, `vendor --vex` -/// and `apply --vex` as a person runs them: each passes and writes the -/// document, with the warning on stderr, the line that it wrote a document -/// on stdout, and no error; with `--silent` each passes, writes the -/// document and prints nothing. After them, `vendor --vex` moves the -/// hosted pin into a committed copy again, and says affected again. +/// rules_python, so a vendored run that writes the line has the switch. +/// Between them, `scan --mode vendored --vex`, `vendor --vex` and +/// `apply --vex` as a person runs them, with no switch, since the file +/// already names the copy: each passes and writes the document, with the +/// warning on stderr, the line that it wrote a document on stdout, and no +/// error; with `--silent` each passes, writes the document and prints +/// nothing. After them, `vendor --vex` moves the hosted pin into a +/// committed copy again, and says affected again. #[test] fn a_vendored_wheel_is_affected_beside_a_hub_that_reads_the_requirements() { let with = Vendoring::new(); @@ -842,8 +903,7 @@ fn a_vendored_wheel_is_affected_beside_a_hub_that_reads_the_requirements() { names[0], with.uuid, names[1], names[2] ); let claim = Claim::unbuilt(PURL, &with.uuid, &names); - let scan = ["scan", "--mode", "vendored", "--yes"]; - for command in [&scan[..], &["vendor"], &["apply"]] { + for command in [&VENDORED[..], &["vendor"], &["apply"]] { let loud = [command, &with_vex(&document)].concat(); cell.tells_a_person(&origin, &loud, &env, &document, &claim, &warned); let silent = [&loud[..], &["--silent"]].concat(); @@ -851,12 +911,15 @@ fn a_vendored_wheel_is_affected_beside_a_hub_that_reads_the_requirements() { } assert_eq!(changed(&vendored, &cell.tree()), NOTHING); - reverts_and_pins(&cell, &with, &before); + let undo = with.run(&cell, &["vendor", "--revert", "--yes"]); + assert_eq!(undo.envelope["summary"]["removed"], 1, "{}", undo.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", undo.dump); + pins(&cell, &with, &before); // `vendor` in a checkout of hosted pins commits a copy of each: the // line of `requirements.txt` points at the wheel again. let ejected = cell.document("eject"); - let eject = [&["vendor", "--yes"][..], &with_vex(&ejected)].concat(); + let eject = [&["vendor", "--yes", ALLOW][..], &with_vex(&ejected)].concat(); let eject = with.run(&cell, &eject); assert_eq!(eject.envelope["status"], "success", "{}", eject.dump); cell.wrote_in_run(&eject, &ejected, &claim); @@ -864,11 +927,11 @@ fn a_vendored_wheel_is_affected_beside_a_hub_that_reads_the_requirements() { assert!(line.contains(".socket/vendor/pypi/"), "{line}"); } -/// Without a Bazel: `vendor --vex` in a checkout whose manifest records -/// the patch, as agent mode leaves one. It commits the wheel, points -/// `requirements.txt` at it, and passes; its document says the package is -/// affected and names the call that reads the file, as the scan of -/// [`vendors_the_wheel`] does. +/// Without a Bazel: `vendor --vex` on the user's word in a checkout whose +/// manifest records the patch, as agent mode leaves one. It commits the +/// wheel, points `requirements.txt` at it, and passes; its document says +/// the package is affected and names the call that reads the file, as the +/// scan of [`vendors_the_wheel`] does. #[test] fn a_wheel_vendored_from_a_manifest_is_affected_beside_the_hub() { let with = Vendoring::new(); @@ -879,7 +942,7 @@ fn a_wheel_vendored_from_a_manifest_is_affected_beside_the_hub() { cell.write(".socket/manifest.json", manifest.to_string()); let document = cell.document("vendor"); - let vendor = [&["vendor", "--yes"][..], &with_vex(&document)].concat(); + let vendor = [&["vendor", "--yes", ALLOW][..], &with_vex(&document)].concat(); let vendor = with.run(&cell, &vendor); let line = String::from_utf8_lossy(&cell.tree()[REQUIREMENTS]).into_owned(); assert!( @@ -899,7 +962,8 @@ fn a_wheel_vendored_from_a_manifest_is_affected_beside_the_hub() { /// Without a Bazel: `vex` with a `--manifest-path` in another project /// attests that project, and asks the workspace about the files of that /// project. The checkout holds `svc`, where vendored mode pointed -/// `requirements.txt` at the wheel, and `app`, where the command is run. +/// `requirements.txt` at the wheel on the user's word, and `app`, where the +/// command is run. /// While the hub reads the file of `svc`, the document says the package /// is affected and names that file. While it reads the file of `app`, /// which pins the same release, the wheel of `svc` is attested as @@ -923,7 +987,7 @@ fn a_vendored_wheel_is_judged_by_the_files_of_the_manifest_s_project() { cell.write("MODULE.bazel", module.replace(&own, &label)); }; reads("svc"); - let vendoring = ["scan", "--mode", "vendored", "--yes", "--cwd", "svc"]; + let vendoring = [&VENDORED[..], &[ALLOW, "--cwd", "svc"]].concat(); let scan = with.run(&cell, &vendoring); assert_eq!(scan.envelope["summary"]["applied"], 1, "{}", scan.dump); @@ -943,6 +1007,131 @@ fn a_vendored_wheel_is_judged_by_the_files_of_the_manifest_s_project() { cell.stands_alone(run, &claim, true); } +/// Without a Bazel: in the fixture's checkout, where the hub reads +/// `requirements.txt`, every command that would vendor the package declines +/// it, writes nothing and fetches no wheel. On the user's word vendored +/// mode goes on, and a later run without it passes and writes nothing: the +/// file the hub reads already names the copy. +#[test] +fn every_command_that_would_vendor_declines_beside_a_hub_that_reads_the_requirements() { + let with = Vendoring::new(); + let cell = checkout(&with); + let names = refusal_names(&cell); + let package = Declined { + purl: PURL, + code: DECLINED, + names: &names.each_ref().map(String::as_str), + }; + let run = |cell: &Cell, args: &[&str], env: &[(&str, &str)]| with.run_with(cell, args, env); + let before = cell.tree(); + cell.declines_every_vendoring(run, &package); + assert_eq!(with.standin.asked(&with.route), 0); + let undo = with.run(&cell, &["rollback", "--yes"]); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", undo.dump); + cell.vendors_on_the_users_word(run, &package); +} + +/// Without a Bazel: the refusal is for a run that would write a file a hub +/// reads, and for no other. In a workspace whose hub reads another file, in +/// a project beside the one whose file it reads, and in no workspace at +/// all, vendored mode vendors the package as it did, with no switch. So it +/// does in a Poetry project beside a hub that reads the requirements file +/// exported from its lock: the lock is wired alone, the file the hub reads +/// stays as it is, and a later run passes. Where the file the hub is given +/// is not written out in `MODULE.bazel`, and where `MODULE.bazel` has a +/// byte that is not UTF-8 (Bazel takes such a file, and the call in it is +/// not seen here), the package is declined, and the refusal names the +/// place and the reason. +#[test] +fn vendored_mode_goes_on_where_no_hub_reads_the_requirements() { + let with = Vendoring::new(); + let own = format!("\"//:{REQUIREMENTS}\""); + let module = |cell: &Cell| String::from_utf8(cell.tree()["MODULE.bazel"].clone()).unwrap(); + let vendors = |cell: &Cell, args: &[&str]| { + let scan = with.run(cell, &[&VENDORED[..], args].concat()); + assert_eq!(scan.code, 0, "{}", scan.dump); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{}", scan.dump); + }; + // Another file of the same project. + let cell = checkout(&with); + cell.write( + "MODULE.bazel", + module(&cell).replace(&own, "\"//:requirements_lock.txt\""), + ); + vendors(&cell, &[]); + // The file of another project, and no workspace file at all. + let cell = checkout(&with); + cell.write(&format!("svc/{REQUIREMENTS}"), requirements(&with.wheels)); + vendors(&cell, &["--cwd", "svc"]); + std::fs::remove_file(cell.path("MODULE.bazel")).expect("MODULE.bazel"); + let undo = with.run(&cell, &["vendor", "--revert", "--yes", "--cwd", "svc"]); + assert_eq!(undo.code, 0, "{}", undo.dump); + vendors(&cell, &[]); + // A Poetry project, whose lock is the one file a run points at the + // copy. The hub reads the requirements file exported from it. + let cell = checkout(&with); + let [_, upstream] = &with.wheels; + let poetry = format!( + "[[package]]\nname = \"{NAME}\"\nversion = \"{VERSION}\"\ndescription = \"\"\n\ + optional = false\npython-versions = \">=3.9\"\ngroups = [\"main\"]\nfiles = [\n \ + {{file = \"{}\", hash = \"sha256:{}\"}},\n]\n\n[metadata]\nlock-version = \"2.1\"\n\ + python-versions = \">=3.9\"\ncontent-hash = \"{}\"\n", + upstream.filename(), + upstream.sha256, + upstream.sha256 + ); + cell.write("poetry.lock", poetry); + let project = format!( + "[tool.poetry]\nname = \"demo\"\nversion = \"0.1.0\"\ndescription = \"\"\n\ + authors = []\npackage-mode = false\n\n[tool.poetry.dependencies]\n\ + python = \">=3.9\"\n{NAME} = \"{VERSION}\"\n" + ); + cell.write("pyproject.toml", project); + let before = cell.tree(); + vendors(&cell, &[]); + let vendored = cell.tree(); + assert!(vendored[REQUIREMENTS] == before[REQUIREMENTS]); + let lock = String::from_utf8_lossy(&vendored["poetry.lock"]); + assert!(lock.contains(".socket/vendor/pypi/"), "{lock}"); + for later in [&VENDORED[..], &["scan", "--yes"]] { + let scan = with.run(&cell, later); + assert_eq!(scan.code, 0, "{}", scan.dump); + assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{}", scan.dump); + } + + // A file that is not written out: the hub may read any. + let cell = checkout(&with); + cell.write("MODULE.bazel", module(&cell).replace(&own, "LOCK")); + let unread = format!( + "(MODULE.bazel:{}: the files `pip.parse` names", + hub_line(&cell) + ); + let package = Declined { + purl: PURL, + code: DECLINED, + names: &[&unread, "cannot be read with certainty"], + }; + let before = cell.tree(); + cell.declined(&with.run(&cell, &VENDORED), &package, 1, "failed", &before); + + // A file that cannot be read here: it may hold a call that reads any. + let cell = checkout(&with); + cell.write( + "MODULE.bazel", + [module(&cell).as_bytes(), b"# caf\xe9\n"].concat(), + ); + let package = Declined { + purl: PURL, + code: DECLINED, + names: &[ + "(MODULE.bazel: it cannot be read: it is not UTF-8)", + "cannot be read with certainty", + ], + }; + let before = cell.tree(); + cell.declined(&with.run(&cell, &VENDORED), &package, 1, "failed", &before); +} + /// Without a Bazel: the fixture's directories are those of its table, and /// the workflow runs each release on its era. The fixture holds no /// `requirements.txt`: every era names the one the test writes, which pins 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 6646f9707..adcae9388 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs @@ -1,10 +1,10 @@ -//! Hosted mode for a gem that comes through rules_ruby's +//! Hosted and vendored mode for a gem that comes through rules_ruby's //! `ruby.bundle_fetch(gemfile = "//:Gemfile", gemfile_lock = "//:Gemfile.lock")` //! under Bzlmod, where `MODULE.bazel` gives no `gem_checksums` and //! `Gemfile.lock` has a `CHECKSUMS` section. //! -//! One flow, on the Bazel the run is given ([`FIXTURE`] says which ruleset -//! goes with its release), in a fresh output base: +//! The hosted flow, on the Bazel the run is given ([`FIXTURE`] says which +//! ruleset goes with its release), in a fresh output base: //! //! - (a) `bazel build` and `bazel run //:consumer` print the unpatched //! marker, and Bazel fetched the upstream gem from the stand-in. @@ -34,6 +34,17 @@ //! 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. +//! //! 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 //! fixture's lock therefore holds no sha256 of a gem: it has a placeholder @@ -68,20 +79,25 @@ //! sends the two gems and the patch host to the stand-in. It is there from //! the first build on, and step (c) changes no flag. Bundler itself (the //! `bundler` gem the lock's `BUNDLED WITH` names) is not rewritten and comes -//! from rubygems.org. +//! from rubygems.org. Vendored mode downloads the patched gem itself, from +//! the patch host: the commands of that mode are told that the stand-in is +//! that host (`SOCKET_PATCH_SERVER_URL`). use std::io::Write as _; use std::time::Instant; +use base64::Engine as _; use serde_json::json; -use sha2::{Digest, Sha256}; +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::harness::{ - cell_without_bazel, changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, - StandIn, Tree, CONSUMER, NOTHING, + cell_without_bazel, changed, fixture_path, rewrite, with_vex, Cell, Claim, Declined, Fixture, + How, Ran, StandIn, Tree, ALLOW, CONSUMER, NOTHING, VENDORED, }; -use crate::hosted_memory_common::{read_tree, Patch}; +use crate::hosted_memory_common::{read_tree, Patch, ORG}; /// The sha256 of `bytes` in lowercase hex, as a `Gemfile.lock` and the gem /// index spell a sum. @@ -168,11 +184,34 @@ fn gem(name: &str, source: &str) -> Vec { ]) } +/// The one file of the fixture's gem. +const LIB: &str = "lib/sp_victim.rb"; + +/// What that file holds in the gem whose consumer prints `status` after +/// `OUT: `. +fn source(status: &str) -> String { + format!("module SpVictim\n STATUS = \"{status}\"\nend\n") +} + /// The fixture's gem, with the text its consumer prints after `OUT: `. fn victim(status: &str) -> Vec { - gem( - NAME, - &format!("module SpVictim\n STATUS = \"{status}\"\nend\n"), + gem(NAME, &source(status)) +} + +/// The specification the patch service serves beside a patched gem, which +/// vendored mode keeps in the copy: what RubyGems prints for the one of +/// [`gem`] (`Gem::Specification#to_ruby`). +fn stub() -> String { + format!( + "# -*- encoding: utf-8 -*-\n# stub: {NAME} {VERSION} ruby lib\n\n\ + Gem::Specification.new do |s|\n\ + \x20 s.name = \"{NAME}\".freeze\n\ + \x20 s.version = \"{VERSION}\".freeze\n\ + \x20 s.require_paths = [\"lib\".freeze]\n\ + \x20 s.authors = [\"socket-patch\".freeze]\n\ + \x20 s.files = [\"{LIB}\".freeze]\n\ + \x20 s.summary = \"a test fixture\".freeze\n\ + end\n" ) } @@ -208,67 +247,59 @@ fn gem_route(base: &str, name: &str) -> String { format!("/{base}/gems/{name}-{VERSION}.gem") } -/// The Socket API on `standin`: one free patch of the fixture's gem, granted -/// as the gem `patched`, with the artifact `url` (which hosted mode does not -/// fetch) and the patch registry `index`. -fn grant(standin: &StandIn, uuid: &str, url: &str, index: &str, patched: &[u8]) { - let sum = sha256_hex(patched); - let reference = json!({ - "status": "granted", - "url": url, - "purl": PURL, - "artifacts": [{ "kind": "tarball", "url": url, "integrity": { "sha256": sum } }], - "registryOverride": { - "kind": "rubygems-compact-index", - "indexUrl": index, - "identifiers": { "name": NAME, "version": VERSION, "gemChecksumSha256": sum }, - }, - }); - let patch = Patch { - purl: PURL.to_string(), - uuid: uuid.to_string(), - reference, - }; - standin.api(&[patch]); +/// A sum of `bytes` as a grant spells the one vendored mode holds a +/// download to. +fn sha512_sri(bytes: &[u8]) -> String { + let digest = base64::engine::general_purpose::STANDARD.encode(Sha512::digest(bytes)); + format!("sha512-{digest}") } -/// What a flow serves on its stand-in and builds: the upstream gem and the -/// patched gem, one gem with two texts in its one file, each with an id -/// that is new for every run. The grant names the patch host as production -/// does, with a token and the patch id in the paths of the artifact and of -/// the patch registry. +/// What a flow builds from and patches with: the fixture's two gems as one +/// run has them, and one patch of [`NAME`], on a stand-in. Each gem of +/// [`NAME`] holds an id that is new for every run. struct Served { standin: StandIn, /// The id of the patch. uuid: String, - /// The line the consumer prints from the upstream gem, and from the + /// The line the consumer prints for the upstream gem, and for the /// patched one. unpatched: String, patched: String, upstream_gem: Vec, patched_gem: Vec, neighbour_gem: Vec, - /// The patch registry of the grant, and the routes of the gem on - /// rubygems.org and on that registry. + /// The patch registry of the grant. index: String, + /// The routes of the stand-in for the upstream gem and for the patched + /// one, as Bazel fetches them. upstream_route: String, patched_route: String, + /// The route of the patched gem as vendored mode downloads it. + artifact_route: String, } impl Served { - /// Starts the stand-in, and sends the downloads of `cell`'s Bazel to it. - fn start(cell: &mut Cell) -> Served { - let run = uuid::Uuid::new_v4().to_string(); - let uuid = uuid::Uuid::new_v4().to_string(); - let token = uuid::Uuid::new_v4().to_string(); - let patched_gem = victim(&format!("PATCHED {uuid}")); - let upstream_gem = victim(&format!("PRISTINE {run}")); + /// The stand-in of a flow in `cell`, whose lock then pins the two + /// upstream gems of this run, which only the stand-in has. + /// + /// The grant names the patch host as production does, with a token and + /// the patch id in the paths of its artifacts and of the patch + /// registry: the patched gem and its specification, which vendored + /// mode downloads, and the registry hosted mode writes into the lock. + /// The record of the patch holds the hashes of the file it changes. + /// + /// Bazel's downloads of the fixture's two gems on rubygems.org and of + /// anything on the patch host go to the stand-in, under the route + /// prefix of the host. A URL of the patch host that no rule rewrote is + /// refused, so no download of Bazel's reaches the real one. + fn to(cell: &mut Cell) -> Served { + let [run, uuid, token] = [(); 3].map(|()| uuid::Uuid::new_v4().to_string()); + let (pristine, fixed) = (format!("PRISTINE {run}"), format!("PATCHED {uuid}")); + let (upstream_gem, patched_gem) = (victim(&pristine), victim(&fixed)); let neighbour_gem = neighbour(); let registry = format!("{PATCH_HOST}/patch-registry/gem/{token}/{uuid}"); let index = format!("https://{registry}/"); - let artifact = format!( - "https://{PATCH_HOST}/patch/gem/{NAME}/{VERSION}/{token}/{uuid}/{NAME}-{VERSION}.gem" - ); + let artifacts = format!("/patch/gem/{NAME}/{VERSION}/{token}/{uuid}/{NAME}-{VERSION}"); let (upstream_route, patched_route) = (gem_route(RUBYGEMS, NAME), gem_route(®istry, NAME)); @@ -277,15 +308,56 @@ impl Served { standin.serve(5, &upstream_route, &upstream_gem); standin.serve(5, &gem_route(RUBYGEMS, NEIGHBOUR), &neighbour_gem); standin.serve(5, &patched_route, &patched_gem); - // What `rollback` reads to restore the upstream `CHECKSUMS` line: the - // gem's file of the compact index, one line per version. + // What `rollback` reads to restore the upstream `CHECKSUMS` line: + // the gem's file of the compact index, one line per version. let info = format!("---\n{VERSION} |checksum:{}\n", sha256_hex(&upstream_gem)); standin.serve(5, &format!("/{RUBYGEMS}/info/{NAME}"), info.as_bytes()); - grant(&standin, &uuid, &artifact, &index, &patched_gem); - // Bazel's downloads of the fixture's two gems on rubygems.org and of - // anything on the patch host go to the stand-in, under the route - // prefix of the host. A URL of the patch host that no rule rewrote is - // refused, so no download of Bazel's reaches the real one. + + let sum = sha256_hex(&patched_gem); + let url = |file: &str| format!("https://{PATCH_HOST}{artifacts}.{file}"); + let stub = stub(); + standin.serve(5, &format!("{artifacts}.gem"), &patched_gem); + standin.serve(5, &format!("{artifacts}.gemspec"), stub.as_bytes()); + let reference = json!({ + "status": "granted", + "url": url("gem"), + "purl": PURL, + "artifacts": [{ + "kind": "tarball", + "url": url("gem"), + "integrity": { "sha256": sum, "sha512": sha512_sri(&patched_gem) }, + }, { + "kind": "gem-stub-gemspec", + "url": url("gemspec"), + "integrity": { "sha512": sha512_sri(stub.as_bytes()) }, + }], + "registryOverride": { + "kind": "rubygems-compact-index", + "indexUrl": index, + "identifiers": { "name": NAME, "version": VERSION, "gemChecksumSha256": sum }, + }, + }); + standin.api(&[Patch { + purl: PURL.to_string(), + uuid: uuid.clone(), + reference, + }]); + let hash = |status: &str| compute_git_sha256_from_bytes(source(status).as_bytes()); + let record = json!({ + "uuid": uuid, + "purl": PURL, + "publishedAt": "2026-01-01T00:00:00Z", + "files": { LIB: { "beforeHash": hash(&pristine), "afterHash": hash(&fixed) } }, + "vulnerabilities": { "GHSA-test-aaaa-bbbb": { + "cves": ["CVE-2024-0001"], "summary": "s", "severity": "high", "description": "d", + }}, + "description": "fixture", + "license": "MIT", + "tier": "free", + }); + 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), @@ -293,26 +365,36 @@ impl Served { rewrite(&format!("{PATCH_HOST}/"), &origin), format!("block {PATCH_HOST}"), ]); + cell.write("Gemfile.lock", lock_pinning(&neighbour_gem, &upstream_gem)); Served { standin, - unpatched: format!("OUT: PRISTINE {run}"), - patched: format!("OUT: PATCHED {uuid}"), uuid, + unpatched: format!("OUT: {pristine}"), + patched: format!("OUT: {fixed}"), upstream_gem, patched_gem, neighbour_gem, index, upstream_route, patched_route, + artifact_route: format!("{artifacts}.gem"), } } } -/// `socket-patch ` in `cell`, against `standin`. -fn socket_patch_at(standin: &StandIn, cell: &Cell, args: &[&str]) -> Ran { +/// `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 { let origin = standin.origin(); let rubygems = format!("{origin}/{RUBYGEMS}"); - cell.socket_patch(&origin, args, &[("SOCKET_RUBYGEMS_URL", rubygems.as_str())]) + let env = [&[("SOCKET_RUBYGEMS_URL", rubygems.as_str())], env].concat(); + cell.socket_patch(&origin, args, &env) +} + +/// `text` without its white space: a line a terminal may have wrapped, or a +/// message Bundler broke at the width of its console. +fn squeezed(text: &str) -> String { + text.split_whitespace().collect() } /// The flow of the module docs. @@ -325,6 +407,7 @@ fn hosted_bundle_fetch() { return; }; let release = cell.release().to_string(); + let Served { standin, uuid, @@ -332,17 +415,15 @@ fn hosted_bundle_fetch() { patched, upstream_gem, patched_gem, - neighbour_gem, index, upstream_route, patched_route, - } = Served::start(&mut cell); + .. + } = Served::to(&mut cell); let origin = standin.origin(); - let socket_patch = |cell: &Cell, args: &[&str]| socket_patch_at(&standin, cell, args); + let socket_patch = |cell: &Cell, args: &[&str]| run(&standin, cell, args, &[]); - // (a) The unpatched build. The lock of the checkout pins the two - // upstream gems of this run, which only the stand-in has. - cell.write("Gemfile.lock", lock_pinning(&neighbour_gem, &upstream_gem)); + // (a) The unpatched build, from the upstream gem of this run. let before = cell.builds_unpatched(&unpatched); let upstream_fetches = standin.asked(&upstream_route); assert!( @@ -558,9 +639,9 @@ fn hosted_bundle_fetch_gem_checksums() { return; }; let release = cell.release().to_string(); - let served = Served::start(&mut cell); + let served = Served::to(&mut cell); let standin = &served.standin; - let socket_patch = |cell: &Cell, args: &[&str]| socket_patch_at(standin, cell, args); + let socket_patch = |cell: &Cell, args: &[&str]| run(standin, cell, args, &[]); let (other, upstream, patched) = ( sha256_hex(&served.neighbour_gem), sha256_hex(&served.upstream_gem), @@ -569,11 +650,7 @@ fn hosted_bundle_fetch_gem_checksums() { let files = ["Gemfile", "Gemfile.lock"]; // (a) The unpatched build, with the two upstream gems pinned in the - // lock and in the call. - cell.write( - "Gemfile.lock", - lock_pinning(&served.neighbour_gem, &served.upstream_gem), - ); + // lock, as `Served::to` left it, and in the call. let held = module_pinning(&[(NEIGHBOUR, &other), (NAME, &upstream)]); cell.write("MODULE.bazel", &held); let before = cell.builds_unpatched(&served.unpatched); @@ -646,11 +723,147 @@ fn hosted_bundle_fetch_gem_checksums() { ); } +/// 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. +const DECLINED: Declined = Declined { + purl: PURL, + code: "vendor_gem_bazel_hub", + names: &[ + "`ruby.bundle_fetch` (MODULE.bazel:15)", + "names Gemfile.lock; ", + ], +}; + +/// 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. +/// +/// - (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. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn vendored_bundle_fetch() { + let test = "ruby::vendored_bundle_fetch"; + 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(); + let vendoring = |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); + 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}"); + + // 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() + ); + 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); + + // (d) The undo: every file is the one of before, and so is the build. + let undo = socket_patch(&cell, &["vendor", "--revert", "--yes"]); + cell.undone(&undo, "removed", &before, &served.unpatched); + + // (e) The remedy the refusal names: hosted mode patches the build. + let scan = socket_patch(&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 {:?}; {:?}", + served.unpatched, + DECLINED.code, + before.len(), + served.patched, + started.elapsed() + ); +} + /// Without a Bazel: the fixture in a checkout of its own, with the lock /// that pins the two upstream gems of `served` and `module` as its /// `MODULE.bazel`; `None` leaves the checkout without one, in no Bazel /// workspace. -fn checkout(served: &Served, module: Option<&str>) -> Cell { +fn checkout_with(served: &Served, module: Option<&str>) -> Cell { let cell = cell_without_bazel("9.3.2"); for part in ["common", "e9"] { for (rel, bytes) in read_tree(&fixture_path(FIXTURE.dir).join(part)) { @@ -669,9 +882,96 @@ fn checkout(served: &Served, module: Option<&str>) -> Cell { cell } -/// `text` without its white space: a line a terminal may have wrapped. -fn unspaced(text: &str) -> String { - text.split_whitespace().collect() +/// Without a Bazel: the fixture in a checkout of its own, as it is, whose +/// lock pins the gems of the stand-in that comes with it. +fn checkout() -> (Cell, Served) { + let served = Served::to(&mut cell_without_bazel("9.3.2")); + let module = fixture_path(FIXTURE.dir).join("e9/MODULE.bazel"); + let module = std::fs::read_to_string(module).expect("the fixture's MODULE.bazel"); + (checkout_with(&served, Some(&module)), 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. +#[test] +fn every_command_that_would_vendor_declines_beside_a_hub_that_reads_the_lock() { + let (cell, served) = checkout(); + let standin = &served.standin; + let origin = standin.origin(); + let run = |cell: &Cell, args: &[&str], env: &[(&str, &str)]| { + run( + standin, + cell, + args, + &[&patch_host(&origin)[..], env].concat(), + ) + }; + let module = String::from_utf8(cell.tree()["MODULE.bazel"].clone()).expect("a text file"); + let called = module.lines().nth(14); + assert_eq!(called, Some("ruby.bundle_fetch("), "{}", DECLINED.names[0]); + let before = cell.tree(); + cell.declines_every_vendoring(run, &DECLINED); + assert_eq!(standin.asked(&served.artifact_route), 0); + let undo = run(&cell, &["rollback", "--yes"], &[]); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", undo.dump); + cell.vendors_on_the_users_word(run, &DECLINED); +} + +/// 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 +/// it did, with no switch. Where the files the hub is given are not +/// written out in `MODULE.bazel`, the gem is declined, and the refusal +/// names the call and the reason. +#[test] +fn vendored_mode_goes_on_where_no_hub_reads_the_lock() { + let own = [ + "gemfile = \"//:Gemfile\"", + "gemfile_lock = \"//:Gemfile.lock\"", + ]; + let reads = |cell: &Cell, files: [&str; 2]| { + let module = String::from_utf8(cell.tree()["MODULE.bazel"].clone()).expect("a text file"); + let other = module.replace(own[0], files[0]).replace(own[1], files[1]); + assert_ne!(other, module); + cell.write("MODULE.bazel", other); + }; + let scan = |cell: &Cell, served: &Served| { + let origin = served.standin.origin(); + run(&served.standin, cell, &VENDORED, &patch_host(&origin)) + }; + let vendors = |cell: &Cell, served: &Served| { + let scan = scan(cell, served); + assert_eq!(scan.code, 0, "{}", scan.dump); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{}", scan.dump); + }; + let (cell, served) = checkout(); + reads( + &cell, + [ + "gemfile = \"//svc:Gemfile\"", + "gemfile_lock = \"//svc:Gemfile.lock\"", + ], + ); + vendors(&cell, &served); + let (cell, served) = checkout(); + std::fs::remove_file(cell.path("MODULE.bazel")).expect("MODULE.bazel"); + vendors(&cell, &served); + + // Files that are not written out: the hub may read any. + let (cell, served) = checkout(); + reads(&cell, ["gemfile = GEMFILE", "gemfile_lock = LOCK"]); + let package = Declined { + names: &[ + "(MODULE.bazel:15: the files `ruby.bundle_fetch` names", + "cannot be read with certainty", + ], + ..DECLINED + }; + let before = cell.tree(); + cell.declined(&scan(&cell, &served), &package, 1, "failed", &before); } /// Without a Bazel: steps (b), (d) and (f) of @@ -682,8 +982,8 @@ fn unspaced(text: &str) -> String { /// `MODULE.bazel`, and `rollback` restores them and leaves the call. #[test] fn a_gem_that_the_hub_holds_to_its_upstream_sha256_is_left_alone() { - let served = Served::start(&mut cell_without_bazel("9.3.2")); - let run = |cell: &Cell, args: &[&str]| socket_patch_at(&served.standin, cell, args); + let served = Served::to(&mut cell_without_bazel("9.3.2")); + let run = |cell: &Cell, args: &[&str]| run(&served.standin, cell, args, &[]); let (other, upstream, patched) = ( sha256_hex(&served.neighbour_gem), sha256_hex(&served.upstream_gem), @@ -691,13 +991,13 @@ fn a_gem_that_the_hub_holds_to_its_upstream_sha256_is_left_alone() { ); let hosted = ["scan", "--mode", "hosted", "--yes"]; let files = ["Gemfile", "Gemfile.lock"]; - let plain = checkout(&served, None); + let plain = checkout_with(&served, None); let before = plain.tree(); let scan = run(&plain, &hosted); let plain = plain.pinned_by(&scan, PURL, &served.uuid, &before, &files); let held = module_pinning(&[(NEIGHBOUR, &other), (NAME, &upstream)]); - let cell = checkout(&served, Some(&held)); + let cell = checkout_with(&served, Some(&held)); let before = cell.tree(); let warned = left_alone(&cell, &run(&cell, &hosted), &before); assert_eq!(way_on(&warned), (patched.as_str(), true), "{warned}"); @@ -725,8 +1025,8 @@ fn a_gem_that_the_hub_holds_to_its_upstream_sha256_is_left_alone() { " {PURL}: no lockfile entry pinning it could be rewritten (see the warning below)" ); assert!(stderr.lines().any(|line| line == unpinned), "{said}"); - let warning = unspaced(&format!("Warning: {warned}")); - assert!(unspaced(&stderr).contains(&warning), "{said}"); + let warning = squeezed(&format!("Warning: {warned}")); + assert!(squeezed(&stderr).contains(&warning), "{said}"); assert_eq!(changed(&before, &cell.tree()), NOTHING, "{said}"); // A pin that an earlier release wrote beside the entry stays: the scan @@ -789,8 +1089,8 @@ fn a_gem_that_the_hub_holds_to_its_upstream_sha256_is_left_alone() { /// `MODULE.bazel`. #[test] fn a_call_stands_against_a_gem_only_where_it_may_hold_it() { - let served = Served::start(&mut cell_without_bazel("9.3.2")); - let run = |cell: &Cell, args: &[&str]| socket_patch_at(&served.standin, cell, args); + let served = Served::to(&mut cell_without_bazel("9.3.2")); + let run = |cell: &Cell, args: &[&str]| run(&served.standin, cell, args, &[]); let (upstream, patched) = ( sha256_hex(&served.upstream_gem), sha256_hex(&served.patched_gem), @@ -800,7 +1100,7 @@ fn a_call_stands_against_a_gem_only_where_it_may_hold_it() { let held = module_pinning(&[(NAME, &upstream)]); // A lock that Bundler holds no gem to. - let cell = checkout(&served, Some(&held)); + let cell = checkout_with(&served, Some(&held)); let lock = lock_pinning(&served.neighbour_gem, &served.upstream_gem); let (unchecked, _) = lock.split_once("CHECKSUMS\n").expect("the section"); cell.write( @@ -815,7 +1115,7 @@ fn a_call_stands_against_a_gem_only_where_it_may_hold_it() { let (calls, _) = held.split_once(" gem_checksums = {").expect("the dict"); let unread = format!("{calls} gem_checksums = HELD,\n)\n"); let unread = unread.replace("ruby.bundle_fetch(", "HELD = {}\n\nruby.bundle_fetch("); - let cell = checkout(&served, Some(&unread)); + let cell = checkout_with(&served, Some(&unread)); let before = cell.tree(); let scan = run(&cell, &hosted); let warned = codes_in(&scan.envelope["warnings"]); @@ -829,7 +1129,7 @@ fn a_call_stands_against_a_gem_only_where_it_may_hold_it() { assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", scan.dump); // Nothing stands against the gem: as without a `MODULE.bazel`. - let plain = checkout(&served, None); + let plain = checkout_with(&served, None); let before = plain.tree(); let scan = run(&plain, &hosted); let plain = plain.pinned_by(&scan, PURL, &served.uuid, &before, &files); @@ -838,7 +1138,7 @@ fn a_call_stands_against_a_gem_only_where_it_may_hold_it() { let unheld = std::fs::read_to_string(unheld).expect("the fixture's MODULE.bazel"); for module in [elsewhere, unheld] { assert!(module.contains("ruby.bundle_fetch("), "{module}"); - let cell = checkout(&served, Some(&module)); + let cell = checkout_with(&served, Some(&module)); let before = cell.tree(); let scan = run(&cell, &hosted); let pinned = cell.pinned_by(&scan, PURL, &served.uuid, &before, &files); diff --git a/crates/socket-patch-core/src/bazel/built.rs b/crates/socket-patch-core/src/bazel/built.rs index 6c86baad8..60cefae56 100644 --- a/crates/socket-patch-core/src/bazel/built.rs +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -13,8 +13,10 @@ //! 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. What rules_ruby does with a vendored gem no build has -//! shown, so a vendored gem is not judged. +//! 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. //! //! [`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 @@ -50,8 +52,23 @@ //! rules_js links nothing of the document pnpm 11 keeps for its own //! configuration. //! +//! [`reader`] answers the question vendored mode asks before it writes: +//! does a call of the hub name a file that the run would make point at a +//! copy under `.socket/vendor`? Where [`unbuilt`] says nothing when it is +//! in doubt, this one says so, because there a wrong "no" breaks a build. +//! Every call of the hub counts, also one that may not run, and so does a +//! call of a `WORKSPACE` file that passes one of the hub's files, which is +//! how the older form of the ruleset is called there (`pip_parse`, +//! `rb_bundle_fetch`). And where something of the workspace cannot be read +//! with certainty and a call of the hub may be behind it, the answer is +//! that doubt: the workspace calls the hub, or a file that was read names +//! its ruleset, or the root module file or the `WORKSPACE` file could not +//! be read at all. A file with one byte that is not UTF-8 is such a file, +//! and Bazel builds it. +//! //! Not looked at: what a `--override_repository` or an rc file changes, -//! BUILD files, and hubs of other rulesets. +//! BUILD files, the `.bzl` files a `WORKSPACE` file loads, and hubs of +//! other rulesets. //! //! [`Tags::doubts`]: super::workspace::Tags::doubts @@ -61,8 +78,9 @@ use std::path::{Component, Path}; use aho_corasick::AhoCorasick; -use super::starlark::{Call, Value}; -use super::workspace::{disk, Extension, Repo, Workspace}; +use super::starlark::{Call, File, Value}; +use super::workspace::{disk, Doubt, Extension, Repo, Workspace}; +use super::BazelRoot; use crate::formats::gem::locked_specs; use crate::formats::pnpm::grammar::documents; use crate::formats::pnpm::workspace::lock_text_member_importers; @@ -110,7 +128,8 @@ struct Hub { extension: Extension<'static>, tag: &'static str, /// The attributes that name such a file: a label, or a dict with a - /// label as each key. + /// label as each key. `uv_lock` is one for [`reader`] alone: [`judge`] + /// passes over a call that has it. files: &'static [&'static str], /// The packages a file lists plainly, each as its name and version. lists: fn(&str) -> Vec<(String, String)>, @@ -118,8 +137,8 @@ struct Hub { /// each from that directory: the members of a pnpm workspace. 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 of - /// rules_ruby no build has shown that it does not. + /// points at a copy under `.socket/vendor`: rules_js does, and + /// rules_ruby does when the call lists the files of the copy. builds_vendored: bool, } @@ -158,6 +177,7 @@ const HUBS: [Hub; 3] = [ "requirements_darwin", "requirements_linux", "requirements_windows", + "uv_lock", ], lists: |text| { let lines = logical_lines(text); @@ -218,16 +238,172 @@ pub async fn unbuilt(project: &Path, packages: Vec) -> Vec = parts - .map(|part| part.as_os_str().to_string_lossy()) - .collect(); - judge(&workspace, &parts.join("/"), &read, &packages) + judge(&workspace, &slashed(&root.project), &read, &packages) + }) + .await +} + +/// `path` with `/` between its parts, as Bazel has it on every system. +fn slashed(path: &Path) -> String { + let parts = path.components(); + let parts: Vec<_> = parts + .map(|part| part.as_os_str().to_string_lossy()) + .collect(); + parts.join("/") +} + +/// What stands between vendored mode and the locks of a project +/// ([`reader`]). `Ok`: this call of the hub names one of them, `lock`. +/// `Err`: this is why the files of the workspace are not read with +/// certainty, where a call of the hub that names such a lock may be behind +/// that. +pub type Reader = Result; + +/// The call of the workspace `root` that hands Bazel one of `locks`: files +/// of the project in that workspace, each by its path from the project, +/// which vendored mode would rewrite for a package of `ecosystem` (the type +/// of its purls), or the doubt that leaves that open. A requirements file +/// that a call names hands Bazel each file its `-r` includes reach as +/// well, and is then the file returned. `None` when the +/// calls of the hub are read with certainty and name other files, and when +/// nothing shows that the workspace may call it: no call of the hub and no +/// file that names its ruleset, with a root module file and a `WORKSPACE` +/// file that were read or are not there. +pub async fn reader( + root: &BazelRoot, + ecosystem: &'static str, + locks: Vec, +) -> Option { + let (dir, project) = (root.dir.clone(), slashed(&root.project)); + run_blocking(move || { + let read = |file: &str| lock_text(&dir, file); + reads( + &Workspace::read(&disk(&dir)), + &project, + ecosystem, + &locks, + &read, + ) }) .await } +/// The path from the Bazel root `root` of `file`, a path from its project. +pub(crate) fn from_root(root: &BazelRoot, file: &str) -> String { + below(&slashed(&root.project), file) +} + +/// [`reader`] for the workspace `workspace` and the project in its +/// directory `project` (empty: the root itself), with `read` for the text +/// of a file of the workspace. +fn reads( + workspace: &Workspace, + project: &str, + ecosystem: &str, + locks: &[String], + read: &dyn Fn(&str) -> Option, +) -> Option { + let hub = HUBS.iter().find(|hub| hub.ecosystem == ecosystem)?; + let tags = workspace.tags(&hub.extension, hub.tag); + let tag = format!("{}.{}", hub.extension.name, hub.tag); + let tagged = tags.calls.iter().map(|at| (at.file, at.call, tag.as_str())); + // In a `WORKSPACE` file, the calls that pass one of the hub's files. + let legacy = workspace + .legacy + .as_ref() + .and_then(|read| read.as_ref().ok()); + let passes = |call: &&Call| hub.files.iter().any(|file| call.arg(file).is_some()); + let legacy = legacy.into_iter().flat_map(|(name, file)| { + // `workspace(name = "shop")` makes `@shop//` the main repository + // for the labels of that file. + let main = file.calls.iter().find_map(workspace_name); + let calls = file.calls.iter().filter(passes); + calls.map(move |call| (name.as_str(), call, call.callee.as_str(), main)) + }); + let tagged = tagged.map(|(file, call, name)| (file, call, name, None)); + let mut doubt = tags.doubts.first().cloned(); + let mut called = doubt.is_some(); + for (file, call, name, main) in tagged.chain(legacy) { + called = true; + let own = |lock: &String| locks.iter().any(|own| below(project, own) == *lock); + let named = files(workspace, call, hub.files, main); + // A requirements file that brings one of the locks in with `-r` + // hands the hub that lock as well. + let includes = |lock: &&String| ecosystem == "pypi" && includes_one(lock, &own, read); + let found = named.iter().find(|lock| own(lock)); + if let Some(lock) = found.or_else(|| named.iter().find(includes)) { + return Some(Ok(Unbuilt { + call: name.to_string(), + file: file.to_string(), + line: call.line, + lock: lock.clone(), + })); + } + let written = |file: &&str| { + let value = call.arg(file); + matches!(value, None | Some(Value::Str(_) | Value::Dict(_))) + }; + if doubt.is_none() && (call.unpacks() || !hub.files.iter().all(written)) { + doubt = Some(Doubt { + file: file.to_string(), + line: call.line, + why: format!("the files `{name}` names are not all written out"), + }); + } + } + // What could not be read of the workspace may hide a call of the hub + // where the hub is seen to be called, where a file that was read names + // its ruleset (as a dependency, or by the file of its extension under + // any name of the repository), and where the root module file was not + // read at all. So may a `WORKSPACE` file that could not be read. + let names = |call: &Call| match (call.callee.as_str(), call.arg("name"), call.positional(0)) { + ("bazel_dep", Some(Value::Str(name)), _) => name == hub.extension.module, + ("use_extension", _, Some(Value::Str(file))) => file.ends_with(hub.extension.file), + _ => false, + }; + let named = |(_, file): &(String, File)| file.calls.iter().any(names); + let may = || called || workspace.files.is_empty() || workspace.files.iter().any(named); + let hidden = || workspace.doubts.first().filter(|_| may()); + let unread = || workspace.legacy.as_ref()?.as_ref().err(); + doubt.or_else(|| hidden().or_else(unread).cloned()).map(Err) +} + +/// 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 +/// nothing that can be seen. +fn includes_one( + start: &str, + own: &dyn Fn(&String) -> bool, + read: &dyn Fn(&str) -> Option, +) -> bool { + let mut seen = HashSet::new(); + let mut stack = vec![start.to_string()]; + while let Some(file) = stack.pop() { + if !seen.insert(file.clone()) { + continue; + } + let Some(text) = read(&file) else { + continue; + }; + for include in crate::vendor::pypi_requirements::requirements_includes(&file, &text) { + if own(&include) { + return true; + } + stack.push(include); + } + } + false +} + +/// The name a `workspace(name = ...)` call gives the main repository. +fn workspace_name(call: &Call) -> Option<&str> { + match (call.callee.as_str(), call.arg("name")) { + ("workspace", Some(Value::Str(name))) => Some(name.as_str()), + _ => None, + } +} + /// The most of a lock that is read: the lock of a large pnpm workspace has /// some tens of MiB. A larger file decides nothing. const MAX_LOCK: u64 = 64 << 20; @@ -239,7 +415,7 @@ const MAX_LOCK: u64 = 64 << 20; /// workspace. `None` for that, for what is no file (a directory, which /// Windows does not even open, like any other) or not UTF-8, and for a /// file over [`MAX_LOCK`]. -fn lock_text(root: &Path, file: &str) -> Option { +pub(crate) fn lock_text(root: &Path, file: &str) -> Option { let path = root.join(file); let mut bytes = Vec::new(); let plain = |part| matches!(part, Component::Normal(_)); @@ -287,7 +463,7 @@ fn judge( let mut listed = HashMap::new(); let elsewhere = |call: &Call| call.unpacks() || call.arg("uv_lock").is_some(); for tag in (tags.calls.iter()).filter(|tag| tag.call.whole && !elsewhere(tag.call)) { - for lock in files(workspace, tag.call, hub.files) { + for lock in files(workspace, tag.call, hub.files, None) { for &at in &ours { let package = &packages[at]; let unpatched = match &package.pins { @@ -340,8 +516,15 @@ fn judge( /// The files of the main repository that `call` names under `attributes`, /// each by its path from the Bazel root. An attribute that is not written -/// out as a string, or as a dict with strings as keys, names none. -fn files(workspace: &Workspace, call: &Call, attributes: &[&str]) -> Vec { +/// out as a string, or as a dict with strings as keys, names none. `main` +/// is the name a `WORKSPACE` file gives the main repository, for a call of +/// that file: `@
//` is then the main repository too. +fn files( + workspace: &Workspace, + call: &Call, + attributes: &[&str], + main: Option<&str>, +) -> Vec { let mut labels: Vec<&str> = Vec::new(); for attribute in attributes { match call.arg(attribute) { @@ -352,13 +535,16 @@ fn files(workspace: &Workspace, call: &Call, attributes: &[&str]) -> Vec _ => {} } } - let main = |label: &&str| { - let label = workspace - .label(label) - .filter(|label| label.repo == Repo::Main); - label.map(|label| label.path()) + let ours = |label: &&str| { + let label = workspace.label(label)?; + let ours = match &label.repo { + Repo::Main => true, + Repo::Apparent(repo) => main == Some(repo.as_str()), + Repo::Canonical(_) => false, + }; + ours.then(|| label.path()) }; - labels.iter().filter_map(main).collect() + labels.iter().filter_map(ours).collect() } /// The path from the Bazel root of `file`, a path from the project in the @@ -862,6 +1048,249 @@ use_repo(ruby, "bundle") } } + /// What [`reads`] says of the locks `locks` of the project in + /// `project`, in the workspace of `files`: `call file:line lock`, or + /// `? file:line why` for a doubt. A file whose text starts with + /// [`UNREADABLE`] is one that cannot be read, for the reason after it. + fn reader_of(files: &[(&str, &str)], project: &str, ecosystem: &str, locks: &[&str]) -> String { + let text = |path: &str| files.iter().find(|(name, _)| *name == path); + let workspace = Workspace::read(&|path| match text(path) { + Some((_, text)) => match text.strip_prefix(UNREADABLE) { + Some(why) => Entry::Unreadable(why.to_string()), + None => Entry::Text(text.to_string()), + }, + None => Entry::Absent, + }); + let locks: Vec = locks.iter().map(|lock| lock.to_string()).collect(); + let read = |path: &str| text(path).map(|(_, text)| text.to_string()); + match reads(&workspace, project, ecosystem, &locks, &read) { + Some(Ok(by)) => format!("{} {}:{} {}", by.call, by.file, by.line, by.lock), + Some(Err(doubt)) => format!("? {}:{} {}", doubt.file, doubt.line, doubt.why), + None => String::new(), + } + } + + /// The shop with `new` in the place of `old` in its root module. + fn shop_with(old: &str, new: &str) -> Vec<(&'static str, &'static str)> { + let root = ROOT.replace(old, new); + assert_ne!(root, ROOT, "{old}"); + with("MODULE.bazel", Box::leak(root.into_boxed_str())) + } + + const UNREADABLE: &str = "unreadable: "; + const PIP: &str = " requirements_lock = \"//api:requirements.txt\",\n"; + const UNWRITTEN: &str = "the files `pip.parse` names are not all written out"; + + /// A call of the hub that names a file vendored mode would rewrite is + /// found, under each attribute, and a project whose files no call + /// names has none. + #[test] + fn the_call_that_reads_a_lock_of_the_project_is_found() { + let pypi = |project, locks: &[&str]| reader_of(&SHOP, project, "pypi", locks); + let api = "pip.parse MODULE.bazel:15 api/requirements.txt"; + assert_eq!(pypi("api", &["requirements.txt"]), api); + assert_eq!(pypi("api", &["base.txt", "./requirements.txt"]), api); + let darwin = "pip.parse MODULE.bazel:20 tools/requirements_darwin.txt"; + assert_eq!( + pypi("tools", &["uv.lock", "requirements_darwin.txt"]), + darwin + ); + let gem = |project, locks: &[&str]| reader_of(&SHOP, project, "gem", locks); + let lock = "ruby.bundle_fetch billing/ruby.MODULE.bazel:2 billing/Gemfile.lock"; + assert_eq!(gem("billing", &["Gemfile", "Gemfile.lock"]), lock); + let gemfile = "ruby.bundle_fetch billing/ruby.MODULE.bazel:2 billing/Gemfile"; + assert_eq!(gem("billing", &["Gemfile"]), gemfile); + // A call that may not run counts, and so does a `uv_lock`. + let looped = "[pip.parse(requirements_lock = \"//api:requirements.txt\") for v in V]\n"; + let files = shop_with( + "pip.parse(\n hub_name = \"pypi\",", + &format!("{looped}pip.parse("), + ); + let looped = "pip.parse MODULE.bazel:15 api/requirements.txt"; + assert_eq!( + reader_of(&files, "api", "pypi", &["requirements.txt"]), + looped + ); + let files = shop_with(PIP, " uv_lock = \"//api:uv.lock\",\n"); + let uv = "pip.parse MODULE.bazel:15 api/uv.lock"; + assert_eq!(reader_of(&files, "api", "pypi", &["uv.lock"]), uv); + + // Other files of the project, another project, a file of another + // repository, another ecosystem, and one without a hub. + assert_eq!(pypi("api", &["requirements-dev.txt", "uv.lock"]), ""); + assert_eq!(pypi("mobile", &["requirements.txt"]), ""); + assert_eq!(pypi("", &["requirements.txt"]), ""); + assert_eq!(pypi("api/worker", &["requirements.txt"]), ""); + let files = shop_with( + "\"//api:requirements.txt\"", + "\"@other//api:requirements.txt\"", + ); + assert_eq!(reader_of(&files, "api", "pypi", &["requirements.txt"]), ""); + assert_eq!(gem("api", &["requirements.txt"]), ""); + assert_eq!(reader_of(&SHOP, "api", "cargo", &["requirements.txt"]), ""); + } + + /// A requirements file a call names that brings a lock of the project + /// in with `-r`, directly or through another include, hands the hub + /// that lock: the call is found, with the file it names. An include + /// that reaches no lock of the project, or a Gemfile, is not. + #[test] + fn a_hub_file_that_includes_a_lock_of_the_project_is_found() { + let parent = "api/requirements.txt"; + let mut files = with(parent, "-r requirements/all.txt\n"); + files.push(("api/requirements/all.txt", "-r ../base.txt\n-r dev.txt\n")); + files.push(("api/requirements/dev.txt", "-r all.txt\n")); + let api = "pip.parse MODULE.bazel:15 api/requirements.txt"; + assert_eq!(reader_of(&files, "api", "pypi", &["base.txt"]), api); + let all = ["requirements/all.txt"]; + assert_eq!(reader_of(&files, "api", "pypi", &all), api); + assert_eq!(reader_of(&files, "api", "pypi", &["other.txt"]), ""); + let mut files = with("billing/Gemfile.lock", "-r Gemfile.other\n"); + files.push(("billing/Gemfile", "-r Gemfile.other\n")); + assert_eq!(reader_of(&files, "billing", "gem", &["Gemfile.other"]), ""); + } + + /// Where the workspace calls the hub and what a call names cannot be + /// read, the answer is the doubt, for every project. A doubt of a + /// workspace that does not call the hub is none. + #[test] + fn a_hub_that_is_not_read_with_certainty_is_a_doubt() { + let pypi = |files: &[(&str, &str)], project| { + reader_of(files, project, "pypi", &["requirements.txt"]) + }; + let unwritten = format!("? MODULE.bazel:15 {UNWRITTEN}"); + for argument in [" requirements_lock = LOCK,\n", " **COMMON\n"] { + let files = shop_with(PIP, argument); + assert_eq!(pypi(&files, "api"), unwritten, "{argument}"); + assert_eq!(pypi(&files, "mobile"), unwritten, "{argument}"); + // A call that names a lock of the project is the answer all + // the same. + let darwin = "pip.parse MODULE.bazel:20 tools/requirements_darwin.txt"; + let named = reader_of(&files, "tools", "pypi", &["requirements_darwin.txt"]); + assert_eq!(named, darwin, "{argument}"); + } + // The proxy is handed on: other calls of the hub may be made. + let handed = with( + "MODULE.bazel", + Box::leak(format!("{ROOT}print(pip)\n").into_boxed_str()), + ); + let said = "? MODULE.bazel:31 `pip` is used other than to call a tag"; + assert_eq!(pypi(&handed, "mobile"), said); + assert_eq!( + pypi(&handed, "api"), + "pip.parse MODULE.bazel:15 api/requirements.txt" + ); + assert_eq!(reader_of(&handed, "mobile", "gem", &["Gemfile"]), ""); + + // A file of the workspace is missing: it may hold a call of the + // Python hub, which is called, and one of the Ruby hub, which is + // not seen while the root names its ruleset. + let missing: Vec<_> = SHOP + .into_iter() + .filter(|(name, _)| !name.ends_with("ruby.MODULE.bazel")) + .collect(); + let hidden = "? billing/ruby.MODULE.bazel:0 it does not exist; MODULE.bazel:30 includes it"; + assert_eq!(pypi(&missing, "mobile"), hidden); + let gem = reader_of(&missing, "billing", "gem", &["Gemfile", "Gemfile.lock"]); + assert_eq!(gem, hidden); + } + + /// A file that cannot be read may hold a call of a hub that no file + /// shows. Bazel builds one with a byte that is not UTF-8, so the answer + /// is a doubt where the root module file or the `WORKSPACE` file is + /// such a file, and where another is while a file that was read names + /// the ruleset. A doubt of a workspace that names neither ruleset is + /// none. + #[test] + fn a_file_that_cannot_be_read_may_hold_a_call_of_the_hub() { + let asked = |files: &[(&str, &str)], ecosystem| { + reader_of(files, "svc", ecosystem, &["requirements.txt", "Gemfile"]) + }; + let unread = "unreadable: it is not UTF-8"; + let why = "it cannot be read: it is not UTF-8"; + let root = [("MODULE.bazel", unread)]; + for ecosystem in ["pypi", "gem"] { + assert_eq!(asked(&root, ecosystem), format!("? MODULE.bazel:0 {why}")); + } + // An included file, under a root that names the Python ruleset: as + // a dependency, or by the file of its extension under a name that + // the unread file gives the repository. + let include = "include(\"//py:deps.MODULE.bazel\")\n"; + let said = format!("? py/deps.MODULE.bazel:0 {why}; MODULE.bazel:2 includes it"); + for names in [ + "bazel_dep(name = \"rules_python\", version = \"2.5.0-rc4\")\n", + "pip = use_extension(\"@py//python/extensions:pip.bzl\", \"pip\")\n", + ] { + let root = format!("{names}{include}"); + let files = [ + ("MODULE.bazel", root.as_str()), + ("py/deps.MODULE.bazel", unread), + ]; + assert_eq!(asked(&files, "pypi"), said, "{names}"); + assert_eq!(asked(&files, "gem"), "", "{names}"); + } + let neither = "bazel_dep(name = \"rules_go\", version = \"0.65.0\")\n"; + let root = format!("{neither}{include}"); + let files = [ + ("MODULE.bazel", root.as_str()), + ("py/deps.MODULE.bazel", unread), + ]; + assert_eq!( + (asked(&files, "pypi"), asked(&files, "gem")), + Default::default() + ); + // The `WORKSPACE` file, beside a `MODULE.bazel` that is read or + // alone. + let module = ("MODULE.bazel", "module(name = \"shop\")\n"); + for files in [ + vec![module, ("WORKSPACE.bazel", unread)], + vec![("WORKSPACE", unread)], + ] { + let said = format!("? {}:0 {why}", files.last().unwrap().0); + for ecosystem in ["pypi", "gem"] { + assert_eq!(asked(&files, ecosystem), said); + } + } + } + + /// A call of a `WORKSPACE` file that passes one of the hub's files is + /// a call of the ruleset's older form, with or without a `MODULE.bazel`. + #[test] + fn a_workspace_file_that_names_the_lock_counts() { + let legacy = "load(\"@rules_python//python:pip.bzl\", \"pip_parse\")\n\ + pip_parse(\n name = \"pypi\",\n requirements_lock = \"//svc:requirements.txt\",\n)\n\ + rb_bundle_fetch(name = \"bundle\", gemfile = \"//svc:Gemfile\", gemfile_lock = LOCK)\n\ + http_archive(name = \"x\", requirements = \"//other:requirements.txt\")\n"; + for files in [with("WORKSPACE", legacy), vec![("WORKSPACE.bazel", legacy)]] { + let name = files.last().unwrap().0; + let asked = + |project, ecosystem, locks: &[&str]| reader_of(&files, project, ecosystem, locks); + let pip = format!("pip_parse {name}:2 svc/requirements.txt"); + assert_eq!(asked("svc", "pypi", &["requirements.txt"]), pip); + assert_eq!(asked("other", "pypi", &["requirements.txt"]), ""); + let gemfile = format!("rb_bundle_fetch {name}:6 svc/Gemfile"); + assert_eq!(asked("svc", "gem", &["Gemfile", "Gemfile.lock"]), gemfile); + let doubt = + format!("? {name}:6 the files `rb_bundle_fetch` names are not all written out"); + assert_eq!(asked("other", "gem", &["Gemfile", "Gemfile.lock"]), doubt); + } + // A file that calls neither says nothing of them. + let rule = "http_archive(name = \"x\", urls = [LOCK])\n"; + let files = [("WORKSPACE", rule)]; + assert_eq!(reader_of(&files, "svc", "pypi", &["requirements.txt"]), ""); + // The name the file gives the main repository names it in a label + // of that file; without that call the label is another + // repository's. + let call = + "pip_parse(name = \"pypi\", requirements_lock = \"@shop//svc:requirements.txt\")\n"; + let named = format!("workspace(name = \"shop\")\n{call}"); + let files = [("WORKSPACE", named.as_str())]; + let pip = "pip_parse WORKSPACE:2 svc/requirements.txt"; + assert_eq!(reader_of(&files, "svc", "pypi", &["requirements.txt"]), pip); + let files = [("WORKSPACE", call)]; + assert_eq!(reader_of(&files, "svc", "pypi", &["requirements.txt"]), ""); + } + #[test] fn a_project_is_in_the_directory_of_a_lock_or_below_it_or_neither() { for (project, lock, from) in [ diff --git a/crates/socket-patch-core/src/vendor/bazel_hub.rs b/crates/socket-patch-core/src/vendor/bazel_hub.rs new file mode 100644 index 000000000..cde62bcc7 --- /dev/null +++ b/crates/socket-patch-core/src/vendor/bazel_hub.rs @@ -0,0 +1,532 @@ +//! PyPI and RubyGems vendored mode for a project whose lock a Bazel hub +//! reads: declined unless the user allows it. +//! +//! 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 +//! makes the lock name the patched copy by a path under `.socket/vendor`, +//! and neither ruleset builds from that. rules_python 2.5.0-rc4 makes the +//! name of a repository from the path of a requirements line (`invalid +//! user-provided repo name 'pip_311__/_socket/vendor/pypi/...'`). +//! rules_ruby 1.0.0-rc2 runs `bundle install` in a repository that holds +//! the Gemfile and its lock and not the copy (`The path ... does not +//! exist.`). Either fails the build of everything the hub serves, after a +//! command that exited 0 (Bazel 9.3.2, 8.8.2 and 7.7.2). +//! +//! Which lock a hub reads is in the files of the workspace +//! ([`crate::bazel::built::reader`]), so the refusal is for a package whose +//! run may write a file that one reads and for no other. The requirements +//! files of a project count as one set there, since a file the hub reads +//! can bring in the rewritten one with `-r`. A project +//! beside a workspace whose calls name other files is vendored as it is +//! without Bazel, and so is a package whose run leaves the file the hub +//! reads alone: one of a Poetry or PDM project, whose lock is wired alone, +//! beside a hub that reads the requirements file exported from it +//! ([`super::pypi::hub_files`]). Where the files of the workspace cannot be +//! read with certainty and a call of the hub may be behind that, the +//! package is declined as well. Going on there can break a build; +//! declining costs a vendored run that the user's word brings back. +//! +//! What is declined is the write of that path into the lock the hub reads. +//! A package that this lock already names by the copy of the same patch is +//! let through: the run adds nothing to what the hub reads, so a project +//! that was vendored before (by an earlier release, or with the flag) keeps +//! passing its in-sync runs. Where the reading is in doubt no lock is known +//! to be the hub's, and nothing is let through. + +use std::path::Path; + +use crate::bazel::built::{from_root, lock_text, reader, Unbuilt}; +use crate::bazel::workspace::Doubt; +use crate::bazel::BazelRoot; +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::vendor::path::vendor_uuid_dir_rel; +use crate::vendor::refusals::ALLOW_IN_BAZEL_ENV; + +/// The codes of [`refusals`], one per ecosystem. +pub const PYPI_CODE: &str = "vendor_pypi_bazel_hub"; +pub const GEM_CODE: &str = "vendor_gem_bazel_hub"; + +/// The PyPI and RubyGems `candidates` (`(purl, uuid)` pairs) that vendored +/// mode declines in the project at `project`, each with its code and the +/// detail. It declines a package whose hub may read a file of the project +/// that the run would rewrite, unless the user allowed it +/// ([`ALLOW_IN_BAZEL_ENV`]), and lets through a package the hub's lock +/// already names by the copy of that patch. Nothing is declined outside a +/// Bazel workspace ([`crate::bazel::bazel_root`]). Read-only, and it starts +/// no program. +pub async fn refusals<'a>( + project: &Path, + candidates: &[(&'a str, &str)], +) -> Vec<(&'a str, &'static str, String)> { + refusals_unless(project, candidates, env_flag(ALLOW_IN_BAZEL_ENV)).await +} + +/// 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)>; + +/// 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. +const GEM_HOSTED: &str = " where its call passes no `gem_checksums`"; + +/// [`refusals`] for a user who `allowed` it or did not. +async fn refusals_unless<'a>( + project: &Path, + candidates: &[(&'a str, &str)], + allowed: bool, +) -> Vec<(&'a str, &'static str, String)> { + let mut refused = Vec::new(); + // The code, the type of the purls, the ruleset, and what its hosted + // pin takes. + let hub = |purl: &str| match Ecosystem::from_purl(purl)? { + Ecosystem::Pypi => Some((PYPI_CODE, "pypi", "rules_python", "")), + Ecosystem::Gem => Some((GEM_CODE, "gem", "rules_ruby", GEM_HOSTED)), + _ => None, + }; + if allowed || !candidates.iter().any(|(purl, _)| hub(purl).is_some()) { + return refused; + } + let dir = project.to_path_buf(); + let Some(root) = run_blocking(move || crate::bazel::bazel_root(&dir)).await else { + return refused; + }; + // What stands in the way of each list of files, asked once per list. + let mut asked: Vec<(_, Standing)> = Vec::new(); + for (purl, uuid) in candidates { + let Some((code, purls, ruleset, hosted)) = hub(purl) else { + continue; + }; + // The files a hub can be given that the run for this package would + // point at a copy. With none, no hub stands in its way. + let locks = match Ecosystem::from_purl(purl) { + Some(Ecosystem::Pypi) => super::pypi::hub_files(project, purl).await, + Some(Ecosystem::Gem) => [super::gem::GEMFILE, super::gem::GEMFILE_LOCK] + .map(String::from) + .to_vec(), + _ => continue, + }; + if locks.is_empty() { + continue; + } + let list = (purls, locks); + let at = match asked.iter().position(|(of, _)| *of == list) { + Some(at) => at, + None => { + let stands = standing(&root, purls, ruleset, hosted, list.1.clone()).await; + asked.push((list, stands)); + asked.len() - 1 + } + }; + let Some((detail, lock)) = &asked[at].1 else { + continue; + }; + // A lock names the copy of a patch by the copy's directory, outside + // a comment (`#` starts one in each of these files). + let copy = vendor_uuid_dir_rel(purls, uuid).map(|dir| format!("{dir}/")); + let names = |lock: &Option| match (lock, ©) { + (Some(lock), Some(copy)) => { + let names = |line: &str| line.split('#').next().is_some_and(|l| l.contains(copy)); + lock.lines().any(names) + } + _ => false, + }; + let mut wired = names(lock); + // The first file a call names says nothing of a second one. Another + // file of the list that a call names, or may name where the reading + // is in doubt, stands in the way when it holds the package and not + // by the copy (a `uv.lock` locked again beside a vendored + // requirements file): the run would rewrite it. One that cannot be + // read may hold it. + let name = purl + .rsplit('/') + .next() + .and_then(|rest| rest.split('@').next()); + let squash = |text: &str| text.to_ascii_lowercase().replace(['_', '.'], "-"); + let name = squash(name.unwrap_or_default()); + let holds = |text: &Option| match text { + Some(text) => squash(text).contains(&name), + None => true, + }; + let files = &asked[at].0 .1; + let several = wired && files.len() > 1; + for file in files.iter().filter(|_| several) { + if !wired { + break; + } + if reader(&root, purls, vec![file.clone()]).await.is_some() { + let (dir, file) = (root.dir.clone(), from_root(&root, file)); + let text = run_blocking(move || lock_text(&dir, &file)).await; + wired = names(&text) || !holds(&text); + } + } + if !wired { + refused.push((*purl, code, detail.clone())); + } + } + 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`. +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? { + Ok(Unbuilt { + call, + file, + line, + lock, + }) => { + let reads = + format!("`{call}` ({file}:{line}) of the Bazel workspace at {at} names {lock}"); + // 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) + } + Err(Doubt { file, line, why }) => { + let line = match line { + 0 => String::new(), + line => format!(":{line}"), + }; + let reads = format!( + "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) + } + }; + 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)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + const UUID: &str = "11111111-1111-4111-8111-111111111111"; + const OTHER_UUID: &str = "33333333-3333-4333-8333-333333333333"; + + /// A checkout whose root `MODULE.bazel` is `module`, canonical, with + /// the files `files`. + fn checkout(module: &str, files: &[(&str, &str)]) -> (tempfile::TempDir, std::path::PathBuf) { + let tmp = tempfile::tempdir().unwrap(); + let root = fs::canonicalize(tmp.path()).unwrap(); + let all = [ + (".git/HEAD", "ref: refs/heads/main\n"), + ("MODULE.bazel", module), + ]; + 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) + } + + const HUBS: &str = r#"pip = use_extension("@rules_python//python/extensions:pip.bzl", "pip") +pip.parse(hub_name = "pypi", python_version = "3.11", requirements_lock = "//api:base.txt") +ruby = use_extension("@rules_ruby//ruby:extensions.bzl", "ruby") +ruby.bundle_fetch(name = "bundle", gemfile = "//api:Gemfile", gemfile_lock = "//api:Gemfile.lock") +"#; + + /// The refusal of one package of `ecosystem` in `project`, for a user + /// who `allowed` it or did not: its code and detail. + async fn asked( + project: &Path, + ecosystem: Ecosystem, + allowed: bool, + ) -> Option<(&'static str, String)> { + let purl = format!("pkg:{}/x@1.0.0", ecosystem.cli_name()); + let refused = refusals_unless(project, &[(&purl, UUID)], allowed).await; + refused.into_iter().map(|(_, code, why)| (code, why)).next() + } + + async fn declined(project: &Path, ecosystem: Ecosystem) -> (&'static str, String) { + asked(project, ecosystem, false).await.unwrap_or_default() + } + + #[tokio::test] + async fn a_project_whose_lock_a_hub_reads_is_declined_and_no_other() { + let requirements = ("api/requirements.txt", "-r base.txt\nidna==3.7\n"); + let (_tmp, root) = checkout(HUBS, &[requirements, ("web/requirements.txt", "")]); + let (api, web) = (root.join("api"), root.join("web")); + let shown = without_verbatim_prefix(root.clone()); + let at = format!("of the Bazel workspace at {} names", shown.display()); + // The requirements file the hub is given is one the project's own + // brings in; the Gemfile and its lock are the project's. + for (ecosystem, code, names) in [ + ( + Ecosystem::Pypi, + PYPI_CODE, + [ + "`pip.parse` (MODULE.bazel:2)", + "names api/base.txt; ", + "and rules_python fails the build", + ], + ), + ( + Ecosystem::Gem, + GEM_CODE, + [ + "`ruby.bundle_fetch` (MODULE.bazel:4)", + "names api/Gemfile.lock; ", + "and rules_ruby fails the build", + ], + ), + ] { + let (declined, detail) = declined(&api, ecosystem).await; + assert_eq!(declined, code); + let named = [&at, "`--mode hosted`", "`--allow-vendored-in-bazel`"]; + let mut named = named.iter().chain(&names); + assert!(named.all(|part| detail.contains(part)), "{detail}"); + // The user's word lifts it, and a project whose files no call + // names is not declined: one beside it, and the root. + assert_eq!(asked(&api, ecosystem, true).await, None); + assert_eq!(asked(&web, ecosystem, false).await, None); + assert_eq!(asked(&root, ecosystem, false).await, None); + } + // No other ecosystem has such a hub. + for other in [Ecosystem::Npm, Ecosystem::Composer, Ecosystem::Cargo] { + assert_eq!(asked(&api, other, false).await, None, "{other:?}"); + } + // The Gemfile alone is a file the run rewrites, and hosted mode is + // named with what rules_ruby builds of it. + let alone = HUBS.replace(", gemfile_lock = \"//api:Gemfile.lock\"", ""); + fs::write(root.join("MODULE.bazel"), alone).unwrap(); + let (code, detail) = declined(&api, Ecosystem::Gem).await; + assert_eq!(code, GEM_CODE); + let named = [ + "names api/Gemfile; ", + "that rules_ruby fetches where its call passes no `gem_checksums`, or pass", + ]; + assert!(named.iter().all(|part| detail.contains(part)), "{detail}"); + let (_, detail) = declined(&api, Ecosystem::Pypi).await; + assert!( + detail.contains("that rules_python fetches, or pass"), + "{detail}" + ); + // Without the workspace file nothing is declined. + fs::remove_file(root.join("MODULE.bazel")).unwrap(); + assert_eq!(asked(&api, Ecosystem::Pypi, false).await, None); + assert_eq!(asked(&api, Ecosystem::Gem, false).await, None); + } + + /// A package that the lock the hub reads already names by the copy of + /// the same patch is let through: the run adds nothing to what the hub + /// reads. A package whose patch that lock does not name is declined, + /// and so is one whose copy is named only in a comment or only in + /// another file than the one the call names, and every package of a + /// hub that is in doubt. + #[tokio::test] + async fn a_package_the_hub_s_lock_already_names_by_the_patch_s_copy_is_let_through() { + let (_tmp, root) = checkout(HUBS, &[("api/requirements.txt", "-r base.txt\n")]); + let api = root.join("api"); + let (wheel, other, gem) = ("pkg:pypi/a@1.0.0", "pkg:pypi/c@2.0.0", "pkg:gem/b@1.0.0"); + let candidates = [(wheel, UUID), (other, OTHER_UUID), (gem, UUID)]; + let declined = || async { + let refused = refusals_unless(&api, &candidates, false).await; + refused + .into_iter() + .map(|(purl, _, _)| purl) + .collect::>() + }; + let line = format!("./.socket/vendor/pypi/{UUID}/a-1.0.0-py3-none-any.whl # a==1.0.0\n"); + let path = format!("PATH\n remote: .socket/vendor/gem/{UUID}/b-1.0.0\n"); + let gemfile = path.replace("remote:", "gem 'b', path:"); + fs::write(api.join("base.txt"), &line).unwrap(); + fs::write(api.join("Gemfile"), &gemfile).unwrap(); + fs::write(api.join("Gemfile.lock"), &path).unwrap(); + assert_eq!(declined().await, [other]); + // The other file the call names is read too: a Gemfile that cannot + // be read may hold the gem by the registry. + fs::remove_file(api.join("Gemfile")).unwrap(); + assert_eq!(declined().await, [other, gem]); + fs::write(api.join("Gemfile"), &gemfile).unwrap(); + // The lock is read as a file of the workspace is: one that is a + // link out of the Bazel root lets nothing through. + #[cfg(unix)] + { + let outside = tempfile::tempdir().unwrap(); + let named = outside.path().join("base.txt"); + fs::write(&named, &line).unwrap(); + fs::remove_file(api.join("base.txt")).unwrap(); + std::os::unix::fs::symlink(&named, api.join("base.txt")).unwrap(); + assert_eq!(declined().await, [wheel, other]); + fs::remove_file(api.join("base.txt")).unwrap(); + } + // Named in a comment, the copy is not what the lock installs. + fs::write(api.join("base.txt"), format!("a==1.0.0 # was {line}")).unwrap(); + assert_eq!(declined().await, [wheel, other]); + // Named by the Gemfile alone: the lock is the file the call names + // first, and it still holds the registry's gem. + fs::write(api.join("Gemfile.lock"), "GEM\n specs:\n b (1.0.0)\n").unwrap(); + assert_eq!(declined().await, [wheel, other, gem]); + // A hub whose file is not written out: no lock is known to be its. + fs::write(api.join("base.txt"), &line).unwrap(); + let unwritten = HUBS.replace("\"//api:base.txt\"", "LOCK"); + fs::write(root.join("MODULE.bazel"), unwritten).unwrap(); + assert_eq!(declined().await, [wheel, other, gem]); + // A second file that the hub reads: the uv lock, locked again + // beside the vendored requirements file. It holds the package by + // the registry's wheel, so the run would rewrite it. + let both = "\"//api:base.txt\", uv_lock = \"//api:uv.lock\""; + fs::write( + root.join("MODULE.bazel"), + HUBS.replace("\"//api:base.txt\"", both), + ) + .unwrap(); + let entry = + |source: &str| format!("[[package]]\nname = \"a\"\nversion = \"1.0.0\"\n{source}"); + fs::write(api.join("uv.lock"), entry("")).unwrap(); + assert_eq!(declined().await, [wheel, other, gem]); + // Held by the copy there too, or not held at all: let through. + let copy = format!("source = {{ path = \".socket/vendor/pypi/{UUID}/a.whl\" }}\n"); + fs::write(api.join("uv.lock"), entry(©)).unwrap(); + assert_eq!(declined().await, [other, gem]); + fs::write(api.join("uv.lock"), "").unwrap(); + assert_eq!(declined().await, [other, gem]); + // A second attribute that is not written out may name the uv lock: + // it is read as one the call names. (The hub names the vendored + // requirements file itself here: `-r base.txt` would hold `a`.) + fs::write(api.join("requirements.txt"), &line).unwrap(); + let unwritten = "\"//api:requirements.txt\", requirements_by_platform = PLATFORMS"; + fs::write( + root.join("MODULE.bazel"), + HUBS.replace("\"//api:base.txt\"", unwritten), + ) + .unwrap(); + fs::write(api.join("uv.lock"), entry("")).unwrap(); + assert_eq!(declined().await, [wheel, other, gem]); + fs::write(api.join("uv.lock"), entry(©)).unwrap(); + assert_eq!(declined().await, [other, gem]); + } + + /// A requirements file the hub reads that brings the project's own in + /// with `-r` hands the hub every file the run would write: declined. + #[tokio::test] + async fn a_hub_file_that_includes_the_project_s_requirements_is_declined() { + let hub = HUBS.replace("//api:base.txt", "//api:all.txt"); + let files = [ + ("api/all.txt", "-r requirements.txt\n"), + ("api/requirements.txt", "x==1.0.0\n"), + ]; + let (_tmp, root) = checkout(&hub, &files); + let (code, detail) = declined(&root.join("api"), Ecosystem::Pypi).await; + assert_eq!(code, PYPI_CODE); + assert!(detail.contains("names api/all.txt; "), "{detail}"); + // Without the include, the hub reads a file the run leaves alone. + fs::write(root.join("api/all.txt"), "y==1.0.0\n").unwrap(); + assert_eq!(asked(&root.join("api"), Ecosystem::Pypi, false).await, None); + } + + /// The uv lock of the project is a file a hub can be given, and a hub + /// whose files are not written out declines every project of its + /// ecosystem that a run would write, with the place and the reason. + #[tokio::test] + async fn a_uv_lock_counts_and_a_hub_that_cannot_be_read_declines() { + let uv = HUBS.replace( + "requirements_lock = \"//api:base.txt\"", + "uv_lock = \"//api:uv.lock\"", + ); + let (_tmp, root) = checkout(&uv, &[("api/uv.lock", "")]); + let (code, detail) = declined(&root.join("api"), Ecosystem::Pypi).await; + assert_eq!(code, PYPI_CODE); + assert!(detail.contains("names api/uv.lock; "), "{detail}"); + + let unwritten = HUBS.replace("\"//api:base.txt\"", "LOCK"); + let web = ("web/requirements.txt", ""); + let (_tmp, root) = checkout(&unwritten, &[web]); + let (code, detail) = declined(&root.join("web"), Ecosystem::Pypi).await; + assert_eq!(code, PYPI_CODE); + let named = [ + "cannot be read with certainty, so a call of rules_python may name a lock of this \ + project (MODULE.bazel:2: the files `pip.parse` names are not all written out); ", + "`--mode hosted`", + "`--allow-vendored-in-bazel`", + ]; + assert!(named.iter().all(|part| detail.contains(part)), "{detail}"); + // The doubt is about the Python hub alone. + assert_eq!(asked(&root.join("web"), Ecosystem::Gem, false).await, None); + // A file the root includes is missing: the doubt is about a file. + let included = format!("{HUBS}include(\"//api:more.MODULE.bazel\")\n"); + let (_tmp, root) = checkout(&included, &[]); + let (_, detail) = declined(&root.join("web"), Ecosystem::Gem).await; + assert!( + detail.contains("(api/more.MODULE.bazel: it does not exist"), + "{detail}" + ); + } + + /// The requirements file a hub reads is one the run writes where it is + /// what is wired, and where it names the package beside a uv, Pipenv or + /// Python lock. A Poetry or PDM lock is wired alone: the package of + /// such a project is not declined beside a hub that reads the + /// requirements file exported from the lock, whatever the hub's files + /// leave open. Nor is a package the requirements file beside a uv lock + /// does not name. + #[tokio::test] + async fn a_package_whose_run_leaves_the_hub_s_file_alone_is_not_declined() { + let hub = HUBS.replace("//api:base.txt", "//api:requirements.txt"); + let (_tmp, root) = checkout(&hub, &[("api/requirements.txt", "x==1.0.0\n")]); + let api = root.join("api"); + let pypi = || async { + let asked = asked(&api, Ecosystem::Pypi, false).await; + asked.map(|(code, _)| code) + }; + assert_eq!(pypi().await, Some(PYPI_CODE)); + let unwritten = hub.replace("\"//api:requirements.txt\"", "LOCK"); + for lock in ["poetry.lock", "pdm.lock"] { + fs::write(api.join(lock), "").unwrap(); + assert_eq!(pypi().await, None, "{lock}"); + fs::write(root.join("MODULE.bazel"), &unwritten).unwrap(); + assert_eq!(pypi().await, None, "{lock}, a hub in doubt"); + fs::write(root.join("MODULE.bazel"), &hub).unwrap(); + // But for a hosted pin of the requirements file: a run that + // takes it over restores the line the hub reads. + let hosted = "x @ https://h/x-1.0.0-py3-none-any.whl\n"; + fs::write(api.join("requirements.txt"), hosted).unwrap(); + assert_eq!(pypi().await, Some(PYPI_CODE), "{lock}, a hosted pin"); + fs::write(api.join("requirements.txt"), "x==1.0.0\n").unwrap(); + fs::remove_file(api.join(lock)).unwrap(); + } + // A uv or Pipenv lock is wired with the pin of the requirements + // file, also one that hosted mode made or an earlier patch. + for lock in ["uv.lock", "Pipfile.lock"] { + fs::write(api.join(lock), "").unwrap(); + let vendored = format!("./.socket/vendor/pypi/{OTHER_UUID}/x-1.0.0-py3-none-any.whl\n"); + for names in [ + "x==1.0.0\n", + "x @ https://h/x-1.0.0-py3-none-any.whl\n", + &vendored, + ] { + fs::write(api.join("requirements.txt"), names).unwrap(); + assert_eq!(pypi().await, Some(PYPI_CODE), "{lock}: {names}"); + } + fs::write(api.join("requirements.txt"), "y==1.0.0\n").unwrap(); + assert_eq!(pypi().await, None, "{lock}"); + fs::remove_file(api.join(lock)).unwrap(); + } + } +} diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 2948d5da0..0151109a7 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -138,8 +138,8 @@ use crate::formats::gem::{ is_plain_gem_token, listed_specs, split_checksum_entry, split_entry, GemfileLock, }; -const GEMFILE: &str = "Gemfile"; -const GEMFILE_LOCK: &str = "Gemfile.lock"; +pub(super) const GEMFILE: &str = "Gemfile"; +pub(super) const GEMFILE_LOCK: &str = "Gemfile.lock"; /// Wiring-record discriminators (`key` is the gem name for all three). /// diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 90742bbb8..8d38a2ca4 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -48,6 +48,7 @@ pub mod path; pub mod state; +pub mod bazel_hub; #[cfg(any(test, feature = "test-fixtures"))] pub(crate) mod berry_zip; mod bun_binary; diff --git a/crates/socket-patch-core/src/vendor/pypi.rs b/crates/socket-patch-core/src/vendor/pypi.rs index 4010f649f..e0adf56e9 100644 --- a/crates/socket-patch-core/src/vendor/pypi.rs +++ b/crates/socket-patch-core/src/vendor/pypi.rs @@ -1609,6 +1609,51 @@ fn sibling_lock(flavor: PypiFlavor) -> Option<(&'static str, &'static str)> { } } +/// The files of the project that a vendored run for `purl` may point at the +/// patched copy and that a hub of a Bazel workspace can be given +/// ([`super::bazel_hub`]), each by its path from the project. `uv.lock` +/// where it governs. The requirements files where they are what is wired, +/// and where they name the package beside a uv, Pipenv or Python lock, +/// which is wired together with a pin of theirs +/// ([`super::pypi_requirements::sibling_names_package`]). Beside a Poetry +/// or PDM lock, which is wired alone, only where they hold the package by a +/// URL: that is a hosted pin, which a run that takes it over restores +/// ([`super::pypi_requirements::sibling_names_package_by_url`]). None for a +/// project the router refuses, where nothing is written. +/// +/// The requirements files are counted as one set, the file a hub names and +/// the files it brings in with `-r` alike, and not only the files that pin +/// the package: a file the hub reads can reach the rewritten one through an +/// include. +pub(super) async fn hub_files(project_root: &Path, purl: &str) -> Vec { + let mut files = Vec::new(); + let Some((name, version)) = parse_pypi_purl(purl) else { + return files; + }; + let name = canonicalize_pypi_name(&name); + let Ok((flavor, _)) = detect_pypi_flavor(project_root, Some((&name, &version))).await else { + return files; + }; + let requirements = match flavor { + PypiFlavor::Requirements => true, + _ if sibling_lock(flavor).is_none() => { + super::pypi_requirements::sibling_names_package_by_url(project_root, &name).await + } + _ => super::pypi_requirements::sibling_names_package(project_root, &name).await, + }; + if requirements { + // The walk names `requirements.txt` first; where it fails, that file + // alone stands for the set. + let root = || vec![crate::formats::governing_locks::PYPI_REQUIREMENTS.to_string()]; + let included = super::requirements_include_names(project_root).await; + files = included.unwrap_or_else(|_| root()); + } + if flavor == PypiFlavor::UvProject { + files.push("uv.lock".to_string()); + } + files +} + /// How the sibling notes name the requirements file wired with `flavor`'s /// lock: an export of a Pipenv or uv lock, but the file a `pip lock` /// pylock was locked from (#1758). diff --git a/crates/socket-patch-core/src/vendor/pypi_requirements.rs b/crates/socket-patch-core/src/vendor/pypi_requirements.rs index 79f436fa1..d0e860d89 100644 --- a/crates/socket-patch-core/src/vendor/pypi_requirements.rs +++ b/crates/socket-patch-core/src/vendor/pypi_requirements.rs @@ -483,6 +483,36 @@ pub(super) async fn sibling_pin_wirable(root: &Path, canon_name: &str, version: && refuse_symlinked(root, &rels).await.is_ok() } +/// Whether a vendored run that wires a Pipenv, uv or Python lock for +/// `canon_name` may write the requirements set beside it as well: a file of +/// the set names the package. A pin of the release is wired with the lock +/// ([`sibling_pin_wirable`]), a hosted pin is such a pin once a takeover +/// has restored it, and a vendor line is re-wired by a later patch of the +/// package. A set that does not name the package is never written. +pub(super) async fn sibling_names_package(root: &Path, canon_name: &str) -> bool { + let names = |file: &ReqFile| { + names_package(&file.content, canon_name) || has_vendor_line(&file.content, canon_name) + }; + let files = collect_requirements_files(root).await; + files.is_ok_and(|files| files.iter().any(names)) +} + +/// Whether a requirements file of the project names the package by a URL +/// (`name @ https://...`), which is the form of a hosted pin. A lock that +/// is wired alone leaves the requirements files as they are, but a run +/// that takes a hosted pin over restores the line that holds it. +pub(super) async fn sibling_names_package_by_url(root: &Path, canon_name: &str) -> bool { + let by_url = |file: &ReqFile| { + logical_lines(&file.content).into_iter().any(|ll| { + let text = strip_comment(&ll.text); + let named = requirement_name(text).map(canonicalize_pypi_name); + text.contains("://") && named.as_deref() == Some(canon_name) + }) + }; + let files = collect_requirements_files(root).await; + files.is_ok_and(|files| files.iter().any(by_url)) +} + /// #1873: refuse a requirements line naming `canon_name` through a /// `${NAME}` pip expands where it runs (`six==${SIXV}`). What it installs /// is unknowable here, so the vendor neither rewrites it nor names the file diff --git a/crates/socket-patch-core/src/vendor/refusals.rs b/crates/socket-patch-core/src/vendor/refusals.rs index 437316fc8..59feaff0a 100644 --- a/crates/socket-patch-core/src/vendor/refusals.rs +++ b/crates/socket-patch-core/src/vendor/refusals.rs @@ -23,10 +23,12 @@ //! as a skip); //! 6. a Maven version no module of the build selects //! (`vendor_maven_version_not_selected`, a skip too); -//! 7. a Composer project in a Bazel workspace -//! (`vendor_composer_bazel_workspace`), unless the user allowed it -//! ([`ALLOW_IN_BAZEL_ENV`]) or the lock already names the patch's copy -//! ([`bazel_workspace_refusals`]); +//! 7. a project in a Bazel workspace whose build would not find the +//! vendored copy ([`bazel_workspace_refusals`]), unless the user allowed +//! 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`); //! 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. @@ -43,7 +45,9 @@ use crate::crawlers::Ecosystem; use crate::patch::redirect::upstream::HostedPin; use crate::utils::purl_key::PurlKey; use crate::vendor::state::{lookup_entry, VendorEntry}; -use crate::vendor::{bun_lock, composer_lock, gem, lock_inventory, npm_flavor, npm_lock, vlt_lock}; +use crate::vendor::{ + bazel_hub, bun_lock, composer_lock, gem, lock_inventory, npm_flavor, npm_lock, vlt_lock, +}; /// The vendor ledger as the refusals consume it: the caller's own load /// outcome, so an UNREADABLE ledger is a refusal the run can report @@ -116,10 +120,12 @@ fn is_composer(purl: &str) -> bool { /// vendored entry point takes this one answer: [`vendor_refusals`] hands it /// to a scan, a `get` and a `vendor`, and the eject of hosted pins asks it /// before it fetches or restores anything. A refusal of this kind for -/// another ecosystem belongs here. Composer's is the one the user's word -/// lifts. Maven's is not lifted: vendored mode patches a pinned -/// rules_jvm_external hub, and where the hub is the only build of a patch -/// and no entry can be shown to work for it +/// another ecosystem belongs here. The user's word lifts the one of any +/// Composer project ([`composer_lock::bazel::refusals`]) and the one of a +/// PyPI or RubyGems project whose lock a hub of the workspace reads +/// ([`bazel_hub::refusals`]). Maven's is not lifted: vendored mode patches +/// a pinned rules_jvm_external hub, and where the hub is the only build of +/// a patch and no entry can be shown to work for it /// ([`super::maven_repo::hub_refusals`]), there is nothing else to write. pub async fn bazel_workspace_refusals<'a>( project_root: &Path, @@ -131,6 +137,7 @@ pub async fn bazel_workspace_refusals<'a>( .copied() .collect(); let mut refused = composer_lock::bazel::refusals(project_root, &composer).await; + refused.extend(bazel_hub::refusals(project_root, candidates).await); let maven = |(purl, _): &&(&str, &str)| Ecosystem::from_purl(purl) == Some(Ecosystem::Maven); let maven: Vec<(&'a str, &str)> = candidates.iter().filter(maven).copied().collect(); if !maven.is_empty() { @@ -503,6 +510,39 @@ mod tests { assert!(!refusal_is_benign(got[one].code)); } + /// A project whose requirements a hub of its Bazel workspace reads: + /// every PyPI candidate is refused with the one answer of the project, + /// and no candidate of an ecosystem whose hub the workspace does not + /// call. The switch is read from the environment, so the test holds it + /// unset. + #[tokio::test] + #[serial_test::serial] + async fn the_candidates_of_a_lock_that_a_bazel_hub_reads_are_refused() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let tmp = tempfile::tempdir().unwrap(); + let (one, other) = ("pkg:pypi/a@1.0.0", "pkg:pypi/b@2.0.0"); + let pairs = [(one, UUID), (other, OTHER_UUID), ("pkg:gem/x@1.0.0", UUID)]; + let empty = HashMap::new(); + let module = "pip = use_extension(\"@rules_python//python/extensions:pip.bzl\", \"pip\")\n\ + pip.parse(requirements_lock = \"//:requirements.txt\")\n"; + std::fs::write(tmp.path().join("MODULE.bazel"), module).unwrap(); + // The file a run for either package would write. + std::fs::write(tmp.path().join("requirements.txt"), "").unwrap(); + let got = run(tmp.path(), &pairs, Ok(&empty)).await; + assert_eq!(got.keys().collect::>(), [one, other]); + assert_eq!(got[one].code, "vendor_pypi_bazel_hub"); + assert_eq!(got[one], got[other]); + assert!(!refusal_is_benign(got[one].code)); + // The same answer is the eject's, and a hub that reads another + // file refuses nothing. + let asked = bazel_workspace_refusals(tmp.path(), &pairs).await; + let asked: Vec<_> = asked.iter().map(|(purl, code, _)| (*purl, *code)).collect(); + assert_eq!(asked, [(one, got[one].code), (other, got[one].code)]); + let elsewhere = module.replace("//:requirements.txt", "//:requirements_lock.txt"); + std::fs::write(tmp.path().join("MODULE.bazel"), elsewhere).unwrap(); + assert!(run(tmp.path(), &pairs, Ok(&empty)).await.is_empty()); + } + mod gem { use super::*; diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 1388da628..949a0d26b 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -19,10 +19,10 @@ below is about what a package manager installs and builds. | Ecosystem | agent (`--mode agent`) | vendored (`--mode vendored`) | hosted (`--mode hosted`) | |-----------|------------------------|------------------------------|--------------------------| | npm (`npm`) — pnpm / yarn / berry / bun / vlt | ✅ any install layout, vlt's `node_modules/.vlt` store included (every store copy, copy-on-write) | ✅ seven lockfile flavors: package-lock, yarn classic, yarn berry (node-modules linker; PnP refused), pnpm v9, pnpm legacy v5.4/v6.0 (`pnpm 7/8` — frozen installs are path-bound because those majors absolutize `file:` override specifiers; moved checkouts run one `pnpm install --offline --no-frozen-lockfile`, surfaced as `vendor_pnpm_legacy_absolute_specifier`), bun text `bun.lock` lockfileVersion 0/1/2/3 and native binary `bun.lockb` revisions 1/2/3 (binary locks stay binary; text workspace vendoring requires lockfileVersion 2 — see [Bun compatibility](testing/bun-compatibility.md)), vlt `vlt-lock.json` lockfileVersion 0/1 (patched package directories for direct dependencies of the root or a workspace member; transitive targets refused — see [vlt notes](#npm-vlt-notes)). Rush monorepos on pnpm 9 and newer are wired through `pnpm-config.json` and each directly-depending project's `package.json` — see [Rush notes](#npm-rush-monorepos) | ✅ package-lock / npm-shrinkwrap, pnpm-lock.yaml and legacy shrinkwrap.yaml (pnpm majors 1–12; block and flow resolutions), yarn classic, yarn berry, bun, vlt (`vlt-lock.json` without `lockfileVersion`, 0 or 1) — pnpm, berry, bun and vlt carry constraints, see [npm hosted-mode notes](#npm-hosted-mode-notes) and [vlt notes](#npm-vlt-notes) | -| PyPI (`pypi`) — uv / poetry / pdm / pipenv / pip | ✅ in place | ✅ uv project/script locks, PEP 751 `pylock.toml` / `pylock..toml`, poetry, pdm, pipenv (Pipenv 2018 or later — every `Pipfile.lock` category is rewired, lock-only checkouts included; Pipenv 2023+ does not hash-check local wheels — `vendor_integrity_unverified`; Pipenv 2023.7.9+ exports the vendored wheel without a hash, so `pipenv requirements --hash` output fails pip's hash-checking mode — `pypi_pipenv_hash_export_unsupported`; a venv still holding the upstream release is reported as `pypi_pipenv_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)), and requirements.txt. Native uv vendoring requires uv ≥ 0.2.35 (the `[[package]]` lock grammar); hosted mode covers native `uv.lock` from uv 0.1.45 (the first release whose `uv lock` writes one) and requirements from uv 0.0.5; see [uv compatibility](testing/uv-compatibility.md). | ✅ requirements.txt including hash continuations, uv project/script locks, and PEP 751 locks. Version/source ambiguity is refused; see [uv compatibility](testing/uv-compatibility.md). Poetry 1.x and 2.x locks are supported; Poetry 0.x ignores URL sources and is refused. See [Poetry compatibility](testing/poetry-compatibility.md). Pipenv `Pipfile.lock` (pipfile-spec 6 — Pipenv 7 and later; `path` references for 7–11, `file` from 2018; lock-only checkouts and Pipenv's out-of-tree venv are discovered; a warm venv that Pipenv will not reinstall over warns `redirect_pypi_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)). `pdm.lock` is supported for the lock formats PDM 0.12–1.4 and 2.8.1+ write (`lock_version` 2 / 4.3–4.5.1); the identity-losing 3.1 / 4.0–4.2 formats (PDM 1.8–2.7) are refused. PDM 2.8.0 writes an indistinguishable `4.3` lock but shares that identity-loss bug, so a rewritten 2.8.0 lock crashes `pdm sync` — upgrade to ≥ 2.8.1. See [PDM compatibility](testing/pdm-compatibility.md). | +| PyPI (`pypi`) — uv / poetry / pdm / pipenv / pip | ✅ in place | ✅ uv project/script locks, PEP 751 `pylock.toml` / `pylock..toml`, poetry, pdm, pipenv (Pipenv 2018 or later — every `Pipfile.lock` category is rewired, lock-only checkouts included; Pipenv 2023+ does not hash-check local wheels — `vendor_integrity_unverified`; Pipenv 2023.7.9+ exports the vendored wheel without a hash, so `pipenv requirements --hash` output fails pip's hash-checking mode — `pypi_pipenv_hash_export_unsupported`; a venv still holding the upstream release is reported as `pypi_pipenv_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)), and requirements.txt. Native uv vendoring requires uv ≥ 0.2.35 (the `[[package]]` lock grammar); hosted mode covers native `uv.lock` from uv 0.1.45 (the first release whose `uv lock` writes one) and requirements from uv 0.0.5; see [uv compatibility](testing/uv-compatibility.md). Declined where a rules_python hub of a Bazel workspace reads the file, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ requirements.txt including hash continuations, uv project/script locks, and PEP 751 locks. Version/source ambiguity is refused; see [uv compatibility](testing/uv-compatibility.md). Poetry 1.x and 2.x locks are supported; Poetry 0.x ignores URL sources and is refused. See [Poetry compatibility](testing/poetry-compatibility.md). Pipenv `Pipfile.lock` (pipfile-spec 6 — Pipenv 7 and later; `path` references for 7–11, `file` from 2018; lock-only checkouts and Pipenv's out-of-tree venv are discovered; a warm venv that Pipenv will not reinstall over warns `redirect_pypi_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)). `pdm.lock` is supported for the lock formats PDM 0.12–1.4 and 2.8.1+ write (`lock_version` 2 / 4.3–4.5.1); the identity-losing 3.1 / 4.0–4.2 formats (PDM 1.8–2.7) are refused. PDM 2.8.0 writes an indistinguishable `4.3` lock but shares that identity-loss bug, so a rewritten 2.8.0 lock crashes `pdm sync` — upgrade to ≥ 2.8.1. See [PDM compatibility](testing/pdm-compatibility.md). | | pixi (`pypi`) — the Python packages of a pixi project, from conda channels or PyPI | ✅ in place, in every environment under `.pixi/envs`: PyPI wheels and pure-Python conda packages (compiled conda packages are not supported yet and are skipped) — see [PyPI: pixi projects](#pypi-pixi-projects) | ❌ refused (`pypi_no_requirements` / `pypi_pyproject_only`, which name agent mode) | ❌ nothing rewritten (`redirect_pypi_pixi_project` names agent mode) | | Cargo (`cargo`) | ✅ in-place + `.cargo-checksum.json` rewrite (shared registry-cache caveat — see [Cargo: shared registry cache](#cargo-shared-registry-cache)) | ✅ `[patch.crates-io]` path entry in the root `Cargo.toml` (v5; per-version Socket keys; pre-v5 `.cargo/config*` wiring migrates on re-run) | ✅ per-patch sparse registry (`[registries.socket-patch-]` + Cargo.lock source/checksum); needs cargo 1.68+ (sparse registries) — a project whose `rust-version` or `rust-toolchain[.toml]` declares an older cargo is refused (`redirect_cargo_old_cargo`), use `--mode vendored`; direct dependencies only — a crate another dependency also pulls in is refused, use `--mode vendored`; a crate the user overrides with `[patch]` (path, git or another registry) is refused too, the override is left alone; a `cargo vendor` or `cargo local-registry` project (crates.io replaced by an on-disk source in the project's, a parent directory's or `$CARGO_HOME`'s `.cargo/config*`) is refused, use agent mode; with no `Cargo.lock` the graph is unknown, so only a project whose sole dependency is the patched crate is redirected; in a Bazel workspace a crate is not pinned while a rules_rust hub reads the project's Cargo files without its cargo config (`redirect_cargo_bazel_config_unread`), see [Bazel workspaces: Cargo](#bazel-workspaces-cargo) | -| RubyGems (`gem`) | ✅ in place | ✅ Gemfile + Gemfile.lock path pair (a CRLF `Gemfile.lock`, as a `core.autocrlf` checkout leaves it, is edited and reverted in its own line ending, and a lock mixing CRLF and LF fails closed; a gem locked as precompiled platform gems is vendored from prebuilt patched platform gems, see [Ruby gems: native extensions](#ruby-gems-native-extensions); `Gemfile` spelling only — a `gems.rb` twin, which bundler ≥ 2 loads instead, or a `BUNDLE_GEMFILE`-configured manifest makes vendoring refuse with `gemfile_not_loaded` before any write) | ✅ a `source:` option on the gem's own declaration, the lock converged to match (see [Ruby gems: hosted mode](#ruby-gems-hosted-mode)) — edits `gems.rb` + `gems.locked` or `Gemfile` + `Gemfile.lock`, whichever the project holds (a `Gemfile` + `gems.rb` twin is refused with `redirect_gem_twin_manifest_ambiguous`: bundler 1.x loads the `Gemfile`, bundler ≥ 2 loads `gems.rb`, and nothing in the project says which bundler installs it; bundler 4's `BUNDLE_LOCKFILE` (environment, app config or global config) naming any other lock is refused with `redirect_gem_bundle_lockfile_unsupported`, as is vendoring with `gemfile_not_loaded`; spellings that diverge beyond Socket's own edits fail closed with `redirect_gem_gemfile_spellings_diverge`; `BUNDLE_GEMFILE` from `.bundle/config` (which outranks the environment, as in bundler), the environment, or the global `~/.bundle/config` / `$BUNDLE_USER_CONFIG` (lowest, as in bundler) is followed when it names the project's `Gemfile` / `gems.rb`, and any other configured manifest is refused with `redirect_gem_bundle_gemfile_unsupported`); a Bundler all-source, exact-source or hostname mirror in app config or the scan environment can capture the patch registry, so the redirect is refused with `redirect_gem_mirror_overrides_source` without printing mirror URLs (scope mirrors to `mirror.https://rubygems.org`; user-global config and mirrors set only in a later install environment are not inspected); the `CHECKSUMS` pin needs bundler ≥ 2.6 (an older lock is still pinned by source and installs frozen; the run says once, with `redirect_gem_no_checksums_section`, that it cannot record the checksums); a stale pre-redirect materialization that `bundle install` would reuse instead of refetching is replaced with the verified patched gem when it is the project's own, else flagged `redirect_gem_stale_install` with the remedy (see "Ruby gems: gems already installed" below and CLI_CONTRACT.md's "Gem stale-install guard"). In a Bazel workspace whose rules_ruby call holds the gem to another sha256 in `gem_checksums`, or has a `gem_checksums` that is not written out in the call, nothing is written for it (`redirect_bazel_gem_checksums_pinned`); see [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems) | +| RubyGems (`gem`) | ✅ in place | ✅ Gemfile + Gemfile.lock path pair (a CRLF `Gemfile.lock`, as a `core.autocrlf` checkout leaves it, is edited and reverted in its own line ending, and a lock mixing CRLF and LF fails closed; a gem locked as precompiled platform gems is vendored from prebuilt patched platform gems, see [Ruby gems: native extensions](#ruby-gems-native-extensions); `Gemfile` spelling only — a `gems.rb` twin, which bundler ≥ 2 loads instead, or a `BUNDLE_GEMFILE`-configured manifest makes vendoring refuse with `gemfile_not_loaded` before any write); declined where a rules_ruby hub of a Bazel workspace reads the pair, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ a `source:` option on the gem's own declaration, the lock converged to match (see [Ruby gems: hosted mode](#ruby-gems-hosted-mode)) — edits `gems.rb` + `gems.locked` or `Gemfile` + `Gemfile.lock`, whichever the project holds (a `Gemfile` + `gems.rb` twin is refused with `redirect_gem_twin_manifest_ambiguous`: bundler 1.x loads the `Gemfile`, bundler ≥ 2 loads `gems.rb`, and nothing in the project says which bundler installs it; bundler 4's `BUNDLE_LOCKFILE` (environment, app config or global config) naming any other lock is refused with `redirect_gem_bundle_lockfile_unsupported`, as is vendoring with `gemfile_not_loaded`; spellings that diverge beyond Socket's own edits fail closed with `redirect_gem_gemfile_spellings_diverge`; `BUNDLE_GEMFILE` from `.bundle/config` (which outranks the environment, as in bundler), the environment, or the global `~/.bundle/config` / `$BUNDLE_USER_CONFIG` (lowest, as in bundler) is followed when it names the project's `Gemfile` / `gems.rb`, and any other configured manifest is refused with `redirect_gem_bundle_gemfile_unsupported`); a Bundler all-source, exact-source or hostname mirror in app config or the scan environment can capture the patch registry, so the redirect is refused with `redirect_gem_mirror_overrides_source` without printing mirror URLs (scope mirrors to `mirror.https://rubygems.org`; user-global config and mirrors set only in a later install environment are not inspected); the `CHECKSUMS` pin needs bundler ≥ 2.6 (an older lock is still pinned by source and installs frozen; the run says once, with `redirect_gem_no_checksums_section`, that it cannot record the checksums); a stale pre-redirect materialization that `bundle install` would reuse instead of refetching is replaced with the verified patched gem when it is the project's own, else flagged `redirect_gem_stale_install` with the remedy (see "Ruby gems: gems already installed" below and CLI_CONTRACT.md's "Gem stale-install guard"). In a Bazel workspace whose rules_ruby call holds the gem to another sha256 in `gem_checksums`, or has a `gem_checksums` that is not written out in the call, nothing is written for it (`redirect_bazel_gem_checksums_pinned`); see [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems) | | Go (`golang`) | ✅ `go.mod` `replace` → `.socket/go-patches/` — see [Go: directory replaces and go.sum](#go-directory-replaces-and-gosum) | ✅ `replace` → the committed vendor tree | ✅ (free tier) fork-style `replace` → `patch.socket.dev/gopatch/` + committed `go.sum` pin; see [Go notes](#go-directory-replaces-and-gosum). Paid hosted patches are unsupported; `redirect_golang_unsupported` names the vendored remedy | | Maven (`maven`) — Maven and Gradle | ✅ in place in every copy the build consumes: each `~/.m2` copy it reads and each Gradle `files-2.1` copy; `~/.m2` `.sha1`/`.md5` sidecars are rewritten, Gradle copies get advisories; jar-member records swap in the patch service's whole jar — prefer vendored / hosted, see [Maven & NuGet caveats](#maven--nuget-caveats) and [Gradle](#gradle) | ✅ suffixed Maven repository (`-socket.` pin + `.mvn/maven.config` + fallback file repository) for every pom root, single-module or reactor, or Gradle 6.8+ same-GAV repository with settings wiring and SHA-256 checks (a root with both `pom.xml` and a Gradle build wires both); see [JVM vendoring](design/maven-vendoring.md) and [Gradle](#gradle) | ✅ fail-closed by a Socket-only `-socket.` suffix: pom projects get a pinned `` (`${property}` versions are refused); Gradle 6.8+ builds get an owned settings script, lock-entry rewrites and a resolution tripwire — see [Maven & NuGet caveats](#maven--nuget-caveats) and [Gradle](#gradle) | | sbt / Mill / scala-cli (`maven`) | ✅ Coursier caches (sbt 1.3+, sbt 2, Mill, scala-cli) and Ivy caches (sbt 0.13–1.2, `useCoursier := false`) patched in place, Coursier checksum sidecars resynced — see [Scala build tools](#scala-build-tools-sbt-mill-scala-cli) | ✅ sbt 0.13.18+: generated `socket-patch-vendor.sbt` over the committed suffixed `.socket/vendor/maven2` tree; scala-cli directory builds: owned `socket-patch.scala` + same-GAV `.socket/vendor/coursier` tree (Linux / macOS); Mill: not wired (agent or hosted guidance) | ✅ sbt 0.13.18+: one generated `socket-patch.sbt`, gated on sbt's own `sbt update` records; Mill / scala-cli: paste-able snippets only (`redirect_mill_manual_snippet`, `redirect_scala_cli_manual_snippet`) | @@ -2173,6 +2173,11 @@ 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 + 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)). - **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 @@ -2252,12 +2257,10 @@ fails until one that may has rewritten it. Known problems. In each of these a command exits 0 today and the next Bazel build fails: -- **Vendored mode for PyPI, RubyGems and NuGet.** The path of the committed copy means - nothing where Bazel runs: rules_python takes it for a package name, rules_ruby's - `bundle install` does not find it (`The path ... does not exist`), and rules_csharp reads - it as a URL (`Bad URL`, or a crash of Bazel 9.3.2). Run `socket-patch vendor --revert`, - then `socket-patch scan --mode hosted`. Of these builds a test of this repository runs the - PyPI one; the others were measured by hand on the three Bazel releases. +- **Vendored mode for NuGet.** The path of the committed copy means nothing where Bazel + runs: rules_csharp reads it as a URL (`Bad URL`, or a crash of Bazel 9.3.2). Run + `socket-patch vendor --revert`, then `socket-patch scan --mode hosted`. Measured by hand on + the three Bazel releases; no test of this repository runs that build. - **Vendored mode for Composer, where its refusal is lifted or does not apply.** In a Bazel workspace vendored mode declines a Composer package: [Bazel workspaces: Composer](#bazel-workspaces-composer) has the refusal, what lifts it and @@ -3227,8 +3230,9 @@ adds no line. What the line is for, measured with rules_rust 0.75.0 on Bazel 9.3 tags the crate's library so). That package names repositories only the hub sees, so for a vendored crate with a dependency the commands that analyse every target fail on it: `bazel cquery //...` and `bazel query 'deps(//...)'` end with `No repository visible as - '@crates__' from main repository`. With the line both pass, and `//...` holds - your own targets alone. + '@crates__' from main repository`, or with the same words about `@platforms`, + which the file names too: Bazel reports the first of the two that it meets. With the line + both pass, and `//...` holds your own targets alone. **Under that line, the file is no change of the copy.** `vendor --check` passes, `vex` attests the crate, `repair` has nothing to restore, and a second `scan --mode vendored` @@ -3726,7 +3730,9 @@ project's directory, or where the build finds the copy all the same: socket-patch checks none of these. The switch is not Composer's alone: it lets vendored mode write for any package it would decline because the project is in a Bazel workspace, where the -build may not find the vendored copy. The Composer refusal is the only such refusal today. +build may not find the vendored copy. PyPI and RubyGems have such a refusal too, for a project +whose lock a hub of the workspace reads: see +[Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode). `vendor --revert` is never declined. Neither is a package that is already vendored: where `composer.lock` already names the copy of the same patch, a vendored run leaves the lock as it @@ -3753,6 +3759,168 @@ Limits: [`e2e_bazel_build/composer.rs`](../crates/socket-patch-cli/tests/e2e_bazel_build/composer.rs) runs these flows on a real Bazel. +## Bazel workspaces: PyPI and RubyGems vendored mode + +Two rulesets hand a lock of the checkout to Bazel through one call, a hub: rules_python's +`pip.parse` reads requirements files, and rules_ruby's `ruby.bundle_fetch` reads a `Gemfile` and +its lock. Each fetches what the file names into repositories of Bazel's own and builds from +there. Vendored mode makes that file name the patched copy by a path under `.socket/vendor`, +and neither ruleset builds from such a file: + +- **PyPI.** The package's line of `requirements.txt` becomes + `./.socket/vendor/pypi// --hash=sha256:...`. rules_python 2.5.0-rc4 makes the + name of a repository from that path, and the build of everything the hub serves fails with + `invalid user-provided repo name 'pip_311__/_socket/vendor/pypi//'`. +- **RubyGems.** The gem's declaration in `Gemfile` gets a `path:` and its entry of + `Gemfile.lock` moves into a `PATH` section. rules_ruby 1.0.0-rc2 copies the two files into a + repository of Bazel's and runs `bundle install` there, which fails with + `The path .../.socket/vendor/gem//- does not exist.` + +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. + +**What is read.** The project is in a Bazel workspace by the lookup of +[Bazel workspaces: `.bazelignore`](#bazel-workspaces-bazelignore). There socket-patch reads +`MODULE.bazel` and the files it includes, and the `WORKSPACE` file, as +[Bazel workspaces: VEX](#bazel-workspaces-vex) describes; nothing is evaluated and no Bazel is +run. A package is declined when one of these calls names, by a label written out as a string, +a file of the package's project that the vendored run for that package would point at a copy: + +| Call | Attributes | Files of the project that count | +|---|---|---| +| rules_python `pip.parse` | `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows`, `uv_lock` | `requirements.txt` and each file it includes with `-r` (in the project), as one set, where the run writes a requirements file; `uv.lock` in a uv project | +| rules_ruby `ruby.bundle_fetch` | `gemfile_lock`, `gemfile` | `Gemfile`, `Gemfile.lock` | +| any call of the `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`) | the same; a label `@//...` names the main repository where the file says `workspace(name = "")` | the same | + +Which files a run writes depends on the tool that locks the Python project, as in the matrix +at the top: + +- A project with no tool lock is wired through its requirements files. They count as one + set: a package is declined when the hub reads any file of the set, also one that does not + pin it, because that file can bring in the rewritten one with `-r`. +- A uv, Pipenv or PEP 751 lock is wired together with a pin of the same package in the + requirements files beside it. So those files count for a package they name, and not for + one they do not name. +- A Poetry or PDM lock is wired alone. A hub that reads the requirements file exported from + it stands in no run's way, and the package is vendored as it is without Bazel. Bazel goes on + building the registry's package from that file; `socket-patch vex` does not say so yet (see + the limits of [Bazel workspaces: VEX](#bazel-workspaces-vex)). The one exception is a + requirements file that holds the package by a URL, which is what a hosted pin is: a + vendored run that takes the pin over restores that line, so the files count and the + package is declined. + +Every such call counts, also one that may not run (in a comprehension, behind an `and`). The +refusal is for every package whose run would write a file the call names, since the lock is +the project's, with one exception: a package that is already vendored (see below). + +**What an uncertain reading does.** Where something of the workspace's files cannot be read +with certainty, and a call of the hub may be behind that, every package whose run would write +one of the files above is declined, in every project of the workspace, because the call may +read its lock. That is: + +- a call of the hub whose file is not a plain string (a constant, a concatenation), or one + that passes `*` or `**`; +- a hub proxy that is handed to anything but `use_repo` or `inject_repo`; +- a module file that is missing or cannot be read, or a statement of one that cannot be + read, where the workspace calls the hub or a file that was read names its ruleset (a + `bazel_dep` on rules_python or rules_ruby, or a `use_extension` of the hub's `.bzl` file); +- a root `MODULE.bazel` or a `WORKSPACE` file that cannot be read at all. + +A file cannot be read here when one byte of it is not UTF-8 (a name in a comment is enough), +or when it is larger than 1 MiB; Bazel builds both. Going on there can leave a broken build +behind a command that exited 0; declining costs a vendored run, which the switch below brings +back. A workspace whose root `MODULE.bazel` and `WORKSPACE` file were read (or are not +there), and in which no file that was read calls the hub or names its ruleset, is never +declined for it, whatever else cannot be read. + +**What you see.** Every command that would vendor the package reports it `failed` with +`vendor_pypi_bazel_hub` or `vendor_gem_bazel_hub` and exits 1: `scan --mode vendored`, +`get --mode vendored` and `vendor`. It writes nothing and downloads no patch, and a +package that is pinned hosted stays pinned (`vendor` reports `eject_refused`). With +`--dry-run`, `scan` and `get` list the package as one the run would refuse and exit 0; +`vendor --dry-run` reports the refusal and exits 1. The message names the call with its file +and line, the lock, and the mode to use instead: + +``` +`pip.parse` (MODULE.bazel:15) of the Bazel workspace at /repo names requirements.txt; vendored mode makes the lock name the patched copy by a path under .socket/vendor, and rules_python fails the build on such a lock; use `--mode hosted`, which names the patched package by a URL that rules_python fetches, or pass `--allow-vendored-in-bazel` if no build takes the packages of this project from rules_python +``` + +For an uncertain reading the message names the file, the line and the reason where the +call stands. Hosted mode pins the patch in the same file, as a wheel URL with its sha256 or +as a gem source, and both rulesets build it: that is tested on the three Bazel releases, in +the checkout where vendored mode was declined. For a gem that holds for a +`ruby.bundle_fetch` without `gem_checksums`, as the message for a gem says. Where a +`gem_checksums` of the call holds the gem to another sha256, or is not written out in the +call, hosted mode writes nothing for the gem and its warning names the way on: see +[Bazel workspaces: RubyGems](#bazel-workspaces-rubygems). + +**Where nothing changes.** A project in no Bazel workspace, a workspace that calls neither +hub, and a package whose run writes no file that a call names are vendored as before, with +the same output and the same files: a Python or Ruby project beside the one whose lock the +hub reads, a Poetry or PDM project whose exported requirements file the hub reads, or a +project that keeps a `requirements.txt` for pip while the hub reads a `requirements_lock.txt` +that socket-patch does not rewrite. In the last two cases Bazel goes on building the +unpatched package from its own file, as before. + +Vendored mode goes on when you say so, with `--allow-vendored-in-bazel` or +`SOCKET_ALLOW_VENDORED_IN_BAZEL=1`: for a hub that no build of yours uses, for a `WORKSPACE` +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). + +`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 +(`.socket/vendor/pypi//`, `.socket/vendor/gem//`), a vendored run adds nothing to +what the hub reads. So a project that was vendored with the switch, or by an earlier release, +keeps passing its runs without the switch, a `scan` or `get` with no `--mode` included, which +runs in vendored mode there. A new patch for that package, or another package, is declined +until the run has the switch. Where the calls name more than one file of the project, each +of them that holds the package has to name the copy: a `uv.lock` that was locked again +beside a vendored requirements file does not, and the package is declined. Where the reading +is uncertain no file is known to be the hub's, so nothing is let through: every vendored run +there needs the switch. + +Passing such a run does not mean that the build is the patched one. A build that takes the +project's packages from the hub fails on a vendored PyPI package, and on a vendored gem +unless the call lists the copy's files. For a PyPI package `vex` says of that state that the +package is `affected` ([Bazel workspaces: VEX](#bazel-workspaces-vex)); the way out is +`vendor --revert`, then `scan --mode hosted`. + +Limits: + +- Not seen, so vendored mode goes on as before and the build can break: a hub call in a + `.bzl` file that a `WORKSPACE` file loads, a hub that another Bazel module declares, + another tag or another ruleset that reads the same file under Bzlmod (rules_ruby's older + `ruby.bundle`, rules_pycross, aspect_rules_py), a `WORKSPACE` call that hides its + arguments behind `**`, the `pip_install(requirements = ...)` of an older rules_python in a + `WORKSPACE` file, a Bazel root that the lookup does not reach, and a hub whose call + and whose `bazel_dep` are both in an included file that cannot be read, while the files + that were read name neither. +- Declined although the build would pass: a `WORKSPACE` file that names the lock while the + Bazel in use does not read that file, a hub call that never runs, and a workspace that + does not use the ruleset while its root `MODULE.bazel` or its `WORKSPACE` file cannot be + read here, or while a file that was read names the ruleset and another cannot be read. +- Declined although the run would write nothing to the file the call names: a package that + is already vendored where the file that names its copy is not the one the call names (a + requirements file that the named one includes with `-r`; the `Gemfile` when the call names + the lock too and the lock does not name the copy), any already vendored package where the + reading is uncertain, a package of a uv, Pipenv or PEP 751 project that the + requirements file names in a form that is not wired with the lock (a range, extras), and a + package of a project with no tool lock where the hub reads a file of the requirements set + that neither pins the package nor brings in the file that does. +- Only the `Gemfile` spelling is looked for, as vendored mode wires no `gems.rb` project. +- A `pip.parse` that names a `uv.lock` is declined by the rule above, not by a measurement: + no build was run on a vendored `uv.lock`. +- `repair` is not gated: it replaces a damaged copy of a package that is vendored already, + and leaves the lock as it is. + +[`e2e_bazel_build/pypi.rs`](../crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs) and +[`ruby.rs`](../crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs) run the refusal, the +switch and hosted mode on a real Bazel. + ## Ruby gems: hosted mode `scan --mode hosted` makes Bundler install a patched gem from that patch's own gem source on @@ -4300,8 +4468,12 @@ 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: no test here runs the build of one yet, so nothing is - said of it. + vendored gem, for another reason: rules_ruby builds one 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. 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 @@ -4437,9 +4609,10 @@ the build is broken): `-r`. Measured for PyPI, where the build fails. - **Vendored mode for RubyGems** 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. Read from its source and - measured by hand, where the build fails; no test runs it yet, so the statement is left as - it is. + 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. - **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 2be5dcf83..01494161d 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 3917 + "max": 4042 }, "lock-readers": { "paths": [