diff --git a/.github/workflows/bazel-pypi.yml b/.github/workflows/bazel-pypi.yml index 381838cab..866418375 100644 --- a/.github/workflows/bazel-pypi.yml +++ b/.github/workflows/bazel-pypi.yml @@ -44,7 +44,8 @@ on: # 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 + # command, and for the form vendored mode writes where a build takes + # a committed wheel (vendor/pypi_distdir.rs). Nothing else that # another ecosystem's flow owns is here, so any other change to one # ecosystem starts that ecosystem's legs only. # @@ -79,6 +80,7 @@ on: - '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/pypi_distdir.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/**' @@ -116,6 +118,7 @@ on: - '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/pypi_distdir.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/**' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 45aed9c43..1751d7800 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -122,7 +122,7 @@ Every subcommand accepts the same set of "global" flags via a single shared `Glo | `--no-vlt-install-cleanup` | — | `SOCKET_NO_VLT_INSTALL_CLEANUP` | `false` | bool | Opt out of hosted mode's warm-tree heal for vlt: stale installed copies (`node_modules/.vlt-lock.json` and the stale `node_modules/.vlt/` entries) are left in place after `vlt-lock.json` is repointed (`scan`/`get --mode hosted`) or restored (`rollback`/`remove`), and the `redirect_vlt_reinstall_required` advisory tells you to run `vlt ci` instead. Stale copies of optional dependencies are always left in place (see `redirect_vlt_reinstall_required`). Other subcommands accept it silently | | `--no-gem-install-refresh` | — | `SOCKET_NO_GEM_INSTALL_REFRESH` | `false` | bool | Opt out of hosted mode's gem stale-install refresh: the gems Bundler already holds for the project (an installed gem under the project and its cached `.gem`, an archive in `vendor/cache`) are left as they are after `Gemfile.lock` is repointed (`scan`/`get --mode hosted`) or restored (`rollback`/`remove`, of a hosted pin or of a vendored gem; `vendor --revert`), and the `redirect_gem_stale_install` / `upstream_gem_stale_install` warning names the files to remove by hand instead (see the "Gem stale-install guard" section). Other subcommands accept it silently | | `--gem-refresh-shared` | — | `SOCKET_GEM_REFRESH_SHARED` | `false` | bool | Extend the gem stale-install refresh to gem homes OUTSIDE the project (the system gems, `~/.gem`, an rbenv or asdf home) and to project bundle or cache paths that resolve outside the project directory. Off by default: another project on the machine may pin the other build of the same gem version, and its `bundle pristine` then fails on the replaced archive's checksum (see the "Gem stale-install guard" section). Other subcommands accept it silently | -| `--allow-vendored-in-bazel` | — | `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `false` | bool | Let vendored mode write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. Vendored mode declines such a package by default, and the switch lifts each of those refusals. `vendor_composer_bazel_workspace`: the lock then names the patched copy by a path relative to the directory Composer runs in, and a Bazel rule that runs `composer install` anywhere else fails on it. `vendor_pypi_bazel_hub` and `vendor_gem_bazel_hub`: a rules_python or rules_ruby hub of the workspace reads the lock, which then names the patched copy by a path under `.socket/vendor`, and neither ruleset builds from that. For a project whose build does find the copy, or does not take its packages from that lock. Read by `vendor`, `scan --mode vendored` and `get --mode vendored`; other subcommands accept it silently. See docs/ecosystems.md "Bazel workspaces: Composer" and "Bazel workspaces: PyPI and RubyGems vendored mode" | +| `--allow-vendored-in-bazel` | — | `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `false` | bool | Let vendored mode write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. Vendored mode declines such a package by default, and the switch lifts each of those refusals. `vendor_composer_bazel_workspace`: the lock then names the patched copy by a path relative to the directory Composer runs in, and a Bazel rule that runs `composer install` anywhere else fails on it. `vendor_pypi_bazel_hub` and `vendor_gem_bazel_hub`: a rules_python or rules_ruby hub of the workspace reads the lock, which then names the patched copy by a path under `.socket/vendor`, and neither ruleset builds from that. For a project whose build does find the copy, or does not take its packages from that lock. With it a PyPI package is written by its path also where vendored mode would otherwise commit its wheel as a download cache of Bazel (`vendor_pypi_bazel_download_cache`). 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. @@ -1733,7 +1733,7 @@ to **six flavors**. | 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). 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` | +| 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 package is not written this way without `--allow-vendored-in-bazel`. Where the checkout shows that Bazel takes a committed wheel, the wheel is committed as a download cache instead: the pin line → ` @ --hash=sha256:`, the line hosted mode writes; the wheel at `.socket/vendor/pypi//` under the file name of its URL; and `common --distdir=` under a comment line in the `.bazelrc` at the Bazel root (`vendor_pypi_bazel_download_cache`). The ledger entry is one of this flavor whose record holds that line. Everywhere else the package is refused `vendor_pypi_bazel_hub`. See docs/ecosystems.md "Bazel workspaces: PyPI vendored mode as a download cache" | | 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,7 +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_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 PyPI package whose wheel vendored mode commits as a download cache of Bazel, which it does where the checkout shows that the build takes it (`vendor_pypi_bazel_download_cache`; where a `pip.parse` was read with certainty and it does not, the detail ends with the condition that failed), and one that already is such a cache, while `requirements.txt` holds the line as the run wrote it (a line that has been changed since is refused before any download, and the committed wheel stays); 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. The refusal is asked again where the lock is about to be written, since a hosted → vendored takeover has put the registry's pin back by then: a pin the download cache is not written for is refused there under this code, and the hosted pin stays. One thing only the download shows, that the URL the patch service served the wheel from is not one hosted mode would pin for this patch: that run is `failed` / `apply_failed` with an `error` that starts `vendor_pypi_bazel_hub:`, as a wiring failure of any vendored backend is reported, and the wheel it fetched is removed again unless an earlier run had committed it there. 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. | @@ -2711,6 +2711,8 @@ command's integration tests check its output. | `patch_withdrawn` | `rolledBack` / `verified` (hosted event) | scan `--mode hosted`: the lockfile pinned a patch the server reports `withdrawn` or `not_found`; the pin was restored (dry run: would be) to its upstream registry entry. `reason` names the uuid and status. See "Withdrawn pins". | | `maven_bazel_entry_stale` | `rolledBack` / `verified` (hosted event) | scan `--mode hosted` at the root of a Bazel workspace, with Maven in scope (additive): the block in `MODULE.bazel` held an entry of hosted mode for a jar that no pinned rules_jvm_external hub fetches at that version any more, at which Bazel stops ("does not generate repository"); the entry was taken out (dry run: would be), and with the last entry the block. Only when every hub was read, and not in a root, or for a package, that the `socket.yml` policy filters. A pin of the same patch in another build's files (a `pom.xml`, the hosted Gradle index) stays, and so does a stale entry of vendored mode (the lockfile supplement says who takes that one out). `reason` names the uuid. A restore that fails keeps the entry with a `redirect_withdrawn_restore_failed` warning; one that leaves a file half written stops the run (`lockfile_write_failed`, exit 1), also when the scan has no package. See the lockfile supplement and docs/ecosystems.md "Bazel workspaces: Maven". | | `vendor_prebuilt_stub_invalid` | `failed` | RubyGems: the server stub lacks required attributes or is otherwise invalid; no local stub fallback is permitted. | +| `vendor_pypi_bazel_download_cache` | `skipped` (advisory) | vendor / scan / get `--mode vendored` (pypi / requirements.txt), on the run that writes it: the patched wheel was committed as a download cache of Bazel, because a rules_python `pip.parse` of the project's Bazel workspace reads `requirements.txt` and builds no wheel from a path line. The line of `requirements.txt` is the one hosted mode writes (the wheel by its URL on the patch host, with its sha256), the wheel is at `.socket/vendor/pypi//`, and a `common --distdir=` line of the `.bazelrc` at the Bazel root makes the build take it and ask no host (rules_python 2.5.0-rc4 on Bazel 9.3.2, 8.8.2, 7.7.2, with the patch host stopped). The detail says what the form does not do: pip outside Bazel asks the patch host; Bazel replaces a changed or missing copy from the patch host, without a message, when it can reach it; `vendor --check` is what holds the committed wheel to the patch. Written only where the checkout shows that it works: the project pins in a hashed `requirements.txt` alone, the requirement is one exact pin, a `pip.parse` names that file by `requirements_lock` and no other file of the project, every call of the hub is read with certainty and no `WORKSPACE` file defines repositories, `MODULE.bazel.lock` says that Bazel selected rules_python 2.5.0 (or 2.5.0-rc4), the checkout names Bazel 7, 8 or 9 (or names none and has a lock of version 13 to 28), no rc file of the checkout names a downloader config, `--repository_disable_download` or a remote downloader or imports a file from outside the checkout (an absolute path, which is not read), `.bazelrc` is no symbolic link and not read-only, and the project's path holds nothing an rc line reads otherwise. Elsewhere the package is refused `vendor_pypi_bazel_hub`. `list`, `vex`, `vendor --check`, `vendor --revert`, `rollback` and `remove` treat the package as vendored; the undo restores the pin and takes the line out of `.bazelrc`. See docs/ecosystems.md "Bazel workspaces: PyPI vendored mode as a download cache". | +| `bazelrc_not_updated` | run-level `warnings[]` | PyPI vendored mode in a Bazel workspace (additive): the `.bazelrc` at the Bazel root, whose `common --distdir=` lines make Bazel take the wheels committed as download caches under `.socket/vendor/pypi`, was not updated. It could not be read or written (a symbolic link or a directory in its place, a read-only directory, a read-only file). A `.bazelrc` that is a link or read-only declines the package before anything is written (`vendor_pypi_bazel_hub`), so the run that writes a download cache gives this warning only for a file that changed since or a directory that takes no new file; an undo gives it for a pair it may not take out. The detail names the line to add (without it the build downloads the wheel from the patch host), or says that the lines of a copy that is gone can be deleted; the command's patch or undo stands and its exit code is unchanged. See docs/ecosystems.md "Bazel workspaces: PyPI vendored mode as a download cache". | | `bazelignore_not_updated` | run-level `warnings[]` | Go vendored and agent mode, Cargo vendored mode under a rules_rust crate hub, and Maven vendored mode, in a Bazel workspace (additive): the `.bazelignore` at the Bazel root, which keeps Bazel and gazelle out of the module copies under `.socket/vendor/golang` and `.socket/go-patches` out of the crates under `.socket/vendor/cargo`, and out of the jars vendored for a rules_jvm_external hub under `.socket/vendor/maven`, was not updated. It could not be read or written (a symbolic link or a directory in its place, a read-only directory, a read-only file). The detail names the line to add, or says that the lines of a copy that is gone can be deleted; the command's patch or undo stands and its exit code is unchanged. See docs/ecosystems.md "Bazel workspaces: `.bazelignore`". | | `redirect_cargo_bazel_config_unread` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (additive): a rules_rust crate_universe hub (`crate.from_cargo` in `MODULE.bazel` or a file it includes, or `crates_repository` in the `WORKSPACE` file) reads the project's `Cargo.lock` or one of its `Cargo.toml` files, or may read them (its `cargo_lockfile` or `manifests` is not written out as strings, or a use of the extension may hide a call), and its `cargo_config` is not one string that is the label of the cargo config hosted mode writes (`.cargo/config.toml`, or the project's `.cargo/config`). cargo-bazel runs cargo with the config its hub names and no other, so the registry of a pin would be unknown to it and `bazel build` would fail (`registry index was not found in any configuration`). The crate is not pinned: nothing is written for it, its event is `skipped` / `redirect_unconfirmed` (a vendored crate that the scan would take over stays vendored: `skipped` with this code, and `redirect_takeover_kept_vendored`), and status and exit code are unchanged. One warning per crate; the detail names the hub's file and line, the config to commit (created with a comment line in it where the project has none), the attribute to give the hub (`cargo_config = "//:.cargo/config.toml"`; the label is written in the package of the hub's own labels), after which the same command pins the crate, and `--mode vendored`. A hub that names that config is still in the way while the file is there and holds nothing: `rollback` deletes a cargo config it leaves empty, and the hub fails on the missing file; the detail asks for a comment line in it. For a use of the extension that may hide a call the detail names that line to rewrite and no attribute: the next run pins the crate or names the hub that is in the way. A `WORKSPACE` call (`crates_repository`, also under the name a `load` of that file gives it) counts only when no hub of the module files reads the project's Cargo files and the checkout names no Bazel 9 or later. The rewriter's own refusals answer first and keep their codes. A pin that is in place already stays `applied`, and no warning is given for it. Nothing is read or changed in no Bazel workspace, or where no such hub is seen to read the project's Cargo files. See docs/ecosystems.md "Bazel workspaces: Cargo". | | `maven_bazel_hub_unpatched` | run-level `warnings[]` (human: `Warning: …`) | Maven in a Bazel workspace, agent and vendored mode (additive): a pinned rules_jvm_external hub of the root `MODULE.bazel` fetches the jar of a Maven patch of this run, and the block that hosted and vendored mode keep in `MODULE.bazel` holds no entry for that jar after it. The hub builds the jar its own lock (`maven_install.json`) names, so the patch does not reach the Bazel build. Agent mode (`apply`, and `get` / `scan` in that mode; only for a package it found installed; never under `--global`) patches no hub: one warning per purl; the detail names the lock, the hub, the file and line of its `maven.install`, and the hosted command that patches a pinned hub; the events, the exit code and every written file are those of the same run without the workspace. Vendored mode (`vendor`, and `get` / `scan` in that mode) patches a pinned hub (below), and gives this code only for a jar it could have written an entry for and vendored nothing for, because the package failed or was skipped for another reason (never in a dry run); a jar it cannot write an entry for gets the `maven_bazel_*` code of the reason instead. A `vendor` whose `--ecosystems` leaves Maven out gives none. A hosted run never gives it: see the `maven_bazel_*` rows below and docs/ecosystems.md "Bazel workspaces: Maven". | diff --git a/crates/socket-patch-cli/src/args.rs b/crates/socket-patch-cli/src/args.rs index 2f1354fcd..42007d737 100644 --- a/crates/socket-patch-cli/src/args.rs +++ b/crates/socket-patch-cli/src/args.rs @@ -435,8 +435,9 @@ pub struct GlobalArgs { /// (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`), which builds /// nothing from a lock that names a copy under `.socket/vendor`. Pass /// it when the build does find the copy, or does not take the - /// project's packages from that lock. Other subcommands accept it - /// silently. + /// project's packages from that lock. A PyPI package is then written + /// by its path also where vendored mode would commit its wheel as a + /// download cache of Bazel. Other subcommands accept it silently. #[arg( help_heading = GLOBAL_OPTIONS, long = "allow-vendored-in-bazel", diff --git a/crates/socket-patch-cli/src/commands/mod.rs b/crates/socket-patch-cli/src/commands/mod.rs index 93bd32267..bfc32b73a 100644 --- a/crates/socket-patch-cli/src/commands/mod.rs +++ b/crates/socket-patch-cli/src/commands/mod.rs @@ -59,23 +59,28 @@ pub(crate) fn project_state_in_scope(common: &crate::args::GlobalArgs) -> bool { /// the project's patched Go module copies, of the vendored crates a crate /// hub builds, and of the patched Maven jars that vendored mode keeps for a /// rules_jvm_external hub, so that Bazel and gazelle read no package there -/// (`socket_patch_core::bazel::ignore`). A command that can write or -/// remove such a copy calls this once, after the last step that can change -/// a copy or take one back and before it gives up its apply lock. Nothing -/// is done in a dry run or a `--global` run, and a run whose `--ecosystems` -/// leaves `golang`, `cargo` or `maven` out only takes away that ecosystem's pair of -/// a copy that is gone. So does the prune pass of a scan, which comes here -/// after its scan has (`adds` false) and can only have removed a copy: a -/// file it cannot write is left to the next command's warning. +/// (`socket_patch_core::bazel::ignore`), and the root's `.bazelrc` names +/// the directory of each patched wheel that vendored mode committed as a +/// download cache of Bazel, so that the build takes the wheel from there +/// (`socket_patch_core::vendor::pypi_distdir`). A command that can write +/// or remove such a copy calls this once, after the last step that can +/// change a copy or take one back and before it gives up its apply lock. +/// Nothing is done in a dry run or a `--global` run, and a run whose +/// `--ecosystems` leaves `golang`, `cargo`, `maven` or `pypi` out only takes away +/// that ecosystem's pair of a copy that is gone. So does the prune pass of +/// a scan, which comes here after its scan has (`adds` false) and can only +/// have removed a copy: a file it cannot write is left to the next +/// command's warning. /// -/// A human run is told here that the file changed, or why it could not be; +/// A human run is told here that a file changed, or why it could not be; /// the result is that warning again, for the command's envelope. pub(crate) async fn sync_bazelignore( common: &crate::args::GlobalArgs, adds: bool, ) -> Vec { - use socket_patch_core::bazel::ignore; - use socket_patch_core::crawlers::Ecosystem::{Cargo, Golang, Maven}; + use socket_patch_core::bazel::{distdir, ignore}; + use socket_patch_core::crawlers::Ecosystem::{Cargo, Golang, Maven, Pypi}; + use socket_patch_core::vendor::pypi_distdir::sync_bazelrc; let mut warnings = Vec::new(); if common.dry_run || common.is_global() { return warnings; @@ -87,13 +92,14 @@ pub(crate) async fn sync_bazelignore( projects.push(common.project_root()); } let (loud, mut told) = (!common.json && !common.silent, Vec::new()); - let [go, cargo, maven] = - [Golang, Cargo, Maven].map(|eco| adds && common.ecosystem_selected(eco)); + let [go, cargo, maven, pypi] = + [Golang, Cargo, Maven, Pypi].map(|eco| adds && common.ecosystem_selected(eco)); for project in projects { - match ignore::sync(&project, go, cargo, maven).await { - Ok(Some((file, copies))) if loud => { - // A root that both projects are under is named once for - // each kind of copy whose lines changed there. + // For each file that changed: the line a person is told, and what + // that line is told once by. + let copies = ignore::sync(&project, go, cargo, maven).await; + let copies = copies.map(|changed| { + changed.map(|(file, copies)| { let (shown, copies) = (file.display(), copies.join(" and ")); let line = match file.exists() { true => format!( @@ -104,21 +110,47 @@ pub(crate) async fn sync_bazelignore( format!("Removed {shown}: no patched {copies} copy is left under .socket") } }; - if !told.contains(&line) { + // A root that both projects are under is named once for + // each kind of copy whose lines changed there. + (line.clone(), line) + }) + }); + let wheels = sync_bazelrc(&project, pypi).await.map(|changed| { + changed.map(|file| { + let shown = file.display(); + let line = match file.exists() { + true => format!( + "Updated {shown}: the lines that make Bazel take patched wheels from \ + .socket/vendor/pypi" + ), + false => format!( + "Removed {shown}: no patched wheel is left under .socket/vendor/pypi for \ + Bazel to take" + ), + }; + // A root that both projects are under is named once. + (shown.to_string(), line) + }) + }); + let synced = [ + (copies, ignore::NOT_UPDATED), + (wheels, distdir::NOT_UPDATED), + ]; + for (synced, not_updated) in synced { + match synced { + Ok(Some((once, line))) if loud && !told.contains(&once) => { println!("{line}"); - told.push(line); + told.push(once); } - } - Err(detail) if adds => { - if loud { - eprintln!("Warning: {detail}"); + Err(detail) if adds => { + if loud { + eprintln!("Warning: {detail}"); + } + let warning = crate::json_envelope::RunWarning::new(not_updated, detail); + warnings.push(warning); } - warnings.push(crate::json_envelope::RunWarning::new( - ignore::NOT_UPDATED, - detail, - )); + _ => {} } - _ => {} } } warnings diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 2505e0cfd..67eb91caa 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -1950,7 +1950,13 @@ async fn unbuilt_by_bazel( } let patched = |purl: &String| { let record = plan.view.patches.get(purl)?; - let judged = !plan.hosted.contains_key(purl) && !record.vulnerabilities.is_empty(); + // A wheel committed as a download cache of Bazel is pinned in the + // file the hub reads as a hosted pin is: by its URL and sha256. + let cached = plan.vendor_entries.get(purl); + let cached = cached + .is_some_and(|entry| socket_patch_core::vendor::pypi_distdir::line_of(entry).is_some()); + let pinned = cached || plan.hosted.contains_key(purl); + let judged = !pinned && !record.vulnerabilities.is_empty(); judged.then(|| Patched { purl: purl.clone(), uuid: record.uuid.clone(), 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 758f68df2..981df60ee 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -1008,6 +1008,14 @@ impl Cell { Run::of(cmd).unwrap_or_else(|why| panic!("{}: {why}", self.test)) } + /// [`Cell::bazel`] from the directory `dir` of the workspace copy, as a + /// user who works below the root runs it. + pub fn bazel_below(&self, dir: &str, command: &str, args: &[&str]) -> Run { + let mut cmd = self.command("update", command, args); + cmd.current_dir(self.path(dir)); + Run::of(cmd).unwrap_or_else(|why| panic!("{}: {why}", self.test)) + } + /// `bazel build --lockfile_mode=error `: passes only when /// `MODULE.bazel.lock` already holds what the build resolves. fn frozen_build(&self, targets: &[&str]) -> Run { 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 357c8e54d..ee318c593 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs @@ -42,19 +42,27 @@ //! 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. //! -//! 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 +//! Vendored mode as it is without Bazel 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 where the hub reads that file and +//! the checkout does not show that the other form works, the command +//! declines the package and writes nothing ([`vendored_pip_parse`]): the +//! build stays the unpatched one. With `--allow-vendored-in-bazel` it +//! writes the path line, 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. //! +//! The vendored copy that rules_python does build is in +//! [`vendored_download_cache`]: hosted mode's pin, the patched wheel +//! committed where a `--distdir` line of `.bazelrc` makes Bazel look for +//! its downloads, and so a build that needs no patch host. Vendored mode +//! writes that where the checkout shows that it works, which the fixture +//! does once Bazel has built in it, and declines elsewhere. +//! //! 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 //! the index, and the JSON document `rollback` reads through @@ -97,6 +105,7 @@ use sha2::{Digest, Sha512}; use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; +use crate::envelope::{all_codes, event_for, find_event}; use crate::harness::{ cell_without_bazel, changed, fixture_path, rewrite, with_vex, Cell, Claim, Declined, Fixture, How, Ran, StandIn, Tree, ALLOW, CONSUMER, NOTHING, VENDORED, @@ -264,8 +273,19 @@ fn grant(standin: &StandIn, uuid: &str, pinned: &Wheel) -> String { /// [`grant`] with `integrity` as the sums the grant names for the wheel. fn grant_by(standin: &StandIn, uuid: &str, pinned: &Wheel, integrity: Value) -> String { + grant_at(standin, (uuid, uuid), pinned, integrity) +} + +/// [`grant_by`] for the patch `uuid`, at a URL that names the id `level` +/// where a patch host names the patch. +fn grant_at( + standin: &StandIn, + (uuid, level): (&str, &str), + pinned: &Wheel, + integrity: Value, +) -> String { let filename = pinned.filename(); - let route = format!("/patch/pypi/{NAME}/{VERSION}/grant-token/{uuid}/{filename}"); + let route = format!("/patch/pypi/{NAME}/{VERSION}/grant-token/{level}/{filename}"); let url = format!("{}{route}", standin.origin()); let reference = json!({ "status": "granted", @@ -570,13 +590,22 @@ fn hosted_pip_parse() { /// hashes of the module it changes. Vendored mode holds the wheel it /// downloads to that record. struct Vendoring { + /// The index, and with [`Vendoring::new`] the Socket API and the patch + /// host as well. standin: StandIn, + /// With [`Vendoring::apart`], the Socket API and the patch host on a + /// server of their own, until [`Vendoring::stop`]. + host: Option, + /// The origin of the Socket API and the patch host. + origin: String, /// The id of the run and of its patch. uuid: String, wheels: [Wheel; 2], patched: Wheel, /// The route of the patched wheel on the stand-in's patch host. route: String, + /// The sums the grant names for the patched wheel. + sums: Value, /// The record of the patch, as the API serves it. record: Value, } @@ -591,19 +620,31 @@ fn vendored_line(copy: &str, wheel: &Wheel) -> String { impl Vendoring { fn new() -> Vendoring { + Vendoring::on(None) + } + + /// [`Vendoring::new`] with the Socket API and the patch host on a + /// server of their own, which a flow can stop while the index goes on + /// answering. + fn apart() -> Vendoring { + Vendoring::on(Some(StandIn::start())) + } + + fn on(host: Option) -> Vendoring { let uuid = uuid::Uuid::new_v4().to_string(); let wheels = upstream(&uuid); let marker = format!("PATCHED {uuid}"); let patched = package(&marker, &uuid); - let standin = StandIn::start(); - wheels.iter().for_each(|wheel| publish(&standin, wheel)); - standin.serve(5, OTHER_PROJECTS, NO_FILES.as_bytes()); + let index = StandIn::start(); + wheels.iter().for_each(|wheel| publish(&index, wheel)); + index.serve(5, OTHER_PROJECTS, NO_FILES.as_bytes()); + let standin = host.as_ref().unwrap_or(&index); // Vendored mode downloads the wheel itself, and takes it only by // its sha512. let sha512 = base64::engine::general_purpose::STANDARD.encode(Sha512::digest(&patched.bytes)); let sums = json!({ "sha256": patched.sha256, "sha512": format!("sha512-{sha512}") }); - let route = grant_by(&standin, &uuid, &patched, sums); + let route = grant_by(standin, &uuid, &patched, sums.clone()); standin.serve(5, &route, &patched.bytes); let hash = |marker: &str| compute_git_sha256_from_bytes(module(marker, &uuid).as_bytes()); let record = json!({ @@ -623,12 +664,16 @@ impl Vendoring { }); let record_route = format!("/v0/orgs/{ORG}/patches/view/{uuid}"); standin.serve(1, &record_route, record.to_string().as_bytes()); + let origin = standin.origin(); Vendoring { - standin, + standin: index, + host, + origin, uuid, wheels, patched, route, + sums, record, } } @@ -641,13 +686,26 @@ impl Vendoring { /// [`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 origin = &self.origin; + let json_api = format!("{}/{INDEX}/pypi", self.standin.origin()); let env = [ ("SOCKET_PATCH_SERVER_URL", origin.as_str()), ("SOCKET_PYPI_JSON_API", json_api.as_str()), ]; - cell.socket_patch(&origin, args, &[&env[..], more].concat()) + cell.socket_patch(origin, args, &[&env[..], more].concat()) + } + + /// How often the patched wheel was asked for at the patch host. + fn fetched(&self) -> usize { + let host = self.host.as_ref().unwrap_or(&self.standin); + host.asked(&self.route) + } + + /// Stop the patch host of [`Vendoring::apart`], and the Socket API + /// with it: the index goes on answering. + fn stop(&mut self) { + let host = self.host.take().expect("a host apart from the index"); + host.stop(); } } @@ -757,30 +815,20 @@ fn 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`. +/// Vendored mode beside a hub that reads `requirements.txt`, where the +/// checkout does not show that Bazel takes a committed wheel. /// /// - (a) `bazel build` and `bazel run //:consumer` print the unpatched /// marker. -/// - (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 +/// - (b) The checkout loses Bazel's lock, as a clone of a repository that +/// does not commit it has none: nothing says which rules_python Bazel +/// selected. `scan --mode vendored --yes` declines the package: it exits +/// 1, names the call of `MODULE.bazel` that reads the file, hosted mode, +/// the switch and that reason, writes nothing and downloads no wheel. +/// The same two Bazel commands print the unpatched marker, and leave the +/// files of step (a). +/// - (c) With `--allow-vendored-in-bazel` the command writes what it +/// writes without Bazel ([`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` @@ -810,10 +858,21 @@ fn vendored_pip_parse() { // (a) The unpatched build. let before = cell.builds_unpatched(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 package. - declines(&cell, &with, &VENDORED, 1, "failed", &before); + // (b) The one command of vendored mode, without Bazel's lock: + // declined, with nothing written and nothing of the patch fetched. The + // same build passes, on the upstream package, and writes the lock of + // before. + std::fs::remove_file(cell.path(LOCK)).expect("remove Bazel's lock"); + let unlocked = cell.tree(); + let declined = with.run(&cell, &VENDORED); + let [call, file] = refusal_names(&cell); + let unshown = "does not say which release of rules_python Bazel selected"; + let package = Declined { + purl: PURL, + code: DECLINED, + names: &[&call, &file, unshown], + }; + cell.declined(&declined, &package, 1, "failed", &unlocked); assert_eq!(with.standin.asked(&with.route), 0, "{test}"); cell.builds_patched(&before, UNPATCHED); @@ -851,8 +910,9 @@ fn vendored_pip_parse() { cell.stands_alone(run, &claim, true); println!( - "{test}: Bazel {release} built {UNPATCHED:?}; `scan --mode vendored` declined \ - ({DECLINED}), wrote nothing, and the build stayed {UNPATCHED:?}; with {ALLOW} it \ + "{test}: Bazel {release} built {UNPATCHED:?}; without Bazel's lock `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; {:?}", @@ -860,6 +920,130 @@ fn vendored_pip_parse() { ); } +/// The comment line above a `--distdir` line of `.bazelrc`. +const CACHE_COMMENT: &str = "# socket-patch: the committed copy of a patched wheel, for \ + Bazel's downloads (to opt out, comment out the next line)"; + +/// Give the checkout of `cell` a `--distdir` of the user's own: a +/// directory of downloads, and its line at the end of `.bazelrc`. +fn has_a_distdir_of_its_own(cell: &Cell) { + cell.write("third_party/distfiles/notes.txt", "downloads of our own\n"); + let rc = String::from_utf8(cell.tree()[".bazelrc"].clone()).expect("a text file"); + cell.write( + ".bazelrc", + format!("{rc}common --distdir=third_party/distfiles\n"), + ); +} + +/// Vendored mode beside a hub that reads `requirements.txt`, where the +/// checkout shows that Bazel takes a committed wheel: the patched wheel as +/// a download cache of Bazel. The checkout has a `--distdir` of the user's +/// own in its `.bazelrc` from the start. +/// +/// - (a) `bazel build` and `bazel run //:consumer` print the unpatched +/// marker. +/// - (b) `scan --mode vendored --yes` passes ([`caches`]). It writes the +/// three files that this flow wrote by hand before the command did +/// ([`cached_by_hand`]), byte for byte: the line of `requirements.txt` +/// as hosted mode writes it, the wheel under +/// `.socket/vendor/pypi//`, and +/// `common --distdir=.socket/vendor/pypi/` under a comment line at +/// the end of `.bazelrc`, after the lines the checkout had. It fetched the +/// wheel once, and Bazel's repository cache does not hold it. +/// `vendor --check` passes, and `vex` attests the package as vendored. +/// The patch host is then stopped, and the Socket API with it. The index +/// goes on answering, since a hub asks it about the other packages. +/// - (c) On a second machine (a new output base), with one byte of the +/// committed copy changed: `vendor --check` fails, and so does the +/// build. Bazel passes over a copy whose sha256 is not the pin's, and +/// asks the patch host, which does not answer. +/// - (d) On a third machine, with the copy as it was committed: a build +/// from a sub-directory passes, and the two Bazel commands print the +/// patched marker, although the patch host is stopped. The repository +/// cache holds the wheel afterwards, and Bazel changed no file of the +/// checkout but its own lock, as in hosted mode. +/// - (e) `vendor --revert --yes`, with the patch host still stopped, puts +/// every file back, the `.bazelrc` with its own lines among them, and the +/// two Bazel commands print the unpatched marker again. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn vendored_download_cache() { + let test = "pypi::vendored_download_cache"; + let started = Instant::now(); + let Some(mut cell) = Cell::open(test, &FIXTURE) else { + return; + }; + let release = cell.release().to_string(); + let mut with = Vendoring::apart(); + cell.route_downloads(&downloads(&with.standin.origin(), &with.wheels)); + cell.write(REQUIREMENTS, requirements(&with.wheels)); + has_a_distdir_of_its_own(&cell); + let marker = format!("OUT: PATCHED {}", with.uuid); + let sha256 = with.patched.sha256.clone(); + + // (a) The unpatched build. + let before = cell.builds_unpatched(UNPATCHED); + + // (b) The one command of vendored mode, and what it says of the copy. + let (copy, cached) = caches(&cell, &with, &before); + assert_eq!(with.fetched(), 1, "{test}: the wheel is fetched once"); + assert!( + !cell.cached(&sha256), + "{test}: the repository cache holds it" + ); + let check = with.run(&cell, &["vendor", "--check"]); + assert_eq!(check.code, 0, "{test}: {}", check.dump); + let run = |cell: &Cell, args: &[&str]| with.run(cell, args); + cell.stands_alone(run, &Claim::new(PURL, &with.uuid, How::Vendored), true); + assert_eq!(changed(&cached, &cell.tree()), NOTHING, "{test}"); + with.stop(); + + // (c) One changed byte, on a machine that has built nothing. The + // message names the URL of the pin; a console may break it. + let twin = cell.twin(); + let mut bytes = with.patched.bytes.clone(); + bytes[0] ^= 1; + twin.write(©, bytes); + let check = with.run(&twin, &["vendor", "--check"]); + assert_eq!(check.code, 1, "{test}: {}", check.dump); + let build = twin.bazel("build", &[CONSUMER]); + let squeezed = |text: &str| text.split_whitespace().collect::(); + assert!( + !build.ok() && squeezed(&build.stderr()).contains(&squeezed(&with.route)), + "{test}: the build with a changed copy did not fail on the download of the wheel:\n{}", + build.dump() + ); + assert!(!twin.cached(&sha256), "{test}: {}", build.dump()); + drop(twin); + + // (d) The copy as committed, on a machine that has built nothing: its + // first Bazel command runs below the root. + let twin = cell.twin(); + std::fs::create_dir(twin.path("sub")).expect("create sub"); + let below = twin.bazel_below("sub", "build", &[CONSUMER]); + assert!(below.ok(), "{test}: {}", below.dump()); + twin.builds(&marker); + assert!(twin.cached(&sha256), "{test}: Bazel did not keep the wheel"); + let recorded = cell.numbers() >= (8, 5, 0); + let bazel_rewrites: &[&str] = if recorded { &[LOCK] } else { &[] }; + assert_eq!(changed(&cached, &twin.tree()), bazel_rewrites, "{test}"); + drop(twin); + + // (e) The undo, which needs no host. + let undo = with.run(&cell, &["vendor", "--revert", "--yes"]); + cell.undone(&undo, "removed", &before, UNPATCHED); + + println!( + "{test}: Bazel {release} built {UNPATCHED:?}; `scan --mode vendored` committed {copy}, \ + pinned it by its URL and wrote `common --distdir` to .bazelrc; with the patch host \ + stopped, a new output base failed on a copy with one changed byte, which `vendor \ + --check` named, and built {marker:?} from the copy as committed, from a sub-directory \ + too, with no request for the wheel; Bazel rewrote {bazel_rewrites:?} itself; `vendor \ + --revert` put every file back and the build printed {UNPATCHED:?}; {:?}", + started.elapsed() + ); +} + /// Without a Bazel: the fixture in a checkout of its own, with the /// `requirements.txt` that pins the wheels of `with`. fn checkout(with: &Vendoring) -> Cell { @@ -1031,6 +1215,491 @@ fn every_command_that_would_vendor_declines_beside_a_hub_that_reads_the_requirem cell.vendors_on_the_users_word(run, &package); } +/// What vendored mode reads of the `MODULE.bazel.lock` that a build writes: +/// the version of the lock, and the release of rules_python that Bazel +/// selected. The checkout of [`checkout`] has no such file: no Bazel has +/// built there. +fn bazel_lock(version: u32, rules_python: &str) -> String { + let source = format!("https://bcr.bazel.build/modules/rules_python/{rules_python}/source.json"); + json!({ "lockFileVersion": version, "registryFileHashes": { source: "sha256-x" } }).to_string() +} + +/// The files of a checkout that holds the patch of `with` as a download +/// cache, beside those of `before`, as a person writes them by hand: the +/// line of `requirements.txt` that hosted mode writes, the patched wheel +/// under `.socket/vendor/pypi/`, by the name its URL ends in, and +/// at the end of `.bazelrc` a comment line and the line that makes that +/// directory one Bazel looks in before it downloads. Bazel takes a file +/// from there by the name of the download and its sha256, which the pin +/// holds. Gives the path of the wheel and the three files. +fn cached_by_hand(with: &Vendoring, before: &Tree) -> (String, [(String, Vec); 3]) { + let dir = format!(".socket/vendor/pypi/{}", with.uuid); + let copy = format!("{dir}/{}", with.patched.filename()); + let [dependency, _] = &with.wheels; + let direct = format!("{NAME} @ {}{}", with.origin, with.route); + let pinned = format!( + "{}{direct} --hash=sha256:{}\n", + dependency.requirement(), + with.patched.sha256 + ); + let rc = String::from_utf8_lossy(&before[".bazelrc"]); + let rc = format!("{rc}{CACHE_COMMENT}\ncommon --distdir={dir}\n"); + let files = [ + (".bazelrc".to_string(), rc.into_bytes()), + (copy.clone(), with.patched.bytes.clone()), + (REQUIREMENTS.to_string(), pinned.into_bytes()), + ]; + (copy, files) +} + +/// The one command of vendored mode in the checkout of `cell`, where the +/// hub reads `requirements.txt` and the workspace shows that Bazel takes a +/// committed wheel: `scan --mode vendored --yes` passes, and writes the +/// files of [`cached_by_hand`], byte for byte, with what vendored mode +/// keeps beside every wheel and its ledger. It says in a warning what the +/// form does not do. Gives the path of the wheel and the files of the +/// checkout. +fn caches(cell: &Cell, with: &Vendoring, before: &Tree) -> (String, Tree) { + let test = &cell.test; + let scan = with.run(cell, &VENDORED); + 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 (copy, by_hand) = cached_by_hand(with, before); + let dir = format!(".socket/vendor/pypi/{}", with.uuid); + let written = [ + ".bazelrc".to_string(), + format!("{dir}/.gitattributes"), + format!("{dir}/.gitignore"), + format!("{dir}/socket-patch.vendor.json"), + copy.clone(), + ".socket/vendor/state.json".to_string(), + REQUIREMENTS.to_string(), + ]; + assert_eq!(changed(before, &vendored), written, "{test}: {said}"); + for (file, bytes) in by_hand { + assert!( + vendored[&file] == bytes, + "{test}: {file} is not the file written by hand:\n{}\n{said}", + String::from_utf8_lossy(&vendored[&file]) + ); + } + let warned = all_codes(&scan.envelope).contains(&CACHE_NOTICE.to_string()); + assert!(warned, "{test}: no {CACHE_NOTICE}: {said}"); + (copy, vendored) +} + +/// The code of the warning with which a run says what a download cache +/// does not do. +const CACHE_NOTICE: &str = "vendor_pypi_bazel_download_cache"; + +/// Without a Bazel: the fixture's checkout as a build leaves it, where the +/// hub reads `requirements.txt`, Bazel selected the rules_python of the +/// fixture and no rc file names a downloader setting. `scan --mode +/// vendored` commits the patched wheel as a download cache of Bazel +/// ([`caches`]). A later run, with the mode or without, with the switch or +/// without, passes and writes nothing. `vendor --check` holds the wheel to +/// the patch: it passes, and fails on one changed byte. `list` and `vex` +/// show a vendored package, and `vex` attests it as not affected. Each of +/// `vendor --revert`, `rollback` and `remove` puts every file back: the +/// pin, and the `.bazelrc` with the lines of the user. +#[test] +fn vendored_mode_commits_a_download_cache_where_the_workspace_shows_it_works() { + let with = Vendoring::new(); + let cell = checkout(&with); + cell.write(LOCK, bazel_lock(28, "2.5.0-rc4")); + let before = cell.tree(); + let run = |cell: &Cell, args: &[&str]| with.run(cell, args); + let (copy, vendored) = caches(&cell, &with, &before); + assert_eq!(with.fetched(), 1); + + for later in [ + &VENDORED[..], + &["scan", "--yes"], + &[&VENDORED[..], &[ALLOW]].concat(), + ] { + let scan = run(&cell, later); + assert_eq!(scan.code, 0, "{}", scan.dump); + assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{}", scan.dump); + } + assert_eq!(with.fetched(), 1); + + let check = run(&cell, &["vendor", "--check"]); + assert_eq!(check.code, 0, "{}", check.dump); + assert_eq!(check.envelope["summary"]["verified"], 1, "{}", check.dump); + let mut bytes = with.patched.bytes.clone(); + bytes[0] ^= 1; + cell.write(©, bytes); + let check = run(&cell, &["vendor", "--check"]); + assert_eq!(check.code, 1, "{}", check.dump); + let failed = event_for(&check.envelope, PURL); + assert_eq!(failed["errorCode"], "vendor_check_failed", "{}", check.dump); + cell.write(©, &with.patched.bytes); + + let list = run(&cell, &["list"]); + let listed = list.envelope.to_string(); + assert!(listed.contains("\"vendored\""), "{}", list.dump); + assert!(!listed.contains("\"hosted\""), "{}", list.dump); + let claim = Claim::new(PURL, &with.uuid, How::Vendored); + cell.stands_alone(run, &claim, true); + cell.stands_alone(run, &claim, false); + assert_eq!(changed(&vendored, &cell.tree()), NOTHING); + + // The line the run wrote, changed by hand (a comment after it, its hash + // on a line of its own, a second blank): the next run declines the + // package before it fetches anything, so the committed wheel, its line + // of `.bazelrc` and the changed line all stay. + let wrote = String::from_utf8(vendored[REQUIREMENTS].clone()).expect("a text file"); + let line = wrote.lines().last().expect("the line of the package"); + let names = refusal_names(&cell); + let changed_by_hand = Declined { + purl: PURL, + code: DECLINED, + names: &[ + &names[0], + "has been changed since", + "`socket-patch vendor --revert`", + ], + }; + for by_hand in [ + format!("{line} # checked"), + line.replace(" --hash", " \\\n --hash"), + line.replacen(' ', " ", 1), + ] { + assert_ne!(by_hand, line); + cell.write(REQUIREMENTS, wrote.replace(line, &by_hand)); + let kept = cell.tree(); + let scan = run(&cell, &VENDORED); + cell.declined(&scan, &changed_by_hand, 1, "failed", &kept); + } + assert_eq!(with.fetched(), 1); + cell.write(REQUIREMENTS, &wrote); + + let undos: [&[&str]; 3] = [ + &["vendor", "--revert", "--yes"], + &["rollback", "--yes"], + &["remove", PURL, "--yes"], + ]; + for undo in undos { + let ran = run(&cell, undo); + assert_eq!(ran.code, 0, "{}", ran.dump); + let undone = changed(&before, &cell.tree()); + assert_eq!(undone, NOTHING, "{undo:?}: {}", ran.dump); + caches(&cell, &with, &before); + } + + // Hosted mode takes the package over: the pin stays, and the copy and + // its line of `.bazelrc` go. Vendored mode takes it back. + let hosted = run(&cell, &["scan", "--mode", "hosted", "--yes"]); + assert_eq!(hosted.code, 0, "{}", hosted.dump); + let (_, by_hand) = cached_by_hand(&with, &before); + let [_, _, (_, pinned)] = by_hand; + let taken = cell.tree(); + assert_eq!(changed(&before, &taken), [REQUIREMENTS], "{}", hosted.dump); + assert!(taken[REQUIREMENTS] == pinned, "{}", hosted.dump); + let listed = run(&cell, &["list"]).envelope.to_string(); + assert!(listed.contains("\"hosted\"") && !listed.contains("\"vendored\"")); + caches(&cell, &with, &before); + + // A user who comments the line out has declined it: a later run adds + // none, and the undo leaves those two lines of the user. + let line = format!("common --distdir=.socket/vendor/pypi/{}", with.uuid); + let rc = String::from_utf8(vendored[".bazelrc"].clone()).expect("a text file"); + let declined = rc.replace(&line, &format!("# {line}")); + assert_ne!(declined, rc); + cell.write(".bazelrc", &declined); + let kept = cell.tree(); + let scan = run(&cell, &VENDORED); + assert_eq!(scan.code, 0, "{}", scan.dump); + assert_eq!(changed(&kept, &cell.tree()), NOTHING, "{}", scan.dump); + let undo = run(&cell, &["vendor", "--revert", "--yes"]); + assert_eq!(undo.code, 0, "{}", undo.dump); + let undone = cell.tree(); + assert_eq!(changed(&before, &undone), [".bazelrc"], "{}", undo.dump); + assert!(undone[".bazelrc"] == declined.as_bytes(), "{}", undo.dump); +} + +/// Without a Bazel: a newer patch of a package that is a download cache +/// replaces the older one. The line names the newer wheel, the older +/// directory and its line of `.bazelrc` are gone, and the undo still puts +/// back the pin of before the first patch. +#[test] +fn a_newer_patch_replaces_the_download_cache_of_the_older_one() { + let (older, newer) = (Vendoring::new(), Vendoring::new()); + let cell = checkout(&older); + cell.write(LOCK, bazel_lock(28, "2.5.0-rc4")); + let before = cell.tree(); + caches(&cell, &older, &before); + + let scan = newer.run(&cell, &VENDORED); + assert_eq!(scan.code, 0, "{}", scan.dump); + let replaced = cell.tree(); + let (copy, by_hand) = cached_by_hand(&newer, &before); + for (file, bytes) in by_hand { + // The line pins the dependency as the checkout does: the wheels + // of the first run. + let bytes = match file == REQUIREMENTS { + true => { + let [dependency, _] = &older.wheels; + let direct = format!("{NAME} @ {}{}", newer.origin, newer.route); + let sha256 = &newer.patched.sha256; + let pin = format!( + "{}{direct} --hash=sha256:{sha256}\n", + dependency.requirement() + ); + pin.into_bytes() + } + false => bytes, + }; + assert!( + replaced[&file] == bytes, + "{file}:\n{}\n{}", + String::from_utf8_lossy(&replaced[&file]), + scan.dump + ); + } + let of_older = |file: &&String| file.contains(&older.uuid); + let left: Vec<&String> = replaced.keys().filter(of_older).collect(); + assert!(left.is_empty() && replaced.contains_key(©), "{left:?}"); + let rc = String::from_utf8_lossy(&replaced[".bazelrc"]); + assert!(!rc.contains(&older.uuid), "{rc}"); + + let undo = newer.run(&cell, &["vendor", "--revert", "--yes"]); + assert_eq!(undo.code, 0, "{}", undo.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", undo.dump); +} + +/// Without a Bazel: where the checkout does not show that Bazel takes a +/// committed wheel, vendored mode declines the package as before, says +/// why, writes nothing and fetches no wheel. Each checkout is the one of +/// [`vendored_mode_commits_a_download_cache_where_the_workspace_shows_it_works`] +/// but for one thing: a rules_python or a Bazel it is not shown for, an rc +/// file that names a downloader setting or imports a file from outside the +/// checkout, a `.bazelrc` that is read-only, a hub that hands Bazel +/// another file of the project as well, a pin without a hash, and a lock +/// of a tool beside the requirements. +#[test] +fn a_download_cache_is_declined_where_the_workspace_does_not_show_that_it_works() { + let with = Vendoring::new(); + let files = checkout(&with).tree(); + let text = |file: &str| String::from_utf8(files[file].clone()).expect("a text file"); + let own = format!("requirements_lock = \"//:{REQUIREMENTS}\""); + let more = format!("{own},\n requirements_windows = \"//:win.txt\""); + let downloads = "common --downloader_config=ci/downloads.cfg\n"; + let unhashed = requirements(&with.wheels).replace(" \\\n --hash=sha256:", " # "); + // The package held by a URL that is the user's own, not one of a patch. + let own_url = requirements(&with.wheels).replace( + &format!("{NAME}=={VERSION}"), + &format!( + "{NAME} @ https://files.example/{}", + with.wheels[1].filename() + ), + ); + // What each checkout has that the one of the test above has not, and + // what the refusal says of it. + let cases = || -> [(&str, &str, String); 8] { + [ + ( + "which .bazelrc:6 imports from outside the checkout", + ".bazelrc", + text(".bazelrc") + "try-import /etc/bazel/site.bazelrc\n", + ), + ( + "Bazel selected rules_python 2.4.6", + LOCK, + bazel_lock(28, "2.4.6"), + ), + ( + "name the release in `.bazelversion`", + LOCK, + bazel_lock(29, "2.5.0-rc4"), + ), + ( + "the checkout names Bazel 10.0.0", + ".bazelversion", + "10.0.0\n".to_string(), + ), + ( + ".bazelrc:6 names `--downloader_config=ci/downloads.cfg`", + ".bazelrc", + text(".bazelrc") + downloads, + ), + ( + "names more than `requirements_lock = \"requirements.txt\"`", + "MODULE.bazel", + text("MODULE.bazel").replace(&own, &more), + ), + ( + "requirements.txt pins no hashes", + REQUIREMENTS, + unhashed.clone(), + ), + ( + "a tool's lock of this project holds the package", + "uv.lock", + "version = 1\n".to_string(), + ), + ] + }; + for (why, file, content) in cases() { + let cell = checkout(&with); + cell.write(LOCK, bazel_lock(28, "2.5.0-rc4")); + assert!( + files.get(file) != Some(&content.clone().into_bytes()), + "{file}" + ); + cell.write(file, content); + let names = refusal_names(&cell); + let package = Declined { + purl: PURL, + code: DECLINED, + names: &[&names[0], "is written only where the checkout shows", why], + }; + let before = cell.tree(); + cell.declined(&with.run(&cell, &VENDORED), &package, 1, "failed", &before); + // The dry run names it too. + let dry = with.run(&cell, &[&VENDORED[..], &["--dry-run"]].concat()); + cell.declined(&dry, &package, 0, "skipped", &before); + } + // A `.bazelrc` that takes no line, where this user cannot write a + // read-only file (root can). + let cell = checkout(&with); + cell.write(LOCK, bazel_lock(28, "2.5.0-rc4")); + let rc = cell.path(".bazelrc"); + let mut bits = std::fs::metadata(&rc).expect(".bazelrc").permissions(); + bits.set_readonly(true); + std::fs::set_permissions(&rc, bits).expect("make .bazelrc read-only"); + if std::fs::OpenOptions::new().append(true).open(&rc).is_err() { + let names = refusal_names(&cell); + let package = Declined { + purl: PURL, + code: DECLINED, + names: &[&names[0], ".bazelrc is read-only"], + }; + let before = cell.tree(); + cell.declined(&with.run(&cell, &VENDORED), &package, 1, "failed", &before); + } + assert_eq!(with.fetched(), 0); + + // The package held by a URL of the user's own. No scan finds a package + // in such a line; `get` is given the release, and declines it before + // it fetches anything. + let cell = checkout(&with); + cell.write(LOCK, bazel_lock(28, "2.5.0-rc4")); + cell.write(REQUIREMENTS, own_url); + let names = refusal_names(&cell); + let package = Declined { + purl: PURL, + code: DECLINED, + names: &[ + &names[0], + "is written only where the checkout shows", + "names the package by a URL of its own", + ], + }; + let before = cell.tree(); + let get = ["get", PURL, "--mode", "vendored", "--yes"]; + cell.declined(&with.run(&cell, &get), &package, 1, "failed", &before); + assert_eq!(with.fetched(), 0); + + // A hosted pin of a requirement that the form is not written for: the + // run that would take it over is let through to put the registry's pin + // back, and declines once it sees that pin. The hosted pin stays. + let cell = checkout(&with); + cell.write(LOCK, bazel_lock(28, "2.5.0-rc4")); + let [(_, _, _), .., (unhashed, _, pins), _] = cases(); + cell.write(REQUIREMENTS, pins); + let hosted = with.run(&cell, &["scan", "--mode", "hosted", "--yes"]); + assert_eq!(hosted.envelope["summary"]["applied"], 1, "{}", hosted.dump); + let pinned = cell.tree(); + let taken = with.run(&cell, &VENDORED); + let declined = find_event(&taken.envelope, "failed", Some(DECLINED)); + let why = declined["error"].as_str().unwrap_or_default(); + assert!( + taken.code == 1 && declined["purl"] == PURL && why.contains(unhashed), + "{}", + taken.dump + ); + assert_eq!(changed(&pinned, &cell.tree()), NOTHING, "{}", taken.dump); + assert_eq!(with.fetched(), 0); +} + +/// Without a Bazel: a run that fails after it fetched the wheel keeps a +/// copy that an earlier run committed. The pin of the registry is back in +/// `requirements.txt`, as after a relock, so the run vendors the package +/// again. It asks another service, which grants the patch as a wheel at a +/// URL that names another id where a patch host names the patch: no line +/// is written for such a URL. The wheel, its ledger entry and its line of +/// `.bazelrc` stay; only the time in the note beside the wheel is new. +#[test] +fn a_run_that_fails_after_the_fetch_keeps_the_committed_wheel() { + let with = Vendoring::new(); + let cell = checkout(&with); + cell.write(LOCK, bazel_lock(28, "2.5.0-rc4")); + let before = cell.tree(); + caches(&cell, &with, &before); + cell.write(REQUIREMENTS, &before[REQUIREMENTS]); + let relocked = cell.tree(); + + let other = StandIn::start(); + let level = uuid::Uuid::new_v4().to_string(); + let ids = (with.uuid.as_str(), level.as_str()); + let route = grant_at(&other, ids, &with.patched, with.sums.clone()); + other.serve(5, &route, &with.patched.bytes); + let record = format!("/v0/orgs/{ORG}/patches/view/{}", with.uuid); + other.serve(1, &record, with.record.to_string().as_bytes()); + let origin = other.origin(); + let scan = cell.socket_patch( + &origin, + &VENDORED, + &[("SOCKET_PATCH_SERVER_URL", origin.as_str())], + ); + let said = scan.envelope.to_string(); + assert!( + scan.code == 1 && said.contains("that names the patch on a patch host"), + "{}", + scan.dump + ); + assert_eq!(other.asked(&route), 1, "{}", scan.dump); + let note = format!(".socket/vendor/pypi/{}/socket-patch.vendor.json", with.uuid); + let mut left = changed(&relocked, &cell.tree()); + left.retain(|file| *file != note); + assert_eq!(left, NOTHING, "{}", scan.dump); +} + +/// Without a Bazel: a project below the Bazel root, whose `requirements.txt` +/// the hub reads. The line of `.bazelrc` is written at the Bazel root and +/// names the directory from there, and the undo takes it away. +#[test] +fn a_project_below_the_bazel_root_gets_its_line_in_the_root_s_rc_file() { + let with = Vendoring::new(); + let cell = checkout(&with); + cell.write(LOCK, bazel_lock(13, "2.5.0-rc4")); + std::fs::remove_file(cell.path(REQUIREMENTS)).expect(REQUIREMENTS); + cell.write(&format!("svc/{REQUIREMENTS}"), requirements(&with.wheels)); + let own = format!("\"//:{REQUIREMENTS}\""); + let module = String::from_utf8(cell.tree()["MODULE.bazel"].clone()).expect("a text file"); + let label = format!("\"//svc:{REQUIREMENTS}\""); + cell.write("MODULE.bazel", module.replace(&own, &label)); + let before = cell.tree(); + + let scan = with.run(&cell, &[&VENDORED[..], &["--cwd", "svc"]].concat()); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{}", scan.dump); + let vendored = cell.tree(); + let dir = format!("svc/.socket/vendor/pypi/{}", with.uuid); + let rc = String::from_utf8_lossy(&before[".bazelrc"]); + let rc = format!("{rc}{CACHE_COMMENT}\ncommon --distdir={dir}\n"); + assert_eq!(String::from_utf8_lossy(&vendored[".bazelrc"]), rc); + assert!(vendored.contains_key(&format!("{dir}/{}", with.patched.filename()))); + assert!(!vendored.contains_key("svc/.bazelrc")); + + let undo = with.run(&cell, &["vendor", "--revert", "--yes", "--cwd", "svc"]); + assert_eq!(undo.code, 0, "{}", undo.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", undo.dump); +} + /// 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 diff --git a/crates/socket-patch-core/src/bazel/built.rs b/crates/socket-patch-core/src/bazel/built.rs index 60cefae56..e06afd459 100644 --- a/crates/socket-patch-core/src/bazel/built.rs +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -368,6 +368,82 @@ fn reads( doubt.or_else(|| hidden().or_else(unread).cloned()).map(Err) } +/// Why the files of `workspace` do not show, with certainty, that the hub +/// of `ecosystem` hands Bazel `lock` and no other file of `locks`, each a +/// file of the project of `root` by its path from the project: `lock` +/// under `attribute` alone, in calls that run. `Ok` when they show it, +/// which takes what [`unbuilt`] takes: no doubt about the workspace or +/// about the hub, no `WORKSPACE` file that defines anything, and every +/// call of the hub written out, and none that names a requirements file +/// which brings a file of `locks` in with `-r` (each read with `read`). +/// +/// This is what vendored mode asks before it writes a form that only a +/// build through that one file takes ([`super::distdir`]): a call that +/// hands Bazel another file of the project for some platform builds from +/// a file the run does not write. +pub(crate) fn alone( + workspace: &Workspace, + root: &BazelRoot, + ecosystem: &str, + (attribute, lock): (&str, &str), + locks: &[String], + read: &dyn Fn(&str) -> Option, +) -> Result<(), String> { + let project = slashed(&root.project); + let Some(hub) = HUBS.iter().find(|hub| hub.ecosystem == ecosystem) else { + return Err(format!("no hub of {ecosystem} packages is known")); + }; + let tags = workspace.tags(&hub.extension, hub.tag); + if let Some(Doubt { file, line, why }) = workspace.doubts.first().or(tags.doubts.first()) { + return Err(format!("{file}:{line}: {why}")); + } + if workspace.legacy.is_some() { + let why = "a WORKSPACE file defines repositories beside MODULE.bazel, and what it does \ + with the packages of the hub is not read"; + return Err(why.to_string()); + } + let tag = format!("{}.{}", hub.extension.name, hub.tag); + for at in &tags.calls { + let (call, place) = (at.call, format!("`{tag}` ({}:{})", at.file, at.call.line)); + let given = hub.files.iter().filter(|file| call.arg(file).is_some()); + let written = |value: &Value| matches!(value, Value::Str(_) | Value::Dict(_)); + if call.unpacks() + || !given + .clone() + .all(|file| call.arg(file).is_some_and(written)) + { + return Err(format!("the files {place} names are not all written out")); + } + let named = files(workspace, call, hub.files, None); + let own = |file: &String| locks.iter().any(|own| below(&project, own) == *file); + if !named.iter().any(own) { + // A requirements file that brings one of them in with `-r` + // hands the hub that file as well, in whatever order the + // calls are written. + let includes = |file: &String| ecosystem == "pypi" && includes_one(file, &own, read); + if let Some(file) = named.iter().find(|file| includes(file)) { + return Err(format!( + "{place} names {file}, which brings a file of this project in with `-r`: \ + no build through such a file is shown to take the committed copy" + )); + } + continue; + } + if !call.whole { + return Err(format!( + "{place} may not run: it is no statement of its own" + )); + } + if !given.eq([&attribute]) || named != [below(&project, lock)] { + return Err(format!( + "{place} names more than `{attribute} = \"{lock}\"`, the one file that holds \ + the pin" + )); + } + } + Ok(()) +} + /// Whether the requirements file `start` (a path from the Bazel root) /// brings in a file for which `own` holds, through its `-r` includes and /// theirs, each read with `read`. An include that cannot be read brings in diff --git a/crates/socket-patch-core/src/bazel/distdir.rs b/crates/socket-patch-core/src/bazel/distdir.rs new file mode 100644 index 000000000..c34246269 --- /dev/null +++ b/crates/socket-patch-core/src/bazel/distdir.rs @@ -0,0 +1,680 @@ +//! The `.bazelrc` lines that make Bazel take a patched wheel from the +//! checkout, and what a workspace must show before one is written. +//! +//! rules_python's `pip.parse` fetches a requirement that names a wheel by +//! its URL with Bazel's downloader, by the sha256 of the line. Before +//! Bazel downloads a file that has a checksum, it looks in each +//! `--distdir` for a file of the download's name with that checksum, and +//! takes it. So where vendored mode pins the patched wheel by its URL on +//! the patch host, as hosted mode does, and commits the wheel under +//! `.socket/vendor/pypi//`, one line of the `.bazelrc` at the Bazel +//! root, `common --distdir=`, makes the build take the +//! committed copy and ask no host ([`crate::vendor::pypi_distdir`]). +//! +//! Measured with rules_python 2.5.0-rc4 on Bazel 9.3.2, 8.8.2 and 7.7.2: a +//! fresh clone builds the patched package with the patch host stopped, a +//! new output base and no copy in the repository cache, also from a +//! sub-directory and beside a `--distdir` of the user's own. Bazel reads a +//! relative path from the workspace root, and takes `%workspace%` in this +//! option literally, so the line holds the path from the Bazel root. With +//! the host stopped a changed or missing copy fails the build. With the +//! host up, Bazel passes over such a copy without a message and downloads +//! the wheel of the pin, never other bytes. A downloader config that +//! blocks the patch host fails the build although the copy is there: +//! Bazel refuses before it looks in a `--distdir`. +//! +//! A `--distdir` is one flat directory, searched by file name. Each patch +//! gets a line for its own directory: two patches of one release have +//! wheels of one name, and the directory of a patch is the unit that +//! vendored mode writes, checks and removes. + +use std::path::PathBuf; + +use super::ignore::{content, edited, settled, update, Kept}; +use super::maven::{asked, known_release}; +use super::rc::{declared_release, mentions, ModuleLock}; +use super::workspace::{disk, disk_up_to, Entry, Workspace}; +use super::BazelRoot; + +/// The warning code of a `.bazelrc` that [`sync`] could not update. +pub const NOT_UPDATED: &str = "bazelrc_not_updated"; + +/// The line above every line [`sync`] writes. +const COMMENT: &str = "# socket-patch: the committed copy of a patched wheel, for Bazel's \ + downloads (to opt out, comment out the next line)"; + +/// What every line of [`sync`] is about, for the one comment line they +/// share. +const WHEEL: &str = "wheel"; + +/// How a line of [`sync`] starts: the directory follows, from the Bazel +/// root. +const OPTION: &str = "common --distdir="; + +const LINES: Kept = Kept { + file: ".bazelrc", + comment: |_| COMMENT.to_string(), + // Only the line itself: a `--distdir` above the copy's is not searched + // below itself. + covers: |old, line| { + let mut lines = old.split_inclusive(|byte| *byte == b'\n'); + lines.any(|own| content(own) == line.as_bytes()) + }, +}; + +/// The module of the ruleset whose hub reads a requirements file. +const RULESET: &str = "rules_python"; + +/// The releases of [`RULESET`] whose hub is shown to fetch a wheel that a +/// requirement names by its URL with Bazel's downloader, under the name +/// the URL ends in and with the sha256 of the line: 2.5.0-rc4 was measured, +/// and 2.5.0 is the same commit. The releases before it fetch through +/// other code, which no build here has run. +const RULESETS: [&str; 2] = ["2.5.0-rc4", "2.5.0"]; + +/// The options of an rc file under which Bazel does not take a download +/// from a `--distdir`, or was not measured to. +const AGAINST: [&str; 3] = [ + "downloader_config", + "repository_disable_download", + "remote_downloader", +]; + +/// The path of the project of `root` from the Bazel root, as a line of +/// [`sync`] starts after [`OPTION`]: empty, or ending in `/`. +fn below(root: &BazelRoot) -> String { + let parts = root.project.components(); + parts + .map(|part| format!("{}/", part.as_os_str().to_string_lossy())) + .collect() +} + +/// Whether a line of an rc file takes `project`, a path from the Bazel +/// root, as it is: Bazel splits a line at blanks and reads quotes, `\` and +/// `#` otherwise. +fn plain(project: &str) -> bool { + !project.contains(|c: char| c.is_whitespace() || "\"'\\#".contains(c)) +} + +/// Make the `.bazelrc` at the Bazel root `root` agree with `dirs`, the +/// directories of the project's committed wheels, each by its path from +/// the project (`.socket/vendor/pypi/`): one line under [`COMMENT`] +/// for each while it exists and the file neither has nor declines the line +/// ([`settled`]), and no such pair for a directory of the project under +/// `.socket/vendor/pypi` that is gone. Without `add`, and for a project +/// whose path a line does not take as it is ([`plain`]), pairs are only +/// taken away. A directory that cannot be probed keeps what the file says of it, +/// and a file left empty is deleted. The edit is made as the one of +/// [`super::ignore`] is: under a lock of the root, never through a link. +/// +/// `Ok(Some)` is the file, when it was changed. `Err` is the detail of a +/// [`NOT_UPDATED`] warning. +pub fn sync(root: &BazelRoot, dirs: &[String], add: bool) -> Result, String> { + let from_root = below(root); + // A project that was moved to a path no line can hold as it is (a + // blank would start a second word for Bazel) gets no line: the build + // then downloads the wheel, as without the pair. + let add = add && plain(&from_root); + let project = root.dir.join(&root.project); + // `None`: it cannot be told. Only a directory that is not found is gone. + let exists = |dir: &str| match std::fs::metadata(project.join(dir)) { + Ok(meta) => Some(meta.is_dir()), + Err(e) => (e.kind() == std::io::ErrorKind::NotFound).then_some(false), + }; + let line = |dir: &str| format!("{OPTION}{from_root}{dir}"); + // The lines to have, and the lines the file has for a directory of + // this project that is gone. + let wanted = |old: &[u8]| { + // A copy that is there gets its line only from a run that adds. + let state = |dir: &str| exists(dir).filter(|there| add || !there); + let mut wanted: Vec<_> = (dirs.iter()) + .map(|dir| (line(dir), state(dir), WHEEL)) + .collect(); + let lines = old.split_inclusive(|byte| *byte == b'\n').map(content); + for had in lines.filter_map(|had| std::str::from_utf8(had).ok()) { + let dir = had.strip_prefix(&line("")); + let dir = dir.filter(|dir| dir.starts_with(".socket/vendor/pypi/")); + let gone = dir.is_some_and(|dir| exists(dir) == Some(false)); + if gone && !wanted.iter().any(|(line, ..)| line == had) { + wanted.push((had.to_string(), Some(false), WHEEL)); + } + } + wanted + }; + let mut edit = |old: &[u8]| edited(&LINES, old, &wanted(old)); + let (shown, failed, old) = match update(&LINES, &root.dir, &mut edit) { + Ok(changed) => return Ok(changed.map(|(file, ..)| file)), + Err(failed) => failed, + }; + let missing: Vec = wanted(&old) + .iter() + .filter(|(line, exists, _)| *exists == Some(true) && !settled(&LINES, &old, line)) + .map(|(line, ..)| format!("`{line}`")) + .collect(); + let advice = if !missing.is_empty() { + format!( + "add {} to it on a line of its own, so that Bazel takes the committed copy of the \ + patched wheel; without the line the build downloads the wheel from the patch host", + missing.join(" and ") + ) + } else { + "the lines under socket-patch's comment in it name directories that no longer exist \ + and can be deleted" + .to_string() + }; + Err(format!( + "could not update {}: {failed}; {advice}", + shown.display() + )) +} + +/// Why the files of the workspace `root` do not show that a build takes a +/// wheel from a line of [`sync`], for a project whose `locks` (each by its +/// path from the project) a run could rewrite and whose `lock` is the one +/// that holds the pin. `Ok` when they show all of it: +/// +/// - the hub hands Bazel `lock` and no other file of `locks`, in calls +/// that are read with certainty ([`super::built::alone`]); +/// - Bazel selected a release of [`RULESETS`], by what `MODULE.bazel.lock` +/// says it selected and the root module asks for, as the Maven lane +/// reads its ruleset's ([`known_release`]); +/// - the checkout names a Bazel 7, 8 or 9 (`.bazeliskrc`, `.bazelversion`), +/// or names none and has a lock that 7.5.0 to 9.3.2 write (measured: +/// 7.7.2, 8.8.2 and 9.3.2); +/// - no rc file of the checkout names an option of [`AGAINST`], all of +/// them can be read, and none imports a file from outside the checkout, +/// which is not read; +/// - the line can be written: the project's path holds nothing that an rc +/// file reads otherwise, and `.bazelrc` is no link and not read-only. +pub fn ready(root: &BazelRoot, lock: &str, locks: &[String]) -> Result<(), String> { + let project = below(root); + if !plain(&project) { + return Err(format!( + "the path of the project from the Bazel root, {project}, holds a character that a \ + line of .bazelrc does not take as it is" + )); + } + let rc = root.dir.join(LINES.file); + if crate::utils::containment::is_link(&rc) { + let link = "is a symbolic link, which socket-patch does not write through"; + return Err(format!("{} {link}", LINES.file)); + } + // The line editor reads only a regular file. A FIFO or device there + // would also block the append probe below in open(2). + if std::fs::metadata(&rc).is_ok_and(|m| !m.is_file()) { + return Err(format!("{} is not a regular file", LINES.file)); + } + // As the write itself asks: a file that is there opens for appending. + // Non-blocking on Unix, so a FIFO swapped in after the check above + // fails the open (ENXIO) instead of waiting for a reader. + let mut probe = std::fs::OpenOptions::new(); + probe.append(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::custom_flags(&mut probe, libc::O_NONBLOCK); + let denied = |e: std::io::Error| e.kind() == std::io::ErrorKind::PermissionDenied; + if probe.open(&rc).is_err_and(denied) { + let closed = "is read-only, so the line that makes Bazel take the committed wheel \ + cannot be written to it"; + return Err(format!("{} {closed}", LINES.file)); + } + let view = disk(&root.dir); + let view: &dyn Fn(&str) -> Entry = &view; + let workspace = Workspace::read(view); + let read = |file: &str| super::built::lock_text(&root.dir, file); + let hub = ("requirements_lock", lock); + super::built::alone(&workspace, root, "pypi", hub, locks, &read)?; + + let written = match disk_up_to(&root.dir, 64 << 20)("MODULE.bazel.lock") { + Entry::Text(lock) => ModuleLock::parse(&lock), + _ => ModuleLock::default(), + }; + let beyond = |selected: &str| { + format!( + "Bazel selected {RULESET} {selected}, and that the hub takes a committed wheel in \ + the place of a download is shown for {RULESET} 2.5.0 alone" + ) + }; + let asked = asked(&workspace, RULESET); + known_release(&asked, &written, RULESET, &RULESETS, "", &beyond)?; + match declared_release(view) { + Some((major, minor, patch)) if !(7..=9).contains(&major) => { + return Err(format!( + "the checkout names Bazel {major}.{minor}.{patch} (`.bazeliskrc` or \ + `.bazelversion`), and this is shown for Bazel 7, 8 and 9" + )) + } + None if !written.version.is_some_and(|v| (13..=28).contains(&v)) => { + let why = "no file of the checkout says that Bazel 7, 8 or 9 builds it: name the \ + release in `.bazelversion`"; + return Err(why.to_string()); + } + _ => {} + } + match mentions(view, &AGAINST, true).map(|found| found.into_iter().next()) { + Ok(None) => Ok(()), + Ok(Some((file, line, word))) => Err(format!( + "{file}:{line} names `{word}`, under which Bazel is not shown to take a download \ + from the checkout" + )), + Err(file) => Err(format!( + "the rc file {file} cannot be read, and may name a downloader config" + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + const UUID: &str = "11111111-1111-4111-8111-111111111111"; + const OTHER: &str = "33333333-3333-4333-8333-333333333333"; + + fn dir(uuid: &str) -> String { + format!(".socket/vendor/pypi/{uuid}") + } + + fn pair(line: &str) -> String { + format!("{COMMENT}\n{OPTION}{line}\n") + } + + /// A checkout whose root has the workspace files `files` and whose + /// project `project` has the committed directories `dirs`. + fn checkout( + project: &str, + files: &[(&str, &str)], + dirs: &[&str], + ) -> (tempfile::TempDir, BazelRoot) { + let tmp = tempfile::tempdir().unwrap(); + let top = fs::canonicalize(tmp.path()).unwrap(); + let all = [ + (".git/HEAD", "ref: refs/heads/main\n"), + ("MODULE.bazel", ""), + ]; + for (path, text) in all.iter().chain(files) { + let path = top.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + for uuid in dirs { + fs::create_dir_all(top.join(project).join(dir(uuid))).unwrap(); + } + fs::create_dir_all(top.join(project)).unwrap(); + let root = crate::bazel::bazel_root(&top.join(project)).unwrap(); + (tmp, root) + } + + fn rc(root: &BazelRoot) -> Option { + fs::read_to_string(root.dir.join(".bazelrc")).ok() + } + + /// A project at a path that a line of the file does not take as it is + /// gets no line, however it came to hold a committed wheel: a blank in + /// the line would be a second word on every Bazel command. + #[test] + fn a_project_whose_path_a_line_does_not_take_gets_no_line() { + let user = "build --jobs=4\n"; + let (_tmp, root) = checkout("my svc", &[(".bazelrc", user)], &[UUID]); + assert_eq!(sync(&root, &[dir(UUID)], true), Ok(None)); + assert_eq!(rc(&root).unwrap(), user); + } + + /// The line follows the directory: added for a directory that is + /// there, from the Bazel root, after the lines the file has; taken + /// away with the directory, and the file is then the one of before. + #[test] + fn a_line_is_kept_for_each_directory_and_taken_away_with_it() { + let user = "build --jobs=4\n"; + for (project, from_root) in [("", ""), ("svc/api", "svc/api/")] { + let (_tmp, root) = checkout(project, &[(".bazelrc", user)], &[UUID, OTHER]); + let both = [dir(UUID), dir(OTHER)]; + let lines = both + .each_ref() + .map(|dir| pair(&format!("{from_root}{dir}"))); + let changed = sync(&root, &both, true).unwrap(); + // The file is reported as a person reads a path: on Windows + // without the verbatim prefix the root's own path carries. + let file = + crate::utils::pnpm_workspace::without_verbatim_prefix(root.dir.join(".bazelrc")); + assert_eq!(changed, Some(file)); + assert_eq!( + rc(&root).unwrap(), + format!("{user}{}{}", lines[0], lines[1]) + ); + // Nothing to change: no write. + assert_eq!(sync(&root, &both, true), Ok(None)); + // One directory is gone, with whatever the ledger says. + fs::remove_dir(root.dir.join(project).join(dir(UUID))).unwrap(); + for dirs in [&both[..], &both[1..]] { + sync(&root, dirs, false).unwrap(); + assert_eq!( + rc(&root).unwrap(), + format!("{user}{}", lines[1]), + "{project}" + ); + } + fs::remove_dir(root.dir.join(project).join(dir(OTHER))).unwrap(); + sync(&root, &[], true).unwrap(); + assert_eq!(rc(&root).unwrap(), user, "{project}"); + } + // A file that socket-patch made is gone with its last line, and + // one whose last line had no line break is the file of before. + for user in [None, Some("build --jobs=4")] { + let files = user.map(|user| (".bazelrc", user)); + let (_tmp, root) = checkout("", files.as_slice(), &[UUID]); + sync(&root, &[dir(UUID)], true).unwrap(); + let line = pair(&dir(UUID)); + let with = match user { + Some(user) => format!("{user}\n{}", line.trim_end()), + None => line, + }; + assert_eq!(rc(&root).unwrap(), with); + fs::remove_dir(root.dir.join(dir(UUID))).unwrap(); + sync(&root, &[dir(UUID)], true).unwrap(); + assert_eq!(rc(&root), files.map(|(_, user)| user.to_string())); + } + } + + /// Only a directory that the caller names gets a line, only a line of + /// this project under socket-patch's comment is taken away, and a line + /// that the user commented out is declined: nothing is added. + #[test] + fn other_lines_stay_and_a_commented_line_declines() { + let own = format!("{OPTION}{}", dir(UUID)); + let (_tmp, root) = checkout("", &[], &[OTHER]); + // A directory with no entry of the ledger, and without `add`. + assert_eq!(sync(&root, &[], true), Ok(None)); + assert_eq!(sync(&root, &[dir(OTHER)], false), Ok(None)); + assert_eq!(rc(&root), None); + // Lines that are not socket-patch's to remove, for directories + // that are gone: the user's own, another project's, and a + // `--distdir` elsewhere. + let kept = format!( + "{own}\n{}{}{}", + pair(&format!("svc/{}", dir(UUID))), + pair("third_party/distdir"), + pair(&format!("{}/sub", dir(UUID))).replace("common", "build"), + ); + fs::write(root.dir.join(".bazelrc"), &kept).unwrap(); + assert_eq!(sync(&root, &[], true), Ok(None)); + // The user's own line is the line: no second one. + fs::create_dir_all(root.dir.join(dir(UUID))).unwrap(); + assert_eq!(sync(&root, &[dir(UUID)], true), Ok(None)); + // A line above the directory is not: Bazel does not look below. + let above = format!("{OPTION}.socket/vendor/pypi\n"); + fs::write(root.dir.join(".bazelrc"), &above).unwrap(); + sync(&root, &[dir(UUID)], true).unwrap(); + assert_eq!(rc(&root).unwrap(), format!("{above}{}", pair(&dir(UUID)))); + // Declined, in each spelling, also once the directory is gone. + for declined in [format!("#{own}"), format!("# {own}")] { + let declined = format!("{COMMENT}\n{declined}\n"); + fs::write(root.dir.join(".bazelrc"), &declined).unwrap(); + assert_eq!( + sync(&root, &[dir(UUID), dir(OTHER)], true).map(|_| ()), + Ok(()) + ); + let with_other = format!("{declined}{}", pair(&dir(OTHER))); + assert_eq!(rc(&root).unwrap(), with_other); + fs::remove_dir_all(root.dir.join(".socket")).unwrap(); + sync(&root, &[], true).unwrap(); + assert_eq!(rc(&root).unwrap(), declined); + fs::create_dir_all(root.dir.join(dir(UUID))).unwrap(); + fs::create_dir_all(root.dir.join(dir(OTHER))).unwrap(); + } + } + + /// A file that cannot be written is reported with the line to add, + /// and stays: a link is not written through. + #[cfg(unix)] + #[test] + fn a_file_that_cannot_be_updated_is_reported_with_the_line() { + let (_tmp, root) = checkout("", &[("elsewhere", "build --jobs=4\n")], &[UUID]); + std::os::unix::fs::symlink("elsewhere", root.dir.join(".bazelrc")).unwrap(); + let why = sync(&root, &[dir(UUID)], true).unwrap_err(); + let line = format!("add `{OPTION}{}` to it", dir(UUID)); + for part in ["could not update", "symbolic link", &line, "patch host"] { + assert!(why.contains(part), "{why}"); + } + assert_eq!(rc(&root).unwrap(), "build --jobs=4\n"); + } + + const MODULE: &str = r#"bazel_dep(name = "rules_python", version = "2.5.0") +pip = use_extension("@rules_python//python/extensions:pip.bzl", "pip") +pip.parse(hub_name = "pip", python_version = "3.11", requirements_lock = "//:requirements.txt") +use_repo(pip, "pip") +"#; + + /// The lock of a Bazel that selected `release` of the ruleset. + fn lock(version: u32, release: &str) -> String { + format!( + "{{\"lockFileVersion\": {version}, \"registryFileHashes\": {{\ + \"https://bcr.bazel.build/modules/rules_python/{release}/source.json\": \"x\"}}}}" + ) + } + + /// [`ready`] for the root project of a checkout with `files`. + fn asked_of(files: &[(&str, &str)]) -> Result<(), String> { + let (_tmp, root) = checkout("", files, &[]); + ready(&root, "requirements.txt", &["requirements.txt".to_string()]) + } + + fn declined(files: &[(&str, &str)], names: &str) { + let why = asked_of(files).unwrap_err(); + assert!(why.contains(names), "{names:?} is not in {why:?}"); + } + + #[test] + fn a_workspace_that_shows_all_of_it_is_ready() { + let module = ("MODULE.bazel", MODULE); + for (version, release) in [(28, "2.5.0"), (28, "2.5.0-rc4"), (13, "2.5.0")] { + let lock = lock(version, release); + let asks = MODULE.replace("2.5.0", release); + let files = [("MODULE.bazel", &*asks), ("MODULE.bazel.lock", &*lock)]; + assert_eq!(asked_of(&files), Ok(()), "{release}"); + } + // A Bazel that the checkout names, with any lock version; rc lines + // that are the user's own; another hub that reads another file. + let unknown = lock(99, "2.5.0"); + let lock = ("MODULE.bazel.lock", &*unknown); + for release in ["7.4.1", "8.8.2", "9.3.2"] { + assert_eq!( + asked_of(&[module, lock, (".bazelversion", release)]), + Ok(()) + ); + } + let rc = + "build --jobs=4\ncommon --distdir=third_party/distdir\ncommon --lockfile_mode=error\n"; + let good = super::tests::lock(28, "2.5.0"); + let lock = ("MODULE.bazel.lock", &*good); + assert_eq!(asked_of(&[module, lock, (".bazelrc", rc)]), Ok(())); + let more = format!( + "{MODULE}pip.parse(hub_name = \"tools\", python_version = \"3.11\", \ + requirements_lock = \"//tools:requirements.txt\")\n" + ); + assert_eq!(asked_of(&[("MODULE.bazel", &more), lock]), Ok(())); + } + + #[test] + fn a_ruleset_or_a_bazel_that_is_not_shown_declines() { + let module = ("MODULE.bazel", MODULE); + let good = lock(28, "2.5.0"); + let good = ("MODULE.bazel.lock", &*good); + // No lock, a lock that names no release, and an unmeasured release. + declined(&[module], "does not say which release of rules_python"); + declined(&[module, ("MODULE.bazel.lock", "{}")], "does not say which"); + for release in ["2.4.6", "2.5.0-rc3", "2.5.1", "1.9.2"] { + let lock = lock(28, release); + let names = format!("Bazel selected rules_python {release}"); + declined(&[module, ("MODULE.bazel.lock", &lock)], &names); + } + // The root asks for a newer release than the lock holds, or takes + // the ruleset from somewhere that names no release. + let newer = MODULE.replace("2.5.0", "2.6.0"); + declined( + &[("MODULE.bazel", &newer), good], + "build once so that Bazel updates its lock", + ); + let local = + format!("{MODULE}local_path_override(module_name = \"rules_python\", path = \"x\")\n"); + declined( + &[("MODULE.bazel", &local), good], + "with this `local_path_override`", + ); + // A Bazel outside 7 to 9, or none that the checkout shows. + for release in ["6.5.0", "10.0.0"] { + let names = format!("names Bazel {release}"); + declined(&[module, good, (".bazelversion", release)], &names); + } + for version in [11, 29] { + let lock = lock(version, "2.5.0"); + declined( + &[module, ("MODULE.bazel.lock", &lock)], + "name the release in `.bazelversion`", + ); + } + } + + #[test] + fn an_rc_file_that_names_a_downloader_setting_declines() { + let module = ("MODULE.bazel", MODULE); + let good = lock(28, "2.5.0"); + let good = ("MODULE.bazel.lock", &*good); + for (option, word) in [ + ("--downloader_config=ci/downloads.cfg", "downloader_config"), + ("--experimental_downloader_config=x", "downloader_config"), + ( + "--repository_disable_download", + "repository_disable_download", + ), + ( + "--experimental_remote_downloader=grpc://x", + "remote_downloader", + ), + ] { + let rc = format!("build --jobs=4\ncommon {option}\n"); + let names = format!(".bazelrc:2 names `{option}`"); + declined(&[module, good, (".bazelrc", &rc)], &names); + assert!(option.contains(word)); + // In a file the root one imports, too. + let files = [ + module, + good, + (".bazelrc", "import %workspace%/ci.bazelrc\n"), + ("ci.bazelrc", &*rc), + ]; + declined(&files, &format!("ci.bazelrc:2 names `{option}`")); + } + // One that cannot be read may name any, and so may one that an + // import brings in from outside the checkout, which is not read. + let files = [module, good, (".bazelrc", "build 'unclosed\n")]; + declined(&files, "the rc file .bazelrc:1 cannot be read"); + let outside = "build --jobs=4\ntry-import /etc/bazel/site.bazelrc\n"; + let imported = [ + (".bazelrc", "import %workspace%/ci.bazelrc\n"), + ("ci.bazelrc", outside), + ]; + for (rc, from) in [ + (&[(".bazelrc", outside)][..], ".bazelrc"), + (&imported[..], "ci.bazelrc"), + ] { + let names = format!( + "the rc file /etc/bazel/site.bazelrc, which {from}:2 imports from outside the \ + checkout, cannot be read" + ); + declined(&[&[module, good][..], rc].concat(), &names); + } + } + + #[test] + fn a_hub_that_is_not_read_with_certainty_declines() { + let good = lock(28, "2.5.0"); + let good = ("MODULE.bazel.lock", &*good); + let call = "requirements_lock = \"//:requirements.txt\")"; + for (with, names) in [ + // Another file of the build's platform, a file not written + // out, a call that may not run, and a hub that is not read. + ( + "requirements_lock = \"//:requirements.txt\", requirements_windows = \"//:win.txt\")", + "names more than `requirements_lock = \"requirements.txt\"`", + ), + ("requirements_lock = LOCK)", "are not all written out"), + ("**ARGS)", "are not all written out"), + ("requirements_lock = \"//:requirements.txt\") if ON else None", "may not run"), + ("requirements_lock = \"//:requirements.txt\")\nother(pip)", "MODULE.bazel:"), + ] { + let module = MODULE.replace(call, with); + assert_ne!(module, MODULE); + declined(&[("MODULE.bazel", &module), good], names); + } + // A second hub whose file brings the project's in with `-r`: it is + // judged although the first call names the file itself. + let second = "pip.parse(hub_name = \"all\", python_version = \"3.11\", \ + requirements_lock = \"//:all.txt\")\n"; + let both = format!("{MODULE}{second}"); + let module = ("MODULE.bazel", &*both); + declined( + &[module, good, ("all.txt", "-r requirements.txt\n")], + "names all.txt, which brings a file of this project in with `-r`", + ); + // Without the include that file stands against nothing. + let other = ("all.txt", "y==1.0.0\n"); + assert_eq!(asked_of(&[module, good, other]), Ok(())); + // A `WORKSPACE` file that defines repositories, and a module file + // with a byte that is not UTF-8. + let legacy = ("WORKSPACE", "pip_parse(name = \"pip\")\n"); + declined(&[("MODULE.bazel", MODULE), good, legacy], "WORKSPACE"); + let (_tmp, root) = checkout("", &[good], &[]); + fs::write( + root.dir.join("MODULE.bazel"), + [MODULE.as_bytes(), b"# caf\xe9\n"].concat(), + ) + .unwrap(); + let locks = ["requirements.txt".to_string()]; + let why = ready(&root, "requirements.txt", &locks).unwrap_err(); + assert!(why.contains("MODULE.bazel"), "{why}"); + } + + /// The line itself: a project whose path an rc file would read + /// otherwise, and a `.bazelrc` that is a link or read-only. + #[test] + fn a_line_that_cannot_be_written_declines() { + let good = lock(28, "2.5.0"); + let files = [("MODULE.bazel", MODULE), ("MODULE.bazel.lock", &*good)]; + let (_tmp, root) = checkout("my app", &files, &[]); + let locks = ["requirements.txt".to_string()]; + let why = ready(&root, "requirements.txt", &locks).unwrap_err(); + assert!(why.contains("my app/, holds a character"), "{why}"); + #[cfg(unix)] + { + let (_tmp, root) = checkout("", &files, &[]); + std::os::unix::fs::symlink("elsewhere", root.dir.join(".bazelrc")).unwrap(); + let why = ready(&root, "requirements.txt", &locks).unwrap_err(); + assert!(why.contains(".bazelrc is a symbolic link"), "{why}"); + // A FIFO declines at once instead of hanging the probe. + let (_tmp, root) = checkout("", &files, &[]); + let fifo = std::ffi::CString::new(std::os::unix::ffi::OsStrExt::as_bytes( + root.dir.join(".bazelrc").as_os_str(), + )) + .unwrap(); + assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o644) }, 0); + let why = ready(&root, "requirements.txt", &locks).unwrap_err(); + assert!(why.contains(".bazelrc is not a regular file"), "{why}"); + } + // A directory there is no file to write the line into either. + let (_tmp, root) = checkout("", &files, &[]); + fs::create_dir(root.dir.join(".bazelrc")).unwrap(); + let why = ready(&root, "requirements.txt", &locks).unwrap_err(); + assert!(why.contains(".bazelrc is not a regular file"), "{why}"); + let (_tmp, root) = checkout("", &[files[0], files[1], (".bazelrc", "")], &[]); + assert_eq!(ready(&root, "requirements.txt", &locks), Ok(())); + let rc = root.dir.join(".bazelrc"); + let mut bits = fs::metadata(&rc).unwrap().permissions(); + bits.set_readonly(true); + fs::set_permissions(&rc, bits).unwrap(); + // Root writes a read-only file all the same. + if fs::OpenOptions::new().append(true).open(&rc).is_err() { + let why = ready(&root, "requirements.txt", &locks).unwrap_err(); + assert!(why.contains(".bazelrc is read-only"), "{why}"); + } + } +} diff --git a/crates/socket-patch-core/src/bazel/ignore.rs b/crates/socket-patch-core/src/bazel/ignore.rs index 785cf81b4..f344150c5 100644 --- a/crates/socket-patch-core/src/bazel/ignore.rs +++ b/crates/socket-patch-core/src/bazel/ignore.rs @@ -82,6 +82,25 @@ fn comment(what: &str) -> String { /// leaves both lines alone. const MARK: &str = "# socket-patch:"; +/// The lines socket-patch keeps in one file at a Bazel root, each under a +/// comment line of its own. They are added and taken away in one way for +/// `.bazelignore` and for the `.bazelrc` of [`super::distdir`]. +pub(super) struct Kept { + /// The name of the file at the Bazel root. + pub(super) file: &'static str, + /// The line above a line written, which starts with [`MARK`], for + /// what the line's entry says it is about. + pub(super) comment: fn(&str) -> String, + /// Whether a line of the file's text already does what a line would. + pub(super) covers: fn(&[u8], &str) -> bool, +} + +const IGNORED: Kept = Kept { + file: ".bazelignore", + comment, + covers, +}; + /// Make the `.bazelignore` at the Bazel root of `project` agree with the /// copies of the project: for each of `.socket/vendor/golang`, /// `.socket/go-patches`, `.socket/vendor/cargo` and `.socket/vendor/maven` @@ -174,32 +193,88 @@ fn sync_blocking( let mut hub = None; let mut under_a_hub = |wanted: &mut [(String, Option, &'static str); 4], text: &[u8]| { for ((.., of), (line, state, _)) in COPIES.iter().zip(wanted.iter_mut()) { - let adds = *of == Of::Crates && *state == Some(true) && !settled(text, line); + let adds = *of == Of::Crates && *state == Some(true) && !settled(&IGNORED, text, line); if adds && !*hub.get_or_insert_with(|| cargo_bazel::hub(&root)) { *state = None; } } }; - let file = root.dir.join(".bazelignore"); + let mut edit = |text: &[u8]| { + under_a_hub(&mut wanted, text); + edited(&IGNORED, text, &wanted) + }; + let (shown, failed, old) = match update(&IGNORED, &root.dir, &mut edit) { + Ok(None) => return Ok(None), + Ok(Some((shown, old, new))) => { + // Whose lines the file has more or fewer of than before. + let lines = |text: &[u8], line: &str| { + let is = |l: &&[u8]| content(l) == line.as_bytes(); + text.split(|byte| *byte == b'\n').filter(is).count() + }; + let differs = |line: &str| lines(&old, line) != lines(&new, line); + let whose = wanted.iter().filter(|(line, ..)| differs(line)); + let mut whose: Vec<_> = whose.map(|(.., what)| *what).collect(); + whose.dedup(); + return Ok(Some((shown, whose))); + } + Err(failed) => failed, + }; + // A missing line is what the user has to act on. A pair that stays + // behind for a directory that is gone ignores nothing. + let missing: Vec = wanted + .iter() + .filter(|(line, state, _)| *state == Some(true) && !settled(&IGNORED, &old, line)) + .map(|(line, ..)| format!("`{line}`")) + .collect(); + let advice = if !missing.is_empty() { + format!( + "add {} to it on a line of its own, with no space before or after, so that Bazel \ + and gazelle do not read the patched copies there as packages (`bazel run \ + //:gazelle`, `bazel build //...` or `bazel cquery //...` can otherwise fail)", + missing.join(" and ") + ) + } else { + "the lines under socket-patch's comment in it name directories that no longer exist \ + and can be deleted" + .to_string() + }; + Err(format!( + "could not update {}: {failed}; {advice}", + shown.display() + )) +} + +/// The file [`update`] changed, what it held and what it holds now. +pub(super) type Written = (PathBuf, Vec, Vec); + +/// Make the file of `kept` at the Bazel root `root` hold what `edit` makes +/// of its bytes, under a lock of the root ([`lock`]). `Ok(Some)` is the +/// file, when it was changed, with what it held and what it holds now. +/// `Err` is the file, why it could not be read or written (it may be a +/// link, which socket-patch does not write through), and what it held. +pub(super) fn update( + kept: &Kept, + root: &Path, + edit: &mut dyn FnMut(&[u8]) -> Vec, +) -> Result, (PathBuf, std::io::Error, Vec)> { + let file = root.join(kept.file); let read = || match read_regular_to_bytes_sync(&file) { Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), read => read, }; // Most runs find nothing to change, and take no lock to find that. A - // file that cannot be read is an edit only with a copy to name in it. + // file that cannot be read is an edit only with a line to add to it. let unlocked = read().unwrap_or_default(); - under_a_hub(&mut wanted, &unlocked); - if edited(&unlocked, &wanted) == unlocked { + if edit(&unlocked) == unlocked { return Ok(None); } - let _lock = lock(&root.dir); + let _lock = lock(root); let (old, unreadable) = match read() { Ok(old) => (old, None), Err(e) => (Vec::new(), Some(e)), }; - under_a_hub(&mut wanted, &old); - let new = edited(&old, &wanted); + let new = edit(&old); // The root is canonical: on Windows that spelling has a prefix no user // types and no tool prints. let shown = crate::utils::pnpm_workspace::without_verbatim_prefix(file.clone()); @@ -212,47 +287,14 @@ fn sync_blocking( "it is a symbolic link, which socket-patch does not write through", ), None => match write(&file, &old, &new) { - Ok(()) => { - // Whose lines the file has more or fewer of than before. - let lines = |text: &[u8], line: &str| { - let is = |l: &&[u8]| content(l) == line.as_bytes(); - text.split(|byte| *byte == b'\n').filter(is).count() - }; - let differs = |line: &str| lines(&old, line) != lines(&new, line); - let whose = wanted.iter().filter(|(line, ..)| differs(line)); - let mut whose: Vec<_> = whose.map(|(.., what)| *what).collect(); - whose.dedup(); - return Ok(Some((shown, whose))); - } + Ok(()) => return Ok(Some((shown, old, new))), Err(e) => e, }, }; - // A missing line is what the user has to act on. A pair that stays - // behind for a directory that is gone ignores nothing. - let missing: Vec = wanted - .iter() - .filter(|(line, state, _)| *state == Some(true) && !settled(&old, line)) - .map(|(line, ..)| format!("`{line}`")) - .collect(); - let advice = if !missing.is_empty() { - format!( - "add {} to it on a line of its own, with no space before or after, so that Bazel \ - and gazelle do not read the patched copies there as packages (`bazel run \ - //:gazelle`, `bazel build //...` or `bazel cquery //...` can otherwise fail)", - missing.join(" and ") - ) - } else { - "the lines under socket-patch's comment in it name directories that no longer exist \ - and can be deleted" - .to_string() - }; - Err(format!( - "could not update {}: {failed}; {advice}", - shown.display() - )) + Err((shown, failed, old)) } -/// The lock of the `.bazelignore` at `root`, which a process holds from its +/// The lock of the file at `root`, which a process holds from its /// read of the file to its write: without it, a pair that one project adds /// between the read and the replacement of another project's removal is /// lost. It is an advisory lock on the root directory itself, so that no @@ -298,7 +340,7 @@ fn write(file: &Path, old: &[u8], new: &[u8]) -> std::io::Result<()> { } /// A line of the file without its line break (`\n`, or `\r\n`). -fn content(line: &[u8]) -> &[u8] { +pub(super) fn content(line: &[u8]) -> &[u8] { let line = line.strip_suffix(b"\n").unwrap_or(line); line.strip_suffix(b"\r").unwrap_or(line) } @@ -323,10 +365,10 @@ fn covers(old: &[u8], path: &str) -> bool { } /// Whether `old` needs no pair for the directory `path`: a line covers it -/// ([`covers`]), or the user declined the pair by commenting its path line -/// out: a [`MARK`] line, then a line of `#`, any blanks, and the [`plain`] -/// path. -fn settled(old: &[u8], path: &str) -> bool { +/// ([`Kept::covers`]), or the user declined the pair by commenting its +/// path line out: a [`MARK`] line, then a line of `#`, any blanks, and the +/// [`plain`] path. +pub(super) fn settled(kept: &Kept, old: &[u8], path: &str) -> bool { let lines: Vec<&[u8]> = (old.split_inclusive(|byte| *byte == b'\n')) .map(content) .collect(); @@ -335,7 +377,7 @@ fn settled(old: &[u8], path: &str) -> bool { pair[0].starts_with(MARK.as_bytes()) && commented.is_some_and(|rest| plain(rest.trim_ascii_start()) == path.as_bytes()) }; - covers(old, path) || lines.windows(2).any(declined) + (kept.covers)(old, path) || lines.windows(2).any(declined) } /// `old` as [`sync`] leaves it for `wanted`, the line of each directory, @@ -347,7 +389,7 @@ fn settled(old: &[u8], path: &str) -> bool { /// the pair and none after it, and loses that one (the comment line's own) /// with a pair that ends the file that way, so that the file without the /// pair is the file of before, byte for byte. -fn edited(old: &[u8], wanted: &[(String, Option, &str)]) -> Vec { +pub(super) fn edited(kept: &Kept, old: &[u8], wanted: &[(String, Option, &str)]) -> Vec { let gone = |line: &[u8]| { wanted .iter() @@ -373,10 +415,10 @@ fn edited(old: &[u8], wanted: &[(String, Option, &str)]) -> Vec { } let nl = crate::utils::line_endings::terminator(&String::from_utf8_lossy(old)); for (line, exists, what) in wanted { - if *exists != Some(true) || settled(&new, line) { + if *exists != Some(true) || settled(kept, &new, line) { continue; } - let comment = comment(what); + let comment = (kept.comment)(what); let pair = match new.is_empty() || new.ends_with(b"\n") { true => format!("{comment}{nl}{line}{nl}"), false => format!("{nl}{comment}{nl}{line}"), @@ -403,7 +445,7 @@ mod tests { fn edit(old: &str, vendor: bool, patches: bool) -> String { let wanted = [(VENDOR, vendor), (PATCHES, patches)]; let wanted = wanted.map(|(line, exists)| (line.to_string(), Some(exists), "Go module")); - String::from_utf8(edited(old.as_bytes(), &wanted)).unwrap() + String::from_utf8(edited(&IGNORED, old.as_bytes(), &wanted)).unwrap() } fn pair(line: &str) -> String { @@ -607,8 +649,8 @@ mod tests { assert_eq!(other, format!("{declined}{}", pair(PATCHES))); assert_eq!(edit(&other, vendor, false), declined); } - assert!(settled(declined.as_bytes(), VENDOR)); - assert!(!settled(declined.as_bytes(), PATCHES)); + assert!(settled(&IGNORED, declined.as_bytes(), VENDOR)); + assert!(!settled(&IGNORED, declined.as_bytes(), PATCHES)); } // No "no": without the comment line above it (a commented-out // one included), or not that path. diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index 73eb1d69d..7ce55b7c3 100644 --- a/crates/socket-patch-core/src/bazel/maven.rs +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -395,7 +395,7 @@ pub enum Built<'a> { /// Discovery.java lines 158 and 159 at 7.7.2, 178 and 179 at 8.8.2 and /// 9.3.2). #[derive(Debug, PartialEq, Eq)] -enum Asked { +pub(super) enum Asked { /// No version is given. Nothing, /// A `bazel_dep` asks for this release: Bazel selects it or a newer @@ -430,11 +430,11 @@ fn ordered(version: &str) -> impl Ord + '_ { (identifiers(release), pre.is_empty(), identifiers(pre)) } -/// What the root module of `ws` says of the ruleset's release: by its -/// calls that name the ruleset, a `bazel_dep` and the overrides, which are -/// the functions whose name ends in `_override`. -fn asked(ws: &Workspace) -> Asked { - let named = Some(&Value::Str(EXTENSION.module.to_string())); +/// What the root module of `ws` says of the release of the ruleset +/// `module`: by its calls that name the ruleset, a `bazel_dep` and the +/// overrides, which are the functions whose name ends in `_override`. +pub(super) fn asked(ws: &Workspace, module: &str) -> Asked { + let named = Some(&Value::Str(module.to_string())); let names = |call: &&Call| { call.bind.is_none() && [call.arg("name"), call.arg("module_name")].contains(&named) }; @@ -462,6 +462,51 @@ fn asked(ws: &Workspace) -> Asked { } } +/// Why the release of the ruleset `module` that Bazel builds with is not +/// one of `known`: by the one release `lock` (`MODULE.bazel.lock`) says +/// Bazel selected, where the root module (`asked`) has not asked for +/// another since. `Ok` when it is one. `so` is what hangs on the release, +/// for the two reasons that it cannot be told, and `beyond` what to say of +/// a release outside `known`. +/// +/// A lock that holds another release than the root now takes is one that +/// Bazel has not written since: older than what is asked for, or any other +/// than the one a `single_version_override` pins. +pub(super) fn known_release( + asked: &Asked, + lock: &ModuleLock, + module: &str, + known: &[&str], + so: &str, + beyond: &dyn Fn(&str) -> String, +) -> Result<(), String> { + let stale = |selected: &str| match asked { + Asked::Exactly(pinned) => ordered(pinned) != ordered(selected), + Asked::AtLeast(least) => ordered(least) > ordered(selected), + Asked::Nothing | Asked::Unknown(_) => false, + }; + let wanted = match asked { + Asked::Exactly(wanted) | Asked::AtLeast(wanted) => wanted.as_str(), + Asked::Nothing | Asked::Unknown(_) => "", + }; + Err(match (asked, &lock.selected(module)[..]) { + (Asked::Unknown(at), _) => format!( + "{at} of {module} socket-patch cannot tell which release of the ruleset Bazel \ + builds with{so}" + ), + (_, [selected]) if !known.contains(selected) => beyond(selected), + (_, [selected]) if stale(selected) => format!( + "{FILE} asks for {module} {wanted} and MODULE.bazel.lock holds {selected}: build once \ + so that Bazel updates its lock" + ), + (_, [_]) => return Ok(()), + _ => format!( + "MODULE.bazel.lock does not say which release of {module} Bazel selected{so}: build \ + once so that Bazel writes its lock" + ), + }) +} + /// What the hubs of a workspace build: read once, asked per artifact. #[derive(Debug)] pub struct Hubs { @@ -539,7 +584,7 @@ impl Hubs { why: "the block that socket-patch keeps there was changed by hand".to_string(), }), ); - let asked = asked(&ws); + let asked = asked(&ws, EXTENSION.module); let overrides = ws.tags(&EXTENSION, "override").calls.into_iter(); let overrides = overrides.map(|Tag { file, call, .. }| { let (replaced, why) = match call.arg("coordinates") { @@ -1149,7 +1194,7 @@ fn rc(view: &dyn Fn(&str) -> Entry, release: Option) -> Vec< }; Some((code, format!("{file}:{line} names `{word}`, {why}"))) }; - match mentions(view, &flags) { + match mentions(view, &flags, false) { Ok(found) => found.into_iter().filter_map(against).collect(), Err(file) => { let why = format!("the rc file {file} cannot be read, and may switch an entry off"); @@ -1194,47 +1239,26 @@ fn settings( } _ => {} } - // A lock that holds another release than the root now takes is one - // that Bazel has not written since: older than what is asked for, or - // any other than the one a `single_version_override` pins. let module = EXTENSION.module; - let stale = |selected: &str| match asked { - Asked::Exactly(pinned) => ordered(pinned) != ordered(selected), - Asked::AtLeast(least) => ordered(least) > ordered(selected), - Asked::Nothing | Asked::Unknown(_) => false, - }; - let wanted = match asked { - Asked::Exactly(wanted) | Asked::AtLeast(wanted) => wanted.as_str(), - Asked::Nothing | Asked::Unknown(_) => "", - }; - let why = match (asked, &lock.selected(module)[..]) { - (Asked::Unknown(at), _) => format!( - "{at} of {module} socket-patch cannot tell which release of the ruleset Bazel \ - builds with, and the name of a jar's repository depends on it" - ), - (_, [selected]) if !RULESETS.contains(selected) => format!( + let so = ", and the name of a jar's repository depends on it"; + let beyond = |selected: &str| { + format!( "Bazel selected {module} {selected}, and how the ruleset names the repository of a \ jar is known for its releases 6.4 to 7.2: update socket-patch" - ), - (_, [selected]) if stale(selected) => format!( - "{FILE} asks for {module} {wanted} and MODULE.bazel.lock holds {selected}: build once \ - so that Bazel updates its lock" - ), + ) + }; + match known_release(asked, &lock, module, &RULESETS, so, &beyond) { // The jar of a vendored entry is in the checkout: no option about // downloads stands against it. - (_, [_]) => { + Ok(()) => { let against = |(code, _): &Declined| !vendored || *code != DOWNLOAD; - return rc(view, release) + rc(view, release) .into_iter() .find(against) - .map_or(Ok(()), Err); + .map_or(Ok(()), Err) } - _ => format!( - "MODULE.bazel.lock does not say which release of {module} Bazel selected, and the \ - name of a jar's repository depends on it: build once so that Bazel writes its lock" - ), - }; - Err((RELEASE, why)) + Err(why) => Err((RELEASE, why)), + } } impl Hubs { diff --git a/crates/socket-patch-core/src/bazel/mod.rs b/crates/socket-patch-core/src/bazel/mod.rs index fe8331b95..327e8c7d1 100644 --- a/crates/socket-patch-core/src/bazel/mod.rs +++ b/crates/socket-patch-core/src/bazel/mod.rs @@ -11,6 +11,7 @@ pub const WORKSPACE_FILES: [&str; 4] = pub mod built; pub mod cargo; pub(crate) mod cargo_bazel; +pub mod distdir; pub mod ignore; pub mod maven; pub mod nuget; @@ -25,7 +26,7 @@ use std::path::{Path, PathBuf}; use crate::utils::repo_root::{repo_at_end_of, search_dirs, GitRepo}; /// The Bazel workspace a project is in. -#[derive(Debug, PartialEq)] +#[derive(Debug, Clone, PartialEq)] pub struct BazelRoot { /// The root: the nearest directory, from the project up, that holds one /// of [`WORKSPACE_FILES`]. Canonical. diff --git a/crates/socket-patch-core/src/bazel/rc.rs b/crates/socket-patch-core/src/bazel/rc.rs index 47346de05..9088f8ec8 100644 --- a/crates/socket-patch-core/src/bazel/rc.rs +++ b/crates/socket-patch-core/src/bazel/rc.rs @@ -143,13 +143,18 @@ fn words(line: &str) -> Option> { /// absolute is one Bazel opens from where it runs: it is read from the /// Bazel root. An rc file that is there and cannot be read, a line that /// [`words`] does not read, and one file more than the bound are an error: -/// the path, with the line. +/// the path, with the line. For a caller that needs `all` the files the +/// checkout brings in, so is an import of an absolute path, which is a +/// file outside the checkout and is not read: its path, and where it is +/// imported. /// -/// Not seen: the rc files of the machine and of the home directory, an -/// import of an absolute path, and the command line. +/// Not seen: the rc files of the machine and of the home directory, the +/// command line, a file that an import names and the checkout does not +/// have and, without `all`, an import of an absolute path. pub fn mentions( view: &dyn Fn(&str) -> Entry, flags: &[&str], + all: bool, ) -> Result, String> { let (mut todo, mut read) = (vec![".bazelrc".to_string()], Vec::new()); let mut found = Vec::new(); @@ -189,7 +194,12 @@ pub fn mentions( }; let inside = path.strip_prefix("%workspace%/"); let path = inside.map_or(&*path, |path| path.trim_start_matches('/')); - todo.extend((!Path::new(path).has_root()).then(|| path.to_string())); + if !Path::new(path).has_root() { + todo.push(path.to_string()); + } else if all { + let from = format!("which {file}:{at} imports from outside the checkout,"); + return Err(format!("{path}, {from}")); + } } _ => { let names = |word: &String| flags.iter().any(|flag| word.contains(flag)); @@ -447,7 +457,7 @@ mod tests { #[test] fn an_option_is_found_in_the_rc_files_of_the_workspace() { let flags = ["enable_bzlmod", "vendor_dir"]; - let found = |files: &[(&str, &str)]| mentions(&view(files), &flags); + let found = |files: &[(&str, &str)]| mentions(&view(files), &flags, false); let at = |file: &str, line, word: &str| (file.to_string(), line, word.to_string()); assert_eq!(found(&[]), Ok(vec![])); let rc = "# common --noenable_bzlmod\n\ @@ -487,6 +497,13 @@ mod tests { at("tools/more.bazelrc", 1, "--vendor_dir=v"), ]; assert_eq!(found(&files), Ok(expected)); + // For a caller that needs all of them, the absolute one is a file + // that may hold anything. + let outside = "/etc/bazel.bazelrc, which .bazelrc:6 imports from outside the checkout,"; + assert_eq!( + mentions(&view(&files), &flags, true), + Err(outside.to_string()) + ); // The path of an import is a word like any other (line 126 / 148): // without its quotes, joined over a line break, and `%workspace%/` // joined to the root however many `/` follow it (`JoinPath`, diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index 7df8fe1b8..83afc7e3f 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -107,7 +107,7 @@ mod pypi_takeover; pub use pypi_takeover::preflight_pypi_takeover; #[cfg(test)] mod python_lock_equivalence_tests; -mod requirements; +pub(crate) mod requirements; pub mod sbt; pub mod scala_guidance; pub use requirements::preflight_requirements_takeover; diff --git a/crates/socket-patch-core/src/patch/redirect/requirements.rs b/crates/socket-patch-core/src/patch/redirect/requirements.rs index a1309be35..75a28558a 100644 --- a/crates/socket-patch-core/src/patch/redirect/requirements.rs +++ b/crates/socket-patch-core/src/patch/redirect/requirements.rs @@ -200,7 +200,7 @@ fn line_requirement(text: &str) -> Option> { parse_requirement(code.trim_end().trim_end_matches('\\')) } -pub(super) fn rewrite( +pub(crate) fn rewrite( files: &BTreeMap, overrides: &[DepOverride], result: &mut RewriteResult, diff --git a/crates/socket-patch-core/src/vendor/bazel_hub.rs b/crates/socket-patch-core/src/vendor/bazel_hub.rs index cde62bcc7..92a9f0fc1 100644 --- a/crates/socket-patch-core/src/vendor/bazel_hub.rs +++ b/crates/socket-patch-core/src/vendor/bazel_hub.rs @@ -65,9 +65,18 @@ pub async fn refusals<'a>( } /// What stands between vendored mode and a list of files of a project -/// ([`standing`]): the words of the refusal, and the text of the lock the -/// hub reads where a call names one. `None` where nothing does. -type Standing = Option<(String, Option)>; +/// ([`standing`]): the words of the refusal, the text of the lock the hub +/// reads where a call names one, and whether one names, with certainty, a +/// file of the list itself (and not one that brings it in with `-r`). +/// `None` where nothing does. +type Standing = Option<(String, Option, bool)>; + +/// What the refusal says after its own words where a wheel could be a +/// download cache of Bazel ([`super::pypi_distdir`]) and is not made one: +/// the reason follows. +const NO_CACHE: &str = "the form that rules_python does build, the patched wheel committed as a \ + download cache of Bazel, is written only where the checkout shows that \ + it works, and not here"; /// 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. @@ -103,6 +112,14 @@ async fn refusals_unless<'a>( // 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) { + // A wheel that already is a download cache: nothing to write. + Some(Ecosystem::Pypi) + if super::pypi_distdir::in_sync(project, purl, uuid) + .await + .is_some() => + { + continue + } Some(Ecosystem::Pypi) => super::pypi::hub_files(project, purl).await, Some(Ecosystem::Gem) => [super::gem::GEMFILE, super::gem::GEMFILE_LOCK] .map(String::from) @@ -121,7 +138,7 @@ async fn refusals_unless<'a>( asked.len() - 1 } }; - let Some((detail, lock)) = &asked[at].1 else { + let Some((detail, lock, named)) = &asked[at].1 else { continue; }; // A lock names the copy of a patch by the copy's directory, outside @@ -163,13 +180,61 @@ async fn refusals_unless<'a>( wired = names(&text) || !holds(&text); } } - if !wired { + if wired { + continue; + } + // A wheel is committed as a download cache of Bazel where the + // checkout shows that the build takes it; elsewhere the refusal + // says why not. + if code != PYPI_CODE || !*named { refused.push((*purl, code, detail.clone())); + continue; + } + let gate = super::pypi_distdir::gate(project, &root, files, (purl, uuid)); + if let Err(why) = gate.await { + refused.push((*purl, code, format!("{detail}; {NO_CACHE}: {why}"))); } } refused } +/// How the run for the PyPI package `purl` of `project` and its patch +/// `uuid` writes the wheel as a download cache of Bazel +/// ([`super::pypi_distdir`]): `Some(Some(pin))` when it already is one, +/// pinned at that path and sha256, and `Some(None)` when the run makes it +/// one, which is where [`refusals`] lets the package through for that. +/// `None` for every other package: one that the user allowed +/// ([`ALLOW_IN_BAZEL_ENV`]) is written as it is without Bazel. +/// +/// `Err` is the refusal of [`refusals`], asked again where the lock is +/// about to be written: a run that takes a hosted pin over has put the +/// registry's pin back since the run was let through, and that pin may be +/// one the form is not written for. +pub(super) async fn download_cache( + project: &Path, + purl: &str, + uuid: &str, +) -> Result>, (&'static str, String)> { + if let Some(pin) = super::pypi_distdir::in_sync(project, purl, uuid).await { + return Ok(Some(Some(pin))); + } + if let Some((_, code, why)) = refusals(project, &[(purl, uuid)]).await.pop() { + return Err((code, why)); + } + let dir = project.to_path_buf(); + let root = run_blocking(move || crate::bazel::bazel_root(&dir)).await; + let Some(root) = root.filter(|_| !env_flag(ALLOW_IN_BAZEL_ENV)) else { + return Ok(None); + }; + let locks = super::pypi::hub_files(project, purl).await; + // As in [`standing`]: a call that names a file of the project itself. + let own = |lock: &String| locks.iter().any(|own| from_root(&root, own) == *lock); + let named = !locks.is_empty() + && matches!(reader(&root, "pypi", locks.clone()).await, Some(Ok(read)) if own(&read.lock)); + let gate = super::pypi_distdir::gate(project, &root, &locks, (purl, uuid)); + Ok((named && gate.await.is_ok()).then_some(None)) +} + /// 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`. @@ -184,7 +249,8 @@ async fn standing( // types and no tool prints. let at = without_verbatim_prefix(root.dir.clone()); let at = at.display(); - let (reads, lock) = match reader(root, purls, locks).await? { + let own: Vec = locks.iter().map(|lock| from_root(root, lock)).collect(); + let (reads, lock, named) = match reader(root, purls, locks).await? { Ok(Unbuilt { call, file, @@ -193,10 +259,15 @@ async fn standing( }) => { let reads = format!("`{call}` ({file}:{line}) of the Bazel workspace at {at} names {lock}"); + // A file that only brings a file of the project in with `-r` is + // none the run writes: no build through it is shown to take a + // committed copy, so it does not count as named. + let named = own.contains(&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) + let text = run_blocking(move || lock_text(&dir, &lock)).await; + (reads, text, named) } Err(Doubt { file, line, why }) => { let line = match line { @@ -207,7 +278,7 @@ async fn standing( "the files of the Bazel workspace at {at} cannot be read with certainty, so a \ call of {ruleset} may name a lock of this project ({file}{line}: {why})" ); - (reads, None) + (reads, None, false) } }; let detail = format!( @@ -217,7 +288,7 @@ async fn standing( `--allow-vendored-in-bazel` if no build takes the packages of this project from \ {ruleset}" ); - Some((detail, lock)) + Some((detail, lock, named)) } #[cfg(test)] @@ -436,6 +507,9 @@ ruby.bundle_fetch(name = "bundle", gemfile = "//api:Gemfile", gemfile_lock = "// let (code, detail) = declined(&root.join("api"), Ecosystem::Pypi).await; assert_eq!(code, PYPI_CODE); assert!(detail.contains("names api/all.txt; "), "{detail}"); + // No build through the including file is shown to take a committed + // wheel, so the download cache is not even asked about. + assert!(!detail.contains(NO_CACHE), "{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); diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 8d38a2ca4..800959b5d 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -91,6 +91,7 @@ pub mod pnpm_lock; pub mod pnpm_lock_legacy; pub mod prestage; pub mod pypi; +pub mod pypi_distdir; pub(crate) mod pypi_distribution; mod pypi_hatch; mod pypi_lock; diff --git a/crates/socket-patch-core/src/vendor/pypi.rs b/crates/socket-patch-core/src/vendor/pypi.rs index e0adf56e9..80fe7e6ae 100644 --- a/crates/socket-patch-core/src/vendor/pypi.rs +++ b/crates/socket-patch-core/src/vendor/pypi.rs @@ -609,6 +609,10 @@ enum WiringPlan { /// beside it is wired too (#1758). PythonLocks(super::pypi_lock::PythonLocks, bool), Requirements, + /// `requirements.txt` beside a Bazel hub that reads it: the line holds + /// the wheel by its URL, and Bazel takes the committed copy + /// ([`super::pypi_distdir`]). + BazelCache, /// Re-wire the vendor lines an OLDER patch uuid's ledger entry recorded /// to this uuid in place (#765). RequirementsRewire(Box), @@ -1192,14 +1196,30 @@ async fn pypi_prelude<'p>( } } PypiFlavor::Requirements => { - match preflight_requirements(project_root, &canon_name, version, &record.uuid).await { - Ok(RequirementsTarget::InSync { pin }) => { - wired_pin = pin; + // Beside a Bazel hub that reads the file, the wheel is a + // download cache of Bazel, or already is (its pin). + let cache = super::bazel_hub::download_cache(project_root, base, &record.uuid).await; + match cache.map_err(|(code, detail)| refused(code, detail))? { + Some(Some(pin)) => { + wired_pin = Some(pin); WiringPlan::InSync } - Ok(RequirementsTarget::Fresh) => WiringPlan::Requirements, - Ok(RequirementsTarget::Rewire { prev }) => WiringPlan::RequirementsRewire(prev), - Err((code, detail)) => return Err(refused(code, detail)), + Some(None) => WiringPlan::BazelCache, + None => { + match preflight_requirements(project_root, &canon_name, version, &record.uuid) + .await + { + Ok(RequirementsTarget::InSync { pin }) => { + wired_pin = pin; + WiringPlan::InSync + } + Ok(RequirementsTarget::Fresh) => WiringPlan::Requirements, + Ok(RequirementsTarget::Rewire { prev }) => { + WiringPlan::RequirementsRewire(prev) + } + Err((code, detail)) => return Err(refused(code, detail)), + } + } } } PypiFlavor::Poetry => { @@ -1527,7 +1547,9 @@ async fn pypi_prelude<'p>( None }; - let reused_wheel = if !in_sync { + // The line of a download cache holds the URL of the wheel, which only + // a fetch gives. + let reused_wheel = if !in_sync && !matches!(plan, WiringPlan::BazelCache) { fresh_reuse_wheel( base, project_root, @@ -1609,6 +1631,17 @@ fn sibling_lock(flavor: PypiFlavor) -> Option<(&'static str, &'static str)> { } } +/// Whether the project wires the package `purl` through its requirements +/// files alone ([`PypiFlavor::Requirements`]): no lock of a tool holds it. +pub(super) async fn pins_in_requirements_alone(project_root: &Path, purl: &str) -> bool { + let Some((name, version)) = parse_pypi_purl(strip_purl_qualifiers(purl)) else { + return false; + }; + let name = canonicalize_pypi_name(&name); + let flavor = detect_pypi_flavor(project_root, Some((&name, &version))).await; + matches!(flavor, Ok((PypiFlavor::Requirements, _))) +} + /// 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` @@ -2084,10 +2117,16 @@ pub async fn vendor_pypi_with_pipenv_version<'a>( Err(outcome) => return outcome, }; let version = version.as_str(); - let reused = reused_wheel.is_some(); + // A download cache is fetched again for its URL, into the directory an + // earlier run may have committed: that wheel stays when this run fails, + // as a reused one does. + let reused = reused_wheel.is_some() + || (matches!(plan, WiringPlan::BazelCache) + && uuid_dir_has_wheel(&project_root.join(&uuid_dir_rel)).await); let AcquiredWheel { wheel_name, + url, rel_wheel, result, artifact, @@ -2430,6 +2469,22 @@ pub async fn vendor_pypi_with_pipenv_version<'a>( ) .await .map(|wiring| (wiring, MetaSlot::None)), + WiringPlan::BazelCache => super::pypi_distdir::wire( + project_root, + base, + &record.uuid, + (&wheel_name, &url, &artifact.sha256_hex), + &hosted_origins, + ) + .await + .map(|wiring| { + warnings.push(super::pypi_distdir::notice( + &canon_name, + version, + &rel_wheel, + )); + (wiring, MetaSlot::None) + }), WiringPlan::RequirementsRewire(prev) => rewire_requirements( project_root, &prev, @@ -3932,6 +3987,7 @@ async fn fresh_reuse_wheel( }; let abs = project_root.join(&art.rel_path); Some(AcquiredWheel { + url: String::new(), rel_wheel: art.rel_path.clone(), result: already_patched_result(base, &abs, &record.files), artifact: Some(WheelArtifact { @@ -3957,6 +4013,9 @@ fn reusable_wheel_leaf(leaf: &str, canon_name: &str, version: &str) -> bool { struct AcquiredWheel { wheel_name: String, + /// Where the wheel was fetched from; empty for a committed wheel that + /// is reused. + url: String, rel_wheel: String, result: ApplyResult, /// `None` on a dry run. @@ -4087,6 +4146,7 @@ async fn try_pypi_service_wheel( }; warnings.push(archive.downloaded_warning(format_args!("the wheel for {base}"))); Ok(Box::new(AcquiredWheel { + url: archive.source_url.clone(), rel_wheel, result: if dry_run { super::common::preview_result(base, &dest, &record.files) diff --git a/crates/socket-patch-core/src/vendor/pypi_distdir.rs b/crates/socket-patch-core/src/vendor/pypi_distdir.rs new file mode 100644 index 000000000..10e940598 --- /dev/null +++ b/crates/socket-patch-core/src/vendor/pypi_distdir.rs @@ -0,0 +1,585 @@ +//! PyPI vendored mode for a project whose `requirements.txt` a Bazel hub +//! reads: the patched wheel as a download cache of Bazel. +//! +//! rules_python builds no wheel from the path line that vendored mode +//! writes ([`super::bazel_hub`]). It does build the line hosted mode +//! writes, ` @ +//! --hash=sha256:`: its hub fetches such a wheel with Bazel's +//! downloader, and that one takes a file of the download's name and sha256 +//! from a `--distdir` before it asks a host ([`crate::bazel::distdir`]). So +//! here vendored mode writes +//! +//! 1. the package's line of `requirements.txt` as hosted mode writes it, by +//! hosted mode's own rewriter; +//! 2. the patched wheel, fetched once, at `.socket/vendor/pypi//` +//! under the name its URL ends in, with what vendored mode keeps beside +//! every wheel; +//! 3. one `common --distdir=` line in the `.bazelrc` at the +//! Bazel root ([`sync_bazelrc`]). +//! +//! The build then takes the committed wheel and asks no host. The ledger +//! entry is an ordinary one of the requirements flavor whose record holds +//! the URL line in the place of the path line ([`line_of`]), so the revert +//! of that flavor puts the pin back, and lockfile discovery reads the line +//! as the wiring of that entry ([`claim`]): `list`, `vex`, `vendor +//! --check`, `rollback` and `remove` see a vendored package. +//! +//! It is written only where [`gate`] can show from the checkout that it +//! works, and the refusal of [`super::bazel_hub`] stands everywhere else. +//! Three limits come with the line being the hosted one. pip outside Bazel +//! asks the patch host for the wheel. Bazel replaces a changed or missing +//! copy from the patch host, without a message, when it can reach it. +//! And what holds the committed wheel to the patch is `vendor --check`. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +use crate::bazel::{distdir, BazelRoot}; +use crate::crawlers::python_crawler::canonicalize_pypi_name; +use crate::formats::governing_locks::PYPI_REQUIREMENTS as FILE; +use crate::patch::redirect::requirements::rewrite; +use crate::patch::redirect::{grant, DepOverride, Integrity, RewriteResult}; +use crate::utils::fs::{atomic_write_bytes_preserving_mode, read_regular_to_string, run_blocking}; +use crate::utils::line_endings::split_lines; +use crate::utils::purl::{parse_pypi_purl, strip_purl_qualifiers}; +use crate::utils::purl_key::{canonical_base_purl, PurlKey}; +use crate::utils::requirements::{direct_reference, logical_lines, requires_hashes, strip_comment}; +use crate::vex::discover::{Discovery, Recognized, WiringMode}; + +use super::bazel_hub::PYPI_CODE; +use super::path::vendor_uuid_dir_rel; +use super::pypi_requirements::{one_pin, RECORD_KIND}; +use super::state::{ + load_state_shared as load_state, lookup_entry, VendorEntry, WiringAction, WiringRecord, +}; +use super::VendorWarning; + +/// The code of the warning a run gives with the form: what it does not do. +pub const NOTICE: &str = "vendor_pypi_bazel_download_cache"; + +/// Whether `line` is one requirement that holds the release `purl` by a +/// URL of the patch `uuid`: the line of this form. +pub(super) fn names(line: &str, purl: &str, uuid: &str) -> bool { + let Some((name, _)) = parse_pypi_purl(strip_purl_qualifiers(purl)) else { + return false; + }; + let named = |(of, url): (&str, &str)| { + canonicalize_pypi_name(of) == canonicalize_pypi_name(&name) + && url.split('/').any(|level| level == uuid) + }; + !line.contains(['\n', '\r']) && direct_reference(strip_comment(line)).is_some_and(named) +} + +/// The line of `requirements.txt` that `entry` wrote, when the entry is +/// one of this form. +pub fn line_of(entry: &VendorEntry) -> Option<&str> { + let own = |rec: &&WiringRecord| rec.kind == RECORD_KIND && rec.file == FILE; + let own = entry.wiring.iter().filter(own); + let line = own.filter_map(|rec| rec.new.as_ref()?.as_str()).next()?; + (entry.ecosystem == "pypi" && names(line, &entry.base_purl, &entry.uuid)).then_some(line) +} + +/// Where the committed wheel is pinned, `(path, sha256)`, when the project +/// already holds the package `purl` in this form for the patch `uuid`: the +/// ledger has the entry and `requirements.txt` its line. Such a run writes +/// nothing, whatever the workspace says now. +pub(super) async fn in_sync(project: &Path, purl: &str, uuid: &str) -> Option<(String, String)> { + let state = load_state(project).await.ok()?; + let entry = lookup_entry(&state.entries, purl).filter(|entry| entry.uuid == uuid)?; + let line = line_of(entry)?; + let content = read_regular_to_string(&project.join(FILE)).await.ok()?; + let held = logical_lines(&content) + .iter() + .any(|own| own.text.trim() == line.trim()); + held.then(|| (entry.artifact.path.clone(), entry.artifact.sha256.clone())) +} + +/// `content` with the pin back that an older patch of `purl` replaced in +/// this form: the newer patch `uuid` is then written over that pin, and +/// records it as its own original. +async fn without_older(project: &Path, purl: &str, uuid: &str, content: String) -> String { + let Ok(state) = load_state(project).await else { + return content; + }; + let older = lookup_entry(&state.entries, purl).filter(|entry| entry.uuid != uuid); + let Some((line, older)) = older.and_then(|older| Some((line_of(older)?, older))) else { + return content; + }; + let pin: Option = older.wiring.iter().find_map(|rec| { + let lines = rec.original.as_ref()?.as_array()?.iter(); + lines.map(Value::as_str).collect() + }); + let lines = split_lines(&content).into_iter(); + let restored = |(text, eol): (&str, &str)| match (text.trim() == line.trim(), &pin) { + (true, Some(pin)) => format!("{pin}{eol}"), + _ => format!("{text}{eol}"), + }; + lines.map(restored).collect() +} + +/// What hosted mode is granted for the release `purl`: the patch `uuid` as +/// the wheel at `url` with `sha256`. `None` for a purl that names no +/// release of a PyPI package. +fn granted(purl: &str, uuid: &str, (url, sha256): (&str, &str)) -> Option { + let (name, version) = parse_pypi_purl(strip_purl_qualifiers(purl))?; + Some(DepOverride { + ecosystem: "pypi".to_string(), + name: name.to_string(), + namespace: None, + version: version.to_string(), + token: String::new(), + patch_uuid: uuid.to_string(), + artifact_url: url.to_string(), + npm_registry_url: None, + registry_override: None, + integrity: Integrity { + sha256: Some(sha256.to_string()), + ..Integrity::default() + }, + }) +} + +/// `content` with the pin of the release `purl` as hosted mode writes it +/// for the wheel at `url` with `sha256`, and the record of that edit. Or +/// why the line is not written: hosted mode's rewriter does not pin the +/// package there, or the line would hold more than the form was measured +/// with, a name, the URL and one `--hash`. +fn planned( + content: &str, + purl: &str, + uuid: &str, + (url, sha256): (&str, &str), +) -> Result<(String, WiringRecord), String> { + let Some(dep) = granted(purl, uuid, (url, sha256)) else { + return Err(format!("{purl} names no release of a PyPI package")); + }; + let (name, version) = (&dep.name, &dep.version); + if !requires_hashes(content) { + return Err(format!( + "{FILE} pins no hashes, and Bazel takes a committed wheel only for a download \ + that the line gives a sha256" + )); + } + let files = BTreeMap::from([(FILE.to_string(), content.to_string())]); + let mut result = RewriteResult::default(); + rewrite(&files, std::slice::from_ref(&dep), &mut result); + let (edit, new) = match (&result.edits[..], result.files.remove(FILE)) { + ([edit], Some(new)) if result.warnings.is_empty() => (edit, new), + _ => { + let why = result.warnings.first().map(|warning| &*warning.detail); + let why = why.unwrap_or("it holds no pin for hosted mode to rewrite"); + return Err(format!( + "hosted mode does not pin {name}=={version} in {FILE}: {why}" + )); + } + }; + let text = |value: &Option| value.as_ref().and_then(Value::as_str).map(str::to_string); + let (original, line) = (text(&edit.original), text(&edit.new)); + let (original, line) = (original.unwrap_or_default(), line.unwrap_or_default()); + let plain = format!("{name} @ {url} --hash=sha256:{sha256}"); + if line != plain || !one_pin(&original, &canonicalize_pypi_name(name), version) { + return Err(format!( + "the requirement of {name}=={version} in {FILE} is more than one exact pin with its \ + hashes (extras, a marker, an option, a comment or an indent), and Bazel was \ + measured with the plain line" + )); + } + // Each line of the pin with its own line break, but for the last. + let lines = split_lines(&original).into_iter(); + let lines = lines.map(|(text, eol)| Value::String(format!("{text}{eol}"))); + let at = content + .find(&original) + .map_or(0, |at| content[..at].matches('\n').count()); + let record = WiringRecord { + file: FILE.to_string(), + kind: RECORD_KIND.to_string(), + action: WiringAction::Rewritten, + key: Some(format!("{FILE}:{}", at + 1)), + original: Some(Value::Array(lines.collect())), + new: Some(Value::String(line)), + }; + Ok((new, record)) +} + +/// Why vendored mode cannot show, from the checkout, that this form works +/// for the package `purl` of `project` and its patch `uuid`, where a call +/// of the workspace `root` hands Bazel one of `locks`, the files of the +/// project a run could rewrite. `Ok` when it can: +/// +/// - the project pins in `requirements.txt` alone, with no lock of a tool +/// beside it; +/// - the workspace shows that a build takes the wheel from the line +/// ([`distdir::ready`]): the hub reads that file and no other of the +/// project, the releases of rules_python and Bazel are ones it is shown +/// for, and no rc file names a downloader setting; +/// - hosted mode pins the package in that file, in a line of the measured +/// shape ([`planned`]), or the file holds a pin that hosted mode made; +/// - a line of this form that the ledger knows is still as it was written. +pub(super) async fn gate( + project: &Path, + root: &BazelRoot, + locks: &[String], + (purl, uuid): (&str, &str), +) -> Result<(), String> { + if !super::pypi::pins_in_requirements_alone(project, purl).await { + return Err(format!( + "a tool's lock of this project holds the package beside {FILE}, and the form is \ + for a project that pins in {FILE} alone" + )); + } + let (root, locks) = (root.clone(), locks.to_vec()); + let dir = root.dir.clone(); + run_blocking(move || distdir::ready(&root, FILE, &locks)).await?; + rc_committed(&dir).await?; + let content = read_regular_to_string(&project.join(FILE)).await; + let content = content.map_err(|e| format!("{FILE} cannot be read: {e}"))?; + let content = without_older(project, purl, uuid, content).await; + let name = parse_pypi_purl(strip_purl_qualifiers(purl)).map(|(name, _)| name); + let name = canonicalize_pypi_name(&name.unwrap_or_default()); + let by_url = |line: &crate::utils::requirements::LogicalLine| { + let held = direct_reference(strip_comment(&line.text)); + held.is_some_and(|(of, _)| canonicalize_pypi_name(of) == name) + }; + let planned = planned(&content, purl, uuid, ("-", &"0".repeat(64))); + if planned.is_ok() || !logical_lines(&content).iter().any(by_url) { + return planned.map(drop); + } + // The file holds the package by a URL. Where the ledger has the package + // in this form, that is the line of the form, and no longer as it was + // written ([`in_sync`] and [`without_older`] know it as written): a + // run over it would fetch the wheel and then not write the line. + // Elsewhere it is a pin that hosted mode made, where its URL is one of + // a patch (which host serves it is judged with the pin): the run that + // takes it over puts the registry's pin back first, and the line is + // judged then ([`wire`]). Any other URL is the user's own reference, + // which no run takes over: declined here, before anything is fetched. + let state = load_state(project).await.unwrap_or_default(); + if lookup_entry(&state.entries, purl) + .and_then(line_of) + .is_some() + { + return Err(format!( + "the line that socket-patch wrote for this wheel in {FILE} has been changed since: \ + put it back as it was, or run `socket-patch vendor --revert` and vendor the package \ + again" + )); + } + let of_a_patch = |line: &crate::utils::requirements::LogicalLine| { + let held = direct_reference(strip_comment(&line.text)); + // The URL of a patch names the patch's id before its file. + let patch = |url| super::lock_inventory::pypi::hosted_artifact_url(url).ok(); + let names_patch = + |url| patch(url).is_some_and(|at| at.uuid_level.is_some_and(|id| !id.is_empty())); + held.is_some_and(|(of, url)| canonicalize_pypi_name(of) == name && names_patch(url)) + }; + if logical_lines(&content).iter().any(of_a_patch) { + return Ok(()); + } + Err(format!( + "{FILE} names the package by a URL of its own, and the form is written over a pin of \ + one version with its hashes" + )) +} + +/// Why the `.bazelrc` at the Bazel root `dir` would not reach a fresh +/// checkout: git ignores it and does not track it. The committed wheel +/// does (its own guard asks git), but without the rc file's line a build +/// of that checkout downloads the wheel from the patch host. A tracked +/// file is never ignored, and git that cannot answer, or a root outside a +/// work tree, lets it through, as the wheel's guard does. +async fn rc_committed(dir: &Path) -> Result<(), String> { + let rc = [".bazelrc".to_string()]; + match super::npm_dir::ignoring_rule_lines(dir, &rc, false).await { + Ok(Some(rules)) => Err(format!( + ".bazelrc is ignored by git and not tracked ({}), so a fresh checkout would not have \ + the line that makes Bazel take the committed wheel: commit .bazelrc or stop \ + ignoring it", + super::npm_dir::summarize_rules(&rules) + )), + _ => Ok(()), + } +} + +/// Whether the file `artifact` is a wheel that every platform installs +/// (`---none-any.whl`): what a build has taken from +/// a `--distdir` here. A source distribution and a wheel of one platform +/// reach the hub through other code, which no build here has run. +fn for_every_platform(artifact: &str) -> bool { + artifact.ends_with("-none-any.whl") +} + +/// Write the line of this form for the release `purl`, whose patched wheel +/// `wheel` (its file name) was fetched from `url` and has `sha256`: the +/// record of the edit, for the ledger. The URL is held to what hosted mode +/// asks of a grant, to naming the patch `uuid` on a patch host (`origins` +/// are the operator's own), and to ending in the name of the committed +/// file, by which Bazel finds it. +pub(super) async fn wire( + project: &Path, + purl: &str, + uuid: &str, + (wheel, url, sha256): (&str, &str, &str), + origins: &[String], +) -> Result, (&'static str, String)> { + let declined = |why: String| (PYPI_CODE, why); + if !for_every_platform(wheel) { + return Err(declined(format!( + "the patch service serves {wheel}, and the form was built with a wheel for every \ + platform (`-none-any.whl`) alone, not with a source distribution or a wheel of \ + one platform" + ))); + } + let hosted = super::lock_inventory::pypi::hosted_pypi_reference(url, origins); + let of_patch = hosted.is_some_and(|at| at.uuid_level.as_deref() == Some(uuid)); + if !of_patch || !url.ends_with(&format!("/{wheel}")) { + return Err(declined(format!( + "the patch service gave no URL for {wheel} that names the patch on a patch host \ + and ends in the name of the file" + ))); + } + let flaw = granted(purl, uuid, (url, sha256)).map(|dep| grant::check(&dep, origins)); + if let Some(Err(grant::Flaw::Malformed(why) | grant::Flaw::InsecureUrl(why))) = flaw { + return Err(declined(format!( + "hosted mode does not write the grant of the patched wheel: {why}" + ))); + } + let path = project.join(FILE); + let before = read_regular_to_string(&path).await; + let before = before.map_err(|e| declined(format!("{FILE} cannot be read: {e}")))?; + let content = without_older(project, purl, uuid, before).await; + let (content, record) = planned(&content, purl, uuid, (url, sha256)).map_err(declined)?; + super::common::refuse_symlinked(project, &[FILE]).await?; + match atomic_write_bytes_preserving_mode(&path, content.as_bytes()).await { + Ok(()) => Ok(vec![record]), + Err(e) => Err(( + "pypi_requirements_write_failed", + format!("cannot write {FILE}: {e}"), + )), + } +} + +/// What a run that wrote the form says of it: what it rests on, and the +/// three things it does not do. +pub(super) fn notice(name: &str, version: &str, wheel: &str) -> VendorWarning { + VendorWarning::new( + NOTICE, + format!( + "{name}=={version} is vendored as a download cache of Bazel: {FILE} names the \ + patched wheel by its URL on the patch host, as hosted mode does, and a \ + `--distdir` line of the .bazelrc at the Bazel root makes the build take the \ + committed copy {wheel} and ask no host: commit that file with the copy. pip \ + outside Bazel still asks the patch host. Bazel replaces a changed or missing copy \ + from the patch host, without a message, when it can reach it. `socket-patch \ + vendor --check` is what holds the committed wheel to the patch." + ), + ) +} + +/// Make the `.bazelrc` at the Bazel root of `project` agree with the +/// wheels the project has committed in this form ([`distdir::sync`]): the +/// directory of each ledger entry of the form has its line while it +/// exists. Without `add`, and with a ledger that cannot be read, lines are +/// only taken away. Outside a Bazel workspace nothing is read or written, +/// and that lookup is all the call costs. +pub async fn sync_bazelrc(project: &Path, add: bool) -> Result, String> { + let dir = project.to_path_buf(); + let Some(root) = run_blocking(move || crate::bazel::bazel_root(&dir)).await else { + return Ok(None); + }; + let state = load_state(project).await.unwrap_or_default(); + let cached = state + .entries + .values() + .filter(|entry| line_of(entry).is_some()); + let dirs: Vec = cached + .filter_map(|entry| vendor_uuid_dir_rel("pypi", &entry.uuid)) + .collect(); + run_blocking(move || distdir::sync(&root, &dirs, add)).await +} + +/// For lockfile discovery of the project at `root`: a reference of +/// `requirements.txt` to a wheel on the patch host is the wiring of a +/// vendored copy where a ledger entry of this form wrote that line. It is +/// then a vendored reference to the entry's wheel, and what the file says +/// of the patch (its id, and the grant in its URL) names no hosted pin. +/// Without such an entry nothing changes. +pub(crate) async fn claim(root: &Path, out: &mut Discovery) { + let line = |r: &crate::vex::discover::PatchedRef| { + r.mode == WiringMode::Hosted && r.source_file == Path::new(FILE) + }; + if !out.refs.iter().any(line) { + return; + } + let Ok(state) = load_state(root).await else { + return; + }; + let Discovery { + refs, recognized, .. + } = out; + for entry in state.entries.values().filter(|e| line_of(e).is_some()) { + let key = canonical_base_purl(&entry.base_purl); + let own = refs + .iter_mut() + .filter(|r| line(r) && r.uuid == entry.uuid && PurlKey::same(&r.purl, &key)); + for wired in own { + let url = wired.url.take().unwrap_or_default(); + wired.mode = WiringMode::Vendored; + wired.artifact_rel = Some(entry.artifact.path.trim_start_matches("./").to_string()); + wired.integrity_required = false; + let (file, hosted) = (wired.source_file.clone(), WiringMode::Hosted); + let of_url = |id: &Recognized| url.split('/').any(|level| level == id.uuid); + recognized.retain(|id| !(id.mode == hosted && id.file == file && of_url(id))); + recognized.push(Recognized { + uuid: entry.uuid.clone(), + mode: WiringMode::Vendored, + file, + }); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const UUID: &str = "11111111-1111-4111-8111-111111111111"; + const PURL: &str = "pkg:pypi/six@1.16.0"; + const SHA: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + const PINS: &str = "idna==3.7 \\\n --hash=sha256:1111\nsix==1.16.0 \\\n \ + --hash=sha256:2222 \\\n --hash=sha256:3333\n"; + + fn url(uuid: &str) -> String { + format!( + "https://patch.socket.dev/patch/pypi/six/1.16.0/tok/{uuid}/six-1.16.0-py3-none-any.whl" + ) + } + + /// An untracked `.bazelrc` that git ignores, there or not yet, would + /// not reach a fresh checkout; one that is tracked, or not ignored, + /// does. + #[tokio::test] + async fn an_ignored_untracked_bazelrc_is_declined() { + let Some(git) = crate::utils::process::resolve_tool("git") else { + return; + }; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let git = |args: &[&str]| { + let status = std::process::Command::new(&git) + .args(["-c", "user.name=t", "-c", "user.email=t@t"]) + .args(args) + .current_dir(root) + .status() + .unwrap(); + assert!(status.success(), "git {args:?}"); + }; + git(&["init", "-q"]); + assert_eq!(rc_committed(root).await, Ok(()), "no rule ignores it"); + std::fs::write(root.join(".gitignore"), ".bazelrc\n").unwrap(); + let missing = rc_committed(root).await.unwrap_err(); + assert!(missing.contains(".gitignore:1:.bazelrc"), "{missing}"); + std::fs::write(root.join(".bazelrc"), "build --jobs=4\n").unwrap(); + let untracked = rc_committed(root).await.unwrap_err(); + assert!(untracked.starts_with(".bazelrc is ignored"), "{untracked}"); + git(&["add", "-f", ".bazelrc"]); + assert_eq!( + rc_committed(root).await, + Ok(()), + "a tracked file is committed" + ); + } + + #[test] + fn only_a_wheel_for_every_platform_is_one_the_form_is_written_for() { + assert!(for_every_platform("six-1.16.0-py2.py3-none-any.whl")); + for other in [ + "six-1.16.0.tar.gz", + "six-1.16.0.zip", + "lxml-5.2.0-cp311-cp311-manylinux_2_28_x86_64.whl", + "pkg-1.0-cp311-abi3-any.whl", + ] { + assert!(!for_every_platform(other), "{other}"); + } + } + + #[test] + fn the_line_is_hosted_mode_s_and_the_record_restores_the_pin() { + let url = url(UUID); + let (new, record) = planned(PINS, PURL, UUID, (&url, SHA)).unwrap(); + let line = format!("six @ {url} --hash=sha256:{SHA}"); + assert_eq!( + new, + format!("idna==3.7 \\\n --hash=sha256:1111\n{line}\n") + ); + assert_eq!(record.new, Some(Value::String(line.clone()))); + assert_eq!(record.key.as_deref(), Some("requirements.txt:3")); + let pin = serde_json::json!([ + "six==1.16.0 \\\n", + " --hash=sha256:2222 \\\n", + " --hash=sha256:3333" + ]); + assert_eq!(record.original, Some(pin)); + assert!(names(&line, PURL, UUID)); + // Another package, another patch, a path line and two lines are + // not the line of this entry. + let other = "22222222-2222-4222-8222-222222222222"; + assert!(!names(&line, "pkg:pypi/idna@3.7", UUID)); + assert!(!names(&line, PURL, other)); + assert!(!names( + "./.socket/vendor/pypi/x/six-1.16.0-py3-none-any.whl", + PURL, + UUID + )); + assert!(!names(&format!("{line}\nidna==3.7"), PURL, UUID)); + // CRLF files keep their line breaks in the record. + let crlf = PINS.replace('\n', "\r\n"); + let (new, record) = planned(&crlf, PURL, UUID, (&url, SHA)).unwrap(); + assert!(new.ends_with(&format!("{line}\r\n")), "{new:?}"); + let first = record.original.as_ref().and_then(|lines| lines[0].as_str()); + assert_eq!(first, Some("six==1.16.0 \\\r\n")); + } + + /// The line is written for one exact pin with its hashes, where + /// hosted mode pins the package, and for nothing else. + #[test] + fn a_requirement_that_is_not_the_measured_shape_is_not_written() { + let pin = "six==1.16.0 --hash=sha256:2222\n"; + assert!(planned(pin, PURL, UUID, (&url(UUID), SHA)).is_ok()); + for (content, names) in [ + ("six==1.16.0\n", "pins no hashes"), + ( + "idna==3.7 --hash=sha256:1\n", + "hosted mode does not pin six==1.16.0", + ), + ("six>=1.16.0 --hash=sha256:2\n", "hosted mode does not pin"), + ("six==1.15.0 --hash=sha256:2\n", "hosted mode does not pin"), + ( + "-r base.txt\nidna==3.7 --hash=sha256:1\n", + "hosted mode does not pin", + ), + ( + "six[x]==1.16.0 --hash=sha256:2\n", + "is more than one exact pin", + ), + ( + "six==1.16.0 ; python_version > '3' --hash=sha256:2\n", + "is more than", + ), + ( + "six==1.16.0 --hash=sha256:2 # ours\n", + "is more than one exact pin", + ), + ( + " six==1.16.0 --hash=sha256:2\n", + "is more than one exact pin", + ), + ("six --hash=sha256:2\n", "is more than one exact pin"), + ] { + let why = planned(content, PURL, UUID, (&url(UUID), SHA)).unwrap_err(); + assert!(why.contains(names), "{content:?}: {why}"); + } + assert!(planned(pin, "pkg:npm/six@1.16.0", UUID, (&url(UUID), SHA)).is_err()); + } +} diff --git a/crates/socket-patch-core/src/vendor/pypi_requirements.rs b/crates/socket-patch-core/src/vendor/pypi_requirements.rs index d0e860d89..2bd4f36f8 100644 --- a/crates/socket-patch-core/src/vendor/pypi_requirements.rs +++ b/crates/socket-patch-core/src/vendor/pypi_requirements.rs @@ -1036,7 +1036,8 @@ fn ledger_record_refusal(entry: &VendorEntry, rec: &WiringRecord) -> Option Option Option bool { + let scan = scan_pins(text, canon_name, version); + logical_lines(text).len() == 1 + && scan.exact.len() == 1 + && !(scan.extras || scan.range || scan.other_branches || scan.templated) +} + fn drift_warning(file: &str, rec: &WiringRecord) -> VendorWarning { VendorWarning::new( "vendor_revert_line_drifted", diff --git a/crates/socket-patch-core/src/vex/discover/mod.rs b/crates/socket-patch-core/src/vex/discover/mod.rs index 8df5f54f7..9e397a4c7 100644 --- a/crates/socket-patch-core/src/vex/discover/mod.rs +++ b/crates/socket-patch-core/src/vex/discover/mod.rs @@ -2071,6 +2071,11 @@ async fn discover_with_ctx(mut ctx: DiscoverCtx<'_>) -> Discovery { out.recognized.extend(ctx.take_recognized()); out.read.extend(ctx.take_read()); out.patch_server_origins = ctx.origin.origins().to_vec(); + // A wheel that vendored mode committed as a download cache of Bazel + // is wired by a line that names it on the patch host. + if let Some(root) = ctx.disk_root_reading([crate::vendor::VENDOR_STATE_REL]) { + crate::vendor::pypi_distdir::claim(root, &mut out).await; + } out.finalize(); out } diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 949a0d26b..c17fcf146 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2151,7 +2151,7 @@ workspace and that Bazel does not build keeps the matrix at the top. | Ecosystem, and how Bazel takes its packages | Hosted | Vendored | Agent | VEX | |---|---|---|---|---| | npm: aspect_rules_js `npm.npm_translate_lock` over a pnpm lock | Supported with `pnpm-workspace.yaml` in the `data` of a hub that runs pnpm 11 or later | Supported | Not supported | Supported | -| PyPI: rules_python `pip.parse` over a requirements file | Supported | Not supported | Not supported | Supported | +| PyPI: rules_python `pip.parse` over a requirements file | Supported | Supported with rules_python 2.5.0 | Not supported | Supported | | Go: gazelle `go_deps.from_file` over `go.mod` | Supported | Supported | Not supported | Supported with a hosted or vendored patch | | RubyGems: rules_ruby `ruby.bundle_fetch` over `Gemfile.lock` | Supported with no `gem_checksums` on the call, or with one written out in the call that does not name the gem or holds it to the patched gem's sha256 | Not supported | Not supported | Supported | | Cargo: rules_rust `crate.from_cargo` over `Cargo.lock` | Supported with `cargo_config` on the hub | Supported | Not supported | Supported with a hosted or vendored patch | @@ -2178,6 +2178,9 @@ exits 0 and leaves a build that fails (the known problems below). What a cell sa 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)). + For PyPI it declines outside the condition of its cell, which + [Bazel workspaces: PyPI vendored mode as a download cache](#bazel-workspaces-pypi-vendored-mode-as-a-download-cache) + spells out. - **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 @@ -2209,7 +2212,10 @@ What the table was tested with: itself (10.34.9) and no `data`, and with pnpm 11.28.10 and `pnpm-workspace.yaml` in `data`. [Bazel workspaces: npm](#bazel-workspaces-npm) says what hosted mode does on such a hub. - **PyPI**: rules_python 2.5.0-rc4, `pip.parse(requirements_lock = "//:requirements.txt")`, - and a root `requirements.txt` with hashes. + and a root `requirements.txt` with hashes. Vendored mode pins the wheel by its URL, as + hosted mode does, commits it, and makes Bazel take the committed copy with a `--distdir` + line in [`.bazelrc`](#bazel-workspaces-pypi-vendored-mode-as-a-download-cache); the test + builds it with the patch host stopped. - **Go**: gazelle 0.54.0 with rules_go 0.65.0 (Bazel 9 and 8) and gazelle 0.45.0 with rules_go 0.53.0 (Bazel 7), `go_deps.from_file(go_mod = "//:go.mod")` with `go_deps.config(check_direct_dependencies = "error")`, and the module required directly in @@ -2248,7 +2254,7 @@ A ruleset, a release of one or a way of calling it that the list does not name i Treat it as not supported until a build after the command has shown you the patched package. Bazel's own lock: a command or an undo leaves `MODULE.bazel.lock` stale for PyPI on Bazel 8.5 -and later, for NuGet, and for Cargo under rules_rust 0.75.0. A build that may not update the +and later (hosted and vendored mode), for NuGet, and for Cargo under rules_rust 0.75.0. A build that may not update the lock (`--lockfile_mode=error`) fails until one that may, or `bazel mod deps --lockfile_mode=update`, has rewritten it. Commit the rewritten lock with the patch. The same holds for the file of hashes that rules_js keeps under `.aspect/` for a hub @@ -2327,8 +2333,16 @@ In these a command exits 0 and the Bazel build passes on the unpatched package: [Bazel workspaces: VEX](#bazel-workspaces-vex) lists what the document says in such cases. -And three that concern neither: +And four that concern neither: +- **Vendored PyPI is a download cache, not a lock that names the copy.** The line of + `requirements.txt` is the hosted one, so pip outside Bazel asks the patch host for the + wheel; Bazel replaces a changed or missing copy from the patch host, without a message, + when it can reach it (it never builds other bytes than the pinned wheel's); and a + downloader config that blocks the patch host fails the build although the copy is + committed, which is why vendored mode declines where an rc file of the checkout names + one or imports a file from outside the checkout. `socket-patch vendor --check` is what + holds the committed wheel to the patch: run it in CI. - **Vendored Cargo under rules_rust 0.75.0**: a build writes a `BUILD.bazel` into the committed copy, and right after it `vendor --check` exits 1 (`vendor_inventory_mismatch`) and `vex` writes no document, although the build is the patched one. A second @@ -3778,7 +3792,11 @@ and neither ruleset builds from such a file: Both were measured on Bazel 9.3.2, 8.8.2 and 7.7.2, after a `scan --mode vendored` that exited 0 and reported the package vendored. So vendored mode now declines such a package, where the -files of the workspace show that a hub reads the file it would rewrite. +files of the workspace show that a hub reads the file it would rewrite. For a PyPI package it +first asks whether the checkout shows that another form works, in which the build takes the +committed wheel, and writes that one where it does: +[Bazel workspaces: PyPI vendored mode as a download cache](#bazel-workspaces-pypi-vendored-mode-as-a-download-cache). +What follows is what happens everywhere else. **What is read.** The project is in a Bazel workspace by the lookup of [Bazel workspaces: `.bazelignore`](#bazel-workspaces-bazelignore). There socket-patch reads @@ -3847,7 +3865,9 @@ and line, the lock, and the mode to use instead: ``` 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 +call stands. For a PyPI package whose hub was read with certainty the message goes on with +why the download cache is not written +([the conditions](#bazel-workspaces-pypi-vendored-mode-as-a-download-cache)). 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 @@ -3921,6 +3941,148 @@ Limits: [`ruby.rs`](../crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs) run the refusal, the switch and hosted mode on a real Bazel. +## Bazel workspaces: PyPI vendored mode as a download cache + +Where a rules_python `pip.parse` hub reads the project's `requirements.txt`, the path line of +vendored mode breaks the build +([Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode)). +The line of hosted mode does not: the hub fetches a wheel that a requirement names by its URL +with Bazel's own downloader, by the sha256 of the line. And before Bazel downloads a file +that has a checksum, it looks in every `--distdir` for a file of that name and checksum. So +in such a project `scan --mode vendored` (and `get --mode vendored`, and `vendor`) writes +three things: + +1. **The package's line of `requirements.txt`, exactly as hosted mode writes it**: + ` @ --hash=sha256:`. +2. **The patched wheel**, downloaded once, at `.socket/vendor/pypi//`, under the + file name its URL ends in, with the files vendored mode keeps beside every wheel and its + entry in `.socket/vendor/state.json`. +3. **One line in the `.bazelrc` at the Bazel root**, under a comment line of socket-patch's + own: + + ``` + # socket-patch: the committed copy of a patched wheel, for Bazel's downloads (to opt out, comment out the next line) + common --distdir=.socket/vendor/pypi/ + ``` + + The directory is written from the Bazel root (`svc/.socket/vendor/pypi/` for a + project in `svc`): Bazel reads a relative `--distdir` from the workspace root, from any + directory a command runs in, and does not expand `%workspace%` in this option. + +Commit all of it. The build then takes the committed wheel and asks no host. Measured with +rules_python 2.5.0-rc4 on Bazel 9.3.2, 8.8.2 and 7.7.2: a fresh clone builds the patched +package with the patch host stopped, a new output base and no copy of the wheel in Bazel's +repository cache, also from a sub-directory and beside a `--distdir` of your own. +[`e2e_bazel_build/pypi.rs`](../crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs) builds +that on the three releases, in a checkout whose `.bazelrc` has a `--distdir` line of its own. + +Each patch gets a line for its own directory. A `--distdir` is one flat directory that Bazel +searches by file name, two patches of one release have wheels of one name, and the directory +of a patch is what vendored mode writes, checks and removes as a unit. + +**When it is written.** Only where the files of the checkout show that it works. Each +condition that fails declines the package with `vendor_pypi_bazel_hub`, as before, and the +message ends with the one that failed: + +- The project pins in `requirements.txt` alone (no uv, Pipenv, Poetry, PDM or PEP 751 lock + holds the package), and that file is in pip's hash-checking mode: Bazel takes a committed + file only for a download that has a checksum. +- The package's requirement is one exact pin with its hashes, which is what hosted mode + rewrites; extras, an environment marker, an option, a comment or an indent on it decline, + because the form was measured with the plain line. +- A `pip.parse` names that file by `requirements_lock`, and names no other file of the + project by any attribute (a `requirements_linux` or `requirements_by_platform` beside it + would build some platform from a file that is not written). Every call of the hub is + written out and runs, nothing of the module files is in doubt, and no `WORKSPACE` file + defines repositories. +- Bazel selected rules_python 2.5.0 (or 2.5.0-rc4, the same commit). socket-patch reads that + as it reads the release of rules_jvm_external: from the one `source.json` of the ruleset + that `MODULE.bazel.lock` records, checked against what `MODULE.bazel` asks for. A checkout + without that lock, or with a stale one, is declined: build once, so that Bazel writes it. + Other releases fetch a wheel through other code, which no build here has run. +- The checkout names Bazel 7, 8 or 9 (`.bazeliskrc`, `.bazelversion`); or it names none and + its `MODULE.bazel.lock` has a version that Bazel 7.5.0 to 9.3.2 write. +- No rc file of the checkout (`.bazelrc` and what it imports) names a downloader config + (`--downloader_config`, `--experimental_downloader_config`), `--repository_disable_download` + or a remote downloader, and all of them can be read. Bazel refuses a download that such a + config blocks before it looks in a `--distdir`. An `import` or `try-import` of an absolute + path declines as well: that file is outside the checkout, socket-patch does not read it, + and it is where the settings of a site's mirror usually are. +- The line can be written: `.bazelrc` is no symbolic link and not read-only, and the + project's path from the Bazel root holds no blank, quote, backslash or `#`. + +Three more are seen only later. A requirement that names the package by a URL of the user's +own, and not by a version, is declined before anything is fetched (no scan finds a package in +such a line; `get` for the release does). A hub that names a file which brings +`requirements.txt` in with `-r` is declined, whichever of several hubs is written first. And +what the patch service serves must be a wheel for every platform (`-none-any.whl`): for a +source distribution or a wheel of one platform the run fails after its download +(`apply_failed`, with an error that starts `vendor_pypi_bazel_hub:`), writes no line and +keeps a wheel that an earlier run committed. + +With `--allow-vendored-in-bazel` vendored mode writes the path line instead, here too: the +switch says that no build takes the project's packages from the hub. + +**What it does not do.** The command says the first two in a warning +(`vendor_pypi_bazel_download_cache`) when it writes the form: + +- pip outside Bazel reads the same line, and asks the patch host for the wheel. It does not + take the committed copy. +- With the patch host unreachable, a changed or missing copy fails the build. With the host + reachable, Bazel passes over such a copy without a message and downloads the pinned wheel: + it never builds other bytes, and it never says that the committed copy is wrong. + `socket-patch vendor --check` is what holds the committed wheel to the patch, so run it + in CI. A machine whose repository cache already holds the wheel does not read the copy at + all. +- A relock (`pip-compile`, a version bump) writes the registry's pin back over the line. The + build is then green and unpatched, and the copy and its `.bazelrc` line stay behind + without effect. `socket-patch vendor --check` fails on that, and the next scan pins the + package again. That scan asks the patch service for the wheel once more, also where the + committed copy is intact: the line holds the URL the service grants, and a run takes it + from the grant. +- A downloader config that the files of the checkout do not show is not seen: one given on + the command line, in the rc file of the home directory or of the machine, or in a file + that a `try-import` names and this checkout does not have (a `user.bazelrc` that is not + committed). Where it blocks the patch host the build fails although the copy is + committed, as it fails on a hosted pin. +- A build that may not update Bazel's lock (`--lockfile_mode=error`) fails right after the + command on Bazel 8.5 and later, until a build that may update `MODULE.bazel.lock` has + run, as in hosted mode. Commit the updated lock with the patch. +- A Bazel command that reads no workspace rc file (`--ignore_all_rc_files`, + `--noworkspace_rc`) does not see the line, and asks the patch host (by Bazel's + documentation of the two options; not run). +- Not measured: a second Python version in the hub, Linux and Windows (every run was on + macOS; CI runs the test on Linux), and remote execution. + +**The `.bazelrc` lines.** They are kept as the `.bazelignore` lines of +[Bazel workspaces: `.bazelignore`](#bazel-workspaces-bazelignore) are, by the same commands +(every one that can write or remove a copy ends by bringing the file in line, unless it is a +dry run; one whose `--ecosystems` leaves `pypi` out adds no line). A line is added at the +end of the file for the directory of each such wheel while it exists, and the pair is taken +away once the directory is gone, which leaves the file as it was, byte for byte; a `.bazelrc` +left empty is removed, also when it was an empty file of yours. Your own lines are never +touched. To decline a line, put a `#` before it and leave socket-patch's comment above it: +nothing is added for that directory again, and the two lines stay yours. A `.bazelrc` that is +a link or read-only declines the package before anything is written (the conditions above). +A file that cannot be written when the command gets to it (it became read-only since, the +root directory takes no new file, or an undo finds its pair in a file it may not change) is +a warning, `bazelrc_not_updated`, that names the line to add or the pair that can be +deleted; without the line the build downloads the wheel from the patch host, as in hosted +mode. + +**The other commands.** `list` shows the package as vendored, and `vex` attests it as a +vendored package whose committed wheel holds the patch (`not_affected`): the hub builds that +wheel, by the sha256 of the line. `vendor --check` verifies the committed wheel against the +patch and that `requirements.txt` still holds the line. `vendor --revert`, `rollback` and +`remove` put the pin back as it was, delete the directory and take the pair out of +`.bazelrc`; none of them needs a host. A later run in the same mode writes nothing, while +`requirements.txt` holds the line as the run wrote it. A line that has been changed since +(by hand: a comment after it, its hash moved to a line of its own) declines the package +with `vendor_pypi_bazel_hub` before anything is fetched, and the committed wheel and its +`.bazelrc` line stay: put the line back, or run `socket-patch vendor --revert` and vendor +again. A `scan --mode hosted` takes the package over: the line stays, and the copy and its +`.bazelrc` pair go. A newer patch of the package replaces the line, the wheel and the pair. + ## Ruby gems: hosted mode `scan --mode hosted` makes Bundler install a patched gem from that patch's own gem source on @@ -4473,7 +4635,10 @@ is patched: 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. + earlier release. A wheel that vendored mode committed as a + [download cache](#bazel-workspaces-pypi-vendored-mode-as-a-download-cache) is not such a + copy: the file the hub reads names it by its URL and sha256, as a hosted pin does, and the + package keeps its `not_affected` statement. 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 @@ -4570,7 +4735,7 @@ The document and the build are tested to agree on real Bazel 9.3.2, 8.8.2 and `go.mod` (hosted and vendored mode), npm through aspect_rules_js's `npm.npm_translate_lock(pnpm_lock = "//:pnpm-lock.yaml")` (hosted and vendored), PyPI through rules_python's `pip.parse(requirements_lock = "//:requirements.txt")` -(hosted), and RubyGems through rules_ruby's +(hosted, and vendored as a download cache), and RubyGems through rules_ruby's `ruby.bundle_fetch(gemfile_lock = "//:Gemfile.lock")` without `gem_checksums` (hosted). There the build prints the patched package, and the document of the run (`--vex`), of `vex` and of `vex --no-verify` is one `not_affected` statement that names the package and the patch; the diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 01494161d..dae5ba114 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 4042 + "max": 4304 }, "lock-readers": { "paths": [