diff --git a/.github/workflows/bazel-cargo.yml b/.github/workflows/bazel-cargo.yml index 931c7dbac..e19a1adcc 100644 --- a/.github/workflows/bazel-cargo.yml +++ b/.github/workflows/bazel-cargo.yml @@ -3,8 +3,9 @@ name: Bazel patch compatibility (Cargo) # The Cargo flows of the real-Bazel tests (`cargo::` in `e2e_bazel_build`): # hosted and vendored mode for a crate that rules_rust's crate_universe # resolves from a Cargo workspace (`crate.from_cargo`, with the project's -# cargo config and no cargo-bazel lock), and hosted mode on the hub that -# names no cargo config, on each Bazel release below. +# cargo config and no cargo-bazel lock), hosted mode on the hub that names +# no cargo config, and agent mode for the copy of the crate in a cargo +# home, on each Bazel release below. # bazel-compatibility.yml holds the legs and what every ecosystem shares; # this file says when the Cargo legs run and on which releases. # @@ -16,9 +17,9 @@ name: Bazel patch compatibility (Cargo) # it comes to about 230 MB after one Bazel release and about 240 MB once # both releases of the era have used it, and to about 155 MB for the era of # 0.56.0 (macOS arm64). Every workspace copy unpacks the toolchain for -# itself, about 1.8 GB, and a leg has two at a time, one per test: a test -# removes its first copy before its second machine builds (3.6 GB at the -# peak on Bazel 9.3.2, macOS arm64). +# itself, about 1.8 GB, and a leg has two at a time, one per test that +# runs: a test removes its first copy before its second machine builds +# (3.6 GB at the peak on Bazel 9.3.2, macOS arm64). # # No leg asks crates.io about the crate under test. cargo-bazel's cargo # reads no downloader config, so the test's workspace names a mirror of @@ -47,25 +48,30 @@ on: # source replacement (formats/cargo/), the vendored backend # (vendor/cargo*, the lock inventory), the upstream restore of # `rollback`, the crawler every `scan` starts, the cargo home and - # workspace lookups, and the reader of a Cargo project that `vex` runs - # (vex/discover/cargo.rs). They also match Cargo files no flow runs - # (agent mode's sidecars and build cache), which are no other - # ecosystem's either. One more file is here for what the flows + # workspace lookups, the reader of a Cargo project that `vex` runs + # (vex/discover/cargo.rs), and the Cargo files of agent mode (its + # sidecars and build cache). One more file is here for what the flows # run through: patch/user_patches.rs, the inspection of the project's # own patches, which reads the Cargo.toml and the cargo config of every # scan. That file also holds the npm, Composer and Go parts of the # gate, so a change to those starts the Cargo legs too. The globs name - # that one crate, so no bench fixture is here, and nothing another - # ecosystem's flow owns: a change to one ecosystem starts that - # ecosystem's legs only. + # that one crate, so no bench fixture is here. Last, the VEX code: + # `vex/` of the core, the files of the `vex` command, and of `bazel/` + # of the core the reader of the workspace files (mod.rs, starlark.rs, + # workspace.rs, and rc.rs, which bazel/cargo.rs reads) and built.rs, + # which says what a hub builds. The agent flow holds the exact + # document socket-patch writes about its build, so a change to how a + # document is built or worded starts the legs of every ecosystem. + # Nothing else that another ecosystem's flow owns is here: any other + # change to one ecosystem starts that ecosystem's legs only. # # What it does not cover: shared engine code (patch/redirect/mod.rs, - # the rest of vendor/, hosted/, commands/), the shared test helpers and - # the toolchain files. A change there gets its run on the push to main - # (when the file is in the list below) or in the nightly run, not on the - # pull request: that is the price of not running every ecosystem's legs - # on every shared change. On demand, workflow_dispatch runs the legs on - # any branch. + # the rest of vendor/, hosted/, the rest of commands/, the apply engine + # of agent mode), the shared test helpers and the toolchain files. A + # change there gets its run on the push to main (when the file is in + # the list below) or in the nightly run, not on the pull request: that + # is the price of not running every ecosystem's legs on every shared + # change. On demand, workflow_dispatch runs the legs on any branch. paths: - '.github/workflows/bazel-cargo.yml' - '.github/workflows/bazel-compatibility.yml' @@ -77,6 +83,13 @@ on: - 'crates/socket-patch-core/src/**/*cargo*' - 'crates/socket-patch-core/src/**/*cargo*/**' - 'crates/socket-patch-core/src/patch/user_patches.rs' + - 'crates/socket-patch-core/src/bazel/built.rs' + - 'crates/socket-patch-core/src/bazel/mod.rs' + - 'crates/socket-patch-core/src/bazel/rc.rs' + - 'crates/socket-patch-core/src/bazel/starlark.rs' + - 'crates/socket-patch-core/src/bazel/workspace.rs' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' push: branches: [main] # The pull request paths, and what only a push to main covers: the @@ -96,6 +109,13 @@ on: - 'crates/socket-patch-core/src/**/*cargo*' - 'crates/socket-patch-core/src/**/*cargo*/**' - 'crates/socket-patch-core/src/patch/user_patches.rs' + - 'crates/socket-patch-core/src/bazel/built.rs' + - 'crates/socket-patch-core/src/bazel/mod.rs' + - 'crates/socket-patch-core/src/bazel/rc.rs' + - 'crates/socket-patch-core/src/bazel/starlark.rs' + - 'crates/socket-patch-core/src/bazel/workspace.rs' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/vendor/**' diff --git a/.github/workflows/bazel-nuget.yml b/.github/workflows/bazel-nuget.yml index e746a4755..135293751 100644 --- a/.github/workflows/bazel-nuget.yml +++ b/.github/workflows/bazel-nuget.yml @@ -2,8 +2,9 @@ name: Bazel patch compatibility (NuGet) # The NuGet flows of the real-Bazel tests (`nuget::` in `e2e_bazel_build`): # hosted mode for a package that rules_csharp's `nuget.from_lock` reads from -# `packages.lock.json` and `nuget.config`, and for a tag that names no -# `nuget_config`, on each Bazel release below. +# `packages.lock.json` and `nuget.config`, for a tag that names no +# `nuget_config`, and agent mode for the copy of the package in NuGet's +# global packages folder, on each Bazel release below. # bazel-compatibility.yml holds the legs and what every ecosystem shares; # this file says when the NuGet legs run and on which releases. # @@ -27,34 +28,41 @@ name: Bazel patch compatibility (NuGet) on: pull_request: types: [opened, synchronize, reopened, ready_for_review] - # What a pull request run covers: the NuGet flow and its fixture, the + # What a pull request run covers: the NuGet flows and their fixture, the # harness and the workflows that run it, the Bazel installer and its # pins, and the NuGet files of the product that `scan --mode hosted`, - # `vex` and `rollback` run through in the fixture, each by its own - # path: the readers of `packages.lock.json` and `nuget.config` and the - # `contentHash` of a package (formats/nuget), the NuGet crawler, which - # finds a package in the global packages folder, the reader of the - # NuGet settings a project inherits (vendor/nuget_config.rs), the - # discovery of a hosted pin in the two files, the upstream restore of - # `rollback`, and the hosted scan's check of that folder. Then what - # reads the tag in `MODULE.bazel`: the reader of the workspace files, - # which every ecosystem's flow shares (bazel/mod.rs, starlark.rs and - # workspace.rs), and what hosted mode makes of the tag (bazel/nuget.rs). + # `scan --mode agent`, `vex` and `rollback` run through in the fixture, + # each by its own path: the readers of `packages.lock.json` and + # `nuget.config` and the `contentHash` of a package (formats/nuget), the + # NuGet crawler, which finds a package in the global packages folder, + # the reader of the NuGet settings a project inherits + # (vendor/nuget_config.rs), the discovery of a hosted pin in the two + # files, the upstream restore of `rollback`, and the hosted scan's check + # of that folder. Then what reads the tag in `MODULE.bazel`: the reader + # of the workspace files, which every ecosystem's flow shares + # (bazel/mod.rs, starlark.rs and workspace.rs), and what hosted mode + # makes of the tag (bazel/nuget.rs). # vendor/nuget_feed.rs is the vendored backend; it is here for the # version and folder helpers that every one of those files calls. - # Nothing else that another ecosystem's flow owns is here, so any other - # change to one ecosystem starts that ecosystem's legs only. + # patch/sidecars/nuget.rs is what agent mode does to a package in + # NuGet's folder beyond its files. Last, the VEX code: `vex/` of the + # core, the files of the `vex` command, and what `vex` makes of the tag + # (bazel/built.rs, which says what the hub of each ecosystem builds). + # The agent flow holds the exact document socket-patch writes about its + # build, so a change to how a document is built or worded starts the + # legs of every ecosystem. Nothing else that another ecosystem's flow + # owns is here: any other change to one ecosystem starts that + # ecosystem's legs only. # # What it does not cover: shared engine code. The hosted rewrite itself # is there (`rewrite_nuget` in patch/redirect/mod.rs, the file of every # ecosystem's rewriter), and so are patch/redirect/grant.rs, - # hosted/engine.rs, commands/scan/hosted.rs and the rest of vex/, the - # shared test helpers and the toolchain files. A change to one of those - # gets its run on the push to main (when the file is in the list below) - # or in the nightly run, not on the pull request: that is the price of - # not running every ecosystem's legs on every shared change. The flow - # does not run agent mode (patch/sidecars/nuget.rs), which is in neither - # list. On demand, workflow_dispatch runs the legs on any branch. + # hosted/engine.rs, commands/scan/hosted.rs, the apply engine of agent + # mode, the shared test helpers and the toolchain files. A change to + # one of those gets its run on the push to main (when the file is in + # the list below) or in the nightly run, not on the pull request: that + # is the price of not running every ecosystem's legs on every shared + # change. On demand, workflow_dispatch runs the legs on any branch. paths: - '.github/workflows/bazel-nuget.yml' - '.github/workflows/bazel-compatibility.yml' @@ -70,18 +78,22 @@ on: - 'crates/socket-patch-core/src/vex/discover/nuget.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/nuget.rs' - 'crates/socket-patch-cli/src/commands/scan/hosted/nuget.rs' + - 'crates/socket-patch-core/src/bazel/built.rs' - 'crates/socket-patch-core/src/bazel/mod.rs' - 'crates/socket-patch-core/src/bazel/nuget.rs' - 'crates/socket-patch-core/src/bazel/starlark.rs' - 'crates/socket-patch-core/src/bazel/workspace.rs' + - 'crates/socket-patch-core/src/patch/sidecars/nuget.rs' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' push: branches: [main] # The pull request paths, and what only a push to main covers: the # root of the test target (it changes when an ecosystem's module is # added; ci.yml builds the target and runs its hermetic tests on every - # pull request), the shared engine code and test helpers the flow runs - # through, `vex`, whose verdicts the flow asserts, and the toolchain - # files. A main push outside this list waits for the nightly run below. + # pull request), the shared engine code and test helpers the flows run + # through, and the toolchain files. A main push outside this list waits + # for the nightly run below. paths: - '.github/workflows/bazel-nuget.yml' - '.github/workflows/bazel-compatibility.yml' @@ -97,14 +109,17 @@ on: - 'crates/socket-patch-core/src/vex/discover/nuget.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/nuget.rs' - 'crates/socket-patch-cli/src/commands/scan/hosted/nuget.rs' + - 'crates/socket-patch-core/src/bazel/built.rs' - 'crates/socket-patch-core/src/bazel/mod.rs' - 'crates/socket-patch-core/src/bazel/nuget.rs' - 'crates/socket-patch-core/src/bazel/starlark.rs' - 'crates/socket-patch-core/src/bazel/workspace.rs' + - 'crates/socket-patch-core/src/patch/sidecars/nuget.rs' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/hosted/**' - - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/src/commands/**' - 'crates/socket-patch-cli/tests/common/**' - 'crates/socket-patch-cli/tests/hosted_memory_common/**' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index bc390b2e6..346a92ba3 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -4178,7 +4178,7 @@ match it, withholds the statement: | `gradle_unpatched_copy` | `failed[].reason` | The purl the warning above (or `vex_gradle_derived_cache_check_failed`) withheld. | | `vex_gradle_derived_cache_check_failed` | run warning | The derived-cache check of an attested Gradle copy did not finish (it crashed), so a copy derived from the unpatched jar cannot be ruled out; no statement for that purl. | | `vex_gradle_lock_above_base` | run warning and `failed[].reason` | A hosted pin is wired, but a lock file records a release above its base, which that build resolves instead of the patch; no statement until it is re-locked or the patch is rolled back. | -| `vex_bazel_not_in_build` | run warning and `skipped` event of `vex` | In a Bazel workspace, `MODULE.bazel` or a file it includes hands the package to a hub that builds it from a lock (aspect_rules_js `npm.npm_translate_lock`, rules_python `pip.parse`, rules_ruby `ruby.bundle_fetch`), and the patch is not in what the hub builds: it is in the installed copy while the project's own lock, which the call names, lists the package at that version without naming the patch (the lock in the project's directory, or the lock of a pnpm workspace above it that names that directory among its importers), or it is a PyPI copy under `.socket/vendor` and the call names the file that points at it. The package is not omitted: each advisory of its patch gets a statement of the package's own with `status: "affected"`, the package as the one subcomponent of the product, and an `action_statement` that says what Bazel builds the package from and what to run (`scan --mode hosted` in the directory of that lock; for a vendored copy `vendor --revert` first), and for an installed copy ends with the way out of a repository that ships the installed tree (``If what you ship is the installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).``), with no `justification` and no `impact_statement`; they come after the `not_affected` statement of an advisory that a patched package shares. The warning, one per package, starts `: the VEX document says affected.` and goes on with the action statement; no `vendored_tree_out_of_sync` warning is given for such a package. The document is always written for it, and the exit code is the one of a run without it: standalone `vex` exits 0 with the document, also when every statement is `affected`. It does not report the package as verified: each such statement is a `skipped` event with this `errorCode` and `details.status: "affected"`, counted in `summary.skipped` and not in `summary.verified`, and the envelope's `status` is `partialFailure`. A command run with `--vex` writes the document, keeps its exit code and status, and carries the warning in `vex.warnings` and the number of such statements in `vex.affected`. The one-line summary counts them: `Wrote OpenVEX document with 2 statements (1 affected) to `. `--no-verify` changes none of it. Not raised in a run with `--no-bazel` / `--vex-no-bazel` / `SOCKET_VEX_NO_BAZEL`, which reads no Bazel file (see "The installed tree" under "VEX provenance markers"), for a hosted pin, for a vendored gem (no build has shown what rules_ruby does with one), in a `--global` run, for a patch whose record names no advisory (no run attests it), for the lock of another project (beside the project, below it, or above it without naming it), for a package that only the env document of a pnpm 11 lock lists, for a call that is not a statement of its own (in a comprehension, behind `and`, in a conditional, in the arguments of another call: it may never run), for a call that passes `*` or `**` or a `pip.parse` with `uv_lock` (it may take its packages from a file that is not read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, a label that is not a plain string, a lock that cannot be read, is over 64 MiB or is a link out of the Bazel root): the statement is then the `not_affected` one of a project without Bazel. See "Bazel workspaces: VEX" in `docs/ecosystems.md`. | +| `vex_bazel_not_in_build` | run warning and `skipped` event of `vex` | In a Bazel workspace, `MODULE.bazel` or a file it includes hands the package to a hub that builds it from a lock (aspect_rules_js `npm.npm_translate_lock`, rules_python `pip.parse`, rules_ruby `ruby.bundle_fetch`, rules_rust `crate.from_cargo`, rules_csharp `nuget.from_lock`), and the patch is not in what the hub builds: it is in the installed copy while the project's own lock, which the call names, lists the package at that version without naming the patch (the lock in the project's directory, the lock of a pnpm workspace above it that names that directory among its importers, or a `packages.lock.json` below it), or it is a PyPI copy under `.socket/vendor` and the call names the file that points at it. The package is not omitted: each advisory of its patch gets a statement of the package's own with `status: "affected"`, the package as the one subcomponent of the product, and an `action_statement` that says what Bazel builds the package from and what to run (`scan --mode hosted` in the directory of that lock, with the attribute the call has to carry for a crate, `cargo_config`, and for a NuGet package, `nuget_config`, and for a crate `scan --mode vendored` as well; for a vendored copy `vendor --revert` first), and for an installed copy ends with the way out of a repository that ships the installed tree (``If what you ship is the installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).``), with no `justification` and no `impact_statement`; they come after the `not_affected` statement of an advisory that a patched package shares. The warning, one per package, starts `: the VEX document says affected.` and goes on with the action statement; no `vendored_tree_out_of_sync` warning is given for such a package. The document is always written for it, and the exit code is the one of a run without it: standalone `vex` exits 0 with the document, also when every statement is `affected`. It does not report the package as verified: each such statement is a `skipped` event with this `errorCode` and `details.status: "affected"`, counted in `summary.skipped` and not in `summary.verified`, and the envelope's `status` is `partialFailure`. A command run with `--vex` writes the document, keeps its exit code and status, and carries the warning in `vex.warnings` and the number of such statements in `vex.affected`. The one-line summary counts them: `Wrote OpenVEX document with 2 statements (1 affected) to `. `--no-verify` changes none of it. Not raised in a run with `--no-bazel` / `--vex-no-bazel` / `SOCKET_VEX_NO_BAZEL`, which reads no Bazel file (see "The installed tree" under "VEX provenance markers"), for a hosted pin, for a vendored gem or NuGet package (no test builds one under its hub), for a vendored crate (rules_rust builds it), in a `--global` run, for a patch whose record names no advisory (no run attests it), for the lock of another project (beside the project, below it unless it is a `packages.lock.json`, or above it without naming it), for a package that only the env document of a pnpm 11 lock lists, for a call that is not a statement of its own (in a comprehension, behind `and`, in a conditional, in the arguments of another call: it may never run), for a call that passes `*` or `**`, a `pip.parse` with `uv_lock` or a `crate.from_cargo` with a cargo-bazel lock, `lockfile` (it may take its packages from a file that is not read), for a crate the lock does not take from a registry, for a NuGet package when the `nuget_config` of any `nuget.from_lock` call names the patch, is not a plain string label of the main repository or cannot be read, or when such a call passes `*` or `**` (rules_csharp makes one hub of all the calls, so the pin of another project may be what it builds), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, a label that is not a plain string, a lock that cannot be read, is over 64 MiB or is a link out of the Bazel root): the statement is then the `not_affected` one of a project without Bazel. See "Bazel workspaces: VEX" in `docs/ecosystems.md`. | | `vex_pnpm_bundled_copy` | run warning and `failed[].reason` | An npm pin is wired, but its pnpm lock names a package whose `bundledDependencies` may ship an unpatched copy of it (the lock does not record that copy's version); no statement while that package bundles it. `vendor --check` and `scan` still treat the wiring as live. | | `vex_deno_lock_copy` | run warning and `failed[].reason` | An npm pin is wired, but `deno.lock` locks the same `name@version`, which `deno install` installs without the wiring; no statement while it does. `vendor --check` and `scan` still treat the wiring as live. | | `vex_maven_reactor_root` | run warning and `failed[].reason` | A hosted Maven patch is wired in a reactor (`` / ``, a profile's included, or Maven 4 subproject discovery) one of whose modules may build the unpatched version: it resolves the patched version, or its selection cannot be told on the machine that runs `vex`, and no pin or declaration of the patch reaches it; or a declaration may still build the base version; or a pom of the reactor cannot be read. No statement; the note names the module (#261). `list`, `rollback` and `remove` still find the wiring. | diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 2505e0cfd..74a908d22 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -1908,14 +1908,14 @@ const AFFECTED_REASON: &str = "attested as affected, not as patched: Bazel does const INSTALLED_TREE_SHIPS: &str = "If what you ship is the installed tree and not what Bazel \ builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor)."; -/// In a Bazel workspace, a hub of aspect_rules_js, rules_python or -/// rules_ruby builds a package from the lock a workspace file names, never -/// from the copy a package manager installed, and rules_python builds -/// nothing from a line that points at a copy under `.socket/vendor` -/// ([`socket_patch_core::bazel::built`]). A patch that is only in such a -/// copy is in no build of Bazel's, so its package is not attested as -/// patched: it leaves `outcome.applied` and is returned with what to do -/// about it, for statements that say `affected` +/// In a Bazel workspace, a hub of aspect_rules_js, rules_python, +/// rules_ruby, rules_rust or rules_csharp builds a package from the lock a +/// workspace file names, never from the copy a package manager installed, +/// and rules_python builds nothing from a line that points at a copy under +/// `.socket/vendor` ([`socket_patch_core::bazel::built`]). A patch that is +/// only in such a copy is in no build of Bazel's, so its package is not +/// attested as patched: it leaves `outcome.applied` and is returned with +/// what to do about it, for statements that say `affected` /// ([`build_document_with_affected`]). A run warning tells a person the /// same. Nothing is omitted for this, so a document is always written. /// The package also leaves `outcome.vendored_out_of_sync`: that warning @@ -1977,8 +1977,9 @@ async fn unbuilt_by_bazel( /// The action statement for `package`, whose patch Bazel does not build: /// what `call` builds the package from, and what to run so that the build -/// holds the patch. Hosted mode pins a patch in the lock of the project it -/// runs in, so the remedy names the directory of the lock. +/// holds the patch. For an installed copy that is the hub's own remedy +/// ([`Unbuilt::remedy`]). Hosted and vendored mode write in the project +/// they run in, so it names the directory of the lock. /// /// For an installed copy it ends with the way out of a repository that /// ships the installed tree and keeps the hub for something else: the @@ -1993,13 +1994,13 @@ fn bazel_build_action(package: &Patched, call: &Unbuilt) -> String { file, line, lock, + remedy, } = call; match pins { None => format!( "Bazel builds this package from {lock} (`{tag}`, {file}:{line}), which does not \ - name Socket patch {uuid}: the patch is only in the installed copy. Run \ - `socket-patch scan --mode hosted` in the directory of that lock to pin the patch \ - there. {INSTALLED_TREE_SHIPS}" + name Socket patch {uuid}: the patch is only in the installed copy. {remedy} \ + {INSTALLED_TREE_SHIPS}" ), Some(_) => format!( "Bazel builds no package from the line of {lock} that points at the copy of Socket \ diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs index d77fb6975..2aa5d7ab9 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/cargo.rs @@ -1,5 +1,5 @@ -//! Hosted and vendored mode for a crate that rules_rust's crate_universe -//! resolves from a Cargo workspace: `crate.from_cargo(cargo_lockfile = +//! Hosted, vendored and agent mode for a crate that rules_rust's +//! crate_universe resolves from a Cargo workspace: `crate.from_cargo(cargo_lockfile = //! "//:Cargo.lock", manifests = ["//:Cargo.toml"], cargo_config = //! "//:.cargo/config.toml")` under Bzlmod, with no cargo-bazel lock (the //! hub's `lockfile`). @@ -15,8 +15,9 @@ //! cargo-bazel lock the hub follows `Cargo.toml` and `Cargo.lock` as they //! are, and no build needs a repin (`CARGO_BAZEL_REPIN`). //! -//! Two flows, one test each, on the Bazel the run is given ([`FIXTURE`] -//! says which ruleset goes with its release), each in a fresh output base: +//! The hosted and the vendored flow, one test each, on the Bazel the run is +//! given ([`FIXTURE`] says which ruleset goes with its release), each in a +//! fresh output base: //! //! - (a) `bazel build` and `bazel run //:consumer` print the unpatched //! marker. The stand-in registry was asked for the crate's file of the @@ -83,6 +84,15 @@ //! right after the build, `vex` attests the crate, and a second scan //! reports the copy `already_vendored` and leaves it alone. //! +//! Another flow is agent mode ([`agent_from_cargo_with_config`]), which +//! patches the copy of the crate in the cargo home, where a `cargo fetch` +//! or a `cargo build` of the user unpacked it. No build of Bazel's reads a +//! cargo home: the hub has Bazel download the crate file the lock pins. So +//! the build is the unpatched one before the command and after it. The flow +//! asserts that, and that every form of `vex` says so meanwhile: the crate +//! is affected ([`affected`]), unless `vex` is told that the installed tree +//! is what ships (`--no-bazel`). +//! //! The two releases also differ in the home of the hub's cargo //! ([`cargo_env`]). rules_rust 0.75.0 gives it a directory inside the //! output base that is empty whenever the hub is evaluated, so every @@ -172,10 +182,12 @@ //! the same. //! - Bazel would read that file as a package of the user's workspace. The //! crate has a dependency ([`DEP`]), so the file names a repository of -//! the hub, which the main repository does not see, and the commands -//! that analyse every target fail on it: `bazel cquery //...` and -//! `bazel query 'deps(//...)'` ([`analyses`]). The line that the scan -//! wrote into `.bazelignore` keeps the copies out of Bazel's packages: +//! the hub, which the main repository does not see, as it does not see +//! `platforms`, which the file names too. The commands that analyse +//! every target fail on the first of the two that Bazel meets: +//! `bazel cquery //...` and `bazel query 'deps(//...)'` ([`analyses`]). +//! The line that the scan wrote into `.bazelignore` keeps the copies out +//! of Bazel's packages: //! `//...` is the user's own target ([`every_target`]), both commands //! pass, and the build is the patched one, because the hub reads the //! copy by its path, not as a package. A user who comments the line out @@ -193,18 +205,18 @@ //! ([`only_the_build_file_of_cargo_bazel_is_no_change_of_a_vendored_copy`], //! [`the_vendored_crates_get_a_bazelignore_line_where_a_crate_hub_builds_them`]). -use std::path::Path; +use std::path::{Path, PathBuf}; use std::time::Instant; use base64::Engine as _; -use serde_json::json; +use serde_json::{json, Value}; use sha2::{Digest, Sha256, Sha512}; use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; use crate::envelope::{codes_in, event_for, has_event}; use crate::harness::{ - cell_without_bazel, changed, fixture_path, Cell, Fixture, Ran, Release, StandIn, Tree, - CONSUMER, NOTHING, REPO_CACHE, + cell_without_bazel, changed, fixture_path, with_vex, Cell, Claim, Fixture, How, Ran, Release, + StandIn, Tree, CONSUMER, NOTHING, REPO_CACHE, }; use crate::hosted_memory_common::{Patch, ORG}; @@ -521,6 +533,43 @@ fn registry(upstream: &Package) -> StandIn { /// API and the index name the checksum of the patch's own crate file, /// whatever is served. fn grant(standin: &StandIn, upstream: &Package, patch: &Patched, served: &[u8]) { + grant_recorded(standin, patch, served, &record(upstream, patch)); +} + +/// The record of `patch`: the library of `upstream` becomes the one of the +/// patch. +fn record(upstream: &Package, patch: &Patched) -> Value { + json!({ + "uuid": patch.uuid, + "purl": PURL, + "publishedAt": "2026-01-01T00:00:00Z", + "files": { "src/lib.rs": { + "beforeHash": compute_git_sha256_from_bytes(upstream.lib_rs.as_bytes()), + "afterHash": compute_git_sha256_from_bytes(patch.package.lib_rs.as_bytes()), + }}, + "vulnerabilities": { "GHSA-test-aaaa-bbbb": { + "cves": ["CVE-2024-0001"], "summary": "s", "severity": "high", "description": "d", + }}, + "description": "fixture", + "license": "MIT", + "tier": "free", + }) +} + +/// [`grant`] of the patch's own crate file, with a record that carries both +/// libraries: agent mode patches the copy in a cargo home from the record +/// and asks for no crate file. +fn grant_installed(standin: &StandIn, upstream: &Package, patch: &Patched) { + let b64 = |text: &str| base64::engine::general_purpose::STANDARD.encode(text); + let mut record = record(upstream, patch); + let file = &mut record["files"]["src/lib.rs"]; + file["blobContent"] = b64(&patch.package.lib_rs).into(); + file["beforeBlobContent"] = b64(&upstream.lib_rs).into(); + grant_recorded(standin, patch, &patch.package.crate_file, &record); +} + +/// [`grant`] with `record` as the record of the patch. +fn grant_recorded(standin: &StandIn, patch: &Patched, served: &[u8], record: &Value) { let origin = standin.origin(); let url = format!("{origin}{}", patch.route); let checksum = patch.package.checksum(); @@ -551,22 +600,7 @@ fn grant(standin: &StandIn, upstream: &Package, patch: &Patched, served: &[u8]) // Priority 1: ahead of the shared API mock's patch record, whose hashes // are fixed, because vendored mode holds the unpacked library to // `afterHash`. - let record = json!({ - "uuid": patch.uuid, - "purl": PURL, - "publishedAt": "2026-01-01T00:00:00Z", - "files": { "src/lib.rs": { - "beforeHash": compute_git_sha256_from_bytes(upstream.lib_rs.as_bytes()), - "afterHash": compute_git_sha256_from_bytes(patch.package.lib_rs.as_bytes()), - }}, - "vulnerabilities": { "GHSA-test-aaaa-bbbb": { - "cves": ["CVE-2024-0001"], "summary": "s", "severity": "high", "description": "d", - }}, - "description": "fixture", - "license": "MIT", - "tier": "free", - }); - let record = serde_json::to_vec(&record).expect("a JSON document"); + let record = serde_json::to_vec(record).expect("a JSON document"); let record_route = format!("/v0/orgs/{ORG}/patches/view/{}", patch.uuid); standin.serve(1, &record_route, &record); let dl = format!( @@ -675,15 +709,21 @@ fn open_readme_hub(test: &str) -> Option<(tempfile::TempDir, Cell, StandIn, Pack /// the patch server (a hosted pin is recognised by that origin) and as the /// index `rollback` reads the upstream checksum from. fn socket_patch(cell: &Cell, standin: &StandIn, args: &[&str]) -> Ran { + socket_patch_at(cell, standin, Path::new(NO_CARGO_HOME), args) +} + +/// [`socket_patch`] on a machine whose cargo home is `home`. +fn socket_patch_at(cell: &Cell, standin: &StandIn, home: &Path, args: &[&str]) -> Ran { let (origin, index) = hosts(standin); - cell.socket_patch(&origin, args, &env(&origin, &index)) + let home = home.to_string_lossy(); + cell.socket_patch(&origin, args, &env(&origin, &index, &home)) } /// [`socket_patch`] as a person runs it: what it printed on stdout and on /// stderr. fn person(cell: &Cell, standin: &StandIn, args: &[&str]) -> [String; 2] { let (origin, index) = hosts(standin); - cell.socket_patch_person(&origin, args, &env(&origin, &index)) + cell.socket_patch_person(&origin, args, &env(&origin, &index, NO_CARGO_HOME)) } /// The origin of `standin`, and the index of crates.io there. @@ -693,12 +733,13 @@ fn hosts(standin: &StandIn) -> (String, String) { (origin, index) } -/// What a `socket-patch` child of a flow is told of its hosts. -fn env<'a>(origin: &'a str, index: &'a str) -> [(&'a str, &'a str); 3] { +/// What a `socket-patch` child of a flow is told of its hosts, on a machine +/// whose cargo home is `home`. +fn env<'a>(origin: &'a str, index: &'a str, home: &'a str) -> [(&'a str, &'a str); 3] { [ ("SOCKET_PATCH_SERVER_URL", origin), ("SOCKET_CRATES_INDEX", index), - ("CARGO_HOME", NO_CARGO_HOME), + ("CARGO_HOME", home), ] } @@ -872,15 +913,42 @@ fn every_target(cell: &Cell) -> Vec { targets } +/// Whether `stderr` says that the main repository does not see a +/// repository that the build file in the copy names: one of the hub, or +/// `platforms`. Bazel names the first one it meets, and which one that is +/// differs from run to run. The same words about another repository's view +/// are another failure. +fn unseen(stderr: &str) -> bool { + (stderr.split("No repository visible as '@").skip(1)) + .filter_map(|rest| rest.split_once("' from main repository")) + .any(|(repo, _)| { + !repo.contains('\'') && (repo == "platforms" || repo.starts_with("crates__")) + }) +} + +/// [`unseen`] takes the two messages Bazel was seen to print, and neither +/// another repository's name nor another repository's view. +#[test] +fn an_unseen_repository_is_one_the_copy_names_and_the_main_repository_misses() { + let said = |repo: &str, from: &str| { + format!("ERROR: no such package: No repository visible as '@{repo}' from {from}\n") + }; + assert!(unseen(&said("platforms", "main repository"))); + assert!(unseen(&said("crates__dep-1.0.0", "main repository"))); + assert!(!unseen(&said("rules_cc", "main repository"))); + assert!(!unseen(&said("platforms", "repository '@@rules_rust+'"))); + assert!(!unseen("Loading: 0 packages loaded\n")); +} + /// Whether the commands that analyse every target of the checkout of /// `cell` pass: `bazel cquery //...` and `bazel query 'deps(//...)'`, which -/// agree. One that fails has met a repository of the hub, which the main -/// repository does not see. +/// agree. One that fails has met a repository that the build file in the +/// copy names and the main repository does not see ([`unseen`]). fn analyses(cell: &Cell) -> bool { let runs = [("cquery", "//..."), ("query", "deps(//...)")]; let runs = runs.map(|(command, targets)| cell.bazel(command, &[targets])); for run in &runs { - let unseen = run.stderr().contains("No repository visible as '@crates__"); + let unseen = unseen(&run.stderr()); assert_ne!(run.ok(), unseen, "{}: {}", cell.test, run.dump()); } assert_eq!(runs[0].ok(), runs[1].ok(), "{}", cell.test); @@ -1194,8 +1262,9 @@ fn vendored_from_cargo_with_config() { // package: `//...` is the consumer alone, and the commands that analyse // every target pass. A user who comments the line out has the package // back, where the ruleset writes the build file: `//...` names targets - // there, those commands fail on the repository of the dependency, and - // the file Bazel now reads is a change of the copy again. + // there, those commands fail on a repository that the file names and + // the main repository does not see, and the file Bazel now reads is a + // change of the copy again. assert_eq!(every_target(&cell), [CONSUMER], "{test}"); assert!(analyses(&cell), "{test}: under the line of the scan"); cell.write(".bazelignore", DECLINED); @@ -1675,6 +1744,207 @@ fn hosted_from_cargo_without_config() { ); } +/// The name of a directory of `registry/src` in a cargo home: cargo names +/// one after the host of an index and a hash of its own, which nothing +/// here reads. +const INDEX_DIR: &str = "127.0.0.1-0000000000000000"; + +/// The library of the crate in the cargo home `home`, where agent mode +/// looks for a crate: the copy that a cargo unpacked under `registry/src`, +/// or, in a home that holds none, one laid out here as `cargo fetch` +/// leaves it (the files of `upstream`'s crate file, and the mark cargo +/// sets on a directory it has unpacked). No cargo runs here. The home of a +/// flow is the one its Bazel children have: rules_rust 0.56.0 runs the +/// hub's cargo with it, and rules_rust 0.75.0 gives that cargo a home in +/// the output base and leaves this one empty. +fn fetched(home: &Path, upstream: &Package) -> PathBuf { + let sources = home.join("registry").join("src"); + let name = format!("{NAME}-{VERSION}"); + let indexes = std::fs::read_dir(&sources).into_iter().flatten().flatten(); + let mut unpacked = indexes.map(|index| index.path().join(&name)); + let copy = unpacked.find(|copy| copy.is_dir()).unwrap_or_else(|| { + let copy = sources.join(INDEX_DIR).join(&name); + let files = [ + ("Cargo.toml", CRATE_MANIFEST), + ("src/lib.rs", upstream.lib_rs.as_str()), + (".cargo-ok", "{\"v\":1}"), + ]; + for (file, text) in files { + let path = copy.join(file); + std::fs::create_dir_all(path.parent().expect("a file path")).expect("create the copy"); + std::fs::write(&path, text).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + } + copy + }); + let library = copy.join("src").join("lib.rs"); + let holds = std::fs::read_to_string(&library).unwrap_or_default(); + assert_eq!(holds, upstream.lib_rs, "{}", library.display()); + library +} + +/// What every form of `vex` has to say of the crate while its patch is in +/// the cargo home alone and the hub of `module`, the text of the checkout's +/// `MODULE.bazel`, builds it from the lock: the whole action statement of +/// the document, which the run warning repeats. It names the lock, the call +/// and its line, the two modes that a flow of this file builds patched, +/// with what hosted mode needs of the hub, and the option for a repository +/// that ships the installed tree. +fn affected(module: &str, patch: &Patched) -> Vec { + vec![format!( + "Bazel builds this package from {LOCK} (`crate.from_cargo`, {}), which does not name \ + Socket patch {}: the patch is only in the installed copy. Run `socket-patch scan --mode \ + hosted` in the directory of that lock to pin the patch there (the call has to name the \ + project's cargo config, `cargo_config`), or `socket-patch scan --mode vendored` to \ + commit a patched copy of the crate. If what you ship is the installed tree and not what \ + Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).", + hub_at(module), + patch.uuid + )] +} + +/// Agent mode beside a hub that builds the crate from the lock. +/// +/// - (a) `bazel build` and `bazel run //:consumer` print the unpatched +/// marker. +/// - (b) The crate is in the cargo home ([`fetched`]), as after the user's +/// `cargo fetch` or `cargo build`. `scan --mode agent --yes` patches the +/// library of that copy and writes nothing into the checkout but its +/// `.socket` directory, and `apply` passes +/// ([`Cell::patches_outside`]). Both, `vex` and `vex --no-verify` exit 0 +/// and write a document that says the crate is affected, with what to do +/// about it ([`affected`]). +/// - (c) The same two Bazel commands print the unpatched marker again, as +/// the documents said, and change no file: the hub has Bazel download +/// the crate file the lock pins, and no build reads a cargo home. +/// `vex --no-bazel` says not affected, through the patch: its document +/// then speaks of the cargo home, for a repository that ships what cargo +/// built from it, and not of the Bazel build. +/// - (d) A second machine prints the unpatched marker too. Its Bazel has +/// built nothing and evaluates the hub anew, with the patched cargo home +/// as the one of its environment ([`Cell::builds_anew`]); the build of +/// (c) is a warm one, which looks at nothing outside the checkout again. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn agent_from_cargo_with_config() { + let test = "cargo::agent_from_cargo_with_config"; + let started = Instant::now(); + let Some((home, cell, standin, upstream)) = open(test) else { + return; + }; + let release = cell.release().to_string(); + let patch = Patched::new(); + grant_installed(&standin, &upstream, &patch); + + // (a) The unpatched build, with the upstream crate from the stand-in. + builds_upstream(&cell, &standin, &upstream); + + // (b) Agent mode patches the copy in the cargo home, and every + // document says the crate is affected. + let library = fetched(home.path(), &upstream); + let run = |cell: &Cell, args: &[&str]| socket_patch_at(cell, &standin, home.path(), args); + let names = affected(&text(&cell.tree(), MODULE), &patch); + let claim = Claim::unbuilt(PURL, &patch.uuid, &names); + let patched = cell.patches_outside(run, &library, &patch.package.lib_rs, &claim); + + // (c) The build is the one of (a): Bazel never reads the patched copy. + // Told that the installed tree is what ships, `vex` attests that tree. + cell.builds(&upstream.marker); + let shipped = |cell: &Cell, args: &[&str]| run(cell, &[args, &["--no-bazel"]].concat()); + cell.stands_alone(shipped, &Claim::new(PURL, &patch.uuid, How::Agent), true); + assert_eq!(changed(&patched, &cell.tree()), NOTHING, "{test}"); + + // (d) Nor does a Bazel that evaluates the hub anew read it. + cell.builds_anew(&upstream.marker); + + println!( + "{test}: Bazel {release} built {:?} before and after `scan --mode agent` patched {}, \ + and on a second machine; every form of `vex` said the crate is affected, in the words \ + {names:?}, and `vex --no-bazel` said it is not affected in the installed tree; {:?}", + upstream.marker, + library.display(), + started.elapsed() + ); +} + +/// Without a Bazel: a checkout of the fixture's Cargo project whose +/// `MODULE.bazel` is `module`, a cargo home that holds the crate +/// ([`fetched`]), the stand-in of the run, and a patch of the crate granted +/// to agent mode. +fn fetched_checkout(module: &str) -> (Cell, tempfile::TempDir, StandIn, Package, Patched) { + let (upstream, patch) = (Package::upstream(), Patched::new()); + let standin = registry(&upstream); + grant_installed(&standin, &upstream, &patch); + let cell = checkout("", &upstream, &[(MODULE, module)]); + (cell, cargo_home(), standin, upstream, patch) +} + +/// Without a Bazel: step (b) of [`agent_from_cargo_with_config`] in a +/// checkout of the fixture, where `MODULE.bazel` hands the lock to +/// rules_rust, by either name of the file that defines the extension. Then +/// each of the two modes the document names, in a checkout of its own: the +/// scan of that mode pins or vendors the crate, and its document and the +/// one of `vex` say not affected, through that mode. +#[test] +fn an_installed_crate_is_affected_beside_a_hub_that_reads_the_lock() { + let named = module_naming_config(); + let older = named.replace("universe:extensions.bzl", "universe:extension.bzl"); + assert_ne!(older, named); + let ways = [ + (&named, "hosted", How::Hosted), + (&older, "vendored", How::Vendored), + ]; + for (module, mode, how) in ways { + let (cell, home, standin, upstream, patch) = fetched_checkout(module); + let library = fetched(home.path(), &upstream); + let run = |cell: &Cell, args: &[&str]| socket_patch_at(cell, &standin, home.path(), args); + let names = affected(module, &patch); + let claim = Claim::unbuilt(PURL, &patch.uuid, &names); + cell.patches_outside(run, &library, &patch.package.lib_rs, &claim); + + // What the document says to do ends in one that says not affected. + let document = cell.document(mode); + let scan = ["scan", "--mode", mode, "--yes"]; + let scan = run(&cell, &[&scan[..], &with_vex(&document)].concat()); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{}", scan.dump); + let claim = Claim::new(PURL, &patch.uuid, how); + cell.wrote_in_run(&scan, &document, &claim); + cell.stands_alone(run, &claim, true); + } +} + +/// Without a Bazel: what stays the statement of a project without Bazel +/// while the patch is in the cargo home alone +/// ([`Cell::keeps_its_statement`]). The hubs that decide nothing: one over +/// the Cargo files of another directory, one with a cargo-bazel lock, one +/// that names no `Cargo.lock`, and one whose call may not run. +#[test] +fn an_installed_crate_is_attested_where_no_hub_is_shown_to_build_it() { + let named = module_naming_config(); + let (cell, home, standin, upstream, patch) = fetched_checkout(&named); + let library = fetched(home.path(), &upstream); + let run = |cell: &Cell, args: &[&str]| socket_patch_at(cell, &standin, home.path(), args); + let names = affected(&named, &patch); + let claim = Claim::unbuilt(PURL, &patch.uuid, &names); + cell.patches_outside(run, &library, &patch.package.lib_rs, &claim); + + let (origin, index) = hosts(&standin); + let at_home = home.path().to_string_lossy(); + let told = env(&origin, &index, &at_home); + let gives = |args: &[&str], document: &Path| cell.gives(&origin, args, &told, document); + let lock = " cargo_lockfile = \"//:Cargo.lock\",\n"; + let undecided = [ + named.replace("\"//:", "\"//third_party:"), + named.replace( + lock, + &format!("{lock} lockfile = \"//:cargo-bazel-lock.json\",\n"), + ), + named.replace(lock, ""), + named.replace("crate.from_cargo(", "ENABLED and crate.from_cargo("), + ]; + let installed = Claim::new(PURL, &patch.uuid, How::Agent); + cell.keeps_its_statement(run, gives, &installed, &undecided); +} + /// Without a Bazel: the Cargo project of the fixture in a checkout of its /// own, in the directory `project` of it (`""`: the root, else with a `/` /// at its end), its lock pinning `upstream`, with `files` beside it, each diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs index dea1f4b94..f8f76acce 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -1050,6 +1050,21 @@ impl Cell { ); } + /// [`Cell::builds`] on a second machine ([`Cell::twin`]) that has no + /// lock of Bazel's either: its Bazel has fetched and built nothing and + /// holds no record of a hub, so it evaluates every hub anew, with the + /// `repo_env` of this cell. A warm rebuild here proves nothing of what + /// lies outside the checkout: Bazel does not look there again. This + /// cell goes before the second one builds, unless it holds the + /// repository cache (no [`REPO_CACHE`]): a flow keeps one output base + /// at a time. + pub fn builds_anew(self, marker: &str) { + let twin = self.twin(); + let _first = var(REPO_CACHE).is_none().then_some(self); + std::fs::remove_file(twin.path("MODULE.bazel.lock")).expect("Bazel's lock"); + twin.builds(marker); + } + /// Step (a) of a flow: the build prints `marker`, and Bazel wrote its /// lock. Gives the files of the checkout, that lock among them. pub fn builds_unpatched(&self, marker: &str) -> Tree { @@ -1435,6 +1450,87 @@ impl Cell { assert_eq!(there, here, "{test}: the two checkouts word it apart"); } + /// Agent mode in this checkout, through `run`, for a package that its + /// package manager keeps outside the checkout, where `installed` is a + /// file of that copy: `scan --mode agent --yes` gives the file the text + /// `patched`, from the record of the patch, and writes nothing into the + /// checkout but its own `.socket` directory, and the `apply` of a later + /// run passes. Then what the two say with `--vex`, and what `vex` and + /// `vex --no-verify` say: all four pass and write one document, which + /// says `claim`. Gives the files of the checkout. + pub fn patches_outside( + &self, + run: impl Fn(&Cell, &[&str]) -> Ran, + installed: &Path, + patched: &str, + claim: &Claim, + ) -> Tree { + let test = &self.test; + let before = self.tree(); + let in_run = self.document("in-run"); + let agent = ["scan", "--mode", "agent", "--yes"]; + let scan = run(self, &[&agent[..], &with_vex(&in_run)].concat()); + let said = &scan.dump; + assert_eq!(scan.code, 0, "{test}: {said}"); + assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{test}: {said}"); + let left = self.tree(); + let mut wrote = changed(&before, &left); + wrote.retain(|file| !file.starts_with(".socket/")); + assert_eq!(wrote, NOTHING, "{test}: {said}"); + let holds = std::fs::read_to_string(installed).unwrap_or_default(); + assert_eq!(holds, patched, "{test}: {}", installed.display()); + + let again = self.document("apply"); + let apply = run(self, &[&["apply"][..], &with_vex(&again)].concat()); + let status = &apply.envelope["status"]; + assert_eq!(*status, "success", "{test}: {}", apply.dump); + self.wrote_in_run(&scan, &in_run, claim); + self.wrote_in_run(&apply, &again, claim); + self.stands_alone(&run, claim, true); + self.stands_alone(&run, claim, false); + assert_eq!(changed(&left, &self.tree()), NOTHING, "{test}"); + left + } + + /// What stays the statement of a project without Bazel in this + /// checkout, after [`Cell::patches_outside`] under a hub that builds + /// the package from the project's lock. With `--no-bazel`, and with + /// each of `undecided` as its `MODULE.bazel`, whose files do not show + /// such a hub, `vex` attests the package as `installed` says, through + /// the patch. And what it gives a script and a person is what it gives + /// in the same checkout without its `MODULE.bazel`: the exit code, + /// both streams and the document. `gives` is [`Cell::gives`] of this + /// cell with the Socket API and the environment of `run`. + pub fn keeps_its_statement( + &self, + run: impl Fn(&Cell, &[&str]) -> Ran, + gives: impl Fn(&[&str], &Path) -> Value, + installed: &Claim, + undecided: &[String], + ) { + let shipped = |cell: &Cell, args: &[&str]| run(cell, &[args, &["--no-bazel"]].concat()); + self.stands_alone(shipped, installed, true); + let document = self.document("undecided"); + let vex = vex(&document); + let mut given = vec![gives(&[&vex[..], &["--no-bazel"]].concat(), &document)]; + let module = self.path("MODULE.bazel"); + let hub = std::fs::read_to_string(&module).expect("MODULE.bazel"); + for other in undecided { + assert_ne!(*other, hub, "{}", self.test); + self.write("MODULE.bazel", other); + self.stands_alone(&run, installed, true); + given.push(gives(&vex, &document)); + } + std::fs::remove_file(&module).expect("MODULE.bazel"); + self.stands_alone(&run, installed, true); + let without_bazel = gives(&vex, &document); + for (at, given) in given.iter().enumerate() { + assert_eq!(*given, without_bazel, "{}: the run {at}", self.test); + } + println!("`vex` in a checkout without MODULE.bazel:\n{without_bazel:#}"); + } + /// The stand-alone `vex` of a checkout that holds no patch any more, /// through `run`: it exits `code` with the error `error` and leaves no /// document, and says that it removed the one [`Cell::stands_alone`] diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs index a51c1b7e8..b4df3ccca 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs @@ -1,5 +1,5 @@ -//! Hosted mode for a NuGet package that comes through rules_csharp's -//! `nuget.from_lock(packages_lock_json = "//:packages.lock.json", +//! Hosted and agent mode for a NuGet package that comes through +//! rules_csharp's `nuget.from_lock(packages_lock_json = "//:packages.lock.json", //! nuget_config = "//:nuget.config")` under Bzlmod: the lock that //! `dotnet restore` writes beside a project, and a `nuget.config` whose one //! package source is nuget.org. @@ -21,8 +21,8 @@ //! ([`Package::restore_into`]); on the other it holds nothing, as on a //! runner that only ever ran Bazel. //! -//! One flow, on the Bazel the run is given ([`FIXTURE`] says which ruleset -//! goes with its release), in a fresh output base: +//! The hosted flow, on the Bazel the run is given ([`FIXTURE`] says which +//! ruleset goes with its release), in a fresh output base: //! //! - (a) `bazel build` and `bazel run //:consumer` print the unpatched //! marker, and Bazel fetched the upstream package from the stand-in. @@ -70,6 +70,14 @@ //! Bazel's downloader refuses the file over its sha256, and then the copy //! on nuget.org, which the hub tries next. //! +//! Another flow is agent mode ([`agent_from_lock`]), which patches the +//! copy of the package in NuGet's global packages folder, where the user's +//! `dotnet restore` unpacked it. No build of Bazel's reads that folder, so +//! the build is the unpatched one before the command and after it. The flow +//! asserts that, and that every form of `vex` says so meanwhile: the +//! package is affected ([`affected`]), unless `vex` is told that the +//! installed tree is what ships (`--no-bazel`). +//! //! Both markers are read from what Bazel built, and each holds an id made //! for the run. Bazel's downloader keeps every file it fetches in the //! repository cache, under its sha256, and hands it out again without a @@ -130,7 +138,7 @@ //! //! # Known gaps //! -//! Three outcomes the flow asserts are gaps of the product, not its +//! Three outcomes the flows assert are gaps of the product, not its //! contract. Each is asserted as the release has it, and marked //! `KNOWN GAP` there with what a fix would change in this test: //! @@ -154,8 +162,8 @@ use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; use crate::envelope::{codes_in, event_triples}; use crate::harness::{ - cell_without_bazel, changed, fixture_path, rewrite, Cell, Fixture, Ran, StandIn, Tree, - CONSUMER, NOTHING, + cell_without_bazel, changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, + StandIn, Tree, CONSUMER, NOTHING, }; use crate::hosted_memory_common::{read_tree, Patch, ORG}; @@ -440,6 +448,44 @@ fn registry(packages: &[&Package]) -> StandIn { /// patch's own package, whatever is served. The source holds no other /// package: a route nobody serves is a 404. fn grant(standin: &StandIn, upstream: &Package, patch: &Patched, served: &[u8]) { + grant_recorded(standin, patch, served, &record(upstream, patch)); +} + +/// The record of `patch`: the assembly of `upstream` becomes the one of the +/// patch. +fn record(upstream: &Package, patch: &Patched) -> Value { + let package = &patch.package; + json!({ + "uuid": patch.uuid, + "purl": package.purl(), + "publishedAt": "2026-01-01T00:00:00Z", + "files": { assembly_path(&package.id): { + "beforeHash": compute_git_sha256_from_bytes(upstream.assembly.as_bytes()), + "afterHash": compute_git_sha256_from_bytes(package.assembly.as_bytes()), + }}, + "vulnerabilities": { "GHSA-test-aaaa-bbbb": { + "cves": ["CVE-2024-0001"], "summary": "s", "severity": "high", "description": "d", + }}, + "description": "fixture", + "license": "MIT", + "tier": "free", + }) +} + +/// [`grant`] of the patch's own package, with a record that carries both +/// assemblies: agent mode patches the copy in NuGet's folder from the +/// record and asks for no package. +fn grant_installed(standin: &StandIn, upstream: &Package, patch: &Patched) { + let b64 = |text: &str| base64::engine::general_purpose::STANDARD.encode(text); + let mut record = record(upstream, patch); + let file = &mut record["files"][assembly_path(&patch.package.id)]; + file["blobContent"] = b64(&patch.package.assembly).into(); + file["beforeBlobContent"] = b64(&upstream.assembly).into(); + grant_recorded(standin, patch, &patch.package.nupkg, &record); +} + +/// [`grant`] with `record` as the record of the patch. +fn grant_recorded(standin: &StandIn, patch: &Patched, served: &[u8], record: &Value) { let package = &patch.package; // A route starts with the `/` that ends `https://`. let url = format!("https:/{}", patch.file(package)); @@ -472,22 +518,7 @@ fn grant(standin: &StandIn, upstream: &Package, patch: &Patched, served: &[u8]) // Priority 1: ahead of the shared API mock's patch record, which names // a file no NuGet package has. `vex` holds the package in NuGet's // folder to the hashes of this one. - let record = json!({ - "uuid": patch.uuid, - "purl": package.purl(), - "publishedAt": "2026-01-01T00:00:00Z", - "files": { assembly_path(&package.id): { - "beforeHash": compute_git_sha256_from_bytes(upstream.assembly.as_bytes()), - "afterHash": compute_git_sha256_from_bytes(package.assembly.as_bytes()), - }}, - "vulnerabilities": { "GHSA-test-aaaa-bbbb": { - "cves": ["CVE-2024-0001"], "summary": "s", "severity": "high", "description": "d", - }}, - "description": "fixture", - "license": "MIT", - "tier": "free", - }); - let record = serde_json::to_vec(&record).expect("a JSON document"); + let record = serde_json::to_vec(record).expect("a JSON document"); let record_route = format!("/v0/orgs/{ORG}/patches/view/{}", patch.uuid); standin.serve(1, &record_route, &record); let index = json!({ "version": "3.0.0", "resources": [{ @@ -970,6 +1001,155 @@ fn hosted_no_config() { ); } +/// What a run of agent mode is made of. +struct Restored { + /// The stand-in of the run: nuget.org with the two packages of the + /// fixture, and the Socket API with `patch`. + standin: StandIn, + /// The package a patch replaces, as nuget.org has it for this run. + upstream: Package, + /// One patch of it, granted with a record that agent mode patches + /// from ([`grant_installed`]). + patch: Patched, + /// The .NET home of a machine that restored the project: its NuGet + /// folder holds the two packages ([`Package::restore_into`]). + home: tempfile::TempDir, +} + +/// Make `cell` the checkout of a new run of agent mode ([`check_out`]), +/// whose builds fetch from the stand-in of the run ([`downloads`]). +fn restored(cell: &mut Cell) -> Restored { + let run = format!("R{}", uuid::Uuid::new_v4().simple()); + let upstream = Package::new(NAME, &run, &format!("PRISTINE {run}")); + let neighbour = Package::new(NEIGHBOUR, &run, "NEIGHBOUR"); + let patch = Patched::new(&run); + let standin = registry(&[&neighbour, &upstream]); + grant_installed(&standin, &upstream, &patch); + cell.route_downloads(&downloads(&standin.origin())); + check_out(cell, &run, &[&neighbour, &upstream]); + let home = tempfile::Builder::new() + .prefix("sp-bazel-nuget-") + .tempdir() + .expect("create a .NET home"); + for package in [&neighbour, &upstream] { + package.restore_into(home.path()); + } + // Bazel has the two variables of that home which `socket-patch` has + // ([`on_machine`]): a build that read NuGet's folder would find it. + let folder = packages_folder(home.path()); + let pairs = [ + ("NUGET_PACKAGES", folder.as_path()), + ("DOTNET_CLI_HOME", home.path()), + ]; + let owned = |(name, path): (&str, &Path)| (name.to_string(), path.to_string_lossy().into()); + cell.repo_env = pairs.map(owned).to_vec(); + Restored { + standin, + upstream, + patch, + home, + } +} + +impl Restored { + /// The assembly of the package in NuGet's folder, where agent mode + /// patches it. + fn assembly(&self) -> PathBuf { + let package = packages_folder(self.home.path()).join(self.upstream.lower()); + package.join(VERSION).join(assembly_path(&self.upstream.id)) + } +} + +/// What every form of `vex` has to say of the package while `patch` is in +/// NuGet's folder alone and the hub of the checkout of `cell` builds it +/// from the lock: the whole action statement of the document, which the +/// run warning repeats. It names the lock, the call and its line, hosted +/// mode, which [`hosted_from_lock`] builds patched, with what it needs of +/// the hub, and the option for a repository that ships the installed tree. +fn affected(cell: &Cell, patch: &Patched) -> Vec { + let module = text(&cell.tree(), MODULE); + let call = module.lines().position(|line| line == "nuget.from_lock("); + vec![format!( + "Bazel builds this package from {LOCK} (`nuget.from_lock`, {MODULE}:{}), which does not \ + name Socket patch {}: the patch is only in the installed copy. Run `socket-patch scan \ + --mode hosted` in the directory of that lock to pin the patch there (the call has to \ + name the project's nuget.config, `nuget_config`). If what you ship is the installed \ + tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and \ + vendor).", + call.expect("a hub") + 1, + patch.uuid + )] +} + +/// Agent mode beside the hub, which builds the package from the lock. +/// +/// - (a) `bazel build` and `bazel run //:consumer` print the unpatched +/// marker, and Bazel fetched the upstream package from the stand-in. +/// - (b) NuGet's folder holds the two packages, as after the user's +/// `dotnet restore` ([`restored`]). `scan --mode agent --yes` patches the +/// assembly of the package there and writes nothing into the checkout +/// but its `.socket` directory, and `apply` passes +/// ([`Cell::patches_outside`]). Both, `vex` and `vex --no-verify` exit 0 +/// and write a document that says the package is affected, with what to +/// do about it ([`affected`]). +/// - (c) The same two Bazel commands print the unpatched marker again, as +/// the documents said, and change no file: the hub has Bazel download +/// the package the lock pins, and no build reads NuGet's folder. +/// `vex --no-bazel` says not affected, through the patch: its document +/// then speaks of NuGet's folder, for a repository that ships what +/// `dotnet` built from it, and not of the Bazel build. +/// - (d) A second machine prints the unpatched marker too. Its Bazel has +/// built nothing and evaluates the hub anew, with the patched folder +/// named in its environment ([`Cell::builds_anew`]); the build of (c) +/// is a warm one, which looks at nothing outside the checkout again. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn agent_from_lock() { + let test = "nuget::agent_from_lock"; + let started = Instant::now(); + let Some(mut cell) = Cell::open(test, &FIXTURE) else { + return; + }; + let release = cell.release().to_string(); + let machine = restored(&mut cell); + let (standin, upstream, patch) = (&machine.standin, &machine.upstream, &machine.patch); + let (purl, unpatched) = (upstream.purl(), upstream.marker()); + + // (a) The unpatched build, with the upstream package from the stand-in. + cell.builds_unpatched(&unpatched); + assert!( + standin.asked(&upstream.file(FLAT_CONTAINER)) > 0, + "{test}: the build did not fetch the upstream package from the stand-in" + ); + + // (b) Agent mode patches the copy in NuGet's folder, and every + // document says the package is affected. + let assembly = machine.assembly(); + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, standin, machine.home.path(), args); + let names = affected(&cell, patch); + let claim = Claim::unbuilt(&purl, &patch.uuid, &names); + let patched = cell.patches_outside(run, &assembly, &patch.package.assembly, &claim); + + // (c) The build is the one of (a): Bazel never reads the patched copy. + // Told that the installed tree is what ships, `vex` attests that tree. + cell.builds(&unpatched); + let shipped = |cell: &Cell, args: &[&str]| run(cell, &[args, &["--no-bazel"]].concat()); + cell.stands_alone(shipped, &Claim::new(&purl, &patch.uuid, How::Agent), true); + assert_eq!(changed(&patched, &cell.tree()), NOTHING, "{test}"); + + // (d) Nor does a Bazel that evaluates the hub anew read it. + cell.builds_anew(&unpatched); + + println!( + "{test}: Bazel {release} built {unpatched:?} before and after `scan --mode agent` \ + patched {}, and on a second machine; every form of `vex` said the package is affected, \ + in the words {names:?}, and `vex --no-bazel` said it is not affected in the installed \ + tree; {:?}", + assembly.display(), + started.elapsed() + ); +} + /// Without a Bazel: `scan --mode hosted --yes` through the binary, in /// checkouts of the fixture's project that hold no `nuget.config`. What it /// gives a person, then a script, and the files it leaves are the same in @@ -1255,6 +1435,83 @@ fn the_pin_is_written_where_the_hub_takes_it() { } } +/// Without a Bazel: a checkout of the fixture for a new run of agent mode +/// ([`restored`]), with the `MODULE.bazel` of its era at the root. +fn restored_checkout() -> (Cell, Restored) { + let mut cell = cell_without_bazel("9.3.2"); + for part in ["common", "e9"] { + for (rel, bytes) in read_tree(&fixture_path(FIXTURE.dir).join(part)) { + cell.write(&rel, bytes); + } + } + cell.write(".git/HEAD", "ref: refs/heads/main\n"); + let machine = restored(&mut cell); + (cell, machine) +} + +/// Without a Bazel: step (b) of [`agent_from_lock`] in a checkout of the +/// fixture, where `MODULE.bazel` hands the lock to rules_csharp. Then what +/// the document says to do: `scan --mode hosted --yes` pins the patch in +/// the two files the hub names, and its document and the one of `vex` say +/// not affected, through the pin. +#[test] +fn an_installed_package_is_affected_beside_a_hub_that_reads_the_lock() { + let (cell, machine) = restored_checkout(); + let (standin, patch) = (&machine.standin, &machine.patch); + let purl = machine.upstream.purl(); + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, standin, machine.home.path(), args); + let names = affected(&cell, patch); + let claim = Claim::unbuilt(&purl, &patch.uuid, &names); + cell.patches_outside(run, &machine.assembly(), &patch.package.assembly, &claim); + + let document = cell.document("hosted"); + let scan = run(&cell, &[&SCAN[..], &with_vex(&document)].concat()); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{}", scan.dump); + let claim = Claim::new(&purl, &patch.uuid, How::Hosted); + cell.wrote_in_run(&scan, &document, &claim); + cell.stands_alone(run, &claim, true); +} + +/// Without a Bazel: what stays the statement of a project without Bazel +/// while the patch is in NuGet's folder alone +/// ([`Cell::keeps_its_statement`]). The hubs that decide nothing: one over +/// a lock that is not in the checkout, one whose `nuget_config` is not written +/// out, one whose call may not run, and one with a second call, for the +/// lock of another project, whose `nuget_config` names the patch: +/// rules_csharp makes one hub of both calls, which may build the patched +/// package through that project's pin. +#[test] +fn an_installed_package_is_attested_where_no_hub_is_shown_to_build_it() { + let (cell, machine) = restored_checkout(); + let (standin, patch) = (&machine.standin, &machine.patch); + let (purl, home) = (machine.upstream.purl(), machine.home.path()); + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, standin, home, args); + let names = affected(&cell, patch); + let claim = Claim::unbuilt(&purl, &patch.uuid, &names); + let patched = cell.patches_outside(run, &machine.assembly(), &patch.package.assembly, &claim); + + let gives = |args: &[&str], document: &Path| { + on_machine(standin, home, |api, env| { + cell.gives(api, args, env, document) + }) + }; + // The config of another project, which hosted mode pinned the patch in. + let pinned = format!("\n", patch.index()); + cell.write("pinned.config", pinned); + let module = text(&patched, MODULE); + let undecided = [ + module.replace("\"//:", "\"//third_party:"), + module.replace(NAMES_CONFIG, " nuget_config = CONFIG,\n"), + module.replace("nuget.from_lock(", "ENABLED and nuget.from_lock("), + format!( + "{module}nuget.from_lock(\n nuget_config = \"//:pinned.config\",\n \ + packages_lock_json = \"//third_party:{LOCK}\",\n)\n" + ), + ]; + let installed = Claim::new(&purl, &patch.uuid, How::Agent); + cell.keeps_its_statement(run, gives, &installed, &undecided); +} + /// Without a Bazel, what stays fixed now that no id and no sum is /// committed: the fixture's directories and the legs of its workflow are /// those of its table; every era names the two files the hub reads; the diff --git a/crates/socket-patch-core/src/bazel/built.rs b/crates/socket-patch-core/src/bazel/built.rs index 6c86baad8..f569ec39d 100644 --- a/crates/socket-patch-core/src/bazel/built.rs +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -1,20 +1,23 @@ //! Whether the Bazel build of a workspace takes the copy of a package that //! socket-patch patched. //! -//! Three rulesets hand the packages of an ecosystem to Bazel through one +//! Five rulesets hand the packages of an ecosystem to Bazel through one //! tag of a module extension, a hub: aspect_rules_js reads a pnpm lock //! (`npm.npm_translate_lock`), rules_python reads requirements files -//! (`pip.parse`) and rules_ruby reads a Gemfile and its lock -//! (`ruby.bundle_fetch`). Each fetches what those files name into +//! (`pip.parse`), rules_ruby reads a Gemfile and its lock +//! (`ruby.bundle_fetch`), rules_rust reads a `Cargo.lock` +//! (`crate.from_cargo`) and rules_csharp reads a `packages.lock.json` +//! (`nuget.from_lock`). Each fetches what those files name into //! repositories of Bazel's own and builds from there. None of them reads -//! what a package manager installed in the checkout (`node_modules`, a -//! virtualenv, a gem home), so a patch that is only in such a copy is not -//! in the build. And rules_python builds no package from a line that -//! points at a copy committed under `.socket/vendor`: 2.5.0-rc4 takes the -//! path for the name of a project and fails the build of everything the -//! hub serves (Bazel 9.3.2, 8.8.2 and 7.7.2). rules_js does build a -//! vendored tarball. What rules_ruby does with a vendored gem no build has -//! shown, so a vendored gem is not judged. +//! what a package manager installed (`node_modules`, a virtualenv, a gem +//! home, a cargo home, NuGet's packages folder), so a patch that is only +//! in such a copy is not in the build. And rules_python builds no package +//! from a line that points at a copy committed under `.socket/vendor`: +//! 2.5.0-rc4 takes the path for the name of a project and fails the build +//! of everything the hub serves (Bazel 9.3.2, 8.8.2 and 7.7.2). rules_js +//! does build a vendored tarball, and rules_rust a vendored crate. What +//! rules_ruby does with a vendored gem and rules_csharp with a vendored +//! package no test here builds, so neither is judged. //! //! [`unbuilt`] names, for a patched package, the call that builds it from a //! file without its patch. It says so only when the files of the workspace @@ -31,15 +34,18 @@ //! lists the same package (in a directory beside the project, below it, or //! above it without naming it) is the lock of another project, and says //! nothing of this one: a project of the checkout that Bazel does not -//! build keeps what socket-patch says of it. +//! build keeps what socket-patch says of it. A `packages.lock.json` below +//! the project's directory is the project's own as well ([`Hub::nested`]). //! //! Only a call that is a statement of its own counts ([`Call::whole`]): //! it runs, once. One in a comprehension, behind an `and`, in a //! conditional or in the arguments of another call may never run, and is //! passed over. So is a call that passes `*` or `**`, whose arguments are -//! not all written out, and a `pip.parse` with `uv_lock`: rules_python -//! (2.2.0 and later) can take the packages of such a call from that file -//! alone, which is not read here. +//! not all written out, and one that can take its packages from a file +//! that is not read here ([`Hub::elsewhere`]). A `crate.from_cargo` without +//! `cargo_lockfile` names no lock, so nothing is said: rules_rust 0.75.0 +//! has its cargo resolve the manifests anew, and no file says which +//! versions it builds. //! //! A lock is read like a file of the workspace ([`disk`]): never through a //! link that leads out of the Bazel root, although Bazel follows such a @@ -48,13 +54,27 @@ //! searched once for the patches of all the packages, and not kept. Of a //! pnpm lock the project documents are read, for their keys alone: //! rules_js links nothing of the document pnpm 11 keeps for its own -//! configuration. +//! configuration. Of a `Cargo.lock` the packages of a registry are read: +//! the hub has Bazel download the crate file of each, and takes no other +//! from a cargo home. A `packages.lock.json` never names a patch (a pin +//! there is a hash, and its source is in `nuget.config`), and rules_csharp +//! makes one hub of all its `nuget.from_lock` calls: the sources of the +//! last call that has any serve every package, and the first lock that +//! names a package pins it. So the config of every such call is searched +//! with the lock ([`Hub::beside`]), and nothing is said of the hub when +//! one of them is not a plain label of the main repository or a call +//! passes `*` or `**`. The locks are still read one call at a time, and `feeds` and +//! `local_package_dirs` are not read. Whether a hub takes a hosted pin of +//! the project itself is not judged here: [`super::cargo`] and +//! [`super::nuget`] say that to hosted mode, and the caller hands over no +//! package that has one. //! //! Not looked at: what a `--override_repository` or an rc file changes, //! BUILD files, and hubs of other rulesets. //! //! [`Tags::doubts`]: super::workspace::Tags::doubts +use std::cell::OnceCell; use std::collections::{HashMap, HashSet}; use std::io::Read; use std::path::{Component, Path}; @@ -62,8 +82,10 @@ use std::path::{Component, Path}; use aho_corasick::AhoCorasick; use super::starlark::{Call, Value}; -use super::workspace::{disk, Extension, Repo, Workspace}; +use super::workspace::{disk, Extension, Repo, Tag, Workspace}; +use crate::formats::cargo::CargoLock; use crate::formats::gem::locked_specs; +use crate::formats::nuget::lock::{nuget_lock_entries, parse_lock}; use crate::formats::pnpm::grammar::documents; use crate::formats::pnpm::workspace::lock_text_member_importers; use crate::formats::pnpm::{pnpm_registry_key, PnpmDocument, PnpmLock}; @@ -100,6 +122,9 @@ pub struct Unbuilt { /// installed copy the lock that lists the package, for a committed copy /// the file that points at it. pub lock: String, + /// What to run so that the build holds the patch of an installed copy + /// ([`Hub::remedy`]). + pub remedy: &'static str, } /// The tag of a module extension that names the files a ruleset builds the @@ -107,32 +132,56 @@ pub struct Unbuilt { struct Hub { /// The type of the ecosystem's purls. ecosystem: &'static str, - extension: Extension<'static>, + /// The extension, by each file of the ruleset that defines it. + extensions: &'static [Extension<'static>], tag: &'static str, /// The attributes that name such a file: a label, or a dict with a /// label as each key. files: &'static [&'static str], + /// The attributes with which a call can take its packages from a file + /// that is not read here, whatever its lock lists. + elsewhere: &'static [&'static str], /// The packages a file lists plainly, each as its name and version. lists: fn(&str) -> Vec<(String, String)>, /// The directories below a file's own whose lock the file is as well, /// each from that directory: the members of a pnpm workspace. members: fn(&str) -> Vec, + /// Whether a lock below the project's directory is the project's own + /// as well. A NuGet project is every project file below the directory + /// of a run, each with a lock beside it: agent mode patches what any of + /// them restored, and hosted mode pins in each of their locks. + nested: bool, /// Whether a call of the tag may build a package from a line that - /// points at a copy under `.socket/vendor`: rules_js does, and of - /// rules_ruby no build has shown that it does not. + /// points at a copy under `.socket/vendor`: rules_js and rules_rust + /// do, and of rules_ruby and rules_csharp no test here has shown + /// that they do not. builds_vendored: bool, + /// The attributes that name a file beside the lock, where a pin in + /// the lock does not name its patch. The calls of such a tag make one + /// hub, so the file of every call is searched with a lock for the id + /// of a patch. + beside: &'static [&'static str], + /// What to run so that the build holds a patch that is only in the + /// installed copy: the modes that a test builds patched on real Bazel + /// under this hub, with what hosted mode needs of the call. + remedy: &'static str, } -const HUBS: [Hub; 3] = [ +/// Hosted mode, which pins a patch in the lock the hub reads. +const HOSTED: &str = "Run `socket-patch scan --mode hosted` in the directory of that lock to pin \ + the patch there."; + +const HUBS: [Hub; 5] = [ Hub { ecosystem: "npm", - extension: Extension { + extensions: &[Extension { module: "aspect_rules_js", file: "//npm:extensions.bzl", name: "npm", - }, + }], tag: "npm_translate_lock", files: &["pnpm_lock"], + elsewhere: &[], lists: |text| { let project = documents(text).into_iter(); let project = project.filter(|(_, kind)| *kind == PnpmDocument::Project); @@ -142,15 +191,18 @@ const HUBS: [Hub; 3] = [ owned(keys.filter_map(|package| pnpm_registry_key(package.key))) }, members: lock_text_member_importers, + nested: false, builds_vendored: true, + beside: &[], + remedy: HOSTED, }, Hub { ecosystem: "pypi", - extension: Extension { + extensions: &[Extension { module: "rules_python", file: "//python/extensions:pip.bzl", name: "pip", - }, + }], tag: "parse", files: &[ "requirements_lock", @@ -159,6 +211,8 @@ const HUBS: [Hub; 3] = [ "requirements_linux", "requirements_windows", ], + // rules_python 2.2.0 and later. + elsewhere: &["uv_lock"], lists: |text| { let lines = logical_lines(text); owned( @@ -168,20 +222,71 @@ const HUBS: [Hub; 3] = [ ) }, members: |_| Vec::new(), + nested: false, builds_vendored: false, + beside: &[], + remedy: HOSTED, }, Hub { ecosystem: "gem", - extension: Extension { + extensions: &[Extension { module: "rules_ruby", file: "//ruby:extensions.bzl", name: "ruby", - }, + }], tag: "bundle_fetch", files: &["gemfile_lock", "gemfile"], + elsewhere: &[], lists: |text| owned(locked_specs(text).into_iter()), members: |_| Vec::new(), + nested: false, + builds_vendored: true, + beside: &[], + remedy: HOSTED, + }, + Hub { + ecosystem: "cargo", + extensions: &super::cargo::EXTENSIONS, + tag: "from_cargo", + files: &["cargo_lockfile"], + // The lock of rules_rust's own tool, which a hub renders its crates + // from until a repin, and which is not held to the `Cargo.lock` + // (0.75.0). + elsewhere: &["lockfile"], + lists: |text| { + let lock = CargoLock::parse(text).ok(); + let packages = lock.iter().flat_map(|lock| lock.packages()); + let fetched = packages.filter(|package| package.is_from_registry()); + let built = fetched.filter(|package| package.replace.is_none()); + owned(built.map(|package| (package.name.as_str(), package.version.as_str()))) + }, + members: |_| Vec::new(), + nested: false, + builds_vendored: true, + beside: &[], + remedy: "Run `socket-patch scan --mode hosted` in the directory of that lock to pin \ + the patch there (the call has to name the project's cargo config, \ + `cargo_config`), or `socket-patch scan --mode vendored` to commit a patched copy \ + of the crate.", + }, + Hub { + ecosystem: "nuget", + extensions: &[super::nuget::EXTENSION], + tag: "from_lock", + files: &["packages_lock_json"], + elsewhere: &[], + lists: |text| { + let lock = parse_lock(text).ok(); + let entries = lock.iter().flat_map(nuget_lock_entries); + owned(entries.map(|entry| (entry.id, entry.resolved))) + }, + members: |_| Vec::new(), + nested: true, builds_vendored: true, + beside: &["nuget_config"], + remedy: "Run `socket-patch scan --mode hosted` in the directory of that lock to pin \ + the patch there (the call has to name the project's nuget.config, \ + `nuget_config`).", }, ]; @@ -276,17 +381,44 @@ fn judge( if ours.is_empty() { continue; } - let tags = workspace.tags(&hub.extension, hub.tag); - if !tags.doubts.is_empty() { + let tags = |extension| workspace.tags(extension, hub.tag); + let tags: Vec<_> = hub.extensions.iter().map(tags).collect(); + if tags.iter().any(|tags| !tags.doubts.is_empty()) { continue; } + let calls = || tags.iter().flat_map(|tags| &tags.calls); + // The files beside the locks, of every call of the tag: the calls + // with such a file make one hub (rules_csharp), where the file of + // one call says where the packages of every lock come from. So + // the file of any call may name the patch, and one that a call + // does not give as a plain label of the main repository, or may + // pass unseen, may name any. + let plain = |value: &Value| match value { + Value::Str(label) => file(workspace, label), + _ => None, + }; + let beside = |tag: &Tag| { + let given = hub.beside.iter().filter_map(|name| tag.call.arg(name)); + given.map(plain).collect::>>() + }; + let beside: Option>> = calls().map(beside).collect(); + let unseen = !hub.beside.is_empty() && calls().any(|tag| tag.call.unpacks()); + let Some(beside) = beside.filter(|_| !unseen) else { + continue; + }; + // Their text, read when a lock first asks and once for the hub. + let beside = beside.concat(); + let texts = || beside.iter().map(|file| read(file)).collect(); + let configs: OnceCell> = OnceCell::new(); // What a file lists, and which patches of the packages its text - // names: read when a package first asks and once for all the calls - // that name it, and the text is not kept. `None` for a file that - // is not the project's lock or cannot be read. + // names, with the text of the files beside it: read when a package + // first asks and once for all the calls that name it, and the + // text is not kept. `None` for a file that is not the project's + // lock, or when one of them cannot be read. let mut listed = HashMap::new(); - let elsewhere = |call: &Call| call.unpacks() || call.arg("uv_lock").is_some(); - for tag in (tags.calls.iter()).filter(|tag| tag.call.whole && !elsewhere(tag.call)) { + let named = |call: &Call| hub.elsewhere.iter().any(|name| call.arg(name).is_some()); + let elsewhere = |call: &Call| call.unpacks() || named(call); + for tag in calls().filter(|tag| tag.call.whole && !elsewhere(tag.call)) { for lock in files(workspace, tag.call, hub.files) { for &at in &ours { let package = &packages[at]; @@ -297,13 +429,15 @@ fn judge( } None => { let listed = listed.entry(lock.clone()).or_insert_with(|| { - let member = from_lock(project, &lock)?; - let text = read(&lock)?; + let nested = hub.nested && inside(project, &lock); + let member = from_lock(project, &lock).or(nested.then_some(""))?; + let mut text = read(&lock)?; let named = || (hub.members)(&text).iter().any(|m| m == member); if !(member.is_empty() || named()) { return None; } let listed = (hub.lists)(&text).into_iter(); + text.push_str(configs.get_or_init(texts).as_deref()?); let key = |(name, version)| { PurlKey::new(&format!("pkg:{}/{name}@{version}", hub.ecosystem)) }; @@ -325,10 +459,11 @@ fn judge( }; if unpatched && found[at].is_none() { found[at] = Some(Unbuilt { - call: format!("{}.{}", hub.extension.name, hub.tag), + call: format!("{}.{}", hub.extensions[0].name, hub.tag), file: tag.file.to_string(), line: tag.call.line, lock: lock.clone(), + remedy: hub.remedy, }); } } @@ -352,13 +487,8 @@ fn files(workspace: &Workspace, call: &Call, attributes: &[&str]) -> Vec _ => {} } } - let main = |label: &&str| { - let label = workspace - .label(label) - .filter(|label| label.repo == Repo::Main); - label.map(|label| label.path()) - }; - labels.iter().filter_map(main).collect() + let main = labels.iter().filter_map(|label| file(workspace, label)); + main.collect() } /// The path from the Bazel root of `file`, a path from the project in the @@ -371,6 +501,21 @@ fn below(project: &str, file: &str) -> String { } } +/// The file of the main repository that `label` names, by its path from +/// the Bazel root. +fn file(workspace: &Workspace, label: &str) -> Option { + let label = workspace.label(label); + let label = label.filter(|label| label.repo == Repo::Main); + label.map(|label| label.path()) +} + +/// Whether the workspace's file `lock` lies in a directory below the +/// directory `project`. +fn inside(project: &str, lock: &str) -> bool { + let rest = lock.strip_prefix(project); + rest.is_some_and(|rest| project.is_empty() || rest.starts_with('/')) +} + /// The directory `project` from the directory of the workspace's file /// `lock`: empty for the project the file lies in, `apps/web` for one that /// far below it. `None` for a project that is neither: no file beside the @@ -619,12 +764,287 @@ use_repo(ruby, "bundle") assert_eq!(installed("web", "pkg:npm/right-pad@1.3.0"), ""); assert_eq!(installed("api", "pkg:pypi/requests@2.31.0"), ""); assert_eq!(installed("api", "pkg:pypi/idna@3.6"), ""); - // An ecosystem without a hub here, and no purl at all. + // An ecosystem whose hub this workspace does not call, one without + // a hub, and no purl at all. assert_eq!(installed("web", "pkg:cargo/serde@1.0.0"), ""); assert_eq!(installed("web", "pkg:golang/example.com/m@v1.0.0"), ""); assert_eq!(installed("web", "left-pad"), ""); } + /// A workspace with the hubs of rules_rust and rules_csharp, each over + /// the lock of one directory. + const CRATES: &str = r#"module(name = "shop", version = "0.0.0") + +bazel_dep(name = "rules_rust", version = "0.75.0") +bazel_dep(name = "rules_csharp", version = "0.5.0") + +crate = use_extension("@rules_rust//crate_universe:extensions.bzl", "crate") +crate.from_cargo( + name = "crates", + cargo_lockfile = "//engine:Cargo.lock", + manifests = ["//engine:Cargo.toml"], +) +use_repo(crate, "crates") + +nuget = use_extension("@rules_csharp//csharp:extensions.bzl", "nuget") +nuget.from_lock( + nuget_config = "//desk:nuget.config", + packages_lock_json = "//desk:packages.lock.json", +) +use_repo(nuget, "nuget") +"#; + + /// A registry crate, one of another registry, one from git, one from a + /// path, and one that a `[replace]` swaps out. + const CARGO_LOCK: &str = r#"version = 4 + +[[package]] +name = "engine" +version = "0.1.0" +dependencies = ["serde", "tokens", "fork", "local", "swapped"] + +[[package]] +name = "serde" +version = "1.0.200" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + +[[package]] +name = "tokens" +version = "0.3.0" +source = "sparse+https://crates.example/index/" +checksum = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + +[[package]] +name = "fork" +version = "2.0.0" +source = "git+https://git.example/fork#0123456789abcdef0123456789abcdef01234567" + +[[package]] +name = "local" +version = "0.2.0" + +[[package]] +name = "swapped" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +replace = "swapped 3.0.0" +"#; + + const NUGET_LOCK: &str = r#"{ + "version": 1, + "dependencies": { + "net8.0": { + "Newtonsoft.Json": { + "type": "Direct", + "requested": "[13.0.3, )", + "resolved": "13.0.3", + "contentHash": "AAAA" + }, + "Shop.Core": { "type": "Project" } + } + } +} +"#; + + const NUGET_CONFIG: &str = "\n \n \n \n\n"; + + const BUILT: [(&str, &str); 4] = [ + ("MODULE.bazel", CRATES), + ("engine/Cargo.lock", CARGO_LOCK), + ("desk/packages.lock.json", NUGET_LOCK), + ("desk/nuget.config", NUGET_CONFIG), + ]; + + const CARGO: &str = "crate.from_cargo MODULE.bazel:7 engine/Cargo.lock"; + const NUGET: &str = "nuget.from_lock MODULE.bazel:15 desk/packages.lock.json"; + const SERDE: &str = "pkg:cargo/serde@1.0.200"; + const JSON: &str = "pkg:nuget/newtonsoft.json@13.0.3"; + + /// [`BUILT`] with `text` in the place of the file `path`, and with + /// `from` of that text replaced by `to`. + fn built_with(path: &str, from: &str, to: &str) -> Vec<(&'static str, &'static str)> { + let changed = |(name, text): (&'static str, &'static str)| match name == path { + true => { + assert!(text.contains(from), "{path}: no {from:?}"); + let text: &'static str = Box::leak(text.replace(from, to).into_boxed_str()); + (name, text) + } + false => (name, text), + }; + BUILT.into_iter().map(changed).collect() + } + + /// A crate in a cargo home and a package in NuGet's folder are not + /// what `crate.from_cargo` and `nuget.from_lock` build: each has Bazel + /// download what the lock of the project lists. + #[test] + fn an_installed_crate_or_nuget_package_is_not_what_a_hub_builds() { + let installed = |project, purl| said(&BUILT, project, purl, None); + // A crate of crates.io and one of another registry. + assert_eq!(installed("engine", SERDE), CARGO); + assert_eq!(installed("engine", "pkg:cargo/tokens@0.3.0"), CARGO); + // The id as the lock spells it and as NuGet's folder does, and a + // version with a fourth part. + assert_eq!(installed("desk", JSON), NUGET); + assert_eq!( + installed("desk", "pkg:nuget/Newtonsoft.Json@13.0.3.0"), + NUGET + ); + // What the hub does not download: a crate from git, from a path or + // behind a `[replace]`, the workspace's own, a project reference. + for other in [ + "pkg:cargo/fork@2.0.0", + "pkg:cargo/local@0.2.0", + "pkg:cargo/swapped@3.0.0", + "pkg:cargo/engine@0.1.0", + "pkg:cargo/serde@1.0.199", + ] { + assert_eq!(installed("engine", other), "", "{other}"); + } + assert_eq!(installed("desk", "pkg:nuget/shop.core@1.0.0"), ""); + assert_eq!(installed("desk", "pkg:nuget/newtonsoft.json@13.0.2"), ""); + // The lock of another project: beside it, above it, below it. + for (project, purl) in [("desk", SERDE), ("", SERDE), ("engine/cli", SERDE)] { + assert_eq!(installed(project, purl), "", "{project:?}"); + } + for project in ["engine", "desk/tests", "des"] { + assert_eq!(installed(project, JSON), "", "{project:?}"); + } + // But a NuGet project is every project file below the directory of + // the run, each with its lock: the lock of `desk` is the root's. + assert_eq!(installed("", JSON), NUGET); + assert!(inside("shop", "shop/desk/packages.lock.json")); + assert!(!inside("shop/desk/tests", "shop/desk/packages.lock.json")); + // A copy committed under `.socket/vendor` is not judged. + let pins = ["Cargo.toml", "Cargo.lock"]; + assert_eq!(said(&BUILT, "engine", SERDE, Some(&pins)), ""); + let pins = ["nuget.config", "packages.lock.json"]; + assert_eq!(said(&BUILT, "desk", JSON, Some(&pins)), ""); + } + + /// What to run is the hub's: hosted mode under every hub, with what it + /// needs of a `crate.from_cargo` and a `nuget.from_lock`, and vendored + /// mode for a crate, which alone of the two is built from a committed + /// copy. + #[test] + fn a_hub_names_the_modes_that_patch_what_it_builds() { + let remedy = |files: &[(&str, &str)], project: &str, purl: &str| { + let text = |path: &str| files.iter().find(|(name, _)| *name == path); + let workspace = Workspace::read(&|path| match text(path) { + Some((_, text)) => Entry::Text(text.to_string()), + None => Entry::Absent, + }); + let package = Patched { + purl: purl.to_string(), + uuid: UUID.to_string(), + pins: None, + }; + let read = |path: &str| text(path).map(|(_, text)| text.to_string()); + let found = judge(&workspace, project, &read, &[package]).remove(0); + found.expect("a call that builds the package").remedy + }; + assert_eq!(remedy(&SHOP, "web", "pkg:npm/left-pad@1.3.0"), HOSTED); + assert_eq!(remedy(&SHOP, "api", "pkg:pypi/flask-cors@4.0.0"), HOSTED); + assert_eq!(remedy(&SHOP, "billing", "pkg:gem/rack@2.2.8"), HOSTED); + let pins = HOSTED.trim_end_matches('.'); + let cargo = remedy(&BUILT, "engine", SERDE); + let vendored = "), or `socket-patch scan --mode vendored` to commit"; + let names = cargo.contains("`cargo_config`") && cargo.contains(vendored); + assert!(cargo.starts_with(pins) && names, "{cargo}"); + let nuget = remedy(&BUILT, "desk", JSON); + let names = nuget.contains("`nuget_config`") && !nuget.contains("vendored"); + assert!(nuget.starts_with(pins) && names, "{nuget}"); + } + + /// A call that names more than the lock: nothing is said where its + /// packages can come from a file that is not read, or where a file + /// beside the lock names the patch or cannot be read. + #[test] + fn a_crate_or_nuget_call_that_may_build_something_else_withholds_nothing() { + let lock = " cargo_lockfile = \"//engine:Cargo.lock\",\n"; + let cargo = |argument: &str| { + let files = built_with("MODULE.bazel", lock, &format!("{lock} {argument},\n")); + said(&files, "engine", SERDE, None) + }; + assert_eq!( + cargo("cargo_config = \"//engine:.cargo/config.toml\""), + CARGO + ); + // The lock of rules_rust's own tool, and arguments not written out. + assert_eq!(cargo("lockfile = \"//engine:cargo-bazel-lock.json\""), ""); + assert_eq!(cargo("**COMMON"), ""); + // `manifests` alone names no lock. + let files = built_with("MODULE.bazel", lock, ""); + assert_eq!(said(&files, "engine", SERDE, None), ""); + // The extension by the older name of its file is the same one. + let files = built_with( + "MODULE.bazel", + "universe:extensions.bzl", + "universe:extension.bzl", + ); + assert_eq!(said(&files, "engine", SERDE, None), CARGO); + // A lock that names the patch: the registry of a hosted pin. + let source = "registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"aaaa"; + let pinned = format!("sparse+https://patch.example/{UUID}/index/\"\nchecksum = \"cccc"); + let files = built_with("engine/Cargo.lock", source, &pinned); + assert_eq!(said(&files, "engine", SERDE, None), ""); + + let config = " nuget_config = \"//desk:nuget.config\",\n"; + let nuget = |files: &[(&str, &str)]| said(files, "desk", JSON, None); + assert_eq!(nuget(&BUILT), NUGET); + // No config: the hub asks nuget.org alone. + assert_eq!(nuget(&built_with("MODULE.bazel", config, "")), NUGET); + // The config names the patch: the source of a hosted pin, whose + // hash the lock holds without a word of it. + let org = "\n {org}"); + let files = built_with("desk/nuget.config", org, &source); + assert_eq!(nuget(&files), ""); + // The config is not named plainly, or is not there. + let computed = " nuget_config = CONFIG,\n"; + assert_eq!(nuget(&built_with("MODULE.bazel", config, computed)), ""); + assert_eq!(nuget(&BUILT[..3]), ""); + + // rules_csharp makes one hub of every call: the config of the call + // for another project's lock may be the one this project's package + // comes through. Nothing is said when it names the patch, is not + // named plainly, or may be passed unseen. + let hosted: &'static str = Box::leak(NUGET_CONFIG.replace(org, &source).into_boxed_str()); + let beside = |call: &str| { + let hub = "use_repo(nuget, \"nuget\")\n"; + let call = format!("nuget.from_lock({call})\n{hub}"); + let mut files = built_with("MODULE.bazel", hub, &call); + let till = [ + ("till/packages.lock.json", NUGET_LOCK), + ("till/nuget.config", hosted), + ]; + files.extend(till); + nuget(&files) + }; + let lock = "packages_lock_json = \"//till:packages.lock.json\""; + assert_eq!(beside(lock), NUGET); + let upstream = format!("{lock}, nuget_config = \"//desk:nuget.config\""); + assert_eq!(beside(&upstream), NUGET); + for other in [ + "nuget_config = \"//till:nuget.config\"", + "nuget_config = \"//till:missing.config\"", + "nuget_config = CONFIG", + "nuget_config = {\"//desk:nuget.config\": \"desk\"}", + "**TILL", + ] { + assert_eq!(beside(&format!("{lock}, {other}")), "", "{other}"); + } + + // A proxy that is handed on: a doubt on that hub alone, by either + // file of its extension. + let files = built_with("MODULE.bazel", CRATES, &format!("{CRATES}print(crate)\n")); + assert_eq!(said(&files, "engine", SERDE, None), ""); + assert_eq!(said(&files, "desk", JSON, None), NUGET); + } + #[test] fn a_committed_copy_is_not_built_from_a_line_that_points_at_it() { let vendored = |project, purl, pins: &[&str]| said(&SHOP, project, purl, Some(pins)); @@ -791,16 +1211,17 @@ use_repo(ruby, "bundle") [ said(&files, "api", "pkg:pypi/flask-cors@4.0.0", None), said(&files, "api", "pkg:pypi/requests@2.31.0", Some(&pins)), + said(&files, "tools", "pkg:pypi/idna@3.6", None), ] }; let judged = "pip.parse MODULE.bazel:15 api/requirements.txt".to_string(); - assert_eq!(pypi("quiet = False"), [judged.clone(), judged]); + // The other call of the hub is judged whatever this one passes. + let other = "pip.parse MODULE.bazel:21 tools/requirements_linux.txt".to_string(); + let both = [judged.clone(), judged, other.clone()]; + assert_eq!(pypi("quiet = False"), both); for elsewhere in ["uv_lock = \"//api:uv.lock\"", "**COMMON", "*LOCKS"] { - assert_eq!( - pypi(elsewhere), - [String::new(), String::new()], - "{elsewhere}" - ); + let passed_over = [String::new(), String::new(), other.clone()]; + assert_eq!(pypi(elsewhere), passed_over, "{elsewhere}"); } } @@ -904,7 +1325,7 @@ use_repo(ruby, "bundle") pins, }; let packages = vec![ - package("pkg:cargo/serde@1.0.0", None), + package("pkg:golang/example.com/m@v1.0.0", None), package("pkg:npm/left-pad@1.3.0", None), package("pkg:npm/left-pad@1.2.0", None), ]; diff --git a/crates/socket-patch-core/src/bazel/cargo.rs b/crates/socket-patch-core/src/bazel/cargo.rs index dea7b128e..5d16e13a5 100644 --- a/crates/socket-patch-core/src/bazel/cargo.rs +++ b/crates/socket-patch-core/src/bazel/cargo.rs @@ -90,7 +90,7 @@ pub const UNREAD: &str = "redirect_cargo_bazel_config_unread"; /// The module extension whose `from_cargo` tag makes a hub, by the two /// files that define it at rules_rust 0.56.0 and 0.75.0: `extension.bzl` /// hands on the `crate` of `extensions.bzl`. -const EXTENSIONS: [Extension<'static>; 2] = [ +pub(super) const EXTENSIONS: [Extension<'static>; 2] = [ Extension { module: "rules_rust", file: "//crate_universe:extensions.bzl", diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 1388da628..fc0ed2637 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2154,8 +2154,8 @@ workspace and that Bazel does not build keeps the matrix at the top. | PyPI: rules_python `pip.parse` over a requirements file | Supported | Not supported | Not supported | Supported | | Go: gazelle `go_deps.from_file` over `go.mod` | Supported | Supported | Not supported | Supported with a hosted or vendored patch | | RubyGems: rules_ruby `ruby.bundle_fetch` over `Gemfile.lock` | Supported with no `gem_checksums` on the call, or with one written out in the call that does not name the gem or holds it to the patched gem's sha256 | Not supported | Not supported | Supported | -| Cargo: rules_rust `crate.from_cargo` over `Cargo.lock` | Supported with `cargo_config` on the hub | Supported | Not supported | Supported with a hosted or vendored patch | -| NuGet: rules_csharp `nuget.from_lock` over `packages.lock.json` | Supported with `nuget_config` on the tag | Not supported | Not supported | Supported with no restored copy on the machine | +| Cargo: rules_rust `crate.from_cargo` over `Cargo.lock` | Supported with `cargo_config` on the hub | Supported | Not supported | Supported | +| NuGet: rules_csharp `nuget.from_lock` over `packages.lock.json` | Supported with `nuget_config` on the tag | Not supported | Not supported | Supported; for a hosted patch, with no restored copy on the machine | | Composer: a rule of your own that runs `composer install` from `composer.lock` | Supported | Not supported | Not supported | Supported with a hosted patch | | Maven: rules_jvm_external `maven.install` with a `lock_file` | Supported with Bazel 7.4.0 or later | Supported with Bazel 7.4.0 or later | Not supported | Supported with a hosted or vendored patch | @@ -2176,7 +2176,9 @@ exits 0 and leaves a build that fails (the known problems below). What a cell sa - **Supported**, for VEX: `socket-patch vex` and `--vex` say `not_affected` of a package the Bazel build takes patched, and `affected` of one whose patch Bazel does not build. [Bazel workspaces: VEX](#bazel-workspaces-vex) has the cases and the limits; a vendored gem - is one of the limits. + is one of the limits. The NuGet cell names another: of a hosted patch `vex` writes no + document on a machine whose NuGet folder still holds the unpatched package (the last list + below). - **Supported with a condition**, for VEX: under the condition the cell names, the document says `not_affected` of a package the Bazel build takes patched, and a test holds it to that (for a hosted Maven patch a test without Bazel). It does not say `affected` of a @@ -3227,8 +3229,9 @@ adds no line. What the line is for, measured with rules_rust 0.75.0 on Bazel 9.3 tags the crate's library so). That package names repositories only the hub sees, so for a vendored crate with a dependency the commands that analyse every target fail on it: `bazel cquery //...` and `bazel query 'deps(//...)'` end with `No repository visible as - '@crates__' from main repository`. With the line both pass, and `//...` holds - your own targets alone. + '@crates__' from main repository`, or with the same words about `@platforms`, + which the file names too: Bazel reports the first of the two that it meets. With the line + both pass, and `//...` holds your own targets alone. **Under that line, the file is no change of the copy.** `vendor --check` passes, `vex` attests the crate, `repair` has nothing to restore, and a second `scan --mode vendored` @@ -4276,7 +4279,7 @@ What is read, and what is not: `vex` and `--vex` read what socket-patch wrote and what the project's own package manager installed. In a Bazel workspace (the Bazel root of the section on `.bazelignore` above) they -also read `MODULE.bazel` and the files it includes, for the calls of three rulesets that hand +also read `MODULE.bazel` and the files it includes, for the calls of five rulesets that hand a lock to Bazel: | Call | Files it names | @@ -4284,24 +4287,38 @@ a lock to Bazel: | aspect_rules_js `npm.npm_translate_lock` | `pnpm_lock` | | rules_python `pip.parse` | `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows` | | rules_ruby `ruby.bundle_fetch` | `gemfile_lock`, `gemfile` | +| rules_rust `crate.from_cargo` | `cargo_lockfile` | +| rules_csharp `nuget.from_lock` | `packages_lock_json` | Each of them builds a package from what those files name, in a repository of Bazel's own, -and never from `node_modules`, a virtualenv or a gem home. So two kinds of patch are in no -build of Bazel's, and the document says of their package that it is `affected`, not that it -is patched: - -- **A patch in the installed copy** (agent mode) of an npm, PyPI or RubyGems package, when - such a call names the project's own lock and that lock lists the package at that version - without naming the patch. The project's own lock is the one in the project's directory, or - the lock of a pnpm workspace above it that names that directory among its `importers`. - Measured for rules_js 3.6.0 on Bazel 9.3.2, 8.8.2 and 7.7.2: the build prints the - unpatched package before `scan --mode agent` and after it. +and never from `node_modules`, a virtualenv, a gem home, a cargo home or NuGet's packages +folder. So two kinds of patch are in no build of Bazel's, and the document says of their +package that it is `affected`, not that it is patched: + +- **A patch in the installed copy** (agent mode) of an npm, PyPI, RubyGems, Cargo or NuGet + package, when such a call names the project's own lock and that lock lists the package at + that version without naming the patch. The project's own lock is the one in the project's + directory, or the lock of a pnpm workspace above it that names that directory among its + `importers`. For NuGet it is a `packages.lock.json` below that directory as well: a NuGet + project is every project file below the directory the command runs in, each with a lock + beside it. Of a `Cargo.lock` the crates of a registry count, which are the ones the hub + has Bazel download. A `packages.lock.json` never names a patch (a hosted pin there is a + hash), and rules_csharp makes one hub of all its `nuget.from_lock` calls: the sources of + the last call that has any serve every package, and the first lock that names a package + pins it. So the `nuget_config` of every such call is searched for the patch as well: where + one names it, the hub may build the patched package through the pin of another project, + and the statement stays `not_affected`. The locks are read one call at a time, and the + `feeds` and `local_package_dirs` of a call are not read. + Measured on Bazel 9.3.2, 8.8.2 and 7.7.2 for rules_js 3.6.0, for rules_rust 0.75.0 and + 0.56.0 and for rules_csharp 0.5.0: the build prints the unpatched package before + `scan --mode agent` and after it; for rules_rust and rules_csharp also on a second machine + that has built nothing and has the patched cargo home or NuGet folder. - **A PyPI patch committed under `.socket/vendor`** (vendored mode), when such a call names the file that points at the copy. rules_python 2.5.0-rc4 takes the path of the line for the name of a project, and the build of everything the hub serves fails (same three - releases). A vendored npm tarball is built by rules_js and keeps its statement. So does a - vendored gem, for another reason: no test here runs the build of one yet, so nothing is - said of it. + releases). A vendored npm tarball is built by rules_js and a vendored crate by rules_rust, + and each keeps its statement. So do a vendored gem and a vendored NuGet package, for + another reason: no test here runs the build of one yet, so nothing is said of it. 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 @@ -4333,6 +4350,18 @@ Bazel builds no package from the line of requirements.txt that points at the cop Both ways out are tested on real Bazel: after the hosted scan the build prints the patched package and the document says `not_affected`. +For a crate and a NuGet package the action statement names what hosted mode needs of the +call, and for a crate vendored mode as well, which rules_rust builds from the committed copy: + +``` +Run `socket-patch scan --mode hosted` in the directory of that lock to pin the patch there (the call has to name the project's cargo config, `cargo_config`), or `socket-patch scan --mode vendored` to commit a patched copy of the crate. +Run `socket-patch scan --mode hosted` in the directory of that lock to pin the patch there (the call has to name the project's nuget.config, `nuget_config`). +``` + +A test without Bazel runs each of those scans after agent mode, and the document then says +`not_affected`; the patched build after a hosted or a vendored scan is tested on real Bazel +from a checkout that agent mode has not touched. + A run tells a person the same in a warning (`vex_bazel_not_in_build`, one per package): ``` @@ -4366,14 +4395,18 @@ Nothing changes where the files do not show such a call: outside a Bazel workspa the workspace is not read with certainty: the statement is then `not_affected`, as without Bazel. A lock elsewhere that lists the same package is the lock of another project and decides nothing for this one: in a directory beside the project, -below it, or above it without naming it among the importers of a pnpm workspace (a pnpm app +below it (but for a `packages.lock.json`, see above), or above it without naming it among the +importers of a pnpm workspace (a pnpm app beside a Java build; a project with a lock of its own under a root whose lock a hub reads; a Python or Ruby project below the directory of the file a hub reads). The workspace is not read with certainty when a module file is missing, cannot be read or holds a statement the reader does not follow (a `load`, an `if`, a hub proxy handed to anything but `use_repo` or `inject_repo`); when the call gives its file as anything but a plain string label of the main repository, passes `*` or `**`, or is a `pip.parse` with `uv_lock`, whose packages -rules_python 2.2.0 and later can take from that file; when the lock cannot be read, is +rules_python 2.2.0 and later can take from that file, or a `crate.from_cargo` with a +cargo-bazel lock (`lockfile`), which the hub builds from until a repin, or without +`cargo_lockfile`; when any `nuget.from_lock` call gives a `nuget_config` that is no such +label or cannot be read, or passes `*` or `**`; when the lock cannot be read, is larger than 64 MiB, or is a link that leads out of the Bazel root (Bazel follows such a link; socket-patch reads no file outside the root); and when a `WORKSPACE`, `WORKSPACE.bazel` or `WORKSPACE.bzlmod` at the root holds more than a `workspace(...)` call. @@ -4412,8 +4445,11 @@ Three more flows hold the document of `vex` to their patched build on the same r after a hosted scan: Cargo through rules_rust's `crate.from_cargo` with `cargo_config` (and after a vendored scan), Composer through a rule or a genrule of the project's own that runs `composer install` from the lock, and NuGet through rules_csharp's `nuget.from_lock` with -`nuget_config`, on a machine whose NuGet folder does not hold the package. For these, and -for a Maven entry in `MODULE.bazel`, +`nuget_config`, on a machine whose NuGet folder does not hold the package. For Cargo and +NuGet a flow of agent mode holds the documents to the unpatched build as well: the run +(`--vex`), `vex` and `vex --no-verify` each write one `affected` statement, and +`vex --no-bazel` one `not_affected` statement. For these, and for a Maven entry in +`MODULE.bazel`, [Bazel workspaces: what is supported](#bazel-workspaces-what-is-supported) says what the document does not show. @@ -4421,15 +4457,22 @@ For no other Bazel shape do these pages say that the document and the build agre these the document is still wrong (`not_affected` while Bazel builds the unpatched package, or while the build is broken): -- **Agent mode beside rules_js, rules_python or rules_ruby**, wherever the statement does - not say `affected` above. `npm_translate_lock` is given an `npm_package_lock` or a - `yarn_lock`, which are not read, or `pip.parse` a `uv_lock`. The hub reads a lock above - the project that does not name the project among its importers. The hub reads a lock - below the directory the command runs in: a run at the repository root while the hub reads - `web/pnpm-lock.yaml`. A Python or Ruby project lies below the directory of the file the +- **Agent mode beside rules_js, rules_python, rules_ruby, rules_rust or rules_csharp**, + wherever the statement does not say `affected` above. `npm_translate_lock` is given an + `npm_package_lock` or a `yarn_lock`, which are not read, or `pip.parse` a `uv_lock`. + `crate.from_cargo` is given a cargo-bazel lock (`lockfile`) or no `cargo_lockfile`, or the + crates come through `crate.from_specs` or a `crates_repository` of a `WORKSPACE` file. + Any `nuget.from_lock` call is given a `nuget_config` that is not read, or passes `*` or + `**`. The hub reads a lock above + the project that does not name the project among its importers: also the `Cargo.lock` of + a Cargo workspace, for a run in one of its members. The hub reads a lock + below the directory the command runs in, other than a `packages.lock.json`: a run at the + repository root while the hub reads `web/pnpm-lock.yaml`. A Python or Ruby project lies + below the directory of the file the hub reads. The call is not a statement of its own, or passes `*` or `**`. A `WORKSPACE` file at the root defines something, or the workspace has no `MODULE.bazel`. Measured for - rules_js, which builds from the lock and never reads the patched `node_modules`. + rules_js, rules_rust and rules_csharp, which build from the lock and never read the + patched copy. - **Vendored mode for PyPI**, where the workspace is not read with certainty: a `WORKSPACE` file that defines something, no `MODULE.bazel`, a call that is not a statement of its own, a file that is not given as a plain string label. And where the line that @@ -4440,6 +4483,9 @@ the build is broken): lists as `srcs`, so the path of the copy does not exist there. Read from its source and measured by hand, where the build fails; no test runs it yet, so the statement is left as it is. +- **Vendored mode for NuGet** beside `nuget.from_lock`. rules_csharp 0.5.0 reads the path of + the committed copy as a URL. Measured by hand, where the build fails; no test runs it yet, + so the statement is left as it is. - **A vendored package whose own files the hub does not read**, while the lock the hub does read still lists the registry's package: a uv or Poetry project vendored through `pyproject.toml` and its lock while `pip.parse` reads a requirements file exported before; diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 2be5dcf83..ea94cfb34 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 3917 + "max": 4006 }, "lock-readers": { "paths": [